query
stringlengths 9
9.05k
| document
stringlengths 10
222k
| negatives
listlengths 19
20
| metadata
dict |
---|---|---|---|
Tests that custom error is raised in the default eigenvalue representation.
|
def test_eigvals_undefined(self):
with pytest.raises(qml.operation.EigvalsUndefinedError):
MyOp.compute_eigvals()
with pytest.raises(qml.operation.EigvalsUndefinedError):
op.eigvals()
|
[
"def test_error_deterministic_model_with_realizations(ensemble_cube, interpreter):\n ensemble_cube.attributes[\"mosg__model_configuration\"] = \"uk_det\"\n ensemble_cube.attributes[\"title\"] = \"UKV Model on UK 2 km Standard Grid\"\n msg = \"Deterministic model should not have . realizations\"\n with pytest.raises(ValueError, match=msg):\n interpreter.run(ensemble_cube)",
"def test_eigenvals_calcfunction(\n configure, # pylint: disable=unused-argument\n sample,\n):\n eigenvals_calcfunction = CalculationFactory(\n 'tbmodels.calcfunctions.eigenvals'\n )\n tb_model = DataFactory('singlefile')(file=sample('model.hdf5'))\n\n k_mesh = DataFactory('array.kpoints')()\n k_mesh.set_kpoints_mesh([4, 4, 4], offset=[0, 0, 0])\n\n res = eigenvals_calcfunction(tb_model=tb_model, kpoints=k_mesh)\n assert isinstance(res, DataFactory('array.bands'))\n assert res.get_array('bands').shape == (64, 14)",
"def test_eigen_caching(self):\n diag_op = ValidOp(*self.simple_operands)\n eig_decomp = diag_op.eigendecomposition\n\n eig_vecs = eig_decomp[\"eigvec\"]\n eig_vals = eig_decomp[\"eigval\"]\n\n eigs_cache = diag_op._eigs[diag_op.hash]\n cached_vecs = eigs_cache[\"eigvec\"]\n cached_vals = eigs_cache[\"eigval\"]\n\n assert np.allclose(eig_vals, cached_vals)\n assert np.allclose(eig_vecs, cached_vecs)",
"def test_kparr2eta_error():\n test_kparr = 0.1\n test_z = 9.19508\n pytest.raises(TypeError, cosmo.kparr2eta, test_kparr, test_z)",
"def test_eigenvals(\n configure_with_daemon, # pylint: disable=unused-argument\n sample,\n get_tbmodels_process_builder\n):\n builder = get_tbmodels_process_builder('tbmodels.eigenvals')\n\n builder.tb_model = DataFactory('singlefile')(file=sample('model.hdf5'))\n\n k_mesh = DataFactory('array.kpoints')()\n k_mesh.set_kpoints_mesh([4, 4, 4], offset=[0, 0, 0])\n builder.kpoints = k_mesh\n\n output = run(builder)\n assert isinstance(output['bands'], DataFactory('array.bands'))",
"def test_estimation_cost_error(norm, error):\n with pytest.raises(ValueError, match=\"must be greater than zero\"):\n qml.resource.DoubleFactorization.estimation_cost(norm, error)",
"def test_analytic_raise_error(self):\n self.fitting_problem.hessian = None\n with self.assertRaises(exceptions.NoHessianError):\n Analytic(self.cost_func.problem, self.jacobian)",
"def GetRaiseValueError(self):\n raise ValueError('RaiseValueError Parameter')",
"def test_eigval(file):\n filedir = \"__testfiles__/\" + file\n mass = sol.input_reader(filedir)[0]\n x_min, x_max = sol.input_reader(filedir)[1][:2]\n length = x_max - x_min\n eigmin, eigmax = sol.input_reader(filedir)[4:6]\n # getting the eigenvalues for the specific problem from data or equations\n eigvallist = []\n if file == \"test_infpot.txt\":\n for nn in range(eigmin, eigmax + 1):\n eigval = (4 * np.pi**2) / (8 * mass * length**2) * nn**2\n eigvallist.append(eigval)\n elif file == \"test_harmonic.txt\":\n for nn in range(eigmin - 1, eigmax):\n eigval = 1 / 2 * (nn + 1 / 2)\n eigvallist.append(eigval)\n elif file == \"test_pot.txt\":\n eigvallist = np.loadtxt(\"__unittestfiles__/test_pot_energy.dat\")\n elif file == \"test_dualpot_lin.txt\":\n eigvallist = np.loadtxt\\\n (\"__unittestfiles__/test_dualpot_lin_energy.dat\")\n elif file == \"test_dualpot_cspline.txt\":\n eigvallist = np.loadtxt\\\n (\"__unittestfiles__/test_dualpot_cspline_energy.dat\")\n elif file == \"test_asympot.txt\":\n eigvallist = np.loadtxt(\"__unittestfiles__/test_asympot_energy.dat\")\n else:\n eigvallist = np.ones((1, eigmax - eigmin + 1))\n eigvalarray = np.array(eigvallist)\n sol.run(filedir, \"__output__\")\n testeigarray = np.loadtxt(\"__output__/energies.dat\")\n assert np.all(np.abs(eigvalarray - testeigarray) < ERROR)",
"def test_non_base_multierror():\n\n exc = MultiError([ZeroDivisionError(), ValueError()])\n assert type(exc) is NonBaseMultiError\n assert isinstance(exc, ExceptionGroup)",
"def testNonNumerical(self):\n csv = StringIO('Ignored, A, B, C\\n'\n 'name, 2, 3, hello\\n')\n if PY3:\n error = \"^could not convert string to float: ' hello'$\"\n else:\n error = '^could not convert string to float: hello$'\n assertRaisesRegex(self, ValueError, error, Matrix, csv)",
"def test_expression_error():\n ee = ExpressionError(\"Expression\", \"MSG\")\n assert_true(ee.expression == \"Expression\")\n assert_true(ee.msg == \"MSG\")\n assert_true(ee.__str__() == \"[Expression] MSG\")",
"def test_eval_bad_input_type_failure(self, error):\n\n def test_func():\n raise ValueError(\"test func\")\n\n with pytest.raises(ValueError) as verr:\n testing.eval_bad_input(test_func, error, \"test func\")\n\n assert str(verr).find(\"test func\") >= 0\n return",
"def test_bad_numeric_raises_exception(self):\n with self.assertRaises(KeyError):\n math_diff(\n self.thresh_dict,\n os.path.join(self.diff_files_dir, 'eplusout.csv'),\n os.path.join(self.diff_files_dir, 'eplusout_bad_numeric.csv'),\n os.path.join(self.temp_output_dir, 'abs_diff.csv'),\n os.path.join(self.temp_output_dir, 'rel_diff.csv'),\n os.path.join(self.temp_output_dir, 'math_diff.log'),\n os.path.join(self.temp_output_dir, 'summary.csv'),\n )",
"def test_sparse_matrix_error(self):\n\n t = qml.PauliX(0) @ qml.Hermitian(np.eye(4), wires=[1, 2])\n with pytest.raises(ValueError, match=\"Can only compute\"):\n t.sparse_matrix()",
"def test_arithmetic_errors(self):\n H = qml.Hamiltonian([1], [qml.PauliZ(0)])\n A = [[1, 0], [0, -1]]\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n _ = H @ A\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n _ = A @ H\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n _ = H + A\n with pytest.raises(TypeError, match=\"can't multiply sequence by non-int\"):\n _ = H * A\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n _ = H - A\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n H += A\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n H *= A\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n H -= A",
"def test_constraint_raising_error(self):\n with mn.model() as m:\n mn.constant('X7Allowed', False)\n mn.constraint(\n ['X7Allowed'],\n lambda machine: 1 / 0,\n \"Whatever\",\n lambda names, amounts, trt: 'whatever')\n\n vresult = m.validate_all()\n self.assertEqual(\n m.validate_all(),\n {\n 'success': False,\n 'errors': [\n {\n 'error_code': 'Whatever',\n 'inconsistent_variables': ['X7Allowed'],\n 'error_message': \n 'Constraint raised exception division by zero',\n 'treatment': ''\n }\n\n ]\n })\n\n with mn.model() as m:\n mn.constant('X7Allowed', False)\n mn.constraint(\n ['X7Allowed'],\n lambda x: False,\n \"Whatever\",\n lambda names, amounts, trt: 1 / 0)\n\n self.assertEqual(\n m.validate_all(),\n {\n 'success': False,\n 'errors': [\n {\n 'error_code': 'Whatever',\n 'inconsistent_variables': ['X7Allowed'],\n 'error_message': \n 'Constraint raised exception division by zero',\n 'treatment': ''\n }\n\n ]\n })",
"def test_mae_examples():\n\n mae = smlb.MeanAbsoluteError()\n\n assert mae([-1, 2], [0, 9]) == 4",
"def test_e0(self):\n self.assertAlmostEqual(self.thermodata.E0.value_si, self.E0, 6)",
"def test_invalid_type():\n with pytest.raises(TypeError):\n # Test with string value\n assert calculate_E_min(B_degrees=\"blah\")\n with pytest.raises(ValueError):\n # Test with NaN value\n assert calculate_E_min(B_degrees=nan)\n with pytest.raises(ValueError):\n # Test with infinite value\n assert calculate_E_min(B_degrees=inf)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests that custom error is raised in the default diagonalizing gates representation.
|
def test_diaggates_undefined(self):
with pytest.raises(qml.operation.DiagGatesUndefinedError):
MyOp.compute_diagonalizing_gates(wires=[1])
with pytest.raises(qml.operation.DiagGatesUndefinedError):
op.diagonalizing_gates()
|
[
"def test_diagonalizing_gates_overlapping(self):\n diag_op = ValidOp(qml.S(0), qml.PauliX(0))\n diagonalizing_gates = diag_op.diagonalizing_gates()\n\n assert len(diagonalizing_gates) == 1\n diagonalizing_mat = diagonalizing_gates[0].matrix()\n\n true_mat = np.eye(2)\n\n assert np.allclose(diagonalizing_mat, true_mat)",
"def test_add_diagonals_fails():\n a = np.array([\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [1, 2, 3, 4]\n ])\n b = np.array([\n [1, 2, 3, 4],\n [5, 6, 7, 8]\n ])\n\n # row mismatch is not a multiple of 2 when lower_only=False\n with pytest.raises(ValueError):\n _banded_utils._add_diagonals(a, b, lower_only=False)\n\n # mismatched number of columns\n with pytest.raises(ValueError):\n _banded_utils._add_diagonals(a[:, 1:], b)",
"def test_diagonalizing_gates_non_overlapping(self):\n diag_op = ValidOp(qml.PauliZ(wires=0), qml.Identity(wires=1))\n assert diag_op.diagonalizing_gates() == []",
"def testinvalidtriangle(self):\n self.assertEqual(classify_triangle(5, 1, 2), 'NotATriangle', 'NotATriangle')",
"def testUpperDiagonalForUnknownFeature(self):\n csv = StringIO('Ignored, A, B, C\\n'\n 'name1, 1, 2, 3\\n'\n 'name2, 4, 5, 6\\n')\n m = Matrix(csv)\n error = \"^'XXX'$\"\n assertRaisesRegex(self, KeyError, error, m.upperDiagonal, 'XXX')",
"def test_reconstruct_not_raised(self, *shapes):\n self.assert_exception_is_not_raised(matting.reconstruct, shapes)",
"def test_diff_penalty_diagonals_order_neg():\n with pytest.raises(ValueError):\n _banded_utils.diff_penalty_diagonals(10, -1)",
"def _handle_error_diagonalization(self, calculation):\n input_parameters = calculation.inp.parameters.get_dict()\n input_electrons = input_parameters.get('ELECTRONS', {})\n diagonalization = input_electrons.get('diagonalization', self.defaults['qe']['diagonalization'])\n\n if ((\n any(['too many bands are not converged' in w for w in calculation.res.warnings]) or\n any(['eigenvalues not converged' in w for w in calculation.res.warnings])\n ) and (\n diagonalization == 'david'\n )):\n new_diagonalization = 'cg'\n self.ctx.inputs.parameters['ELECTRONS']['diagonalization'] = 'cg'\n self.ctx.restart_calc = calculation\n self.report('PwCalculation<{}> failed to diagonalize with \"{}\" scheme'.format(calculation.pk, diagonalization))\n self.report('Restarting with diagonalization scheme \"{}\"'.format(new_diagonalization))\n return ErrorHandlerReport(True, True)",
"def test_fixNegsDiag(self):\n q = Rates([[-6,2,2,2],[-6,-2,4,4],[2,2,-6,2],[4,4,-2,-6]], RnaPairs)\n m = q.fixNegsDiag()._data\n self.assertEqual(m,array([[-6,2,2,2],[0,-8,4,4],[2,2,-6,2],[4,4,0,-8]]))",
"def test_diagonal_data_types(self, xp, sp):\n n = 40\n m = 4\n # Define the generalized eigenvalue problem Av = cBv\n # where (c, v) is a generalized eigenpair,\n # and where we choose A and B to be diagonal.\n vals = xp.arange(1, n + 1)\n # A and B matrices based on parametrization\n A = sp.diags([vals * vals], [0], (n, n), format=self.sparse_format)\n A = A.astype(xp.dtype(self.A_dtype))\n A = A if self.A_sparsity is True else A.toarray()\n\n B = sp.diags([vals], [0], (n, n), format=self.sparse_format)\n B = B if self.B_sparsity is True else B.toarray()\n\n M_LO = None\n if self.preconditioner_dtype is not None:\n M = sp.diags([1. / vals], [0], (n, n), format=self.sparse_format)\n M = M if self.preconditioner_sparsity else M.toarray()\n\n def fun(x):\n return M @ x\n # Define Preconditioner function as Linear Operator\n M_LO = sp.linalg.LinearOperator(matvec=fun,\n matmat=fun,\n shape=(n, n),\n dtype=xp.dtype(self.preconditioner_dtype)) # NOQA\n\n # Cannot be sparse array\n X = testing.shaped_random((n, m), xp=xp, dtype=xp.dtype(self.X_dtype),\n seed=1234)\n\n # Require tht returned eigenvectors be in the orthogonal\n # complement of the first few standard basis vectors\n # (Cannot be sparse array)\n m_excluded = 3\n Y = xp.eye(n, m_excluded, dtype=xp.dtype(self.Y_dtype))\n # core call to lobpcg solver\n eigvals, eigvecs = sp.linalg.lobpcg(A, X, B=B, M=M_LO, Y=Y,\n tol=1e-4, maxiter=100,\n largest=False)\n return eigvals, _eigen_vec_transform(eigvecs, xp)",
"def test_sparse_matrix_error(self):\n\n t = qml.PauliX(0) @ qml.Hermitian(np.eye(4), wires=[1, 2])\n with pytest.raises(ValueError, match=\"Can only compute\"):\n t.sparse_matrix()",
"def test_diamond_norm_non_square():\n with np.testing.assert_raises(ValueError):\n choi_1 = np.array([[1, 2, 3], [4, 5, 6]])\n choi_2 = np.array([[1, 2, 3], [4, 5, 6]])\n diamond_norm(choi_1, choi_2)",
"def test_diff_penalty_diagonals_datasize_too_small():\n with pytest.raises(ValueError):\n _banded_utils.diff_penalty_diagonals(0)\n with pytest.raises(ValueError):\n _banded_utils.diff_penalty_diagonals(-1)",
"def test_edge_dirc_spec(self):\n with self.assertRaises(ValueError):\n ed.Edge(\"O\",\"1\")",
"def test_analytic_raise_error(self):\n self.fitting_problem.hessian = None\n with self.assertRaises(exceptions.NoHessianError):\n Analytic(self.cost_func.problem, self.jacobian)",
"def test_estimation_cost_error(norm, error):\n with pytest.raises(ValueError, match=\"must be greater than zero\"):\n qml.resource.DoubleFactorization.estimation_cost(norm, error)",
"def test_gaussian_euclidean_ndim_invalid(shape):\n x = jnp.ones(shape=shape)\n\n with pytest.raises(ValueError) as e:\n metrics.gaussian_euclidean(x)\n assert \"The mass matrix has the wrong number of dimensions\" in str(e)",
"def test_bad_instructions():\n # Given\n canvas = ['C', 20, 4]\n instructions = ['C', 2, 4, 5, 6]\n # When\n dw = drawingTool.Drawer(canvas, instructions)\n # Expected\n with pytest.raises(InvalidArgumentType):\n dw.graph()",
"def test_circuit_init_except(self):\n circuit = self.simple_circuit_with_measure()\n self.assertRaises(QiskitError, SuperOp, circuit)",
"def test_arithmetic_errors(self):\n H = qml.Hamiltonian([1], [qml.PauliZ(0)])\n A = [[1, 0], [0, -1]]\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n _ = H @ A\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n _ = A @ H\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n _ = H + A\n with pytest.raises(TypeError, match=\"can't multiply sequence by non-int\"):\n _ = H * A\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n _ = H - A\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n H += A\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n H *= A\n with pytest.raises(TypeError, match=\"unsupported operand type\"):\n H -= A"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests that custom error is raised in the default generator representation.
|
def test_generator_undefined(self):
with pytest.raises(qml.operation.GeneratorUndefinedError):
gate.generator()
|
[
"def test_custom_formatting():\r\n \r\n try: SampleAPI.execute('custom_err.fail')\r\n except Exception, e:\r\n assert e.data['error'] == True\r\n assert 'desc' in e.data\r\n assert e.data['num'] == 99\r\n # hook can modified the error instance directly\r\n assert e.http_status == 555\r\n assert e.custom_arg == True",
"def test_accept_custom_exception_text():\n custom_converter = lambda value: value + \" converted\"\n custom_type = hug.types.accept(custom_converter, \"A string Value\", \"Error occurred\")\n assert custom_type(\"bacon\") == \"bacon converted\"\n with pytest.raises(ValueError):\n custom_type(1)",
"def test_throw_runtime_error(self):\n with self.assertRaisesRegex(RuntimeError, \"runtime_error\"):\n throw_runtime_error()",
"def test_base_error_raises():\n with pytest.raises(PypyrSlackError) as err_info:\n raise PypyrSlackError(\"this is error text right here\")\n\n assert str(err_info.value) == \"this is error text right here\"",
"def test_from_exception_random(self):\r\n exc = errors.LibraryError.from_exception(ValueError(\"visa.dll\"), \"visa.dll\")\r\n assert \"Error while accessing\" in str(exc)",
"def test_create_type():\n\n @hug.type(\n extend=hug.types.text,\n exception_handlers={TypeError: ValueError, LookupError: \"Hi!\"},\n error_text=\"Invalid\",\n )\n def prefixed_string(value):\n if value == \"hi\":\n raise TypeError(\"Repeat of prefix\")\n elif value == \"bye\":\n raise LookupError(\"Never say goodbye!\")\n elif value == \"1+1\":\n raise ArithmeticError(\"Testing different error types\")\n return \"hi-\" + value\n\n assert prefixed_string(\"there\") == \"hi-there\"\n with pytest.raises(ValueError):\n prefixed_string([])\n with pytest.raises(ValueError):\n prefixed_string(\"hi\")\n with pytest.raises(ValueError):\n prefixed_string(\"bye\")\n\n @hug.type(extend=hug.types.text, exception_handlers={TypeError: ValueError})\n def prefixed_string(value):\n if value == \"1+1\":\n raise ArithmeticError(\"Testing different error types\")\n return \"hi-\" + value\n\n with pytest.raises(ArithmeticError):\n prefixed_string(\"1+1\")\n\n @hug.type(extend=hug.types.text)\n def prefixed_string(value):\n return \"hi-\" + value\n\n assert prefixed_string(\"there\") == \"hi-there\"\n\n @hug.type(extend=hug.types.one_of)\n def numbered(value):\n return int(value)\n\n assert numbered([\"1\", \"2\", \"3\"])(\"1\") == 1",
"def test_accept_custom_exception_handlers():\n custom_converter = lambda value: (str(int(value)) if value else value) + \" converted\"\n custom_type = hug.types.accept(\n custom_converter, \"A string Value\", exception_handlers={TypeError: \"0 provided\"}\n )\n assert custom_type(\"1\") == \"1 converted\"\n with pytest.raises(ValueError):\n custom_type(\"bacon\")\n with pytest.raises(ValueError):\n custom_type(0)\n\n custom_type = hug.types.accept(\n custom_converter, \"A string Value\", exception_handlers={TypeError: KeyError}\n )\n with pytest.raises(KeyError):\n custom_type(0)",
"def test_meta_fail(self):\n with self.assertRaises(ValueError):\n self.resource.meta()",
"def test_return_raises(self):\n with self.assertRaises(TypeError):\n # Thi function should raise TypeErrors\n type_hint_test(1, 'x', 'x')",
"def test_person_valueerror_not_mutate():\n person = Person()\n data = {\n 'is_organization': True\n }\n assert_raises(ValueError, person.format_data_set, data)",
"def test_bad_grammar(self):\n assert_raises(BadGrammar, Grammar, 'just a bunch of junk')",
"def test_error(self):\n results = yield self.runCommand(\n command_bogusCommand,\n script=\"calendarserver_config\")\n self.assertEquals(results[\"error\"], \"Unknown command 'bogus'\")",
"def testBlank(self):\n self.assertRaises(roman_noRe.InvalidRomanNumeralError,roman_noRe.fromRoman,\"\")",
"def test_base_multierror():\n\n exc = MultiError([ZeroDivisionError(), KeyboardInterrupt()])\n assert type(exc) is MultiError",
"def test_eval_bad_input_msg_failure(self):\n\n def test_func():\n raise ValueError(\"test func\")\n\n with pytest.raises(AssertionError) as aerr:\n testing.eval_bad_input(test_func, ValueError, \"testing function\")\n\n assert str(aerr).find(\"unexpected error message\") >= 0\n return",
"def test_eval_bad_input_type_failure(self, error):\n\n def test_func():\n raise ValueError(\"test func\")\n\n with pytest.raises(ValueError) as verr:\n testing.eval_bad_input(test_func, error, \"test func\")\n\n assert str(verr).find(\"test func\") >= 0\n return",
"def test_non_base_multierror():\n\n exc = MultiError([ZeroDivisionError(), ValueError()])\n assert type(exc) is NonBaseMultiError\n assert isinstance(exc, ExceptionGroup)",
"def test_decode_data_errors(self):\n self.assert_raises(ValueError, self.import_cls.decode_data, 'hello', None)",
"def test_PlasmaPyError_subclassing(exception):\n with pytest.raises(PlasmaPyError, message=(\n f\"Problem with subclassing of {exception}\")):\n raise exception(\"I'm sorry, Dave. I'm afraid I can't do that.\")",
"def test_atom_exception(self):\n with pytest.raises(ValueError):\n assert Atom(0, 0, 0)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test that the default of an operation raised to a zero power is an empty array.
|
def test_pow_zero(self):
assert len(gate.pow(0)) == 0
|
[
"def test_11_empty_input(self):\n out, err = self._iquery(\n 'create temp array empty<val:double>[k=0:39:4:20]',\n quiet=False)\n assert not err, err\n self._array_cleanups.append(\"empty\")\n out, err = self._iquery('redimension(empty, <val:double>[k=0:39:3])',\n format='tsv+', no_fetch=False)\n assert not err, err\n assert not out, \"Redim of empty array is not empty: '%s'\" % out",
"def test_optional_array_no_input():\n length = 10\n output = _validation._check_optional_array(length, None)\n\n assert isinstance(output, np.ndarray)\n assert_array_equal(output, np.ones(length))",
"def test_exponential_zeros(self):\n data = [0, 0, 0, 0]\n exp = mc.experiment([])\n result = exp.calculateBitsExponential(data)\n # holds value of 0 exponential and word to hold the number of bits\n numBits = 1 + mc.bitsStandardWord\n self.assertEqual(result, numBits)",
"def test_default_work_empty():\n assert Work().empty()",
"def test_zeros(self):\n win_s, hop_s = 1024, 256\n f = pvoc (win_s, hop_s)\n t = fvec (hop_s)\n for _ in range( int ( 4 * win_s / hop_s ) ):\n s = f(t)\n r = f.rdo(s)\n assert_equal ( t, 0.)\n assert_equal ( s.norm, 0.)\n assert_equal ( s.phas, 0.)\n assert_equal ( r, 0.)",
"def test_diffusion_operator_empty():\n with pytest.raises(AssertionError):\n diffusion_operator([])",
"def testEmpty(self):\n assert Iter.empty(Iter.map(lambda x: x, iter([])))",
"def zero_test():\n x, y , theta, t = simulate(Theta=0)\n if abs(x.max()) > 0 or abs(y.max()) > 0:\n\t\t print \"Error in the numerical scheme!\"\n else:\n\t\t print \"Theta = 0 and epsilon = 0 gives x = y = 0 for all times, as intended.\"",
"def test_pow3_array_none_b1(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(TypeError):\n\t\t\tarrayfunc.pow3(self.data1, maxlen='a')",
"def test_empty(self):\n self.assert_tensor_equal([], index_tensor([]))",
"def zeros(self, *args, **kwargs):\n return self.nplike_lib.zeros(*args, **kwargs)",
"def test_zero_lists():\n arr = [0, 0, 0]\n check_sum_of_four(arr, arr, arr, arr) == len(arr) ** 4",
"def argument_empty_test(self):\n cases = []\n\n cases.append('\\n;; Test operation with empty argument\\n')\n\n case_data = {\n 'op': '',\n 'extended_name': 'arg-empty',\n 'param_type': '',\n 'result_type': '(result v128)',\n 'params': '',\n }\n\n for op in self.BINARY_OPS:\n case_data['op'] = '{lane_type}.{op}'.format(lane_type=self.LANE_TYPE, op=op)\n case_data['extended_name'] = '1st-arg-empty'\n case_data['params'] = SIMD.v128_const('0', self.LANE_TYPE)\n cases.append(AssertInvalid.get_arg_empty_test(**case_data))\n\n case_data['extended_name'] = 'arg-empty'\n case_data['params'] = ''\n cases.append(AssertInvalid.get_arg_empty_test(**case_data))\n\n return '\\n'.join(cases)",
"def test_pow3_basic_array_none_a1(self):\n\t\texpected = self.pyexpected\n\n\t\tarrayfunc.pow3(self.data1)\n\n\t\t# The behavour of assertEqual is modified by addTypeEqualityFunc.\n\t\tself.assertEqual(list(self.data1), expected)",
"def test3c_allzero(self):\n\t\tsz = self.szlist[1]\n\t\tfor func in self.wshp_l:\n\t\t\tthismask = mk_apod_mask(sz, apodsz=0, apod_f=func)\n\t\t\tnnonzero = (thismask != 0).sum()\n\t\t\tself.assertEqual(nnonzero, 0, \\\n\t\t\t\t\"Apod size 0 gives values != 0 (got %d nonzeros)\" % nnonzero)",
"def test_empty_lists_case():\n assert check_sum_of_four([], [], [], []) == 0",
"def testEmpty(self):\n assert Iter.foldl(self.f, 23, self.empty()) == 23\n assert Iter.foldr(self.f, 32, self.empty()) == 32",
"def test_pow3_array_none_d1(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.dataok)\n\n\t\t# This is the actual test.\n\t\ttry:\n\t\t\tarrayfunc.pow3(self.errordataend, matherrors=True)\n\t\texcept OverflowError:\n\t\t\tself.fail('Exception OverflowError raised unexpectedly.')",
"def test_pow3_inf_array_none_b1(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(ArithmeticError):\n\t\t\tarrayfunc.pow3(self.errordataend)",
"def test_empty_lists():\n check_sum_of_four([], [], [], []) == 0"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test that the default of an operation raised to the power of one is a copy.
|
def test_pow_one(self):
pow_gate = gate.pow(1)
assert len(pow_gate) == 1
assert pow_gate[0].__class__ is gate.__class__
|
[
"def testPower(self):\n f8 = self.f8\n self.assertTrue(f8(1, 1, 1) ** 2 == f8(1, 1, 0))",
"def test_pow_method_with_non_numeric_power_raises_error(self):\n\n class DummyOp(qml.operation.Operation):\n r\"\"\"Dummy custom operator\"\"\"\n num_wires = 1\n\n with pytest.raises(ValueError, match=\"Cannot raise an Operator\"):\n _ = DummyOp(wires=[0]) ** DummyOp(wires=[0])",
"def test_copy_add_one():\n print('Testing copy_add_one')\n # List of one element\n x = [1]\n result = accum2.copy_add_one(x)\n introcs.assert_equals([2],result)\n # Make sure x is NOT modified\n introcs.assert_equals([1],x)\n\n # More than one element\n x = [2,5,-1]\n result = accum2.copy_add_one(x)\n introcs.assert_equals([3,6,0],result)\n # Make sure x is NOT modified\n introcs.assert_equals([2,5,-1],x)\n\n # Empty List\n x = []\n result = accum2.copy_add_one(x)\n introcs.assert_equals([],result)\n # Make sure x is NOT modified\n introcs.assert_equals([],x)",
"def test_power_except(self):\n chan = SuperOp(self.depol_sop(1))\n # Non-integer power raises error\n self.assertRaises(QiskitError, chan.power, 0.5)",
"def test_power(val: Union[Val, Real], power: Union[Val, Real], expected: Val):\n assert dataclasses.astuple(val ** power) == pytest.approx(dataclasses.astuple(expected))",
"def _test_copy_copy(self):\n t = TreeNode('t')\n u = TreeNode('u')\n t.append(u)\n self.assertRaises(TypeError, copy, t)\n self.assertRaises(TypeError, copy, u)",
"def testCopy(self):\n lpcopy = copy.copy(self.glp)\n self.assertNotEqual(lpcopy, self.glp)\n self.assertNotEqual(lpcopy.lp, self.glp.lp)",
"def test_negative_powers(self):\n s = rangefunc([1, 2, 3, 0, 5, 6, 4]) # s.cycles() <-> (0,1,2,3)(4,5,6)\n a = Bijection(zip(range(7), \"abcdefg\")).conj(s)\n ii = rangefunc(range(7))\n ia = Permutation(zip(*([\"abcdefg\"]*2)))\n for i in range(13):\n self.assertEqual(ii, (s**i) * (s**-i))\n self.assertEqual(ii, (s**-i) * (s**i))\n self.assertEqual(ia, (a**i) * (a**-i))\n self.assertEqual(ia, (a**-i) * (a**i))",
"def enableCopySpecial(self) -> bool:\n ...",
"def canCopySpecial(self) -> bool:\n ...",
"def __rpow__(self, other):\n return self._instance_handler(other, 'pow', True)",
"def test_if_spectrum_is_cloned():\n mz = numpy.array([10, 20, 30, 40], dtype=\"float\")\n intensities = numpy.array([0, 1, 10, 100], dtype=\"float\")\n spectrum_in = Spectrum(mz=mz, intensities=intensities)\n spectrum_in.set(\"precursor_mz\", 1.)\n\n spectrum = require_precursor_below_mz(spectrum_in)\n spectrum.set(\"testfield\", \"test\")\n\n assert not spectrum_in.get(\"testfield\"), \"Expected input spectrum to remain unchanged.\"",
"def test_copy_ntm(self):\n new_ntm = self.ntm1.copy()\n self.assert_is_copy(new_ntm, self.ntm1)",
"def copied(object, original):",
"def test__EULA__copy_with__0():\n content = 'kimi'\n name = 'Red'\n \n eula = EULA(\n content = content,\n name = name,\n )\n \n copy = eula.copy_with()\n _assert_is_every_attribute_set(copy)\n vampytest.assert_eq(copy, eula)\n vampytest.assert_not_is(copy, eula)",
"def test_copy_default_behavior(ac_dc_network):\n snapshot = ac_dc_network.snapshots[2]\n copied_network = ac_dc_network.copy()\n\n loads = ac_dc_network.loads.index.tolist()\n generators = ac_dc_network.generators.index.tolist()\n copied_loads = copied_network.loads.index.tolist()\n copied_generators = copied_network.generators.index.tolist()\n\n assert loads == copied_loads\n assert generators == copied_generators\n assert not copied_network.snapshots.empty\n assert snapshot in copied_network.snapshots",
"def test__EULA__copy():\n content = 'kimi'\n name = 'Red'\n \n eula = EULA(\n content = content,\n name = name,\n )\n \n copy = eula.copy()\n _assert_is_every_attribute_set(copy)\n vampytest.assert_eq(copy, eula)\n vampytest.assert_not_is(copy, eula)",
"def testCopy(self):\n\t\tfor atomType in atomTypes:\n\t\t\tfor electronState in electronStates:\n\t\t\t\tatom1 = Atom(atomType, electronState, -1, '1*')\n\t\t\t\tatom2 = atom1.copy()\n\t\t\t\tself.assertTrue(atom2 is not None)\n\t\t\t\tself.assertTrue(atom1 is not atom2)\n\t\t\t\tself.assertTrue(atom1.atomType == atom2.atomType)\n\t\t\t\tself.assertTrue(atom1.electronState == atom2.electronState)\n\t\t\t\tself.assertTrue(atom1.charge == atom2.charge)\n\t\t\t\tself.assertTrue(atom1.label == atom2.label)",
"def test_copy(self):\n data = np.arange(24).reshape(2, 3, 4)\n mode_index = {0: [\"idx1\", \"idx2\"],\n 1: [\"idx1\", \"idx2\", \"idx3\"],\n 2: [\"idx1\", \"idx2\", \"idx3\", \"idx4\"],}\n tensor = Tensor(data, mode_names=['pixel_x', 'pixel_y', 'color']).set_mode_index(mode_index=mode_index)\n tensor_copy = tensor.copy()\n assert tensor_copy == tensor\n assert (tensor_copy is not tensor)\n assert (tensor_copy._data is not tensor._data)\n assert (tensor_copy._modes is not tensor._modes)\n assert (tensor_copy._state is not tensor._state)",
"def test_copysign_no_params_g1(self):\n\t\twith self.assertRaises(TypeError):\n\t\t\tarrayfunc.copysign()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests that custom error is raised in the default pow decomposition.
|
def test_pow_undefined(self):
with pytest.raises(qml.operation.PowUndefinedError):
gate.pow(1.234)
|
[
"def test_pow_method_with_non_numeric_power_raises_error(self):\n\n class DummyOp(qml.operation.Operation):\n r\"\"\"Dummy custom operator\"\"\"\n num_wires = 1\n\n with pytest.raises(ValueError, match=\"Cannot raise an Operator\"):\n _ = DummyOp(wires=[0]) ** DummyOp(wires=[0])",
"def test_power_except(self):\n chan = SuperOp(self.depol_sop(1))\n # Non-integer power raises error\n self.assertRaises(QiskitError, chan.power, 0.5)",
"def test_multiply_except(self):\n chan = SuperOp(self.sopI)\n self.assertRaises(QiskitError, chan.multiply, 's')\n self.assertRaises(QiskitError, chan.multiply, chan)",
"def test_pow3_array_num_none_a1(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(TypeError):\n\t\t\tarrayfunc.pow3(self.data1, matherrors='a')",
"def test_pow3_array_array_a2(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1, self.dataoutput)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(TypeError):\n\t\t\tarrayfunc.pow3(self.data1, self.dataoutput, matherrors='a')",
"def test_pow3_inf_array_none_b1(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(ArithmeticError):\n\t\t\tarrayfunc.pow3(self.errordataend)",
"def test_pow3_array_array_c2(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1, self.dataoutput)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(TypeError):\n\t\t\tarrayfunc.pow3(self.data1, self.dataoutput, matherrors='a', maxlen='a')",
"def test_pow3_array_none_d1(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.dataok)\n\n\t\t# This is the actual test.\n\t\ttry:\n\t\t\tarrayfunc.pow3(self.errordataend, matherrors=True)\n\t\texcept OverflowError:\n\t\t\tself.fail('Exception OverflowError raised unexpectedly.')",
"def test_pow3_inf_array_array_a2(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1, self.dataoutput)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(ArithmeticError):\n\t\t\tarrayfunc.pow3(self.errordata, self.dataoutput)",
"def test_base_multierror():\n\n exc = MultiError([ZeroDivisionError(), KeyboardInterrupt()])\n assert type(exc) is MultiError",
"def test_pow3_NaN_array_none_b1(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(ArithmeticError):\n\t\t\tarrayfunc.pow3(self.errordataend)",
"def test_estimation_cost_error(norm, error):\n with pytest.raises(ValueError, match=\"must be greater than zero\"):\n qml.resource.DoubleFactorization.estimation_cost(norm, error)",
"def testConvertionWithExponent(unit_database_custom_conversion) -> None:\n unit_database = unit_database_custom_conversion\n assert approx(abs(100 - unit_database.Convert(\"length\", [(\"m\", 1)], [(\"cm\", 1)], 1)), 5) == 0\n assert approx(abs(10000 - unit_database.Convert(\"length\", [(\"m\", 2)], [(\"cm\", 2)], 1)), 5) == 0\n\n # Doesn't make sense changing the exponent in the from and to\n with pytest.raises(ValueError):\n unit_database.Convert(\"length\", [(\"m\", 2)], [(\"m\", 1)], 1)",
"def test_circuit_init_except(self):\n circuit = self.simple_circuit_with_measure()\n self.assertRaises(QiskitError, SuperOp, circuit)",
"def test_mul_with_not_supported_object_raises_error(self):\n with pytest.raises(ValueError, match=\"Cannot multiply Observable by\"):\n _ = \"dummy\" * qml.PauliX(0)",
"def test_not_a_positive_number_error():\n calc = Calculator(-4)\n with pytest.raises(NotAPositiveNumber):\n result = calc.n_root(2)",
"def test_kparr2eta_error():\n test_kparr = 0.1\n test_z = 9.19508\n pytest.raises(TypeError, cosmo.kparr2eta, test_kparr, test_z)",
"def get_error():\n if DEBUG:\n raise ZeroDivisionError(\"This is a debugging feature.\")",
"def test_real_Pow():\n k = Symbol('k', integer=True, nonzero=True)\n assert (k**(I*pi/log(k))).is_real",
"def test_hamiltonian_invalid_init_exception(self, coeffs, ops):\n with pytest.raises(ValueError, match=\"number of coefficients and operators does not match\"):\n qml.Hamiltonian(coeffs, ops)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests if the function raises an exception if the input operation has no generator
|
def test_no_generator_raise(self):
class CustomOp(qml.operation.Operation):
num_wires = 1
num_params = 1
op = CustomOp(0.5, wires=0)
with pytest.raises(
qml.operation.GeneratorUndefinedError,
match="Operation CustomOp does not have a generator",
):
operation_derivative(op)
|
[
"def test_generator(self):\n def generate(a: int):\n assert check_argument_types()\n yield a\n yield a + 1\n\n gen = generate(1)\n next(gen)",
"def ensure_empty(gen):\n try:\n next(gen)\n return False\n except StopIteration:\n return True",
"def generator_is_empty(generator):\n\ttry:\n\t\tx = generator.next()\n\t\treturn False\n\texcept StopIteration:\n\t\treturn True",
"def testNoGeneratorExpression(self):\n\n self.assertNotIn(_MethodWithGeneratorExpression(), self._code_objects)",
"def test_wrapped_generator_no_return_type_annotation(self):\n @typechecked\n def generate(a: int):\n yield a\n yield a + 1\n\n gen = generate(1)\n next(gen)",
"def isgenerator(obj):\r\n return (isgeneratorfunction(obj)\r\n or getattr(obj, 'testGenerator', None) is not None)",
"def test_square_is_gen(self):\n res = isinstance(square(grid_one, 1), types.GeneratorType)\n self.assertTrue(res)",
"def test_yield_none(self):\n y_empty = yield_empty()\n y_none = yield_none()\n self.assertEqual(next(y_empty), None)\n self.assertEqual(next(y_none), None)",
"def test_in_order_empty_error():\n bst = BinarySearchTree()\n bst_traversal = bst.in_order()\n with pytest.raises(StopIteration):\n next(bst_traversal)",
"def test_square_ind_is_gen(self):\n res = isinstance(square_indices(1), types.GeneratorType)\n self.assertTrue(res)",
"def test_not_iterable(self):\n\n self.assertFalse(isiterable(None))",
"def test_eval_bad_input_success(self, error):\n\n def test_func():\n raise error(\"test func\")\n\n testing.eval_bad_input(test_func, error, \"test func\")\n return",
"def test_build_ops_error():\n qubit = cirq.LineQubit.range(1)\n with pytest.raises(ValueError):\n cirq_utils.qubit_op_to_gate('W', qubit[0])",
"def testOrShortcut(self):\n assert Iter.Or(self.trueerror_maker()) == 1",
"def test_concat_fails_iterable(arg, msg):\n match = f\"'{msg}' object is not iterable\"\n with pytest.raises(TypeError, match=match):\n concat(arg)",
"def test_input_overlap_exceptions(sample_ds_1d):\n with pytest.raises(ValueError) as e:\n BatchGenerator(sample_ds_1d, input_dims={\"x\": 10}, input_overlap={\"x\": 20})\n assert len(e) == 1",
"def test_param_invalid_array_param_type_01(self):\n\t\twith self.assertRaises(TypeError):\n\t\t\tresult = arrayfunc.takewhile('==', self.data, self.dataout, 'e')\n\n\t\t# Check that the exception raised corresponds to the native Python behaviour.\n\t\twith self.assertRaises(TypeError):\n\t\t\tresult = itertools.takewhile(lambda x: x < 1, 99)",
"def test_return_raises(self):\n with self.assertRaises(TypeError):\n # Thi function should raise TypeErrors\n type_hint_test(1, 'x', 'x')",
"def throws_an_error_if_buzz_has_no_input():",
"def test_input_dim_exceptions(sample_ds_1d):\n with pytest.raises(ValueError) as e:\n BatchGenerator(sample_ds_1d, input_dims={\"x\": 110})\n assert len(e) == 1"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test if the function correctly returns the derivative of RX
|
def test_rx(self):
p = 0.3
op = qml.RX(p, wires=0)
derivative = operation_derivative(op)
expected_derivative = 0.5 * np.array(
[[-np.sin(p / 2), -1j * np.cos(p / 2)], [-1j * np.cos(p / 2), -np.sin(p / 2)]]
)
assert np.allclose(derivative, expected_derivative)
op.inv()
derivative_inv = operation_derivative(op)
expected_derivative_inv = 0.5 * np.array(
[[-np.sin(p / 2), 1j * np.cos(p / 2)], [1j * np.cos(p / 2), -np.sin(p / 2)]]
)
assert not np.allclose(derivative, derivative_inv)
assert np.allclose(derivative_inv, expected_derivative_inv)
|
[
"def test_derivative():\n\t# Testing for derivative of exponential at points x=0,1,2\n\tactual = np.array([(np.exp(1)-np.exp(0)), (np.exp(2)-np.exp(0))/2, (np.exp(2)-np.exp(1))])\n\t# Testing implementation\n\tdef exponential():\n\t\tt = np.linspace(0,2,3)\n\t\tex = np.vectorize(np.exp)\n\t\tex = ex(t)\n\t\treturn ex\n\ttrial = np.dot(ac.derivative(0,2,3),exponential())\n\t# Debug message\n\tprint(\"Should be: \",actual,\" but returned this: \",trial)\n\tfor m in range(3):\n\t\tnose.tools.assert_almost_equal(actual[m],trial[m],4)",
"def funcDer(x, func):\n return derivative(func, x, dx)",
"def derivative(x):\n return x * (1 - x)",
"def test_controlled_RX_gradient(self, tol):\n dev = qml.device(\"default.qubit\", wires=2)\n\n @qml.qnode(dev)\n def circuit(x):\n qml.PauliX(wires=0)\n qml.CRX(x, wires=[0, 1])\n return qml.expval(qml.PauliZ(0))\n\n a = 0.542 # any value of a should give zero gradient\n\n # get the analytic gradient\n gradA = circuit.jacobian([a], method=\"A\")\n # get the finite difference gradient\n gradF = circuit.jacobian([a], method=\"F\")\n\n # the expected gradient\n expected = 0\n\n assert np.allclose(gradF, expected, atol=tol, rtol=0)\n assert np.allclose(gradA, expected, atol=tol, rtol=0)\n\n @qml.qnode(dev)\n def circuit1(x):\n qml.RX(x, wires=0)\n qml.CRX(x, wires=[0, 1])\n return qml.expval(qml.PauliZ(0))\n\n b = 0.123 # gradient is -sin(x)\n\n # get the analytic gradient\n gradA = circuit1.jacobian([b], method=\"A\")\n # get the finite difference gradient\n gradF = circuit1.jacobian([b], method=\"F\")\n\n # the expected gradient\n expected = -np.sin(b)\n\n assert np.allclose(gradF, expected, atol=tol, rtol=0)\n assert np.allclose(gradA, expected, atol=tol, rtol=0)",
"def funcDer2(x, func):\n return derivative(funcDer, x, dx, n=1, args=[func])",
"def test_error(err):\n f = lambda x1, x2, x3: np.exp(x1 + x2 + x3)\n x0 = (0, 0, 0)\n dx = 0.1\n maximum = -np.inf\n while True:\n # val = 0\n x = tuple([c+dx for c in x0])\n domain = [(x0[0]+i, x0[1]+i, x0[2]+i) for i in np.linspace(x0[0], x[0], 10)]\n for t in domain:\n if maximum > err:\n # compare(f, t)\n return t\n deriv_t = [part_diff(f, t, i) for i in range(len(t))] # all partial derivatives at point t as vector\n deriv_x = [part_diff(f, x, i) for i in range(len(x))] # all partial derivatives at point x as vector\n right_fact = sum([i**2 for i in (np.array(x) - np.array(x0))])**(1/2) # right factor of formula\n val = (np.matrix(deriv_t) * np.matrix(deriv_x).transpose()) * right_fact # total value\n if val >= maximum:\n maximum = val\n dx += dx",
"def test_second_derivative():\n\t# Testing the second derivative at x = 0,1,2,3,4\n\tactual = np.array([1.47625,6.96536,10.20501, 25.82899, 10.90807])\n\t# Testing impementation\n\tdef exponential():\n\t\tt = np.linspace(0,4,5)\n\t\tex = np.vectorize(np.exp)\n\t\tex = ex(t)\n\t\treturn ex\n\ttrial = np.dot(ac.second_derivative(0,4,5),exponential())\n\t# Debug message\n\tprint(\"Should be: \",actual,\" but returned this \",trial)\n\tfor m in range(5):\n\t\tnose.tools.assert_almost_equal(actual[m],trial[m],4)",
"def test_return_of_non_observable(self, operable_mock_device_2_wires):\n\n def circuit(x):\n qml.RX(x, wires=[0])\n return qml.expval(qml.PauliZ(wires=0)), 0.3\n\n node = qml.QNode(circuit, operable_mock_device_2_wires)\n\n with pytest.raises(QuantumFunctionError, match=\"must return either\"):\n node(0.5)",
"def check_grad_rel(func, grad, x0, *args):\n step = 1.49e-08\n target = approx_fprime(x0, func, step, *args)\n actual = grad(x0, *args)\n delta = target - actual\n # make sure target is not 0\n delta[target > 0] /= target[target > 0]\n return delta",
"def check_grad(fcn,theta0,delta):\n x,dx = fcn(theta0)\n for i in range(len(theta0)):\n theta = theta0.copy()\n theta[i]=theta0[i]+delta\n xp,_ = fcn(theta)\n theta[i]=theta0[i]-delta\n xn,_ = fcn(theta)\n est_grad = (xp-xn)/2/delta\n print('Estimate gradient:')\n print(est_grad )\n print('Returned gradient:')\n print(dx[i])\n print('Error:',((est_grad-dx[i])**2).sum())",
"def test_trace_distance_qnodes_rx_state(self, device):\n dev = qml.device(device, wires=1)\n\n @qml.qnode(dev)\n def circuit0(x):\n qml.RX(x, wires=0)\n return qml.state()\n\n @qml.qnode(dev)\n def circuit1():\n return qml.state()\n\n td = qml.qinfo.trace_distance(circuit0, circuit1, wires0=[0], wires1=[0])(np.pi, None)\n assert qml.math.allclose(td, 1.0)\n\n td = qml.qinfo.trace_distance(circuit1, circuit0, wires0=[0], wires1=[0])(None, np.pi)\n assert qml.math.allclose(td, 1.0)",
"def test_undifferentiable_operation(self, operable_mock_device_2_wires):\n\n def circuit(x):\n qml.BasisState(np.array([x, 0]), wires=[0, 1])\n qml.RX(x, wires=[0])\n return qml.expval(qml.PauliZ(0))\n\n node = qml.QNode(circuit, operable_mock_device_2_wires)\n\n with pytest.raises(ValueError, match=\"Cannot differentiate wrt parameter\"):\n node.jacobian(0.5)",
"def getSecondDerivative(self, *args) -> \"bool\" :\n return _core.SurfaceEvaluator_getSecondDerivative(self, *args)",
"def test_trace_distance_qnodes_rx_tworx_jax_grad(self, param, wire, device, use_jit):\n dev = qml.device(device, wires=wire)\n\n @qml.qnode(dev, interface=\"jax\" if not use_jit else \"jax-jit\")\n def circuit(x):\n qml.RX(x, wires=wire - 1)\n return qml.state()\n\n td_grad = jax.grad(\n qml.qinfo.trace_distance(circuit, circuit, wires0=[wire - 1], wires1=[wire - 1]),\n argnums=[0, 1],\n )\n\n if use_jit:\n td_grad = jax.jit(td_grad)\n\n td_grad = td_grad(\n (jax.numpy.array(param)),\n (jax.numpy.array(2 * param)),\n )\n expected = expected_grad_trace_distance_rx_pauliz(param)\n expected_td = [-expected, expected]\n assert qml.math.allclose(td_grad, expected_td, rtol=1e-04, atol=1e-03)",
"def test_trace_distance_qnodes_rx_tworx_torch_grad(self, param, wire):\n dev = qml.device(\"default.qubit\", wires=wire)\n\n @qml.qnode(dev, interface=\"torch\", diff_method=\"backprop\")\n def circuit(x):\n qml.RX(x, wires=wire - 1)\n return qml.state()\n\n expected = expected_grad_trace_distance_rx_pauliz(param)\n expected_td = [-expected, expected]\n params = (\n torch.tensor(param, dtype=torch.float64, requires_grad=True),\n torch.tensor(2 * param, dtype=torch.float64, requires_grad=True),\n )\n td = qml.qinfo.trace_distance(circuit, circuit, wires0=[wire - 1], wires1=[wire - 1])(\n *params\n )\n td.backward()\n td_grad = [p.grad for p in params]\n assert qml.math.allclose(td_grad, expected_td)",
"def binary_derivative_test(f, x0, x1, d0=1e-5, d1=1e-5, tol=0.02):\n assert(isinstance(f, AMPLExternalFunction))\n y, g, h = f.evaluate_fgh(args=(value(x0), value(x1)))\n yf0, gf0, hf0 = f.evaluate_fgh(args=(value(x0 + d0), value(x1)))\n yb0, gb0, hb0 = f.evaluate_fgh(args=(value(x0 - d0), value(x1)))\n yf1, gf1, hf1 = f.evaluate_fgh(args=(value(x0), value(x1 + d1)))\n yb1, gb1, hb1 = f.evaluate_fgh(args=(value(x0), value(x1 - d1)))\n gf = [(yf0 - y)/d0, (yf1 - y)/d1]\n gb = [-(yb0 - y)/d0, -(yb1 - y)/d1]\n hf = [(gf0[0] - g[0])/d0, (gf0[1] - g[1])/d0, (gf1[1] - g[1])/d1]\n hb = [-(gb0[0] - g[0])/d0, -(gb0[1] - g[1])/d0, -(gb1[1] - g[1])/d1]\n\n zero_cut = 1e-9 # how close to zero before maybe it is zero?\n # check that the forward and backward FD approximations are close enough\n # that the accuracy is good enough for the test and that the detivative\n # is not ~ zero. I know this rough but what can you do?\n\n if abs(g[0]) > zero_cut: # derivative is not 0\n assert(abs((gf[0] - g[0])/g[0]) < tol or\n abs((gb[0] - g[0])/g[0]) < tol or\n between(g[0], gf[0], gb[0]))\n\n if abs(g[1]) > zero_cut and abs((gf[1] - gb[1])/g[1]) < tol:\n assert (abs((gf[1] - g[1])/g[1]) < tol or\n abs((gb[1] - g[1])/g[1]) < tol or\n between(g[1], gf[1], gb[1]))\n\n if abs(h[0]) > zero_cut and abs((hf[0] - hb[0])/h[0]) < tol:\n assert (abs((hf[0] - h[0])/h[0]) < tol or\n abs((hb[0] - h[0])/h[0]) < tol or\n between(h[0], hf[0], hb[0]))\n\n if abs(h[1]) > zero_cut and abs((hf[1] - hb[1])/h[1]) < tol:\n assert (abs((hf[1] - h[1])/h[1]) < tol or\n abs((hb[1] - h[1])/h[1]) < tol or\n between(h[1], hf[1], hb[1]))\n\n if abs(h[2]) > zero_cut and abs((hf[2] - hb[2])/h[2]) < tol:\n assert (abs((hf[2] - h[2])/h[2]) < tol or\n abs((hb[2] - h[2])/h[2]) < tol or\n between(h[2], hf[2], hb[2]))",
"def test_differentiate():\n # Expect exact results\n t = np.linspace(0, 4, 9)\n u = 2*t + 7\n dudt = differentiate(u, dt=t[1]-t[0])\n diff = abs(dudt - 2).max()\n tol = 1E-15\n assert diff < tol",
"def __call__(self, x):\n val = self._f(x)\n if self._diff == 0:\n val += self.eps\n return val",
"def getSecondDerivative(self, *args) -> \"bool\" :\n return _core.CurveEvaluator2D_getSecondDerivative(self, *args)",
"def dxdt_equals_x_true(t):\r\n x = np.exp(t)\r\n return x"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test if the function correctly returns the derivative of PhaseShift
|
def test_phase(self):
p = 0.3
op = qml.PhaseShift(p, wires=0)
derivative = operation_derivative(op)
expected_derivative = np.array([[0, 0], [0, 1j * np.exp(1j * p)]])
assert np.allclose(derivative, expected_derivative)
|
[
"def phase_shift(H, op):\n return -2*np.pi*np.matmul(H, op.tran) / op.DEN",
"def phase_shift(phase):\n\n # sort data\n y = np.argsort(phase)\n data = phase[y]\n\n # double phase data so it goes from 0 to 2\n ph2 = data.copy()\n ph2 = ph2+1.0\n datan = np.concatenate((data,ph2))\n\n #find the largest gap in phase\n\n gaps = datan[1:] - datan[:-1] \n indices = np.where(gaps==max(gaps))[0]\n \n #take data which avoids this gap if gap is greater than 1 then take original data\n\n if datan[indices[0]] >= 1.0:\n\n dataf = data\n \n elif len(indices) == 1:\n\n dataf = data\n\n else:\n \n dataf = datan[(datan>= datan[indices[0]+1]) & (datan < datan[indices[1]+1.0])] \n\n\n phshift = min(dataf)-min(data)\n\n return phshift",
"def _is_phase(phase):\n return phase in [\"+1\", \"-1\"]",
"def test_doppler_shift(self):\n # Test 1\n df = doppler_shift(self.x_sat_1, self.x_obs_1, self.f_ref, c=C)\n np.testing.assert_equal(df[0], -0.008790992659944792)\n\n # Test 2 - Array\n x_sat_arr = np.concatenate([self.x_sat_1, self.x_sat_2], axis=1)\n x_obs_arr = np.concatenate([self.x_obs_1, self.x_obs_2], axis=1)\n\n df_arr = doppler_shift(x_sat_arr, x_obs_arr, self.f_ref, c=C)\n\n np.testing.assert_almost_equal(df_arr, np.array([-0.008790992659944792, -0.002468671789450662]))",
"def derivative(x):\n return x * (1 - x)",
"def test_cphase_phase(self, wires, res):\n commutation = qml.is_commuting(\n qml.CPhase(0.2, wires=wires[0]), qml.PhaseShift(0.1, wires=wires[1])\n )\n assert commutation == res",
"def test_coherent_state_deriv():\n t = symbols('t', is_positive=True)\n alpha = Function('alpha')\n expr = CoherentStateKet(alpha(t), hs=1)\n assert not expr.diff(t).is_zero",
"def _multiply_compute_phase(s1, s2):\n # Compute the number of i and -i phases\n has_minus_i = StabilizerState._get_minus_i_mask(s1, s2)\n has_i = StabilizerState._get_i_mask(s1, s2)\n num_i = np.count_nonzero(has_i)\n num_minus_i = np.count_nonzero(has_minus_i)\n has_minus_phase = ((num_i - num_minus_i) % 4) / 2\n return np.logical_xor(np.logical_xor(s1[-1], s2[-1]), has_minus_phase)",
"def phase_shift(annuli,annulus):\n \n if checks:\n if annulus > len(annuli) or annulus < 0:\n print ('ERROR in input to function:phase_shift. Annulus must be within the array')\n \n delta_t = viscous_timescale(annuli[annulus+1]) - viscous_timescale(annuli[annulus])\n return int(delta_t * sample_ratio)",
"def phase_difference(phi0: np.ndarray, phi1: np.ndarray) -> np.ndarray:\n dphi = phi0-phi1\n dphi = np.mod(dphi+np.pi, 2*np.pi) - np.pi\n return dphi",
"def test_derivative():\n\t# Testing for derivative of exponential at points x=0,1,2\n\tactual = np.array([(np.exp(1)-np.exp(0)), (np.exp(2)-np.exp(0))/2, (np.exp(2)-np.exp(1))])\n\t# Testing implementation\n\tdef exponential():\n\t\tt = np.linspace(0,2,3)\n\t\tex = np.vectorize(np.exp)\n\t\tex = ex(t)\n\t\treturn ex\n\ttrial = np.dot(ac.derivative(0,2,3),exponential())\n\t# Debug message\n\tprint(\"Should be: \",actual,\" but returned this: \",trial)\n\tfor m in range(3):\n\t\tnose.tools.assert_almost_equal(actual[m],trial[m],4)",
"def phase(dp):\n from tayph.vartests import typetest\n import numpy as np\n from astropy.io import ascii\n from astropy.time import Time\n from astropy import units as u, coordinates as coord\n import tayph.util as ut\n dp=check_dp(dp)#Path object\n d=ascii.read(dp/'obs_times',comment=\"#\")#,names=['mjd','time','exptime','airmass'])\n #Not using the named columns because I may not know for sure how many columns\n #there are, and read-ascii breaks if only some columns are named.\n #The second column has to be a date array though.\n\n # t = Time(d['col2'],scale='utc', location=coord.EarthLocation.of_site('paranal'))# I determined that the difference between this and geodetic 0,0,0 is zero.\n t = Time(d['col2'],scale='utc', location=coord.EarthLocation.from_geodetic(0,0,0))\n\n jd = t.jd\n P=paramget('P',dp)\n RA=paramget('RA',dp)\n DEC=paramget('DEC',dp)\n Tc=paramget('Tc',dp)#Needs to be given in BJD!\n\n typetest(P,float,'P in sp.phase()')\n typetest(Tc,float,'Tc in sp.phase()')\n typetest(RA,str,'RA in sp.phase()')\n typetest(DEC,str,'DEC in sp.phase()')\n\n ip_peg = coord.SkyCoord(RA,DEC,unit=(u.hourangle, u.deg), frame='icrs')\n ltt_bary = t.light_travel_time(ip_peg)\n\n n=0.0\n Tc_n=Time(Tc,format='jd',scale='tdb')\n while Tc_n.jd >= min(jd):\n Tc_n=Time(Tc-100.0*n*P,format='jd',scale='tdb')#This is to make sure that the Transit central time PRECEDES the observations (by tens or hundreds or thousands of years). Otherwise, the phase could pick up a minus sign somewhere and be flipped. I wish to avoid that.\n n+=1\n BJD = t.tdb + ltt_bary\n diff = BJD-Tc_n\n phase=((diff.jd) % P)/P\n return phase",
"def delta_function(self, symbol, discretised_symbol):\n raise NotImplementedError",
"def s11_phase_func(x, *p):\n return np.angle(((p[2] - p[1]) / p[2] + 2 * 1j * (x - p[0]) * p[1] / p[0]) / (\n (p[1] + p[2]) / p[2] + 2 * 1j * (x - p[0]) * p[1] / p[0]))",
"def funcDer(x, func):\n return derivative(func, x, dx)",
"def phase(config, first, second):\n lower, upper=min(first, second), max(first, second)\n nswaps=sum(config[lower+1:upper])\n return -1 if nswaps & 1 else 1",
"def test_cphase_z(self, wires, res):\n commutation = qml.is_commuting(qml.CPhase(0.2, wires=wires[0]), qml.PauliZ(wires=wires[1]))\n assert commutation == res",
"def phase_spherical_variance():\n pass",
"def identity_derivative(x):\n return 1.0",
"def zeldovich_step(redshift_start, redshift_end, psi, pos, cosmo):\n omegaM = cosmo.omegaM\n omegaL = cosmo.omegaL\n omegaR = cosmo.omegaR\n boxlen = psi.boxlen\n \n gridsize = len(psi.x.t)\n \n index = np.int32(pos/boxlen*gridsize)\n \n psi1 = psi.x.t[index[0], index[1], index[2]]\n psi2 = psi.y.t[index[0], index[1], index[2]]\n psi3 = psi.z.t[index[0], index[1], index[2]]\n\n dx = boxlen/gridsize\n f = fpeebl(redshift_end, omegaR, omegaM, omegaL)\n D_end = grow(redshift_end, omegaR, omegaM, omegaL)\n D_start = grow(redshift_start, omegaR, omegaM, omegaL) # used for normalization of D to t = 0\n H = hubble(redshift_end, omegaR, omegaM, omegaL)\n \n xfact = D_end/D_start\n vfact = D_end/D_start*H*f/(1+redshift_end) # KLOPT DIT WEL? CHECK EVEN WAAR AL DE FACTOREN VANDAAN KOMEN\n # denk het wel, snelheid heeft verder niets met vorige stappen te maken\n v = vfact * np.array([psi1,psi2,psi3]) # vx,vy,vz\n X = (pos + xfact*(v/vfact))%boxlen\n #~ # Mirror coordinates, because somehow it doesn't match the coordinates put\n #~ # into the constrained field.\n #~ X = boxlen - X # x,y,z\n #~ v = -v\n # FIXED MIRRORING: using different FFT convention now (toolbox.rfftn etc).\n \n return X,v"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test if the function correctly returns the derivative of CRY
|
def test_cry(self):
p = 0.3
op = qml.CRY(p, wires=[0, 1])
derivative = operation_derivative(op)
expected_derivative = 0.5 * np.array(
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, -np.sin(p / 2), -np.cos(p / 2)],
[0, 0, np.cos(p / 2), -np.sin(p / 2)],
]
)
assert np.allclose(derivative, expected_derivative)
|
[
"def test_coherent_state_deriv():\n t = symbols('t', is_positive=True)\n alpha = Function('alpha')\n expr = CoherentStateKet(alpha(t), hs=1)\n assert not expr.diff(t).is_zero",
"def test_derivative():\n\t# Testing for derivative of exponential at points x=0,1,2\n\tactual = np.array([(np.exp(1)-np.exp(0)), (np.exp(2)-np.exp(0))/2, (np.exp(2)-np.exp(1))])\n\t# Testing implementation\n\tdef exponential():\n\t\tt = np.linspace(0,2,3)\n\t\tex = np.vectorize(np.exp)\n\t\tex = ex(t)\n\t\treturn ex\n\ttrial = np.dot(ac.derivative(0,2,3),exponential())\n\t# Debug message\n\tprint(\"Should be: \",actual,\" but returned this: \",trial)\n\tfor m in range(3):\n\t\tnose.tools.assert_almost_equal(actual[m],trial[m],4)",
"def discr_calc(a, b, c):\n\n discriminant = b**2-4*a*c\n\n return(discriminant)",
"def funcDer(x, func):\n return derivative(func, x, dx)",
"def conjugate_function_X(latex_dict: dict) -> str:\n trace_id = str(random.randint(1000000, 9999999))\n logger.info(\"[trace start \" + trace_id + \"]\")\n\n # d1 = sympy.simplify(latex_dict[\"input\"][0][\"LHS\"] - latex_dict[\"input\"][0][\"LHS\"])\n # d2 = sympy.simplify(latex_dict[\"input\"][0][\"LHS\"] - latex_dict[\"input\"][0][\"LHS\"])\n #\n # if (d1 == 0) and (d2 == 0):\n # logger.info(\"[trace end \" + trace_id + \"]\")\n # return \"valid\"\n # else:\n # logger.info(\"[trace end \" + trace_id + \"]\")\n # return \"LHS diff is \" + str(d1) + \"\\nRHS diff is \" + str(d2)\n\n logger.info(\"[trace end \" + trace_id + \"]\")\n return \"no check performed\"",
"def derivative(x):\n return x * (1 - x)",
"def derivative(self, s, k=1):\n self.__check_init()\n s = self.__CC(s)\n k = Integer(k)\n z = self.gp().eval('L(%s,,%s)'%(s,k))\n if 'pole' in z:\n raise ArithmeticError(z)\n elif 'Warning' in z:\n i = z.rfind('\\n')\n msg = z[:i].replace('digits','decimal digits')\n verbose(msg, level=-1)\n return self.__CC(z[i:])\n return self.__CC(z)",
"def test_e_function_subtract_output(self):\n # Try to import before testing\n try:\n import lab3c as lab3cStudent\n except:\n self.fail('lab3c.py contains errors(HINT: run the function and fix errors')\n error_output = 'problem subtracting(HINT: operate(10, 5, \\'subtract\\')'\n self.assertEqual(str(lab3cStudent.operate(10, 5, 'subtract')), '5', msg=error_output)",
"def getThirdDerivative(self, *args) -> \"bool\" :\n return _core.SurfaceEvaluator_getThirdDerivative(self, *args)",
"def getThirdDerivative(self, *args) -> \"bool\" :\n return _core.CurveEvaluator2D_getThirdDerivative(self, *args)",
"def funcDer2(x, func):\n return derivative(funcDer, x, dx, n=1, args=[func])",
"def testD():\n #Test case for valid iscurrency\n result24 = a1.iscurrency('USD')\n cornell.assert_equals = (True, result24)\n \n #test case for invalid iscurrency\n result25 = a1.iscurrency('AAA')\n cornell.assert_equals = (False, result25)\n \n #Test case for invalid iscurrency\n result26 = a1.iscurrency('usd')\n cornell.assert_equals = (False, result26)\n\n #Test case for valid exchange\n result27 = a1.exchange('USD','HKD',1.0)\n cornell.assert_floats_equal(7.82541, result27)",
"def gradchek(w, func, grad, *args):\n # Reasonable value for step size\n epsilon = 1.0e-6\n\n #func = fcnchk(func, len(args))\n #grad = fcnchk(grad, len(args))\n\n # Treat\n nparams = len(w)\n deltaf = np.zeros(nparams)\n step = np.zeros(nparams)\n for i in range(nparams):\n # Move a small way in the ith coordinate of w\n step[i] = 1.0\n fplus = linef(epsilon, func, w, step, *args)\n fminus = linef(-epsilon, func, w, step, *args)\n # Use central difference formula for approximation\n deltaf[i] = 0.5*(fplus - fminus)/epsilon\n step[i] = 0.0\n \n gradient = grad(w, *args)\n print 'Checking gradient ...'\n print\n delta = gradient - deltaf\n print ' analytic diffs delta'\n print\n print np.c_[gradient.T, deltaf.T, delta.T]",
"def costDerivative(self,output, y):\r\n\r\n return (output - y)",
"def test_cnot_cz(self, wires, res):\n commutation = qml.is_commuting(qml.CNOT(wires=wires[0]), qml.CZ(wires=wires[1]))\n assert commutation == res",
"def is_dcp(self):\n return self.args[0].is_convex()",
"def test_get_alpha(self):\n for T in [300, 400, 500, 600, 800, 1000, 1500, 2000]:\n dEdown0 = 1000. * self.alpha0 * (T / self.T0) ** self.n\n dEdown = self.singleExponentialDown.get_alpha(T)\n self.assertAlmostEqual(dEdown0, dEdown, 6)",
"def test_deriv(n=100):\n import numpy as np\n import numpy.random as nr\n import matplotlib.pyplot as mp\n x = 2.0*np.pi*np.arange(n)/n\n z = -np.cos(x)\n y = np.sin(x)\n x_ran = 2.0*np.pi*np.sort(nr.rand(n))\n z_ran = -np.cos(x_ran)\n y_ran = np.sin(x_ran)\n y3 = deriv(z, x=None, npts=3, cyclic=False)/delta(x)\n y3x = deriv(z, x=x, npts=3, cyclic=False)\n y3_ran = deriv(z_ran, x=x_ran, npts=3, cyclic=False)\n y3_cyc = deriv(z, x=None, npts=3, cyclic=True)/delta(x)\n y5 = deriv(z, x=None, npts=5, cyclic=False)/delta(x)\n y5x = deriv(z, x=x, npts=5, cyclic=False)\n y5_ran = deriv(z_ran, x=x_ran, npts=5, cyclic=False)\n y5_cyc = deriv(z, x=None, npts=5, cyclic=True)/delta(x)\n err3 = rms(y - y3)\n err3x = rms(y - y3x)\n err3_cyc = rms(y - y3_cyc)\n err5 = rms(y - y5)\n err5x = rms(y - y5x)\n err5_cyc = rms(y - y5_cyc)\n print 'err3', err3, 'err3x', err3x, 'err3_cyc', err3_cyc\n print 'err5', err5, 'err5x', err5x, 'err5_cyc', err5_cyc\n mp.clf()\n# mp.subplot(2, 1, 1)\n# mp.plot(x, z, label='actual')\n# mp.plot(x_ran, z_ran, label='random')\n# mp.subplot(2, 1, 2)\n mp.plot(x, y, label='actual')\n mp.plot(x, y3, label='3')\n mp.plot(x, y3x, label='3x')\n mp.plot(x_ran, y3_ran, 'o-', label='3 random')\n mp.plot(x, y3_cyc, label='3 cyclic')\n mp.plot(x, y5, label='5')\n mp.plot(x, y5x, label='5x')\n mp.plot(x_ran, y5_ran, 'o-', label='5 random')\n mp.plot(x, y5_cyc, label='5 cyclic')\n mp.legend(loc='best')\n mp.xlim(xmax=2.0*np.pi)",
"def getThirdDerivative(self, *args) -> \"bool\" :\n return _core.CurveEvaluator3D_getThirdDerivative(self, *args)",
"def check_grad(fcn,theta0,delta):\n x,dx = fcn(theta0)\n for i in range(len(theta0)):\n theta = theta0.copy()\n theta[i]=theta0[i]+delta\n xp,_ = fcn(theta)\n theta[i]=theta0[i]-delta\n xn,_ = fcn(theta)\n est_grad = (xp-xn)/2/delta\n print('Estimate gradient:')\n print(est_grad )\n print('Returned gradient:')\n print(dx[i])\n print('Error:',((est_grad-dx[i])**2).sum())"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test if the function correctly returns the derivative of CRY if the wires are not consecutive. This is expected behaviour, since without any other context, the operation derivative should make no assumption about the wire ordering.
|
def test_cry_non_consecutive(self):
p = 0.3
op = qml.CRY(p, wires=[1, 0])
derivative = operation_derivative(op)
expected_derivative = 0.5 * np.array(
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, -np.sin(p / 2), -np.cos(p / 2)],
[0, 0, np.cos(p / 2), -np.sin(p / 2)],
]
)
assert np.allclose(derivative, expected_derivative)
|
[
"def test_cnot_cz(self, wires, res):\n commutation = qml.is_commuting(qml.CNOT(wires=wires[0]), qml.CZ(wires=wires[1]))\n assert commutation == res",
"def test_cnot_x(self, wires, res):\n commutation = qml.is_commuting(qml.CNOT(wires=wires[1]), qml.PauliX(wires=wires[0]))\n assert commutation == res",
"def test_basic_classical_wires(self):\n original = QuantumCircuit(2, 1)\n original.x(0).c_if(original.cregs[0], 0)\n original.x(1).c_if(original.cregs[0], 0)\n # This transpilation shouldn't change anything, but it should succeed. At one point it was\n # triggering an internal logic error and crashing.\n transpiled = PassManager([CommutativeCancellation()]).run(original)\n self.assertEqual(original, transpiled)",
"def test_cnot_multicx(self, wires, res):\n commutation = qml.is_commuting(\n qml.CNOT(wires=wires[0]),\n qml.MultiControlledX(wires=wires[1], control_values=\"111\"),\n )\n assert commutation == res",
"def test_cancellation_not_crossing_between_blocks(self):\n test2 = QuantumCircuit(2, 2)\n with test2.if_test((0, True)):\n test2.x(1)\n with test2.if_test((0, True)):\n test2.cx(0, 1)\n test2.x(1)\n\n passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()])\n new_circuit = passmanager.run(test2)\n self.assertEqual(new_circuit, test2)",
"def test_x_cnot(self, wires, res):\n commutation = qml.is_commuting(qml.PauliX(wires=wires[0]), qml.CNOT(wires=wires[1]))\n assert commutation == res",
"def test_cancellation_not_crossing_block_boundary(self):\n test1 = QuantumCircuit(2, 2)\n test1.x(1)\n with test1.if_test((0, False)):\n test1.cx(0, 1)\n test1.x(1)\n\n passmanager = PassManager([CommutationAnalysis(), CommutativeCancellation()])\n new_circuit = passmanager.run(test1)\n self.assertEqual(new_circuit, test1)",
"def test_cnot_toffoli(self, wires, res):\n commutation = qml.is_commuting(qml.CNOT(wires=wires[0]), qml.Toffoli(wires=wires[1]))\n assert commutation == res",
"def test_coherent_state_deriv():\n t = symbols('t', is_positive=True)\n alpha = Function('alpha')\n expr = CoherentStateKet(alpha(t), hs=1)\n assert not expr.diff(t).is_zero",
"def test_x_cnot(self, wires, res):\n op1 = qml.PauliX(wires=wires[0])\n op2 = qml.CNOT(wires=wires[1])\n assert qml.is_commuting(op1, op2) == res\n assert qml.is_commuting(op2, op1) == res",
"def test_cnot_cascade(self):\n\n qr = QuantumRegister(10, \"qr\")\n circuit = QuantumCircuit(qr)\n circuit.cx(qr[0], qr[1])\n circuit.cx(qr[1], qr[2])\n circuit.cx(qr[2], qr[3])\n circuit.cx(qr[3], qr[4])\n circuit.cx(qr[4], qr[5])\n circuit.cx(qr[5], qr[6])\n circuit.cx(qr[6], qr[7])\n circuit.cx(qr[7], qr[8])\n circuit.cx(qr[8], qr[9])\n\n circuit.cx(qr[8], qr[9])\n circuit.cx(qr[7], qr[8])\n circuit.cx(qr[6], qr[7])\n circuit.cx(qr[5], qr[6])\n circuit.cx(qr[4], qr[5])\n circuit.cx(qr[3], qr[4])\n circuit.cx(qr[2], qr[3])\n circuit.cx(qr[1], qr[2])\n circuit.cx(qr[0], qr[1])\n\n passmanager = PassManager()\n # passmanager.append(CommutativeCancellation())\n passmanager.append(\n [CommutationAnalysis(), CommutativeCancellation(), Size(), FixedPoint(\"size\")],\n do_while=lambda property_set: not property_set[\"size_fixed_point\"],\n )\n new_circuit = passmanager.run(circuit)\n expected = QuantumCircuit(qr)\n\n self.assertEqual(expected, new_circuit)",
"def test_cry_zero_hadamard(self, wires, res):\n commutation = qml.is_commuting(qml.CRY(0.0, wires=wires[0]), qml.Hadamard(wires=wires[1]))\n assert commutation == res",
"def test_cswap_cnot(self, wires, res):\n commutation = qml.is_commuting(qml.CSWAP(wires=wires[0]), qml.CNOT(wires=wires[1]))\n assert commutation == res",
"def test_cry_hadamard(self, wires, res):\n commutation = qml.is_commuting(qml.CRY(0.1, wires=wires[0]), qml.Hadamard(wires=wires[1]))\n assert commutation == res",
"def test_conditional_gates_dont_commute(self):\n\n # ┌───┐┌─┐\n # q_0: ┤ H ├┤M├─────────────\n # └───┘└╥┘ ┌─┐\n # q_1: ──■───╫────■───┤M├───\n # ┌─┴─┐ ║ ┌─┴─┐ └╥┘┌─┐\n # q_2: ┤ X ├─╫──┤ X ├──╫─┤M├\n # └───┘ ║ └─╥─┘ ║ └╥┘\n # ║ ┌──╨──┐ ║ ║\n # c: 2/══════╩═╡ 0x0 ╞═╩══╩═\n # 0 └─────┘ 0 1\n circuit = QuantumCircuit(3, 2)\n circuit.h(0)\n circuit.measure(0, 0)\n circuit.cx(1, 2)\n circuit.cx(1, 2).c_if(circuit.cregs[0], 0)\n circuit.measure([1, 2], [0, 1])\n\n new_pm = PassManager(CommutativeCancellation())\n new_circuit = new_pm.run(circuit)\n\n self.assertEqual(circuit, new_circuit)",
"def test_swap_cnot(self, wires, res):\n commutation = qml.is_commuting(qml.SWAP(wires=wires[0]), qml.CNOT(wires=wires[1]))\n assert commutation == res",
"def test_x_cy(self, wires, res):\n commutation = qml.is_commuting(qml.PauliX(wires=wires[0]), qml.CY(wires=wires[1]))\n assert commutation == res",
"def test_control_bit_of_cnot(self):\n\n qr = QuantumRegister(2, \"qr\")\n circuit = QuantumCircuit(qr)\n circuit.cx(qr[0], qr[1])\n circuit.x(qr[0])\n circuit.cx(qr[0], qr[1])\n\n new_pm = PassManager(CommutativeCancellation())\n new_circuit = new_pm.run(circuit)\n expected = QuantumCircuit(qr)\n expected.cx(qr[0], qr[1])\n expected.x(qr[0])\n expected.cx(qr[0], qr[1])\n\n self.assertEqual(expected, new_circuit)",
"def test_wrong_order_in_finite_difference(self, operable_mock_device_2_wires):\n\n def circuit(x):\n qml.Rot(0.3, x, -0.2, wires=[0])\n return qml.expval(qml.PauliZ(0))\n\n node = qml.QNode(circuit, operable_mock_device_2_wires)\n\n with pytest.raises(ValueError, match=\"Order must be 1 or 2\"):\n node.jacobian(0.5, method=\"F\", order=3)",
"def test_disconnected_gates1(self, do_commutative_analysis):\n circuit1 = QuantumCircuit(4)\n circuit1.cx(0, 1)\n circuit1.cx(2, 3)\n\n # collect linear functions\n circuit2 = PassManager(\n CollectLinearFunctions(do_commutative_analysis=do_commutative_analysis)\n ).run(circuit1)\n\n # check that there are no LinearFunctions present in synthesized_circuit\n self.assertNotIn(\"linear_function\", circuit2.count_ops().keys())"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Make sure that size of input for `heisenberg_expand` method is validated
|
def test_input_validation(self):
class DummyOp(qml.operation.CVOperation):
num_wires = 1
op = DummyOp(wires=1)
with pytest.raises(ValueError, match="Heisenberg matrix is the wrong size"):
U_wrong_size = np.eye(1)
op.heisenberg_expand(U_wrong_size, op.wires)
|
[
"def gaussian_expansion(input_array, n_grid_points, d_max):\n\n return expanded_array",
"def small_input_problem(\n problem: DerivativesTestProblem, max_input_numel: int = 100\n) -> DerivativesTestProblem:\n if problem.input.numel() > max_input_numel:\n skip(\"Input is too large:\" + f\" {problem.input.numel()} > {max_input_numel}\")\n else:\n yield problem",
"def _test_expand_H_single(r):\n x = np.random.random(r)\n\n # Do a valid expand_H() calculation and check dimensions.\n s = r*(r+1)//2\n Hc = np.random.random((r,s))\n H = roi.utils.expand_H(Hc)\n assert H.shape == (r,r**2)\n\n # Check that Hc(x^2) == H(x⊗x).\n Hxx = H @ np.kron(x,x)\n assert np.allclose(Hc @ roi.utils.kron2c(x), Hxx)\n\n # Check properties of the tensor for H.\n Htensor = H.reshape((r,r,r))\n assert np.allclose(Htensor @ x @ x, Hxx)\n for subH in H:\n assert np.allclose(subH, subH.T)",
"def test_get_hamiltonian_from_openfermion_raises():\n with pytest.raises(AssertionError):\n fqe.get_hamiltonian_from_openfermion([])",
"def _e_to_h_on_basis(self, A):\n h = self.realization_of().h()\n sign = lambda B: (-1)**(B.size() - len(B))\n coeff = lambda B: sign(B) * prod(factorial(sum( 1 for part in B if part.issubset(big) )) for big in A)\n R = self.base_ring()\n return h._from_dict({B: R(coeff(B)) for B in A.refinements()},\n remove_zeros=False)",
"def _h_to_e_on_basis(self, A):\n e = self.realization_of().e()\n sign = lambda B: (-1)**(B.size() - len(B))\n coeff = lambda B: (sign(B) * prod(factorial(sum( 1 for part in B if part.issubset(big) ))\n for big in A))\n R = self.base_ring()\n return e._from_dict({B: R(coeff(B)) for B in A.refinements()},\n remove_zeros=False)",
"def bayes_expand(p: Probability) -> Expression:\n if not p.parents:\n return p\n warnings.warn(\n \"Bayes expansion is now auto-normalized to fraction expansion \"\n \"since introducing new rules in Sum.safe in \"\n \"https://github.com/y0-causal-inference/y0/pull/159. Simply use fraction_expand() instead\",\n DeprecationWarning,\n stacklevel=2,\n )\n return p.uncondition().normalize_marginalize(p.children)",
"def _test_expand_G_single(r):\n x = np.random.random(r)\n\n # Do a valid expand_H() calculation and check dimensions.\n s = r*(r+1)*(r+2)//6\n Gc = np.random.random((r,s))\n G = roi.utils.expand_G(Gc)\n assert G.shape == (r,r**3)\n\n # Check that Gc(x^3) == G(x⊗x⊗x).\n Gxxx = G @ np.kron(x,np.kron(x,x))\n assert np.allclose(Gc @ roi.utils.kron3c(x), Gxxx)\n\n # Check properties of the tensor for G.\n Gtensor = G.reshape((r,r,r,r))\n assert np.allclose(Gtensor @ x @ x @ x, Gxxx)\n for subG in G:\n assert np.allclose(subG, subG.T)",
"def _check_input_dim(self, forward_input):\n pass",
"def assert_die_size_within_limits(self, bound_args: BoundArguments) -> None:\n raise NotImplementedError",
"def test_expand_all(self):\n nb_points_per_interval = 4\n nb_itvs_per_side = 2\n nb_intervals_per_side = tf.Variable(nb_itvs_per_side,\n dtype=tf.int64,\n trainable=False)\n low_projection = 1.e-6\n max_abs = tf.constant(2.)\n \n nb_points = 2*nb_points_per_interval*nb_itvs_per_side + 1\n \n # `grid_init` is used as initializer.\n # An initializer must have the same\n # data-type as the tensor it initializes.\n grid_init = numpy.linspace(-nb_itvs_per_side,\n nb_itvs_per_side,\n num=nb_points,\n dtype=numpy.float32)\n grid = tf.Variable(grid_init,\n dtype=tf.float32,\n trainable=False)\n parameters = tf.Variable(tf.random_uniform([2, nb_points], minval=0., maxval=1., dtype=tf.float32),\n dtype=tf.float32,\n trainable=False)\n (grid_exp, parameters_exp, nb_intervals_per_side_exp) = tfuls.expand_all(grid,\n parameters,\n low_projection,\n nb_points_per_interval,\n nb_intervals_per_side,\n max_abs)\n node_expansion = [\n tf.assign(grid, grid_exp, validate_shape=False),\n tf.assign(parameters, parameters_exp, validate_shape=False),\n tf.assign(nb_intervals_per_side, nb_intervals_per_side_exp)\n ]\n with tf.Session() as sess:\n if tf.__version__.startswith('0'):\n tf.initialize_all_variables().run()\n else:\n tf.global_variables_initializer().run()\n print('Number of sampling points per unit interval in the grid: {}'.format(nb_points_per_interval))\n print('Number of unit intervals in the right half of the grid before the expansion: {}'.format(nb_intervals_per_side.eval()))\n print('Largest absolute latent variable plus half the largest quantization bin width: {}'.format(max_abs.eval()))\n print('Grid before the expansion:')\n print(grid.eval())\n print('Parameters of the piecewise linear functions before the expansion:')\n print(parameters.eval())\n sess.run(node_expansion)\n print('Number of unit intervals in the right half of the grid after the expansion: {}'.format(nb_intervals_per_side.eval()))\n print('Grid after the expansion:')\n print(grid.eval())\n print('Parameters of the piecewise linear functions after the expansion:')\n print(parameters.eval())",
"def test_ksb_sig():\n gal = galsim.Gaussian(fwhm=1.0).shear(e1=0.2, e2=0.1)\n psf = galsim.Gaussian(fwhm=0.7)\n gal_img = galsim.Convolve(gal, psf).drawImage(nx=32, ny=32, scale=0.2)\n psf_img = psf.drawImage(nx=16, ny=16, scale=0.2)\n\n # First just check that combination of ksb_sig_weight and ksb_sig_factor is consistent.\n hsmparams1 = galsim.hsm.HSMParams(ksb_sig_weight=2.0)\n result1 = galsim.hsm.EstimateShear(gal_img, psf_img, shear_est='KSB', hsmparams=hsmparams1)\n\n hsmparams2 = galsim.hsm.HSMParams(ksb_sig_weight=1.0, ksb_sig_factor=2.0)\n result2 = galsim.hsm.EstimateShear(gal_img, psf_img, shear_est='KSB', hsmparams=hsmparams2)\n\n np.testing.assert_almost_equal(result1.corrected_g1, result2.corrected_g1, 9,\n \"KSB weight fn width inconsistently manipulated\")\n np.testing.assert_almost_equal(result1.corrected_g2, result2.corrected_g2, 9,\n \"KSB weight fn width inconsistently manipulated\")\n\n # Now check that if we construct a galaxy with an ellipticity gradient, we see the appropriate\n # sign of the response when we change the width of the weight function.\n narrow = galsim.Gaussian(fwhm=1.0).shear(e1=0.2)\n wide = galsim.Gaussian(fwhm=2.0).shear(e1=-0.2)\n gal = narrow + wide\n gal_img = galsim.Convolve(gal, psf).drawImage(nx=32, ny=32, scale=0.2)\n hsmparams_narrow = galsim.hsm.HSMParams() # Default sig_factor=1.0\n result_narrow = galsim.hsm.EstimateShear(gal_img, psf_img, shear_est='KSB',\n hsmparams=hsmparams_narrow)\n hsmparams_wide = galsim.hsm.HSMParams(ksb_sig_factor=2.0)\n result_wide = galsim.hsm.EstimateShear(gal_img, psf_img, shear_est='KSB',\n hsmparams=hsmparams_wide)\n\n np.testing.assert_array_less(result_wide.corrected_g1, result_narrow.corrected_g1,\n \"Galaxy ellipticity gradient not captured by ksb_sig_factor.\")",
"def test_generate_sample_lending_intervals_invalid_num_entries():\n\twith pytest.raises(ValueError):\n\t\tresult = utils.generate_sample_lending_intervals(512, -1, 1489123456, 1489123457)",
"def expand_invalid_trainable_stoch_pulse_grad(x, *args, **kwargs):\n # pylint:disable=unused-argument\n return x",
"def hankel(SElength, wavelength, thickness, q, Iq):\n\n from sas.sascalc.data_util.nxsunit import Converter\n wavelength = Converter(wavelength[1])(wavelength[0],\"A\")\n thickness = Converter(thickness[1])(thickness[0],\"A\")\n Iq = Converter(\"1/cm\")(Iq,\"1/A\") # All models default to inverse centimeters\n SElength = Converter(SElength[1])(SElength[0],\"A\")\n\n G = np.zeros_like(SElength, 'd')\n#==============================================================================\n# Hankel Transform method if \"wavelength\" is a scalar; mono-chromatic SESANS\n#==============================================================================\n for i, SElength_i in enumerate(SElength):\n integral = besselj(0, q*SElength_i)*Iq*q\n G[i] = np.sum(integral)\n G0 = np.sum(Iq*q)\n\n # [m^-1] step size in q, needed for integration\n dq = (q[1]-q[0])\n\n # integration step, convert q into [m**-1] and 2 pi circle integration\n G *= dq*2*pi\n G0 = np.sum(Iq*q)*dq*2*np.pi\n\n P = exp(thickness*wavelength**2/(4*pi**2)*(G-G0))\n\n return P",
"def test_flattened_hernquist():\n\n coeff_path = os.path.abspath(get_pkg_data_filename('data/Snlm-mathematica.csv'))\n\n G = 1.\n M = 1\n a = 1.\n q = 0.9\n\n # Note: this must be the same as in the mathematica notebook\n nmax = 8\n lmax = 8\n\n (Snlm, Serr), (Tnlm, Terr) = compute_coeffs(flattened_hernquist_density,\n nmax=nmax, lmax=lmax, skip_odd=True, skip_m=True,\n M=M, r_s=a, args=(M, a, q))\n\n for l in range(1, lmax+1, 2):\n for m in range(lmax+1):\n assert Snlm[0, l, m] == 0.\n\n m_Snl0 = np.loadtxt(coeff_path, delimiter=',')\n m_Snl0 = m_Snl0[:, ::2] # every other l\n\n assert np.allclose(Snlm[0, ::2, 0], m_Snl0[0])\n\n # check that random points match in gradient and density\n np.random.seed(42)\n n_test = 1024\n r = 10.*np.cbrt(np.random.uniform(0.1**3, 1, size=n_test)) # 1 to 10\n t = np.arccos(2*np.random.uniform(size=n_test) - 1)\n ph = np.random.uniform(0, 2*np.pi, size=n_test)\n x = r*np.cos(ph)*np.sin(t)\n y = r*np.sin(ph)*np.sin(t)\n z = r*np.cos(t)\n xyz = np.vstack((x, y, z))\n\n # confirmed by testing...\n tru_dens = flattened_hernquist_density(xyz[0], xyz[1], xyz[2], M, a, q)\n bfe_dens = density(np.ascontiguousarray(xyz.T), Snlm, Tnlm, M, a)\n assert np.all((np.abs(bfe_dens - tru_dens) / tru_dens) < 0.05) # <5%\n\n tru_grad = np.array([flattened_hernquist_gradient(xyz[0, i], xyz[1, i], xyz[2, i], G, M, a, q)\n for i in range(xyz.shape[1])]).T\n bfe_grad = gradient(np.ascontiguousarray(xyz.T), Snlm, Tnlm, G, M, a).T\n\n # check what typical errors are\n # for j in range(3):\n # pl.hist(np.abs((bfe_grad[j]-tru_grad[j])/tru_grad[j]))\n\n for j in range(3):\n assert np.all(np.abs((bfe_grad[j]-tru_grad[j])/tru_grad[j]) < 0.005) # 0.5%\n\n return\n\n # ------------------------------------------------------------------------\n # plots:\n\n # coefficients\n fig, ax = pl.subplots(1, 1, figsize=(10, 8))\n n, l = np.mgrid[:nmax+1, :lmax+1]\n c = ax.scatter(n.ravel(), l.ravel(), c=Snlm[:, :, 0].ravel(), s=64,\n norm=mpl.colors.SymLogNorm(1E-5), cmap='RdBu_r',\n vmin=-100, vmax=100, linewidths=1., edgecolors='#666666')\n\n ax.xaxis.set_ticks(np.arange(0, nmax+1, 1))\n ax.yaxis.set_ticks(np.arange(0, lmax+1, 1))\n\n ax.set_xlim(-0.5, nmax+0.5)\n ax.set_ylim(-0.5, lmax+0.5)\n\n ax.set_xlabel('$n$')\n ax.set_ylabel('$l$')\n\n tickloc = np.concatenate((-10.**np.arange(2, -5-1, -1),\n 10.**np.arange(-5, 2+1, 1)))\n fig.colorbar(c, ticks=tickloc, format='%.0e')\n fig.tight_layout()\n\n # contour plot in r, t at ph=0\n\n rgrid = np.logspace(-1, 1., 128)\n tgrid = np.linspace(0, np.pi, 128)\n\n r, t = np.meshgrid(rgrid, tgrid)\n x = r*np.sin(t)\n z = r*np.cos(t)\n\n _xyz = np.vstack((x.ravel(), np.zeros_like(x.ravel()), z.ravel()))\n bfe_dens = density(np.ascontiguousarray(_xyz.T), Snlm, Tnlm, M, a)\n true_dens = flattened_hernquist_density(_xyz[0], _xyz[1], _xyz[2], M, a, q)\n\n fig, ax = pl.subplots(1, 1, figsize=(8, 8))\n\n levels = 10**np.linspace(-4.5, 1, 16)\n ax.contour(np.log10(r), t, true_dens.reshape(x.shape),\n levels=levels, colors='k',\n locator=mpl.ticker.LogLocator(), label='True')\n ax.contour(np.log10(r), t, bfe_dens.reshape(x.shape),\n levels=levels, colors='r',\n locator=mpl.ticker.LogLocator(), label='BFE')\n\n ax.legend()\n fig.tight_layout()\n\n pl.show()",
"def assert_explosions_within_limits(self, bound_args: BoundArguments) -> None:\n raise NotImplementedError",
"def hessenbergQ(A):\n m, _ = A.shape\n Q = np.eye(m, dtype=A.dtype)\n\n # Hessenberg Algorithm\n for k in range(m-2):\n x = A[k+1:, k]\n e1 = np.zeros(m-(k+1))\n e1[0] = 1\n\n vk = my_sign(x[0])*np.linalg.norm(x)*e1 + x\n vk = vk/np.linalg.norm(vk)\n\n A[k+1:, k:] = A[k+1:, k:] - 2*np.outer(vk, vk.conjugate().T.dot(A[k+1:, k:]))\n A[:, k+1:] = A[:, k+1:] - 2*np.dot(A[:, k+1:], np.outer(vk, vk).conjugate().T)\n\n # Adapted to find Q\n Q[k+1:, :] = Q[k+1:, :] - 2*np.outer(vk, vk.conj().dot(Q[k+1:, :]))\n \n return Q.conj().T",
"def overflow(contigs, size, decreasing=True):\n # calculate sum of the lengths of the contigs is no length was given\n if size is None:\n size = sum(contigs)\n # sort the list of contig lengths\n sorted_contigs = sorted(contigs, reverse=decreasing)\n # add contig lengths one by one, until half of the given length is reached\n p, running_size = 0, 0.0\n while running_size < (size / 2):\n running_size += sorted_contigs[p]\n p += 1\n return sorted_contigs[p - 1]",
"def test_augment_q(Q):\n M, b = augment_Q(Q)\n assert M.shape == (10, 10)\n assert b.shape == (10, 1)\n assert all(b[0:-1]) == 0\n assert b[-1] == 1"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Ensure that `heisenberg_expand` raises exception if it receives an array with order > 2
|
def test_wrong_input_shape(self):
class DummyOp(qml.operation.CVOperation):
num_wires = 1
op = DummyOp(wires=1)
with pytest.raises(ValueError, match="Only order-1 and order-2 arrays supported"):
U_high_order = np.array([np.eye(3)] * 3)
op.heisenberg_expand(U_high_order, op.wires)
|
[
"def test_series_empty():\n with pytest.raises(ValueError):\n expand_grid(others={\"x\": pd.Series([], dtype=int)})",
"def test_unflatten_error_too_many_elements(self):\n\n reshaped = np.reshape(flat_dummy_array, (16, 2, 2))\n\n with pytest.raises(ValueError, match=\"Flattened iterable has more elements than the model\"):\n unflatten(np.concatenate([flat_dummy_array, flat_dummy_array]), reshaped)",
"def test_param_invalid_input_array_param_value(self):\n\t\twith self.assertRaises(TypeError):\n\t\t\tresult = arrayfunc.takewhile('==', 99, self.dataout, 100)\n\n\t\t# Check that the exception raised corresponds to the native Python behaviour.\n\t\twith self.assertRaises(TypeError):\n\t\t\tresult = itertools.takewhile(lambda x: x < 1, 99)",
"def test_param_invalid_array_param_type_01(self):\n\t\twith self.assertRaises(TypeError):\n\t\t\tresult = arrayfunc.takewhile('==', self.data, self.dataout, 'e')\n\n\t\t# Check that the exception raised corresponds to the native Python behaviour.\n\t\twith self.assertRaises(TypeError):\n\t\t\tresult = itertools.takewhile(lambda x: x < 1, 99)",
"def test_param_invalid_output_array_param_value(self):\n\t\twith self.assertRaises(TypeError):\n\t\t\tresult = arrayfunc.takewhile('==', self.data, 99, 100)\n\n\t\t# Check that the exception raised corresponds to the native Python behaviour.\n\t\twith self.assertRaises(TypeError):\n\t\t\tresult = itertools.takewhile(lambda x: x < 1, 99)",
"def test_expand_groups_unknown() -> None:\n with pytest.raises(KeyError):\n Environment._expand_groups([\"$list\", \"$UNKNOWN\", \"$str\", \"end\"], _GROUPS)",
"def test_param_invalid_input_array_param_length(self):\n\t\twith self.assertRaises(IndexError):\n\t\t\tresult = arrayfunc.takewhile('==', self.dataempty, self.dataout, 100.0)",
"def test_pow3_array_array_b2(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1, self.dataoutput)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(TypeError):\n\t\t\tarrayfunc.pow3(self.data1, self.dataoutput, maxlen='a')",
"def test_param_invalid_output_array_param_length(self):\n\t\twith self.assertRaises(IndexError):\n\t\t\tresult = arrayfunc.takewhile('==', self.data, self.dataempty, 100.0)",
"def test_get_hamiltonian_from_openfermion_raises():\n with pytest.raises(AssertionError):\n fqe.get_hamiltonian_from_openfermion([])",
"def test_pow3_inf_array_array_a2(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1, self.dataoutput)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(ArithmeticError):\n\t\t\tarrayfunc.pow3(self.errordata, self.dataoutput)",
"def test_dequeue_empty_list_raise_error(new_empty_q):\n with pytest.raises(IndexError):\n new_empty_q.dequeue()",
"def test_pow3_array_none_b1(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(TypeError):\n\t\t\tarrayfunc.pow3(self.data1, maxlen='a')",
"def test_abs__array_array_b2(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.abs_(self.inparray1a, self.dataout, maxlen=self.testmaxlen)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(TypeError):\n\t\t\tarrayfunc.abs_(self.inparray1b, self.dataout, maxlen='a')",
"def test_pow3_inf_array_none_b1(self):\n\t\t# This version is expected to pass.\n\t\tarrayfunc.pow3(self.data1)\n\n\t\t# This is the actual test.\n\t\twith self.assertRaises(ArithmeticError):\n\t\t\tarrayfunc.pow3(self.errordataend)",
"def test_concat_fails_iterable(arg, msg):\n match = f\"'{msg}' object is not iterable\"\n with pytest.raises(TypeError, match=match):\n concat(arg)",
"def test_impossibleOrder(self):\n\n warehouses = [{'name': 'warehouse1',\n 'inventory': {'product1': 5}},\n {'name': 'warehouse2',\n 'inventory': {'product1': 5}}]\n order = {'product1': 5, 'product2': 5}\n output = []\n\n allocateor = InventoryAllocator(order, warehouses)\n self.assertEqual(allocateor.getInventoryDistribution(), output)",
"def assert_explosions_within_limits(self, bound_args: BoundArguments) -> None:\n raise NotImplementedError",
"def test_explode_empty_explosion_selection(self):\n a = [\n (0, [\"A\", \"B\", \"C\"]),\n (1, [\"D\"]),\n (2, [\"E\", \"F\"]),\n (3, [])\n ]\n\n expected = [\n (0, \"A\"),\n (0, \"B\"),\n (0, \"C\"),\n (1, \"D\"),\n (2, \"E\"),\n (2, \"F\")\n ]\n\n self.assertListEqual(list(explode(a, itemgetter(1))), expected)",
"def test_InvGamma2D():\n\n # Test sample() method:\n prior = dpmm.InvGamma2D(1.0, 1.0, np.array([0.0, 0.0]))\n arr = prior.sample()\n assert isinstance(arr, float)\n\n arr = prior.sample(size=1)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (1,)\n assert arr.dtype == float\n\n arr = prior.sample(size=(1,))\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (1,)\n assert arr.dtype == float\n\n arr = prior.sample(size=10)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (10,)\n assert arr.dtype == float\n\n arr = prior.sample(size=(10, 20))\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (10, 20)\n assert arr.dtype == float\n\n # Test like1() method:\n prior = dpmm.InvGamma2D(1.0, 1.0, np.array([0.0, 0.0]))\n x = np.array([1.0, 2.0]) # Data is 2D, so trailing axis should always be len 2.\n var = 1.0\n arr = prior.like1(x, var)\n assert isinstance(arr, float)\n\n x = np.array([1.0]) # If trailing axis is not 2, then should get an AssertionError\n var = 1.0\n np.testing.assert_raises(AssertionError, prior.like1, x, var)\n\n x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])\n var = 1.0\n arr = prior.like1(x, var)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (3,)\n assert arr.dtype == float\n for i, r in np.ndenumerate(arr):\n assert r == prior.like1(x[i], var)\n\n x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])\n var = np.array([2.0, 3.0])\n arr = prior.like1(x, var[:, np.newaxis])\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (2, 3)\n assert arr.dtype == float\n for (i, j), r in np.ndenumerate(arr):\n assert r == prior.like1(x[j], var[i])\n\n x = np.arange(24, dtype=float).reshape(3, 4, 2)\n var = np.array([2.0, 3.0])\n arr = prior.like1(x[:,:,np.newaxis,:], var)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (3, 4, 2)\n assert arr.dtype == float\n for (i, j, k), r in np.ndenumerate(arr):\n assert r == prior.like1(x[i, j], var[k])\n\n x = np.arange(24, dtype=float).reshape(3, 4, 2)\n var = np.arange(12, dtype=float).reshape(3, 4) + 1 # add 1 so we don't divide by zero\n arr = prior.like1(x, var)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (3, 4)\n assert arr.dtype == float\n for (i, j), r in np.ndenumerate(arr):\n assert r == prior.like1(x[i, j], var[i, j])\n\n # Test __call__() method:\n prior = dpmm.InvGamma2D(1.0, 1.0, np.array([0.0, 0.0]))\n var = 1.0\n arr = prior(var)\n assert isinstance(arr, float)\n\n var = np.array([1.0])\n arr = prior(var)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (1,)\n assert arr.dtype == float\n assert arr[0] == prior(var[0])\n\n var = np.array([1.0, 2.0])\n arr = prior(var)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (2,)\n assert arr.dtype == float\n for i, r in np.ndenumerate(arr):\n assert r == prior(var[i])\n\n var = np.array([[1.0, 2.0], [3.0, 4.0]])\n arr = prior(var)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (2, 2)\n assert arr.dtype == float\n for (i, j), r in np.ndenumerate(arr):\n assert r == prior(var[i, j])\n\n # Should _post_params method do any broadcasting?\n\n # Test pred method():\n prior = dpmm.InvGamma2D(1.0, 1.0, np.array([0.0, 0.0]))\n x = 1.0\n np.testing.assert_raises(AssertionError, prior.pred, x)\n\n x = np.array([1.0, 2.0])\n arr = prior.pred(x)\n assert isinstance(arr, float)\n\n x = np.arange(24, dtype=float).reshape(3, 4, 2)\n arr = prior.pred(x)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (3, 4)\n assert arr.dtype == float\n for (i, j), r in np.ndenumerate(arr):\n assert r == prior.pred(x[i, j])"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test the case where the wire_order is None it returns the original matrix
|
def test_no_wire_order_returns_base_matrix(self):
res = qml.operation.expand_matrix(self.base_matrix_2, wires=[0, 2])
assert np.allclose(self.base_matrix_2, res)
|
[
"def test_sparse_matrix_extra_wire(self):\n\n t = qml.PauliX(0) @ qml.PauliZ(1)\n s = t.sparse_matrix(wires=[0, 1, 2])\n\n assert s.shape == (8, 8)\n assert np.allclose(s.data, [1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0])\n assert np.allclose(s.indices, [4, 5, 6, 7, 0, 1, 2, 3])\n assert np.allclose(s.indptr, [0, 1, 2, 3, 4, 5, 6, 7, 8])",
"def simple_material(mat):\n return (mat is not None) and (not mat.use_nodes)",
"def test_has_matrix_false_concrete_template(self):\n\n rng = qml.numpy.random.default_rng(seed=42)\n shape = qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=2)\n params = rng.random(shape)\n op = qml.StronglyEntanglingLayers(params, wires=range(2))\n assert not op.has_matrix",
"def test_weightmolar_reversal(self):\n renorm = False\n for renorm in [True, False]:\n with self.subTest(renorm=renorm):\n M = to_molecular(self.df.loc[:, self.components],\n renorm=renorm)\n W = to_weight(self.df.loc[:, self.components],\n renorm=renorm)\n\n W_M = to_weight(M, renorm=renorm)\n M_W = to_molecular(W, renorm=renorm)\n\n # Where values are not close, it's because of nans\n original = self.df.loc[:, self.components]\n if renorm:\n original = renormalise(original, components=self.components)\n W_M_close = np.isclose(W_M.values, original.values)\n self.assertTrue(np.isnan(W_M.values[~W_M_close]).all())\n\n M_W_close = np.isclose(M_W.values, original.values)\n self.assertTrue(np.isnan(M_W.values[~M_W_close]).all())",
"def _format_single_matrix(op):\n # This can be specified as list [[coeff, Pauli], ... ]\n if isinstance(op, numpy.ndarray):\n return op\n if isinstance(op, (Instruction, QuantumCircuit)):\n return Operator(op).data\n if hasattr(op, 'to_operator'):\n return op.to_operator().data\n return None",
"def test_difference_matrix_order_0():\n diff_matrix = _banded_utils.difference_matrix(10, 0).toarray()\n actual_matrix = identity(10).toarray()\n\n assert_array_equal(diff_matrix, actual_matrix)",
"def check_matrix_equality(self, conn, w):\n pos = conn.positive\n neg = conn.negative\n wPos = pos.getConnectionState('weight')\n wNeg = neg.getConnectionState('weight')\n ww = wPos + wNeg\n self.assertEqual(np.array_equal(ww, w), True)",
"def SoViewingMatrixElement_get(state: 'SoState') -> \"SbMatrix const &\":\n return _coin.SoViewingMatrixElement_get(state)",
"def test_inv_3d_blockmatrix_odd(self):\n matrix = np.random.rand(3, 5, 5)\n with self.assertRaises(ValueError):\n inversematrix = geometry.inv_3d_blockmatrix(matrix)",
"def getMatrix(self, action: 'SoGetMatrixAction') -> \"void\":\n return _coin.SoSwitch_getMatrix(self, action)",
"def getMatrix(self, action: 'SoGetMatrixAction') -> \"void\":\n return _coin.SoPointLightManip_getMatrix(self, action)",
"def getMatrix(self, action: 'SoGetMatrixAction') -> \"void\":\n return _coin.SoDirectionalLightManip_getMatrix(self, action)",
"def get_bone_extra_matrix_inv(self, bonename):\n return self.bones_extra_matrix_inv[self.get_bone_name_for_blender(bonename)]",
"def get(state: 'SoState') -> \"SbMatrix const &\":\n return _coin.SoViewingMatrixElement_get(state)",
"def getMatrix(self, action: 'SoGetMatrixAction') -> \"void\":\n return _coin.SoResetTransform_getMatrix(self, action)",
"def influence_matrix(self) -> np.ndarray:",
"def getMatrix(self, action: 'SoGetMatrixAction') -> \"void\":\n return _coin.SoMatrixTransform_getMatrix(self, action)",
"def test_erode_binary_matrix_first(self):\n\n this_matrix = general_utils.erode_binary_matrix(\n binary_matrix=TOY_MASK_MATRIX,\n buffer_distance_px=FIRST_DILATION_DISTANCE_PX\n )\n\n self.assertTrue(numpy.array_equal(\n this_matrix, FIRST_ERODED_MASK_MATRIX\n ))",
"def SoModelMatrixElement_get(*args) -> \"SbMatrix const &\":\n return _coin.SoModelMatrixElement_get(*args)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests the case where the broadcasted original matrix is not changed
|
def test_no_expansion_broadcasted(self):
res = qml.operation.expand_matrix(
self.base_matrix_2_broadcasted, wires=[0, 2], wire_order=[0, 2]
)
assert np.allclose(self.base_matrix_2_broadcasted, res)
|
[
"def test_permutation_broadcasted(self):\n res = qml.operation.expand_matrix(\n self.base_matrix_2_broadcasted, wires=[0, 2], wire_order=[2, 0]\n )\n\n perm = [0, 2, 1, 3]\n expected = self.base_matrix_2_broadcasted[:, perm][:, :, perm]\n assert np.allclose(expected, res)",
"def test_expansion_broadcasted(self):\n res = qml.operation.expand_matrix(\n self.base_matrix_1_broadcasted, wires=[2], wire_order=[0, 2]\n )\n expected = np.array(\n [\n [\n [1, 2, 0, 0],\n [3, 4, 0, 0],\n [0, 0, 1, 2],\n [0, 0, 3, 4],\n ],\n [\n [5, 6, 0, 0],\n [7, 8, 0, 0],\n [0, 0, 5, 6],\n [0, 0, 7, 8],\n ],\n [\n [9, 10, 0, 0],\n [11, 12, 0, 0],\n [0, 0, 9, 10],\n [0, 0, 11, 12],\n ],\n ]\n )\n assert np.allclose(expected, res)\n\n res = qml.operation.expand_matrix(\n self.base_matrix_1_broadcasted, wires=[2], wire_order=[2, 0]\n )\n expected = np.array(\n [\n [\n [1, 0, 2, 0],\n [0, 1, 0, 2],\n [3, 0, 4, 0],\n [0, 3, 0, 4],\n ],\n [\n [5, 0, 6, 0],\n [0, 5, 0, 6],\n [7, 0, 8, 0],\n [0, 7, 0, 8],\n ],\n [\n [9, 0, 10, 0],\n [0, 9, 0, 10],\n [11, 0, 12, 0],\n [0, 11, 0, 12],\n ],\n ]\n )\n assert np.allclose(expected, res)",
"def test_expand_matrix_usage_in_operator_class_broadcasted(self, tol):\n\n perm = [0, 2, 1, 3]\n permuted_matrix = self.base_matrix_2_broadcasted[:, perm][:, :, perm]\n\n expanded_matrix = np.tensordot(\n np.tensordot(\n np.kron(SWAP, I),\n np.kron(I_broadcasted, self.base_matrix_2_broadcasted),\n axes=[[1], [1]],\n ),\n np.kron(SWAP, I),\n axes=[[2], [0]],\n )\n expanded_matrix = np.moveaxis(expanded_matrix, 0, -2)\n\n class DummyOp(qml.operation.Operator):\n num_wires = 2\n\n def compute_matrix(*params, **hyperparams):\n return self.base_matrix_2_broadcasted\n\n op = DummyOp(wires=[0, 2])\n assert np.allclose(op.matrix(), self.base_matrix_2_broadcasted, atol=tol)\n assert np.allclose(op.matrix(wire_order=[2, 0]), permuted_matrix, atol=tol)\n assert np.allclose(op.matrix(wire_order=[0, 1, 2]), expanded_matrix, atol=tol)",
"def test_euclidean_distance_broadcasting():\n\n point = np.array([1, 1, 1])\n\n matrix = np.array([\n [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]],\n [[4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7]],\n ])\n\n expected = np.array([\n [0, np.sqrt(3), np.sqrt(12), np.sqrt(27)],\n [np.sqrt(27), np.sqrt(48), np.sqrt(75), np.sqrt(108)]\n ])\n\n actual = np.linalg.norm(point - matrix, axis=2)\n\n assert np.all(expected == actual)",
"def test_broadcasting(device):\n dev = qml.device(device, wires=2)\n\n @qml.qnode(dev)\n def circuit_state(x):\n qml.IsingXX(x, wires=[0, 1])\n return qml.state()\n\n x = np.array([0.4, 0.6, 0.8])\n y = np.array([0.6, 0.8, 1.0])\n dist = qml.qinfo.trace_distance(circuit_state, circuit_state, wires0=[0], wires1=[1])(x, y)\n\n expected = 0.5 * (\n np.abs(np.cos(x / 2) ** 2 - np.cos(y / 2) ** 2)\n + np.abs(np.sin(x / 2) ** 2 - np.sin(y / 2) ** 2)\n )\n assert qml.math.allclose(dist, expected)",
"def _conform_for_data_broadcasting(self, other):\n\n other = self._conform_for_assignment(other, check_coordinates=True)\n\n # Remove leading size one dimensions\n ndiff = other.ndim - self.ndim\n if ndiff > 0 and set(other.shape[:ndiff]) == set((1,)):\n for i in range(ndiff):\n other = other.squeeze(0)\n\n return other",
"def test_random_spd_matrix_symmetric(random_spd_matrix: np.ndarray):\n np.testing.assert_equal(random_spd_matrix, random_spd_matrix.T)",
"def test_is_identical_to(self):\n self.assertTrue(self.surfarr.is_identical_to(self.surfarr))",
"def test_matrices_dont_commute(self):\n x0 = qml.PauliX(0)\n z0 = qml.PauliZ(0)\n\n assert not _check_mat_commutation(x0, z0)\n assert not _check_mat_commutation(z0, x0)",
"def test_expand_three_nonconsecutive_nonascending_wires_broadcasted(self, tol):\n # test applied to wire 3, 1, 2\n res = qml.operation.expand_matrix(Toffoli_broadcasted, [3, 1, 2], [0, 1, 2, 3])\n # change the control qubit on the Toffoli gate\n rows = [0, 4, 1, 5, 2, 6, 3, 7]\n Toffoli_broadcasted_perm = Toffoli_broadcasted[:, :, rows][:, rows]\n expected = np.kron(I_broadcasted, Toffoli_broadcasted_perm)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n # test applied to wire 3, 0, 2\n res = qml.operation.expand_matrix(Toffoli_broadcasted, [3, 0, 2], [0, 1, 2, 3])\n # change the control qubit on the Toffoli gate\n expected = np.tensordot(\n np.tensordot(\n np.kron(SWAP, II),\n np.kron(I_broadcasted, Toffoli_broadcasted_perm),\n axes=[[1], [1]],\n ),\n np.kron(SWAP, II),\n axes=[[2], [0]],\n )\n expected = np.moveaxis(expected, 0, -2)\n assert np.allclose(res, expected, atol=tol, rtol=0)",
"def test_copy_matrix():\n A = np.ones((3, 3), dtype=FTYPE)\n B = np.zeros((3, 3), dtype=FTYPE)\n\n copy_matrix_guf(A, B)\n\n test = B\n ref = A\n assert np.array_equal(test, ref), f\"test:\\n{test}\\n!= ref:\\n{ref}\"\n\n logging.info(\"<< PASS : test_copy_matrix >>\")",
"def test_swap_operator_is_block_positive(dim):\n mat = swap_operator(dim)\n np.testing.assert_equal(is_block_positive(mat), True)\n np.testing.assert_equal(is_block_positive(mat, k=2), False)",
"def check_matrix_equality(self, conn, w):\n pos = conn.positive\n neg = conn.negative\n wPos = pos.getConnectionState('weight')\n wNeg = neg.getConnectionState('weight')\n ww = wPos + wNeg\n self.assertEqual(np.array_equal(ww, w), True)",
"def test_difference_matrix_order_0():\n diff_matrix = _banded_utils.difference_matrix(10, 0).toarray()\n actual_matrix = identity(10).toarray()\n\n assert_array_equal(diff_matrix, actual_matrix)",
"def _check_can_broadcast_to(shape, target_shape):\n ndim = len(shape)\n ndim_target = len(target_shape)\n if ndim > ndim_target:\n return False\n for i, j in zip(reversed(shape), reversed(target_shape)):\n if i not in (1, j):\n return False\n return True",
"def test_matrix_equality(self):\n\n m1 = matrices.Matrix(2, 2)\n m1.set_row(0, [1, 2])\n m1.set_row(1, [1, 4])\n\n m2 = matrices.Matrix(2, 2)\n m2.set_row(0, [1, 2])\n m2.set_row(1, [1, 4])\n\n self.assertTrue(m1 == m2)\n\n m2.set(1, 1, 50)\n self.assertFalse(m1 == m2)",
"def identical_matrices(A, B):\n if isinstance(A, scipy.sparse.spmatrix):\n A = A.toarray()\n if isinstance(B, scipy.sparse.spmatrix):\n B = B.toarray()\n return qdyn.linalg.norm(A - B) < 1.0e-14",
"def __eq__(self, ret_mat):\n for i in range(0,8):\n if self.data[i] != ret_mat[i]:\n return False\n return True",
"def test_expand_two_consecutive_wires_broadcasted(self, tol):\n U2 = np.array([[0, 1, 1, 1], [1, 0, 1, -1], [1, -1, 0, 1], [1, 1, -1, 0]]) / np.sqrt(3)\n U2 = np.tensordot([2.31, 1.53, 0.7 - 1.9j], U2, axes=0)\n\n # test applied to wire 0+1\n res = qml.operation.expand_matrix(U2, [0, 1], [0, 1, 2, 3])\n expected = np.kron(np.kron(U2, I_broadcasted), I_broadcasted)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n # test applied to wire 1+2\n res = qml.operation.expand_matrix(U2, [1, 2], [0, 1, 2, 3])\n expected = np.kron(np.kron(I_broadcasted, U2), I_broadcasted)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n # test applied to wire 2+3\n res = qml.operation.expand_matrix(U2, [2, 3], [0, 1, 2, 3])\n expected = np.kron(np.kron(I_broadcasted, I_broadcasted), U2)\n assert np.allclose(res, expected, atol=tol, rtol=0)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests the case where the broadcasted original matrix is permuted
|
def test_permutation_broadcasted(self):
res = qml.operation.expand_matrix(
self.base_matrix_2_broadcasted, wires=[0, 2], wire_order=[2, 0]
)
perm = [0, 2, 1, 3]
expected = self.base_matrix_2_broadcasted[:, perm][:, :, perm]
assert np.allclose(expected, res)
|
[
"def test_permutation_operator_dim_2_2_perm_1_2():\n res = permutation_operator([2, 2], [1, 2])\n expected_res = np.identity(4)\n bool_mat = np.isclose(res, expected_res)\n np.testing.assert_equal(np.all(bool_mat), True)",
"def test_permutation_operator_dim_3_perm_1_2():\n res = permutation_operator(3, [1, 2])\n expected_res = np.identity(9)\n bool_mat = np.isclose(res, expected_res)\n np.testing.assert_equal(np.all(bool_mat), True)",
"def test_permutation_operator_dim_2_2_perm_2_1():\n res = permutation_operator([2, 2], [2, 1])\n expected_res = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])\n bool_mat = np.isclose(res, expected_res)\n np.testing.assert_equal(np.all(bool_mat), True)",
"def test_permutation_operator_dim_2_perm_1_3_2():\n res = permutation_operator(2, [1, 3, 2])\n expected_res = np.array(\n [\n [\n [1, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 1],\n ]\n ]\n )\n bool_mat = np.isclose(res, expected_res)\n np.testing.assert_equal(np.all(bool_mat), True)",
"def test_random_spd_matrix_symmetric(random_spd_matrix: np.ndarray):\n np.testing.assert_equal(random_spd_matrix, random_spd_matrix.T)",
"def permute(self, *dims): # real signature unknown; restored from __doc__\n pass",
"def test_matrix_permutation_inversion( ):\n\n def check( x, perm ):\n m, n = x.shape\n perm_ = sl.invert_matrix_permutation( perm )\n x = sc.randn( m, n )\n y = sl.apply_matrix_permutation( perm_, sl.apply_matrix_permutation( perm, x ) )\n assert all( x == y )\n\n z = sl.apply_matrix_permutation( perm, sl.apply_matrix_permutation( perm_, x ) )\n assert all( x == z )\n\n for i in xrange( 10 ):\n m, n = sc.random.randint( 1, 20 ), sc.random.randint( 1, 20 )\n x = sc.randn( m, n )\n perm = sr.matrix_permutation( m, n )\n\n yield check, x, perm",
"def test_euclidean_distance_broadcasting():\n\n point = np.array([1, 1, 1])\n\n matrix = np.array([\n [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]],\n [[4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7]],\n ])\n\n expected = np.array([\n [0, np.sqrt(3), np.sqrt(12), np.sqrt(27)],\n [np.sqrt(27), np.sqrt(48), np.sqrt(75), np.sqrt(108)]\n ])\n\n actual = np.linalg.norm(point - matrix, axis=2)\n\n assert np.all(expected == actual)",
"def test_kraus_transpose_random(self):\n mats = [self.rand_matrix(4, 4) for _ in range(4)]\n chans = [Kraus(Operator(mat)) for mat in mats]\n self._compare_transpose_to_operator(chans, mats)",
"def test_matrices_dont_commute(self):\n x0 = qml.PauliX(0)\n z0 = qml.PauliZ(0)\n\n assert not _check_mat_commutation(x0, z0)\n assert not _check_mat_commutation(z0, x0)",
"def test_drmsd_permutation():\n a = np.asarray([[0, 0, 0],\n [0, 1, 0],\n [0, 0, 2],\n [0, 0, 0]])\n b = np.asarray([[0, 0, 2],\n [0, 1, 0],\n [0, 0, 0],\n [0, 0, 0]])\n a = torch.tensor(a, dtype=torch.float)\n b = torch.tensor(b, dtype=torch.float)\n assert drmsd(a, b) != 0\n assert drmsd(a, b, truncate_dist_matrix=False) != 0",
"def test_expand_matrix_usage_in_operator_class_broadcasted(self, tol):\n\n perm = [0, 2, 1, 3]\n permuted_matrix = self.base_matrix_2_broadcasted[:, perm][:, :, perm]\n\n expanded_matrix = np.tensordot(\n np.tensordot(\n np.kron(SWAP, I),\n np.kron(I_broadcasted, self.base_matrix_2_broadcasted),\n axes=[[1], [1]],\n ),\n np.kron(SWAP, I),\n axes=[[2], [0]],\n )\n expanded_matrix = np.moveaxis(expanded_matrix, 0, -2)\n\n class DummyOp(qml.operation.Operator):\n num_wires = 2\n\n def compute_matrix(*params, **hyperparams):\n return self.base_matrix_2_broadcasted\n\n op = DummyOp(wires=[0, 2])\n assert np.allclose(op.matrix(), self.base_matrix_2_broadcasted, atol=tol)\n assert np.allclose(op.matrix(wire_order=[2, 0]), permuted_matrix, atol=tol)\n assert np.allclose(op.matrix(wire_order=[0, 1, 2]), expanded_matrix, atol=tol)",
"def test_superop_transpose_random(self):\n mats = [self.rand_matrix(4, 4) for _ in range(4)]\n chans = [SuperOp(Operator(mat)) for mat in mats]\n self._compare_transpose_to_operator(chans, mats)",
"def _check_can_broadcast_to(shape, target_shape):\n ndim = len(shape)\n ndim_target = len(target_shape)\n if ndim > ndim_target:\n return False\n for i, j in zip(reversed(shape), reversed(target_shape)):\n if i not in (1, j):\n return False\n return True",
"def test_ptm_conjugate_random(self):\n mats = [self.rand_matrix(4, 4) for _ in range(4)]\n chans = [PTM(Operator(mat)) for mat in mats]\n self._compare_conjugate_to_operator(chans, mats)",
"def test_assertIsPermutation_true(self):\n observed = [3,2,1,4,5]\n items = [1,2,3,4,5]\n self.assertIsPermutation(observed, items)",
"def test_ptm_transpose(self):\n mats = self.unitaries\n chans = [PTM(mat) for mat in self.ptms]\n self._compare_transpose_to_operator(chans, mats)",
"def test_NormInvWish():\n\n # Test sample() method:\n mu_0 = np.arange(3.0)\n kappa_0 = 3.0\n Lam_0 = np.eye(3) + 0.01*np.arange(9).reshape(3,3)\n Lam_0 += Lam_0.T # To make symmetric\n nu_0 = 3\n prior = dpmm.NormInvWish(mu_0, kappa_0, Lam_0, nu_0)\n arr = prior.sample()\n assert isinstance(arr, np.void)\n assert arr.dtype == prior.model_dtype\n\n arr = prior.sample(size=1)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (1,)\n assert arr.dtype == prior.model_dtype\n\n arr = prior.sample(size=(1,))\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (1,)\n assert arr.dtype == prior.model_dtype\n\n arr = prior.sample(size=10)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (10,)\n assert arr.dtype == prior.model_dtype\n\n arr = prior.sample(size=(10, 20))\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (10, 20)\n assert arr.dtype == prior.model_dtype\n\n # Test like1() method:\n prior = dpmm.NormInvWish(mu_0, kappa_0, Lam_0, nu_0)\n x = np.arange(3.0)\n mu = np.arange(3.0)+1.0\n Sig = np.eye(3) + 0.03*np.arange(9).reshape(3, 3)\n Sig += Sig.T\n arr = prior.like1(x, mu, Sig)\n assert isinstance(arr, float)\n\n # If trailing axis of x is not dim 3 (for these prior parameters), should get and AssertionError\n xbad = np.arange(2.0)\n np.testing.assert_raises(AssertionError, prior.like1, xbad, mu, Sig)\n\n # And similar checks for mu and Sig\n mubad = np.arange(4.0)\n np.testing.assert_raises(AssertionError, prior.like1, x, mubad, Sig)\n\n Sigbad = np.eye(2)\n np.testing.assert_raises(AssertionError, prior.like1, x, mu, Sigbad)\n\n # Try some non-trival broadcasts\n mu = np.arange(6.0).reshape(2, 3)\n arr = prior.like1(x, mu, Sig)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (2,)\n for i, r in np.ndenumerate(arr):\n assert r == prior.like1(x, mu[i], Sig)\n\n theta = np.zeros((2,), dtype=prior.model_dtype)\n theta['mu'] = mu\n theta['Sig'] = Sig\n arr = prior.like1(x, theta)\n for i, r in np.ndenumerate(arr):\n assert r == prior.like1(x, theta[i])\n\n mu = np.empty((3, 4, 3), dtype=float)\n Sig = np.empty((3, 4, 3, 3), dtype=float)\n for i in range(3):\n for j in range(4):\n mu[i, j] = np.arange(3.0)\n Sig[i, j] = np.eye(3)+0.1*i+0.2*j\n arr = prior.like1(x, mu, Sig)\n for (i, j), r in np.ndenumerate(arr):\n assert r == prior.like1(x, mu[i, j], Sig[i, j])\n\n theta = np.empty((3, 4), dtype=prior.model_dtype)\n theta['mu'] = mu\n theta['Sig'] = Sig\n arr = prior.like1(x, theta)\n for (i, j), r in np.ndenumerate(arr):\n assert r == prior.like1(x, theta[i, j])\n\n mu = np.arange(6.0).reshape(2, 3)\n arr = prior.like1(x, mu[:, np.newaxis, np.newaxis, :], Sig)\n for (i, j, k), r in np.ndenumerate(arr):\n assert r == prior.like1(x, mu[i], Sig[j, k])\n\n theta = np.empty((2, 3, 4), dtype=prior.model_dtype)\n theta['mu'] = (np.arange(6.0).reshape(2, 3))[:, np.newaxis, np.newaxis, :]\n theta['Sig'] = Sig\n arr = prior.like1(x, theta)\n for (i, j, k), r in np.ndenumerate(arr):\n assert r == prior.like1(x, theta[i, j, k])\n\n # Test __call__() method:\n prior = dpmm.NormInvWish(mu_0, kappa_0, Lam_0, nu_0)\n mu = np.arange(3.0)\n Sig = np.eye(3)\n arr = prior(mu, Sig)\n assert isinstance(arr, float)\n\n theta = np.zeros(1, dtype=prior.model_dtype)\n theta['mu'] = mu\n theta['Sig'] = Sig\n arr = prior(theta[0])\n assert isinstance(arr, float)\n assert arr == prior(mu, Sig)\n\n mu = np.arange(6.0).reshape(2, 3)\n arr = prior(mu, Sig)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (2,)\n assert arr.dtype == float\n for i, r in np.ndenumerate(arr):\n assert r == prior(mu[i], Sig)\n\n theta = np.zeros(2, dtype=prior.model_dtype)\n theta['mu'] = mu\n theta['Sig'] = Sig\n arr = prior(theta)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (2,)\n assert arr.dtype == float\n for i, r in np.ndenumerate(arr):\n assert r == prior(theta[i])\n\n mu = np.empty((3, 4, 3), dtype=float)\n Sig = np.empty((3, 4, 3, 3), dtype=float)\n for i in range(3):\n for j in range(4):\n mu[i, j] = np.arange(3.0)\n Sig[i, j] = np.eye(3)+0.1*i+0.2*j\n arr = prior(mu, Sig)\n for (i, j), r in np.ndenumerate(arr):\n assert r == prior(mu[i, j], Sig[i, j])\n\n theta = np.zeros((3, 4), dtype=prior.model_dtype)\n theta['mu'] = mu\n theta['Sig'] = Sig\n arr = prior(theta)\n for (i, j), r in np.ndenumerate(arr):\n assert r == prior(theta[i, j])\n\n mu = np.arange(6.0).reshape(2, 3)\n arr = prior(mu[:, np.newaxis, np.newaxis, :], Sig)\n for (i, j, k), r in np.ndenumerate(arr):\n assert r == prior(mu[i], Sig[j, k])\n\n theta = np.zeros((2, 3, 4), dtype=prior.model_dtype)\n theta['mu'] = mu[:, np.newaxis, np.newaxis, :]\n theta['Sig'] = Sig\n arr = prior(theta)\n for (i, j, k), r in np.ndenumerate(arr):\n assert r == prior(theta[i, j, k])\n\n # Should _post_params method do any broadcasting?\n\n # Test pred method():\n prior = dpmm.NormInvWish(mu_0, kappa_0, Lam_0, nu_0)\n x = np.arange(3.0)+1\n arr = prior.pred(x)\n assert isinstance(arr, float)\n\n x = np.arange(6.0).reshape(2, 3)\n arr = prior.pred(x)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (2,)\n assert arr.dtype == float\n for i, r in np.ndenumerate(arr):\n assert r == prior.pred(x[i])\n\n x = np.arange(24.0).reshape(2, 4, 3)\n arr = prior.pred(x)\n assert isinstance(arr, np.ndarray)\n assert arr.shape == (2, 4)\n assert arr.dtype == float\n for (i, j), r in np.ndenumerate(arr):\n np.testing.assert_almost_equal(r, prior.pred(x[i, j]))",
"def test_ptm_adjoint_random(self):\n mats = [self.rand_matrix(4, 4) for _ in range(4)]\n chans = [PTM(Operator(mat)) for mat in mats]\n self._compare_adjoint_to_operator(chans, mats)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests the case where the broadcasted original matrix is expanded
|
def test_expansion_broadcasted(self):
res = qml.operation.expand_matrix(
self.base_matrix_1_broadcasted, wires=[2], wire_order=[0, 2]
)
expected = np.array(
[
[
[1, 2, 0, 0],
[3, 4, 0, 0],
[0, 0, 1, 2],
[0, 0, 3, 4],
],
[
[5, 6, 0, 0],
[7, 8, 0, 0],
[0, 0, 5, 6],
[0, 0, 7, 8],
],
[
[9, 10, 0, 0],
[11, 12, 0, 0],
[0, 0, 9, 10],
[0, 0, 11, 12],
],
]
)
assert np.allclose(expected, res)
res = qml.operation.expand_matrix(
self.base_matrix_1_broadcasted, wires=[2], wire_order=[2, 0]
)
expected = np.array(
[
[
[1, 0, 2, 0],
[0, 1, 0, 2],
[3, 0, 4, 0],
[0, 3, 0, 4],
],
[
[5, 0, 6, 0],
[0, 5, 0, 6],
[7, 0, 8, 0],
[0, 7, 0, 8],
],
[
[9, 0, 10, 0],
[0, 9, 0, 10],
[11, 0, 12, 0],
[0, 11, 0, 12],
],
]
)
assert np.allclose(expected, res)
|
[
"def test_no_expansion_broadcasted(self):\n res = qml.operation.expand_matrix(\n self.base_matrix_2_broadcasted, wires=[0, 2], wire_order=[0, 2]\n )\n assert np.allclose(self.base_matrix_2_broadcasted, res)",
"def test_expand_matrix_usage_in_operator_class_broadcasted(self, tol):\n\n perm = [0, 2, 1, 3]\n permuted_matrix = self.base_matrix_2_broadcasted[:, perm][:, :, perm]\n\n expanded_matrix = np.tensordot(\n np.tensordot(\n np.kron(SWAP, I),\n np.kron(I_broadcasted, self.base_matrix_2_broadcasted),\n axes=[[1], [1]],\n ),\n np.kron(SWAP, I),\n axes=[[2], [0]],\n )\n expanded_matrix = np.moveaxis(expanded_matrix, 0, -2)\n\n class DummyOp(qml.operation.Operator):\n num_wires = 2\n\n def compute_matrix(*params, **hyperparams):\n return self.base_matrix_2_broadcasted\n\n op = DummyOp(wires=[0, 2])\n assert np.allclose(op.matrix(), self.base_matrix_2_broadcasted, atol=tol)\n assert np.allclose(op.matrix(wire_order=[2, 0]), permuted_matrix, atol=tol)\n assert np.allclose(op.matrix(wire_order=[0, 1, 2]), expanded_matrix, atol=tol)",
"def test_permutation_broadcasted(self):\n res = qml.operation.expand_matrix(\n self.base_matrix_2_broadcasted, wires=[0, 2], wire_order=[2, 0]\n )\n\n perm = [0, 2, 1, 3]\n expected = self.base_matrix_2_broadcasted[:, perm][:, :, perm]\n assert np.allclose(expected, res)",
"def test_expand_two_consecutive_wires_broadcasted(self, tol):\n U2 = np.array([[0, 1, 1, 1], [1, 0, 1, -1], [1, -1, 0, 1], [1, 1, -1, 0]]) / np.sqrt(3)\n U2 = np.tensordot([2.31, 1.53, 0.7 - 1.9j], U2, axes=0)\n\n # test applied to wire 0+1\n res = qml.operation.expand_matrix(U2, [0, 1], [0, 1, 2, 3])\n expected = np.kron(np.kron(U2, I_broadcasted), I_broadcasted)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n # test applied to wire 1+2\n res = qml.operation.expand_matrix(U2, [1, 2], [0, 1, 2, 3])\n expected = np.kron(np.kron(I_broadcasted, U2), I_broadcasted)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n # test applied to wire 2+3\n res = qml.operation.expand_matrix(U2, [2, 3], [0, 1, 2, 3])\n expected = np.kron(np.kron(I_broadcasted, I_broadcasted), U2)\n assert np.allclose(res, expected, atol=tol, rtol=0)",
"def test_expand_three_nonconsecutive_nonascending_wires_broadcasted(self, tol):\n # test applied to wire 3, 1, 2\n res = qml.operation.expand_matrix(Toffoli_broadcasted, [3, 1, 2], [0, 1, 2, 3])\n # change the control qubit on the Toffoli gate\n rows = [0, 4, 1, 5, 2, 6, 3, 7]\n Toffoli_broadcasted_perm = Toffoli_broadcasted[:, :, rows][:, rows]\n expected = np.kron(I_broadcasted, Toffoli_broadcasted_perm)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n # test applied to wire 3, 0, 2\n res = qml.operation.expand_matrix(Toffoli_broadcasted, [3, 0, 2], [0, 1, 2, 3])\n # change the control qubit on the Toffoli gate\n expected = np.tensordot(\n np.tensordot(\n np.kron(SWAP, II),\n np.kron(I_broadcasted, Toffoli_broadcasted_perm),\n axes=[[1], [1]],\n ),\n np.kron(SWAP, II),\n axes=[[2], [0]],\n )\n expected = np.moveaxis(expected, 0, -2)\n assert np.allclose(res, expected, atol=tol, rtol=0)",
"def test_no_wire_order_returns_base_matrix(self):\n res = qml.operation.expand_matrix(self.base_matrix_2, wires=[0, 2])\n assert np.allclose(self.base_matrix_2, res)",
"def test_euclidean_distance_broadcasting():\n\n point = np.array([1, 1, 1])\n\n matrix = np.array([\n [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]],\n [[4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7]],\n ])\n\n expected = np.array([\n [0, np.sqrt(3), np.sqrt(12), np.sqrt(27)],\n [np.sqrt(27), np.sqrt(48), np.sqrt(75), np.sqrt(108)]\n ])\n\n actual = np.linalg.norm(point - matrix, axis=2)\n\n assert np.all(expected == actual)",
"def test_permutation_operator_dim_2_2_perm_1_2():\n res = permutation_operator([2, 2], [1, 2])\n expected_res = np.identity(4)\n bool_mat = np.isclose(res, expected_res)\n np.testing.assert_equal(np.all(bool_mat), True)",
"def test_elemental_matrix_1D(generate_elemental_matrix_1D):\n\n x = generate_elemental_matrix_1D.copy()\n\n N = len(x)\n\n expected = np.linspace(0, 1, N)\n expected = reorder_array_gmsh(expected, N)\n\n assert np.allclose(x, expected)\n # assert 0",
"def test_broadcasting(device):\n dev = qml.device(device, wires=2)\n\n @qml.qnode(dev)\n def circuit_state(x):\n qml.IsingXX(x, wires=[0, 1])\n return qml.state()\n\n x = np.array([0.4, 0.6, 0.8])\n y = np.array([0.6, 0.8, 1.0])\n dist = qml.qinfo.trace_distance(circuit_state, circuit_state, wires0=[0], wires1=[1])(x, y)\n\n expected = 0.5 * (\n np.abs(np.cos(x / 2) ** 2 - np.cos(y / 2) ** 2)\n + np.abs(np.sin(x / 2) ** 2 - np.sin(y / 2) ** 2)\n )\n assert qml.math.allclose(dist, expected)",
"def expand(matrix, original_wires, expanded_wires):\n if isinstance(expanded_wires, numbers.Integral):\n expanded_wires = list(range(expanded_wires))\n\n N = len(original_wires)\n M = len(expanded_wires)\n D = M - N\n\n if not set(expanded_wires).issuperset(original_wires):\n raise ValueError(\"Invalid target subsystems provided in 'original_wires' argument.\")\n\n if matrix.shape != (2 ** N, 2 ** N):\n raise ValueError(\n \"Matrix parameter must be of size (2**len(original_wires), 2**len(original_wires))\"\n )\n\n dims = [2] * (2 * N)\n tensor = matrix.reshape(dims)\n\n if D > 0:\n extra_dims = [2] * (2 * D)\n identity = np.eye(2 ** D).reshape(extra_dims)\n expanded_tensor = np.tensordot(tensor, identity, axes=0)\n # Fix order of tensor factors\n expanded_tensor = np.moveaxis(expanded_tensor, range(2 * N, 2 * N + D), range(N, N + D))\n else:\n expanded_tensor = tensor\n\n wire_indices = []\n for wire in original_wires:\n wire_indices.append(expanded_wires.index(wire))\n\n wire_indices = np.array(wire_indices)\n\n # Order tensor factors according to wires\n original_indices = np.array(range(N))\n expanded_tensor = np.moveaxis(expanded_tensor, original_indices, wire_indices)\n expanded_tensor = np.moveaxis(expanded_tensor, original_indices + M, wire_indices + M)\n\n return expanded_tensor.reshape((2 ** M, 2 ** M))",
"def test_swap_operator_is_block_positive(dim):\n mat = swap_operator(dim)\n np.testing.assert_equal(is_block_positive(mat), True)\n np.testing.assert_equal(is_block_positive(mat, k=2), False)",
"def test_matmul(self, matrices):\n # Instantiate the 10x10 matrix and test matrix multiplication\n square_mat = chap5.Matrix(matrices.square)\n square_np = np.array(matrices.square)\n square_matmul = (square_mat @ square_mat)._matrix\n square_np_result = square_np @ square_np\n # Compare to the Numpy result of multiplying the matrix times itself\n assert (np.array(square_matmul) == square_np_result).all()\n # Instantiate a 5x10 and 10x5 matrix as Matrix class and Numpy array\n half_row_mat = chap5.Matrix(matrices.half_row)\n half_col_mat = chap5.Matrix(matrices.half_col)\n half_row_np = np.array(matrices.half_row)\n half_col_np = np.array(matrices.half_col)\n # Matrix multiplication amongst the 10x10, 5x10, and 10x5 matrices\n result1 = half_row_mat @ half_col_mat # (5x10) @ (10x5)\n exp_result1 = half_row_np @ half_col_np # (5x10) @ (10x5)\n result2 = half_col_mat @ half_row_mat # (10x5) @ (5x10)\n exp_result2 = half_col_np @ half_row_np # (10x5) @ (5x10)\n result3 = half_row_mat @ square_mat # (5x10) @ (10x10)\n exp_result3 = half_row_np @ square_np # (5x10) @ (10x10)\n result4 = square_mat @ half_col_mat # (10x10) @ (10x5)\n exp_result4 = square_np @ half_col_np # (10x10) @ (10x5)\n assert (np.array(result1._matrix) == exp_result1).all()\n assert (np.array(result2._matrix) == exp_result2).all()\n assert (np.array(result3._matrix) == exp_result3).all()\n assert (np.array(result4._matrix) == exp_result4).all()",
"def _conform_for_data_broadcasting(self, other):\n\n other = self._conform_for_assignment(other, check_coordinates=True)\n\n # Remove leading size one dimensions\n ndiff = other.ndim - self.ndim\n if ndiff > 0 and set(other.shape[:ndiff]) == set((1,)):\n for i in range(ndiff):\n other = other.squeeze(0)\n\n return other",
"def test_copy_matrix():\n A = np.ones((3, 3), dtype=FTYPE)\n B = np.zeros((3, 3), dtype=FTYPE)\n\n copy_matrix_guf(A, B)\n\n test = B\n ref = A\n assert np.array_equal(test, ref), f\"test:\\n{test}\\n!= ref:\\n{ref}\"\n\n logging.info(\"<< PASS : test_copy_matrix >>\")",
"def _check_can_broadcast_to(shape, target_shape):\n ndim = len(shape)\n ndim_target = len(target_shape)\n if ndim > ndim_target:\n return False\n for i, j in zip(reversed(shape), reversed(target_shape)):\n if i not in (1, j):\n return False\n return True",
"def test_augment_q(Q):\n M, b = augment_Q(Q)\n assert M.shape == (10, 10)\n assert b.shape == (10, 1)\n assert all(b[0:-1]) == 0\n assert b[-1] == 1",
"def test_matrix_equality(self):\n\n m1 = matrices.Matrix(2, 2)\n m1.set_row(0, [1, 2])\n m1.set_row(1, [1, 4])\n\n m2 = matrices.Matrix(2, 2)\n m2.set_row(0, [1, 2])\n m2.set_row(1, [1, 4])\n\n self.assertTrue(m1 == m2)\n\n m2.set(1, 1, 50)\n self.assertFalse(m1 == m2)",
"def test_random_spd_matrix_symmetric(random_spd_matrix: np.ndarray):\n np.testing.assert_equal(random_spd_matrix, random_spd_matrix.T)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests differentiation in autograd by computing the Jacobian of the expanded matrix with respect to the canonical matrix.
|
def test_autograd(self, i, base_matrix, tol):
base_matrix = pnp.array(base_matrix, requires_grad=True)
jac_fn = qml.jacobian(self.func_for_autodiff)
jac = jac_fn(base_matrix)
assert np.allclose(jac, self.expected_autodiff[i], atol=tol)
|
[
"def test_autograd(self, tol, batch_dim):\n dev = qml.device(\"default.qubit.autograd\", wires=2)\n params = np.array([0.543, -0.654], requires_grad=True)\n if batch_dim is not None:\n params = np.outer(np.arange(1, 1 + batch_dim), params, requires_grad=True)\n tangent = np.array([1.0, 0.3], requires_grad=False)\n\n def cost_fn(params, tangent):\n with qml.queuing.AnnotatedQueue() as q:\n ansatz(params[..., 0], params[..., 1])\n\n tape = qml.tape.QuantumScript.from_queue(q)\n tape.trainable_params = {0, 1}\n tapes, fn = qml.gradients.jvp(tape, tangent, param_shift)\n jvp = fn(dev.batch_execute(tapes))\n return jvp\n\n res = cost_fn(params, tangent)\n exp = expected_jvp(params, tangent)\n assert np.allclose(res, exp, atol=tol, rtol=0)\n\n res = qml.jacobian(cost_fn)(params, tangent)\n exp = qml.jacobian(expected_jvp)(params, tangent)\n assert np.allclose(res, exp, atol=tol, rtol=0)",
"def J_dense(x): # dense Jacobian\n return np.array([[1.004, -1e3*x[2], -1e3*x[1]],\n [-0.004, 1.0 + 1e3*x[2] + 60.0*x[1], 1e3*x[1]],\n [0.0, -60.0*x[1], 1.0]])",
"def jacobian(function, x):\n x = np.asarray(x)\n assert x.ndim == 1, \"x must be a vector\"\n x_ad = np.empty(x.shape, dtype=np.object)\n for i in range(x.size):\n der = np.zeros(x.size)\n der[i] = 1\n x_ad.flat[i] = AutoDiffXd(x.flat[i], der)\n y_ad = np.asarray(function(x_ad))\n return np.vstack(\n [y.derivatives() for y in y_ad.flat]).reshape(y_ad.shape + (-1,))",
"def jacobian(A,aparams):\n l1 = aparams['l1']\n l2 = aparams['l2']\n dHxdA1 = -l1*sin(A[0]) - l2*sin(A[0]+A[1])\n dHxdA2 = -l2*sin(A[0]+A[1])\n dHydA1 = l1*cos(A[0]) + l2*cos(A[0]+A[1])\n dHydA2 = l2*cos(A[0]+A[1])\n J = matrix([[dHxdA1,dHxdA2],[dHydA1,dHydA2]])\n return J",
"def jacobian(\n self, t: float, state: np.ndarray, u: np.ndarray) -> np.ndarray:\n pass",
"def jacobian(Q, d):\n return zeros([n, n])",
"def broyden_update(wam, error, jacobian, alpha, prev_joint_pose, prev_image_error):\n # TODO: Your code HERE!\n x2= numpy.delete(numpy.matrix(wam.last_joint_pose), 1).getT()\n x1= numpy.delete(numpy.matrix(prev_joint_pose) , 1).getT()\n deltaX= x2 - x1\n #print('We have reached here')\n eps = numpy.pi/360\n #if ((deltaX.getT()*deltaX)!=0):\n if (deltaX >= eps).any():\n jacobian= jacobian + alpha*((prev_image_error-jacobian*deltaX)*deltaX.getT())/ (deltaX.getT()*deltaX)\n return jacobian",
"def calc_jacobian(f, x, *args, use_autograd=False, eps = 1e-3):\n\tif use_autograd:\n\t\tJ = jacobian(f)(x, *args)\n\telse:\n\t\tJ = np.zeros((len(f(x, *args)), len(x)))\n\t\tfor i in range(len(x)):\n\t\t\teps_i = np.zeros_like(x)\n\t\t\teps_i[i] = eps\n\t\t\tJ[:,i] = (f(x+eps_i, *args) - f(x, *args))/eps\n\treturn J",
"def evaluate_jacobian_eq(self, out=None):\n pass",
"def test_derivative_Bmat(self):\n from . import intcosMisc\n\n DISP_SIZE = 0.01\n MAX_ERROR = 10 * DISP_SIZE * DISP_SIZE * DISP_SIZE * DISP_SIZE\n\n geom_orig = self.geom # to restore below\n\n logger.info(\"\\tTesting Derivative B-matrix numerically.\")\n if self._dimer_intcos:\n logger.info(\"\\tDerivative B-matrix for interfragment modes not yet implemented.\")\n\n warn = False\n for iF, F in enumerate(self._fragments):\n logger.info(\"\\t\\tTesting fragment %d.\" % (iF + 1))\n\n Natom = F.natom\n Nintco = F.num_intcos\n coord = F.geom # not a copy\n dq2dx2_fd = np.zeros((3 * Natom, 3 * Natom))\n dq2dx2_analytic = np.zeros((3 * Natom, 3 * Natom))\n\n for i, I in enumerate(F._intcos):\n logger.info(\"\\t\\tTesting internal coordinate %d :\" % (i + 1))\n\n dq2dx2_analytic.fill(0)\n I.Dq2Dx2(coord, dq2dx2_analytic)\n\n if op.Params.print_lvl >= 3:\n logger.info(\"Analytic B' (Dq2Dx2) matrix in au\\n\" + print_mat_string(dq2dx2_analytic))\n\n # compute B' matrix from B matrices\n for atom_a in range(Natom):\n for xyz_a in range(3):\n\n coord[atom_a, xyz_a] += DISP_SIZE\n B_p = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] += DISP_SIZE\n B_p2 = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] -= 3.0 * DISP_SIZE\n B_m = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] -= DISP_SIZE\n B_m2 = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] += 2 * DISP_SIZE # restore coord to orig\n\n for atom_b in range(Natom):\n for xyz_b in range(3):\n dq2dx2_fd[3 * atom_a + xyz_a, 3 * atom_b + xyz_b] = (\n B_m2[i, 3 * atom_b + xyz_b]\n - 8 * B_m[i, 3 * atom_b + xyz_b]\n + 8 * B_p[i, 3 * atom_b + xyz_b]\n - B_p2[i][3 * atom_b + xyz_b]\n ) / (12.0 * DISP_SIZE)\n\n if op.Params.print_lvl >= 3:\n logger.info(\n \"\\nNumerical B' (Dq2Dx2) matrix in au, DISP_SIZE = %f\\n\" % DISP_SIZE\n + print_mat_string(dq2dx2_fd)\n )\n\n max_error = -1.0\n max_error_xyz = (-1, -1)\n for I in range(3 * Natom):\n for J in range(3 * Natom):\n if np.fabs(dq2dx2_analytic[I, J] - dq2dx2_fd[I, J]) > max_error:\n max_error = np.fabs(dq2dx2_analytic[I][J] - dq2dx2_fd[I][J])\n max_error_xyz = (I, J)\n\n logger.info(\n \"\\t\\tMax. difference is %.1e; 2nd derivative wrt %d and %d.\"\n % (max_error, max_error_xyz[0], max_error_xyz[1])\n )\n\n if max_error > MAX_ERROR:\n warn = True\n\n self.geom = geom_orig # restore original\n self.unfix_bend_axes()\n\n if warn:\n logger.warning(\n \"\"\"\n \\tSome values did not agree. However, numerical tests may fail for\n \\ttorsions at 180 degrees and linear bond angles. This is OK\n \\tIf discontinuities are interfering with a geometry optimization\n \\ttry restarting your optimization at an updated geometry, and/or\n \\tremove angular coordinates that are fixed by symmetry.\"\"\"\n )\n return False\n else:\n logger.info(\"\\t...Passed.\")\n return True",
"def test_jacobian_variable_multiply(self, torch_support, rep, tol):\n x = 0.43316321\n y = 0.2162158\n z = 0.75110998\n\n dev = qml.device(\"default.tensor.tf\", wires=1, representation=rep)\n\n @qml.qnode(dev)\n def circuit(p):\n qml.RX(3 * p[0], wires=0)\n qml.RY(p[1], wires=0)\n qml.RX(p[2] / 2, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n res = circuit([x, y, z])\n expected = np.cos(3 * x) * np.cos(y) * np.cos(z / 2) - np.sin(3 * x) * np.sin(z / 2)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n res = qml.jacobian(circuit)(np.array([x, y, z]))\n expected = np.array(\n [\n -3 * (np.sin(3 * x) * np.cos(y) * np.cos(z / 2) + np.cos(3 * x) * np.sin(z / 2)),\n -np.cos(3 * x) * np.sin(y) * np.cos(z / 2),\n -0.5 * (np.sin(3 * x) * np.cos(z / 2) + np.cos(3 * x) * np.cos(y) * np.sin(z / 2)),\n ]\n )\n\n assert np.allclose(res, expected, atol=tol, rtol=0)",
"def ApproximateJacobian(f, x, dx=1e-6):\n try:\n n = len(x)\n except TypeError:\n n = 1\n fx = f(x)\n Df_x = N.matrix(N.zeros((n,n)))\n for i in range(n):\n\n v = N.matrix(N.zeros((n,1)))\n v[i,0] = dx\n Df_x[:,i] = (f(x + v) - fx)/v[i,0]\n return Df_x",
"def prepareJacobian(self):\n self.jac.clear()\n self.nm = self.regionManager().parameterCount()\n self.nf = len(self.fops)\n print(self.nm, \"model cells\")\n nd = 0\n for i, fop in enumerate(self.fops):\n self.jac.addMatrix(fop.jacobian(), nd, i*self.nm)\n nd += fop.data.size()\n\n self.jac.recalcMatrixSize()\n self.setJacobian(self.jac)",
"def jacobian_information(self):\n has_jacobian = True\n jacobian_free_solvers = [\"lm-scipy-no-jac\"]\n return has_jacobian, jacobian_free_solvers",
"def jacobian(self, x):\n return self.jnz",
"def test_ragged_output(self):\n dev = qml.device(\"default.qubit\", wires=3)\n params = [1.0, 1.0, 1.0]\n\n with JacobianTape() as tape:\n qml.RX(params[0], wires=[0])\n qml.RY(params[1], wires=[1])\n qml.RZ(params[2], wires=[2])\n qml.CNOT(wires=[0, 1])\n qml.probs(wires=0)\n qml.probs(wires=[1, 2])\n\n res = tape.jacobian(dev)\n assert res.shape == (6, 3)",
"def test_analytic_method(self, mocker):\n mock = mocker.patch(\"pennylane.tape.JacobianTape._grad_method\")\n mock.return_value = \"A\"\n\n with JacobianTape() as tape:\n qml.RX(0.543, wires=[0])\n qml.RY(-0.654, wires=[0])\n qml.expval(qml.PauliY(0))\n\n dev = qml.device(\"default.qubit\", wires=1)\n tape.analytic_pd = mocker.Mock()\n tape.analytic_pd.return_value = [[QuantumTape()], lambda res: np.array([1.0])]\n\n tape.jacobian(dev, method=\"analytic\")\n assert len(tape.analytic_pd.call_args_list) == 2",
"def reach_jacobian(self):\n\n # An example problem of an arm with radius 3 currently at angle theta\n radius = 3\n theta = 0.2\n # Vector to the end point\n r = [ radius * cos(theta), radius * sin(theta), 0]\n # Spin around z\n omega_hat = [0,0,1]\n # always 0 in 3rd component\n omega_cross_r = np.cross(omega_hat, r)\n # Desired x,y change\n dx_dy = np.zeros([2,1])\n dx_dy[0,0] = -0.01\n dx_dy[1,0] = -0.1\n # Jacobian\n J = np.zeros([2,1])\n J[0:2,0] = np.transpose( omega_cross_r[0:2] )\n # Solve\n d_ang = np.linalg.lstsq( J, dx_dy, rcond = None )[0]\n # Check result of solve - should be the same as dx_dy\n res = J @ d_ang\n # The actual point you end up at if you change the angle by that much\n pt_new = [ radius * cos(theta + d_ang), radius * sin(theta + d_ang)]\n\n # begin homework 2 : Problem 2\n mats = self.robot_arm.get_matrics()\n jacob = np.zeros([2,3])\n\n matrix_order = ['wrist', 'forearm', 'upperarm']\n mat_accum = np.identity(3)\n for i,c in enumerate(matrix_order):\n mat_accum = mats[c + '_R'] @ mats[c + '_T'] @ mat_accum\n r = [ mat_accum[0,2], mat_accum[1,2], 0 ]\n omega_cross_r = np.cross( omega_hat, r )\n jacob[0:2,2-i] = np.transpose( omega_cross_r[0:2] )\n\n # Desired change in x,y\n pt_reach = self.robot_arm.arm_end_pt()\n dx_dy[0,0] = self.reach_x.value() - pt_reach[0]\n dx_dy[1,0] = self.reach_y.value() - pt_reach[1]\n\n\n # Use pseudo inverse to solve\n d_ang = np.linalg.lstsq( jacob, dx_dy, rcond = None )[0]\n res = jacob @ d_ang\n# print(jacob)\n d_ang_save = [ self.theta_slds[i].value() for i in range(0,3) ]\n d_min = 0\n v_min = pow(dx_dy[0,0], 2) + pow(dx_dy[1,0], 2)\n d_max = min(1, pi / max(d_ang))\n for i,ang in enumerate(d_ang):\n self.theta_slds[i].set_value( self.theta_slds[i].value() + ang )\n pt_reach_move = self.robot_arm.arm_end_pt()\n v_max = pow( pt_reach_move[0] - self.reach_x.value(), 2 ) + pow( pt_reach_move[1] - self.reach_y.value(), 2 )\n d_try = d_min\n v_try = v_min\n if (v_max < v_min):\n d_try = d_max\n v_try = v_max\n while ( d_max - d_min > 0.00001 and v_try > 0.01 ):\n d_try = 0.5 * (d_max + d_min)\n for i,ang in enumerate(d_ang):\n self.theta_slds[i].set_value( d_ang_save[i] + ang * d_try )\n pt_reach_try = self.robot_arm.arm_end_pt()\n v_try = pow( pt_reach_try[0] - self.reach_x.value(), 2 ) + pow( pt_reach_try[1] - self.reach_y.value(), 2 )\n\n if ( v_try < v_min ):\n v_min = v_try\n d_min = d_try\n elif ( v_try < v_max ):\n v_max = v_try\n d_max = d_try\n elif ( v_max > v_min ):\n v_max = v_try\n d_max = d_try\n else:\n v_min = v_try\n d_min = d_try\n\n if ( v_min < v_try and v_min < v_max ):\n d_try = d_min\n\n if ( v_max < v_try and v_max < v_min ):\n d_try = d_max\n \n d_try = 0.2\n for i,ang in enumerate(d_ang):\n self.theta_slds[i].set_value( d_ang_save[i] + ang * d_try )\n\n pt_reach_res = self.robot_arm.arm_end_pt()\n desired_text = \"Desired dx dy {0:0.4f},{1:0.4f},\".format(dx_dy[0,0], dx_dy[1,0])\n got_text = \" got {0:0.4f},{1:0.4f}\".format(res[0,0], res[1,0])\n actual_text = \", actual {0:0.4f},{1:0.4f}\".format(pt_reach_res[0], pt_reach_res[1])\n self.robot_arm.text = desired_text + got_text + actual_text\n # to set text\n # self.robot_arm.text = text\n # end homework 2 problem 2",
"def nnz_jacobian_eq(self):\n pass",
"def JacInv_CF(self) -> ngsolve.fem.CoefficientFunction:"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests differentiation in torch by computing the Jacobian of the expanded matrix with respect to the canonical matrix.
|
def test_torch(self, i, base_matrix, tol):
import torch
base_matrix = torch.tensor(base_matrix, requires_grad=True)
jac = torch.autograd.functional.jacobian(self.func_for_autodiff, base_matrix)
assert np.allclose(jac, self.expected_autodiff[i], atol=tol)
|
[
"def jacobian(Q, d):\n return zeros([n, n])",
"def J_dense(x): # dense Jacobian\n return np.array([[1.004, -1e3*x[2], -1e3*x[1]],\n [-0.004, 1.0 + 1e3*x[2] + 60.0*x[1], 1e3*x[1]],\n [0.0, -60.0*x[1], 1.0]])",
"def test_jacobian_variable_multiply(self, torch_support, rep, tol):\n x = 0.43316321\n y = 0.2162158\n z = 0.75110998\n\n dev = qml.device(\"default.tensor.tf\", wires=1, representation=rep)\n\n @qml.qnode(dev)\n def circuit(p):\n qml.RX(3 * p[0], wires=0)\n qml.RY(p[1], wires=0)\n qml.RX(p[2] / 2, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n res = circuit([x, y, z])\n expected = np.cos(3 * x) * np.cos(y) * np.cos(z / 2) - np.sin(3 * x) * np.sin(z / 2)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n res = qml.jacobian(circuit)(np.array([x, y, z]))\n expected = np.array(\n [\n -3 * (np.sin(3 * x) * np.cos(y) * np.cos(z / 2) + np.cos(3 * x) * np.sin(z / 2)),\n -np.cos(3 * x) * np.sin(y) * np.cos(z / 2),\n -0.5 * (np.sin(3 * x) * np.cos(z / 2) + np.cos(3 * x) * np.cos(y) * np.sin(z / 2)),\n ]\n )\n\n assert np.allclose(res, expected, atol=tol, rtol=0)",
"def jacobian(function, x):\n x = np.asarray(x)\n assert x.ndim == 1, \"x must be a vector\"\n x_ad = np.empty(x.shape, dtype=np.object)\n for i in range(x.size):\n der = np.zeros(x.size)\n der[i] = 1\n x_ad.flat[i] = AutoDiffXd(x.flat[i], der)\n y_ad = np.asarray(function(x_ad))\n return np.vstack(\n [y.derivatives() for y in y_ad.flat]).reshape(y_ad.shape + (-1,))",
"def JacInv_CF(self) -> ngsolve.fem.CoefficientFunction:",
"def call_jacobian(*args) -> ngsolve.bla.MatrixC:",
"def jacobian(\n self, t: float, state: np.ndarray, u: np.ndarray) -> np.ndarray:\n pass",
"def evaluate_jacobian_eq(self, out=None):\n pass",
"def jacobian(self, x):\n return self.jnz",
"def network_jacobian(self, batch_slice):\n inputs = self.inputs[batch_slice]\n representatives = self.representatives[batch_slice]\n\n layer = self.network.layers[self.layer_index]\n\n original_outputs = self.network.compute(inputs)\n n_inputs, out_dims = original_outputs.shape\n\n if isinstance(layer, FullyConnectedLayer):\n weight_scales, bias_scales = self.layer_jacobian(\n inputs, representatives)\n # weight_scales is (n_inputs, out_dims, in_dims, mid_dims)\n # bias_scales is (n_inputs, out_dims, mid_dims)\n else:\n # This *SHOULD* be possible in general, but I don't know how to\n # express it nicely in Numpy/Pytorch. Trying to run layer_jacobian\n # will create a huge matrix, which is not what we want. The\n # approach below is pretty slow (due primarily to limitations with\n # Jacobian computation in Pytorch) but should work as long as we're\n # not using representatives.\n filters = layer.filter_weights\n biases = layer.biases\n\n def set_grad(v, g):\n v.requires_grad_(g)\n def maybe_zero(v):\n if v is not None:\n v.zero_()\n\n for v in [filters, biases]:\n set_grad(v, True)\n pytorch_x = torch.tensor(inputs, requires_grad=True, dtype=torch.float)\n if self.inputs is self.representatives:\n output = self.network.compute(pytorch_x)\n else:\n masknet = DDNN(self.network.layers, self.network.layers)\n output = masknet.compute(pytorch_x, representatives)\n assert len(output.shape) == 2\n n_inputs, out_dims = output.shape\n\n weight_scales = np.zeros((n_inputs, out_dims,) + filters.shape)\n bias_scales = np.zeros((n_inputs, out_dims,) + biases.shape)\n for i in range(output.shape[0]):\n for j in range(output.shape[1]):\n maybe_zero(filters.grad)\n maybe_zero(biases.grad)\n output[i, j].backward(retain_graph=True)\n weight_scales[i, j, :, :, :] = filters.grad.numpy()\n bias_scales[i, j, :] = biases.grad.numpy()\n\n for v in [filters, biases]:\n set_grad(v, False)\n weight_scales = np.array(weight_scales)\n bias_scales = np.array(bias_scales)\n\n # (n_inputs, out_dims, [filter_shape]) -> (out, [filter_size])\n weight_scales = weight_scales.reshape((n_inputs, out_dims, -1))\n # (n_inputs, out_dims, [bias_shape])\n bias_scales = bias_scales.reshape((n_inputs, out_dims, -1))\n return np.concatenate((weight_scales, bias_scales), axis=2), original_outputs",
"def test_derivative_Bmat(self):\n from . import intcosMisc\n\n DISP_SIZE = 0.01\n MAX_ERROR = 10 * DISP_SIZE * DISP_SIZE * DISP_SIZE * DISP_SIZE\n\n geom_orig = self.geom # to restore below\n\n logger.info(\"\\tTesting Derivative B-matrix numerically.\")\n if self._dimer_intcos:\n logger.info(\"\\tDerivative B-matrix for interfragment modes not yet implemented.\")\n\n warn = False\n for iF, F in enumerate(self._fragments):\n logger.info(\"\\t\\tTesting fragment %d.\" % (iF + 1))\n\n Natom = F.natom\n Nintco = F.num_intcos\n coord = F.geom # not a copy\n dq2dx2_fd = np.zeros((3 * Natom, 3 * Natom))\n dq2dx2_analytic = np.zeros((3 * Natom, 3 * Natom))\n\n for i, I in enumerate(F._intcos):\n logger.info(\"\\t\\tTesting internal coordinate %d :\" % (i + 1))\n\n dq2dx2_analytic.fill(0)\n I.Dq2Dx2(coord, dq2dx2_analytic)\n\n if op.Params.print_lvl >= 3:\n logger.info(\"Analytic B' (Dq2Dx2) matrix in au\\n\" + print_mat_string(dq2dx2_analytic))\n\n # compute B' matrix from B matrices\n for atom_a in range(Natom):\n for xyz_a in range(3):\n\n coord[atom_a, xyz_a] += DISP_SIZE\n B_p = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] += DISP_SIZE\n B_p2 = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] -= 3.0 * DISP_SIZE\n B_m = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] -= DISP_SIZE\n B_m2 = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] += 2 * DISP_SIZE # restore coord to orig\n\n for atom_b in range(Natom):\n for xyz_b in range(3):\n dq2dx2_fd[3 * atom_a + xyz_a, 3 * atom_b + xyz_b] = (\n B_m2[i, 3 * atom_b + xyz_b]\n - 8 * B_m[i, 3 * atom_b + xyz_b]\n + 8 * B_p[i, 3 * atom_b + xyz_b]\n - B_p2[i][3 * atom_b + xyz_b]\n ) / (12.0 * DISP_SIZE)\n\n if op.Params.print_lvl >= 3:\n logger.info(\n \"\\nNumerical B' (Dq2Dx2) matrix in au, DISP_SIZE = %f\\n\" % DISP_SIZE\n + print_mat_string(dq2dx2_fd)\n )\n\n max_error = -1.0\n max_error_xyz = (-1, -1)\n for I in range(3 * Natom):\n for J in range(3 * Natom):\n if np.fabs(dq2dx2_analytic[I, J] - dq2dx2_fd[I, J]) > max_error:\n max_error = np.fabs(dq2dx2_analytic[I][J] - dq2dx2_fd[I][J])\n max_error_xyz = (I, J)\n\n logger.info(\n \"\\t\\tMax. difference is %.1e; 2nd derivative wrt %d and %d.\"\n % (max_error, max_error_xyz[0], max_error_xyz[1])\n )\n\n if max_error > MAX_ERROR:\n warn = True\n\n self.geom = geom_orig # restore original\n self.unfix_bend_axes()\n\n if warn:\n logger.warning(\n \"\"\"\n \\tSome values did not agree. However, numerical tests may fail for\n \\ttorsions at 180 degrees and linear bond angles. This is OK\n \\tIf discontinuities are interfering with a geometry optimization\n \\ttry restarting your optimization at an updated geometry, and/or\n \\tremove angular coordinates that are fixed by symmetry.\"\"\"\n )\n return False\n else:\n logger.info(\"\\t...Passed.\")\n return True",
"def test_fallback_log_jac_det():\n\n class SquareTransform(RVTransform):\n name = \"square\"\n\n def forward(self, value, *inputs):\n return at.power(value, 2)\n\n def backward(self, value, *inputs):\n return at.sqrt(value)\n\n square_tr = SquareTransform()\n\n value = at.scalar(\"value\")\n value_tr = square_tr.forward(value)\n log_jac_det = square_tr.log_jac_det(value_tr)\n\n assert np.isclose(log_jac_det.eval({value: 3}), -np.log(6))",
"def get_determinant_of_jacobian(self):\n return self.__det_jac",
"def jacobian_information(self):\n has_jacobian = True\n jacobian_free_solvers = [\"lm-scipy-no-jac\"]\n return has_jacobian, jacobian_free_solvers",
"def ApproximateJacobian(f, x, dx=1e-6):\n try:\n n = len(x)\n except TypeError:\n n = 1\n fx = f(x)\n Df_x = N.matrix(N.zeros((n,n)))\n for i in range(n):\n\n v = N.matrix(N.zeros((n,1)))\n v[i,0] = dx\n Df_x[:,i] = (f(x + v) - fx)/v[i,0]\n return Df_x",
"def _approx_diag(self):\n if self.size(-2) != self.size(-1):\n raise NotImplementedError(\n \"diag does not make sense when matrix is not square\"\n )\n\n # calling approx diag\n with torch.set_grad_enabled(True):\n loss = self.criterion(self.model(self.data), self.target)\n\n ones_list = []\n for param in self.model.parameters():\n ones_list.append(torch.ones_like(param))\n\n # this may not strictly be an upper bound because J^T 1 may not\n # be a good approximator of \\sum_p |df/d\\theta_p|\n # J^T 1 = \\sum_j J_{ij} (returns a n dimensional vector)\n jac_sum_by_point = Rop(loss, self.model.parameters(), ones_list)[0]\n\n if self.num_outputs == 1:\n jac_sum_by_point = jac_sum_by_point.squeeze(-1)\n elif len(jac_sum_by_point.shape) > 1:\n jac_sum_by_point = jac_sum_by_point.t()\n\n # squares the n dimensional vector\n return jac_sum_by_point.pow(2.0)",
"def test_jacobian_is_none_single(self):\n\n tangent = np.array([[1.0, 2.0], [3.0, 4.0]])\n jac = None\n\n jvp = qml.gradients.compute_jvp_single(tangent, jac)\n assert jvp is None",
"def nnz_jacobian_eq(self):\n pass",
"def prepareJacobian(self):\n self.jac.clear()\n self.nm = self.regionManager().parameterCount()\n self.nf = len(self.fops)\n print(self.nm, \"model cells\")\n nd = 0\n for i, fop in enumerate(self.fops):\n self.jac.addMatrix(fop.jacobian(), nd, i*self.nm)\n nd += fop.data.size()\n\n self.jac.recalcMatrixSize()\n self.setJacobian(self.jac)",
"def test_determinant_2_by_2(self):\n\n M = matrices.Matrix(2, 2)\n M.set_row(0, [1, 5])\n M.set_row(1, [-3, 2])\n\n self.assertEqual(M.det(), 17)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests differentiation in jax by computing the Jacobian of the expanded matrix with respect to the canonical matrix.
|
def test_jax(self, i, base_matrix, tol):
import jax
base_matrix = jax.numpy.array(base_matrix)
jac_fn = jax.jacobian(self.func_for_autodiff)
jac = jac_fn(base_matrix)
assert np.allclose(jac, self.expected_autodiff[i], atol=tol)
|
[
"def J_dense(x): # dense Jacobian\n return np.array([[1.004, -1e3*x[2], -1e3*x[1]],\n [-0.004, 1.0 + 1e3*x[2] + 60.0*x[1], 1e3*x[1]],\n [0.0, -60.0*x[1], 1.0]])",
"def jacobian(function, x):\n x = np.asarray(x)\n assert x.ndim == 1, \"x must be a vector\"\n x_ad = np.empty(x.shape, dtype=np.object)\n for i in range(x.size):\n der = np.zeros(x.size)\n der[i] = 1\n x_ad.flat[i] = AutoDiffXd(x.flat[i], der)\n y_ad = np.asarray(function(x_ad))\n return np.vstack(\n [y.derivatives() for y in y_ad.flat]).reshape(y_ad.shape + (-1,))",
"def jacobian_information(self):\n has_jacobian = True\n jacobian_free_solvers = [\"lm-scipy-no-jac\"]\n return has_jacobian, jacobian_free_solvers",
"def jacobian(self, x):\n return self.jnz",
"def jacobian(Q, d):\n return zeros([n, n])",
"def test_richardson_solve(self):\n\n # Ensure we converge to the fixed point\n matrix = jax.random.normal(jax.random.PRNGKey(0), (50, 50))\n matrix = jnp.eye(50) - 0.9 * matrix / jnp.sum(\n jnp.abs(matrix), axis=0, keepdims=True)\n b = jax.random.normal(jax.random.PRNGKey(1), (50,))\n\n def iter_solve(matrix, b):\n return linear_solvers.richardson_solve(\n lambda x: matrix @ x, b, iterations=100)\n\n # Correct output\n np.testing.assert_allclose(\n iter_solve(matrix, b), jax.scipy.linalg.solve(matrix, b), rtol=1e-4)\n\n # Correct jvp\n dmatrix = jax.random.normal(jax.random.PRNGKey(2), (50, 50))\n db = jax.random.normal(jax.random.PRNGKey(3), (50,))\n np.testing.assert_allclose(\n jax.jvp(iter_solve, (matrix, b), (dmatrix, db)),\n jax.jvp(jax.scipy.linalg.solve, (matrix, b), (dmatrix, db)),\n atol=1E-5, rtol=1e-4)\n\n # Correct vjp\n co_x = jax.random.normal(jax.random.PRNGKey(3), (50,))\n jax.tree_util.tree_map(\n functools.partial(np.testing.assert_allclose, atol=1E-5, rtol=1E-4),\n jax.vjp(iter_solve, matrix, b)[1](co_x),\n jax.vjp(jax.scipy.linalg.solve, matrix, b)[1](co_x))",
"def evaluate_jacobian_eq(self, out=None):\n pass",
"def test_derivative_Bmat(self):\n from . import intcosMisc\n\n DISP_SIZE = 0.01\n MAX_ERROR = 10 * DISP_SIZE * DISP_SIZE * DISP_SIZE * DISP_SIZE\n\n geom_orig = self.geom # to restore below\n\n logger.info(\"\\tTesting Derivative B-matrix numerically.\")\n if self._dimer_intcos:\n logger.info(\"\\tDerivative B-matrix for interfragment modes not yet implemented.\")\n\n warn = False\n for iF, F in enumerate(self._fragments):\n logger.info(\"\\t\\tTesting fragment %d.\" % (iF + 1))\n\n Natom = F.natom\n Nintco = F.num_intcos\n coord = F.geom # not a copy\n dq2dx2_fd = np.zeros((3 * Natom, 3 * Natom))\n dq2dx2_analytic = np.zeros((3 * Natom, 3 * Natom))\n\n for i, I in enumerate(F._intcos):\n logger.info(\"\\t\\tTesting internal coordinate %d :\" % (i + 1))\n\n dq2dx2_analytic.fill(0)\n I.Dq2Dx2(coord, dq2dx2_analytic)\n\n if op.Params.print_lvl >= 3:\n logger.info(\"Analytic B' (Dq2Dx2) matrix in au\\n\" + print_mat_string(dq2dx2_analytic))\n\n # compute B' matrix from B matrices\n for atom_a in range(Natom):\n for xyz_a in range(3):\n\n coord[atom_a, xyz_a] += DISP_SIZE\n B_p = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] += DISP_SIZE\n B_p2 = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] -= 3.0 * DISP_SIZE\n B_m = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] -= DISP_SIZE\n B_m2 = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] += 2 * DISP_SIZE # restore coord to orig\n\n for atom_b in range(Natom):\n for xyz_b in range(3):\n dq2dx2_fd[3 * atom_a + xyz_a, 3 * atom_b + xyz_b] = (\n B_m2[i, 3 * atom_b + xyz_b]\n - 8 * B_m[i, 3 * atom_b + xyz_b]\n + 8 * B_p[i, 3 * atom_b + xyz_b]\n - B_p2[i][3 * atom_b + xyz_b]\n ) / (12.0 * DISP_SIZE)\n\n if op.Params.print_lvl >= 3:\n logger.info(\n \"\\nNumerical B' (Dq2Dx2) matrix in au, DISP_SIZE = %f\\n\" % DISP_SIZE\n + print_mat_string(dq2dx2_fd)\n )\n\n max_error = -1.0\n max_error_xyz = (-1, -1)\n for I in range(3 * Natom):\n for J in range(3 * Natom):\n if np.fabs(dq2dx2_analytic[I, J] - dq2dx2_fd[I, J]) > max_error:\n max_error = np.fabs(dq2dx2_analytic[I][J] - dq2dx2_fd[I][J])\n max_error_xyz = (I, J)\n\n logger.info(\n \"\\t\\tMax. difference is %.1e; 2nd derivative wrt %d and %d.\"\n % (max_error, max_error_xyz[0], max_error_xyz[1])\n )\n\n if max_error > MAX_ERROR:\n warn = True\n\n self.geom = geom_orig # restore original\n self.unfix_bend_axes()\n\n if warn:\n logger.warning(\n \"\"\"\n \\tSome values did not agree. However, numerical tests may fail for\n \\ttorsions at 180 degrees and linear bond angles. This is OK\n \\tIf discontinuities are interfering with a geometry optimization\n \\ttry restarting your optimization at an updated geometry, and/or\n \\tremove angular coordinates that are fixed by symmetry.\"\"\"\n )\n return False\n else:\n logger.info(\"\\t...Passed.\")\n return True",
"def call_jacobian(*args) -> ngsolve.bla.MatrixC:",
"def JacobianMatrix(Angle1,Angle2,Link1,Link2):\n\tTheta1, Theta2 = sp.symbols('Theta1 Theta2', real = True)\n\tG = sp.Matrix([\tLink1*sp.cos(Theta1)+Link2*sp.cos(Theta1+Theta2),\\\n\t\t\t\t\tLink1*sp.sin(Theta1)+Link2*sp.sin(Theta1+Theta2)\t])\n\tJ = G.jacobian([Theta1,Theta2])\n\tJ_inv_trans = (J**-1).T\n\tJ = J.subs([(Theta1,Angle1),(Theta2,Angle2)])\n\tJ_inv_trans = J_inv_trans.subs([(Theta1,Angle1),(Theta2,Angle2)])\n\treturn(J,J_inv_trans)",
"def test_ragged_output(self):\n dev = qml.device(\"default.qubit\", wires=3)\n params = [1.0, 1.0, 1.0]\n\n with JacobianTape() as tape:\n qml.RX(params[0], wires=[0])\n qml.RY(params[1], wires=[1])\n qml.RZ(params[2], wires=[2])\n qml.CNOT(wires=[0, 1])\n qml.probs(wires=0)\n qml.probs(wires=[1, 2])\n\n res = tape.jacobian(dev)\n assert res.shape == (6, 3)",
"def test_jacobian_variable_multiply(self, torch_support, rep, tol):\n x = 0.43316321\n y = 0.2162158\n z = 0.75110998\n\n dev = qml.device(\"default.tensor.tf\", wires=1, representation=rep)\n\n @qml.qnode(dev)\n def circuit(p):\n qml.RX(3 * p[0], wires=0)\n qml.RY(p[1], wires=0)\n qml.RX(p[2] / 2, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n res = circuit([x, y, z])\n expected = np.cos(3 * x) * np.cos(y) * np.cos(z / 2) - np.sin(3 * x) * np.sin(z / 2)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n res = qml.jacobian(circuit)(np.array([x, y, z]))\n expected = np.array(\n [\n -3 * (np.sin(3 * x) * np.cos(y) * np.cos(z / 2) + np.cos(3 * x) * np.sin(z / 2)),\n -np.cos(3 * x) * np.sin(y) * np.cos(z / 2),\n -0.5 * (np.sin(3 * x) * np.cos(z / 2) + np.cos(3 * x) * np.cos(y) * np.sin(z / 2)),\n ]\n )\n\n assert np.allclose(res, expected, atol=tol, rtol=0)",
"def JacInv_CF(self) -> ngsolve.fem.CoefficientFunction:",
"def jacobian(\n self, t: float, state: np.ndarray, u: np.ndarray) -> np.ndarray:\n pass",
"def prepareJacobian(self):\n self.jac.clear()\n self.nm = self.regionManager().parameterCount()\n self.nf = len(self.fops)\n print(self.nm, \"model cells\")\n nd = 0\n for i, fop in enumerate(self.fops):\n self.jac.addMatrix(fop.jacobian(), nd, i*self.nm)\n nd += fop.data.size()\n\n self.jac.recalcMatrixSize()\n self.setJacobian(self.jac)",
"def jacobian(A,aparams):\n l1 = aparams['l1']\n l2 = aparams['l2']\n dHxdA1 = -l1*sin(A[0]) - l2*sin(A[0]+A[1])\n dHxdA2 = -l2*sin(A[0]+A[1])\n dHydA1 = l1*cos(A[0]) + l2*cos(A[0]+A[1])\n dHydA2 = l2*cos(A[0]+A[1])\n J = matrix([[dHxdA1,dHxdA2],[dHydA1,dHydA2]])\n return J",
"def jacobian_energy(params, X, y, weights):\n \n du = y - energy(params, X)\n grad = gradient_energy(params, X)\n jac = -2.0*grad.T.dot(np.diag(weights)).dot(du)\n \n return jac",
"def test_nontrainable_coeffs_jax(self):\n coeffs = np.array([-0.05, 0.17])\n param = jnp.array(1.7)\n\n # differentiating a circuit with measurement expval(H)\n @qml.qnode(dev, interface=\"jax\", diff_method=\"backprop\")\n def circuit(coeffs, param):\n qml.RX(param, wires=0)\n qml.RY(param, wires=0)\n return qml.expval(qml.Hamiltonian(coeffs, [qml.PauliX(0), qml.PauliZ(0)]))\n\n grad_fn = jax.grad(circuit, argnums=(1))\n grad = grad_fn(coeffs, param)\n\n # differentiating a cost that combines circuits with\n # measurements expval(Pauli)\n half1 = qml.QNode(circuit1, dev, interface=\"jax\", diff_method=\"backprop\")\n half2 = qml.QNode(circuit2, dev, interface=\"jax\", diff_method=\"backprop\")\n\n def combine(coeffs, param):\n return coeffs[0] * half1(param) + coeffs[1] * half2(param)\n\n grad_fn_expected = jax.grad(combine, argnums=(1))\n grad_expected = grad_fn_expected(coeffs, param)\n\n assert np.allclose(grad, grad_expected)",
"def test_fallback_log_jac_det():\n\n class SquareTransform(RVTransform):\n name = \"square\"\n\n def forward(self, value, *inputs):\n return at.power(value, 2)\n\n def backward(self, value, *inputs):\n return at.sqrt(value)\n\n square_tr = SquareTransform()\n\n value = at.scalar(\"value\")\n value_tr = square_tr.forward(value)\n log_jac_det = square_tr.log_jac_det(value_tr)\n\n assert np.isclose(log_jac_det.eval({value: 3}), -np.log(6))",
"def jacobian(self, xs, argdict=None, eps_f=5e-11):\n jac = []\n xs = np.asarray(xs)\n for i, x in enumerate(xs):\n # Determine the separation to use\n # Optimal one-pt separation is (eps_f*f/f'')^(1/2) ~ sqrt(eps_f)*x\n # Optimal two-pt separation is (eps_f*f/f''')^(1/3) ~ cbrt(eps_f)*x\n h = np.zeros(len(xs))\n h[i] = (eps_f**(1./3.))*x\n\n # Evaluate the function\n # One-pt\n #f1 = rebound_2d_earth_res(xs...)\n # Two-pt\n f1 = self.residuals(xs-h, argdict)\n f2 = self.residuals(xs+h, argdict)\n\n # Difference\n # One-pt\n #(f2-f1)/h\n # Two-pt\n jac.append((f2-f1)*0.5/h[i])\n\n # put them together\n jac = np.asarray(jac)\n return jac"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests differentiation in TensorFlow by computing the Jacobian of the expanded matrix with respect to the canonical matrix.
|
def test_tf(self, i, base_matrix, tol):
import tensorflow as tf
base_matrix = tf.Variable(base_matrix)
with tf.GradientTape() as tape:
res = self.func_for_autodiff(base_matrix)
jac = tape.jacobian(res, base_matrix)
assert np.allclose(jac, self.expected_autodiff[i], atol=tol)
|
[
"def J_dense(x): # dense Jacobian\n return np.array([[1.004, -1e3*x[2], -1e3*x[1]],\n [-0.004, 1.0 + 1e3*x[2] + 60.0*x[1], 1e3*x[1]],\n [0.0, -60.0*x[1], 1.0]])",
"def test_FullOrderRecovery(self):\n Q = tf.linalg.diag([1.0, 2.0, 3.0])\n def Qv(v):\n return tf.matmul(Q, v)\n V, T = lanczos_algorithm.lanczos_algorithm(Qv, 3, 3)\n Q_lanczos = tf.matmul(tf.matmul(V, T), V, transpose_b=True)\n self.assertAllClose(Q_lanczos, Q, atol=1e-7)",
"def jacobian(\n self, t: float, state: np.ndarray, u: np.ndarray) -> np.ndarray:\n pass",
"def test_derivative_Bmat(self):\n from . import intcosMisc\n\n DISP_SIZE = 0.01\n MAX_ERROR = 10 * DISP_SIZE * DISP_SIZE * DISP_SIZE * DISP_SIZE\n\n geom_orig = self.geom # to restore below\n\n logger.info(\"\\tTesting Derivative B-matrix numerically.\")\n if self._dimer_intcos:\n logger.info(\"\\tDerivative B-matrix for interfragment modes not yet implemented.\")\n\n warn = False\n for iF, F in enumerate(self._fragments):\n logger.info(\"\\t\\tTesting fragment %d.\" % (iF + 1))\n\n Natom = F.natom\n Nintco = F.num_intcos\n coord = F.geom # not a copy\n dq2dx2_fd = np.zeros((3 * Natom, 3 * Natom))\n dq2dx2_analytic = np.zeros((3 * Natom, 3 * Natom))\n\n for i, I in enumerate(F._intcos):\n logger.info(\"\\t\\tTesting internal coordinate %d :\" % (i + 1))\n\n dq2dx2_analytic.fill(0)\n I.Dq2Dx2(coord, dq2dx2_analytic)\n\n if op.Params.print_lvl >= 3:\n logger.info(\"Analytic B' (Dq2Dx2) matrix in au\\n\" + print_mat_string(dq2dx2_analytic))\n\n # compute B' matrix from B matrices\n for atom_a in range(Natom):\n for xyz_a in range(3):\n\n coord[atom_a, xyz_a] += DISP_SIZE\n B_p = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] += DISP_SIZE\n B_p2 = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] -= 3.0 * DISP_SIZE\n B_m = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] -= DISP_SIZE\n B_m2 = intcosMisc.Bmat(F.intcos, coord)\n\n coord[atom_a, xyz_a] += 2 * DISP_SIZE # restore coord to orig\n\n for atom_b in range(Natom):\n for xyz_b in range(3):\n dq2dx2_fd[3 * atom_a + xyz_a, 3 * atom_b + xyz_b] = (\n B_m2[i, 3 * atom_b + xyz_b]\n - 8 * B_m[i, 3 * atom_b + xyz_b]\n + 8 * B_p[i, 3 * atom_b + xyz_b]\n - B_p2[i][3 * atom_b + xyz_b]\n ) / (12.0 * DISP_SIZE)\n\n if op.Params.print_lvl >= 3:\n logger.info(\n \"\\nNumerical B' (Dq2Dx2) matrix in au, DISP_SIZE = %f\\n\" % DISP_SIZE\n + print_mat_string(dq2dx2_fd)\n )\n\n max_error = -1.0\n max_error_xyz = (-1, -1)\n for I in range(3 * Natom):\n for J in range(3 * Natom):\n if np.fabs(dq2dx2_analytic[I, J] - dq2dx2_fd[I, J]) > max_error:\n max_error = np.fabs(dq2dx2_analytic[I][J] - dq2dx2_fd[I][J])\n max_error_xyz = (I, J)\n\n logger.info(\n \"\\t\\tMax. difference is %.1e; 2nd derivative wrt %d and %d.\"\n % (max_error, max_error_xyz[0], max_error_xyz[1])\n )\n\n if max_error > MAX_ERROR:\n warn = True\n\n self.geom = geom_orig # restore original\n self.unfix_bend_axes()\n\n if warn:\n logger.warning(\n \"\"\"\n \\tSome values did not agree. However, numerical tests may fail for\n \\ttorsions at 180 degrees and linear bond angles. This is OK\n \\tIf discontinuities are interfering with a geometry optimization\n \\ttry restarting your optimization at an updated geometry, and/or\n \\tremove angular coordinates that are fixed by symmetry.\"\"\"\n )\n return False\n else:\n logger.info(\"\\t...Passed.\")\n return True",
"def jacobian(Q, d):\n return zeros([n, n])",
"def test_density_matrix_qnode_tf_jit(self):\n dev = qml.device(\"default.qubit\", wires=2)\n\n @qml.qnode(dev, interface=\"tf\")\n def circuit(x):\n qml.IsingXX(x, wires=[0, 1])\n return qml.state()\n\n density_matrix = tf.function(\n qml.qinfo.reduced_dm(circuit, wires=[0]),\n jit_compile=True,\n input_signature=(tf.TensorSpec(shape=(), dtype=tf.float32),),\n )\n density_matrix = density_matrix(tf.Variable(0.0, dtype=tf.float32))\n assert np.allclose(density_matrix, [[1, 0], [0, 0]])",
"def jacobian(function, x):\n x = np.asarray(x)\n assert x.ndim == 1, \"x must be a vector\"\n x_ad = np.empty(x.shape, dtype=np.object)\n for i in range(x.size):\n der = np.zeros(x.size)\n der[i] = 1\n x_ad.flat[i] = AutoDiffXd(x.flat[i], der)\n y_ad = np.asarray(function(x_ad))\n return np.vstack(\n [y.derivatives() for y in y_ad.flat]).reshape(y_ad.shape + (-1,))",
"def evaluate_jacobian_eq(self, out=None):\n pass",
"def test_cost_gradient(self):\n\n # Use seed for deterministic testing\n np.random.seed(42)\n\n def test(shape, plates, \n axis=-1, \n alpha_plates=None, \n plate_axis=None,\n mu=3):\n \n if plate_axis is not None:\n precomputes = [False, True]\n else:\n precomputes = [False]\n \n for precompute in precomputes:\n # Construct the model\n D = shape[axis]\n if alpha_plates is not None:\n alpha = Gamma(3, 5,\n plates=alpha_plates)\n alpha.initialize_from_random()\n else:\n alpha = 2\n X = GaussianARD(mu, alpha,\n shape=shape,\n plates=plates)\n\n # Some initial learning and rotator constructing\n X.initialize_from_random()\n Y = GaussianARD(X, 1)\n Y.observe(np.random.randn(*(Y.get_shape(0))))\n X.update()\n if alpha_plates is not None:\n alpha.update()\n rotX = RotateGaussianARD(X, alpha, \n axis=axis,\n precompute=precompute)\n else:\n rotX = RotateGaussianARD(X, \n axis=axis,\n precompute=precompute)\n try:\n mu.update()\n except:\n pass\n\n # Rotation matrices\n R = np.random.randn(D, D)\n if plate_axis is not None:\n C = plates[plate_axis]\n Q = np.random.randn(C, C)\n else:\n Q = None\n\n # Compute bound terms\n rotX.setup(plate_axis=plate_axis)\n\n if plate_axis is None:\n def f_r(r):\n (b, dr) = rotX.bound(np.reshape(r, np.shape(R)))\n return (b, np.ravel(dr))\n else:\n def f_r(r):\n (b, dr, dq) = rotX.bound(np.reshape(r, np.shape(R)),\n Q=Q)\n return (b, np.ravel(dr))\n\n def f_q(q):\n (b, dr, dq) = rotX.bound(R,\n Q=np.reshape(q, np.shape(Q)))\n return (b, np.ravel(dq))\n\n # Check gradient with respect to R\n err = optimize.check_gradient(f_r, \n np.ravel(R), \n verbose=False)[1]\n self.assertAllClose(err, 0, \n atol=1e-4,\n msg=\"Gradient incorrect for R\")\n\n # Check gradient with respect to Q\n if plate_axis is not None:\n err = optimize.check_gradient(f_q, \n np.ravel(Q), \n verbose=False)[1]\n self.assertAllClose(err, 0,\n atol=1e-4,\n msg=\"Gradient incorrect for Q\")\n\n return\n\n #\n # Basic rotation\n #\n test((3,), (), axis=-1)\n test((2,3,4), (), axis=-1)\n test((2,3,4), (), axis=-2)\n test((2,3,4), (), axis=-3)\n test((2,3,4), (5,6), axis=-2)\n\n #\n # Rotation with mu\n #\n\n # Simple\n test((1,), (), axis=-1,\n mu=GaussianARD(2, 4,\n shape=(1,),\n plates=()))\n test((3,), (), axis=-1,\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=()))\n # Broadcast mu over rotated dim\n test((3,), (), axis=-1,\n mu=GaussianARD(2, 4,\n shape=(1,),\n plates=()))\n test((3,), (), axis=-1,\n mu=GaussianARD(2, 4,\n shape=(),\n plates=()))\n # Broadcast mu over dim when multiple dims\n test((2,3), (), axis=-1,\n mu=GaussianARD(2, 4,\n shape=(1,3),\n plates=()))\n test((2,3), (), axis=-1,\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=()))\n # Broadcast mu over rotated dim when multiple dims\n test((2,3), (), axis=-2,\n mu=GaussianARD(2, 4,\n shape=(1,3),\n plates=()))\n test((2,3), (), axis=-2,\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=()))\n # Broadcast mu over plates\n test((3,), (4,5), axis=-1,\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=(4,1)))\n test((3,), (4,5), axis=-1,\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=(5,)))\n\n #\n # Rotation with alpha\n #\n\n # Simple\n test((1,), (), axis=-1,\n alpha_plates=())\n test((3,), (), axis=-1,\n alpha_plates=(3,))\n # Broadcast alpha over rotated dim\n test((3,), (), axis=-1,\n alpha_plates=())\n test((3,), (), axis=-1,\n alpha_plates=(1,))\n # Broadcast alpha over dim when multiple dims\n test((2,3), (), axis=-1,\n alpha_plates=(1,3))\n test((2,3), (), axis=-1,\n alpha_plates=(3,))\n # Broadcast alpha over rotated dim when multiple dims\n test((2,3), (), axis=-2,\n alpha_plates=(1,3))\n test((2,3), (), axis=-2,\n alpha_plates=(3,))\n # Broadcast alpha over plates\n test((3,), (4,5), axis=-1,\n alpha_plates=(4,1,3))\n test((3,), (4,5), axis=-1,\n alpha_plates=(5,3))\n\n #\n # Rotation with alpha and mu\n #\n\n # Simple\n test((1,), (), axis=-1,\n alpha_plates=(1,),\n mu=GaussianARD(2, 4,\n shape=(1,),\n plates=()))\n test((3,), (), axis=-1,\n alpha_plates=(3,),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=()))\n # Broadcast mu over rotated dim\n test((3,), (), axis=-1,\n alpha_plates=(3,),\n mu=GaussianARD(2, 4,\n shape=(1,),\n plates=()))\n test((3,), (), axis=-1,\n alpha_plates=(3,),\n mu=GaussianARD(2, 4,\n shape=(),\n plates=()))\n # Broadcast alpha over rotated dim\n test((3,), (), axis=-1,\n alpha_plates=(1,),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=()))\n test((3,), (), axis=-1,\n alpha_plates=(),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=()))\n # Broadcast both mu and alpha over rotated dim\n test((3,), (), axis=-1,\n alpha_plates=(1,),\n mu=GaussianARD(2, 4,\n shape=(1,),\n plates=()))\n test((3,), (), axis=-1,\n alpha_plates=(),\n mu=GaussianARD(2, 4,\n shape=(),\n plates=()))\n # Broadcast mu over plates\n test((3,), (4,5), axis=-1,\n alpha_plates=(4,5,3),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=(4,1)))\n test((3,), (4,5), axis=-1,\n alpha_plates=(4,5,3),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=(5,)))\n # Broadcast alpha over plates\n test((3,), (4,5), axis=-1,\n alpha_plates=(4,1,3),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=(4,5)))\n test((3,), (4,5), axis=-1,\n alpha_plates=(5,3),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=(4,5)))\n # Broadcast both mu and alpha over plates\n test((3,), (4,5), axis=-1,\n alpha_plates=(4,1,3),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=(4,1)))\n test((3,), (4,5), axis=-1,\n alpha_plates=(5,3),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=(5,)))\n # Broadcast both mu and alpha over plates but different plates\n test((3,), (4,5), axis=-1,\n alpha_plates=(4,1,3),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=(5,)))\n test((3,), (4,5), axis=-1,\n alpha_plates=(5,3),\n mu=GaussianARD(2, 4,\n shape=(3,),\n plates=(4,1)))\n\n #\n # Rotation with missing values\n #\n\n # TODO\n\n #\n # Plate rotation\n #\n\n # Simple\n test((2,), (3,), axis=-1, plate_axis=-1)\n test((2,), (3,4,5), axis=-1, plate_axis=-1)\n test((2,), (3,4,5), axis=-1, plate_axis=-2)\n test((2,), (3,4,5), axis=-1, plate_axis=-3)\n test((2,3), (4,5), axis=-2, plate_axis=-2)\n\n # With mu\n test((2,), (3,), axis=-1, plate_axis=-1,\n mu=GaussianARD(3, 4,\n shape=(2,),\n plates=(3,)))\n # With mu broadcasted\n test((2,), (3,), axis=-1, plate_axis=-1,\n mu=GaussianARD(3, 4,\n shape=(2,),\n plates=(1,)))\n test((2,), (3,), axis=-1, plate_axis=-1,\n mu=GaussianARD(3, 4,\n shape=(2,),\n plates=()))\n # With mu multiple plates\n test((2,), (3,4,5), axis=-1, plate_axis=-2,\n mu=GaussianARD(3, 4,\n shape=(2,),\n plates=(3,4,5)))\n # With mu multiple dims\n test((2,3,4), (5,), axis=-2, plate_axis=-1,\n mu=GaussianARD(3, 4,\n shape=(2,3,4),\n plates=(5,)))\n\n #\n # With alpha\n #\n print(\"Test: Plate rotation with alpha. Scalars.\")\n test((1,), (1,), axis=-1, plate_axis=-1,\n alpha_plates=(1,1),\n mu=0)\n print(\"Test: Plate rotation with alpha. Plates.\")\n test((1,), (3,), axis=-1, plate_axis=-1,\n alpha_plates=(3,1),\n mu=0)\n print(\"Test: Plate rotation with alpha. Dims.\")\n test((3,), (1,), axis=-1, plate_axis=-1,\n alpha_plates=(1,3),\n mu=0)\n print(\"Test: Plate rotation with alpha. Broadcast alpha over rotated plates.\")\n test((1,), (3,), axis=-1, plate_axis=-1,\n alpha_plates=(1,1),\n mu=0)\n test((1,), (3,), axis=-1, plate_axis=-1,\n alpha_plates=(1,),\n mu=0)\n print(\"Test: Plate rotation with alpha. Broadcast alpha over dims.\")\n test((3,), (1,), axis=-1, plate_axis=-1,\n alpha_plates=(1,1),\n mu=0)\n test((3,), (1,), axis=-1, plate_axis=-1,\n alpha_plates=(),\n mu=0)\n print(\"Test: Plate rotation with alpha. Multiple dims.\")\n test((2,3,4,5), (6,), axis=-2, plate_axis=-1,\n alpha_plates=(6,2,3,4,5),\n mu=0)\n print(\"Test: Plate rotation with alpha. Multiple plates.\")\n test((2,), (3,4,5), axis=-1, plate_axis=-1,\n alpha_plates=(3,4,5,2),\n mu=0)\n test((2,), (3,4,5), axis=-1, plate_axis=-2,\n alpha_plates=(3,4,5,2),\n mu=0)\n test((2,), (3,4,5), axis=-1, plate_axis=-3,\n alpha_plates=(3,4,5,2),\n mu=0)\n\n #\n # With alpha and mu\n #\n print(\"Test: Plate rotation with alpha and mu. Scalars.\")\n test((1,), (1,), axis=-1, plate_axis=-1,\n alpha_plates=(1,1),\n mu=GaussianARD(2, 3,\n shape=(1,),\n plates=(1,)))\n print(\"Test: Plate rotation with alpha and mu. Plates.\")\n test((1,), (3,), axis=-1, plate_axis=-1,\n alpha_plates=(3,1),\n mu=GaussianARD(2, 3,\n shape=(1,),\n plates=(3,)))\n print(\"Test: Plate rotation with alpha and mu. Dims.\")\n test((3,), (1,), axis=-1, plate_axis=-1,\n alpha_plates=(1,3),\n mu=GaussianARD(2, 3,\n shape=(3,),\n plates=(1,)))\n print(\"Test: Plate rotation with alpha and mu. Broadcast over rotated \"\n \"plates.\")\n test((1,), (3,), axis=-1, plate_axis=-1,\n alpha_plates=(1,1),\n mu=GaussianARD(2, 3,\n shape=(1,),\n plates=(1,)))\n test((1,), (3,), axis=-1, plate_axis=-1,\n alpha_plates=(1,),\n mu=GaussianARD(2, 3,\n shape=(1,),\n plates=()))\n print(\"Test: Plate rotation with alpha and mu. Broadcast over dims.\")\n test((3,), (1,), axis=-1, plate_axis=-1,\n alpha_plates=(1,1),\n mu=GaussianARD(2, 3,\n shape=(1,),\n plates=(1,)))\n test((3,), (1,), axis=-1, plate_axis=-1,\n alpha_plates=(),\n mu=GaussianARD(2, 3,\n shape=(),\n plates=(1,)))\n print(\"Test: Plate rotation with alpha and mu. Multiple dims.\")\n test((2,3,4,5), (6,), axis=-2, plate_axis=-1,\n alpha_plates=(6,2,3,4,5),\n mu=GaussianARD(2, 3,\n shape=(2,3,4,5),\n plates=(6,)))\n print(\"Test: Plate rotation with alpha and mu. Multiple plates.\")\n test((2,), (3,4,5), axis=-1, plate_axis=-1,\n alpha_plates=(3,4,5,2),\n mu=GaussianARD(2, 3,\n shape=(2,),\n plates=(3,4,5,)))\n test((2,), (3,4,5), axis=-1, plate_axis=-2,\n alpha_plates=(3,4,5,2),\n mu=GaussianARD(2, 3,\n shape=(2,),\n plates=(3,4,5,)))\n test((2,), (3,4,5), axis=-1, plate_axis=-3,\n alpha_plates=(3,4,5,2),\n mu=GaussianARD(2, 3,\n shape=(2,),\n plates=(3,4,5,)))\n\n # TODO: With missing values\n \n pass",
"def test_jacobian_variable_multiply(self, torch_support, rep, tol):\n x = 0.43316321\n y = 0.2162158\n z = 0.75110998\n\n dev = qml.device(\"default.tensor.tf\", wires=1, representation=rep)\n\n @qml.qnode(dev)\n def circuit(p):\n qml.RX(3 * p[0], wires=0)\n qml.RY(p[1], wires=0)\n qml.RX(p[2] / 2, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n res = circuit([x, y, z])\n expected = np.cos(3 * x) * np.cos(y) * np.cos(z / 2) - np.sin(3 * x) * np.sin(z / 2)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n res = qml.jacobian(circuit)(np.array([x, y, z]))\n expected = np.array(\n [\n -3 * (np.sin(3 * x) * np.cos(y) * np.cos(z / 2) + np.cos(3 * x) * np.sin(z / 2)),\n -np.cos(3 * x) * np.sin(y) * np.cos(z / 2),\n -0.5 * (np.sin(3 * x) * np.cos(z / 2) + np.cos(3 * x) * np.cos(y) * np.sin(z / 2)),\n ]\n )\n\n assert np.allclose(res, expected, atol=tol, rtol=0)",
"def test_autograd(self, tol, batch_dim):\n dev = qml.device(\"default.qubit.autograd\", wires=2)\n params = np.array([0.543, -0.654], requires_grad=True)\n if batch_dim is not None:\n params = np.outer(np.arange(1, 1 + batch_dim), params, requires_grad=True)\n tangent = np.array([1.0, 0.3], requires_grad=False)\n\n def cost_fn(params, tangent):\n with qml.queuing.AnnotatedQueue() as q:\n ansatz(params[..., 0], params[..., 1])\n\n tape = qml.tape.QuantumScript.from_queue(q)\n tape.trainable_params = {0, 1}\n tapes, fn = qml.gradients.jvp(tape, tangent, param_shift)\n jvp = fn(dev.batch_execute(tapes))\n return jvp\n\n res = cost_fn(params, tangent)\n exp = expected_jvp(params, tangent)\n assert np.allclose(res, exp, atol=tol, rtol=0)\n\n res = qml.jacobian(cost_fn)(params, tangent)\n exp = qml.jacobian(expected_jvp)(params, tangent)\n assert np.allclose(res, exp, atol=tol, rtol=0)",
"def test_fallback_log_jac_det():\n\n class SquareTransform(RVTransform):\n name = \"square\"\n\n def forward(self, value, *inputs):\n return at.power(value, 2)\n\n def backward(self, value, *inputs):\n return at.sqrt(value)\n\n square_tr = SquareTransform()\n\n value = at.scalar(\"value\")\n value_tr = square_tr.forward(value)\n log_jac_det = square_tr.log_jac_det(value_tr)\n\n assert np.isclose(log_jac_det.eval({value: 3}), -np.log(6))",
"def test_ragged_output(self):\n dev = qml.device(\"default.qubit\", wires=3)\n params = [1.0, 1.0, 1.0]\n\n with JacobianTape() as tape:\n qml.RX(params[0], wires=[0])\n qml.RY(params[1], wires=[1])\n qml.RZ(params[2], wires=[2])\n qml.CNOT(wires=[0, 1])\n qml.probs(wires=0)\n qml.probs(wires=[1, 2])\n\n res = tape.jacobian(dev)\n assert res.shape == (6, 3)",
"def testDenseLayerAutoJit(self):\n\n os.environ[\"TF_XLA_FLAGS\"] = (\n \"--tf_xla_cpu_global_jit \" + os.environ.get(\"TF_XLA_FLAGS\", \"\"))\n config = config_pb2.ConfigProto()\n config.graph_options.optimizer_options.global_jit_level = (\n config_pb2.OptimizerOptions.ON_1)\n\n with self.session(config=config) as sess:\n x = array_ops.placeholder(shape=[None, None, 3], dtype=np.float32)\n y = layers.dense(x, 3)\n\n self.evaluate(variables.global_variables_initializer())\n run_metadata = config_pb2.RunMetadata()\n test_utils.RunWithWarmup(\n sess,\n y, {x: np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])},\n run_metadata=run_metadata,\n options=config_pb2.RunOptions(\n trace_level=config_pb2.RunOptions.FULL_TRACE))\n\n labels = GetRunMetadataLabels(run_metadata)\n self.assertEqual(1, self.countXlaOps(labels))\n self.assertFalse(InLabels(labels, \"MatMult\"))",
"def computeSymbolicJacobian(self):\n degree = self._params[2].size - 1\n\n x = self._stateSymb[0]\n y = self._stateSymb[1]\n z = self._stateSymb[2]\n x_dot = self._stateSymb[3]\n y_dot = self._stateSymb[4]\n z_dot = self._stateSymb[5]\n\n mu = sp.symbols('mu')\n R_E = sp.symbols('R_E')\n J = sp.symarray('J', degree + 1)\n\n CD_drag, A_drag, mass_sat, rho_0_drag, r0_drag, \\\n H_drag, theta_dot = sp.symbols('CD_drag A_drag mass_sat rho_0_drag r0_drag H_drag theta_dot')\n\n nmbrOfStates = self.getNmbrOfStates()\n\n F = [0 for i in range(0, nmbrOfStates)]\n dF = [[0 for i in range(0, nmbrOfStates)] for i in range(0, nmbrOfStates)]\n A_lambda = [[0 for i in range(0, nmbrOfStates)] for i in range(0, nmbrOfStates)]\n\n if self._usingDMC:\n w_x = self._stateSymb[-3]\n w_y = self._stateSymb[-2]\n w_z = self._stateSymb[-1]\n B = sp.symarray('B', 3)\n for i in range(0, nmbrOfStates) :\n F[i] = self._modelSymb[i]\n for j in range(0, nmbrOfStates) :\n dF[i][j] = sp.diff(F[i], self._stateSymb[j])\n A_lambda[i][j] = sp.lambdify((x, y, z, x_dot, y_dot, z_dot, w_x, w_y, w_z, mu, R_E, [J], CD_drag, A_drag, mass_sat, rho_0_drag, r0_drag, H_drag, theta_dot, [B]), dF[i][j], \"numpy\")\n else:\n for i in range(0, nmbrOfStates) :\n F[i] = self._modelSymb[i]\n for j in range(0, nmbrOfStates) :\n dF[i][j] = sp.diff(F[i], self._stateSymb[j])\n A_lambda[i][j] = sp.lambdify((x, y, z, x_dot, y_dot, z_dot, mu, R_E, [J], CD_drag, A_drag, mass_sat, rho_0_drag, r0_drag, H_drag, theta_dot), dF[i][j], \"numpy\")\n\n self._jacobianSymb = dF\n self._jacobianLambda = A_lambda\n\n return self._jacobianSymb",
"def call_jacobian(*args) -> ngsolve.bla.MatrixC:",
"def ApproximateJacobian(f, x, dx=1e-6):\n try:\n n = len(x)\n except TypeError:\n n = 1\n fx = f(x)\n Df_x = N.matrix(N.zeros((n,n)))\n for i in range(n):\n\n v = N.matrix(N.zeros((n,1)))\n v[i,0] = dx\n Df_x[:,i] = (f(x + v) - fx)/v[i,0]\n return Df_x",
"def test_compute_jvp_single(self, jac, tangent, exp):\n jvp = qml.gradients.compute_jvp_single(tangent, jac)\n assert isinstance(jvp, np.ndarray)\n assert np.array_equal(jvp, exp)",
"def Jacobian(self,t,y):\n return -self.lambd",
"def testDiMatrix(self):\n absoluteTolerance = 0.003;# Absolute error tolerance for test data (we only have it to 4 digits)\n relativeTolerance = 0.1; # Relative error tolerance (probably not necessary)\n kx = 1.0006; # x component of k vector\n ky = 0.4247; # y component of k vector\n l0 = 2.7; # Free-space wavelength\n k0 = 2.3271; # Free-space wavenumber\n\n # LAYER 1 DATA\n er = 2.0;\n ur = 1.0;\n kz = 0.9046;\n A = complexArray([[2.0049, -0.0427], [-0.0427, 2.0873]]);\n B = complexArray([[-0.0049, 0.0427], [0.0427, -0.0873]]);\n X = complexArray([[0.1493 + 0.9888j, 0+0j],[0+0j, 0.4193 + 0.9888j]]);\n\n D_calc = calculateScatteringDMatrix(A, B, X);\n D_actual = complexArray([[2.0057 - 0.0003j, -0.0445 + 0.0006j],[-0.0445 + 0.0006j, 2.0916 - 0.0013j]]);\n assertAlmostEqual(D_actual, D_calc, absoluteTolerance, relativeTolerance);\n\n # LAYER 2 DATA\n # Since now we have the d-matrix to higher precision we can test it more strongly.\n absoluteTolerance = 0.0001;# Absolute error tolerance for test data (we only have it to 4 digits)\n relativeTolerance = 0.001; # Relative error tolerance (probably not necessary)\n er = 1.0;\n ur = 3.0;\n kz = 1.3485;\n L = 0.5*l0;\n\n A = complexArray([[3.8324, 0.2579],[0.2579, 3.3342]]);\n B = complexArray([[-1.8324, -0.2579], [-0.2579, -1.3342]]);\n X = complexArray([[-0.4583 - 0.8888j, 0+0j],[0+0j, -0.4583 - 0.8888j]]);\n\n D_calc = calculateScatteringDMatrix(A, B, X);\n D_actual = complexArray([[4.3436 - 0.7182j, 0.3604 - 0.1440j], [0.3604 - 0.1440j, 3.6475 - 0.4401j]]);\n assertAlmostEqual(D_actual, D_calc, absoluteTolerance, relativeTolerance);"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test that a broadcasted 2 qubit gate on consecutive wires correctly expands to 4 qubits.
|
def test_expand_two_consecutive_wires_broadcasted(self, tol):
U2 = np.array([[0, 1, 1, 1], [1, 0, 1, -1], [1, -1, 0, 1], [1, 1, -1, 0]]) / np.sqrt(3)
U2 = np.tensordot([2.31, 1.53, 0.7 - 1.9j], U2, axes=0)
# test applied to wire 0+1
res = qml.operation.expand_matrix(U2, [0, 1], [0, 1, 2, 3])
expected = np.kron(np.kron(U2, I_broadcasted), I_broadcasted)
assert np.allclose(res, expected, atol=tol, rtol=0)
# test applied to wire 1+2
res = qml.operation.expand_matrix(U2, [1, 2], [0, 1, 2, 3])
expected = np.kron(np.kron(I_broadcasted, U2), I_broadcasted)
assert np.allclose(res, expected, atol=tol, rtol=0)
# test applied to wire 2+3
res = qml.operation.expand_matrix(U2, [2, 3], [0, 1, 2, 3])
expected = np.kron(np.kron(I_broadcasted, I_broadcasted), U2)
assert np.allclose(res, expected, atol=tol, rtol=0)
|
[
"def test_6q_circuit_20q_coupling(self):\n # ┌───┐┌───┐┌───┐┌───┐┌───┐\n # q0_0: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├\n # └─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘\n # q0_1: ──┼────■────┼────┼────┼──\n # │ ┌───┐ │ │ │\n # q0_2: ──┼──┤ X ├──┼────■────┼──\n # │ └───┘ │ │\n # q1_0: ──■─────────┼─────────┼──\n # ┌───┐ │ │\n # q1_1: ─────┤ X ├──┼─────────■──\n # └───┘ │\n # q1_2: ────────────■────────────\n qr0 = QuantumRegister(3, \"q0\")\n qr1 = QuantumRegister(3, \"q1\")\n circuit = QuantumCircuit(qr0, qr1)\n circuit.cx(qr1[0], qr0[0])\n circuit.cx(qr0[1], qr0[0])\n circuit.cx(qr1[2], qr0[0])\n circuit.x(qr0[2])\n circuit.cx(qr0[2], qr0[0])\n circuit.x(qr1[1])\n circuit.cx(qr1[1], qr0[0])\n\n dag = circuit_to_dag(circuit)\n pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32)\n pass_.run(dag)\n\n layout = pass_.property_set[\"layout\"]\n self.assertEqual([layout[q] for q in circuit.qubits], [7, 8, 12, 6, 11, 13])",
"def test_5q_circuit_20q_coupling(self):\n # ┌───┐\n # q_0: ──■───────┤ X ├───────────────\n # │ └─┬─┘┌───┐\n # q_1: ──┼────■────┼──┤ X ├───────■──\n # ┌─┴─┐ │ │ ├───┤┌───┐┌─┴─┐\n # q_2: ┤ X ├──┼────┼──┤ X ├┤ X ├┤ X ├\n # └───┘┌─┴─┐ │ └───┘└─┬─┘└───┘\n # q_3: ─────┤ X ├──■─────────┼───────\n # └───┘ │\n # q_4: ──────────────────────■───────\n qr = QuantumRegister(5, \"q\")\n circuit = QuantumCircuit(qr)\n circuit.cx(qr[0], qr[2])\n circuit.cx(qr[1], qr[3])\n circuit.cx(qr[3], qr[0])\n circuit.x(qr[2])\n circuit.cx(qr[4], qr[2])\n circuit.x(qr[1])\n circuit.cx(qr[1], qr[2])\n\n dag = circuit_to_dag(circuit)\n pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32)\n pass_.run(dag)\n\n layout = pass_.property_set[\"layout\"]\n self.assertEqual([layout[q] for q in circuit.qubits], [18, 11, 13, 12, 14])",
"def test_two_qubit_gates_controlled_by(backend, nqubits, ndevices):\n for _ in range(5):\n activeq = random_active_qubits(nqubits, nmin=2)\n qibo_gate = gates.SWAP(*activeq[-2:]).controlled_by(*activeq[:-2])\n cirq_gate = [(cirq.SWAP.controlled(len(activeq) - 2), activeq)]\n assert_gates_equivalent(backend, qibo_gate, cirq_gate, nqubits, ndevices)\n\n theta = np.random.random()\n phi = np.random.random()\n qibo_gate = gates.fSim(*activeq[-2:], theta, phi).controlled_by(*activeq[:-2])\n cirq_gate = [(cirq.FSimGate(theta, phi).controlled(len(activeq) - 2), activeq)]\n assert_gates_equivalent(backend, qibo_gate, cirq_gate, nqubits, ndevices)",
"def test_multiple_measurements_on_same_wire(self, operable_mock_device_2_wires):\n\n def circuit(x):\n qml.RX(x, wires=[0])\n qml.CNOT(wires=[0, 1])\n return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliX(0))\n\n node = qml.QNode(circuit, operable_mock_device_2_wires)\n\n with pytest.raises(QuantumFunctionError, match=\"can only be measured once\"):\n node(0.5)",
"def test_expand_three_nonconsecutive_nonascending_wires_broadcasted(self, tol):\n # test applied to wire 3, 1, 2\n res = qml.operation.expand_matrix(Toffoli_broadcasted, [3, 1, 2], [0, 1, 2, 3])\n # change the control qubit on the Toffoli gate\n rows = [0, 4, 1, 5, 2, 6, 3, 7]\n Toffoli_broadcasted_perm = Toffoli_broadcasted[:, :, rows][:, rows]\n expected = np.kron(I_broadcasted, Toffoli_broadcasted_perm)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n # test applied to wire 3, 0, 2\n res = qml.operation.expand_matrix(Toffoli_broadcasted, [3, 0, 2], [0, 1, 2, 3])\n # change the control qubit on the Toffoli gate\n expected = np.tensordot(\n np.tensordot(\n np.kron(SWAP, II),\n np.kron(I_broadcasted, Toffoli_broadcasted_perm),\n axes=[[1], [1]],\n ),\n np.kron(SWAP, II),\n axes=[[2], [0]],\n )\n expected = np.moveaxis(expected, 0, -2)\n assert np.allclose(res, expected, atol=tol, rtol=0)",
"def test_multiple_registers_with_good_layout(self):\n coupling = CouplingMap([[0, 1], [1, 2]])\n\n qr_q = QuantumRegister(2, 'q')\n qr_a = QuantumRegister(1, 'a')\n cr_c = ClassicalRegister(3, 'c')\n circ = QuantumCircuit(qr_q, qr_a, cr_c)\n circ.cx(qr_q[0], qr_a[0])\n circ.cx(qr_q[1], qr_a[0])\n circ.measure(qr_q[0], cr_c[0])\n circ.measure(qr_q[1], cr_c[1])\n circ.measure(qr_a[0], cr_c[2])\n dag = circuit_to_dag(circ)\n\n layout = Layout({qr_q[0]: 0, qr_a[0]: 1, qr_q[1]: 2})\n\n pass_ = StochasticSwap(coupling, layout, 20, 13)\n after = pass_.run(dag)\n\n self.assertEqual(dag, after)",
"def test_phase_estimated_two_qubit(self):\n\n unitary = unitary_group.rvs(4, random_state=1967)\n eigvals, eigvecs = np.linalg.eig(unitary)\n\n state = eigvecs[:, 0]\n eigval = eigvals[0]\n phase = np.real_if_close(np.log(eigval) / (2 * np.pi * 1j))\n\n estimates = []\n wire_range = range(3, 11)\n\n for wires in wire_range:\n dev = qml.device(\"default.qubit\", wires=wires)\n\n target_wires = [0, 1]\n estimation_wires = range(2, wires)\n\n with qml.tape.QuantumTape() as tape:\n # We want to prepare an eigenstate of RX, in this case |+>\n qml.QubitStateVector(state, wires=target_wires)\n\n qml.templates.QuantumPhaseEstimation(\n unitary, target_wires=target_wires, estimation_wires=estimation_wires\n )\n qml.probs(estimation_wires)\n\n tape = tape.expand()\n res = tape.execute(dev).flatten()\n\n if phase < 0:\n estimate = np.argmax(res) / 2 ** (wires - 2) - 1\n else:\n estimate = np.argmax(res) / 2 ** (wires - 2)\n estimates.append(estimate)\n\n # Check that the error is monotonically decreasing\n for i in range(len(estimates) - 1):\n err1 = np.abs(estimates[i] - phase)\n err2 = np.abs(estimates[i + 1] - phase)\n assert err1 >= err2\n\n # This is quite a large error, but we'd need to push the qubit number up more to get it\n # lower\n assert np.allclose(estimates[-1], phase, rtol=1e-2)",
"def test_permute_wires_1(self):\n coupling = CouplingMap([[0, 1], [0, 2]])\n\n qr = QuantumRegister(3, 'q')\n circuit = QuantumCircuit(qr)\n circuit.cx(qr[1], qr[2])\n dag = circuit_to_dag(circuit)\n\n pass_ = StochasticSwap(coupling, None, 20, 13)\n after = pass_.run(dag)\n\n self.assertEqual(dag, after)",
"def test_correct_gates_single_wire(self):\n weights = np.arange(3, dtype=float)\n\n with qml.tape.OperationRecorder() as rec:\n ArbitraryUnitary(weights, wires=[0])\n\n assert all(op.name == \"PauliRot\" and op.wires == Wires([0]) for op in rec.queue)\n\n pauli_words = [\"X\", \"Y\", \"Z\"]\n\n for i, op in enumerate(rec.queue):\n assert op.data[0] == weights[i]\n assert op.data[1] == pauli_words[i]",
"def test_correct_gates_two_wires(self):\n weights = np.arange(15, dtype=float)\n\n with qml.tape.OperationRecorder() as rec:\n ArbitraryUnitary(weights, wires=[0, 1])\n\n assert all(op.name == \"PauliRot\" and op.wires == Wires([0, 1]) for op in rec.queue)\n\n pauli_words = [\n \"XI\",\n \"YI\",\n \"ZI\",\n \"ZX\",\n \"IX\",\n \"XX\",\n \"YX\",\n \"YY\",\n \"ZY\",\n \"IY\",\n \"XY\",\n \"XZ\",\n \"YZ\",\n \"ZZ\",\n \"IZ\",\n ]\n\n for i, op in enumerate(rec.queue):\n assert op.data[0] == weights[i]\n assert op.data[1] == pauli_words[i]",
"def test_multiple_registers_with_layout_adjust(self):\n coupling = CouplingMap([[0, 1], [1, 2]])\n\n qr_q = QuantumRegister(2, 'q')\n qr_a = QuantumRegister(1, 'a')\n cr_c = ClassicalRegister(3, 'c')\n circ = QuantumCircuit(qr_q, qr_a, cr_c)\n circ.cx(qr_q[0], qr_a[0])\n circ.cx(qr_q[1], qr_a[0])\n circ.measure(qr_q[0], cr_c[0])\n circ.measure(qr_q[1], cr_c[1])\n circ.measure(qr_a[0], cr_c[2])\n dag = circuit_to_dag(circ)\n\n layout = Layout({qr_q[0]: 0, qr_q[1]: 1, qr_a[0]: 2})\n\n pass_ = StochasticSwap(coupling, layout, 20, 13)\n after = pass_.run(dag)\n\n self.assertEqual(dag, after)",
"def test_different_batch_sizes_raises_error(self):\n base = qml.RX(np.array([1.2, 2.3, 3.4]), 0)\n with pytest.raises(\n ValueError, match=\"Broadcasting was attempted but the broadcasted dimensions\"\n ):\n _ = ValidOp(base, qml.RY(1, 0), qml.RZ(np.array([1, 2, 3, 4]), wires=2))",
"def test_different_queue_measurements_outside(self, obs):\n\n with qml.tape.QuantumTape() as tape1:\n with qml.tape.QuantumTape() as tape2:\n op1 = qml.expval(obs)\n op2 = qml.apply(op1, tape1)\n\n assert tape1.measurements == [op2]\n assert tape2.measurements == [op1]",
"def test_one_qubit_gates(backend, gate_name, nqubits, ndevices):\n targets = random_active_qubits(nqubits, nactive=1)\n qibo_gate = getattr(gates, gate_name)(*targets)\n cirq_gate = [(getattr(cirq, gate_name), targets)]\n assert_gates_equivalent(backend, qibo_gate, cirq_gate, nqubits, ndevices)",
"def test_no_expansion_broadcasted(self):\n res = qml.operation.expand_matrix(\n self.base_matrix_2_broadcasted, wires=[0, 2], wire_order=[0, 2]\n )\n assert np.allclose(self.base_matrix_2_broadcasted, res)",
"def test_expansion_broadcasted(self):\n res = qml.operation.expand_matrix(\n self.base_matrix_1_broadcasted, wires=[2], wire_order=[0, 2]\n )\n expected = np.array(\n [\n [\n [1, 2, 0, 0],\n [3, 4, 0, 0],\n [0, 0, 1, 2],\n [0, 0, 3, 4],\n ],\n [\n [5, 6, 0, 0],\n [7, 8, 0, 0],\n [0, 0, 5, 6],\n [0, 0, 7, 8],\n ],\n [\n [9, 10, 0, 0],\n [11, 12, 0, 0],\n [0, 0, 9, 10],\n [0, 0, 11, 12],\n ],\n ]\n )\n assert np.allclose(expected, res)\n\n res = qml.operation.expand_matrix(\n self.base_matrix_1_broadcasted, wires=[2], wire_order=[2, 0]\n )\n expected = np.array(\n [\n [\n [1, 0, 2, 0],\n [0, 1, 0, 2],\n [3, 0, 4, 0],\n [0, 3, 0, 4],\n ],\n [\n [5, 0, 6, 0],\n [0, 5, 0, 6],\n [7, 0, 8, 0],\n [0, 7, 0, 8],\n ],\n [\n [9, 0, 10, 0],\n [0, 9, 0, 10],\n [11, 0, 12, 0],\n [0, 11, 0, 12],\n ],\n ]\n )\n assert np.allclose(expected, res)",
"def test_build_circuit_product():\n qpu = cirq.Simulator(dtype=numpy.complex128)\n qubits = cirq.LineQubit.range(4)\n ops = QubitOperator('', 1.0)\n for i in range(4):\n ops *= QubitOperator('X' + str(i), 1.0)\n for j in ops.terms:\n circuit = cirq_utils.qubit_ops_to_circuit(j, qubits)\n init_state = numpy.zeros(2**4, dtype=numpy.complex128)\n init_state[0] = 1.0 + 0.0j\n result = qpu.simulate(circuit, qubit_order=qubits, initial_state=init_state)\n final_state = numpy.zeros(2**4, dtype=numpy.complex128)\n final_state[-1] = 1.0 + 0.0j\n assert list(result.final_state_vector) == list(final_state)",
"def test_append_qubit_observables(self):\n with Queue() as q:\n # wire repetition is deliberate, Queue contains no checks/logic\n # for circuits\n ops = [\n qml.Hadamard(wires=0),\n qml.PauliX(wires=1),\n qml.PauliY(wires=1),\n qml.Hermitian(np.ones([2, 2]), wires=7),\n ]\n assert q.queue == ops",
"def test_compiling_gates_different_sampling_number():\n\n class MockCompiler(GateCompiler):\n def __init__(self, num_qubits, params=None):\n super().__init__(num_qubits, params=params)\n self.gate_compiler[\"U1\"] = self.single_qubit_gate_compiler\n self.gate_compiler[\"U2\"] = self.two_qubit_gate_compiler\n self.args.update({\"params\": params})\n\n def single_qubit_gate_compiler(self, gate, args):\n pulse_info = [(\"x\", np.array([1.0] * 3))]\n return [\n Instruction(\n gate, tlist=np.linspace(0, 2, 3), pulse_info=pulse_info\n )\n ]\n\n def two_qubit_gate_compiler(self, gate, args):\n pulse_info = [(\"xx\", np.array([2.0] * 5))]\n return [\n Instruction(\n gate, tlist=np.linspace(0, 4, 5), pulse_info=pulse_info\n )\n ]\n\n num_qubits = 2\n circuit = QubitCircuit(num_qubits)\n circuit.add_gate(\"U1\", targets=0, arg_value=1.0)\n circuit.add_gate(\"U2\", targets=[0, 1], arg_value=1.0)\n circuit.add_gate(\"U1\", targets=0, arg_value=1.0)\n\n compiler = MockCompiler(num_qubits=2)\n compiled_tlists, compiled_coeffs = compiler.compile(circuit)\n\n # Filter out the nonzero part of the pulse\n # and check if they are correct.\n np.testing.assert_array_equal(\n compiled_tlists[\"x\"][np.nonzero(compiled_coeffs[\"x\"])[0]],\n np.array([1, 2, 7, 8]),\n )\n np.testing.assert_array_equal(\n compiled_tlists[\"xx\"][np.nonzero(compiled_coeffs[\"xx\"])[0]],\n np.array([3, 4, 5, 6]),\n )"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test that a broadcasted 3 qubit gate on nonconsecutive nonascending wires correctly expands to 4 qubits
|
def test_expand_three_nonconsecutive_nonascending_wires_broadcasted(self, tol):
# test applied to wire 3, 1, 2
res = qml.operation.expand_matrix(Toffoli_broadcasted, [3, 1, 2], [0, 1, 2, 3])
# change the control qubit on the Toffoli gate
rows = [0, 4, 1, 5, 2, 6, 3, 7]
Toffoli_broadcasted_perm = Toffoli_broadcasted[:, :, rows][:, rows]
expected = np.kron(I_broadcasted, Toffoli_broadcasted_perm)
assert np.allclose(res, expected, atol=tol, rtol=0)
# test applied to wire 3, 0, 2
res = qml.operation.expand_matrix(Toffoli_broadcasted, [3, 0, 2], [0, 1, 2, 3])
# change the control qubit on the Toffoli gate
expected = np.tensordot(
np.tensordot(
np.kron(SWAP, II),
np.kron(I_broadcasted, Toffoli_broadcasted_perm),
axes=[[1], [1]],
),
np.kron(SWAP, II),
axes=[[2], [0]],
)
expected = np.moveaxis(expected, 0, -2)
assert np.allclose(res, expected, atol=tol, rtol=0)
|
[
"def test_5q_circuit_20q_coupling(self):\n # ┌───┐\n # q_0: ──■───────┤ X ├───────────────\n # │ └─┬─┘┌───┐\n # q_1: ──┼────■────┼──┤ X ├───────■──\n # ┌─┴─┐ │ │ ├───┤┌───┐┌─┴─┐\n # q_2: ┤ X ├──┼────┼──┤ X ├┤ X ├┤ X ├\n # └───┘┌─┴─┐ │ └───┘└─┬─┘└───┘\n # q_3: ─────┤ X ├──■─────────┼───────\n # └───┘ │\n # q_4: ──────────────────────■───────\n qr = QuantumRegister(5, \"q\")\n circuit = QuantumCircuit(qr)\n circuit.cx(qr[0], qr[2])\n circuit.cx(qr[1], qr[3])\n circuit.cx(qr[3], qr[0])\n circuit.x(qr[2])\n circuit.cx(qr[4], qr[2])\n circuit.x(qr[1])\n circuit.cx(qr[1], qr[2])\n\n dag = circuit_to_dag(circuit)\n pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32)\n pass_.run(dag)\n\n layout = pass_.property_set[\"layout\"]\n self.assertEqual([layout[q] for q in circuit.qubits], [18, 11, 13, 12, 14])",
"def test_6q_circuit_20q_coupling(self):\n # ┌───┐┌───┐┌───┐┌───┐┌───┐\n # q0_0: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├\n # └─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘\n # q0_1: ──┼────■────┼────┼────┼──\n # │ ┌───┐ │ │ │\n # q0_2: ──┼──┤ X ├──┼────■────┼──\n # │ └───┘ │ │\n # q1_0: ──■─────────┼─────────┼──\n # ┌───┐ │ │\n # q1_1: ─────┤ X ├──┼─────────■──\n # └───┘ │\n # q1_2: ────────────■────────────\n qr0 = QuantumRegister(3, \"q0\")\n qr1 = QuantumRegister(3, \"q1\")\n circuit = QuantumCircuit(qr0, qr1)\n circuit.cx(qr1[0], qr0[0])\n circuit.cx(qr0[1], qr0[0])\n circuit.cx(qr1[2], qr0[0])\n circuit.x(qr0[2])\n circuit.cx(qr0[2], qr0[0])\n circuit.x(qr1[1])\n circuit.cx(qr1[1], qr0[0])\n\n dag = circuit_to_dag(circuit)\n pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32)\n pass_.run(dag)\n\n layout = pass_.property_set[\"layout\"]\n self.assertEqual([layout[q] for q in circuit.qubits], [7, 8, 12, 6, 11, 13])",
"def test_three_qubit_no_parameters(self, device, init_state, op, mat, tol, skip_if):\n n_wires = 3\n dev = device(n_wires)\n skip_if(dev, {\"inverse_operations\": False})\n\n rnd_state = init_state(3)\n\n @qml.qnode(dev)\n def circuit():\n qml.QubitStateVector(rnd_state, wires=range(n_wires))\n op(wires=range(n_wires)).inv()\n return qml.probs(wires=range(n_wires))\n\n res = circuit()\n\n mat = mat.conj().T\n expected = np.abs(mat @ rnd_state) ** 2\n assert np.allclose(res, expected, atol=tol(dev.analytic))",
"def test_two_qubit_gates_controlled_by(backend, nqubits, ndevices):\n for _ in range(5):\n activeq = random_active_qubits(nqubits, nmin=2)\n qibo_gate = gates.SWAP(*activeq[-2:]).controlled_by(*activeq[:-2])\n cirq_gate = [(cirq.SWAP.controlled(len(activeq) - 2), activeq)]\n assert_gates_equivalent(backend, qibo_gate, cirq_gate, nqubits, ndevices)\n\n theta = np.random.random()\n phi = np.random.random()\n qibo_gate = gates.fSim(*activeq[-2:], theta, phi).controlled_by(*activeq[:-2])\n cirq_gate = [(cirq.FSimGate(theta, phi).controlled(len(activeq) - 2), activeq)]\n assert_gates_equivalent(backend, qibo_gate, cirq_gate, nqubits, ndevices)",
"def test_append_qubit_observables(self):\n with Queue() as q:\n # wire repetition is deliberate, Queue contains no checks/logic\n # for circuits\n ops = [\n qml.Hadamard(wires=0),\n qml.PauliX(wires=1),\n qml.PauliY(wires=1),\n qml.Hermitian(np.ones([2, 2]), wires=7),\n ]\n assert q.queue == ops",
"def test_qubit_order(self):\n\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n qc = QuantumCircuit(qr, cr)\n qc.x(qr[0])\n\n result = execute(qc, backend=self.projectq_sim).result()\n self.assertEqual(result.status, 'COMPLETED')\n actual = result.get_statevector(qc)\n\n # state is |01> (up to a global phase), because qubit 0 is LSB\n self.assertAlmostEqual(abs(actual[0]), 0)\n self.assertAlmostEqual((abs(actual[1]))**2, 1)\n self.assertAlmostEqual(abs(actual[2]), 0)\n self.assertAlmostEqual(abs(actual[3]), 0)",
"def test_expand_two_consecutive_wires_broadcasted(self, tol):\n U2 = np.array([[0, 1, 1, 1], [1, 0, 1, -1], [1, -1, 0, 1], [1, 1, -1, 0]]) / np.sqrt(3)\n U2 = np.tensordot([2.31, 1.53, 0.7 - 1.9j], U2, axes=0)\n\n # test applied to wire 0+1\n res = qml.operation.expand_matrix(U2, [0, 1], [0, 1, 2, 3])\n expected = np.kron(np.kron(U2, I_broadcasted), I_broadcasted)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n # test applied to wire 1+2\n res = qml.operation.expand_matrix(U2, [1, 2], [0, 1, 2, 3])\n expected = np.kron(np.kron(I_broadcasted, U2), I_broadcasted)\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n # test applied to wire 2+3\n res = qml.operation.expand_matrix(U2, [2, 3], [0, 1, 2, 3])\n expected = np.kron(np.kron(I_broadcasted, I_broadcasted), U2)\n assert np.allclose(res, expected, atol=tol, rtol=0)",
"def test_correct_gates_single_wire(self):\n weights = np.arange(3, dtype=float)\n\n with qml.tape.OperationRecorder() as rec:\n ArbitraryUnitary(weights, wires=[0])\n\n assert all(op.name == \"PauliRot\" and op.wires == Wires([0]) for op in rec.queue)\n\n pauli_words = [\"X\", \"Y\", \"Z\"]\n\n for i, op in enumerate(rec.queue):\n assert op.data[0] == weights[i]\n assert op.data[1] == pauli_words[i]",
"def test_layout_with_classical_bits(self):\n qc = QuantumCircuit.from_qasm_str(\n \"\"\"\nOPENQASM 2.0;\ninclude \"qelib1.inc\";\nqreg q4833[1];\nqreg q4834[6];\nqreg q4835[7];\ncreg c982[2];\ncreg c983[2];\ncreg c984[2];\nrzz(0) q4833[0],q4834[4];\ncu(0,-6.1035156e-05,0,1e-05) q4834[1],q4835[2];\nswap q4834[0],q4834[2];\ncu(-1.1920929e-07,0,-0.33333333,0) q4833[0],q4834[2];\nccx q4835[2],q4834[5],q4835[4];\nmeasure q4835[4] -> c984[0];\nccx q4835[2],q4835[5],q4833[0];\nmeasure q4835[5] -> c984[1];\nmeasure q4834[0] -> c982[1];\nu(10*pi,0,1.9) q4834[5];\nmeasure q4834[3] -> c984[1];\nmeasure q4835[0] -> c982[0];\nrz(0) q4835[1];\n\"\"\"\n )\n res = transpile(qc, FakeKolkata(), layout_method=\"sabre\", seed_transpiler=1234)\n self.assertIsInstance(res, QuantumCircuit)\n layout = res._layout.initial_layout\n self.assertEqual(\n [layout[q] for q in qc.qubits], [13, 10, 11, 12, 17, 14, 22, 26, 5, 16, 25, 19, 7, 8]\n )",
"def test_build_circuit_product():\n qpu = cirq.Simulator(dtype=numpy.complex128)\n qubits = cirq.LineQubit.range(4)\n ops = QubitOperator('', 1.0)\n for i in range(4):\n ops *= QubitOperator('X' + str(i), 1.0)\n for j in ops.terms:\n circuit = cirq_utils.qubit_ops_to_circuit(j, qubits)\n init_state = numpy.zeros(2**4, dtype=numpy.complex128)\n init_state[0] = 1.0 + 0.0j\n result = qpu.simulate(circuit, qubit_order=qubits, initial_state=init_state)\n final_state = numpy.zeros(2**4, dtype=numpy.complex128)\n final_state[-1] = 1.0 + 0.0j\n assert list(result.final_state_vector) == list(final_state)",
"def test_permute_wires_1(self):\n coupling = CouplingMap([[0, 1], [0, 2]])\n\n qr = QuantumRegister(3, 'q')\n circuit = QuantumCircuit(qr)\n circuit.cx(qr[1], qr[2])\n dag = circuit_to_dag(circuit)\n\n pass_ = StochasticSwap(coupling, None, 20, 13)\n after = pass_.run(dag)\n\n self.assertEqual(dag, after)",
"def test_real_amplitudes_circuit_4q(self, do_commutative_analysis):\n ansatz = RealAmplitudes(4, reps=2)\n circuit1 = ansatz.decompose()\n\n # collect linear functions\n circuit2 = PassManager(\n CollectLinearFunctions(do_commutative_analysis=do_commutative_analysis)\n ).run(circuit1)\n self.assertEqual(circuit2.count_ops()[\"linear_function\"], 2)\n\n # synthesize linear functions\n circuit3 = PassManager(HighLevelSynthesis()).run(circuit2)\n self.assertEqual(circuit3.count_ops()[\"cx\"], 6)",
"def test_u3_simplified_x(self, wires, res):\n commutation = qml.is_commuting(\n qml.U3(0.1, -np.pi / 2, np.pi / 2, wires=wires[0]), qml.PauliX(wires=wires[1])\n )\n assert commutation == res",
"def test_three_mode(self, tol):\n N = 3\n wires = range(N)\n\n theta = [0.321, 0.4523, 0.21321]\n phi = [0.234, 0.324, 0.234]\n varphi = [0.42342, 0.234, 0.1121]\n\n with qml.tape.OperationRecorder() as rec_rect:\n Interferometer(theta, phi, varphi, wires=wires)\n\n with qml.tape.OperationRecorder() as rec_tria:\n Interferometer(theta, phi, varphi, wires=wires)\n\n for rec in [rec_rect, rec_tria]:\n # test both meshes (both give identical results for the 3 mode case).\n assert len(rec.queue) == 6\n\n expected_bs_wires = [[0, 1], [1, 2], [0, 1]]\n\n for idx, op in enumerate(rec_rect.queue[:3]):\n assert isinstance(op, qml.Beamsplitter)\n assert op.parameters == [theta[idx], phi[idx]]\n assert op.wires == Wires(expected_bs_wires[idx])\n\n for idx, op in enumerate(rec.queue[3:]):\n assert isinstance(op, qml.Rotation)\n assert op.parameters == [varphi[idx]]\n assert op.wires == Wires([idx])",
"def test_real_amplitudes_circuit_5q(self, do_commutative_analysis):\n ansatz = RealAmplitudes(5, reps=2)\n circuit1 = ansatz.decompose()\n\n # collect linear functions\n circuit2 = PassManager(\n CollectLinearFunctions(do_commutative_analysis=do_commutative_analysis)\n ).run(circuit1)\n self.assertEqual(circuit2.count_ops()[\"linear_function\"], 2)\n\n # synthesize linear functions\n circuit3 = PassManager(HighLevelSynthesis()).run(circuit2)\n self.assertEqual(circuit3.count_ops()[\"cx\"], 8)",
"def test_u3_simplified_z(self, wires, res):\n commutation = qml.is_commuting(\n qml.U3(0.0, 0.1, 0.0, wires=wires[1]), qml.PauliZ(wires=wires[0])\n )\n assert commutation == res",
"def test_multi_channel_phase_space(self):\n \n # A specific sets of s- and t-channels for this test:\n\n ####################################################################\n # a) A simple unique massless photon s-channel from e+ e- > d d~ / z\n ####################################################################\n \n massless_photon_schannel_specifier = (\n # s-channels first:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 15,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': -1,\n 'number': 4,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 1,\n 'number': 3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 22,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n })\n ])\n }),\n ]),\n # t-channels then:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 34,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 11,\n 'number': 1,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 22,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': -11,\n 'number': -2,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n })\n ])\n }),\n ])\n ) \n \n ####################################################################\n # a) A simple unique massive Z-boson s-channel from e+ e- > d d~ / a\n ####################################################################\n \n massive_zboson_schannel_specifier = (\n # s-channels first:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 22,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': -1,\n 'number': 4,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 1,\n 'number': 3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n ]),\n # t-channels then:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 40,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 11,\n 'number': 1,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': -11,\n 'number': -2,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n ]),\n )\n \n ###############################################################################\n # c) A complicated fully decayed VBF topology: \n # from: generate u c > h > u c e+ e- mu+ mu- $$ c u / a s d s~ d~ QCD=0 --LO\n ###############################################################################\n vbf_topology_s_and_t_channel_specifier = (\n # s-channels first:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 41,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 13,\n 'number': 8,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': -13,\n 'number': 7,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 40,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 11,\n 'number': 6,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': -11,\n 'number': 5,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -2,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 13,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -2,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 25,\n 'number': -3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n })\n ]),\n # t-channels then:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 63,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': -2,\n 'number': 1,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 2,\n 'number': 3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -4,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 13,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -4,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 25,\n 'number': -3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -5,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 64,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -5,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 4,\n 'number': 4,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': -4,\n 'number': -6,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n ]),\n )\n\n\n ###############################################################################\n # d) A complicated fully decayed VBF topology: \n # from: generate e- e+ > h > e+ e- mu+ mu- ta+ ta- $$ e+ e- \\ a QCD=0 --diagram_filter --LO\n ###############################################################################\n # where diagram filter removes the first three diagrams\n # import model sm-dario\n self.vbf_topology_s_and_t_channel_specifier2 = (\n # s-channels first:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 42,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 15,\n 'number': 8,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': -15,\n 'number': 7,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 41,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 13,\n 'number': 6,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': -13,\n 'number': 5,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -2,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 13,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -2,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 25,\n 'number': -3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n })\n ]),\n # t-channels then:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 40,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': -11,\n 'number': 1,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 11,\n 'number': 4,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -4,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 13,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -4,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 25,\n 'number': -3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -5,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 40,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -5,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': -11,\n 'number': 3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 11,\n 'number': -6,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n ]),\n )",
"def test_faulty_full_no_reset_no_daggered_circuits():\n q_in = {'q0': 0, 'q1': 1}\n q_latent = {'q1': 1}\n q_refresh = {'q2': 2}\n n_shots = 10\n trash_training = False\n reset = False\n\n sp_circuit = lambda theta, qubit_indices: Program(RY(theta[0], qubit_indices[1]),\n CNOT(qubit_indices[1], qubit_indices[0]))\n \n list_SP_circuits = []\n angle_list = numpy.linspace(-10, 10, 5) # Generate 5 data pts\n\n for angle in angle_list:\n state_prep_unitary = sp_circuit([angle], [0, 1])\n list_SP_circuits.append(state_prep_unitary)\n\n training_circuit = lambda theta, qubit_indices=[0, 1]: Program(RY(-theta[0]/2, qubit_indices[0]),\n CNOT(qubit_indices[1], qubit_indices[0]))\n\n with pytest.raises(ValueError):\n faulty = quantum_autoencoder(state_prep_circuits=list_SP_circuits,\n training_circuit=training_circuit,\n q_in=q_in, q_latent=q_latent, q_refresh=q_refresh,\n trash_training=trash_training, reset=reset, \n n_shots=n_shots, verbose=False)",
"def _makequads_all(self):\n nholes = self.ctrs_eqt.shape[0]\n qlist = []\n for i in range(nholes):\n for j in range(nholes):\n for k in range(nholes):\n for q in range(nholes):\n if i < j and j < k and k < q:\n qlist.append((i, j, k, q))\n qarray = np.array(qlist).astype(int)\n if self.verbose:\n print(\"qarray\", qarray.shape, \"\\n\", qarray)\n qname = []\n uvwlist = []\n # foreach row of 3 elts...\n for quad in qarray:\n qname.append(\"{0:d}_{1:d}_{2:d}_{3:d}\".format(\n quad[0], quad[1], quad[2], quad[3]))\n if self.verbose:\n print('quad:', quad, qname[-1])\n uvwlist.append((self.ctrs_eqt[quad[0]] - self.ctrs_eqt[quad[1]],\n self.ctrs_eqt[quad[1]] - self.ctrs_eqt[quad[2]],\n self.ctrs_eqt[quad[2]] - self.ctrs_eqt[quad[3]]))\n if self.verbose:\n print(qarray.shape, np.array(uvwlist).shape)\n return qarray, np.array(uvwlist)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Tests that the method is used correctly with a broadcasted matrix by defining a dummy operator and checking the permutation/expansion.
|
def test_expand_matrix_usage_in_operator_class_broadcasted(self, tol):
perm = [0, 2, 1, 3]
permuted_matrix = self.base_matrix_2_broadcasted[:, perm][:, :, perm]
expanded_matrix = np.tensordot(
np.tensordot(
np.kron(SWAP, I),
np.kron(I_broadcasted, self.base_matrix_2_broadcasted),
axes=[[1], [1]],
),
np.kron(SWAP, I),
axes=[[2], [0]],
)
expanded_matrix = np.moveaxis(expanded_matrix, 0, -2)
class DummyOp(qml.operation.Operator):
num_wires = 2
def compute_matrix(*params, **hyperparams):
return self.base_matrix_2_broadcasted
op = DummyOp(wires=[0, 2])
assert np.allclose(op.matrix(), self.base_matrix_2_broadcasted, atol=tol)
assert np.allclose(op.matrix(wire_order=[2, 0]), permuted_matrix, atol=tol)
assert np.allclose(op.matrix(wire_order=[0, 1, 2]), expanded_matrix, atol=tol)
|
[
"def test_no_expansion_broadcasted(self):\n res = qml.operation.expand_matrix(\n self.base_matrix_2_broadcasted, wires=[0, 2], wire_order=[0, 2]\n )\n assert np.allclose(self.base_matrix_2_broadcasted, res)",
"def test_permutation_broadcasted(self):\n res = qml.operation.expand_matrix(\n self.base_matrix_2_broadcasted, wires=[0, 2], wire_order=[2, 0]\n )\n\n perm = [0, 2, 1, 3]\n expected = self.base_matrix_2_broadcasted[:, perm][:, :, perm]\n assert np.allclose(expected, res)",
"def test_expansion_broadcasted(self):\n res = qml.operation.expand_matrix(\n self.base_matrix_1_broadcasted, wires=[2], wire_order=[0, 2]\n )\n expected = np.array(\n [\n [\n [1, 2, 0, 0],\n [3, 4, 0, 0],\n [0, 0, 1, 2],\n [0, 0, 3, 4],\n ],\n [\n [5, 6, 0, 0],\n [7, 8, 0, 0],\n [0, 0, 5, 6],\n [0, 0, 7, 8],\n ],\n [\n [9, 10, 0, 0],\n [11, 12, 0, 0],\n [0, 0, 9, 10],\n [0, 0, 11, 12],\n ],\n ]\n )\n assert np.allclose(expected, res)\n\n res = qml.operation.expand_matrix(\n self.base_matrix_1_broadcasted, wires=[2], wire_order=[2, 0]\n )\n expected = np.array(\n [\n [\n [1, 0, 2, 0],\n [0, 1, 0, 2],\n [3, 0, 4, 0],\n [0, 3, 0, 4],\n ],\n [\n [5, 0, 6, 0],\n [0, 5, 0, 6],\n [7, 0, 8, 0],\n [0, 7, 0, 8],\n ],\n [\n [9, 0, 10, 0],\n [0, 9, 0, 10],\n [11, 0, 12, 0],\n [0, 11, 0, 12],\n ],\n ]\n )\n assert np.allclose(expected, res)",
"def test_has_matrix_true(self):\n\n class MyOp(qml.operation.Operator):\n num_wires = 1\n\n @staticmethod\n def compute_matrix():\n return np.eye(2)\n\n assert MyOp.has_matrix\n assert MyOp(wires=0).has_matrix",
"def test_permutation_operator_dim_2_2_perm_1_2():\n res = permutation_operator([2, 2], [1, 2])\n expected_res = np.identity(4)\n bool_mat = np.isclose(res, expected_res)\n np.testing.assert_equal(np.all(bool_mat), True)",
"def test_permutation_operator_dim_2_2_perm_2_1():\n res = permutation_operator([2, 2], [2, 1])\n expected_res = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])\n bool_mat = np.isclose(res, expected_res)\n np.testing.assert_equal(np.all(bool_mat), True)",
"def test_broadcasted_params(self, params, exp_batch_size):\n import jax\n\n class DummyOp(qml.operation.Operator):\n r\"\"\"Dummy custom operator that declares ndim_params as a class property\"\"\"\n ndim_params = (0, 2)\n num_wires = 1\n\n params = tuple(jax.numpy.array(p) for p in params)\n op = DummyOp(*params, wires=0)\n assert op.ndim_params == (0, 2)\n assert op._batch_size == exp_batch_size",
"def test_superop_transpose_random(self):\n mats = [self.rand_matrix(4, 4) for _ in range(4)]\n chans = [SuperOp(Operator(mat)) for mat in mats]\n self._compare_transpose_to_operator(chans, mats)",
"def test_has_matrix_false(self):\n\n class MyOp(qml.operation.Operator):\n num_wires = 1\n\n assert not MyOp.has_matrix\n assert not MyOp(wires=0).has_matrix",
"def test_permutation_operator_dim_3_perm_1_2():\n res = permutation_operator(3, [1, 2])\n expected_res = np.identity(9)\n bool_mat = np.isclose(res, expected_res)\n np.testing.assert_equal(np.all(bool_mat), True)",
"def test_broadcasted_params(self, params, exp_batch_size):\n import torch\n\n class DummyOp(qml.operation.Operator):\n r\"\"\"Dummy custom operator that declares ndim_params as a class property\"\"\"\n ndim_params = (0, 2)\n num_wires = 1\n\n params = tuple(torch.tensor(p, requires_grad=True) for p in params)\n op = DummyOp(*params, wires=0)\n assert op.ndim_params == (0, 2)\n assert op._batch_size == exp_batch_size",
"def test_broadcasted_params(self, params, exp_batch_size):\n\n class DummyOp(qml.operation.Operator):\n r\"\"\"Dummy custom operator that declares ndim_params as a class property\"\"\"\n ndim_params = (0, 2)\n num_wires = 1\n\n params = tuple(pnp.array(p, requires_grad=True) for p in params)\n op = DummyOp(*params, wires=0)\n assert op.ndim_params == (0, 2)\n assert op._batch_size == exp_batch_size",
"def test_broadcasted_params(self, params, exp_batch_size):\n import tensorflow as tf\n\n class DummyOp(qml.operation.Operator):\n r\"\"\"Dummy custom operator that declares ndim_params as a class property\"\"\"\n ndim_params = (0, 2)\n num_wires = 1\n\n params = tuple(tf.Variable(p) for p in params)\n op = DummyOp(*params, wires=0)\n assert op.ndim_params == (0, 2)\n assert op._batch_size == exp_batch_size",
"def test_permutation_operator_dim_2_perm_1_3_2():\n res = permutation_operator(2, [1, 3, 2])\n expected_res = np.array(\n [\n [\n [1, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 1],\n ]\n ]\n )\n bool_mat = np.isclose(res, expected_res)\n np.testing.assert_equal(np.all(bool_mat), True)",
"def test_superop_adjoint_random(self):\n mats = [self.rand_matrix(4, 4) for _ in range(4)]\n chans = [SuperOp(Operator(mat)) for mat in mats]\n self._compare_adjoint_to_operator(chans, mats)",
"def test_dot(self):\n\n # If no arrays, return 0\n self.assertAllClose(linalg.dot(),\n 0)\n # If only one array, return itself\n self.assertAllClose(linalg.dot([[1,2,3],\n [4,5,6]]),\n [[1,2,3],\n [4,5,6]])\n # Basic test of two arrays: (2,3) * (3,2)\n self.assertAllClose(linalg.dot([[1,2,3],\n [4,5,6]],\n [[7,8],\n [9,1],\n [2,3]]),\n [[31,19],\n [85,55]])\n # Basic test of four arrays: (2,3) * (3,2) * (2,1) * (1,2)\n self.assertAllClose(linalg.dot([[1,2,3],\n [4,5,6]],\n [[7,8],\n [9,1],\n [2,3]],\n [[4],\n [5]],\n [[6,7]]),\n [[1314,1533],\n [3690,4305]])\n\n # Test broadcasting: (2,2,2) * (2,2,2,2)\n self.assertAllClose(linalg.dot([[[1,2],\n [3,4]],\n [[5,6],\n [7,8]]],\n [[[[1,2],\n [3,4]],\n [[5,6],\n [7,8]]],\n [[[9,1],\n [2,3]],\n [[4,5],\n [6,7]]]]),\n [[[[ 7, 10],\n [ 15, 22]],\n\n [[ 67, 78],\n [ 91, 106]]],\n\n\n [[[ 13, 7],\n [ 35, 15]],\n\n [[ 56, 67],\n [ 76, 91]]]])\n\n # Inconsistent shapes: (2,3) * (2,3)\n self.assertRaises(ValueError,\n linalg.dot,\n [[1,2,3],\n [4,5,6]],\n [[1,2,3],\n [4,5,6]])\n # Other axes do not broadcast: (2,2,2) * (3,2,2)\n self.assertRaises(ValueError,\n linalg.dot,\n [[[1,2],\n [3,4]],\n [[5,6],\n [7,8]]],\n [[[1,2],\n [3,4]],\n [[5,6],\n [7,8]],\n [[9,1],\n [2,3]]])\n # Do not broadcast matrix axes: (2,1) * (3,2)\n self.assertRaises(ValueError,\n linalg.dot,\n [[1],\n [2]],\n [[1,2,3],\n [4,5,6]])\n # Do not accept less than 2-D arrays: (2) * (2,2)\n self.assertRaises(ValueError,\n linalg.dot,\n [1,2],\n [[1,2,3],\n [4,5,6]])",
"def test_swap_operator_is_block_positive(dim):\n mat = swap_operator(dim)\n np.testing.assert_equal(is_block_positive(mat), True)\n np.testing.assert_equal(is_block_positive(mat, k=2), False)",
"def check_elementwise_random(op='sum', shape=(1, 3, 224, 224)):\n a = mx.sym.Variable('a')\n b = mx.sym.Variable('b')\n if op == 'sum':\n sym = a + b\n elif op == 'sub':\n sym = a - b\n elif op == 'mul':\n sym = a * b\n\n a_data = mx.ndarray.random.uniform(shape=shape, ctx=mx.gpu())\n b_data = mx.ndarray.random.uniform(shape=shape, ctx=mx.gpu())\n\n executor = sym.simple_bind(ctx=mx.gpu(), a=shape, b=shape,\n grad_req='null', force_rebind=True)\n y = executor.forward(is_train=False, a=a_data, b=b_data)\n trt_sym = sym.get_backend_symbol('TensorRT')\n original_precision_value = mx.contrib.tensorrt.get_use_fp16()\n try:\n mx.contrib.tensorrt.set_use_fp16(True)\n executor = trt_sym.simple_bind(ctx=mx.gpu(), a=shape, b=shape,\n grad_req='null', force_rebind=True)\n y_trt = executor.forward(is_train=False, a=a_data, b=b_data)\n mx.contrib.tensorrt.set_use_fp16(False)\n executor = trt_sym.simple_bind(ctx=mx.gpu(), a=shape, b=shape,\n grad_req='null', force_rebind=True)\n y_trt_fp32 = executor.forward(is_train=False, a=a_data, b=b_data)\n assert_almost_equal(y[0].asnumpy(), y_trt[0].asnumpy(), 1e-1, 1e-2)\n assert_almost_equal(y[0].asnumpy(), y_trt_fp32[0].asnumpy(), 1e-4, 1e-4)\n finally:\n mx.contrib.tensorrt.set_use_fp16(original_precision_value)",
"def test_superop_conjugate_random(self):\n mats = [self.rand_matrix(4, 4) for _ in range(4)]\n chans = [SuperOp(Operator(mat)) for mat in mats]\n self._compare_conjugate_to_operator(chans, mats)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test that `args_to_gan_model` produces correctly named functions.
|
def testargs_to_gan_model_name(self):
def loss_fn(x):
return x
new_loss_fn = args_to_gan_model(loss_fn)
self.assertEqual('loss_fn', new_loss_fn.__name__)
self.assertTrue('The gan_model version of' in new_loss_fn.__docstring__)
|
[
"def _args_to_gan_model(loss_fn):\n # Match arguments in `loss_fn` to elements of `namedtuple`.\n # TODO(joelshor): Properly handle `varargs` and `keywords`.\n argspec = tf_inspect.getargspec(loss_fn)\n defaults = argspec.defaults or []\n\n required_args = set(argspec.args[:-len(defaults)])\n args_with_defaults = argspec.args[-len(defaults):]\n default_args_dict = dict(zip(args_with_defaults, defaults))\n\n def new_loss_fn(gan_model, **kwargs): # pylint:disable=missing-docstring\n def _asdict(namedtuple):\n \"\"\"Returns a namedtuple as a dictionary.\n\n This is required because `_asdict()` in Python 3.x.x is broken in classes\n that inherit from `collections.namedtuple`. See\n https://bugs.python.org/issue24931 for more details.\n\n Args:\n namedtuple: An object that inherits from `collections.namedtuple`.\n\n Returns:\n A dictionary version of the tuple.\n \"\"\"\n return {k: getattr(namedtuple, k) for k in namedtuple._fields}\n gan_model_dict = _asdict(gan_model)\n\n # Make sure non-tuple required args are supplied.\n args_from_tuple = set(argspec.args).intersection(set(gan_model._fields))\n required_args_not_from_tuple = required_args - args_from_tuple\n for arg in required_args_not_from_tuple:\n if arg not in kwargs:\n raise ValueError('`%s` must be supplied to %s loss function.' % (\n arg, loss_fn.__name__))\n\n # Make sure tuple args aren't also supplied as keyword args.\n ambiguous_args = set(gan_model._fields).intersection(set(kwargs.keys()))\n if ambiguous_args:\n raise ValueError(\n 'The following args are present in both the tuple and keyword args '\n 'for %s: %s' % (loss_fn.__name__, ambiguous_args))\n\n # Add required args to arg dictionary.\n required_args_from_tuple = required_args.intersection(args_from_tuple)\n for arg in required_args_from_tuple:\n assert arg not in kwargs\n kwargs[arg] = gan_model_dict[arg]\n\n # Add arguments that have defaults.\n for arg in default_args_dict:\n val_from_tuple = gan_model_dict[arg] if arg in gan_model_dict else None\n val_from_kwargs = kwargs[arg] if arg in kwargs else None\n assert not (val_from_tuple is not None and val_from_kwargs is not None)\n kwargs[arg] = (val_from_tuple if val_from_tuple is not None else\n val_from_kwargs if val_from_kwargs is not None else\n default_args_dict[arg])\n\n return loss_fn(**kwargs)\n\n new_docstring = \"\"\"The gan_model version of %s.\"\"\" % loss_fn.__name__\n new_loss_fn.__docstring__ = new_docstring\n new_loss_fn.__name__ = loss_fn.__name__\n new_loss_fn.__module__ = loss_fn.__module__\n return new_loss_fn",
"def infogan_model(\n # Lambdas defining models.\n generator_fn,\n discriminator_fn,\n # Real data and conditioning.\n real_data,\n unstructured_generator_inputs,\n structured_generator_inputs,\n # Optional scopes.\n generator_scope='Generator',\n discriminator_scope='Discriminator'):\n # Create models\n with variable_scope.variable_scope(generator_scope) as gen_scope:\n unstructured_generator_inputs = _convert_tensor_or_l_or_d(\n unstructured_generator_inputs)\n structured_generator_inputs = _convert_tensor_or_l_or_d(\n structured_generator_inputs)\n generator_inputs = (\n unstructured_generator_inputs + structured_generator_inputs)\n generated_data = generator_fn(generator_inputs)\n with variable_scope.variable_scope(discriminator_scope) as disc_scope:\n dis_gen_outputs, predicted_distributions = discriminator_fn(\n generated_data, generator_inputs)\n #_validate_distributions(predicted_distributions, structured_generator_inputs)\n with variable_scope.variable_scope(disc_scope, reuse=True):\n real_data = ops.convert_to_tensor(real_data)\n dis_real_outputs, _ = discriminator_fn(real_data, generator_inputs)\n\n if not generated_data.get_shape().is_compatible_with(real_data.get_shape()):\n raise ValueError(\n 'Generator output shape (%s) must be the same shape as real data '\n '(%s).' % (generated_data.get_shape(), real_data.get_shape()))\n\n # Get model-specific variables.\n generator_variables = variables_lib.get_trainable_variables(gen_scope)\n discriminator_variables = variables_lib.get_trainable_variables(\n disc_scope)\n\n return namedtuples.InfoGANModel(\n generator_inputs,\n generated_data,\n generator_variables,\n gen_scope,\n generator_fn,\n real_data,\n dis_real_outputs,\n dis_gen_outputs,\n discriminator_variables,\n disc_scope,\n lambda x, y: discriminator_fn(x, y)[0], # conform to non-InfoGAN API\n structured_generator_inputs,\n predicted_distributions)",
"def simple_arg(model):",
"def test_ProjE_args():\n testing_function_with_args('proje_pointwise')",
"def test_TransM_args():\n testing_function_with_args('transm')",
"def test_shape_predictor(*args, **kwargs): # real signature unknown; restored from __doc__\n pass",
"def test_Tucker_args():\n testing_function_with_args('tucker')",
"def test_TransD_args():\n testing_function_with_args('transd')",
"def test_transE_args():\n testing_function_with_args('transe')",
"def test_transR_args():\n testing_function_with_args('transr')",
"def test_transH_args():\n testing_function_with_args('transh')",
"def test_gaussian_args(self):\n self.logTestName()\n\n with self.assertRaisesRegex(TypeError, \"missing 1 required positional argument: 'wires'\"):\n dev = qml.device('strawberryfields.gaussian')",
"def adapt_args(is_gat, args):\n new = {}\n for field, value in args.__dict__.items():\n last = field.split('_')[-1].lower()\n rest = '_'.join(field.split('_')[:-1])\n to_use = 'gat' if is_gat else 'conv'\n if last not in ['gat', 'conv']:\n new[field] = value\n elif last == to_use:\n new[rest] = value\n else:\n pass\n new.pop('epochs') # artifact doesn't use this\n return Namespace(**new)",
"def test_special_names():",
"def test_KG2E_EL_args():\n testing_function_with_args('kg2e', distance_measure=\"expected_likelihood\")",
"def test_regression_function(*args, **kwargs): # real signature unknown; restored from __doc__\n pass",
"def test_numpy_input_fn(self):\n label_dimension = 2\n batch_size = 10\n train_input_fn, eval_input_fn, predict_input_fn = self._create_input_fn(\n label_dimension, batch_size)\n\n self._test_complete_flow(\n train_input_fn=train_input_fn,\n eval_input_fn=eval_input_fn,\n predict_input_fn=predict_input_fn,\n input_dimension=label_dimension,\n label_dimension=label_dimension,\n batch_size=batch_size)",
"def test_gen():\n # Define a click runner to invoke click commands\n\n logger.info(\"Calling 'gen' with a specific amount of scores.\")\n gen_case(\n n_subjects=5,\n n_probes_per_subject=5,\n n_unknown_subjects=2,\n n_pos=10,\n n_neg=60,\n n_unk=20,\n )\n\n logger.info(\"Calling 'gen' without a specific amount.\")\n gen_case(\n n_subjects=5,\n n_probes_per_subject=5,\n n_unknown_subjects=2,\n )\n\n logger.info(\"Calling 'gen' without unknown subjects.\")\n gen_case(\n n_subjects=5,\n n_probes_per_subject=2,\n n_unknown_subjects=0,\n )\n\n logger.info(\"Calling 'gen' with no subjects.\")\n gen_case(\n n_subjects=0,\n n_probes_per_subject=2,\n n_unknown_subjects=0,\n )\n\n logger.info(\"Calling 'gen' with no probes.\")\n gen_case(\n n_subjects=5,\n n_probes_per_subject=0,\n n_unknown_subjects=2,\n )\n\n logger.info(\"Calling 'gen' with only unknowns.\")\n gen_case(\n n_subjects=5,\n n_probes_per_subject=0,\n n_unknown_subjects=2,\n )",
"def test_DistMult_args():\n testing_function_with_args('distmult')"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test that optional args can be changed with tuple losses.
|
def test_tuple_respects_optional_args(self):
tuple_type = collections.namedtuple('fake_type', ['arg1', 'arg2'])
def args_loss(arg1, arg2, arg3=3):
return arg1 + 2 * arg2 + 3 * arg3
loss_fn = args_to_gan_model(args_loss)
loss = loss_fn(tuple_type(arg1=-1, arg2=2), arg3=4)
# If `arg3` were not set properly, this value would be different.
self.assertEqual(-1 + 2 * 2 + 3 * 4, loss)
|
[
"def test_HoLE_args():\n testing_function_with_args('hole')",
"def test_ignorearg(self):\n self.assertEqual(check_args(self.ignorearg), {})",
"def test_check_args_correct_args(self):\n\n retval = check_args([1, 2, 3, 4, 5, 6])\n self.assertEqual(0, retval)",
"def test_error_ignored_args(coordinates_small, data_small, region):\n # Define sample equivalent sources and fit against synthetic data\n eqs = EquivalentSourcesGB(window_size=500).fit(coordinates_small, data_small)\n # Build a target grid\n grid_coords = vd.grid_coordinates(region=region, shape=(4, 4), extra_coords=2e3)\n # Try to grid passing kwarg arguments that will be ignored\n msg = \"The 'bla' arguments are being ignored.\"\n with pytest.warns(FutureWarning, match=msg):\n eqs.grid(coordinates=grid_coords, bla=\"bla\")",
"def test_SLM_args():\n testing_function_with_args('slm')",
"def test_passed_tooManyArgs(self):\n\n def func(a, b):\n pass\n\n self.assertRaises(TypeError, self.checkPassed, func, 1, 2, 3)",
"def test_Complex_args():\n testing_function_with_args('complex')",
"def _check_positional_only_arguments_expected(self, node: nodes.Call) -> None:\n inferred_func = utils.safe_infer(node.func)\n while isinstance(inferred_func, (astroid.BoundMethod, astroid.UnboundMethod)):\n inferred_func = inferred_func._proxied\n if not (\n isinstance(inferred_func, (nodes.FunctionDef))\n and inferred_func.args.posonlyargs\n ):\n return\n if inferred_func.args.kwarg:\n return\n pos_args = [a.name for a in inferred_func.args.posonlyargs]\n kws = [k.arg for k in node.keywords if k.arg in pos_args]\n if not kws:\n return\n\n self.add_message(\n \"positional-only-arguments-expected\",\n node=node,\n args=(node.func.as_string(), \", \".join(f\"'{k}'\" for k in kws)),\n confidence=INFERENCE,\n )",
"def should_execute_combination(self, kwargs):\n del kwargs\n return (True, None)",
"def test_update_args_kwargs(self):\n s1 = Square(10, 10, 10, 1)\n self.assertEqual(s1.__str__(), \"[Square] (1) 10/10 - 10\")\n s1.update(10, id=7, size=3)\n self.assertEqual(s1.__str__(), \"[Square] (10) 10/10 - 10\")",
"def test_tuple_for_class_arg_causes_unshared_dependencies_when_downstream():\n three_wa = ThreeWithArgs().create(\n two_with_args=(TwoWithArgs, dict(one_with_args=False, make_one_with_args=True, two_with_args_kw_arg=234)), three_with_args_kw_arg=345\n )\n assert isinstance(three_wa.ds.one_with_args, OneWithArgs)\n assert isinstance(three_wa.ds.two_with_args, TwoWithArgs)\n assert isinstance(three_wa.ds.two_with_args.ds.one_with_args, OneWithArgs)\n assert three_wa.ds.one_with_args != three_wa.ds.two_with_args.ds.one_with_args\n assert three_wa.ds.one_with_args.kw == dict()\n assert three_wa.ds.two_with_args.kw == dict(two_with_args_kw_arg=234)\n assert three_wa.ds.two_with_args.ds.one_with_args.kw == dict(a='a', b='b', c='c')\n assert three_wa.kw == dict(three_with_args_kw_arg=345)",
"def no_mutable_default_args(logical_line):\n msg = \"S360: Method's default argument shouldn't be mutable!\"\n if RE_MUTABLE_DEFAULT_ARGS.match(logical_line):\n yield (0, msg)",
"def test_ProjE_args():\n testing_function_with_args('proje_pointwise')",
"def test_tuples_for_class_arg_cause_unshared_dependencies_when_downstream():\n four_wa = FourWithArgs().create(\n two_with_args=(TwoWithArgs, dict(one_with_args=False, make_one_with_args=True, two_with_args_kw_arg=456)),\n # No shared dependencies with four_wa.ds.two_with_args\n three_with_args=(ThreeWithArgs, dict(one_with_args=(OneWithArgs, {}), two_with_args=False)),\n four_with_args_kw=567,\n )\n assert isinstance(four_wa.ds.two_with_args, TwoWithArgs)\n assert isinstance(four_wa.ds.three_with_args, ThreeWithArgs)\n assert isinstance(four_wa.ds.two_with_args.ds.one_with_args, OneWithArgs)\n assert isinstance(four_wa.ds.three_with_args.ds.one_with_args, OneWithArgs)\n assert four_wa.ds.three_with_args.ds.one_with_args != four_wa.ds.two_with_args.ds.one_with_args\n with pytest.raises(AttributeError):\n four_wa.ds.three_with_args.ds.two_with_args\n assert four_wa.kw == dict(four_with_args_kw=567)",
"def test_RESCAL_args():\n testing_function_with_args('rescal')",
"def test_predefine_params():\n @ParameterValidator((int, False, (3,5)), (str, False), (list, True))\n def myfunc(num, str, list):\n print(\"Hello from standalone function\")\n\n\n # Splatting - OK\n single_args = [3, \"hey\", None]\n print(\"Standalone Args Splatting - success\")\n myfunc(*single_args)\n\n\n # Standard call but make first parameter None where it's not allowed\n try:\n print(\"Standalone Args Standard - failure on invalid type for parameter\")\n myfunc(\"1\", \"hey\", None)\n except ParameterValidationException as ex:\n assert(isinstance(ex, ParameterTypeValidationException))\n print(\"\\t\",str(ex))\n\n # Standard call but make first parameter None where it's out of range\n try:\n print(\"Standalone Args Standard - failure on range of parameter\")\n myfunc(1, \"hey\", None)\n except ParameterValidationException as ex:\n assert(isinstance(ex, ParameterRangeValidationException))\n print(\"\\t\",str(ex))\n\n try:\n print(\"Standalone Args Standard - failure on range of parameter\")\n myfunc(None, \"hey\", None)\n except ParameterValidationException as ex:\n assert(isinstance(ex, ParameterNoneValidationException))\n print(\"\\t\",str(ex))",
"def test_wrong_args_unobserve(observed_atom):\n a, _, _ = observed_atom\n\n # Too many args\n with pytest.raises(TypeError) as excinfo:\n a.unobserve(\"val\", lambda change: change, 1)\n assert \"2 arguments\" in excinfo.exconly()\n\n # Non-iterable first arg\n with pytest.raises(TypeError) as excinfo:\n a.unobserve(1)\n assert \"iterable\" in excinfo.exconly()\n\n # Non-iterable first arg with callable\n with pytest.raises(TypeError) as excinfo:\n a.unobserve(1, lambda change: change)\n assert \"iterable\" in excinfo.exconly()\n\n # Non iterable fo string first arg\n with pytest.raises(TypeError) as excinfo:\n a.unobserve((1, 1))\n assert \"str\" in excinfo.exconly()\n\n # Non iterable fo string first arg with callable\n with pytest.raises(TypeError) as excinfo:\n a.unobserve((1, 1), lambda change: change)\n assert \"str\" in excinfo.exconly()\n\n # Non callable second arg\n with pytest.raises(TypeError) as excinfo:\n a.unobserve(\"vsl\", 1)\n assert \"callable\" in excinfo.exconly()",
"def test_RotatE_args():\n testing_function_with_args('rotate')",
"def test_wrong_args_observe():\n dt1 = DynamicAtom()\n\n with pytest.raises(TypeError) as excinfo:\n dt1.observe(\"val\")\n assert \"2 or 3 arguments\" in excinfo.exconly()\n\n with pytest.raises(TypeError) as excinfo:\n dt1.observe(\"val\", lambda change: change, ChangeType.ANY, \"bar\")\n assert \"2 or 3 arguments\" in excinfo.exconly()\n\n with pytest.raises(TypeError) as excinfo:\n dt1.observe(1, lambda change: change)\n assert \"iterable\" in excinfo.exconly()\n\n with pytest.raises(TypeError) as excinfo:\n dt1.observe((1, 1), lambda change: change)\n assert \"str\" in excinfo.exconly()\n\n with pytest.raises(TypeError) as excinfo:\n dt1.observe(\"val\", 1)\n assert \"callable\" in excinfo.exconly()\n\n with pytest.raises(TypeError) as excinfo:\n dt1.observe(\"val\", lambda change: change, \"foo\")\n assert \"int\" in excinfo.exconly()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test the input model type for `cycle_consistency_loss`.
|
def test_model_type(self):
with self.assertRaises(ValueError):
tfgan.losses.cycle_consistency_loss(self._model_x2y)
|
[
"def test_correct_loss(self):\n loss = tfgan.losses.cycle_consistency_loss(\n tfgan.CycleGANModel(\n model_x2y=self._model_x2y,\n model_y2x=self._model_y2x,\n reconstructed_x=tf.constant([9, 8], dtype=tf.float32),\n reconstructed_y=tf.constant([7, 2], dtype=tf.float32)))\n with self.cached_session(use_gpu=True) as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n self.assertNear(5.0, sess.run(loss), 1e-5)",
"def validate_model_type(model_type):\n model_type = model_type.lower()\n valid_types = ['dense', 'rnn', 'covrnn']\n\n if model_type not in valid_types:\n raise NotImplementedError('model type {0} is not yet a valid model type.'.format(model_type))\n\n return model_type",
"def test_model(artifacts, expected_type):\n returned_type = artifacts_type.model(artifacts=artifacts)\n\n assert returned_type == expected_type",
"def validate_for_tf_model(\n input_dtype, output0_dtype, output1_dtype, input_shape, output0_shape, output1_shape\n):\n\n # Not extending test to uint8 yet\n if (\n input_dtype == np.uint8\n or output0_dtype == np.uint8\n or output1_dtype == np.uint8\n ):\n return False\n\n # If the input type is string the output type must be string or\n # int32. This is because the QA models we generate convert strings\n # internally to int32 for compute.\n if (input_dtype == np.object_) and (\n ((output0_dtype != np.object_) and (output0_dtype != np.int32))\n or ((output1_dtype != np.object_) and (output1_dtype != np.int32))\n ):\n return False\n\n return True",
"def _check_for_loss_mismatch(self, loss):\n # Only handle a single loss.\n if isinstance(loss, (dict, list, tuple)):\n return\n # Only handle tasks with activation.\n if not hasattr(self, \"activation\"):\n return\n\n loss = keras.losses.get(loss)\n activation = keras.activations.get(self.activation)\n if isinstance(loss, keras.losses.SparseCategoricalCrossentropy):\n from_logits = loss.get_config()[\"from_logits\"]\n elif loss == keras.losses.sparse_categorical_crossentropy:\n from_logits = False\n else:\n # Only handle sparse categorical crossentropy.\n return\n\n softmax_output = activation == keras.activations.softmax\n logit_output = activation == keras.activations.linear\n if softmax_output and from_logits:\n raise ValueError(\n \"The `loss` passed to `compile()` expects logit output, but \"\n \"the model is configured to output softmax probabilities \"\n \"(`activation='softmax'`). This will not converge! Pass \"\n \"`from_logits=False` to your loss, e.g. \"\n \"`loss=keras.losses.SparseCategoricalCrossentropy(from_logits=False)`. \"\n )\n if logit_output and not from_logits:\n raise ValueError(\n \"The `loss` passed to `compile()` expects softmax probability \"\n \"output, but the model is configured to output logits \"\n \"(`activation=None`). This will not converge! Pass \"\n \"`from_logits=True` to your loss, e.g. \"\n \"`loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True)`. \"\n )",
"def validate_for_ensemble_model(\n ensemble_type,\n input_dtype,\n output0_dtype,\n output1_dtype,\n input_shape,\n output0_shape,\n output1_shape,\n):\n\n # Not extending test to uint8 yet\n if (\n input_dtype == np.uint8\n or output0_dtype == np.uint8\n or output1_dtype == np.uint8\n ):\n return False\n\n # Those ensemble types contains \"identity\" model which doesn't allow STRING\n # data type\n # Test types that use identity for both input and output\n test_type_involved = [\"reshape\", \"zero\", \"fan\"]\n if (\n input_dtype == np.object_\n or output0_dtype == np.object_\n or output1_dtype == np.object_\n ):\n for type_str in test_type_involved:\n if type_str in ensemble_type:\n return False\n\n # Otherwise, check input / output separately\n if input_dtype == np.object_ and \"sequence\" in ensemble_type:\n return False\n\n return True",
"def consistent_motion_types(self):#, cycles=[]):\n# if cycles==[]:\n cycles = self.four_cycles_ordered()\n\n k23s = [Graph(self._graph).subgraph(k23_ver).edges(labels=False) for k23_ver in self._graph.induced_K23s()]\n\n aa_pp = [('a', 'a'), ('p', 'p')]\n ao = [('a','o'), ('o','a')]\n ae = [('a','e'), ('e','a')]\n oe = [('o', 'e'), ('e', 'o')]\n oo_ee = [('e','e'), ('o','o')]\n\n H = {self._edge_ordered(u,v):None for u,v in self._graph.edges(labels=False)}\n types_prev=[[{}, []]]\n \n self._num_tested_combinations = 0\n\n for i, new_cycle in enumerate(cycles):\n types_ext = []\n new_cycle_neighbors = [[c2,\n new_cycle.index(self._four_cycle_graph.edge_label(new_cycle, c2)),\n c2.index(self._four_cycle_graph.edge_label(new_cycle, c2)),\n ] for c2 in self._four_cycle_graph.neighbors(new_cycle) if c2 in cycles[:i]]\n for types_original, ramification_eqs_prev in types_prev:\n for type_new_cycle in ['g','a','p','o','e']:\n self._num_tested_combinations +=1\n types = deepcopy(types_original)\n types[tuple(new_cycle)] = type_new_cycle\n # H = deepcopy(orig_graph)\n inconsistent = False\n\n for c2, new_index, c2_index in new_cycle_neighbors:\n type_pair = (types[new_cycle], types[c2])\n if (type_pair in aa_pp\n or (type_pair in oe and new_index%2 == c2_index%2)\n or (type_pair in oo_ee and new_index%2 != c2_index%2)):\n inconsistent = True\n break\n if type_pair in ao:\n ind_o = type_pair.index('o')\n if [new_index, c2_index][ind_o] % 2 == 1:\n # odd deltoid (1,2,3,4) is consistent with 'a' if the common vertex is odd,\n # but Python lists are indexed from 0\n inconsistent = True\n break\n if type_pair in ae:\n ind_e = type_pair.index('e')\n if [new_index, c2_index][ind_e] % 2 == 0:\n inconsistent = True\n break\n if inconsistent:\n continue\n\n self._set_same_lengths(H, types)\n for c in types:\n if types[c]=='g':\n labels = [H[self._edge_ordered(c[i-1],c[i])] for i in range(0,4)]\n if (not None in labels\n and ((len(Set(labels))==2 and labels.count(labels[0])==2)\n or len(Set(labels))==1)):\n inconsistent = True\n break\n if inconsistent:\n continue\n for K23_edges in k23s:\n if MotionClassifier._same_edge_lengths(H, K23_edges):\n inconsistent = True\n break\n if inconsistent:\n continue\n\n ramification_eqs = ramification_eqs_prev + self.ramification_formula(new_cycle, type_new_cycle)\n zero_variables, ramification_eqs = self.consequences_of_nonnegative_solution_assumption(ramification_eqs)\n for cycle in types:\n if inconsistent:\n break\n for t in self.motion_types2NAC_types(types[cycle]):\n has_necessary_NAC_type = False\n for delta in self._restriction_NAC_types[cycle][t]:\n if not self.mu(delta) in zero_variables:\n has_necessary_NAC_type = True\n break\n if not has_necessary_NAC_type:\n inconsistent = True\n break\n if inconsistent:\n continue\n\n types_ext.append([types, ramification_eqs])\n\n types_prev=types_ext\n\n return [t for t, _ in types_prev]",
"def test_is_in_cycle_ethane(self):\n molecule = Molecule().from_smiles('CC')\n for atom in molecule.atoms:\n self.assertFalse(molecule.is_atom_in_cycle(atom))\n for atom1 in molecule.atoms:\n for atom2, bond in atom1.bonds.items():\n self.assertFalse(molecule.is_bond_in_cycle(bond))",
"def check_model(self):\n layers_map = self.infer_engine_.query_network(self.network_, \"CPU\")\n\n logger.debug('* layers info *')\n layer_num = 0\n unsupport_layers = []\n\n for layer, hw in layers_map.items():\n if not hw in ['CPU']:\n logger.debug(' [U] #%d: %s [%s]' % (layer_num, layer, hw))\n unsupport_layers.append(layer)\n else:\n logger.debug(' [S] #%d: %s [%s]' % (layer_num, layer, hw))\n pass\n layer_num += 1\n\n logger.info(f'[ {self.model_name} ]')\n\n if len(unsupport_layers) == 0:\n logger.info(' All the layers are supported')\n else:\n assert False, f' There is unsupported layer(s): {unsupport_layers}'",
"def CheckModelAndSerialCompatibility(model, serial):\n incompatible = False\n if (model == 'oktoberkite' and system_types.WingSerialToModel(serial) !=\n system_types.kWingModelOktoberKite):\n incompatible = True\n elif (model == 'm600' and system_types.WingSerialToModel(serial) !=\n system_types.kWingModelYm600):\n incompatible = True\n assert not incompatible, (\n 'Model %s and serial number %i are not compatible.' % (model, serial))",
"def test_model_type_exception(self):\n\n with pytest.raises(\n TypeError,\n match=re.escape(\n f\"model is not in expected types {[lgb.Booster]}, got {list}\"\n ),\n ):\n\n LGBMBoosterAbsoluteErrorConformalPredictor([1, 2, 3])",
"def testConvergence(self):\n synthetic_test = Synthetic()\n # Silence output of fit\n save_stdout = sys.stdout\n sys.stdout = open( os.devnull, 'w' )\n synthetic_test.fit(0.001, n_iters = 10**3)\n sys.stdout.close()\n sys.stdout = save_stdout\n # Discard burn in\n loss_storage = np.array( synthetic_test.lr.training_loss[1:] )\n loss_var = np.var( loss_storage )\n self.assertTrue( loss_var < 1 / float( synthetic_test.lr.N ) )",
"def test_dependencies_sink_input_can_only_be_driven_once(\n self,\n get_sos_model,\n get_sector_model,\n energy_supply_sector_model,\n sample_scenarios,\n ):\n get_sos_model[\"model_dependencies\"] = [\n {\n \"source\": \"energy_demand\",\n \"source_output\": \"output_a\",\n \"sink\": \"energy_supply\",\n \"sink_input\": \"input_a\",\n },\n {\n \"source\": \"energy_demand\",\n \"source_output\": \"output_b\",\n \"sink\": \"energy_supply\",\n \"sink_input\": \"input_a\",\n },\n ]\n get_sector_model[\"outputs\"] = [\n {\n \"name\": \"output_a\",\n \"dims\": [\"dim_a\"],\n \"dtype\": \"dtype_a\",\n \"unit\": \"unit_a\",\n },\n {\n \"name\": \"output_b\",\n \"dims\": [\"dim_a\"],\n \"dtype\": \"dtype_a\",\n \"unit\": \"unit_a\",\n },\n ]\n energy_supply_sector_model[\"inputs\"] = [\n {\"name\": \"input_a\", \"dims\": [\"dim_a\"], \"dtype\": \"dtype_a\", \"unit\": \"unit_a\"}\n ]\n\n try:\n validate_sos_model_config(\n get_sos_model,\n [get_sector_model, energy_supply_sector_model],\n sample_scenarios,\n )\n except SmifDataError as ex:\n assert len(ex.args[0]) == 2\n assert ex.args[0][0].component == \"model_dependencies\"\n assert (\n \"Sink input `input_a` is driven by multiple sources\"\n in ex.args[0][0].error\n )\n assert ex.args[0][1].component == \"model_dependencies\"\n assert (\n \"Sink input `input_a` is driven by multiple sources\"\n in ex.args[0][0].error\n )",
"def test_incorrect_termination_model():\n\n # setup arguments for the model-based agent constructor\n py_env = suite_gym.load(\"MountainCarContinuous-v0\")\n tf_env = TFPyEnvironment(py_env)\n time_step_spec = tf_env.time_step_spec()\n observation_spec = tf_env.observation_spec()\n action_spec = tf_env.action_spec()\n network = LinearTransitionNetwork(observation_spec)\n transition_model = KerasTransitionModel([network], observation_spec, action_spec)\n reward_model = MountainCarReward(observation_spec, action_spec)\n initial_state_distribution_model = MountainCarInitialState(observation_spec)\n termination_model = MountainCarTermination(observation_spec)\n policy = RandomTFPolicy(time_step_spec, action_spec)\n\n with pytest.raises(AssertionError) as excinfo:\n ModelBasedAgent(\n time_step_spec,\n action_spec,\n transition_model,\n reward_model,\n termination_model,\n initial_state_distribution_model,\n policy,\n policy,\n )\n\n assert \"Only constant false termination supported\" in str(excinfo.value)",
"def _is_correct_type(m):\n if (\n isinstance(m, nn.Linear)\n or isinstance(m, nn.Conv1d)\n or isinstance(m, nn.Conv2d)\n or isinstance(m, nn.Conv3d)\n ):\n return True\n else:\n return False",
"def _validate_model(self, model):\n if model.module_class not in (ModuleClass.primitive, ModuleClass.cluster):\n raise PRGAInternalError(\"Only primitives or clusters may be instantiated in a custer/block.\")",
"def test_fermionaction_type_consistency(self):\n propagator = OneToAllHisqParser.create_instance()\n wave = MesonParser.create_instance()\n\n parameters = dict(self.get_parameters())\n parameters[\"propagator\"] = propagator\n parameters[\"wave\"] = wave\n\n with self.assertRaises(ConsistencyError) as context:\n self.model.objects.create(**parameters)\n print(context.exception.error)",
"def validate_for_trt_model(\n input_dtype, output0_dtype, output1_dtype, input_shape, output0_shape, output1_shape\n):\n supported_datatypes = [bool, np.int8, np.int32, np.uint8, np.float16, np.float32]\n # FIXME: Remove this check when jetson supports TRT 8.5 (DLIS-4256)\n if not support_trt_uint8():\n supported_datatypes.remove(np.uint8)\n if not input_dtype in supported_datatypes:\n return False\n if not output0_dtype in supported_datatypes:\n return False\n if not output1_dtype in supported_datatypes:\n return False\n\n datatype_set = set([input_dtype, output0_dtype, output1_dtype])\n\n # Incompatible datatype conversions\n if (np.int32 in datatype_set) and (np.int8 in datatype_set):\n return False\n if (np.float32 in datatype_set) and (np.int32 in datatype_set):\n return False\n\n return True",
"def __check_hidden_type(self):\n if self.hidden_layer_type not in ['fc', 'conv']:\n raise Exception(\n 'hidden type neither fc nor conv')"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test the output of `cycle_consistency_loss`.
|
def test_correct_loss(self):
loss = tfgan.losses.cycle_consistency_loss(
tfgan.CycleGANModel(
model_x2y=self._model_x2y,
model_y2x=self._model_y2x,
reconstructed_x=tf.constant([9, 8], dtype=tf.float32),
reconstructed_y=tf.constant([7, 2], dtype=tf.float32)))
with self.cached_session(use_gpu=True) as sess:
sess.run(tf.compat.v1.global_variables_initializer())
self.assertNear(5.0, sess.run(loss), 1e-5)
|
[
"def test_model_type(self):\n with self.assertRaises(ValueError):\n tfgan.losses.cycle_consistency_loss(self._model_x2y)",
"def testConvergence(self):\n synthetic_test = Synthetic()\n # Silence output of fit\n save_stdout = sys.stdout\n sys.stdout = open( os.devnull, 'w' )\n synthetic_test.fit(0.001, n_iters = 10**3)\n sys.stdout.close()\n sys.stdout = save_stdout\n # Discard burn in\n loss_storage = np.array( synthetic_test.lr.training_loss[1:] )\n loss_var = np.var( loss_storage )\n self.assertTrue( loss_var < 1 / float( synthetic_test.lr.N ) )",
"def check_consistency(self) -> None:\n pass",
"def _test_resilience(command, ops=[], initial=None, sources=1,\n partition_multiplier=5, cycles=1, validate_output=True,\n sender_mps=1000, sender_interval=0.01,\n retry_count=5,\n api=None):\n t0 = datetime.datetime.now()\n log_stream = add_in_memory_log_stream(level=logging.DEBUG)\n persistent_data = {}\n res_ops = []\n try:\n try:\n _run(\n persistent_data=persistent_data,\n res_ops=res_ops,\n command=command,\n ops=ops*cycles,\n initial=initial,\n sources=sources,\n partition_multiplier=partition_multiplier,\n validate_output=validate_output,\n sender_mps=sender_mps,\n sender_interval=sender_interval)\n except:\n logging.error(\"Resilience test encountered an error after the steps\"\n \" {}\".format([o.name() for o in res_ops]))\n # Do this ugly thing to use proper exception handling here\n try:\n raise\n except RunnerHasntStartedError as err:\n logging.warn(\"Runner failed to start properly.\")\n if retry_count > 0:\n logging.info(\"Restarting the test!\")\n _test_resilience(\n command=command,\n ops=ops,\n initial=initial,\n sources=sources,\n partition_multiplier=partition_multiplier,\n cycles=cycles,\n validate_output=validate_output,\n sender_mps=sender_mps,\n sender_interval=sender_interval,\n retry_count=retry_count-1)\n else:\n logging.error(\"Max retry attempts reached.\")\n raise\n except SinkAwaitTimeoutError:\n logging.error(\"SinkAWaitTimeoutError encountered.\")\n raise\n except TimeoutError:\n logging.error(\"TimeoutError encountered.\")\n raise\n except:\n if persistent_data.get('runner_data'):\n logging.error(\"Some workers exited badly. The last {} lines of \"\n \"each were:\\n\\n{}\"\n .format(FROM_TAIL,\n runner_data_format(\n persistent_data.get('runner_data'),\n from_tail=FROM_TAIL)))\n raise\n except Exception as err:\n # save log stream to file\n try:\n cwd = os.getcwd()\n trunc_head = cwd.find('/wallaroo/') + len('/wallaroo/')\n base_dir = ('/tmp/wallaroo_test_errors/{head}/{api}/{ops}/{time}'\n .format(\n head=cwd[trunc_head:],\n api=api,\n time=t0.strftime('%Y%m%d_%H%M%S'),\n ops='_'.join((o.name().replace(':','')\n for o in ops*cycles))))\n save_logs_to_file(base_dir, log_stream, persistent_data)\n except Exception as err_inner:\n logging.exception(err_inner)\n logging.warn(\"Encountered an error when saving logs files to {}\"\n .format(base_dir))\n logging.exception(err)\n raise",
"def test_loss_and_train_output(\n test: test_utils.TestCase,\n expect_equal_loss_values: bool,\n agent: tf_agent.TFAgent,\n experience: types.NestedTensor,\n weights: Optional[types.Tensor] = None,\n **kwargs\n):\n loss_info_from_loss = agent.loss(\n experience=experience, weights=weights, **kwargs\n )\n loss_info_from_train = agent.train(\n experience=experience, weights=weights, **kwargs\n )\n if not tf.executing_eagerly():\n test.evaluate(tf.compat.v1.global_variables_initializer())\n loss_info_from_loss = test.evaluate(loss_info_from_loss)\n loss_info_from_train = test.evaluate(loss_info_from_train)\n\n test.assertIsInstance(loss_info_from_train, tf_agent.LossInfo)\n test.assertEqual(type(loss_info_from_train), type(loss_info_from_loss))\n\n # Compare loss values.\n if expect_equal_loss_values:\n test.assertEqual(\n loss_info_from_train.loss,\n loss_info_from_loss.loss,\n msg=(\n 'Expected equal loss values, but train() has output '\n '{loss_from_train} vs loss() output {loss_from_loss}.'.format(\n loss_from_train=loss_info_from_train.loss,\n loss_from_loss=loss_info_from_loss.loss,\n )\n ),\n )\n else:\n test.assertNotEqual(\n loss_info_from_train.loss,\n loss_info_from_loss.loss,\n msg=(\n 'Expected train() and loss() output to have different loss values, '\n 'but both are {loss}.'.format(loss=loss_info_from_train.loss)\n ),\n )\n\n # Check that both `LossInfo` outputs have matching dtypes and shapes.\n nest_utils.assert_tensors_matching_dtypes_and_shapes(\n loss_info_from_train,\n loss_info_from_loss,\n test,\n '`LossInfo` from train()',\n '`LossInfo` from loss()',\n )",
"def test_is_in_cycle_ethane(self):\n molecule = Molecule().from_smiles('CC')\n for atom in molecule.atoms:\n self.assertFalse(molecule.is_atom_in_cycle(atom))\n for atom1 in molecule.atoms:\n for atom2, bond in atom1.bonds.items():\n self.assertFalse(molecule.is_bond_in_cycle(bond))",
"def test_connectivity_error(self):\n\n data_batch, bad_pred1, bad_pred2, good_pred = (\n self.data_batch,\n self.bad_preds1,\n self.bad_preds2,\n self.good_preds,\n )\n\n conn_err = ConnectivityError()\n\n with pytest.raises(ValueError):\n conn_err.process(data_batch, bad_pred1)\n\n with pytest.raises(ValueError):\n conn_err.process(data_batch, bad_pred2)\n\n # process 2 batches\n conn_err.process(data_batch, good_pred)\n conn_err.process(data_batch, good_pred)\n\n assert conn_err.results == [\n {\n 'conn_err': 0.256,\n },\n {\n 'conn_err': 0.256,\n },\n ]\n\n res = conn_err.compute_metrics(conn_err.results)\n\n assert list(res.keys()) == ['ConnectivityError']\n assert np.allclose(res['ConnectivityError'], 0.256)",
"def check_nocycles(Adj: np.ndarray, verbosity: int = 2) -> bool:\n dim = Adj.shape[0]\n for g in range(dim):\n v = np.zeros(dim)\n v[g] = 1\n for i in range(dim):\n v = Adj.dot(v)\n if v[g] > 1e-10:\n if verbosity > 2:\n settings.m(0, Adj)\n settings.m(\n 0,\n 'contains a cycle of length',\n i + 1,\n 'starting from node',\n g,\n '-> reject',\n )\n return False\n return True",
"def check_training_outputs_are_reasonable(testcase, training_outputs,\n print_training_accuracy,\n max_final_loss=10.,\n previous_final_loss=None):\n if previous_final_loss is not None:\n # Ensure the loss hasn't raised significantly from the final loss of the\n # previous training run.\n testcase.assertLessEqual(training_outputs[0].loss,\n previous_final_loss * 1.01)\n for output in training_outputs:\n testcase.assertLessEqual(output.loss, 100.)\n last_output = training_outputs[-1]\n if print_training_accuracy:\n testcase.assertEqual(last_output.top_1_accuracy, 1.0)\n testcase.assertEqual(last_output.top_5_accuracy, 1.0)\n if max_final_loss is not None:\n testcase.assertLessEqual(last_output.loss, max_final_loss)",
"def test_loss_function(self):\n model = FakeSemanticSegmentationModel()\n batch, output, _ = get_fake_batch_output()\n batch_replicated, outputs_replicated = (jax_utils.replicate(batch),\n jax_utils.replicate(output))\n\n # Test loss function in the pmapped setup:\n loss_function_pmapped = jax.pmap(model.loss_function, axis_name='batch')\n total_loss = loss_function_pmapped(outputs_replicated, batch_replicated)\n # Check that loss is returning valid values:\n self.is_valid(jax_utils.unreplicate(total_loss), value_name='loss')",
"def test_auxiliary_loss_consistency(self):\n\n model = MyObjectDetectionWithMatchingModel()\n outputs, batch, indices = fake_model_outputs_batch(num_boxes=4)\n\n # Test loss function in the pmapped setup:\n loss_function_pmapped = jax.pmap(model.loss_function, axis_name='batch')\n\n indices_replicated = jax_utils.replicate(\n # Fake matching for the final output + 2 aux outputs:\n [indices] * 3)\n outputs_replicated, batch_replicated = (jax_utils.replicate(outputs),\n jax_utils.replicate(batch))\n _, metrics_dict = loss_function_pmapped(outputs_replicated,\n batch_replicated,\n indices_replicated)\n\n metrics_dict = jax_utils.unreplicate(metrics_dict)\n\n for key in ['loss_class', 'loss_bbox', 'loss_giou']:\n for i in range(NUM_AUX_OUTPUTS):\n self.assertAlmostEqual(\n metrics_dict[key + '_unscaled'],\n metrics_dict[key + f'_aux_{i}_unscaled'],\n places=5)\n self.assertAlmostEqual(\n metrics_dict[key], metrics_dict[key + f'_aux_{i}'], places=5)",
"def test_two_ctrl_sawtooth_outofphase(self, period=2):\n #for period in [2, 4, 5, 10]:\n timesteps = period * 2\n dur = 1\n for max_demand in [2,4,6,8,10]:\n workload = dual_offset_workload(switches=['sw1', 'sw2'],\n period=period, offset=period / 2.0,\n max_demand=max_demand, size=1,\n duration=dur, timesteps=timesteps,\n workload_fcn=sawtooth)\n\n ctrls = strictly_local_ctrls(2)\n\n sim = LinkBalancerSim(two_switch_topo(), ctrls)\n myname = sys._getframe().f_code.co_name + str(period)\n metrics = sim.run_and_trace(myname, workload, old=True,\n sync_period=timesteps,\n ignore_remaining=True)\n self.assertEqual(len(metrics['rmse_servers']), timesteps)\n for i, metric_val in enumerate(metrics['rmse_servers']):\n print \"step: %d, metric_val=%d, period=%d\" %(i, metric_val, period)\n # When aligned with a sawtooth crossing, RMSE should be equal.\n if i % (period / 2.0) == period / 4.0:\n self.assertAlmostEqual(metric_val, 0.0)\n else:\n self.assertTrue(metric_val > 0.0)",
"def test_cycle(self):\n with self.assertRaises(mn.MinnetonkaError) as me:\n with mn.model() as m:\n Foo = mn.variable('Foo', lambda x: x+1, 'FooVelocity')\n FooVelocity = mn.velocity('FooVelocity', 'Foo')\n self.assertEqual(me.exception.message,\n 'Circularity among variables: Foo <- FooVelocity <- Foo')",
"def test_loss_zero_same(loss_cls):\n\n if loss_cls != CosineSiameseLoss:\n loss = loss_cls(margin=0.0)\n else:\n loss = loss_cls()\n\n target = paddle.ones((_N_BATCH,))\n emb_anchor = paddle.rand((_N_BATCH, _N_DIM))\n embeddings = [emb_anchor, emb_anchor]\n if loss.arity == 3:\n emb_negative = paddle.rand((_N_BATCH, _N_DIM))\n embeddings.append(emb_negative)\n\n output = loss(embeddings, target)\n\n np.testing.assert_almost_equal(output.item(), 0)",
"def test_is_in_cycle_cyclohexane(self):\n molecule = Molecule().from_inchi('InChI=1/C6H12/c1-2-4-6-5-3-1/h1-6H2')\n for atom in molecule.atoms:\n if atom.is_hydrogen():\n self.assertFalse(molecule.is_atom_in_cycle(atom))\n elif atom.is_carbon():\n self.assertTrue(molecule.is_atom_in_cycle(atom))\n for atom1 in molecule.atoms:\n for atom2, bond in atom1.bonds.items():\n if atom1.is_carbon() and atom2.is_carbon():\n self.assertTrue(molecule.is_bond_in_cycle(bond))\n else:\n self.assertFalse(molecule.is_bond_in_cycle(bond))",
"def test_call(self):\n # Test that should_continue from callback is correct\n for early_stopping in (False, True):\n callback = ConvergenceCallback(early_stopping=early_stopping)\n for converged_states in its.product(*((True, False),) * NUM_NODES):\n for held_out_log_prob_deltas in its.product(*((-EPSILON, EPSILON),) *\n NUM_HELD_OUT_NODES):\n for node, state in zip(self.learner.nodes.values(), converged_states):\n node.converged = state\n for (node, held_out_log_prob_delta) in zip(\n self.learner.nodes.values()[:NUM_HELD_OUT_NODES],\n held_out_log_prob_deltas):\n node.log_prob_delta = held_out_log_prob_delta\n\n expected_should_continue = not all(converged_states[NUM_HELD_OUT_NODES:])\n if early_stopping and sum(held_out_log_prob_deltas) <= 0:\n expected_should_continue = False\n\n actual_should_continue = callback(self.learner)\n\n self.assertEqual(expected_should_continue, actual_should_continue)\n\n # Test condition check\n for node in self.learner.nodes.values():\n node.held_out = False\n callback = ConvergenceCallback(early_stopping=True)\n with self.assertRaises(ValueError):\n callback(self.learner)",
"def test_is_output_correct_for_normalization_correction_learn_model(self):\n # define the arguments needed by MUSiCC\n musicc_args = {'input_file': MUSiCCTestCase.path_to_data + '/examples/simulated_ko_relative_abundance.tab',\n 'output_file': MUSiCCTestCase.path_to_data + '/examples/test3.tab',\n 'input_format': 'tab', 'output_format': 'tab', 'musicc_inter': True,\n 'musicc_intra': 'learn_model', 'compute_scores': True, 'verbose': False}\n # run the MUSiCC correction\n correct_and_normalize(musicc_args)\n # assert that the result is equal to the example (up to small difference due to de novo learning)\n example = pd.read_table(MUSiCCTestCase.path_to_data + '/examples/simulated_ko_MUSiCC_Normalized_Corrected_learn_model.tab', index_col=0)\n output = pd.read_table(MUSiCCTestCase.path_to_data + '/examples/test3.tab', index_col=0)\n example_vals = example.values\n output_vals = output.values\n self.assertTrue(example_vals.shape[0] == output_vals.shape[0])\n self.assertTrue(example_vals.shape[1] == output_vals.shape[1])\n for i in range(example_vals.shape[0]):\n for j in range(example_vals.shape[1]):\n self.assertTrue(abs(example_vals[i, j] - output_vals[i, j]) < 1)\n\n os.remove(MUSiCCTestCase.path_to_data + '/examples/test3.tab')",
"def test_multiscale_zero(self):\n self.assertEqual(0, metrics.multiscale_spectral_loss(self.x, self.x))",
"def test_network_failure(aggregator, check):\n instance = common.generate_instance_config(common.SCALAR_OBJECTS)\n\n # Change port so connection will fail\n instance['port'] = 162\n\n check.check(instance)\n\n # Test service check\n aggregator.assert_service_check(\"snmp.can_check\", status=SnmpCheck.CRITICAL, tags=common.CHECK_TAGS, at_least=1)\n\n aggregator.all_metrics_asserted()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test StarGAN generator loss wrapper.
|
def test_stargan_generator_loss_wrapper(self):
loss_fn = tfgan.losses.wargs.wasserstein_generator_loss
wrapped_loss_fn = tfgan.losses.stargan_generator_loss_wrapper(loss_fn)
loss_result_tensor = loss_fn(
self.discriminator_generated_data_source_predication)
wrapped_loss_result_tensor = wrapped_loss_fn(self.model)
with self.cached_session() as sess:
sess.run(tf.compat.v1.global_variables_initializer())
loss_result, wrapped_loss_result = sess.run(
[loss_result_tensor, wrapped_loss_result_tensor])
self.assertAlmostEqual(loss_result, wrapped_loss_result)
|
[
"def generator_loss(discriminator_gen_outputs):\n loss = tf.losses.sigmoid_cross_entropy(\n tf.zeros_like(discriminator_gen_outputs), discriminator_gen_outputs)\n return loss",
"def test_stargan_discriminator_loss_wrapper(self):\n loss_fn = tfgan.losses.wargs.wasserstein_discriminator_loss\n wrapped_loss_fn = tfgan.losses.stargan_discriminator_loss_wrapper(loss_fn)\n\n loss_result_tensor = loss_fn(\n self.discriminator_generated_data_source_predication,\n self.discriminator_generated_data_source_predication)\n wrapped_loss_result_tensor = wrapped_loss_fn(self.model)\n\n with self.cached_session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n loss_result, wrapped_loss_result = sess.run(\n [loss_result_tensor, wrapped_loss_result_tensor])\n self.assertAlmostEqual(loss_result, wrapped_loss_result)",
"def loss(alpha_star, alpha, mu_star, mu, l, r):\n d_real = discriminator_expectation(alpha, mu_star, l, r)\n d_fake = 1 - discriminator_expectation(alpha, mu, l, r)\n return d_real + d_fake",
"def test_loss_function(self):\n model = FakeSemanticSegmentationModel()\n batch, output, _ = get_fake_batch_output()\n batch_replicated, outputs_replicated = (jax_utils.replicate(batch),\n jax_utils.replicate(output))\n\n # Test loss function in the pmapped setup:\n loss_function_pmapped = jax.pmap(model.loss_function, axis_name='batch')\n total_loss = loss_function_pmapped(outputs_replicated, batch_replicated)\n # Check that loss is returning valid values:\n self.is_valid(jax_utils.unreplicate(total_loss), value_name='loss')",
"def generator_loss(logits_fake):\n \n ####################################\n # YOUR CODE HERE #\n ####################################\n D_G_x = bce_loss(logits_fake, torch.ones(logits_fake.size()).to(device))\n total = D_G_x.mean()\n ########## END ##########\n \n return total",
"def gan_loss(self,gen_images,loss):\n labels = Variable(torch.ones( [gen_images.size()[0], 1] ))\n \n return(loss(gen_images,labels))",
"def test_square_sgd(self):\n model_vars, loss = self._test_loss_opt('square', 'sgd')",
"def generator_loss(self, fake_res, fake_img, fake_local, data_batch):\n gt = data_batch['gt_img']\n mask = data_batch['mask']\n masked_img = data_batch['masked_img']\n\n loss = dict()\n\n # if cur_iter <= iter_td, do not calculate adversarial loss\n if self.with_gan and self.cur_iter > self.train_cfg.iter_td:\n g_fake_pred = self.disc((fake_img, fake_local))\n loss_g_fake = self.loss_gan(g_fake_pred, True, False)\n loss['loss_g_fake'] = loss_g_fake\n\n if self.with_l1_hole_loss:\n loss_l1_hole = self.loss_l1_hole(fake_res, gt, weight=mask)\n loss['loss_l1_hole'] = loss_l1_hole\n\n if self.with_l1_valid_loss:\n loss_l1_valid = self.loss_l1_valid(fake_res, gt, weight=1. - mask)\n loss['loss_l1_valid'] = loss_l1_valid\n\n res = dict(\n gt_img=gt.cpu(),\n masked_img=masked_img.cpu(),\n fake_res=fake_res.cpu(),\n fake_img=fake_img.cpu())\n\n return res, loss",
"def gen_generator_loss(self):\n encoder_loss = self.get_covered_image_loss()\n decoder_loss = self.get_decoder_loss()\n\n return tf.keras.layers.Lambda(\n lambda x:(\n encoder_loss(x['color'], x['encoder_output']),\n decoder_loss(x['gray'], x['decoder_output']),\n 1 * encoder_loss(x['color'], x['encoder_output']) +\n 1.25 * decoder_loss(x['gray'], x['decoder_output']) +\n 5 * tf.expand_dims(x['discriminator_output'], axis=1)/1000.\n ),\n trainable=False,\n name='generator_loss'\n )",
"def loss(self, y_true: ndarray, y_pred: ndarray):\n \"\"\"\n ###########################\n Write here the PEGASOS loss.\n ###########################\n \"\"\"\n\n err = [np.max([0, 1-y_true[i]*y_pred[i]]) for i in range(0, y_true.size)]\n return np.sum(err) / y_true.size\n # return np.random.normal(loc=100.0, scale=5.0, size=(1,))[0]",
"def discriminator_loss(real_output, fake_output):\n\n real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)\n total_loss = real_loss + fake_loss\n return total_loss",
"def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', t.tensor(target_real_label))\n self.register_buffer('fake_label', t.tensor(target_fake_label))\n self.gan_mode = gan_mode\n if gan_mode == 'lsgan':\n self.loss = nn.MSELoss()\n elif gan_mode == 'vanilla':\n self.loss = nn.BCEWithLogitsLoss()\n elif gan_mode in ['wgangp']:\n self.loss = None\n else:\n raise NotImplementedError('gan mode %s not implemented' % gan_mode)",
"def test_init(self, loss_name):\n config = TEST_CONFIG_SEGM.copy()\n config.loss = {loss_name: {}}\n loss = get_loss(config)\n self.assertTrue(callable(loss))\n self.assertEqual(loss.__class__.__name__, loss_name)",
"def lsgan_loss(scores_real, scores_fake):\n D_loss = 0.5 * tf.reduce_mean(tf.square(scores_real-1)) + 0.5 * tf.reduce_mean(tf.square(scores_fake))\n G_loss = 0.5 * tf.reduce_mean(tf.square(scores_fake - 1))\n return D_loss, G_loss",
"def generator_loss_fn(y_generated, x_generated, x_sim ,lam=0.2, data_label=0):\n assert data_label == 1 or data_label == 0\n loss = torch.mean((y_generated - data_label)**2)\n\n loss_fn = nn.L1Loss()\n l1 = loss_fn(x_generated, x_sim)\n\n return loss + lam*l1",
"def compute_G_loss(self):\n # netD(0) for the separation branch.\n pred_fake1 = self.netD(0, self.fake_A)\n pred_fake2 = self.netD(0, self.fake_B)\n pred_fake3 = self.netD(0, self.fake_C)\n pred_fake4 = self.netD(0, self.fake_D)\n pred_fake5 = self.netD(0, self.fake_E)\n\n self.loss_G_GAN = self.criterionGAN(pred_fake1, True) \\\n + self.criterionGAN(pred_fake2, True) * self.label[0] \\\n + self.criterionGAN(pred_fake3, True) * self.label[1] \\\n + self.criterionGAN(pred_fake4, True) * self.label[2] \\\n + self.criterionGAN(pred_fake5, True) * self.label[3]\n\n self.loss_Ln = self.criterionL1(self.real_A, self.fake_A) \\\n + self.criterionL2(self.real_B, self.fake_B) * self.label[0] \\\n + self.criterionL2(self.real_C, self.fake_C) * self.label[1] \\\n + self.criterionL1(self.real_D, self.fake_D) * self.label[2] \\\n + self.criterionL2(self.real_E, self.fake_E) * self.label[3]\n\n self.loss_VGG = self.criterionVGG(self.fake_A, self.real_A) \\\n + self.criterionVGG(self.fake_B, self.real_B) * self.label[0] \\\n + self.criterionVGG(self.fake_C, self.real_C) * self.label[1] \\\n + self.criterionVGG(self.fake_D, self.real_D) * self.label[2] \\\n + self.criterionVGG(self.fake_E, self.real_E) * self.label[3]\n\n self.loss_G = self.loss_G_GAN * self.opt.lambda_GAN + self.loss_Ln * self.opt.lambda_Ln + self.loss_VGG * self.opt.lambda_VGG\n\n return self.loss_G",
"def test_stargan_gradient_penalty_wrapper(self):\n if tf.executing_eagerly():\n # Can't use `tf.gradient` when executing eagerly\n return\n loss_fn = tfgan.losses.wargs.wasserstein_gradient_penalty\n tfgan.losses.stargan_gradient_penalty_wrapper(loss_fn)\n wrapped_loss_fn = tfgan.losses.stargan_gradient_penalty_wrapper(loss_fn)\n\n loss_result_tensor = loss_fn(\n real_data=self.input_data,\n generated_data=self.generated_data,\n generator_inputs=self.input_data_domain_label.shape.as_list()[-1],\n discriminator_fn=self.discriminator_fn,\n discriminator_scope=self.discriminator_scope)\n wrapped_loss_result_tensor = wrapped_loss_fn(self.model)\n\n with self.cached_session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n loss_result, wrapped_loss_result = sess.run(\n [loss_result_tensor, wrapped_loss_result_tensor])\n self.assertAlmostEqual(loss_result, wrapped_loss_result)",
"def get_loss(generation_img):\n generation_img = K.reshape(generation_img, [1, 300, 400, 3])\n return fn([generation_img])[0].astype('float64')",
"def test_square_adam(self):\n model_vars, loss = self._test_loss_opt('square', 'adam')"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test StarGAN discriminator loss wrapper.
|
def test_stargan_discriminator_loss_wrapper(self):
loss_fn = tfgan.losses.wargs.wasserstein_discriminator_loss
wrapped_loss_fn = tfgan.losses.stargan_discriminator_loss_wrapper(loss_fn)
loss_result_tensor = loss_fn(
self.discriminator_generated_data_source_predication,
self.discriminator_generated_data_source_predication)
wrapped_loss_result_tensor = wrapped_loss_fn(self.model)
with self.cached_session() as sess:
sess.run(tf.compat.v1.global_variables_initializer())
loss_result, wrapped_loss_result = sess.run(
[loss_result_tensor, wrapped_loss_result_tensor])
self.assertAlmostEqual(loss_result, wrapped_loss_result)
|
[
"def loss(alpha_star, alpha, mu_star, mu, l, r):\n d_real = discriminator_expectation(alpha, mu_star, l, r)\n d_fake = 1 - discriminator_expectation(alpha, mu, l, r)\n return d_real + d_fake",
"def ls_discriminator_loss(scores_real, scores_fake):\n \n loss = None\n \n ####################################\n # YOUR CODE HERE #\n ####################################\n \n D_x = bce_loss(scores_real, torch.ones(scores_real.size()).to(device))\n D_G_x = bce_loss(scores_fake, torch.zeros(scores_fake.size()).to(device))\n total = D_x + D_G_x\n total = 0.5 * total\n total.mean()\n ########## END ##########\n return total",
"def discriminator_loss(real_output, fake_output):\n\n real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)\n total_loss = real_loss + fake_loss\n return total_loss",
"def discriminator_loss(logits_real, logits_fake):\n \n ####################################\n # YOUR CODE HERE #\n ####################################\n \n D_x = bce_loss(logits_real, torch.ones(logits_real.size()).to(device))\n D_G_x = bce_loss(logits_fake, torch.zeros(logits_fake.size()).to(device))\n total = D_x + D_G_x\n total.mean()\n ########## END ##########\n return total",
"def generator_loss(discriminator_gen_outputs):\n loss = tf.losses.sigmoid_cross_entropy(\n tf.zeros_like(discriminator_gen_outputs), discriminator_gen_outputs)\n return loss",
"def test_stargan_generator_loss_wrapper(self):\n loss_fn = tfgan.losses.wargs.wasserstein_generator_loss\n wrapped_loss_fn = tfgan.losses.stargan_generator_loss_wrapper(loss_fn)\n\n loss_result_tensor = loss_fn(\n self.discriminator_generated_data_source_predication)\n wrapped_loss_result_tensor = wrapped_loss_fn(self.model)\n\n with self.cached_session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n loss_result, wrapped_loss_result = sess.run(\n [loss_result_tensor, wrapped_loss_result_tensor])\n self.assertAlmostEqual(loss_result, wrapped_loss_result)",
"def discriminator_loss(disc_real_output,\n disc_generated_output,\n l2_weight = 0.0001,\n L2_OPT = False,\n WASSERSTEIN_OPT = False):\n # log(DIS)\n if (WASSERSTEIN_OPT):\n real_loss = tf.reduce_mean(disc_real_output) - tf.reduce_mean(disc_generated_output)\n generated_loss = tf.zeros_like(disc_real_output) # equal to zero-like tensor...\n else:\n real_loss = cross_entropy(tf.ones_like(disc_real_output), disc_real_output)\n generated_loss = cross_entropy(tf.zeros_like(disc_generated_output), disc_generated_output)\n # total_loss = real_loss + generated_loss\n\n # real_loss = tf.nn.sigmoid_cross_entropy_with_logits(\n # labels=tf.ones_like(disc_real_output), logits=disc_real_output) # label=1\n\n # log(1-DIS(GEN))\n # generated_loss = tf.nn.sigmoid_cross_entropy_with_logits(\n # labels=tf.zeros_like(disc_generated_output), logits=disc_generated_output) # label=0\n\n # L2 loss\n l2_loss = tf.reduce_mean(tf.abs(disc_real_output - disc_generated_output)) # loss with target...\n\n total_loss = real_loss + generated_loss + (L2_OPT * l2_weight * l2_loss)\n\n # total_disc_loss = tf.reduce_mean(real_loss) \\\n # + tf.reduce_mean(generated_loss) \\\n # + (l2_weight * l2_loss * L2_OPT)\n\n return total_loss",
"def discriminator_loss(self, x):\n _freeze(self) # save memory by excluding parameters from autograd\n _unfreeze(self.D)\n z_prior = self.sample_prior(len(x))\n if self.use_E(): # encoder case\n z = self.E(x)\n zs = torch.cat((z_prior, z), 0)\n x_real = torch.cat((x,x), 0)\n else: # no encoder (pure GAN) case\n zs = z_prior\n x_real = x\n x_fake = self.G(zs)\n return {\n 'D_critic_loss': \n self.D(x_fake).mean() - self.D(x).mean(),\n 'D_gradient_penalty':\n self.gradient_penalty(self.D, x_real, x_fake)\n }",
"def make_discriminator():\n\n input_data = Input(shape=(IMG_DIM[0], IMG_DIM[1], 1))\n x = Conv2D(D, (5, 5), strides=(2,2), padding='same')(input_data)\n x = LeakyReLU(alpha=0.2)(x)\n x = Conv2D(D * 2, (5, 5), strides=(2,2), kernel_initializer='he_normal',padding='same')(x)\n x = LeakyReLU(alpha=0.2)(x)\n x = Conv2D(D * 4, (5, 5), strides=(2,2), kernel_initializer='he_normal',padding='same')(x)\n x = LeakyReLU(alpha=0.2)(x)\n x = Conv2D(D * 8, (5, 5), strides=(2,2), kernel_initializer='he_normal',padding='same')(x)\n x = LeakyReLU(alpha=0.2)(x)\n x = Conv2D(D * 16, (5, 5), strides=(2,2), kernel_initializer='he_normal', padding='same')(x)\n x = LeakyReLU(alpha=0.2)(x)\n x = Flatten()(x)\n real_fake = Dense(1, kernel_initializer='he_normal', name='real_fake')(x) # no activation for wasserstein_loss\n\n model = Model(input_data, real_fake)\n\n return model",
"def train_step_discriminator(self):\n self.discriminator.zero_grad() # Same as above\n\n # real samples\n real_samples = self.data_fn(self.batch_size) # Get some real samples\n pred_real = self.discriminator(real_samples) # Get the discriminator confidence that they're real\n loss_real = self.criterion(pred_real, self.target_ones) # Calculate the loss function\n\n # generated samples\n latent_vec = self.noise_fn(self.batch_size) # repeat this process with generated samples\n with torch.no_grad(): # we don't care so much about gradients in the generator here because we're training the discriminator\n fake_samples = self.generator(latent_vec) # This context manager detaches the genetaor from its computational graph and saves computing overhead.\n pred_fake = self.discriminator(fake_samples)\n loss_fake = self.criterion(pred_fake, self.target_zeros)\n\n # combine\n loss = (loss_real + loss_fake) / 2 # average the graphs for the loss using simple python arithmetic. PyTorch is great.\n loss.backward() # Calculate gradients\n self.optim_d.step() # Nudge along the slope\n return loss_real.item(), loss_fake.item() # Return losses",
"def compute_G_loss(self):\n # netD(0) for the separation branch.\n pred_fake1 = self.netD(0, self.fake_A)\n pred_fake2 = self.netD(0, self.fake_B)\n pred_fake3 = self.netD(0, self.fake_C)\n pred_fake4 = self.netD(0, self.fake_D)\n pred_fake5 = self.netD(0, self.fake_E)\n\n self.loss_G_GAN = self.criterionGAN(pred_fake1, True) \\\n + self.criterionGAN(pred_fake2, True) * self.label[0] \\\n + self.criterionGAN(pred_fake3, True) * self.label[1] \\\n + self.criterionGAN(pred_fake4, True) * self.label[2] \\\n + self.criterionGAN(pred_fake5, True) * self.label[3]\n\n self.loss_Ln = self.criterionL1(self.real_A, self.fake_A) \\\n + self.criterionL2(self.real_B, self.fake_B) * self.label[0] \\\n + self.criterionL2(self.real_C, self.fake_C) * self.label[1] \\\n + self.criterionL1(self.real_D, self.fake_D) * self.label[2] \\\n + self.criterionL2(self.real_E, self.fake_E) * self.label[3]\n\n self.loss_VGG = self.criterionVGG(self.fake_A, self.real_A) \\\n + self.criterionVGG(self.fake_B, self.real_B) * self.label[0] \\\n + self.criterionVGG(self.fake_C, self.real_C) * self.label[1] \\\n + self.criterionVGG(self.fake_D, self.real_D) * self.label[2] \\\n + self.criterionVGG(self.fake_E, self.real_E) * self.label[3]\n\n self.loss_G = self.loss_G_GAN * self.opt.lambda_GAN + self.loss_Ln * self.opt.lambda_Ln + self.loss_VGG * self.opt.lambda_VGG\n\n return self.loss_G",
"def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', t.tensor(target_real_label))\n self.register_buffer('fake_label', t.tensor(target_fake_label))\n self.gan_mode = gan_mode\n if gan_mode == 'lsgan':\n self.loss = nn.MSELoss()\n elif gan_mode == 'vanilla':\n self.loss = nn.BCEWithLogitsLoss()\n elif gan_mode in ['wgangp']:\n self.loss = None\n else:\n raise NotImplementedError('gan mode %s not implemented' % gan_mode)",
"def compile_discriminator_model(discriminator: Functional, learning_rate) -> Functional:\n optimizer: SGD = SGD(learning_rate=learning_rate)\n model: Functional = Model(inputs=discriminator.input, outputs=discriminator.output)\n model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])\n model.summary()\n return model",
"def build_discriminator():\n input_layer = layers.Input((2,))\n X = input_layer\n for i in range(5):\n X = layers.Dense(128)(X)\n X = layers.LeakyReLU(0.01)(X)\n output_layer = layers.Dense(1, activation=\"sigmoid\")(X)\n D = Model(input_layer, output_layer)\n D.compile(\n Adam(learning_rate=0.001, beta_1=0.5),\n loss=\"binary_crossentropy\",\n metrics=[\"accuracy\"],\n )\n return D",
"def _loss_discriminators(self, real_a, real_b, fake_b_disc, fake_a_disc, device):\n # take note that image pooling for fake(generated) images can be implemented here\n # calculate loss for ab_discriminator\n ab_disc_loss = self._loss_discriminators_base(self.ab_discriminator, real_b, fake_b_disc, device)\n\n # calculate loss for ba_discriminator\n ba_disc_loss = self._loss_discriminators_base(self.ba_discriminator, real_a, fake_a_disc, device)\n\n return ab_disc_loss, ba_disc_loss",
"def dragan_penalty(self, x, discriminator, is_training):\n _, var = tf.nn.moments(x, axes=list(range(len(x.get_shape()))))\n std = tf.sqrt(var)\n x_noisy = x + std * (tf.random_uniform(x.shape) - 0.5)\n x_noisy = tf.clip_by_value(x_noisy, 0.0, 1.0)\n logits = discriminator(x_noisy, is_training=is_training, reuse=True)[1]\n gradients = tf.gradients(logits, [x_noisy])[0]\n slopes = tf.sqrt(0.0001 + tf.reduce_sum(\n tf.square(gradients), reduction_indices=[1, 2, 3]))\n gradient_penalty = tf.reduce_mean(tf.square(slopes - 1.0))\n return gradient_penalty",
"def __init__(self, GAN_mode, real_label=1.0, fake_label=0.0):\n super(GANLossObj, self).__init__()\n # registering the labels for model storage\n self.register_buffer('real_label', torch.tensor(real_label))\n self.register_buffer('fake_label', torch.tensor(fake_label))\n self.GAN_mode = GAN_mode\n # Determine the loss function\n if GAN_mode == 'vanilla':\n self.loss = nn.BCEWithLogitsLoss()\n elif GAN_mode == 'lsgan':\n self.loss = nn.MSELoss()\n elif GAN_mode == 'wgangp':\n self.loss = None\n else:\n raise NotImplementedError('GAN mode %s is not found' % GAN_mode)",
"def train_discriminator(discriminator, dis_opt, real_data_samples, generator, d_steps, epochs, pad_states):\n\n # generating a small validation set before training (using generator)\n pos_val = pad_states[:100]\n neg_val = generator.sample(100, expert_st)[0]\n val_inp, val_target = prepare_discriminator_data(pos_val, neg_val, gpu=CUDA)\n\n for d_step in range(d_steps):\n s, a = batchwise_sample(generator, POS_NEG_SAMPLES, BATCH_SIZE, expert_st)\n dis_inp, dis_target = prepare_discriminator_data(pad_states, s, gpu=CUDA)\n for epoch in range(epochs):\n print('d-step %d epoch %d : ' % (d_step + 1, epoch + 1), end='')\n sys.stdout.flush()\n total_loss = 0\n total_acc = 0\n\n for i in range(0, 2 * POS_NEG_SAMPLES, BATCH_SIZE):\n inp, target = dis_inp[i:i + BATCH_SIZE], dis_target[i:i + BATCH_SIZE]\n dis_opt.zero_grad()\n out = discriminator.batchClassify(inp)\n loss_fn = nn.BCELoss()\n loss = loss_fn(out, target)\n loss.backward()\n dis_opt.step()\n\n total_loss += loss.data.item()\n total_acc += torch.sum((out>0.5)==(target>0.5)).data.item()\n\n if (i / BATCH_SIZE) % ceil(ceil(2 * POS_NEG_SAMPLES / float(\n BATCH_SIZE)) / 10.) == 0: # roughly every 10% of an epoch\n print('.', end='')\n sys.stdout.flush()\n\n total_loss /= ceil(2 * POS_NEG_SAMPLES / float(BATCH_SIZE))\n total_acc /= float(2 * POS_NEG_SAMPLES)\n\n val_pred = discriminator.batchClassify(val_inp)\n print(' average_loss = %.4f, train_acc = %.4f, val_acc = %.4f' % (\n total_loss, total_acc, torch.sum((val_pred>0.5)==(val_target>0.5)).data.item()/200.))",
"def test_square_sgd(self):\n model_vars, loss = self._test_loss_opt('square', 'sgd')"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test StaGAN gradient penalty wrapper.
|
def test_stargan_gradient_penalty_wrapper(self):
if tf.executing_eagerly():
# Can't use `tf.gradient` when executing eagerly
return
loss_fn = tfgan.losses.wargs.wasserstein_gradient_penalty
tfgan.losses.stargan_gradient_penalty_wrapper(loss_fn)
wrapped_loss_fn = tfgan.losses.stargan_gradient_penalty_wrapper(loss_fn)
loss_result_tensor = loss_fn(
real_data=self.input_data,
generated_data=self.generated_data,
generator_inputs=self.input_data_domain_label.shape.as_list()[-1],
discriminator_fn=self.discriminator_fn,
discriminator_scope=self.discriminator_scope)
wrapped_loss_result_tensor = wrapped_loss_fn(self.model)
with self.cached_session() as sess:
sess.run(tf.compat.v1.global_variables_initializer())
loss_result, wrapped_loss_result = sess.run(
[loss_result_tensor, wrapped_loss_result_tensor])
self.assertAlmostEqual(loss_result, wrapped_loss_result)
|
[
"def test_policy_gradient(self):\n model = VanillaPolicyGradient(self.hparams.env)\n self.trainer.fit(model)",
"def gradient(self, var, bayesianOptimizer):\n pass",
"def test_fast_gradient_method():\n context.set_context(mode=context.GRAPH_MODE, device_target=\"Ascend\")\n input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)\n label = np.asarray([2], np.int32)\n label = np.eye(3)[label].astype(np.float32)\n\n attack = FastGradientMethod(Net())\n ms_adv_x = attack.generate(input_np, label)\n\n assert np.any(ms_adv_x != input_np), 'Fast gradient method: generate value' \\\n ' must not be equal to original value.'",
"def verify_gradients(self):\n \n print 'WARNING: calling verify_gradients reinitializes the learner'\n \n rng = np.random.mtrand.RandomState(1234)\n \n self.initialize(10,3)\n example = (rng.rand(4,10),np.array([0,1,1,2]))\n input,target = example\n epsilon=1e-6\n self.lr = 0.1\n self.decrease_constant = 0\n\n self.weights = [0.01*rng.rand(self.input_size,self.n_classes),\n 0.01*rng.rand(self.input_size,self.n_classes),\n 0.01*rng.rand(self.input_size,self.n_classes)]\n self.bias = 0.01*rng.rand(self.n_classes)\n self.lateral_weights = 0.01*rng.rand(self.n_classes,self.n_classes)\n \n self.fprop(input,target)\n self.bprop(input,target) # compute gradients\n\n import copy\n emp_grad_weights = copy.deepcopy(self.weights)\n \n for h in range(len(self.weights)):\n for i in range(self.weights[h].shape[0]):\n for j in range(self.weights[h].shape[1]):\n self.weights[h][i,j] += epsilon\n a = self.fprop(input,target)\n self.weights[h][i,j] -= epsilon\n \n self.weights[h][i,j] -= epsilon\n b = self.fprop(input,target)\n self.weights[h][i,j] += epsilon\n \n emp_grad_weights[h][i,j] = (a-b)/(2.*epsilon)\n\n\n print 'grad_weights[-1] diff.:',np.sum(np.abs(self.grad_weights[-1].ravel()-emp_grad_weights[-1].ravel()))/self.weights[-1].ravel().shape[0]\n print 'grad_weights[0] diff.:',np.sum(np.abs(self.grad_weights[0].ravel()-emp_grad_weights[0].ravel()))/self.weights[0].ravel().shape[0]\n print 'grad_weights[1] diff.:',np.sum(np.abs(self.grad_weights[1].ravel()-emp_grad_weights[1].ravel()))/self.weights[1].ravel().shape[0]\n \n emp_grad_lateral_weights = copy.deepcopy(self.lateral_weights)\n \n for i in range(self.lateral_weights.shape[0]):\n for j in range(self.lateral_weights.shape[1]):\n self.lateral_weights[i,j] += epsilon\n a = self.fprop(input,target)\n self.lateral_weights[i,j] -= epsilon\n\n self.lateral_weights[i,j] -= epsilon\n b = self.fprop(input,target)\n self.lateral_weights[i,j] += epsilon\n \n emp_grad_lateral_weights[i,j] = (a-b)/(2.*epsilon)\n\n\n print 'grad_lateral_weights diff.:',np.sum(np.abs(self.grad_lateral_weights.ravel()-emp_grad_lateral_weights.ravel()))/self.lateral_weights.ravel().shape[0]\n\n emp_grad_bias = copy.deepcopy(self.bias)\n for i in range(self.bias.shape[0]):\n self.bias[i] += epsilon\n a = self.fprop(input,target)\n self.bias[i] -= epsilon\n \n self.bias[i] -= epsilon\n b = self.fprop(input,target)\n self.bias[i] += epsilon\n \n emp_grad_bias[i] = (a-b)/(2.*epsilon)\n \n print 'grad_bias diff.:',np.sum(np.abs(self.grad_bias.ravel()-emp_grad_bias.ravel()))/self.bias.ravel().shape[0]",
"def wgangp_penalty(self, x, x_fake, discriminator, is_training):\n alpha = tf.random_uniform(shape=[self.batch_size, 1, 1, 1])\n interpolates = x + alpha * (x_fake - x)\n logits = discriminator(interpolates, is_training=is_training, reuse=True)[1]\n gradients = tf.gradients(logits, [interpolates])[0]\n slopes = tf.sqrt(0.0001 + tf.reduce_sum(\n tf.square(gradients), reduction_indices=[1, 2, 3]))\n gradient_penalty = tf.reduce_mean(tf.square(slopes - 1.0))\n return gradient_penalty",
"def test_gradient_boosting(n_samples=1000, distance = 0.6):\n # Generating some samples correlated with first variable\n testX, testY = generate_sample(n_samples, 10, distance)\n trainX, trainY = generate_sample(n_samples, 10, distance)\n # We will try to get uniform distribution along this variable\n uniform_features = ['column0']\n\n loss1 = LogLossFunction()\n loss2 = AdaLossFunction()\n loss3 = losses.CompositeLossFunction()\n loss4 = losses.KnnAdaLossFunction(uniform_features=uniform_features, knn=5, uniform_label=1)\n loss5 = losses.KnnAdaLossFunction(uniform_features=uniform_features, knn=5, uniform_label=[0, 1])\n loss6bin = losses.BinFlatnessLossFunction(uniform_features, fl_coefficient=1., uniform_label=0)\n loss7bin = losses.BinFlatnessLossFunction(uniform_features, fl_coefficient=1., uniform_label=[0, 1])\n loss6knn = losses.KnnFlatnessLossFunction(uniform_features, fl_coefficient=1., uniform_label=1)\n loss7knn = losses.KnnFlatnessLossFunction(uniform_features, fl_coefficient=1., uniform_label=[0, 1])\n\n for loss in [loss1, loss2, loss3, loss4, loss5, loss6bin, loss7bin, loss6knn, loss7knn]:\n clf = UGradientBoostingClassifier(loss=loss, min_samples_split=20, max_depth=5, learning_rate=0.2,\n subsample=0.7, n_estimators=25, train_features=None)\n clf.fit(trainX[:n_samples], trainY[:n_samples])\n result = clf.score(testX, testY)\n assert result >= 0.7, \"The quality is too poor: {} with loss: {}\".format(result, loss)\n\n trainX['fake_request'] = numpy.random.randint(0, 4, size=len(trainX))\n testX['fake_request'] = numpy.random.randint(0, 4, size=len(testX))\n for loss in [losses.MSELossFunction(),\n losses.MAELossFunction(),\n losses.RankBoostLossFunction(request_column='fake_request')]:\n print(loss)\n clf = UGradientBoostingRegressor(loss=loss, max_depth=3, n_estimators=50, learning_rate=0.01, subsample=0.5,\n train_features=list(trainX.columns[1:]))\n clf.fit(trainX, trainY)\n roc_auc = roc_auc_score(testY, clf.predict(testX))\n assert roc_auc >= 0.7, \"The quality is too poor: {} with loss: {}\".format(roc_auc, loss)",
"def __gradient_penalty(self, real_samps, fake_samps, latent_vector,\n height, alpha, reg_lambda=10):\n from torch.autograd import grad\n\n batch_size = real_samps.shape[0]\n\n # generate random epsilon\n epsilon = th.rand((batch_size, 1, 1, 1)).to(self.device)\n\n # create the merge of both real and fake samples\n merged = (epsilon * real_samps) + ((1 - epsilon) * fake_samps)\n\n # forward pass\n op, logits = self.dis.forward(merged, latent_vector, height, alpha)\n\n # obtain gradient of op wrt. merged\n gradient = grad(outputs=op, inputs=merged, create_graph=True, grad_outputs=th.ones_like(op), retain_graph=True, only_inputs=True)[0]\n\n # calculate the penalty using these gradients\n penalty = reg_lambda * ((gradient.norm(p=2, dim=1) - 1) ** 2).mean()\n\n # return the calculated penalty:\n #print(\"losses.py penalty:\", penalty)\n return penalty",
"def test_random_fast_gradient_method():\n context.set_context(mode=context.GRAPH_MODE, device_target=\"Ascend\")\n input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)\n label = np.asarray([2], np.int32)\n label = np.eye(3)[label].astype(np.float32)\n\n attack = RandomFastGradientMethod(Net())\n ms_adv_x = attack.generate(input_np, label)\n\n assert np.any(ms_adv_x != input_np), 'Random fast gradient method: ' \\\n 'generate value must not be equal to' \\\n ' original value.'",
"def test_grad():\n for ex in EXAMPLES:\n input, b_grad, w_grad = ex[\"in\"], ex[\"bias_grad\"], ex[\"weight_grad\"]\n\n loss = loss_function(g_lin(input))\n with backpack(new_ext.BatchGrad()):\n loss.backward()\n\n assert allclose(g_lin.bias.grad, b_grad)\n assert allclose(g_lin.weight.grad, w_grad)\n\n del g_lin.bias.grad\n del g_lin.weight.grad",
"def gradCheck(l=GRULayer(1, 10)):\n\n def loss(h):\n \"\"\"A dummy loss function; the square error compared to a linspace.\"\"\"\n dh = h - np.linspace(-1, 1, h.shape[0])[:, None, None]\n return 0.5 * np.sum(dh * dh), dh\n\n num_checks = 5\n delta = 1e-5\n n = 20\n x = np.arange(n * 2.0).reshape((n, 1, 2)) # dummy input; batch of size 2, 20 samples per sequence\n h = l.forward(x)\n dh = loss(h)[1]\n dx = l.backward(dh) # analytical gradient\n\n for param, name in zip([x, l.W, l.Wr, l.Wz],\n ['x', 'W', 'Wr', 'Wz']):\n\n print(name)\n a = param if (name == 'x') else param.a # only x is not a Param object\n\n for i in range(num_checks):\n ri = int(np.random.randint(a.size))\n # compute the derivative from definition - evaluate loss at [x+delta] and [x-delta]\n old_val = a.flat[ri]\n a.flat[ri] = old_val + delta\n cg0 = loss(l.forward(x))[0]\n a.flat[ri] = old_val - delta\n cg1 = loss(l.forward(x))[0]\n a.flat[ri] = old_val # reset old value for this parameter\n # fetch both numerical and analytic gradient\n grad_analytic = (dx if (name == 'x') else param.d).flat[ri] # again, treat x differently\n grad_numerical = (cg0 - cg1) / (2 * delta)\n\n rel_error = abs(grad_analytic - grad_numerical) / abs(grad_numerical + grad_analytic)\n print('%f, %f => %e ' % (grad_numerical, grad_analytic, rel_error))\n # rel_error should be on order of 1e-7 or less",
"def testAdamOptimizerWithNewLearningRate(self):\n self._assertOptimizerWithNewLearningRate(\"adam_optimizer\")",
"def _compare_range_learning_with_default_grad(self):\n\n iterations = 10\n pass_through_grad_avg_time = self.test_qc_custom_gradient_training_loop_pass_through(iterations)\n range_learning_avg_time = self.test_qc_custom_gradient_training_loop_range_learning(iterations)\n print('% increase ', ((range_learning_avg_time - pass_through_grad_avg_time)\n / pass_through_grad_avg_time) * 100)",
"def test_random_fast_gradient_sign_method():\n context.set_context(mode=context.GRAPH_MODE, device_target=\"Ascend\")\n input_np = np.random.random((1, 28)).astype(np.float32)\n label = np.asarray([2], np.int32)\n label = np.eye(28)[label].astype(np.float32)\n\n attack = RandomFastGradientSignMethod(Net())\n ms_adv_x = attack.generate(input_np, label)\n\n assert np.any(ms_adv_x != input_np), 'Random fast gradient sign method: ' \\\n 'generate value must not be equal to' \\\n ' original value.'",
"def test_square_sgd(self):\n model_vars, loss = self._test_loss_opt('square', 'sgd')",
"def test_fast_gradient_sign_method():\n context.set_context(mode=context.GRAPH_MODE, device_target=\"Ascend\")\n input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)\n label = np.asarray([2], np.int32)\n label = np.eye(3)[label].astype(np.float32)\n\n attack = FastGradientSignMethod(Net())\n ms_adv_x = attack.generate(input_np, label)\n\n assert np.any(ms_adv_x != input_np), 'Fast gradient sign method: generate' \\\n ' value must not be equal to' \\\n ' original value.'",
"def test_2():\n d = 3\n x = np.array([1, 1.5, 2])\n\n grad_val = mt_obj.griewank_grad(x, d)\n assert(np.all(np.round(grad_val, 6) == np.array([0.166577,\n 0.135511,\n 0.140324])))",
"def test_build_optimizer_sgd(self):\n opt_config = {\"name\": \"SGD\"}\n opt_get = optimizer.build_optimizer(opt_config)\n assert isinstance(opt_get, tf.keras.optimizers.SGD)",
"def sgd_update(trainables, learning_rate=1e-2):\n for node in trainables:\n node.value -= learning_rate * node.gradients[node]",
"def dragan_penalty(self, x, discriminator, is_training):\n _, var = tf.nn.moments(x, axes=list(range(len(x.get_shape()))))\n std = tf.sqrt(var)\n x_noisy = x + std * (tf.random_uniform(x.shape) - 0.5)\n x_noisy = tf.clip_by_value(x_noisy, 0.0, 1.0)\n logits = discriminator(x_noisy, is_training=is_training, reuse=True)[1]\n gradients = tf.gradients(logits, [x_noisy])[0]\n slopes = tf.sqrt(0.0001 + tf.reduce_sum(\n tf.square(gradients), reduction_indices=[1, 2, 3]))\n gradient_penalty = tf.reduce_mean(tf.square(slopes - 1.0))\n return gradient_penalty"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
creates a learning rate decay operation in tensorflow using inverse time decay
|
def learning_rate_decay(alpha, decay_rate, global_step, decay_step):
train = tf.train.inverse_time_decay(alpha, global_step, decay_step,
decay_rate, staircase=True)
return train
|
[
"def _decay(self):\n costs = []\n for var in tf.trainable_variables():\n if var.op.name.find(r'DW') > 0:\n costs.append(tf.nn.l2_loss(var))\n # tf.summary.histogram(var.op.name, var)\n\n self.wdec = tf.add_n(costs)\n return tf.multiply(self.args.weight_decay, self.wdec)",
"def learning_rate_decay(epoch):\n return alpha / (1 + decay_rate * epoch)",
"def params_decay(decay):\n params = tf.get_collection_ref(tf.GraphKeys.WEIGHTS) + tf.get_collection_ref(tf.GraphKeys.BIASES)\n while len(params) > 0:\n p = params.pop()\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS,\n p.assign(decay*p + (1-decay)*tf.truncated_normal(p.get_shape(), stddev=0.01)))",
"def _decayed_lr(self, var_dtype):\n lr_t = self._get_hyper(\"learning_rate\", var_dtype)\n if isinstance(lr_t, learning_rate_schedule.LearningRateSchedule):\n local_step = math_ops.cast(self.iterations, var_dtype)\n lr_t = math_ops.cast(lr_t(local_step), var_dtype)\n if self._initial_decay > 0.:\n local_step = math_ops.cast(self.iterations, var_dtype)\n decay_t = math_ops.cast(self._initial_decay, var_dtype)\n lr_t = lr_t / (1. + decay_t * local_step)\n return lr_t",
"def lr_decay(self):\n\t\tself.lr = self.lr * self.gamma",
"def _f_decay_of_t(t):\n\n return 0.689*np.exp(-1.6*t) + 0.0303*np.exp(-0.2783*t)",
"def test_exp_schedule(backend):\n lr_init = 0.1\n decay = 0.01\n sch = ExpSchedule(decay)\n for epoch in range(10):\n lr = sch.get_learning_rate(learning_rate=lr_init, epoch=epoch)\n assert np.allclose(lr, lr_init / (1. + decay * epoch))",
"def learning_rate_step_decay(epoch, lr, step=24, initial_power=-3):\n num = epoch // step\n lrate = 10 ** (initial_power - num)\n print(\"Learning rate for epoch {} is {}.\".format(epoch + 1, 1.0 * lrate))\n return np.float(lrate)",
"def instant_forward_rate(self, t: types.RealTensor) -> types.RealTensor:\n return self._instant_forward_rate_fn(t)",
"def _decay(i,n):\n if n > 1 and i < n:\n a = (1-alpha)/((n))\n return alpha + a*((i+1))\n else:\n return 1",
"def decay(exploration_rate=0.1, decay_type='polynomial_decay', start_decay_at=0, stop_decay_at=1e9,\n decay_rate=0., staircase=False, decay_steps=10000, min_exploration_rate=0):\n def decay_fn(timestep):\n \"\"\"The computed decayed exploration rate.\n\n Args:\n timestep: the current timestep.\n \"\"\"\n timestep = tf.to_int32(timestep)\n decay_type_fn = getattr(exploration_decay, decay_type)\n kwargs = dict(\n exploration_rate=exploration_rate,\n timestep=tf.minimum(timestep, tf.to_int32(stop_decay_at)) - tf.to_int32(start_decay_at),\n decay_steps=decay_steps,\n name=\"decayed_exploration_rate\"\n )\n decay_fn_args = get_arguments(decay_type_fn)\n if 'decay_rate' in decay_fn_args:\n kwargs['decay_rate'] = decay_rate\n if 'staircase' in decay_fn_args:\n kwargs['staircase'] = staircase\n\n decayed_exploration_rate = decay_type_fn(**kwargs)\n\n final_exploration_rate = tf.train.piecewise_constant(\n x=timestep,\n boundaries=[start_decay_at],\n values=[exploration_rate, decayed_exploration_rate])\n\n if min_exploration_rate:\n final_exploration_rate = tf.maximum(final_exploration_rate, min_exploration_rate)\n\n return final_exploration_rate\n\n learning_rate = decay_fn(get_global_step())\n track(learning_rate, tf.GraphKeys.EXPLORATION_RATE)\n return learning_rate",
"def create_decay_callback(initial_learning_rate, epochs_drop):\n\n def step_decay(epoch):\n \"\"\"learning decay callback\"\"\"\n\n drop = 0.5\n decrease_pow = math.floor((1 + epoch) / epochs_drop)\n lrate = initial_learning_rate * math.pow(drop, decrease_pow)\n\n return lrate\n\n return step_decay",
"def lr_schedule(epoch: int) -> float:\n epoch += epoch_base\n learning_rate = 1e-3\n if epoch > 180:\n learning_rate *= 0.5e-3\n elif epoch > 160:\n learning_rate *= 1e-3\n elif epoch > 120:\n learning_rate *= 1e-2\n elif epoch > 80:\n learning_rate *= 1e-1\n return learning_rate",
"def create_optimizer(init_lr, num_train_steps, num_warmup_steps):\n # Implements linear decay of the learning rate.\n learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(\n initial_learning_rate=init_lr,\n decay_steps=num_train_steps,\n end_learning_rate=0.0)\n if num_warmup_steps:\n learning_rate_fn = WarmUp(initial_learning_rate=init_lr,\n decay_schedule_fn=learning_rate_fn,\n warmup_steps=num_warmup_steps)\n optimizer = AdamWeightDecay(\n learning_rate=learning_rate_fn,\n weight_decay_rate=0.01,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-6,\n exclude_from_weight_decay=['layer_norm', 'bias'])\n return optimizer",
"def make_learning_rate_decay_fn(opt, num_training_steps):\n if opt.decay_method == \"linear\":\n return functools.partial(\n linear_decay,\n warmup_steps=opt.warmup_steps,\n num_training_steps=num_training_steps)\n elif opt.decay_method == 'noam':\n return functools.partial(\n noam_decay,\n warmup_steps=opt.warmup_steps,\n model_size=opt.rnn_size)\n elif opt.decay_method == 'noamwd':\n return functools.partial(\n noamwd_decay,\n warmup_steps=opt.warmup_steps,\n model_size=opt.rnn_size,\n rate=opt.learning_rate_decay,\n decay_steps=opt.decay_steps,\n start_step=opt.start_decay_steps)\n elif opt.decay_method == 'rsqrt':\n return functools.partial(\n rsqrt_decay, warmup_steps=opt.warmup_steps)\n elif opt.start_decay_steps is not None:\n return functools.partial(\n exponential_decay,\n rate=opt.learning_rate_decay,\n decay_steps=opt.decay_steps,\n start_step=opt.start_decay_steps)\n else:\n return None",
"def learning_rate(self):\n return tf.placeholder(tf.float32, name=\"lr\")",
"def _add_weight_decay_regularizer(self):\n self.all_params = tf.trainable_variables()\n if self.weight_decay > 0:\n with tf.variable_scope('l2_loss'):\n l2_loss = tf.add_n([tf.nn.l2_loss(v) for v in self.all_params])\n self.loss += self.weight_decay * l2_loss",
"def exponentialDecay(self):\n\n lr = self._lr * pow(self._decay_rate, self._step / self._decay_steps)\n for param_group in self._optimizer.param_groups:\n param_group[\"lr\"] = lr",
"def alpha_decay(self):\n self.atomic_num -= 2\n self.isotope_num -= 2"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Fetches Distinct locations for selected biomimic type, country and state_province
|
def fetch_distinct_locations(self, query_dict):
cursor = self.connection.cursor()
query = """SELECT DISTINCT geo.location
FROM `cnx_logger` log
INNER JOIN `cnx_logger_biomimic_type` biotype
ON biotype.`biomimic_id`=log.`biomimic_id`
INNER JOIN `cnx_logger_geographics` geo
ON geo.`geo_id`=log.`geo_id` """
where_condition = self.build_where_condition(query_dict)
cursor.execute(query + where_condition + " ORDER BY 1 ASC")
result = cursor.fetchall()
final_result = [row[0] for row in result]
cursor.close()
count_records, min_date, max_date = self.fetch_metadata(query_dict)
return final_result, count_records, min_date, max_date
|
[
"def get_locations_choices():\n locations = [(loc.id, '%s, %s' % (loc.country.title(), loc.city.title()))\n for loc in db_queries.get_all_locations()]\n return locations",
"def all_locations(self) -> List[Tuple[str, str, str]]:\n query = \"\"\"\n SELECT\n DISTINCT coa_summary_view.site_name,\n coa_summary_view.town,\n coa_summary_view.county\n FROM coa.coa_summary_view\n \"\"\"\n with self.connection as cursor:\n cursor.execute(query)\n return cursor.fetchall()",
"def allCountries():",
"def geolocation(address):\n location = address[0]\n area = address[1]\n state = address[2]\n country = address[3]\n \n \n def country_search(country):\n if country != '':\n with open(countrycode_processed) as f:\n local_list = json.load(f)\n \n code_list, abbrv_list, name_list = [], [], []\n for i in range(len(local_list)):\n code_list.append(local_list[i][0])\n abbrv_list.append(local_list[i][1])\n name_list.append(local_list[i][2])\n \n adj_country_list = []\n for i in range(len(local_list)):\n if country in str(code_list[i]) or country in str(abbrv_list[i]) or country in str(name_list[i]):\n if code_list[i] not in adj_country_list:\n adj_country_list.append(code_list[i])\n \n if len(adj_country_list) > 1:\n fuzz_list = []\n for i in range(len(local_list)):\n if country in str(code_list[i]) or country in str(abbrv_list[i]) or country in str(name_list[i]):\n #print(name_list[i], code_list[i])\n name_fuzz = fuzz.ratio(str(country), str(name_list[i]))\n abbrv_fuzz = fuzz.ratio(country, abbrv_list[i])\n code_fuzz = fuzz.ratio(country, code_list[i])\n #print(name_fuzz, abbrv_fuzz, code_fuzz)\n fuzz_max = max([name_fuzz, abbrv_fuzz, code_fuzz])\n fuzz_list.append(fuzz_max)\n \n best_match = []\n for i in range(len(fuzz_list)):\n if fuzz_list[i] == max(fuzz_list):\n best_match.append(adj_country_list[i])\n \n adj_country_list = best_match\n \n else:\n adj_country_list = ['']\n \n #print(adj_country_list)\n return adj_country_list\n \n def state_search(state):\n if state != '':\n with open(admincode1_processed) as f:\n local_list = json.load(f)\n \n code_list, name_list1, name_list2 = [], [], []\n for i in range(len(local_list)):\n code_list.append(local_list[i][0])\n name_list1.append(local_list[i][1])\n name_list2.append(local_list[i][2])\n \n adj_state_list = []\n for i in range(len(local_list)):\n if state in str(code_list[i]) or state in str(name_list1[i]) or state in str(name_list2[i]):\n if code_list[i] not in adj_state_list:\n adj_state_list.append(code_list[i])\n else:\n adj_state_list = ['']\n \n #print(adj_state_list)\n return adj_state_list \n \n def area_search(area):\n if area != '':\n with open(admincode2_processed) as f:\n local_list = json.load(f)\n \n code_list, name_list1, name_list2 = [], [], []\n for i in range(len(local_list)):\n code_list.append(local_list[i][0])\n name_list1.append(local_list[i][1])\n name_list2.append(local_list[i][2])\n \n adj_area_list = []\n for i in range(len(local_list)):\n if area in str(code_list[i]) or area in str(name_list1[i]) or area in str(name_list2[i]):\n if code_list[i] not in adj_area_list:\n adj_area_list.append(code_list[i])\n else:\n adj_area_list = ['']\n \n #print(adj_area_list)\n return adj_area_list \n\n def location_search(location):\n if location != '':\n with open(cities500_processed) as f:\n local_list = json.load(f)\n \n possible_list = []\n for i in range(len(local_list)):\n if location in str(local_list[i][1]) or location in str(local_list[i][3]) or location in str(local_list[i][2]):\n possible_list.append(local_list[i])\n \n if possible_list == []:\n possible_list = ['']\n \n else:\n possible_list = ['']\n \n #print(possible_list)\n return possible_list \n\n \n #==============================start logic here\n country_list = country_search(country)\n if len(country_list) > 1:\n print(\"More than one country found return error.\")\n Exception\n \n possible_list = []\n\n if area == '' and state == '':\n possible_list.append(country_list[0])\n\n trial_list = [location, area, state]\n for item in trial_list:\n state_list = state_search(item)\n area_list = area_search(item)\n \n for item1 in state_list:\n if str(item1)[:2] == country_list[0]:\n possible_list.append(item1)\n\n for item2 in area_list:\n if str(item2)[:2] == country_list[0]:\n possible_list.append(item2) \n\n if possible_list == []:\n possible_list.append(country_list[0])\n \n with open(cities500_processed) as f:\n cities_list = json.load(f)\n \n #print(possible_list)\n positive_ids = []\n if location == '':\n for item in possible_list:\n code_list = item.split('.')\n criteria = len(code_list)\n for i in range(3-criteria):\n code_list.append('')\n \n \n for all_detail in cities_list:\n count = 0\n if all_detail[8] == code_list[0]:\n count += 1\n if all_detail[10] == code_list[1]:\n count += 1\n if all_detail[11] == code_list[2]:\n count += 1\n if count >= criteria:\n positive_ids.append(all_detail)\n \n else:\n location_list = location_search(location)\n if location_list == ['']:\n location_list = cities_list\n\n for item in possible_list:\n code_list = item.split('.')\n criteria = len(code_list)\n for i in range(3-criteria):\n code_list.append('')\n \n \n for all_detail in location_list:\n count = 0\n if all_detail[8] == code_list[0]:\n count += 1\n if all_detail[10] == code_list[1]:\n count += 1\n if all_detail[11] == code_list[2]:\n count += 1\n if count >= criteria:\n positive_ids.append(all_detail)\n \n lat_list, lon_list = [], []\n for all_detail in positive_ids:\n lat_list.append(float(all_detail[4]))\n lon_list.append(float(all_detail[5]))\n \n #print(positive_ids) \n lat = statistics.mean(lat_list)\n lon = statistics.mean(lon_list)\n \n return [lat, lon]",
"def test_get_loc_list_many(self):\n coupon = COUPON_FACTORY.create_coupon_many_locations(\n business_location_count=8)\n COUPON_FACTORY.normalize_coupon_locations(coupon)\n locations = coupon.location.all()\n display_location, display_city = coupon.get_location_string()\n LOG.debug('display_location: %s' % display_location)\n LOG.debug('display_city: %s' % display_city)\n LOG.debug('locations: %s' %\n [(loc.location_city, loc.location_state_province)\n for loc in locations])\n self.assertEqual(display_location, [\n locations[0].location_city,\n locations[1].location_city,\n locations[2].location_city,\n locations[3].location_city,\n locations[4].location_city,\n locations[5].location_city,\n locations[6].location_city,\n '%s, %s' % (locations[7].location_city,\n locations[7].location_state_province)])\n self.assertEqual(display_city, '%s, %s' % (\n locations[0].location_city, locations[0].location_state_province))",
"def location_combiner(city_name, country_name):\n\n # Initialize variables\n location = city_name + ', ' + country_name\n\n return location",
"def get_possible_municipalities(self):\n query = Municipality.all(keys_only=True)\n query.filter(\"province = \", self.division.province.kye())\n return query.fetch(500)",
"def get_all_locations(self, input_df):\n return set(pd.unique(input_df[self._LOCATION_COLUMN_NAME]))",
"def list_locations():",
"def pick_city(self):\n cities = {\"RM\": 4, \"VC\": 3, \"GD\": 2, \"BN\": 1}\n output = []\n for key, value in cities.items():\n try:\n city = self.driver.find_element_by_id(key)\n print(f\"{key} is a location to pick up\")\n output.append(key)\n except:\n print(f\"{key} is not location to pick up\")\n continue\n try:\n options = {key: cities[key] for key in output}\n chosen_location = max(options, key=options.get)\n except:\n print(\"No locations in the Lower Mainland (except for coquitlam)\")\n\n return chosen_location",
"def get_all_areas_and_associated_states(ss_client,sheet_id,column_filter_list = []):\n #first pass, grab all the areas and put in list, then remove duplicates\n temp_area_list = []\n sheet = ss_client.Sheets.get_sheet(sheet_id, column_ids=column_filter_list) \n for row in sheet.rows:\n temp_area_list.append(str(row.cells[0].value))\n area_list = list(set(temp_area_list))\n\n #prep data structure\n temp_dict = {}\n for area in area_list:\n #temp_dict looks like: {\"south\":[],\"west\":[]}\n temp_dict[area] = []\n\n #second pass, append all states to their associated area and remove duplicates\n for row in sheet.rows:\n temp_dict[str(row.cells[0].value)].append(str(row.cells[1].value))\n #print(f\"Data from sheets: key: {str(row.cells[0].value)} value: {str(row.cells[1].value)}\")\n #Looks like: Data from sheets: key: East value: Maryland\n #print(f\"Temp dict items: {temp_dict}\")\n #Looks like: Temp dict items: {'All': ['Nevada', '--', '--', 'District of Columbia (DC)', 'California'],...\n area_dict = {}\n for key, value in temp_dict.items():\n value = process_state_codes(value,reverse=True)\n area_dict[key] = value\n #print(f\"Final area_dict: {area_dict}\")\n return area_dict",
"def copy_places():\r\n\r\n cities = []\r\n countries = []\r\n states = []\r\n subregions = []\r\n regions = []\r\n for place in Region.objects.all():\r\n plural_names, additional_keywords, abbreviations= same_attributes(place)\r\n array = {\r\n \"name\": place.name,\r\n \"plural_names\": plural_names,\r\n \"additional_keywords\": additional_keywords,\r\n \"abbreviations\": abbreviations,\r\n \"place_id\": place.place_id\r\n }\r\n regions.append(array)\r\n for place in Subregion.objects.all():\r\n plural_names, additional_keywords, abbreviations= same_attributes(place)\r\n array = {\r\n \"name\": place.name,\r\n \"plural_names\": plural_names,\r\n \"additional_keywords\": additional_keywords,\r\n \"abbreviations\": abbreviations,\r\n \"place_id\": place.place_id,\r\n \"region\": place.region.name\r\n }\r\n subregions.append(array)\r\n for place in Country.objects.all():\r\n plural_names, additional_keywords, abbreviations= same_attributes(place)\r\n array = {\r\n \"name\": place.name,\r\n \"plural_names\": plural_names,\r\n \"additional_keywords\": additional_keywords,\r\n \"abbreviations\": abbreviations,\r\n \"place_id\": place.place_id,\r\n \"region\": place.region.name\r\n }\r\n if place.subregion:\r\n array[\"subregion\"] = place.subregion.name\r\n countries.append(array)\r\n for place in State.objects.all():\r\n plural_names, additional_keywords, abbreviations= same_attributes(place)\r\n array = {\r\n \"name\": place.name,\r\n \"plural_names\": plural_names,\r\n \"additional_keywords\": additional_keywords,\r\n \"abbreviations\": abbreviations,\r\n \"place_id\": place.place_id,\r\n \"region\": place.region.name,\r\n \"country\": place.country.name\r\n }\r\n if place.subregion:\r\n array[\"subregion\"] = place.subregion.name\r\n states.append(array)\r\n for place in City.objects.all():\r\n plural_names, additional_keywords, abbreviations= same_attributes(place)\r\n array = {\r\n \"name\": place.name,\r\n \"plural_names\": plural_names,\r\n \"additional_keywords\": additional_keywords,\r\n \"abbreviations\": abbreviations,\r\n \"place_id\": place.place_id,\r\n \"region\": place.region.name,\r\n \"country\": place.country.name\r\n }\r\n if place.subregion:\r\n array[\"subregion\"] = place.subregion.name\r\n if place.state:\r\n array[\"state\"] = place.state.name\r\n if place.iata:\r\n array[\"iata\"] = place.iata\r\n else:\r\n array[\"iata\"] = []\r\n cities.append(array)\r\n mass_array = {\r\n \"regions\": regions,\r\n \"subregions\": subregions,\r\n \"countries\": countries,\r\n \"states\": states,\r\n \"cities\": cities}\r\n with open('places.JSON','w') as fi:\r\n json.dump(mass_array, fi)\r\n return mass_array",
"def get_neighborhoods(state):\n\n neighborhoods = set()\n \n listings = Listing.query.filter(Listing.address.like('%{}%'.format(state))).all()\n for listing in listings: \n neighborhoods.add(listing.neighborhood)\n\n return neighborhoods",
"def test_geocode_city_state(self):\n self._select_geocoder()\n resource = GeocoderResource()\n req = HttpRequest()\n req.method = 'GET'\n req.GET['q'] = \"golden, co\"\n bundle = resource.build_bundle(request=req)\n results = resource.obj_get_list(bundle)\n self.assertApxEqual(results[0].lat, 39.756655, .001) \n self.assertApxEqual(results[0].lng, -105.224949, .001)",
"def test_form_select_state_province(self):\n self.check_ajax(\"state_province\", \"DummyState\", self.db.fetch_distinct_locations)",
"def test_get_loc_list_one(self):\n coupon = COUPON_FACTORY.create_coupon()\n location = coupon.location.all()[0]\n display_location, display_city = coupon.get_location_string()\n string = '%s, %s' % (location.location_city,\n location.location_state_province)\n self.assertEqual(display_location, [string])\n self.assertEqual(display_city, string)",
"def get_locations(input_file, output_file):\n with zipfile.ZipFile(input_file, 'r') as z:\n for filename in z.namelist():\n with z.open(filename) as f:\n json_list = json.load(f)\n\n state_locations = _generate_state_dictionary()\n location_dict = {}\n for item in json_list:\n location_dict[item['id']] = re.split(r'[`\\-=~!@#$%^&*()_+\\[\\]{};\\'\\\\:\"|<,./<>?]', item['location'].lower())\n state_flag = 0\n us_flag = 0\n cnt = 0\n for user_id in location_dict:\n for item in location_dict[user_id]:\n for state in state_locations:\n if item == state:\n location_dict[user_id] = state\n state_flag = 1\n break\n if state_flag == 1:\n break\n if state_flag == 0:\n for item in location_dict[user_id]:\n for state in state_locations:\n if item.strip() in state_locations[state]:\n location_dict[user_id] = state\n state_flag = 1\n break\n if state_flag == 1:\n break\n if state_flag == 1:\n state_flag = 0\n else:\n for item in location_dict[user_id]:\n if item.strip() == 'us' or item.strip() == 'usa' or item.strip() == 'united states':\n location_dict[user_id] = 'usa'\n us_flag = 1\n break\n if us_flag == 1:\n us_flag = 0\n else:\n location_dict[user_id] = 'N/A'\n cnt += 1\n\n with open(output_file, 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['user_id', 'location'])\n for data in location_dict:\n writer.writerow([data, location_dict[data]])",
"def _geo_places(self, places, min_popln):\n loclist = {}\n #kwargs = {}\n if 'country' in places:\n cstr = places['country'].strip()\n country = self.gazetteer._querycountry(cstr)\n if country == []:\n country = self.gazetteer.query(cstr.lower(), featureCode='pcli')\n\n loclist[cstr] = country\n #cc2 = country.get(\"ISO\", country.get('countryCode')).lower()\n #kwargs = {'countryCode': cc2}\n\n if 'twitter_country_code' in places:\n loclist[places['twitter_country_code']] = CountryDB.fromISO(places['twitter_country_code'])\n if loclist[places['twitter_country_code']]:\n loclist[places['twitter_country_code']] = [GeoPoint(**loclist[places['twitter_country_code']])]\n\n if 'name' in places:\n loclist[places['name']] = self.gazetteer.query(places['name'].lower(),\n min_popln=min_popln,\n analyzer='standard')\n\n if 'full_name' in places:\n for tmp in RE_SPLIT.split(places['full_name']):\n if tmp not in loclist:\n loclist[tmp] = self.gazetteer.query(tmp, min_popln=min_popln,\n analyzer='standard')\n\n if 'displayName' in places:\n for tmp in RE_SPLIT.split(places['displayName']):\n if tmp not in loclist:\n loclist[tmp] = self.gazetteer.query(tmp, min_popln=min_popln,\n analyzer='standard')\n\n return self.get_geoPoints_intersection(loclist, min_popln)",
"def get_location_by_filter(self, **kwargs):\n\n all_params = ['filter', 'page', 'limit', 'sort']\n all_params.append('callback')\n\n params = locals()\n for key, val in iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method get_location_by_filter\" % key\n )\n params[key] = val\n del params['kwargs']\n\n\n resource_path = '/beta/location/search'.replace('{format}', 'json')\n path_params = {}\n\n query_params = {}\n if 'filter' in params:\n query_params['filter'] = params['filter']\n if 'page' in params:\n query_params['page'] = params['page']\n if 'limit' in params:\n query_params['limit'] = params['limit']\n if 'sort' in params:\n query_params['sort'] = params['sort']\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.\\\n select_header_accept(['application/json'])\n if not header_params['Accept']:\n del header_params['Accept']\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.\\\n select_header_content_type([])\n\n # Authentication setting\n auth_settings = ['api_key']\n\n response = self.api_client.call_api(resource_path, 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='list[Location]',\n auth_settings=auth_settings,\n callback=params.get('callback'))\n return response"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Fetches Distinct Subzones for selected biomimic type, country, state_province, location and zones
|
def fetch_distinct_sub_zones(self, query_dict):
cursor = self.connection.cursor()
query = """SELECT DISTINCT prop.sub_zone
FROM `cnx_logger` log
INNER JOIN `cnx_logger_biomimic_type` biotype
ON biotype.`biomimic_id`=log.`biomimic_id`
INNER JOIN `cnx_logger_geographics` geo
ON geo.`geo_id`=log.`geo_id`
INNER JOIN `cnx_logger_properties` prop
ON prop.`prop_id`=log.`prop_id` """
where_condition = self.build_where_condition(query_dict)
cursor.execute(query + where_condition + " ORDER BY 1 ASC")
result = cursor.fetchall()
final_result = ['N/A' if row[0] is None else row[0] for row in result]
cursor.close()
count_records, min_date, max_date = self.fetch_metadata(query_dict)
return final_result, count_records, min_date, max_date
|
[
"def _fetch_all_zones(self):\n query = tables.zones.select()\n return self.storage.session.execute(query).fetchall()",
"def allCountries():",
"def subdivisions(self, *args, search_term=None, ordering='name'):\n return CountrySubdivision.list_for_country(\n country_code=self.alpha_2,\n search_term=search_term,\n ordering=ordering\n )",
"def iterate_zones(self):\r\n return self._get_more('zones')",
"def copy_places():\r\n\r\n cities = []\r\n countries = []\r\n states = []\r\n subregions = []\r\n regions = []\r\n for place in Region.objects.all():\r\n plural_names, additional_keywords, abbreviations= same_attributes(place)\r\n array = {\r\n \"name\": place.name,\r\n \"plural_names\": plural_names,\r\n \"additional_keywords\": additional_keywords,\r\n \"abbreviations\": abbreviations,\r\n \"place_id\": place.place_id\r\n }\r\n regions.append(array)\r\n for place in Subregion.objects.all():\r\n plural_names, additional_keywords, abbreviations= same_attributes(place)\r\n array = {\r\n \"name\": place.name,\r\n \"plural_names\": plural_names,\r\n \"additional_keywords\": additional_keywords,\r\n \"abbreviations\": abbreviations,\r\n \"place_id\": place.place_id,\r\n \"region\": place.region.name\r\n }\r\n subregions.append(array)\r\n for place in Country.objects.all():\r\n plural_names, additional_keywords, abbreviations= same_attributes(place)\r\n array = {\r\n \"name\": place.name,\r\n \"plural_names\": plural_names,\r\n \"additional_keywords\": additional_keywords,\r\n \"abbreviations\": abbreviations,\r\n \"place_id\": place.place_id,\r\n \"region\": place.region.name\r\n }\r\n if place.subregion:\r\n array[\"subregion\"] = place.subregion.name\r\n countries.append(array)\r\n for place in State.objects.all():\r\n plural_names, additional_keywords, abbreviations= same_attributes(place)\r\n array = {\r\n \"name\": place.name,\r\n \"plural_names\": plural_names,\r\n \"additional_keywords\": additional_keywords,\r\n \"abbreviations\": abbreviations,\r\n \"place_id\": place.place_id,\r\n \"region\": place.region.name,\r\n \"country\": place.country.name\r\n }\r\n if place.subregion:\r\n array[\"subregion\"] = place.subregion.name\r\n states.append(array)\r\n for place in City.objects.all():\r\n plural_names, additional_keywords, abbreviations= same_attributes(place)\r\n array = {\r\n \"name\": place.name,\r\n \"plural_names\": plural_names,\r\n \"additional_keywords\": additional_keywords,\r\n \"abbreviations\": abbreviations,\r\n \"place_id\": place.place_id,\r\n \"region\": place.region.name,\r\n \"country\": place.country.name\r\n }\r\n if place.subregion:\r\n array[\"subregion\"] = place.subregion.name\r\n if place.state:\r\n array[\"state\"] = place.state.name\r\n if place.iata:\r\n array[\"iata\"] = place.iata\r\n else:\r\n array[\"iata\"] = []\r\n cities.append(array)\r\n mass_array = {\r\n \"regions\": regions,\r\n \"subregions\": subregions,\r\n \"countries\": countries,\r\n \"states\": states,\r\n \"cities\": cities}\r\n with open('places.JSON','w') as fi:\r\n json.dump(mass_array, fi)\r\n return mass_array",
"def _load_time_zones_per_country(self):\n pg.cur.execute(\"\"\"\n SELECT countries.geonameid, time_zones_per_country.name\n FROM time_zones_per_country\n INNER JOIN countries\n ON time_zones_per_country.ISO2=countries.ISO2\n \"\"\")\n timezones = dd(set)\n for geonameid, time_zone_loc_name in pg.cur.fetchall():\n timezones[geonameid].add(time_zone_loc_name)\n return dict(timezones)",
"def test_form_Zone_name_select(self):\n self.check_ajax(\"sub_zone\", \"DummyZoneType\", self.db.fetch_distinct_sub_zones)",
"def get_sub_pages(self):\n return self.country_set.all()",
"def pull_zones(*args, **kwargs):\n zones = api_call('/zones').json()\n for zone in zones:\n print(bcolors.HEADER + \"== Zone {zone[name]} [{zone[uuid]}] ==\".format(zone=zone) + bcolors.ENDC)\n\n # Retrieve the records for this zone\n records_response = api_call(zone['zone_records_href'], headers={'Accept': 'text/plain'})\n print(\"\\tWriting... \", end='')\n\n # Save the records in a file\n filename = \"{zone[name]}_{zone[uuid]}.txt\".format(zone=zone)\n with open(ZONES_FOLDER + filename, 'w') as records_file:\n records_file.write(records_response.content.decode('utf-8'))\n print(\"{bcolors.OKGREEN}done{bcolors.ENDC} ({fn})\".format(fn=filename, bcolors=bcolors))\n\n print(\"\\n\" + bcolors.OKBLUE + \"Written all zones in \" + ZONES_FOLDER + bcolors.ENDC)",
"def list_zones(self):\r\n return list(self.iterate_zones())",
"def get_subregions(self) -> List[str]:\r\n return sorted([subregion for subregion in self._regional_groups['sub-region']])",
"def ex_list_zones(self):\r\n list_zones = []\r\n request = '/zones'\r\n response = self.connection.request(request, method='GET').object\r\n list_zones = [self._to_zone(z) for z in response['items']]\r\n return list_zones",
"def test_form_select_zone_name(self):\n self.check_ajax(\"zone\", \"DummyZone\", self.db.fetch_distinct_sub_zones)",
"def getCountries():\n return loadJson(BASE_URL_COUNTRY, limit=0)['objects']",
"def list(cls, api_client, **kwargs):\n\n cmd = {}\n cmd.update(kwargs)\n if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():\n cmd['listall'] = True\n return super(Zone, cls).list(api_client.listZones(**cmd).get('zone'))",
"def retrieve_zones_dyn(zone=None):\n zone_data = {}\n if zone is not None:\n dyn_zones = [Zone(zone)]\n else:\n dyn_zones = get_all_zones()\n\n secondary_zones = get_all_secondary_zones()\n sec_zone_map = {}\n for sec_zone in secondary_zones:\n sec_zone_map[sec_zone.zone] = \"Secondary\"\n\n\n for i, single_zone in enumerate(dyn_zones):\n if single_zone.name in sec_zone_map:\n del dyn_zones[i]\n else:\n try:\n #node_records = Node(node.zone, node.fqdn).get_all_records()\n zone_records = single_zone.get_all_records()\n #print(zone_records)\n if zone_records and single_zone.name not in sec_zone_map:\n all_recs = {}\n for rec in zone_records:\n zone_rec = {}\n zone_rec['resource_recs'] = []\n for rec_type in zone_records[rec]:\n if rec_type.fqdn not in all_recs:\n all_recs[rec_type.fqdn] = {}\n if rec_type.rec_name not in all_recs[rec_type.fqdn]:\n all_recs[rec_type.fqdn][rec_type.rec_name] = {}\n all_recs[rec_type.fqdn][rec_type.rec_name]['type'] = rec_type.rec_name.upper()\n all_recs[rec_type.fqdn][rec_type.rec_name]['name'] = rec_type.fqdn\n type = rec_type.rec_name.upper()\n if type == \"PTR\":\n rrec = rec_type.ptrdname\n elif type == \"CNAME\":\n rrec = rec_type.cname\n elif type == \"TXT\":\n rrec = \"\\\"\" + rec_type.txtdata + \"\\\"\"\n elif type == \"MX\":\n rrec = str(rec_type.preference) + \" \" + rec_type.exchange\n elif type == \"SRV\":\n srv_string = str(rec_type.priority) + \" \" + str(rec_type.weight) + \" \" + str(rec_type.port) + \\\n \" \" + str(rec_type.target)\n rrec = srv_string\n elif type == \"SPF\":\n rrec = \"\\\"\" + rec_type.txtdata + \"\\\"\"\n elif type == \"ALIAS\":\n rrec = rec_type.alias\n elif type == \"SOA\":\n rrec = rec_type.rname\n elif type == \"NS\":\n rrec = rec_type.nsdname\n else:\n rrec = rec_type.address\n if 'resource_recs' in all_recs[rec_type.fqdn][rec_type.rec_name]:\n all_recs[rec_type.fqdn][rec_type.rec_name]['resource_recs'].append(rrec)\n else:\n all_recs[rec_type.fqdn][rec_type.rec_name]['resource_recs'] = [rrec]\n\n all_recs[rec_type.fqdn][rec_type.rec_name]['ttl'] = rec_type._ttl\n for node in all_recs:\n for record_type in all_recs[node]:\n if single_zone.name not in zone_data:\n zone_data[single_zone.name] = [all_recs[node][record_type]]\n else:\n zone_data[single_zone.name].append(all_recs[node][record_type])\n except Exception as e:\n print(e)\n return zone_data",
"def test_form_select_sub_zone_name(self):\n self.check_ajax(\"sub_zone\", \"DummySubZone\", self.db.fetch_distinct_wave_exposures)",
"def get_sub_info(request):\n obj_id = request.GET.get('obj_id')\n sc_type = request.GET.get('type') # Category, State, City, District\n rndr_str = '<option value=\"\">-Select-</option>'\n\n if sc_type == 'category':\n for cc in Category.objects.filter(parent__id=obj_id).order_by('name'):\n if cc.category_set.all():\n rndr_str += '<option value=\"\" disabled>{}</option>'.format(cc.name) \n for sc in cc.category_set.all():\n rndr_str += '<option value=\"{}\"> {}</option>'.format(sc.id, sc.name) \n else:\n rndr_str += '<option value=\"{}\">{}</option>'.format(cc.id, cc.name) \n objects = []\n elif sc_type == 'state':\n objects = State.objects.filter(country__id=obj_id)\n elif sc_type == 'city':\n objects = City.objects.filter(state__id=obj_id, district__isnull=True)\n else:\n objects = City.objects.filter(district_id=obj_id)\n \n for sc in objects:\n rndr_str += '<option value=\"{}\">{}</option>'.format(sc.id, sc.name)\n return HttpResponse(rndr_str)",
"def get_zones():\n zonefld = Globals.app.GetDataFolder(\"ElmZone\")\n zones = zonefld.GetContents()\n #for zone in zones:\n #Globals.app.PrintPlain(zone)\n return zones"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Fetches Distinct Wave Exp for selected biomimic type, country, state_province, location, zones and sub_zones
|
def fetch_distinct_wave_exposures(self, query_dict):
cursor = self.connection.cursor()
query = """SELECT DISTINCT prop.wave_exp FROM `cnx_logger` log
INNER JOIN `cnx_logger_biomimic_type` biotype
ON biotype.`biomimic_id`=log.`biomimic_id`
INNER JOIN `cnx_logger_geographics` geo
ON geo.`geo_id`=log.`geo_id`
INNER JOIN `cnx_logger_properties` prop
ON prop.`prop_id`=log.`prop_id`"""
where_condition = self.build_where_condition(query_dict)
cursor.execute(query + where_condition + " ORDER BY 1 ASC")
result = cursor.fetchall()
final_result = ['N/A' if row[0] is None else row[0] for row in result]
cursor.close()
count_records, min_date, max_date = self.fetch_metadata(query_dict)
return final_result, count_records, min_date, max_date
|
[
"def get_observations(self):\n self.config.validate()\n log.info(\"Fetching observations.\")\n datastore_path = make_path(self.settings[\"observations\"][\"datastore\"])\n if datastore_path.is_file():\n datastore = DataStore().from_file(datastore_path)\n elif datastore_path.is_dir():\n datastore = DataStore().from_dir(datastore_path)\n else:\n raise FileNotFoundError(f\"Datastore {datastore_path} not found.\")\n ids = set()\n selection = dict()\n for criteria in self.settings[\"observations\"][\"filters\"]:\n selected_obs = ObservationTable()\n\n # TODO: Reduce significantly the code.\n # This block would be handled by datastore.obs_table.select_observations\n selection[\"type\"] = criteria[\"filter_type\"]\n for key, val in criteria.items():\n if key in [\"lon\", \"lat\", \"radius\", \"border\"]:\n val = Angle(val)\n selection[key] = val\n if selection[\"type\"] == \"angle_box\":\n selection[\"type\"] = \"par_box\"\n selection[\"value_range\"] = Angle(criteria[\"value_range\"])\n if selection[\"type\"] == \"sky_circle\" or selection[\"type\"].endswith(\"_box\"):\n selected_obs = datastore.obs_table.select_observations(selection)\n if selection[\"type\"] == \"par_value\":\n mask = (\n datastore.obs_table[criteria[\"variable\"]] == criteria[\"value_param\"]\n )\n selected_obs = datastore.obs_table[mask]\n if selection[\"type\"] == \"ids\":\n obs_list = datastore.get_observations(criteria[\"obs_ids\"])\n selected_obs[\"OBS_ID\"] = [obs.obs_id for obs in obs_list.list]\n if selection[\"type\"] == \"all\":\n obs_list = datastore.get_observations()\n selected_obs[\"OBS_ID\"] = [obs.obs_id for obs in obs_list.list]\n\n if len(selected_obs):\n if \"exclude\" in criteria and criteria[\"exclude\"]:\n ids.difference_update(selected_obs[\"OBS_ID\"].tolist())\n else:\n ids.update(selected_obs[\"OBS_ID\"].tolist())\n self.observations = datastore.get_observations(ids, skip_missing=True)\n for obs in self.observations.list:\n log.info(obs)",
"def fetch_distinct_sub_zones(self, query_dict):\n cursor = self.connection.cursor()\n query = \"\"\"SELECT DISTINCT prop.sub_zone\n FROM `cnx_logger` log\n INNER JOIN `cnx_logger_biomimic_type` biotype\n ON biotype.`biomimic_id`=log.`biomimic_id`\n INNER JOIN `cnx_logger_geographics` geo\n ON geo.`geo_id`=log.`geo_id`\n INNER JOIN `cnx_logger_properties` prop\n ON prop.`prop_id`=log.`prop_id` \"\"\"\n where_condition = self.build_where_condition(query_dict)\n cursor.execute(query + where_condition + \" ORDER BY 1 ASC\")\n result = cursor.fetchall()\n final_result = ['N/A' if row[0] is None else row[0] for row in result]\n cursor.close()\n count_records, min_date, max_date = self.fetch_metadata(query_dict)\n return final_result, count_records, min_date, max_date",
"def _get_all_wai_wells():\n # there are some wells where the flux is greater than the CAV;\n # however these are rather minor, moslty in Selwyn, and most could be true.\n mike = pd.read_hdf(\"{}/m_ex_bd_inputs/sd_est_all_mon_vol.h5\".format(smt.sdp))\n mike = mike.loc[(mike.time >= pd.datetime(2008, 1, 1)) & (mike.take_type == 'Take Groundwater')]\n mike.loc[:, 'd_in_m'] = mike.time.dt.daysinmonth\n data = mike.groupby('wap').aggregate(\n {'usage_est': np.sum, 'crc': ','.join, 'd_in_m': np.sum, 'mon_allo_m3': np.sum})\n data.loc[:, 'flux'] = data.loc[:, 'usage_est'] / (mike.time.max() - pd.datetime(2007, 12, 31)).days\n data.loc[:, 'cav_flux'] = data.loc[:, 'mon_allo_m3'] / (mike.time.max() - pd.datetime(2007, 12, 31)).days\n\n well_details = rd_sql(**sql_db.wells_db.well_details)\n well_details = well_details.set_index('WELL_NO')\n out_data = pd.merge(data, pd.DataFrame(well_details.loc[:, 'WMCRZone']), left_index=True, right_index=True)\n out_data = out_data.loc[np.in1d(out_data.WMCRZone, [4, 7, 8])]\n out_data.loc[:, 'cwms'] = out_data.loc[:, 'WMCRZone'].replace({7: 'chch', 8: 'selwyn', 4: 'waimak'})\n out_data = out_data.drop('WMCRZone', axis=1)\n\n out_data['type'] = 'well'\n out_data = add_use_type(out_data)\n\n # set WDC (waimak and other usage) wells to 10% of CAV\n idx = (out_data.cwms == 'waimak') & (out_data.use_type == 'other')\n out_data.loc[idx, 'flux'] = out_data.loc[\n idx, 'cav_flux'] * 0.25 # this comes from average of the WDC CAV vs usage made before my time I also confirmed with colin as WDC that this is about right\n\n out_data.loc[:, 'flux'] *= -1\n\n out_data['consent'] = [tuple(e.split(',')) for e in out_data.loc[:, 'crc']]\n out_data = out_data.drop('crc', axis=1)\n out_data = out_data.dropna()\n\n out_data.loc[out_data.cwms == 'waimak', 'zone'] = 'n_wai'\n out_data.loc[~(out_data.cwms == 'waimak'), 'zone'] = 's_wai'\n out_data.index.names = ['well']\n\n return out_data",
"def allCountries():",
"def download_country_data():\n url = 'https://www.worldometers.info/world-population/population-by-country/'\n populations = requests.get(url)\n populations.raise_for_status()\n return BeautifulSoup(populations.text, 'html.parser')",
"def test_obs_waveform_get(external_getter, code):\n net, sta, loc, cha = code.split('.')\n\n st = external_getter.obs_waveform_get(code)\n assert(len(st) == 3)\n\n stats = st.select(component=\"Z\")[0].stats\n assert stats.network == net\n assert stats.station == sta",
"def data_retriever(self):\n\n sql_st = '''\n SELECT *\n FROM geo_expense_data\n '''\n cur = self.conn.cursor()\n geo_comp_data = cur.execute(sql_st).fetchall()\n\n for record in geo_comp_data:\n geo_expense_id = record[0]\n year = record[2]\n month = record[3]\n day = record[4]\n comp_name = record[5]\n country = record[6]\n city = record[7]\n state = record[9]\n lat = record[11]\n lng = record[12]\n goog_details = self.company_type(comp_name,lat,lng)\n\n locations = self.locations_visited(year,month,day)\n # Find distance matrix between locations and visited places\n # Generate matrix n_location by n_goog_records\n # Should probably look to add some heuristic for name match\n if len(goog_details) == 0:\n sql_record = (geo_expense_id,'','','','','','')\n elif type(goog_details[0]) == dict:\n dist_array = np.zeros((len(locations),len(goog_details)))\n for i in range(len(locations)):\n loc_lat = locations[i][0]\n loc_lng = locations[i][1]\n for j in range(len(goog_details)):\n goog_lat = goog_details[j]['geometry']['location']['lat']\n goog_lng = goog_details[j]['geometry']['location']['lng']\n\n dist_array[i,j] = self.distance(goog_lat,goog_lng,loc_lat,loc_lng)\n\n min_dist_idx = np.argmin(dist_array)\n m = min_dist_idx // dist_array.shape[1]\n n = min_dist_idx - dist_array.shape[1] * m\n comp_type = goog_details[n]['types'][0]\n goog_name = goog_details[n]['name']\n address = goog_details[n]['formatted_address']\n placeid = goog_details[n]['place_id']\n goog_lat = goog_details[n]['geometry']['location']['lat']\n goog_lng = goog_details[n]['geometry']['location']['lng']\n\n sql_record = (geo_expense_id,goog_name,comp_type,address,placeid,goog_lat,goog_lng)\n else:\n comp_type = goog_details[0]\n sql_record = (geo_expense_id,'',comp_type,'','','','')\n\n self.data_writer(sql_record)",
"def get_data():\n points = get_alameda_county_points()\n return filter_ranson_criteria(clean_data(get_weather_data(points)))",
"def extract_owid(file):\n # Open, country-filter & relevant column-filer data\n data = pd.read_csv(file, sep=\",\",header=0)\n data = data[data['iso_code'] == 'FRA']\n cols = ['date', 'total_cases', 'total_deaths', 'stringency_index', \n 'population','gdp_per_capita',\n 'cvd_death_rate', 'diabetes_prevalence', 'female_smokers',\n 'male_smokers', 'hospital_beds_per_thousand']\n # Drop unnecesary columns\n data = data.drop([c for c in data.columns if c not in cols], axis=1)\n # Get single-valued columns to return as country attribute\n uniques = unique_columns(data)\n attrs = {}\n for col in uniques:\n attrs[col] = data[col].iloc[0]\n # Drop single-valued columns\n data = data.drop(uniques, axis=1)\n return data, attrs",
"def getCountries():\n return loadJson(BASE_URL_COUNTRY, limit=0)['objects']",
"def _query_samples(self, filter, orderby, limit):\n return self.clients(\"ceilometer\").query_samples.query(\n filter, orderby, limit)",
"def _feature_country_process(self):\n if 'Country' not in self.df_invoice.columns:\n return\n\n list_countries_keep = ['United Kingdom']\n rows_before = self.df_invoice.shape[0]\n \n df_invoice_new = pd.DataFrame()\n for country in list_countries_keep : \n df_invoice_new = df_invoice_new.append(\\\n self._df_invoice[self.df_invoice['Country']==country]\\\n , ignore_index=True)\n\n self.df_invoice = df_invoice_new\n del(df_invoice_new)\n \n rows_after = self._df_invoice.shape[0] \n P5_SegmentClassifier.print_stat_rows(\"Countries filtering : \"\\\n , rows_before, rows_after)\n\n \n #-------------------------------------------------------------------------\n # Due to the fact only one country is used, then this feature is dropped\n #-------------------------------------------------------------------------\n list_col_to_keep = [col for col in self._df_invoice.columns \\\n if col not in 'Country']\n \n self._df_invoice = self._df_invoice[list_col_to_keep] \n\n return",
"def get_data(disaster_type):\n disaster_names = driver.find_elements_by_css_selector(\"h4.title a\")\n # Check whether there are disasters found\n if len(disaster_names) > 0:\n # Create objects to retreive country and amount of countries\n disaster_countries = driver.find_elements_by_css_selector(\"dd.country a\")\n multiple_countries = driver.find_elements_by_css_selector(\"dt.country\")\n for (name, country, more) in itertools.zip_longest(disaster_names, disaster_countries,\n multiple_countries):\n d_name = name.text\n d_date = get_date(d_name)\n # If there are multiple countries affected for a given disaster, visit disaster page (via get_all_countries)\n if more.text == \"Affected countries\":\n try:\n d_countries = get_all_countries(name.get_attribute(\"href\"))\n # For every country write a line in a csv file (via write_to_csv)\n for element in d_countries:\n write_to_csv(d_name, d_date, disaster_type, element)\n except NoSuchElementException:\n print(\"Error occurred in multiple countries function for: \" + d_name)\n else:\n try:\n # Write a line in csv file for given disaster\n d_country = country.text\n write_to_csv(d_name, d_date, disaster_type, d_country)\n except NoSuchElementException:\n print(\"Error occurred in single countries function for: \" + d_name)\n else:\n print(\"No disasters found in this category\")",
"def test_country_query_filter_by_iso(self):\n url = get_country_url_with_filters({'iso': 'NL'})\n\n response = self.client.get(url)\n\n object_list = response.context.get('object_list', None)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertTemplateUsed(response, 'country_list.html')\n self.assertEqual(len(object_list), 1)\n self.assertEqual(object_list[0]['name'], 'Netherlands')",
"def _subset_by_area(self, country, province):\n df = self._cleaned_df.copy()\n return df.loc[(df[self.COUNTRY] == country) & (df[self.PROVINCE] == province)]",
"def get_from_oilbase(self,engine, wells:list=None, fields:list=None):\n \n \n well_heads_query= \"\"\"\n select w.well, w.surface_x, w.surface_y, w.epsg, w.kbe\n from list.wells w\n join list.fields f on w.field_id = f.id\n \"\"\"\n\n well_surveys_query= \"\"\"\n select w.well, s.md, s.inc, s.azi\n from list.surveys s\n join list.wells w on s.well_id = w.id\n join list.fields f on w.field_id = f.id\n \"\"\"\n\n well_perforations_query= \"\"\"\n select w.well, p.md_top, p.md_bottom, fm.formation\n from list.perforations p\n join list.wells w on p.well_id = w.id\n join list.fields f on w.field_id = f.id\n join list.formations fm on p.formation_id = fm.id\n \"\"\"\n\n well_formations_tops_query= \"\"\"\n select w.well, ft.md_top, ft.md_bottom, fm.formation\n from list.formations_tops ft\n join list.wells w on ft.well_id = w.id\n join list.fields f on w.field_id = f.id\n join list.formations fm on ft.formation_id = fm.id\n \"\"\"\n\n well_units_tops_query = \"\"\"\n select w.well, ut.md_top, ut.md_bottom, u.unit, fm.formation\n from list.units_tops ut\n join list.units u on ut.unit_id = u.id \n join list.formations fm on u.formation_id = fm.id\n join list.wells w on ut.well_id = w.id\n join list.fields f on w.field_id = f.id\n \"\"\"\n\n #Custom the query\n query_list = {\n 'well_heads':well_heads_query,\n 'well_surveys': well_surveys_query,\n 'well_perforations':well_perforations_query,\n 'well_formations_tops':well_formations_tops_query,\n 'well_units_tops':well_units_tops_query\n }\n\n if wells is not None:\n assert isinstance(wells,(str,list))\n\n for i in query_list:\n query_list[i] = query_list[i] + f\" where w.well in {tuple(wells)}\".replace(',)',')')\n\n\n if fields is not None:\n assert isinstance(fields,(str,list))\n\n if wells is None:\n for i in query_list:\n query_list[i] = query_list[i] + f\" where f.field in {tuple(fields)}\".replace(',)',')')\n else:\n for i in query_list:\n query_list[i] = query_list[i] + f\" and f.field in {tuple(fields)}\".replace(',)',')')\n\n\n # query from oilbase\n df_dict = {}\n for i in query_list:\n try:\n _df = pd.read_sql(query_list[i], con=engine)\n df_dict[i] = _df\n except:\n df_dict[i] = None\n \n #List of wells\n wells_list = df_dict['well_heads']['well'].tolist()\n\n #Create wells object\n for i in wells_list:\n #Perforations\n _p = df_dict['well_perforations']\n try:\n _perf = perforations(_p.loc[_p['well']==i,['md_top','md_bottom','formation']])\n if _perf.empty:\n _perf = None\n except:\n _perf = None \n \n #Tops\n _t = df_dict['well_formations_tops']\n\n try:\n _tops = tops(_t.loc[_t['well']==i,:])\n if _tops.empty:\n _tops = None\n except:\n _tops = None\n\n #units\n _u = df_dict['well_units_tops']\n\n try:\n _units = tops(_u.loc[_u['well']==i,:])\n if _units.empty:\n _units = None\n except:\n _units = None\n\n #surveys\n _s = df_dict['well_surveys']\n\n try:\n _survey = _s.loc[_s['well']==i,['md','inc','azi']].sort_values(by='md', ascending=True)\n\n if _survey.empty:\n _survey = None\n except:\n _survey = None\n \n _wh = df_dict['well_heads']\n _rte = _wh.loc[_wh['well']==i,'kbe'].iloc[0]\n _crs = _wh.loc[_wh['well']==i,'epsg'].iloc[0]\n _surf_coord = _wh.loc[_wh['well']==i,['surface_x','surface_y']].squeeze().tolist()\n \n _surf_coord = None if any([i is None for i in _surf_coord]) else _surf_coord\n _well = well(\n name = i,\n rte = _rte,\n crs = _crs,\n surf_coord = _surf_coord, \n survey = _survey,\n perforations = _perf,\n tops = _tops,\n units = _units\n )\n\n try:\n _well.to_tvd(which=['tops','perforations','units'])\n _well.to_tvd(which=['tops','perforations','units'],ss=True)\n _well.to_coord(which=['tops','perforations','units'])\n except:\n pass\n\n self.add_well(_well)",
"def download_data(countries):\n today = pd.to_datetime(\"today\")\n yesterday = today - pd.DateOffset(days=1)\n # start date is when first case was reported in United States\n dates = pd.date_range(start=\"01-21-2020\", end=yesterday)\n df = pd.DataFrame(dates, columns=[\"date\"])\n print(\"Base dataframe created\")\n soup_objects = get_wiki_pages(countries)\n country_codes = [wiki_shortcodes[c] for c in countries]\n for soup, country_code in zip(soup_objects, country_codes):\n country_data = create_df(soup, country_code)\n df = df.merge(country_data, how=\"left\", on=\"date\")\n print(\"Fill missing data.\")\n df = fill_missing_data(df)\n print(\"Dataframe ready.\")\n return df",
"def getExtentCounty(province, prefecture, county, extent, ansidate, coverage):\n \n extent = [117.04640962322863,33.00404358318741,117.59765626636589,33.50222015793983] # left, bottom, right, top\n d = 150842\n endpoint='http://192.168.1.104:8080/rasdaman/ows'\n field={}\n field['SERVICE']='WCS'\n field['VERSION']='2.0.1'\n field['REQUEST']='GetCoverage'\n field['COVERAGEID']=coverage#'trmm_3b42_coverage_1'\n field['SUBSET']=['ansi('+str(d)+')',\n 'Lat('+str(extent[1])+','+str(extent[3])+')',\n 'Long('+str(extent[0])+','+str(extent[2])+')']\n field['FORMAT']='image/tiff'\n url_values = urllib.urlencode(field,doseq=True)\n full_url = endpoint + '?' + url_values\n print full_url\n wcsCoverage_filename='coverage'+str(d)+'.tif'\n f,h = urllib.urlretrieve(full_url,wcsCoverage_filename)\n print h \n \n #path_base = \"/home/rasdaman/Downloads\"\n #CHN_adm_gpkg = os.path.join(path_base, \"CHN_adm.gpkg\") \n \n #wcsCoverage_filename_clip = 'coverage'+str(d)+'clip.tif' \n\n #command = [\"/usr/bin/gdalwarp\", \"-cutline\", CHN_adm_gpkg, \"-csql\", \"SELECT NAME_3 FROM CHN_adm3 WHERE NAME_1 = \"+province+\" and NAME_2 = \"+prefecture+\" and NAME_3 = \"+county+\"\",\n # \"-crop_to_cutline\", \"-of\", \"GTiff\", \"-dstnodata\",\"-9999\",wcsCoverage_filename, wcsCoverage_filename_clip, \"-overwrite\"] # \n\n #print (sp.list2cmdline(command))\n\n #norm = sp.Popen(sp.list2cmdline(command), shell=True) \n #norm.communicate() \n \n return wcsCoverage_filename #wcsCoverage_filename_clip",
"def countries_by_density():\n\n v_low=int(request.form.get(\"v_low\"))\n low=int(request.form.get(\"low\"))\n medium=int(request.form.get(\"medium\"))\n\n content = json.loads(dumps(db.getInstance().get_countries_by_density(v_low, low, medium)))\n return content"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Builds the where_condition for the Select Query
|
def build_where_condition(self, query_dict):
analysis_type = query_dict.get("analysis_type")
where = (" WHERE biotype.`biomimic_type`=\'%s\'") % query_dict['biomimic_type']
if query_dict.get('country') is not None:
where += " AND geo.`country`=\'%s\'" % (query_dict['country'])
if query_dict.get('state_province') is not None:
where += " AND geo.`state_province`=\'%s\'" % (query_dict['state_province'])
if query_dict.get('location') is not None:
where += " AND geo.`location`=\'%s\'" % (query_dict['location'])
if (query_dict.get('zone') is not None) and (query_dict.get('zone') != 'All'):
where += " AND prop.`zone`=\'%s\'" % (query_dict.get('zone'))
if (query_dict.get('sub_zone') is not None) and (query_dict.get('sub_zone') != 'All'):
if query_dict.get('sub_zone') == 'N/A':
where += " AND prop.sub_zone is Null"
else:
where += " AND prop.`sub_zone`=\'%s\'" % (query_dict.get('sub_zone'))
if (query_dict.get('wave_exp') is not None) and (query_dict.get('wave_exp') != 'All'):
if query_dict.get('wave_exp') == 'N/A':
where += " AND prop.wave_exp is Null"
else:
where += " AND prop.`wave_exp`=\'%s\' " % (query_dict.get('wave_exp'))
if (query_dict.get('start_date') is not None) and (query_dict.get('end_date') is not None):
where += """ AND cast(temp.Time_GMT as date) >= \'%s\'
AND cast(temp.Time_GMT as date) <= \'%s\'""" % \
(query_dict.get('start_date'), query_dict.get('end_date'))
if analysis_type == "Daily":
where += " GROUP BY cast(temp.Time_GMT as date)"
elif analysis_type == "Monthly":
where += """ GROUP BY YEAR(temp.Time_GMT), MONTHNAME(temp.Time_GMT)
ORDER BY YEAR(temp.Time_GMT), MONTH(temp.Time_GMT) ASC"""
elif analysis_type == "Yearly":
where += " GROUP BY YEAR(temp.Time_GMT)"
else:
pass
return where
|
[
"def _where(self):\n result = []\n result.extend(self._partition_selector())\n result.extend(self._job_and_fuzzer_selector())\n\n result = ' AND '.join(result)\n if result:\n return 'WHERE ' + result\n\n return ''",
"def BuildSubQuery(self):\n MultipleValuePairs = ''\n #This is to make sure psycopg2 uses the correct %s values\n sqlidx=0\n for ivaluedict in self.ConditionColumns:\n if MultipleValuePairs:\n MultipleValuePairs += \" OR \"\n MultipleValuePairs += \"({})\".format(self.BuildSubqString(ivaluedict,sqlidx))\n sqlidx += 1\n self.subquery = \"\"\"SELECT align_id FROM {} WHERE {} \"\"\".format(Db.searched_table,MultipleValuePairs)",
"def add_where_clause(self):\n if len(self.query_model.triples) > 0 or len(self.query_model.subqueries) > 0 or \\\n len(self.query_model.unions) >0 or len(self.query_model.optionals) > 0 or \\\n len(self.query_model.filter_clause) > 0 or len(self.query_model.optional_subqueries) > 0 or \\\n len(self.query_model.graph_triples) > 0 or len(self.query_model.graph_clause) > 0 or \\\n len(self.query_model.optional_graph_clause) > 0:\n where_string = self.__add_patterns()\n self.query_string += \"WHERE {\" + where_string + \"\\n\\t}\"\n else:\n self.query_string += \"WHERE {}\"",
"def _make_where_clause(row_filter: str = None) -> psql.SQL:\n if row_filter:\n psql_filter = to_psql(row_filter)\n return psql.SQL(f\" WHERE {psql_filter}\")\n return psql.SQL(\"\")",
"def make_where_clause(spec, **kwargs):\n where = []\n for col_to_query in spec['query_cols']:\n ids = kwargs.get(col_to_query)\n if ids:\n where.append('{} in [{}]'.format(col_to_query,\n ','.join([str(i) for i in ids])))\n\n # If boolean include_risks is false, then failing to\n # specify rei_id means you don't want attributable results.\n # Otherwise, it means you want all rei results\n if not kwargs.get('rei_id') and not kwargs.get('include_risks'):\n where.append('rei_id == 0')\n\n return \" & \".join(where)",
"def convert_condition(self, condition):\n\n new_con = \" WHERE\"\n\n for item in condition:\n\n if item is int:\n\n if item == 0:\n\n new_con += \" OR\"\n\n if item == 1:\n\n new_con += \" AND\"\n\n elif type(item) is list:\n\n new_con += \" \" + item[0] + \" = \" + '\"' + item[1] + '\"'\n\n return new_con",
"def build_queryString(conditions: Dict) -> str:\n\n queryString_components = []\n\n for columnName, columnValue in conditions.items():\n if isinstance(columnValue, tuple):\n queryString_components.append('{0} <= {1} <= {2}'.format(columnValue[0], columnName, columnValue[1]))\n elif any(isinstance(columnValue, _type) for _type in [float, int]):\n queryString_components.append('{0} == {1}'.format(columnName, columnValue))\n\n queryString = str.join(' and ', queryString_components)\n return queryString",
"def _build_db_query(self):\n\n base_query = \"select * from \" + self._trim_db_measure_param()\n if all([self.db_params['db_where_jkey'], self.db_params['db_where_comp_id']]):\n self.db_params['db_where_key'] = self.db_params['db_where_jkey'] + \" and \" + \\\n self.db_params['db_where_comp_id']\n elif self.db_params['db_where_jkey']:\n self.db_params['db_where_key'] = self.db_params['db_where_jkey']\n elif self.db_params['db_where_comp_id']:\n self.db_params['db_where_key'] = self.db_params['db_where_comp_id']\n else:\n t.log(level='info', message=base_query)\n base_query = base_query + \" limit \" + str(self.db_params['db_limit']) + \";\"\n return base_query\n base_query = base_query + \" where \" + self.db_params['db_where_key'] + \" limit \" \\\n + str(self.db_params['db_limit']) + \";\"\n t.log(level='info', message=base_query)\n t.log(level='info', message=base_query)\n return base_query",
"def process_fetch_conditions(driver_id, c_constraints):\n sql = \"\"\n\n if c_constraints:\n filter_fields = c_constraints.filter_fields\n if filter_fields:\n num_fields = len(filter_fields)\n sql += \" where \"\n\n for i, (field, operator) in enumerate(c_constraints.filter_fields.items()):\n if num_fields > 1 and i >= 1:\n sql = sql + \" AND \"\n\n value = c_constraints.get_filter_field_value(field)\n if value is None:\n if operator == Constraints.FilterType.EQUAL:\n sql = sql + field + \" is null\"\n else:\n sql = sql + field + \" is not null\"\n elif operator == Constraints.FilterType.PARTIAL or operator == Constraints.FilterType.IPARTIAL:\n sql = sql + field + \" \" + get_filter_operator(driver_id, operator) + \" '%\" + str(value) + \"%'\"\n elif isinstance(value, str):\n sql += field + get_filter_operator(driver_id, operator) + \"'\" + str(value) + \"'\"\n elif isinstance(value, bool):\n sql += field + get_filter_operator(driver_id, operator) + \"'\" + get_as_bool(driver_id, value) + \"'\"\n else:\n sql += field + get_filter_operator(driver_id, operator) + str(value)\n\n sort_fields = c_constraints.sort_fields\n if sort_fields:\n num_sort_fields = len(sort_fields)\n\n if num_sort_fields > 0:\n sql += \" order by \"\n\n for i, (field, direction) in enumerate(c_constraints.sort_fields.items()):\n if i >= 1:\n sql = sql + \",\"\n sql = sql + field + \" \" + str(direction)\n return sql",
"def must_return_select_with_specific_where_clause():\n\ttest = Test(1, 2, 3)\n\tquery = 'SELECT a, b, c FROM Test WHERE a = 5 AND b = 4'\n\tselect_query = entity.select(test, where_clause={'a': 5, 'b': 4})\n\tassert query == select_query",
"def _parse_where(self, where_dict: dict, parent: BaseObjectBuilder):\r\n assert isinstance(where_dict, dict)\r\n assert isinstance(parent, BaseObjectBuilder)\r\n\r\n name = None\r\n sql_sets = []\r\n arguments = []\r\n\r\n for (key, val) in where_dict.items():\r\n key = _strip_key(key)\r\n if key == 'dialects':\r\n for chv in self.fetch_dicts_from_list(key, val, 'dialect'):\r\n sql = SqlStatementBuilder(parent)\r\n sql_sets.append(sql.make(chv))\r\n elif key in ['sql', 'value']:\r\n chv = {\r\n 'syntax': 'universal',\r\n 'platforms': 'all',\r\n 'sql': val\r\n }\r\n sql = SqlStatementBuilder(parent)\r\n sql_sets.append(sql.make(chv))\r\n elif key == 'name':\r\n name = parent.to_str(key, val).strip()\r\n elif key in ['arg', 'argument']:\r\n arguments.append(self._parse_argument(val, parent))\r\n elif key in ['arguments', 'args']:\r\n for chv in self.fetch_dicts_from_list(\r\n key, val, ['arg', 'argument']):\r\n arguments.append(self._parse_argument(chv, parent))\r\n else:\r\n parent.unknown_key(key, val)\r\n if len(sql_sets) <= 0:\r\n parent.problem(\"no sql or dialects set for where clause\",\r\n FATAL_TYPE)\r\n return None\r\n\r\n return WhereClause(name, SqlSet(sql_sets, arguments))",
"def _validate_select_where(self):\n # check that there's either a =, a IN or a CONTAINS (collection)\n # relationship with a primary key or indexed field. We also allow\n # custom indexes to be queried with any operator (a difference\n # between a secondary index)\n equal_ops = [self.model._get_column_by_db_name(w.field) \\\n for w in self._where if not isinstance(w.value, Token)\n and (isinstance(w.operator, EqualsOperator)\n or self.model._get_column_by_db_name(w.field).custom_index)]\n token_comparison = any([w for w in self._where if isinstance(w.value, Token)])\n if not any(w.primary_key or w.has_index for w in equal_ops) and not token_comparison and not self._allow_filtering:\n raise QueryException(\n ('Where clauses require either =, a IN or a CONTAINS '\n '(collection) comparison with either a primary key or '\n 'indexed field. You might want to consider setting '\n 'custom_index on fields that you manage index outside '\n 'cqlengine.'))\n\n if not self._allow_filtering:\n # if the query is not on an indexed field\n if not any(w.has_index for w in equal_ops):\n if not any([w.partition_key for w in equal_ops]) and not token_comparison:\n raise QueryException(\n ('Filtering on a clustering key without a partition '\n 'key is not allowed unless allow_filtering() is '\n 'called on the queryset. You might want to consider '\n 'setting custom_index on fields that you manage '\n 'index outside cqlengine.'))",
"def build_query( fields, table, condition, func=None):\n\n if func is not None:\n new_fields = [\"%s(%s)\" %(func,f) for f in fields]\n else:\n new_fields = fields\n q = \"SELECT \"\n q += \", \".join( new_fields )\n q += \" FROM \"\n q += table\n q += condition\n return q",
"def generate_query(self):\n self.query = self._add_select_statement() +\\\n self._add_case_statement() +\\\n self._add_from_statement() +\\\n self._add_group_by_statement()\n\n return self.query",
"def sqlCondition(writer):",
"def build_query(self):\n\n query = super(FilteredTableSourceMixin, self).build_query()\n\n if self.config.filterlist_available:\n query = self.extend_query_with_filter(query)\n\n if self.config.subject_filter_available:\n SubjectFilter(self.config.context, self.request).update_query(query)\n\n return query",
"def where_conditions_location(cartesian_table, conditions_list):\n operator = conditions_list[1]\n column_list = []\n column_list.append(cartesian_table[conditions_list[0]])\n\n #This part determines the format of the where token\n if conditions_list[2] in cartesian_table:\n column_list.append(cartesian_table[conditions_list[2]])\n value = ''\n else:\n value = conditions_list[2].strip(\"'\")\n\n #Then based on the format, we just apply the proper operation\n return apply_operation(column_list, operator, value)",
"def select_given_all_true(self, conditions, cols_to_select='all'):\n \n # check all the column names to return\n if isinstance(cols_to_select, list):\n for column in cols_to_select:\n self._check_column_valid(column)\n \n # make condition, start with everything true\n final_condition = pd.Series(np.ones(self._data.shape[0], dtype=bool))\n for condition in conditions:\n \n condition_col = condition[0]\n op = condition[1]\n val = condition[2]\n \n print \"Adding condition that column: \", condition_col , op , val\n final_condition = operator.and_( final_condition, ops[op](self._data[condition_col],val) )\n\n if isinstance(cols_to_select, list):\n return self._data[final_condition][cols_to_select]\n else:\n return self._data[final_condition]",
"def make_query_string(self, filter_string):\n if len(filter_string) > 0:\n self.query_string += \"where \"\n for filter in filter_string:\n # first element be column name, second be operator, last be the variable\n parameters = filter.split(' ')\n\n self.query_string += parameters[0]\n self.convert_oprater(parameters[1])\n self.str_variable(parameters[2], parameters[0])\n\n if len(filter_string) > 0:\n self.query_string = self.query_string[:-4]\n\n self.query_string += \" order by chat_time\""
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Insert new Biomimic Type Data in DB
|
def insert_biomimic_type_data(self, cursor, biomimic_type):
corrupt = False
query = """ INSERT INTO `cnx_logger_biomimic_type` (`biomimic_type`)
VALUES (%s)"""
try:
res = cursor.execute(query, (biomimic_type,))
except MySQLdb.Error:
res = 0
if res == 1:
pass
else:
corrupt = True
return cursor.lastrowid, corrupt
|
[
"def insert(self, sql):",
"def create_data_type():\n logger.info('Creating Data Types..')\n\n data_codes = ['DAILY', 'INTRADAY']\n data_description = ['Data for a 24 period', 'Data for a 1 minute perioo']\n\n for code, description in zip(data_codes, data_description):\n DataType.objects.update_or_create(code=code, description=description)\n\n logger.info('{} DataType created'.format(DataType.code))",
"def test_can_insert_model_with_all_column_types(self):\n\n class AllDatatypesModel(Model):\n id = columns.Integer(primary_key=True)\n a = columns.Ascii()\n b = columns.BigInt()\n c = columns.Blob()\n d = columns.Boolean()\n e = columns.DateTime()\n f = columns.Decimal()\n g = columns.Double()\n h = columns.Float()\n i = columns.Inet()\n j = columns.Integer()\n k = columns.Text()\n l = columns.TimeUUID()\n m = columns.UUID()\n n = columns.VarInt()\n o = columns.Duration()\n\n sync_table(AllDatatypesModel)\n\n input = ['ascii', 2 ** 63 - 1, bytearray(b'hello world'), True, datetime.utcfromtimestamp(872835240),\n Decimal('12.3E+7'), 2.39, 3.4028234663852886e+38, '123.123.123.123', 2147483647, 'text',\n UUID('FE2B4360-28C6-11E2-81C1-0800200C9A66'), UUID('067e6162-3b6f-4ae2-a171-2470b63dff00'),\n int(str(2147483647) + '000')]\n\n AllDatatypesModel.create(id=0, a='ascii', b=2 ** 63 - 1, c=bytearray(b'hello world'), d=True,\n e=datetime.utcfromtimestamp(872835240), f=Decimal('12.3E+7'), g=2.39,\n h=3.4028234663852886e+38, i='123.123.123.123', j=2147483647, k='text',\n l=UUID('FE2B4360-28C6-11E2-81C1-0800200C9A66'),\n m=UUID('067e6162-3b6f-4ae2-a171-2470b63dff00'), n=int(str(2147483647) + '000'),\n o=Duration(2, 3, 4))\n\n self.assertEqual(1, AllDatatypesModel.objects.count())\n output = AllDatatypesModel.objects.first()\n\n for i, i_char in enumerate(range(ord('a'), ord('a') + 14)):\n self.assertEqual(input[i], output[chr(i_char)])",
"def test_can_insert_model_with_all_protocol_v4_column_types(self):\n\n if PROTOCOL_VERSION < 4:\n raise unittest.SkipTest(\"Protocol v4 datatypes require native protocol 4+, currently using: {0}\".format(PROTOCOL_VERSION))\n\n class v4DatatypesModel(Model):\n id = columns.Integer(primary_key=True)\n a = columns.Date()\n b = columns.SmallInt()\n c = columns.Time()\n d = columns.TinyInt()\n\n sync_table(v4DatatypesModel)\n\n input = [Date(date(1970, 1, 1)), 32523, Time(time(16, 47, 25, 7)), 123]\n\n v4DatatypesModel.create(id=0, a=date(1970, 1, 1), b=32523, c=time(16, 47, 25, 7), d=123)\n\n self.assertEqual(1, v4DatatypesModel.objects.count())\n output = v4DatatypesModel.objects.first()\n\n for i, i_char in enumerate(range(ord('a'), ord('a') + 3)):\n self.assertEqual(input[i], output[chr(i_char)])",
"def add_type(self, d_type):\n conn = sqlite3.connect(\"dampers.db\")\n conn.execute(\"PRAGMA foreign_keys=1\") # enable cascade deleting and updating.\n cur = conn.cursor()\n try:\n cur.execute(\"INSERT INTO d_types(d_type) VALUES(:d_type)\", {\"d_type\": d_type})\n except sqlite3.DatabaseError as err:\n raise sqlite3.DatabaseError(err)\n else:\n conn.commit()\n finally:\n cur.close()\n conn.close()",
"def data_writer(self,sql_record):\n\n sql_st = '''\n INSERT OR IGNORE INTO exp_comp_type(geo_expense_id,goog_name,comp_type,address,placeid,goog_lat,goog_lng)\n VALUES (?,?,?,?,?,?,?)\n '''\n cur = self.conn.cursor()\n cur.execute(sql_st,sql_record)\n self.conn.commit()",
"def createAndAdd(data):",
"def insert_data(self, data:dict,):\n \n assert(isinstance(data, dict))\n field, value = \"\", \"\"\n for key in data.keys():\n field += key + ', '\n value += ':' + key + ', '\n \n field = field[:-2]\n value = value[:-2]\n sql_query = \"\"\"INSERT INTO %s (%s) VALUES(%s)\"\"\"%(self.db, field, value)\n self.conn.execute(sql_query, data)\n self.conn.commit()",
"def create(self, validated_data):\n\t\treturn Type.objects.create(**validated_data)",
"def insert_data(self):\n self.type_vm_1 = TypeVersionManager(\n title=\"type 1\",\n user=None,\n is_disabled=False,\n )\n self.type_vm_1.save_version_manager()\n self.type_1_1 = Type(\n filename=\"type1_1.xsd\",\n content=\"content1_1\",\n hash=\"hash1_1\",\n is_complex=True,\n version_manager=self.type_vm_1,\n )\n self.type_1_1.save_template()\n self.type_1_2 = Type(\n filename=\"type1_2.xsd\",\n content=\"content1_2\",\n hash=\"hash1_2\",\n is_complex=True,\n version_manager=self.type_vm_1,\n is_disabled=True,\n )\n self.type_1_2.save_template()\n self.type_1_3 = Type(\n filename=\"type1_3.xsd\",\n content=\"content1_3\",\n hash=\"hash1_3\",\n is_complex=True,\n version_manager=self.type_vm_1,\n is_current=True,\n )\n self.type_1_3.save_template()\n\n self.type_vm_2 = TypeVersionManager(\n title=\"type 2\",\n user=\"1\",\n is_disabled=False,\n )\n self.type_vm_2.save_version_manager()\n\n self.type_2_1 = Type(\n filename=\"type2_1.xsd\",\n content=\"content2_1\",\n hash=\"hash2_1\",\n is_complex=True,\n version_manager=self.type_vm_2,\n is_current=True,\n )\n self.type_2_1.save_template()\n\n self.type_vm_collection = [self.type_vm_1, self.type_vm_2]",
"def insert_node(self, data, tbn, mult=False):\n query_mode = self.c.execute if not mult else self.c.executemany\n query_mode(\"\"\"INSERT INTO {tbn} VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\"\"\".format(tbn=tbn), data)",
"def test_insert(self, record):",
"def insert_row(self, data):\n print(\"Inserting row to database\")\n self.cursor.executemany(self.insert_query, data)\n self.connection.commit()",
"def test_all_datatypes_write(self):\n self.all_datatypes_prepare()\n\n insert_statement = self.session.prepare(\n \"\"\"INSERT INTO testdatatype (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\"\"\")\n self.session.execute(insert_statement, self.data)\n\n self.tempfile = NamedTemporaryFile(delete=False)\n debug('Exporting to csv file: {name}'.format(name=self.tempfile.name))\n self.node1.run_cqlsh(cmds=\"COPY ks.testdatatype TO '{name}'\".format(name=self.tempfile.name))\n\n results = list(self.session.execute(\"SELECT * FROM testdatatype\"))\n\n self.assertCsvResultEqual(self.tempfile.name, results)",
"def test_create_from_gds_type(self):\n _b = emdb_sff.biological_annotationType(\n name=self.name,\n description=self.description,\n number_of_instances=self.no,\n external_references=self._external_references\n )\n b = adapter.SFFBiologicalAnnotation.from_gds_type(_b)\n self.assertRegex(\n _str(b),\n r\"\"\"SFFBiologicalAnnotation\\(\"\"\" \\\n r\"\"\"name=\"{}\", description=\"{}\", \"\"\" \\\n r\"\"\"number_of_instances={}, \"\"\" \\\n r\"\"\"external_references=SFFExternalReferenceList\\(\\[.*\\]\\)\\)\"\"\".format(\n self.name,\n self.description,\n self.no\n )\n )\n self.assertEqual(b.name, self.name)\n self.assertEqual(b.description, self.description)\n self.assertEqual(b.number_of_instances, self.no)\n self.assertEqual(b.external_references, self.external_references)",
"def store_data(self,table_name,data):\n if len(data) == 0:\n log.warning(\"Inserting empty data\")\n return\n n = len(data[0]) # number of columns for each row inserted\n tuple_format=\"(\"+\"?,\"*(n-1)+\"?)\"\n sql_command=\"INSERT INTO %s VALUES %s \" % (table_name, tuple_format)\n # Fill the table with the info in the tuples\n types = self.get_table_types(table_name)\n# log.debug(\"Storing types: %s\", types)\n for i in xrange(len(data)):\n data[i] = [apply_type(d) for d,apply_type in zip(data[i], types)]\n self.executemany(sql_command, data)\n self.commit()",
"def insert_record(self,list_holding_record):",
"def insert(connection, row_data):\n cur = connection.cursor()\n cur.execute(\"INSERT INTO pomodoros VALUES (?,?,?,?)\", row_data)",
"def insert(cls, env, record):\n with env.db_transaction as db:\n\n cursor = db.cursor()\n sqlString = \"\"\"INSERT INTO ticket_template_store\n (tt_time,tt_user,tt_name,tt_field,tt_value)\n VALUES (%s,%s,%s,%s,%s)\"\"\"\n cursor.execute(sqlString, record)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Insert new Properties Data in DB
|
def insert_properties_data(self, cursor, record):
corrupt = False
values = " VALUES (\'%s\'" % record.get("zone")
if record.get('sub_zone') is None:
values += ", NULL"
else:
values += ", \'%s\'" % record.get("sub_zone")
if record.get('wave_exp') is None:
values += ", NULL"
else:
values += ", \'%s\'" % record.get("wave_exp")
values += ")"
query = """INSERT INTO `cnx_logger_properties`
(`zone`, `sub_zone`, `wave_exp`)""" + values
try:
res = cursor.execute(query)
except MySQLdb.Error:
res = 0
if res == 1:
pass
else:
corrupt = True
return cursor.lastrowid, corrupt
|
[
"def insert_properties(self, properties: list) -> None:\n self.properties.insert_many(properties)",
"def insert_data(self, data:dict,):\n \n assert(isinstance(data, dict))\n field, value = \"\", \"\"\n for key in data.keys():\n field += key + ', '\n value += ':' + key + ', '\n \n field = field[:-2]\n value = value[:-2]\n sql_query = \"\"\"INSERT INTO %s (%s) VALUES(%s)\"\"\"%(self.db, field, value)\n self.conn.execute(sql_query, data)\n self.conn.commit()",
"def insert(self, sql):",
"def save(self):\r\n values = [str(prop)+\" = \"+str(sqlRender(getattr(self,prop))) for prop in self._column_list]\r\n \r\n if getattr(self,self.pk):\r\n Base.cursor.execute(f\"UPDATE {self._table_name} SET {', '.join(values)} WHERE {self.pk}={sqlRender(self.pk)}\")\r\n Base.cursor.commit()\r\n Base.cursor.fetchall()\r\n else:\r\n list_without_pk = self._column_list.copy()\r\n list_without_pk.remove(self.pk)\r\n values = [getattr(self,item) if getattr(self,item) else \"NULL\" for item in list_without_pk]\r\n Base.cursor.execute(f\"INSERT INTO {self._table_name} ({', '.join(list_without_pk)}) VALUES ( { ', '.join([str(sqlRender(value)) for value in values])}\")\r\n Base.cursor.commit()\r\n Base.cursor.fetchall()",
"def insert_product(self, data):\n query = \"INSERT INTO Products VALUES (NULL, %s, %s, %s, %s, %s)\"\n self.mycursor.execute(query, data)\n self.connector.commit()",
"def storeProposerInfoInDB():\n #collection.remove({})\n responders = []\n responders.append(flask.session['name'])\n free_times = []\n free_times.append(flask.session['revised_free'])\n proposal_id = str(ObjectId())\n flask.session['proposal_id'] = proposal_id\n record = { \"type\": \"proposal\",\n \"_id\": proposal_id,\n \"start_date\": flask.session['begin_date'], \n \"end_date\": flask.session['end_date'],\n \"start_time\": flask.session['begin_time'],\n \"end_time\": flask.session['end_time'],\n \"responders\": responders,\n \"free_times\": free_times\n }\n collection.insert(record)",
"def metadataInsert(self, data, md5=False, db=None):\n\n localClose = False\n if not db:\n db = self.dbConnect()\n localClose = True\n cursor = db.cursor()\n\n for obj in data:\n md5 = files.fileMD5(obj[\"object_path\"])\n\n sql = (\n \"INSERT INTO %s.PLADMIN_METADATA VALUES('%s', '%s', '%s','%s', sysdate, TO_DATE('%s','RRRR/MM/DD HH24:MI:SS'))\"\n % (\n self.user,\n obj[\"object_name\"],\n obj[\"object_type\"],\n obj[\"object_path\"],\n md5,\n obj[\"last_ddl_time\"],\n )\n )\n cursor.execute(sql)\n\n cursor.close()\n\n if localClose:\n db.commit()\n db.close()",
"def populate_database(self):\n self.dye_stocks.add_new_dye_stocks()\n self.detections.add_new_detections()\n self.profiles.add_new_profiles()",
"def insert(cls, env, record):\n with env.db_transaction as db:\n\n cursor = db.cursor()\n sqlString = \"\"\"INSERT INTO ticket_template_store\n (tt_time,tt_user,tt_name,tt_field,tt_value)\n VALUES (%s,%s,%s,%s,%s)\"\"\"\n cursor.execute(sqlString, record)",
"def _insert_entities_in_db(self):\n # TODO: can change it to just use the values of the dictionary\n pg_entity_values = np.arange(len(self.ent_to_idx)).reshape(-1, 1).tolist()\n conn = sqlite3.connect(\"{}\".format(self.dbname))\n cur = conn.cursor()\n try:\n cur.executemany('INSERT INTO entity_table VALUES (?)', pg_entity_values)\n conn.commit()\n except sqlite3.Error:\n conn.rollback()\n cur.close()\n conn.close()",
"async def set_data_in_db(self):\n try:\n result = await self._data_table.bulk_write(self._data[0], ordered=False)\n print('Insertion result %s' % repr(result.bulk_api_result))\n except pymongo.errors.BulkWriteError as bwe:\n result = bwe.details",
"def __insert( self, criteria, con ):\n id = None\n table_name = ''\n\n keys = criteria.keys()\n if keys:\n table_name = criteria.getTableName(keys[0])\n else:\n raise ProofException.ProofImproperUseException( \\\n \"Database insert attempted without anything specified to insert.\" )\n\n db_map = self.__proof.getDatabaseMap(self.__db_name)\n table_map = db_map.getTable(table_name)\n column_maps = table_map.getColumns()\n key_info = table_map.getPrimaryKeyMethodInfo()\n key_gen = table_map.getIdGenerator()\n\n # create primary key\n pk = None\n for column_map in column_maps:\n if column_map.isPrimaryKey():\n pk = column_map\n break\n\n if pk and not criteria.has_key(pk.getFullyQualifiedName()):\n if not key_gen:\n raise ProofException.ProofNotFoundException( \\\n \"IDGenerator for table '%s' is None\" % (table_name) )\n\n if key_gen.isPriorToInsert():\n id = key_gen.getId(connection=con, key_info=key_info)\n criteria[pk.getFullyQualifiedName()] = id\n\n # perform the insert\n column_list = []\n value_list = []\n for column in column_maps:\n column_name = column.getFullyQualifiedName()\n if criteria.has_key(column_name):\n column_list.append(column_name)\n value_list.append(criteria[column_name])\n\n sql_expr = SQLExpression.SQLExpression()\n #self.log(\"doInsert: (%s) (%s)\"%(column_list, value_list), level=logging.INFO)\n (column_list, value_list) = sql_expr.buildInsertList(column_list, value_list)\n\n sql = \"INSERT INTO %s (%s) VALUES (%s)\" % ( table_name,\n string.join(column_list, \", \"),\n string.join(value_list, \", \") )\n\n self.log( \"%s.doInsert: %s\" % (self.__class__.__name__, sql) )\n\n self.__execute(sql, con)\n\n if pk and key_gen and key_gen.isPostInsert():\n id = key_gen.getId(connection=con, key_info=key_info)\n\n return id",
"def save(self, instance):\n cursor = db.cursor()\n cursor.execute(\n f\"\"\"INSERT IGNORE INTO {self.table} (product_id, store_id)\n VALUES (%(product_id)s, %(store_id)s)\n \"\"\",\n vars(instance),\n )\n db.commit()\n cursor.close()",
"def insert_in_db(the_json, success):\n DB.session.add(email_record_from_json(the_json, success))\n DB.session.commit()",
"def create_property(property_info):\n return insert('property', property_info.keys(), property_info.values())",
"def insert(self, **kwargs):\n logging.debug(\"Saving new entry: %s\" % \", \".join(\n reduce(lambda name, value: \"%s - %s\" % (name, value),\n kwargs.iteritems())))\n post = self.schema()\n for name, value in kwargs.iteritems():\n post[name] = value\n if name == 'problemId':\n post[name] = ObjectId(post[name])\n if '_id' in post:\n if not isinstance(post['_id'], ObjectId):\n post['_id'] = ObjectId(post['_id'])\n return self._collection.insert(self.validate(post))",
"def populate_db():\n data = [\n Clientes(primeiro_nome='Cliente', ultimo_nome='1', email='cliente1@email.com'),\n ]\n db.session.bulk_save_objects(data)\n db.session.commit()\n\n data_pedido = [\n Pedidos(data_pedido='22-10-2020', status_pedido='Encaminhado', valor_pedido='22.00', cliente_id=1),\n ]\n db.session.bulk_save_objects(data_pedido)\n db.session.commit()\n return True",
"def insert_info(self):\n\t\tself.get_connection()\n\t\tc = self.conn.cursor()\n\t\t#For every USER in the dictionary\n\t\tfor i in range(len(self.info['USER'])):\n\t\t\t#insert them into the database (I <3 SQL INJECTIONS)\n\t\t\tc.execute(\"INSERT OR REPLACE INTO '{tn}' ('{user}', '{dp}', '{g}', '{f}', '{l}', '{e}') VALUES ('{idv}', '{dpv}', '{gv}', '{fv}', '{lv}', '{ev}');\".\\\n\t\t\t\tformat(tn=self.tn, user=self.user, dp=self.dp, g=self.g, f=self.f, l=self.l, e=self.e,\n\t\t\t\t\tidv=self.info['USER'][i], dpv=self.info['pass'][i], gv=self.info['group'][i],\n\t\t\t\t\t fv=self.info['first'][i], lv=self.info['last'][i], ev=self.info['email'][i]))\n\t\t#Log this datbase manipulation\n\t\tself.log_users_creation()\n\t\t#commit to database and close connection\n\t\tself.commit_db()",
"def setup(self):\n scripts = []\n script = '''CREATE TABLE settings (\n id INTEGER PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n value TEXT NOT NULL) WITHOUT ROWID\n '''\n scripts.append(script)\n script = '''INSERT INTO settings (id, name, value)\n VALUES (1, \"out_path\", \"output\")'''\n scripts.append(script)\n self.db.put(scripts)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Check for Duplicate Microsite Id in DB
|
def check_for_duplicate(self, cursor, microsite_id):
query = """SELECT `logger_id`
FROM `cnx_logger`
WHERE `microsite_id`=%s"""
cursor.execute(query, (microsite_id,))
results = cursor.fetchall()
results = list(results)
return len(results) > 0
|
[
"def flag_duplicate_in_whole_db():\n pubs = Publication.objects.all()\n duplicates = get_duplicate_pubs(pubs)\n for pub in pubs:\n if pub in duplicates:\n with transaction.atomic():\n pub.status = Publication.STATUS_DUPLICATE\n pub.checked_for_duplicates = False\n pub.save()",
"def unique_sn(self, sn):\n if Instrument.query.filter_by(sn=sn).first() is not None:\n self.sn.errors.append('This sn already exists in our system. Please try a different SN')\n\n return False",
"def __handle_duplicate(self, duplicate: dict):\n duplicate_website = self.get_one(duplicate['_id'])\n\n # CHECK FQDN\n if duplicate_website['fqdn'] == self.fqdn:\n return False\n \n # CHECK NAME\n if duplicate['parameter'] == \"website_name\":\n if self.subdomain != \"www\" and self.subdomain != \"\":\n self.name = f\"{self.subdomain.capitalize()} {self.domain.capitalize()}\"\n else:\n self.name = f\"{self.domain.capitalize()} {self.suffix}\"\n \n # CHECK DUPLICATE AGAIN\n duplicate = self.__check_duplicates()\n\n if duplicate: self.existing = True",
"def __check_duplicates(self):\n data = {\n \"_id\": None,\n \"parameter\": None\n }\n\n try:\n ws = self.get({\"website_name\": self.name}, limit=5, raw_website=False)\n data['parameter'] = \"website_name\" if ws else None\n \n if not ws:\n ws = self.get(body={\"fqdn\": self.fqdn}, limit=5, raw_website=False)\n data['parameter'] = \"fqdn\" if ws else None\n\n if not ws:\n ws = self.get(body={\"website_url\": self.website_url}, limit=5, raw_website=False)\n data['parameter'] = \"website_url\" if ws else None\n\n if not ws:\n return None\n else:\n if len(ws) > 1:\n return data\n else:\n data['_id'] = ws[0]['_id']\n return data\n except:\n raise",
"def is_id_duplicate(self) -> bool:\n for step in self.job.steps:\n if (step.id == self.id) and (step != self):\n return True\n return False",
"def has_unique_ids(self):\n self.unique_ids = {}\n\n for row in self:\n if row['unique_data_id'] in self.unique_ids:\n return False\n else:\n #don't add flags that won't make it into the SQL database\n if row['include_flag'] in Manifest._include_flags_positive:\n self.unique_ids[row['unique_data_id']] = 'found'\n return True",
"def test_create_unique_uid(self) -> None:\n\n self.assertEqual(first=Uid.objects.all().count(), second=2)\n _create_unique_uid(user_id=1)\n self.assertEqual(first=Uid.objects.all().count(), second=3)",
"def _checkIdUniqueness(self, id):\n if id == 'time':\n logger.warn(\"Specifying 'time' as a variable is dangerous! Are you \"\n \"sure you know what you're doing?\")\n elif id == 'default':\n logger.warn(\"'default' is a reserved keyword in C. This will cause \"\n \"problems using the C-based integrator.\")\n elif id[0].isdigit():\n raise ValueError(\"The id %s is invalid. ids must not start with a \"\n \"number.\" % id)\n if id in list(self.variables.keys())\\\n or id in list(self.reactions.keys())\\\n or id in list(self.functionDefinitions.keys())\\\n or id in list(self.events.keys())\\\n or id in list(self.constraints.keys())\\\n or id == self.id:\n raise ValueError('The id %s is already in use!' % id)",
"def test_structure_creation_payload_for_duplicates(self):\n\n CommonTestCases.admin_token_assert_in(\n self,\n office_structure_mutation_with_duplicates,\n 'The office stuctures does not contain unique ids'\n )",
"def is_unique(self, field):\n return field.scheme.unique",
"def test_integrity_error(self):\n\n individual = Individual.objects.create(mk='eda9f62ad321b1fbe5f283cc05e2484516203117')\n Identity.objects.create(uuid='eda9f62ad321b1fbe5f283cc05e2484516203117',\n source='scm',\n name='Jane Roe',\n email='jroe@example.com',\n username='jrae',\n individual=individual)\n\n client = graphene.test.Client(schema)\n\n # Tests\n params = {\n 'source': 'scm',\n 'name': 'Jane Roe',\n 'email': 'jroe@example.com',\n 'username': 'jrae',\n }\n executed = client.execute(self.SH_ADD_IDENTITY,\n context_value=self.context_value,\n variables=params)\n msg = executed['errors'][0]['message']\n self.assertEqual(msg, DUPLICATED_INDIVIDUAL)\n\n # Different case letters, but same identity\n params = {\n 'source': 'scm',\n 'name': 'jane roe',\n 'email': 'jroe@example.com',\n 'username': 'jrae',\n }\n executed = client.execute(self.SH_ADD_IDENTITY,\n context_value=self.context_value,\n variables=params)\n msg = executed['errors'][0]['message']\n self.assertEqual(msg, DUPLICATED_INDIVIDUAL)\n\n # Different accents, but same identity\n params = {\n 'source': 'scm',\n 'name': 'Jane Röe',\n 'email': 'jroe@example.com',\n 'username': 'jrae',\n }\n executed = client.execute(self.SH_ADD_IDENTITY,\n context_value=self.context_value,\n variables=params)\n msg = executed['errors'][0]['message']\n self.assertEqual(msg, DUPLICATED_INDIVIDUAL)",
"def check_duplicate_fields(subscription_name):\n\n existing_subscription = (SubscriptionModel.query.filter(\n SubscriptionModel.subscription_name == subscription_name).one_or_none())\n if existing_subscription is not None:\n raise DuplicateDataException(f'subscription Name: {subscription_name} already exists.')",
"def check_dupe(request):\n \n artist = request.POST['artist']\n album = request.POST['album']\n client_ver = float(request.META['HTTP_USER_AGENT'].split(' v')[1])\n \n if client_ver < settings.MIN_CLIENT_VERSION:\n return HttpResponse(\"Too Old Client\", mimetype=\"text/plain\")\n \n ver = \"\"\n if client_ver < settings.CURRENT_CLIENT_VERSION:\n ver = \" %s\" % settings.CURRENT_CLIENT_VERSION\n \n if Album.objects.filter(album__iexact=album, artist__iexact=artist).exists():\n return HttpResponse(\"Yes%s\" % ver, mimetype=\"text/plain\")\n else:\n return HttpResponse(\"No%s\" % ver, mimetype=\"text/plain\")",
"def unique(self):\r\n if self.id or self.process:\r\n return self.process.slug == \"upload-metadata-unique\"\r\n\r\n # If no info, consider this true by default\r\n return True",
"def isUniqueVariable(self) -> bool:\n ...",
"def is_duplicate(self, bot_wsocket):\n assert bot_wsocket.team_uuid is not None\n assert bot_wsocket.box_uuid is not None\n return (\n 0\n < self.botdb.query(Bot)\n .filter(\n and_(\n Bot.team_uuid == str(bot_wsocket.team_uuid),\n Bot.box_uuid == str(bot_wsocket.box_uuid),\n )\n )\n .count()\n )",
"def check_website_existence(self,website):\n ##Comprobamos si es la primera vez que aparece este sitio web\n ##Aniade a la base de datos los nuevos sitios webs diferente al que se ha crawleado\n\n\n is_i2p_link=self.check_if_i2p_link.search(website)\n logging.debug('(Website existence) %s check if i2p site result:[%s]', website, is_i2p_link)\n if is_i2p_link:\n\n visited_website_before=self.visited_i2p_webpages.website_known(website)\n website_in_queue=self.not_visited_i2p_webpages.website_known(website)\n logging.debug('Website visited before:[%s] and website in queue:[%s]', visited_website_before, website_in_queue)\n if visited_website_before == False and website_in_queue==False:\n\n query=\"INSERT INTO websites (name) VALUES (%s)\"\n self.cursor.execute(query,(website,))\n\n logging.debug('{DATABASE} Added new i2psite:[%s]', website)\n else:\n self.cursor.execute(\"SELECT id FROM websites where name = %s\",\n (website,))\n website_exist=self.cursor.fetchone()\n if not website_exist:\n query=\"INSERT INTO websites (name) VALUES (%s)\"\n self.cursor.execute(query,(website,))\n logging.debug('{DATABASE} Added new normal website:[%s]', website)",
"def validate_id(form, field):\n if db.query_db('select count(*) from teams where teamId=?', [field.data])[0]['count(*)'] > 0:\n raise StopValidation('Team \"{}\" already exists. Please specify a unique team name.'.format(field.data))",
"def is_duplicated(node):\n address = read_address(node)\n verifier = read_verifier(node)\n\n if not all((address, verifier)):\n # Node did not have the attributes for verification,\n # this is new node.\n return True\n else:\n return not verifier == _generate_verifier(read_uuid(node), address)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Parse new Logger Temperature Data
|
def parse_logger_temp(self, data_list):
parsed_record = dict()
error = False
if (len(data_list) != 2) or \
(self.is_not_float(data_list[1])) or \
(data_list[0] == "None") or \
(data_list[0] == ""):
error = True
else:
# handle datetime error
try:
parsed_record['Time_GMT'] = datetime.strptime(data_list[0], '%m/%d/%Y %H:%M')
except ValueError:
try:
parsed_record['Time_GMT'] = datetime.strptime(data_list[0], '%m/%d/%y %H:%M')
except ValueError:
error = True
if not error:
parsed_record['Temp_C'] = data_list[1]
return parsed_record, error
|
[
"def process_temperature():\n \n \"\"\"for mutliple Sensors\"\"\"\n\n for SENSOR in W1ThermSensor.get_available_sensors():\n\tlogging.info(\"Sensor %s has temperature %.2f\" % (SENSOR.id, SENSOR.get_temperature()))\n \tG.labels(\"%s\" % SENSOR.id).set(\"%.2f\" % SENSOR.get_temperature())",
"def read_temperature_data(self):\n\n current_temp = serialChiller.readCoolantTemperature(serialPort = self.ser)\n self.temperature_data.append(current_temp)",
"def parseLine(line):\n tokens = line.split(':')\n # print(tokens)\n stamp=\"\"\n temp=-999.0\n humt=-999.0\n pres=-999.0\n lght=-999.0\n clock=False\n thermometer=False\n barometer=False\n hygrometer=False\n firmware=\"\"\n hardware=\"\"\n devName=\"\"\n for t in tokens:\n if t == 'DATA ':\n pass # ignore header\n elif t[0:1] == 'C':\n stamp = datetime.strptime(t[1:], '%Y%m%d%H%M%S').replace(tzinfo=pytz.UTC)\n elif t[0:1] == 'T':\n temp = float(t[1:])\n elif t[0:1] == 'H':\n humt = float(t[1:])\n elif t[0:1] == 'P':\n pres = float(t[1:])\n elif t[0:1] == 'L':\n lght = float(t[1:])\n elif t[0:1] == 'F':\n firmware = t[1:]\n elif t[0:1] == 'D':\n devList = t[1:]\n # print(devList)\n clock = devList[0:1] == 'C'\n thermometer = devList[1:2] == 'T'\n hygrometer = devList[2:3] == 'H'\n barometer = devList[3:4] == 'P'\n elif t[0:1] == 'W':\n hardware = t[1:]\n elif t[0:1] == \"N\":\n devName = t[1:]\n return stamp,temp,humt,pres,lght,firmware,hardware,devName,clock,thermometer,hygrometer,barometer",
"def process_temp_line( self, line ):\n #print \"process temp line\"\n #self.logger.debug( \"process_temp_line \" + line )\n\n ok, values = self.helper_thread.parse_out_floats( line, )\n\n if not ok:\n self.logger.error( \"error in parse return value for temp >>>\" + line + \"<<<\" )\n return # NEED better handling here\n\n if len( values ) != self.no_temps :\n self.logger.error( \"error in parse len of values for temp : \" + str( len( values )) + \" >>>\" + line + \"<<<\" )\n return\n\n for ix_value, i_value in enumerate( values ):\n self.dv_temps[ix_value].add_value( i_value )",
"def read_temp(self):\n\n \"\"\"\n read outdoor-air-temperature (variable v00104) / Aussenluft\n \"\"\"\n debug(\"Reads the sensor for the outdoor-air-temperature...\")\n self.modbusclient.write_multiple_registers(0, str2duohex(\"v00104\"))\n outTemp = duohex2str(self.modbusclient.read_holdingregisters(0, 8))[7:]\n\n \"\"\"\n read supplied-air-temperature (variable v00105) / Zuluft\n \"\"\"\n debug(\"Reads the sensor for the supplied-air-temperature...\")\n self.modbusclient.write_multiple_registers(0, str2duohex(\"v00105\"))\n suppTemp = duohex2str(self.modbusclient.read_holdingregisters(0, 8))[7:]\n\n \"\"\"\n read exhaust-air-temperature (variable v00106) / Fortluft\n \"\"\"\n debug(\"Reads the sensor for the exhaust-air-temperature...\")\n self.modbusclient.write_multiple_registers(0, str2duohex(\"v00106\"))\n exhaustTemp = duohex2str(self.modbusclient.read_holdingregisters(0, 8))[7:]\n\n \"\"\"\n read extract-air-temperature (variable v00107) / Abluft\n \"\"\"\n debug(\"Reads the sensor for the extract-air-temperature...\")\n self.modbusclient.write_multiple_registers(0, str2duohex(\"v00107\"))\n extractTemp = duohex2str(self.modbusclient.read_holdingregisters(0, 8))[7:]\n\n info(\"Successfully read all temperature sensors!\")\n return float(outTemp), float(suppTemp), float(exhaustTemp), float(extractTemp)",
"def temperature(self) -> TemperatureData:\n pass",
"def readtemperature(self):\r\n\t\tdata = bus.read_i2c_block_data(TMP101NA_DEFAULT_ADDRESS, TMP101NA_REG_TEMP, 2)\r\n\t\t\r\n\t\t# Convert the data to 12-bits\r\n\t\tcTemp = (data[0] * 256 + (data[1] & 0xF0)) / 16\r\n\t\tif cTemp > 2047:\r\n\t\t\tcTemp -= 4096\r\n\t\tcTemp = cTemp * 0.0625\r\n\t\tfTemp = cTemp * 1.8 + 32\r\n\t\t\r\n\t\treturn {'c' : cTemp, 'f' : fTemp}",
"def _get_temperature(self, ws_name):\r\n instr, run_number = self._get_InstrRun(ws_name)\r\n\r\n facility = config.getFacility()\r\n pad_num = facility.instrument(instr).zeroPadding(int(run_number))\r\n zero_padding = '0' * (pad_num - len(run_number))\r\n\r\n run_name = instr + zero_padding + run_number\r\n log_filename = run_name.upper() + '.log'\r\n\r\n run = mtd[ws_name].getRun()\r\n\r\n if self._sample_log_name in run:\r\n # Look for temperature in logs in workspace\r\n tmp = run[self._sample_log_name].value\r\n value_action = {'last_value': lambda x: x[len(x) - 1],\r\n 'average': lambda x: x.mean()\r\n }\r\n temp = value_action[self._sample_log_value](tmp)\r\n logger.debug('Temperature %d K found for run: %s' % (temp, run_name))\r\n return temp\r\n\r\n else:\r\n # Logs not in workspace, try loading from file\r\n logger.information('Log parameter not found in workspace. Searching for log file.')\r\n log_path = FileFinder.getFullPath(log_filename)\r\n\r\n if log_path != '':\r\n # Get temperature from log file\r\n LoadLog(Workspace=ws_name, Filename=log_path)\r\n run_logs = mtd[ws_name].getRun()\r\n if self._sample_log_name in run_logs:\r\n tmp = run_logs[self._sample_log_name].value\r\n temp = tmp[len(tmp) - 1]\r\n logger.debug('Temperature %d K found for run: %s' % (temp, run_name))\r\n return temp\r\n else:\r\n logger.warning('Log entry %s for run %s not found' % (self._sample_log_name, run_name))\r\n else:\r\n logger.warning('Log file for run %s not found' % run_name)\r\n\r\n # Can't find log file\r\n logger.warning('No temperature found for run: %s' % run_name)\r\n return None",
"def get_temperature_data():\n\n vals = get_data()\n values = []\n for val in vals:\n values.append({\"value\": val[\"temperature\"], \"time\": val[\"time\"]})\n return values",
"def get_temperature(self):\n self.get_reading()\n if self.raw_temperature < 0x3FFF:\n temperature = self.set_precision((self.raw_temperature * 165.0 / 2**14) - 40.0)\n return (temperature, 'temp', 'c')\n else:\n raise ValueError(\"Temperature value out of range (RawValue=0x%04X Max:0x3FFF)\" % raw_t)",
"def read_temp(self, request_number):\n try:\n\n status_log = \"{\\\"batch_id\\\":\\\"\" + request_number + \"\\\", \\\"brew_batch_stage\\\":\\\"Prep\\\", \\\"log\\\":\\\"Temperature\\\"}\"\n sn_log = ServiceNowLog()\n ServiceNowLog.create_new_log(sn_log, status_log)\n self.log_no = self.log_no + 1\n log = Log(self.log_no, \"Prep.Temperature\", \"Waiting to measure temperature of yeast\",\n datetime.datetime.now(), \"pass\")\n print(log.generate_log())\n time.sleep(sleep_time)\n ml = MongoLogging.MongoLogging()\n MongoLogging.MongoLogging.MongoLog(ml, request_number, \"Prep.Temperature\",\n \"Waiting to measure temperature of yeast\")\n time.sleep(sleep_time)\n temperature = random.randrange(55, 85, 1)\n input(\"\\033[1m 2. Press Enter to measure temperature of yeast: \\033[0m\\n\")\n time.sleep(sleep_time * 3)\n print('\\t\\t\\tTemp = \\033[1m{0:0.0f}*\\033[0;0m F'.format(temperature))\n time.sleep(sleep_time * 2)\n status_log = \"{\\\"batch_id\\\":\\\"\" + request_number + \"\\\", \\\"brew_batch_stage\\\":\\\"Prep\\\", \\\"log\\\":\\\"Temperature\\\"}\"\n sn_log = ServiceNowLog()\n ServiceNowLog.create_new_log(sn_log, status_log)\n self.log_no = self.log_no + 1\n log = Log(self.log_no, \"Prep.Temperature\", \"Temperature of yeast received\", datetime.datetime.now(), \"pass\")\n print(log.generate_log())\n ml = MongoLogging.MongoLogging()\n MongoLogging.MongoLogging.MongoLog(ml, request_number, \"Prep.Temperature\",\n \"Temperature of yeast received\")\n time.sleep(sleep_time * 2)\n return temperature\n except Exception as e:\n # Exception: checks if measurement has failed\n print(e)\n status_log = \"{\\\"batch_id\\\":\\\"\" + request_number + \"\\\", \\\"brew_batch_stage\\\":\\\"Prep\\\", \\\"log\\\":\\\"Temperature\\\"}\"\n sn_log = ServiceNowLog()\n ServiceNowLog.create_new_log(sn_log, status_log)\n self.log_no = self.log_no + 1\n log = Log(self.log_no, \"Prep.Temperature\", \"Failed to check temperature of yeast\", datetime.datetime.now(),\n \"fail\")\n print(log.generate_log())\n time.sleep(sleep_time * 2)\n ml = MongoLogging.MongoLogging()\n MongoLogging.MongoLogging.MongoLog(ml, request_number, \"Prep.Temperature\",\n \"Fail to check temperature of yeast\")\n time.sleep(sleep_time * 2)",
"def _determine_and_print_average_temperatures(\n logger: Logger, parsed_args: Namespace, system_data: Dict[float, SystemData]\n) -> None:\n\n def _print_temperature_info(\n average_temperature_map: Dict[str, float],\n logger: Logger,\n maximum_temperature_map: Dict[str, float],\n minimum_temperature_map: Dict[str, float],\n verbose_mode: bool = False,\n ) -> None:\n \"\"\"\n Prints out the average temperatures to the console and logger.\n\n :param average_temperature_map:\n A mapping between temperature name, as a `str`, and the average temperature for\n the run.\n\n :param logger:\n The logger used.\n\n :param maximum_temperature_run:\n A mapping between temperature name, as a `str`, and the maximum temperature for\n the run.\n\n :param minimum_temperature_run:\n A mapping between temperature name, as a `str`, and the minimum temperature for\n the run.\n\n :param verbose_mode:\n If True, then colouring will be done of the output to indicate that it is\n verbose-mode specific.\n\n \"\"\"\n\n logger.info(\n \"Average temperatures for the run in degC:\\n%s\\n%s\",\n \"|\".join(\n [\n \" {}{}\".format(\n key,\n \" \"\n * (\n max([len(key) for key in average_temperature_map])\n - len(key)\n + 1\n ),\n )\n for key in average_temperature_map\n ]\n ),\n \"|\".join(\n [\n \" {}{}\".format(\n value,\n \" \"\n * (\n max([len(key) for key in average_temperature_map])\n - len(str(value))\n + 1\n ),\n )\n for value in average_temperature_map.values()\n ]\n ),\n )\n print(\n \"{}Average temperatures for the run in degC:\\n{}\\n{}{}\".format(\n BColours.OKTEAL if verbose_mode else \"\",\n \"|\".join(\n [\n \" {}{}\".format(\n key,\n \" \"\n * (\n max([len(key) for key in average_temperature_map])\n - len(key)\n + 1\n ),\n )\n for key in average_temperature_map\n ]\n ),\n \"|\".join(\n [\n \" {}{}\".format(\n value,\n \" \"\n * (\n max([len(key) for key in average_temperature_map])\n - len(str(value))\n + 1\n ),\n )\n for value in average_temperature_map.values()\n ]\n ),\n BColours.ENDC,\n )\n )\n\n logger.info(\n \"Maximum temperatures for the run in degC:\\n%s\\n%s\",\n \"|\".join(\n [\n \" {}{}\".format(\n key,\n \" \"\n * (\n max([len(key) for key in maximum_temperature_map])\n - len(key)\n + 1\n ),\n )\n for key in maximum_temperature_map\n ]\n ),\n \"|\".join(\n [\n \" {}{}\".format(\n value,\n \" \"\n * (\n max([len(key) for key in maximum_temperature_map])\n - len(str(value))\n + 1\n ),\n )\n for value in maximum_temperature_map.values()\n ]\n ),\n )\n print(\n \"{}Maximum temperatures for the run in degC:\\n{}\\n{}{}\".format(\n BColours.OKTEAL if verbose_mode else \"\",\n \"|\".join(\n [\n \" {}{}\".format(\n key,\n \" \"\n * (\n max([len(key) for key in maximum_temperature_map])\n - len(key)\n + 1\n ),\n )\n for key in maximum_temperature_map\n ]\n ),\n \"|\".join(\n [\n \" {}{}\".format(\n value,\n \" \"\n * (\n max([len(key) for key in maximum_temperature_map])\n - len(str(value))\n + 1\n ),\n )\n for value in maximum_temperature_map.values()\n ]\n ),\n BColours.ENDC,\n )\n )\n\n logger.info(\n \"Minimum temperatures for the run in degC:\\n%s\\n%s\",\n \"|\".join(\n [\n \" {}{}\".format(\n key,\n \" \"\n * (\n max([len(key) for key in minimum_temperature_map])\n - len(key)\n + 1\n ),\n )\n for key in minimum_temperature_map\n ]\n ),\n \"|\".join(\n [\n \" {}{}\".format(\n value,\n \" \"\n * (\n max([len(key) for key in minimum_temperature_map])\n - len(str(value))\n + 1\n ),\n )\n for value in minimum_temperature_map.values()\n ]\n ),\n )\n print(\n \"{}Minimum temperatures for the run in degC:\\n{}\\n{}{}\".format(\n BColours.OKTEAL if verbose_mode else \"\",\n \"|\".join(\n [\n \" {}{}\".format(\n key,\n \" \"\n * (\n max([len(key) for key in minimum_temperature_map])\n - len(key)\n + 1\n ),\n )\n for key in minimum_temperature_map\n ]\n ),\n \"|\".join(\n [\n \" {}{}\".format(\n value,\n \" \"\n * (\n max([len(key) for key in minimum_temperature_map])\n - len(str(value))\n + 1\n ),\n )\n for value in minimum_temperature_map.values()\n ]\n ),\n BColours.ENDC,\n )\n )\n\n # Determine the average, minimum, and maximum temperatures.\n average_temperature_map = {\n \"pv\": round(mean({entry.pv_temperature for entry in system_data.values()}), 3),\n \"absorber\": round(\n mean({entry.absorber_temperature for entry in system_data.values()}), 3\n ),\n \"htf\": round(\n mean({entry.bulk_water_temperature for entry in system_data.values()}),\n 3,\n ),\n }\n maximum_temperature_map = {\n \"pv\": max({round(entry.pv_temperature, 3) for entry in system_data.values()}),\n \"absorber\": max(\n {round(entry.absorber_temperature, 3) for entry in system_data.values()}\n ),\n \"htf\": max(\n {round(entry.bulk_water_temperature, 3) for entry in system_data.values()}\n ),\n }\n minimum_temperature_map = {\n \"pv\": min({round(entry.pv_temperature, 3) for entry in system_data.values()}),\n \"absorber\": min(\n {round(entry.absorber_temperature, 3) for entry in system_data.values()}\n ),\n \"htf\": min(\n {round(entry.bulk_water_temperature, 3) for entry in system_data.values()}\n ),\n }\n\n if \"dg\" in parsed_args.layers:\n average_temperature_map[\"upper_glass\"] = round(\n mean({entry.upper_glass_temperature for entry in system_data.values()}), 3 # type: ignore\n )\n maximum_temperature_map[\"upper_glass\"] = max(\n {round(entry.upper_glass_temperature, 3) for entry in system_data.values()} # type: ignore\n )\n minimum_temperature_map[\"upper_glass\"] = min(\n {round(entry.upper_glass_temperature, 3) for entry in system_data.values()} # type: ignore\n )\n\n if \"g\" in parsed_args.layers:\n average_temperature_map[\"glass\"] = round(\n mean({entry.glass_temperature for entry in system_data.values()}), 3 # type: ignore\n )\n maximum_temperature_map[\"glass\"] = max(\n {round(entry.glass_temperature, 3) for entry in system_data.values()} # type: ignore\n )\n minimum_temperature_map[\"glass\"] = min(\n {round(entry.glass_temperature, 3) for entry in system_data.values()} # type: ignore\n )\n\n if not parsed_args.decoupled:\n average_temperature_map[\"tank\"] = round(\n mean({entry.tank_temperature for entry in system_data.values()}), 3 # type: ignore\n )\n maximum_temperature_map[\"tank\"] = max(\n {round(entry.tank_temperature, 3) for entry in system_data.values()} # type: ignore\n )\n minimum_temperature_map[\"tank\"] = min(\n {round(entry.tank_temperature, 3) for entry in system_data.values()} # type: ignore\n )\n\n # Print these out to the console.\n logger.info(\"Average, minimum, and maximum temperatures determined.\")\n _print_temperature_info(\n average_temperature_map,\n logger,\n maximum_temperature_map,\n minimum_temperature_map,\n True,\n )",
"def _build_parsed_values(self):\n match = BATTERY_DATA_REGEX.search(self.raw_data)\n if not match:\n raise SampleException(\n \"NortekEngBatteryDataParticle: No regex match of parsed sample data: [%r]\" % self.raw_data)\n\n # Calculate value\n battery_voltage = NortekProtocolParameterDict.convert_word_to_int(match.group(1))\n if battery_voltage is None:\n raise SampleException(\"No battery_voltage value parsed\")\n\n # report values\n result = [{DataParticleKey.VALUE_ID: NortekEngBatteryDataParticleKey.BATTERY_VOLTAGE,\n DataParticleKey.VALUE: battery_voltage}]\n log.debug('NortekEngBatteryDataParticle: particle=%r', result)\n return result",
"def extract_values(data, dig_t, dig_p, dig_h):\n raw_pressure, raw_temperature, raw_humidity = extract_raw_values(data)\n\n temperature, t_fine = improve_temperature_measurement(raw_temperature,\n dig_t)\n pressure = improve_pressure_measurement(raw_pressure, dig_p, t_fine)\n humidity = improve_humidity_measurement(raw_humidity, dig_h, t_fine)\n\n return temperature, pressure, humidity",
"def read_old():\n global previous_hum\n global previous_temp\n logging.debug(\"Start reading DHT22\")\n # Check if ther is a None item in the tuple\n if temp is None or hum is None:\n raise Exception('DHT22 reading exception')\n hum = validate(hum, previous_hum, 0, 100, 1, \"Humidity\")\n temp = validate(temp, previous_temp, -40, 80, 10, \"Temperature\")\n return (round(hum,1), round(temp,1))",
"def temperature(self):\n noun = 'DEV:T' + str(self.temperature_channel) + ':TEMP:SIG:TEMP'\n command = 'READ:' + noun + '\\r\\n'\n response = self.query_and_receive(command)\n\n return self.extract_value(response, noun, 'K')",
"def readTemp(self):\r\n\t\tdata = bus.read_i2c_block_data(MCP9808_DEFAULT_ADDRESS, MCP9808_REG_AMBIENT_TEMP, 2)\r\n\t\t\r\n\t\t# Convert the data to 13-bits\r\n\t\tcTemp = ((data[0] & 0x1F) * 256) + data[1]\r\n\t\tif cTemp > 4095 :\r\n\t\t\tcTemp -= 8192\r\n\t\tcTemp = cTemp * 0.0625\r\n\t\tfTemp = cTemp * 1.8 + 32\r\n\t\treturn {\"c\": cTemp, \"f\": fTemp}",
"def parse_line(line):\n\tif not line:\n\t\treturn None\n\n\t# Split our first 4 fields, and the string containing temperature values for each day of the month.\n\trecord, temperature_string = (line[:11], int(line[11:15]), int(line[15:17]), line[17:21]), line[21:]\n\n\t# raise exception if temperature_stirng is too short.\n\tif len(temperature_string) < 248:\n\t\traise ValueError(\"String not long enough - {} {}\".format(temperature_string, str(line)))\n\n\t# Use a list comprehension on temperature_string to extract and convert the values.\n\t# Notice how we use \"range()\" to extract each value. \n\t# Each numeric value is 5 characters, and they are each 8 characters apart.\n\t# Missing values for any day are indicated by a valud of \"-9999\".\n\tvalues = [ float(temperature_string[i:i+5])/10 for i in range(0, 248, 8) if not temperature_string[i:i+5].startswith(\"-9999\") ]\n\n\t# Calculate values based on all the days of the month.\n\tcount = len(values)\n\ttmax = round(max(values),1)\n\ttmin = round(min(values),1)\n\tmean = round(sum(values)/count,1)\n\n\t# Add our calculated values to the fields extracted earlier, and return them.\n\treturn record + (tmax, tmin, mean, count)",
"def get_temperatures(self):\n T = []\n if not self.temper:\n for lmp_file in self.lmp_files:\n for line in lmp_file:\n if \"velocity\" in line:\n T.append(re.findall(r'\\d+', line)[0])\n break\n else:\n for line in self.lmp_files[0]:\n if \"variable T world\" in line:\n T = re.findall(r'\\d+\\.?\\d*', line)\n break\n T.sort()\n return np.array(T, dtype=float)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Inserts new Logger Temperature in DB
|
def insert_logger_temp(self, records, logger_id):
# records is a list of dict
cursor = self.connection.cursor()
proper_counter = 0
query = """INSERT IGNORE INTO `cnx_logger_temperature` (`logger_id`, `Time_GMT`, `Temp_C`)
VALUES (%s, %s, %s)"""
values = [(logger_id, record.get("Time_GMT"), record.get("Temp_C")) for record in records]
try:
# duplicate entries are ignored while inserting data
cursor.executemany(query, values)
self.connection.commit()
proper_counter = cursor.rowcount
except MySQLdb.DatabaseError:
self.connection.rollback()
cursor.close()
self.update_summary_table(logger_id)
return proper_counter
|
[
"def log_temperature(temp):\n \n conn = sqlite3.connect(dbname)\n curs = conn.cursor()\n\n curs.execute(\"INSERT INTO temps values(datetime('now', 'localtime'), '{0}', '{1}' )\".format(temp['temperature'], temp['id']))\n\n conn.commit()\n conn.close()",
"def insert():\n\t#get values sent from sensors\n\tsensor_name = request.args.get('name')\n\tsensor_temperature = request.args.get('temperature')\n\n\t#add to database and get all values\n\tvalue = db.insert(sensor_name, sensor_temperature)\n\n\t#emit socket io to send values to dashboard\n\tsocketio.emit('update-sensors', value)\n\treturn {\"status\": 1, \"values\":value}",
"def _add_temperature_entry(self):\n self.temperature = round(uniform(95.0, 102.0), 2)\n\n notes = \"\"\n if choice([True, False, False, False]):\n notes = \" \".join(self.faker.sentences(randint(1, 5)))\n\n instance = models.Temperature.objects.create(\n child=self.child, temperature=self.temperature, time=self.time, notes=notes\n )\n instance.save()\n self._add_tags(instance)",
"def insert(cls, env, record):\n with env.db_transaction as db:\n\n cursor = db.cursor()\n sqlString = \"\"\"INSERT INTO ticket_template_store\n (tt_time,tt_user,tt_name,tt_field,tt_value)\n VALUES (%s,%s,%s,%s,%s)\"\"\"\n cursor.execute(sqlString, record)",
"def insertweather(values):\n weather = sqlModels.Weather()\n weather.weather_group = values['weather'][0]['main'] # TODO: is it the right data here?\n weather.temperature = values['main']['temp']\n weather.pressure = values['main']['pressure']\n weather.humidity_percentage = values['main']['humidity']\n weather.min_temperature = values['main']['temp_min']\n weather.max_temperature = values['main']['temp_max']\n weather.wind_speed = values['wind']['speed']\n if 'deg' in values['wind']:\n weather.wind_direction = values['wind']['deg']\n weather.cloudiness_percentage = values['clouds']['all']\n if 'rain' in values:\n weather.rain_quantity = values['rain']['3h']\n if 'snow' in values:\n weather.snow_quantity = values['snow']['3h']\n weather.sun_set = values['sys']['sunset']\n weather.sun_rise = values['sys']['sunrise']\n weather.calculation_time = values['dt']\n weather.latitude = values['coord']['lat']\n weather.longitude = values['coord']['lon']\n weather.city_name = values['name']\n weather.country_code = values['id']\n weather.save()",
"def insert_data(self, sensorname, value, timestamp = None):\n con = psycopg2.connect(**self.conn)\n cur = con.cursor()\n\n q = \"SELECT id FROM sensors WHERE name = '{0}'\".format(sensorname)\n cur.execute(q)\n ids = cur.fetchall()\n\n if len(ids) == 0:\n raise Exception('Sensor {0} does not exist in the database. Add it first using method create_new_sensor'.format(sensorname))\n\n ids = ids[0][0]\n\n if timestamp == None:\n q = \"INSERT INTO sensordata (sensorid, datatime, value) VALUES ({0}, now(), {1})\".format(ids, value)\n else:\n q = \"INSERT INTO sensordata (sensorid, datatime, value) VALUES ({0}, {1}, {2})\".format(ids, datetime.datetime.now, value)\n\n cur.execute(q)\n con.commit()\n\n con.close()",
"def insert(self, sql):",
"def test_insert_dict(self):\n value = {\"value1\": 56}\n temperature = temperature_record.TempTracer()\n result = temperature.insert(value)\n self.assertFalse(result)",
"def test_insert_number(self):\n value = 12\n temperature = temperature_record.TempTracer()\n result = temperature.insert(value)\n self.assertTrue(result)",
"def add_record(conn, data):\n\n query = \"\"\" INSERT INTO person(serial_num,fname,lname,birth_date,\n identification_num,street,city,postcode_num,phone_num,\n note,date_created)\n VALUES(?,?,?,?,?,?,?,?,?,?,?) \"\"\"\n data.append(str(datetime.now().strftime(\"%d/%m/%y %H:%M%S.%f\")))\n c = conn.cursor()\n c.execute(query, data)\n conn.commit()\n\n print(f\"SQL: Record ADDED | serial_num = {data[0]}\")",
"def save_sensors(data):\n decoded_data = json2obj(data)\n\n x = decoded_data.vdata.x\n y = decoded_data.vdata.y\n z = decoded_data.vdata.z\n t = decoded_data.vdata.t\n\n try:\n connection = mysql.connector.connect(host='localhost',\n database='ulceras_db',\n user='mnavas',\n password='mnavas123')\n mySql_insert_query = \"\"\"INSERT INTO sensors_data (sensor, property, x, y, z, timestamp)\n VALUES\n ('\"\"\"+decoded_data.sensor+\"\"\"', '\"\"\"+decoded_data.properties+\"\"\"', \"\"\"+str(x)+\"\"\", \"\"\"+str(y)+\"\"\", \"\"\"+str(z)+\"\"\", \"\"\"+str(t)+\"\"\") \"\"\"\n\n cursor = connection.cursor()\n cursor.execute(mySql_insert_query)\n connection.commit()\n print(cursor.rowcount, \"Record inserted successfully into sensor_data table\")\n cursor.close()\n\n except mysql.connector.Error as error:\n print(\"Failed to insert record into sensor_data table {}\".format(error))\n\n finally:\n if (connection.is_connected()):\n connection.close()\n print(\"MySQL connection is closed\")",
"def insert_dummy_temperatures(number_of_readings_per_probe=1000): \n readings = []\n probe_ids = hardware.temperature_probes.probe_ids \n for probe_number in range(0, number_of_readings_per_probe): \n for probe_id in probe_ids: \n readings.append(get_temperature_for_probe(probe_id, probe_number))\n database.db_adapter.store_temperatures(readings) \n database.db_adapter.db.commit()\n print 'Added ' + str(number_of_readings_per_probe * len(probe_ids)) + ' test temperature readings.'",
"def insert_info(self):\n\t\tself.get_connection()\n\t\tc = self.conn.cursor()\n\t\t#For every USER in the dictionary\n\t\tfor i in range(len(self.info['USER'])):\n\t\t\t#insert them into the database (I <3 SQL INJECTIONS)\n\t\t\tc.execute(\"INSERT OR REPLACE INTO '{tn}' ('{user}', '{dp}', '{g}', '{f}', '{l}', '{e}') VALUES ('{idv}', '{dpv}', '{gv}', '{fv}', '{lv}', '{ev}');\".\\\n\t\t\t\tformat(tn=self.tn, user=self.user, dp=self.dp, g=self.g, f=self.f, l=self.l, e=self.e,\n\t\t\t\t\tidv=self.info['USER'][i], dpv=self.info['pass'][i], gv=self.info['group'][i],\n\t\t\t\t\t fv=self.info['first'][i], lv=self.info['last'][i], ev=self.info['email'][i]))\n\t\t#Log this datbase manipulation\n\t\tself.log_users_creation()\n\t\t#commit to database and close connection\n\t\tself.commit_db()",
"def add_sensor_data():\n if not request.json or not 'value' in request.json:\n abort(400)\n\n #handle data obj\n sendat = HomeSensorData(\n name = request.json['name'],\n location = request.json['location'],\n category = request.json['category'], # actual or prediction\n measurementType = request.json['measurementType'],\n value = request.json['value'],\n dsCollected = request.json['dsCollected']\n )\n # add new record\n db.session.add(sendat)\n \n # conditional checks for prediction updates\n # 24 hours must have elapsed since last prediction\n # Atleast 7 days of data (24*7=168 records) \n\n # truncate old predictions\n #HomeSensorData.query.filter(HomeSensorData.category==\"pred\",\n # HomeSensorData.name==request.json['name']).delete()\n\n # get \"actual\" data\n actuals = HomeSensorData.query.filter(HomeSensorData.category==\"actual\",\n HomeSensorData.name==request.json['name'])\n\n # create pandas dataframe\n\n # create rolling mean (4 hour window)\n\n # create regular intervals (1 hour)\n\n # create new columns and \"shift\" n hours (48 records for one day=48 cols) \n\n # create a target column (shift(-24) hours)\n\n # random forest prediction\n\n # merge datestamp with predictions (now to 24 hours)\n\n # create list of dictionaries with sensor data\n\n # add all new predictions\n\n # commit all changes include deletion and recreation of predictions\n db.session.commit()\n return \"Record added successfully\\n\"",
"def insertDiscoveryPersist(\n service_name,\n ip,\n port,\n current_time_stamp,\n status,\n retryid):\n DB_PATH = Config.getDbPath()\n conn = sqlite3.connect(DB_PATH)\n conn.execute(\n \"\"\"INSERT INTO DISCOVERY_LOGS (SERVICE_NAME, IP, PORT, TIME_STAMP, STATUS, RETRY_ID) \\\n VALUES (?, ?, ?, ?, ?, ?)\"\"\",\n (service_name,\n ip,\n port,\n current_time_stamp,\n status,\n retryid))\n conn.commit()\n conn.close()",
"def insert_into_influxdb(measurement, value):\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n payload = \"{} value={}\".format(measurement, value)\n requests.post(INFLUXDB_URL, headers=headers, data=payload)",
"def add_to_database(results):\n\n err = CLIENT.write(['%s,hashid=%s warnings=%d,errors=%d,status=\"%s\"' % (DB_NAME, results['hashid'], results['warnings'], results['errors'], results['status'])], {'db':DB_NAME}, protocol='line')\n if not err:\n log_to_file (\"[ERROR] %s fail to post to InfluxDB\" % (results['hashid']))",
"def insert_data(api_call, timestamp):\n location = api_call[\"name\"]\n temp = api_call[\"main\"][\"temp\"]\n utcdt = api_call[\"dt\"]\n condition = [item[\"main\"] for item in api_call[\"weather\"]]\n\n with contextlib.closing(sqlite3.connect(\"weather_test1.db\")) as cursor:\n # cursor.execute(\"INSERT INTO weather VALUES (\"\n cursor.execute(\n \"INSERT OR IGNORE INTO weather VALUES (\"\n \":location, :temp, :conditions, :utc_epoch, :local)\",\n {\n \"location\": location,\n \"temp\": temp,\n \"conditions\": condition[0],\n \"utc_epoch\": utcdt,\n \"local\": timestamp,\n },\n )\n cursor.commit()",
"def test_insert_empty(self):\n value = None\n temperature = temperature_record.TempTracer()\n result = temperature.insert(value)\n self.assertFalse(result)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Fetch logger_id according to microsite_id
|
def find_microsite_id(self, microsite_id):
cursor = self.connection.cursor()
query = """SELECT `logger_id` as 'logger_id' FROM `cnx_logger` WHERE microsite_id=%s"""
cursor.execute(query, (microsite_id,))
results = cursor.fetchone()
cursor.close()
if results is None:
return None
else:
return results[0]
|
[
"def check_for_duplicate(self, cursor, microsite_id):\n query = \"\"\"SELECT `logger_id`\n FROM `cnx_logger`\n WHERE `microsite_id`=%s\"\"\"\n cursor.execute(query, (microsite_id,))\n results = cursor.fetchall()\n results = list(results)\n return len(results) > 0",
"def get_log_id(self) -> str:\n pass",
"def get_log_id(self) -> str:\n return self.log_id",
"def _log_request_id(request_id):\n request = list(logservice.fetch(\n include_incomplete=True, include_app_logs=True, request_ids=[request_id]))\n if not request:\n logging.info('Dang, didn\\'t find the request_id %s', request_id)\n return None\n assert len(request) == 1, request\n return request[0]",
"def get_log_id(self):\n return # osid.id.Id",
"def _site_id(self):\n self.last_site_index = (self.last_site_index + 1) % len(self.site_device)\n return list(self.site_device.keys())[self.last_site_index]",
"def get_log(log_id):\n# print('¤'*100)\n# print('¤'*100)\n# print('¤'*100)\n# print(logging.Logger.manager.loggerDict.keys())\n# print('¤'*100)\n for item in logging.Logger.manager.loggerDict.keys():\n# print('{} _ {}'.format(log_id, item))\n if log_id in item:\n log_id = item\n break\n return logging.getLogger(log_id)",
"def get_litter_robot_id(self, call_data):\n litter_robot_id = call_data.get('litter_robot_id', None)\n if litter_robot_id is not None:\n return [x for x\n in self._hass.data[DOMAIN][LITTER_ROBOTS]\n if x['litterRobotId'] == litter_robot_id][0]['litterRobotId']\n return self._hass.data[DOMAIN][LITTER_ROBOTS][0]['litterRobotId']",
"def record_id(uri):\n parsed = urlparse.urlparse(uri)\n return urlparse.parse_qs(parsed.query)['persistentId'][0]",
"def get_log_hierarchy_id(self):\n return # osid.id.Id",
"def get_tiki_blog_id(tiki_connection, tiki_blog_name):\n statement =\\\n \"SELECT blogId FROM `tiki_blogs`\" +\\\n \" WHERE title = \" + sql_quote(tiki_blog_name)\n cursor = tiki_connection.Execute(statement)\n for row in cursor:\n return row[0]\n\n return None",
"def get_log(self, log_id):\n return # osid.logging.Log",
"def get_build_id(log_file):\n\n # Initialize variables\n build_id = None\n\n # Read in the first line of the log file\n with open(log_file, 'r') as input_fh:\n log_line = input_fh.readline()\n\n # Split the line\n line_split = filter(None, re.split('[\" ]', log_line))\n\n # Find the build ID parameter\n for item in line_split:\n if item.startswith('build'):\n build_id = item\n break\n\n return build_id",
"def get_log_ids_by_log_entry(self, log_entry_id):\n return # osid.id.IdList",
"def inject_thread_id(record):\n record.extra[THREAD_ID_KEY] = get_ident()",
"def get_parent_logs(self, log_id):\n return # osid.logging.LogList",
"def collect_id(event):\n return event.get('trace_id')",
"def get_wikidata_id(wikidata_uri):\n wikidata_base_uri = \"http://www.wikidata.org/entity/\"\n if wikidata_uri.startswith(wikidata_base_uri):\n wikidata_id = wikidata_uri[len(wikidata_base_uri):]\n else:\n wikidata_id = None\n return wikidata_id",
"def get_logbook_id(self, logbook_num, archive_id):\n\n sql = ('SELECT logbook_id FROM {} '\n 'WHERE archive_id=%s AND logbook_num=%s'\n .format(self.table_name('logbook')))\n logbook_id = self.db.execute_query(sql, (archive_id, logbook_num))\n return logbook_id"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
This method updates the summary table with count, min and max dates of the microsite id of the temperature records inserted
|
def update_summary_table(self, logger_id):
cursor = self.connection.cursor()
select_query = ("""SELECT COUNT(*), MIN(Time_GMT), MAX(Time_GMT)
FROM cnx_logger_temperature WHERE logger_id=%s""")
cursor.execute(select_query, (logger_id,))
select_results = cursor.fetchone()
cursor.close()
if select_results is not None:
cursor = self.connection.cursor()
try:
update_query = """INSERT INTO `cnx_logger_metadata`
(logger_id, logger_count, logger_min_date, logger_max_date)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
logger_count = VALUES(logger_count),
logger_min_date = VALUES(logger_min_date),
logger_max_date = VALUES(logger_max_date)"""
cursor.execute(update_query, (logger_id, select_results[0], \
select_results[1], select_results[2]))
self.connection.commit()
cursor.close()
except MySQLdb.DatabaseError:
self.connection.rollback()
|
[
"def update_all():\r\n \r\n # Delete everything in summary table\r\n q_string = \"\"\"\r\n\tTRUNCATE summary;\r\n \"\"\"\r\n try:\r\n cursor.execute(q_string)\r\n except:\r\n print(\"ERROR: Could not delete summary table data\")\r\n sys.exit()\r\n print(\"Summary table truncated.\")\r\n \r\n # Determine date range to use from query table in database\r\n q_string = \"\"\"\r\n SELECT max(qdate), min(qdate)\r\n FROM query;\r\n \"\"\"\r\n try:\r\n cursor.execute(q_string)\r\n result = cursor.fetchall()\r\n except:\r\n print(\"ERROR: Could not fetch dates from query table\")\r\n sys.exit()\r\n \r\n dates = pandas.date_range(start=result[0][1], end=result[0][0])\r\n date1 = datetime.datetime.strftime(result[0][0], '%Y-%m-%d')\r\n date2 = datetime.datetime.strftime(result[0][1], '%Y-%m-%d')\r\n \r\n # Pull in all new summary data using commit_summary() on a loop.\r\n print('Please be patient, populating summary table from {} to {}.'.format(date2, date1))\r\n \r\n for date in dates:\r\n try:\r\n pulldate = datetime.datetime.strftime(date, '%Y-%m-%d')\r\n commit_summary(pulldate)\r\n except:\r\n print(\"ERROR: Missing date {} from database.\".format(pulldate))\r\n pass\r\n \r\n print('Added summary table data for date range: {} to {}.'.format(date2, date1))\r\n \r\n # Update state and candidate table based on the most recent date from\r\n # query table in database.\r\n update_state_winner(date1)\r\n print('Updated state table with candidate winner using 7 day average.')\r\n update_candidate_delegates(date1)\r\n print('Updated average number of delegates per candidate over 7 days.')\r\n \r\n print('Complete.')",
"def update_summary(self):\n self.n_patients = self.table[\"sample_size\"][0]\n self.n_snps = len(self.table)\n self.min_maf = np.min(self.table[\"maf\"].values)\n self.max_maf = np.max(self.table[\"maf\"].values)\n self.min_ld = np.min(self.table[\"l\"].values)\n self.max_ld = np.max(self.table[\"l\"].values)\n self.avg_stats = np.average(self.table[\"stats\"].values)\n self.n_genes = len(set(self.table[\"gene\"].values.tolist()))",
"def upload_summaries(self):\n logger.info(\"Upload summaries.\")\n db_connect.wipe_database_upload(model_version_id=self.model_version_id,\n conn_def=self.conn_def)\n data = self.data_summaries[['model_version_id', 'year_id', 'location_id', 'sex_id',\n 'age_group_id', 'mean_cf', 'lower_cf', 'upper_cf',\n 'inserted_by',\n 'last_updated_by', 'last_updated_action']].reset_index(drop=True)\n db_connect.write_data(df=data, db='cod', table='model', conn_def=self.conn_def)",
"def update_users_count_data(self):\n users = self.users_db.find({\"status\":\"active\"})\n total_current_users = users.count()\n #insert present data# sort the dict and remove the last one\n admin_data = self.admin_db.find_one({\"entitled\":\"all\"})\n user_trend_count = admin_data[\"userCountTrend\"]\n curr_date = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n min_key = min(user_trend_count.keys())\n if(len(user_trend_count)>=1):\n del user_trend_count[min(user_trend_count.keys())]\n user_trend_count[str(curr_date)] = total_current_users\n self.admin_db.update_one({\"entitled\": \"all\"}, {\"$set\": {\"userCountTrend\":user_trend_count}})",
"def manual_temp_imputation(self): \n\n self.data = self.data.sort_values(['series_id', 'timestamp'])\n\n print(self.data.loc[self.data.series_id == 100948,\"temperature\"])\n\n # one timestamp before\n self.data['temperature'] = self.data['temperature'].fillna(self.data.groupby(['series_id'])['temperature'].\\\n ffill())\n # one timestamp after\n self.data['temperature'] = self.data['temperature'].fillna(self.data.groupby(['series_id'])['temperature'].\\\n bfill())\n # same time one day ago\n self.data['temperature'] = self.data['temperature'].fillna(self.data.groupby(['series_id', 'hour'])\\\n ['temperature'].ffill())\n # same time one year ago\n self.data['temperature'] = self.data['temperature'].fillna(self.data.groupby(['series_id', 'dayofyear'])\\\n ['temperature'].ffill())\n # same week (mean)\n self.data['temperature'] = self.data.groupby(['series_id', 'week']).temperature.\\\n transform(lambda x:x.fillna(x.mean()))\n # same month (mean)\n self.data['temperature'] = self.data.groupby(['series_id', 'month']).temperature.\\\n transform(lambda x:x.fillna(x.mean()))\n # same timestamp, surface, base_temperature (mean)\n self.data['temperature'] = self.data.groupby(['timestamp', 'surface', 'base_temperature']).temperature. \\\n transform(lambda x:x.fillna(x.mean()))\n # one timestamp before\n self.data['temperature'] = self.data['temperature'].fillna(self.data.groupby(['series_id'])['temperature']. \\\n ffill())\n # same timestamp mean\n self.data['temperature'] = self.data.groupby(['timestamp']).temperature.transform(lambda x:x.fillna(x.mean()))\n\n print(self.data.loc[self.data.series_id == 100948,\"temperature\"])\n\n self._logger.info(\"Complete imputation for temperature.\")",
"def update_daily_measurements(data):\n for i in data:\n key = {'_id': i['_id']}\n db.device_daily_measurements.replace_one(key, i, upsert=True)",
"def updateDailyHistoryDatabase(self):\n\n # Query to history database\n lastDay = datetime.date.today() - datetime.timedelta(days=1)\n minVal = datetime.datetime.combine(lastDay, datetime.datetime.min.time())\n maxVal = datetime.datetime.combine(lastDay, datetime.datetime.max.time())\n data = self.dbc.queryBetweenValues(self.historyDataName, 'date', formatDatetime(minVal), formatDatetime(maxVal))\n dailyData = dict.fromkeys(self.dbDailyHistoryHeader, 0)\n dailyData['date'] = formatDatetime(lastDay)\n numValues = dict.fromkeys(self.sensorTypes, 0)\n\n # Initialization of dailyData\n for column in dailyData:\n if 'MIN' in column:\n dailyData[column] = float('inf')\n elif 'MAX' in column:\n dailyData[column] = float('-inf')\n elif 'AVG' in column:\n dailyData[column] = 0.\n\n # Calculus of MIN, MAX and addition of all values to AVG\n for entry in data:\n for key,value in entry.items():\n if key != 'date' and value != None:\n dailyData[key + 'MIN'] = min(dailyData[key + 'MIN'], value)\n dailyData[key + 'MAX'] = max(dailyData[key + 'MAX'], value)\n dailyData[key + 'AVG'] += value\n numValues[key] += 1\n\n # Calculus of AVG\n for key in self.sensorTypes.keys():\n if numValues[key] != 0:\n dailyData[key + 'AVG'] = round(dailyData[key + 'AVG']/numValues[key],1)\n else:\n # there is no value registered for this sensor in 'lastDay'\n dailyData[key + 'AVG'] = None\n dailyData[key + 'MIN'] = None\n dailyData[key + 'MAX'] = None\n\n # Update daily history database.\n self.dbc.insert(self.dailyHistoryDataName, dailyData)\n\n # Change next update time\n nextUpdate = self.alarms.getNextUpdateStr('updateDailyHistory')\n self.dbc.update(\"nextUpdates\", {\"nextUpdate\":nextUpdate}, \"name\", \"dailyHistory\")\n\n print('Inserted data to daily history')",
"def summary_table(self):\n\n sql_st = '''\n INSERT OR IGNORE INTO expenses(yr, mnth, dy, general_name, comp_type,value)\n SELECT yr, mnth, dy, general_name, comp_type,value\n FROM exp_type_loc\n '''\n\n cur = self.conn.cursor()\n cur.execute(sql_st)\n self.conn.commit()",
"def day_stats(meta, resource, time_index, hour_range=(7, 17)):\n\n # Here are the times in UTC\n print(\"Converting date strings to datetime objects...\")\n time_array = np.array([t.astype(\"str\")[:-13] for t in time_index])\n time = [dt.datetime.strptime(t, \"%Y-%m-%dT%H:%M\") for t in time_array]\n\n # Add time to end of temp - memory management is important here.\n print(\"Setting up local time filter process...\") \n adj = np.array([meta[\"zone\"].values])\n combined = da.concatenate([resource, adj]).compute()\n\n # This needs to be on disk to avoid memory spikes\n with h5py.File(\"/scratch/twillia2/fleet/temp.h5\", \"w\") as temp:\n temp.create_dataset(name=\"temperature_tz\", data=combined)\n del combined\n\n # Use Dask distributed to schedule workers\n with Client() as client:\n # Print IP address of dask dashboard?\n print(\"Calculating summary statistics. \\nDask Scheduler \" + \n str(client).replace(\"<\", \"\").replace(\">\", \"\") + \n \"\\nDask Diagnostics Dashboard: 'http://127.0.0.1:8787/status'\") \n \n with h5py.File(\"/scratch/twillia2/fleet/temp.h5\", \"r\") as ds:\n combined = da.from_array(ds[\"temperature_tz\"], chunks=\"auto\")\n \n filtered = np.apply_along_axis(tz_filter, axis=0, arr=combined,\n time_list=time, time_range=(7, 17))\n min_values = filtered.min(axis=0).compute()\n max_values = filtered.max(axis=0).compute()\n mean_values = filtered.mean(axis=0).compute()\n\n meta[\"max_value\"] = max_values\n meta[\"min_value\"] = min_values\n meta[\"mean_values\"] = mean_values\n\n return meta",
"def process_aggregation(month):\n\n # input variables\n filepath = \"/home/jen/projects/ace_data_management/wip/cruise_track_data\"\n one_sec_resolution_filename = \"ace_cruise_track_1sec_{}.csv\".format(month)\n date_column_list = [0]\n \n datatypes = { 'latitude': 'float64',\n 'longitude': 'float64',\n 'fix_quality': 'int8',\n 'number_satellites': 'int8',\n 'horiz_dilution_of_position': 'float16',\n 'altitude': 'float16',\n 'altitude_units': 'category',\n 'geoid_height': 'float16',\n 'geoid_height_units': 'category',\n 'device_id': 'int8',\n 'speed': 'float64',\n 'measureland_qualifier_flags_overall': 'int8'}\n\n output_filename_minute = \"ace_cruise_track_1min_{}.csv\".format(month)\n output_filename_hour = \"ace_cruise_track_1hour_{}.csv\".format(month)\n columns = ['date_time', 'latitude', 'longitude', 'fix_quality', 'number_satellites', 'horiz_dilution_of_position',\n 'altitude', 'altitude_units', 'geoid_height', 'geoid_height_units', 'device_id', 'speed', 'measureland_qualifier_flag_overall']\n\n # get the data from the csv files (1 second resolution)\n second_res_df = cruise_track_data_processing_utils.get_data_from_csv(filepath, one_sec_resolution_filename, datatypes, date_column_list)\n\n print(\"Number of rows in second resolution file: \", len(second_res_df))\n\n # check what is to be expected once aggregated\n investigate_aggregation_by_time(second_res_df)\n\n # do one minute resolution\n minute_res_df = get_minute_resolution(second_res_df)\n output_dataframe_to_csv(minute_res_df, columns, filepath, output_filename_minute)\n\n # do one hour resolution\n hour_res_df = get_hour_resolution(second_res_df)\n output_dataframe_to_csv(hour_res_df, columns, filepath, output_filename_hour)\n\n # do plots and checking of output aggregations\n plot_aggregated_data_separate_graphs(minute_res_df, hour_res_df, month)\n\n plot_aggregated_data_same_axes(minute_res_df, hour_res_df, month)\n\n check_aggregation_output(second_res_df)",
"def init_measurements_collection(self):\n self.measurements_collection.create_index(\"device_id\")\n self.measurements_collection.create_index(\"timestamp_ms\")",
"def generate_summary(weather_data):\n count = 0\n min_temps = []\n max_temps = []\n date_time = []\n\n for index, item in enumerate(weather_data):\n if index != []:\n count += 1\n date_time.append(item[0])\n min_temps.append(item[1])\n max_temps.append(item[2])\n \n min_temp, index_date_min = find_min(min_temps)\n max_temp, index_date_max = find_max(max_temps)\n\n min_temps_c = convert_f_to_c(str(min_temp))\n max_temps_c = convert_f_to_c(str(max_temp))\n\n date_min = date_time[index_date_min]\n date_max = date_time[index_date_max]\n\n mean_min_c = convert_f_to_c(calculate_mean(min_temps))\n mean_max_c = convert_f_to_c(calculate_mean(max_temps))\n\n result = \"\"\n result += f\"{count} Day Overview\\n\"\n result += f\" The lowest temperature will be {format_temperature(min_temps_c)}, and will occur on {convert_date(date_min)}.\\n\"\n result += f\" The highest temperature will be {format_temperature(max_temps_c)}, and will occur on {convert_date(date_max)}.\\n\"\n result += f\" The average low this week is {format_temperature(mean_min_c)}.\\n\"\n result += f\" The average high this week is {format_temperature(mean_max_c)}.\\n\"\n\n return result",
"def US_cml_top10_tracker_update():\n \n import pandas as pd\n from datetime import datetime\n US = US_tracker_update()\n\n US['state_county'] = US['state'] + \"_\" + US['county'] \n US['days_since_150_cases'] = \"\" \n date_list = np.unique(US[\"date\"].dt.strftime('%Y-%m-%d')).tolist()\n\n last_date = max(np.unique(US[\"date\"].dt.strftime('%Y-%m-%d')).tolist())\n\n US[\"total_num_infections\"] = US.groupby('county')['num_infections'].cumsum()\n US[\"total_num_deaths\"] = US.groupby('county')['num_deaths'].cumsum()\n\n US_today = US.loc[(US.date == last_date)]\n US_today.sort_values(by = 'total_num_infections', ascending = False, inplace=True)\n top10 = US_today.head(10)\n\n county_list = top10.state_county.tolist()\n\n county_name = []\n over150 = []\n\n for county in county_list:\n for date in date_list:\n if US.loc[(US.date == date) & (US.state_county == county)].total_num_infections.values[0] > 150:\n over150.append(date)\n county_name.append(county)\n break\n\n top10 = US.loc[(US.state_county == county_name[0])]\n for county in county_name[1:]:\n top10 = pd.concat([top10, US.loc[(US.state_county == county)]])\n\n\n over150 = [datetime.strptime(x, '%Y-%m-%d') for x in over150]\n for x in range(0,len(county_name)):\n for i in range(0,len(top10)):\n infection_date = over150[x]\n if top10.iloc[i,5] == county_name[x] and top10.iloc[i,0] == infection_date:\n top10.iloc[i,6] = 1\n elif top10.iloc[i,5] == county_name[x] and top10.iloc[i,0] >= infection_date:\n top10.iloc[i,6] = top10.iloc[i-1,6] + 1\n elif top10.iloc[i,5] == county_name[x] and top10.iloc[i,0] < infection_date:\n top10.iloc[i,6] = (top10.iloc[i,0] - over150[x]).days\n \n \n top10 = top10.drop(['num_infections','num_deaths', 'state_county'], axis=1)\n top10.reset_index(drop = True, inplace= True)\n return top10",
"def update_summary(self, new_info):\r\n name = new_info['name']\r\n if name not in self.summary_dict:\r\n self.summary_dict[name] = \\\r\n TabularSummary(value_cols=self.op.value_columns, skip_cols=self.op.skip_columns, name=name)\r\n self.summary_dict[name].update(new_info['df'])",
"def fix_time_adjustment(weather_train:pd.DataFrame, weather_test:pd.DataFrame):\r\n # weather_train['DataType'], weather_test['DataType'] = 'train', 'test'\r\n weather_key = ['site_id', 'timestamp']\r\n weather = pd.concat([weather_train, weather_test], ignore_index=True, axis=0, sort=False)\r\n temp_skeleton = weather[weather_key + ['air_temperature']].drop_duplicates(subset=weather_key).sort_values(by=weather_key).copy()\r\n data_to_plot = temp_skeleton.copy()\r\n data_to_plot[\"hour\"] = data_to_plot[\"timestamp\"].dt.hour\r\n count = 1\r\n fig = plt.figure(figsize=(25, 15))\r\n for site_id, data_by_site in data_to_plot.groupby('site_id'):\r\n by_site_by_hour = data_by_site.groupby('hour').mean()\r\n ax = plt.subplot(4, 4, count)\r\n plt.plot(by_site_by_hour.index, by_site_by_hour['air_temperature'], 'xb-')\r\n ax.set_title('site: ' + str(site_id))\r\n count += 1\r\n plt.tight_layout()\r\n plt.show()\r\n # fig.savefig(cfg.eda_dir + \"/air_temperature_before_Adjustment.png\")\r\n del data_to_plot\r\n temp_skeleton['temp_rank'] = temp_skeleton.groupby(['site_id', temp_skeleton.timestamp.dt.date])[\r\n 'air_temperature'].rank('average')\r\n df_2d = temp_skeleton.groupby(['site_id', temp_skeleton.timestamp.dt.hour])['temp_rank'].mean().unstack(level=1)\r\n site_ids_offsets = pd.Series(df_2d.values.argmax(axis=1) - 14)\r\n site_ids_offsets.index.name = 'site_id'\r\n\r\n def timestamp_align(df):\r\n df['offset'] = df.site_id.map(site_ids_offsets)\r\n df['timestamp_aligned'] = (df.timestamp - pd.to_timedelta(df.offset, unit='H'))\r\n df['timestamp'] = df['timestamp_aligned']\r\n del df['timestamp_aligned'], df['offset']\r\n return df\r\n\r\n return timestamp_align(weather_train), timestamp_align(weather_test)",
"def calc_temps(num_days, num_years, search_dates, engine):\n # import necessary modules\n import numpy as np\n import pandas as pd\n \n # set up sqlalchemy engine\n from sqlalchemy import create_engine\n engine = engine\n\n # set up sqlalchemy base\n from sqlalchemy.ext.automap import automap_base\n Base = automap_base()\n Base.prepare(engine, reflect=True)\n\n # map classes\n Station = Base.classes.stations\n Measurement = Base.classes.measurements\n \n final_result_list = []\n dict_result_list = []\n\n # get list of dataframes where each date has a df with all needed data\n for i in np.arange(num_days + 1):\n temp_result_df = pd.DataFrame()\n for j in np.arange(num_years):\n query = f'SELECT date, temp AS \"Temp\" FROM measurements \\\n WHERE date = \"{search_dates[i][j].strftime(\"%Y-%m-%d\")}\"'\n temp_result_df = temp_result_df.append((pd.read_sql(query, engine)),\n ignore_index=True)\n \n final_result_list.append(temp_result_df)\n \n # iterate through each dataframe and get the min, max, etc\n for i in np.arange(num_days + 1):\n curr_df = final_result_list[i]\n curr_df['year'], curr_df['month'], curr_df['day'] = curr_df['date'].str.split('-', 2).str\n dict_result_list.append({'date':curr_df['date'][0],\n 'month':curr_df['month'][0],\n 'year':curr_df['year'][0],\n 'min_temp':(curr_df.groupby('day').min()['Temp'][0]), \n 'max_temp':(curr_df.groupby('day').max()['Temp'][0]),\n 'avg_temp':(curr_df.groupby('day').mean()['Temp'][0])})\n \n # create dataframe\n result_df= pd.DataFrame.from_records(dict_result_list, \n columns=['date', 'avg_temp', 'max_temp', 'min_temp'])\n \n # clean dataframe\n result_df['year'], result_df['month/day'] = (result_df['date'].\n str.split('-', 1).\n str)\n result_df.drop(columns=['year','date'], inplace=True)\n result_df = result_df[['month/day', 'avg_temp', 'min_temp', 'max_temp']]\n \n # add column with difference between min, avg, and max\n result_df['avg/min diff'] = result_df['avg_temp'] - result_df['min_temp']\n result_df['avg/max diff'] = result_df['max_temp'] - result_df['avg_temp']\n \n return result_df;",
"def updateHistoryDatabase(self):\n\n # Compute means from the received values.\n newValues = {'date' : getTimestamp()}\n nullKeys = []\n for elem in self.sensorSum.keys():\n if self.sensorNum[elem] == 0:\n newValues[elem] = None\n nullKeys.append(elem)\n else:\n newValues[elem]= round(self.sensorSum[elem]/self.sensorNum[elem], 1)\n\n if len(nullKeys) != 0:\n logger.warning('-History update- No data received for %s', ', '.join(nullKeys))\n \n logger.info('-History update- %s', ', '.join(\"%s:%i\" % (k,v) for k,v in self.sensorNum.items()))\n\n # Update database\n self.dbc.insert(self.historyDataName, newValues)\n\n # Change next update time\n nextUpdate = self.alarms.getNextUpdateStr('updateHistory')\n self.dbc.update(\"nextUpdates\", {\"nextUpdate\":nextUpdate}, \"name\", \"history\")\n\n print('Inserted data to history')\n\n # Reset data\n self.sensorSum = dict.fromkeys(self.sensorSum, 0)\n self.sensorNum = dict.fromkeys(self.sensorNum, 0)",
"def insert_dummy_temperatures(number_of_readings_per_probe=1000): \n readings = []\n probe_ids = hardware.temperature_probes.probe_ids \n for probe_number in range(0, number_of_readings_per_probe): \n for probe_id in probe_ids: \n readings.append(get_temperature_for_probe(probe_id, probe_number))\n database.db_adapter.store_temperatures(readings) \n database.db_adapter.db.commit()\n print 'Added ' + str(number_of_readings_per_probe * len(probe_ids)) + ' test temperature readings.'",
"def db_update_metrics():\n db_put_metrics(get_metric_list())"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns the underlying neural network.
|
def neural_network(self):
return self._neural_network
|
[
"def inference_network(self):\n return self.DNN",
"def get_network(self) -> nx.Graph:\n return self.graph",
"def train_network(self):\n return self._train_network",
"def build(self) -> NeuralNetworkModel:\n return NeuralNetworkModel(\n self.node_counts, self.activation_functions, self.weights, self.biases\n )",
"def eval_network(self):\n return self._eval_network",
"def internal_network(self):\n ret = self._get_attr(\"internalNetwork\")\n return ret",
"def _initialize_neural_network(self, topology):\n\n # Create shallow copy of topology.\n neural_network = copy(topology)\n # Create output neuron.\n neural_network.output_neuron = create_neuron('identity', None)\n # Create hidden layer.\n neural_network.hidden_layers = self._initialize_hidden_layers(neural_network)\n # Establish connections\n self._connect_nodes(neural_network.sensors, neural_network.hidden_layers[0], random=True)\n previous_neurons = neural_network.hidden_layers[0]\n for hidden_layer in neural_network.hidden_layers[1:]:\n self._connect_nodes(previous_neurons, hidden_layer, random=False)\n previous_neurons = hidden_layer\n # Calculate hidden neurons.\n for layer in neural_network.hidden_layers:\n for neuron in layer:\n neuron.calculate()\n # Connect last neuron to output neuron with learning step.\n self._connect_learning_step(neural_network)\n # Calculate output semantics.\n neural_network.output_neuron.calculate()\n # Return neural network.\n return neural_network",
"def nat_network(self):\n ret = self._get_attr(\"NATNetwork\")\n return ret",
"def net(self, net=None):\n if net is not None:\n NetBuilder.current().add(net)\n return net\n return NetBuilder.current().current_net()",
"def _mutate_network(self):\n\n # Create shallow copy of champion neural network.\n neural_network = copy(self.champion.neural_network)\n # Create mutated hidden layers.\n mutation_layers = self.mutation_operator.mutate_network(self)\n # Connect hidden neurons to remainder of network.\n self._connect_nodes_mutation(mutation_layers)\n # Calculate mutated hidden layer.\n for mutation_layer in mutation_layers:\n for neuron in mutation_layer:\n neuron.calculate()\n # Extend hidden layers.\n for hidden_layer, mutation_layers in zip(neural_network.hidden_layers, mutation_layers):\n hidden_layer.extend(mutation_layers)\n # Connect final hidden neuron to output neuron.\n self._connect_learning_step(neural_network)\n # Get most recent connection.\n connection = neural_network.output_neuron.input_connections[-1]\n # Update semantics of output neuron.\n neural_network.output_neuron.semantics += connection.from_node.semantics * connection.weight\n # Return neural network.\n return neural_network",
"def getOutputNeuron(self):\n return self.outputNeuron",
"def return_network(self):\n return self.mention_network",
"def get_network_object(self):\n return self.g",
"def create_network(self, neurons_input=1, neurons_hidden=0):\n\t\t\n\t\tself.rate = 0.01\t#Learning rate\n\t\tself.weights_input = []\n\t\tself.weights_hidden = []\n\t\tself.weights_output = []\n\t\tself.neurons_input = neurons_input\n\t\tself.neurons_hidden = neurons_hidden\n\n\t\tif neurons_input > 1:\n\t\t\tneurons_output = 1\n\t\telse:\n\t\t\tneurons_output = 0\n\t\tself.neurons_output = neurons_output\n\n\t\t# set random starting weights\n\t\tfor i in range(neurons_input):\n\t\t\tself.weights_input.append(randint(-1,1))\n\t\tfor i in range(neurons_hidden):\n\t\t\tfor j in range(neurons_input*neurons_hidden):\n\t\t\t\tself.weights_hidden.append(randint(-1,1))\n\t\tfor i in range(neurons_output):\n\t\t\tfor j in range(neurons_hidden):\n\t\t\t\tself.weights_output.append(randint(-1,1))",
"def ip_network(self):\n return netaddr.IPNetwork(self.net)",
"def get_neural_net_output(input, neural_net):\n\tfor layer_index, layer in enumerate(neural_net):\n\t\tfor neuron_idx, neuron in enumerate(layer):\n\t\t\tif layer_index == 0:\n\t\t\t\tneural_net[layer_index][neuron_idx].input = input[neuron_idx]\n\t\t\t\tneural_net[layer_index][neuron_idx].output = input[neuron_idx]\n\t\t\telse:\n\t\t\t\tneurons_from_previous_layer = neuron.previous_layer_neurons\n\t\t\t\tweights_from_previous_layer = neuron.weights_from_previous_layer\n\t\t\t\tsum_of_products = 0\n\t\t\t\tfor weight_idx, previous_neuron in enumerate(neurons_from_previous_layer):\n\t\t\t\t\tsum_of_products += previous_neuron.output*weights_from_previous_layer[weight_idx]\n\n\t\t\t\tneural_net[layer_index][neuron_idx].output = float(sigmoid(sum_of_products))\n\t\tif layer_index == len(neural_net) - 1:\n\t\t\tnn_output = [neuron.output for neuron in layer]\n\treturn nn_output",
"def active_graph(self):\n return self._neural_graph_manager.active_graph",
"def body_network(self):\n return self._body_network",
"def latest_network(self, config: MuZeroConfig) -> Network:\n if self._networks:\n return self._networks[max(self._networks.keys())]\n else:\n return Network(config)",
"def evaluate(self, neural_network: NeuralNetwork) -> np.ndarray:\n return neural_network.feed_forward(self.test_set)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns the warm start flag.
|
def warm_start(self) -> bool:
return self._warm_start
|
[
"def warm_mist_enabled(self):\n if self.warm_mist_feature:\n return self.details['warm_mist_enabled']\n return False",
"def start_training(self):\n if self.minibatch_method == 'random' or self.minibatch_method == 'prioritized':\n start = False if len(self.experience_replay) < self.experience_replay_size else True\n\n elif self.minibatch_method == 'stratified':\n start = False if len(self.experience_replay_positive) + len(\n self.experience_replay_negative) < self.experience_replay_size else True\n\n return start",
"def is_start(self):\n\n com = Competition.query.order_by(Competition.id.desc()).first()\n return com.flag if com else False",
"def has_start_time(self):\n return # boolean",
"def start():\n\n wdb = Wordbase.dawg()\n ok = u\"upphitun\" in wdb # Use a random word to check ('upphitun' means warm-up)\n logging.info(u\"Start/warmup, instance {0}, ok is {1}\".format(\n os.environ.get(\"INSTANCE_ID\", \"\"), ok))\n return jsonify(ok = ok)",
"def start(self):\n\t\treturn self.__params['start']",
"def is_start(self):\n return self._status == EventStatus.START",
"def start_new_minibatch(self):\n\n return True",
"def state_min(self):\n return self.__state_min",
"async def is_start_in_required(self):\n runlevel = await self.create_and_send_command(STARTLEVEL)\n return not bool(int(runlevel))",
"def should_start(self):\n # XXX Don't return true if it should_stop.\n now = datetime.datetime.utcnow()\n delay_delta = datetime.timedelta(seconds=self.container_set.run_delay)\n return now >= self.run.started_at + delay_delta",
"def get_min_delay():\n return globals_variables.get_simulator().min_delay",
"def startOnly(self):\n self.begin=time.time()",
"def warmup(self):\n\t\treturn int(self._warmup/self.tick_period) * self.tick_period",
"def _warm_start_encoding(self) -> torch.Tensor:\n assert self.env.dt == mantrap.constants.ENV_DT_DEFAULT # pre-computation only for default time-step\n encoding = self.encode()\n\n enc_file, db_file = mantrap.constants.WARM_START_PRE_COMPUTATION_FILE\n enc_file = mantrap.utility.io.build_os_path(os.path.join(\"third_party\", \"warm_start\", enc_file))\n db_file = mantrap.utility.io.build_os_path(os.path.join(\"third_party\", \"warm_start\", db_file))\n encoding_db = torch.load(enc_file)\n assert encoding.shape[-1] == encoding.numel()\n warm_start_db = torch.load(db_file)\n assert len(warm_start_db.shape) == 3\n assert warm_start_db.shape[1] >= self.planning_horizon\n assert warm_start_db.shape[2] == 2 # controls\n\n # Due to the limited number of pre-computed scenarios (and since it is a single, batched computation)\n # compare matching distance to all encoding (instead of using clustering).\n encoding_distance = torch.norm(encoding_db - encoding, dim=1)\n encoding_best_match = torch.argmin(encoding_distance)\n return warm_start_db[encoding_best_match, :self.planning_horizon, :]",
"def is_start(self) -> bool:\n return self.num_river == 1 and self.num_coast == 0",
"def is_start(self) -> bool:\n return self.colour == ORANGE",
"def min_condenser_load(self):\n return self._min_condenser_load",
"def get_starting_state(self):\n\t\treturn self._current_state # state 0",
"def autostart_enabled(self):\n ret = self._get_attr(\"autostartEnabled\")\n return ret"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Sets the warm start flag.
|
def warm_start(self, warm_start: bool) -> None:
self._warm_start = warm_start
|
[
"def startOnly(self):\n self.begin=time.time()",
"def _starting(self):\n \n self.__state = runlevel.STATE_STARTING",
"def start_new_minibatch(self):\n\n return True",
"def set_train(self):\n BaseModule.train_flag = True",
"def startAt(self, startkey):\n if startkey:\n print(\"Starting at {}\".format(startkey))\n dry = True\n for s in self.steps:\n if s.key == startkey:\n dry = False\n s.dry = dry",
"def warm_mist_enabled(self):\n if self.warm_mist_feature:\n return self.details['warm_mist_enabled']\n return False",
"def start():\n\n wdb = Wordbase.dawg()\n ok = u\"upphitun\" in wdb # Use a random word to check ('upphitun' means warm-up)\n logging.info(u\"Start/warmup, instance {0}, ok is {1}\".format(\n os.environ.get(\"INSTANCE_ID\", \"\"), ok))\n return jsonify(ok = ok)",
"async def require_start_in(self, value: bool = True):\n setpoint = int(not value)\n await self.create_and_send_command(STARTLEVEL, setpoint=setpoint)\n logger.debug(f\"Start in required set to {value}\")",
"def __enter_sequence_main_region_warmup_default(self):\n\t\tself.__entry_action_main_region_warmup()\n\t\tself.__state_vector[0] = self.State.main_region_warmup\n\t\tself.__state_conf_vector_changed = True",
"def at_start(self):\r\n self.obj.cmdset.add(cmdsetexamples.BlindCmdSet)",
"def start_stage(self, time: int):\n self.active = 1\n self.start_time = time",
"def _set_start(self, val):\n self.Data.Start = val",
"def setStartSweep(self,start):\r\n self.isSIUnit(start)\r\n self.startFreqSweep = start",
"def start_time(self, start_time):\n self.__start = start_time",
"def start_training(self):\n if self.minibatch_method == 'random' or self.minibatch_method == 'prioritized':\n start = False if len(self.experience_replay) < self.experience_replay_size else True\n\n elif self.minibatch_method == 'stratified':\n start = False if len(self.experience_replay_positive) + len(\n self.experience_replay_negative) < self.experience_replay_size else True\n\n return start",
"def start_one():\n world.app_one_started = True",
"def start_stopwatch():\n global start_time\n start_time = time.time()",
"def training_start_sp(self, training_start_sp):\n\n self._training_start_sp = training_start_sp",
"def _started(self):\n\n self.active = True\n self.stopped = False",
"def start(self):\n self.running = True"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns current initial point
|
def initial_point(self) -> np.ndarray:
return self._initial_point
|
[
"def _choose_initial_point(self) -> np.ndarray:\n if self._warm_start and self._fit_result is not None:\n self._initial_point = self._fit_result.x\n elif self._initial_point is None:\n self._initial_point = algorithm_globals.random.random(self._neural_network.num_weights)\n return self._initial_point",
"def getLocalStartingPoint(self) -> \"SbVec3f\":\n return _coin.SoDragger_getLocalStartingPoint(self)",
"def GetMinPoint(self):\n ...",
"def CurrentPoint(self):\n return self.__cur_point",
"def curr_curve_start_xyt(self):\n if self._curr_curve_start_index is None:\n return None\n else:\n return self._recent_near_coords[self._curr_curve_start_index]",
"def start_point(self):\n return self.circle_profile.center",
"def getWorldStartingPoint(self) -> \"SbVec3f\":\n return _coin.SoDragger_getWorldStartingPoint(self)",
"def first_point(self):\r\n return self._call_property(\"first_point\", as_ga=True)",
"def _calc_min(self):\n return np.min(self.get_points()) - 1",
"def min_x(self):\n return self.origin[0]",
"def set_zero_point(self):\n self.current_position = 0.0\n self.goal_position = 0.0",
"def _auto_set_start_point(self):\n # sum the image along each axis within the central 1/3 (avoids outlier influence from say, gantry shots)\n top_third = int(self.image.array.shape[0]/3)\n bottom_third = int(top_third * 2)\n left_third = int(self.image.array.shape[1]/3)\n right_third = int(left_third * 2)\n central_array = self.image.array[top_third:bottom_third, left_third:right_third]\n\n x_sum = np.sum(central_array, 0)\n y_sum = np.sum(central_array, 1)\n\n # Calculate Full-Width, 80% Maximum\n fwxm_x_point = SingleProfile(x_sum).get_FWXM_center(80) + left_third\n fwxm_y_point = SingleProfile(y_sum).get_FWXM_center(80) + top_third\n\n # find maximum points\n x_max = np.unravel_index(np.argmax(central_array), central_array.shape)[1] + left_third\n y_max = np.unravel_index(np.argmax(central_array), central_array.shape)[0] + top_third\n\n # which one is closer to the center\n fwxm_dist = Point(fwxm_x_point, fwxm_y_point).dist_to(self.image.center)\n max_dist = Point(x_max, y_max).dist_to(self.image.center)\n\n if fwxm_dist < max_dist:\n center_point = Point(fwxm_x_point, fwxm_y_point)\n else:\n center_point = Point(x_max, y_max)\n\n self.circle_profile.center = center_point",
"def random_initial_point(num_points):\n\treturn (numpy.random.rand(num_points)-0.5)*4*np.pi",
"def GetCurrentSetpoint(self):\n current = self.query(b\"ACC\")\n try:\n return float(current)\n except Exception as e:\n logging.warning(\n \"KoherasBoostik warning in GetCurrentSetpoint() : \" + str(e)\n )\n return np.nan",
"def current_x(self):\n return self._current_position[0]",
"def initial_position(lat,lon):\n\tstarting_lat = lat\n\tstarting_lon = lon % 360\n\treturn starting_lat, starting_lon",
"def get_min_x(self):\n\n return self.x0",
"def start_coord(self):\n return self.lat_s, self.lon_s",
"def start_point(self) -> int:\n return self._start_point",
"def getoriginx(self):\n return self.origin[0]"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Sets the initial point
|
def initial_point(self, initial_point: np.ndarray) -> None:
self._initial_point = initial_point
|
[
"def set_zero_point(self):\n self.current_position = 0.0\n self.goal_position = 0.0",
"def setStartingPoint(self, *args) -> \"void\":\n return _coin.SoDragger_setStartingPoint(self, *args)",
"def _choose_initial_point(self) -> np.ndarray:\n if self._warm_start and self._fit_result is not None:\n self._initial_point = self._fit_result.x\n elif self._initial_point is None:\n self._initial_point = algorithm_globals.random.random(self._neural_network.num_weights)\n return self._initial_point",
"def set_initial_location(self):\n self.changed = True\n self.new_location = (np.random.rand(self.num_dimensions) * (self.mx-self.mn)) + self.mn\n # random initial velocities of swarm\n self.velocities[0, :] = (np.random.rand(self.num_dimensions) * (self.mx-self.mn)) + self.mn",
"def _set_init_pose(self):\n self.reached_goal_reward = rospy.get_param(\n '/locobot/reached_goal_reward')\n\n self.max_distance_from_ee_to_goal = rospy.get_param('/locobot/max_distance_from_ee_to_goal')\n\n # DEBUG: Check the initial joint positions\n rospy.logdebug(\"Initial Joint Positions:\")\n rospy.logdebug(self.initial_joint_pos)\n\n self.movement_result = self._set_startup_position()\n gripper_pose = self.get_end_effector_pose()\n self.last_gripper_target = [gripper_pose.pose.position.x,\n gripper_pose.pose.position.y,\n gripper_pose.pose.position.z]\n rospy.logdebug(\"Initial EE Position = {}\".format(self.last_gripper_target))\n self.last_joint_positions = self.get_joints_position()\n rospy.logdebug(\"Initial Joint Position = {}\".format(self.last_joint_positions))\n\n # Samle a Goal or Not\n if self.use_random_goal:\n rospy.logdebug(\"SAMPLING a new DESIRED GOAL Position\")\n self.desired_position = self._sample_goal(self.last_gripper_target)\n\n\n self.last_action= \"INIT\"\n rospy.logdebug(\"Set to Startup initial pose ---> \" + str(self.movement_result))",
"def set(self, p: BasePoint):\n self._x, self._y = p.xy()",
"def _set_start_position(self):\n\n self.start_position = self.game.level.beetle_den['left'].coordinates",
"def _auto_set_start_point(self):\n # sum the image along each axis within the central 1/3 (avoids outlier influence from say, gantry shots)\n top_third = int(self.image.array.shape[0]/3)\n bottom_third = int(top_third * 2)\n left_third = int(self.image.array.shape[1]/3)\n right_third = int(left_third * 2)\n central_array = self.image.array[top_third:bottom_third, left_third:right_third]\n\n x_sum = np.sum(central_array, 0)\n y_sum = np.sum(central_array, 1)\n\n # Calculate Full-Width, 80% Maximum\n fwxm_x_point = SingleProfile(x_sum).get_FWXM_center(80) + left_third\n fwxm_y_point = SingleProfile(y_sum).get_FWXM_center(80) + top_third\n\n # find maximum points\n x_max = np.unravel_index(np.argmax(central_array), central_array.shape)[1] + left_third\n y_max = np.unravel_index(np.argmax(central_array), central_array.shape)[0] + top_third\n\n # which one is closer to the center\n fwxm_dist = Point(fwxm_x_point, fwxm_y_point).dist_to(self.image.center)\n max_dist = Point(x_max, y_max).dist_to(self.image.center)\n\n if fwxm_dist < max_dist:\n center_point = Point(fwxm_x_point, fwxm_y_point)\n else:\n center_point = Point(x_max, y_max)\n\n self.circle_profile.center = center_point",
"def _set_start_position(self):\n\n self.start_position = self.game.level.beetle_den['right'].coordinates",
"def start_point(self, start_point: int):\n\n self._start_point = start_point",
"def set_origin(self, value):\n x, y = value\n self._origin.xy = (-x, -y)",
"def reset(self):\n self.x=0\n self.y=0",
"def set_initial_bound(self, initialBound):\n self.initialBound = initialBound",
"def _start_point_is_set(self):\n if self.circle_profile.center.x == 0:\n return False\n else:\n return True",
"def setOrigin(self, *args, **kwargs):\n origin = galsim.utilities.parse_pos_args(args, kwargs, 'x0', 'y0', integer=True)\n self._shift(origin - self.image.bounds.origin())",
"def reset(self, setpoint):\n self.setpoint = setpoint\n self.last_diff = 0\n self.error_integral = 0",
"def set_initial_value(self, initial_value, time=0.0):\n\t\tif isinstance(initial_value,dict):\n\t\t\tinitial_value = self._list_from_dynvar_dict(\n\t\t\t\t\tinitial_value,\n\t\t\t\t\t\"initial value\",\n\t\t\t\t\tself.n,\n\t\t\t\t)\n\t\t\n\t\tif self.n != len(initial_value):\n\t\t\traise ValueError(\"The dimension of the initial value does not match the dimension of your differential equations.\")\n\t\t\n\t\tself.y = np.array( initial_value, copy=True, dtype=float )\n\t\tself.t = time\n\t\treturn self",
"def update_InitialLaserPosition(self, pos):\n modifiers = QtGui.QApplication.keyboardModifiers()\n if modifiers == QtCore.Qt.ControlModifier: \n Initial_Parameters['X_Offset'] = int(pos[0])\n Initial_Parameters['Y_Offset'] = int(pos[1])\n self.scatterThread.updateScatter(Initial_Parameters)",
"def setInitialVolumePose(self, R, t) -> None:\n ...",
"def reset_position(self):\n self.xyz = self.xyz + self.tfm"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns trained weights as a numpy array. The weights can be also queried by calling `model.fit_result.x`, but in this case their representation depends on the optimizer used.
|
def weights(self) -> np.ndarray:
self._check_fitted()
return np.asarray(self._fit_result.x)
|
[
"def get_weights(self):\r\n return self.weights # returning the weight matrix\r",
"def model_weights_as_vector(model):\r\n weights_vector = []\r\n\r\n for layer in model.layers: # model.get_weights():\r\n if layer.trainable:\r\n layer_weights = layer.get_weights()\r\n for l_weights in layer_weights:\r\n vector = numpy.reshape(l_weights, newshape=(l_weights.size))\r\n weights_vector.extend(vector)\r\n\r\n return numpy.array(weights_vector)",
"def get_weights(self, ):\n return [w for l in self.weights for w in l.flat]",
"def get_weights(self, key):\n return np.array([entry.data[\"weights\"][key] for entry in self._entries])",
"def get_recurrent_weights(self):\n return npify(self.w_rec.weight)",
"def sample_weights(self):\n return self.to_dataframe()[\"sample_weight\"].values",
"def weights ( self ) :\n N = len ( self ) \n return array ( 'd' , ( self.weight ( i ) for i in range ( N ) ) )",
"def getWeight(self):\n return np.concatenate([self.weight.ravel()] * 4)",
"def get_weights(self):\n\n weights = []\n for layer in self.NN:\n for node in layer:\n for weight in node.weights:\n weights.append(weight)\n return weights",
"def get_weights_from_layer(self, i: int) -> np.ndarray:\n return self.__weights[i]",
"def get_recurrent_weights(self):\n return npify(self.rnn_layer.weight_hh_l0)",
"def get_weight(self):\n return self.graph_weights.reshape(self.size_graph_rows, self.size_graph_cols)",
"def get_weight_matrix(self):\n return self.W",
"def get_all_weights(self):\n\n # add weights for each layer if layer is a Dense layer and return the list\n return [l.weights for l in self.layers if isinstance(l, Dense)]",
"def weight(self):\n vec = np.array([[reqt.weight for reqt in self.requirements]])\n return vec.T # Return as column vector",
"def get_trainable_weight(op_weights):\n return op_weights[\"trainable\"]",
"def get_weights(model_name):\t\n\tfrom os.path import join, exists\n\timport config\n\timport torch\n\tfrom torchvision.datasets.utils import download_file_from_google_drive\n\n\t\n\tpretrained_path = join(config.DATA_FOLDER, 'pretrained_models')\t\n\tassert model_name in config.WEIGHT_IDS, f'no weights for model: {model_name}'\n\n\tfile_name = f'{model_name}.pt'\n\tfile_dest = join(pretrained_path, file_name)\n\n\tif not exists(file_dest):\n\t\tid = config.WEIGHT_IDS[model_name]\n\t\tdownload_file_from_google_drive(file_id=id, root=pretrained_path, filename=file_name)\n\t\tprint(f'weights downloaded & saved at: {file_dest}')\n\t\t\n\treturn torch.load(file_dest)",
"def sample(self):\n return np.array(self.prior_weights)",
"def get_batch_weights(self, results):\n\n\t\tresult_counts = Counter(results)\n\t\tnum_results = float(len(results))\n\t\tinv_result_prob = {result: num_results/(2 * float(count)) for result, count in result_counts.items()}\n\t\tbatch_weights = np.array([inv_result_prob[result] for result in results])\n\n\t\treturn batch_weights"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Choose an initial point for the optimizer. If warm start is set and the model is already trained then use a fit result as an initial point. If initial point is passed, then use this value, otherwise pick a random location.
|
def _choose_initial_point(self) -> np.ndarray:
if self._warm_start and self._fit_result is not None:
self._initial_point = self._fit_result.x
elif self._initial_point is None:
self._initial_point = algorithm_globals.random.random(self._neural_network.num_weights)
return self._initial_point
|
[
"def set_initial_location(self):\n self.changed = True\n self.new_location = (np.random.rand(self.num_dimensions) * (self.mx-self.mn)) + self.mn\n # random initial velocities of swarm\n self.velocities[0, :] = (np.random.rand(self.num_dimensions) * (self.mx-self.mn)) + self.mn",
"def _ask(self):\n\n # after being \"told\" n_initial_points we switch from sampling\n # random points to using a surrogate model in update_next()\n if self._n_initial_points > 0 or self.base_model is None:\n if self._initial_samples is None:\n # Not sure I can ever get to this piece of code\n return self._point_sampler.generate(1, self._search_space['X_pointsgrid'])\n else:\n # The samples are evaluated starting form initial_samples[0]\n return self._initial_samples[\n len(self._initial_samples) - self._n_initial_points].reshape(1, self._search_space['ndim'])\n\n else:\n\n if not hasattr(self, '_next_x'):\n self.update_next() # Should only happen on the first call, after which _next_x should always be set.\n\n # Currently being found in acquisition, however, should use _next_xs and find _next_x here\n # in later refactor.\n next_x = self._next_x\n\n\n # return point computed from last call to tell()\n return next_x",
"def _default_initial_position_sample_func(self):\n ped_position_list = self._sim.get_ped_state()['ped_position']\n initial_position = None\n allowed = False\n while not allowed:\n allowed = True\n initial_position = np.array([random.uniform(0, self._screen_size[0]), \n random.uniform(0, self._screen_size[1])])\n if np.linalg.norm(initial_position - self._agent.position) < 10:\n allowed = False\n for ped_index in range(ped_position_list.shape[0]):\n if np.linalg.norm(initial_position - ped_position_list[ped_index]) < 10:\n allowed = False\n return initial_position",
"def fit_with_starting_params(self, y, model_params):\n optimization = self.context.create_params_optimizer()\n return optimization.optimize(y, model_params).optimal_model()",
"def _initialize_train(self):\n self._train_input = acme_utils.prefetch(self._build_train_input())\n\n # Check we haven't already restored params\n if self._byol_state is None:\n logging.info(\n 'Initializing parameters rather than restoring from checkpoint.')\n\n # initialize Byol and setup optimizer state\n inputs = next(self._train_input)\n init_byol = jax.pmap(self._make_initial_state, axis_name='i')\n\n # Init uses the same RNG key on all hosts+devices to ensure everyone\n # computes the same initial state and parameters.\n init_rng = jax.random.PRNGKey(self._random_seed)\n init_rng = helpers.bcast_local_devices(init_rng)\n\n self._byol_state = init_byol(rng=init_rng, dummy_input=inputs)",
"def update_initial(self, illumination=0):\n if self.fit_result_values is None:\n raise ValueError(\"Fit has not yet been performed\")\n for param in self.parameters:\n if param.multi:\n param.initial = self.fit_result_values[f\"{param.name}{illumination}\"]\n else:\n param.initial = self.fit_result_values[param.name]",
"def _set_init_pose(self):\n self.reached_goal_reward = rospy.get_param(\n '/locobot/reached_goal_reward')\n\n self.max_distance_from_ee_to_goal = rospy.get_param('/locobot/max_distance_from_ee_to_goal')\n\n # DEBUG: Check the initial joint positions\n rospy.logdebug(\"Initial Joint Positions:\")\n rospy.logdebug(self.initial_joint_pos)\n\n self.movement_result = self._set_startup_position()\n gripper_pose = self.get_end_effector_pose()\n self.last_gripper_target = [gripper_pose.pose.position.x,\n gripper_pose.pose.position.y,\n gripper_pose.pose.position.z]\n rospy.logdebug(\"Initial EE Position = {}\".format(self.last_gripper_target))\n self.last_joint_positions = self.get_joints_position()\n rospy.logdebug(\"Initial Joint Position = {}\".format(self.last_joint_positions))\n\n # Samle a Goal or Not\n if self.use_random_goal:\n rospy.logdebug(\"SAMPLING a new DESIRED GOAL Position\")\n self.desired_position = self._sample_goal(self.last_gripper_target)\n\n\n self.last_action= \"INIT\"\n rospy.logdebug(\"Set to Startup initial pose ---> \" + str(self.movement_result))",
"def _maybe_compute_init_and_min_vals_from_trace(self) -> None:\n if not len(self.history):\n # nothing to be computed from empty history\n return\n\n # some optimizers may evaluate hess+grad first to compute trust region\n # etc\n for ix in range(len(self.history)):\n fval = self.history.get_fval_trace(ix)\n x = self.history.get_x_trace(ix)\n if not is_none_or_nan(fval) and allclose(x, self.x0):\n self.fval0 = float(fval)\n break\n\n # find best fval\n result = self._get_optimal_point_from_history()\n\n # assign values\n for key in OptimizerHistory.MIN_KEYS:\n setattr(self, f'{key}_min', result[key])",
"def _auto_set_start_point(self):\n # sum the image along each axis within the central 1/3 (avoids outlier influence from say, gantry shots)\n top_third = int(self.image.array.shape[0]/3)\n bottom_third = int(top_third * 2)\n left_third = int(self.image.array.shape[1]/3)\n right_third = int(left_third * 2)\n central_array = self.image.array[top_third:bottom_third, left_third:right_third]\n\n x_sum = np.sum(central_array, 0)\n y_sum = np.sum(central_array, 1)\n\n # Calculate Full-Width, 80% Maximum\n fwxm_x_point = SingleProfile(x_sum).get_FWXM_center(80) + left_third\n fwxm_y_point = SingleProfile(y_sum).get_FWXM_center(80) + top_third\n\n # find maximum points\n x_max = np.unravel_index(np.argmax(central_array), central_array.shape)[1] + left_third\n y_max = np.unravel_index(np.argmax(central_array), central_array.shape)[0] + top_third\n\n # which one is closer to the center\n fwxm_dist = Point(fwxm_x_point, fwxm_y_point).dist_to(self.image.center)\n max_dist = Point(x_max, y_max).dist_to(self.image.center)\n\n if fwxm_dist < max_dist:\n center_point = Point(fwxm_x_point, fwxm_y_point)\n else:\n center_point = Point(x_max, y_max)\n\n self.circle_profile.center = center_point",
"def min_cool_setpoint(self, min_cool_setpoint):\n\n self._min_cool_setpoint = min_cool_setpoint",
"def _generate_initial_model(self):\n initial_parameters = [p.current_value for p in self.current_parameters]\n try:\n initial_model = self.specification(*initial_parameters)\n except TypeError:\n raise TypeError(\n 'Failed to build initial model. Make sure that the input '\n 'parameters match the number and order of arguements '\n 'expected by the input specification.')\n initial_model.pack_new_sequences(self.sequences)\n self.current_energy = self.eval_function(initial_model)\n self.best_energy = copy.deepcopy(self.current_energy)\n self.best_parameters = copy.deepcopy(self.current_parameters)\n self.best_model = initial_model\n return",
"def _get_initial_state(initial_position, tolerance, expectation_value_function,\n learning_rate, alpha, perturb, gamma, blocking,\n allowed_increase):\n init_args = {\n \"converged\": tf.Variable(False),\n \"num_iterations\": tf.Variable(0),\n \"num_objective_evaluations\": tf.Variable(0),\n \"position\": tf.Variable(initial_position),\n \"objective_value\":\n (tf.cast(expectation_value_function(initial_position), tf.float32)),\n \"objective_value_prev\": tf.Variable(np.inf),\n \"tolerance\": tolerance,\n \"learning_rate\": tf.Variable(learning_rate),\n \"alpha\": tf.Variable(alpha),\n \"perturb\": tf.Variable(perturb),\n \"gamma\": tf.Variable(gamma),\n \"blocking\": tf.Variable(blocking),\n \"allowed_increase\": tf.Variable(allowed_increase),\n }\n return SPSAOptimizerResults(**init_args)",
"def get_initial_stake(self):\n pass",
"def random_initial_point(num_points):\n\treturn (numpy.random.rand(num_points)-0.5)*4*np.pi",
"def initialize_optimizer(self, use_previous_observations=False, only_nonzero_observations=False):\n # Get the initialization samples from the ObjectiveFunction\n print(\"\\tInitializing optimizer at\", self._params['optimizer_initialization'])\n # init_dict will store the initialization data in the format the optimizer likes:\n # A list for each parameter with their values plus a 'target' list for the respective result value\n init_dict = {p_name: [] for p_name in self._params['optimizer_initialization'][0]}\n # Fill init_dict with values from the optimizer initialization:\n for optimized_rosparams in self._params['optimizer_initialization']:\n if self._params['normalize']:\n self.obj_function.normalize_parameters(optimized_rosparams)\n for p_name, p_value in optimized_rosparams.items():\n init_dict[p_name].append(p_value)\n # If desired, previously generated observations will be used as initialization as well.\n if use_previous_observations:\n print(\"\\tUsing previous observations to initialize the optimizer.\")\n for complete_params, y, s in self.obj_function: # gets the complete params dict of each sample\n if y > 0 or not only_nonzero_observations:\n if self._params['normalize']:\n self.obj_function.normalize_parameters(complete_params)\n # only get values of optimized params; requires at least one initialization value defined in the experiment.yaml, but that should be the case anyway.\n for optimized_rosparam in self._params['optimizer_initialization'][0].keys():\n init_dict[optimized_rosparam].append(complete_params[optimized_rosparam])\n # Add the initilizations via the BayesianOptimization framework's explore method\n self.optimizer.explore(init_dict)",
"def set_zero_point(self):\n self.current_position = 0.0\n self.goal_position = 0.0",
"def start_point(self, start_point: int):\n\n self._start_point = start_point",
"def _warm_start_optimization(self, env: mantrap.environment.base.GraphBasedEnvironment,\n modules: typing.Union[typing.List[typing.Tuple], typing.List]) -> torch.Tensor:\n solver_part = self.__class__(env=env, goal=self.goal, modules=modules,\n t_planning=self.planning_horizon, config_name=self.config_name,\n is_logging=self.logger.is_logging, is_debug=self.logger.is_debug)\n\n # As initial guess for this first optimization, without prior knowledge, going straight\n # from the current position to the goal with maximal control input is chosen.\n _, u_max = self.env.ego.control_limits()\n dx_goal = self.goal - self.env.ego.position\n dx_goal_length = torch.norm(dx_goal).item()\n ego_controls_init = torch.stack([dx_goal / dx_goal_length * u_max] * self.planning_horizon)\n z_init = self.ego_controls_to_z(ego_controls=ego_controls_init)\n\n # Solve the simplified optimization and return its results.\n z_opt_hard = solver_part.optimize(z0=torch.from_numpy(z_init), tag=mantrap.constants.TAG_WARM_START)\n self.logger.log_update(solver_part.logger.log)\n return z_opt_hard",
"def setup_optimizer(self):\n # The statistical model of our objective function\n init_param_point = dict(zip(self.hyper_param_names,\n self.init_hyper_param))\n init_param_point.update(self.fixed_params_dict)\n init_train_error, init_test_error, init_exec_time = \\\n self.get_obj(init_param_point)\n init_X = np.expand_dims(np.array(self.init_hyper_param), axis=0)\n self.best_obj = init_test_error\n self.train_erro_gp = GPy.models.GPRegression(init_X,\n init_train_error,\n self.train_error_kernel,\n noise_var=\n self.noise_level ** 2)\n self.train_erro_gp.optimize()\n\n self.test_erro_gp = GPy.models.GPRegression(init_X,\n init_test_error,\n self.test_error_kernel,\n noise_var=\n self.noise_level ** 2)\n self.test_erro_gp.optimize()\n\n self.exec_time_gp = GPy.models.GPRegression(init_X,\n init_exec_time,\n self.exec_time_kernel,\n noise_var=\n self.noise_level ** 2)\n self.exec_time_gp.optimize()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Wraps the given `ObjectiveFunction` to add callback calls, if `callback` is not None, along with evaluating the objective value. Returned objective function is passed to `Optimizer.minimize()`.
|
def _get_objective(
self,
function: ObjectiveFunction,
) -> Callable:
if self._callback is None:
return function.objective
def objective(objective_weights):
objective_value = function.objective(objective_weights)
self._callback(objective_weights, objective_value)
return objective_value
return objective
|
[
"def minimize(self, cost_function, initial_params=None, callback=None):\n\n if self.keep_value_history:\n cost_function = recorder(cost_function)\n\n jacobian = None\n if hasattr(cost_function, \"gradient\") and callable(\n getattr(cost_function, \"gradient\")\n ):\n jacobian = cost_function.gradient\n\n result = scipy.optimize.minimize(\n cost_function,\n initial_params,\n method=self.method,\n options=self.options,\n constraints=self.constraints,\n jac=jacobian,\n )\n opt_value = result.fun\n opt_params = result.x\n\n nit = result.get(\"nit\", None)\n nfev = result.get(\"nfev\", None)\n\n return optimization_result(\n opt_value=opt_value,\n opt_params=opt_params,\n nit=nit,\n nfev=nfev,\n history=cost_function.history if self.keep_value_history else [],\n )",
"def minimizer(self, value: Callable) -> None:\n self._minimizer = value",
"def minimize_with_timeout(\n fun: Callable[[np.ndarray, *Any], float],\n x0: np.ndarray,\n args: Tuple[Any, ...] = (),\n method: Optional[str] = None,\n jac: Optional[Union[str, Callable, bool]] = None,\n hess: Optional[Union[str, Callable, optimize.HessianUpdateStrategy]] = None,\n hessp: Optional[Callable] = None,\n bounds: Optional[Union[Sequence[Tuple[float, float]], optimize.Bounds]] = None,\n constraints=(), # Typing this properly is a s**t job\n tol: Optional[float] = None,\n callback: Optional[Callable] = None,\n options: Optional[Dict[str, Any]] = None,\n timeout_sec: Optional[float] = None,\n) -> optimize.OptimizeResult:\n if timeout_sec:\n\n start_time = time.monotonic()\n callback_data = {\"num_iterations\": 0} # update from withing callback below\n\n def timeout_callback(xk: np.ndarray) -> bool:\n runtime = time.monotonic() - start_time\n callback_data[\"num_iterations\"] += 1\n if runtime > timeout_sec:\n raise OptimizationTimeoutError(current_x=xk, runtime=runtime)\n return False\n\n if callback is None:\n wrapped_callback = timeout_callback\n\n elif callable(method):\n raise NotImplementedError(\n \"Custom callable not supported for `method` argument.\"\n )\n\n elif method == \"trust-constr\": # special signature\n\n def wrapped_callback(\n xk: np.ndarray, state: optimize.OptimizeResult\n ) -> bool:\n # order here is important to make sure base callback gets executed\n return callback(xk, state) or timeout_callback(xk=xk)\n\n else:\n\n def wrapped_callback(xk: np.ndarray) -> None:\n timeout_callback(xk=xk)\n callback(xk)\n\n else:\n wrapped_callback = callback\n\n try:\n return optimize.minimize(\n fun=fun,\n x0=x0,\n args=args,\n method=method,\n jac=jac,\n hess=hess,\n hessp=hessp,\n bounds=bounds,\n constraints=constraints,\n tol=tol,\n callback=wrapped_callback,\n options=options,\n )\n except OptimizationTimeoutError as e:\n msg = f\"Optimization timed out after {e.runtime} seconds.\"\n current_fun, *_ = fun(e.current_x, *args)\n\n return optimize.OptimizeResult(\n fun=current_fun,\n x=e.current_x,\n nit=callback_data[\"num_iterations\"],\n success=False, # same as when maxiter is reached\n status=1, # same as when L-BFGS-B reaches maxiter\n message=msg,\n )",
"def from_callback(\n func: Callable[..., Callable[..., None]],\n mapper: Optional[typing.Mapper[Any, Any]] = None,\n) -> Callable[[], Observable[Any]]:\n from .observable.fromcallback import from_callback_\n\n return from_callback_(func, mapper)",
"def add_objective_function(self, objective_function):\n objective_function = objective_function.sort_values('variable_id')\n objective_function = objective_function.set_index('variable_id')\n obj = minimize(xsum(objective_function['cost'][i] * self.variables[i] for i in\n list(objective_function.index)))\n self.mip_model.objective = obj\n self.linear_mip_model.objective = obj",
"def add_callback(self, callback_function):\n\n def extra_callback_function(pin):\n new_value = self._gpio_controller.input(self._pin)\n alert = (\n self.position == self.HIGH and new_value == self._gpio_controller.HIGH\n ) or (self.position == self.LOW and new_value == self._gpio_controller.HIGH)\n callback_function(pin, alert)\n\n self._gpio_controller.add_event_callback(self._pin, extra_callback_function)",
"def _make_obj_func_wrapper(\n self,\n progress,\n display_iter,\n warns,\n warns_with_params,\n obj_func,\n like_eval_task=None,\n evals_per_iteration=None,\n ignore_direction=False,\n ):\n direction = 1 if self.direction == \"minimize\" or ignore_direction else -1\n\n # This is the number of evaluations we need per search iteration.\n self.num_evals = 0\n\n # Create a wrapper function for the objective. This lets us keep track of progress and such\n def objfunc_wrapper(x):\n params = dict(zip(self.fit_param_names, x))\n t0 = time.time()\n obj_val = obj_func(*x)\n p = direction * obj_val\n elapsed = time.time() - t0\n self.num_evals = self.num_evals + 1\n\n # Keep a log of warnings and the parameters that caused them\n if len(warns) > 0 and warns[-1].category == PECObjectiveFuncWarning:\n warns_with_params.append((warns[-1], params))\n\n # Are we displaying each iteration\n if display_iter:\n # If we got a warning generating the objective function value, report it\n if len(warns) > 0 and warns[-1].category == PECObjectiveFuncWarning:\n progress.console.print(f\"Warning: \", style=\"bold red\")\n progress.console.print(f\"{warns[-1].message}\", style=\"bold red\")\n progress.console.print(\n f\"{get_param_str(params)}, {self.obj_func_desc_str}: {obj_val}, \"\n f\"Eval-Time: {elapsed} (seconds)\",\n style=\"bold red\",\n )\n # Clear the warnings\n warns.clear()\n else:\n progress.console.print(\n f\"{get_param_str(params)}, {self.obj_func_desc_str}: {obj_val}, \"\n f\"Eval-Time: {elapsed} (seconds)\"\n )\n\n # Certain algorithms like differential evolution evaluate the objective function multiple times per\n # iteration. We need to update the progress bar accordingly.\n if evals_per_iteration is not None:\n # We need to update the progress bar differently depending on whether we are doing\n # the first generation (which is twice as long) or not.\n if self.num_evals < 2 * evals_per_iteration:\n max_evals = 2 * evals_per_iteration\n progress.tasks[like_eval_task].total = max_evals\n eval_task_str = f\"|-- Iteration {self.gen_count} ...\"\n progress.tasks[like_eval_task].description = eval_task_str\n progress.update(\n like_eval_task, completed=self.num_evals % max_evals\n )\n else:\n max_evals = evals_per_iteration\n progress.tasks[like_eval_task].total = max_evals\n eval_task_str = f\"|-- Iteration {self.gen_count} ...\"\n progress.tasks[like_eval_task].description = eval_task_str\n progress.update(\n like_eval_task,\n completed=(self.num_evals - (2 * evals_per_iteration))\n % max_evals,\n )\n\n return p\n\n return objfunc_wrapper",
"def minimize(objective, p0,\n nboundupdate=100,\n reltol=1e-4, abstol=0.0, maxiters=1e7,\n algo='fast',\n show_progress=False,\n callback=None,\n full_return=False,\n mask=None):\n\n if mask is not None:\n mask = np.asarray(mask)\n\n def mobjective(x):\n f, grad = objective(x)\n if grad is not None:\n grad[mask] = 0.0\n return f, grad\n mobjective = mobjective\n mproject = lambda p: project(p, mask)\n else:\n mobjective = objective\n mproject = project\n # initialize p from function input\n p = mproject(np.asarray(p0))\n # counting variable for number of iterations\n k = 0\n # lower bound for the cost function\n low = 0.0\n\n # setup for accelerated algorithm\n if algo == 'fast':\n y = p\n f, grad = mobjective(p)\n # starting guess for gradient scaling parameter 1 / | nabla f |\n s = 1.0 / np.linalg.norm(grad)\n # refine by backtracking search\n while True:\n y_new = mproject(y - s * grad)\n # abs important as values close to machine precision\n # might become negative in fft convolution screwing\n # up cost calculations\n f_new, grad_new = mobjective(y_new)\n if f_new < f + np.dot(y_new - y, grad.T) + \\\n 0.5 * np.linalg.norm(y_new - y)**2 / s:\n break\n s *= 0.8\n # reduce s by some factor as optimal s might become smaller during\n # the course of optimization\n s /= 3.0\n\n told = time.time()\n while k < maxiters:\n k += 1\n f, grad = mobjective(p)\n\n # update lower bound on cost function\n # initialize at beginning (k=1) and then every nboundupdateth iteration\n if (k % nboundupdate == 0) or (k == 1):\n if mask is not None:\n i = np.argmin(grad[~mask])\n low = max((low, f - np.sum(p * grad) + grad[~mask][i]))\n else:\n i = np.argmin(grad)\n low = max((low, f - np.sum(p * grad) + grad[i]))\n gap = f - low\n if callback:\n callback(f, p)\n if show_progress:\n print '%g: f %e, gap %e, relgap %e' % (k, f, gap, gap/low if low != 0 else np.inf)\n if ((low != 0 and gap/low < reltol) or gap < abstol):\n if show_progress:\n print 'stopping criterion reached'\n break\n\n if algo == 'fast':\n f, grad = mobjective(y)\n p, pold = mproject(y - s * grad), p\n y = p + k/(k+3.0) * (p - pold)\n else:\n # generate feasible direction by projection\n s = 0.1\n d = mproject(p - s * grad) - p\n # Backtracking line search\n deriv = np.dot(grad.T, d)\n alpha = 0.1\n # in (0, 0.5)\n p1 = 0.2\n # in (0, 1)\n p2 = 0.25\n fnew, grad = mobjective(p + alpha * d)\n while fnew > f + p1*alpha*deriv:\n alpha *= p2\n fnew, grad = mobjective(p + alpha * d)\n p += alpha * d\n\n else:\n print 'warning: maxiters reached before convergence'\n if show_progress:\n print 'niters %e, t per iteration %e' % (k, (time.time() - told) / k)\n print 'cost %e, low %e, gap %e, relgap %e' % (f, low, gap, gap/low if low != 0 else np.inf)\n\n if not full_return:\n return p\n return p, dict(niter=k, f=f, low=low)",
"def set_pec_objective_function(self, objective_function: Callable):\n self._pec_objective_function = objective_function",
"def register_objective_functional(self):\n raise NotImplementedError(\"Must be subclassed.\")",
"def invoke_on_callback_thread_nowait(func):\n return _invoke_on_executor_thread(func=func, thread_name=\"callback\", block=False)",
"def setFunction(self, callbackfunction: 'SoSensorCB *') -> \"void\":\n return _coin.SoSensor_setFunction(self, callbackfunction)",
"def SoVRMLScript_setScriptEvaluateCB(cb: 'SoVRMLScriptEvaluateCB *', closure: 'void *') -> \"void\":\n return _coin.SoVRMLScript_setScriptEvaluateCB(cb, closure)",
"def nonimmediate(func):\n ioloop = tornado.ioloop.IOLoop.instance()\n @wraps(func)\n def delayed_call(*args, **kwargs):\n callback = partial(func, *args, **kwargs)\n ioloop.add_callback(callback)\n return delayed_call",
"def addCallbacks(\n self,\n callback: Union[\n Callable[..., _NextResultT],\n Callable[..., Deferred[_NextResultT]],\n Callable[..., Failure],\n Callable[\n ...,\n Union[_NextResultT, Deferred[_NextResultT], Failure],\n ],\n ],\n errback: Union[\n Callable[..., _NextResultT],\n Callable[..., Deferred[_NextResultT]],\n Callable[..., Failure],\n Callable[\n ...,\n Union[_NextResultT, Deferred[_NextResultT], Failure],\n ],\n None,\n ] = None,\n callbackArgs: Tuple[Any, ...] = (),\n callbackKeywords: Mapping[str, Any] = _NONE_KWARGS,\n errbackArgs: _CallbackOrderedArguments = (),\n errbackKeywords: _CallbackKeywordArguments = _NONE_KWARGS,\n ) -> \"Deferred[_NextResultT]\":\n if errback is None:\n errback = _failthru\n\n # Default value used to be None and callers may be using None\n if callbackArgs is None:\n callbackArgs = () # type: ignore[unreachable]\n if callbackKeywords is None:\n callbackKeywords = {} # type: ignore[unreachable]\n if errbackArgs is None:\n errbackArgs = () # type: ignore[unreachable]\n if errbackKeywords is None:\n errbackKeywords = {} # type: ignore[unreachable]\n\n assert callable(callback)\n assert callable(errback)\n\n self.callbacks.append(\n (\n (callback, callbackArgs, callbackKeywords),\n (errback, errbackArgs, errbackKeywords),\n )\n )\n\n if self.called:\n self._runCallbacks()\n\n # type note: The Deferred's type has changed here, but *idiomatically*\n # the caller should treat the result as the new type, consistently.\n return self # type:ignore[return-value]",
"def add_hook(function: Callable[[Any], Any],\n pre_exec_hook: Optional[Callable[[Any], Any]] = None,\n post_exec_hook: Optional[Callable[[Any], Any]] = None):\n if pre_exec_hook is None and post_exec_hook is None:\n raise Exception('Some hooks must be included')\n\n @functools.wraps(function)\n def run(*args, **kwargs):\n sanitizer_log(f'Hook start {str(function)}', LOG_DEBUG)\n\n # Call hook\n if pre_exec_hook is not None:\n pre_exec_hook(*args, **kwargs)\n\n # Call the original function in the even the hook did not indicate\n # failure.\n ret = function(*args, **kwargs)\n\n # Post execution hook. Overwrite return value if anything is returned\n # by post hook.\n if post_exec_hook is not None:\n tmp_ret = post_exec_hook(ret, *args, **kwargs)\n if tmp_ret is not None:\n sanitizer_log('Overwriting return value', LOG_DEBUG)\n ret = tmp_ret\n sanitizer_log(f'Hook end {str(function)}', LOG_DEBUG)\n return ret\n\n return run",
"def spawn_and_call_back(function, callback):\n def wrapper(*args, **kwargs):\n d = threads.deferToThread(function, *args, **kwargs)\n d.addCallback(callback)\n return d\n return wrapper",
"def addCallback(*args, **kwargs):\n \n pass",
"def setScriptEvaluateCB(cb: 'SoVRMLScriptEvaluateCB *', closure: 'void *') -> \"void\":\n return _coin.SoVRMLScript_setScriptEvaluateCB(cb, closure)",
"def preproc_func(self, func):\n if func is not None and not callable(func):\n msg = f\"{func} is not callable!\"\n raise ValueError(msg)\n\n if func is None:\n self._preproc = self.preproc\n else:\n self._preproc = func"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CNN model based on the paper.
|
def CNN_paper(input_shape):
inputs = Input(shape=input_shape)
x = Conv2D(96, kernel_size=(3,3), padding='same', strides=1, kernel_initializer='he_normal')(inputs)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(96, kernel_size=(3,3), padding='same', strides=1, kernel_initializer='he_normal')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(96, kernel_size=(3,3), padding='same', strides=2, kernel_initializer='he_normal')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
for i in range(4):
if i==2:
x = Conv2D(192, kernel_size=(3,3), padding='same', strides=2, kernel_initializer='he_normal')(x)
else:
x = Conv2D(192, kernel_size=(3,3), padding='same', strides=1, kernel_initializer='he_normal')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(192, kernel_size=(1,1), padding='same', strides=1, kernel_initializer='he_normal')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(10, kernel_size=(1,1), padding='same', strides=1, kernel_initializer='he_normal')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Flatten()(x)
x = Dense(1000, activation='relu')(x)
x = Dense(1000, activation='relu')(x)
outputs = Dense(1)(x)
return Model(inputs=inputs, outputs=outputs)
|
[
"def construct_model():\n #Building the MLP\n \n model = Sequential()\n model.add(Flatten(input_shape=(64,64,3)))\n model.add(Dense(1000, activation=\"relu\"))\n model.add(Dropout(0.2))\n model.add(Dense(512, activation=\"relu\"))\n model.add(Dropout(0.2))\n model.add(Dense(3, activation=\"softmax\"))\n\n #8 Compilation of MLP\n model.compile(loss='categorical_crossentropy',\n optimizer='adam', \n metrics=['accuracy'])\n \n print(model.summary())\n print('Initialise and Compilation of CNN complete')\n\n \n \n return model",
"def create_conv():\r\n\tmodel = tf.keras.Sequential()\r\n\tmodel.add(Dense((8190), input_shape=(260,)))\r\n\tmodel.add(Reshape((105, 78), input_shape=(8190,)))\r\n\tmodel.add(Conv1D(100, 10, activation='relu', input_shape=(105, 78)))\r\n\tmodel.add(Conv1D(100, 10, activation='relu'))\r\n\tmodel.add(MaxPooling1D(3))\r\n\tmodel.add(Conv1D(160, 10, activation='relu'))\r\n\tmodel.add(Conv1D(160, 10, activation='relu'))\r\n\tmodel.add(GlobalAveragePooling1D())\r\n\tmodel.add(Dropout(0.5))\r\n\tmodel.add(Dense(87, activation='softmax'))\r\n\treturn model",
"def build_CNN(input_shape, filters= [3], kernels = [4], activation = 'relu', optimizer= 'Adam'):\n model = Sequential()\n model.add(BatchNormalization(axis=1, momentum=0.1, epsilon=1e-05, input_shape = input_shape))\n model.add( Conv1D(filters=3, kernel_size= 4, strides =1, activation = activation))\n for (f, k) in zip(filters, kernels):\n \n model.add(BatchNormalization(axis=1, momentum=0.1, epsilon=1e-05))\n model.add(Dropout(0.1))\n model.add(Conv1D(filters=f, kernel_size= k, strides =1, activation = activation))\n model.add(MaxPooling1D())\n\n model.add(Flatten())\n model.add(BatchNormalization(axis=1, momentum=0.1, epsilon=1e-05))\n model.add(Dropout(0.1))\n model.add(Dense(units=1, activation='sigmoid')) \n\n\n\n model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])\n\n\n return model",
"def create_classifier(self):\n\t\treturn mlpy.Knn(1)",
"def buildNetwork(self):\n if self.loaded_checkpoint:\n self.model = keras.models.load_model(self.loaded_checkpoint, compile=False)\n self.model.load_weights(self.loaded_checkpoint)\n else:\n self.model = self.cnn() # CNN\n\n self.model.compile(\n loss= keras.losses.sparse_categorical_crossentropy,\n optimizer=keras.optimizers.SGD(lr=self.learning_rate),\n metrics=[\"accuracy\"])",
"def __init__(self, char_embed_size, word_embed_size, kernel_size=5):\n super(CNN, self).__init__()\n self.conv = nn.Conv1d(char_embed_size, word_embed_size, kernel_size)\n self.maxpool = nn.AdaptiveMaxPool1d(1)",
"def _create_critic_network(self):\n model = Sequential()\n # Input = (28x28x1)\n model.add(Conv2D(filters=16, kernel_size=3, strides=2, padding=\"same\"))\n # Dim = (14x14x16)\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(0.25))\n model.add(Conv2D(filters=32, kernel_size=3, strides=2, padding=\"same\"))\n # Dim = (7x7x32)\n model.add(ZeroPadding2D(padding=((0,1),(0,1))))\n # Dim = (8x8x32)\n model.add(BatchNormalization(momentum=0.8))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(0.25))\n model.add(Conv2D(filters=64, kernel_size=3, strides=2, padding=\"same\"))\n # Dim = (4x4x64)\n model.add(BatchNormalization(momentum=0.8))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(0.25))\n model.add(Conv2D(filters=128, kernel_size=3, strides=1, padding=\"same\"))\n # Dim = (4x4x128)\n model.add(BatchNormalization(momentum=0.8))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(0.25))\n model.add(Flatten())\n # Dim = (2048)\n model.add(Dense(1))\n # No activation is used since critic network outputs a single valued\n #score.\n image = Input(shape=self.image_dimensions)\n critic_score = model(image)\n\n model.summary()\n return Model(image, critic_score)",
"def model_cnn(preload = True):\n filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n '../checkpoints', args.filename + '.h5')\n print(filepath)\n if os.path.isfile(filepath) and preload:\n print (\"Loading model...\")\n model = load_model(filepath)\n model.summary()\n return model\n else:\n return create_model_cnn(preload, args.embed_dim, args.sequence_length,\n args.num_filters, args.lang,len(data['y_train'][0]), args.use_static,\n args.init_layer, data['vocabulary'], args.learning_rate, args.num_split)",
"def build_network(self): \r\n self.network = input_data(shape = [None, 48, 48, 1])\r\n print(\"Input data \",self.network.shape[1:])\r\n self.network = conv_2d(self.network, 64, 5, activation = 'relu')\r\n print(\"Conv1 \",self.network.shape[1:])\r\n self.network = max_pool_2d(self.network, 3, strides = 2)\r\n print(\"Maxpool1 \",self.network.shape[1:])\r\n self.network = conv_2d(self.network, 64, 5, activation = 'relu')\r\n print(\"Conv2 \",self.network.shape[1:])\r\n self.network = max_pool_2d(self.network, 3, strides = 2)\r\n print(\"Maxpool2 \",self.network.shape[1:])\r\n self.network = conv_2d(self.network, 128, 4, activation = 'relu')\r\n print(\"Conv3 \",self.network.shape[1:])\r\n self.network = dropout(self.network, 0.3)\r\n print(\"Dropout \",self.network.shape[1:])\r\n self.network = fully_connected(self.network, 3072, activation = 'relu')\r\n print(\"Fully connected\",self.network.shape[1:])\r\n self.network = fully_connected(self.network, len(self.target_classes), activation = 'softmax')\r\n print(\"Output \",self.network.shape[1:])\r\n print(\"\\n\")\r\n # Generates a TrainOp which contains the information about optimization process - optimizer, loss function, etc\r\n self.network = regression(self.network,optimizer = 'momentum',metric = 'accuracy',loss = 'categorical_crossentropy')\r\n # Creates a model instance.\r\n self.model = tflearn.DNN(self.network,checkpoint_path = 'model_1_atul',max_checkpoints = 1,tensorboard_verbose = 2)\r\n # Loads the model weights from the checkpoint\r\n self.load_model()",
"def init_model_scratch(args):\n img_size = args.img_size\n channels = args.channels\n num_class = args.num_class\n inputs = Input(shape=(img_size, img_size, channels), name='input')\n conv1 = Conv2D(16, (3,3), padding='same', activation='relu', name='conv1')(inputs)\n pool1 = MaxPooling2D(name='pool1')(conv1)\n conv2 = Conv2D(32, (3,3), padding='same', activation='relu', name='conv2')(pool1)\n pool2 = MaxPooling2D(name='pool2')(conv2)\n conv3 = Conv2D(64, (3,3), padding='same', activation='relu', name='conv3')(pool2)\n pool3 = MaxPooling2D(name='pool3')(conv3)\n flatten = Flatten(name='flatten')(pool3)\n fc1 = Dense(units=128, activation='relu', name='fc1')(flatten)\n dropout = Dropout(rate=0.5, name='dropout')(fc1)\n predictions = Dense(units=num_class, activation='softmax', name='prediction')(dropout)\n model = models.Model(inputs=inputs, outputs=predictions)\n model.compile(\n optimizer=optimizers.Adam(),\n loss=\"categorical_crossentropy\",\n metrics=[\"accuracy\"]\n )\n\n return model",
"def run_CNN(X):\r\n\r\n print(\"Making CNN predictions\")\r\n model_path = resource_filename(__name__, \"models/model_CNN.json\")\r\n weights_path = resource_filename(__name__, \"models/model_CNN_weights.hdf5\")\r\n\r\n with open(model_path, 'rt') as model_json_file:\r\n model_json = model_json_file.read()\r\n\r\n model = model_from_json(model_json, custom_objects={EmbeddingWithDropout.__name__: EmbeddingWithDropout})\r\n model.load_weights(weights_path)\r\n model.compile(loss='binary_crossentropy', optimizer='adam')\r\n result = model.predict(X).flatten()\r\n\r\n return result",
"def __init__(self, input_channels, output_channels, kernel_size=5):\n super(CNN, self).__init__()\n self.conv = nn.Conv1d(in_channels=input_channels,\n out_channels=output_channels,\n kernel_size=kernel_size,\n )\n self.max_pool = nn.AdaptiveMaxPool1d(output_size=1)",
"def cnn_random():\n input_size = 600\n input_dim = 28\n input_depth = 1\n label_size = 10\n train_X = np.random.random((input_size, input_dim, input_dim, input_depth))\n train_y = np.zeros((input_size, label_size))\n for _ in xrange(input_size):\n train_y[_,np.random.randint(0, label_size)] = 1\n\n model =Sequential()\n model.add(Input(batch_input_shape=(None, 28, 28, 1)))\n model.add(Conv2d((3, 3), 1, activator='relu'))\n model.add(AvgPooling((2, 2), stride=2))\n model.add(Conv2d((4, 4), 2, activator='relu'))\n model.add(AvgPooling((2, 2), stride=2))\n model.add(Flatten())\n model.add(Softmax(label_size))\n model.compile('CCE', optimizer=SGD(1e-2))\n model.fit(train_X, train_y)",
"def preprocess_caffemodel(self, net):\n BatchNormalization = \\\n chainer.links.normalization.batch_normalization.BatchNormalization\n Scale = chainer.links.connection.scale.Scale\n\n if self.verbose:\n print(\"Applying caffemodel preprocessing to the network\")\n\n # Algorithm:\n # There are 2 patterns of mergeable BN+Scale.\n # 1. Both BN and Scale refer the same src (ResNet caffemodel pattern)\n # 2. Scale refers BN (DenseNet caffemodel patten)\n\n # for pattern 1, finding common source (str => index)\n bn_scale_common_sources = dict()\n bns = dict()\n scale_indices = []\n for i, (func_name, bottoms, _) in enumerate(net.layers):\n if not hasattr(net, func_name):\n # function that has no parameter like ReLU doesn't exist\n # in `net` as an attr but BN and Scale do\n continue\n layer = getattr(net, func_name)\n\n # Find sources that are referred by both BN and Scale layers\n for src_name in bottoms:\n # In net.layers, BN always comes first and Scale comes next\n if type(layer) is BatchNormalization:\n # For patten 1: Mark the source `bottom` is referred by BN\n bn_scale_common_sources[src_name] = i\n\n # For patten 2: Mark the layer is BN\n bns[func_name] = i\n elif type(layer) is Scale:\n if bn_scale_common_sources.get(src_name) is not None:\n # Pattern 1 found:\n # This source `bottom` is already marked;\n # That is obviously BN\n i = bn_scale_common_sources[src_name]\n bn_layer_name, _, _ = net.layers[i]\n bn = getattr(net, bn_layer_name)\n bn.gamma = chainer.Parameter(layer.W.data)\n if hasattr(layer, 'bias'):\n bn.beta = chainer.Parameter(layer.bias.b.data)\n scale_indices.append(i)\n if self.verbose:\n print('Mergeable BN detected '\n '(BN:{}/Scale:{} both refer {})'\n .format(bn_layer_name, func_name, src_name))\n elif src_name in bns:\n # Pattern 2 found: This scale layers refers BN layer!!\n bn = getattr(net, src_name)\n bn.gamma = chainer.Parameter(layer.W.data)\n if hasattr(layer, 'bias'):\n bn.beta = chainer.Parameter(layer.bias.b.data)\n scale_indices.append(i)\n if self.verbose:\n print('Mergeable BN detected '\n '(Scale:{} refers BN:{})'\n .format(func_name, src_name))\n\n # Remove scale layers that are no longer necessary\n for i in sorted(scale_indices, reverse=True):\n del net.layers[i]",
"def nvidia_model():",
"def get_conv_net(self):\n layers = []\n in_channels = self.channels\n\n for layer in configs[self.config]:\n if layer == 'M':\n layers.append(nn.MaxPool2d(kernel_size=2, stride=2))\n else:\n layer = layer.split('-')\n kernel_size = int(layer[0])\n out_channels = int(layer[1])\n layers.append(nn.Conv2d(in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n padding=1))\n\n if self.batch_norm:\n layers.append(nn.BatchNorm2d(out_channels))\n\n layers.append(nn.ReLU(inplace=True))\n in_channels = out_channels\n\n return nn.Sequential(*layers)",
"def __init__(self):\n self.pictures = pickle.load(open(\"X.pickle\", \"rb\"))\n self.labels = pickle.load(open(\"Y.pickle\", \"rb\"))\n \n # Declaracion de las capas de la modelo\n self.model = keras.Sequential([\n keras.layers.Flatten(input_shape=(50, 50,1)),\n keras.layers.Dense(128, activation=tf.nn.relu), #128 nodos\n keras.layers.Dense(10, activation=tf.nn.softmax) #2 etiquetas\n ])\n\n # Compila el modelo\n self.model.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])",
"def baseline_convnet(input_shape, num_classes):\n model = Sequential()\n\n model.add(Conv2D(48, (3, 3), padding='same', input_shape=input_shape))\n model.add(BatchNormalization())\n model.add(PReLU())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Conv2D(16, (3, 3), padding='same'))\n model.add(BatchNormalization())\n model.add(PReLU())\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Flatten())\n model.add(Dense(num_classes, activation='softmax'))\n\n return model",
"def create_model(self):\n # Calculate the input shape\n self.__calculate_the_input_shape()\n\n self.__keras_model = Sequential()\n self.__keras_model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=self.input_shape))\n self.__keras_model.add(Conv2D(64, (3, 3), activation='relu'))\n self.__keras_model.add(MaxPooling2D(pool_size=(2, 2)))\n self.__keras_model.add(Dropout(0.25))\n self.__keras_model.add(Flatten())\n self.__keras_model.add(Dense(128, activation='relu'))\n self.__keras_model.add(Dropout(0.5))\n self.__keras_model.add(Dense(self.__number_of_classes, activation='softmax'))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Create new TXs at rate lambda and do PoW
|
def issue_txs(self, Time):
if MODE[self.NodeID]>0:
if MODE[self.NodeID]==2:
if self.BackOff:
self.LastIssueTime += TAU#BETA*REP[self.NodeID]/self.Lambda
while Time+STEP >= self.LastIssueTime + self.LastIssueWork/self.Lambda:
self.LastIssueTime += self.LastIssueWork/self.Lambda
Parents = self.select_tips()
#Work = np.random.uniform(AVG_WORK[self.NodeID]-0.5, AVG_WORK[self.NodeID]+0.5)
if IOT[self.NodeID]:
Work = np.random.uniform(IOTLOW,IOTHIGH)
else:
Work = 1
self.LastIssueWork = Work
self.TranCounter += 1
self.IssuedTrans.append(Transaction(self.LastIssueTime, Parents, self, Work, Index=self.TranCounter))
elif MODE[self.NodeID]==1:
if IOT[self.NodeID]:
Work = np.random.uniform(IOTLOW,IOTHIGH)
else:
Work = 1
times = np.sort(np.random.uniform(Time, Time+STEP, np.random.poisson(STEP*self.Lambda/Work)))
for t in times:
Parents = self.select_tips()
#Work = np.random.uniform(AVG_WORK[self.NodeID]-0.5, AVG_WORK[self.NodeID]+0.5)
self.TranCounter += 1
# if self.TranCounter==170 and self.Repchange and self.NodeID==4:
# print('Time',Time)
# self.Repchange=False
# self.IssuedTrans.append(Transaction(t, Parents, self, Work, Index=self.TranCounter, Rep_change=7, Rep_massage=True, RepTX=self, RepRX=(self.Neighbours+self.Network.Nodes[3].Neighbours)))
#else:
self.IssuedTrans.append(Transaction(t, Parents, self, Work, Index=self.TranCounter))
else:
Work = 1
times = np.sort(np.random.uniform(Time, Time+STEP, np.random.poisson(STEP*self.Lambda/Work)))
for t in times:
Parents = self.select_tips()
#Work = np.random.uniform(AVG_WORK[self.NodeID]-0.5, AVG_WORK[self.NodeID]+0.5)
self.TranCounter += 1
self.IssuedTrans.append(Transaction(t, Parents, self, Work, Index=self.TranCounter))
# check PoW completion
while self.IssuedTrans:
Tran = self.IssuedTrans.pop(0)
p = Packet(self, self, Tran, Tran.IssueTime, Tran.IssueTime)
if MODE[self.NodeID]>2: # malicious don't consider own txs for scheduling
self.add_to_ledger(self, Tran, Tran.IssueTime)
else:
self.add_to_inbox(p, Tran.IssueTime)
|
[
"def block(max_number_of_txns, exp_time):\n blk = {'transactions':[transaction(randrange(2, max_txt_length)) for i in range(randrange(1, max_number_of_txns))], 'time':exp_time}\n return blk",
"def handle(self, *args, **options):\n number_accounts_per_node = 150\n\n nodes_list = get_nodes()\n wallets_list = get_wallets()\n for node in nodes_list:\n wallet = None\n\n for wallet_check in wallets_list:\n if wallet_check.node.id == node.id:\n wallet = wallet_check\n\n if wallet is None:\n wallet = new_wallet(node=node)\n\n for i in range(number_accounts_per_node):\n print(\"Created %s\" % (new_account(wallet=wallet)))\n\n all_accounts = list(get_accounts())\n funding_account = all_accounts[0]\n input(\"Please deposit funds to %s and press enter\" % funding_account.address)\n\n ## Init. PoW\n funding_account.POW = None\n funding_account.save()\n\n ## Wait for funds to clear\n while funding_account.current_balance == 0:\n sync_accounts()\n funding_account = Account.objects.filter(address=funding_account.address)[0]\n time.sleep(5)\n\n\n rpc = nano.rpc.Client(funding_account.wallet.node.URL)\n for i in range(6):\n try:\n address_nano = funding_account.address.replace(\"xrb\", \"nano\", 1)\n frontier = rpc.frontiers(account=funding_account.address, count=1)[address_nano]\n if funding_account.POW is None or not rpc.work_validate(work=funding_account.POW, hash=frontier):\n print(\"Generating PoW account %s \" % (funding_account.address))\n\n data = {\n 'hash': str(frontier),\n 'key': settings.DPOW_API_KEY\n }\n\n res = requests.post(url=settings.DPOW_ENDPOINT, json=data, timeout=15)\n funding_account.POW = res.json()['work']\n funding_account.save()\n break\n except Exception:\n if i == 5:\n print('dPoW failure account %s unlocked without PoW' % funding_account.address)\n funding_account.unlock()\n\n while not funding_account.POW:\n funding_account = Account.objects.get(address=funding_account.address)\n time.sleep(1)\n\n empty_accounts = Account.objects.filter(current_balance=0).all()\n\n #Distribute funds between accounts to open them\n amount = funding_account.current_balance / len(empty_accounts[:])\n\n random.shuffle(all_accounts) # spread opening load across nodes\n print(\"Accounts empty %s \" % (len(empty_accounts[:])))\n for account_init in all_accounts:\n # Already opened\n if account_init.current_balance > 0:\n print(\"Skipping\")\n continue\n try:\n address_nano = funding_account.address.replace(\"xrb\", \"nano\")\n frontier = rpc.frontiers(account=funding_account.address, count=1)[address_nano]\n if funding_account.POW is None or not rpc.work_validate(work=funding_account.POW, hash=frontier):\n\n data = {\n 'hash': str(frontier),\n 'key': settings.DPOW_API_KEY\n }\n\n res = requests.post(url=settings.DPOW_ENDPOINT, json=data, timeout=15)\n funding_account.POW = res.json()['work']\n funding_account.save()\n except Exception:\n if i == 5:\n print('dPoW failure account %s unlocked without PoW' % funding_account.address)\n funding_account.unlock()\n count = 0\n while not funding_account.POW and count < 5:\n funding_account = Account.objects.get(address=funding_account.address)\n count += 1\n time.sleep(1)\n\n simple_send(funding_account, account_init.address, int(amount), generate_PoW=False) ##Using send simple allows node to generate open block for us",
"def generate_data_oscilatory(nTrials, N, T,freq_coinc, amp_coinc, offset_coinc,freq_bg, amp_bg,offset_bg,RateJitter = 10*pq.Hz):\n# from stocmod import poisson_nonstat as pn\n import neo\n h = 1*pq.ms\n # modulatory coincidence rate\n tc = numpy.arange(0,T.rescale('ms').magnitude,h.rescale('ms').magnitude)*pq.ms\n bbc = (2*numpy.pi*freq_coinc*tc).simplified\n coincrate = offset_coinc+ amp_coinc*numpy.sin(bbc)*offset_coinc.units\n coincrate[coincrate <0*coincrate.units]=0*coincrate.units\n\n # background rate\n tb = numpy.arange(0,T.rescale('ms').magnitude,h.rescale('ms').magnitude)*pq.ms\n bbb = (2*numpy.pi*freq_bg*tb).simplified\n backgroundrate = offset_bg+ amp_bg*numpy.sin(bbb)*offset_bg.units\n backgroundrate[backgroundrate <0*backgroundrate.units]=0*backgroundrate.units\n\n # inhomogenious rate across trials\n rndRateJitter = (numpy.random.rand(nTrials)-0.5)*RateJitter\n spiketrain = []\n for i in range(nTrials):\n rate_signal_bg = neo.AnalogSignal((backgroundrate.rescale('Hz')+rndRateJitter[i]).magnitude,sampling_period=h, units=pq.Hz,t_start=0*pq.ms)\n rate_signal_coinc = neo.AnalogSignal(coincrate.rescale('Hz').magnitude,sampling_period=h, units=pq.Hz,t_start=0*pq.ms)\n sts_bg = poisson_nonstat(rate_signal_bg,N=N)\n # inserting coincidences\n sts_coinc = poisson_nonstat(rate_signal_coinc,N=1)\n sts_bg_coinc = []\n for j in sts_bg:\n sts_bg_coinc.append(\n neo.SpikeTrain(numpy.sort(numpy.append(j.magnitude, sts_coinc[0].magnitude))*j.units,\n t_start=j.t_start,t_stop = j.t_stop))\n spiketrain.append(sts_bg_coinc)\n return {'st':spiketrain, 'backgroundrate':backgroundrate, 'coincrate':coincrate}",
"def parallel_call(self, request, claims):\n\n self.sleep(request['number'])\n request['number'] = request['number']**POWER\n return request",
"async def generate_everything(count: int = 200,\n user_creation_weight: int = 1, item_creation_weight: int = 1,\n order_creation_weight: int = 1, top_up_user_weight: int = 1,\n pay_order_weight: int = 1, return_order_weigth: int = 1):\n actions = [generate_user] * user_creation_weight + \\\n [generate_item] * item_creation_weight + \\\n [generate_order] * order_creation_weight + \\\n [top_up_user] * top_up_user_weight + \\\n [pay_order] * pay_order_weight + \\\n [return_order] * return_order_weigth\n for _ in range(count):\n try:\n await random.choice(actions)()\n except IndexError:\n pass\n return {\"message\": \"OK\"}",
"def test_task_creation(self):\n\n\n temp_script = \"\"\"\n stream\n |from()\n .measurement('cpu')\n |alert()\n .crit(lambda: \"value\" < 70)\n .log('/tmp/alerts.log')\n \"\"\"\n\n temp_id = self.template_id\n task_id = self.task_id\n\n\n # Create task\n temp = self.kap.create_task(task_id, dbrps=self.dbrps, script=temp_script, task_type='stream')\n self.assertEqual(temp['status'],'enabled')\n sleep(20)\n\n for i in reversed(range(0,5)):\n sleep(1)\n dp_dict = {'cpu': i}\n self.i.send_object_measurements(dp_dict, tags={\"site_name\":\"test_site\"}, database=self._influx_db_name)\n temp = self.kap.get_task(task_id)\n\n self.assertGreater(temp['stats']['node-stats']['alert2']['alerts_triggered'], 0)",
"def calculate_payoff_times(self):\n with self.database.transaction():\n current_id = 0\n for Bo in constants.initial_balance_range():\n for r in constants.interest_rate_range():\n for p in constants.monthly_payment_range():\n print(\"Calculating for initial balance {0}, rate {1}, monthly payment {2}\".format(Bo, r, p))\n t = time_until_zero_balance(r, Bo, p)\n if t is not None:\n database.create_point(current_id, Bo, r, p, t)\n current_id += 1",
"def test_create_wire_transaction(session):\n # Create an account and an invoice for the account\n account = factory_create_wire_account(auth_account_id='1', status=CfsAccountStatus.ACTIVE.value)\n previous_day = datetime.now() - timedelta(days=1)\n # Create an invoice for this account\n invoice = factory_invoice(payment_account=account, created_on=previous_day, total=10, payment_method_code=None)\n\n fee_schedule = FeeScheduleModel.find_by_filing_type_and_corp_type('CP', 'OTANN')\n line = factory_payment_line_item(invoice.id, fee_schedule_id=fee_schedule.fee_schedule_id)\n line.save()\n\n assert invoice.invoice_status_code == InvoiceStatus.CREATED.value\n assert invoice.payment_method_code == 'WIRE'\n\n CreateInvoiceTask.create_invoices()\n\n updated_invoice: InvoiceModel = InvoiceModel.find_by_id(invoice.id)\n inv_ref: InvoiceReferenceModel = InvoiceReferenceModel. \\\n find_by_invoice_id_and_status(invoice.id, InvoiceReferenceStatus.ACTIVE.value)\n\n assert inv_ref\n assert updated_invoice.invoice_status_code == InvoiceStatus.SETTLEMENT_SCHEDULED.value",
"def distribute_deprecated(self, radius = 5):\n\t\t\n\t\tself.is_processing = True\n\t\tself.save()\n\t\tenough_points = True \n\t\t\n\t\tt = TxtTemplates()\n\n\t\t#print \"Sending out offers\"\n\n\t\t# 70 percent of old customers, 30 percent of new\n\t\tmax_offers = self.max_offers\n\t\texisting_num = int(round(0.7*max_offers))\n\n\t\tmerchant = self.merchant\n\t\t\n\t\tnearby_customers = self.merchant.get_customers_within_miles(radius)\n\t\tfans = merchant.fans.filter(pk__in=nearby_customers, verified_phone=0).exclude(active=False).exclude(verified=False).order_by('?').values_list('pk', flat=True)\n\t\tantifans = merchant.antifans.all().values_list('pk', flat=True)\n\t\t# TODO: geographically filter\n\t\t\n\t\tnonfans = Customer.objects.filter(pk__in=nearby_customers, verified_phone=0).exclude(active=False).exclude(verified=False).exclude(pk__in=fans).exclude(pk__in=antifans).values_list('pk',flat=True)\n\t\t#nonfans = Customer.objects.exclude(active=False).exclude(verified=False).exclude(pk__in=fans).exclude(pk__in=antifans).filter(zipcode=merchant.zipcode).values_list('pk', flat=True)\n\n\t\tprint \"Num fans:\",fans.count()\n\t\tprint \"Num nonfans:\",nonfans.count()\n\t\tfan_target = set(list(fans))\n\t\tnonfan_target = set(list(nonfans))\t\n\t\ttarget = fan_target | nonfan_target\n\t\tif len(target) > max_offers:\n\t\t\ttarget_list = random.sample(target, max_offers)\n\t\telse:\n\t\t\ttarget_list = list(target)\n\n\t\tfrom worldbank.models import Transaction\n\n\t\tallowed_number =int( self.merchant.balance/abs(Transaction.points_table[\"MOD\"]))\n\t\t#print \"balance=\" ,self.merchant.balance\n\t\t#print \"allowed_number\", allowed_number\n\t\tif allowed_number == 0:\n\t\t\t# check if there's enough balance\n\t\t\tenough_points = False\n\n\t\tif len(target_list) > allowed_number:\n\t\t\ttarget_list = random.sample(target_list, allowed_number)\n\t\tsentto = self.gen_offer_codes(Customer.objects.filter(pk__in=target_list))\t\n\t\t#print \"count=\" , self.offercode_set.all().count()\n\t\tfor o in self.offercode_set.all():\n\t\t\toffer_msg = t.render(TxtTemplates.templates[\"CUSTOMER\"][\"OFFER_RECEIVED\"],{ \"merchant\":self.merchant.business_name, \"title\":self.title, \"code\":o.code })\t\t\n\t\t\tsms_notify(o.customer.phone, offer_msg, SMS_DEBUG)\n\t\t\ttransaction = Transaction.objects.create(time_stamp=datetime.now(),\n\t\t\t\t\t\t\toffer = self,\n\t\t\t\t\t\t\toffercode = o,\n\t\t\t\t\t\t\tdst = self.merchant,\n\t\t\t\t\t\t\tttype = \"MOD\")\n\t\t\ttransaction.execute()\n\n\t\tself.num_init_sentto =sentto\n\t\tself.is_processing = False\n\t\tself.expired_time = self.starting_time + timedelta(minutes=self.duration)\n\t\tself.save()\n\n\t\n\n\t\t\n\t\tif enough_points: \n\t\t\t# number of people sent to, it can be 0 \n\t\t\treturn self.num_init_sentto\n\t\telse:\n\t\t\t# not enough points to send to\n\t\t\treturn -2",
"def mutate(self, rate):\n for i in range(self.number_of_transitions):\n shape = np.shape(self.weights[i])\n size = self.weights[i].size\n weights = self.weights[i].flatten()\n for j in range(len(weights)):\n if np.random.uniform(0, 1) < rate:\n weights[j] = np.random.normal(0, 1 / np.sqrt(shape[0]))\n self.weights[i] = weights.reshape(shape)\n for j in range(len(self.biases[i])):\n if np.random.uniform(0, 1) < rate:\n self.biases[i][j] = np.random.normal(0, 1)",
"def test_get_transactions(self):\n start_time = time.time()\n\n for _ in range(0, NR_TESTS):\n user = random.randint(0, MAX_USERS)\n threshold = random.randint(0, MAX_SUM + 200)\n date_offset = random.randint(-10, 70)\n date = next_date_string(DAY_STRING1, date_offset)\n response = requests.get(HOME_URL + \"transactions/?user=\" +\n str(user) + \"&day=\" + date + \"&threshold=\" +\n str(threshold))\n assert response.status_code == 200\n\n end_time = time.time()\n print \"\\nGet transactions time: \" + str(end_time - start_time)",
"def create_backtesting_data_async(to_days=None, max_price=300):\n strategies = Strategy.objects.filter(backtesting_ready=True)\n liquid_stocks = get_liquid_stocks(max_price=max_price)\n today_date = get_local_time().date()\n task_counter = 0\n start_time = time(16,30)\n end_time = time(7,30)\n current_time = get_local_time().time()\n\n if current_time > start_time or current_time < end_time:\n\n def get_day_count(entry_time:datetime, candle_type):\n entry_date = entry_time.date()\n day_count = (today_date - entry_date).days\n if candle_type in [\"1H\", \"M30\"]:\n return day_count + 10\n return day_count + 2\n \n run_task_after = 0\n for stock in liquid_stocks:\n if task_counter >= 10:\n break\n data = {\n \"entry_type\" : \"BUY\",\n \"stock_id\" : stock.id,\n \"to_days\" : to_days or 90,\n \"strategy_id\" : \"\",\n \"end_date\" : str(get_local_time().date())\n }\n for strategy in strategies:\n data[\"strategy_id\"] = strategy.id\n reports = BacktestReport.objects.filter(strategy_name=strategy.strategy_name, symbol_name=stock.symbol)\n for candle_choice in strategy.timeframe:\n last_backtest_log = stock.get_last_backtesting_log(strategy.strategy_name, candle_choice, \"BUY\")\n candle_type_report = reports.filter(candle_type=candle_choice)\n data[\"candle_type\"] = candle_choice\n buy_reports = candle_type_report.filter(entry_type=data[\"entry_type\"])\n if not buy_reports.exists():\n SendBackTestingRequest().apply_async(kwargs=data, countdown=run_task_after)\n task_counter += 1\n elif last_backtest_log == None or (last_backtest_log and last_backtest_log.backtest_date < (today_date - timedelta(10))):\n data[\"to_days\"] = get_day_count(buy_reports.last().entry_time, data[\"candle_type\"])\n SendBackTestingRequest().apply_async(kwargs=data, countdown=run_task_after)\n task_counter += 1\n\n data[\"entry_type\"] = \"SELL\"\n last_backtest_log = stock.get_last_backtesting_log(strategy.strategy_name, candle_choice, \"SELL\")\n sell_reports = candle_type_report.filter(entry_type=data[\"entry_type\"])\n if not sell_reports.exists():\n SendBackTestingRequest().apply_async(kwargs=data, countdown=run_task_after)\n task_counter += 1\n elif last_backtest_log == None or (last_backtest_log and last_backtest_log.backtest_date < (today_date - timedelta(10))):\n data[\"to_days\"] = get_day_count(sell_reports.last().entry_time, data[\"candle_type\"])\n SendBackTestingRequest().apply_async(kwargs=data, countdown=run_task_after)\n task_counter += 1\n run_task_after += 30 # In seconds\n return True\n return False",
"def gen_rate_profile(b,A,w,t,t0):\n tau2 = float(w)/numpy.sqrt(5)\n if t<t0:\n return b\n else:\n return b+ float(A)*((1./(tau2)) * (numpy.exp(-(t-t0)/(2*tau2)) - numpy.exp(-(t-t0)/tau2)))",
"def hunt(self, trials=10000, sleep_time=0.1):\n num_runs = 0\n pre_arbitrage_assets = self.load_arbitrage_assets()\n time.sleep(sleep_time)\n while(num_runs < trials):\n try:\n self.update_orderbook()\n except ConnectionError as e:\n print(e + \"will suspend bot for 10 seconds\")\n time.sleep(10)\n continue\n #Search for inefficiency\n orderbook_btc = self.orderbook_btc_eth(self.orderbook)\n orderbook_eth = self.orderbook_eth_btc(self.orderbook)\n if(orderbook_btc[0][1] - (self.fee * orderbook_btc[0][1]) > self.bit_rate['btc_one'] and\n orderbook_eth[0][1] - (self.fee * orderbook_eth[0][1]) > float(self.bit_rate['askPrice'])): \n #print('found' + orderbook_btc[0][0] + orderbook_eth[0][0] + str(num_runs))\n num_runs += 1\n purchase = []\n for k in self.orderbook:\n if(list(k.keys())[0] == orderbook_btc[0][0]):\n purchase.insert(0, k)\n if(list(k.keys())[0] == orderbook_eth[0][0]):\n purchase.insert(1, k)\n btc_limit = binance_config.btc_trade_limit\n while(btc_limit > 0.001):\n if(self.determine_feasibility(orderbook_btc[0][0], orderbook_eth[0][0], purchase, btc_limit) is True):\n self.execute_trade(orderbook_btc[0][0], orderbook_eth[0][0], purchase, btc_limit)\n break\n else:\n btc_limit = btc_limit - 0.001\n num_runs += 1\n if(num_runs % 100 == 0):\n print(str(num_runs))\n post_arbitrage_assets = self.load_arbitrage_assets()\n \n #Print results\n time_delta = datetime.datetime.now().replace(microsecond=0) - pre_arbitrage_assets['datetime'] \n print('Initial: BTC:', pre_arbitrage_assets['BTC'],'ETH:', pre_arbitrage_assets['ETH'], 'BNB:', pre_arbitrage_assets['BNB'])\n print('After__: BTC:', post_arbitrage_assets['BTC'],'ETH:', post_arbitrage_assets['ETH'], 'BNB:', post_arbitrage_assets['BNB'])\n print('Diff___: BTC:', float(post_arbitrage_assets['BTC'])-float(pre_arbitrage_assets['BTC']),\n 'ETH:', float(post_arbitrage_assets['ETH'])-float(pre_arbitrage_assets['ETH']),\n 'BNB:', float(post_arbitrage_assets['BNB'])-float(pre_arbitrage_assets['BNB']),\n 'TIME:', divmod(time_delta.total_seconds(), 60))",
"def test_add_entries(self):\n start_time = time.time()\n\n ts_start = get_timestamp(DAY_STRING1)\n ts_end = get_timestamp(DAY_STRING2)\n for _ in range(0, NR_TESTS):\n timestamp = random.randint(ts_start - 5000, ts_end + 5000)\n sender = random.randint(0, MAX_USERS)\n receiver = random.randint(0, MAX_USERS)\n sent_sum = random.randint(0, MAX_SUM)\n\n payload = {'sender': sender, 'receiver': receiver, 'sum': sent_sum,\n 'timestamp': timestamp}\n response = requests.post(HOME_URL + \"transactions/\", json=payload)\n assert response.status_code == 200\n\n end_time = time.time()\n print \"\\nPost transactions time: \" + str(end_time - start_time)",
"def handle(self, *args, **options):\n # command to run: python manage.py tunga_update_task_payment_rates.py\n\n # Initialize missing logs\n tasks = Task.objects.filter(closed=False)\n for task in tasks:\n active_participants = task.participation_set.filter(accepted=True).count()\n print task.id, active_participants\n if not active_participants:\n task.dev_rate = Decimal(19)\n task.pm_rate = Decimal(39)\n task.pm_time_percentage = Decimal(15)\n task.tunga_percentage_dev = Decimal('34.21')\n task.tunga_percentage_pm = Decimal('48.71')\n task.save()",
"def test_center(self):\n\n test_rates = list()\n for _ in range(10):\n test_rates.append(round(random.random(), 3))\n test_rates.append(float(0.0))\n test_rates.append(float(0.5))\n test_rates.append(float(1.0))\n\n for target_rate in test_rates:\n rtcp = RandomTaskConsumptionPolicy(target_rate)\n\n num_tests = 10000\n true_count = 0\n for _ in range(num_tests):\n if rtcp.process_task(self._test_task_meta):\n true_count += 1\n\n err = 0.01 - (target_rate - (true_count / num_tests))\n logging.info(str(err))\n self.assertAlmostEqual(float(0), err, places=1)\n return",
"def insert_dummy_temperatures(number_of_readings_per_probe=1000): \n readings = []\n probe_ids = hardware.temperature_probes.probe_ids \n for probe_number in range(0, number_of_readings_per_probe): \n for probe_id in probe_ids: \n readings.append(get_temperature_for_probe(probe_id, probe_number))\n database.db_adapter.store_temperatures(readings) \n database.db_adapter.db.commit()\n print 'Added ' + str(number_of_readings_per_probe * len(probe_ids)) + ' test temperature readings.'",
"def create_exchanges():\n coinbasepro = ccxt.coinbasepro({\n 'apiKey': api_keys.coinbasepro['apiKey'],\n 'secret': api_keys.coinbasepro['secret'],\n 'enableRateLimit': True,\n })\n\n cex = ccxt.cex({\n 'apiKey': api_keys.cex['apiKey'],\n 'secret': api_keys.cex['secret'],\n 'enableRateLimit': True,\n })\n\n poloniex = ccxt.poloniex({\n 'apiKey': api_keys.poloniex['apiKey'],\n 'secret': api_keys.poloniex['secret'],\n 'enableRateLimit': True,\n })\n\n bittrex = ccxt.bittrex({\n 'apiKey': api_keys.bittrex['apiKey'],\n 'secret': api_keys.bittrex['secret'],\n 'enableRateLimit': True,\n })\n\n binance = ccxt.binance({\n 'apiKey': api_keys.binance['apiKey'],\n 'secret': api_keys.binance['secret'],\n 'enableRateLimit': True,\n })\n\n bitfinex = ccxt.bitfinex({\n 'apiKey': api_keys.bitfinex['apiKey'],\n 'secret': api_keys.bitfinex['secret'],\n 'enableRateLimit': True,\n })\n\n kucoin = ccxt.kucoin({\n 'apiKey': api_keys.kucoin['apiKey'],\n 'secret': api_keys.kucoin['secret'],\n 'enableRateLimit': True,\n })\n\n kraken = ccxt.kraken({\n 'apiKey': api_keys.kraken['apiKey'],\n 'secret': api_keys.kraken['secret'],\n 'enableRateLimit': True,\n 'options': { # ←--------------------- inside 'options' subkey\n 'fetchMinOrderAmounts': False, # ←---------- set to False \n }\n })\n\n bitmex = ccxt.bitmex({\n 'apiKey': api_keys.bitmex['apiKey'],\n 'secret': api_keys.bitmex['secret'],\n 'enableRateLimit': True,\n })\n\n okex = ccxt.okex({\n 'apiKey': api_keys.okex['apiKey'],\n 'secret': api_keys.okex['secret'],\n 'enableRateLimit': True,\n })\n\n exchanges =[coinbasepro, cex, poloniex, bittrex, binance, bitfinex, kucoin, kraken, okex, bitmex]\n\n return exchanges"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Implements uniform random tip selection
|
def select_tips(self):
ValidTips = [tip for tip in self.TipsSet if self.ValidTips[tip.NodeID]]
if len(ValidTips)>1:
Selection = sample(ValidTips, 2)
elif len(self.Ledger)<2:
Selection = [self.Ledger[0]]
else:
Selection = self.Ledger[-2:-1]
return Selection
|
[
"def random_subset(self, perc=0.5):",
"def sample_random_node(self):\n #Naive Approach \n return self.tree[int(self.rng.random()*len(self.tree))] # OUT OF BOUNDS ERRORS? Check this",
"def rand_temp():\n return BASE_T + random() * RAND_MULT",
"def random_states(T, n, cutoff=25, qutip=True):\n data = [x for x in StateIterator(n, T=T, cutoff=cutoff, qutip=qutip)]\n states, labels = zip(*data)\n if qutip:\n states = np.array(states)\n else:\n states = np.array([s[:cutoff] for s in states])\n labels = np.array(labels)\n return states, labels",
"def pickNode(self):\n\treturn sample_weighted([1.0/n.density for n in self.nodes],self.nodes)",
"def random(self):\r\n if self.ate_apple:\r\n self.x = 20 * random.randint(0, 23)\r\n self.y = 20 * random.randint(3, 23)",
"def random_choice(x, a, p):\n np.random.seed()\n return np.random.choice(a = a, size = x , p =p)",
"def random():\n return Scale(Note.random(), Mode.random())",
"def draw_uniform_sample(choices: List[T], n: int) -> List[T]:\n return random.default_rng().choice(a=choices, size=n)",
"def roulette_selection(self):\n #.....calc all the probabilities\n prob= []\n for ind in self.population:\n prob.append(self.fitfunc(ind.value))\n\n istore=[]\n for i in range(len(self.population)):\n istore.append(0)\n\n for i in range(self.nindv):\n ptot= 0.0\n for ii in range(len(self.population)):\n if istore[ii] == 1: continue\n ptot += prob[ii]\n prnd= random()*ptot\n #print i,ptot\n ptot= 0.0\n for ii in range(len(self.population)):\n if istore[ii] == 1: continue\n ptot= ptot +prob[ii]\n #print ii,prnd,ptot\n if prnd < ptot:\n istore[ii]= 1\n break\n\n while istore.count(0) > 0:\n idx= istore.index(0)\n del self.population[idx]\n del istore[idx]\n\n if len(self.population) != self.nindv:\n print \"{0:*>20}: len(self.population != self.nindv) !!!\".format(' Error')\n print len(self.population), self.nindv\n exit()",
"def rand_init_state(self):\n state = np.random.random((self.lattice, self.lattice))\n state[state >= 0.5] = 1\n state[state < 0.5] = -1\n return state",
"def random_state(self):\n return np.random.randint(0, 2, self.nodes)",
"def __init__(self):\n self.prob_heads = random()",
"def sample(self, n, unique=False):\n self._sampled_unique = unique\n random_values = np.random.rand(int(n * 1 if unique else n))\n tree_idxs, scaled_random_values = self.find(random_values)\n if unique:\n i = 0\n while i < 100:\n tree_idxs, unique_idx = np.unique(tree_idxs, return_index=True)\n scaled_random_values = scaled_random_values[unique_idx]\n if len(tree_idxs) < n:\n new_idxs, new_values = self.find(\n np.random.rand(2 * (n - len(tree_idxs))))\n tree_idxs = np.concatenate([tree_idxs, new_idxs])\n scaled_random_values = np.concatenate(\n [scaled_random_values, new_values])\n else:\n break\n i += 1\n if len(tree_idxs) < n:\n raise RuntimeError(\n \"After 100 tries, unable to get unique indexes.\")\n tree_idxs = tree_idxs[:n]\n\n priorities = self.tree[tree_idxs]\n self.prev_tree_idxs = tree_idxs\n T_idxs, B_idxs = np.divmod(tree_idxs - self.low_idx, self.B)\n return (T_idxs, B_idxs), priorities",
"def randomPoint(self):\n # make sure to copy it, so there are no hidden connections between dataset and clusters\n return self.uniques[random.randint(0, self.uniques.shape[0] - 1),:].copy()",
"def long_tail():\n randint = random.randint(0,3)\n # Values are based on a mean mu of 0.92\n if randint == 0:\n tis = random.expovariate(1/0.68)\n else:\n tis =random.expovariate(1)\n return tis",
"def randomSample(tree):\r\n\r\n\t# Take an initial sample\r\n\tsample = Node((uniform(-pi, pi), uniform(-2, 2)))\r\n\r\n\twhile existsInTree(tree, sample): # sample again until we haven't see said sample\r\n\t\tsample = Node((uniform(-pi, pi), uniform(-2, 2)))\r\n\r\n\treturn sample",
"def rand_selector(population, num_to_select=3):\n return random.sample(population, num_to_select)",
"def draw(self,n):\n selected=[]\n for i in range(n):\n index = random.randint(0, len(self.balls)-1)\n color = self.balls.pop(index) #select color and remove it from hat\n selected.append(color)\n return selected"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
schedule txs from inbox at a fixed deterministic rate NU
|
def schedule_txs(self, Time):
# sort inboxes by arrival time
self.Inbox.AllPackets.sort(key=lambda p: p.EndTime)
self.Inbox.SolidPackets.sort(key=lambda p: p.EndTime)
for NodeID in range(NUM_NODES):
self.Inbox.Packets[NodeID].sort(key=lambda p: p.Data.IssueTime)
# process according to global rate Nu
while self.Inbox.SolidPackets or self.Inbox.Scheduled:
if self.Inbox.Scheduled:
nextSchedTime = self.LastScheduleTime+(self.LastScheduleWork/NU)
else:
nextSchedTime = max(self.LastScheduleTime+(self.LastScheduleWork/NU), self.Inbox.SolidPackets[0].EndTime)
if nextSchedTime<Time+STEP:
if SCHEDULING=='drr':
Packet = self.Inbox.drr_schedule(nextSchedTime)
elif SCHEDULING=='drr_lds':
Packet = self.Inbox.drr_lds_schedule(nextSchedTime,Time)
elif SCHEDULING=='drrpp':
Packet = self.Inbox.drrpp_schedule(nextSchedTime)
elif SCHEDULING=='fifo':
Packet = self.Inbox.fifo_schedule(nextSchedTime)
if Packet is not None:
if Packet.Data not in self.Ledger:
self.add_to_ledger(Packet.TxNode, Packet.Data, nextSchedTime)
# update AIMD
#if Packet.Data.NodeID==self.NodeID:
self.Network.Nodes[Packet.Data.NodeID].InboxLatencies.append(nextSchedTime-Packet.EndTime)
self.Inbox.Avg = (1-W_Q)*self.Inbox.Avg + W_Q*sum([p.Data.Work for p in self.Inbox.Packets[self.NodeID]])
self.set_rate(nextSchedTime)
self.LastScheduleTime = nextSchedTime
self.LastScheduleWork = Packet.Data.Work
self.ServiceTimes.append(nextSchedTime)
else:
break
else:
break
|
[
"def schedule_safety_net_messages():\n\tsnc = SafetyNetCenter()\n\tnow = datetime.datetime.now()\n\tsnc.schedule_safety_net_messages(\n\t\twindow_start=now - snc.window, \n\t\twindow_finish=now, \n\t\tthreshold=snc.threshold, \n\t\ttimeout=snc.timeout)",
"def tick_scheduler():\n\n scheduler.tick()",
"def scheduled(self, scheduler):",
"def schedule(self):\n \n #for tihs algorithm we travel the entire array anyway so no need to \n #actually start from curridx\n \n #if the current is not completed \n if self.tasks[self.curridx].STATE == STATE_RUN:\n min_prio = self.tasks[self.curridx].prio\n min_dead = self.tasks[self.curridx].dead\n schedule_this = self.curridx\n #else take them from IDLE\n #the effect is that if idle is the only one in the run queue it will keep running\n #else it will preempted by any possible task\n else:\n min_prio = self.tasks[-1].prio\n min_dead = self.tasks[-1].dead\n schedule_this = self.idle_id\n \n\n\n for tnext in self.idx_needs_schedul: \n \n \n tprio = self.tasks[tnext].prio\n tdead = self.tasks[tnext].dead\n \n \n if tprio == min_prio:\n #if the next deadline is shorter schedule this \n if tdead < min_dead:\n schedule_this = tnext\n \n #there is a task with higher priority \n if tprio < min_prio:\n #update the min prio\n min_prio = tprio\n min_dead = tdead\n schedule_this = tnext\n \n\n\n print(\"Schedule from {} to {}\".format( self.tasks[self.curridx].ID, self.tasks[schedule_this].ID ) ) \n self.curridx = schedule_this",
"def schedule(self):\n self.m_engine.schedule_event(REQ_INTERVAL,\\\n EVENT_SCHEDULE, self)\n\n if len(self.m_nbrs) == 0: return\n # self.m_avail_bw = REQ_INTERVAL / SEND_INTERVAL\n self.maintain_nbrs()\n\n if APP == STREAMING and self.m_buffering == True:\n chunk_num = 0\n obj_nbr = None\n for nbr in self.m_nbrs:\n if nbr.m_peer.avail_items_absolute() > chunk_num:\n chunk_num = nbr.m_peer.avail_items_absolute()\n obj_nbr = nbr\n if obj_nbr:\n self.m_seq_num = obj_nbr.m_peer.min_seq()\n\n if SCHEDULE == RANDOM_PULL:\n self.random_pull()\n elif SCHEDULE == RF_PULL:\n self.rf_pull()\n elif SCHEDULE == F2F_OPTIMAL: \n if APP == FILE_SHARING:\n self.f2f_fs_optimal()\n else: self.f2f_stream_optimal()\n elif SCHEDULE == F2F_PULL:\n if APP == FILE_SHARING:\n self.f2f_fs_pull()\n else: self.f2f_stream_pull()\n elif SCHEDULE == ENDURE_PULL:\n if APP == STREAMING:\n self.endurable_pull()",
"def run_scheduler():\n schedule.every().monday.do(send_text_recs)\n logging.error(\"Send Text Recs Scheduled\")\n while True:\n schedule.run_pending()\n time.sleep(1)",
"def timed_schedule():\n while running:\n time.sleep(23)\n if not scheduler.check_cluster_state():\n logger.info(\"re-balancing cluster\")\n jobs = storage.cluster_jobs.copy()\n for packet in UdpSerializer.dump(ReBalance(timestamp=datetime.now()), hash_key):\n client(args.udp_communication_port, packet)\n time.sleep(5)\n for job in jobs:\n for packet in UdpSerializer.dump(job, hash_key):\n client(args.udp_communication_port, packet)",
"def send_scheduled_msg(context: CallbackContext):\n # Time format is 21:54\n db.execute(\"SELECT * FROM schedules WHERE time=%s\", (str(datetime.utcnow() + timedelta(hours=8)).split(' ')[1].\n rsplit(':', 1)[0],))\n users = db.fetchall()\n\n for user in users:\n buses_selected_list = list(filter(lambda x: type(x) == str and x != 'None', user[5:10]))\n bus_message = scheduled_bus_timing_format(user[1], buses_selected_list)\n context.bot.send_message(chat_id=user[0], text=bus_message[0], reply_markup=bus_message[1],\n parse_mode=ParseMode.HTML)",
"def _schedule(self, func):\n clock = ScheduledEvent.clock\n clock.scheduled_funcs[func] += 1\n clock.queue.append(func)",
"def run(self):\n schedule.every().day.at(\"13:02\").do(self.fn)\n while True:\n schedule.run_pending()\n time.sleep(1)",
"def send_queued_mail(num):\n call_command('send_queued_mail', processes=1)",
"def test_soft_scheduling_stress_test(self):\n # this value represents evenly scheduled items between 0 & 1\n # and what is produced by the correct soft-scheduler\n expected = [0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5,\n 0.5625, 0.625, 0.6875, 0.75, 0.8125, 0.875, 0.9375, 1]\n\n for i in range(16):\n self.clock.schedule_interval_soft(None, 1)\n\n # sort the clock items\n items = sorted(i.next_ts for i in self.clock._schedule_interval_items)\n\n self.assertEqual(items, expected)",
"def teleopPeriodic(self) -> None:\n ...",
"def issue_txs(self, Time):\r\n if MODE[self.NodeID]>0:\r\n if MODE[self.NodeID]==2:\r\n if self.BackOff:\r\n self.LastIssueTime += TAU#BETA*REP[self.NodeID]/self.Lambda\r\n while Time+STEP >= self.LastIssueTime + self.LastIssueWork/self.Lambda:\r\n self.LastIssueTime += self.LastIssueWork/self.Lambda\r\n Parents = self.select_tips()\r\n #Work = np.random.uniform(AVG_WORK[self.NodeID]-0.5, AVG_WORK[self.NodeID]+0.5)\r\n if IOT[self.NodeID]:\r\n Work = np.random.uniform(IOTLOW,IOTHIGH)\r\n else:\r\n Work = 1\r\n self.LastIssueWork = Work\r\n self.TranCounter += 1\r\n self.IssuedTrans.append(Transaction(self.LastIssueTime, Parents, self, Work, Index=self.TranCounter))\r\n elif MODE[self.NodeID]==1:\r\n if IOT[self.NodeID]:\r\n Work = np.random.uniform(IOTLOW,IOTHIGH)\r\n else:\r\n Work = 1\r\n times = np.sort(np.random.uniform(Time, Time+STEP, np.random.poisson(STEP*self.Lambda/Work)))\r\n for t in times:\r\n Parents = self.select_tips()\r\n #Work = np.random.uniform(AVG_WORK[self.NodeID]-0.5, AVG_WORK[self.NodeID]+0.5)\r\n self.TranCounter += 1\r\n # if self.TranCounter==170 and self.Repchange and self.NodeID==4:\r\n # print('Time',Time)\r\n # self.Repchange=False\r\n # self.IssuedTrans.append(Transaction(t, Parents, self, Work, Index=self.TranCounter, Rep_change=7, Rep_massage=True, RepTX=self, RepRX=(self.Neighbours+self.Network.Nodes[3].Neighbours)))\r\n #else:\r\n self.IssuedTrans.append(Transaction(t, Parents, self, Work, Index=self.TranCounter))\r\n else:\r\n Work = 1\r\n times = np.sort(np.random.uniform(Time, Time+STEP, np.random.poisson(STEP*self.Lambda/Work)))\r\n for t in times:\r\n Parents = self.select_tips()\r\n #Work = np.random.uniform(AVG_WORK[self.NodeID]-0.5, AVG_WORK[self.NodeID]+0.5)\r\n self.TranCounter += 1\r\n self.IssuedTrans.append(Transaction(t, Parents, self, Work, Index=self.TranCounter))\r\n \r\n # check PoW completion\r\n while self.IssuedTrans:\r\n Tran = self.IssuedTrans.pop(0)\r\n p = Packet(self, self, Tran, Tran.IssueTime, Tran.IssueTime)\r\n if MODE[self.NodeID]>2: # malicious don't consider own txs for scheduling\r\n self.add_to_ledger(self, Tran, Tran.IssueTime)\r\n else:\r\n self.add_to_inbox(p, Tran.IssueTime)",
"def sending_auto_request(self, my_list, num, delay):\n \n i = 0\n try:\n \n while i < num:\n \n data = assemble_packet(my_list) \n bytes_sent = self.sock.sendto(data, self.remoteaddr)\n i += 1\n #print bytes_sent\n self.write_text_browser_info(\"Frequency request (%d out of %d) has been sent\" % (i, num))\n time.sleep(delay)\n \n except socket.error: # The socket is closed\n \n self.write_text_browser_error(\"The socket is closed! Please, connect again.\")",
"def schedule_call(delay, func, repeat=False):\n t = Scheduler.timestamp() + delay\n if repeat:\n r = delay\n else:\n r = 0.0\n item = ScheduledCall(t, func, r)\n insort(Scheduler.ourScheduledCalls, item)\n return item",
"async def spam(self, ctx, taskcount: int=200, timeout: int=30):\n while True:\n tasks = []\n done, pending = None, None\n\n with Timer() as timer:\n for i in range(taskcount):\n coro = self.transfer(ctx.bot.user.id,\n ctx.author.id, 0.1)\n t = self.loop.create_task(coro)\n tasks.append(t)\n\n done, pending = await asyncio.wait(tasks, timeout=timeout)\n self.loop.create_task(ctx.send(f'{taskcount} tasks in {timer}'))\n\n if pending:\n return await ctx.send(f'stopping from {lp} > 0 pending')\n\n taskcount *= 2",
"def schedule(self, now=None):\n\n for task in pop_queue_tasks(self.queue, now=now):\n self.schedule_task(task)",
"def run(self,t):\r\n while t>0:\r\n update(min(t,dt))\r\n t -= dt"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Calculate the robot's inverse kinematic (IK) for a given frame. The IK for 6axis industrial robots returns by default 8 possible solutions. These solutions have an order. That means that if you call IK on two subsequent frames and compare the 8 configurations of the first frame with the 8 configurations of the second frame at their respective indices, then these configurations are "close" to one another. For this reason, for certain use cases, e.g. for cartesian path planning, it makes sense to keep the order of solutions. This can be achieved by setting the optional parameter ``keep_order`` to ``True``. The configurations that are in collision or outside joint boundaries are then not removed from the list of solutions, they are set to ``None``.
|
def inverse_kinematics(self, robot, frame_WCF, start_configuration=None, group=None, options=None):
options = options or {}
solver = options.get("solver")
if solver:
self.planner = PLANNER_BACKENDS[solver]()
elif not self.planner: # no solver, no planner
raise ValueError("Please pass an inverse kinematics solver")
keep_order = options.get("keep_order", False)
# convert the frame WCF to RCF
base_frame = robot.get_base_frame(group=group, full_configuration=start_configuration)
frame_RCF = base_frame.to_local_coordinates(frame_WCF)
# calculate inverse with 8 solutions
try:
solutions = self.planner.inverse(frame_RCF)
except ValueError:
raise InverseKinematicsError()
configurations = joint_angles_to_configurations(robot, solutions, group=group)
# check collisions for all configurations (>> sets those to `None` that are not working)
if options.get("check_collision", False) is True:
acms = options.get("attached_collision_meshes", [])
for acm in acms:
cached_robot_model = self.client.get_cached_robot(robot)
if not cached_robot_model.get_link_by_name(acm.collision_mesh.id):
self.client.add_attached_collision_mesh(acm, options={"robot": robot})
for touch_link in acm.touch_links:
self.client.disabled_collisions.add((touch_link, acm.collision_mesh.id))
for i, config in enumerate(configurations):
try:
self.client.check_collisions(robot, config)
except BackendError:
configurations[i] = None
# fit configurations within joint bounds (>> sets those to `None` that are not working)
configurations = try_to_fit_configurations_between_bounds(robot, configurations, group=group)
if not any(configurations):
raise InverseKinematicsError()
for config in configurations:
if config:
yield config.joint_values, config.joint_names
elif keep_order:
yield None, None
|
[
"def inverse_kinematics_offset_wrist(frame, params, q6_des=0.0):\n\n ZERO_THRESH = 0.00000001\n d1, a2, a3, d4, d5, d6 = params\n\n solutions = []\n\n T02, T12, T22 = frame.xaxis\n T00, T10, T20 = frame.yaxis\n T01, T11, T21 = frame.zaxis\n T03, T13, T23 = frame.point\n T02 *= -1\n T03 *= -1\n T12 *= -1\n T13 *= -1\n T20 *= -1\n T21 *= -1\n\n # shoulder rotate joint (q1)\n # q1[2]\n q1 = [0, 0]\n A = d6 * T12 - T13\n B = d6 * T02 - T03\n R = A * A + B * B\n if fabs(A) < ZERO_THRESH:\n div = 0.0\n if fabs(fabs(d4) - fabs(B)) < ZERO_THRESH:\n div = -sign(d4) * sign(B)\n else:\n div = -d4 / B\n arcsin = asin(div)\n if fabs(arcsin) < ZERO_THRESH:\n arcsin = 0.0\n if arcsin < 0.0:\n q1[0] = arcsin + 2.0 * pi\n else:\n q1[0] = arcsin\n q1[1] = pi - arcsin\n\n elif fabs(B) < ZERO_THRESH:\n div = 0.0\n if fabs(fabs(d4) - fabs(A)) < ZERO_THRESH:\n div = sign(d4) * sign(A)\n else:\n div = d4 / A\n arccos = acos(div)\n q1[0] = arccos\n q1[1] = 2.0 * pi - arccos\n\n elif d4 * d4 > R:\n raise ValueError(\"No solutions\")\n else:\n arccos = acos(d4 / sqrt(R))\n arctan = atan2(-B, A)\n pos = arccos + arctan\n neg = -arccos + arctan\n if fabs(pos) < ZERO_THRESH:\n pos = 0.0\n if fabs(neg) < ZERO_THRESH:\n neg = 0.0\n if pos >= 0.0:\n q1[0] = pos\n else:\n q1[0] = 2.0 * pi + pos\n if neg >= 0.0:\n q1[1] = neg\n else:\n q1[1] = 2.0 * pi + neg\n\n # wrist 2 joint (q5)\n q5 = [[0, 0], [0, 0]]\n for i in range(2):\n numer = T03 * sin(q1[i]) - T13 * cos(q1[i]) - d4\n div = 0.0\n if fabs(fabs(numer) - fabs(d6)) < ZERO_THRESH:\n div = sign(numer) * sign(d6)\n else:\n div = numer / d6\n arccos = acos(div)\n q5[i][0] = arccos\n q5[i][1] = 2.0 * pi - arccos\n\n for i in range(2):\n for j in range(2):\n c1 = cos(q1[i])\n s1 = sin(q1[i])\n c5 = cos(q5[i][j])\n s5 = sin(q5[i][j])\n q6 = 0.0\n\n # wrist 3 joint (q6)\n if fabs(s5) < ZERO_THRESH:\n q6 = q6_des\n else:\n q6 = atan2(sign(s5) * -(T01 * s1 - T11 * c1), sign(s5) * (T00 * s1 - T10 * c1))\n if fabs(q6) < ZERO_THRESH:\n q6 = 0.0\n if q6 < 0.0:\n q6 += 2.0 * pi\n\n # RRR joints (q2,q3,q4)\n q2, q3, q4 = [0, 0], [0, 0], [0, 0]\n\n c6 = cos(q6)\n s6 = sin(q6)\n x04x = -s5 * (T02 * c1 + T12 * s1) - c5 * (s6 * (T01 * c1 + T11 * s1) - c6 * (T00 * c1 + T10 * s1))\n x04y = c5 * (T20 * c6 - T21 * s6) - T22 * s5\n p13x = (\n d5 * (s6 * (T00 * c1 + T10 * s1) + c6 * (T01 * c1 + T11 * s1))\n - d6 * (T02 * c1 + T12 * s1)\n + T03 * c1\n + T13 * s1\n )\n p13y = T23 - d1 - d6 * T22 + d5 * (T21 * c6 + T20 * s6)\n\n c3 = (p13x * p13x + p13y * p13y - a2 * a2 - a3 * a3) / (2.0 * a2 * a3)\n if fabs(fabs(c3) - 1.0) < ZERO_THRESH:\n c3 = sign(c3)\n elif fabs(c3) > 1.0:\n solutions.extend([None, None])\n continue\n\n arccos = acos(c3)\n q3[0] = arccos\n q3[1] = 2.0 * pi - arccos\n denom = a2 * a2 + a3 * a3 + 2 * a2 * a3 * c3\n s3 = sin(arccos)\n A = a2 + a3 * c3\n B = a3 * s3\n q2[0] = atan2((A * p13y - B * p13x) / denom, (A * p13x + B * p13y) / denom)\n q2[1] = atan2((A * p13y + B * p13x) / denom, (A * p13x - B * p13y) / denom)\n c23_0 = cos(q2[0] + q3[0])\n s23_0 = sin(q2[0] + q3[0])\n c23_1 = cos(q2[1] + q3[1])\n s23_1 = sin(q2[1] + q3[1])\n q4[0] = atan2(c23_0 * x04y - s23_0 * x04x, x04x * c23_0 + x04y * s23_0)\n q4[1] = atan2(c23_1 * x04y - s23_1 * x04x, x04x * c23_1 + x04y * s23_1)\n\n for k in range(2):\n if fabs(q2[k]) < ZERO_THRESH:\n q2[k] = 0.0\n elif q2[k] < 0.0:\n q2[k] += 2.0 * pi\n if fabs(q4[k]) < ZERO_THRESH:\n q4[k] = 0.0\n elif q4[k] < 0.0:\n q4[k] += 2.0 * pi\n\n solutions.append([q1[i], q2[k], q3[k], q4[k], q5[i][j], q6])\n\n return solutions",
"def inverseKinematic(x, y, z, arm, leg):\n #global theta1, theta2, theta3\n\n theta1 = angle_xy(x, y, z, arm, leg)\n x2 = (x * -0.5) + (y * (sqrt(3) / 2))\n y2 = (y * -0.5) - (x * (sqrt(3) / 2))\n theta2 = angle_xy(x2, y2, z, arm, leg)\n x3 = (x * -0.5) - (y * (sqrt(3) / 2))\n y3 = (y * -0.5) + (x * (sqrt(3) / 2))\n theta3 = angle_xy(x3, y3, z, arm, leg)\n return theta1, theta2, theta3",
"def _inverse_kinematics(self, position, orientation):\n inverse_kinematics = self.sim.inverse_kinematics(\n self.body_name, ee_link=11, position=position, orientation=orientation\n )\n # Replace the fingers coef by [0, 0]\n inverse_kinematics = list(inverse_kinematics[0:7]) + [0, 0]\n return inverse_kinematics",
"def iterative_invkin(robot, desired_pose, q_current, max_steps = 200, Kp = 0.3*np.eye(3), KR = 0.3*np.eye(3), tol = 1e-4): # inverse kinematics that uses Least Square solver\n\n # from scipy.optimize import lsq_linear\n\n # R_d, p_d: Desired orientation and position\n R_d = desired_pose.R\n p_d = desired_pose.p\n \n d_q = q_current\n\n num_joints = len(robot.joint_type)\n\n normalize = normalize_joints(robot, q_current, _ignore_limits = True)\n \n q_cur = d_q # initial guess on the current joint angles\n q_cur = q_cur.reshape((num_joints,1)) \n \n # hist_b = []\n \n itr = 0 # Iterations\n converged = False\n while itr < max_steps and not converged:\n \n pose = rox.fwdkin(robot,q_cur.flatten(),_ignore_limits = True)\n R_cur = pose.R\n p_cur = pose.p\n \n #calculate current Jacobian\n J0T = rox.robotjacobian(robot,q_cur.flatten(),_ignore_limits = True)\n \n # Transform Jacobian to End effector frame from the base frame\n Tr = np.zeros((6,6))\n Tr[:3,:3] = R_cur.T \n Tr[3:,3:] = R_cur.T\n J0T = np.matmul(Tr, J0T)\n \n ER = np.matmul(np.transpose(R_d),R_cur)\n \n EP = np.matmul(R_cur.T,(p_cur - p_d))\n \n #decompose ER to (k,theta) pair\n k, theta = rox.R2rot(ER) \n \n ## set up s for different norm for ER\n # s=2*np.dot(k,np.sin(theta)) #eR1\n # s = np.dot(k,np.sin(theta/2)) #eR2\n s = np.sin(theta/2) * np.array(k) #eR2\n # s=2*theta*k #eR3\n\n vd = np.matmul(Kp, EP)\n wd = np.matmul(KR, s)\n \n b = np.concatenate([wd,vd])\n # np.nan_to_num(b, copy=False, nan=0.0, posinf=None, neginf=None)\n # print(b)\n # print(J0T)\n \n # DEBUG --------------\n # hist_b.append(b)\n # if itr > 0:\n # error_cur = np.linalg.norm(hist_b[itr-1]) - np.linalg.norm(hist_b[itr])\n #print(\"Error= \" + str(error_cur))\n # DEBUG --------------\n\n # res = lsq_linear(J0T,b)\n delta = np.matmul(np.linalg.pinv(J0T),b)\n \n # Convergence Check\n converged = (np.abs(np.hstack((s,EP))) < tol).all()\n\n if not converged:\n # Update for next iteration\n q_cur = q_cur - delta.reshape((num_joints,1))\n\n itr += 1 # Increase the iteration\n\n\n q_normed = normalize(np.arange(num_joints), [np.squeeze(q_cur)])\n \n return converged, q_normed",
"def inverse(T, q_sols, q6_des=0.0):\n num_sols = 0;\n Tcounter=0\n T00 = T[Tcounter];\n Tcounter += 1;\n T01 = T[Tcounter];\n Tcounter += 1;\n T02 = T[Tcounter];\n Tcounter += 1;\n T03 = T[Tcounter];\n Tcounter += 1;\n\n T10 = T[Tcounter];\n Tcounter += 1;\n T11 = T[Tcounter];\n Tcounter += 1;\n T12 = T[Tcounter];\n Tcounter += 1;\n T13 = T[Tcounter];\n Tcounter += 1;\n\n\n T20 = T[Tcounter];\n Tcounter += 1;\n T21 = T[Tcounter];\n Tcounter += 1;\n T22 = T[Tcounter];\n Tcounter += 1;\n T23 = T[Tcounter];\n\n #Rotate joint q1\n #double q1[2];\n q1 = [None] * 2\n A = d6*T12 - T13\n B = d6*T02 - T03\n R = A*A + B*B;\n if np.abs(A) < ZERO_THRESH:\n if np.abs(np.abs(d4) - np.abs(B)) < ZERO_THRESH:\n div = -SIGN(d4)*SIGN(B);\n else:\n div = -d4/B\n arcsin = np.arcsin(div)\n if np.abs(arcsin) < ZERO_THRESH:\n arcsin = 0.0\n if arcsin < 0.0:\n q1[0] = arcsin + 2.0*IKPI\n else :\n q1[0] = arcsin\n q1[1] = IKPI - arcsin\n\n elif np.abs(B) < ZERO_THRESH :\n if np.abs(np.abs(d4) - np.abs(A)) < ZERO_THRESH:\n div = SIGN(d4)*SIGN(A);\n else:\n div = d4/A;\n arccos = np.arccos(div)\n q1[0] = arccos\n q1[1] = 2.0*IKPI - arccos\n\n #elif(d4*d4 > R) :\n # return num_sols\n else:\n arccos = np.arccos(d4 / np.sqrt(R))\n arctan = np.arctan2(-B, A);\n pos = arccos + arctan;\n neg = -arccos + arctan;\n if np.abs(pos) < ZERO_THRESH:\n pos = 0.0;\n if np.abs(neg) < ZERO_THRESH:\n neg = 0.0;\n if(pos >= 0.0):\n q1[0] = pos\n else:\n q1[0] = 2.0*IKPI + pos\n if(neg >= 0.0):\n q1[1] = neg\n else:\n q1[1] = 2.0*IKPI + neg\n ##########################################################################\n\n ####################################### wrist 2 joint (q5) ###############\n q5=[[0]*2 for i in range(2)]\n for i in range (0,2):\n numer = (T03*np.sin(q1[i]) - T13*np.cos(q1[i])-d4)\n if(np.abs(np.abs(numer) - np.abs(d6)) < ZERO_THRESH):\n div = SIGN(numer) * SIGN(d6);\n else:\n div = numer / d6;\n arccos = np.arccos(div);\n q5[i][0] = arccos;\n q5[i][1] = 2.0*IKPI - arccos;\n ###########################################################################\n for i in range (0,2):\n for j in range(0,2):\n c1 = np.cos(q1[i])\n s1 = np.sin(q1[i])\n c5 = np.cos(q5[i][j])\n s5 = np.sin(q5[i][j])\n #////////////////////////////// wrist 3 joint (q6) //////////////////////////////\n if(np.abs(s5) < ZERO_THRESH):\n q6 = q6_des\n else:\n q6 = np.arctan2(SIGN(s5)*-(T01*s1 - T11*c1),\\\n SIGN(s5)*(T00*s1 - T10*c1))\n if(np.abs(q6) < ZERO_THRESH):\n q6 = 0.0;\n if(q6 < 0.0):\n q6 += 2.0*IKPI\n #print(\"q6 is %1.6f\\n\"%q6)\n #////////////////////////////////////////////////////////////////////////////////\n\n q2=[None]*2\n q3=[None]*2\n q4=[None]*2\n #///////////////////////////// RRR joints (q2,q3,q4) ////////////////////////////\n c6 = np.cos(q6)\n s6 = np.sin(q6)\n x04x = -s5*(T02*c1 + T12*s1) - c5*(s6*(T01*c1 + T11*s1) - c6*(T00*c1 + T10*s1))\n x04y = c5*(T20*c6 - T21*s6) - T22*s5\n p13x = d5*(s6*(T00*c1 + T10*s1) + c6*(T01*c1 + T11*s1)) - d6*(T02*c1 + T12*s1) +\\\n T03*c1 + T13*s1\n p13y = T23 - d1 - d6*T22 + d5*(T21*c6 + T20*s6)\n\n c3 = (p13x*p13x + p13y*p13y - a2*a2 - a3*a3) / (2.0*a2*a3)\n if(np.abs(np.abs(c3) - 1.0) < ZERO_THRESH):\n c3 = SIGN(c3)\n elif(np.abs(c3) > 1.0):\n #// TODO NO SOLUTION\n continue\n\n arccos = np.arccos(c3)\n q3[0] = arccos\n q3[1] = 2.0*IKPI - arccos\n denom = a2*a2 + a3*a3 + 2*a2*a3*c3\n s3 = np.sin(arccos)\n A = (a2 + a3*c3)\n B = a3*s3\n q2[0] = np.arctan2((A*p13y - B*p13x) / denom, (A*p13x + B*p13y) / denom)\n q2[1] = np.arctan2((A*p13y + B*p13x) / denom, (A*p13x - B*p13y) / denom)\n c23_0 = np.cos(q2[0]+q3[0]);\n s23_0 = np.sin(q2[0]+q3[0]);\n c23_1 = np.cos(q2[1]+q3[1]);\n s23_1 = np.sin(q2[1]+q3[1]);\n q4[0] = np.arctan2(c23_0*x04y - s23_0*x04x, x04x*c23_0 + x04y*s23_0);\n q4[1] = np.arctan2(c23_1*x04y - s23_1*x04x, x04x*c23_1 + x04y*s23_1);\n\n #////////////////////////////////////////////////////////////////////////////////\n for k in range (0,2):\n if(np.abs(q2[k]) < ZERO_THRESH):\n q2[k] = 0.0\n elif(q2[k] < 0.0):\n q2[k] += 2.0*IKPI\n if(np.abs(q4[k]) < ZERO_THRESH):\n q4[k] = 0.0\n elif(q4[k] < 0.0):\n q4[k] += 2.0*IKPI\n q_sols[num_sols*6+0] = q1[i]\n q_sols[num_sols*6+1] = q2[k]\n q_sols[num_sols*6+2] = q3[k]\n q_sols[num_sols*6+3] = q4[k]\n q_sols[num_sols*6+4] = q5[i][j]\n q_sols[num_sols*6+5] = q6\n num_sols+=1\n return num_sols",
"def get_ik(self, target_pose, avoid_collisions=False):\n service_request = PositionIKRequest()\n service_request.group_name = self._name\n service_request.ik_link_name = self._move_group_commander.get_end_effector_link()\n service_request.pose_stamped = target_pose\n service_request.timeout.secs = 0.005\n service_request.avoid_collisions = avoid_collisions\n\n try:\n resp = self._compute_ik(ik_request=service_request)\n # Check if error_code.val is SUCCESS=1\n if resp.error_code.val != 1:\n if resp.error_code.val == -10:\n rospy.logerr(\"Unreachable point: Start state in collision\")\n elif resp.error_code.val == -12:\n rospy.logerr(\"Unreachable point: Goal state in collision\")\n elif resp.error_code.val == -31:\n rospy.logerr(\"Unreachable point: No IK solution\")\n else:\n rospy.logerr(\"Unreachable point (error: %s)\" % resp.error_code)\n return\n else:\n return resp.solution.joint_state\n\n except rospy.ServiceException, e:\n rospy.logerr(\"Service call failed: %s\" % e)",
"def test_ikfast_6d_case_1(self):\n i = 0\n for (qseed, pose) in zip(self.qseeds, self.poses):\n i += 1\n T = orpy.matrixFromPose(pose)\n with self.robot:\n self.robot.SetActiveDOFValues(qseed)\n ts = time.time()\n sol = self.manip.FindIKSolution(T, ikfilter_checkcollision)\n te = time.time()\n\n if sol is not None:\n self.total_time += te - ts\n self.no_success += 1\n \n with self.robot:\n self.robot.SetActiveDOFValues(sol)\n pose_actual = self.manip.GetTransformPose()\n if pose_actual[0] < 0:\n pose_actual[:4] *= -1.\n \n np.testing.assert_allclose(pose_actual, pose, rtol=1e-5, atol=1e-5)\n self.assertTrue((sol <= self.q_max).all(), msg=\"Violate joint limits\")\n self.assertTrue((self.q_min <= sol).all(), msg=\"Violate joint limits\")",
"def inverse_compound(self, pose1, pose2, robot_idx):\n pose1_inversed = self.inverse_op(pose1)\n pose1, pose1_orig = pose1_inversed, pose1\n if robot_idx == 'a':\n single_graph = self.gtsam_graph1\n elif robot_idx == 'b':\n single_graph = self.gtsam_graph2\n theta1_o = pose1_orig.theta\n x1, y1, theta1 = pose1.x, pose1.y, pose1.theta\n x2, y2, theta2 = pose2.x, pose2.y, pose2.theta\n new_x = x2*np.cos(theta1) - y2*np.sin(theta1) + x1\n new_y = x2*np.sin(theta1) + y2*np.cos(theta1) + y1\n new_theta = theta1 + theta2\n assert pose1.j == pose2.i == 'w'\n cov1 = self.get_covariance(pose1) # The inversed pose1's covariance\n cov2 = self.get_covariance(pose2)\n inversed_cross_cov = single_graph.cross_cov(pose1.i, pose2.j)\n J_minus = np.matrix([[-np.cos(theta1_o), -np.sin(theta1_o), y1], \\\n [np.sin(theta1_o), -np.cos(theta1_o), -x1], \\\n [0, 0, -1]])\n cross_cov = np.matmul(J_minus, inversed_cross_cov)\n # prev_cov is a 6x6 matrix\n prev_cov = np.zeros((6, 6))\n prev_cov[0:3, 0:3] = cov1\n prev_cov[0:3, 3:6] = cross_cov\n prev_cov[3:6, 0:3] = cross_cov.T\n prev_cov[3:6, 3:6] = cov2\n J_plus = np.matrix([[1, 0, -(new_y-y1), np.cos(theta1), -np.sin(theta1), 0], \\\n [0, 1, (new_x-x1), np.sin(theta1), np.cos(theta1), 0], \\\n [0, 0, 1, 0, 0, 1]])\n new_cov = np.matmul(np.matmul(J_plus, prev_cov), J_plus.T)\n new_info = self.to_info(new_cov)\n return Edge2D(pose1.i, pose2.j, new_x, new_y, new_theta, new_info)",
"def robot6_sphericalwrist_invkin(robot, desired_pose, last_joints = None):\n \n \n desired_pose2 = rox.unapply_robot_aux_transforms(robot, desired_pose)\n\n R06 = desired_pose2.R\n p0T = desired_pose2.p\n \n H = robot.H\n P = robot.P\n \n theta_v = []\n \n #Correct for spherical joint position vectors\n if not np.all(P[:,4] == 0):\n P4_d = P[:,4].dot(H[:,3])\n assert np.all(P[:,4] - P4_d*H[:,3] == 0)\n P[:,3] += P[:,4]\n P[:,4] = np.zeros(3)\n \n if not np.all(P[:,5] == 0):\n P5_d = P[:,5].dot(H[:,5])\n assert np.all(P[:,5] - P5_d*H[:,5] == 0)\n P[:,6] += P[:,5]\n P[:,5] = np.zeros(3) \n \n d1 = np.dot(ey, P[:,1] + P[:,2] + P[:,3])\n v1 = p0T - R06.dot(P[:,6]) \n p1 = ey\n \n Q1 = rox.subproblem4(p1, v1, -H[:,0], d1)\n \n normalize = normalize_joints(robot, last_joints)\n \n for q1 in normalize(0, Q1):\n \n R01=rox.rot(H[:,0], q1)\n \n p26_q1 = R01.T.dot(p0T - R06.dot(P[:,6])) - (P[:,0] + P[:,1])\n \n d3 = np.linalg.norm(p26_q1)\n v3 = P[:,2] \n p3 = P[:,3]\n Q3 = rox.subproblem3(p3, v3, H[:,2], d3)\n \n for q3 in normalize(2,Q3):\n \n R23=rox.rot(H[:,2],q3)\n \n v2 = p26_q1 \n p2 = P[:,2] + R23.dot(P[:,3])\n q2 = rox.subproblem1(p2, v2, H[:,1])\n \n q2 = normalize(1, [q2])\n if len(q2) == 0:\n continue\n q2 = q2[0] \n \n R12 = rox.rot(H[:,1], q2)\n \n R03 = R01.dot(R12).dot(R23)\n \n R36 = R03.T.dot(R06)\n \n v4 = R36.dot(H[:,5]) \n p4 = H[:,5]\n \n Q4_Q5 = rox.subproblem2(p4, v4, H[:,3], H[:,4])\n \n for q4, q5 in normalize((3,4), Q4_Q5):\n \n R35 = rox.rot(H[:,3], q4).dot(rox.rot(H[:,4], q5))\n R05 = R03.dot(R35)\n R56 = R05.T.dot(R06)\n \n p6 = H[:,4]\n v6 = R56.dot(H[:,4])\n \n q6 = rox.subproblem1(p6, v6, H[:,5])\n \n q6 = normalize(5, [q6])\n if len(q6) == 0:\n continue\n q6 = q6[0]\n \n theta_v.append(np.array([q1, q2, q3, q4, q5, q6])) \n if last_joints is not None:\n theta_dist = np.linalg.norm(np.subtract(theta_v,last_joints), axis=1)\n return [theta_v[i] for i in list(np.argsort(theta_dist))]\n else:\n return theta_v",
"def inverse(self):\n if not self.is_square():\n raise(ValueError, \"Non-square Matrix does not have an inverse.\")\n if self.h > 2:\n raise(NotImplementedError, \"inversion not implemented for matrices larger than 2x2.\") \n \n matrix = self.g\n inverse = []\n\n if (len(matrix) == 1):\n inverse.append([1/matrix[0][0]])\n else: \n #The following code was suggested from this project's code review:\n #find identity matrix\n I = identity(2)\n #find trace\n tr = self.trace()\n #find the determinant with the previously computed function.\n det = self.determinant()\n #perform inverse\n return 1.0 / det * (tr * I - self)",
"def getIK(self, goalPose, link_name , seedAngles):\n ikreq = kinematics_msgs.msg.PositionIKRequest()\n ikreq.ik_link_name =link_name\n ikreq.pose_stamped = goalPose\n ikreq.ik_seed_state.joint_state.name = self.joint_names\n ikreq.ik_seed_state.joint_state.position = seedAngles\n ikres = self._runIK(ikreq, rospy.Duration(5))\n \n\n #req=kinematics_msgs.srv.GetConstraintAwarePositionIK._request_class()\n #print dir(req)\n \n #ikreq = kinematics_msgs.msg.PositionIKRequest()\n #req.ik_request.ik_link_name =link_name\n #req.ik_request.pose_stamped = goalPose\n #req.ik_request.ik_seed_state.joint_state.name = self.joint_names\n #req.ik_request.ik_seed_state.joint_state.position = seedAngles\n #req.timeout=rospy.Duration(5)\n #ikres = self._runIK(req)#, rospy.Duration(5))\n\tprint \"Error Code: %s\" % ikres.error_code.val\n if (ikres.error_code.val != ikres.error_code.SUCCESS): #figure out which error code\n raise rospy.exceptions.ROSException(\"Could not find IK with \" + self.ikPath + \"\\n\\n\" + ikres.__str__())\n\n return ikres",
"def inverse(self):\r\n\r\n if self.z is None:\r\n self._logger.warn('z array is \"None\" - I cannot invert that')\r\n return\r\n\r\n inverse = copy.copy(self.z)\r\n for idx_f in range(len(inverse)):\r\n try:\r\n inverse[idx_f, :, :] = np.array((np.matrix(self.z[idx_f, :, :])).I)\r\n except:\r\n raise ZError('The {0}ith impedance'.format(idx_f + 1) + \\\r\n 'tensor cannot be inverted')\r\n\r\n return inverse",
"def ks_inv(kappa_map, fourier_forward_matrix=None):\n if fourier_forward_matrix is None:\n fourier_forward_matrix = ks_fourier_matrix(kappa_map.shape[0])\n\n fourier_kappa_vector = np.fft.fft2(kappa_map).flatten()\n\n return np.fft.ifft2(np.reshape(fourier_kappa_vector*fourier_forward_matrix,kappa_map.shape))",
"def estimate_intrinsics(frame):\n return _to_camera_intrinsics(\n _zivid.calibration.estimate_intrinsics(\n frame._Frame__impl # pylint: disable=protected-access\n )\n )",
"def inverse(A):\n\n # note that the routine solve works even if b is a matrix!\n B = pylab.eye(len(A)) # the identity matrix\n return solve(A, B)",
"def build_inverse(self, qc, q, q_ancillas=None, params=None):\n qc_ = QuantumCircuit(*qc.qregs)\n\n self.build(qc_, q, q_ancillas, params)\n try:\n qc_.data = [gate.inverse() for gate in reversed(qc_.data)]\n except Exception as exc:\n raise AquaError('Irreversible circuit! Gate does not support inverse method.') from exc\n qc.extend(qc_)",
"def inverse_kinematic(target_point, orientation = 0.0):\n pos_x = float(target_point.x)\n pos_y = float(target_point.y)\n pos_z = float(target_point.z)\n try:\n r = math.sqrt(FL * FL - pos_y * pos_y)\n R = math.hypot(pos_x, pos_z)\n print 'r = ' + str(r)\n print 'R = ' + str(R)\n\n try:\n cos_theta2 = (R * R - UL * UL - r * r) / (2 * UL * r + VERY_SMALL_NUMBER)\n sin_theta2 = math.sqrt(1 - math.pow(cos_theta2, 2))\n theta2 = math.atan2(sin_theta2, cos_theta2)\n print \"THEHA2 = \" + str(theta2)\n except ValueError:\n print 'FALSE theta2'\n return False\n\n try:\n theta1 = math.atan2(pos_x, math.fabs(pos_z)) - math.atan2(r*math.sin(theta2), UL + r*math.cos(theta2))\n as20 = theta1\n as20 *= -1\n print 'as20 = ' + str(as20)\n as25 = as20\n print 'as25 = ' + str(as25)\n except ValueError:\n print 'FALSE as20 as25'\n return False\n\n try:\n as21 = math.atan2(pos_y, (r + VERY_SMALL_NUMBER))\n print 'as21 = ' + str(as21)\n as26 = -1 * as21\n print 'as26 = ' + str(as26)\n except ValueError:\n print 'FALSE as21 as26'\n return False\n\n try:\n ae22 = theta2 - 0.5*math.pi\n print 'ae22 = ' + str(ae22)\n ae27 = ae22\n print 'ae27 = ' + str(ae27)\n except ValueError:\n print 'FALSE ae22'\n return False\n\n try:\n theta_d = 0.5*math.pi - orientation\n theta3 = theta_d - theta1 - theta2\n print 'theta3 = ' + str(theta3)\n ah41 = -theta3\n print \"ah41 = \" + str(ah41)\n ah46 = ah41\n print 'ah46 = ' + str(ah46)\n except ValueError:\n print 'FALSE ah41'\n\n right_rotate_wrist = as21\n print 'Right rotate = ' + str(right_rotate_wrist)\n ah40 = right_rotate_wrist / 2.0\n print 'ah40 = ' + str(ah40)\n ah42 = ah40\n print 'ah42 = ' + str(ah42)\n\n left_rotate_wrist = as26\n print 'Left rotate = ' + str(left_rotate_wrist)\n ah45 = left_rotate_wrist / 2.0\n print 'ah45 = ' + str(ah45)\n ah47 = ah45\n print 'ah47 = ' + str(ah47)\n\n out_angles = dict()\n out_angles['right_shoulder_1_joint'] = as20\n out_angles['right_shoulder_2_joint'] = as21\n out_angles['right_elbow_joint'] = ae22\n out_angles['right_wrist_1_joint'] = ah40\n out_angles['right_wrist_2_joint'] = ah41\n out_angles['right_wrist_3_joint'] = ah42\n\n out_angles['left_shoulder_1_joint'] = as25\n out_angles['left_shoulder_2_joint'] = as26\n out_angles['left_elbow_joint'] = ae27\n # out_angles['left_wrist_1_joint'] = ah40\n # out_angles['left_wrist_2_joint'] = ah41\n # out_angles['left_wrist_3_joint'] = ah42\n out_angles['left_wrist_1_joint'] = ah45\n out_angles['left_wrist_2_joint'] = ah46\n out_angles['left_wrist_3_joint'] = ah47\n\n return out_angles\n except ValueError:\n print \"CAN'T CALCULATE R or r\"\n return False",
"def knot(self, ij, xy):\n return self.cw(xy[0])*self.cw(xy[1])*self.tau(ij, xy)",
"def ikFkMatch(namespace,\n ikfk_attr,\n ui_host,\n fks,\n ik,\n upv,\n ik_rot=None,\n key=None):\n\n # returns a pymel node on the given name\n def _get_node(name):\n # type: (str) -> pm.nodetypes.Transform\n name = anim_utils.stripNamespace(name)\n if namespace:\n node = anim_utils.getNode(\":\".join([namespace, name]))\n else:\n node = anim_utils.getNode(name)\n\n if not node:\n mgear.log(\"Can't find object : {0}\".format(name), mgear.sev_error)\n\n return node\n\n # returns matching node\n def _get_mth(name):\n # type: (str) -> pm.nodetypes.Transform\n tmp = name.split(\"_\")\n tmp[-1] = \"mth\"\n query = \"_\".join(tmp)\n n = _get_node(query)\n\n if not n:\n mgear.log(\"Can't find mth object : {0} for {1}\".format(query, name), mgear.sev_comment)\n return _get_node(name)\n else:\n return n\n\n # get things ready\n fk_ctrls = [_get_node(x) for x in fks]\n fk_goals = [_get_mth(x) for x in fks]\n ik_ctrl = _get_node(ik)\n ik_goal = _get_mth(ik)\n upv_ctrl = _get_node(upv)\n\n if ik_rot:\n ik_rot_node = _get_node(ik_rot)\n ik_rot_goal = _get_mth(ik_rot)\n\n ui_node = _get_node(ui_host)\n o_attr = ui_node.attr(ikfk_attr)\n\n switch_to_fk = (o_attr.get() == 1.0)\n switch_to_ik = (not switch_to_fk)\n is_leg = (\"leg\" in ikfk_attr)\n\n # sets keyframes before snapping\n if key:\n _all_controls = []\n _all_controls.extend(fk_ctrls)\n _all_controls.extend([ik_ctrl, upv_ctrl, ui_node])\n if ik_rot:\n _all_controls.extend([ik_rot_node])\n [cmds.setKeyframe(\"{}\".format(elem),\n time=(cmds.currentTime(query=True) - 1.0))\n for elem in _all_controls]\n\n # if is IKw then snap FK\n if switch_to_fk:\n\n world_matrices = []\n for src, _ in zip(fk_goals, fk_ctrls):\n world_matrices.append(src.getMatrix(worldSpace=True))\n\n o_attr.set(0.0)\n\n for mat, dst in zip(world_matrices, fk_ctrls):\n dst.setMatrix(mat, worldSpace=True)\n\n for mat, dst in zip(world_matrices, fk_ctrls):\n dst.setMatrix(mat, worldSpace=True)\n\n # if is FKw then sanp IK\n elif switch_to_ik:\n\n shoulder_mat = fk_goals[0].getMatrix(worldSpace=True)\n ik_mat = ik_goal.getMatrix(worldSpace=True)\n\n # transform.matchWorldTransform(ik_goal, ik_ctrl)\n if ik_rot:\n rot_mat = ik_rot_goal.getMatrix(worldSpace=True)\n # transform.matchWorldTransform(ik_rot_goal, ik_rot_node)\n\n if is_leg:\n upv_mat = fk_goals[1].getMatrix(worldSpace=True)\n else:\n upv_mat = fk_goals[2].getMatrix(worldSpace=True)\n\n o_attr.set(1.0)\n\n ik_ctrl.setMatrix(ik_mat, worldSpace=True)\n if ik_rot:\n ik_rot_node.setMatrix(rot_mat, worldSpace=True)\n upv_ctrl.setMatrix(upv_mat, worldSpace=True)\n # for _ in range(10):\n # fk_ctrls[0].setMatrix(shoulder_mat, worldSpace=True)\n\n _m = []\n for row in shoulder_mat:\n for elem in row:\n _m.append(elem)\n for _ in range(20):\n cmds.xform(fk_ctrls[0].name(), ws=True, matrix=_m)\n\n # transform.matchWorldTransform(fk_goals[1], upv_ctrl)\n # calculates new pole vector position\n if is_leg:\n start_end = (fk_goals[-1].getTranslation(space=\"world\") - fk_goals[0].getTranslation(space=\"world\"))\n start_mid = (fk_goals[1].getTranslation(space=\"world\") - fk_goals[0].getTranslation(space=\"world\"))\n else:\n start_end = (fk_goals[-1].getTranslation(space=\"world\") - fk_goals[1].getTranslation(space=\"world\"))\n start_mid = (fk_goals[2].getTranslation(space=\"world\") - fk_goals[1].getTranslation(space=\"world\"))\n\n dot_p = start_mid * start_end\n proj = float(dot_p) / float(start_end.length())\n proj_vector = start_end.normal() * proj\n arrow_vector = (start_mid - proj_vector) * 1.5\n arrow_vector *= start_end.normal().length()\n if is_leg:\n final_vector = (arrow_vector + fk_goals[1].getTranslation(space=\"world\"))\n else:\n final_vector = (arrow_vector + fk_goals[2].getTranslation(space=\"world\"))\n upv_ctrl.setTranslation(final_vector, space=\"world\")\n\n # sets blend attribute new value\n # o_attr.set(1.0)\n roll_att = ui_node.attr(ikfk_attr.replace(\"blend\", \"roll\"))\n roll_att.set(0.0)\n\n ik_ctrl.setMatrix(ik_mat, worldSpace=True)\n if ik_rot:\n ik_rot_node.setMatrix(rot_mat, worldSpace=True)\n # upv_ctrl.setMatrix(upv_mat, worldSpace=True)\n for _ in range(20):\n cmds.xform(fk_ctrls[0].name(), ws=True, matrix=_m)\n\n # sets keyframes\n if key:\n [cmds.setKeyframe(\"{}\".format(elem),\n time=(cmds.currentTime(query=True)))\n for elem in _all_controls]\n\n if is_leg:\n prefix = \"_\".join(ik.split(\"_\")[0:2]).replace(\"leg\", \"foot\")\n leg_tip_con = [\"heel_ctl\", \"bk0_ctl\", \"tip_ctl\", \"roll_ctl\"]\n\n for tip in leg_tip_con:\n node = _get_node(\"{}_{}\".format(prefix, tip))\n if not node:\n continue\n attribute.reset_SRT([node, ])"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Call kubernetes api container to retrieve the deployment id
|
def get_deployment_id():
try:
config.load_incluster_config()
nodes = client.CoreV1Api().list_node(watch=False)
if len(nodes.items) > 0:
return nodes.items[0].metadata.labels.get("hyperpilot/deployment", "")
except config.ConfigException:
print("Failed to load configuration. This container cannot run outside k8s.")
sys.exit(errno.EPERM)
|
[
"def test_get_deployment_by_id(self):\n response = self.client.open(\n '/RadonCTT/deployment/{deploymentId}'.format(deployment_id=789),\n method='GET')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))",
"def get_id(dic):\n\n service = get_service(dic)\n id = service.id\n\n return id",
"def container_id(self) -> uuid.UUID | None:\n return self._container_id",
"def show(self, uuid, **kwargs):\n resp, result = self.client.get(\"./deployments/%s\" % uuid, **kwargs)\n return base.Deployment(result)",
"def GetId(apig,api_name: str):\n\t\t\trest_api_list = AWS.APIGateway.List(apig)\n\n\t\t\tapi_id = ''\n\t\t\tfor api in rest_api_list:\n\t\t\t\tif api['name'] == api_name:\n\t\t\t\t\tapi_id = api['id']\n\t\t\treturn api_id",
"def getImageId(self):\n client = getDockerClient()\n named_image = self.config.getFullImage()\n self.logger.debug('Finding image ID for component %s with named image %s', self.getName(), named_image)\n result = client.inspect_image(named_image)\n return result['id']",
"def _name_to_id(self, container_name: str) -> str:\n container_id = self._ids_by_name(container_name)\n if not container_id:\n container_id = self._ids_by_name(container_name, stopped=True)\n\n if not container_id:\n message = f\"could not find container matching name '{container_name}'.\"\n containers = self._list_containers()\n if containers.count(\"\\n\") > 0:\n message += f\"\\nchoose one of the following:\\n{containers}\"\n warn(message, self.debug)\n\n if \"\\n\" in container_id:\n warn(\n f\"multiple containers found matching name '{container_name}'. Run `docker ps -af name={container_name}` for details.\",\n self.debug,\n )\n\n return container_id",
"def id_and_containers(pod):\n\n pod_id = pod['id']\n container_names = sorted(container['name'] for container\n in pod['spec']['containers'])\n\n container_lines = ('\\n |-{}'.format(name) for name in container_names)\n return pod_id + ''.join(container_lines)",
"async def read_deployment(\n deployment_id: UUID = Path(..., description=\"The deployment id\", alias=\"id\"),\n db: PrefectDBInterface = Depends(provide_database_interface),\n) -> schemas.responses.DeploymentResponse:\n async with db.session_context() as session:\n deployment = await models.deployments.read_deployment(\n session=session, deployment_id=deployment_id\n )\n if not deployment:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"Deployment not found\"\n )\n return schemas.responses.DeploymentResponse.from_orm(deployment)",
"def image_id(self, imgref):\n p = subprocess.run(\n ['docker', 'inspect', imgref, '--format', '{{ .Id }}'],\n capture_output=True,\n encoding='utf8',\n env=self.env)\n if p.returncode != 0:\n return None\n else:\n return p.stdout.strip()",
"def _get_container(self):\n client = self.client.containers\n try:\n container = client.get(self.name)\n return container\n except:\n return None",
"def api_key_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"api_key_id\")",
"def _get_apigateway_rootId(restApiId, _apiGateway):\n\n response = _apiGateway.get_resources(\n restApiId = restApiId,\n embed = ['/']\n )\n return response['items'][0]['id']",
"def get_container_status(pod, name):\n for cs in pod[\"status\"].get(\"containerStatuses\", ()):\n if cs[\"name\"] == name:\n return cs\n return None",
"def container_name(self) -> Optional[str]:\n return pulumi.get(self, \"container_name\")",
"def deployed_index_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"deployed_index_id\")",
"def get_container(self, con_id):\n result = self.connection.request(\"{}/containers/{}\".format(self.baseuri, con_id)).object\n\n return self._to_container(result)",
"def docker_id(self):\n return self._docker_id",
"def get_label_id(key: str, value: str, gc_api: RESTManagementAPI) -> str:\r\n try:\r\n return gc_api.get_label_id(key, value)\r\n except CentraObjectNotFound:\r\n raise LabelNotFoundInCentra(\r\n f\"The label {key}: {value} was not found in Centra\")"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Call kubernetes api container to retrieve the deployment id
|
def deployment_id(self):
try:
config.load_incluster_config()
nodes = client.CoreV1Api().list_node(watch=False)
if len(nodes.items) > 0:
return nodes.items[0].metadata.labels.get("hyperpilot/deployment", "")
except config.ConfigException:
print("Failed to load configuration. This container cannot run outside k8s.")
sys.exit(errno.EPERM)
|
[
"def get_deployment_id():\n try:\n config.load_incluster_config()\n nodes = client.CoreV1Api().list_node(watch=False)\n if len(nodes.items) > 0:\n return nodes.items[0].metadata.labels.get(\"hyperpilot/deployment\", \"\")\n except config.ConfigException:\n print(\"Failed to load configuration. This container cannot run outside k8s.\")\n sys.exit(errno.EPERM)",
"def test_get_deployment_by_id(self):\n response = self.client.open(\n '/RadonCTT/deployment/{deploymentId}'.format(deployment_id=789),\n method='GET')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))",
"def get_id(dic):\n\n service = get_service(dic)\n id = service.id\n\n return id",
"def container_id(self) -> uuid.UUID | None:\n return self._container_id",
"def show(self, uuid, **kwargs):\n resp, result = self.client.get(\"./deployments/%s\" % uuid, **kwargs)\n return base.Deployment(result)",
"def GetId(apig,api_name: str):\n\t\t\trest_api_list = AWS.APIGateway.List(apig)\n\n\t\t\tapi_id = ''\n\t\t\tfor api in rest_api_list:\n\t\t\t\tif api['name'] == api_name:\n\t\t\t\t\tapi_id = api['id']\n\t\t\treturn api_id",
"def getImageId(self):\n client = getDockerClient()\n named_image = self.config.getFullImage()\n self.logger.debug('Finding image ID for component %s with named image %s', self.getName(), named_image)\n result = client.inspect_image(named_image)\n return result['id']",
"def _name_to_id(self, container_name: str) -> str:\n container_id = self._ids_by_name(container_name)\n if not container_id:\n container_id = self._ids_by_name(container_name, stopped=True)\n\n if not container_id:\n message = f\"could not find container matching name '{container_name}'.\"\n containers = self._list_containers()\n if containers.count(\"\\n\") > 0:\n message += f\"\\nchoose one of the following:\\n{containers}\"\n warn(message, self.debug)\n\n if \"\\n\" in container_id:\n warn(\n f\"multiple containers found matching name '{container_name}'. Run `docker ps -af name={container_name}` for details.\",\n self.debug,\n )\n\n return container_id",
"def id_and_containers(pod):\n\n pod_id = pod['id']\n container_names = sorted(container['name'] for container\n in pod['spec']['containers'])\n\n container_lines = ('\\n |-{}'.format(name) for name in container_names)\n return pod_id + ''.join(container_lines)",
"async def read_deployment(\n deployment_id: UUID = Path(..., description=\"The deployment id\", alias=\"id\"),\n db: PrefectDBInterface = Depends(provide_database_interface),\n) -> schemas.responses.DeploymentResponse:\n async with db.session_context() as session:\n deployment = await models.deployments.read_deployment(\n session=session, deployment_id=deployment_id\n )\n if not deployment:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"Deployment not found\"\n )\n return schemas.responses.DeploymentResponse.from_orm(deployment)",
"def image_id(self, imgref):\n p = subprocess.run(\n ['docker', 'inspect', imgref, '--format', '{{ .Id }}'],\n capture_output=True,\n encoding='utf8',\n env=self.env)\n if p.returncode != 0:\n return None\n else:\n return p.stdout.strip()",
"def _get_container(self):\n client = self.client.containers\n try:\n container = client.get(self.name)\n return container\n except:\n return None",
"def api_key_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"api_key_id\")",
"def _get_apigateway_rootId(restApiId, _apiGateway):\n\n response = _apiGateway.get_resources(\n restApiId = restApiId,\n embed = ['/']\n )\n return response['items'][0]['id']",
"def get_container_status(pod, name):\n for cs in pod[\"status\"].get(\"containerStatuses\", ()):\n if cs[\"name\"] == name:\n return cs\n return None",
"def container_name(self) -> Optional[str]:\n return pulumi.get(self, \"container_name\")",
"def deployed_index_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"deployed_index_id\")",
"def get_container(self, con_id):\n result = self.connection.request(\"{}/containers/{}\".format(self.baseuri, con_id)).object\n\n return self._to_container(result)",
"def docker_id(self):\n return self._docker_id",
"def get_label_id(key: str, value: str, gc_api: RESTManagementAPI) -> str:\r\n try:\r\n return gc_api.get_label_id(key, value)\r\n except CentraObjectNotFound:\r\n raise LabelNotFoundInCentra(\r\n f\"The label {key}: {value} was not found in Centra\")"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Create a deck of 108 Uno cards. Return a list of UnoCard namedtuples (for cards w/o suit use None in the namedtuple)
|
def create_uno_deck():
cards = [UnoCard(suit, face) for suit, face in product(SUITS, [0])]
two_of = chain(range(1, 10), 'Draw Two,Skip,Reverse'.split(','))
cards.extend(UnoCard(suit, face) for suit, face in product(SUITS, two_of) for _ in range(2))
four_of = 'Wild,Wild Draw Four'.split(',')
cards.extend(UnoCard(None, face) for _ in range(4) for face in four_of)
return cards
|
[
"def create_deck():\n card_deck = []\n for x in range(6):\n for suit in ('H', 'S', 'C', 'D'):\n for rank in range(2, 11):\n card_deck.append((str(rank) + str(suit)))\n for face_cards in ('A', 'J', 'Q', 'K'):\n card_deck.append((str(face_cards) + str(suit)))\n\n random.shuffle(card_deck)\n return card_deck",
"def get_cards():\n Card = namedtuple('Card', 'rank suit')\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n suits = ['spades', 'hearts', 'diamonds', 'clubs']\n full_deck = [Card(suit, rank) for suit in suits for rank in ranks]\n return full_deck",
"def build_deck():\n\tsuits = {\n\t\t'hearts': [],\n\t\t'diamonds': [],\n\t\t'clubs': [],\n\t\t'spades': []\n\t\t}\n\n\tface_cards = ['jack','queen', 'king', 'ace']\n\n\tfor suit in suits.keys():\n\t\tfor number in range(1,11):\n\t\t\tsuits[suit].append(f'{number} of {suit.title()}')\n\t\tfor face_card in face_cards:\n\t\t\tsuits[suit].append(f'{face_card.title()} of {suit.title()}')\n\n\n\treturn suits",
"def create_Deck(self):\n print('Creating Deck')\n for a in [\"Heart\", \"Diamond\", \"Club\", \"Spade\"]:\n for x in range(2, 11):\n self.cards.append(Card(a, x, x))\n self.cards.append(Card(a, \"A\", 11))\n self.cards.append(Card(a, \"J\", 10))\n self.cards.append(Card(a, \"K\", 10))\n self.cards.append(Card(a, \"Q\", 10))",
"def generatePlayerDeck(self):\n cards = []\n\n for k in EVENT_CARDS: #id, name, description\n cards.append(EventCard(k, EVENT_CARDS[k][\"name\"], EVENT_CARDS[k][\"description\"]))\n\n for k in PLAYER_CARDS: #name,colour,population,area,country\n cards.append(PlayerCard(k, PLAYER_CARDS[k][\"colour\"], PLAYER_CARDS[k][\"population\"], PLAYER_CARDS[k][\"area\"], PLAYER_CARDS[k][\"country\"]))\n\n\n return cards",
"def newDeck(self):\n temp_deck = []\n for card in self.cards:\n for suit in self.suits:\n temp_deck.append(\"{} {}\".format(card, suit))\n return temp_deck",
"def build_deck(self):\n suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs']\n ranks = {\n '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'J':10, 'Q':10, 'K':10, 'A':11,\n }\n for suit in suits:\n for rank, value in ranks.items():\n card = Card(rank, value, suit)\n self.cards.append(card)",
"def initiate_deck(self):\n for suit in self.suits:\n for i in range(1, 14):\n new_card = Card(i, suit)\n self.cards.append(new_card)",
"def build(self):\n cards = []\n # for each suit\n for s in self.SUITS:\n # for each rank\n for r in self.RANKS:\n # create a new card\n card = Card(s, r)\n # set's the image src\n card.set_image_src(CARD_IMAGE_SRC)\n # set the back image src\n card.set_back_image_src(CARD_BACK_IMAGE_SRC)\n # set's the card size\n card.set_size(CARD_IMAGE_SIZE)\n # add the new card into the list\n cards.append(card)\n return cards",
"def generate_deck() -> Deck:\n\n card_suites: List[str] = [\"spade\",\"heart\",\"clubs\",\"diamond\"]\n card_positions: List[str] = [\"ace\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"jack\",\"queen\",\"king\"]\n deck: Deck = deque(maxlen=52)\n\n for suite in card_suites:\n for position in card_positions:\n deck.append((suite, position))\n\n return deck",
"def deck():\n\n suits = ['clubs', 'diamonds', 'hearts', 'spades']\n cards = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K']\n\n return suits, cards",
"def build_deck():\n\n deck = []\n suits = ['clubs', 'diamonds', 'hearts', 'spades']\n ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']\n\n for times in range(6):\n for s in suits:\n for r in ranks:\n deck.append(Card(s, r))\n\n # plastic_card = \" \"\n shuffle(deck)\n # deck.insert(-randint(60, 75), plastic_card) # minus to count from the last card\n\n return deck",
"def create_deck():\n suits = [0, 1, 2, 3]\n ranks = ['two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king', 'ace']\n cards = [Card(suit=suit, rank=rank) for rank in ranks for suit in suits]\n Card.objects.bulk_create(cards)",
"def new_deck(n_sets=4):\n card_set = [Card(rank, suit) for _ in range(n_sets) for rank in Rank for suit in Suit]\n return Deck(card_set)",
"def create_cards():\n return {\n \"A\": (0, 11),\n \"2\": 2,\n \"3\": 3,\n \"4\": 4,\n \"5\": 5,\n \"6\": 6,\n \"7\": 7,\n \"8\": 8,\n \"9\": 9,\n \"10\": 10,\n \"J\": 10,\n \"Q\": 10,\n \"K\": 10\n }",
"def _create_new_deck(self,player):\n\t\tdeck = [Card(character,number,player) for character in [\"A\",\"B\",\"C\",\"D\",\"E\"] for number in range(1,6)]\n\t\trandom.shuffle(deck)\n\t\treturn deck",
"def build_deck(animals_list_of_list):\n deck = []\n for current_row in range(len(animals_list_of_list)):\n card = {'pow_lvl': int(animals_list_of_list[current_row][0]), 'name': animals_list_of_list[current_row][1],\n 'type': animals_list_of_list[current_row][2]}\n deck.append(card)\n\n return deck",
"def make_cards(self):\n\n for suit in self._suits:\n for card_num in xrange(1, self._cards_per_suit + 1):\n left = CARD_WIDTH * (card_num - 1)\n top = CARD_HEIGHT * self._suits.index(suit)\n rect = (left, top, CARD_WIDTH, CARD_HEIGHT)\n image = self._cards_sprite.subsurface(rect)\n rect = image.get_rect()\n card = Card(card_num, suit, image, rect)\n self._cards[str(card)] = card\n self.add(card)\n #card back last row, col = 4,1\n subrect = CARD_WIDTH, CARD_HEIGHT * 4, CARD_WIDTH, CARD_HEIGHT\n image = self._cards_sprite.subsurface(subrect)\n rect = image.get_rect()\n self._cardback = Card(14, 'cardback', image, rect)\n #card back",
"def create_deck(self) -> dict:\n raise NotImplemented"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Compute the squared HS distance between the autocovariance operators of two time series || \\scov^{(y)}_{\\tau} \\scov^{(x)}_{\\tau} ||_{HS}^2 = 1/T2 ( Tr(K_1 x K_1^\\tau) + Tr(K_2 x K_2^\\tau) 2 Tr(K_{1,2} x K_{2,1}^\\tau ) )
|
def distance_hsac_truncated(K, T1, T2, tau=1):
assert tau <= min(T1 / 2.0, T2 / 2.0), "Too big tau"
# define the truncated matrices of the non-shifted series
K1 = K[:T1 - tau, :T1 - tau]
K2 = K[T1:T1 + T2 - tau, T1:T1 + T2 - tau]
K12 = K[:T1 - tau, T1:T1 + T2 - tau]
# define the truncated matrices of the shifted series
K1tau = K[tau:T1, tau:T1]
K2tau = K[T1 + tau:, T1 + tau:]
K12tau = K[tau:T1, T1 + tau:]
# compute the different traces using Hadamard products (and sym of K)
tr1 = np.mean(K1 * K1tau)
tr2 = np.mean(K2 * K2tau)
tr12 = np.mean(K12 * K12tau) # no transpose (K21tau.T == K12tau)
# return dhsac
return tr1 + tr2 - 2 * tr12
|
[
"def pseudochi2(ssys,sK):\n self.ssys = ssys\n self.sK = sK\n \n # Compute CLs value at the signal value that is supposed to be the observed and expected and limit\n # Should be as close to 0.05 \n expCL = self.getCL_direct(s=self.explim,method='simulate',N=100000,nobs=self.b,simall=True)\n obsCL = self.getCL_direct(s=self.obslim,method='simulate',N=100000,nobs=self.o,simall=True)\n print 'ssys = {0}; sK {1}'.format(ssys,sK)\n print 'explim CL: {0}, (target={1})'.format(expCL, 0.05)\n print 'obslim CL: {0}, (target={1})'.format(obsCL, 0.05)\n\n return (expCL - 0.05)**2/0.01**2 + (obsCL - 0.05)**2/0.01**2",
"def chi_square(self, h1, h2):\n d = 0\n for i in range(h1.shape[0]):\n if h1[i] != h2[i]: d += int(((h1[i] - h2[i])**2) / (h1[i] + h2[i]))\n return d",
"def pooled_sd(self, s1, s2, n1, n2):\n # Calculate combined pooled SD for Cohen's D calculation\n # should not be 0\n if (s1 <= 0) or (s2 <= 0) or (n1 <= 0) or (n2 <= 0):\n return -1 # error\n sd = np.sqrt( ( (n1-1)*s1*s1+(n2-1)*s2*s2)/(n1+n2-2))\n return sd",
"def distance_hsac_decomp(K, T1, T2, tau=1, mode=\"truncated\"):\n assert mode in [\"truncated\", \"cyclic\"], \"Unknown HSAC mode (%s)\" % mode\n assert T1 == T2, \"the series should be of same duration\"\n assert tau <= T1 / 2.0, \"Too big tau\"\n T = T1\n if mode == \"truncated\":\n # define the truncated matrices of the non-shifted series\n K1 = K[:T - tau, :T - tau]\n K2 = K[T:T + T - tau, T:T + T - tau]\n K12 = K[:T - tau, T:T + T - tau]\n # define the truncated matrices of the shifted series\n K1tau = K[tau:T, tau:T]\n K2tau = K[T + tau:, T + tau:]\n K12tau = K[tau:T, T + tau:]\n # normalization factor\n nzf = 1.0 / ((T - tau) * (T - tau))\n elif mode == \"cyclic\":\n # define the (non-truncated) matrices of the non-shifted series\n K1 = K[:T, :T]\n K2 = K[T:, T:]\n K12 = K[:T, T:]\n # circular permutation of tau frames\n idxs = np.arange(tau, T + tau) % T\n # indexes used to make the permuted views of the kernel matrix\n perm_slice = np.ix_(idxs, idxs)\n # Note: no need for copy as we re-use the previous centering (indep. of frame order)\n K1tau = K1[perm_slice]\n K2tau = K2[perm_slice]\n K12tau = K12[perm_slice]\n # normalization factor\n nzf = 1.0 / (T * T)\n # compute the different traces using Hadamard products\n tr1 = nzf * (K1 * K1tau.T).sum()\n tr2 = nzf * (K2 * K2tau.T).sum()\n tr12 = nzf * (K12 * K12tau.T).sum() # do not forget the transpose!\n return (tr1, tr2, tr12)",
"def _h3_cmp_dcostheta_ ( h1 ,\n h2 ,\n density = False ) :\n assert isinstance ( h1 , ROOT.TH3 ) and 3 == h1.dim () , \\\n \"cmp_dcos: invalid type of h1 %s/%s\" % ( h1 , type ( h1 ) )\n \n if isinstance ( h2 , ROOT.TH1 ) :\n assert 3 == h2.dim () , \"cmp_dcos: invalid type of h2 %s/%s\" % ( h2 , type ( h2 ) )\n\n if density : \n h1_ = h1.density() if hasattr ( h1 , 'density' ) else h1\n h2_ = h2.density() if hasattr ( h2 , 'density' ) else h2 \n cmp = _h3_cmp_dcostheta_ ( h1_ , h2_ , density = False )\n if h1_ is not h1 : del h1_\n if h2_ is not h2 : del h2_\n return cmp\n\n r1 , r2 , r12 = 0.0 , 0.0 , VE () \n for ix , iy , iz , x , y , z , v1 in h1.items () :\n xv = x.value ()\n xe = x.error () \n yv = y.value ()\n ye = y.error () \n zv = z.value ()\n ze = z.error () \n v2 = VE ( h2 ( xv , yv , zv ) )\n r1 += 8 * xe * ye * ze * ( float ( v1 ) ** 2 )\n r2 += 8 * xe * ye * ze * ( float ( v2 ) ** 2 ) \n r12 += 8 * xe * ye * ze * ( v1 * v2 ) \n\n return r12 / ( r1 * r2 ) ** 0.5",
"def zz_as_syc(theta: float, q0: cirq.Qid, q1: cirq.Qid) -> cirq.Circuit:\n swz = cirq.Circuit(rzz(theta, q0, q1))\n _SingleQubitGates().optimize_circuit(swz)\n swz = cirq.drop_empty_moments(swz)\n return swz",
"def _getCosCdist(DS1, DS2, channels=10, doBack2deg=True):\n \n import scipy.spatial.distance as sd\n import numpy as np\n from HA_extFunctions import _ds2deg, _circdescribe\n \n # each phase (ECC, POL) is converted into nChannels values\n # i.e. 1 phaseval (eg 45 deg) is converted into 10 cos values\n # TODO: now takes nChannel for both inputDS -> make it that both can be different\n if not 'channels' in locals(): channels = DS1.a.deg2cos_channels\n \n # just ignore if no ds as input (use it for plottools..)\n DS1.a['deg2cos_channels'] = channels\n DS2.a['deg2cos_channels'] = channels\n\n cosCdist = []\n for mul in [0,1]:\n ds1 = DS1[(mul*channels):(mul+1)*channels]\n ds2 = DS2[(mul*channels):(mul+1)*channels]\n if doBack2deg:\n ## transform the X-channel-cos-values back to degree and correlate the rad-value ##\n # correlate phase values, thus transform back to deg [0 .. 360]\n ds1 = _ds2deg(ds1)\n ds2 = _ds2deg(ds2)\n \n # if POL values, use cos to get \"circular\" stats\n if mul == 1: \n ds1 = np.cos(np.deg2rad(ds1))\n ds2 = np.cos(np.deg2rad(ds2))\n \n tmp = np.mean(np.diag(sd.cdist(ds1,ds2,'co')))\n else:\n # correlate transformed cos values (nChannels for each ph value)\n # this would implicate circular stats on ECC and POL\n ds1 = ds1.S.reshape(1,ds1.shape[0]*ds1.shape[1])\n ds2 = ds2.S.reshape(1,ds2.shape[0]*ds2.shape[1])\n tmp = sd.cdist(ds1,ds2,'co').squeeze()\n cosCdist.append(tmp)\n\n return cosCdist",
"def skl_estimator_squared_Hellinger_distance(s1, s2, k=1):\n\n n, m = len(s1), len(s2) # NOTE: here different convention of n, m wrt MMD and EnergyDistance\n d = float(s1.shape[1])\n d_2 = d / 2\n\n radius = 10 # this is not used at all...\n s1_neighbourhood_k1 = NearestNeighbors(n_neighbors=k + 1, radius=radius, algorithm='kd_tree').fit(s1)\n s1_neighbourhood_k = NearestNeighbors(n_neighbors=k, radius=radius, algorithm='kd_tree').fit(s1)\n s2_neighbourhood_k1 = NearestNeighbors(n_neighbors=k + 1, radius=radius, algorithm='kd_tree').fit(s2)\n s2_neighbourhood_k = NearestNeighbors(n_neighbors=k, radius=radius, algorithm='kd_tree').fit(s2)\n\n s1_distances, indices = s1_neighbourhood_k1.kneighbors(s1, k + 1)\n s2_distances, indices = s2_neighbourhood_k.kneighbors(s1, k)\n rho = s1_distances[:, -1]\n nu = s2_distances[:, -1]\n if np.any(rho == 0):\n warnings.warn(\n f\"The distance between an element of the first dataset and its {k}-th NN in the same dataset \"\n f\"is 0; this is due to elements which are repeated \"\n f\"{k + 1} times in the first dataset, and may lead to a poor estimate of the distance. \"\n f\"Increasing the value of k usually solves this.\",\n RuntimeWarning)\n\n if np.any(nu == 0):\n warnings.warn(f\"The distance between an element of the first dataset and its {k}-th NN in the second \"\n f\"dataset is 0; this causes divergences in the code, and it is usually due to equal \"\n f\"elements\"\n f\" in the two datasets. Increasing the value of k usually solves this.\", RuntimeWarning)\n first_estimator = np.sum((rho / nu) ** d_2)\n first_estimator = 2 - 2 * np.sqrt((n - 1) / m) * first_estimator\n\n s2_distances, indices = s2_neighbourhood_k1.kneighbors(s2, k + 1)\n s1_distances, indices = s1_neighbourhood_k.kneighbors(s2, k)\n rho = s2_distances[:, -1]\n nu = s1_distances[:, -1]\n if np.any(rho == 0):\n warnings.warn(\n f\"The distance between an element of the second dataset and its {k}-th NN in the same dataset \"\n f\"is 0; this is due to elements which are repeated \"\n f\"{k + 1} times in the second dataset, and may lead to a poor estimate of the distance. \"\n f\"Increasing the value of k usually solves this.\",\n RuntimeWarning)\n # notice: the one below becomes 0 when one element in the s1 dataset is equal to one in the s2 dataset\n # and k=1 (as the distance between those two would be 0, which gives infinity when dividing)\n if np.any(nu == 0):\n warnings.warn(f\"The distance between an element of the second dataset and its {k}-th NN in the first \"\n f\"dataset is 0; this causes divergences in the code, and it is usually due to equal \"\n f\"elements\"\n f\" in the two datasets. Increasing the value of k usually solves this.\", RuntimeWarning)\n second_estimator = np.sum((rho / nu) ** d_2)\n second_estimator = 2 - 2 * np.sqrt((m - 1) / n) * second_estimator\n\n # average the two estimators:\n final_estimator = 0.5 * (first_estimator + second_estimator)\n\n return final_estimator",
"def _h3_cmp_costheta_ ( h1 ,\n h2 ,\n density = False ) :\n assert isinstance ( h1 , ROOT.TH3 ) and 3 == h1.dim () , \\\n \"cmp_cos: invalid type of h1 %s/%s\" % ( h1 , type ( h1 ) )\n \n if isinstance ( h2 , ROOT.TH1 ) :\n assert 3 == h2.dim () , \"cmp_cos: invalid type of h2 %s/%s\" % ( h2 , type ( h2 ) )\n \n if density : \n h1_ = h1.density() if hasattr ( h1 , 'density' ) else h1\n h2_ = h2.density() if hasattr ( h2 , 'density' ) else h2\n cmp = _h3_cmp_costheta_ ( h1_ , h2_ , density = False )\n if h1_ is not h1 : del h1_\n if h2_ is not h2 : del h2_\n return cmp\n \n f1 = lambda x , y , z : float ( h1 ( x , y , z ) ) \n f2 = lambda x , y , z : float ( h2 ( x , y , z ) )\n \n xlims = h1.xminmax()\n ylims = h1.yminmax() \n zlims = h1.zminmax()\n params = xlims [ 0 ] , xlims [ 1 ] , ylims [ 0 ] , ylims [ 1 ] , zlims [ 0 ] , zlims [ 1 ] \n \n from ostap.math.integral import integral3 as _integral3_\n r1 = _integral3_ ( lambda x , y , z : f1 ( x , y , z ) ** 2 , *params )\n r2 = _integral3_ ( lambda x , y , z : f2 ( x , y , z ) ** 2 , *params )\n r12 = _integral3_ ( lambda x , y , z : f1 ( x , y , z ) * f2 ( x , y , z ) , *params ) \n \n return r12 / ( r1 * r2 ) ** 0.5",
"def sig_disk_dm_sech2(self, x, z_, h, sgas=13.2):\n \n z = (z_.to(u.kpc)).value\n h_ = h*u.kpc\n \n vec_integral = np.vectorize(self.integral_sech2tanh)\n integral = vec_integral(x[1], h, z)*u.kpc\n \n sig2 = 4*np.pi*G*np.cosh(z/(2*h))**2*(h_*sgas*u.Msun*u.pc**-2*(1 - np.tanh(z/(2*h))) \n + 4*h_**2*x[2]*u.Msun*u.pc**-3*(np.log(2*np.cosh(z/(2*h))) - z/(2*h)*np.tanh(z/(2*h)))\n + x[0]*u.Msun*u.pc**-2*integral)\n \n return np.sqrt(sig2).to(u.km*u.s**-1)",
"def covariance(data_set1, data_set2):\n n = len(data_set1)\n return np.dot(mean_deviation(data_set1), mean_deviation(data_set2)) / (n - 1)",
"def covariance(xs: List[float], ys: List[float]) -> float:\n \n assert len(xs) == len(ys),\"Vectors must be of the same length\"\n \n mean_xs = sum(xs)/len(xs)\n de_mean_xs = [x_i - mean_xs for x_i in xs]\n \n mean_ys = sum(ys)/len(ys)\n de_mean_ys = [y_i - mean_ys for y_i in ys]\n \n return dot(de_mean_xs,de_mean_ys)/(len(xs) - 1)",
"def comp_chi2(self):\n chi2 = 0.\n for sn in range(self.nsn):\n residu1 = self.y[sn] - np.dot(self.A,np.matrix(self.h[sn]).T).T\n residu2 = self.x[sn,1:] - self.h[sn,1:]\n chi2 += np.dot(np.matrix(residu1),self.wy[sn].dot(np.matrix(residu1).T))+np.dot(np.matrix(residu2),np.dot(self.wx[sn],np.matrix(residu2).T))\n self.chi2 = chi2[0,0]",
"def signal_covar(signal1, signal2):\n return np.cov(signal1,signal2)[0][1]",
"def wasserstein_metric(mu1,mu2,covMat1,covMat2):\n rC2 = utils.sqrtm_22(covMat2)\n mat = covMat1 + covMat2 - (2*utils.sqrtm_22(rC2 @ covMat1 @ rC2))\n wasserstein = np.linalg.norm(mu1-mu2, axis=-1)**2 + np.trace(mat, axis1=-2, axis2=-1)\n return wasserstein",
"def _calculate_sd(self):\n cost = 0\n for k in range(self.k):\n cost += \\\n distance.cdist(np.array([self.centroids[k]]), np.array([self.previous_centroids[k]]),\n metric=self.metric)[\n 0][0]\n return cost",
"def euclideanDistance(timeSeries1, timeSeries2):\n squaredDiffs = [ (t1-t2)**2 for (t1,t2) in zip(timeSeries1,timeSeries2) ] # square all the differences between time series values\n sumOfSquaredDiffs = sum(squaredDiffs)\n return sumOfSquaredDiffs",
"def covariance(first_list_of_values, second_list_of_values):\n result = 0\n mean_first_list = mean(first_list_of_values)\n mean_second_list = mean(second_list_of_values)\n for first, second in zip(first_list_of_values, second_list_of_values):\n result += (first-mean_first_list)*(second-mean_second_list)\n result /= (len(second_list_of_values)-1)\n return result",
"def CLs_corr(a1,a2,s1,s2,rho):\n mu1 = (a1.o - a1.b)/s1\n mu2 = (a2.o - a2.b)/s2 \n sig1 = np.sqrt(1*s1 + a1.b)/s1 # + (1*s*fsigs)**2 + sigb**2)/s #mu'=1\n sig2 = np.sqrt(1*s2 + a2.b)/s2 # \" \" \n \n qobs = qcomb(mu1,sig1,mu2,sig2,rho)\n qAsb = qcomb(1,sig1,1,sig2,rho)\n qAb = qcomb(0,sig1,0,sig2,rho)\n\n obsCLs = CLs(qobs,qAsb) # CLs function assumes q1Asb = -q1Ab\n expCLs = CLs(qAb,qAsb) # median (expected) values of CLs\n \n qAbp = qcomb( sig1,sig1, sig2,sig2,rho)\n qAbm = qcomb(-sig1,sig1,-sig2,sig2,rho)\n\n #+/- 1 sigma\n expCLsp = CLs(qAbp,qAsb)\n expCLsm = CLs(qAbm,qAsb)\n\n return obsCLs,expCLs,expCLsp,expCLsm"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return the components 1/T2 (tr1, tr2, tr12) of HSAC mode {"truncated"/"cyclic"} defines way to compute HSAC
|
def distance_hsac_decomp(K, T1, T2, tau=1, mode="truncated"):
assert mode in ["truncated", "cyclic"], "Unknown HSAC mode (%s)" % mode
assert T1 == T2, "the series should be of same duration"
assert tau <= T1 / 2.0, "Too big tau"
T = T1
if mode == "truncated":
# define the truncated matrices of the non-shifted series
K1 = K[:T - tau, :T - tau]
K2 = K[T:T + T - tau, T:T + T - tau]
K12 = K[:T - tau, T:T + T - tau]
# define the truncated matrices of the shifted series
K1tau = K[tau:T, tau:T]
K2tau = K[T + tau:, T + tau:]
K12tau = K[tau:T, T + tau:]
# normalization factor
nzf = 1.0 / ((T - tau) * (T - tau))
elif mode == "cyclic":
# define the (non-truncated) matrices of the non-shifted series
K1 = K[:T, :T]
K2 = K[T:, T:]
K12 = K[:T, T:]
# circular permutation of tau frames
idxs = np.arange(tau, T + tau) % T
# indexes used to make the permuted views of the kernel matrix
perm_slice = np.ix_(idxs, idxs)
# Note: no need for copy as we re-use the previous centering (indep. of frame order)
K1tau = K1[perm_slice]
K2tau = K2[perm_slice]
K12tau = K12[perm_slice]
# normalization factor
nzf = 1.0 / (T * T)
# compute the different traces using Hadamard products
tr1 = nzf * (K1 * K1tau.T).sum()
tr2 = nzf * (K2 * K2tau.T).sum()
tr12 = nzf * (K12 * K12tau.T).sum() # do not forget the transpose!
return (tr1, tr2, tr12)
|
[
"def distance_hsac_truncated(K, T1, T2, tau=1):\n assert tau <= min(T1 / 2.0, T2 / 2.0), \"Too big tau\"\n # define the truncated matrices of the non-shifted series\n K1 = K[:T1 - tau, :T1 - tau]\n K2 = K[T1:T1 + T2 - tau, T1:T1 + T2 - tau]\n K12 = K[:T1 - tau, T1:T1 + T2 - tau]\n # define the truncated matrices of the shifted series\n K1tau = K[tau:T1, tau:T1]\n K2tau = K[T1 + tau:, T1 + tau:]\n K12tau = K[tau:T1, T1 + tau:]\n # compute the different traces using Hadamard products (and sym of K)\n tr1 = np.mean(K1 * K1tau)\n tr2 = np.mean(K2 * K2tau)\n tr12 = np.mean(K12 * K12tau) # no transpose (K21tau.T == K12tau)\n # return dhsac\n return tr1 + tr2 - 2 * tr12",
"def schmidt_coefficients(schmidt_modes):\n return np.array([mode[0] for mode in schmidt_modes])",
"def calc_beam_modes(self):\n self.beam_modes = {}\n pols = ['X', 'Y']\n for pol in [0, 1]:\n logger.debug('Calculate (accumulate) modes for %s-pol beam. Time is %s' % (pols[pol],\n datetime.datetime.now().time()))\n # Calculate complex excitation voltages\n phases = 2 * math.pi * self.AA.freq * (-self.delays[pol]) * 435e-12 # convert delay to phase\n Vcplx = self.amps[pol] * np.exp(1.0j * phases) # complex excitation col voltage\n\n # sum up modes to create beam described by spherical harmonics\n logger.debug('determine theta-dependent component...')\n\n # finding maximum length of modes for this frequency\n max_length = 0 # initialize\n n_ant = self.AA.n_ant # Was hardcoded to 16\n for ant_i in range(n_ant):\n # select spherical wave table\n name = '%s%s_%s' % (pols[pol], ant_i + 1, self.AA.freq)\n\n # find maximum length\n if self.AA.h5f[name].shape[1] // 2 > max_length:\n max_length = self.AA.h5f[name].shape[1] // 2\n\n # accumulating spherical harmonics coefficients for the array\n # initialize\n Q1_accum = np.zeros(max_length, dtype=np.complex128)\n Q2_accum = np.zeros(max_length, dtype=np.complex128)\n\n # Read in modes\n try:\n Q_modes_all = np.array(self.AA.h5f['modes']).T\n except:\n Q_modes_all = self.AA.h5f['modes'].value.T\n Nmax = 0\n M_accum = None\n N_accum = None\n for ant_i in range(n_ant):\n # re-initialise Q1 and Q2 for every antenna\n Q1 = np.zeros(max_length, dtype=np.complex128)\n Q2 = np.zeros(max_length, dtype=np.complex128)\n\n # select spherical wave table\n name = '%s%s_%s' % (pols[pol], ant_i + 1, self.AA.freq)\n try:\n Q_all = np.array(self.AA.h5f[name]).T\n except:\n Q_all = self.AA.h5f[name].value.T\n\n # current length\n my_len = np.max(Q_all.shape)\n my_len_half = my_len // 2\n\n Q_modes = Q_modes_all[0:my_len, :] # Get modes for this antenna\n\n # convert Qall to M, N, Q1, Q2 vectors for processing\n\n # find s=1 and s=2 indices\n # only find s1 and s2 for this antenna\n s1 = Q_modes[0:my_len, 0] <= 1\n s2 = Q_modes[0:my_len, 0] > 1\n\n # grab m,n vectors\n M = Q_modes[s1, 1]\n N = Q_modes[s1, 2]\n\n # update to the larger M and N\n if np.max(N) > Nmax:\n M_accum = M\n N_accum = N\n Nmax = np.max(N_accum)\n\n # grab Q1mn and Q2mn and make them complex\n Q1[0:my_len_half] = Q_all[s1, 0] * np.exp(1.0j * Q_all[s1, 1] * deg2rad)\n Q2[0:my_len_half] = Q_all[s2, 0] * np.exp(1.0j * Q_all[s2, 1] * deg2rad)\n\n # accumulate Q1 and Q2, scaled by excitation voltage\n Q1_accum += Q1 * Vcplx[ant_i]\n Q2_accum += Q2 * Vcplx[ant_i]\n self.beam_modes[pols[pol]] = {'Q1': Q1_accum, 'Q2': Q2_accum,\n 'M': M_accum, 'N': N_accum}",
"def top_ham_modes(H, isos_012, ns):\n Htop_terms = top_ham_all_terms(H, isos_012)\n N = len(Htop_terms)\n Hns = []\n for n in ns:\n Hn = sum(\n backend.np.exp(1.j * n * j * 2*backend.np.pi / N) * h1 + \n backend.np.exp(1.j * n * (j + 0.5) * 2*backend.np.pi / N) * h2 \n for (j, (h1,h2)) in enumerate(Htop_terms))\n Hns.append(Hn)\n return Hns",
"def test_multi_channel_phase_space(self):\n \n # A specific sets of s- and t-channels for this test:\n\n ####################################################################\n # a) A simple unique massless photon s-channel from e+ e- > d d~ / z\n ####################################################################\n \n massless_photon_schannel_specifier = (\n # s-channels first:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 15,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': -1,\n 'number': 4,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 1,\n 'number': 3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 22,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n })\n ])\n }),\n ]),\n # t-channels then:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 34,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 11,\n 'number': 1,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 22,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': -11,\n 'number': -2,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n })\n ])\n }),\n ])\n ) \n \n ####################################################################\n # a) A simple unique massive Z-boson s-channel from e+ e- > d d~ / a\n ####################################################################\n \n massive_zboson_schannel_specifier = (\n # s-channels first:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 22,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': -1,\n 'number': 4,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 1,\n 'number': 3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n ]),\n # t-channels then:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 40,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 11,\n 'number': 1,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': -11,\n 'number': -2,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n ]),\n )\n \n ###############################################################################\n # c) A complicated fully decayed VBF topology: \n # from: generate u c > h > u c e+ e- mu+ mu- $$ c u / a s d s~ d~ QCD=0 --LO\n ###############################################################################\n vbf_topology_s_and_t_channel_specifier = (\n # s-channels first:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 41,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 13,\n 'number': 8,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': -13,\n 'number': 7,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 40,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 11,\n 'number': 6,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': -11,\n 'number': 5,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -2,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 13,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -2,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 25,\n 'number': -3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n })\n ]),\n # t-channels then:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 63,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': -2,\n 'number': 1,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 2,\n 'number': 3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -4,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 13,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -4,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 25,\n 'number': -3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -5,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 64,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -5,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 4,\n 'number': 4,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': -4,\n 'number': -6,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n ]),\n )\n\n\n ###############################################################################\n # d) A complicated fully decayed VBF topology: \n # from: generate e- e+ > h > e+ e- mu+ mu- ta+ ta- $$ e+ e- \\ a QCD=0 --diagram_filter --LO\n ###############################################################################\n # where diagram filter removes the first three diagrams\n # import model sm-dario\n self.vbf_topology_s_and_t_channel_specifier2 = (\n # s-channels first:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 42,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 15,\n 'number': 8,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': -15,\n 'number': 7,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 41,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 13,\n 'number': 6,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': -13,\n 'number': 5,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -2,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 13,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -1,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -2,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 25,\n 'number': -3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n })\n ]),\n # t-channels then:\n base_objects.VertexList([\n base_objects.Vertex({\n 'id': 40,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': -11,\n 'number': 1,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 11,\n 'number': 4,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -4,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 13,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -4,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': 25,\n 'number': -3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 23,\n 'number': -5,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n base_objects.Vertex({\n 'id': 40,\n 'legs': base_objects.LegList([\n base_objects.Leg({\n 'id': 23,\n 'number': -5,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None \n }),\n base_objects.Leg({\n 'id': -11,\n 'number': 3,\n 'state': True,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n base_objects.Leg({\n 'id': 11,\n 'number': -6,\n 'state': False,\n 'from_group': True,\n 'loop_line': False,\n 'onshell': None\n }),\n ])\n }),\n ]),\n )",
"def adiabatic_level(S, T, p, lat, pref=0,\n pressure_range=400,\n order=1, axis=0,\n eta_calc=True):\n\n # Pressure window - See Bray and Fofonoff 1981 for details\n plev = pressure_range\n\n # Calculate Buoyancy Frequency using GSW toolbox\n N2, p_mid = gsw.stability.Nsquared(S, T, p, lat, axis=axis)\n\n # Keeps as rank 2 array making it compatible with casts and arrays\n if len(N2.shape) < 2:\n N2 = np.expand_dims(N2, 1)\n p_mid = np.expand_dims(p_mid, 1)\n S = np.expand_dims(S, 1)\n T = np.expand_dims(T, 1)\n p = np.expand_dims(p, 1)\n\n # Calculate reference N2 Field\n alpha = np.full((p_mid.shape[0], p_mid.shape[1]), np.nan)\n g = np.full((p_mid.shape[0], p_mid.shape[1]), np.nan)\n rho_bar = np.full((p_mid.shape[0], p_mid.shape[1]), np.nan)\n drho_dz = np.full((p_mid.shape[0], p_mid.shape[1]), np.nan)\n\n\n# N2_ref = np.full_like(N2, np.nan)\n for i in range(p_mid.shape[axis]):\n # Bottom and top for window - the max and min of the 2-element array\n # allows windows to run to ends of profile (I think)\n\n for k in range(p_mid.shape[1]):\n p_min = np.max([p_mid[i,k] - 0.5*plev, p[0,k]])\n p_max = np.min([p_mid[i,k] + 0.5*plev, p[-1,k]])\n data_in = np.logical_and(p >= p_min, p<= p_max)\n\n if np.sum(data_in) > 0:\n p_bar = np.nanmean(p[data_in[:,k],k])\n t_bar = np.nanmean(T[data_in[:,k],k])\n s_bar = np.nanmean(S[data_in[:,k],k])\n rho_bar[i,k] = gsw.density.rho(s_bar, t_bar, p_bar)\n\n # Potential Temperature referenced to pbar\n theta = gsw.conversions.pt_from_t(S[data_in[:,k],k],\n T[data_in[:,k],k],\n p[data_in[:,k],k],\n p_bar)\n\n sv = 1. / gsw.pot_rho_t_exact(S[data_in[:,k],k],\n theta,\n p[data_in[:,k],k],\n p_bar)\n\n # Regress pressure onto de-meaned specific volume and store coefficients\n Poly = np.polyfit(p[data_in[:, k], k], sv - np.nanmean(sv), order)\n\n # Do something with coefficients that I dont understand\n alpha[i, k] = Poly[order - 1]\n\n # calculate reference N2 reference field\n g[i, k] = gsw.grav(lat.T[k], p_bar)\n\n # Calculate N2 grid (10^-4 to convert from db to pascals)\n N2_ref = -1e-4 * rho_bar**2 * g**2 * alpha\n\n # strain calcuations\n strain = (N2 - N2_ref) / N2_ref\n\n # Append row of nans onto the top or bottom because computing N2 chops a row\n p_mid = np.vstack((np.zeros((1, p_mid.shape[1])), p_mid))\n rho_bar = np.vstack((np.full((1, p_mid.shape[1]), np.nan), rho_bar))\n\n return N2_ref, N2, strain, p_mid, rho_bar",
"def getTransmissionCoefficients(self, skipFission=True, method='weakCoupling'):\n allowedMethods=[\"weakCoupling\", '1stOrder', '2ndOrder', 'sumRule', 'opticalModel', 'SPRT']\n if method not in allowedMethods:\n raise ValueError('Transmission coefficient calculation method must be one of '+', '.join(allowedMethods))\n # Initialize the reduced width factors for the elastic channel\n redWidthFactor={}\n if not self.averageWidths: self.getWidthsAndSpacings()\n for lj in self.averageWidths:\n if lj[0] not in redWidthFactor:\n redWidthFactor[lj[0]]=XYs1dModule.XYs1d.createFromFunction(\n XYs1dModule.XYs1d.defaultAxes(\n labelsUnits={\n XYs1dModule.yAxisIndex : ( 'gamma' , '' ),\n XYs1dModule.xAxisIndex : ( 'Ex', 'eV' ) }),\n self.averageWidths[lj]['elastic'].domain(),\n lambda E,nope: math.sqrt(E)*self.penetrationFactor( lj[0], self.rho(E) )/self.rho(E),\n {},\n 1e-6,\n 100)\n\n # Now compute the Tc's\n Tc={}\n channelClass={'capture':GAMMACHANNEL, 'elastic':NEUTRONCHANNEL, 'fission':FISSIONCHANNEL}\n for rxn in channelClass.keys():\n for lj in self.averageWidths:\n if rxn=='elastic':\n tau=math.pi*redWidthFactor[lj[0]]*self.averageWidths[lj][rxn]/self.levelSpacings[lj]\n elif rxn=='fission':\n if skipFission: continue\n if rxn not in self.averageWidths[lj]: continue\n tau=math.pi*self.averageWidths[lj][rxn]/self.levelSpacings[lj]\n else:\n tau=math.pi*self.averageWidths[lj][rxn]/self.levelSpacings[lj]\n c=ChannelDesignator(lj[0], lj[1], rxn, len(Tc), int(2.0*abs(lj[0]-lj[1])), gfact=None,\n particleA=None, particleB=None, isElastic=(rxn=='elastic'),\n channelClass=channelClass[rxn], useRelativistic=False, eliminated=False)\n if method in [\"weakCoupling\", '1stOrder']:\n Tc[c] = 2.0 * tau\n elif method=='2ndOrder':\n Tc[c] = 2.0 * tau * (1.0 - tau)\n elif method==\"opticalModel\":\n Tc[c] = tau.applyFunction(lambda x, par: 1.0 - math.exp(-2.0 * tau.evaluate(x)), None) #FIXME: \"tau.evaluate(x)\" should only be \"x\", but applyFunction() is broken as is exp()\n elif method == 'sumRule':\n Tc[c] = tau.applyFunction(lambda x, par: 2.0 * tau.evaluate(x) * (math.sqrt(1.0 + tau.evaluate(x) * tau.evaluate(x)) - tau.evaluate(x)), None)\n else: #method==\"SPRT\"\n Tc[c] = 2.0*tau/(1.0+tau/2.0)/(1.0+tau/2.0)\n\n # Fix axis label, still says \"Gamma\"\n Tc[c].axes[0].label='Tc(rxn=%s, L=%i, J=%s)'%(c.reaction, c.l, str(c.J))\n return Tc",
"def constructSymbolicHubbard2(hdim,vdim,t,U):\n hdim = hdim*2\n nqubits = vdim*hdim\n # first horizontal line of sites\n firstLine = range(1,hdim-1)\n spinDownList = [x for x in firstLine if x % 2 == 1]\n coefficients=[]\n operators=[]\n # Generating the horizontal contributions to the hamiltonian\n for j in range(0,vdim):\n offset = j*hdim\n for i in spinDownList:\n #print(i)\n operators.append([i+offset,-i-2-offset])\n coefficients.append(-t)\n operators.append([i+1+offset,-i-3-offset])\n coefficients.append(-t) \n # periodic boundary conditions\n if hdim > 2:\n operators.append([hdim-1+offset,-1-offset])\n coefficients.append(-t)\n operators.append([hdim+offset,-2-offset])\n coefficients.append(-t) \n #print(\"spinDownList\",spinDownList)\n #print(\"horizontal contributions:\",operators)\n\n # Generating the vertical contributions to the hamiltonian\n # open boundary conditions\n firstLine = range(1,hdim+1)\n spinDownList = [x for x in firstLine if x % 2 == 1]\n #print(\"spinDownList\",spinDownList)\n for j in range(1,vdim):\n offset1 = (j-1)*hdim\n offset2 = j*hdim\n for i in spinDownList:\n #print(i)\n operators.append([i+offset1,-i-offset2])\n coefficients.append(-t)\n operators.append([i+1+offset1,-i-1-offset2])\n coefficients.append(-t) \n #print(\"vertical contributions:\",operators)\n \n # repulsion terms\n allQubits = range(1,nqubits+1)\n spinDownListAll = [x for x in allQubits if x % 2 == 1]\n for i in spinDownListAll:\n operators.append([i,-i,i+1,-i-1])\n coefficients.append(U)\n \n #print(\"repulsion contributions:\",operators)\n return operators, coefficients, nqubits",
"def sarsa_on_tic_tac_toe_solo() -> PolicyAndActionValueFunction:\n env = TicTacToe()\n\n return sarsa(env, alpha=0.1, epsilon=1, gamma=0.9, max_episodes=10000, env_name='tictactoe')",
"def _thermlc(tautom, theta, deltal, x, jmax, dphdot, bet, c2):\n dphesc = np.zeros(900) # Initialise the output\n a = np.zeros(900); b = np.zeros(900); c = np.zeros(900)\n d = np.zeros(900); alp = np.zeros(900); u = np.zeros(900)\n g = np.zeros(900); gam = np.zeros(900)\n\n #c u(x) is the dimensionless photon occupation number\n c20 = tautom / deltal\n\n #c determine u\n #c define coefficients going into equation\n #c a(j) * u(j + 1) + b(j) * u(j) + c(j) * u(j - 1) = d(j)\n for j in range(1, jmax - 1):\n w1 = np.sqrt( x[j] * x[j + 1] )\n w2 = np.sqrt( x[j - 1] * x[j] )\n #c w1 is x(j + 1 / 2)\n #c w2 is x(j - 1 / 2)\n a[j] = -c20 * c2[j] * (theta / deltal / w1 + 0.5)\n t1 = -c20 * c2[j] * (0.5 - theta / deltal / w1)\n t2 = c20 * c2[j - 1] * (theta / deltal / w2 + 0.5)\n t3 = x[j]**3 * (tautom * bet[j])\n b[j] = t1 + t2 + t3\n c[j] = c20 * c2[j - 1] * (0.5 - theta / deltal / w2)\n d[j] = x[j] * dphdot[j]\n\n #c define constants going into boundary terms\n #c u(1) = aa * u(2) (zero flux at lowest energy)\n #c u(jx2) given from region 2 above\n x32 = np.sqrt(x[0] * x[1])\n aa = (theta / deltal / x32 + 0.5) / (theta / deltal / x32 - 0.5)\n\n #c zero flux at the highest energy\n u[jmax - 1] = 0.0\n\n #c invert tridiagonal matrix\n alp[1] = b[1] + c[1] * aa\n gam[1] = a[1] / alp[1]\n for j in range(2, jmax - 1):\n alp[j] = b[j] - c[j] * gam[j - 1]\n gam[j] = a[j] / alp[j]\n g[1] = d[1] / alp[1]\n for j in range(2, jmax - 2):\n g[j] = (d[j] - c[j] * g[j - 1]) / alp[j]\n g[jmax - 2] = (d[jmax - 2] - a[jmax - 2] * u[jmax - 1] \n - c[jmax - 2] * g[jmax - 3]) / alp[jmax - 2]\n u[jmax - 2] = g[jmax - 2]\n for j in range(2, jmax + 1):\n jj = jmax - j\n u[jj] = g[jj] - gam[jj] * u[jj + 1]\n u[0] = aa * u[1]\n #c compute new value of dph(x) and new value of dphesc(x)\n dphesc[:jmax] = x[:jmax] * x[:jmax] * u[:jmax] * bet[:jmax] * tautom\n\n return dphesc",
"def meyerhoff_and_hanna_capacity(sl_0, sl_1, h0, fd, verbose=0):\n\n # UNFINISHED, this code is copied from the Meyerhoff method\n #horizontal_load = np.sqrt(h_l ** 2 + h_b ** 2)\n\n sl_0.nq_factor_0 = ((np.tan(np.pi / 4 + np.deg2rad(sl_0.phi / 2))) ** 2 * np.exp(np.pi * np.tan(np.deg2rad(sl_0.phi))))\n if sl_0.phi == 0:\n sl_0.nc_factor_0 = 5.14\n else:\n sl_0.nc_factor_0 = (sl_0.nq_factor_0 - 1) / np.tan(np.deg2rad(sl_0.phi))\n sl_0.ng_factor_0 = (sl_0.nq_factor_0 - 1) * np.tan(1.4 * np.deg2rad(sl_0.phi))\n\n\n sl_1.nq_factor_1 = ((np.tan(np.pi / 4 + np.deg2rad(sl_1.phi / 2))) ** 2 * np.exp(np.pi * np.tan(np.deg2rad(sl_1.phi))))\n if sl_1.phi == 0:\n sl_1.nc_factor_1 = 5.14\n else:\n sl_1.nc_factor_1 = (sl_1.nq_factor_1 - 1) / np.tan(np.deg2rad(sl_1.phi))\n sl_1.ng_factor_1 = (sl_1.nq_factor_1 - 1) * np.tan(1.4 * np.deg2rad(sl_1.phi))\n\n if verbose:\n log(\"Nc: \", sl_1.nc_factor_1)\n log(\"Nq: \", sl_1.nq_factor_1)\n log(\"Ng: \", sl_1.ng_factor_1)\n\n sl_0.kp_0 = (np.tan(np.pi / 4 + np.deg2rad(sl_0.phi / 2))) ** 2\n sl_1.kp_1 = (np.tan(np.pi / 4 + np.deg2rad(sl_1.phi / 2))) ** 2\n # shape factors\n\n # s_c = 1 + 0.2 * kp * fd.width / fd.length\n if sl_0.phi >= 10:\n sl_0.s_c_0 = 1 + 0.2 * sl_0.kp_0 * (fd.width / fd.length)\n sl_0.s_q_0 = 1.0 + 0.1 * sl_0.kp_0 * (fd.width / fd.length)\n else:\n sl_0.s_c_0 = 1 + 0.2 * (fd.width / fd.length)\n sl_0.s_q_0 = 1.0\n sl_0.s_g_0 = sl_0.s_q_0\n\n if sl_1.phi >= 10:\n sl_1.s_c_1 = 1 + 0.2 * sl_1.kp_1 * (fd.width / fd.length)\n sl_1.s_q_1 = 1.0 + 0.1 * sl_1.kp_1 * (fd.width / fd.length)\n else:\n sl_1.s_c_1 = 1 + 0.2 * (fd.width / fd.length)\n sl_1.s_q_1 = 1.0\n sl_1.s_g_1 = sl_1.s_q_1\n\n \"\"\"\n # depth factors\n d_c = 1 + 0.2 * np.sqrt(kp) * fd.depth / fd.width\n if sl_0.phi > 10:\n d_q = 1 + 0.1 * np.sqrt(kp) * fd.depth / fd.width\n else:\n d_q = 1.0\n d_g = d_q\n\n # inclination factors:\n theta_load = np.arctan(horizontal_load / vertical_load)\n i_c = (1 - theta_load / (np.pi * 0.5)) ** 2\n i_q = i_c\n if sl_0.phi > 0:\n i_g = (1 - theta_load / sl_0.phi_r) ** 2\n else:\n i_g = 0\n \"\"\"\n\n # stress at footing base:\n #q_d = sl_0.unit_dry_weight_0 * fd.depth\n\n # ks\n sl_0.q_0=(sl_0.cohesion*sl_0.nc_factor_0)+(0.5*sl_0.unit_dry_weight*fd.width*sl_0.ng_factor_0)\n sl_1.q_1 = (sl_1.cohesion * sl_1.nc_factor_1) + (0.5 * sl_1.unit_dry_weight * fd.width * sl_1.ng_factor_1)\n q1_q0= sl_1.q_1 / sl_0.q_0\n\n\n x_0 = np.array([0,20.08, 22.42, 25.08, 27.58, 30.08, 32.58, 34.92, 37.83, 40.00, 42.67, 45.00, 47.00, 49.75])\n y_0 = np.array([0.93,0.93, 0.93, 0.93, 1.01, 1.17, 1.32, 1.56, 1.87, 2.26, 2.72, 3.35, 3.81, 4.82])\n x_2 = np.array([0,20.08, 22.50, 25.08, 27.58, 30.08, 32.50, 35.00, 37.67, 40.17, 42.67, 45.00, 47.50, 50.00])\n y_2 = np.array([1.55,1.55, 1.71, 1.86, 2.10, 2.33, 2.72, 3.11, 3.81, 4.43, 5.28, 6.14, 7.46, 9.24])\n x_4 = np.array([0,20.00, 22.51, 25.10, 27.69, 30.11, 32.45, 35.04, 37.88, 40.14, 42.65, 45.07, 47.33, 50.08])\n y_4 = np.array([2.49,2.49, 2.64, 2.87, 3.34, 3.81, 4.43, 5.20, 6.29, 7.38, 9.01, 11.11, 14.29, 19.34])\n x_10 = np.array([0,20.00, 22.50, 25.08, 28.00, 30.00, 32.50, 34.92, 37.50, 40.17, 42.42, 45.00, 47.17, 50.08])\n y_10 = np.array([3.27,3.27, 3.74, 4.44, 5.37, 6.07, 7.16, 8.33, 10.04, 12.30, 15.95, 21.17, 27.47, 40.00])\n x_int = sl_0.phi\n\n if q1_q0 == 0:\n interpolation = Akima1DInterpolator(x_0, y_0)\n fd.ks = interpolation(x_int)\n\n elif q1_q0 == 0.2:\n interpolation = Akima1DInterpolator(x_2, y_2)\n fd.ks = interpolation(x_int)\n\n elif q1_q0 == 0.4:\n interpolation = Akima1DInterpolator(x_4, y_4)\n fd.ks = interpolation(x_int)\n\n elif q1_q0 == 1.0:\n interpolation = Akima1DInterpolator(x_10, y_10)\n fd.ks = interpolation(x_int)\n\n elif q1_q0 > 0 and q1_q0 < 0.2:\n interpolation_1 = Akima1DInterpolator(x_0, y_0)\n ks_1 = interpolation_1(x_int)\n interpolation_2 = Akima1DInterpolator(x_2, y_2)\n ks_2 = interpolation_2(x_int)\n fd.ks = (((ks_2-ks_1)*q1_q0)/0.2)+ ks_1\n\n elif q1_q0 > 0.2 and q1_q0 < 0.4:\n interpolation_1 = Akima1DInterpolator(x_2, y_2)\n ks_1 = interpolation_1(x_int)\n interpolation_2 = Akima1DInterpolator(x_4, y_4)\n ks_2 = interpolation_2(x_int)\n fd.ks = (((ks_2-ks_1)*(q1_q0-0.2))/0.2)+ ks_1\n\n elif q1_q0 > 0.4 and q1_q0 < 1.0:\n interpolation_1 = Akima1DInterpolator(x_4, y_4)\n ks_1 = interpolation_1(x_int)\n interpolation_2 = Akima1DInterpolator(x_10, y_10)\n ks_2 = interpolation_2(x_int)\n fd.ks = (((ks_2-ks_1)*(q1_q0-0.4))/0.6)+ ks_1\n\n\n\n #ca\n if sl_0.cohesion==0:\n c1_c0 =0\n else:\n c1_c0=sl_1.cohesion/sl_0.cohesion\n x = np.array([0.000,0.082,0.206,0.298,0.404,0.509,0.598,0.685,0.772])\n y = np.array([0.627,0.700,0.794,0.855,0.912,0.948,0.968,0.983,0.997])\n interpolation = Akima1DInterpolator(x, y)\n ca_c0 = interpolation(c1_c0)\n fd.ca = ca_c0*sl_0.cohesion\n\n # Capacity\n a = 1 # ????\n s = 1 # ????\n\n r=1+(fd.width/fd.length)\n q_b1= (sl_1.cohesion * sl_1.nc_factor_1 * sl_1.s_c_1)\n q_b2 = (sl_0.unit_dry_weight * h0 * sl_1.nq_factor_1 * sl_1.s_q_1)\n q_b3 = (sl_1.unit_dry_weight * fd.width * sl_1.ng_factor_1 * sl_1.s_g_1 / 2)\n fd.q_b = q_b1 + q_b2 + q_b3\n fd.q_ult4 = (r * (2 * fd.ca * (h0 - fd.depth) / fd.width) * a)\n fd.q_ult5 = r * (sl_0.unit_dry_weight * ((h0 - fd.depth) ** 2)) * (1 + (2 * fd.depth / (h0 - fd.depth))) * (fd.ks * np.tan(np.deg2rad(sl_0.phi)) / fd.width) * s\n fd.q_ult6 = (sl_0.unit_dry_weight * (h0 - fd.depth))\n fd.q_ult = fd.q_b + fd.q_ult4 + fd.q_ult5 - fd.q_ult6\n\n # maximum value (qu <= qt)\n q_t1 = (sl_0.cohesion * sl_0.nc_factor_0 * sl_0.s_c_0)\n q_t2 = (sl_0.unit_dry_weight * fd.depth * sl_0.nq_factor_0 * sl_0.s_q_0)\n q_t3 = (sl_0.unit_dry_weight * fd.width * sl_0.ng_factor_0 * sl_0.s_g_0 / 2)\n fd.q_t = q_t1 + q_t2 + q_t3\n\n if fd.q_ult > fd.q_t:\n fd.q_ult = fd.q_t\n\n return fd.q_ult",
"def closed_shell_hf(R0, C0, level, half_length, n_gauss=5):\n # =========================================================================\n # Define Computational Mesh\n # =========================================================================\n Mu, cells = mesh(level, half_length)\n L = 2*half_length\n \n # =========================================================================\n # Precompute A, Te and Tn matrices\n # =========================================================================\n #\n # Laplacian A\n #\n A = assemble_laplacian(Mu, L, level)\n \n #\n # Electron-Electron interactions\n # \n Te = assemble_ee_interaction_matrix(cells, n_gauss=n_gauss)\n \n #\n # Electron-Nucleus interactions\n #\n Tn = assemble_ne_interaction_matrix(R0, cells)\n \n #\n # SCI procedure\n # \n for dummy in range(10):\n #\n # Until convergence \n # \n \n CCT = C0.dot(C0.T)\n \n # \n # Coulomb matrix\n # \n J = 2*np.diag(CCT)*np.diag(Te)\n \n #\n # Exchange matrix\n # \n K = CCT*Tn\n \n #\n # Fock Matrix\n # \n F = -0.5*A - Tn + J + K",
"def H(N, W1, c1, phi1, J1=1, W2=0, c2=0, phi2=0, J2=0, nleg=1, mode='open'):\n\n # try to load Sx, Sy, Sz from the Globals dictionary if they have been\n # generated\n try:\n Sx, Sy, Sz = G['sigmas']\n except KeyError:\n Sx, Sy, Sz = c.sigmax(), c.sigmay(), c.sigmaz()\n G['sigmas'] = [Sx, Sy, Sz]\n\n # try to load the full Hilbert space operators from the Globals\n # dictionary if they have been generated\n if not G.__contains__('full_S'):\n G['full_S'] = {}\n try:\n full_S = G['full_S'][N]\n except KeyError:\n full_S = [[half.full_matrix(S, k, N) for k in range(N)]\n for S in [Sx, Sy, Sz]]\n G['full_S'][N] = full_S\n\n # The following section describes a hamiltonian of a 2-D latice that\n # we label the following way\n # 0 l2 2*l2 ... (l1-1)*l2\n # 1 l2+1 2*l2+1 ... (l1-1)*l2+1\n # 2 l2+2 2*l2+2 ... (l1-1)*l2+2\n # ...\n # l2-1 2*l2-1 3*l2-1 ... l1*l2-1\n l1 = N // nleg # number of sites along the \"horizontal\"\n l2 = nleg # number of sites along the \"vertical\" (number of legs)\n # Nearest neighbor contributions along the horizontal direction (along\n # which J1 is the coupling constant)\n if nleg == N:\n J1 = 0 # interaction=0 if there's only 1 site along direction\n # mode == 'periodic' is self-explanatory. l1==2 and lb1=0 would imply\n # adjacent sites along adjacent legs interact with each other twice,\n # not exactly what we are looking for.\n lb1 = 0 if (mode == 'periodic' and not l1 == 2) else l2\n inter_terms1 = J1 * sum(full_S[i][j - l2] * full_S[i][j]\n for j in range(lb1, N) for i in range(3))\n\n # Nearest neighbor contributions along the vertical direction (along\n # which J2 is the coupling constant)\n if nleg == 1:\n J2 = 0 # interaction=0 if there's only 1 site along direction\n # mode == 'periodic' is self-explanatory. l2==2 and js looping over\n # every index would imply adjacent sites interact with each other\n # twice, not exactly what we are looking for.\n if (mode == 'periodic' and not l2 == 2):\n # if periodic BC, loop over every site\n js = range(0, l2)\n else:\n # if open BC, skip indices that are at the start of a column\n js = range(1, l2)\n # \"vert_os\" is the offset -- \"distance\" in our indices between\n # adjacent sites along the same rung. It is in general the number\n # of legs of the lattice.\n inter_terms2 = J2 * sum(full_S[i][vert_os: vert_os + l2][j - 1] *\n full_S[i][vert_os: vert_os + l2][j]\n for j in js for vert_os in range(0, N, l2)\n for i in range(3))\n\n inter_terms = inter_terms1 + inter_terms2\n\n # Contributions from the disorder field\n # --- along horizontal direction ---\n if l1 == 1: # field contrib=0 if length of leg=1 aka 1D\n field1 = np.zeros([1])\n else:\n field1 = W1 * np.cos(2 * np.pi * c1 * np.arange(1, l1 + 1) + phi1)\n # --- along vertical direction ---\n if l2 == 1: # field contrib=0 if length of leg=1 aka 1D\n field2 = np.zeros([1])\n else:\n field2 = W2 * np.cos(2 * np.pi * c2 * np.arange(1, l2 + 1) + phi2)\n\n field = field1.repeat(l2) + field2.repeat(l1).reshape(l2, l1).T.flatten()\n field_terms = sum(field * full_S[2])\n\n # Total\n H = inter_terms + field_terms\n return H.real",
"def calc_RH_from_T_Td(T, Td, mode=0):\n if mode == 0: \n Tk = T + SHR_CONST_TKFRZ\n Tdk = Td + SHR_CONST_TKFRZ\n es = np.exp( -6096.9385 * Tk**(-1) + 21.2409642 - 2.711193e-2 * Tk + \\\n 1.673952e-5 * Tk**2.0 + 2.433502 * np.log(Tk))\n e = np.exp( -6096.9385 * Tdk**(-1) + 21.2409642 - 2.711193e-2 * Tdk + \\\n 1.673952e-5 * Tdk**2.0 + 2.433502 * np.log(Tdk))\n elif mode == 1: # Magnus formulae \n es = np.exp(np.log(611.2) + (17.62*T)/(243.12+T)) # vapor pressure in Pa\n e = np.exp(np.log(611.2) + (17.62*Td)/(243.12+Td)) # vapor pressure in Pa\n\n RH = e/es * 100.0\n\n RH[RH>100] = 100.0\n RH[RH<0] = 0\n\n return RH",
"def expected_sarsa_on_tic_tac_toe_solo() -> PolicyAndActionValueFunction:\n env = TicTacToe()\n\n return expected_sarsa(env, alpha=0.1, epsilon=0.9, gamma=0.9, max_episodes=10000, env_name='tictactoe')",
"def _tapes_data_hardware(tape, operation, key, num_split_times, use_broadcasting):\n op, op_idx, term_idx = operation\n # Map a simple enumeration of numbers from HardwareHamiltonian input parameters to\n # ParametrizedHamiltonian parameters. This is typically a fan-out function.\n fake_params, allowed_outputs = np.arange(op.num_params), set(range(op.num_params))\n reordered = op.H.reorder_fn(fake_params, op.H.coeffs_parametrized)\n\n def _raise():\n raise ValueError(\n \"Only permutations, fan-out or fan-in functions are allowed as reordering functions \"\n \"in HardwareHamiltonians treated by stoch_pulse_grad. The reordering function of \"\n f\"{op.H} mapped {fake_params} to {reordered}.\"\n )\n\n cjacs, tapes, psr_coeffs = [], [], []\n for coeff_idx, x in enumerate(reordered):\n # Find out whether the value term_idx, corresponding to the current parameter of interest,\n # has been mapped to x (for scalar x) or into x (for 1d x). If so, generate tapes and data\n # Also check that only allowed outputs have been produced by the reordering function.\n if not hasattr(x, \"__len__\"):\n if x not in allowed_outputs:\n _raise()\n if x != term_idx:\n continue\n cjac_idx = None\n else:\n if not all(_x in list(range(op.num_params)) for _x in x):\n _raise()\n if term_idx not in x:\n continue\n cjac_idx = np.argwhere([_x == term_idx for _x in x])[0][0]\n\n _operation = (op, op_idx, coeff_idx)\n # Overwriting int_prefactor does not matter, it is equal for all parameters in this op,\n # because it only consists of the duration `op.t[-1]-op.t[0]` and `num_split_times`\n _tapes, _cjacs, int_prefactor, _psr_coeffs = _generate_tapes_and_cjacs(\n tape, _operation, key, num_split_times, use_broadcasting, cjac_idx\n )\n cjacs.append(qml.math.stack(_cjacs))\n tapes.extend(_tapes)\n psr_coeffs.append(_psr_coeffs)\n\n # The fact that psr_coeffs are a tuple only for hardware Hamiltonian generators will be\n # used in `_parshift_and_integrate`.\n data = (len(tapes), tuple(cjacs), int_prefactor, tuple(psr_coeffs))\n return tapes, data",
"def _h3_cmp_costheta_ ( h1 ,\n h2 ,\n density = False ) :\n assert isinstance ( h1 , ROOT.TH3 ) and 3 == h1.dim () , \\\n \"cmp_cos: invalid type of h1 %s/%s\" % ( h1 , type ( h1 ) )\n \n if isinstance ( h2 , ROOT.TH1 ) :\n assert 3 == h2.dim () , \"cmp_cos: invalid type of h2 %s/%s\" % ( h2 , type ( h2 ) )\n \n if density : \n h1_ = h1.density() if hasattr ( h1 , 'density' ) else h1\n h2_ = h2.density() if hasattr ( h2 , 'density' ) else h2\n cmp = _h3_cmp_costheta_ ( h1_ , h2_ , density = False )\n if h1_ is not h1 : del h1_\n if h2_ is not h2 : del h2_\n return cmp\n \n f1 = lambda x , y , z : float ( h1 ( x , y , z ) ) \n f2 = lambda x , y , z : float ( h2 ( x , y , z ) )\n \n xlims = h1.xminmax()\n ylims = h1.yminmax() \n zlims = h1.zminmax()\n params = xlims [ 0 ] , xlims [ 1 ] , ylims [ 0 ] , ylims [ 1 ] , zlims [ 0 ] , zlims [ 1 ] \n \n from ostap.math.integral import integral3 as _integral3_\n r1 = _integral3_ ( lambda x , y , z : f1 ( x , y , z ) ** 2 , *params )\n r2 = _integral3_ ( lambda x , y , z : f2 ( x , y , z ) ** 2 , *params )\n r12 = _integral3_ ( lambda x , y , z : f1 ( x , y , z ) * f2 ( x , y , z ) , *params ) \n \n return r12 / ( r1 * r2 ) ** 0.5",
"def initialSecond(self):\n\n # ************************************************************\n # ***** CHANNEL INITIAL SPLIT UP IN SECOND CHANNEL************\n # ************************************************************\n if option['SplitRouting']:\n\n ChanMan2 = (self.var.ChanMan / self.var.CalChanMan) * loadmap('CalChanMan2')\n AlpTermChan2 = (ChanMan2 / (np.sqrt(self.var.ChanGrad))) ** self.var.Beta\n ChannelAlpha2C = AlpTermChan2 * (self.var.ChanWettedPerimeterAlpha ** self.var.AlpPow)\n self.var.InvChannelAlpha2 = 1/ChannelAlpha2C\n self.var.ChannelAlpha2 = decompress(ChannelAlpha2C)\n # calculating second Alpha for second (virtual) channel\n\n if not(option['InitLisflood']):\n\n self.var.QLimit = loadmap('AvgDis') * loadmap('QSplitMult')\n self.var.M3Limit = self.var.ChannelAlphaC * self.var.ChanLengthC * (self.var.QLimit ** self.var.Beta)\n # lower discharge limit for second line of routing\n # set to mutiple of average discharge (map from prerun)\n # QSplitMult =2 is around 90 to 95% of Q\n self.var.QLimit = self.var.QLimit / self.var.NoRoutSteps\n\n self.var.Chan2M3Start = ChannelAlpha2C * self.var.ChanLengthC * (self.var.QLimit ** self.var.Beta)\n # virtual amount of water in the channel through second line\n\n self.var.Chan2QStart = self.var.QLimit - compressArray(\n upstream(self.var.LddKinematic, decompress(self.var.QLimit)))\n\n # because kinematic routing with a low amount of discharge leads to long travel time:\n # Starting Q for second line is set to a higher value\n\n self.var.Chan2M3Kin = self.var.CrossSection2Area * self.var.ChanLengthC + self.var.Chan2M3Start\n\n self.var.ChanM3Kin = self.var.ChanM3 - self.var.Chan2M3Kin + self.var.Chan2M3Start",
"def C_and_Z_path(A, N1, N2, Z0, Ct, MKMH_option=False):\n Z_path = np.zeros_like(Z0)\n Z_path = np.hstack([Z_path, Z0])\n \n for t in range(T):\n Z = np.matmul(A,Z0)\n Z_path = np.hstack([Z_path,Z])\n Z0 = Z\n \n Z_path = Z_path[:,1:] \n C_path = np.zeros(T)\n KH_path = Z_path[:2,:] \n X_path = Z_path[2:,:] \n MKMH_path = np.matmul(N1,KH_path) + np.matmul(N2,X_path) \n \n for t in range(T-1):\n MK1 = MKMH_path[0,t+1]\n MH1 = MKMH_path[1,t+1]\n H = KH_path[1,t]\n X11 = X_path[0,t+1]\n X2 = X_path[2,t+1]\n MKt1, MHt1, Ht, X1t1, X2t = symbols('MKt1 MHt1 Ht X1t1 X2t')\n \"\"\"\n Ct is the explicit formula of consumption ratio process \n imported from function: solve_habit_persistence\n \"\"\"\n C = Ct.subs([(MKt1,MK1),\n (MHt1,MH1),\n (Ht,H),\n (X1t1,X11),\n (X2t,X2)])\n C_path[t] = C\n \n if MKMH_option: \n return C_path, Z_path, MKMH_path\n else:\n return C_path, Z_path"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Procesa una columna de la serie, calculando los valores de todas las transformaciones posibles para todos los intervalos de tiempo. Devuelve la lista de acciones (dicts) a indexar en Elasticsearch
|
def process_column(col, index):
# Filtro de valores nulos iniciales/finales
col = col[col.first_valid_index():col.last_valid_index()]
orig_freq = col.index.freq
series_id = col.name
actions = []
# Lista de intervalos temporales de pandas EN ORDEN
freqs = constants.PANDAS_FREQS
if orig_freq not in freqs:
raise ValueError(u'Frecuencia inválida: {}'.format(str(orig_freq)))
for freq in freqs:
# Promedio
avg = index_transform(col, lambda x: x.mean(), index, series_id, freq, 'avg')
actions.extend(avg.values.flatten())
if orig_freq == freq:
for row in avg: # Marcamos a estos datos como los originales
row['_source']['raw_value'] = True
break
# Suma
_sum = index_transform(col, sum, index, series_id, freq, 'sum')
actions.extend(_sum.values.flatten())
# End of period
eop = index_transform(col, end_of_period, index, series_id, freq, 'end_of_period')
actions.extend(eop.values.flatten())
return actions
|
[
"def map_func(row):\n return (row[\"device_id\"], row[\"indexed_ts\"]), row",
"def _extract(self, ix, column):\n _df = (\n self.df[ix][self.years + [column]]\n .set_index(column)\n .transpose()\n .applymap(convert)\n )\n _df.columns.name = \"\"\n _df.index = self.daterange\n return _df",
"def make_units_index(row):\n\n\tunits = {}\n\tfor field in row:\n\t\tunits[field] = row[field][0]\n\n\treturn units",
"def time(self, row: typing.Iterable) -> float:",
"def normalize_index(phyche_index, is_convert_dict=False):\n normalize_phyche_value = []\n for phyche_value in phyche_index:\n average_phyche_value = sum(phyche_value) * 1.0 / len(phyche_value)\n sd_phyche = standard_deviation(phyche_value)\n normalize_phyche_value.append([round((e - average_phyche_value) / sd_phyche, 2) for e in phyche_value])\n\n return normalize_phyche_value",
"def get_value_timeseries():\n\n\n value_data = (db.session.query(ValueItem)\n .join(UserValueType)\n .join(UserCondition)\n .filter(UserValueType.is_tracked==True,\n ValueItem.value > 0,\n UserCondition.user_id==session['userid'])\n .order_by(ValueItem.value_date)\n .order_by(UserValueType.usercond_id)\n .all())\n\n value_data_list = []\n for value_item in value_data:\n user_value_name = value_item.user_value_type.value_type.value_name\n value_data_list.append({\"name\": user_value_name,\n \"date\": str(value_item.value_date.date()),\n \"value\": float(value_item.value)})\n\n\n return(jsonify(value_data_list))",
"def normalizar(data):\n for i in range(len(data[0])):\n minimo, maximo = buscar_min_max_a_traves_de_columnas(data, i)\n for instancia in data:\n instancia[i] = (instancia[i] - minimo)/(maximo - minimo)",
"def elasticsearch_pull(start_date, end_date):\n # start_time = time.time()\n if type(start_date) == str:\n # Format date strings to datetime objects\n start_date = datetime.datetime.strptime(start_date, \"%m-%d-%Y\")\n start_date = datetime.datetime.combine(start_date, datetime.datetime.min.time())\n end_date = datetime.datetime.strptime(end_date, \"%m-%d-%Y\")\n end_date = datetime.datetime.combine(end_date, datetime.datetime.max.time())\n\n print(\"Start date : \" + str(start_date))\n print(\"End date : \" + str(end_date))\n # datetime to epoch. Epoch format needed for elastic query\n epoch_start = int(start_date.strftime(\"%s\")) * 1000\n epoch_end = int(end_date.strftime(\"%s\")) * 1000\n else:\n # datetime to epoch. Epoch format needed for elastic query\n epoch_start = int(start_date.strftime(\"%s\")) * 1000\n epoch_end = int(end_date.strftime(\"%s\")) * 1000\n\n print(\"Epoch start : \" + str(epoch_start))\n print(\"Epoch end : \" + str(epoch_end))\n \n \n # Return results of elastic query and format data to dictionary structures\n results = retrieve_elastic_response(epoch_start, epoch_end)\n#################################\n# import pprint\n# pp = pprint.PrettyPrinter(indent=4)\n# pp.pprint(results)\n#################################\n data_array = results_to_formatted_dicts(results)\n \n # Get relative size of data and initiate values\n total_results = results[\"hits\"][\"total\"]\n total_results_length = len(total_results)\n size_results_pulled = len(results[\"hits\"][\"hits\"])\n check_timestamp = 0\n attempt_timestamp = 1\n attempt_index = -2\n try:\n # Start array from first index with a different timestamp than the last element\n check_timestamp = [data_array[-1][\"epoch_timestamp\"]]\n attempt_timestamp = [data_array[attempt_index][\"epoch_timestamp\"]]\n except IndexError:\n sys.exit(\"Oops! Data array from Elasticsearch is empty. Please check Narrative Container logs in Kibana for input date range.\")\n while check_timestamp == attempt_timestamp and (\n (total_results_length + attempt_index) > 0\n ):\n attempt_index -= 1\n attempt_timestamp = [data_array[attempt_index][\"epoch_timestamp\"]]\n timestamp = attempt_timestamp\n\n while size_results_pulled < total_results_length:\n results_sequential = retrieve_elastic_response(\n epoch_start, epoch_end, timestamp\n )\n data_additional = results_to_formatted_dicts(results_sequential)\n\n # Increment data counts\n size_results_pulled += len(results_sequential[\"hits\"][\"hits\"])\n # Start array from first index with a different timestamp than the last element\n try:\n check_timestamp = [data_additional[-1][\"epoch_timestamp\"]]\n attempt_index = -2\n attempt_timestamp = [data_additional[attempt_index][\"epoch_timestamp\"]]\n while check_timestamp == attempt_timestamp:\n attempt_index -= 1\n attempt_timestamp = [data_additional[attempt_index][\"epoch_timestamp\"]]\n timestamp = attempt_timestamp\n except:\n pass\n data_array.extend(data_additional)\n\n # print(\"Elasticsearch data took from {}-{} took {} seconds to retrieve\".format(start_date, end_date, time.time() - start_time))\n print(\"Total number of records : \" + str(len(data_array)))\n return data_array",
"def index(self):\n if self.query['queryType'] == 'scan':\n if not self.query.get('columns') or '__time' in self.query['columns']:\n return ['__time']\n return []\n if self.query['queryType'] in {'groupBy', 'topN', 'timeseries'}:\n index_fields = [] if self.query['granularity'] == 'all' else ['timestamp']\n if self.query['queryType'] == 'groupBy':\n return index_fields + self.query['dimensions']\n elif self.query['queryType'] == 'topN':\n return index_fields + [self.query['dimension']]\n elif self.query['queryType'] == 'timeseries':\n return index_fields",
"def get_model_data_per_date(date):",
"def get_for_indexer(self, value):",
"def elastic_summary_dictionaries(\n str_date=datetime.datetime.combine(yesterday, datetime.datetime.min.time()),\n end_date=datetime.datetime.combine(yesterday, datetime.datetime.max.time()),\n):\n # start_time = time.time()\n\n # Pull elastic results, drop duplicates from backtracking timestamps in elastic queries,\n # and format timestamp to readable datetime format\n elastic_dictionaries = elasticsearch_pull(str_date, end_date)\n elastic_data_df = pd.DataFrame.from_dict(elastic_dictionaries)\n elastic_data_df.drop_duplicates(inplace=True)\n elastic_data_df[\"last_seen\"] = pd.to_datetime(\n elastic_data_df[\"last_seen\"], format=\"%a %b %d %H:%M:%S %Y\"\n )\n # Split query results by day\n DFList = [\n group[1] for group in elastic_data_df.groupby(elastic_data_df.last_seen.dt.day)\n ]\n user_activity_array = []\n # Iterate for day of elastic results activity picked up by the elasticquery\n for index, elastic_data in enumerate(DFList):\n\n # Get list of users to iterate over for day\n users = list(set(list(elastic_data.session_id)))\n for user in users:\n # Set user condition for data\n user_condition = elastic_data.session_id == user\n user_data = elastic_data[user_condition]\n # Get users ip's and check if used ip's > 1\n unique_ips = set(list(user_data.ip))\n\n if len(unique_ips) > 1:\n for ip in unique_ips:\n # Get all results for user on specific ip\n ip_cond = user_data.ip == ip\n user_ip_data = user_data[ip_cond]\n # Check system usage as active\n system_usage = list(set(list(user_ip_data.last_seen)))\n if len(system_usage) > 1:\n # make summary dictionary and append dictionary to data array\n ip_specfic_dict = make_user_activity_dict(\n user_ip_data, ip, user\n )\n user_activity_array.append(ip_specfic_dict)\n else:\n continue\n # else same as above without the ip iteration\n else:\n system_usage = list(set(list(user_data.last_seen)))\n if len(system_usage) > 1:\n ip = list(user_data.ip)[0]\n user_dict = make_user_activity_dict(user_data, ip, user)\n user_activity_array.append(user_dict)\n else:\n continue\n # print(\"Elasticsearch summary dictionaries took \", time.time() - start_time, \" seconds to run\")\n return user_activity_array",
"def dict_to_datetimedf(input_dict,sampling_time,res_type):\r\n from datetime import datetime\r\n #get df\r\n df_out = pd.DataFrame()\r\n for var in input_dict:\r\n if len(var[\"time\"]) < 3:\r\n df_out[var[\"variable\"]] = float(var[\"value\"][0])\r\n else: \r\n df_out[var[\"variable\"]] = var[\"value\"]\r\n df_out[\"time\"] = var[\"time\"]\r\n \r\n #convert df index into datetime\r\n first_date = int(datetime(datetime.now().year, 1, 1).timestamp())\r\n if res_type == \"raw\":\r\n df_out = df_out.set_index(df_out[\"time\"])\r\n df_out_res = df_out\r\n else: \r\n df_out = df_out.set_index(pd.to_datetime(df_out[\"time\"]*10**9)+ \r\n pd.DateOffset(seconds = first_date+3600))\r\n \r\n #Resample data at chosen interval with given resampler\r\n if res_type == \"sum\":\r\n df_out_res = df_out.resample(str(sampling_time)+\"S\", \r\n closed = \"left\", label = \"left\").sum()\r\n elif res_type == \"mean\":\r\n df_out_res = df_out.resample(str(sampling_time)+\"S\",\r\n closed = \"left\", label = \"left\").mean()\r\n else:\r\n raise Exception(\"Operazione errata: \" + str(res_type))\r\n \r\n return df_out_res",
"def map_to_es(self):\n full_name = self.query_path\n return set_default(\n {\n c.names[full_name]: c.es_column\n for k, cs in self.lookup.items()\n # if startswith_field(k, full_name)\n for c in cs if c.jx_type not in STRUCT\n },\n {\n c.names[\".\"]: c.es_column\n for k, cs in self.lookup.items()\n # if startswith_field(k, full_name)\n for c in cs if c.jx_type not in STRUCT\n }\n )",
"def datalist(self,model):\n calender = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}\n data = model.objects.filter(owner=self.request.user).values().order_by('date')\n a= 0\n d= []\n \n for i in data:\n g={}\n for j in i:\n if j=='date':\n \n d_obj = i[j]\n d_day = d_obj.day\n d_month = calender[d_obj.month]\n d_year = d_obj.year\n g['label'] =str(d_month)+' '+str(d_day)+', '+str(d_year)\n \n elif j=='weight':\n w_obj = i[j]\n g['y'] = w_obj\n \n d.append(g)\n\n \n \n return d",
"def multi_temp_task_table_calc(non_empty_rows):\n multi_task_data = []\n for task in ['work','meditation','movement','break','total']: \n row = {}\n row['task']=task\n row[task+'_numeric']=sum([session[task+'_numeric'] for session in non_empty_rows])\n if row[task+'_numeric']==0:\n continue\n row['string']=timedelta_to_string(datetime.timedelta(minutes=np.float64(row[task+'_numeric'])))\n multi_task_data.append(row)\n return multi_task_data",
"def __transform_data(data:list) -> list:\n return tuple(chain.from_iterable((\n ([time] * value) # the value at x-axis must appears value time in data\n for time, value in enumerate(data)\n )))",
"def linearize_table(self):\n pass",
"def map_values(data, column, mapping, **kwargs):\r\n data_column = data.loc[:, column]\r\n mapper = np.vectorize(lambda x: mapping.get(x, x))\r\n data.loc[:, column] = mapper(data_column)\r\n # data[1][:, field_index] = mapper(data[1][:, field_index])\r\n return data"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Sum and product of two numbers
|
def sumproduct(x, y):
return (x+y, x*y)
|
[
"def product(num1, num2):\n\treturn num1 * num2",
"def calculate_product(val1, val2):\n return val1 * val2",
"def prod(numbers: Sequence[number_t]) -> number_t:\n return reduce(_operator.mul, numbers)",
"def product(numbers):\n return reduce(mul, numbers, 1)",
"def scalar_prod(a,b):\n res=0\n for i in range(len(a)):\n res+=a[i]*b[i]\n return res",
"def sum(a, b):\n return a + b",
"def suma_dos_numeros(a, b):\n resultado = a + b\n return resultado",
"def sum(num1, num2):\n\treturn num1 + num2",
"def dot_product(v1, v2):\n return sum(num1 * num2 for num1, num2 in zip(v1, v2))",
"def inner_prod(v1, v2):\n summ = 0\n for i in range(v1):\n summ += v1[i] * v2[i]\n return summ",
"def dot_product(u, v):\n return sum([u * v for (u, v) in zip(u, v)])",
"def multiplyMyNumbers(a, b):\n return str(convert_num(a) * convert_num(b))",
"def add_mult(num1, num2, num3):\n sum1 = num1 + num2\n return sum1 * num3",
"def multiplyAndAdd(n, m):\n\treturn (n + 5) * (m + 7)",
"def default_scalar_prod(vector1, vector2):\r\n\tres = 0\r\n\tv = zip(vector1, vector2)\r\n\tfor i in v:\r\n\t\tres += i[0]*i[1]\r\n\treturn res",
"def add(p1, p2):\n return (p2[0] + p1[0], p2[1] + p1[1])",
"def sum_of_multiplies(first_num, second_num, limit) -> int:\n list_of_nums = []\n total = 0\n for numb in range(first_num, limit + 1, first_num):\n list_of_nums.append(numb)\n for numb in range(second_num, limit + 1, second_num):\n if numb not in list_of_nums:\n list_of_nums.append(numb)\n for elem in list_of_nums:\n total += elem\n return total",
"def sum1(num1, num2):\n return num1+num2",
"def sum_points(a, b):\n return a[0] + b[0], a[1] + b[1]"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
This function takes in the 3D matrix of the satellite data, as well as the minimum values of the latitude and longitude, the spacing and shape of common grid. For each band it creates an empty array which has the size od the common grid. It creates indices for lat and lon from the original satellite image. Then it populates the common grid with the pixels from original image using nearest neighbour (distance) function.
|
def regridding(image_data, min_lon, min_lat, spacing, shape_common_grid):
# create an empty m x n array for each channel
band_data = np.zeros((shape_common_grid)) ####define for each band
band_data = band_data[0,:,:]
band1_data = copy.copy(band_data) #band_data[0,:,:]
band2_data = copy.copy(band_data) #band_data[0,:,:]
band3_data = copy.copy(band_data) #band_data[0,:,:]
band4_data = copy.copy(band_data) #band_data[0,:,:]
band5_data = copy.copy(band_data) #band_data[0,:,:]
band6_data = copy.copy(band_data) #band_data[0,:,:]
band7_data = copy.copy(band_data) #band_data[0,:,:]
#band8_data = copy.copy(band_data) #band_data[0,:,:]
band9_data = copy.copy(band_data) #band_data[0,:,:]
band10_data = copy.copy(band_data) #band_data[0,:,:]
band11_data = copy.copy(band_data) #band_data[0,:,:]
# a count array of the same size
C = np.zeros((shape_common_grid),dtype=np.int) ### this only one
C = C[0,:,:]
# a distance array
D = np.zeros((shape_common_grid))
D = D[0,:,:]
# take arrays of full resolution input
im_lat = image_data[0,:,:]
im_lon = image_data[1,:,:]
data1 = image_data[2,:,:]
data2 = image_data[3,:,:]
data3 = image_data[4,:,:]
data4 = image_data[5,:,:]
data5 = image_data[6,:,:]
data6 = image_data[7,:,:]
data7 = image_data[8,:,:]
#data8 = image_data[9,:,:]
data9 = image_data[9,:,:]
data10 = image_data[10,:,:]
data11 = image_data[11,:,:]
# transform lat and lon arrays
# by subtracting the minimum value from the common grid
# and dividing by spacing of common grid
lat_transf = (im_lat - min_lat) / spacing
lon_transf = (im_lon - min_lon) / spacing
# round down the values from transf arrays
lat_rounded = np.floor(lat_transf)
lon_rounded = np.floor(lon_transf)
print("lat_rounded", lat_rounded)
print("lon_rounded", lon_rounded)
# index of the original image lat and lon
# go through entire x and y for image data
# see if they are all positive integers
# 0 is a valid number
for (i,j), q in np.ndenumerate(lat_rounded):
i = int(i)
j = int(j)
p = int(lon_rounded[i,j])
q = int(lat_rounded[i,j])
if q >= 0 and q <= 400 and p >=0 and p <= 400:
if C[p,q] == 0:
band1_data[p,q] = data1[i,j]
band2_data[p,q] = data2[i,j]
band3_data[p,q] = data3[i,j]
band4_data[p,q] = data4[i,j]
band5_data[p,q] = data5[i,j]
band6_data[p,q] = data6[i,j]
band7_data[p,q] = data7[i,j]
#band8_data[p,q] = data8[i,j]
band9_data[p,q] = data9[i,j]
band10_data[p,q] = data10[i,j]
band11_data[p,q] = data11[i,j]
D[p,q] = distance(im_lat[i,j], im_lon[i,j], min_lat, min_lon, p, q, spacing)
C[p,q] = 1
#C[p,q] += 1
else:
d = distance(im_lat[i,j], im_lon[i,j], min_lat, min_lon, p, q, spacing)
if d < D[p,q]:
band1_data[p,q] = data1[i,j]
band2_data[p,q] = data2[i,j]
band3_data[p,q] = data3[i,j]
band4_data[p,q] = data4[i,j]
band5_data[p,q] = data5[i,j]
band6_data[p,q] = data6[i,j]
band7_data[p,q] = data7[i,j]
#band8_data[p,q] = data8[i,j]
band9_data[p,q] = data9[i,j]
band10_data[p,q] = data10[i,j]
band11_data[p,q] = data11[i,j]
D[p,q] = d
#else:
#print("p and q out of range") #### later can print p and q values
return np.concatenate([[band1_data], [band2_data], [band3_data], [band4_data], [band5_data], [band6_data], [band7_data], [band9_data], [band10_data], [band11_data]]), C, D
|
[
"def interpolate(m: np.ndarray, n: np.ndarray, sgrid: np.ndarray, points_on_sphere: np.ndarray, radius: np.ndarray):\n #print(\"Interpolate\")\n\n\n # =========================\n center_grid = np.zeros((m.shape[0],3))\n east_grid = np.zeros((m.shape[0],3))\n south_grid = np.zeros((m.shape[0],3))\n southeast_grid = np.zeros((m.shape[0],3))\n\n center_dist = np.zeros(m.shape[0])\n east_dist = np.zeros(m.shape[0])\n south_dist = np.zeros(m.shape[0])\n southeast_dist = np.zeros(m.shape[0])\n\n center_weight = np.zeros(m.shape[0])\n east_weight = np.zeros(m.shape[0])\n south_weight = np.zeros(m.shape[0])\n southeast_weight = np.zeros(m.shape[0])\n\n # use a mask to select the point on the boundary============================\n mask_north = m == 0\n mask_south = m == sgrid.shape[0] - 1\n mask_boundary = mask_north + mask_south\n m_boundary = m[mask_boundary]\n n_boundary = n[mask_boundary] % sgrid.shape[1]\n n_boundary_plus_one = (n_boundary + 1) % sgrid.shape[1]\n n_boundary_opposite = (n_boundary + (sgrid.shape[1] / 2)) % sgrid.shape[1]\n n_boundary_opposite=n_boundary_opposite.astype(int)\n n_boundary_plus_one_opposite = (n_boundary_plus_one + (sgrid.shape[1] / 2))%sgrid.shape[1]\n n_boundary_plus_one_opposite=n_boundary_plus_one_opposite.astype(int)\n center_grid[mask_boundary] = sgrid[m_boundary, n_boundary]\n east_grid[mask_boundary] = sgrid[m_boundary, n_boundary_plus_one]\n south_grid[mask_boundary] = sgrid[m_boundary, n_boundary_opposite]\n southeast_grid[mask_boundary] = sgrid[m_boundary, n_boundary_plus_one_opposite]\n\n # calculate distance and relevant weight\n center_dist[mask_boundary] = np.sqrt(np.sum((center_grid[mask_boundary] - points_on_sphere[mask_boundary]) ** 2))\n east_dist[mask_boundary] = np.sqrt(np.sum((east_grid[mask_boundary] - points_on_sphere[mask_boundary]) ** 2))\n south_dist[mask_boundary] = np.sqrt(np.sum((south_grid[mask_boundary] - points_on_sphere[mask_boundary]) ** 2))\n southeast_dist[mask_boundary] = np.sqrt(\n np.sum((southeast_grid[mask_boundary] - points_on_sphere[mask_boundary]) ** 2))\n sum = center_dist[mask_boundary] + east_dist[mask_boundary] + south_dist[mask_boundary] + southeast_dist[\n mask_boundary]\n center_weight[mask_boundary] = center_dist[mask_boundary] / sum\n east_weight[mask_boundary] = east_dist[mask_boundary] / sum\n south_weight[mask_boundary] = south_dist[mask_boundary] / sum\n southeast_weight[mask_boundary] = southeast_dist[mask_boundary] / sum\n\n # save the signal of distance\n radius_boundary = radius[mask_boundary]\n dist_im = np.zeros(sgrid.shape[0:2]) # signal of distance from points to sphere\n weight_im = np.zeros(sgrid.shape[\n 0:2]) # Since each grid point on the sphere could be affected by several different signals, we need to normalize the values.\n dist_im[m_boundary, n_boundary] += radius_boundary[:, 0] * center_weight[mask_boundary]\n dist_im[m_boundary, n_boundary_plus_one] += radius_boundary[:, 0] * east_weight[mask_boundary]\n dist_im[m_boundary, n_boundary_opposite] += radius_boundary[:, 0] * south_weight[mask_boundary]\n dist_im[m_boundary, n_boundary_plus_one_opposite] += radius_boundary[:, 0] * southeast_weight[mask_boundary]\n weight_im[m_boundary, n_boundary] += center_weight[mask_boundary]\n weight_im[m_boundary, n_boundary_plus_one] += east_weight[mask_boundary]\n weight_im[m_boundary, n_boundary_opposite] += south_weight[mask_boundary]\n weight_im[m_boundary, n_boundary_plus_one_opposite] += southeast_weight[mask_boundary]\n\n # use a mask to select the rest points===============================\n mask_rest = ~mask_boundary\n m_rest = m[mask_rest]\n n_rest = n[mask_rest] % sgrid.shape[1]\n n_rest_plus_one = (n_rest + 1) % sgrid.shape[1]\n center_grid[mask_rest] = sgrid[m_rest, n_rest]\n east_grid[mask_rest] = sgrid[m_rest, n_rest_plus_one]\n south_grid[mask_rest] = sgrid[m_rest + 1, n_rest]\n southeast_grid[mask_rest] = sgrid[m_rest + 1, n_rest_plus_one]\n\n # calculate distance and relevant weight\n center_dist[mask_rest] = np.sqrt(np.sum((center_grid[mask_rest] - points_on_sphere[mask_rest]) ** 2))\n east_dist[mask_rest] = np.sqrt(np.sum((east_grid[mask_rest] - points_on_sphere[mask_rest]) ** 2))\n south_dist[mask_rest] = np.sqrt(np.sum((south_grid[mask_rest] - points_on_sphere[mask_rest]) ** 2))\n southeast_dist[mask_rest] = np.sqrt(np.sum((southeast_grid[mask_rest] - points_on_sphere[mask_rest]) ** 2))\n sum = center_dist[mask_rest] + east_dist[mask_rest] + south_dist[mask_rest] + southeast_dist[mask_rest]\n center_weight[mask_rest] = center_dist[mask_rest] / sum\n east_weight[mask_rest] = east_dist[mask_rest] / sum\n south_weight[mask_rest] = south_dist[mask_rest] / sum\n southeast_weight[mask_rest] = southeast_dist[mask_rest] / sum\n\n # save the signal of distance\n radius_rest = radius[mask_rest]\n dist_im = np.zeros(sgrid.shape[0:2]) # signal of distance from points to sphere\n weight_im = np.zeros(sgrid.shape[\n 0:2]) # Since each grid point on the sphere could be affected by several different signals, we need to normalize the values.\n dist_im[m_rest, n_rest] += radius_rest[:, 0] * center_weight[mask_rest]\n dist_im[m_rest, n_rest_plus_one] += radius_rest[:, 0] * east_weight[mask_rest]\n dist_im[m_rest + 1, n_rest] += radius_rest[:, 0] * south_weight[mask_rest]\n dist_im[m_rest + 1, n_rest_plus_one] += radius_rest[:, 0] * southeast_weight[mask_rest]\n weight_im[m_rest, n_rest] += center_weight[mask_rest]\n weight_im[m_rest, n_rest_plus_one] += east_weight[mask_rest]\n weight_im[m_rest + 1, n_rest] += south_weight[mask_rest]\n weight_im[m_rest + 1, n_rest_plus_one] += southeast_weight[mask_rest]\n\n mask_weight = weight_im != 0\n dist_im[mask_weight] /= weight_im[mask_weight]\n dist_im = 1 - dist_im\n return dist_im, center_grid, east_grid, south_grid, southeast_grid",
"def create_grid(data, drone_altitude, safety_distance):#, resolution):\r\n\r\n # minimum and maximum north coordinates\r\n north_min = np.floor(np.min(data[:, 0] - data[:, 3]))\r\n north_max = np.ceil(np.max(data[:, 0] + data[:, 3]))\r\n\r\n # minimum and maximum east coordinates\r\n east_min = np.floor(np.min(data[:, 1] - data[:, 4]))\r\n east_max = np.ceil(np.max(data[:, 1] + data[:, 4]))\r\n\r\n # given the minimum and maximum coordinates we can\r\n # calculate the size of the grid.\r\n north_size = int(np.ceil((north_max - north_min)))#/resolution))\r\n east_size = int(np.ceil((east_max - east_min)))#/resolution))\r\n\r\n # Initialize an empty grid\r\n grid = np.zeros((north_size, east_size))\r\n\r\n # Populate the grid with obstacles\r\n for i in range(data.shape[0]):\r\n north, east, alt, d_north, d_east, d_alt = data[i, :]\r\n if alt + d_alt + safety_distance > drone_altitude:\r\n obstacle = [\r\n int(np.clip(north - d_north - safety_distance - north_min, 0, north_size-1)),\r\n int(np.clip(north + d_north + safety_distance - north_min, 0, north_size-1)),\r\n int(np.clip(east - d_east - safety_distance - east_min, 0, east_size-1)),\r\n int(np.clip(east + d_east + safety_distance - east_min, 0, east_size-1)),\r\n ]\r\n grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = 1\r\n\r\n return grid, int(north_min), int(east_min)",
"def common_grid(wavelist):\n wavelist = sorted(wavelist, key = lambda w: w[0])\n\n #succesively add each grid to a master wavegrid\n #whereever the new one overlaps the old, pick whichever has fewer points\n we = wavelist[0]\n for wei in wavelist[1:]:\n #if no overlap, just app/prepend\n if we[-1] < wei[0]:\n we = np.append(we,wei)\n continue\n if we[0] > wei[-1]:\n we = np.append(wei,we)\n continue\n\n #identify where start and end of wei fall in we, and vise versa\n i0,i1 = np.searchsorted(we, wei[[0,-1]])\n j0,j1 = np.searchsorted(wei, we[[0,-1]])\n #we[i0:i1] is we overlap with wei, wei[j0:j1] is the opposite\n\n #pick whichever has fewer points (lower resolution) for the overlap\n Nwe, Nwei = i1-i0, j1-j0 #no of points for eachch in overlap\n if Nwe < Nwei:\n #get pieces of wei that fall outside of we\n wei_pre, _, wei_app = np.split(wei, [j0,j1])\n #stack with we. leave off endpts to avoid fractional bins at the\n #switchover points\n we = np.hstack([wei_pre[:-1], we, wei_app[1:]])\n else: #same deal\n we_pre, _, we_app = np.split(we, [i0,i1])\n we = np.hstack([we_pre[:-1], wei, we_app[1:]])\n\n return we",
"def regrid(self, new_size, input_lower_lon, input_upper_lon, input_lower_lat, input_upper_lat):\n# Get grid size in meters\n old_size = self.find_base_size()\n\n# Scaling factor is the ratio between the old size and the new size. If the\n# ratio is 4, than 16 times as many squares will be added to the new grid\n scaling_factor = old_size / new_size\n\n# Call wind_data to get 1D of data in a 2D space.\n wind_data = self.get_wind(input_lower_lon, input_upper_lon, input_lower_lat, input_upper_lat) #gather the wind data\n\n# Split wind_data into a list of lists where each list represents data for one row\n# The second input is hard coded based upon reasonable factor pairs of the total\n# length of the data\n wind_data = list(split_list(wind_data, 359))\n new_grid = []\n for sub_list_id, sub_list in enumerate(wind_data): #work through the old data set one row at a time\n counter = 0\n while counter < scaling_factor: #repeate this operation for scaling factor number of columns\n for id, val in enumerate(sub_list):\n if (id + 1) % 359 != 0: #i.e. not exceeded row length\n new_grid.extend([sub_list[id]] * int(scaling_factor)) #add the old value scaling factor number of times in one the row\n else:\n counter = counter + 1\n return new_grid",
"def create_grid(data, drone_altitude, safety_distance):\r\n\r\n # minimum and maximum north coordinates\r\n north_min = np.floor(np.min(data[:, 0] - data[:, 3]))\r\n north_max = np.ceil(np.max(data[:, 0] + data[:, 3]))\r\n\r\n # minimum and maximum east coordinates\r\n east_min = np.floor(np.min(data[:, 1] - data[:, 4]))\r\n east_max = np.ceil(np.max(data[:, 1] + data[:, 4]))\r\n\r\n # given the minimum and maximum coordinates we can\r\n # calculate the size of the grid.\r\n north_size = int(np.ceil(north_max - north_min))\r\n east_size = int(np.ceil(east_max - east_min))\r\n\r\n # Initialize an empty grid\r\n grid = np.zeros((north_size, east_size))\r\n\r\n # Populate the grid with obstacles\r\n for i in range(data.shape[0]):\r\n north, east, alt, d_north, d_east, d_alt = data[i, :]\r\n #if alt + d_alt > drone_altitude:\r\n obstacle = [\r\n int(np.clip(north - d_north - safety_distance - north_min, 0, north_size-1)),\r\n int(np.clip(north + d_north + safety_distance - north_min, 0, north_size-1)),\r\n int(np.clip(east - d_east - safety_distance - east_min, 0, east_size-1)),\r\n int(np.clip(east + d_east + safety_distance - east_min, 0, east_size-1)),\r\n ]\r\n #the \"dimension\" variable is to add height data to grid vs. simple 1/0\r\n grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = alt+d_alt\r\n\r\n return grid, int(north_min), int(east_min)",
"def latlon_meshgrid(hdul):\n\n # get the latitude and longitude arrays\n latitude = hdul['pixelgeometry'].data['pixel_corner_lat']\n longitude = hdul['pixelgeometry'].data['pixel_corner_lon']\n altitude = hdul['pixelgeometry'].data['pixel_corner_mrh_alt'][:, :, 4]\n\n # make meshgrids to hold latitude and longitude grids for pcolormesh display\n X = np.zeros((latitude.shape[0] + 1, latitude.shape[1] + 1))\n Y = np.zeros((longitude.shape[0] + 1, longitude.shape[1] + 1))\n mask = np.ones((latitude.shape[0], latitude.shape[1]))\n\n # loop through pixel geometry arrays\n for i in range(int(latitude.shape[0])):\n for j in range(int(latitude.shape[1])):\n\n # there are some pixels where some of the pixel corner longitudes are undefined\n # if we encounter one of those, set the data value to missing so it isn't displayed\n # with pcolormesh\n if np.size(np.where(np.isfinite(longitude[i, j]))) != 5:\n mask[i, j] = np.nan\n\n # also mask out non-disk pixels\n if altitude[i, j] != 0:\n mask[i, j] = np.nan\n\n # place the longitude and latitude values in the meshgrids\n X[i, j] = longitude[i, j, 1]\n X[i + 1, j] = longitude[i, j, 0]\n X[i, j + 1] = longitude[i, j, 3]\n X[i + 1, j + 1] = longitude[i, j, 2]\n Y[i, j] = latitude[i, j, 1]\n Y[i + 1, j] = latitude[i, j, 0]\n Y[i, j + 1] = latitude[i, j, 3]\n Y[i + 1, j + 1] = latitude[i, j, 2]\n\n # set any of the NaN values to zero (otherwise pcolormesh will break even if it isn't displaying the pixel).\n X[np.where(~np.isfinite(X))] = 0\n Y[np.where(~np.isfinite(Y))] = 0\n\n # set to domain [-180,180)\n X[np.where(X > 180)] -= 360\n\n # return the coordinate arrays and the mask\n return X, Y, mask",
"def test_interp(N, grid, ll_lat, ll_lon, dx, r):\n\n file_name = \"grid_l\" + str(N) + \"_\" + str(int(dx)) + \"x\" + str(int(dx)) + \"_weights.h5\"\n\n f= h5py.File(file_name, 'r')\n\n cols = f[\"column index\"]\n rows = f[\"row index\"]\n w = f[\"weights\"]\n\n map_matrix = csr_matrix((w, cols, rows), shape=(len(ll_lat)*len(ll_lon), 3*len(grid.nodes)))\n\n m = 2.\n n = 3.\n\n ll_x, ll_y = np.meshgrid(ll_lon, ll_lat)\n\n tf_ll = np.cos(m*ll_x) * np.cos(n*ll_y)**4. #+ 0.001*np.cos(3*m*ll_x) * np.cos(3*n*ll_y)\n\n gg_lat, gg_lon = np.array(grid.lats), np.array(grid.lons)\n triang = tri.Triangulation(gg_lon, gg_lat)\n\n tf_gg = np.cos(m*gg_lon) * np.cos(n*gg_lat)**4. #+ 0.001*np.cos(3*m*gg_lon) * np.cos(3*n*gg_lat)\n tf_gg_dlat = 1./r * (-4.*n*np.sin(n*gg_lat)*np.cos(n*gg_lat)**3. *np.cos(m*gg_lon)) #+ -3.*n*0.001*np.cos(3*m*gg_lon) * np.sin(3*n*gg_lat))\n tf_gg_dlon = 1./r * (-m*np.sin(m*gg_lon)*np.cos(n*gg_lat)**4. )/np.cos(gg_lat) #- 3.*m* 0.001*np.sin(3*m*gg_lon) * np.cos(3*n*gg_lat)\n\n gg_data = np.zeros(3*len(grid.nodes))\n ll_interp = np.zeros(len(ll_lat)*len(ll_lon))\n\n for i in range(len(grid.nodes)):\n gg_data[3*i] = tf_gg[i]\n gg_data[3*i + 1] = tf_gg_dlat[i]\n gg_data[3*i + 2] = tf_gg_dlon[i]\n\n ll_interp = map_matrix.dot(gg_data)\n ll_interp = np.reshape(ll_interp, (len(ll_lat), len(ll_lon)))\n\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols=4, figsize=(16,3.5))\n\n vmax = max(np.amax(ll_interp), max(np.amax(tf_ll), np.amax(tf_gg)))\n vmin = min(np.amin(ll_interp), min(np.amin(tf_ll), np.amin(tf_gg)))\n\n levels = np.linspace(vmin, vmax, 9)\n levels2 = 1e3*np.linspace(np.amin(ll_interp-tf_ll), np.amax(ll_interp-tf_ll), 9)\n\n axes = [ax1, ax2, ax3, ax4]\n\n # tf_ll2 = np.cos(m*ll_x) * np.cos(n*ll_y)**4.\n\n # tf_ll = np.cos(m*ll_x) * np.cos(n*ll_y)**4.\n\n c1 = ax1.contourf(ll_lon, ll_lat, tf_ll, levels=levels)\n c2 = ax2.tricontourf(triang, tf_gg, levels=levels)\n c3 = ax3.contourf(ll_lon, ll_lat, ll_interp, levels=levels)\n c4 = ax4.contourf(ll_lon, ll_lat, 1e3*(ll_interp-tf_ll))\n\n c = [c1, c2, c3, c4]\n\n for cb, ax in zip(c,axes):\n ax.set_ylim([-np.pi*0.5, np.pi*0.5])\n ax.set_aspect('equal')\n plt.colorbar(cb, ax=ax, orientation='horizontal')\n\n max_err = np.amax(abs(ll_interp-tf_ll))\n mean_err = np.mean(abs(ll_interp.flatten()-tf_ll.flatten()))\n\n print(\"Max error:\", max_err, \", Mean error:\", mean_err)\n\n ax1.set_title(\"Lat-lon grid (analytic)\")\n ax2.set_title(\"Geodesic grid (analytic)\")\n ax3.set_title(\"Interpolated solution\")\n ax4.set_title(\"Interpolated - analytic solution ($\\\\times 10^3$)\")\n\n fig.savefig(\"/home/hamish/Dropbox/Tests/conservative_interp_test_g6_1x1.pdf\")\n plt.show()\n\n return max_err, mean_err",
"def get_nc_Grid_GLORYS(grdfile, name='GLORYS_NWGOA', area='regional', \\\n irange=(270,460), jrange=(150, 328), ystart=245):\n\n nc = pyroms.io.Dataset(grdfile)\n\n lon_t = nc.variables['longitude'][:]\n lat_t = nc.variables['latitude'][:]\n\n depth = nc.variables['depth'][:]\n# depth_w = nc.variables['gdepw_0'][:]\n depth_bnds = np.zeros(depth.shape[0]+1)\n# depth_bnds[:-1] = depth_w[:]\n depth_bnds[-1] = 6000.\n\n nc_mask_t = nc.variables['zos']\n# mask_t = np.array(~nc_mask_t[:].mask, dtype='int')\n mask_t = np.where(np.array(nc_mask_t[:], dtype='int')==nc_mask_t._FillValue, 0, 1)\n# pdb.set_trace()\n nc_mask_t = nc.variables['thetao']\n\n bottom = pyroms.utility.get_bottom(nc_mask_t[0,::-1,:,:], mask_t[0,:], spval=nc_mask_t._FillValue)\n nlev = mask_t.shape[0]\n bottom = (nlev-1) - bottom\n h = np.zeros(mask_t[0,:].shape)\n for i in range(mask_t[0,:].shape[1]):\n for j in range(mask_t[0,:].shape[0]):\n if mask_t[0,j,i] == 1:\n h[j,i] = depth_bnds[int(bottom[j,i])]\n\n if area == 'global':\n #add rows in the north and the south, east and west\n lon_t = lon_t[:,np.r_[0,:np.size(lon_t,1),-1]]\n lon_t[:,0] = lon_t[:,1] - (lon_t[:,2]-lon_t[:,1])\n lon_t[:,-1] = lon_t[:,-2] + (lon_t[:,-2]-lon_t[:,-3])\n lon_t = lon_t[np.r_[0,0,:np.size(lon_t,0),-1,-1]]\n\n lat_t = lat_t[np.r_[0,0,:np.size(lat_t,0),-1,-1]]\n lat_t[-1,:] = -80\n lat_t[0,:] = -85\n lat_t[-2,:] = lat_t[-3,:]\n lat_t[-1,:] = lat_t[-4,:]\n lat_t = lat_t[:,np.r_[0,:np.size(lat_t,1),-1]]\n\n mask_t = mask_t[:,np.r_[0,0,:np.size(mask_t,1),-1,-1],:]\n mask_t = mask_t[:,:,np.r_[0,:np.size(mask_t,2),-1]]\n mask_t[:,:,0] = mask_t[:,:,-2]\n mask_t[:,:,-1] = mask_t[:,:,1]\n h = h[np.r_[0,0,:np.size(h,0),-1,-1]]\n h = h[:,np.r_[0,:np.size(h,1),-1]]\n h[:,0] = h[:,-2]\n h[:,-1] = h[:,1]\n m,l = h.shape\n irange=(1,l-2)\n jrange=(1,m-2)\n\n if area == 'npolar':\n #add rows in the north and the south, east and west\n lon_t = lon_t[:,np.r_[0,:np.size(lon_t,1),-1]]\n lon_t[:,0] = lon_t[:,1] - (lon_t[:,2]-lon_t[:,1])\n lon_t[:,-1] = lon_t[:,-2] + (lon_t[:,-2]-lon_t[:,-3])\n lon_t = lon_t[np.r_[0,0,:np.size(lon_t,0),-1,-1]]\n\n lat_t = lat_t[np.r_[0,0,:np.size(lat_t,0),-1,-1]]\n lat_t[-1,:] = -80\n lat_t[0,:] = -85\n lat_t[-2,:] = lat_t[-3,:]\n lat_t[-1,:] = lat_t[-4,:]\n lat_t = lat_t[:,np.r_[0,:np.size(lat_t,1),-1]]\n\n mask_t = mask_t[:,np.r_[0,0,:np.size(mask_t,1),-1,-1],:]\n mask_t = mask_t[:,:,np.r_[0,:np.size(mask_t,2),-1]]\n mask_t[:,:,0] = mask_t[:,:,-2]\n mask_t[:,:,-1] = mask_t[:,:,1]\n h = h[np.r_[0,0,:np.size(h,0),-1,-1]]\n h = h[:,np.r_[0,:np.size(h,1),-1]]\n h[:,0] = h[:,-2]\n h[:,-1] = h[:,1]\n m,l = h.shape\n irange=(1,l-2)\n jrange=(ystart+2,m-2)\n\n return Grid_GLORYS(lon_t, lat_t, mask_t, depth, depth_bnds, h, \\\n name, irange, jrange)",
"def create_grid_gebco():\n increment = np.float64(1) / np.float64(240)\n half = np.float64(1) / np.float64(2)\n nx=360*240\n ny=180*240\n # longitude\n lonmin = np.float64(-180.)\n lonmax = np.float64(180.)\n #lon_center = np.empty((nx), dtype=np.float64)\n #lon_center[0] = lonmin + half * increment\n #for k in range(1,nx):\n # lon_center[k] = lon_center[0] + (k * increment)\n lon_edges = np.empty((nx+1), dtype=np.float64)\n lon_edges[0] = lonmin\n for k in range(1,nx+1):\n lon_edges[k] = lon_edges[0] + (k * increment)\n\n lon_center = half * lon_edges[1:] + half * lon_edges[:-1]\n\n # latitude\n latmin = np.float64(-90.)\n latmax = np.float64(90.)\n lat_center = np.empty((ny), dtype=np.float64)\n lat_center[0] = latmin + half * increment\n for k in range(1,ny):\n lat_center[k] = lat_center[0] + (k * increment)\n\n\n ds = xr.Dataset()\n ds['lon'] = xr.DataArray(data=lon_center, dims=('lon'))\n ds['lat'] = xr.DataArray(data=lat_center, dims=('lat'))\n ds['lon'].attrs = {'standard_name': \"longitude\",\n 'long_name': \"longitude\",\n 'units': \"degrees_east\"}\n ds['lat'].attrs = {'standard_name': \"latitude\",\n 'long_name': \"latitude\",\n 'units': \"degrees_north\"}\n return ds",
"def match_det2cube_msm(naxis1, naxis2, naxis3,\n cdelt1, cdelt2,\n zcdelt3,\n xcenters, ycenters, zcoord,\n spaxel_flux,\n spaxel_weight,\n spaxel_iflux,\n flux,\n coord1, coord2, wave,\n rois_pixel, roiw_pixel, weight_pixel, softrad_pixel):\n\n nplane = naxis1 * naxis2\n\n# now loop over the pixel values for this region and find the spaxels that fall\n# withing the region of interest.\n nn = coord1.size\n\n# ilow = 0\n# ihigh = 0\n# imatch = 0\n# print('looping over n points mapping to cloud',nn)\n#________________________________________________________________________________\n for ipt in range(0, nn - 1):\n#________________________________________________________________________________\n # xcenters, ycenters is a flattened 1-D array of the 2 X 2 xy plane\n # cube coordinates.\n # find the spaxels that fall withing ROI of point cloud defined by\n # coord1,coord2,wave\n lower_limit = softrad_pixel[ipt]\n xdistance = (xcenters - coord1[ipt])\n ydistance = (ycenters - coord2[ipt])\n radius = np.sqrt(xdistance * xdistance + ydistance * ydistance)\n indexr = np.where(radius <= rois_pixel[ipt])\n indexz = np.where(abs(zcoord - wave[ipt]) <= roiw_pixel[ipt])\n\n # on the wavelength boundaries the point cloud may not be in the IFUCube\n # the edge cases are skipped and not included in final IFUcube.\n # Left commented code for checking later for NIRSPEC the spectral size\n # in the reference file may be too small\n# if len(indexz[0]) == 0:\n# if wave[ipt] < zcoord[0]:\n# ilow = ilow + 1\n# elif wave[ipt] > zcoord[-1]: \n# ihigh = ihigh + 1\n# else:\n# imatch = imatch + 1\n# print(' no z match found ',wave[ipt],roiw_pixel[ipt])\n# print(zcoord[naxis3-11:naxis3])\n# diff = abs(zcoord[naxis3-11:naxis3] - wave[ipt])\n# print(diff)\n# exit()\n if len(indexz[0]) > 0:\n d1 = np.array(coord1[ipt] - xcenters[indexr]) / cdelt1\n d2 = np.array(coord2[ipt] - ycenters[indexr]) / cdelt2\n d3 = np.array(wave[ipt] - zcoord[indexz]) / zcdelt3[indexz]\n\n dxy = (d1 * d1) + (d2 * d2)\n\n # shape of dxy is #indexr or number of overlaps in spatial plane\n # shape of d3 is #indexz or number of overlaps in spectral plane\n # shape of dxy_matrix & d3_matrix (#indexr, #indexz)\n # rows = number of overlaps in spatial plane\n # cols = number of overlaps in spectral plane\n dxy_matrix = np.tile(dxy[np.newaxis].T, [1, d3.shape[0]])\n d3_matrix = np.tile(d3 * d3, [dxy_matrix.shape[0], 1])\n\n wdistance = dxy_matrix + d3_matrix\n weight_distance = np.power(np.sqrt(wdistance), weight_pixel[ipt])\n weight_distance[weight_distance < lower_limit] = lower_limit\n weight_distance = 1.0 / weight_distance\n weight_distance = weight_distance.flatten('F')\n weighted_flux = weight_distance * flux[ipt]\n\n icube_index = [iz * nplane + ir for iz in indexz[0] for ir in indexr[0]]\n spaxel_flux[icube_index] = spaxel_flux[icube_index] + weighted_flux\n spaxel_weight[icube_index] = spaxel_weight[icube_index] + weight_distance\n spaxel_iflux[icube_index] = spaxel_iflux[icube_index] + 1",
"def define_lat_lon_grid(lon_min,lon_max,lat_min,lat_max):\n \n\n xlim = [lon_min,lon_max]; ylim = [lat_min,lat_max]\n ilat = np.where((lat>ylim[0])&(lat<ylim[1]))[0]\n ilon = np.where((lon>xlim[0])&(lon<xlim[1]))[0]\n\n latitude = lat[ilat]\n longitude = lon[ilon]\n\n\n lat2,lon2 = np.meshgrid(latitude,longitude)\n \n return ilat,ilon, latitude,longitude, lat2,lon2",
"def init_cluster_regular(rows,columns,ki,img,bands):\n\n N = rows * columns\n \n #Setting up SLIC \n S = int((N/ki)**0.5) \n base = int(S/2)\n \n # Recompute k\n k = numpy.floor(rows/base)*numpy.floor(columns/base);\n\n # Allocate memory and initialise clusters, labels and distances.\n C = numpy.zeros([int(k),bands+3]) # Cluster centre data 1:times is mean on each band of series\n # times+1 and times+2 is row, col of centre, times+3 is No of pixels\n l = -numpy.ones([rows,columns]) # Matrix labels.\n d = numpy.full([rows,columns], numpy.inf) # Pixel distance matrix from cluster centres.\n\n vSpacing = int(numpy.floor(rows / ki**0.5))\n hSpacing = int(numpy.floor(columns / ki**0.5))\n\n kk=0\n\n # Initialise grid\n for x in range(base, rows, vSpacing):\n for y in range(base, columns, hSpacing):\n cc = int(numpy.floor(y)); rr = int(numpy.floor(x))\n ts = img[:,int(x),int(y)]\n st = numpy.append(ts,[int(x),int(y),0])\n C[kk, :] = st\n kk = kk+1\n \n w = S/2\n \n return C,int(S),l,d,int(kk)",
"def cubeZ2latlon(x, y, c, xi, yi):\n from scipy.interpolate import griddata\n\n XX, YY = np.meshgrid(xi, yi)\n NN = c.shape\n if len(c.shape)==1:\n nz = 1\n nPt2 = len(c)\n c = c.reshape(nz, nPt2)\n elif len(c.shape)==2:\n nz, nPt2 = c.shape\n nc = int(np.fix(np.sqrt(nPt2/6)))\n nPts = 6*nc*nc\n \n z = np.zeros([nz, len(yi), len(xi)])\n for k in range(nz):\n X = np.reshape(x, [nc, 6*nc])\n Y = np.reshape(y, [nc, 6*nc])\n C = np.reshape(c[k, :nPts], [nc, 6*nc])\n\n \n i = 3*nc + np.arange(nc)\n j = int(np.floor(nc/2))\n X = np.append(X, (X[j, i]-360).reshape(nc, 1), axis=1)\n Y = np.append(Y, Y[j, i].reshape(nc, 1), axis=1) \n C = np.append(C, C[j, i].reshape(nc, 1), axis=1) \n \n i = 5*nc + int(np.floor(nc/2))\n j = np.arange(int(np.floor(nc/2)))\n X = np.append(X, np.zeros([nc, 1]), axis=1)\n Y = np.append(Y, np.zeros([nc, 1]), axis=1)\n C = np.append(C, np.zeros([nc, 1]), axis=1)\n X[j, -1] = X[j, i]-360\n Y[j, -1] = Y[j, i]\n C[j, -1] = C[j, i]\n \n #--\n j = int(np.floor(nc/2))\n i = 2*nc + j\n if Y[j, i]==90:\n X[j, i] = 180\n i = 2*nc + np.arange(int(np.floor(nc/2)), nc)\n j = int(np.floor(nc/2))\n X[i-2*nc, -1] = X[j, i] - 360\n Y[i-2*nc, -1] = Y[j, i]\n C[i-2*nc, -1] = C[j, i]\n \n j = int(np.floor(nc/2))\n i = 5*nc + j\n ij = i + j*nc*6\n if Y[j, i]==-90:\n #% fprintf('South pole: %i %i %f %f\\n',i,j,X(i,j),Y(i,j));\n X[j, i] = 180\n \n \n X = X.reshape(1, np.prod(X.shape))\n Y = Y.reshape(1, np.prod(Y.shape))\n C = C.reshape(1, np.prod(C.shape))\n \n I = np.nonzero(Y==-90)[0]\n \n if len(I)==1:\n #% fprintf('South pole: %i %f %f\\n',I,X(I),Y(I));\n X = np.append(X, X[I] - 360)\n Y = np.append(Y, Y[I])\n C = np.append(C, C[I])\n \n if nPt2 > nPts:\n X = np.append(X, x[nPts+1])\n Y = np.append(Y, y[nPts+1])\n C = np.append(C, c[k, nPts+1])\n\n if nPt2 == nPts+2:\n X = np.append(X, x[nPt2])\n Y = np.append(Y, y[nPt2])\n C = np.append(C, c[k, nPt2])\n \n point = np.zeros([X.shape[1], 2])\n point[:, 0] = X[0, :].T\n point[:, 1] = Y[0, :].T\n z[k, :, :] = griddata(point, np.squeeze(C), (XX, YY))\n \n z = np.squeeze(z)\n\n return z",
"def inflate_map(self, grid_map):\n\n\n \"\"\"\n Fill in your solution here\n \"\"\"\n\n width = grid_map.get_width()\n height = grid_map.get_height()\n radius = self.radius\n #fill in the C space cells whose distance to occupied cells <= robot radius\n for x_grid in range(width):\n for y_grid in range(height):\n\n if grid_map[x_grid, y_grid] == self.occupied_space:\n x_0 = x_grid - radius\n y_0 = y_grid - radius\n\n for delta_x in range(2 * radius + 1):\n for delta_y in range(2 * radius + 1):\n x_check = x_0 + delta_x\n y_check = y_0 + delta_y\n if sqrt((x_check - x_grid)**2 + (y_check - y_grid)**2) <= radius and grid_map[x_check, y_check] != self.occupied_space:\n self.add_to_map(grid_map, x_check, y_check, self.c_space)\n\n\n # Return the inflated map\n return grid_map",
"def grid_mid2edge(lon, lat):\n #\n # Check input\n do2 = np.ndim(lon)\n da2 = np.ndim(lat)\n assert (do2 >=1) & (do2 <= 2), 'longitudes have to be either 1D or 2D arrays.'\n assert (da2 >=1) & (da2 <= 2), 'latitudes have to be either 1D or 2D arrays.'\n assert do2 == da2, 'longitudes and latitudes have to be either 1D or 2D arrays; no mixture possible.'\n #\n # Make 2D\n if do2 == 1:\n lon2, lat2 = np.meshgrid(lon,lat) # have sizes \n else:\n lon2 = lon # no copy\n lat2 = lat\n #\n # N-S or S-N\n isns = True # descending latitudes\n if np.min(np.diff(lat2)) > 0.: isns = False # ascending latitudes\n #\n # 0-360 0r -180-+180\n is360 = True # 0 - 360\n if np.any(lon2 < 0.): # -180 - +180\n lon2 = np.copy(lon2) + 180. # do all calculations in 0-360\n is360 = False\n #\n # out arrays\n nlat = lon2.shape[0]\n nlon = lon2.shape[1]\n lonh = np.empty((nlat+1, nlon+1))\n lath = np.empty((nlat+1, nlon+1))\n # Edge points in interior = mean of 4 surrounding grid boxes\n lonh[1:-1,1:-1] = 0.25*(lon2[0:-1,0:-1] + # upper left\n lon2[0:-1,1:] + # upper right\n lon2[1:,0:-1] + # lower left\n lon2[1:,1:]) # lower right\n lath[1:-1,1:-1] = 0.25*(lat2[0:-1,0:-1] +\n lat2[0:-1,1:] + # same as lon\n lat2[1:,0:-1] +\n lat2[1:,1:])\n # left column w/o corners = left - half distance\n lonh[1:-1,0] = 0.75*lon2[0:-1,0] + 0.75*lon2[1:,0] - 0.25*lon2[0:-1,1] - 0.25*lon2[1:,1]\n lath[1:-1,0] = 0.5*(lat2[0:-1,0] + lat2[1:,0])\n # right column w/o corners = right + half distance\n lonh[1:-1,-1] = 0.75*lon2[0:-1,-1] + 0.75*lon2[1:,-1] - 0.25*lon2[0:-1,-2] - 0.25*lon2[1:,-2]\n lath[1:-1,-1] = 0.5*(lat2[0:-1,-1] + lat2[1:,-1])\n # upper row w/o corners = up + half distance\n lonh[0,1:-1] = 0.5*(lon2[0,0:-1] + lon2[0,1:])\n lath[0,1:-1] = 0.75*lat2[0,0:-1] + 0.75*lat2[0,1:] - 0.25*lat2[1,0:-1] - 0.25*lat2[1,1:]\n # lower row w/o corners = low - half distance\n lonh[-1,1:-1] = 0.5*(lon2[-1,0:-1] + lon2[-1,1:])\n lath[-1,1:-1] = 0.75*lat2[-1,0:-1] + 0.75*lat2[-1,1:] - 0.25*lat2[-2,0:-1] - 0.25*lat2[-2,1:]\n # corners = midpoint plus or minus dist to opposite corner\n lonh[0,0] = lon2[0,0] - (lonh[1,1] - lon2[0,0]) # upper left\n lath[0,0] = lat2[0,0] - (lath[1,1] - lat2[0,0])\n lonh[0,-1] = lon2[0,-1] - (lonh[1,-2] - lon2[0,-1]) # upper right\n lath[0,-1] = lat2[0,-1] - (lath[1,-2] - lat2[0,-1])\n lonh[-1,0] = lon2[-1,0] - (lonh[-2,1] - lon2[-1,0]) # lower left\n lath[-1,0] = lat2[-1,0] - (lath[-2,1] - lat2[-1,0])\n lonh[-1,-1] = lon2[-1,-1] - (lonh[-2,-2] - lon2[-1,-1]) # lower right\n lath[-1,-1] = lat2[-1,-1] - (lath[-2,-2] - lat2[-1,-1])\n\n # lon can be > 360\n # this makes 360=0 and 180=-180: stay with 360 and 180\n # lonh %= 360\n if np.any(lonh > 360.):\n lonh = np.where(lonh > 360., lonh % 360., lonh)\n \n # return to -180-+180\n if not is360:\n lonh -= 180.\n\n return lonh, lath",
"def get_nc_CGrid_GLORYS(grdfile, name='GLORYS_CORAL', area='regional', \\\n xrange=(185,340), yrange=(100, 210), ystart=245):\n\n nc = pyroms.io.Dataset(grdfile)\n\n lon_t = nc.variables['nav_lon'][:]\n lat_t = nc.variables['nav_lat'][:]\n lat_u = nc.variables['gphiu'][:]\n lon_u = nc.variables['glamu'][:]\n lat_v = nc.variables['gphiv'][:]\n lon_v = nc.variables['glamv'][:]\n\n depth = nc.variables['gdept_0'][:]\n depth_w = nc.variables['gdepw_0'][:]\n depth_bnds = np.zeros(depth.shape[0]+1)\n depth_bnds[:-1] = depth_w[:]\n depth_bnds[-1] = 6000.\n\n nc_mask_t = nc.variables['tmask']\n# mask_t = np.array(~nc_mask_t[:].mask, dtype='int')\n mask_t = np.array(nc_mask_t[:], dtype='int')\n\n nc_mask_u = nc.variables['umask']\n# mask_u = np.array(~nc_mask_u[:].mask, dtype='int')\n mask_u = np.array(nc_mask_u[:], dtype='int')\n\n nc_mask_v = nc.variables['vmask']\n# mask_v = np.array(~nc_mask_v[:].mask, dtype='int')\n mask_v = np.array(nc_mask_v[:], dtype='int')\n\n bottom = pyroms.utility.get_bottom(nc_mask_t[::-1,:,:], mask_t[0,:], spval=nc_mask_t.missing_value)\n nlev = mask_t.shape[0]\n bottom = (nlev-1) - bottom\n h = np.zeros(mask_t[0,:].shape)\n for i in range(mask_t[0,:].shape[1]):\n for j in range(mask_t[0,:].shape[0]):\n if mask_t[0,j,i] == 1:\n h[j,i] = depth_bnds[int(bottom[j,i])]\n\n if area == 'global':\n #add rows in the north and the south, east and west\n lon_t = lon_t[:,np.r_[0,:np.size(lon_t,1),-1]]\n lon_t[:,0] = lon_t[:,1] - (lon_t[:,2]-lon_t[:,1])\n lon_t[:,-1] = lon_t[:,-2] + (lon_t[:,-2]-lon_t[:,-3])\n lon_t = lon_t[np.r_[0,0,:np.size(lon_t,0),-1,-1]]\n\n lat_t = lat_t[np.r_[0,0,:np.size(lat_t,0),-1,-1]]\n lat_t[-1,:] = -80\n lat_t[0,:] = -85\n lat_t[-2,:] = lat_t[-3,:]\n lat_t[-1,:] = lat_t[-4,:]\n lat_t = lat_t[:,np.r_[0,:np.size(lat_t,1),-1]]\n\n lon_u = lon_u[:,np.r_[0,:np.size(lon_u,1),-1]]\n lon_u[:,0] = lon_u[:,1] - (lon_u[:,2]-lon_u[:,1])\n lon_u[:,-1] = lon_u[:,-2] + (lon_u[:,-2]-lon_u[:,-3])\n lon_u = lon_u[np.r_[0,0,:np.size(lon_u,0),-1,-1]]\n\n lat_u = lat_u[np.r_[0,0,:np.size(lat_u,0),-1,-1]]\n lat_u[-1,:] = -80\n lat_u[0,:] = -85\n lat_u[-2,:] = lat_u[-3,:]\n lat_u[-1,:] = lat_u[-4,:]\n lat_u = lat_u[:,np.r_[0,:np.size(lat_u,1),-1]]\n\n lon_v = lon_v[:,np.r_[0,:np.size(lon_v,1),-1]]\n lon_v[:,0] = lon_v[:,1] - (lon_v[:,2]-lon_v[:,1])\n lon_v[:,-1] = lon_v[:,-2] + (lon_v[:,-2]-lon_v[:,-3])\n lon_v = lon_v[np.r_[0,0,:np.size(lon_v,0),-1,-1]]\n\n lat_v = lat_v[np.r_[0,0,:np.size(lat_v,0),-1,-1]]\n lat_v[-1,:] = -80\n lat_v[0,:] = -85\n lat_v[-2,:] = lat_v[-3,:]\n lat_v[-1,:] = lat_v[-4,:]\n lat_v = lat_v[:,np.r_[0,:np.size(lat_v,1),-1]]\n\n mask_t = mask_t[:,np.r_[0,0,:np.size(mask_t,1),-1,-1],:]\n mask_t = mask_t[:,:,np.r_[0,:np.size(mask_t,2),-1]]\n mask_t[:,:,0] = mask_t[:,:,-2]\n mask_t[:,:,-1] = mask_t[:,:,1]\n mask_u = mask_u[:,np.r_[0,0,:np.size(mask_u,1),-1,-1],:]\n mask_u = mask_u[:,:,np.r_[0,:np.size(mask_u,2),-1]]\n mask_u[:,:,0] = mask_u[:,:,-2]\n mask_u[:,:,-1] = mask_u[:,:,1]\n mask_v = mask_v[:,np.r_[0,0,:np.size(mask_v,1),-1,-1],:]\n mask_v = mask_v[:,:,np.r_[0,:np.size(mask_v,2),-1]]\n mask_v[:,:,0] = mask_v[:,:,-2]\n mask_v[:,:,-1] = mask_v[:,:,1]\n h = h[np.r_[0,0,:np.size(h,0),-1,-1]]\n h = h[:,np.r_[0,:np.size(h,1),-1]]\n h[:,0] = h[:,-2]\n h[:,-1] = h[:,1]\n m,l = h.shape\n xrange=(1,l-2)\n yrange=(1,m-2)\n\n if area == 'npolar':\n #add rows in the north and the south, east and west\n lon_t = lon_t[:,np.r_[0,:np.size(lon_t,1),-1]]\n lon_t[:,0] = lon_t[:,1] - (lon_t[:,2]-lon_t[:,1])\n lon_t[:,-1] = lon_t[:,-2] + (lon_t[:,-2]-lon_t[:,-3])\n lon_t = lon_t[np.r_[0,0,:np.size(lon_t,0),-1,-1]]\n\n lat_t = lat_t[np.r_[0,0,:np.size(lat_t,0),-1,-1]]\n lat_t[-1,:] = -80\n lat_t[0,:] = -85\n lat_t[-2,:] = lat_t[-3,:]\n lat_t[-1,:] = lat_t[-4,:]\n lat_t = lat_t[:,np.r_[0,:np.size(lat_t,1),-1]]\n\n lon_u = lon_u[:,np.r_[0,:np.size(lon_u,1),-1]]\n lon_u[:,0] = lon_u[:,1] - (lon_u[:,2]-lon_u[:,1])\n lon_u[:,-1] = lon_u[:,-2] + (lon_u[:,-2]-lon_u[:,-3])\n lon_u = lon_u[np.r_[0,0,:np.size(lon_u,0),-1,-1]]\n\n lat_u = lat_u[np.r_[0,0,:np.size(lat_u,0),-1,-1]]\n lat_u[-1,:] = -80\n lat_u[0,:] = -85\n lat_u[-2,:] = lat_u[-3,:]\n lat_u[-1,:] = lat_u[-4,:]\n lat_u = lat_u[:,np.r_[0,:np.size(lat_u,1),-1]]\n\n lon_v = lon_v[:,np.r_[0,:np.size(lon_v,1),-1]]\n lon_v[:,0] = lon_v[:,1] - (lon_v[:,2]-lon_v[:,1])\n lon_v[:,-1] = lon_v[:,-2] + (lon_v[:,-2]-lon_v[:,-3])\n lon_v = lon_v[np.r_[0,0,:np.size(lon_v,0),-1,-1]]\n\n lat_v = lat_v[np.r_[0,0,:np.size(lat_v,0),-1,-1]]\n lat_v[-1,:] = -80\n lat_v[0,:] = -85\n lat_v[-2,:] = lat_v[-3,:]\n lat_v[-1,:] = lat_v[-4,:]\n lat_v = lat_v[:,np.r_[0,:np.size(lat_v,1),-1]]\n\n mask_t = mask_t[:,np.r_[0,0,:np.size(mask_t,1),-1,-1],:]\n mask_t = mask_t[:,:,np.r_[0,:np.size(mask_t,2),-1]]\n mask_t[:,:,0] = mask_t[:,:,-2]\n mask_t[:,:,-1] = mask_t[:,:,1]\n mask_u = mask_u[:,np.r_[0,0,:np.size(mask_u,1),-1,-1],:]\n mask_u = mask_u[:,:,np.r_[0,:np.size(mask_u,2),-1]]\n mask_u[:,:,0] = mask_u[:,:,-2]\n mask_u[:,:,-1] = mask_u[:,:,1]\n mask_v = mask_v[:,np.r_[0,0,:np.size(mask_v,1),-1,-1],:]\n mask_v = mask_v[:,:,np.r_[0,:np.size(mask_v,2),-1]]\n mask_v[:,:,0] = mask_v[:,:,-2]\n mask_v[:,:,-1] = mask_v[:,:,1]\n h = h[np.r_[0,0,:np.size(h,0),-1,-1]]\n h = h[:,np.r_[0,:np.size(h,1),-1]]\n h[:,0] = h[:,-2]\n h[:,-1] = h[:,1]\n m,l = h.shape\n xrange=(1,l-2)\n yrange=(ystart+2,m-2)\n\n return CGrid_GLORYS(lon_t, lat_t, lon_u, lat_u, lon_v, lat_v, mask_t, mask_u, mask_v, depth, depth_bnds, h, \\\n name, xrange, yrange)",
"def build_sparse_ge_mat(self, mni_grid_size=(200, 200, 200)):\n\n if self._proceed_check() == 1:\n return 1\n\n # Talk to Torben about implementation\n # Development on hold 8/27/15\n grid_shift = [dim - 0.5*dim for dim in mni_grid_size]\n mni_space = np.zeros(mni_grid_size)\n for coord in self.aba['mni_coords'].data:\n for entrez_id in self.ge['aba']:\n mni_space[coord[0]+grid_shift[0], coord[1]+grid_shift[1], coord[2]+grid_shift[2]] = 0",
"def compute_grid_params_general(minlon, maxlon, minlat, maxlat, zerolon, zerolat):\n deltalon = (maxlon - minlon) * 111.00 * np.cos(np.deg2rad(zerolat)); # in km.\n deltalat = (maxlat - minlat) * 111.00; # in km.\n start_gridx = (minlon - zerolon) * 111.00 * np.cos(np.deg2rad(zerolat)); # in km\n finish_gridx = (maxlon - zerolon) * 111.00 * np.cos(np.deg2rad(zerolat)); # in km.;\n start_gridy = (minlat - zerolat) * 111.00; # in km.\n finish_gridy = (maxlat - zerolat) * 111.00; # in km.\n xinc = deltalon / 100.0;\n yinc = deltalat / 100.0;\n return [start_gridx, finish_gridx, start_gridy, finish_gridy, xinc, yinc];",
"def seafloor_grid(depths, lat, lon):"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Create a table name for a content type (remove periods).
|
def _table_name_for(content_type):
return content_type.replace('.', '')
|
[
"def __generate_table_name__(self, table, username, end_point_type):\n # If private endpoint\n if end_point_type == 'private':\n if username != \"\":\n return table + \"_\" + username\n else:\n return table\n else:\n return table",
"def __tablename__(self) -> str:\n return gen_tablenames(self.__name__)",
"def Create_table(self, tableName):\n \n return \"CREATE TABLE {} AS \\n\".format(tableName)",
"def create_table_for(self, model):",
"def _table_creation_command(cls) -> str:\n return sql.Metacard.create_table()",
"def _create_table(self, table_name):\n raise NotImplementedError()",
"def _to_table_name(self, param):\n ret = self._to_table(param)\n if isinstance(ret, sa.Table):\n ret = ret.fullname\n return ret",
"def form_table_name(self, bucket_name):\n table_name = bucket_name[3:-4].lower().replace('-', '_')\n return table_name",
"def get_table_name(self, object_name):\n return self.get_table_prefix() + \"Per_\" + object_name",
"def input_table_name(\n self, source: Union[None, DatasetFileDataset]\n ) -> Union[str, None]:\n if not source:\n return None\n\n ext = \"\"\n if source.dataset.dataset_type == DatasetType.ITEM_METADATA:\n ext = \"_metadata\"\n elif source.dataset.dataset_type == DatasetType.RELATED_TIME_SERIES:\n ext = \"_related\"\n\n table_name = f\"{self.unique_id}\"\n table_name = table_name + ext if ext else table_name\n\n return table_name",
"def CreateTable(self, param):\n pass",
"def create_room_types_table(db_file):\n create_table('''CREATE TABLE IF NOT EXISTS room_types\n (id integer NOT NULL PRIMARY KEY, room_type text)''', db_file)",
"def _table_creation_command(cls):\n return sql.Card.create_table()",
"def _classname_for_table(self, base, tablename, table) -> str:\n new_name = self._camelize_classname(base, tablename, table)\n self._class_table_map[new_name] = tablename\n return new_name",
"def table_name(self) -> str:\n return jsii.get(self, \"tableName\")",
"def tableName(file_name):\n return file_name.split(\".\")[0].replace(\",\",\"_\").replace(\" \",\"_\").replace(\"-\",\"_\").replace(\"(\",\"_\").replace(\")\",\"_\")",
"def createTable(self, tableName, columnFamilies):\n pass",
"def createTable(self, dbName, tableName, schema=None, chunkColumns=False):\n\n _log.debug('create table: %s.%s', dbName, tableName)\n data = dict(table=tableName, chunkColumns=str(int(chunkColumns)))\n if schema:\n data['schema'] = schema\n else:\n data['schemaSource'] = 'CSS'\n self._requestJSON('dbs', dbName + '/tables', method='POST', data=data)",
"def create_table (self, tablename = 'motif'):\n\n c = self.connection.cursor()\n\n # create\n\n c.execute('''create table ? (matrix text, source text, factorName text, species\n text, pmid integer, domain text, structureCategory text )''', (tablename))\n\n self.connection.commit()\n\n c.close()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Audit logs tend to have periods (.) in their column names. Take those out. If a log column has the same name as an existing column in the database, but the capitalization doesn't match, rename the column to the existing one. Otherwise SQL will throw an error for duplicate column names.
|
def _validate_column_names(df):
to_rename = {}
for column in df:
if '.' in column:
to_rename[column] = column.replace('.', '')
return df.rename(columns=to_rename)
|
[
"def normalize_col_name(self, col_name, used_column_names, is_relation):\n field_params = {}\n field_notes = []\n\n new_name = clean_utf8(col_name)\n new_name = col_name.lower()\n if new_name != col_name:\n field_notes.append('Field name made lowercase.')\n\n if is_relation:\n if new_name.endswith('_id'):\n new_name = new_name[:-3]\n else:\n field_params['db_column'] = col_name\n\n new_name, num_repl = re.subn(r'\\W', '_', new_name)\n if num_repl > 0:\n field_notes.append('Field renamed to remove unsuitable characters.')\n\n if new_name.find('__') >= 0:\n while new_name.find('__') >= 0:\n new_name = new_name.replace('__', '_')\n if col_name.lower().find('__') >= 0:\n # Only add the comment if the double underscore was in the original name\n field_notes.append(\"Field renamed because it contained more than one '_' in a row.\")\n\n if new_name.startswith('_'):\n new_name = 'field%s' % new_name\n field_notes.append(\"Field renamed because it started with '_'.\")\n\n if new_name.endswith('_'):\n new_name = '%sfield' % new_name\n field_notes.append(\"Field renamed because it ended with '_'.\")\n\n if keyword.iskeyword(new_name):\n new_name += '_field'\n field_notes.append('Field renamed because it was a Python reserved word.')\n\n if new_name[0].isdigit():\n new_name = 'number_%s' % new_name\n field_notes.append(\"Field renamed because it wasn't a valid Python identifier.\")\n\n if new_name in used_column_names:\n num = 0\n while '%s_%d' % (new_name, num) in used_column_names:\n num += 1\n new_name = '%s_%d' % (new_name, num)\n field_notes.append('Field renamed because of name conflict.')\n\n if col_name != new_name and field_notes:\n field_params['db_column'] = col_name\n\n return new_name, field_params, field_notes",
"def _clean_column_names(self):\n self.logger.info(\"Set up column name cleaning.\")\n self.pipeline.steps.append(\n (\"clean_column_names\", TransformerWrapper(CleanColumnNames()))\n )",
"def format_column_name(cls, column_name, normalize=True):\n formatted_column_name = column_name\n if normalize:\n formatted_column_name = cls.__normalize_string(\n cls.__COLUMN_NAME_INVALID_CHARS_REGEX_PATTERN, column_name)\n\n return prepare.DataCatalogStringsHelper.truncate_string(\n formatted_column_name, cls.__COLUMN_NAME_UTF8_MAX_LENGTH)",
"def test_rename_column(self):\n # Create a new dataset\n fh = self.filestore.upload_file(CSV_FILE)\n ds = self.api.load_dataset(\n datastore=self.datastore,\n filestore=self.filestore,\n file_id=fh.identifier\n ).dataset\n ds_rows = ds.fetch_rows()\n # Keep track of column and row identifier\n col_ids = [col.identifier for col in ds.columns]\n row_ids = [row.identifier for row in ds_rows]\n # Rename first column to Firstname\n result = self.api.rename_column(\n ds.identifier,\n ds.column_by_name('Name').identifier,\n 'Firstname',\n self.datastore\n )\n self.assertNotEqual(result.dataset.identifier, ds.identifier)\n ds = self.datastore.get_dataset(result.dataset.identifier)\n self.assertEqual(ds.columns[0].name.upper(), 'Firstname'.upper())\n self.assertEqual(ds.columns[1].name.upper(), 'Age'.upper())\n self.assertEqual(ds.columns[2].name.upper(), 'Salary'.upper())\n result = self.api.rename_column(\n ds.identifier,\n ds.column_by_name('Age').identifier,\n 'BDate',\n self.datastore\n )\n ds = self.datastore.get_dataset(result.dataset.identifier)\n ds_rows = ds.fetch_rows()\n self.assertEqual(ds.columns[0].name.upper(), 'Firstname'.upper())\n self.assertEqual(ds.columns[1].name, 'BDate')\n self.assertEqual(ds.columns[2].name.upper(), 'Salary'.upper())\n # Ensure that row ids haven't changed\n for i in range(len(ds_rows)):\n self.assertEqual(ds_rows[i].identifier, row_ids[i])\n # Make sure column identifier haven't changed\n for i in range(len(ds.columns)):\n self.assertEqual(ds.columns[i].identifier, col_ids[i])\n # No changes if the old and new column name are the same (with exception\n # to upper and lower cases).\n result = self.api.rename_column(\n ds.identifier,\n ds.column_by_name('BDate').identifier,\n 'BDate',\n self.datastore\n )\n self.assertEqual(ds.identifier, result.dataset.identifier)\n # Ensure exception is thrown if dataset identifier is unknown\n with self.assertRaises(ValueError):\n self.api.rename_column('unknown:uri', 0, 'Firstname', self.datastore)\n # Ensure exception is thrown for invalid column id\n with self.assertRaises(ValueError):\n self.api.rename_column(ds.identifier, 500, 'BDate', self.datastore)",
"def rename_columns(self):\r\n self.columns = [self._date, self._net_purchase, self._gross_sale, self._tax, self._margin]\r\n self.all_data.columns = self.columns",
"def change_column_name(\n conn,\n table,\n old_column_name,\n new_column_name,\n schema=None\n):\n activity_table = get_activity_table(schema=schema)\n query = (\n activity_table\n .update()\n .values(\n old_data=jsonb_change_key_name(\n activity_table.c.old_data,\n old_column_name,\n new_column_name\n ),\n changed_data=jsonb_change_key_name(\n activity_table.c.changed_data,\n old_column_name,\n new_column_name\n )\n )\n .where(activity_table.c.table_name == table)\n )\n return conn.execute(query)",
"def format_column_name(c):\n return c.replace(\"-\", \"_\").replace(\"(\", \"\").replace(\")\", \"\")\\\n .replace(\" \", \"_\").lower()",
"def convert_column(col, table=None):\n if '.' in col and table and not col.startswith(table.name):\n raise Exception(\"field %s invalid for table %s\" % (col, table.name))\n elif '.' in col:\n if col.count('.') > 1:\n raise Exception(\"field '%s' invalid (too many '.')\" % col)\n return '.c.'.join(col.split('.'))\n elif '.' not in col and table:\n return '%s.c.%s' % (table.name, col)\n else:\n return \"text('%s')\" % col",
"def column_rename(self, existing_name, hsh=None):\r\n try:\r\n existing_name = str(existing_name)\r\n except UnicodeEncodeError:\r\n pass\r\n if hsh is None:\r\n hsh = self._hash()\r\n if self._name:\r\n return '%s(%s) [%s]' %(self._name, self._remove_hashes(existing_name),\r\n hsh)\r\n return '%s [%s]'%(self._remove_hashes(existing_name),\r\n hsh)",
"def _col_rename_remove_cavity(col_name):\n p = re.compile(r\"^(Sample_\\d+)(_\\d)(_\\w+)\")\n m = p.match(col_name)\n if m:\n return f\"{m.group(1)}{m.group(3)}\"\n else:\n return col_name",
"def rename_column_(self, original_column_name: str, new_column_name: str):\n self._check_values_type()\n for dataset in self.values():\n dataset.rename_column_(original_column_name=original_column_name, new_column_name=new_column_name)",
"def _field_to_column_names(names):\n return [re.sub(r'_(.)', lambda m: m.group(1).upper(), name) for name in names]",
"def split_cols_with_dot(column: str) -> str:\n\n def replace(string: str, char: str, index: int) -> str:\n \"\"\"Helper method which replaces values with dot as a separator and converts it to camelCase format\n\n Parameters\n ----------\n string: str\n String in which we remove dots and convert it to camelcase format.\n char: str\n First letter of given word.\n index:\n Index of string element.\n\n Returns\n -------\n str:\n Camel case string with removed dots. E.g. price.availableSupply -> priceAvailableSupply.\n \"\"\"\n\n return string[:index] + char + string[index + 1 :]\n\n if \".\" in column:\n part1, part2 = column.split(\".\")\n part2 = replace(part2, part2[0].upper(), 0)\n return part1 + part2\n return column",
"def normalize_last_name(entry,field_name):\n spaces_removed_last_name = remove_spaces(getattr(entry,field_name))\n title_case_no_spaces = title_case(spaces_removed_last_name)\n normalized_last_name = remove_suffix(title_case_no_spaces)\n setattr(entry,field_name, normalized_last_name)",
"def standardize_cols(df, dd_name, settings):\n renamer = settings[\"col_rename_by_dd\"][dd_name]\n df = df.rename(columns=renamer)\n\n common = {\"PRTAGE\", \"HRMIS\", \"HRYEAR4\", \"PESEX\", \"HRMONTH\", \"PTDTRACE\",\n \"PEMLR\", \"PRERNWA\", \"PTWK\", \"PEMARITL\", \"PRDISC\",\n \"HEFAMINC\", \"PTDTRACE\", \"HWHHWGT\", \"PEERNHRY\", \"HRMIS\"}\n cols = set(df.columns.tolist())\n extra = cols - common\n missing = common - cols\n\n if missing:\n name = str(df.HRYEAR4.iloc[0]) + str(df.HRMONTH.iloc[0])\n key = ' '.join([str(arrow.utcnow()), name, 'missing'])\n d = {key: list(missing)}\n with open('make_hdf_store_log.json', 'a') as f:\n json.dump(d, f, indent=2)\n\n if extra:\n name = str(df.HRYEAR4.iloc[0]) + str(df.HRMONTH.iloc[0])\n key = ' '.join([str(arrow.utcnow()), name, 'extra'])\n d = {key: list(extra)}\n with open('make_hdf_store_log.json', 'a') as f:\n json.dump(d, f, indent=2)\n\n return df",
"def rename_columns(df_data, new_col):\n df_data.rename(columns=new_col, inplace=True)",
"def change_column_names(data, new_names):\n old_names = data.columns\n if isinstance(new_names, list):\n mapping = dict(zip(old_names, new_names))\n else:\n mapping = new_names\n\n transformed_data = data.select([col(c).alias(mapping.get(c, c)) for c in data.columns])\n return transformed_data",
"def normalize_column_names(df: DataFrame) -> DataFrame:\n list_new_names = []\n for col in df.columns:\n new_name = col.strip()\n new_name = new_name.replace(\" \", \"\")\n new_name = new_name.replace(\".\", \"_\")\n new_name = new_name.lower()\n list_new_names.append(new_name)\n df = df.toDF(*list_new_names)\n return df",
"def clean_cols(data):\n clean_col_map = {x: x.lower().strip() for x in list(data)}\n return data.rename(index=str, columns=clean_col_map)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Not all audit logs have all available columns. There columns in the database might change as logs come in. Check whether all columns in a log already exist in the current table.
|
def _validate_existing_columns(self, df, content_type, engine):
if inspect(engine).has_table(self._table_name_for(content_type=content_type)):
new_cols = df.columns.tolist()
missing_cols = set(new_cols) - set(self._existing_columns_for(content_type, engine=engine))
return not missing_cols
return True
|
[
"def checkColumns(self, row, columns, log):\n rescols = set(row.keys())\n cols = set(columns.values())\n if not rescols >= cols:\n log.error(\n \"result missing columns: '%s'\",\n \",\".join(cols.difference(rescols)),\n )\n return False\n return True",
"def _check_target_columns(self):\n if not self.target_columns:\n self.target_columns = self._infer_target_columns()\n else:\n for target in self.target_columns:\n info = 'target \"%s\" not found in data frame'\n assert target in self.columns, info % target",
"def check_colnames(sample_df: pd.DataFrame, batch_df: pd.DataFrame) -> int:\n alert_colnames = 0\n\n if sample_df.columns.equals(batch_df.columns):\n logger.info(\n f\"Columns names are identical in the train set and the new batch ✔️\"\n )\n else:\n alert_colnames = 1\n for i, name in enumerate(sample_df.columns.tolist()):\n batch_name = batch_df.columns.tolist()[i]\n if batch_name != name:\n message = f'Column \"{name}\" became \"{batch_name}\"❌'\n logger.error(message)\n\n return alert_colnames",
"def _check_missing_columns(\n self,\n columns: List[str],\n table: str,\n ) -> List[str]:\n for column in columns:\n try:\n self.query_table(table, [column], 0)\n except ColumnMissingException:\n if table not in self._missing_variables:\n self._missing_variables[table] = []\n self._missing_variables[table].append(column)\n except IndexError:\n self.warning(f\"Dataset contains no entries for {column}\")\n\n return self._missing_variables.get(table, [])",
"def test_column_values(self):\n for column in self.table.columns:\n assert len(column.values) == 0",
"def test_agg_data_has_expected_columns(self):\n expected_columns = self.keywords + [\"Date\", \"Confirmed\",\n \"ConfirmedChange\", \"Deaths\",\n \"DeathsChange\", \"Recovered\",\n \"RecoveredChange\", \"Country\",\n \"State\"]\n self.assertEqual(set(list(self.data_processor.agg_data_frame.columns)),\n set(expected_columns))",
"def check_data_consistency(self):\r\n current_data = self.all_data\r\n required_columns = [self._year, self._month, self._day_of_week]\r\n if current_data.columns.any() not in required_columns:\r\n self.reload_data()",
"def check_valid_column(observation):\n \n valid_columns = {\n \"observation_id\",\n \"Type\",\n \"Date\",\n \"Part of a policing operation\",\n \"Latitude\",\n \"Longitude\",\n \"Gender\",\n \"Age range\",\n \"Officer-defined ethnicity\",\n \"Legislation\",\n \"Object of search\",\n \"station\"\n }\n \n keys = set(observation.keys())\n \n if len(valid_columns - keys) > 0: \n missing = valid_columns - keys\n error = \"Missing columns: {}\".format(missing)\n return False, error\n \n if len(keys - valid_columns) > 0: \n extra = keys - valid_columns\n error = \"Unrecognized columns provided: {}\".format(extra)\n return False, error \n\n return True, \"\"",
"def check_tables(dic):\n sql_str = \"\"\"select distinct tablename\n from pg_table_def\n where schemaname = '{s}'\n \"\"\".format(s=dic['schema'])\n tables = pd.read_sql(sql_str, conn).tablename.values\n if dic['ad_tab'] not in tables:\n dic['ad_tab'] = None\n if dic['log_tab'] not in tables:\n missing_log(dic)",
"def _assert_cols_in_df(cls, columns_provided, columns_df):\n col_not_valids = (\n set([column for column in columns_provided]).difference(set([column for column in columns_df])))\n assert (col_not_valids == set()), 'Error: The following columns do not exits in dataFrame: %s' % col_not_valids",
"def _get_mismatches(self) -> None:\r\n # Add column to list if it contains a mismatch.\r\n mis = [col for col in self._df_s.columns if not self._df_t[col].equals(self._df_s[col])]\r\n if mis:\r\n self._msg.column_mismatches(columns=self._col_mismatches)\r\n else:\r\n self._msg.column_mismatches_none()\r\n self._col_mismatches = mis",
"def verify_column_names(table_name, test_columns):\n column_names = get_column_names(table_name)\n for column in test_columns:\n if column not in column_names:\n return False\n return True",
"def _verify_dataframe_columns(\n workflow,\n data_frame: pd.DataFrame,\n):\n df_column_names = list(data_frame.columns)\n wf_column_names = [col.name for col in workflow.columns.all()]\n\n if settings.DEBUG:\n # There should not be any columns in the workflow that are not in the\n # DF\n assert not (set(wf_column_names) - set(df_column_names))\n\n # Loop over the columns in the Workflow to refresh the is_key value. There\n # may be values that have been added to the column, so this field needs to\n # be reassessed\n for col in workflow.columns.all():\n # Condition 1: If the column is marked as a key column, it should\n # maintain this property\n if col.is_key and not pandas.is_unique_series(data_frame[col.name]):\n raise Exception(gettext(\n 'Column {0} looses its \"key\" property through this merge.'\n + ' Either remove this property from the column or '\n + 'remove the rows that cause this problem in the new '\n + 'dataset').format(col.name))\n\n # Get the pandas data type\n df_col_type = pandas.datatype_names.get(\n data_frame[col.name].dtype.name)\n\n # Condition 2: Review potential data type changes\n if col.data_type == 'boolean' and df_col_type == 'string':\n # 2.1: A WF boolean with must be DF string with True/False/None\n column_data_types = {\n type(row_value)\n for row_value in data_frame[col.name]\n # Remove the NoneType and Float\n if not isinstance(row_value, float) and row_value is not None\n }\n if len(column_data_types) != 1 or column_data_types.pop() != bool:\n raise Exception(gettext(\n 'New values in column {0} are not of type {1}',\n ).format(col.name, col.data_type))\n elif (\n col.data_type == 'integer' and df_col_type != 'integer'\n and df_col_type != 'double'\n ):\n # 2.2 WF Numeric column must be DF integer or double\n raise Exception(gettext(\n 'New values in column {0} are not of type number',\n ).format(col.name))\n elif col.data_type != 'integer' and df_col_type != col.data_type:\n # 2.3 Any other type change is incorrect\n raise Exception(gettext(\n 'New values in column {0} are not of type {1}',\n ).format(col.name, col.data_type))\n\n # Condition 3: If there are categories, the new values should be\n # compatible with them.\n if col.categories and not all(\n row_val in col.get_categories() for row_val in data_frame[col.name]\n if row_val and not pd.isnull(row_val)\n ):\n raise Exception(gettext(\n 'New values in column {0} are not in categories {1}',\n ).format(col.name, ', '.join(col.categories)))",
"def _validate_constraint_columns(self, table_data):\n if any(col not in table_data.columns for col in self._constraint_columns):\n raise MissingConstraintColumnError()",
"def test_miinvestmentproject_columns_exist():\n destination_fields = _get_db_model_fields(MIInvestmentProject)\n available_destination_fields = destination_fields & ETLInvestmentProjects.COLUMNS\n missing_destination_fields = ETLInvestmentProjects.COLUMNS - available_destination_fields\n\n assert not missing_destination_fields, (\n 'Following required fields do not exist in the MIInvestmentProject model: '\n f'{\", \".join(missing_destination_fields)}. Ensure the changes are compatible with '\n 'MI Dashboards and update the pipeline specification (COLUMNS) accordingly.'\n )",
"def retrieve_metadata(dataframe):\n num_rows, num_columns = dataframe.shape\n columns = dataframe.columns.values.tolist()\n print('Data frame contains %d columns and %d rows' % (num_columns, num_rows))\n for elem in columns:\n print('column %s has %d empty rows'% (elem, sum(dataframe[elem].isnull())))",
"def check_select(tables, query):\n select_cols = query.get_Select()\n for c in select_cols:\n col_present = False\n for t in ts:\n if c in t.get_schema():\n col_present = True\n if not col_present:\n return (False, \"column \" + c + \" wasn't present in tables\")",
"def fields_exist(connection, table, fields):\n s = sql.select('*', from_obj=sql.table(table)).limit(0)\n all_fields = connection.execute(s).keys()\n exists = True\n for field in fields:\n exists = exists and field in all_fields\n return exists",
"def _check_field_mappings(\n column_names: List[str],\n feature_table_name: str,\n feature_table_timestamp_column: str,\n feature_table_field_mappings: Dict[str, str],\n) -> None:\n\n if feature_table_timestamp_column not in column_names:\n raise ValueError(\n f\"Provided data source does not contain timestamp column {feature_table_timestamp_column} in columns {column_names}\"\n )\n\n specified_field_mappings = list()\n for k, v in feature_table_field_mappings.items():\n specified_field_mappings.append(v)\n\n is_valid = all(col_name in column_names for col_name in specified_field_mappings)\n\n if not is_valid:\n raise Exception(\n f\"Provided data source does not contain all field mappings previously \"\n f\"defined for FeatureTable, {feature_table_name}.\"\n )"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Different logs sometimes have identical columns names but with different capitalization (for some reason); merge these columns.
|
def _deduplicate_columns(df):
to_check = df.columns.tolist()
leading_columns = []
to_merge = collections.defaultdict(collections.deque)
for column in to_check:
for leading_column in leading_columns:
if column.lower() == leading_column.lower() and column != leading_column:
to_merge[leading_column].append(column)
break
else:
leading_columns.append(column)
for leading_column, columns_to_merge in to_merge.items():
new_column = df[leading_column]
for column_to_merge in columns_to_merge:
new_column = new_column.combine_first(df[column_to_merge])
del df[column_to_merge]
del df[leading_column]
df[leading_column] = new_column
return df
|
[
"def _clean_column_names(self):\n self.logger.info(\"Set up column name cleaning.\")\n self.pipeline.steps.append(\n (\"clean_column_names\", TransformerWrapper(CleanColumnNames()))\n )",
"def _joined_names_column(df):\n return df.apply(\n lambda row: ','.join(set([\n six.text_type(n)\n for n in [row['main_name'], row['asciiname'], row['alternatenames']]\n if n and n is not np.nan\n ])),\n axis=1\n )",
"def row_merge_multiple_columns(row, dict_mapping):\n new_col_val = ''\n for key in dict_mapping:\n if not pd.isna(row[key]):\n new_col_val = new_col_val + dict_mapping[key] + ' '\n\n return new_col_val",
"def merge_data_columns(self, other: 'DataFrame'):\n for h in other._headers:\n if not h in self._headers:\n self._headers.append(h)\n\n append_rows = []\n\n for self_dict, other_dict in itertools.zip_longest(self._rows, other._rows):\n if not self_dict:\n d = {}\n append_rows.append(d)\n else:\n d = self_dict\n\n d_other = other_dict\n if d_other:\n for k,v in d_other.items():\n d[k] = v\n\n for r in append_rows:\n self._rows.append(r)",
"def extract_column_names(self) -> Dict[str, Tuple[str, str]]:\n fields = []\n for field in self.properties.keys():\n if not is_airbyte_column(field):\n fields.append(field)\n result = {}\n field_names = set()\n for field in fields:\n field_name = self.name_transformer.normalize_column_name(field, in_jinja=False)\n field_name_lookup = self.name_transformer.normalize_column_identifier_case_for_lookup(field_name)\n jinja_name = self.name_transformer.normalize_column_name(field, in_jinja=True)\n if field_name_lookup in field_names:\n # TODO handle column name duplicates or collisions deterministically in this stream\n for i in range(1, 1000):\n field_name = self.name_transformer.normalize_column_name(f\"{field}_{i}\", in_jinja=False)\n field_name_lookup = self.name_transformer.normalize_column_identifier_case_for_lookup(field_name)\n jinja_name = self.name_transformer.normalize_column_name(f\"{field}_{i}\", in_jinja=True)\n if field_name_lookup not in field_names:\n break\n field_names.add(field_name_lookup)\n result[field] = (field_name, jinja_name)\n return result",
"def rename_duplicated_columns(self):\n duplicated_columns = [\n col\n for col in self.catalog_columns\n if list(self.catalog_columns).count(col) > 1\n ]\n ran = 0\n for col in duplicated_columns:\n for idx in range(ran, len(self.catalog_columns)):\n if self.catalog_columns[idx] == col:\n self.catalog_columns[idx] = f\"{col}_{self.column_units[idx]}\"\n ran = idx\n break\n return self.catalog_columns",
"def clean_cols(data):\n clean_col_map = {x: x.lower().strip() for x in list(data)}\n return data.rename(index=str, columns=clean_col_map)",
"def standardize_cols(df, dd_name, settings):\n renamer = settings[\"col_rename_by_dd\"][dd_name]\n df = df.rename(columns=renamer)\n\n common = {\"PRTAGE\", \"HRMIS\", \"HRYEAR4\", \"PESEX\", \"HRMONTH\", \"PTDTRACE\",\n \"PEMLR\", \"PRERNWA\", \"PTWK\", \"PEMARITL\", \"PRDISC\",\n \"HEFAMINC\", \"PTDTRACE\", \"HWHHWGT\", \"PEERNHRY\", \"HRMIS\"}\n cols = set(df.columns.tolist())\n extra = cols - common\n missing = common - cols\n\n if missing:\n name = str(df.HRYEAR4.iloc[0]) + str(df.HRMONTH.iloc[0])\n key = ' '.join([str(arrow.utcnow()), name, 'missing'])\n d = {key: list(missing)}\n with open('make_hdf_store_log.json', 'a') as f:\n json.dump(d, f, indent=2)\n\n if extra:\n name = str(df.HRYEAR4.iloc[0]) + str(df.HRMONTH.iloc[0])\n key = ' '.join([str(arrow.utcnow()), name, 'extra'])\n d = {key: list(extra)}\n with open('make_hdf_store_log.json', 'a') as f:\n json.dump(d, f, indent=2)\n\n return df",
"def _merge_col_meta(out, left, right, col_name_map):\n # Set column meta\n attrs = ('units', 'format', 'description')\n for out_col in out.columns.values():\n left_name, right_name = col_name_map[out_col.name]\n left_col = (left[left_name] if left_name else None)\n right_col = (right[right_name] if right_name else None)\n\n if left_name and right_name:\n out_col.meta = meta.merge(left_col.meta, right_col.meta)\n for attr in attrs:\n left_attr = getattr(left_col, attr)\n right_attr = getattr(right_col, attr)\n merge_attr = left_attr or right_attr\n setattr(out_col, attr, merge_attr)\n if left_attr and right_attr and left_attr != right_attr:\n warnings.warn('Left and right column {0} attributes do not match '\n '({1} != {2}) using left for merged output'\n .format(attr, left_attr, right_attr),\n meta.MergeConflictWarning)\n elif left_name:\n out_col.meta = deepcopy(left_col.meta)\n for attr in attrs:\n setattr(out_col, attr, getattr(left_col, attr))\n elif right_name:\n out_col.meta = deepcopy(right_col.meta)\n for attr in attrs:\n setattr(out_col, attr, getattr(right_col, attr))\n else:\n raise ValueError('Unexpected column names')",
"def stripCols(self):\n for frame in self.files.values():\n for col in frame.columns:\n frame[col] = frame[col].str.strip()",
"def change_col_order(df: pd.DataFrame) -> pd.DataFrame:\n cols = df.columns.to_list()\n common_cols = list(('Name', 'type', 'Inputs', 'Outputs', 'latency.avg_time',\n 'latency.pct_time', 'total_footprint_bytes', 'tactic'))\n common_cols = [col for col in common_cols if col in cols]\n cols = common_cols + [col for col in cols if col not in common_cols]\n df = df[cols]\n return df",
"def _pre_wrap_with_ascii_replace(self, colname, datatype):\n pass",
"def tidy_data(df):\n\n ##clean up column headings\n df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '')",
"def _all_fields_no_dupes_columns(self):\n if self._extra_field_identifiers:\n # '\"imei_norm\", \"first\"(\"reporting_date\")'\n aggregate_field_names = [sql.SQL('first({ex})').format(ex=ex) for ex in self._extra_field_identifiers]\n return sql.SQL(', ').join(self._pk_field_identifiers + aggregate_field_names)\n return self._pk_field_columns",
"def rename_columns(self):\r\n self.columns = [self._date, self._net_purchase, self._gross_sale, self._tax, self._margin]\r\n self.all_data.columns = self.columns",
"def take_log(df_data, columns):\n log_data = df_data.copy()\n for i in columns:\n log_data[i] = np.log(log_data[i])\n rename_columns(log_data, {i: str(i) + '_log'})\n return log_data",
"def cleaning_columns_white_space(self, df):\n return df.rename(columns=lambda x: self.cleaning_some_white_space(x))",
"def _standardize_column_names(cls, data: pd.DataFrame):\n return data.rename(cls._get_column_mapping(), axis='columns')[cls.PPI_DATA_COL_LST].reset_index(drop=True)",
"def _mapColumnNames(self, oldColumns, newColumns):\n newToOldNameMapping = {}\n oldColumnsRemoved = []\n newColumnsAdded = []\n for ocol in oldColumns:\n if ocol in newColumns:\n newToOldNameMapping[ocol] = ocol\n elif self._renamedColumns.has_key(ocol):\n newToOldNameMapping[self._renamedColumns[ocol]] = ocol\n else:\n oldColumnsRemoved.append(ocol)\n for ncol in newColumns:\n if not ncol in oldColumns:\n if not ncol in self._renamedColumns.values():\n newColumnsAdded.append(ncol)\n return (oldColumnsRemoved, newColumnsAdded, newToOldNameMapping)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Write cached logs to database for a content type.
|
def _process_cache(self, content_type):
df = pandas.DataFrame(self.results_cache[content_type])
df = self._validate_column_names(df=df)
df = self._validate_column_value(df=df)
table_name = self._table_name_for(content_type=content_type)
engine = create_engine(self.connection_string)
with engine.connect():
try:
if not self._validate_existing_columns(df=df, content_type=content_type, engine=engine):
self._remake_table(new_data=df, content_type=content_type, engine=engine)
else:
logging.info("Committing {} records of type {} to table {}".format(
len(df), content_type, table_name))
df = df.loc[:, ~df.columns.duplicated()] # Remove any duplicate columns
df = self._deduplicate_columns(df=df)
df.to_sql(
name=table_name, con=engine, index=False, if_exists='append',
chunksize=int((self.collector.config['output', 'sql', 'chunkSize'] or 2000) / len(df.columns)),
method='multi')
except Exception as e:
self.unsuccessfully_sent += len(df)
raise e
else:
self.successfully_sent += len(df)
|
[
"def insert_to_cache(params,content):\n\tdir_name = get_dir_name(params)\n\tf = open(cache_folder+dir_name+'/data.csv',\"w\")\n\tf.write(content)\n\tf.close()",
"def _writeTmpCacheToCache(self, tmpCache, type_):\n cursor = self._conn.cursor()\n for index in tmpCache:\n data = tmpCache[index]\n values = index + tuple(data)\n cursor.execute(\"\"\"INSERT INTO %ss_cache\n VALUES(%s)\"\"\" % (type_, ('?,'*len(values))[0:-1]), values)\n cursor.close()",
"def store(contentType): # @NoSelf\n # If you do a big write()/loseConnection(), how do you tell when the\n # data has actually been written? you don't: commit() ought to return\n # a deferred anyway, and any un-flushed attachment data needs to be\n # dealt with by that too.",
"def log_content(self, sessionid, html):\n self.cursor.execute(\"INSERT INTO contenthistory (sessionid, html) VALUES (?,?);\", (sessionid, html))\n self.connection.commit()",
"def write(self):\r\n try:\r\n with open(self.cachefile, 'wb') as open_cache:\r\n pickle.dump(self.cache, open_cache)\r\n logging.debug('Cache file entries written: filename:cnt: %s:%s', \r\n self.cachefile, len(self.cachefile))\r\n except OSError:\r\n logging.error('Cache file could not be written: %s', self.cachefile)\r\n else:\r\n logging.info('Caching disabled. Touching file: %s', self.cachefile)\r\n touch(self.cachefile)",
"def write_cache(self):\n with open(self.output_filename+\"_cache\"+\".txt\", 'wb') as cache:\n cache.write(\"byte_count: \"+str(self.byte_count)+\"\\r\\n\")\n if self.ini_header.has_key(\"ETag\"):\n cache.write(\"ETag: \"+self.ini_header[\"ETag\"]+\"\\r\\n\")\n if self.ini_header.has_key(\"Last-Modified\"):\n cache.write(\"Last-Modified: \"+self.ini_header[\"Last-Modified\"]+\"\\r\\n\")\n if self.ini_header.has_key(\"Content-Length\"):\n cache.write(\"Content-Length: \"+str(self.content_length)+\"\\r\\n\")\n\n # print \"from extract: \" + cache_dict[\"Content-Length\"",
"def save_to_time_file(self, content, output_file, type=\"wb\", formator='YYYY-MM-DD-HH'):\n local_path = settings.LOCAL_DATAFILE_DIRS\n\n # test.log ==> test{0}.log ==> test-2017-7-7.log\n _output_file = output_file.split('.')\n if len(_output_file) >= 2:\n _output_file[-2] = _output_file[-2] + '-{0}'\n output_file = '.'.join(_output_file)\n else:\n output_file = output_file + '-{0}'\n\n output_path = os.path.join(local_path, self.project_name, output_file)\n\n with open(output_path.format(arrow.now().replace(hours=8).format(formator)), type) as f:\n f.write(content)\n\n return {\n \"status\": True\n }",
"def save_logs(self, log_count):\n with open(self.FILE_PATH) as log_file:\n with tqdm(total=log_count, desc='save to database', ) as pbar:\n record_list = []\n record_count = 1\n for line in log_file:\n\n record = self.parse_line(line)\n if record is None:\n continue\n record_list.append(LogItem(\n ip=record['ip'],\n datetime=self.parse_date(record['date']),\n method=record['method'],\n uri=record['uri'],\n status_code=record['status'],\n body_size=record['body_size'],\n user_agent=record['agent']\n ))\n\n if record_count == self.MASS_SAVE_COUNT:\n LogItem.objects.bulk_create(record_list)\n record_list = []\n record_count = 0\n pbar.update(1)\n record_count += 1",
"def save_log(self,text, stype='',svalue=0):\n gui.logs.append(text)\n self.insert_DB(text)",
"def save(cls):\n\n # Retrieve the save directory from settings\n logdir = Settings.get_logdir()\n # Create the save directory if necessary\n if not logdir.exists():\n os.makedirs(logdir)\n\n # Retrieve the full save path from settings\n logpath = Settings.get_logpath()\n # Write the log out to the file.\n with logpath.open(\"w\", encoding=\"utf-8\") as file:\n for entry in cls._log.values():\n file.write(\n (\n f\"{entry.timestamp_as_string()}|\"\n f\"{entry.duration_as_string()}|\"\n f\"{entry.notes}\\n\"\n )\n )",
"def applyCache(self, path, type):\n\t\t\n\t\treturn None",
"def append_log_cache(self, logname, data, delivery = True):\n if delivery:\n self.append_delivery_data(data)\n filename = self._get_log_cache_filename(logname)\n f = open(filename, \"at\")\n f.write(simplejson.dumps(data) + \"\\n\")\n f.close()",
"def store(self, result: Any) -> None:\n if not self.cache_file_exists():\n logger.info(f\"STORE {self} to {self.cache_fs}/{self.hash}\")\n try:\n # Store to cache.\n start_time = time.perf_counter()\n self.serialize(result, self.cache_fs, self.hash)\n store_time = time.perf_counter() - start_time\n # Write store time and log operation\n self.write_time(\"store\", store_time)\n self.write_log(\"store\")\n except Exception:\n # Not crucial to stop if caching fails.\n logger.exception(f\"Could not write {self.hash}.\")",
"def log(self, message):\n timestamp = datetime.datetime.now().isoformat()\n try:\n with open('logfile.txt','a') as logfile:\n logfile.write(f\"{timestamp} - {self.logType} : {message}\\n\")\n except FileNotFoundError:\n with open('logfile.txt', 'w') as logfile:\n logfile.write(f\"{timestamp} - {self.logType} : {message}\\n\")",
"def write_to_logs(self, data):\n time_now = str(datetime.now())\n time_now = time_now[:time_now.index(\".\")]\n try:\n with open(f\"Logs\\\\Channel Number {self.id} Logs.txt\", \"a\", encoding=\"utf-8\") as f:\n f.write(time_now + \" | \" + data + \"\\n\\n\")\n except Exception as e:\n print(e)\n print(\"An error occurred with writing the logs.\\nPlease check if the Logs directory exists.\")",
"def _log_to_project_history(project, action_time, action_type, message):\r\n Project = get_model('projects', 'Project')\r\n key = redis_key_for_project(project)\r\n data = {\r\n 'action_time': action_time,\r\n 'message': message,\r\n 'action_type': action_type,\r\n }\r\n r = TxRedisMapper()\r\n r.lpush(key, data=data)\r\n r.ltrim(key, 0, 4)\r\n\r\n # Store logs in hubs, too\r\n if project.outsource:\r\n _log_to_project_history(\r\n project.outsource, action_time, action_type, message\r\n )",
"def logToDir(directory='logs', LOG_TYPE=('console',), OBSERVER=MyLogObserver):\n args = ()\n kwargs = {'maxRotatedFiles': 7} #seven days of logs by default\n try: import config #fix for early logging\n except: config = None #also works around daemon wrappers\n if config and config.RETAINED_LOGS:\n kwargs.update({'maxRotatedFiles': config.RETAINED_LOGS})\n for name in LOG_TYPE:\n path = os.path.join(directory, name + '.log')\n logfile = DailyPurgingLogFile.fromFullPath(path, *args, **kwargs)\n logs[name] = OBSERVER(logfile)",
"def saveFlow(self, flow):\n category = input(\"Please give this a category to save to: \")\n directory = self.path + \"/Logs/WebsiteData/\"\n f: typing.IO[bytes] = open(directory + category + \".logfile\" \"\", \"ab\")\n flowWriter = io.FlowWriter(f)\n flowWriter.add(flow)\n f.close()\n ctx.log.info(\"flow saved for category: \" + category + \".logfile\")",
"def log_transaction(self, request):\n self.storage.write_transaction(request)\n self.transaction_history.append(request)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test the trained naive bayes model (self.prior and self.likelihood) on testing dataset, by performing maximum a posteriori (MAP) classification. The accuracy is computed as the average of correctness by comparing between predicted label and true label.
|
def test(self, test_set, test_label):
# YOUR CODE HERE
accuracy = 0
pred_label = np.zeros((len(test_set)))
probs = np.zeros((len(test_set)))
# predict every sample X by likelihood
for X_idx, X in tqdm(enumerate(test_set), total=len(pred_label), desc='BAYES MODEL TEST'):
# initial final log_probs by prior prob
# log_probs = self.prior.copy()
log_probs = np.log(self.prior)
for y_i in range(self.num_class):
for f_i in range(self.feature_dim):
log_probs[y_i] += np.log(self.likelihood[f_i, X[f_i], y_i])
this_predict_label = np.argmax(log_probs)
pred_label[X_idx] = this_predict_label
probs[X_idx]=max(log_probs)
# calculate acc rate
accuracy = np.sum(pred_label == test_label) / len(pred_label)
return accuracy, pred_label, probs
|
[
"def test(self, file_dir=\"training_data\"):\n print(\"loading testing data\")\n test_data = MNIST(file_dir)\n img, lbl = test_data.load_testing()\n\n correct = 0\n for i in range(0, len(img)):\n self.classify(img[i])\n b = np.where(self.activations[-1] == max(self.activations[-1]))[0][0]\n c = lbl[i]\n if (np.where(self.activations[-1] == max(self.activations[-1]))[0][0]) == lbl[i]:\n correct += 1\n\n print(str((correct / len(img)) * 100) + \" % accuracy\")",
"def naive_bayes_predict(data, model):\n # TODO: INSERT YOUR CODE HERE FOR USING THE LEARNED NAIVE BAYES PARAMETERS\n # TO CLASSIFY THE DATA\n\n d, n = data.shape #features = d / examples = n ; #row/#col\n num_classes = model['p(y)'].size\n ddata = data\n idata = 1 - ddata #inverted probability\n fmodel = 1 - model['p(x|y)'] #inverted cond probability\n\n predicted_data = np.zeros((num_classes,n))\n\n for i in range(num_classes):\n \n prior = model['p(y)'][i]\n cond = model['p(x|y)'][i, :] #length d vector\n \n fcond = fmodel[i, :] #false conditional prob\n \n # Error bound checking for np.log for a zero argument to avoid the Runtime Warning#######\n logPrior = 0\n if (prior <= 0):\n logPrior = -999999999\n else:\n logPrior = np.log(prior)\n\n logCond = np.zeros(len(cond))\n flogCond = np.zeros(len(fcond))\n for j in range(cond.shape[0]):\n if cond[j] <= 0:\n logCond[j] = -999999999\n else:\n logCond[j] = np.log(cond[j])\n flogCond[j] = np.log(fcond[j])\n #########################################################################################\n \n # model class by feat and data is feat by examples\n # dot product cancels out feat so you are given class by example\n\n #i by exmaple aka 1 by n\n sum_scores = logCond.dot(ddata) + flogCond.dot(idata) + logPrior \n\n predicted_data[i, :] = sum_scores\n\n max_scores = predicted_data.argmax(0) #max within each col, where each col is an example; # 1 x n\n return max_scores",
"def test(self,test_set,test_label): \n\n\t\t# YOUR CODE HERE\n\t\tpred_label = np.zeros((len(test_set)))\n\n\t\ttest_set_biased = np.c_[test_set, np.ones(test_set.shape[0])]\n\t\tyhat = np.matmul(test_set_biased,self.w)\n\t\t\n\t\tpred_label = np.argmax(yhat, axis=1)\n\n\t\taccuracy = np.sum(np.equal(test_label,pred_label)) / len(test_set)\n\n\t\t# EVALUATION\n # get image with highest and lowest perceptron weight from each class\n\t\tself.highestPosteriorImages = np.zeros((self.feature_dim, self.num_class))\n\t\tself.lowestPosteriorImages = np.zeros((self.feature_dim, self.num_class))\n\n\t\tsummed = yhat\n\n\t\tlabelArgs = [np.nonzero(test_label == l)[0] for l in range(self.num_class)]\n\n\t\tfor classIdx, argsInClass in enumerate(labelArgs):\n\t\t\tmaxArg = np.argmax(summed[argsInClass, classIdx], axis=0)\n\t\t\tminArg = np.argmin(summed[argsInClass, classIdx], axis=0)\n\t\t\tself.highestPosteriorImages[:,classIdx] = (test_set[argsInClass])[maxArg]\n\t\t\tself.lowestPosteriorImages[:,classIdx] = (test_set[argsInClass])[minArg]\n\n\t\tprint (\"Perceptron Accuracy:\", accuracy)\n\t\t\n\t\treturn accuracy, pred_label",
"def _test(self,testing_features_df,best_models_dict):\n best_model=best_models_dict['GaussianNB']\n pred=best_model.predict(testing_features_df.loc[:,testing_features_df.columns != 'Label'].values)\n score=metrics.f1_score(testing_features_df['Label'].values,pred)\n logger.info(\"F1-score on the testing dataset: \" + str('{0:.2f}'.format(score)))",
"def test_predict_proba_classifier(self):\n\n neigh = KNeighborsClassifier(metric=lp_distance)\n\n neigh.fit(self.X, self.y)\n probs = neigh.predict_proba(self.X)\n\n np.testing.assert_array_almost_equal(probs, self.probs)",
"def predict(self, test_data, predict_proba = False, pred_class_and_proba = False):\n pass",
"def test_predict_classifier(self):\n\n for neigh in (KNeighborsClassifier(),\n RadiusNeighborsClassifier(radius=.1),\n NearestCentroids(),\n NearestCentroids(metric=lp_distance, mean=l2_mean)):\n\n neigh.fit(self.X, self.y)\n pred = neigh.predict(self.X)\n np.testing.assert_array_equal(pred, self.y,\n err_msg=f\"fail in {type(neigh)}\")",
"def log_testing(self, model: CapiModel, testing_data: NdArrayLike, testing_labels: NdArrayLike,\n label_map: Dict[int, str] = None) -> NdArrayLike:\n test_pred = self.predict(model, testing_data)\n test_scores = self.scorer(testing_labels, test_pred)\n print(f\"test results for fold number {self.fold}:\")\n\n for metric, score in test_scores:\n print(f\" {metric}: {score}\")\n\n print(\"----------------------------------------\")\n\n if self.use_logger:\n wandb.log({\"test \" + metric: score for (metric, score) in test_scores}, commit=False)\n if self.task == Task.CLF:\n wandb.log({\"testing confusion matrix\": wandb.plot.confusion_matrix(probs=test_pred,\n y_true=testing_labels,\n class_names=list(\n label_map.values()))},\n commit=False)\n\n return test_pred",
"def run(self, x_train_vect, y_train, x_test_vect, y_test):\n\t\tself.MultinomialNB.fit(x_train_vect, y_train)\n\t\tself.predicted = self.MultinomialNB.predict(x_test_vect)\n\t\tself.percent_score = self.MultinomialNB.score(x_test_vect, y_test) * 100",
"def predict_NN(self):\r\n data = self.data_train1\r\n labels = self.labels_train\r\n data_test = self.data_test1\r\n labels_test = self.labels_test\r\n \r\n model = MLPClassifier()\r\n model.fit(data, labels.iloc[:,0])\r\n prediction = model.predict(data_test) \r\n model_score = model.score(data_test, labels_test)\r\n \r\n self.NN_prediction = prediction\r\n self.NN_score = model_score",
"def evaluate_binary_model(self):\n baseline = {}\n baseline['accuracy'] = accuracy_score(self.y_test, [1 for _ in range(\n len(self.y_test))]) # always predict the majority class\n baseline['recall'] = recall_score(\n self.y_test, [1 for _ in range(len(self.y_test))]) # always predict positive\n baseline['precision'] = precision_score(\n self.y_test, [1 for _ in range(len(self.y_test))]) # always predict positive\n baseline['roc'] = 0.5\n baseline['F1score'] = 2 * 0.5 / (0.5 + 1)\n\n test_results = {}\n test_results['accuracy'] = accuracy_score(self.y_test, self.pred_test)\n test_results['recall'] = recall_score(self.y_test, self.pred_test)\n test_results['precision'] = precision_score(\n self.y_test, self.pred_test)\n test_results['roc'] = roc_auc_score(self.y_test, self.prob_test)\n test_results['F1score'] = f1_score(\n self.y_test, self.pred_test) # binary classifier\n\n train_results = {}\n train_results['accuracy'] = accuracy_score(\n self.y_train, self.pred_train)\n train_results['recall'] = recall_score(self.y_train, self.pred_train)\n train_results['precision'] = precision_score(\n self.y_train, self.pred_train)\n train_results['roc'] = roc_auc_score(self.y_train, self.prob_train)\n train_results['F1score'] = f1_score(self.y_train, self.pred_train)\n\n for metric in ['accuracy', 'recall', 'precision', 'roc', 'F1score']:\n print(f'\\n{metric.capitalize()}\\n'\n f'Baseline: {round(baseline[metric], 3)} | '\n f'Test: {round(test_results[metric], 3)} | '\n f'Train: {round(train_results[metric], 3)} ')",
"def evaluate_posterior_predictive(\n samples: xr.Dataset, test: xr.Dataset\n ) -> np.ndarray:\n # size: [iterations, num_categories]\n prev = samples.prev.values\n # size: [iterations, k, num_categories, num_categories]\n confusion_matrix = samples.confusion_matrix.values\n labels = test.labels.values\n labelers = test.labelers.values\n # size of confusion_matrix[:, labelers, :, labels]\n # is [n/2, num_categories, iterations, num_categories]\n likelihood = logsumexp(\n np.log(confusion_matrix[:, labelers, :, labels]).sum(axis=1) + np.log(prev),\n axis=2,\n ).sum(axis=0)\n\n return np.array(likelihood)",
"def evaluate(self, test_data, training_data=None):\n if training_data is not None:\n self.train(training_data)\n pred = self.predict(test_data)\n y_true = test_data.Y.reshape(-1)\n if len(pred.shape) == 3:\n y_pred = pred.reshape(-1, pred.shape[2])\n num_labels = y_pred.shape[-1]\n labels = np.arange(num_labels)\n loss = sklearn.metrics.log_loss(y_true=y_true, y_pred=y_pred,\n labels=labels)\n\n y_pred_best = np.argmax(y_pred, -1)\n acc = sklearn.metrics.accuracy_score(y_true, y_pred_best)\n print loss, acc\n return loss, acc",
"def __check_model_accuracy(self, model: Pipeline, test_data: DataList) -> float:\n predictions = model.predict(test_data.texts)\n return f1_score(test_data.labels, predictions, average='micro')",
"def check_accuracy_on_test():\n correct = 0\n total = 0\n model.eval()\n with torch.no_grad():\n for inputs, labels in testloader:\n inputs, labels = inputs.to(device), labels.to(device)\n outputs = model(inputs)\n _, predicted = torch.max(outputs.data, 1) #gets tensor of predicted classes for max probability values from outputs\n total += labels.size(0)\n correct += (predicted == labels).sum().item() \n print('Accuracy of the network on test data: %d %%' % (100 * correct / total))",
"def do_predictions(self):\n\n self.train_preds = self.tfmodel.predict(self.Data.X_train)\n self.test_preds = self.tfmodel.predict(self.Data.X_test)\n\n self.Helpers.logger.info(\n \"Training predictions: \" + str(self.train_preds))\n self.Helpers.logger.info(\n \"Testing predictions: \" + str(self.test_preds))\n print(\"\")",
"def predict(self, test_data, predict_proba = False, pred_class_and_proba = False):\n X_test, y_test, _ = processData(data=test_data, label_column=self.ag_predictor._learner.label, ag_predictor=self.ag_predictor)\n if self.ag_predictor.problem_type == REGRESSION:\n pred_class_and_proba = False\n predict_proba = False\n y_pred = None\n y_prob = None\n t0 = time.time()\n if (not predict_proba) or pred_class_and_proba:\n y_pred = self.model.predict(X_test)\n y_pred = self.ag_predictor._learner.label_cleaner.inverse_transform(pd.Series(y_pred))\n if predict_proba or pred_class_and_proba:\n y_prob = self.model.predict_proba(X_test)\n y_prob = self.ag_predictor._learner.label_cleaner.inverse_transform_proba(y_prob) # handles rare classes possibly omitted during processing\n self.classes = autogluon_class_order(self.ag_predictor) # ordering of classes corresponding to columns of y_prob\n t1 = time.time()\n predict_time = t1 - t0\n return (y_pred, y_prob, predict_time)",
"def run(X_train, y_train, X_test, y_test, _k=[1]):\n # Compute distances:\n dists = mlBasics.compute_euclidean_distances(X_train, X_test)\n\n print \"Distances computed\"\n\n # For all k,\n for k in _k:\n\n # Predict labels\n y_test_pred = mlBasics.predict_labels(dists, y_train, k=k)\n\n print '{0:0.02f}'.format(np.mean(y_test_pred == y_test) * 100), \"of test examples classified correctly. k =\", key",
"def test_on_dense_dataset(self):\n # Train on sample data\n self.binary_lr_trainer.fit(X=self.x_train,\n y=self.y_train,\n weights=None,\n offsets=None)\n\n # Get predictions and metrics on the training data\n training_pred = self.binary_lr_trainer.predict_proba(X=self.x_train,\n offsets=None)\n training_metrics = self.binary_lr_trainer.compute_metrics(X=self.x_train,\n y=self.y_train,\n offsets=None)\n # Assert prediction shape matches expectation, and training metrics are within expected range\n assert (0.0 <= training_metrics['auc'] <= 1.0)\n assert (training_pred.shape[0] == self.x_train.shape[0])"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get the feature likelihoods for high intensity pixels for each of the classes, by sum the probabilities of the top 128 intensities at each pixel location,
|
def intensity_feature_likelihoods(self, likelihood):
# YOUR CODE HERE
feature_likelihoods = np.sum(likelihood[:, 128:256, :], axis=1)
return feature_likelihoods
|
[
"def top2gating(logits: torch.Tensor, capacity_factor: float) ->Tuple[Tensor, Tensor, Tensor, Tensor]:\n gates = F.softmax(logits, dim=1)\n num_tokens = gates.shape[0]\n num_experts = gates.shape[1]\n capacity = math.ceil(2 * num_tokens / num_experts * capacity_factor)\n indices1_s = torch.argmax(gates, dim=1)\n mask1 = F.one_hot(indices1_s, num_classes=num_experts)\n logits_w_noise = logits + gumbel_rsample(logits.shape, device=logits.device)\n logits_except1 = logits_w_noise.masked_fill(mask1.bool(), float('-inf'))\n indices2_s = torch.argmax(logits_except1, dim=1)\n mask2 = F.one_hot(indices2_s, num_classes=num_experts)\n locations1 = torch.cumsum(mask1, dim=0) - 1\n locations2 = torch.cumsum(mask2, dim=0) - 1\n locations2 += torch.sum(mask1, dim=0, keepdim=True)\n exp_counts = torch.sum(mask1, dim=0).detach()\n me = torch.mean(gates, dim=0)\n ce = torch.mean(mask1.float(), dim=0)\n l_aux = torch.mean(me * ce) * num_experts * num_experts\n mask1 *= torch.lt(locations1, capacity)\n mask2 *= torch.lt(locations2, capacity)\n locations1_s = torch.sum(locations1 * mask1, dim=1)\n locations2_s = torch.sum(locations2 * mask2, dim=1)\n mask1_float = mask1.float()\n mask2_float = mask2.float()\n gates1_s = torch.einsum('se,se->s', gates, mask1_float)\n gates2_s = torch.einsum('se,se->s', gates, mask2_float)\n denom_s = gates1_s + gates2_s\n denom_s = torch.clamp(denom_s, min=torch.finfo(denom_s.dtype).eps)\n gates1_s /= denom_s\n gates2_s /= denom_s\n gates1 = torch.einsum('s,se->se', gates1_s, mask1_float)\n gates2 = torch.einsum('s,se->se', gates2_s, mask2_float)\n locations1_sc = F.one_hot(locations1_s, num_classes=capacity).float()\n locations2_sc = F.one_hot(locations2_s, num_classes=capacity).float()\n combine1_sec = torch.einsum('se,sc->sec', gates1, locations1_sc)\n combine2_sec = torch.einsum('se,sc->sec', gates2, locations2_sc)\n combine_weights = combine1_sec + combine2_sec\n dispatch_mask = combine_weights.bool()\n return l_aux, combine_weights, dispatch_mask, exp_counts",
"def calculate_feature_entropy_for_array(bp_array):\n\n bp_list = [bp_array[:, i] for i in range(bp_array.shape[1])]\n H = np.asarray(list(map(calculate_feature_entropy, bp_list)))\n return H",
"def nb_predict(X, class_prob, class_word_prob):\r\n Ypred = []\r\n ###################################################\r\n # Q8.1 Edit here\r\n ###################################################\r\n for i in range(len(X)):\r\n listinx = X[i]\r\n tempp = []\r\n for indexclass in range(len(class_prob)):\r\n p = calculatelog(class_prob[indexclass])\r\n for j in range(len(listinx)):\r\n if class_word_prob[indexclass, listinx[j][0]] == -1:\r\n continue\r\n p += listinx[j][1] * calculatelog(class_word_prob[indexclass, listinx[j][0]])\r\n\r\n tempp.append(p)\r\n\r\n if(tempp[0] > tempp[1]):\r\n Ypred.append(0)\r\n else:\r\n Ypred.append(1)\r\n\r\n return Ypred",
"def softmax(logits):\n # print(\"logit\", logits.shape)\n\n clas = np.exp(np.minimum(logits, 22.))\n clas = clas / np.maximum(np.sum(clas, axis=-1, keepdims=True), 1e-10)\n return clas",
"def non_max_suppression(prediction, num_classes, conf_thres=0.5, nms_thres=0.4):\n B, num_predictions, _ = prediction.size()\n\n # From (center x, center y, width, height) to (x1, y1, x2, y2)\n box_corner = prediction.new(B, num_predictions, 4)\n box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2\n box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2\n box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2\n box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2\n prediction[:, :, :4] = box_corner[:, :, :4]\n\n outputs = []\n\n for image_pred in prediction:\n # Filter out confidence scores below threshold\n conf_mask = (image_pred[:, 4] >= conf_thres).squeeze() # (num_predictions)\n image_pred = image_pred[conf_mask]\n # If none are remaining => process next image\n if image_pred.size()[0] == 0:\n outputs.append(None)\n continue\n img_outputs = []\n # Get score and class with highest confidence\n class_conf, class_pred = torch.max(image_pred[:, 5:5 + num_classes], 1, keepdim=True)\n # Detections ordered as (x1, y1, x2, y2, obj_conf, class_conf, class_pred)\n detections = torch.cat((image_pred[:, :5], class_conf.float(), class_pred.float()), 1)\n # Iterate through all predicted classes\n unique_labels = detections[:, -1].cpu().unique()\n if prediction.is_cuda:\n unique_labels = unique_labels.cuda()\n for c in unique_labels:\n # Get the detections with the particular class\n detections_class = detections[detections[:, -1] == c]\n # Sort the detections by maximum objectness confidence\n _, conf_sort_index = torch.sort(detections_class[:, 4], descending=True)\n detections_class = detections_class[conf_sort_index]\n # Perform non-maximum suppression\n max_detections = []\n while detections_class.size(0):\n # Get detection with highest confidence and save as max detection\n max_detections.append(detections_class[0].unsqueeze(0))\n # Stop if we're at the last detection\n if len(detections_class) == 1:\n break\n # Get the IOUs for all boxes with lower confidence\n ious = bbox_iou(max_detections[-1], detections_class[1:])\n # Remove detections with IoU >= NMS threshold\n detections_class = detections_class[1:][ious < nms_thres]\n\n max_detections = torch.cat(max_detections).detach()\n # Add max detections to outputs\n img_outputs.append(max_detections)\n outputs.append(torch.cat(img_outputs, dim=0)) # (num_detections x 7)\n\n dict_outputs = []\n for output in outputs:\n if output is None:\n dict_outputs.append({\n 'boxes': torch.zeros(0, 4),\n 'conf': torch.zeros(0),\n 'cls_conf': torch.zeros(0),\n 'classes': torch.zeros(0)\n })\n continue\n num_predictions = output.size()[0]\n\n box_coords = output[:, :4]\n # (x1y1x2y2 to x1y1wh)\n bbox = box_coords.new(*box_coords.size())\n bbox[:, :2] = box_coords[:, :2]\n bbox[:, 2:] = box_coords[:, 2:] - box_coords[:, :2]\n\n if num_classes == 1:\n cls_conf = output.new_ones(num_predictions, dtype=torch.float)\n classes = output.new_zeros(num_predictions, dtype=torch.long)\n else:\n cls_conf = output[:, 5]\n classes = output[:, 6]\n\n dict_outputs.append({\n 'boxes': bbox,\n 'conf': output[:, 4],\n 'cls_conf': cls_conf,\n 'classes': classes\n })\n\n return dict_outputs",
"def classprob(features,Y,beta):\n\n sigma = lambda z: 1/(1+(exp(-z)))\n usigma = frompyfunc(sigma,1,1)\n\n prob = usigma(features*beta)\n\n return prob",
"def calculate_feature_entropy(birth_point_array):\n\n zero_num = np.count_nonzero(birth_point_array == 0)\n selective_rate = zero_num/ len(birth_point_array)\n birth_point_array = birth_point_array[birth_point_array != 0] # remove zeros\n total_num_without0 = len(birth_point_array)\n unique, counts = np.unique(birth_point_array, return_counts=True)\n counts_ratio = counts / total_num_without0\n log_counts_ratio = np.log(counts_ratio)\n feature_entropy = -1 * sum(counts_ratio * log_counts_ratio)\n\n if selective_rate != 1: \n ineffectiveness = feature_entropy / (1- selective_rate)\n else: \n ineffectiveness = feature_entropy\n\n return (feature_entropy, selective_rate, ineffectiveness)",
"def get_score(self, logits):\n return tf.nn.log_softmax(logits)",
"def setEntropy(classCounts):\n \n e = 0\n for count in classCounts:\n count = float(count)\n total_class_counts = sum(classCounts)\n count = count / total_class_counts\n tot = -(count * log(count, 2))\n e += tot\n return e",
"def get_entropy(self, examples_and_tags):\n tags = [tag for example, tag in examples_and_tags]\n if not tags:\n return 0\n tags_and_total_num = Counter()\n entropy = 0.0\n p_per_class = []\n for tag in tags:\n tags_and_total_num[tag] += 1\n for tag_total_num in tags_and_total_num:\n p_per_class.append(float(tags_and_total_num[tag_total_num]) / len(tags))\n for p in p_per_class:\n if p == 0:\n return 0\n entropy += -p * math.log(p, 2)\n return entropy",
"def search(Y, x, u, top_n):\n coefs=np.array([x.dot(vector) for vector in u.T])\n top_imgs=[]\n for img in Y:\n coefs_img=np.array([img.dot(vector) for vector in u.T])\n dist=np.linalg.norm(coefs-coefs_img)\n top_imgs.append((dist,img))\n if len(top_imgs)<=top_n:\n continue\n sorted(top_imgs,key=lambda x:x[0]) #sort according to the distance ascendingly\n del top_imgs[-1] #delete the last one (the furthest one)\n top_imgs=np.array([img[1] for img in top_imgs])\n return top_imgs #np.random.random((top_n, 256))",
"def _profile_likelihood_maximization(self,U, n_elbows):\n if type(U) == list: # cast to array for functionality later\n U = np.array(U)\n\n if n_elbows == 0: # nothing to do..\n return np.array([])\n\n if U.ndim == 2:\n U = np.std(U, axis=0)\n\n if len(U) == 0:\n return np.array([])\n\n elbows = []\n\n if len(U) == 1:\n return np.array(elbows.append(U[0]))\n\n # select values greater than the threshold\n U.sort() # sort\n U = U[::-1] # reverse array so that it is sorted in descending order\n n = len(U)\n\n U = U[:self.hyperparams['max_dimension']].copy()\n\n while len(elbows) < n_elbows and len(U) > 1:\n d = 1\n sample_var = np.var(U, ddof=1)\n sample_scale = sample_var ** (1 / 2)\n elbow = 0\n likelihood_elbow = 0\n while d < len(U):\n mean_sig = np.mean(U[:d])\n mean_noise = np.mean(U[d:])\n sig_likelihood = 0\n noise_likelihood = 0\n for i in range(d):\n sig_likelihood += norm.pdf(U[i], mean_sig, sample_scale)\n for i in range(d, len(U)):\n noise_likelihood += norm.pdf(U[i], mean_noise, sample_scale)\n\n likelihood = noise_likelihood + sig_likelihood\n\n if likelihood > likelihood_elbow:\n likelihood_elbow = likelihood\n elbow = d\n d += 1\n if len(elbows) == 0:\n elbows.append(elbow)\n else:\n elbows.append(elbow + elbows[-1])\n U = U[elbow:]\n\n if len(elbows) == n_elbows:\n return np.array(elbows)\n\n if len(U) == 0:\n return np.array(elbows)\n else:\n elbows.append(n)\n return np.array(elbows)",
"def feature_extractor(X_train, X_test):\n \n hog_train = []\n hog_test = []\n sift_train = []\n sift_test = []\n hog = cv2.HOGDescriptor()\n #HOGFeatureExtractor()\n \n winSize = (64,64)\n blockSize = (16,16)\n blockStride = (8,8)\n cellSize = (8,8)\n nbins = 9\n derivAperture = 1\n winSigma = 4.\n histogramNormType = 0\n L2HysThreshold = 2.0000000000000001e-01\n gammaCorrection = 0\n nlevels = 64\n hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma,\n histogramNormType,L2HysThreshold,gammaCorrection,nlevels)\n winStride = (8,8)\n padding = (8,8)\n locations = ((10,20),)\n \n for img in X_train:\n kps, descs = sift(img)\n #if len(img.shape) == 2 :\n #img = img[:,:,numpy.newaxis]\n hog_train.append(hog.compute(img,winStride,padding,locations))\n if descs is None:\n sift_train.append([])\n else:\n sift_train.append(descs)\n i += 1\n if i%1000 == 0:\n print(i,datetime.now()-t)\n\n for img in X_test: \n kps, descs = sift(img)\n #if len(img.shape) == 2 :\n #img = img[:,:,numpy.newaxis]\n hog_test.append(hog.compute(img,winStride,padding,locations))\n if descs is None:\n sift_test.append([])\n else:\n sift_test.append(descs)\n \n return hog_train, hog_test, sift_train, sift_test",
"def calculateFeatureEntropy(binProbabilities):\n\t\n\ttotalEntropy = 0\n\tfor p in binProbabilities:\n\t\ttotalEntropy += calculateEntropy(p)\n\t\t\n\treturn totalEntropy",
"def Otsu(Thresholds,image):\r\n Thresholds.append(256)\r\n Thresholds.insert(0, 0)\r\n Thresholds.sort()\r\n img = Image.open(image).convert(\"L\")\r\n img=np.asarray(img)\r\n\r\n hist = [0] * 256 \r\n for i in range(len(img)):\r\n for j in range(len(img[0])):\r\n hist[int(img[i][j])] += 1\r\n\r\n Total_Pixels = len(img)*len(img[0])\r\n\r\n for i in range(len(hist)): # Probabilities\r\n hist[i] = hist[i] / Total_Pixels\r\n\r\n cumulative_sum = [] # declaractions\r\n cumulative_mean = []\r\n global_mean = 0\r\n Sigma = 0\r\n\r\n for i in range(len(Thresholds)-1):\r\n cumulative_sum.append(sum(hist[Thresholds[i]:Thresholds[i + 1]])+eps) # Cumulative sum of each Class\r\n\r\n cumulative = 0\r\n for j in range(Thresholds[i], Thresholds[i + 1]):\r\n cumulative = cumulative + (j + 1) * hist[j]\r\n \r\n cumulative_mean.append(cumulative / cumulative_sum[-1]) # Cumulative mean of each Class\r\n\r\n global_mean = global_mean + cumulative # Global Intensity Mean\r\n\r\n for i in range(len(cumulative_mean)): # Computing Sigma\r\n Sigma = Sigma + (cumulative_sum[i] *\r\n ((cumulative_mean[i] - global_mean) ** 2))\r\n\r\n return(Sigma)",
"def entropy(probs):\n return sum(-v*log(v,2) for v in probs.values())",
"def profile_multinomial_nll(true_profs, log_pred_profs, true_counts):\n num_samples = true_profs.shape[0]\n num_tasks = true_profs.shape[1]\n\n # Swap axes on profiles to make them N x T x 2 x O\n true_profs = np.swapaxes(true_profs, 2, 3)\n log_pred_profs = np.swapaxes(log_pred_profs, 2, 3)\n\n nll = -multinomial_log_probs(log_pred_profs, true_counts, true_profs)\n return np.mean(nll, axis=2) # Average strands",
"def extract_dataset_features(classes_imgs, labels, config):\n all_features = []\n all_labels = []\n for i, class_imgs in enumerate(classes_imgs):\n class_features = []\n class_labels = np.repeat(labels[i], len(class_imgs))\n all_labels = class_labels if len(all_labels) == 0 else np.concatenate((all_labels, class_labels))\n for class_img_path in class_imgs:\n img = load_image(class_img_path)\n img_features = compute_features(img, color_space=config.color_space, \n hog_orient=config.hog_orientations, \n hog_pix_per_cell=config.hog_pixels_per_cell,\n hog_cells_per_block=config.hog_cells_per_block,\n hog_color_channels=config.hog_color_channels)\n class_features.append(img_features)\n\n all_features.append(class_features)\n \n normed_features, normaliser = normalise_features(all_features) \n return normed_features, all_labels, normaliser",
"def gain_calculate(merged_freq_dict): # {austen : [1232, 332], milton : [232, 622]}\n\tTOTAL = sum([i for a in merged_freq_dict.values() for i in a])\n\teach_small_big = [i for i in merged_freq_dict.values()];\n\tTOTAL_class = [sum(i) for i in each_small_big] \t\t#[982, 512, 1102(small+big in one class),...]\n\tTOTAL_entropy_in = [each/sum(TOTAL_class) for each in TOTAL_class]\n\tTOTAL_entropy = entropy(TOTAL_entropy_in)\n\tsmall_TOTAL \t = sum([ i[0] for i in each_small_big])/TOTAL\n\tbig_TOTAL \t\t = sum([ i[1] for i in each_small_big])/TOTAL\n\n\tclass_by_small, class_by_big = list(), list()\n\tfor c in merged_freq_dict:\n\t\tclass_by_small.append(merged_freq_dict[c][0])\n\t\tclass_by_big.append(merged_freq_dict[c][1])\n\t\n\tprob_class_by_small = [e/sum(class_by_small) for e in class_by_small]\n\tprob_class_by_big = [e/sum(class_by_big) for e in class_by_big]\n\n\tIG = TOTAL_entropy - (small_TOTAL)*entropy(prob_class_by_small) -(big_TOTAL)*entropy(prob_class_by_big)\n\t#print('head entropy is',entropy(total_small/total_big))\n\t#print('IG is',IG)\n\tif math.isnan(IG):\n\t\t#print('this is nan')\n\t\treturn(-5000) #jsut random minus value.\n\telse :\treturn(round(IG,5))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Validate both grant_type is a valid string and grant_type is allowed for current workflow
|
def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs):
assert(grant_type in GRANT_TYPE_MAPPING) # mapping misconfiguration
return request.client.authorization_grant_type in GRANT_TYPE_MAPPING[grant_type]
|
[
"def validate_grant_type(self, client_id, grant_type, client, request,\r\n *args, **kwargs):\r\n if self._usergetter is None and grant_type == 'password':\r\n log.debug('Password credential authorization is disabled.')\r\n return False\r\n\r\n default_grant_types = (\r\n 'authorization_code', 'password',\r\n 'client_credentials', 'refresh_token',\r\n )\r\n\r\n if grant_type not in default_grant_types:\r\n return False\r\n\r\n if hasattr(client, 'allowed_grant_types') and \\\r\n grant_type not in client.allowed_grant_types:\r\n return False\r\n\r\n if grant_type == 'client_credentials':\r\n if not hasattr(client, 'user'):\r\n log.debug('Client should have a user property')\r\n return False\r\n request.user = client.user\r\n\r\n return True",
"def test_create_token_wrong_grant_type(self):\n client_id, client_secret = self._get_client_data(0)\n wrong_client_data = {\n 'grant_type': 'wrong',\n 'client_id': client_id,\n 'client_secret': client_secret\n }\n res = self._call_token_creation(wrong_client_data)\n self.assertEquals(res.status_code, 400)\n self.assertEquals(res.json(), {'error': 'unsupported_grant_type'})",
"def validate_code(self, client_id, code, client, request, *args, **kwargs):\r\n client = client or self._clientgetter(client_id)\r\n log.debug(\r\n 'Validate code for client %r and code %r', client.client_id, code\r\n )\r\n grant = self._grantgetter(client_id=client.client_id, code=code)\r\n if not grant:\r\n log.debug('Grant not found.')\r\n return False\r\n if hasattr(grant, 'expires') and \\\r\n datetime.datetime.utcnow() > grant.expires:\r\n log.debug('Grant is expired.')\r\n return False\r\n\r\n request.state = kwargs.get('state')\r\n request.user = grant.user\r\n request.scopes = grant.scopes\r\n return True",
"def client_authentication_required(self, request, *args, **kwargs):\r\n if request.grant_type == 'password':\r\n return True\r\n auth_required = ('authorization_code', 'refresh_token')\r\n return 'Authorization' in request.headers and\\\r\n request.grant_type in auth_required",
"def validate_response_type(self, client_id, response_type, client, request,\r\n *args, **kwargs):\r\n if response_type not in ('code', 'token'):\r\n return False\r\n\r\n if hasattr(client, 'allowed_response_types'):\r\n return response_type in client.allowed_response_types\r\n return True",
"def test_post_grant_authorization_code_no_uris(self):\n self._test_post_redirect_uri_grant_combination(\n redirect_uris='',\n grant_type=Application.GRANT_AUTHORIZATION_CODE,\n is_valid=False,\n )",
"def test_post_grant_authorization_code_uris(self):\n self._test_post_redirect_uri_grant_combination(\n redirect_uris='http://example.com',\n grant_type=Application.GRANT_AUTHORIZATION_CODE,\n is_valid=True,\n )",
"def _validate_access_token(self, header, payload, **options):\n\n if not header or not payload or not payload.get(self.USER_IDENTITY_HOLDER) or \\\n payload.get('type') != TokenTypeEnum.ACCESS:\n raise InvalidAccessTokenError(_('Provided access token is invalid.'))\n\n generator = payload.get(self.AUTHENTICATOR_HOLDER)\n if generator != self.name:\n raise InvalidTokenAuthenticatorError(_('This access token is generated using '\n 'another authenticator with name [{name}].')\n .format(name=generator))",
"def test_user_universal_transfer_with_invalid_enum_string():\n\n invalid_params = {\"type\": random_str(), \"asset\": \"BNB\", \"amount\": 0.1}\n client = Client(key, secret)\n client.user_universal_transfer.when.called_with(**invalid_params).should.throw(\n ParameterValueError\n )",
"def is_valid_type(statement_type: str) -> bool:\n return statement_type in MargoStatementTypes.VALID_TYPES",
"def test_post_grant_password_no_uris(self):\n self._test_post_redirect_uri_grant_combination(\n redirect_uris='',\n grant_type=Application.GRANT_PASSWORD,\n is_valid=True,\n )",
"def test_create_account_type_invalid(self):\n payload = {'name': ''}\n res = self.client.post(ACCOUNT_TYPE_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)",
"async def validate_token(self) -> int:\n if not PSQL_URI:\n return\n auth_token = request.headers.get(\"Authorization\") or request.args.get(\"token\")\n try:\n auth_token = validators.Token(auth_token)\n except (Invalid, MultipleInvalid):\n # NOTE: Disable this on Nov 1st\n if self.plan_types is None:\n return\n return 401\n auth_token = await Token.from_token(auth_token)\n # NOTE: Disabled until Nov 1st\n # if auth_token is None:\n # return 403\n if self.plan_types:\n if auth_token is None:\n return 403\n if not auth_token.valid_type(self.plan_types):\n return 403\n # Returns True if exceeded rate limit\n if auth_token and await auth_token.increment():\n return 429\n return",
"def test_post_grant_client_credentials_no_uris(self):\n self._test_post_redirect_uri_grant_combination(\n redirect_uris='',\n grant_type=Application.GRANT_CLIENT_CREDENTIALS,\n is_valid=True,)",
"def token_scheme_check(token, scheme, obj, host):\n if not re.match(\"Bearer\", scheme):\n raise BeaconUnauthorised(obj, host, \"invalid_token\", \"Invalid token scheme, Bearer required.\")\n\n if token is None:\n # Might never happen\n raise BeaconUnauthorised(obj, host, \"invalid_token\", \"Token cannot be empty.\") # pragma: no cover",
"def validate_scope(jwt_token, scope_type):\n\n app.logger.info(\"validate_scope jwt_token: {}, scope_type: {}\".format(jwt_token, scope_type))\n\n # Make sure we can decrypt the token and it makes sense\n\n return_val= False\n try:\n decrypted_jwt_token = decode(jwt_token)\n if decrypted_jwt_token['scope']:\n for user_scope_list in decrypted_jwt_token['scope']:\n if user_scope_list == scope_type:\n app.logger.debug('Valid JWT scope.')\n return_val=True\n\n if not return_val:\n app.logger.warning('Invalid JWT scope.')\n return False\n\n if decrypted_jwt_token['expires_at']:\n # We have a time stamp so check this token has not expired\n #TODO Add UTC Time stamp validation\n app.logger.info('Token: {} has a UTC time stamp of: {}'.format(decrypted_jwt_token['access_token'],decrypted_jwt_token['expires_at']))\n else:\n # We don't have a time stamp\n app.logger.warning('Token has expired for token Value: {}'.format(decrypted_jwt_token['access_token']))\n return False\n\n return return_val\n\n except JWTError:\n app.logger.warning('JWT scope could not be validated.')\n return False\n\n except KeyError:\n app.logger.warning('JWT scope could not be validated.')\n return False",
"def test_should_raise_error_if_type_is_invalid(self):\n with self.assertRaises(ValueError):\n self.spec_parser.parse_statement({'type': 'sugar'})",
"def test_post_grant_implicit_uris(self):\n self._test_post_redirect_uri_grant_combination(\n redirect_uris='https://example.com/',\n grant_type=Application.GRANT_IMPLICIT,\n is_valid=True,\n )",
"def _test_post_redirect_uri_grant_combination(self, redirect_uris,\n grant_type, is_valid):\n post_data = {\n 'authorization_grant_type': grant_type,\n 'client_type': Application.CLIENT_PUBLIC,\n 'name': 'test-app',\n 'redirect_uris': redirect_uris,\n 'skip_authorization': '0',\n }\n\n if is_valid:\n rsp = self.api_post(get_oauth_app_list_url(),\n post_data,\n expected_mimetype=oauth_app_item_mimetype)\n self.assertIn('stat', rsp)\n self.assertEqual(rsp['stat'], 'ok')\n self.compare_item(rsp['oauth_app'],\n Application.objects.get(name='test-app'))\n else:\n rsp = self.api_post(get_oauth_app_list_url(),\n post_data,\n expected_status=400)\n self.assertIn('stat', rsp)\n self.assertEqual(rsp['stat'], 'fail')\n self.assertIn('err', rsp)\n self.assertIn('fields', rsp)\n self.assertIn('redirect_uris', rsp['fields'])",
"def __init__(self, grantId, grantExpireTime):\n self.grantId = grantId\n self.grantStatus = \"GRANTED\"\n self.grantExpireTime = grantExpireTime"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Save access and refresh token, If refresh token is issued, remove old
|
def save_bearer_token(self, token, request, *args, **kwargs):
if request.refresh_token:
# remove used refresh token
try:
RefreshToken.objects.get(token=request.refresh_token).revoke()
except RefreshToken.DoesNotExist:
assert() # TODO though being here would be very strange, at least log the error
expires = timezone.now() + timedelta(seconds=oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS)
if request.grant_type == 'client_credentials':
request.user = None
# TODO: get user from phone number in request, there should be some
# secure system to get user from phone number
data_dict = get_request_body_dict(request)
phone = str(data_dict['phone'])
account_object = get_object('account', 'phone', phone)
user_object = get_object('user', 'id', account_object.user_id)
access_token = AccessToken(
user=user_object,
scope=token['scope'],
expires=expires,
token=token['access_token'],
application=request.client)
access_token.save()
if 'refresh_token' in token:
refresh_token = RefreshToken(
user=user_object,
token=token['refresh_token'],
application=request.client,
access_token=access_token
)
refresh_token.save()
# TODO check out a more reliable way to communicate expire time to oauthlib
token['expires_in'] = oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS
|
[
"def refresh_access_token():\n client = Client(sm.access_token)\n auth_dict = client.refresh_access_token(\n client_id=sm.client_id,\n client_secret=sm.client_secret,\n refresh_token=sm.refresh_token)\n logger.debug('Auth Dict: %s', auth_dict)\n\n # Save the dict back to Secret Manager\n sm.set_auth_dict(auth_dict)",
"def _save_token_data_from_response(self, token_data: dict[str, Any]) -> None:\n self._token_last_refreshed = datetime.utcnow()\n self.access_token = token_data[\"access_token\"]\n if refresh_token := token_data.get(\"refresh_token\"):\n self.refresh_token = refresh_token",
"def _renew(self, data):\n self.created_at = datetime.utcnow()\n if data is None:\n return\n \n self.access_token = data['access_token']\n self.refresh_token = data.get('refresh_token', '')\n self.expires_in = data['expires_in']\n scopes = self.scopes\n scopes.clear()\n for scope in data['scope'].split():\n try:\n scopes.add(SCOPES[scope])\n except KeyError:\n pass",
"def refresh():\n client_id = \"287290951141-dl34gtgp8tvnanm809utk7if4klj0upg.apps.googleusercontent.com\"\n client_secret = \"V5ihqrK506ISAzYFH7V9SRfR\"\n r = requests.post(\"https://www.googleapis.com/oauth2/v3/token\",\n data = {\"client_id\":client_id, \"client_secret\":client_secret,\n \"refresh_token\":\"1/HCZswI4mR3ibVUirYLtQXlIgRlU2RYEbTP8p1kFIwkFIgOrJDtdun6zK6XiATCKT\",\n \"grant_type\":\"refresh_token\"})\n print(r.text)\n raw_cred = r.text\n json_cred = json.loads(r.text)\n my_dir = os.path.dirname(__file__)\n pickle_file_path = os.path.join(my_dir, 'saved_cred.p')\n pickle.dump(raw_cred, open(pickle_file_path, 'wb'))\n # cred = AccessTokenCredentials(json_cred['access_token'], 'SD-NUC/1.0') # For use with google storage library\n return raw_cred",
"def SaveOauth2Tokens(self, system, access_token, refresh_token, expires_on):\n cursor = self._db_client.cursor()\n\n cursor.execute(\n \"\"\"\n UPDATE oauth2\n SET access_token=?, refresh_token=?, expires_on=?, created_on=CURRENT_TIMESTAMP\n WHERE system=?\n \"\"\", (access_token, refresh_token, expires_on, system,))\n\n if cursor.rowcount == 0:\n cursor.execute(\n \"\"\"\n INSERT INTO oauth2 (system, access_token, refresh_token, expires_on)\n VALUES (?, ?, ?, ?)\n \"\"\", (system, access_token, refresh_token, expires_on,))\n\n self._db_client.commit()",
"def _renew_token(self):\n self.token = self._api_auth()",
"def refresh_token(self, token_info):\r\n if 'refresh_token' not in token_info:\r\n return self.get_new_token()\r\n refresh_request = {'refresh_token': token_info['refresh_token'],\r\n 'client_id': self.user_id,\r\n 'client_secret': self.key,\r\n 'grant_type': 'refresh_token'}\r\n\r\n new_token = self._token_request(refresh_request)\r\n if 'refresh_token' not in new_token:\r\n new_token['refresh_token'] = token_info['refresh_token']\r\n return new_token",
"def refresh_token():\n\n enc_token = jwt_helper.get_token_from_cookie(cookies=request.cookies, key='refToken')\n __, jwt_content = jwt_helper.decode(token=enc_token, token_type='refresh')\n\n # check_jti()\n subject = jwt_content['sub']\n refresh_token, access_token = jwt_helper.gen_tokens(subject)\n resp = jwt_helper.make_token_response(access_token, refresh_token)\n return resp",
"def cache_tokens(self):\n if not self.allow_cache:\n return\n\n data = {\n 'access_token': self.access_token,\n 'refresh_token': self.refresh_token,\n 'expires': self.expires\n }\n if not os.path.exists(_cache_dir):\n os.mkdir(_cache_dir)\n with open(_token_file, 'w') as f:\n json.dump(data, f)",
"def refresh_token():\n global SESSION_ID\n if SESSION_ID:\n logger.info(\"Session ID is not none, so will not attempt to authenticate.\")\n else:\n logger.info(\"Session ID is none, so will need to authorize.\")\n SESSION_ID = authorize()\n return",
"def refresh_token(self):\n if not self._refresh_token:\n self.get_oauth_tokens()\n\n return self._refresh_token",
"def save_access_token(self, token, request):\r\n log.debug('Save access token %r', token)\r\n self._tokensetter(token, request)",
"def get_access_token(self):\n # will need to implement method for refreshing refresh token (90 day expiration)\n\n aws_access_key = Variable.get(\"aws_access_key_id\")\n aws_secret_key = Variable.get(\"aws_secret_access_key\")\n s3_client = boto3.client(\n 's3',\n aws_access_key_id=aws_access_key,\n aws_secret_access_key=aws_secret_key\n )\n\n bytes_buffer = io.BytesIO()\n s3_client.download_fileobj(Bucket=\"on-da-dip\", Key=\"tokeninfo.txt\", Fileobj=bytes_buffer)\n byte_value = bytes_buffer.getvalue()\n refresh_token = byte_value.decode()\n\n endpoint = self.url + \"oauth2/token\"\n grant_type = \"refresh_token\"\n access_type = \"offline\"\n\n data = {\n \"grant_type\": grant_type,\n \"access_type\": access_type,\n \"refresh_token\": refresh_token,\n \"client_id\": self.client_id\n }\n\n result = requests.post(url=endpoint, data=data)\n\n if result.status_code == 200:\n result_body = result.json()\n self.access_token = result_body[\"access_token\"]\n\n cwd = os.getcwd()\n dir = os.path.dirname(cwd)\n refresh_token_file = open(dir + \"/creds/tokeninfo.txt\", \"wt\")\n # need to update token file with latest refresh token\n refresh_token_file.write(result_body[\"refresh_token\"])\n refresh_token_file.close()\n\n s3_client.upload_file(Filename=dir + \"/creds/tokeninfo.txt\", Bucket=\"on-da-dip\", Key=\"tokeninfo.txt\")\n\n elif result.status_code == 401:\n print(\"Invalid credentials.\")\n elif result.status_code == 403:\n print(\"User doesn't have access to this account and/or permissions.\")\n elif result.status_code == 400:\n print(\"Validation unsuccessful. Check that client id and refresh tokens are correct.\")\n elif result.status_code == 500:\n print(\"Server error, try again later.\")\n else:\n print(\"Unknown error.\")",
"def refresh_token(user, refresh: bool = True) -> Token:\n Token.objects.filter(user=user).delete()\n token, _ = Token.objects.get_or_create(user=user)\n return token.key",
"def refresh_access_token(user):\n refresh_token = user.refresh_key\n\n payload = {\n \"grant_type\": \"refresh_token\",\n \"client_id\": settings.oauth2_id,\n \"redirect_uri\": settings.oauth2_uri,\n \"client_secret\": settings.oauth2_key,\n \"refresh_token\": refresh_token,\n }\n response = requests.post(settings.BASE_URL + \"login/oauth2/token\", data=payload)\n\n try:\n response.raise_for_status()\n except HTTPError:\n app.logger.exception(\"Failed refresh. Probably bad refresh token.\")\n return {\"access_token\": None, \"expiration_date\": None}\n\n try:\n response_json = response.json()\n except ValueError:\n app.logger.exception(\n \"Unable to load JSON response of refresh. Possibly bad refresh token.\"\n )\n return {\"access_token\": None, \"expiration_date\": None}\n\n if \"access_token\" not in response_json:\n app.logger.warning(\n (\n \"Access token not in json. Bad api key or refresh token.\\n\"\n \"URL: {}\\n\"\n \"Status Code: {}\\n\"\n \"Payload: {}\\n\"\n \"Session: {}\"\n ).format(response.url, response.status_code, payload, session)\n )\n return {\"access_token\": None, \"expiration_date\": None}\n\n api_key = response_json[\"access_token\"]\n app.logger.info(\"New access token created\\n User: {0}\".format(user.user_id))\n\n if \"expires_in\" not in response_json:\n app.logger.warning(\n (\n \"expires_in not in json. Bad api key or refresh token.\\n\"\n \"URL: {}\\n\"\n \"Status Code: {}\\n\"\n \"Payload: {}\\n\"\n \"Session: {}\"\n ).format(response.url, response.status_code, payload, session)\n )\n return {\"access_token\": None, \"expiration_date\": None}\n\n current_time = int(time.time())\n new_expiration_date = current_time + response_json[\"expires_in\"]\n\n try:\n # Update expiration date in db\n user.expires_in = new_expiration_date\n db.session.commit()\n except Exception:\n readable_expires_in = time.strftime(\n \"%a, %d %b %Y %H:%M:%S\", time.localtime(user.expires_in)\n )\n readable_new_expiration = time.strftime(\n \"%a, %d %b %Y %H:%M:%S\", time.localtime(new_expiration_date)\n )\n app.logger.error(\n (\n \"Error in updating user's expiration time in the db:\\n\"\n \"session: {}\\n\"\n \"DB expires_in: {}\\n\"\n \"new_expiration_date: {}\"\n ).format(session, readable_expires_in, readable_new_expiration)\n )\n return {\"access_token\": None, \"expiration_date\": None}\n\n return {\"access_token\": api_key, \"expiration_date\": new_expiration_date}",
"def refresh_access_token(self, **kwargs):\n trace_id = kwargs.get('trace_id', '')\n spotify_client = SpotifyClient(identifier='refresh-access-token:{}'.format(self.spotify_user_id))\n\n try:\n access_token = spotify_client.refresh_access_token(self.refresh_token)\n\n self.access_token = access_token\n self.last_refreshed = timezone.now()\n\n self.save()\n\n logger.info(\n 'Refreshed access token for {}'.format(self.spotify_user_id),\n extra={\n 'fingerprint': auto_fingerprint('success_refresh_access_token', **kwargs),\n 'spotify_username': self.spotify_user_id,\n 'auth_id': self.pk,\n 'user_id': self.user_id,\n 'trace_id': trace_id,\n }\n )\n\n except SpotifyException:\n logger.exception(\n 'Unable to refresh access token for {}'.format(self.spotify_user_id),\n extra={\n 'fingerprint': auto_fingerprint('failed_refresh_access_token', **kwargs),\n 'spotify_username': self.spotify_user_id,\n 'auth_id': self.pk,\n 'user_id': self.user_id,\n 'trace_id': trace_id,\n }\n )\n\n raise",
"def refresh_token(self) -> None:\n payload: Dict[str, str] = {\"apiKey\": API_KEY}\n headers: Dict[str, str] = {\"Content-Type\": \"application/json\"}\n\n r: requests.Response = requests.post(AUTH_URL, json=payload, headers=headers)\n\n if r.status_code != 200:\n raise Unauthorized(msg=\"Bad response from server\")\n\n response = r.json()\n token: str = response.get(\"token\") or \"\"\n auth: bool = response.get(\"auth\", False)\n\n if not auth or not token:\n raise Unauthorized(msg=\"Bad response from server\")\n\n self.token = token\n self.auth = auth",
"def refresh_tokens(self) -> Dict[str, Union[str, int]]:\n LOGGER.info(\"Refreshing tokens ...\")\n token = self._oauth.refresh_token(f\"{self.host}{ENDPOINT_TOKEN}\")\n\n if self.token_updater is not None:\n self.token_updater(token)\n\n return token",
"def access_token(self):\n if not self._access_token:\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded'\n }\n\n payload = urllib.urlencode({\n 'grant_type': 'refresh_token',\n 'client_id': OAUTH_CLIENT_ID,\n 'refresh_token': self.refresh_token\n })\n\n request = urllib2.Request(OAUTH_URL, headers=headers, data=payload)\n request.get_method = lambda: 'POST'\n\n try:\n response = urllib2.urlopen(request)\n data = json.load(response)\n self._access_token = data['access_token']\n except urllib2.HTTPError:\n # the refresh token has expired or become invalid\n self._refresh_token = None\n self.get_oauth_tokens()\n\n return self._access_token"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Compute dEdX based on the cluster size Results expressed in MeV.cm2/g
|
def GetdEdX(self,clusterSize):
return self.GetEloss(clusterSize)/(self.pitch*100/self.rho)
|
[
"def occupancyEMD(swcList, voxelSize):\n\n occupancyDistributionDict = calcOccupancyDistribution(swcList, voxelSize)\n bins = np.arange(1, len(swcList) + 1)\n occupancyDistribution = [occupancyDistributionDict[x] for x in bins]\n perfectOverlapDist = np.zeros(bins.shape)\n perfectOverlapDist[-1] = 1\n\n binsRow = bins.reshape((1, bins.shape[0]))\n distMetric = np.dot(np.ones((bins.shape[0], 1)), binsRow) - binsRow.T\n\n emd_val = emd(np.asarray(occupancyDistribution, dtype=np.float64),\n np.asarray(perfectOverlapDist, dtype=np.float64),\n np.asarray(distMetric, dtype=np.float64))\n return emd_val",
"def find_clu_size_seq(self):\n if np.all([type(i)==int for i in self.clusters]):\n sorted_cluster = sorted(self.clusters)\n else:\n sorted_cluster = sorted(self.clusters, key=lambda v: str(v))\n return [len(self.clu2elm_dict[clu]) for clu in sorted_cluster]",
"def getClusterMinMag(self) -> retval:\n ...",
"def shortdEdx( xzye ):\n \n upsPointIndex = np.argmin( xzye[:,1] )\n\n xzye5cm = []\n for i in range(len(xzye)):\n if np.linalg.norm( xzye[i][:3] - xzye[upsPointIndex][:3] ) <= 5:\n xzye5cm.append( xzye[i] )\n\n try:\n xzye5cm = np.asarray(xzye5cm)\n dEdx = sum(xzye5cm[:,3])*1000/5\n return dEdx\n except:\n return 0",
"def get_34cohom_dim(v,l, even_e):\n op1 = ContractEdgesGO.generate_operator(v,l, even_e)\n op2 = ContractEdgesGO.generate_operator(v+1,l, even_e)\n opc = ContractEdgesGO.generate_operator(v+1,l, even_e, False)\n\n return cohom_formatted_merkulov(op1, op2, opc)\n\n # return vs34.get_34dimension() - D34rank -DD34rank + DD5rank",
"def GetMeasurementVectorSize(self):\n return _itkKdTreePython.itkKdTreeLSVF3_GetMeasurementVectorSize(self)",
"def GetMeasurementVectorSize(self):\n return _itkKdTreePython.itkKdTreeLSVF2_GetMeasurementVectorSize(self)",
"def d(self):\n return self.random_unit_vectors.components_.shape[1]",
"def community_size_distribution(comm):\n c=community_size(comm).values()\n \n return (sp.mean(c), sp.std(c))",
"def mcdEdx( xzyeT ):\n\n points0To5 = np.asarray([ i for i in xzyeT if ( 0 <= i[1]*14 <= 5) ])\n\n dE = (max(points0To5[:,3]) - min(points0To5[:,3]))*1000 if len(points0To5) > 0 else -1\n dx = (max(points0To5[:,1]) - min(points0To5[:,1]))*14 if len(points0To5) > 0 else 1\n\n return dE/dx",
"def coxeter_number(self):\n return (self.number_of_reflection_hyperplanes()\n + self.number_of_reflections()) // self.rank()",
"def GetSizeDistribution(clusters):\n sizeDistribution = {}\n for cluster in clusters:\n if not sizeDistribution.has_key(len(cluster)):\n sizeDistribution[len(cluster)] = 0\n sizeDistribution[len(cluster)] += 1\n\n return sizeDistribution",
"def problem_size(graph, cs, verbose=False):\n\n cluster_size = {}\n for c in cs.subgraphs:\n\n # number of robots\n R = len(cs.agent_clusters[c]) + len(cs.child_clusters[c])\n # number of nodes\n V = len(cs.subgraphs[c]) + len(cs.child_clusters[c])\n # number of occupied nodes\n Rp = len(set(v for r, v in graph.agents.items() if r in cs.agent_clusters[c]))\n # number of transition edges\n Et = graph.number_of_tran_edges(cs.subgraphs[c])\n # number of connectivity edges\n Ec = graph.number_of_conn_edges(cs.subgraphs[c])\n # graph diameter\n D = nx.diameter(nx.subgraph(graph, cs.subgraphs[c]))\n\n T = int(max(D / 2, D - int(Rp / 2)))\n\n size = R * Et * T\n\n if verbose:\n print(\n \"{} size={} [R={}, V={}, Et={}, Ec={}, D={}, Rp={}]\".format(\n c, size, R, V, Et, Ec, D, Rp\n )\n )\n\n cluster_size[c] = size\n\n return cluster_size",
"def clustered_error(demean, consist_col, category_col, cluster_col, n, k, k0, rank, nested=False, c_method='cgm', psdef=True):\n if len(cluster_col) == 1 and c_method == 'cgm2':\n raise NameError('cgm2 must be applied to multi-clusters')\n beta_list = []\n xpx = np.dot(demean[consist_col].values.T, demean[consist_col].values)\n # 2020/11/26\n xpx_inv = np.linalg.pinv(xpx)\n demeaned_df = demean.copy()\n G_array = np.array([])\n \n if nested: \n if (len(category_col) == 0 ):\n scale_df = (n - 1) / (n - k - rank)\n else: \n scale_df = (n - 1) / (n - k + k0 - rank ) \n else:\n if (len(category_col) == 0 ): \n scale_df = (n - 1) / (n - k - rank) \n else:\n scale_df = (n - 1) / (n - k + k0 - rank ) \n \n \n if len(cluster_col) == 1:\n G = np.unique(demeaned_df[cluster_col].values).shape[0]\n \n middle = middle_term(demeaned_df, consist_col, cluster_col)\n m = np.dot(xpx_inv, middle)\n beta = np.dot(m, xpx_inv)\n \n scale = scale_df * G / (G - 1)\n beta = scale * beta\n beta_list.append(beta)\n else:\n if c_method == 'cgm':\n for cluster in cluster_col:\n middle = middle_term(demeaned_df, consist_col, [cluster])\n G = np.unique(demeaned_df[cluster].values).shape[0]\n # print('G:',G)\n # print('middle:',middle)\n m = np.dot(xpx_inv, middle)\n beta = np.dot(m, xpx_inv)\n scale = scale_df * G / (G - 1)\n beta = scale * beta\n beta_list.append(beta)\n for j in range(2, len(cluster_col) + 1):\n for combine_name in list(combinations(cluster_col, j)):\n name_list = [e for e in combine_name]\n # print(name_list)\n # print(j)\n new_col_name = ''\n for i in name_list:\n new_col_name = new_col_name + '_' + i\n demeaned_df[new_col_name] = demeaned_df[name_list[0]].apply(str)\n # print('col_name:', new_col_name)\n for i in range(1, len(name_list)):\n # print('col_name:', new_col_name)\n demeaned_df[new_col_name] = demeaned_df[new_col_name] + '_' + demeaned_df[name_list[i]].apply(\n str)\n middle = np.power(-1, j - 1) * middle_term(demeaned_df, consist_col, [new_col_name])\n # print(middle)\n m = np.dot(xpx_inv, middle)\n beta = np.dot(m, xpx_inv)\n G = np.unique(demeaned_df[new_col_name].values).shape[0]\n scale = scale_df * G / (G - 1)\n # print('g:', G)\n beta = scale * beta\n beta_list.append(beta)\n\n elif c_method == 'cgm2':\n for cluster in cluster_col:\n middle = middle_term(demeaned_df, consist_col, [cluster])\n G = np.unique(demeaned_df[cluster].values).shape[0]\n G_array = np.append(G_array, G)\n # print('G:', G)\n m = np.dot(xpx_inv, middle)\n beta = np.dot(m, xpx_inv)\n beta_list.append(beta)\n for j in range(2, len(cluster_col) + 1):\n for combine_name in list(combinations(cluster_col, j)):\n name_list = [e for e in combine_name]\n new_col_name = ''\n for i in name_list:\n new_col_name = new_col_name + '_' + i\n demeaned_df[new_col_name] = demeaned_df[name_list[0]].apply(str)\n for i in range(1, len(name_list)):\n demeaned_df[new_col_name] = demeaned_df[new_col_name] + '_' + demeaned_df[name_list[i]].apply(\n str)\n middle = np.power(-1, j - 1) * middle_term(demeaned_df, consist_col, [new_col_name])\n m = np.dot(xpx_inv, middle)\n beta = np.dot(m, xpx_inv)\n G = np.unique(demeaned_df[new_col_name].values).shape[0]\n G_array = np.append(G_array, G)\n beta_list.append(beta)\n # print(G_array)\n m = np.zeros((k, k))\n if c_method == 'cgm':\n for i in beta_list:\n m += i\n elif c_method == 'cgm2':\n for i in beta_list:\n G_MIN = np.min(G_array)\n scale = scale_df * G_MIN / (G_MIN - 1)\n m += i * scale\n\n if psdef is True and len(cluster_col) > 1:\n m_eigen_value, m_eigen_vector = np.linalg.eig(m)\n m_new_eigen_value = np.maximum(m_eigen_value, 0)\n if (m_eigen_value != m_new_eigen_value).any():\n warnings.warn('Negative eigenvalues set to zero in multi-way clustered variance matrix.')\n m_new = np.dot(np.dot(m_eigen_vector, np.diag(m_new_eigen_value)), m_eigen_vector.T)\n # print('covariance matrix:')\n # print(m_new)\n return m_new\n else:\n # print('covariance matrix:')\n # print(m)\n return m",
"def min_cluster_size(self):\n return self._parms.get(\"min_cluster_size\")",
"def density_cluster(Data,iradius, Clusters): #This function classifies data points into clusters and noise points",
"def run_and_report_grads(K, d, n_per_cluster, lr, epochs, num_runs, m=None):\n total_opt = 0\n total_gdc = 0\n gdc_under = 0\n\n total_grad_stats = np.zeros((5, epochs))\n\n for i in xrange(num_runs):\n # Generate the clusters\n clusters, actual_centres, global_opt = k_centres_d_space(K, d, n_per_cluster)\n X = np.concatenate(clusters, axis=0)\n\n # Choose K for GDC\n gdc = GDC()\n # co = ConvexOptimizer(gdc)\n # tp = TrainingParams(X, lr, epochs)\n # K, _ = co.bin_search(tp, 0, 10)\n\n # Create same set of starting centres\n X_bar = np.random.uniform(low=-5.0, high=5.0, size=(K, d))\n\n # Train the clustering algorithms\n #W, X_bar_gdc, all_prev_gdc, grad_stats = gdc.train(X, K, lr, epochs, X_bar)\n _, X_bar_gdc, all_prev_gdc = gdc.train_sgd(X, K, lr, epochs, m, X_bar)\n\n\n # Compute total cost of each clustering alg\n gdc_C = cluster_utils.cost_of_closest_to(X, X_bar_gdc)\n\n #total_grad_stats += grad_stats.as_np()\n\n # Update agregates\n total_opt += global_opt\n total_gdc += gdc_C\n if gdc_C < global_opt: #+ 0.1:\n gdc_under += 1\n else:\n print \"Global Optimum: \" + str(global_opt) + \" GDC: \" + str(gdc_C)\n\n print \"Global Optimum: \" + str(total_opt / 100.0)\n print \"GDC: \" + str(total_gdc / 100.0) + \" Percent Under: \" + str(gdc_under)\n #return total_grad_stats/float(num_runs)",
"def boxDimensions(self):\n for vectID in self._clusterAttribution.keys():\n clusterID = self._clusterAttribution[vectID]\n self._boxDims.setdefault(clusterID, (self._boxSpacing, self._boxSpacing))\n w, h = self._boxDims[clusterID]\n wt, ht = verdana.getsize(self.fullLabel(vectID))\n wi = 0\n hi = 0\n thumb = self.getThumbnail(vectID)\n if (thumb != False):\n wi, hi = thumb.size\n self._boxDims[clusterID] = (max(w, wt, wi) + self._boxSpacing, h + ht + hi + self._boxSpacing)\n\n w = self._boxSpacing\n h = self._boxSpacing\n for clusterID in self._boxDims.keys():\n wB, hB = self._boxDims[clusterID]\n w = max(w, wB) + self._boxSpacing\n h = h + hB + self._boxSpacing\n return (w, h)",
"def node_size(rank_spec):"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns patient_x and patient_Y for patient_id
|
def get_features_for_patient(patient_id):
patient_id = str(patient_id)
patient_ema_features, patient_engagement = get_EMA_features_and_target_for_patient(
patient_id)
patient_module_features = get_module_features_for_patient(
patient_id).transpose().fillna(0)
patient_features = patient_ema_features.join(
patient_module_features.fillna(0)).fillna(0)
patient_extended_features = convert_features_to_statistics(
patient_features, SLIDING_WINDOW)
patient_extended_features['weekendDay'] = get_weekend_days(
patient_extended_features.index.to_series())
patient_x = get_relevant_dates(patient_extended_features)
patient_y = get_relevant_dates(patient_engagement)
return (patient_x, patient_y)
|
[
"def get_trajectory():\n return patient_id_trajectory",
"def _GetElementCoords(ID,array):\n coords = np.where(array==ID)\n return coords[0][0],coords[1][0]",
"def get_patient_by_id(self, index):\n return self.patient_dict[index]",
"def extract_xy_values(student_ids, var_names, variable_value_dicts,\n grades_dict, x_only=False, return_ids=False):\n Y = []\n X = []\n ids = []\n for student_id in student_ids:\n training_example = []\n # Loop over all variables and add values to training example\n for var_name in var_names:\n # holds student ids as keys and corresponding statictis as value\n variable_value_dict = variable_value_dicts[var_name]\n if student_id in variable_value_dict:\n training_example.append(\n variable_value_dict[student_id]['value'])\n if len(training_example) == len(variable_value_dicts):\n if student_id in grades_dict:\n X.append(training_example)\n Y.append(grades_dict[student_id])\n ids.append(student_id)\n else:\n if x_only:\n X.append(training_example)\n if return_ids:\n return X, Y, ids\n else: \n return X, Y",
"def getNodeXY(id):\n for n in nodes:\n if n[0] == id:\n return (n[2], n[3])",
"def _coords(self, x, y):\n return y, x * 2",
"def get_all_patient_detailed(request, *args, **kwargs):\n user = request.user\n patient_id = kwargs['id']\n if not patient_id: raise PermissionDenied({'detail': \"mention the patient\", \"error_code\": 609})\n panel = get_my_partner_panel(user, patient_id)\n patient = panel.patient\n panel_serializer = PanelSerializerWithoutDoctor(panel)\n drugs = Drug.objects.filter(doctor__user=user, patient=patient).order_by('-consuming_day')\n drug_serializer = DrugSerializerWithoutPatientAndDoctor(drugs, many=True)\n doctor_events = get_relevant_health_events_queryset(user)\n doctor_patient_events = doctor_events.filter(\n Q(owner=patient.user) | Q(invited_patients=patient)).order_by('-time')\n events_serializer = HealthEventSerializerJustIdAndNameForParticipates(doctor_patient_events, many=True)\n return Response({\"panel\": panel_serializer.data, 'drugs': drug_serializer.data, 'events': events_serializer.data})",
"def _pair_dicom_and_contour(self):\n pid_oid = pd.read_csv(self.link_fn)\n pid_oid['file_id'] = pid_oid.apply(\n lambda row: list(set(self._get_all_dicom_ids(\n row['patient_id'])).intersection(set(self._get_all_contour_ids(\n row['original_id'])))), axis=1)\n return pid_oid",
"def pixelcoord(x, y):\n xp = a * x + b * y + minX\n yp = d * x + e * y + minY\n return xp, yp",
"def get_coords(self):\n return self.x1, self.y1, self.x2, self.y2",
"def _get_pd_x(data, params, shape_x, dtype, cast_dtype):\n pd_x_1, pd_x_2, pd_x_3, var_elta_2_cast, sub_x_mean = \\\n _get_pd_x_front(data, params, shape_x, cast_dtype)\n\n pdx_broad = te.lang.cce.broadcast(pd_x_3, shape_x)\n pdx_add = te.lang.cce.vadd(pd_x_1, pd_x_2)\n pd_x_ub = te.lang.cce.vadd(pdx_add, pdx_broad)\n if dtype == \"float16\" and cast_dtype == \"float32\":\n pd_x = te.lang.cce.cast_to(pd_x_ub, dtype)\n else:\n pd_x = pd_x_ub\n\n return pd_x, var_elta_2_cast, sub_x_mean",
"def test(self, patient):\n\t\treturn (None, None)",
"def damageLoc():\n x_d1 = x_l[8]\n x_d2 = x_l[8]\n x_d3 = np.array([x_l[5], x_l[5]])\n x_d4 = np.array([x_l[7], x_l[7]])\n x_d5 = np.array([x_d1, x_d4])\n x_d6 = np.array([x_d2, x_d4])\n x_d7 = x_g[2]\n x_d8 = x_g[5]\n x_d9 = np.array([x_l[12], np.array([x_l[12], x_l[12]])])\n x_damage = np.array([x_d1, x_d2, x_d3, x_d4, x_d5, x_d6, x_d7, x_d8, x_d9])\n y_d1 = y_l[1]\n y_d2 = y_l[0]\n y_d3 = np.array([y_l[1], y_l[2]])\n y_d4 = np.array([y_l[1], y_l[2]])\n y_d5 = np.array([y_d1, y_d4])\n y_d6 = np.array([y_d2, y_d4])\n y_d7 =-y_g_low[2]\n y_d8 = y_g_low[5]\n y_d9 = np.array([(y_l[0] - y_g_low[7]) / 2, np.array([-y_g_low[7], y_g_low[7]])])\n y_damage = np.array([y_d1, y_d2, y_d3, y_d4, y_d5, y_d6, y_d7, y_d8, y_d9])\n return x_damage,y_damage",
"def conversion_coord_to_id(self, x, y):\n x, y=int(x), int(y)\n\n try:\n id_=[element for element in self.raw_map if self.raw_map[element]['x']==x if self.raw_map[element]['y']==y][0]\n except IndexError:\n id_=0\n\n return id_",
"def patient_scan_helper(patient_id,\n database='openeobs_quality_assurance_db',\n user='nasir', password='nasir'):\n odoo_client = Client('http://localhost:8069', db=database,\n user=user, password=password)\n patient_api = odoo_client.model('nh.clinical.patient')\n patient_record = patient_api.read(patient_id, [\n 'other_identifier',\n 'patient_identifier',\n 'display_name',\n 'current_location_id'\n ])\n return patient_record",
"def _getXYT(self, data):\n x = np.array(data['x'])\n y = np.array(data['y'])\n t = np.array(data['frame'])\n return x, y, t",
"def _get_contpoints(self):\n\n try:\n contpoints = self.meta['contpoints']\n except:\n raise RuntimeError('Meta data `contpoints` does not exist; cannot get contpoints!')\n xy = np.array(contpoints)\n xy = xy.transpose()\n x, y = xy[0], xy[1]\n return x, y",
"def graph_point(self, x, y):\n \n return (self.graph_x(x), self.graph_y(y))",
"def get_scans(self, patient_id):\n images = self._df[self._df[\"Patient ID\"] == patient_id]\n return images[\"Scan ID\"].unique()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Retrieves the overall featureselection columns for all patients.
|
def get_FS_cols(list_patients_objects, max_features=10, technique='correlation'):
if technique == 'correlation':
features = get_patients_correlated_score(
list_patients_objects).index.to_series().tolist()
if technique == 'top_features':
features = get_top_features(list_patients_objects)
return features[:max_features]
|
[
"def get_feature_columns(self):\n return self.feature_columns",
"def get_df_with_all_features(self):\n return self.df_with_all_extracted_features",
"def getAllColumns (self):\n\n return self.columns",
"def create_all_features(self):\n self.create_boatsize_sex_weight_feature()\n self.create_team_feature()\n self.smooth_strokes()\n self.create_dif_feature()\n self.create_sprint_feature()\n self.create_average_strokepace_feature()\n self.create_average_sprint_feature()\n\n return self.df_all",
"def generate_all_feat_df(loader, used_col=None) -> pd.DataFrame:\n\n # generate DataFrame\n output = pd.DataFrame()\n feat_cols = loader.retrieve_all_cols()\n for col_name, arr in feat_cols.items():\n output[col_name] = arr.tolist()\n\n # change name\n if used_col:\n __rename_used_cols(output, used_col)\n\n return output",
"def get_features_for_patient(patient_id):\n patient_id = str(patient_id)\n patient_ema_features, patient_engagement = get_EMA_features_and_target_for_patient(\n patient_id)\n patient_module_features = get_module_features_for_patient(\n patient_id).transpose().fillna(0)\n patient_features = patient_ema_features.join(\n patient_module_features.fillna(0)).fillna(0)\n patient_extended_features = convert_features_to_statistics(\n patient_features, SLIDING_WINDOW)\n patient_extended_features['weekendDay'] = get_weekend_days(\n patient_extended_features.index.to_series())\n patient_x = get_relevant_dates(patient_extended_features)\n patient_y = get_relevant_dates(patient_engagement)\n\n return (patient_x, patient_y)",
"def get_features_column(self):\n return self.features_column",
"def Columns():\n cursor = connection.cursor()\n table = 'patient'\n return render_template(\n 'columns.html',\n title='Columns',\n message='All column names.',\n col = cursor.execute(\"SELECT Column_Name FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME=?\",table)\n )\n cursor.close()",
"def all_question_columns(self):\n if not self._all_question_columns:\n all_question_columns = [q.question_columns for q in self._question_list]\n self._all_question_columns = [item for sublist in all_question_columns for item in sublist]\n return self._all_question_columns",
"def columns(self):\n return self.cs",
"def columns(self):\n return self.c",
"def get_feature_dict(self, dataset: SampleTypeEnum,\n fs_selection: Set[FeatureSetEnum],\n extra_columns: Tuple[str] = ()) -> List[tuple]:\n\n sample: List[Series] = self._sample.get_data(dataset)\n\n res: List[tuple] = [\n (self.generate_features(row, fs_selection),\n row['classification'],\n *self._filter_row(row, extra_columns))\n for row in sample]\n\n return res",
"def selectFeatureSet_RF(data_x, data_y, nFeatures):\n\n rf_filter = RandomForestClassifier(max_features = 'auto')\n rf_filter.fit(data_x, data_y);\n rankings = rf_filter.feature_importances_;\n selectedBool = np.argsort(rankings)[-nFeatures:]\n# selectedBool = sorted(range(len(rankings)), key = lambda x: rankings[x])[-nFeatures:];\n return data_x.columns[selectedBool]",
"def get_columns(self) -> dict:\n\n return self.source.columns",
"def best_features(self):\n # Get individuals in Pareto front\n pareto_front = [self._population.individuals[idx] for idx in range(self._population.length)\n if self._population.fitness[idx].rank == 0]\n\n # Get feature names\n selected_features = [[self._population.features[idx] for idx in individual] for individual in pareto_front]\n\n return selected_features",
"def feature_df(self):\n import pandas as pd\n return pd.DataFrame(self.feature_records)",
"def get_feature_importances(self):\n feat_names = [str(compare) for compare in self.comp_eng.raw_compares]\n f_names = [f'f{i}' for i in range(len(feat_names))]\n\n dfs = []\n for type_ in ['weight', 'gain', 'cover', 'total_cover', 'total_gain']:\n booster = self.model.get_booster()\n # booster.feature_names=var_names\n imp_vals = booster.get_score(importance_type=type_)\n feats_imp = pd.DataFrame(imp_vals, index=np.arange(2)).T\n feats_imp.iloc[:, 0] = feats_imp.index\n feats_imp.columns = ['feature', type_]\n feats_imp.sort_values(type_, inplace=True, ascending=False)\n feats_imp.reset_index(drop=True, inplace=True)\n dfs.append(feats_imp)\n df = reduce(lambda x, y: pd.merge(x, y, on='feature'), dfs)\n df = df.replace(dict(zip(f_names, feat_names)))\n\n return df",
"def get_features(data: pd.DataFrame) -> List[str]:\n feature_columns = [\n column\n for column in data.columns\n if column\n not in [\n \"data\",\n \"stato\",\n \"codice_regione\",\n \"denominazione_regione\",\n \"lat\",\n \"long\",\n \"note\",\n ]\n ]\n return feature_columns",
"def columns ( frame ) :\n names = [ str(c) for c in frame.GetColumnNames() ]\n if ( 6 , 16 ) <= root_info : \n names += [ str(c) for c in frame.GetDefinedColumnNames() ] \n return tuple ( sorted ( set ( names ) ) )"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns an object with all the performances of all MLmodels.
|
def extract_performances_from_models(ml_models, performance_metric='mae'):
results = []
for model in ml_models:
results.append({
'model_name': model['name'],
'model_'+performance_metric: model['score'][performance_metric]
})
return results
|
[
"def evaluate_models(num_splits=10):\n models = {\"Decision Tree\": tree.DecisionTreeClassifier(),\n \"Nearest Neighbor\": neighbors.KNeighborsClassifier(),\n \"Random Forest\": ensemble.RandomForestClassifier(),\n \"Linear SVM\": svm.SVC(kernel=\"linear\"), # the linear kernel shows best performance\n \"LDA\": discriminant_analysis.LinearDiscriminantAnalysis(),\n \"Neural Net\": neural_network.MLPClassifier(solver=\"lbfgs\")} # small datasets favor an lbfgs solver\n\n data = pd.read_csv(f\"features_{num_splits}_splits.csv\", index_col=[0])\n # All the models can achieve near perfect accuracy without normalization except for neural networks\n for feature in [\"Mean\", \"Variance\", \"Up\"]:\n data[feature] = (data[feature] - data[feature].mean())/data[feature].std()\n y = data[\"Class\"]\n x = data.drop([\"Class\"], axis=1)\n\n # performing the model testing\n x_train, x_test, y_train, y_test = model_selection.train_test_split(x, y, test_size=0.3, random_state=1)\n performance = {}\n sources = [\"droneA\", \"droneB\", \"wifi\", \"random-signal\"]\n for name, model in models.items():\n model.fit(x_train, y_train)\n predictions = model.predict(x_test)\n report = metrics.classification_report(predictions, y_test, output_dict=True, zero_division=0)\n # The report gives summary results that are not used, so those are filtered out\n performance[name] = {source: report[source] for source in sources}\n\n return performance",
"def evaluate_models_1():\n df = prepare_general_dataset()\n X = df.loc[:, df.columns != 'bikes']\n Y = df['bikes']\n scores = []\n\n for key, value in MODELS.items():\n X = df.loc[:, df.columns != 'bikes']\n temp_scores = []\n for file in tqdm(glob.glob(value)):\n model = pd.read_csv(file)\n features = model['feature']\n\n # weights\n intercept = model['weight'].values[0]\n weights = model['weight'][1:]\n\n features_used = features.values[1:]\n X = X.filter(items=features_used)\n\n # reindex to perform series multiplication\n weights.index = X.iloc[1, :].index\n\n predictions = X.apply(lambda row: intercept + row.dot(weights), axis=1).astype('int64')\n temp_scores.append(mean_absolute_error(predictions, Y))\n\n print(f'\\nModel {key} performance:')\n print(mean(temp_scores))\n print(min(temp_scores))\n print('\\n')\n\n scores.append(temp_scores)\n\n with open('scores.txt', 'wb') as file:\n pickle.dump(scores, file)\n\n plot_scores_1(scores)",
"def get_models():\n models = {}\n models['LR'] = LogisticRegression()\n models['LDA'] = LinearDiscriminantAnalysis()\n models['KNN'] = KNeighborsClassifier()\n models['CART'] = DecisionTreeClassifier()\n models['NB'] = GaussianNB()\n models['SVM'] = SVC()\n return models",
"def best_performance(self):\n return list()",
"def metrics(self):\n print(f\"\\nML_solver's supported metrics overview: \\n\")\n reg_metrics = [func.__name__ for func in metrics_dict.get(\"regression\")]\n clf_metrics = [\n func.__name__ for func in metrics_dict.get(\"classification\")\n ]\n\n df_metrics = (\n pd.DataFrame.from_dict(\n {\"regression\": reg_metrics, \"classification\": clf_metrics},\n orient=\"index\",\n )\n .transpose()\n .fillna(\"----\")\n )\n\n df_metrics = self._tableize(df_metrics)\n print(df_metrics)",
"def init_models():\n\n return {\n 'KNN': (KNeighborsClassifier(weights='uniform',\n algorithm='auto',\n p=2,\n metric='minkowski'),\n {'n_neighbors': [3, 5, 7]}),\n 'Naive-Bayes': (GaussianNB(), {'var_smoothing': np.logspace(-12, 0, 11)}),\n 'Logistic-Regression': (\n LogisticRegression(penalty='l2',\n dual=False,\n tol=1e-4,\n fit_intercept=True,\n class_weight='balanced',\n random_state=SEED,\n solver='sag', # fast for large dataset\n max_iter=10000,\n verbose=1),\n {\n 'C': np.logspace(-3, 3, 11),\n 'n_jobs': [5]\n }),\n 'SVM': (\n LinearSVC(class_weight='balanced',\n # random folds so class frequencies are unexpected\n dual=False, # n_samples > n_features\n random_state=SEED,\n max_iter=10000,\n verbose=1),\n {'C': np.logspace(-3, 3, 11)}),\n 'Random-Forest': (\n RandomForestClassifier(criterion='gini',\n bootstrap=True,\n verbose=1,\n max_depth=25,\n min_samples_split=2,\n min_samples_leaf=4,\n random_state=SEED,\n max_features='auto'),\n # will do sqrt at each split\n {\n 'n_estimators': [10, 50, 100, 500, 1000],\n 'n_jobs': [5]\n }),\n 'Neural-Network': (\n MLPClassifier(solver='adam',\n learning_rate='adaptive',\n learning_rate_init=0.001,\n max_iter=10000,\n random_state=SEED,\n verbose=True,\n activation='relu',\n early_stopping=True),\n {\n 'hidden_layer_sizes': [(size,) for size in [1, 5, 20, 80, 320, 1280]],\n 'alpha': np.logspace(-3, 3, 11),\n }),\n }",
"def run_evaluation(models,retrain,get_split,num_runs,evaluation_func):\r\n metrics = [defaultdict(list) for m in models]\r\n for _ in xrange(num_runs):\r\n train,users,test = get_split()\r\n for i,model in enumerate(models):\r\n retrain(model,train)\r\n run_metrics = evaluation_func(model,train,users,test)\r\n for m,val in run_metrics.iteritems():\r\n print m,val\r\n metrics[i][m].append(val)\r\n return metrics",
"def evaluate_on_all(w):\n if isinstance(w, dict):\n w = Embedding.from_dict(w)\n\n # Calculate results on similarity\n logger.info(\"Calculating similarity benchmarks\")\n similarity_tasks = {\n \"MEN\": fetch_MEN(),\n \"WS353\": fetch_WS353(),\n \"WS353R\": fetch_WS353(which=\"relatedness\"),\n \"WS353S\": fetch_WS353(which=\"similarity\"),\n \"SimLex999\": fetch_SimLex999(),\n \"RW\": fetch_RW(),\n \"RG65\": fetch_RG65(),\n \"MTurk\": fetch_MTurk(),\n \"TR9856\": fetch_TR9856(),\n }\n\n similarity_results = {}\n\n for name, data in iteritems(similarity_tasks):\n similarity_results[name] = evaluate_similarity(w, data.X, data.y)\n logger.info(\"Spearman correlation of scores on {} {}\".format(name, similarity_results[name]))\n\n # Calculate results on analogy\n logger.info(\"Calculating analogy benchmarks\")\n analogy_tasks = {\n \"Google\": fetch_google_analogy(),\n \"MSR\": fetch_msr_analogy()\n }\n\n analogy_results = {}\n\n for name, data in iteritems(analogy_tasks):\n analogy_results[name] = evaluate_analogy(w, data.X, data.y)\n logger.info(\"Analogy prediction accuracy on {} {}\".format(name, analogy_results[name]))\n\n analogy_results[\"SemEval2012_2\"] = evaluate_on_semeval_2012_2(w)['all']\n logger.info(\"Analogy prediction accuracy on {} {}\".format(\"SemEval2012\", analogy_results[\"SemEval2012_2\"]))\n\n # Calculate results on categorization\n logger.info(\"Calculating categorization benchmarks\")\n categorization_tasks = {\n \"AP\": fetch_AP(),\n \"BLESS\": fetch_BLESS(),\n \"Battig\": fetch_battig(),\n \"ESSLI_2c\": fetch_ESSLI_2c(),\n \"ESSLI_2b\": fetch_ESSLI_2b(),\n \"ESSLI_1a\": fetch_ESSLI_1a()\n }\n\n categorization_results = {}\n\n # Calculate results using helper function\n for name, data in iteritems(categorization_tasks):\n categorization_results[name] = evaluate_categorization(w, data.X, data.y)\n logger.info(\"Cluster purity on {} {}\".format(name, categorization_results[name]))\n\n # Construct pd table\n cat = pd.DataFrame([categorization_results])\n analogy = pd.DataFrame([analogy_results])\n sim = pd.DataFrame([similarity_results])\n results = cat.join(sim).join(analogy)\n\n return results",
"def _compute_model_metrics(self, X, y, sp, verbose=0):\n for structure in self.model_structure:\n\n if verbose > 0:\n print(f\"Fitting {structure.name} Model Structure...\")\n\n (\n miso_ranks,\n miso_correlations,\n cond_num_dict,\n qui_squared_dict,\n ) = structure.fit(X=X, y=y, sp=sp)\n\n self._metrics_dict[structure.name][\"miso_ranks\"] = miso_ranks\n self._metrics_dict[structure.name][\"miso_correlations\"] = miso_correlations\n self._metrics_dict[structure.name][\"cond_num_dict\"] = cond_num_dict\n self._metrics_dict[structure.name][\"qui_squared_dict\"] = qui_squared_dict\n\n if verbose > 0:\n print(f\"{structure.name} Structure fit finished! \\n\\n\")",
"def train():\n model = train_model()\n is_model_valid, metrics = validate_model(model)\n if is_model_valid is False:\n raise Exception(\"Invalid model.\")\n else:\n save_model(model)\n return metrics",
"def list_models():\n response = requests.get(BASE_URL + \"models/\")\n response.raise_for_status()\n data = response.json()\n\n LOGGER.info(\"Found %i models\", data[RESULTS_COUNT])\n\n models = DataFrame(columns=[\"bigg_id\", \"metabolites\", \"reactions\", \"genes\", \"organism\"])\n for i, d in enumerate(data[RESULTS]):\n models.loc[i] = [d[BIGG_ID], d[METABOLITE_COUNT], d[REACTION_COUNT], d[GENE_COUNT], d[ORGANISM]]\n\n return models",
"def compute_evaluation_metrics(scores=utils.SCORES, models=utils.ALL_MODELS,\n results_path=utils.RESULTS_FILE_PATH):\n results = {}\n X, y = utils.get_data()\n sss = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)\n for model in models:\n model_name = utils.get_model_name(model)\n print(\"Training {}\".format(model_name))\n aux_scores = [elem for elem in scores]\n clf = utils.pipeline_model(model)\n s = cross_validate(clf, X, y, cv=sss, scoring=aux_scores,\n return_train_score=False)\n results[model_name] = {x: s[x] for x in s}\n print()\n print(\"Finished training {}\".format(model_name))\n w = csv.writer(open(results_path, \"w\"))\n for key, val in results.items():\n w.writerow([key, val])\n return results",
"def get_performance(splits=(10, 25, 50)) -> pd.DataFrame:\n performance = {num_splits: evaluate_models(num_splits) for num_splits in splits}\n performance_flattened = {(model, num_splits, source, performance[num_splits][model][source]['f1-score'])\n for num_splits in splits\n for model in performance[num_splits]\n for source in performance[num_splits][model]}\n return pd.DataFrame(performance_flattened, columns=(\"Model\", \"Splits\", \"Source\", \"F Score\"))",
"def predict_all():\n \n # Loads the serialised analytic models. \n lrm = joblib.load(\"app/mod_stat/model_linear.pkl\") \n log = joblib.load(\"app/mod_stat/model_binary.pkl\")\n \n # Queries each unique associated count value from the database.\n results = Counts.select(Counts.counts_associated).distinct()\n \n count_values = []\n for result in results:\n if result.get_result()[\"counts_associated\"] != \"None\":\n count_values.append(result.get_result()[\"counts_associated\"])\n\n # For each unique associated count value:\n for count in count_values:\n # Updates every row of the database having that value with a corresponding predicted count. \n query = Counts.update(counts_predicted=int(lrm.predict(int(count))[0])).where(Counts.counts_associated == count)\n query.execute()\n\n # Updates every row of the database having that value with a corresponding binary estimation. \n query = Counts.update(counts_predicted_is_occupied=log.predict(int(count))[0]).where(Counts.counts_associated == count)\n query.execute()",
"def train_metrics(self):\n return self._train_metrics",
"def get_scoring_engine_list(self):",
"def evaluate_models_2():\n df = prepare_individual_datasets()\n get_averaged_models()\n scores = []\n mean_plot = []\n print(\"Starting evaluation...\")\n for model in glob.glob('*_averaged.csv'):\n averaged_model = pd.read_csv(model)\n featuress = averaged_model['feature']\n\n # weights\n intercept = averaged_model['weight'].values[0]\n weights = averaged_model['weight'][1:]\n features_used = featuress.values[1:]\n # reindex to perform series multiplication\n weights.index = features_used\n\n temp_scores = []\n for station in df:\n X = station.loc[:, station.columns != 'bikes']\n Y = station['bikes']\n X = X.filter(items=features_used)\n predictions = X.apply(lambda row: intercept + row.dot(weights), axis=1).astype('int64')\n temp_scores.append(mean_absolute_error(predictions, Y))\n name = model.split('_averaged')[0]\n scores.append((name, temp_scores))\n mean_score = mean(temp_scores)\n print(f'Accuracy of model {name} is {mean_score}\\n')\n mean_plot.append(mean_score)\n plot_scores_2(scores, mean(mean_plot))\n print(mean(mean_plot))",
"def evaluate(self):\n # Training the Multiple Linear Regression model on the Training set\n self.regressor = LinearRegression()\n return self.evaluate_from_dataset_manager_and_regressor(\"Multiple Linear Regression\", self.regressor)",
"def load_models():\n logger.info(\"[CATEGORIES] Loading the encoder ...\")\n encoder = load_pickled(ENCODER_PATH)\n\n logger.info(\"[CATEGORIES] Loading the vectorizer ...\")\n (_vectorize_many, vectorize_one) = load_vectorizer(STEMMER, TFIDF_PATH, SVD_PATH)\n\n logger.info(\"[CATEGORIES] Loading the regression models ...\")\n reg_categories = load_pickled(REG_CAT_PATH)\n\n logger.info(\"[CATEGORIES] Loading the boosting models ...\")\n xgb_urgency = load_xgb(XBG_URG_PATH)\n cat_urgency = load_cat(CAT_URG_PATH)\n lgb_categories = load_lgb(LGB_CAT_PATH)\n\n def build_classifier(\n first: Classifier, second: Classifier, weights: List[float]\n ) -> Callable[[np.ndarray], np.ndarray]:\n def classifier(vectors: np.ndarray) -> np.ndarray:\n return blend(vectors, [first, second], weights=weights)\n\n return classifier\n\n urgency_clf = build_classifier(\n xgb_urgency.predict_proba, cat_urgency.predict_proba, LGB_REG_URGENCY_WEIGHTS\n )\n category_clf = build_classifier(\n reg_categories.predict_proba, lgb_categories.predict, LGB_REG_CATEGORIES_WEIGHTS\n )\n return encoder, vectorize_one, urgency_clf, category_clf"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns an average of all MAE scores for all patients.
|
def get_patients_mean_MAE_score(list_patients_objects):
return pd.DataFrame(list_patients_objects).mean()['MAE']
|
[
"def _normal_scores_average(self):\n average_scores = npi.group_by(self.normal_score_matrix[:, 0], self.normal_score_matrix[:, 3], np.mean)\n\n return average_scores",
"def average(self):\n # Sum each data item across all Exons in the list\n summed_data = None\n for exon in self:\n if summed_data is None:\n summed_data = []\n for item in exon.data:\n summed_data.append(item)\n else:\n for i in range(len(summed_data)):\n try:\n summed_data[i] += float(exon.data[i])\n except ValueError:\n summed_data[i] = None\n # Divide sums to get averages\n averaged_data = []\n if summed_data is not None:\n n = float(len(self))\n for s in summed_data:\n try:\n averaged_data.append(s/n)\n except TypeError:\n averaged_data.append(None)\n return averaged_data",
"def calc_mean_score(movies):\r\n list_of_scores = []\r\n for m in movies:\r\n list_of_scores.append(m.score)\r\n return round(mean(list_of_scores), 1)",
"def calc_mean_score(movies):\n \n\n return round(sum(movie.score for movie in movies) /len(movies),1)",
"def average(data):\n counts = len(data)\n total = sum(data)\n return total / counts",
"def compute_averages(self):\n self.energy_average = self.cumulative_energy / self.N\n self.energy_squared_average = self.cumulative_squared_energy / self.N\n self.wave_function_derivative_average = self.cumulative_wave_function_derivative / self.N\n self.wave_function_energy_average = self.cumulative_wave_function_energy / self.N",
"def calculate_all_average_scores(context_data: list[dict[str, Any]]) -> CommandResults:\n scores = defaultdict(list) # Format is 'indicator: [collected scores]'\n\n for dbot_score_item in context_data:\n indicator = dbot_score_item['Indicator']\n\n scores[indicator].append(dbot_score_item['Score'])\n\n context_output = []\n\n for indicator, scores_list in scores.items():\n context_output.append(calculate_average_score(indicator=indicator, scores_list=scores_list))\n\n return CommandResults(\n outputs_prefix='DBotAvgScore',\n outputs_key_field='Indicator',\n outputs=context_output,\n readable_output=tableToMarkdown('DBot Average Scores', t=context_output),\n )",
"def apg(self):\n if self._games is None:\n raise TypeError('games has not been set')\n return self._games['assists'].mean()",
"def item_mean(grades):\n result = {}\n exams1 = [int(gradeDict['Exam 1']) for _, gradeDict in grades.items()]\n exams2 = [int(gradeDict['Exam 2']) for _, gradeDict in grades.items()]\n exams3 = [int(gradeDict['Exam 3']) for _, gradeDict in grades.items()]\n result['Exam 1'] = sum(exams1) / len(exams1)\n result['Exam 2'] = sum(exams2) / len(exams2)\n result['Exam 3'] = sum(exams3) / len(exams3)\n return result",
"def get_average(self):\n # compute the mean\n self.average_fit = statistics.mean([self.fitness_dict[key] for key in self.fitness_dict])\n self.average_age = statistics.mean([self.age_dict[key] for key in self.age_dict])\n\n # Add average fitness at each time step to the collector\n self.average_fit_list.append(self.average_fit)\n self.average_age_list.append(self.average_age)",
"def _get_average_best_scores(self):\n return numpy.mean([x['best_scores'] for x in self.results], axis=0)",
"def calculate_mean(collection):\n ratings = []\n for game in collection['items']['item']:\n ratings.append(float(game['stats']['rating']['@value']))\n mean = sum(ratings)/len(ratings)\n return mean",
"def compute_average_rewards(self, episodes_back):\n reward = 0\n for agent in self.child_agents:\n agent_average_reward = reduce(\n lambda x, y: x + y, agent.ep_rewards[-episodes_back:]) / episodes_back\n reward += agent_average_reward\n\n reward /= self.num_childs\n\n return reward",
"def macro_average(scores):\n n = len(scores)\n ave_p = sum(s.precision for s in scores) / n\n ave_r = sum(s.recall for s in scores) / n\n return Score(ave_p, ave_r)",
"def avg_score(self, filtered=False):\n _, grading, scores, students = self.sentiment_analysis(self.dataset, filtered)\n libStu2Score = defaultdict(lambda: [])\n for ite, stu in enumerate(students):\n libStu2Score[stu].append(scores[ite])\n return {k: np.average(v) for k, v in libStu2Score.items()}",
"def ml_mean(values):\n\n # return the equation for mean\n return sum(values)/len(values)",
"def average(data):\n return 1.0*sum(data)/len(data)",
"def average_grades(grades):\n for key in grades.keys():\n \tgrades[key] = sum(grades[key]) / len(grades[key])\n return grades",
"def averages(self):\n return int(self.visa_ask(':aver?'))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Stores a patient object (containing the patient_id) to a npy format.
|
def save_patient_object(patient_object, prefix='', path_to_features=FEATURE_PATH):
np.save(path_to_features + str(prefix) + str(patient_object['patient_id'])+'_'+'top_features.npy', patient_object)
|
[
"def save_npy(object, file_name):\n\twith open(file_name, \"wb\") as fw:\n\t\tnp.save(fw, object)",
"def save_npy(self, filename):\n np.save(filename, self.data)",
"def save_object_npy(alfpath, dico, object):\n alfpath = Path(alfpath)\n status = check_dimensions(dico)\n if status != 0:\n raise ValueError('Dimensions are not consistent to save all arrays in ALF format: ' +\n str([(k, v.shape) for k, v in dico.items()]))\n\n for k, v in dico.items():\n np.save(alfpath / (object + '.' + k + '.npy'), v)",
"def save_sample(self, fp = None):\n \n if fp == None:\n fp = self.fp\n \n # save every possible key / value of sampler object\n dataDict = dict()\n storable_dtypes = (str, int, float, bool, np.float32, np.float64, list, np.ndarray)\n \n for key, val in self.__dict__.items():\n if isinstance(val, storable_dtypes) == True:\n dataDict[key] = val\n \n m.patch()\n try:\n binary = msgpack.packb(dataDict, use_bin_type = True)\n with open(fp, 'wb') as f:\n f.write(binary)\n except Exception as e:\n print(e)",
"def save_data(self, patient, phase):\n output_list.append(\n [patient.patient_id, patient.state, patient.treatment_cycles, phase, patient.cost, patient.utility,\n self.run_number, self.env.now])",
"def save_pickle(self, filepath):\n with open(filepath, mode='wb') as picklefile:\n pickle.dump(self.data_numpy, picklefile, protocol=-1)",
"def _save_tensor_in_npy(self, op_name, tensor_type, idx, tensor, dump_data_array):\n out_file_name = \"%s.%s.%d.%s.npy\" % (\n op_name,\n tensor_type,\n idx,\n self.cann_tools.common.get_format_string(tensor.format)\n )\n out_path = os.path.join(self.args_parser.output_path, out_file_name)\n np.save(out_path, dump_data_array)\n os.chmod(out_path, stat.S_IRUSR)",
"def save(location: str, data: DictClass) -> None:\n os.makedirs(location, exist_ok=True)\n if hasattr(data, \"attrs\"):\n np.save(os.path.join(location, \"attrs\"), dict(data.attrs), allow_pickle=True)\n\n for key_top in data.keys():\n os.makedirs(os.path.join(location, key_top), exist_ok=True)\n for key, val in data[key_top].items():\n np.save(os.path.join(location, key_top, key + \".npy\"), val)",
"def _safe_save(group, array, name):\n\n if array is not None:\n ds = group.create_dataset(name, shape=array.shape,\n dtype=array.dtype, chunks=True)\n ds[:] = array",
"def save_synapses_npy(synapse_point_df, npy_path, save_index=None):\n assert save_index in (True, False, None)\n if save_index is None:\n save_index = (synapse_point_df.index.name is not None)\n\n dtypes = {}\n\n # Avoid 'pickle' objects (harder to load) by converting\n # categories/strings to fixed-width strings\n max_kind = synapse_point_df['kind'].map(len).astype(int).max()\n dtypes['kind'] = f'U{max_kind}'\n\n if 'user' in synapse_point_df:\n max_user = synapse_point_df['user'].map(len).astype(int).max()\n dtypes['user'] = f'U{max_user}'\n\n np.save(npy_path, synapse_point_df.to_records(index=save_index, column_dtypes=dtypes))",
"def serialize_numpy(self, buff, numpy):\n try:\n pass\n except struct.error as se: self._check_types(struct.error(\"%s: '%s' when writing '%s'\" % (type(se), str(se), str(_x))))\n except TypeError as te: self._check_types(ValueError(\"%s: '%s' when writing '%s'\" % (type(te), str(te), str(_x))))",
"def save(self):\n idevicesDir = self.config.configDir/'idevices'\n if not idevicesDir.exists():\n idevicesDir.mkdir()\n fileOut = open(idevicesDir/'generic.data', 'wb')\n fileOut.write(persist.encodeObject(self.generic))",
"def save_volume(self, volume, affine, patient, volume_type):\n self.data_io_obj.save_volume(volume, affine, patient, volume_type)",
"def __init__(self,patient_dictionary):\n self.demographics = patient_dictionary\n # Initialize instance vars for backward compatibility\n self.pid = self.demographics['PID']\n self.fname = self.demographics['fname']\n self.lname = self.demographics['lname']\n self.gender= self.demographics['gender']\n self.zip = self.demographics['pcode']\n self.dob = self.demographics['dob']\n \n # Initialize additional instance vars\n self.initial = self.demographics['initial']\n self.street = self.demographics['street']\n self.apartment = self.demographics['apartment']\n self.city = self.demographics['city']\n self.region = self.demographics['region']\n self.pcode = self.demographics['pcode']\n self.country = self.demographics['country']\n self.email = self.demographics['email']\n self.home = self.demographics['home']\n self.cell = self.demographics['cell']\n \n # Insert the patient instance into the Patient mpi store:\n pid = self.demographics['PID']\n if not pid in self.__class__.mpi: self.__class__.mpi[pid]=self",
"def save(self, fpath):\n payload = {\n \"size\": self.size,\n \"step\": self.steps,\n \"active_cells\": [x for x in zip(*np.where(self.mat == 1))],\n }\n\n # HACK: np.int64 cause problems serializing\n def default(o):\n if isinstance(o, np.int64):\n return int(o)\n raise TypeError\n\n with open(fpath, \"w\") as f:\n f.write(json.dumps(payload, default=default))",
"def numpy_save(list_to_save, write_location):\n np.save(write_location, list_to_save)",
"def Save_to_Disk(self,fitness,dna_proto):\n dna_proto.fitness = fitness\n with open('./Protocol_Buffer/'+str(dna_proto.ID)+\".pickel\", 'wb') as p:\n pickle.dump(dna_proto, p)",
"def save_dict(dict_obj, path):\n assert path[-4:] == '.npy', 'Missing the .npy extension!'\n\n np.save(os.path.expanduser(path), dict_obj)",
"def write_record(self, s):\n s = np.array(s, order='F')\n np.array([s.nbytes],dtype=self._header_dtype).tofile(self._fp)\n s.tofile(self._fp)\n np.array([s.nbytes],dtype=self._header_dtype).tofile(self._fp)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Helper to turn a string into a list of not empty lines and returns it.
|
def _non_empty_lines(output):
return [line for line in output.splitlines() if line.strip()]
|
[
"def split_and_strip_non_empty_lines(text):\r\n return [line.strip() for line in text.splitlines() if line.strip()]",
"def remove_empty_lines(strIn):\n return os.linesep.join([s for s in strIn.splitlines() if s.strip()])",
"def no_emptylines(array):\n new_array = []\n for a in array:\n if a != '\\n':\n new_array.append(a)\n return new_array",
"def _to_list(items):\n return [\n item.strip() for item in items.split('\\n') if item.strip()\n ]",
"def non_comment_lines(self):\n return [_ for _ in self.stripped_whole_lines() if not _.startswith(\"#\")]",
"def get_lines(filename: str) -> List[str]:\n try:\n f = open(filename, \"r\")\n return f.read().splitlines()\n except IOError:\n return\n finally:\n f.close()",
"def removeEmptyLines(self, lines):\n\n\t\tnoneEmptyLines = []\n\t\tfor line in lines:\n\t\t\tif line.strip() != '':\n\t\t\t\tnoneEmptyLines.append(line)\n\t\t\t\n\t\treturn noneEmptyLines",
"def get_lines(stream):\n s = stream.read()\n return re.split(r'\\r\\n|\\n|\\r', s)",
"def _get_log_lines(self):\n return [\n log_line\n for log_line in self.captured_output.getvalue().split(\"\\n\")\n if log_line\n ]",
"def _splitlines(s, keepends=0):\n # Implementation notes:\n # I am copying Python 2.2's splitlines algorithm. I am sure there\n # is an easier way.\n lines = []\n\n i = j = 0 # line delimiters\n length = len(s)\n while i < length:\n # move i to end of line\n while i < length and s[i] != '\\n' and s[i] != '\\r':\n i = i + 1\n # handle EOL\n eol = i\n if i < length:\n if s[i] == '\\r' and i+i < length and s[i+1] == '\\n':\n i = i + 2\n else:\n i = i + 1\n if keepends:\n eol = i\n # append new line segment and move on to next\n lines.append( s[j:eol] )\n j = i\n if j < length:\n lines.append( s[j:length] )\n return lines",
"def remove_blanks_list(src):\n return [el for el in src if el]",
"def __wrapline__(self, line, unindented=False):\n if line.strip() == '':\n return ['', ]\n lines = []\n for wrappedline in textwrap.wrap(line, self.MAXLINE - len(self.INDENT)):\n if unindented:\n lines.append(wrappedline.rstrip())\n else:\n lines.append(self.__unindent__(wrappedline))\n return lines",
"def chunk_by_blank_lines(data: List[str]) -> List[List[str]]:\n\n responses: List[List[str]] = []\n\n group_answers: List[str] = []\n\n for count, line in enumerate(data, start=1):\n\n blank_line = line.strip() == \"\"\n\n if not blank_line:\n group_answers.append(line.strip())\n\n if blank_line or count == len(data):\n responses.append(group_answers)\n group_answers = []\n\n return responses",
"def line_endings_list(self):\n items = [\n ['None'],\n ['New Line', '\\n'],\n ['Carriage Return', '\\r'],\n ['Both NL & CR', '\\r\\n']\n ]\n current = get_setting('line_ending', None)\n\n simplified = [i[1] for i in items if len(i) > 1]\n simplified.insert(0, None)\n\n self.index = simplified.index(current)\n\n return items",
"def string2lines(self, convert_whitespace=True):\n if convert_whitespace:\n self.text = self._munge_whitespace(self.text)\n new_text = [s for s in self.text.splitlines()]\n return new_text",
"def _listify(grid):\n return [list(row) for row in grid.split('\\n') if row]",
"def _next_nonempty_line(self):\n line = \"\"\n while not line:\n line = self._next_line()\n return line",
"def sympy_cell_line_lists(cell: str) -> List[List[str]]:\n raw_lines = cell.split(\"\\n\")\n raw_line_components = [\n [elem.strip() for elem in line.split(\"=\")] for line in raw_lines\n ]\n return raw_line_components",
"def cleansplit(r_input):\n if isinstance(r_input, list):\n return [string.extract().strip(' \\t\\n\\r') for string in r_input if string.extract().split()]\n elif r_input == None:\n return ['']\n else:\n return r_input.strip(' \\t\\n\\r')"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Transforms EE image in numpy Array based on the aoi region
|
def get_array_from_image(self, image):
return geemap.ee_to_numpy(image, region=self.aoi)
|
[
"def fancyConvert(image):",
"def FI(image):\n a = iulib.floatarray()\n iulib.narray_of_numpy(a,transpose(image[::-1,...]))\n return a",
"def transform_image(self, inputImage: np.ndarray, imageColor: str) -> np.ndarray:\n pass",
"def register_component_images(fixed_array, moving_array, component_images_array, translation_range=1):\n fixed_itk = sitk.GetImageFromArray(fixed_array)\n dim = fixed_itk.GetDimension()\n translated_component_images = component_images_array.copy()\n translation_array = np.zeros(component_images_array.shape[:-1] + (dim,))\n\n for i in range(component_images_array.shape[-1]):\n transform = sitk.TranslationTransform(dim)\n component_image = component_images_array[..., i]\n component_image_itk = sitk.GetImageFromArray(component_image)\n x = [0] * dim\n ranges = (slice(0, 1.0, 1.0),) * (dim-2) + (slice(-translation_range, translation_range+1, 1.0),) * 2\n x0 = optimizer.brute(lambda x=x: find_best_translation(x, transform, fixed_itk, component_image_itk), ranges=ranges, finish=None)\n parameters = list(transform.GetParameters())\n parameters[0] = x0[0]\n parameters[1] = x0[1]\n transform.SetParameters(parameters)\n\n print(parameters)\n resampler = initialize_resampler(fixed_itk, transform)\n deformed_itk = resampler.Execute(component_image_itk)\n deformed_array = sitk.GetArrayFromImage(deformed_itk)\n translated_component_images[..., i] = deformed_array\n\n threshold_filter = sitk.OtsuThresholdImageFilter()\n threshold_filter.SetInsideValue(0)\n threshold_filter.SetOutsideValue(1)\n deformed_thresholded = threshold_filter.Execute(component_image_itk)\n deformed_thresholded_array = sitk.GetArrayFromImage(deformed_thresholded)\n xy = np.argwhere(deformed_thresholded_array > 0)\n new_xy = np.array(parameters)\n current_xy = translation_array[xy[:, 0], xy[:, 1]]\n translation_array[xy[:, 0], xy[:, 1]] = np.sign(new_xy) * np.maximum(current_xy, np.abs(new_xy))\n\n translated_moving_array = moving_array.copy()\n sorted_indices = np.argsort(np.linalg.norm(translation_array, axis=-1), axis=None)[::-1]\n for i, ind in enumerate(sorted_indices):\n xy = np.unravel_index(ind, component_images_array.shape[:-1])\n t = translation_array[xy][::-1]\n if not t.any():\n break\n upper_bound = np.array(component_images_array.shape[:-1])-1\n old_xy = (np.minimum(np.maximum(xy + t, [0, 0]), upper_bound)).astype(np.int)\n new_xy = (np.minimum(np.maximum(xy - t, [0, 0]), upper_bound)).astype(np.int)\n x, y = xy\n translated_moving_array[new_xy[0], new_xy[1], ...] = moving_array[x, y, ...]\n translated_moving_array[x, y, ...] = moving_array[old_xy[0], old_xy[1], ...]\n\n\n\n return translated_component_images, translated_moving_array",
"def transformData(X):\n #from 28 bits to 14 bits\n bits1 = 28\n bits2 = 14\n sq = 2\n m = X.shape[0]\n Xnew = np.zeros((m, bits2*bits2))\n for i in range(m):\n #reshape and process\n mat = np.reshape(X[i], (bits1,bits1))\n matnew = np.zeros((bits2,bits2))\n #take sqxsq pixels\n for j in range(bits2):\n for k in range(bits2):\n matnew[j,k] = np.average(mat[sq*j:sq*j+2,sq*k:sq*k+2])\n Xnew[i] = matnew.flatten()\n return Xnew",
"def transform(image, clicked_idx, min_max):\n image.undraw()\n\n #for switch rgb to work properly the function needs to iterate through the pixels\n if clicked_idx == 1:\n image = switch_rgb_channels(image)\n\n #iterates through all pixels going col by col from left to right\n for i in range(image.getWidth()):\n for j in range(image.getHeight()):\n\n rgb = image.getPixel(i,j)\n\n #invert colors\n if clicked_idx == 0:\n\n rgb = invert_pixel_color(rgb)\n\n #for switch rgb to work properly the function needs to iterate through the pixels\n\n #contrast change\n elif clicked_idx == 2:\n for g in range(3):\n rgb[g] = normalize(rgb[g], min_max[g][0] + 25, min_max[g][1] - 25 )\n\n #turn list to color object, set pixel\n rgb = color_rgb(rgb[0], rgb[1], rgb[2])\n image.setPixel(i, j, rgb)\n\n return image",
"def convert(self):\r\n\t\tself.image.convert_alpha()",
"def fast_ica(image, components):\n\n lab_img = transform.get_LAB_L(image)\n lab_img = np.array(lab_img, 'uint8')\n\n ica = FastICA(n_components=50)\n # run ICA on image\n ica.fit(lab_img)\n # reconstruct image with independent components\n image_ica = ica.fit_transform(lab_img)\n restored_image = ica.inverse_transform(image_ica)\n\n return restored_image",
"def FindAdaptiveROIversion2(image, center_ROI, aspr_ROI, array_ROI, displayImages, debug = True):\n #inputfilename = 'img6.png'\n #outputfilename = 'edge2.png'\n #nucleation_down = 1 # 0 for nucleation up\n #center_ROI = (511,672) #center of the object to be identified\n #aspr_ROI = 2/3 # x_width/y_width for ROI. This is found by TRAINING\n #debug = True # flag to output ERRRORs\n #remove the strip at the bottom\n #cropsequence = ((0,44),(0,0))\n #img = ReadImage(inputfilename)\n #img = CropImage(img,cropsequence,0)\n #to mainain the aspect ratio of roi to be same as that of image, set the aspect ratio\n #asp_ratio = int(1344/(1066-44))\n #list of pad sizes to be removed along x axis\n array_x_ROI = array_ROI\n array_y_ROI = (array_x_ROI*aspr_ROI).astype(int)\n n = array_x_ROI.size\n optimum_x_ROI = 0\n optimum_y_ROI = 0\n #set the array for relative strengths and maxima positions for the unimodal or bimodal distributions.\n array_rel_strength = np.zeros(n)\n array_maximum = np.zeros((n,2))\n #displayImages = 0\n for i in np.arange(n):\n x_width = array_x_ROI[i]\n y_width = array_y_ROI[i]\n #set up the cropsequence so that pads are removed centered around the center of the image.\n cropsequence = CropSequenceGenerate(image,(center_ROI,(x_width,y_width)))\n cropimg = CropImage(image,cropsequence,0)\n imgbyte = Img2Ubyte(cropimg,0)\n img_med = MedianFilter(imgbyte,displayImages)\n maximum,rel_strength = modal_analysis(img_med,displayImages,debug) #strength is zero if distribution is unimodal and close to zero if the foreground is very small compared to background or vice versa\n array_rel_strength[i] = rel_strength \n array_maximum[i] = maximum\n #displayImages = 1\n if displayImages==1:\n #plot the relative strength variation and choose the appropriate ROI\n plt.figure(),plt.title(\"Finding Optimum ROI by varying xROI\"),plt.plot(array_x_ROI,array_rel_strength)\n #if all are unimodal distributions, then there either is no object to be found or object is beyond the ROI. This means that we need to check for bigger ROIs with progressive increase in y axis width\n max_rel_strength = np.max(array_rel_strength)\n if debug: print(\"maximum relative strength is \" + str(max_rel_strength))\n if max_rel_strength < 0.001:\n optimum_x_ROI = 902\n else:\n #find the optimum ROI from maximum of the relative strength vs ROI variation\n optimum_x_ROI = array_x_ROI[array_rel_strength.argsort()[-1]]\n optimum_y_ROI = array_y_ROI[array_rel_strength.argsort()[-1]]\n #proceed with further processing with optimum ROI\n optimum_ROI = (optimum_x_ROI,optimum_y_ROI)\n if debug: print(\"Optimum ROI is \",optimum_ROI)\n return optimum_ROI",
"def numpy_to_vti(array, offset=[0, 0, 0], spacing=[1, 1, 1]):\n nx, ny, nz = array.shape\n image = vtk.vtkImageData()\n image.SetExtent(offset[0], nx+offset[0]-1, offset[1], ny+offset[1]-1,\n offset[2], nz+offset[2]-1)\n image.SetSpacing(spacing)\n image.AllocateScalars(vtk.VTK_FLOAT, 1)\n scalars = image.GetPointData().GetScalars()\n\n for x in range(offset[0], nx):\n for y in range(offset[1], ny):\n for z in range(offset[2], nz):\n scalars.SetTuple1(image.ComputePointId([x, y, z]),\n float(array[x, y, z]))\n\n return image",
"def transformData2(X):\n #from 28 bits to 14 bits\n bits1 = 28\n bits2 = 14\n sq = 2\n m = X.shape[0]\n Xnew = np.zeros((m, bits2*bits2))\n for i in range(m):\n #reshape and process\n mat = np.reshape(X[i], (bits1,bits1))\n matnew = np.zeros((bits2,bits2))\n #take sqxsq pixels\n for j in range(bits2):\n for k in range(bits2):\n a = np.average(mat[sq*j:sq*j+2,sq*k:sq*k+2])\n matnew[j,k] = 1.0 if a >= 128 else 0\n Xnew[i] = matnew.flatten()\n return Xnew",
"def image_process(img):\n data = image.img_to_array(img)\n data = np.expand_dims(data, axis=0)\n return data",
"def reconstruct_input_image(input_data, predicted_region):\r\n offset = 7\r\n\r\n def normalize(x):\r\n return np.array((x - np.min(x)) / (np.max(x) - np.min(x)))\r\n \r\n predicted_region = normalize(predicted_region)\r\n \r\n h, w, _ = np.shape(predicted_region)\r\n\r\n mask = np.sum(input_data, axis=2) == 0\r\n mask_i = np.sum(mask, axis=0)\r\n mask_j = np.sum(mask, axis=1)\r\n \r\n #print(list(np.where(mask_i == 50)[0])[0])\r\n i = np.where(mask_i == 50)[0][0] - offset\r\n j = np.where(mask_j == 50)[0][0] - offset\r\n\r\n full_image = input_data.copy()\r\n full_image[j+offset:j+h-offset, i+offset:i+w-offset] = predicted_region[offset:-offset,offset:-offset]\r\n\r\n return full_image",
"def remap(a,r,interp=cv2.INTER_CUBIC):\n imy,imx = a.shape\n x,y = np.meshgrid(range(imx),range(imy))\n return cv2.remap(a.astype(np.float32),\n (x+r[:,:,0]).astype(np.float32),(y+r[:,:,1]).astype(np.float32),interp)",
"def transform(self, images):\n images = check_images(images)\n \n ndims = len(images.value_shape)\n selections = []\n for region in self.regions:\n transformed = [[] for _ in range(ndims)]\n for indices in region.coordinates:\n for dim in range(ndims):\n transformed[dim].append(indices[dim])\n selections.append([array(indices) for indices in transformed])\n\n def mean_by_indices(image):\n out = array([mean(image[indices]) for indices in selections]).reshape((1, -1))\n return out\n\n return images.map(mean_by_indices).toseries()",
"def identify_ICA(self):\n self.ica = []\n config = self.config\n for i, eeg in enumerate(self.eegs):\n ica = ICA(n_components=config['lowlands']['ICAparam']['n_components'],\n method=config['lowlands']['ICAparam']['method'],\n random_state=config['lowlands']['ICAparam']['random_state'])\n ica.fit(eeg)\n\n ica.plot_components(inst=eeg)\n self.eegs[i] = ica.apply(eeg)",
"def image_to_DataArray(image, include_name=False):\n \n \n ypix = np.arange(image.SampleBase64.shape[0])\n xpix = np.arange(image.SampleBase64.shape[1])\n \n is_RGB = len( image.SampleBase64.shape)==3\n \n dims = [\"y\", \"x\"]\n coords = {\"xpix\":(\"x\", xpix), \"ypix\":(\"y\", ypix)}\n \n if is_RGB:\n dims.append(\"color\")\n coords.update({\"color\":[\"R\",\"G\",\"B\", \"A\"]})\n \n transform = image.get_transform(global_coords=True, \n mtransform=False)\n \n \n \n arr = xr.DataArray(image.SampleBase64,\n dims=dims,\n coords=coords)\n \n \n arr.attrs[\"TimeStamp\"] = timeparser(image.TimeStamp)\n arr.attrs[\"transform\"] = transform\n label = image.Label\n if not is_RGB:\n label += \" ({})\".format(image.Tags[\"TraceRetrace\"])\n arr.attrs[\"Label\"] = label\n \n arr = arr.assign_coords(ExportSettingsHeightMap.create_coord_dict(image))\n arr = arr.assign_attrs(ExportSettingsHeightMap.create_attr_dict(image))\n \n \n if include_name:\n return image.DataChannel, arr\n return arr",
"def angle_map(setup: object) -> np.ndarray:\n pixels_x = np.arange(setup.resolution[1])-setup.resolution[1]/2+0.5\n pixels_y = np.arange(setup.resolution[0])-setup.resolution[0]/2+0.5\n PX, PY = np.meshgrid(pixels_x, pixels_y)\n angles = np.arctan2(PY,PX)\n return angles",
"def _intri_camera(self):\n fx = -self.Img_WIDTH/(2.0*self.Dis_FAR*math.tan(self.theta * self.EDG2RAD))\n fy = fx\n u0 = self.Img_WIDTH / 2\n v0 = self.Img_HEIGHT / 2\n self.intri = np.array([[fx, 0, u0],\n [0, fy, v0],\n [0, 0, 1]])"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Save image of column with file name f_name, you can precise title, FOR EXAMPLE title= 'NDVI index on Nice' get_data.output_images(df['NDVI'],'NDVI_Nice',title=title) or title= 'Normalized temperature in Nice' get_data.output_images(df['Norm_Temp'],'Temp_Nice',title=title)
|
def output_images(self, col, f_name, cmap='RdYlGn', title='', band=10):
img = np.array(col)
img = img.reshape((self.shapes[band][0], self.shapes[band][1]))
plt.figure(figsize=(15, 10))
if title != '':
plt.title(title, fontsize=30)
plt.imshow(img, cmap=cmap)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.savefig(f'../output_images/{f_name}_{self.date}.png')
plt.close()
return None
|
[
"def get_image_filepath(data_dir, row):\n return os.path.join(data_dir, f\"{row.Species}___{row.Label}\", row.Filename)",
"def image_name(self, image_id: int):\n image_id_expanded = \"0\" * (12 - len(str(image_id))) + str(image_id)\n if self.mode == \"train\":\n return \"COCO_train2014_\" + image_id_expanded + \".jpg\", \"COCO_val2014_\" + image_id_expanded + \".jpg\"\n elif \"2018\" in self.mode:\n return \"VisualDialog_\" + self.mode + \"_\" + image_id_expanded + \".jpg\"\n elif \"2014\" in self.mode:\n return \"COCO_\" + self.mode + \"_\" + image_id_expanded + \".jpg\"\n else:\n raise FileNotFoundError",
"def process_csv(dataframe: pd.DataFrame, image_column_name: str,\n label_column_name: str,\n folder_with_images: str) -> pd.DataFrame:\n dataframe[image_column_name] = dataframe[image_column_name].apply(\n lambda x: f\"{folder_with_images}{x}.png\")\n dataframe[label_column_name] = dataframe[label_column_name].astype('str')\n return dataframe",
"def image_filename(cod_setor, coord_id, heading=None):\n if heading is not None:\n return \"IMG_{cod_setor:15d}_{coord_id:03d}_{heading:03d}.jpg\".format(cod_setor=int(cod_setor),coord_id=int(coord_id),heading=int(heading))\n else:\n return \"IMG_{cod_setor:15d}_{coord_id:03d}.jpg\".format(cod_setor=int(cod_setor),coord_id=int(coord_id))",
"def save_image(\n self, figure: plt.Figure, filename: str, img_title: str, **kwargs\n ):\n # Saving image to file\n img_path = self.img_directory + filename\n figure.savefig(img_path, **kwargs)\n # Include image in the report\n self.report_file.write(self.parse_image(img_path, img_title))",
"def save_img(self, label):\n dataset_to_save = self.dataset\n # New images will be saved outside SOTA dataset if the line below is\n # uncommented\n # dataset_to_save = \"extra-dataset\"\n\n label_path = \"utils/datasets/{0}/{1}\".format(dataset_to_save, label)\n if not os.path.exists(label_path):\n os.makedirs(label_path)\n img_num = 0\n while os.path.exists(\"{0}/{1}{2}.png\".format(label_path, label, img_num)):\n img_num += 1\n\n img_path = \"{0}/{1}{2}.png\".format(label_path, label, img_num)\n\n cv2.imwrite(img_path, self.display_img)",
"def image_filename(im_num=0, pos_num=0, channel_num=0, z_num=0):\n filename = \"img_channel{0:03d}_position{1:03d}_time{2:09d}_z{3:03d}.tif\"\n return filename.format(channel_num, pos_num, im_num, z_num)",
"def get_image_labels_file(self, subset):\n\n return \"{}-annotations-human-imagelabels{}.csv\".format(subset, \"-boxable\" if not self.image_level else \"\")",
"def get_image_df(image_path, df):\n image = process_image(image_path)\n return image, df",
"def save_df_as_img(df, out_file_path):\n\n fig, ax = plt.subplots()\n\n # hide axes\n fig.patch.set_visible(False)\n ax.axis('off')\n ax.axis('tight')\n\n df2 = df.iloc[:-2, :-1]\n df2 = df2.round(2)\n df2['accuracy'] = [df2.iloc[3, 0], df2.iloc[3, 0], df2.iloc[3, 0], df2.iloc[3, 0]]\n df2 = df2.iloc[:-1]\n\n tab = ax.table(cellText=df2.values, colLabels=['Precision', 'Recall', 'F1-score', 'Accuracy'],\n rowLabels=['Normal', 'Covid-19', 'Pneumonia'], loc='center', cellLoc='center')\n tab.auto_set_font_size(False)\n tab.set_fontsize(10)\n\n mergecells(tab, (2, 3), (1, 3))\n mergecells(tab, (2, 3), (3, 3))\n\n tab.scale(0.8, 1.4)\n\n for i in range(4):\n for j in range(4):\n tab.get_celld()[(i, j)].set_width(0.16)\n\n tab[2, 3].visible_edges = 'LR'\n\n fig.tight_layout()\n\n plt.savefig(os.path.join(out_file_path) + '.png')\n\n img = Image.open(os.path.join(out_file_path) + '.png')\n\n w, h = img.size\n img.crop((30, 180, w - 120, h - 180)).save(os.path.join(out_file_path) + '_cut.png')",
"def get_save_image_name(org_im, org_im_path, output_dir):\n # name prefix of orginal image\n org_im_name = os.path.split(org_im_path)[-1]\n im_prefix = os.path.splitext(org_im_name)[0]\n ext = '.png'\n # save image path\n save_im_path = os.path.join(output_dir, im_prefix + ext)\n if os.path.exists(save_im_path):\n save_im_path = os.path.join(output_dir, im_prefix + 'time={}'.format(int(time.time())) + ext)\n\n return save_im_path",
"def create_forecast_images(self):\n results = self.get_forecast_range_from_db()\n if results:\n for w in results:\n im = ImageMaker(w.date, w.weather_type, w.temperature)\n im.write_text()\n print(\"Готово\")\n else:\n print(\"К сожалению на эти даты прогноза в базе нет.\")",
"def PlotToFileName(self) -> str:",
"def saveImage(self):\r\n files = listdir(self.out_dir)\r\n filename = \"slicer-{}-output\".format(self.slice_mode)\r\n\r\n counter = 1\r\n while filename + self.props.extension in files:\r\n filename = \"slicer-\" + self.slice_mode + \"-output\" + str(counter)\r\n counter += 1\r\n\r\n fullname = path.join(self.out_dir, filename + self.props.extension)\r\n self.final_img.save(fullname)",
"def current_filename(self):\n return \"%s_%s_%s.png\" % (LABELS[self.metadata['creating_entity']],\n SECTORS[self.metadata['sector']],\n CHANNELS[self.metadata['channel']])",
"def show_bird(prediction):\n try: \n img = Image.open('./images/' + prediction + '.jpg')\n st.image(img, use_column_width=True, caption='your lovely ' + FULL_NAMES[prediction])\n except FileNotFoundError:\n st.write('no image available for your lovely ' + FULL_NAMES[prediction])",
"def create_output_image(img, instances):\n pass",
"def save_image(input, output, target, filename):\n all_images = torch.cat((input, output, target))\n vutils.save_image(all_images, filename=\"saved_models/\" + filename, normalize=True)",
"def generate_image_filename(file_obj):\n return '%s.%s' % (generate_sha1(file_obj), detect_image_format(file_obj))"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Displays folium map of Temp (Celsius) and NDVI with scales
|
def display_folium_map(self, min_temp=20, max_temp=40, minNDVI=-1, maxNDVI=1):
linearndvi = cmp.LinearColormap(
['#d73027', '#fc8d59', '#fee08b', '#d9ef8b', '#91cf60', '#1a9850'],
vmin=minNDVI,
vmax=maxNDVI,
caption='NDVI - Vegetation index' #Caption for Color scale or Legend
)
palettetemp = ['blue', '#fddbc7', 'red']
linear_temp = cmp.LinearColormap(
palettetemp,
vmin=min_temp,
vmax=max_temp,
caption='Temperature (°C)' #Caption for Color scale or Legend
)
image = ee.Image(self.ee_image)
nir = image.select('B5')
red = image.select('B4')
b10 = image.select('B10')
ndvi = nir.subtract(red).divide(nir.add(red)).rename('NDVI')
temp = b10.subtract(273.15)
print(temp.max)
mapNice = folium.Map(location=[self.pos[1], self.pos[0]],
zoom_start=12)
mapNice.addLayer(temp, {
'min': min_temp,
'max': max_temp,
'palette': palettetemp
}, 'Temp')
mapNice.addLayer(
ndvi, {
'min':
-0.5,
'max':
0.7,
'palette': [
'#d73027', '#fc8d59', '#fee08b', '#d9ef8b', '#91cf60',
'#1a9850'
]
}, 'NDVI')
#FloatImage(image_ndvi, bottom=0, left=10).add_to(mapNice)
folium.LayerControl().add_to(mapNice)
mapNice.add_child(linearndvi)
mapNice.add_child(linear_temp)
mapNice
#linear_temp,linearndvi
return mapNice
|
[
"def display_basemap():\n world = gp.read_file(gp.datasets.get_path('naturalearth_lowres'))\n world.plot()",
"def plot_maps(df):\r\n\r\n df = pd.read_csv('Results/final_df.csv', index_col=0)\r\n\r\n fig = go.Figure(data=go.Scattergeo(\r\n lat=df.loc[:, 'Latitude'],\r\n lon=df.loc[:, 'Longitude'],\r\n mode='markers',\r\n marker=dict(\r\n color=df.loc[:, 'Total Cost per kg H2'],\r\n size=2,\r\n ),\r\n ))\r\n\r\n fig.update_layout(\r\n geo=dict(\r\n showland=True,\r\n landcolor=\"rgb(212, 212, 212)\",\r\n subunitcolor=\"rgb(255, 255, 255)\",\r\n countrycolor=\"rgb(255, 255, 255)\",\r\n showlakes=True,\r\n lakecolor=\"rgb(255, 255, 255)\",\r\n showsubunits=True,\r\n showcountries=True,\r\n projection=dict(\r\n type='natural earth'\r\n ),\r\n ),\r\n title='Total cost per kg H2 (Eur)'\r\n )\r\n fig.show()\r\n\r\n return",
"def draw_heatmap(x,y,z):\n x,y = np.meshgrid(x,y)\n terrain_map = folium.Map(location=[x[0,0], y[0,0]], tiles='Stamen Terrain', zoom_start=12)\n HeatMap(zip(x.flatten(),y.flatten(),z.flatten()), radius=10).add_to(terrain_map) \n terrain_map.save('map.html')",
"def plot_geo(lat,lon,param,ptype='scatter',figsize=plt.rcParams[\"figure.figsize\"],cmap=plt.rcParams[\"image.cmap\"],cbar=True,dark_map=False,show=False,contourlevels=15,log_contour=False,show_lat=True,show_lon=False,show_grid=True,**kwargs):\n mapkw={ 'llcrnrlon':None, 'llcrnrlat':None, 'urcrnrlon':None, \n 'urcrnrlat':None, 'llcrnrx':None, 'llcrnry':None, 'urcrnrx':None,\n 'urcrnry':None, 'width':None, 'height':None, 'projection':'moll',\n 'resolution':'c', 'area_thresh':None, 'rsphere':6370997.0,\n 'ellps':None, 'lat_ts':None, 'lat_1':None, 'lat_2':None, \n 'lat_0':None, 'lon_0':0, 'lon_1':None, 'lon_2':None, 'o_lon_p':None,\n 'o_lat_p':None, 'k_0':None, 'no_rot':False, 'suppress_ticks':True, \n 'satellite_height':35786000, 'boundinglat':None, 'fix_aspect':True, \n 'anchor':'C', 'celestial':False, 'round':False, 'epsg':None, \n 'ax':None}\n \n for kw in list(kwargs.keys()):\n if kw in mapkw:\n mapkw[kw]=kwargs.pop(kw)\n # to set default values different from standard default values\n s_kwargs={\n 'cmap':cmap,'linewidths':0.0, 'vmin':np.min(param),'vmax':np.max(param)}\n contour_kwargs={'linewidths':0.5,'animated':True}\n cmesh_kwargs={'shading':'flat','cmap':s_kwargs['cmap'],'alpha':0.8}\n \n m = Basemap(**mapkw)\n if ptype in ('colormesh','contour') and len(np.asarray(lon).shape)==1:\n x,y=np.meshgrid(lon,lat)\n else:#scatter or 1D contour/colormesh\n x, y = m(lon,lat)\n if ptype in ('colormesh','contour'):\n cmesh_kwargs['latlon']=True\n\n fig=plt.figure(figsize=figsize)\n if show_grid:\n if (mapkw['projection'] not in ('ortho',)) and show_lat:\n m.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])\n else: \n m.drawparallels(np.arange(-90,90,30))\n if show_lon:\n m.drawmeridians(np.arange(m.lonmin,m.lonmax+30,60),labels=[0,0,0,1])\n else: \n m.drawmeridians(np.arange(m.lonmin,m.lonmax+30,60))\n \n if dark_map:\n m.drawmapboundary(fill_color='#333333')\n m.fillcontinents(color='#000000',lake_color='#333333',zorder=0, alpha=0.8)\n else: \n m.drawmapboundary(fill_color='#dddddd')\n m.fillcontinents(color='#ffffff',lake_color='#dddddd',zorder=0, alpha=0.8)\n if ptype=='colormesh':\n cmesh_kwargs.update(kwargs)\n im=m.pcolormesh(x,y,param,**cmesh_kwargs)\n elif ptype=='contour':\n if not log_contour:\n clevs=np.linspace(np.min(param),np.max(param),contourlevels)\n else:\n clevs=np.logspace(np.min(param),np.max(param),contourlevels)\n contour_kwargs.update(kwargs)\n im=m.contour(x,y,param,clevs,**contour_kwargs)\n else: #assume ptype to default, ie 'scatter'\n s_kwargs.update(kwargs)\n im=m.scatter(x,y,c=param,**s_kwargs)\n \n\n if cbar:\n if 'vmax' in kwargs and 'vmin' in kwargs:\n import matplotlib as mpl\n norm=mpl.colors.Normalize(vmin=kwargs['vmin'], vmax=kwargs['vmax'])\n c_ax=fig.add_axes([0.95, 0.3, 0.015, 0.5])\n cb = mpl.colorbar.ColorbarBase(c_ax, cmap=cmap,norm=norm)\n else:\n cb = m.colorbar(im,\"right\", size=\"2%\", pad='2%')\n \n if show:\n plt.show()\n return fig,m",
"def nuclear_position_map() -> None:\r\n px.set_mapbox_access_token(open(\"mapbox_token\").read())\r\n\r\n mapdf = nuclear_locations_df()\r\n\r\n fig = px.scatter_mapbox(mapdf, lat='Latitudes', lon='Longitudes',\r\n template='seaborn',\r\n zoom=1.5,\r\n size='Emissions',\r\n color='Emissions',\r\n color_continuous_scale='jet',\r\n hover_name='Countries',\r\n hover_data=['Power Plant'],\r\n title='Nuclear Power plants around the World')\r\n fig.show()",
"def PFT_map(PFT,plats,plons, vmax=250):\n \n # remove negatives before plotting log scale (or else warnings apear)\n PFT_pos = np.copy(PFT)\n #PFT_pos[PFT_pos > vmax] = vmax\n PFT_pos[PFT_pos<=0] = np.NaN\n \n cs = plt.contourf(plons, plats, PFT_pos,\n levels = np.arange(0,vmax,30),\n cmap=\"Reds_r\",\n extend=\"max\",\n vmax=vmax, vmin=0)\n cs.cmap.set_over(\"blue\")\n cs.changed()\n \n tickvals = np.append(np.arange(0,vmax,100),vmax)\n #print(\"DEBUG:\",tickvals)\n cb = plt.colorbar(cs,pad=0.01,ticks=tickvals)\n cb.set_label('PFT [Gigawatts]')\n \n cb.set_ticks(list(tickvals))\n cb.ax.set_yticklabels(list(tickvals))\n \n \n return cs, cb",
"def PlotTomoMap(fname, dlon=0.5, dlat=0.5, title='', datatype='ph', outfname='', browseflag=False, saveflag=True):\n if title=='':\n title=fname;\n if outfname=='':\n outfname=fname;\n Inarray=np.loadtxt(fname)\n LonLst=Inarray[:,0]\n LatLst=Inarray[:,1]\n ZValue=Inarray[:,2]\n llcrnrlon=LonLst.min()\n llcrnrlat=LatLst.min()\n urcrnrlon=LonLst.max()\n urcrnrlat=LatLst.max()\n Nlon=int((urcrnrlon-llcrnrlon)/dlon)+1\n Nlat=int((urcrnrlat-llcrnrlat)/dlat)+1\n fig=plt.figure(num=None, figsize=(8, 12), dpi=80, facecolor='w', edgecolor='k')\n m = Basemap(llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, \\\n rsphere=(6378137.00,6356752.3142), resolution='l', projection='merc')\n \n lon = LonLst\n lat = LatLst\n x,y = m(lon, lat)\n xi = np.linspace(x.min(), x.max(), Nlon)\n yi = np.linspace(y.min(), y.max(), Nlat)\n xi, yi = np.meshgrid(xi, yi)\n \n #-- Interpolating at the points in xi, yi\n zi = griddata(x, y, ZValue, xi, yi)\n # m.pcolormesh(xi, yi, zi, cmap='seismic_r', shading='gouraud')\n cmap=matplotlib.cm.seismic_r\n cmap.set_bad('w',1.)\n m.imshow(zi, cmap=cmap)\n m.drawcoastlines()\n m.colorbar(location='bottom',size='2%')\n # m.fillcontinents()\n # draw parallels\n m.drawparallels(np.arange(-90,90,10),labels=[1,1,0,1])\n # draw meridians\n m.drawmeridians(np.arange(-180,180,10),labels=[1,1,1,0])\n plt.suptitle(title,y=0.9, fontsize=22);\n if browseflag==True:\n plt.draw()\n plt.pause(1) # <-------\n raw_input(\"<Hit Enter To Close>\")\n plt.close('all')\n if saveflag==True:\n fig.savefig(outfname+'.ps', format='ps')\n return",
"def map(stop_id,modeled,observed,colmn_per,colmn_per_str,colmn_diff,df,col_func,rad_func,lat,lon):\n\n\n #sets the map zoomed into san fran with a scale bar\n mapa = folium.Map([37.765, -122.45],\n zoom_start=13,\n tiles='cartodbpositron',\n control_scale = True)\n \n #sets the layers up so that marks can be added to it (NEED TO CHANGE WHEN THE DATA IM MAPPING CHANGES!!!)\n\n good_group = folium.FeatureGroup(name = 'Modeled vs. Observed Average Ridership (Tenth-Mile & Buffer Route Stop Data)')\n \n for name, row in df.iterrows():\n\n #takes care of a bug when there is a stop name in one year but not the other and a bug of having an infinite percent difference when the base year is zero \n if row[observed] == 0:\n row[observed] = 0.00001 \n row[colmn_per] = ((row[modeled] - row[observed])/row[observed])*100\n \n else:\n row[observed] = row[observed]\n \n html=\"\"\"\n <h2> STOP: \"\"\" + str(row[stop_id]) + \"\"\" </h2>\n <p> \n Stop Name: \"\"\" + row['STOPNAME'] + \"\"\" <br>\n </p> \n <p> \n Percent Difference: \"\"\" + str(round(row[colmn_per])) + \"\"\"%\n <br>\n Difference: \"\"\" + str(round(row[colmn_diff])) + \"\"\"\n </p>\n <p>\n Modeled Value: \"\"\" + str(round(row[modeled])) + \"\"\"\n <br>\n Observed Value: \"\"\" + str(round(row[observed])) + \"\"\"\n </p>\n <br>\n <h3> VALUES </h3> \n Employment (Log): \"\"\" + str(row['EDD_EMP_LOG']) + \"\"\" <br>\n Frequency (Log): \"\"\" + str(row['FREQ_S_LOG']) + \"\"\" <br>\n EOL_SOL (Dummy): \"\"\" + str(row['EOL_SOL']) + \"\"\" <br>\n Housing Density (Log): \"\"\" + str(row['HOUSING_16_DEN_LOG']) + \"\"\" <br>\n High Income Share: \"\"\" + str(row['SHR_INCOME_100P']) + \"\"\" <br>\n On Street Parking Price (Log): \"\"\" + str(row['PARK_HOURLY_AVG_ON_LOG']) + \"\"\" <br>\n Reliability: \"\"\" + str(row['ONTIME5']) + \"\"\" <br>\n BART Ridership (Log): \"\"\" + str(row['AVG_BART_LOG']) + \"\"\" <br>\n Close Stop (Dummy): \"\"\" + str(row['CLOSE_STOP']) + \"\"\" <br>\n Limited Route (Dummy): \"\"\" + str(row['LIMITED']) + \"\"\" <br>\n Express Route (Dummy): \"\"\" + str(row['EXPRESS']) + \"\"\" <br>\n Transbay Terminal (Dummy): \"\"\" + str(row['TRANSBAY']) + \"\"\" <br>\n MUNI Rail Ridership: \"\"\" + str(row['MUNI_RAIL_AVG']) + \"\"\" <br>\n </p>\"\"\"\n \n iframe = folium.IFrame(html=html, width=300, height=150)\n pop_up = folium.Popup(iframe, max_width=2650)\n \n folium.CircleMarker([row[lat], row[lon]], \n color=col_func(row[colmn_per]), \n fill_color=col_func(row[colmn_per]), \n radius=rad_func(row[colmn_diff]),\n fill_opacity = 0.3, popup=pop_up).add_to(good_group)\n \n \n\n good_group.add_to(mapa)\n \n return mapa",
"def bath_map(lat,lon,**kwargs):\n from mpl_toolkits.basemap import Basemap\n# from scipy.io.netcdf import netcdf_file\n\n\n# bath = kwargs.pop('bath','color')\n# cmap = kwargs.pop('cmap',cm.Spectral_r)\n# title = kwargs.pop('title',None)\n# pvmin = kwargs.pop('pvmin',None)\n rivers = kwargs.pop('rivers',False)\n landfill = kwargs.pop('landfill',True)\n coastlines = kwargs.pop('coastlines',True)\n figsz = kwargs.pop('figsz',None)\n res = kwargs.pop('res','i')\n# lvls = kwargs.pop('lvls',np.arange(-6000,000,500))\n\n # SETTING DOMAIN\n minLat, maxLat = map(float, lat)\n minLon, maxLon = map(float, lon)\n lond = maxLon-minLon\n latd = maxLat-minLat\n\n # SETTING FIGURE SIZE\n coord_ratio = latd/lond\n if not figsz:\n figsz = [8,8]\n if coord_ratio > 1:\n figsz[0] = figsz[0] / coord_ratio\n else:\n figsz[1] = figsz[1] * coord_ratio\n\n # MAP\n# fig = plt.figure(figsize=figsz)\n m = Basemap(llcrnrlon = minLon,\n llcrnrlat = minLat,\n urcrnrlon = maxLon,\n urcrnrlat = maxLat,\n resolution = res[0],\n projection = 'cyl',\n #~ lon_0 = minLon+(maxLon-minLon)/2,\n #~ lat_0 = minLat+(maxLat-minLat)/2,\n area_thresh=100000)\n # MAP FEATURES\n\n if landfill:\n m.fillcontinents(color='#DEDEDE')\n if coastlines:\n m.drawcoastlines(linewidth=1)\n if rivers:\n m.drawrivers()\n\n# if not pvmax: pvmax = 0\n\n # BATHYMETRY\n\n# if bath and (bath!='marble') and (bath!='none'):\n# print \"\\t processing bathymetry\"\n# bathfile = '/home/luke/Dropbox/Data/ETOPO/ETOPO1_Ice_g_gmt4.grd'\n# nc = netcdf_file(bathfile,'r')\n#\n# ncX = nc.variables['x'][::i]\n# ncY = nc.variables['y'][::i]\n# ncZ = nc.variables['z'][::i,::i]\n# ncXind = (ncX>minLon-.0002) & (ncX<maxLon+.0002)\n# ncYind = (ncY>minLat-.0002) & (ncY<maxLat+.0002)\n#\n# X = ncX[ncXind]\n# Y = ncY[ncYind]\n# Z = sp.array([z[ncXind] for z in ncZ[ncYind]])\n# X,Y = m(*meshgrid( X, Y))\n#\n# if (bath is 'color') or (bath is 'both'):\n# print \"\\t plotting colour bathymetry \"\n# m.pcolormesh(X,Y,Z,cmap=cmap,vmin=pvmin,vmax=pvmax)\n# colorbar()\n#\n# if (bath is 'contour') or (bath is 'both'):\n# print \"\\t plotting contour bathymetry\"\n#\n# contours = m.contour(X,Y,Z,levels=lvls,colors='gray',linestyles='-',linewidths=1.,alpha=1.0)#\n# clabel(contours,fmt='%.0f', fontsize=6)\n\n\n # GRIDLINES\n pstep = None\n mstep = None\n for degs in [.1,.5,1,5,10,20,50,100]:\n if (latd<=degs) & (not pstep): pstep = degs/10.\n if (lond<=degs) & (not mstep): mstep = degs/10.\n\n if not pstep: pstep=20\n if not mstep: mstep=20\n\n if pstep>mstep:mstep=pstep\n if mstep>pstep:pstep=mstep\n\n dec = -int(np.ceil(np.log10(pstep)))\n parallels = np.arange(np.around(minLat, dec),\n np.around(maxLat, dec)+pstep,\n pstep)\n meridians = np.arange(np.around(minLon, dec),\n np.around(maxLon, dec)+mstep,\n mstep)\n\n if len(meridians)>5: meridians = meridians[0::2]\n if len(parallels)>5: parallels = parallels[0::2]\n\n m.drawparallels(parallels,color='k',labels=[1,0,0,0],linewidth=0.5,dashes=[1,3])\n m.drawmeridians(meridians,color='k',labels=[0,0,0,1],linewidth=0.5,dashes=[1,3])\n\n return m",
"def TEST_Map_Geoid():\n HC, HS = imp.Fetch_Coef(\"full4\")\n lmax = 10; mins = 600; levels = 70;\n title = f\"Map of Geoid undulation\"\n fig = Map_Geoid(mins, levels, title, lmax, HC, HS)",
"def YKR_map():\n # Reading the grid file\n grid = gpd.read_file(GridFpFinder())\n # Creating the map instance\n m = folium.Map(location=[60.25, 24.8], zoom_start=10, control_scale=True)\n # Creating the choropleth map\n folium.features.GeoJson(grid, \n name='Grid',\n style_function=lambda x: {'edgecolor':'black', 'fillColor': 'transparent', 'weight': 0.2},\n tooltip=folium.features.GeoJsonTooltip(fields=['YKR_ID'],\n aliases = ['YKR ID:'],\n labels=True,\n sticky=False\n )\n ).add_to(m)\n # Adding layer control\n folium.LayerControl().add_to(m)\n display(m)",
"def plot_STSF(lon_CTD,lat_CTD,T,S,profs,t_parametros = [22.12,7.6,15.02],s_parametros = [36.77,33.8,27.73]):\n\n STSF_list,STSF,x,y = f_ubicacion_STSF(lon_CTD,lat_CTD,T,S,profs,t_parametros = [22.12,7.6,15.02],s_parametros = [36.77,33.8,27.73])\n\n #isobata 200m\n lon200,lat200 = fCTD.isobata_200()\n\n fig = plt.figure()\n ax = fig.add_axes([0.05,0.05,0.8,0.9],projection=ccrs.Mercator())\n ax.set_extent([-60,-48,-40,-30],crs = ccrs.PlateCarree())\n ax.add_feature(cfeature.LAND, color='#BDA973')\n ax.add_feature(cfeature.LAKES, color='lightcyan')\n ax.add_feature(cfeature.RIVERS, edgecolor='black')\n ax.coastlines(resolution='50m', color='black', linewidth=1)\n gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,\n linewidth=1, color='black', alpha=0.5, linestyle='-')\n gl.xlabels_top = False; gl.ylabels_right = False\n gl.xlocator = mticker.FixedLocator([-60,-58,-56,-54,-52,-50,-48])\n gl.ylocator = mticker.FixedLocator([-40,-38,-36,-34,-32,-30])\n gl.xformatter = LONGITUDE_FORMATTER; gl.yformatter = LATITUDE_FORMATTER\n gl.xlabel_style = {'size': 24, 'color': 'k'}\n gl.ylabel_style = {'size': 24, 'color': 'k'}\n # --- isobata\n ax.plot(lon200,lat200,color='grey', transform = ccrs.PlateCarree())\n # --- estaciones\n ax.scatter(lon_CTD,lat_CTD,s = 10,color = 'k', transform = ccrs.PlateCarree())\n colors = ['Red','Blue','Green','Grey','Orange','Purple']\n for iz in range(len(profs)):\n ax.scatter(STSF_list[iz][:,1],STSF_list[iz][:,0],s = 10,transform = ccrs.PlateCarree(),label = profs[iz])\n # ax.pcolor(x,y,STSF[iz],color = colors[iz], alpha = 0.7,transform = ccrs.PlateCarree(), label = str(profs[iz])+'m')\n plt.legend(fontsize = 30)",
"def plot_many_altitude(alt1, lon1, lat1, lim, hrange = None, alt2 = None, lon2 = None, lat2 = None, legend = None, h = None, title = None):\n f = 14\n my_cmap = copy(plt.cm.viridis_r)\n \n if hrange is None:\n hrange = [np.nanmin(alt1), np.nanmax(alt1)]\n\n fig, axes = plt.subplots(1, 1, figsize = [8, 8])\n plt.subplots_adjust(hspace = 0, wspace = 0)\n plt.subplot(111)\n \n plt.xlim(lim[0], lim[1])\n plt.ylim(lim[2], lim[3])\n plt.ylabel('Latitude ($\\degree$)', fontsize = f)\n plt.yticks(fontsize = f)\n plt.xlabel('Longitude ($\\degree$)', fontsize = f)\n plt.xticks(fontsize = f)\n \n if h is not None:\n brmodel = isa.fieldmodel.model_map([lim[0], lim[1]], [lim[2], lim[3]], h, 'Br')\n \n lengthx = (lim[1] - lim[0]) / (np.size(brmodel, 0)-1)\n lengthy = (lim[3] - lim[2]) / (np.size(brmodel, 1)-1)\n \n x = np.arange(lim[0], lim[1] + lengthx, lengthx)\n y = np.arange(lim[2], lim[3] + lengthy, lengthy)\n X, Y = np.meshgrid(x, y)\n C = plt.contour(X, Y, brmodel, 4, colors = 'k', alpha = 0.7)\n plt.clabel(C, inline = True, fmt = '%1.0f', fontsize = 12)\n \n p1 = plt.scatter(lon1, lat1, c = alt1, cmap = my_cmap, norm = colors.Normalize(vmin = hrange[0], vmax = hrange[1]), \\\n edgecolors = 'black', alpha = 1, s = 50)\n \n if alt2 is not None:\n p2 = plt.scatter(lon2, lat2, c = alt2, cmap = my_cmap, norm = colors.Normalize(vmin = hrange[0], vmax = hrange[1]), \\\n edgecolors = 'black', marker = '^', alpha = 1, s = 50)\n \n if legend is not None:\n plt.legend([p1, p2], [legend[0], legend[1]], fancybox = True, loc = 'lower left', edgecolor = 'inherit', \\\n framealpha = 1.0, fontsize = f, handletextpad = 0.4)\n \n plt.subplots_adjust(right = 0.8)\n cbar_ax = fig.add_axes([0.82, 0.2, 0.03, 0.6])\n cbar = fig.colorbar(p1, cax = cbar_ax)\n cbar.set_label('Altitude (km)', fontsize = f)\n cbar.ax.tick_params(labelsize = f)\n \n if title is None:\n plt.savefig('altitudes.pdf', bbox_inches = 'tight')\n else:\n plt.savefig('altitudes_' + title + '.pdf', bbox_inches = 'tight')\n return",
"def plot_staticmap1(self, ita, im, tc, fname, out, SOX):\n SOXf = r'SO$_' + SOX[-1] + '$'\n so2title = ('Atmospheric ' + SOXf + ' concentrations at ' +\n 'ground level (hourly means). \\n GCRF UNRESP')\n plt.figure(figsize=(16, 12))\n fle = fname\n if SOX == \"SO4\":\n binLims = self.binLimsSO4\n norm = self.normso4\n else:\n binLims = self.binLims\n norm = self.norm\n concA = conc_array(self.ny, self.nx, fle, binLims)[0]\n latMin, latMax, lonMin = self.latMin, self.latMax, self.lonMin\n lonMax = self.lonMax\n bmap = Basemap(llcrnrlon=lonMin, llcrnrlat=latMin,\n urcrnrlon=lonMax, urcrnrlat=latMax)\n bmap.imshow(im, origin='upper')\n bmap.pcolormesh(self.glon, self.glat, concA,\n norm=norm, cmap=self.cmap, alpha=0.5)\n cbar = bmap.colorbar(location='bottom', pad='20%', cmap=self.cmap,\n norm=norm, boundaries=[0.] + binLims\n + [100000.], extend='both', extendfrac='auto',\n ticks=binLims, spacing='uniform')\n cbar.ax.set_xticklabels(['v low', 'low', 'moderate', 'mod high',\n 'high', 'v high']) # horizontal colorbar\n cbar.set_label(label=(SOX + ' concentration'), fontsize=18)\n cbar.ax.tick_params(labelsize=16)\n cbar.solids.set(alpha=1)\n latTicks = np.arange(round(latMin, 1), round(latMax, 1) + 0.1, 0.1)\n lonTicks = np.arange(round(lonMin, 1), round(lonMax, 1) + 0.1, 0.2)\n bmap.drawparallels(latTicks, labels=[1, 0, 0, 0], linewidth=0.0,\n fontsize=16)\n bmap.drawmeridians(lonTicks, labels=[0, 0, 0, 1], linewidth=0.0,\n fontsize=16)\n for i, town in enumerate(self.towns):\n plt.plot(self.townCoords[i][0], self.townCoords[i]\n [1], 'ok', markersize=4)\n plt.text(self.townCoords[i][0], self.townCoords[i][1], town,\n color=tc, fontproperties=self.font, fontsize=12)\n for i, city in enumerate(self.cities):\n plt.plot(self.cityCoords[i][0], self.cityCoords[i]\n [1], 'sk', markersize=6)\n plt.text(self.cityCoords[i][0], self.cityCoords[i][1], city,\n fontproperties=self.font, fontsize=16)\n font0 = FontProperties()\n font0.set_family('monospace')\n plt.plot(self.volcCoords[0], self.volcCoords[1], '^r', markersize=6)\n plt.suptitle(so2title, fontsize=24)\n plt.title(self.dates[ita].strftime('%c %z'), fontsize=18)\n PNGfile = SOX + '_static_' + out + fle[-17:-4] + '.png'\n print(\"Writing out file \" + PNGfile)\n PNGpath = os.path.join(self.outDir, PNGfile)\n plt.savefig(PNGpath, dpi=250)\n plt.close()",
"def cMapDustTempMass(data,wcs=None,wcsMinMax=None,fluxImage=None,\n raCenter=None,decCenter=None,\n plotTitle=None,saveName=None):\n matplotlib.rcParams['xtick.labelsize'] = 6\n matplotlib.rcParams['ytick.labelsize'] = 6\n matplotlib.rcParams['axes.labelsize'] = 6\n\n fig = plt.figure()\n\n # Grid helper\n grid_helper = pywcsgrid2.GridHelper(wcs=wcs)\n # Setup the grid for plotting.\n grid = AxesGrid(fig, 111,\n nrows_ncols=(1, 2),\n axes_pad= (0.35,0.07),\n cbar_mode='each',\n cbar_location='right',\n cbar_pad=0,\n axes_class=(pywcsgrid2.Axes,dict(grid_helper=grid_helper)),\n share_all=True)\n for ii in range(2):\n # Get the axis.\n ax = grid[ii]\n # Set background color\n ax.patch.set_facecolor('black')\n # Make the tickmarks black.\n ax.tick_params(axis='both', colors='black',width=0)\n\n # Create the colormap.\n cmap = matplotlib.cm.rainbow\n cmap.set_bad('black',1.) #Set masked pixels to be black.\n\n # Crop and plot the image.\n image = data[ii,:,:]\n #im = ax.contourf(image,cmap=cmap)\n im = ax.imshow(image,cmap=cmap)\n\n # Label the property inside the subplot.\n if ii == 0 : label = 'Dust Temp [K]'\n if ii == 1 : label = r'Dust Mass [M$_{\\odot}$]'\n at = AnchoredText(label, loc=2, prop=dict(size=5))\n ax.add_artist(at)\n\n # Flip the axis per convention.\n ax.invert_yaxis()\n\n # Mark the center of the galaxy.\n ax['fk5'].plot(raCenter,decCenter,markeredgewidth=.9,\n marker='+', color='k',ms=7)\n\n # Mark flux contours and continuum contours.\n ax.contour(fluxImage,linewidths=0.85,alpha=0.8,colors='black')\n\n # Make a colorbar.\n cax1 = grid.cbar_axes[ii]\n if ii == 0 : fm = '%d'\n if ii ==1 : fm = '%.1e'\n cbar1 = cax1.colorbar(im,format=fm)\n cbar1.ax.tick_params(labelsize=4)\n\n # Set figure title.\n fig.text(0.5, 0.82, plotTitle,ha='center',fontsize=10)\n # Save the plot to PDF\n pp = PdfPages(saveName)\n pp.savefig(fig, bbox_inches='tight')\n pp.close()\n plt.close()",
"def station_anc_map():\n fig, ax = plt.subplots(figsize=(10,12))\n ctx_gdf.plot(figsize=(10, 10), alpha=0.5, edgecolor='red', ax=ax)\n ax.set_aspect('equal')\n ctx.add_basemap(ax, alpha=0.5)\n dc_stations.plot(ax=ax, color='yellow', alpha=0.6)\n ax.set_title('DC Capital Bikeshare stations with ANC boundaries', fontsize=18)\n ax.set(xticks=[], yticks=[])\n fig.tight_layout()\n plt.show();\n return fig, ax",
"def plot_sky_map(self, metric=None):\n if metric is None:\n pass # Just plot locations, no grayscale for metric.\n\n fig = plt.figure(figsize=(8, 8))\n ax = plt.subplot(111, projection=\"aitoff\")\n for name in self.regions.keys():\n x, y = radec2project(self.regions[name].ra, self.regions[name].dec)\n if metric is None:\n ax.scatter(x, y, alpha=0.7, label=name) # Marker color is assigned automatically\n else:\n if metric == 'Nvis':\n z = self.regions[name].Nvis\n # Need to add Nvis per filter as possible metrics.\n else:\n try:\n z = self.regions[name][metric]\n except:\n raise ValueError(\"unrecognized metric {}\".format(metric))\n s = ax.scatter(x, y, c=z, cmap='viridis')\n # s.set_clim([0,1000])\n plt.grid(True)\n if metric is None:\n plt.legend()\n else:\n plt.colorbar(s, orientation='horizontal')\n return",
"def show_heatmap(self):\n plt.show()",
"def CreatePlumesMap(lon, lat, plumes, out_name):\n \n plt.figure(figsize=(10,6))#, dpi=1200)\n \n ax = plt.axes(projection=ccrs.PlateCarree())\n gl = ax.gridlines(draw_labels=True)\n gl.top_labels = False\n gl.right_labels = False\n \n # Load some Cartopy Features\n ocean_50m = cfeature.NaturalEarthFeature('physical', 'ocean', '50m')\n ax.add_feature(ocean_50m, edgecolor = 'face', facecolor = '#FFFFFF', zorder=1)#'#d0d0d0', zorder=1) \n \n # bounds = [no plume, TROPOMI, GFED, TROPOMI+GFED, EDGAR, EDGAR+TROPOMI, GFED+EDGAR, GFED+EDGAR+TROPOMI]\n colors = ['#E5E5E5', '#F77F00', '#8FC93A', '#594236', '#0496FF', '#791E94', '#7AFDD6', '#F0C808']\n cmap = ListedColormap(colors)\n # Setting the (discrete) boundaries of the map\n bounds = [0,1,10,11,100,101,111,112]\n norm = BoundaryNorm(bounds, cmap.N)\n \n ax.pcolormesh(lon, lat, plumes, cmap = cmap, norm=norm, transform=ccrs.PlateCarree())\n it = lambda color: plt.Rectangle((0,0),1,1, facecolor=color, edgecolor='black')\n ax.legend([it(colors[0]), it(colors[1]), it(colors[2]), it(colors[3]), \\\n it(colors[4]), it(colors[5]), it(colors[6]), it(colors[7])], \\\n [\"no plume\", \"TROPOMI\", \"GFED\", \"TROPOMI + GFED\", \"EDGAR\", \\\n \"EDGAR + TROPOMI\", \"GFED + EDGAR\", \"GFED + EDGAR + TROPOMI\"], \\\n loc='upper center', bbox_to_anchor=(0.5, -0.045), ncol=3, \\\n fancybox=False, shadow=False, frameon=False)\n\n # Save the figure\n plt.savefig(out_name, bbox_inches='tight')#, dpi=1200)\n plt.cla()\n plt.clf()\n\n return"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
REMOVES SEA PIXELS OF A DATAFRAME based on the sea_pixel_table output of sea_pixel_of_Nice_ref_image class method
|
def remove_sea(self, working_df):
if type(self.sea_pixels) == "<class 'pandas.core.frame.DataFrame'>":
print(
'No criteria for exclusion of the sea, plz provide a sea_pixels df when instanciating class Smartrees'
)
return working_df
output_df = working_df.join(self.sea_pixels)
output_df.columns = ['Norm_Temp', 'NDVI', 'sea_pixel']
return output_df[output_df['sea_pixel'] == 1][['Norm_Temp', 'NDVI']]
|
[
"def seam_removal_mask(self, remove_pix, mask):\n m, n = mask.shape\n output = np.zeros((m, n - 1))\n for row in range(m):\n col = remove_pix[row]\n output[row, :] = np.delete(mask[row, :], [col])\n mask = np.copy(output)\n return mask",
"def remove_seam(img, seam):\n seam_rows = len(seam)\n for i in range(0, seam_rows):\n # Finding the seam point in a row,\n # moving all the values in the row before the seam point to\n # the right by one index,\n # deleting the first column from the row\n seam_col = seam[i]\n img[i, 1:seam_col + 1, :] = img[i, 0:seam_col, :]\n\n return numpy.delete(img, 0, 1)",
"def replace(self, img, dst_clr):\n for i in range(80, 340): #x1 x2\n for j in range(500, 800): #y1 y2\n img[j][i] = dst_clr\n return img",
"def dark_removal(image, darkframe):\n\n if len(image.shape) == 2:\n image -= darkframe\n else:\n raise Exception(\"Dark noise correction should be done before demosaic.\")\n return image",
"def replace_fast(self, img, dst_clr):\n img[535:750, :290, :] = dst_clr #h(y) w(x) c\n img[575:705, 900:, :] = dst_clr\n return img",
"def pixel_blender(sat_set_path, match_df):\r\n #Get the USAID point coordinates:\r\n pxl_points = match_df[['pxlX','pxlY']].values.tolist()\r\n #Get the mean and std one band at a time:\r\n for band in BAND_LIST:\r\n print(band, end='|', flush=True)\r\n #Load up the band:\r\n band_img = get_band(band,sat_set_path)\r\n #If the image is not on the 10980x10980 grid, use bilinear interpolation to blow it up:\r\n if band_img.shape[0]!=SAT_SIZE:\r\n band_img = scipy.misc.imresize(band_img,SAT_SIZE/band_img.shape[0],interp='bilinear',mode='F')\r\n #Crop the image around each USAID point and get distilled values for each:\r\n band_mean = []\r\n band_std = []\r\n for pair in pxl_points:\r\n x0 = int(np.round(pair[0]-VIEW_SIZE))\r\n x1 = int(np.round(pair[0]+VIEW_SIZE))\r\n y0 = int(np.round(pair[1]-VIEW_SIZE))\r\n y1 = int(np.round(pair[1]+VIEW_SIZE))\r\n img_crop = band_img[y0:y1,x0:x1]\r\n #Some points will be too close to the borders of the satellite image, so we can't get the whole crop:\r\n if img_crop.shape!=(2*VIEW_SIZE,2*VIEW_SIZE):\r\n print('ERROR:')\r\n print(img_crop.shape)\r\n band_mean += [np.mean(img_crop)]\r\n band_std += [np.std(img_crop)]\r\n #Check for strange problem with zeros:\r\n if np.mean(img_crop) < .1:\r\n print('Dark image problem!')\r\n #Put new features into dataframe:\r\n match_df[band+'_mean'] = band_mean\r\n match_df[band+'_std'] = band_std\r\n print(' -OK')\r\n return match_df",
"def crop(data, rows, columns):\n remove_pixels = set()\n for i in range(rows):\n for j in range(columns):\n if i == 0 or i == 1 or i == (columns-2) or i == (columns-1):\n remove_pixels.add(i + columns*j)\n if j == 0 or j == 1 or j == (rows-2) or j == (rows-1):\n remove_pixels.add(i + rows*j)\n output = sorted(list(remove_pixels))\n pixels_to_crop = ['pixel' + str(x) for x in output]\n return data[data.columns.difference(pixels_to_crop)]",
"def mark_reflections(original_image, out_image, high_coords, width, height, rgb_limit):\n\n\t# Convert it to np array of uint8 before sending to weave\n\trgb_limit_np = np.array(rgb_limit, dtype=np.uint8)\n\n\tcode = r\"\"\"\n\t\t// img_array: The original image\n\t\t// out_array: The output image\n\t\t// high_coords: A mask, 1 = above rgb limit, 0 = under rgb limit\n\n\t\tuint8_t *out_array_tmp = (uint8_t *)malloc(height * width * 3);\n\t\tuint8_t *img_array_tmp = (uint8_t *)malloc(height * width * 3);\n\t\tuint8_t *high_coords_tmp = (uint8_t *)malloc(height * width);\n\t\tuint8_t rgb_limit_tmp[3];\n\n\t\t#define IMG_ARRAY(i, j, k) (img_array_tmp[i * width * 3 + j * 3 + k])\n\t\t#define OUT_ARRAY(i, j, k) (out_array_tmp[i * width * 3 + j * 3 + k])\n\t\t#define HIGH_COORDS(i, j) (high_coords_tmp[i * width + j])\n\n\t\t// Copy from the arguments to the arrays\n\t\tmemcpy(out_array_tmp, out_image, width * height * 3);\n\t\tmemcpy(img_array_tmp, original_image, width * height * 3);\n\t\tmemcpy(high_coords_tmp, high_coords, width * height);\n\t\tmemcpy(rgb_limit_tmp, rgb_limit_np, 3);\n\n\n\t\t// Mark the bright pixels red\n\t\tfor (int i = 0; i < height; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < width; j++)\n\t\t\t{\n\t\t\t\tif (IMG_ARRAY(i, j, 0) > rgb_limit_tmp[0] && IMG_ARRAY(i, j, 1) > rgb_limit_tmp[1] && IMG_ARRAY(i, j, 2) > rgb_limit_tmp[2])\n\t\t\t\t{\n\t\t\t\t\tOUT_ARRAY(i, j, 0) = 0;\n\t\t\t\t\tOUT_ARRAY(i, j, 1) = 0;\n\t\t\t\t\tOUT_ARRAY(i, j, 2) = 255;\n\t\t\t\t\tHIGH_COORDS(i, j) = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmemcpy(out_image, out_array_tmp, width * height * 3);\n\t\tmemcpy(high_coords, high_coords_tmp, width * height);\n\n\t\tfree(out_array_tmp);\n\t\tfree(img_array_tmp);\n\t\tfree(high_coords_tmp);\n\t\"\"\"\n\tio = [\"original_image\", \"out_image\", \"high_coords\", \"width\", \"height\", \"rgb_limit_np\"]\n\tweave.inline(code, io, extra_compile_args=['-O0'])\n\n\treturn out_image, high_coords",
"def sharpen_image(frame):\n # Sharpen the image up so we can see edges under the heatmap\n kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])\n frame = cv2.filter2D(frame, -1, kernel)\n return frame",
"def analyse_une_seule_image(self, pixels):\n\t\tdef find_polynome(pixels):\n\t\t\t\"\"\"\n\t\t\tcherche le polinome d'ordre 2 qui permet au mieu\n\t\t\tde normaliser la courbe\n\t\t\tle polinome est de la forme a*x**2+b*x+c\n\t\t\t\"\"\"\n\t\t\tdef diff(f, x):\n\t\t\t\t\"\"\"\n\t\t\t\tderive f en x\n\t\t\t\t\"\"\"\n\t\t\t\th = 1e-8\n\t\t\t\treturn (f(x+h)-f(x-h))/(2*h)\n\n\t\t\tdef distance(a, b, c, pixels, rayon):\n\t\t\t\t\"\"\"\n\t\t\t\tretourne la distance entre les pixels et le polinome\n\t\t\t\tc'est comme un moindre carre mais en plus subtile\n\t\t\t\t\"\"\"\n\t\t\t\td = 0\n\t\t\t\tfor x, pixel in enumerate(pixels):\n\t\t\t\t\td_locale = abs(pixel - (a*(x-64)**2 + b*(x-64) + c))\n\t\t\t\t\tif d_locale < rayon:\n\t\t\t\t\t\td += d_locale\n\t\t\t\treturn d\n\n\t\t\tdef gradient(a, b, c, pixels, rayon):\n\t\t\t\t\"\"\"\n\t\t\t\tretourne la derivee partiel de l'erreur selon les trois\n\t\t\t\tcomposante a, b et c\n\t\t\t\t\"\"\"\n\t\t\t\treturn (\n\t\t\t\tdiff(lambda a: distance(a=a, b=b, c=c, pixels=pixels, rayon=rayon), a),\n\t\t\t\tdiff(lambda b: distance(a=a, b=b, c=c, pixels=pixels, rayon=rayon), b),\n\t\t\t\tdiff(lambda c: distance(a=a, b=b, c=c, pixels=pixels, rayon=rayon), c),\n\t\t\t\t)\n\n\t\t\tdef init(pixels):\n\t\t\t\t\"\"\"\n\t\t\t\tretourne le a, le b et le c initial\n\t\t\t\t\"\"\"\n\t\t\t\thaut = sum(pixels[64:])/64\n\t\t\t\tbas = sum(pixels[:64])/64\n\t\t\t\ta = -0.001\n\t\t\t\tb = (haut-bas)/128\n\t\t\t\tc = .5*(bas+haut)\n\t\t\t\treturn a, b, c\n\n\t\t\ta, b, c = init(pixels)\n\n\t\t\trayon = 100\n\t\t\ti = 0\n\t\t\twhile rayon >= 7:\n\t\t\t\ti+=1\n\t\t\t\trayon /= 1.004\n\t\t\t\tgrad = gradient(a, b, c, pixels, rayon)\n\t\t\t\ta -= 1e-8 * grad[0]\n\t\t\t\tb -= 3e-6 * grad[1]\n\t\t\t\tc -= 1e-3 * grad[2]\n\n\t\t\treturn a, b, c\n\n\t\tdef normalize(a, b, c, pixels):\n\t\t\t\"\"\"\n\t\t\tretourne la liste des points entre -1 et 1\n\t\t\t\"\"\"\n\t\t\tdifference = [p - a*(i-64)**2 - b*(i-64) - c for i,p in enumerate(pixels)]\n\t\t\tmaximum = max(difference)\n\t\t\tminimum = -min(difference)\n\t\t\tborne = max(maximum, minimum)\n\t\t\tif borne:\n\t\t\t\timage_redressee = [d/borne for d in difference]\n\t\t\telse:\n\t\t\t\timage_redressee = [0 for d in difference]\n\t\t\treturn image_redressee\n\n\t\tdef get_seuil(image_redressee):\n\t\t\t\"\"\"\n\t\t\tretourne un scalaire entre -1 et 1\n\t\t\tce scalaire est tel que tous ce qui est en dessous\n\t\t\test noir et tous ce qui est au dessu est blanc\n\t\t\t\"\"\"\n\t\t\tpourcentage = 0.1 # pourcentage de noir dans l'image\n\t\t\tbordure = 0.05 # pour le calcul du seuil 'median', 0 pour prendre le extremitee, 0.5 pour prendre le centre\n\t\t\tpoid_pourcentage_seuil = 0.4 # influence du pourcentage 'seuil_pourcentage'. 0: aucune influence, 1: seul lui compte\n\t\t\tpixels_triees = sorted(image_redressee)\n\t\t\tseuil_pourcentage = pixels_triees[int(pourcentage*len(image_redressee))] # c'est le seuil tel que pourceantage des points soient en dessous de ce seuil\n\t\t\tseuil_median = (pixels_triees[int(len(image_redressee)*bordure)]+pixels_triees[-int(len(image_redressee)*bordure)])/2\n\n\t\t\treturn seuil_median*(1-poid_pourcentage_seuil) + seuil_pourcentage*poid_pourcentage_seuil\n\n\t\tdef get_probas_couleur(image_redressee, seuil):\n\t\t\t\"\"\"\n\t\t\tretourne pour chaque pixel la probabilite qu'il soit blanc\n\t\t\t0: noir certain\n\t\t\t0.5: couci-coussa\n\t\t\t1: blanc certain\n\t\t\t\"\"\"\n\t\t\tordonne = sorted(((rang_initial, ecart) for rang_initial, ecart in enumerate(image_redressee)), key=(lambda couple: couple[1]))# liste de tous les points classes par ordre croissant\n\t\t\trang_seuil = sorted([(faux_rang, abs(ecart-seuil)) for faux_rang, (rang_initial, ecart) in enumerate(ordonne)], key=(lambda couple: couple[1]))[0][0]# on recupere le rang de la liste ordonne ou se trouve le suile\n\t\t\trang_initial_couleur = [(rang_initial,\n\t\t\t\t\t\t\t\t\trang*0.5/rang_seuil\n\t\t\t\t\t\t\t\t\tif rang <= rang_seuil else\n\t\t\t\t\t\t\t\t\t0.5 + (rang-rang_seuil)*0.5/(len(ordonne)-1-rang_seuil)\n\t\t\t\t\t\t\t\t\t) for rang, (rang_initial, ecart) in enumerate(ordonne)]\n\t\t\tprobas_couleur = [proba for rang_initial, proba in sorted(rang_initial_couleur, key=lambda couple: couple[0])]\n\t\t\treturn probas_couleur\n\n\t\tdef get_masse_zonnes(probas_couleur):\n\t\t\t\"\"\"\n\t\t\tretourne une liste de la meme longueur que 'probas_couleur'\n\t\t\trepere chaque zonnes (noir ou blanche)\n\t\t\tdans chaque zonne, l'aire algebrique entre 0,5 et probas_couleur\n\t\t\test presente de partout\n\t\t\tla valeur renvoyee est normee entre 0 et 1\n\t\t\t\"\"\"\n\t\t\tALPHA = 2.0 # entre 0 et oo, oo => masse_relative = sign(masse_absolu)\n\n\t\t\tsomme_cumul = [0]\n\t\t\tfor proba_couleur in probas_couleur:\n\t\t\t\tif proba_couleur >= 0.5 and somme_cumul[-1] >= 0 \\\n\t\t\t\tor proba_couleur < 0.5 and somme_cumul[-1] < 0:\n\t\t\t\t\tsomme_cumul.append(somme_cumul[-1] + proba_couleur - 0.5)\n\t\t\t\telse:\n\t\t\t\t\tsomme_cumul.append(proba_couleur - 0.5)\n\t\t\tdel somme_cumul[0]\n\n\t\t\tmasse_absolu = [somme_cumul[-1]]\n\t\t\tfor i in range(len(somme_cumul)-2, -1, -1):\n\t\t\t\tif somme_cumul[i]*masse_absolu[0] > 0:\t\t\t\t\t\t\t# si c'est toujour du meme signe\n\t\t\t\t\tmasse_absolu.insert(0, masse_absolu[0])\t\t\t\t\t\t# on met a plat\n\t\t\t\telse:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# si le signe change\n\t\t\t\t\tmasse_absolu.insert(0, somme_cumul[i])\t\t\t\t\t\t# on repart a zero\n\n\t\t\tmasse_relative = list(map(lambda p: 0.5 + math.atan(ALPHA*p)/math.pi, masse_absolu))\n\n\t\t\treturn masse_relative\n\n\t\t# calculs\n\t\tresultat = {}\n\t\tresultat[\"luminosite_moyenne\"] = sum(pixels)/128\t\t\t\t\t\t# cette grandeur permet d'adapter le temps avant de prendre l'image suivante\n\t\tresultat[\"a\"], resultat[\"b\"], resultat[\"c\"] = find_polynome(pixels)\t\t# le a, b, c initial\n\t\tresultat[\"image_redressee\"] = normalize(resultat[\"a\"], resultat[\"b\"], resultat[\"c\"], pixels)# l'image comprise entre 0 et 1\n\t\tresultat[\"seuil\"] = get_seuil(resultat[\"image_redressee\"])\t\t\t\t# le seuil qui separe blanc/noir\n\t\tresultat[\"probas_couleur\"] = get_probas_couleur(resultat[\"image_redressee\"], resultat[\"seuil\"])# probabilite qui donne la couleur du sol\n\t\tresultat[\"masse_zonnes\"] = get_masse_zonnes(resultat[\"probas_couleur\"])\t# l'aire de chaque 'bloc'\n\n\t\t# affichage\n\t\tself.ax1.cla()\n\t\tself.ax1.axis((-64, 64, 0, 255))\n\t\tself.ax1.set_title(\"Image Brute\")\n\t\tself.ax1.plot(list(range(-64, 64)), pixels, label=\"camera brute\")\n\t\tself.ax1.plot(list(range(-64, 64)), [resultat[\"a\"]*x**2 + resultat[\"b\"]*x + resultat[\"c\"] for x in range(-64, 64)], label=\"polynome\")\n\n\t\tself.ax2.cla()\n\t\tself.ax2.axis((-64, 64, -1.1, 1.1))\n\t\tself.ax2.set_title(\"Image Redressee\")\n\t\tself.ax2.plot(list(range(-64, 64)), resultat[\"image_redressee\"], label=\"camera formatte\")\n\t\tself.ax2.plot([-64, 64], [resultat[\"seuil\"], resultat[\"seuil\"]], label=\"seuil\")\n\n\t\tself.ax3.cla()\n\t\tself.ax3.axis((-64, 64, -.1, 1.1))\n\t\tself.ax3.set_title(\"Couleur Finale\")\n\t\tself.ax3.plot([-64, 64], [0.5, 0.5])\n\t\tself.ax3.plot(list(range(-64, 64)), resultat[\"probas_couleur\"], label=\"hors de tout contexte\")\n\t\tself.ax3.plot(list(range(-64, 64)), resultat[\"masse_zonnes\"], label=\"masse hors contexte\")\n\n\t\tself.ax1.legend()\n\t\tself.ax2.legend()\n\t\tself.ax3.legend()\n\t\tplt.draw()\n\t\tplt.pause(0.01)\n\n\t\treturn resultat",
"def replace_good_pixels_main(paths, anneal_date, superdark_list, ctecorr, mode):\n\n print('\\tReplacing pixels in superdarks with values from masterdark')\n\n # Determine which masterdark to use\n masterdark = get_masterdark(anneal_date, paths, ctecorr, mode)\n\n if mode == 'prod':\n # Copy masterdark to the local masterdark directory\n masterdark_dst = os.path.join(paths['masterdark_create_dir'], os.path.basename(masterdark))\n shutil.copyfile(masterdark, masterdark_dst)\n\n process_anneal(superdark_list, masterdark, mode) #LP added mode",
"def remove_seam(image, seam):\n\n # Add extra dimension if 2D input\n if len(image.shape) == 2:\n image = np.expand_dims(image, axis=2)\n\n out = None\n H, W, C = image.shape\n ### YOUR CODE HERE\n # 根据seam和原有图像尺寸构造新的图像像素区域\n # 方式一:没理解\n # out = image[np.arange(W) != seam[:, None]].reshape(H, W - 1, C)\n\n # 方式二:每行删除一个\n out = np.zeros((H,W-1,C))\n for i in range(H):\n out[i] = np.delete(image[i], seam[i], axis=0)\n\n ### END YOUR CODE\n out = np.squeeze(out) # remove last dimension if C == 1\n\n return out",
"def remove_seam(img, seam):\n h = img.shape[0]\n w = img.shape[1]\n\n newImage = [[[] for _ in xrange(w - 1)] for _ in xrange(h)]\n for i in range(0, h):\n currentJ = 0\n for j in range(0, w):\n if (j != seam[i]):\n newImage[i][currentJ][:] = img[i][j][:]\n currentJ = currentJ + 1\n #print(\"The image without the seam is: \")\n #print(newImage)\n return newImage",
"def wipealldata(self):\n\n\t\t\"\"\" Goes through all the pixels and makes the LSB 0. It runs through 2 for loops, and just does the changes accordingly using the same methods for encrypting and decrypting\"\"\"\n\t\timgarr = self.img.size\n\t\tgrysc = 0\n\t\tif(type(self.pic[0,0]) is int):\n\t\t\tgrysc = 1\n\t\tfor x in range(0, imgarr[0]):\n\t\t\tfor y in range(0,imgarr[1]):\n\t\t\t\tif(grysc == 1):\n\t\t\t\t\tnewrgb = []\n\t\t\t\t\tdig = []\n\t\t\t\t\tdig.append(self.pic[x,y])\n\t\t\t\t\tnewrgb.append(self.pic[x,y])\n\t\t\t\telse:\n\t\t\t\t\tnewrgb = list(self.pic[x, y])\n\t\t\t\t\tdig = self.pic[x, y]\n\t\t\t\tfor z in range(0, len(newrgb)):\n\t\t\t\t\tif((dig[z] % 2) == 1):\n\t\t\t\t\t\tnewrgb[z] -= 1\n\t\t\t\tif(grysc == 1):\n\t\t\t\t\tself.pic[x,y] = newrgb[0]\n\t\t\t\t\tdel dig\n\t\t\t\t\tdel newrgb\n\t\t\t\telse:\n\t\t\t\t\tself.pic[x,y] = tuple(newrgb)\n\t\t\t\t\tdel dig\n\t\t\t\t\tdel newrgb\n\t\tself.img.save(self.imgname)",
"def load_8_color(MST_data, frames=range(5,12), remove_edges=True, data=False, start_n = 13, end_n = 46, ignore=[22]):\n # Only process the specified pixels\n include_pix = range(start_n, end_n+1)\n for pix in ignore:\n if pix >= start_n and pix <= end_n:\n index = include_pix.index(pix)\n del include_pix[index]\n \n num_pixels = len(include_pix)\n \n # Data containers\n counts_set = [[] for i in range(len(frames))]\n thresh_set = [[] for i in range(len(frames))]\n k_data = [[] for i in range(len(frames))]\n sigma_data = [[] for i in range(len(frames))]\n\n edge_pixels = get_ignore_x(remove_edges=True)\n\n for frame in range(len(frames)):\n counts_frame = [[] for i in range(num_pixels)]\n thresh_frame = [[] for i in range(num_pixels)]\n kd_frame = np.zeros(num_pixels)\n ks_frame = np.zeros(num_pixels)\n\n for k_n, index in enumerate(include_pix):\n thresholds = np.copy(MST_data['ME']['thresholds'])\n counts = np.array([MST_data['ME']['profiles'][frame][Ec][index] for Ec in thresholds])\n\n # Remove the edge points, if desired\n if remove_edges:\n x_index = np.array([MST_data['ME']['x_index'][Ec][index] for Ec in thresholds])\n to_remove = []\n\n for Ec_index, x_n in enumerate(x_index):\n if x_n in edge_pixels:\n to_remove.append(Ec_index)\n\n counts = np.delete(counts, to_remove)\n thresholds = np.delete(thresholds, to_remove)\n\n # Compute k_hat and k_sigma\n kd, ks = compute_k_hat(counts, thresholds)\n kd_frame[k_n] = kd\n ks_frame[k_n] = ks\n\n # Store counts for later inspection\n counts_frame[k_n] = counts\n thresh_frame[k_n] = thresholds\n\n # Store results in the appropriate frame\n k_data[frame] = kd_frame\n sigma_data[frame] = ks_frame\n counts_set[frame] = counts_frame\n thresh_set[frame] = thresh_frame\n \n p_set = np.array([np.average([MST_data['ME']['impact_p'][Ec][index] for Ec in MST_data['ME']['thresholds']]) for index in include_pix])\n \n k_hat_data = {'k_hat':k_data, 'sigma':sigma_data, 'avg_p':p_set, 'time':MST_data['time'][frames],\n 'counts':counts_set, 'Ec':thresh_set}\n\n if data:\n return k_hat_data, MST_data\n else:\n return k_hat_data",
"def remove_roi(self, roi):\n\n if roi in self.rois:\n idx = self.rois.index(roi)\n for sample in self.samples:\n sample['TimeSeries'] = np.delete(sample['TimeSeries'], obj=idx, axis=0)\n # self.recompute()\n self.rois.remove(roi)\n else:\n raise LookupError",
"def _analyze_sparse_noise_frames(sn_grp):\n\n if sn_grp['stim_name'].value != 'SparseNoise':\n raise NameError('The input stimulus should be \"SparseNoise\".')\n\n frames = sn_grp['data'].value\n frames = [tuple(x) for x in frames]\n dtype = [('isDisplay', int), ('azimuth', float), ('altitude', float), ('sign', int), ('isOnset', int)]\n frames = np.array(frames, dtype=dtype)\n\n all_squares = []\n for i in range(len(frames)):\n if frames[i]['isDisplay'] == 1 and \\\n (i == 0 or (frames[i - 1]['isOnset'] == -1 and frames[i]['isOnset'] == 1)):\n all_squares.append(np.array((i, frames[i]['azimuth'], frames[i]['altitude'], frames[i]['sign']),\n dtype=np.float32))\n\n all_squares = np.array(all_squares)\n\n pooled_squares = {}\n unique_squares = list(set([tuple(x[1:]) for x in all_squares]))\n for i, unique_square in enumerate(unique_squares):\n curr_square_n = 'square_' + ft.int2str(i, 5)\n curr_azi = unique_square[0]\n curr_alt = unique_square[1]\n curr_sign = unique_square[2]\n curr_onset_ind = []\n for j, give_square in enumerate(all_squares):\n if np.array_equal(give_square[1:], unique_square):\n curr_onset_ind.append(j)\n pooled_squares.update({curr_square_n: {'azi': curr_azi,\n 'alt': curr_alt,\n 'sign': curr_sign,\n 'onset_ind': curr_onset_ind}})\n all_squares = np.array(all_squares)\n data_format = ['display frame indices for the onset of each square', 'azimuth of each square',\n 'altitude of each square', 'sign of each square']\n description = 'TimeSeries of sparse noise square onsets. Stimulus generated by ' \\\n 'corticalmapping.VisualStim.SparseNoise class.'\n return all_squares, data_format, description, pooled_squares",
"def clear_pixel_data(self):\n for field in PIXEL_FIELDS:\n self.delete_field(field)",
"def crop(self, frame):\r\n # Extract out the object and place into output image\r\n out = np.zeros_like(frame)\r\n out[self.__table_bounds_mask == 255] = frame[self.__table_bounds_mask == 255]\r\n (x, y, _) = np.where(self.__table_bounds_mask == 255)\r\n (topx, topy) = (np.min(x), np.min(y))\r\n (bottomx, bottomy) = (np.max(x), np.max(y))\r\n frame = out[topx:bottomx + 1, topy:bottomy + 1]\r\n return frame"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Save the learned policy to disk. Since we only learned the last step therefore we save the value of the last step along with the index of the homing policy for previous step.
|
def _save_policy(learned_policy, policy_folder_name, horizon, policy_index):
if not os.path.exists(policy_folder_name):
os.makedirs(policy_folder_name)
learned_policy[horizon].save(folder_name=policy_folder_name, model_name="step_%d" % horizon)
with open(policy_folder_name + "prev_policy_index", 'wb') as fobj:
pickle.dump(policy_index, fobj)
|
[
"def save_model(self):\n saver = PolicySaver(self.agent.policy)\n saver.save(self.model_dir)",
"def save_policy(self, save_dir) -> None:\n pickle.dump(self, open(f\"{save_dir}policy.p\", \"wb\"))",
"def _save_snapshot(self) -> None:\n for brain_name in self.current_policy_snapshot:\n current_snapshot_for_brain_name = self.current_policy_snapshot[brain_name]\n\n try:\n self.policy_snapshots[self.snapshot_counter][\n brain_name\n ] = current_snapshot_for_brain_name\n except IndexError:\n self.policy_snapshots.append(\n {brain_name: current_snapshot_for_brain_name}\n )\n self.policy_elos[self.snapshot_counter] = self.current_elo\n self.snapshot_counter = (self.snapshot_counter + 1) % self.window",
"def save_model(self):\n torch.save(\n {\n 'epoch': self.epoch,\n 'model_state_dict': self.model.state_dict(),\n 'optimizer_state_dict': self.opt.state_dict(),\n 'acc': self.val_stats[\"acc\"],\n }, os.path.join(self.params.model_dir,\"snapshot.ep{}.pth\".format(self.epoch)))\n if self.val_stats[\"best_acc\"] <= self.val_stats[\"acc\"]:\n self.val_stats[\"best_acc\"] = self.val_stats[\"acc\"]\n self.val_stats[\"best_epoch\"] = self.epoch\n print(\"Saving model after epoch {}\".format(self.epoch))\n torch.save(\n {\n 'epoch': self.epoch,\n 'model_state_dict': self.model.state_dict(),\n 'acc': self.val_stats[\"acc\"],\n }, os.path.join(self.params.model_dir,\"model.acc.best\"))\n #else:\n # checkpoint = torch.load(os.path.join(self.params.model_dir,\"model.acc.best\"))\n # self.model.load_state_dict(checkpoint[\"model_state_dict\"])",
"def save_checkpoint(self, basename):\n if self._output_dir is None:\n _log('Did not save checkpoint as output_dir is None')\n return\n\n inputs.save_data_counters(self._output_dir)\n if not self.is_chief:\n _log('Did not save checkpoint as we are not chief.')\n return\n\n dir_and_basename = os.path.join(self._output_dir, basename)\n pkl_file = dir_and_basename + '.pkl.gz'\n\n _log('Saving checkpoint to %s' % pkl_file, stdout=False)\n weights = self._model.weights\n if base.N_WEIGHTS_SHARDS > 1:\n weights = self._trainer_per_task[0].accelerated_model_with_loss.weights\n weights = tl.unshard(weights)\n state = self._model.state\n compresslevel = 0 if self._use_memory_efficient_trainer else 2\n # Serialize optimizer slots.\n for i, trainer in enumerate(self._trainer_per_task):\n flat_slots = _flatten_and_remove_empty(trainer.slots)\n tl.np_to_file(self._to_bits(flat_slots),\n f'{dir_and_basename}.opt_slots{i}.npy.gz',\n compresslevel=compresslevel)\n # We only need the input signature for the body, not for the loss layers.\n # That part is the same across tasks - take it from the first one.\n input_signature = self._batch_signature[:self._model.n_in]\n flat_weights, flat_state = tl.flatten_weights_and_state(weights, state)\n _, flat_eval_state = tl.flatten_weights_and_state(\n weights, self._eval_model.state)\n tl.np_to_file(self._to_bits(flat_weights),\n f'{dir_and_basename}.weights.npy.gz',\n compresslevel=compresslevel)\n d = {\n 'step': self.step,\n 'flat_weights': compresslevel, # for compatibility with older format\n 'flat_state': flat_state,\n 'flat_eval_state': flat_eval_state,\n 'history': self._history.to_dict(),\n 'slots_per_task': compresslevel, # for compatibility with older format\n 'input_signature': input_signature,\n 'version_timestamp': 'Mar-10-2021' # To update in the future if needed.\n }\n pickle_to_file(d, pkl_file, gzip=True)\n _log('Checkpoint saved in %s' % pkl_file, stdout=False)",
"def save_policy(self, policy_path: types.AnyPath) -> None:\n self.bc_trainer.save_policy(policy_path)",
"def save(self, save_path='training_savings'):\n if not os.path.exists(save_path):\n os.makedirs(save_path, exist_ok=True)\n\n # save weights of Q networks and the optimizer\n manager = tf.train.CheckpointManager(\n checkpoint=self.checkpoint, directory=save_path, max_to_keep=3\n )\n manager.save()\n\n # save hyperparameters\n hyperparams_path = os.path.join(save_path, \"hyperparams.npz\")\n np.savez_compressed(\n hyperparams_path,\n reward_gamma=self.reward_gamma,\n epsilon=self.epsilon(self.num_trained_steps),\n train_steps_per_q_sync=self.train_steps_per_q_sync\n )\n\n # save the loss values\n loss_records_path = os.path.join(save_path, \"loss_records.npz\")\n if os.path.exists(loss_records_path):\n loss_npzfile = np.load(loss_records_path)\n loss_records = dict(loss_npzfile)\n else:\n loss_records = {}\n loss_records[\n f\"loss_{time.strftime('%Y%m%d_%H%M%S')}\"\n ] = np.array(self.loss_history)\n\n np.savez_compressed(\n loss_records_path,\n **loss_records,\n )\n\n # reset the loss history since the values have been stored\n self.loss_history: typing.List[typing.Tuple[int, float]] = []",
"def __save_policies__(self, policies):\n if self.pacman_class == agents.BehaviorLearningPacmanAgent:\n policies[self.pacman.agent_id] = self.__get_policy__(self.pacman)\n\n if self.ghost_class == agents.BehaviorLearningGhostAgent:\n for ghost in self.ghosts:\n policies[ghost.agent_id] = self.__get_policy__(ghost)\n\n self.__write_to_file__(self.policy_file, policies)",
"def save_rollout(self, episode):\n\n complete_episode = self.compute_total_rewards(episode, self.gamma)\n # print(complete_episode)\n self.rollout_memory.append(complete_episode)\n self.flush_recorder_memory()",
"def save_trainer(self) -> Tuple[pathlib.Path, pathlib.Path]:\n self.scratch_dir.mkdir(parents=True, exist_ok=True)\n\n # save full trainer checkpoints\n checkpoint_paths = [\n self.scratch_dir / f\"checkpoint-{self.round_num:03d}.pt\",\n self.scratch_dir / \"checkpoint-latest.pt\",\n ]\n for checkpoint_path in checkpoint_paths:\n th.save(self, checkpoint_path)\n\n # save policies separately for convenience\n policy_paths = [\n self.scratch_dir / f\"policy-{self.round_num:03d}.pt\",\n self.scratch_dir / \"policy-latest.pt\",\n ]\n for policy_path in policy_paths:\n self.save_policy(policy_path)\n\n return checkpoint_paths[0], policy_paths[0]",
"def save_checkpoint(checkpoint_path, current_epoch, net, optimizer, loss):\r\n save_dict = {'epoch': current_epoch+1, # after training one epoch, the start_epoch should be epoch+1\r\n 'optimizer_state_dict': optimizer.state_dict(),\r\n 'loss': loss,\r\n }\r\n try: # with nn.DataParallel() the net is added as a submodule of DataParallel\r\n save_dict['model_state_dict'] = net.module.state_dict()\r\n except:\r\n save_dict['model_state_dict'] = net.state_dict()\r\n torch.save(save_dict, checkpoint_path)",
"def save_best_path(self, pth):\n best_traj = self.get_best_path()\n bp = np.array(best_traj)\n np.save(pth, bp)",
"def write_policy_file():\n global maze\n\n for r in range(rows):\n for c in range(cols):\n max_reward = max(q_table[r, c])\n\n if max_reward != 0:\n action = list(q_table[r, c]).index(max_reward)\n action = actions[action]\n\n maze[r, c] = action\n\n with open(policy_file, \"w\") as fout:\n for r in maze.tolist():\n fout.write(\"\".join(r) + \"\\n\")",
"def save_state(self, dir_path):\n for learner_id, learner in enumerate(self.global_learners_ensemble):\n save_path = os.path.join(dir_path, f\"chkpts_{learner_id}.pt\")\n torch.save(learner.model.state_dict(), save_path)\n\n learners_weights = np.zeros((self.n_clients, self.n_learners))\n test_learners_weights = np.zeros((self.n_test_clients, self.n_learners))\n\n for mode, weights, clients in [\n ['train', learners_weights, self.clients],\n ['test', test_learners_weights, self.test_clients]\n ]:\n save_path = os.path.join(dir_path, f\"{mode}_client_weights.npy\")\n\n for client_id, client in enumerate(clients):\n weights[client_id] = client.learners_ensemble.learners_weights\n\n np.save(save_path, weights)",
"def autosave(self):\n\n checkpoint = {\n 'epoch': self.epoch,\n 'state_dict': self.model.state_dict(),\n 'optimizer': self.optimizer.state_dict(),\n 'userdata': self.checkpoint_userdata,\n 'elapsed': self.elapsed,\n 'adaptative_optimizer': self.adaptative_optimizer.state_dict(),\n 'best_error': self.best_error\n }\n torch.save(checkpoint, self.checkpoint_name + \".autosave\")",
"def __save(self, path, optimizer, scheduler, iter_, current_epoch):\n custom_dict = {'state_dict': self.model.module.state_dict(), 'optimizer': optimizer.state_dict(),\n 'scheduler': scheduler.state_dict(), 'iter': iter_, 'current_epoch': current_epoch}\n torch.save(custom_dict, path)",
"def save_checkpoint(state, is_best, filename=os.path.join(os.environ.get('USER_PATH'),'/data/checkpoints/checkpoint.pt')):\n\t if is_best:\n\t\t print (\"=> Saving a new best model\")\n\t\t print(f'SAVING TO: {filename}')\n\t\t torch.save(state, filename) # save checkpoint\n\t else:\n\t\t print (\"=> Loss did not improve\")",
"def save_model(self, path):\r\n torch.save(self.model.state_dict(), path)",
"def save_current_state(model, optimizer, epoch, best_validation_loss, config):\n with open(get_model_name_config(config) + \"TEMP_epoch_counter\", \"w+\", encoding='utf-8') as f:\n print(\"saving epoch\", epoch)\n f.write(str(epoch))\n torch.save({\"model\":model.state_dict(),\n \"optimizer\":optimizer.state_dict(),\n \"epoch\":epoch,\n \"best_validation_loss\":best_validation_loss}, get_model_name_config(config)+ f\"TEMP_{epoch % 2}\")",
"def save_checkpoint(state, is_best, filename=\"/output/checkpoint.pkl\"):\n if is_best:\n print(\"=> Saving a new best model.\")\n torch.save(state, filename) # save checkpoint\n else:\n print(\"=> Validation loss did not improve.\")"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Read the policy from the disk
|
def read_policy(self, policy_folder_name, horizon, previous_step_homing_policy, delete=False):
homing_policy = dict()
with open(policy_folder_name + "prev_policy_index", 'rb') as fobj:
policy_index = pickle.load(fobj)
for j in range(1, horizon):
homing_policy[j] = previous_step_homing_policy[policy_index][j]
policy = StationaryDeterministicPolicy(self.config, self.constants)
policy.load(folder_name=policy_folder_name, model_name="step_%d" % horizon)
homing_policy[horizon] = policy
if delete:
# Delete the file after reading for saving disk space
os.remove(policy_folder_name + "step_%d" % horizon)
return homing_policy
|
[
"def read_policy_data(policy_id):\n if not os.path.exists(\"data/policy{}.txt\".format(policy_id)):\n pull_policy_data.write_data(policy_id)\n with open(\"data/policy{}.txt\".format(policy_id), \"rb\") as f:\n raw_policy_data = f.read()\n return json.loads(raw_policy_data.decode(\"utf-8\"))",
"def __load_policies_from_file__(self, filename):\n policies = {}\n if filename and os.path.isfile(filename):\n log('Loading policies from {}.'.format(filename))\n with open(filename) as f:\n policies = pickle.loads(f.read())\n return policies",
"def test_read_policy_from_file(self):\n policy_file = tempfile.NamedTemporaryFile(\n dir=self.temp_dir,\n delete=False\n )\n with open(policy_file.name, 'w') as f:\n f.write(\n '{\"test\": {'\n '\"groups\": {\"group_A\": {\"SPLIT_KEY\": {\"GET\": \"ALLOW_ALL\"}}}, '\n '\"preset\": {\"SPLIT_KEY\": {\"GET\": \"ALLOW_ALL\"}}}'\n '}'\n )\n\n policies = policy.read_policy_from_file(policy_file.name)\n\n self.assertEqual(1, len(policies))\n self.assertIn('test', policies.keys())\n\n expected = {\n 'groups': {\n 'group_A': {\n enums.ObjectType.SPLIT_KEY: {\n enums.Operation.GET: enums.Policy.ALLOW_ALL\n }\n }\n },\n 'preset': {\n enums.ObjectType.SPLIT_KEY: {\n enums.Operation.GET: enums.Policy.ALLOW_ALL\n }\n }\n }\n\n self.assertEqual(expected, policies.get('test'))",
"def get_policy(self, policy):\r\n return self.manager.get_policy(self, policy)",
"def test_read_policy_from_file_legacy(self):\n policy_file = tempfile.NamedTemporaryFile(\n dir=self.temp_dir,\n delete=False\n )\n with open(policy_file.name, 'w') as f:\n f.write(\n '{\"test\": {\"CERTIFICATE\": {\"LOCATE\": \"ALLOW_ALL\"}}}'\n )\n\n policies = policy.read_policy_from_file(policy_file.name)\n\n self.assertEqual(1, len(policies))\n self.assertIn('test', policies.keys())\n\n expected = {\n 'preset': {\n enums.ObjectType.CERTIFICATE: {\n enums.Operation.LOCATE: enums.Policy.ALLOW_ALL\n }\n }\n }\n\n self.assertEqual(expected, policies.get('test'))",
"def __load_policy__(self, agent, policy):\n msg = comm.PolicyMessage(agent_id=agent.agent_id, policy=policy)\n return agent.communicate(msg)",
"def test_read_policy_from_file_empty_policy(self):\n policy_file = tempfile.NamedTemporaryFile(\n dir=self.temp_dir,\n delete=False\n )\n with open(policy_file.name, 'w') as f:\n f.write(\n '{\"test\": {}}'\n )\n\n policies = policy.read_policy_from_file(policy_file.name)\n\n self.assertEqual(0, len(policies))",
"def test_read_policy_from_file_default_only(self):\n policy_file = tempfile.NamedTemporaryFile(\n dir=self.temp_dir,\n delete=False\n )\n with open(policy_file.name, 'w') as f:\n f.write(\n '{\"test\": '\n '{\"preset\": {\"SPLIT_KEY\": {\"GET\": \"ALLOW_ALL\"}}}}'\n )\n\n policies = policy.read_policy_from_file(policy_file.name)\n\n self.assertEqual(1, len(policies))\n self.assertIn('test', policies.keys())\n\n expected = {\n 'preset': {\n enums.ObjectType.SPLIT_KEY: {\n enums.Operation.GET: enums.Policy.ALLOW_ALL\n }\n }\n }\n\n self.assertEqual(expected, policies.get('test'))",
"def policy(self) -> pulumi.Output['outputs.BlobInventoryPolicySchemaResponse']:\n return pulumi.get(self, \"policy\")",
"def test_read_policy_from_file_groups_only(self):\n policy_file = tempfile.NamedTemporaryFile(\n dir=self.temp_dir,\n delete=False\n )\n with open(policy_file.name, 'w') as f:\n f.write(\n '{\"test\": '\n '{\"groups\": {\"group_A\": {\"SPLIT_KEY\": {\"GET\": \"ALLOW_ALL\"}}}}}'\n )\n\n policies = policy.read_policy_from_file(policy_file.name)\n\n self.assertEqual(1, len(policies))\n self.assertIn('test', policies.keys())\n\n expected = {\n 'groups': {\n 'group_A': {\n enums.ObjectType.SPLIT_KEY: {\n enums.Operation.GET: enums.Policy.ALLOW_ALL\n }\n }\n }\n }\n\n self.assertEqual(expected, policies.get('test'))",
"def read_resource(self, namespace: typing.Optional[str] = None):\n names = [\n \"read_namespaced_network_policy\",\n \"read_network_policy\",\n ]\n return _kube_api.execute(\n action=\"read\",\n resource=self,\n names=names,\n namespace=namespace,\n api_client=None,\n api_args={\"name\": self.metadata.name},\n )",
"def parse_policies_part1(filepath):\n with open(filepath, \"r\") as f:\n file_lines = map(str.strip, f.readlines())\n\n # Split policy/password, then parse policy\n fully_parsed_policies = map(parse_policy_part1, file_lines)\n return fully_parsed_policies",
"def __get_policy__(self, agent):\n msg = comm.RequestPolicyMessage(agent.agent_id)\n reply_msg = agent.communicate(msg)\n return reply_msg.policy",
"def simple_policy():\n Oso.load_file(Path(__file__).parent / \"simple.polar\")",
"def test_read_only_policy() -> None:\n # Make sure it's valid\n POLICY_SCHEMA(system_policies.READ_ONLY_POLICY)\n\n perms = PolicyPermissions(system_policies.READ_ONLY_POLICY, None)\n assert perms.check_entity(\"light.kitchen\", \"read\")\n assert not perms.check_entity(\"light.kitchen\", \"control\")\n assert not perms.check_entity(\"light.kitchen\", \"edit\")",
"def get_policy(self, policy: str, *, vhost: str = None):\n vhost = vhost if vhost is not None else self.vhost\n endpoint = self.build_url(\"/policies/{vhost}/{policy}\", vhost=vhost, policy=policy)\n return self.request('get', endpoint)",
"def fetch_policy(self, device, **kwargs):\n all_entry_list = self._common_get_processing(device=device, cmd_keyword=\"policy\", kwargs=kwargs)\n device.log(message=\"{} return value:\\n{}\".format(self.tool.get_current_function_name(), self.tool.pprint(all_entry_list)))\n return all_entry_list",
"def test_read_policy_from_file_empty(self):\n policy_file = tempfile.NamedTemporaryFile(\n dir=self.temp_dir,\n delete=False\n )\n with open(policy_file.name, 'w') as f:\n f.write('')\n\n args = (policy_file.name, )\n regex = \"Loading the policy file '{}' generated a JSON error:\".format(\n policy_file.name\n )\n self.assertRaisesRegex(\n ValueError,\n regex,\n policy.read_policy_from_file,\n *args\n )",
"def get_bucket_policy(self, bucket_name):\n check_bucket_name(bucket_name)\n\n response = self._url_open(\"GET\",\n bucket_name=bucket_name,\n query={\"policy\": \"\"})\n return response.data"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
That method handle post_save signal from Model3d and check if a reward must be granted to the owner of the Model3d.
|
def check_if_user_earned_collector_reward(sender, instance, created, **kwargs):
logger.debug("check_if_user_earned_collector_reward raised")
if created:
user = instance.user
sketchfab_services.check_collector_reward(user)
|
[
"def check_if_user_earned_star_reward(sender, instance, **kwargs):\n\n logger.debug(\"check_if_user_earned_star_reward raised\")\n\n hits = instance.hits\n content_object = instance.content_object\n if type(content_object) is Model3d:\n sketchfab_services.check_star_reward(content_object, hits)",
"def is_reward(self):\n return self._reward",
"def observe(self, pre_observation, action, reward, post_observation, done):",
"def compute_reward(self, obs, action):\n pass",
"def __handleJellybeanRewardDone(self):\n self.ignore(self.showRewardDoneEvent)\n self.handleRewardDone()",
"def hasExperienceReward(self):\n return self.handle.rewardExp",
"def update_reward(self, reward, force=False):\n if force or reward >= 0:\n self._reward = reward",
"def perform_update(self, action, reward):\n\t\tpass",
"def _reward(self, player, state, actions):\n raise(NotImplementedError)",
"def _should_save(self) -> bool:\n return random.randint(0, self.MAX_RAND_INT) == 0",
"def update(self, instance, validated_data):\n print \"went into the reward update method\"\n instance.name = validated_data.get('name', instance.name)\n instance.required_points = validated_data.get('required_points', instance.required_points)\n instance.save()\n return instance",
"async def _before_save(self) -> None:",
"def has_access(self, model):\n return True",
"def observe(self, observation):\n if observation.get('reward') is not None:\n reward = observation['reward']\n for log_prob in self.log_probs:\n loss = - log_prob * reward\n self.backward(loss)\n \n self.log_probs = []\n\n for parameter in self.model.parameters(): # pylint: disable=access-member-before-definition\n if parameter.grad is not None:\n parameter.grad.data.clamp_(min=-5, max=5)\n \n if observation.get('model') is not None:\n # Deepcopied and frozen clone of the model\n self.model = observation['model']\n\n return super(RLTorchGeneratorAgent, self).observe(\n observation)",
"def userCanAffordItemObj(self, user : basedUser.BasedUser, item : gameItem.GameItem) -> bool:\n return user.credits >= item.getValue()",
"def get_reward(self):\n\n # Premise is sound, as we want to reward highest when sim.pose x,y,z is \n # essentially equal target_pos x,y,z (making the product of discount rate\n # and pose diff essentially 0 -- therefore, reward would be close to 1).\n #reward = 1.-.3*(abs(self.sim.pose[:3] - self.target_pos).sum())\n \n # rrm - discounting the error\n #reward = 1.-.3*(abs(self.sim.pose[:3] - self.target_pos).sum())\n reward = 2.-.2*(abs(self.sim.pose[:3] - self.target_pos).sum())\n \n # By experience in running, this reward gets negative quickly. We need to\n # scale it, so it can hopefully learn more efficiently.\n # Let's see what happens when we just cap the negative reward at -1\n \"\"\"\n if reward > 1.0:\n print(\"Reward is > 1: {0}\".format(reward))\n reward = 1.0\n elif reward < -1.0:\n print(\"Reward is < 1: {0}\".format(reward))\n reward = -1.0\n \"\"\"\n\n # Works pretty well... Trying something different below\n \"\"\"\n if reward > 0 and reward < 0.5:\n reward = reward * 2\n elif reward > 0.5:\n reward = reward * 4\n elif reward < -1.0:\n #print(\"Reward is < 1: {0}\".format(reward))\n reward = -1.0\n \"\"\"\n\n # Works well, but what if we provide extra reward (or penalize more) based on z coordinate (for hovering)\n \"\"\"\n absoluteZDiff = abs(self.sim.pose[2] - self.target_pos[2])\n if reward > 0 and reward < 0.5 and absoluteZDiff < 1:\n reward = reward * 3\n elif reward >= 0.5 and reward < 0.8 and absoluteZDiff < 1:\n reward = reward * 4\n elif reward >= 0.8 and absoluteZDiff < 1:\n reward = reward * 5\n elif reward > -1.0 and absoluteZDiff > 2:\n reward = -3.0 # penalize more for bad z\n else:\n reward = -1.0 # Cap it here\n \"\"\"\n \n # Instead of comparing to target z, compare to last z\n origTargetZDiff = abs(self.reward_last_z - self.target_pos[2])\n self.reward_last_z = self.reward_this_z\n self.reward_this_z = self.sim.pose[2]\n \n # diff between current z and last z\n lastZDiff = abs(self.reward_last_z - self.reward_this_z)\n # diff betwen current z and target z\n targetZDiff = abs(self.reward_this_z - self.target_pos[2])\n \n \"\"\"\n if lastZDiff < 0.1:\n if reward > 0 and reward < 0.5:\n reward = 0.5\n elif reward >= 0.5 and reward < 0.8:\n reward = 0.8\n elif reward >= 0.8 and reward < 1:\n reward = 1.0\n elif reward < -1.0:\n reward = -1.0 # Cap it here\n\n if reward > 0 and targetZDiff < 2:\n reward = reward * 1.2\n\n if (targetZDiff < origTargetZDiff):\n if reward > 0:\n reward = reward * 1.5\n else:\n reward = reward * 0.5\n \"\"\"\n \n if reward < -1.0:\n reward = -1.0\n \n return reward",
"def is_permitted_to_restore(domain, couch_user, as_user_obj):\n try:\n _ensure_valid_domain(domain, couch_user)\n if as_user_obj is not None and not _restoring_as_yourself(couch_user, as_user_obj):\n _ensure_valid_restore_as_user(domain, couch_user, as_user_obj)\n _ensure_accessible_location(domain, couch_user, as_user_obj)\n _ensure_edit_data_permission(domain, couch_user)\n except RestorePermissionDenied as e:\n return False, str(e)\n else:\n return True, None",
"def perform_update(self, state, action, reward):\n\t\tpass",
"def test_action_claim_reward_triggered_event_handler_without_reward_doesnt_trigger_claim_call( # noqa\n context: Context,\n):\n context = setup_state_with_closed_channel(context)\n\n context.db.upsert_monitor_request(\n get_signed_monitor_request(nonce=Nonce(6), reward_amount=TokenAmount(0))\n )\n\n trigger_event = ActionClaimRewardTriggeredEvent(\n token_network_address=DEFAULT_TOKEN_NETWORK_ADDRESS,\n channel_identifier=DEFAULT_CHANNEL_IDENTIFIER,\n non_closing_participant=DEFAULT_PARTICIPANT2,\n )\n\n channel = context.db.get_channel(\n trigger_event.token_network_address, trigger_event.channel_identifier\n )\n assert channel\n assert channel.claim_tx_hash is None\n\n # Set update state\n channel.update_status = OnChainUpdateStatus(\n update_sender_address=context.ms_state.address, nonce=Nonce(6)\n )\n context.db.upsert_channel(channel)\n\n action_claim_reward_triggered_event_handler(trigger_event, context)\n\n # check that the monitor call has been done\n assert context.monitoring_service_contract.functions.claimReward.called is False"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
That method handle post_save signal from HitCount and check if a reward must be granted to the owner of the Model3d.
|
def check_if_user_earned_star_reward(sender, instance, **kwargs):
logger.debug("check_if_user_earned_star_reward raised")
hits = instance.hits
content_object = instance.content_object
if type(content_object) is Model3d:
sketchfab_services.check_star_reward(content_object, hits)
|
[
"def check_if_user_earned_collector_reward(sender, instance, created, **kwargs):\n\n logger.debug(\"check_if_user_earned_collector_reward raised\")\n if created:\n user = instance.user\n sketchfab_services.check_collector_reward(user)",
"def observe(self, pre_observation, action, reward, post_observation, done):",
"def compute_reward(self, obs, action):\n pass",
"def should_hit(self):\n \n return self.hand.compute_bj_count() < 17",
"def on_put(self, world, agent, item):\n # log(f\"{self}.on_put({agent})\")\n return False",
"def is_reward(self):\n return self._reward",
"def perform_update(self, action, reward):\n\t\tpass",
"def __handleJellybeanRewardDone(self):\n self.ignore(self.showRewardDoneEvent)\n self.handleRewardDone()",
"def perform_update(self, state, action, reward):\n\t\tpass",
"def update_reward(self, reward, force=False):\n if force or reward >= 0:\n self._reward = reward",
"def _reward(self, player, state, actions):\n raise(NotImplementedError)",
"def hasExperienceReward(self):\n return self.handle.rewardExp",
"def observe(self, observation):\n if observation.get('reward') is not None:\n reward = observation['reward']\n for log_prob in self.log_probs:\n loss = - log_prob * reward\n self.backward(loss)\n \n self.log_probs = []\n\n for parameter in self.model.parameters(): # pylint: disable=access-member-before-definition\n if parameter.grad is not None:\n parameter.grad.data.clamp_(min=-5, max=5)\n \n if observation.get('model') is not None:\n # Deepcopied and frozen clone of the model\n self.model = observation['model']\n\n return super(RLTorchGeneratorAgent, self).observe(\n observation)",
"def _should_save(self) -> bool:\n return random.randint(0, self.MAX_RAND_INT) == 0",
"async def _before_save(self) -> None:",
"async def _after_save(self) -> None:",
"def post_validate(self):\n pass",
"def checkAwarded(self):\r\n self.awarded = self.moveCount <= 20\r\n if self.awarded:\r\n CURRENT_PROFILE.addMoveRating(self.level)",
"def has_access(self, model):\n return True"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Set the distance model.
|
def set_distance_model(
self, model: DistanceModelStr | QtSpatialAudio.QSpatialSound.DistanceModel
):
self.setDistanceModel(DISTANCE_MODEL.get_enum_value(model))
|
[
"def setDistance(self, distance) -> None:\n ...",
"def set_arbitrary_distance(self):\n self.dist = np.min(self.mx-self.mn)",
"def set_distorion(self, distortion):\n self.dist = distortion",
"def set_velocity_dist(self, velocity_dist):\n self.erase_lookup_tables()\n if self.isotropic:\n default = 0.5 * velocity_dist(self.VELOCITY)\n default = np.broadcast_to(default, (self.BINS, self.BINS))\n else:\n default = velocity_dist(*self.MESH)\n\n norm = self.dtrapz(default)\n self.default = default / norm",
"def update_distance(self, map_distance):\n try:\n assert isinstance(map_distance, float)\n except AssertionError:\n raise TypeError\n self._mapd = map_distance",
"def setdistance(self, other, distance):\n vx, vy = self.__vec2__\n if isNumberType(other):\n ox = oy = other\n else:\n ox, oy = getattr(other, \"__vec2__\", other)\n dx = vx - ox\n dy = vy - oy\n l = hypot(dx, dy)\n if l:\n l = distance / l\n return Vec2((ox + vx * l, oy + vy * l))\n return Vec2(None, (ox, oy + distance))",
"def distance(self, distanceDict):\n self._distance = copy.deepcopy(distanceDict)",
"def update_distance(self):\n if self.serial is not None:\n if len(self.data_points) > 0:\n self.distance = sum(self.data_points)/len(self.data_points)\n else:\n self.distance = 300",
"def set_new_bond_distance(self,mol, dist, atm1, atm2, confid=0):\n conf = mol.GetConformer(confid)\n rdmt.SetBondLength(conf, atm1, atm2, dist)\n return mol",
"def setDistObj(self):\n if self.type == 'normal':\n self.distObj = stats.norm(loc=self.loc, scale=self.scale)\n\n elif self.type == 'lognormal':\n self.distObj = stats.lognorm(s=self.shape, loc=self.loc, scale=self.scale)\n\n elif self.type == 'weibull':\n self.distObj = stats.weibull_min(c=self.shape, loc=self.loc, scale=self.scale)\n\n elif self.type == 'exponential':\n self.distObj = stats.expon(loc=self.loc, scale=self.scale)\n\n elif self.type == 'triangular':\n self.distObj = stats.triang(c=self.shape, loc=self.loc, scale=self.scale)\n\n elif self.type == 'uniform':\n self.distObj = stats.uniform(loc=self.loc, scale=self.scale)\n\n elif self.type == 'gamma':\n self.distObj = stats.gamma(a=self.shape, loc=self.loc, scale=self.scale)\n\n # elif self.type == 'constant':\n # self.value = float(settings[self.name + '_' + 'value'])\n\n return",
"def set_device(self, device):\n self.device = device\n self.model = self.model.to(device)",
"def updateDist(self, d):\n self.DistText.set('Distance Measured = ' + d)",
"def attenuation_distance(self, distance):\n self._player.min_distance = distance",
"def model_dir(self, model_dir):\n self._model_dir = model_dir",
"def update_distance(self, new_distance):\n self._node_id[0][2] = new_distance",
"def init_distributed(self):\n self.model = DDP(self.model, device_ids=[self.device])",
"def get_distance_model(self) -> DistanceModelStr:\n return DISTANCE_MODEL.inverse[self.distanceModel()]",
"def set_distances(self):\n\n for metric in tqfunc(self.distance_metrics,desc='Distances'):\n metric_name = metric['metric']\n for group in tqfunc(self.experiment_groups,desc=metric_name):\n group.distance(metric_name)",
"def setDistance(self, value, ids):\n id_1, id_2 = ids\n if (id_1 < id_2):\n ordered_ids = (id_1, id_2)\n else:\n ordered_ids = (id_2, id_1)\n self.distance[ordered_ids] = value"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return current distance model.
|
def get_distance_model(self) -> DistanceModelStr:
return DISTANCE_MODEL.inverse[self.distanceModel()]
|
[
"def _get_distance(self):\n\n # implement here",
"def get_distance():\n return sensor.distance_cm()",
"def get_distance_vector(self):\r\n return self.routingTable[self.sourceRouter]",
"def get_distance(self):\n\n\t\tif self.tour_completed:\n\t\t\treturn self.distance_travelled\n\t\treturn None",
"def get_distance(self):\n state_desc = self.env.get_state_desc()\n return state_desc[\"body_pos\"][\"pelvis\"][0]",
"def get_admin_distance(self):\n pass",
"def distance_to_current_waypoint(self):\r\n # TODO: error safe it\r\n nextwaypoint=self.cmds.next\r\n if nextwaypoint ==0:\r\n return None\r\n missionitem=self.cmds[nextwaypoint-1] #commands are zero indexed\r\n lat=missionitem.x\r\n lon=missionitem.y\r\n alt=missionitem.z\r\n targetWaypointLocation=LocationGlobalRelative(lat,lon,alt)\r\n distancetopoint = frame_conversion.get_distance_metres(self.vehicle.location.global_frame, targetWaypointLocation)\r\n return distancetopoint",
"def get_model(self):\n return self._model",
"def get_model(self):\n return self.forecaster_model",
"def get_distance(self):\n assert self._distance_from_target != -1, \"Non e' ancora stata settata la distanza dal target\"\n\n return self._distance_from_target",
"def get_map_distance(self):\n return self._mapd",
"def get_distance(self):\n \n\n # Specify -1 to retrieve the absolute position.\n return self.vr.simxReadProximitySensor(self.handle, vrep.simx_opmode_buffer)",
"def _get_distance_matrix(self):\n\n # implement here",
"def getBestModel(self):\n return self.best_model",
"def get_distance_to_goal(self):\n self._update_distance_and_heading_to_goal()\n return self.distance_to_goal",
"def model(self) -> CFGModel:\n return self._model",
"def get_distance(self, source, target, distance):\n pass",
"def getCurrentEdge(self):\n keys = self._distance.keys()\n if keys:\n return self._distance[max(keys)]\n else:\n return ('-',0)",
"def get_model_costs(self):\n return self.costs"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
This class __init__ method will return a list with all disconnected clusters of a city. Each cluster is a list of the street ways connected themselves. !!! ATENTION !!! It considers the city streets network as a UNDIRECTED GRAPH!!!
|
def __init__(self, city):
self.clusters = []
# We get all city street network nodes:
allNodes = city.getStreetNodes()
# When a node is added to a cluster, we eliminate it from the allNodes list.
# So we go adding nodes to a cluster while allNodes list is not empty.
while len(allNodes)!=0:
# Initialize a new cluster:
openSet = []
closeSet = []
actCluster = []
openSet.append(allNodes[0])
# The actual cluster grows adding neighbors of the nodes belonging to it.
# When the actual node neighbors are added to the openSet, the actual node is eliminated from openSet and added to closeSet
# So we go adding nodes to the actCluster while openSet is not empty.
while len(openSet)!=0:
# First openSet node, get neighbors.
neig = city.getNodeNeigNodes(openSet[0])
# Add first openSet node neighbors to the openSet.
if neig!=None:
for n in neig:
# Each n is a tuple (neigNode, wayToGetNeigNode).
# Add neighbor node to openSet if is not already in it:
if (n[0] not in openSet) and (n[0] not in closeSet):
openSet.append(n[0])
# Add way to get to the neighbor node to the actCluster if is not already in it:
if n[1] not in actCluster:
actCluster.append(n[1])
# When actual node has been added to the cluster:
# we add it to the closeSet
closeSet.append(openSet[0])
# and we eliminate it form allNodes and openSet lists
allNodes.remove(openSet[0])
del openSet[0]
# A cluster is completed, no more neighbors
self.clusters.append(actCluster)
# No nodes on allNodes_l, so all clusters found
|
[
"def __init__(self):\n\n self.clusters = [ ]",
"def cluster_conn(self):\n assert self.clusters\n cluster_conn = []\n for i, cluster_atoms in enumerate(self.clusters):\n this_cluster_conn = []\n ext_bond = []\n for ia in cluster_atoms:\n via = self.molg.vertex(ia)\n for j in via.all_neighbours():\n if j not in cluster_atoms:\n ext_bond.append(int(str(j)))\n #print(\"cluster %s consisting of %d atoms is %d times connected\" % (str(i), len(cluster_atoms), len(ext_bond)))\n # now check to which clusters these external bonds belong to\n for ea in ext_bond:\n for ji, j in enumerate(self.clusters):\n if ea in j:\n this_cluster_conn.append(ji)\n # print(\" -> bonded to cluster \", ji)\n break\n cluster_conn.append(this_cluster_conn)\n return cluster_conn",
"def select_cluster(self, start_city, max_cities_per_cluster, steiner_points, mst_P):\n \n P = list(self.cities)\n P.extend(steiner_points)\n P_edges = dict()\n for p in P:\n P_edges[p] = set()\n for edge in mst_P:\n P_edges[edge[0]].add(edge[1])\n P_edges[edge[1]].add(edge[0])\n\n # take a random city and improve its local graph\n cluster_cities, cluster_steiner_points_set = self.find_cluster_cities_and_steiner_points(\n start_city, max_cities_per_cluster, P_edges)\n\n cluster_P = set(cluster_cities)\n cluster_P.update(cluster_steiner_points_set)\n cluster_tree = list()\n for edge in mst_P:\n if edge[0] in cluster_P and edge[1] in cluster_P:\n cluster_tree.append(edge)\n cluster_tree_cost = 1 + sum([Point.chebyshev_distance(edge[0], edge[1]) for edge in cluster_tree])\n \n return cluster_cities, list(cluster_steiner_points_set), cluster_tree, cluster_tree_cost",
"def get_cs1(self, start_vertex=0, start_cell=np.array([0,0,0])):\n visited = []\n # loop over all neighbouring clusters and add them to the list\n for nj, j in enumerate(self.mol.conn[start_vertex]):\n current_vertex = j\n current_cell = start_cell + self.mol.pconn[start_vertex][nj]\n visited.append([current_vertex, current_cell])\n return visited",
"def clustersWithout0(self):\n clusters = [] # liste de clusters (individu)\n temp_list = [] # liste temporaire contenant un seul cluster\n\n for i in self.individual: # pour chaque élément dans l'individu\n if i != 0: # si l'élément est différent de 0\n temp_list.append(i) # met cet élément dans la temp_list\n else:\n if temp_list: # sinon si temp_list n'est pas vide (différent d'une liste vide)\n clusters.append(temp_list) # ajoute les éléments de temp_list à la liste de clusters\n temp_list = [] # vide temp_list\n if temp_list: # si temp_list existe, ajoute temps_list si on n'a pas rencontré de 0 dans la boucle\n clusters.append(temp_list)\n return clusters",
"def cluster_nodes(self):\n clusters = []\n explored = set()\n nodes_iter = iter(self._data)\n while len(explored) < len(self._data):\n node1 = next(nodes_iter)\n if node1 not in explored:\n this_cluster = set()\n new_neighbors = self._data[node1]\n while new_neighbors:\n this_cluster.update(new_neighbors)\n explored.update(new_neighbors)\n just_added = new_neighbors\n new_neighbors = set(i for node in just_added for i in self._data[node] if i not in explored)\n clusters.append(this_cluster)\n return clusters",
"def __update_clusters(self):\n \n clusters = [[] for i in range(len(self.__centers))];\n for index_point in range(len(self.__pointer_data)):\n index_optim = -1;\n dist_optim = 0.0;\n \n for index in range(len(self.__centers)):\n # dist = euclidean_distance(data[index_point], centers[index]); # Slow solution\n dist = euclidean_distance_sqrt(self.__pointer_data[index_point], self.__centers[index]); # Fast solution\n \n if ( (dist < dist_optim) or (index is 0)):\n index_optim = index;\n dist_optim = dist;\n \n clusters[index_optim].append(index_point);\n \n # If cluster is not able to capture object it should be removed\n clusters = [cluster for cluster in clusters if len(cluster) > 0];\n \n return clusters;",
"def generate_connectivity(conn, location_map):\n\n import networkx as nx\n\n df_cluster = pd.read_sql(\"\"\"\n SELECT\n m.user_id, m.cluster_id\n FROM\n media_events AS m, cluster AS c\n WHERE\n cluster_id IS NOT NULL AND m.cluster_id = c.id;\n \"\"\", conn)\n\n df_edge = pd.merge(df_cluster, df_cluster, left_on='user_id', right_on='user_id')\n\n all_edge = df_edge[['cluster_id_x', 'cluster_id_y']].values\n all_edge_tuple = set([(edge[0], edge[1]) for edge in all_edge])\n\n inverse_map = {val:key for key,val in enumerate(location_map)}\n \n graph = nx.Graph()\n\n for edge in all_edge_tuple:\n start, end = edge\n graph.add_edge(inverse_map[start], inverse_map[end])\n\n return nx.to_scipy_sparse_matrix(graph)",
"def connected_cities():\n for i in range(len(list_of_instances)):\n #list_connected_cities = [city_names[i]]\n # fill this list for each city with user input, safe in self.roads_to, reset\n # instance.name since city is always connected to itself\n list_adjacent[i][i] = 1 # Straße zu sich selbst\n\n a = True # checker while loop\n\n while a:\n\n connected_cities_input = input(\"Which other cities \\\nshould %s be connected to? When you're done enter next to proceed to the \\\nnext city.\" % city_names[i]) # instance name gibt namen der stadt zurück\n\n if connected_cities_input == \"next\": # FIX zweite condition frisst er nicht # enter next to get to next city, oder wenn alle connections gezogen wurden\n print(\"Connections for\", city_names[i], \"are complete.\")\n\n list_of_instances[i].adjacency_list(list_adjacent[i]) # assign binary list of adj. cities of city i to class object adjacency\n a = False\n\n elif connected_cities_input in city_names:\n if list_adjacent[i][city_names.index(connected_cities_input)] == 1: # check if cities are already connected\n print(\"There is already a connection between\", city_names[i], \"and\", connected_cities_input)\n\n elif list_adjacent[city_names.index(connected_cities_input)][i] == 1: # check via symmetry (matrix) if cities are already connected\n print(\"There is already a connection between\", city_names[i], \"and\", connected_cities_input)\n\n else:\n #for a in range(len(list_of_instances)): # scheinbar überflüssiges code stück\n list_adjacent[i][city_names.index(connected_cities_input)] = 1 # Straße zu der Stadt aus Input Matrix hinzufügen\n list_adjacent[city_names.index(connected_cities_input)][i] = 1 # Symmetrie Straße von Input zu Stadt\n\n else: # Fehleingaben, nichts wird als fehleingabe gewertet\n print(\"Unexpected input. Please enter a city name thats in the list.\")\n\n PrintMatrix()",
"def computeClusters(self):\n comm = self.g.community_fastgreedy(weights=self.g.es[\"weight\"])\n self.clusters = comm.as_clustering()",
"def clusterSeeds(seeds, l): \n \n # Code to complete - you are free to define other functions as you like\n seedClusterSet = set()\n nodeList = list()\n orphanNodeList = list()\n for i in seeds:\n # Because we know that the k-mers occur left-to-right, we can optimize DFS to be O(n)\n x1 = i[0]\n # First iterate all of the seeds of the form (x, (y_1, y_2, ... ))\n for y1j in i[1]:\n # Then iterate all of our string2 list of y coords\n if not len(nodeList):\n # If our current connected component is empty, then start a new one\n nodeList.append((x1, y1j)) \n elif abs(x1 - nodeList[-1][0]) <= l and abs(y1j - nodeList[-1][1]) <= l:\n # If we are connected with our current component, then append to it\n nodeList.append((x1, y1j))\n else:\n orphanNodeList.append((x1, y1j))\n # Try one last time to attach orphans\n connectOrphans = False\n if len(orphanNodeList):\n connectOrphans = True\n found = False\n while connectOrphans:\n # Iterate the orphans and if we add any then loop again\n orphanLength = len(orphanNodeList)\n for o in range(orphanLength):\n x1 = orphanNodeList[o][0]\n y1j = orphanNodeList[o][1]\n for node in nodeList[:]: # because we already checked the last one...\n if abs(x1 - node[0]) <= l and abs(y1j - node[1]) <= l:\n # If we are connected with our current component, then append to it\n nodeList.append((x1, y1j))\n del orphanNodeList[o]\n found = True\n break\n # If we connect then we can break\n if found:\n found = False\n break\n if len(orphanNodeList) == orphanLength:\n connectOrphans = False\n\n # Dump the nodeList if everything so far was connected\n if len(nodeList):\n seedClusterSet.add(SeedCluster(nodeList))\n\n return seedClusterSet",
"def connections(self):\n if self._connections is None:\n # get connection pairs\n w = 10 if self.width == 24 else 11\n conn = [(anode, cathode) for cathode in range(12) for anode in [a for a in range(12) if a!= cathode][:w]]\n # arrange connection pairs in coordinate grid\n col_height, cols = (5, 24) if self.width == 24 else (11, 12)\n self._connections = [conn[col_height*i:col_height*i+col_height] for i in range(cols)]\n return self._connections",
"def neighbors_clustering(user, directed, algorithm_keywords):\n pass",
"def connect_all(self):\n # All classrooms are disconnected nodes\n for classroom in self.nodes.classrooms:\n a, b = funcs.naive_knn(classroom, self.nodes.hallways, k=2)\n d = funcs.project(a, b, classroom)\n\n self.add_edge(a, d, weight=funcs.euclidean_dist_nodes(a, d))\n self.add_edge(b, d, weight=funcs.euclidean_dist_nodes(b, d))\n self.add_edge(classroom, d, weight=funcs.euclidean_dist_nodes(classroom, d))",
"def _generate_city_connection_points(self, city_positions: IntVector2DArray, city_radius: int,\n vector_field: IntVector2DArray, rails_between_cities: int,\n rail_pairs_in_city: int = 1, np_random: RandomState = None) -> (\n List[List[List[IntVector2D]]],\n List[List[List[IntVector2D]]],\n List[np.ndarray],\n List[Grid4TransitionsEnum]):\n inner_connection_points: List[List[List[IntVector2D]]] = []\n outer_connection_points: List[List[List[IntVector2D]]] = []\n city_orientations: List[Grid4TransitionsEnum] = []\n city_cells: IntVector2DArray = []\n\n for city_position in city_positions:\n\n # Chose the directions where close cities are situated\n neighb_dist = []\n for neighbour_city in city_positions:\n neighb_dist.append(Vec2dOperations.get_manhattan_distance(city_position, neighbour_city))\n closest_neighb_idx = self.__class__.argsort(neighb_dist)\n\n # Store the directions to these neighbours and orient city to face closest neighbour\n connection_sides_idx = []\n idx = 1\n if self.grid_mode:\n current_closest_direction = np_random.randint(4)\n else:\n current_closest_direction = direction_to_point(city_position, city_positions[closest_neighb_idx[idx]])\n connection_sides_idx.append(current_closest_direction)\n connection_sides_idx.append((current_closest_direction + 2) % 4)\n city_orientations.append(current_closest_direction)\n city_cells.extend(self._get_cells_in_city(city_position, city_radius, city_orientations[-1], vector_field))\n # set the number of tracks within a city, at least 2 tracks per city\n connections_per_direction = np.zeros(4, dtype=int)\n # NEW : SCHED CONST\n nr_of_connection_points = np_random.randint(1, rail_pairs_in_city + 1) * 2 # can be (1,2,3)*2 = (2,4,6)\n for idx in connection_sides_idx:\n connections_per_direction[idx] = nr_of_connection_points\n connection_points_coordinates_inner: List[List[IntVector2D]] = [[] for i in range(4)]\n connection_points_coordinates_outer: List[List[IntVector2D]] = [[] for i in range(4)]\n number_of_out_rails = np_random.randint(1, min(rails_between_cities, nr_of_connection_points) + 1)\n start_idx = int((nr_of_connection_points - number_of_out_rails) / 2)\n for direction in range(4):\n connection_slots = np.arange(nr_of_connection_points) - start_idx\n # Offset the rails away from the center of the city\n offset_distances = np.arange(nr_of_connection_points) - int(nr_of_connection_points / 2)\n # The clipping helps ofsetting one side more than the other to avoid switches at same locations\n # The magic number plus one is added such that all points have at least one offset\n inner_point_offset = np.abs(offset_distances) + np.clip(offset_distances, 0, 1) + 1\n for connection_idx in range(connections_per_direction[direction]):\n if direction == 0:\n tmp_coordinates = (\n city_position[0] - city_radius + inner_point_offset[connection_idx],\n city_position[1] + connection_slots[connection_idx])\n out_tmp_coordinates = (\n city_position[0] - city_radius, city_position[1] + connection_slots[connection_idx])\n if direction == 1:\n tmp_coordinates = (\n city_position[0] + connection_slots[connection_idx],\n city_position[1] + city_radius - inner_point_offset[connection_idx])\n out_tmp_coordinates = (\n city_position[0] + connection_slots[connection_idx], city_position[1] + city_radius)\n if direction == 2:\n tmp_coordinates = (\n city_position[0] + city_radius - inner_point_offset[connection_idx],\n city_position[1] + connection_slots[connection_idx])\n out_tmp_coordinates = (\n city_position[0] + city_radius, city_position[1] + connection_slots[connection_idx])\n if direction == 3:\n tmp_coordinates = (\n city_position[0] + connection_slots[connection_idx],\n city_position[1] - city_radius + inner_point_offset[connection_idx])\n out_tmp_coordinates = (\n city_position[0] + connection_slots[connection_idx], city_position[1] - city_radius)\n connection_points_coordinates_inner[direction].append(tmp_coordinates)\n if connection_idx in range(start_idx, start_idx + number_of_out_rails):\n connection_points_coordinates_outer[direction].append(out_tmp_coordinates)\n\n inner_connection_points.append(connection_points_coordinates_inner)\n outer_connection_points.append(connection_points_coordinates_outer)\n return inner_connection_points, outer_connection_points, city_orientations, city_cells",
"def get_cluster_atoms(self):\n try:\n assert self.clusters\n except:\n self.get_clusters()\n midx_list = self.keep.vp.midx.get_array().tolist()\n # set edge filter\n for i, c in enumerate(self.clusters):\n cluster_atoms = self.clusters[i]\n for ia in cluster_atoms:\n via = self.molg.vertex(ia)\n for j in via.all_neighbours():\n if j not in cluster_atoms:\n # found external bond, set edge filter here\n midx = (self.molg.vp.midx[via], self.molg.vp.midx[j])\n atomid = (midx_list.index(midx[0]), midx_list.index(midx[1]))\n keepedge = self.keep.edge(atomid[0], atomid[1])\n self.keep.ep.act[keepedge] = False\n self.keep.set_edge_filter(self.keep.ep.act)\n # then find all connecting atoms\n clusters_vertices = []\n clusters_atoms = []\n self.keep.vp.filled.set_value(False)\n for ic, c in enumerate(self.clusters):\n for vid in c:\n v = self.molg.vertex(vid)\n midx = self.molg.vp.midx[v]\n atomid = midx_list.index(midx)\n atom = self.keep.vertex(atomid)\n if self.keep.vp.filled[atom] == False:\n this_cluster_verts = self.flood_fill(self.keep, atom, [])\n clusters_vertices.append(this_cluster_verts)\n this_cluster_atoms = []\n for i in this_cluster_verts:\n this_cluster_atoms.append(self.keep.vp.midx[i])\n # set atomtypes in self.mol\n self.mol.atypes[self.keep.vp.midx[i]] = ic\n clusters_atoms.append(this_cluster_atoms)\n self.keep.clear_filters()\n return clusters_vertices, clusters_atoms",
"def make_city(name,neighbours):\n\t\n\treturn [name, False, list(numpy.where(neighbours==1)[0])]",
"def __init__(self, kmers):\r\n self.kmers = kmers\r\n self.adjacencyList = []",
"def clustering_with_location(network):\n print('Clustering nodes using their location info...')\n communities = {}\n\n for vertex in network.nodes(data=True):\n loc = vertex[1]['location']\n try:\n communities[loc].append(vertex[0])\n except KeyError:\n communities[loc] = [vertex[0]]\n\n by_location_coms = NodeClustering(communities.values(), network,\n method_name='by_location',\n method_parameters=None, overlap=False)\n print('Done!\\n')\n return by_location_coms"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
This method returns the clusters found
|
def getClusters(self):
return self.clusters
|
[
"def get_cluster_list(self):\n LOG.info(\"Getting clusters\")\n return self.client.request(constants.GET,\n constants.GET_CLUSTER.format\n (self.server_ip), payload=None,\n querystring=constants.\n SELECT_ID_AND_NAME)",
"def _cluster_list():\n\n CLUSTER_TABLE = storage.get_cluster_table()\n clusters = []\n cluster_items = CLUSTER_TABLE.scan()\n\n for cluster in cluster_items['Items']:\n clusters.append(cluster['id'])\n\n print(f'tracked clusters: {clusters}')\n\n return clusters",
"def get_cluster_centers(self):\n pass",
"def get_clusters(self):\n return set(host.cluster for host in self.hosts)",
"def get_cluster_centers(self):\n return None",
"def __determine_clusters(self, pointli):\n if self.opt.within_cluster_dist < 0:\n return\n clusterli = []\n for p1 in pointli:\n if self.opt.stop_requested:\n return []\n if p1.cluster:\n continue\n for p2 in pointli:\n if p1 != p2 and p1.dist(p2) <= geometry.to_pixel_units(self.opt.within_cluster_dist,\n self.pixelwidth):\n if p2.cluster is not None:\n p1.cluster = p2.cluster\n clusterli[p1.cluster].append(p1)\n break\n else:\n p1.cluster = len(clusterli)\n clusterli.append(ClusterData([p1]))\n self.__process_clusters(clusterli)\n return clusterli",
"def cluster_nodes(self):\n clusters = []\n explored = set()\n nodes_iter = iter(self._data)\n while len(explored) < len(self._data):\n node1 = next(nodes_iter)\n if node1 not in explored:\n this_cluster = set()\n new_neighbors = self._data[node1]\n while new_neighbors:\n this_cluster.update(new_neighbors)\n explored.update(new_neighbors)\n just_added = new_neighbors\n new_neighbors = set(i for node in just_added for i in self._data[node] if i not in explored)\n clusters.append(this_cluster)\n return clusters",
"def __update_clusters(self):\n \n clusters = [[] for i in range(len(self.__centers))];\n for index_point in range(len(self.__pointer_data)):\n index_optim = -1;\n dist_optim = 0.0;\n \n for index in range(len(self.__centers)):\n # dist = euclidean_distance(data[index_point], centers[index]); # Slow solution\n dist = euclidean_distance_sqrt(self.__pointer_data[index_point], self.__centers[index]); # Fast solution\n \n if ( (dist < dist_optim) or (index is 0)):\n index_optim = index;\n dist_optim = dist;\n \n clusters[index_optim].append(index_point);\n \n # If cluster is not able to capture object it should be removed\n clusters = [cluster for cluster in clusters if len(cluster) > 0];\n \n return clusters;",
"def get_clusters(self) -> List[Dict]:\n\n \"\"\"\n GET /v1/clusters HTTP/1.1\n Host: containers.bluemix.net\n Accept: application/json\n Authorization: [PRIVATE DATA HIDDEN]\n Content-Type: application/json\n X-Region: au-syd\n \"\"\"\n # returns 200 OK on success\n\n resp = self.session.get(\n \"{0}/v1/clusters\".format(self.endpoint_url),\n headers={\"X-Region\": self.region, \"Accept\": \"application/json\"},\n )\n\n if resp.status_code != 200:\n raise Exception(\n \"error getting clusters: code=%d body=%r\"\n % (resp.status_code, resp.text)\n )\n\n return resp.json()",
"def computeClusters(self):\n comm = self.g.community_fastgreedy(weights=self.g.es[\"weight\"])\n self.clusters = comm.as_clustering()",
"def cluster_nodes(self) -> pulumi.Output[Sequence['outputs.ClusterClusterNode']]:\n return pulumi.get(self, \"cluster_nodes\")",
"def cluster_ids(self) -> pulumi.Output[Sequence[str]]:\n return pulumi.get(self, \"cluster_ids\")",
"def clusters(self):\n return (self.input_array[lower:upper]\n for lower, upper in self.slices)",
"def get_fit_cluster_indices(self):\n\n\t\treturn self._fit_cluster_indices",
"def clustering(self, cloud, vg_size=0.1, tolerance=0.5, min_cluster_size=1000):\n\n\n cluster_list = list()\n cloud_value = cloud\n vg = cloud.make_voxel_grid_filter()\n vg.set_leaf_size(vg_size, vg_size, vg_size)\n cloud_filtered = vg.filter()\n\n tree = cloud_filtered.make_kdtree()\n ec = cloud_filtered.make_EuclideanClusterExtraction()\n ec.set_ClusterTolerance(tolerance) # 0.5 = 50cm\n ec.set_MinClusterSize(min_cluster_size) # impose that the clusters found must have at least\n ec.set_MaxClusterSize(cloud_value.size) # impose that the clusters found must have at Maximum\n ec.set_SearchMethod(tree)\n\n\n cluster_indices = ec.Extract() # return index number that is included in the result of clustering\n\n for j, indices in enumerate(cluster_indices):\n\n cloud_cluster = pcl.PointCloud()\n\n points = np.zeros((len(indices), 3), dtype=np.float32)\n\n\n for i, indice in enumerate(indices):\n\n points[i][0] = cloud_filtered[indice][0]\n points[i][1] = cloud_filtered[indice][1]\n points[i][2] = cloud_filtered[indice][2]\n\n cloud_cluster.from_array(points)\n cluster_list.append(cloud_cluster)\n\n if len(cluster_list) != 0:\n\n return cluster_list\n else:\n cluster_list.append(cloud)\n\n return cluster_list",
"def test_api_v1_radar_container_clusters_get(self):\n pass",
"def get_centers_for_given_clusters(self, current_indices_cluster):\n\n size = len(current_indices_cluster)\n assert size > 0, \"set is empty\"\n assert size == len(\n current_indices_cluster), \"current_indices_cluster size is not the number of lines in the set\"\n\n displacements = self.displacements\n dim = self.dim\n\n k = np.max(current_indices_cluster) + 1\n for i in range(k):\n indices_clustered_to_i = np.asarray(np.where(current_indices_cluster == i))[\n 0] # all the indices that contains i in current_indices_cluster\n displacements_clustered_to_i = displacements[\n indices_clustered_to_i] # all the displacements in the i-th cluster\n cluster_i_center = np.mean(displacements_clustered_to_i, axis=0).reshape(-1,\n dim) # the center of cluster of lines, that minimizes the sum of squared distances to the lines in the cluster is the mean of the displacements in the cluster, under the assumption that each line is spanned by a unit vector and its displacements is the closest point in the line to the origin\n if i == 0:\n centers = cluster_i_center\n else:\n centers = np.concatenate((centers, cluster_i_center), axis=0).reshape(-1, dim)\n centers = centers.reshape(-1, dim)\n return centers",
"def fetch_cluster_instances():\n\n\trds = boto3.client('rds', region_name = regionName)\n\ttry:\n\t\tprint(\"Fetching cluster information for cluster \", clusterIdentifier)\n\t\tresult = rds.describe_db_clusters(DBClusterIdentifier = clusterIdentifier)\n\t\tcluster = result['DBClusters'][0]\n\t\tclusterMembers = cluster['DBClusterMembers']\n\t\tinstanceIdentifiers = []\n\t\tfor instance in clusterMembers:\n\t\t\tinstanceIdentifiers.append(instance['DBInstanceIdentifier'])\n\t\treturn instanceIdentifiers\n\texcept Exception as e:\n\t\tprint(\"Error while fetching cluster data: \", e)\n\t\traise e",
"def get_instance(self):\n return self.clusters",
"def get_cluster_list(self, context, filters=None, limit=None,\n marker=None, sort_key=None, sort_dir=None):"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
generate xpaths based on a tag_name and attributes
|
def generate_xpath(self, tag_name, attributes):
xpaths_plural = "<ul>"
for key in attributes.keys():
xpaths_plural += "<li>.//{}[contains(@{}, '{}')]</li>".format(
tag_name, key, attributes[key])
xpaths_plural += "</ul>"
return xpaths_plural
|
[
"def xpath(self, *args, **kw):\n nodes = super(_Tag, self).xpath(*args, **kw)\n\n renderer = self.renderer\n for node in nodes:\n node._renderer = renderer\n\n return nodes",
"def xpath_iter(xpath):\n for separator, token in re.compile('(|/|\\.\\.)/([^/]+)').findall(xpath):\n index, attributes = None, []\n if '[' in token:\n tag = token[:token.find('[')]\n for attribute in re.compile('\\[(.*?)\\]').findall(token):\n try:\n index = int(attribute)\n except ValueError:\n match = re.compile('@(.*?)=[\"\\']?(.*?)[\"\\']?$').search(attribute)\n if match:\n key, value = match.groups()\n attributes.append((key.lower(), value.lower()))\n else:\n raise common.WebScrapingError('Unknown format: ' + attribute)\n else:\n tag = token\n yield separator, tag, index, attributes",
"def _getNodesByXpath (element, xpath, xpath_delimiter=\"/\"):\n\t\t# if xpath_delimiter == '/':\n\t\t\t# raise Exception, 'delimiter is /'\n\t\tsplits = xpath.split (xpath_delimiter)\n\t\ttagName = splits[0]\n\t\t\n\t\tif not tagName:\n\t\t\treturn []\n\t\t\n\t\tindex = None\n\t\tm = indexPat.match (splits[0])\n\t\tif m:\n\t\t\ttagName = m.group(1)\n\t\t\tindex = int(m.group(2))\n\t\t\tif index < 1:\n\t\t\t\traise KeyError, \"illegal xpath index: %d\" % index\n\t\t\n\t\t\n\t\tattrRestriction = AttributeRestriction (splits[0])\n\t\tif attrRestriction.isRestriction:\n\t\t\t#filter by attribute restriction\n\t\t\ttagName = attrRestriction.tagName\n\t\t\tchildren = filter (lambda x: attrRestriction.matchesElement(x), getChildElements(element))\n\t\t\t\n\t\telse:\n\t\t\t# contruct list of child elements that match leaf segment of xpath\n\t\t\tchildren = getChildElements(element,tagName)\n\t\t\n\t\tif 0:\n\t\t\tprint \"\\nxpath: %s (%d)\" % (xpath, len(splits))\n\t\t\t# print element.toxml()\n\t\t\tprint \"\\nCHILDREN (%d)\" % len(children)\n\t\t\tprint \"----------------\\n\"\n\t\t\n\t\t# if there is an index, we are effectively reducing the children to a \n\t\t# list containing only the indexed child\n\t\tif index is not None:\n\t\t\t# print 'INDEX: %d' % index\n\t\t\tif len(children) > index -1:\n\t\t\t\tchildren = [children[index-1]]\n\t\t\telse:\n\t\t\t\t# this was an out-of-bounds index\n\t\t\t\treturn []\n\t\t\n\t\tif len(splits) == 1:\n\t\t\t# print 'LENGTH 1!'\n\t\t\tif tagName[0] == '@':\n\t\t\t\treturn [element.getAttributeNode (tagName[1:])]\n\t\t\treturn children\n\t\telse:\n\t\t\telements = []\n\t\t\tfor child in children:\n\t\t\t\telements = elements + _getNodesByXpath (child, xpath_delimiter.join( splits[1:]), xpath_delimiter)\n\t\t\treturn filter (None, elements)",
"def _build_xpath_expression(tag, attribute_value_dict, direct_children_only=False): \r\n xpath_expr = (\"./\" + tag) if (direct_children_only==True) else (\".//\" + tag)\r\n \r\n if(len(attribute_value_dict) > 0 and type(attribute_value_dict) == dict):\r\n attr_value_pairs = []\r\n for attr, val in attribute_value_dict.items(): #combine all pairs as xpath and append to list\r\n if(val == None):\r\n attr_value_pairs.append('@' + attr)\r\n else:\r\n attr_value_pairs.append('@' + attr + '=\"' + val +'\"')\r\n attr_xpath_expr = \" and \".join(attr_value_pairs)\r\n xpath_expr += '[' + attr_xpath_expr + ']'\r\n return xpath_expr",
"def xpath_soup(element):\n components = []\n child = element if element.name else element.parent\n for parent in child.parents: # parent: bs4.element.Tag\n previous = itertools.islice(parent.children, 0, parent.contents.index(child))\n xpath_tag = child.name\n xpath_index = sum(1 for i in previous if i.name == xpath_tag) + 1\n components.append(xpath_tag if xpath_index == 1 else '%s[%d]' % (xpath_tag, xpath_index))\n child = parent\n components.reverse()\n return '/%s' % '/'.join(components)",
"def find_all_by(tag_name, attribs, ctx):\n return ctx.find_all(tag_name, attribs)",
"def findall(self, tag: str) -> Iterable[\"Element\"]:",
"def aon_xpath_basic(name):\n\n return f\"//b[text()='{name}']\"",
"def _find_xpath(self, iter, x_path, xml1=None, xml2=None):\n if xml1 is not None:\n pre_nodes = xml1.xpath(x_path) if iter else xml1.xpath(x_path)[0:1]\n else:\n pre_nodes = xml2.xpath(x_path) if iter else xml2.xpath(x_path)[0:1]\n post_nodes = xml2.xpath(x_path) if iter else xml2.xpath(x_path)[0:1]\n return pre_nodes, post_nodes",
"def findKeysXml(node, tag):\n for el in node.findall('*'):\n for ch in list(el):\n if ch.tag == tag:\n yield ch.text",
"def findall(element, node_name):\n if \"/\" in node_name:\n node_name = \"//ns:\".join(node_name.split(\"/\"))\n return element.findall(\n \".//ns:{0}\".format(node_name), namespaces={\"ns\": XHTML_NAMESPACE}\n )",
"def attributes(self):\n # \"\"\" Returns a List of an element's attributes \"\"\"\n # try:\n # return [Attr(key.lstrip('_'), value) for key, value in self.kwargs.items()]\n # except Exception as e:\n # print('Error - no tag!', e)\n # return []\n # print('attributes', self.kwargs)\n newargs = []\n for key, value in self.kwargs.items():\n # print('key', key)\n # print('value', value)\n newargs.append(Attr(key.lstrip('_'), value))\n\n nnm = NamedNodeMap(newargs, None, self)\n return nnm",
"def _locator(self):\n try:\n return 'id=' + self.attrib['id']\n except KeyError:\n return 'xpath=' + self.fq_xpath",
"def _props(tree):\n for elem in tree.findall(\".//property[@name]\"):\n yield elem",
"def find_by(tag_name, attributes, ctx):\n return ctx.find(tag_name, attributes)",
"def xpath(element, node_name):\n if \"/\" in node_name:\n node_name = \"//ns:\".join(node_name.split(\"/\"))\n return element.xpath(\n \"//ns:{0}\".format(node_name), namespaces={\"ns\": XHTML_NAMESPACE}\n )",
"def xtp_get_recursive_attributes(elem: ET.Element, root_name: str = \"\") -> str:\n s = \"\"\n name = root_name + elem.tag\n if list(elem):\n return ''.join(xtp_get_recursive_attributes(el, f\"{name}.\") for el in list(elem))\n\n description = split_line(elem.attrib.get(\"help\", \"\"))\n default = split_line(elem.attrib.get(\"default\", \"\"))\n choices = multiline(elem.attrib.get(\"choices\", \"\"))\n s += XTP_TABLE_LINE(name, default, description, choices)\n\n return s",
"def xml_findall(xpath):\n def xpath_findall(value):\n validate(ET.iselement, value)\n return value.findall(xpath)\n\n return transform(xpath_findall)",
"def get_elementattributes(element, xpath, attribute, tag_converted):\n\n subelements = element.findall(xpath)\n listofattrs = []\n for subelement in subelements:\n attr_value = subelement.get(attribute, None)\n if tag_converted:\n tag_attribute_converted(subelement, attribute)\n if attr_value is not None:\n listofattrs.append(attr_value)\n return listofattrs"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
capture image of the element that is pointed to.
|
def capture_element(self, element, name):
LOG.info(f'Performing element image capture {element}')
location = element.location
size = element.size
img = self.driver.get_screenshot_as_png()
img = Image.open(BytesIO(img))
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
LOG.debug('Name: {} Image Range: {}'.format(name,
(int(left),
int(top),
int(right),
int(bottom))))
img = img.crop((int(left), int(top), int(right), int(bottom)))
try:
img.save(name)
except SystemError as e:
LOG.error(e)
return name
|
[
"def capture(self):\n # insert the canvas\n self.fitsimage.add(self.canvas, tag='mycanvas')",
"def capture(self):\n self.camera = self.ids['camera']\n timestr = time.strftime(\"%Y%m%d_%H%M%S\")\n self.camera.export_to_png(\"IMG_{}.png\".format(timestr))\n print(\"Captured\")",
"def image(self, obj):",
"def capture_image(self, image_path, raw_file_path=None):\n pass",
"def get_image(self):",
"def capture():\r\n (x, y) = global_camera.get_coordinates()\r\n # Label snapshot image with the x- and y-coordinates:\r\n path = \"/capture/X{}Y{}.jpeg\".format(x,y)\r\n return redirect(path)",
"def capture_image(self):\n if self.__captured_image is None:\n raise HardwareException(\"uvc driver has not been opened yet to capture image.\")\n return self.__captured_image",
"def webcameCapture():\r\n retval, frame = cap.read()\r\n cv2.imwrite(\"webcam.png\",frame)\r\n img=cv2.imread(\"webcam.png\")\r\n return(img)",
"def preview_capture_example():",
"def takePicture(self, mode=None):\n return myro.takePicture(mode)",
"def display(self):\n self.o.display_image(self.image)",
"def snapshot(camera):\n #lamps(GPIO.HIGH)\n #reference to camera capture\n with PiRGBArray(camera) as raw:\n #raw = PiRGBArray(camera) \n #get image from camera\n lamps(GPIO.HIGH)\n camera.capture(raw, format='bgr')\n lamps(GPIO.LOW)\n #print('Captured')\n imRef = raw.array\n \n return imRef",
"def snapshot(self):\n ts = datetime.datetime.now() # grab the current timestamp\n filename = \"{}.png\".format(ts.strftime(\n \"%Y-%m-%d_%H-%M-%S\")) # construct filename\n\n ok, frame = self.cap.read()\n image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n image = Image.fromarray(image)\n\n # save image as jpeg file\n image.save('exports/snapshots/' + filename, \"PNG\")\n print(\"[INFO] saved {}\".format(filename))",
"def highlight_and_make_screenshot(self, file_name='element.png'):\r\n return self.screenshot(file_name)",
"def draw(self, img) -> img:\n ...",
"def captureImage(self, location, name, type):\n self.camLightOn() #turn flash on\n time.sleep(.25)\n self.cam.capture(location+name+type) # call to camera image capture function\n time.sleep(.25)\n self.camLightOff() # flash off",
"def take_snapshot(self, filename=None):\n captured_figure = self.simulation_control_widget.opengl_widget.takeSnapShot()\n\n _save_file = QtGui.QFileDialog()\n _save_file.setDirectory(self.MBD_system.MBD_folder_abs_path)\n abs_save_file_path, filetype = _save_file.getSaveFileNameAndFilter(self, \"Save file\", self.MBD_system.MBD_folder_abs_path, (\"png (*.png)\"))\n abs_save_file_path = str(abs_save_file_path).replace(\"/\", \"\\\\\")\n captured_figure.save(abs_save_file_path)",
"def take_image_virtualcam(filename, pwi4):\r\n\r\n pwi4.virtualcamera_take_image_and_save(filename)",
"def capture(robot: cozmo.robot.Robot):\n\tlog.info('Capture image...')\n\trobot.set_head_angle(cozmo.robot.MIN_HEAD_ANGLE).wait_for_completed()\n\timg = np.array(robot.world.latest_image.raw_image)\n\trect_img = draw_grid(img)\n\tth, b_cnt_rects=get_cnt_rects(rect_img, b_zn)\n\trect_img = draw_cnt_rects(rect_img, b_cnt_rects, (0,255,255))\n\trect_img = draw_path_rect(rect_img, get_path_rect(rect_img, b_zn),(0,255,0))\n\tth, l_cnt_rects=get_cnt_rects(rect_img, l_zn)\n\trect_img = draw_cnt_rects(rect_img, l_cnt_rects, (0,255,255))\n\trect_img = draw_path_rect(rect_img, get_path_rect(rect_img, l_zn),(0,255,0))\n\tth, r_cnt_rects=get_cnt_rects(rect_img, r_zn)\n\trect_img = draw_cnt_rects(rect_img, r_cnt_rects, (0,255,255))\n\trect_img = draw_path_rect(rect_img, get_path_rect(rect_img, r_zn),(0,255,0))\n\tcv2.imshow('rect_img', rect_img)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Runs NEAT's genetic algorithm for at most n generations. If n is None, run until solution is found or extinction occurs.
|
def run(self, fitness_function, n=None):
if self.config.no_fitness_termination and (n is None):
raise RuntimeError("Cannot have no generational limit with no fitness termination")
k = 0
while n is None or k < n:
k += 1
self.reporters.start_generation(self.generation)
# Evaluate all genomes using the user-provided function.
fitness_function(list(self.population.items()), self.config)
# Gather and report statistics.
best = None
for g in self.population.values():
if g.fitness is None:
raise RuntimeError("Fitness not assigned to genome {}".format(g.key))
if best is None or g.fitness > best.fitness:
best = g
self.reporters.post_evaluate(self.config, self.population, self.species, best)
# Track the best genome ever seen.
if self.best_genome is None or best.fitness > self.best_genome.fitness:
self.best_genome = best
if not self.config.no_fitness_termination:
# End if the fitness threshold is reached.
fv = self.fitness_criterion(g.fitness for g in self.population.values())
if fv >= self.config.fitness_threshold:
self.reporters.found_solution(self.config, self.generation, best)
break
# Create the next generation from the current generation.
self.population = self.reproduction.reproduce(self.config, self.species,
self.config.pop_size, self.generation)
# Check for complete extinction.
if not self.species.species:
self.reporters.complete_extinction()
# If requested by the user, create a completely new population,
# otherwise raise an exception.
if self.config.reset_on_extinction:
self.population = self.reproduction.create_new(self.config.genome_type,
self.config.genome_config,
self.config.pop_size)
else:
raise CompleteExtinctionException()
# Divide the new population into species.
self.species.speciate(self.config, self.population, self.generation)
self.reporters.end_generation(self.config, self.population, self.species)
self.generation += 1
if self.config.no_fitness_termination:
self.reporters.found_solution(self.config, self.generation, self.best_genome)
return self.best_genome
|
[
"def evolve(self, n):\n assert n > 0, \"Cannot evolve 0 or less generations!\"\n\n # Prepare the genomes\n self.reset()\n \n # Whether the performance details should be printed\n verbose = False\n\n for i in range(n):\n\n # Print information every 50th time \n if i % 50 == 0:\n print(\"Generation {0}\".format(i))\n verbose = True\n else:\n verbose = False\n \n # Evolve!\n self.evolve_step(verbose = verbose)\n\n # Termination condition that depends on \n # the maximum performance of a Gym environment\n if i % 50 == 0 and self.get_average() > 180.0:\n break\n\n self.selection()\n self.mutation()\n \n # Reset the score every generation for better performance metric\n self.reset()",
"def demo_naif(n_gen=30, n_pop=200):\n from matplotlib import pyplot as plt\n E = Essai.naif_non_random(2, 3, n_pop)\n try:\n for i in range(n_gen):\n print(\"generation {}\".format(i))\n E.generation_suivante()\n except KeyboardInterrupt:\n pass\n E.evolution_statistique(plt, 5)\n generation = E.generations[-1]\n generation.evaluation()\n return generation.genes[0]",
"def run(self, n):\n \n for i in range(n):\n self.iteration()\n return self.best",
"def ga_v1(nth_paramset, max_generation, n_population, n_children, n_gene, allowable_error):\n population = get_initial_population(n_population, n_gene)\n print('Generation%d: Best Fitness = %e' % (1, population[0, -1]))\n with open('./out/%d/out.log' % (nth_paramset), mode='w') as f:\n f.write(\n 'Generation1: Best Fitness = %e\\n' % (population[0, -1])\n )\n best_indiv = decode_gene2val(population[0, :n_gene])\n\n best_fitness = population[0, -1]\n\n np.save('./out/%d/generation.npy' % (nth_paramset), 1)\n np.save('./out/%d/fit_param1' % (nth_paramset), best_indiv)\n np.save('./out/%d/best_fitness.npy' % (nth_paramset), best_fitness)\n\n if population[0, -1] <= allowable_error:\n best_indiv = decode_gene2val(population[0, :n_gene])\n best_fitness = population[0, -1]\n\n return best_indiv, best_fitness\n\n generation = 1\n while generation < max_generation:\n population = mgg_alternation(\n population, n_population, n_children, n_gene\n )\n print(\n 'Generation%d: Best Fitness = %e' % (\n generation + 1, population[0, -1]\n )\n )\n best_indiv = decode_gene2val(population[0, :n_gene])\n\n if population[0, -1] < best_fitness:\n np.save(\n './out/%d/generation.npy' % (nth_paramset), generation + 1\n )\n np.save(\n './out/%d/fit_param%d.npy' % (\n nth_paramset, generation + 1\n ), best_indiv\n )\n best_fitness = population[0, -1]\n np.save(\n './out/%d/best_fitness.npy' % (nth_paramset), best_fitness\n )\n np.save(\n './out/%d/count_num.npy' % (nth_paramset), generation + 1\n )\n with open('./out/%d/out.log' % (nth_paramset), mode='a') as f:\n f.write(\n 'Generation%d: Best Fitness = %e\\n' % (\n generation + 1, best_fitness\n )\n )\n if population[0, -1] <= allowable_error:\n best_indiv = decode_gene2val(population[0, :n_gene])\n best_fitness = population[0, -1]\n\n return best_indiv, best_fitness\n\n generation += 1\n\n best_indiv = decode_gene2val(population[0, :n_gene])\n best_fitness = population[0, -1]\n\n return best_indiv, best_fitness",
"def eval(self, n_iter=10, init_x_max=None):\n\n # get a random initial value for the incumbent from our search space if not specified\n if not init_x_max:\n x_max = self.search_space[np.random.randint(len(self.search_space))]\n x_max = x_max.item()\n else:\n x_max = init_x_max\n\n # for storing the best return and some parameters specifying it\n best_return = None\n best_return_x = None\n best_return_param = None\n\n for i in range(n_iter):\n\n # print some information\n print(\"\\nBO Iteration %d --> Chosen parameter: %f %s\" % (i, x_max,\n \"\" if (init_x_max or i != 0) else \"(randomly)\"))\n # evaluate the function\n y, param = self.f(x_max)\n\n # store if it is the best\n if not best_return or y > best_return:\n best_return = y\n best_return_x = x_max\n best_return_param = param\n\n # add the new sample to the dataset\n self.dataset.append([x_max, y])\n\n # get all the data samples in the dataset\n xs = np.array(self.dataset)[:, 0].reshape(-1, 1)\n ys = np.array(self.dataset)[:, 1].reshape(-1, 1)\n\n # fit the GP with the updated dataset\n if self.mode == \"linear\":\n self.gp.fit(xs, ys)\n else:\n self.gp.fit(np.log10(xs), ys)\n\n # calculate the maximum utilization and its position\n x_max, util_max, util = self._max_acq()\n\n # save the state for later plotting\n self.states.append({\"dataset\": self.dataset.copy(),\n \"util\": util,\n \"GP\": self.gp.predict(self.gp_search_space, return_std=True)})\n\n return best_return_x, best_return_param",
"def generate(generations, population, nn_param_choices):\n\n optimizer = Optimizer(nn_param_choices)\n networks = optimizer.create_population(population)\n\n # Prepare an array to record average and best losses.\n loss_t = np.empty((generations,))\n loss_bt = np.empty((generations,))\n\n data = get_stock_data()\n\n # Evolve the generation.\n for i in range(generations):\n logging.info(\"***Doing generation %d of %d***\" %\n (i + 1, generations))\n\n # Train and get loss for networks.\n train_networks(networks, data)\n\n # Get and record the average loss for this generation.\n average_loss = get_average_loss(networks)\n loss_t[i] = average_loss\n\n # Get and record the best loss for this generation.\n best_loss = get_best_loss(networks)\n loss_bt[i] = best_loss\n\n # Print out the average and best loss of each generation.\n logging.info(\"Average Generation loss: %.3f\" % (average_loss))\n logging.info('-'*80)\n logging.info(\"Best Generation loss: %.3f\" % (best_loss))\n logging.info('-'*80)\n\n # Evolve, except on the last iteration.\n if i != (generations - 1):\n # Do the evolution.\n networks = optimizer.evolve(networks)\n else:\n pass\n\n # Record elapsed time\n end_time = time.time()\n time_elapsed = end_time - start_time\n minutes, seconds = divmod(time_elapsed, 60)\n hours, minutes = divmod(minutes, 60)\n print(\" Total running time was that of %d h : %d m : %d s\" % (hours, minutes, seconds))\n\n # Sort our final population.\n networks = sorted(networks, key=lambda x: x.loss, reverse=False)\n\n # Print best network\n print \"Best Performing Network:\"\n print network_arch(networks[0].network)\n print \"Network Loss:\"\n print networks[0].loss\n\n # Save best network to hdf5 and JSON\n compile_model(networks[0].network).save(\"bestGeneticModel.hdf5\")\n print(\"Saved best model to disk as HDF5\")\n model_json = compile_model(networks[0].network).to_json()\n with open(\"model.json\", \"w\") as json_file:\n json_file.write(model_json)\n print(\"Saved best model to disk as JSON\")\n\n # Print out the top 5 networks.\n print \"Top 5 Best Performing Networks:\"\n print_networks(networks[:5])\n\n # Make and print plot with average loss history\n plt.figure()\n plt.plot(np.arange(1, generations + 1, 1), loss_t)\n plt.xlabel('Generation')\n plt.ylabel('Average loss')\n plt.grid(True)\n\n plt.figure()\n plt.plot(np.arange(1, generations + 1, 1), loss_bt)\n plt.xlabel('Generation')\n plt.ylabel('Best loss')\n plt.grid(True)\n\n plt.show()",
"def evolutionRevolution(ntrials, \n populationSize = 1000, \n generations = 25, \n retain = 0.25, \n add_random = 0.2, \n mutate = 0.01, \n elite = 0.0):\n for i in range(ntrials):\n EVevolution(index = (i+1), \n populationSize = populationSize, \n generations = generations, \n retain = retain, \n add_random = add_random, \n mutate = mutate, \n elite = elite)\n print(\"Done with trial \" + str(i+1))\n print(\"Done with everything! Hooray!\")\n return",
"def generate(self, n: int = math.inf, up_to: int = math.inf) -> None:\n with Session() as s:\n num_progs = self.num_programs(s)\n\n # Determine the termination criteria:\n if n == math.inf and up_to == math.inf:\n max_value = math.inf\n bar_max = progressbar.UnknownLength\n elif n == math.inf:\n max_value = up_to\n bar_max = max_value\n else:\n max_value = num_progs + n\n bar_max = max_value\n\n # Exit early if possible:\n if num_progs >= max_value:\n print(f\"There are already {Colors.BOLD}{num_progs}{Colors.END} \"\n \"programs in the database. Nothing to be done.\")\n return\n\n # Print a preamble message:\n num_to_generate = max_value - num_progs\n if num_to_generate < math.inf:\n estimated_time = (self.generation_time(s) / max(num_progs, 1)) * num_to_generate\n eta = humanize.naturaldelta(datetime.timedelta(seconds=estimated_time))\n print(f\"{Colors.BOLD}{num_to_generate}{Colors.END} programs are \"\n \"to be generated. Estimated generation time is \" +\n f\"{Colors.BOLD}{eta}{Colors.END}.\")\n else:\n print(f\"Generating programs {Colors.BOLD}forever{Colors.END} ...\")\n\n bar = progressbar.ProgressBar(initial_value=num_progs,\n max_value=bar_max,\n redirect_stdout=True)\n\n # The actual generation loop:\n buf = []\n while num_progs < max_value:\n buf.append(self.generate_one(s))\n\n # Update progress bar\n num_progs += 1\n bar.update(num_progs)\n\n if len(buf) >= dsmith.DB_BUF_SIZE:\n save_proxies_uniq_on(s, buf, \"sha1\")\n num_progs = self.num_programs(s)\n buf = []\n save_proxies_uniq_on(s, buf, \"sha1\")\n print(f\"All done! You now have {Colors.BOLD}{num_progs}{Colors.END} \"\n f\"{self} programs in the database\")",
"def run(var, goal, n=None):\n solns = gen_solutions(var, goal)\n return list(solns if n is None else islice(solns, 0, n))",
"def generate(generations, population, nn_param_choices, dataset):\n optimizer = Optimizer(nn_param_choices)\n networks = optimizer.create_population(population)\n # Evolve the generation.\n for i in range(generations):\n logging.info(\"***Doing generation %d of %d***\" %\n (i + 1, generations))\n # Train and get accuracy for networks.\n train_networks(networks)\n\n # Evolve, except on the last iteration.\n if i != generations - 1:\n # Do the evolution.\n networks = optimizer.evolve(networks)\n print(networks)\n\n # Sort our final population.\n networks = sorted(networks, key=lambda x: x.loss, reverse=False)\n\n # Print out the top 5 networks.\n print_networks(networks[:5])",
"def run_nsga2(random, problem, display=False, num_vars=0, use_bounder=True,\n variator=None, **kwargs) :\n \n #create dictionaries to store data about initial population, and lines\n initial_pop_storage = {}\n \n algorithm = NSGA2(random)\n algorithm.terminator = terminators.generation_termination \n if variator is None : \n algorithm.variator = [variators.blend_crossover,\n variators.gaussian_mutation]\n else :\n algorithm.variator = variator\n \n kwargs[\"num_selected\"]=kwargs[\"pop_size\"] \n if use_bounder :\n kwargs[\"bounder\"]=problem.bounder\n \n if display and problem.objectives == 2:\n algorithm.observer = [inspyred_utils.initial_pop_observer]\n else :\n algorithm.observer = inspyred_utils.initial_pop_observer\n \n final_pop = algorithm.evolve(evaluator=problem.evaluator, \n maximize=problem.maximize,\n initial_pop_storage=initial_pop_storage,\n num_vars=num_vars, \n generator=problem.generator,\n **kwargs) \n \n best_guy = final_pop[0].candidate[0:num_vars]\n best_fitness = final_pop[0].fitness\n #final_pop_fitnesses = asarray([guy.fitness for guy in algorithm.archive])\n #final_pop_candidates = asarray([guy.candidate[0:num_vars] for guy in algorithm.archive])\n final_pop_fitnesses = asarray([guy.fitness for guy in final_pop])\n final_pop_candidates = asarray([guy.candidate[0:num_vars] for guy in final_pop])\n\n if display :\n # Plot the parent and the offspring on the fitness landscape \n # (only for 1D or 2D functions)\n if num_vars == 1 :\n plot_utils.plot_results_multi_objective_1D(problem, \n initial_pop_storage[\"individuals\"], \n initial_pop_storage[\"fitnesses\"], \n final_pop_candidates, final_pop_fitnesses,\n 'Initial Population', 'Final Population',\n len(final_pop_fitnesses[0]), kwargs)\n \n elif num_vars == 2 :\n plot_utils.plot_results_multi_objective_2D(problem, \n initial_pop_storage[\"individuals\"], \n final_pop_candidates, 'Initial Population',\n 'Final Population',\n len(final_pop_fitnesses[0]), kwargs)\n\n plot_utils.plot_results_multi_objective_PF(final_pop, kwargs['fig_title'] + ' (Pareto front)')\n\n return final_pop_candidates, final_pop_fitnesses",
"def search( self ):\n problem = self._problem_instance\n select = self._selection_approach.select\n cross = self._crossover_approach\n mutate = self._mutation_approach\n replace = self._replacement_approach\n is_admissible = self._problem_instance.is_admissible\n\n #Terminal.print_box(['Genetic Algorithms - Search Started'], font_color = FontColor.Green)\n #print(f' - Crossover Probability : {self._crossover_probability}')\n #print(f' - Mutation Probability : {self._mutation_probability}')\n\n self._generation = 0\n\n # 1. Initial population\n self._population = self._initialize( problem, self._population_size )\n\n #Terminal.print_line(message = f'\\nGeneration # {0}')\n #print( f' > Fittest # { self._population.fittest.representation } - fitness: {self._population.fittest.fitness}' )\n self._population.sort()\n #for solution in self._population.solutions:\n #print(f' > {solution.id} - {solution.representation} - Fitness : {solution.fitness}')\n\n\n #2. Repeat n generations )(#1 loop )\n for generation in range( 1, self._number_of_generations ):\n\n new_population = Population( problem = problem, maximum_size = self._population_size, solution_list=[] )\n i = 0\n\n #Terminal.print_line(message = f'\\nGeneration # {generation}')\n # 2.1. Repeat until generate the next generation (#2 loop )\n while new_population.has_space:\n #print('.', end = '')\n # 2.1.1. Selection\n parent1, parent2 = select( self._population, problem.objective, self._params )\n offspring1 = deepcopy(parent1) # parent1.clone()\n offspring2 = deepcopy(parent2) # parent2.clone()\n # 2.1.2. Try Apply Crossover (depends on the crossover probability)\n if self.apply_crossover:\n offspring1, Offspring2 = cross(problem, parent1, parent2)\n #print(offspring1,offspring2)\n offspring1.id = [generation, i]\n i += 1\n offspring2.id = [generation, i]\n i += 2\n #print(f'XO')\n #print(f'P1: {parent1.id}-{parent1.representation}')\n #print(f'P2: {parent2.id}-{parent2.representation}')\n #print(f'O1: {offspring1.id}-{offspring1.representation}')\n #print(f'O2: {offspring2.id}-{offspring2.representation}')\n\n # 2.1.3. Try Apply Mutation (depends on the mutation probability)\n if self.apply_mutation:\n offspring1 = mutate( problem, offspring1 )\n #print(offspring1)\n offspring1.id = [generation, i]\n i += 1\n #print(f'MU : O1 {offspring1.id}-{offspring1.representation}')\n if self.apply_mutation:\n offspring2 = mutate( problem, offspring2 )\n #print(offspring2)\n offspring2.id = [generation, i]\n i += 1\n #print(f'MU : O2 {offspring2.id}-{offspring2.representation}')\n\n # add the offsprings in the new population (New Generation)\n if new_population.has_space and is_admissible( offspring1 ):\n problem.evaluate_solution ( offspring1 )\n new_population.solutions.append( offspring1 )\n #print(f'Added O1 - {offspring1.id}-{offspring1.representation}')\n\n if new_population.has_space and is_admissible( offspring2 ):\n problem.evaluate_solution( offspring2 )\n new_population.solutions.append( offspring2 )\n #print(f'Added O2 - {offspring2.id}-{offspring2.representation}')\n\n # 2.2. Replacement\n\n #print('\\n # NEW GENERATION *** BEFORE *** REPLACEMENT')\n #fittest = new_population.fittest\n #print( f' > Fittest # id: {fittest.id} - { fittest.representation } - fitness: {fittest.fitness} - weight: {self.calc_weights( fittest )}' )\n #for solution in new_population.solutions:\n # print(f' > {solution.id} - {solution.representation} - Fitness : {solution.fitness} - weight: {self.calc_weights( solution )}')\n\n #print(' # CURRENT GENERATION' )\n #fittest = self._population.fittest\n #print( f' > Fittest # id: {fittest.id} - { fittest.representation } - fitness: {fittest.fitness} - weight: {self.calc_weights( fittest )}' )\n #for solution in self._population.solutions:\n # print(f' > {solution.id} - {solution.representation} - Fitness : {solution.fitness} - weight: {self.calc_weights( solution )}')\n\n self._population = replace(problem, self._population, new_population )\n\n #print(' # NEW GENERATION *** AFTER *** REPLACEMENT' )\n fittest = self._population.fittest\n #print( f' > Fittest # id: {fittest.id} - { fittest.representation } - fitness: {fittest.fitness}' )\n #for solution in self._population.solutions:\n # print(f' > {solution.id} - {solution.representation} - Fitness : {solution.fitness} - weight: {self.calc_weights( solution )}')\n \n return fittest.id, fittest.representation, fittest.fitness\n #new_population = None",
"def newGeneration(self):\n \n for i in range(0, len(self.population)):\n\n parent1, parent2 = self.randomSelection()\n \n if sys.argv[3] == '1' : \n child = self.pmxCrossover(parent1, parent2)\n elif sys.argv[3] == '2' :\n child = self.uniformCrossover(parent1, parent2)\n \n if sys.argv[4] == '1' : \n mutated = self.inversionMutation(child)\n elif sys.argv[4] == '2' :\n mutated = self.reciprocalExchangeMutation(child)\n\n mutated.computeFitness()\n self.updateBest(mutated)\n self.population[i] = mutated",
"def g_iter(n):\n if n <= 3:\n return n\n else:\n g1, g2, g3 = 1, 2, 3\n for i in range(4, n+1):\n g1, g2, g3 = g2, g3, g3 + 2 * g2 + 3 * g1\n return g3",
"def _generate_nodes(self, n, new_node):\n i = 0\n while i < n:\n x, y = random.random(), random.random()\n if (x - .5) ** 2 + (y - .5) ** 2 < .5 ** 2:\n yield new_node(x, y)\n i += 1",
"def next_generation(self, survivors=5, chance_of_mutation=0.01):\n\n self.sort_by_fitness()\n # add fitness of current generation to self.fitness_history:\n self.fitness_history.append(self.individuals['Fitness'])\n # assign fittest individuals to next generation\n new_individuals = self.individuals.iloc[0:survivors, :]\n # calculate probability of individual getting selected for reproduction:\n p = np.array(self.individuals.index)\n p = self.size - p\n p = p/p.sum()\n for i in range(survivors, self.size):\n [first_parent, second_parent] = np.random.choice(self.individuals['Individual'], p=p, size=2)\n first_parent = first_parent.zip()\n second_parent = second_parent.zip()\n # set new individual as first parent and change weights and biases to values from second parent randomly\n new_individual = first_parent\n choice = np.random.choice([True, False], size=len(first_parent))\n new_individual[choice] = second_parent[choice]\n # mutate:\n mutation_array = JanniksNN(input_size=self.individuals['Individual'][0].input_size,\n hidden_layers=self.individuals['Individual'][0].layers,\n output_size=self.individuals['Individual'][0].output_size).initialize().zip()\n choice = np.random.choice([True, False], size=len(first_parent),\n p=[chance_of_mutation, 1-chance_of_mutation])\n new_individual[choice] = mutation_array[choice]\n new_individual = JanniksNN(input_size=self.individuals['Individual'][0].input_size,\n hidden_layers=self.individuals['Individual'][0].layers,\n output_size=self.individuals['Individual'][0].output_size).unzip(new_individual)\n new_individuals = new_individuals.append(pd.DataFrame(index=[i], columns=['Individual', 'Fitness'],\n data=[[new_individual, np.nan]]))\n\n self.individuals = new_individuals\n self.generation += 1",
"def main():\n\n \"Calls on the population function\"\n chr_population = population()\n\n \"Calls on the fitness function\"\n chr_pop_fitness, chr_best_fitness_index = fitness(chr_pop=chr_population)\n\n \"Calls on the rank function to generate ranking\"\n chr_ranked_population = ranking(chr_pop_fitness=chr_pop_fitness, pop=chr_population)\n\n \"Calls on the crossover and mutation function\"\n chr_crossover_mutated_population = dna(chr_pop_fitness=chr_pop_fitness,\n ranked_population=chr_ranked_population, chr_best_fitness_index=\n chr_best_fitness_index, last_pop=chr_population)\n\n show_plot(best_chromosome=chr_crossover_mutated_population[0])\n\n while not Config.stop_generation:\n\n prev_best_fit = chr_pop_fitness[chr_best_fitness_index[0], 0]\n\n chr_pop_fitness, chr_best_fitness_index = fitness(\n chr_pop=chr_crossover_mutated_population)\n\n chr_ranked_population = ranking(chr_pop_fitness=chr_pop_fitness, \n pop=chr_crossover_mutated_population)\n\n chr_crossover_mutated_population = dna(chr_pop_fitness=chr_pop_fitness,\n ranked_population=chr_ranked_population, chr_best_fitness_index=\n chr_best_fitness_index, last_pop=chr_crossover_mutated_population)\n \n print(\"Best chromosome is:\", chr_crossover_mutated_population[chr_best_fitness_index[0]]) \n \n if prev_best_fit == chr_pop_fitness[chr_best_fitness_index[0], 0]:\n Config.stop_criteria += 1\n else:\n Config.stop_criteria = 0\n\n if Config.stop_criteria >= 5:\n Config.stop_generation = True\n\n show_plot(best_chromosome=chr_crossover_mutated_population[0])\n progress = []\n for i in range(0, Config.generations+1):\n progress.append(sum(chr_crossover_mutated_population[chr_best_fitness_index[i]]))\n ave = []\n for i in range(0, Config.generations+1):\n ave.append(mean(chr_pop_fitness[i]))\n\n Config.generations += 1\n\n show_plot(best_chromosome=chr_crossover_mutated_population[0], inf_time=True)\n evolution_plot(progress)\n average_plot(ave)",
"def g_iter(n):\n if n <= 3:\n return n\n\n f1, f2, f3 = 1, 2, 3 \n for i in range(1,n):\n f1, f2, f3 = f2, f3, g(n-1) + 2*g(n-2) + 3*g(n-3)\n return f1",
"def next_generation(self, tournament_size=2,\n selection_rand=None, mutation_rand=None,\n verbose=False):\n self.generation_number += 1\n new_generation = self.__selection(tournament_size, selection_rand)\n if verbose:\n print 'New generation after selection:'\n print new_generation\n mutated_generation = self.__mutation(new_generation, mutation_rand)\n if verbose:\n print 'New generation after mutation:'\n print mutated_generation\n for chromosome in mutated_generation:\n # Discretize discreet variables\n for i in range(len(self.variables)):\n variable = self.variables[i]\n if self.definition[variable]['category'] is 'discreet':\n chromosome[i] = round(chromosome[i])\n for chromosome in mutated_generation:\n self.__add_chromosome(chromosome)\n self.__trim_generation()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Actions for returning all the s3 objects in buckets
|
def _get_s3_objects(self):
try:
s3_actions = S3Actions()
object_details_list = s3_actions.list_objects_in_buckets(self.bucket_name)
if not object_details_list:
return 'Objects not found',404
else:
return object_details_list,200
except Exception,e:
logging.error(e.message)
return 'Exception Occured',400
|
[
"def list():\n return [b.name for b in s3.buckets.all()]",
"def bucket_listing(bucket):\n response = s3.list_objects(Bucket=bucket)\n\n file_listing = []\n for file_data in response[\"Contents\"]:\n data = {\"filename\": file_data[\"Key\"], \"size\": file_data[\"Size\"]}\n file_listing.append(data)\n\n print(\"File listing: {}\".format(file_listing))\n return file_listing",
"def bucket_generator():\n bucket_collection = get_s3_resource().buckets.all()\n for bucket in bucket_collection:\n yield bucket",
"def printS3items(): \r\n session = Session(aws_access_key_id=access_key_id,\r\n aws_secret_access_key=secret_access_key)\r\n your_bucket = session.resource('s3').Bucket(Bucket_name)\r\n for s3_file in your_bucket.objects.all():\r\n print(s3_file.key)",
"def list_files(bucket: str):\n s3 = boto3.client('s3')\n contents = []\n for item in s3.list_objects(Bucket=bucket)['Contents']:\n contents.append(item)\n print(contents)\n return contents",
"def print_bucket_files(s3):\n for bucket in s3.buckets.all():\n print(bucket.name)\n for ob in bucket.objects.all():\n print(\"\\t+\" + ob.__str__())",
"def _get_all_s3_keys(bucket):\n keys = []\n\n resp = client.list_objects(Bucket=bucket)\n\n file_list = resp['Contents']\n\n for s3_key in file_list:\n keys.append(s3_key['Key'])\n\n return keys",
"def print_all_buckets(self):\n print(\"Printing All Buckets--------\")\n for bucket in self.my_s3.buckets.all():\n self.print_bucket(bucket)\n print()\n print()",
"def list():\n s3 = boto3.resource('s3')\n\n this_bucket = s3.Bucket(config.S3_ZOOM_BUCKET)\n\n keys = [x.key for x in this_bucket.objects.all() if x.key.endswith('.dzi')]\n return flask.jsonify({'keys': keys})",
"def download_s3_objects(self):\n\n _lookup_tables = {}\n\n for bucket, files in self._buckets_info.iteritems():\n for json_file in files:\n table_name = os.path.splitext(json_file)[0]\n try:\n start_time = time.time()\n s3_object = self._s3_client.Object(bucket, json_file).get()\n size_kb = round(s3_object.get('ContentLength') / 1024.0, 2)\n size_mb = round(size_kb / 1024.0, 2)\n display_size = '{}MB'.format(size_mb) if size_mb else '{}KB'.format(size_kb)\n LOGGER.info('Downloaded S3 file size %s and updated lookup table %s',\n display_size, table_name)\n _lookup_tables[table_name] = json.loads(s3_object.get('Body').read())\n except ClientError as err:\n LOGGER.error('Encounterred error while downloading %s from %s, %s',\n json_file, bucket, err.response['Error']['Message'])\n return _lookup_tables\n\n total_time = time.time() - start_time\n LOGGER.info('Downloaded S3 file %s seconds', round(total_time, 2))\n\n return _lookup_tables",
"def iterate_bucket(self, bucket, prefix, fn):\n paginator = boto3.client('s3').get_paginator('list_objects')\n for page in paginator.paginate(Bucket=bucket, Prefix=prefix):\n for obj in page['Contents']:\n key = obj['Key']\n fn(bucket, key)",
"def test_s3_bucket_objects_correct(self) -> None:\n contents = self.s3.list_objects(Bucket='asset.saintsxctf.com').get('Contents')\n self.assertTrue(all([\n len(contents) == 11,\n contents[0].get('Key') == 'amazon-app-store.png',\n contents[1].get('Key') == 'app-store.png',\n contents[2].get('Key') == 'ben-f.jpg',\n contents[3].get('Key') == 'evan-g.jpg',\n contents[4].get('Key') == 'google-play-store.svg',\n contents[5].get('Key') == 'joe-s.jpg',\n contents[6].get('Key') == 'lisa-g.jpg',\n contents[7].get('Key') == 'saintsxctf-vid.mp4',\n contents[8].get('Key') == 'saintsxctf.png',\n contents[9].get('Key') == 'thomas-c.jpg',\n contents[10].get('Key') == 'trevor-b.jpg'\n ]))",
"def list_files_s3(my_bucket, file_type):\n logging.info(\"List files recursively s3 bucket\")\n logging.info(\"Bucket Used : {}\".format(BUCKET_NAME))\n logging.info(\"File type : {}\".format(file_type))\n list_of_files_in_s3 = []\n for bucket in my_bucket.objects.all():\n list_of_files_in_s3.append(bucket.key)\n tar_video_list = [tar if tar.endswith('.tar.gz') else None for tar in list_of_files_in_s3]\n logging.info(tar_video_list)\n return tar_video_list",
"def test_api_can_get_all_bucket(self):\n res = self.client.post('/buckets/', json=self.bucket)\n self.assertEqual(res.status_code, 201)\n res = self.client.get('/buckets/')\n self.assertEqual(res.status_code, 200)\n self.assertEqual(1, res.json['total'])",
"def clean_buckets() -> list:\n helpers.starting_clean_print(RESOURCE_NAME)\n s3_client = boto3.client(BOTO3_NAME)\n buckets = get_buckets(s3_client)\n terminated_items = delete_buckets(buckets)\n helpers.finished_clean_print(RESOURCE_NAME, terminated_items)\n return terminated_items",
"def getBuckets(cos):\r\n\r\n res = []\r\n print(\"* Retrieving list of buckets\")\r\n\r\n try:\r\n buckets = cos.list_buckets()\r\n \r\n for b in buckets['Buckets']:\r\n res.append(b['Name'])\r\n\r\n return res\r\n \r\n except ClientError as err:\r\n print(\"[ERROR] Client error: {0}\\n\".format(err))\r\n \r\n except Exception as err:\r\n print(\"[ERROR] Unable to retrieve list buckets: {0}\".format(err))",
"def _get_current_keys_on_s3(self):\n logger.info('Fetching current files on S3')\n try:\n s3_objects = self.bucket.objects.filter(Prefix=self.game)\n for s3_object in s3_objects:\n s3_key = s3_object.key\n s3_etag = s3_object.e_tag.replace('\"', \"\")\n logger.debug('Found %s with tag %s' % (s3_key, s3_etag))\n self.objects_on_s3[s3_key] = s3_etag\n except:\n pass",
"def s3_list_all_folder(bucket_name):\n s3 = boto3.resource('s3')\n bucket = s3.Bucket(bucket_name)\n all_objects = [obj.key for obj in bucket.objects.all()]\n return [obj for obj in all_objects if obj[-1] == \"/\"]",
"def get_all_buckets(self):\n method = \"GET\"\n\n http_connection = HTTPConnection(\n compute_default_hostname(),\n self._identity.user_name,\n self._identity.auth_key,\n self._identity.auth_key_id\n )\n uri = compute_uri(\n \"/\".join([\"customers\", self._identity.user_name, \"collections\"]), \n )\n\n self._log.info(\"requesting {0}\".format(uri))\n try:\n response = http_connection.request(method, uri, body=None)\n except LumberyardHTTPError:\n instance = sys.exc_info()[1]\n self._log.error(str(instance))\n http_connection.close()\n raise\n \n self._log.info(\"reading response\")\n data = response.read()\n http_connection.close()\n collection_list = json.loads(data.decode(\"utf-8\"))\n\n bucket_list = list()\n for collection_dict in collection_list:\n bucket = Bucket(\n self._identity, \n collection_dict[\"name\"], \n versioning=collection_dict[\"versioning\"]\n )\n bucket_list.append(bucket)\n return bucket_list"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Convert GC bert checkpoint to Google original checkpoint 1. combine `word_embeddings` if split 2. rename scope `bert/encoder/layer_x/attention/projection/` to `bert/encoder/layer_x/attention/output/` 3. add back attention_projection_bias. 4. split `qkv_weight` to query,key,value, and add relative bias. 5. rename `GroupNorm` to `LayerNorm`. 6. add back dense layer before mlm loss.
|
def convert_gc_ckpt_to_google(ckpt_file,
output_dir=None,
include_qkv_bias=False,
dtype=tf.float32):
graph = tf.Graph()
dir_name, ckpt_name = os.path.split(os.path.abspath(ckpt_file))
if not output_dir:
output_dir = os.path.join(dir_name, "google_ckpt")
if not os.path.exists(output_dir):
os.makedirs(output_dir)
reader = pywrap_tensorflow.NewCheckpointReader(ckpt_file)
var_to_shape_map = reader.get_variable_to_shape_map()
with graph.as_default():
sess = tf.Session()
num_hidden_layers = 0
optimizer_names = ["adam", "Momentum", "lamb"] # optimizer weights
word_embeddings = []
new_variables = []
keep_vardiables = []
for tensor_name in var_to_shape_map:
print(f"Load {tensor_name}......")
# Filter the optimizer variables
if filter_optimizer(tensor_name, optimizer_names):
continue
tensor_value = tf.cast(reader.get_tensor(tensor_name), dtype=dtype)
print(f"Shape is {tensor_value.shape}")
if "word_embeddings" in tensor_name:
word_embeddings.append(tensor_name)
elif "attention" in tensor_name:
layer_idx = int(tensor_name.split("/")[2].split("_")[-1])
num_hidden_layers = max(layer_idx, num_hidden_layers)
# split query, key, value.
if "qkv_weight" in tensor_name:
hidden_size = tensor_value.shape[1]//3
query = tensor_value[:, :hidden_size]
key = tensor_value[:, hidden_size:2*hidden_size]
value = tensor_value[:, 2*hidden_size:]
qw = tf.Variable(query, name=tensor_name.replace(
"qkv_weight", "query/kernel"))
kw = tf.Variable(key, name=tensor_name.replace(
"qkv_weight", "key/kernel"))
vw = tf.Variable(value, name=tensor_name.replace(
"qkv_weight", "value/kernel"))
new_variables.extend([qw, kw, vw])
elif "qkv_bias" in tensor_name and include_qkv_bias:
hidden_size = tensor_value.shape[0]//3
query_bias = tensor_value[:hidden_size]
key_bias = tensor_value[hidden_size:2*hidden_size]
value_bias = tensor_value[2*hidden_size:]
qb = tf.Variable(query_bias, name=tensor_name.replace(
"qkv_bias", "query/bias"))
kb = tf.Variable(key_bias, name=tensor_name.replace(
"qkv_bias", "key/bias"))
vb = tf.Variable(value_bias, name=tensor_name.replace(
"qkv_bias", "value/bias"))
new_variables.extend([qb, kb, vb])
# rename projection to output
elif "projection" in tensor_name:
logging.debug(f"Rename projection......")
new_name = tensor_name.replace("projection", "output")
if "GroupNorm" in tensor_name:
logging.debug(f"Rename GroupNorm in attention ......")
new_name = new_name.replace("GroupNorm", "LayerNorm")
proj = tf.Variable(tensor_value, name=new_name)
new_variables.append(proj)
# rename other GroupNorm
elif "GroupNorm" in tensor_name:
logging.debug(f"Rename GroupNorm ......")
gn = tf.Variable(tensor_value, name=tensor_name.replace(
"GroupNorm", "LayerNorm"))
new_variables.append(gn)
else:
var = tf.get_variable(
tensor_name, shape=tensor_value.shape, dtype=dtype)
keep_vardiables.append(var)
# Combine split embeddings
word_embeddings = np.sort(word_embeddings)
embeddings_vals = [reader.get_tensor(k) for k in word_embeddings]
unit_embeddings = np.vstack(embeddings_vals)
logging.debug(
f"Concated word_embeddings shape: {unit_embeddings.shape}")
we = tf.Variable(
unit_embeddings,
dtype=dtype,
shape=unit_embeddings.shape,
name="bert/embeddings/word_embeddings")
new_variables.append(we)
saved_variables = new_variables + keep_vardiables
print("Finish concat word embeddings.")
sess.run(tf.compat.v1.global_variables_initializer())
saver = tf.compat.v1.train.Saver(var_list=saved_variables)
output_file = os.path.join(output_dir, ckpt_name)
saver.save(sess, output_file)
print("Save to :" + output_file)
|
[
"def _get_assignment_map_from_checkpoint(tvars, init_checkpoint):\n assignment_map = {}\n initialized_variable_names = {}\n\n name_to_variable = collections.OrderedDict()\n for var in tvars:\n name = var.name\n m = re.match(\"^(.*):\\\\d+$\", name)\n if m is not None:\n name = m.group(1)\n name_to_variable[name] = var\n init_vars = tf.train.list_variables(init_checkpoint)\n\n assignment_map = {\n 'bert/embeddings/word_embeddings': 'bert/word_embeddings/w',\n #'bert/embeddings/word_embeddings': 'bert_decoder/word_embeddings/w',\n #'bert/embeddings/position_embeddings':'bert_decoder/transformer_decoder/position_embedder/w',\n 'bert/embeddings/token_type_embeddings': 'bert/token_type_embeddings/w',\n 'bert/embeddings/position_embeddings':\n 'bert/encoder/position_embedder/w',\n 'bert/embeddings/LayerNorm/beta': 'bert/encoder/LayerNorm/beta',\n 'bert/embeddings/LayerNorm/gamma': 'bert/encoder/LayerNorm/gamma',\n }\n for check_name, model_name in assignment_map.items():\n initialized_variable_names[model_name] = 1\n initialized_variable_names[model_name + \":0\"] = 1\n\n for check_name, shape in init_vars:\n if check_name.startswith('bert'):\n if check_name.startswith('bert/embeddings'):\n continue\n model_name = re.sub(\n 'layer_\\d+/output/dense',\n lambda x: x.group(0).replace('output/dense', 'ffn/output'),\n check_name)\n if model_name == check_name:\n model_name = re.sub(\n 'layer_\\d+/output/LayerNorm',\n lambda x: x.group(0).replace('output/LayerNorm',\n 'ffn/LayerNorm'),\n check_name)\n if model_name == check_name:\n model_name = re.sub(\n 'layer_\\d+/intermediate/dense',\n lambda x: x.group(0).replace('intermediate/dense',\n 'ffn/intermediate'),\n check_name)\n if model_name == check_name:\n model_name = re.sub('attention/output/dense',\n 'attention/self/output', check_name)\n if model_name == check_name:\n model_name = check_name.replace('attention/output/LayerNorm',\n 'output/LayerNorm')\n assert model_name in name_to_variable.keys(),\\\n 'model name:{} not exists!'.format(model_name)\n\n assignment_map[check_name] = model_name\n initialized_variable_names[model_name] = 1\n initialized_variable_names[model_name + \":0\"] = 1\n return (assignment_map, initialized_variable_names)",
"def protobuf_from_checkpoint(model_name, checkpoint_location, export_location):\n\n im_input = tf.placeholder(shape=(None, 299, 299, 3), dtype=tf.float32, name=\"Model_Input\")\n\n if model_name == \"InceptionV3\":\n from architectures.inception_v3 import inception_v3, inception_v3_arg_scope\n model = inception_v3\n model_scope = inception_v3_arg_scope\n output_node_names = [\"Model_Input\", \"Model_Output\"]\n\n\n elif model_name == \"InceptionResnetV2\":\n from architectures.inseption_resnet_v2 import inception_resnet_v2, inception_resnet_v2_arg_scope\n model = inception_resnet_v2\n model_scope = inception_resnet_v2_arg_scope\n output_node_names = [\"Model_Input\", \"InceptionResnetV2/Logits/Dropout/Identity\"]\n\n\n else:\n raise NotImplemented(\"The only supported models are [\\\"InceptionV3\\\", \\\"InceptionResnetV2\\\"]\")\n\n\n\n slim = tf.contrib.slim\n\n with tf.Session() as sess:\n with slim.arg_scope(model_scope()):\n if model_name == \"InceptionV3\":\n logits, terminals = model(im_input, is_training=False, create_aux_logits=True, num_classes=1001)\n output = tf.squeeze(terminals['AvgPool_1a'], axis=[1, 2], name='Model_Output')\n elif model_name == \"InceptionResnetV2\":\n logits, terminals = model(im_input, is_training=False, create_aux_logits=True)\n\n saver = tf.train.Saver()\n\n # Restore variables from disk.\n saver.restore(sess, checkpoint_location)\n sess.graph.as_default()\n print(\"Model restored.\")\n\n # Write graph to tensorboard\n writer = tf.summary.FileWriter(\"./tf_summary\", graph=sess.graph)\n\n output_graph_def = tf.graph_util.convert_variables_to_constants(\n sess, # The session is used to retrieve the weights\n tf.get_default_graph().as_graph_def(), # The graph_def is used to retrieve the nodes\n output_node_names # The output node names are used to select the usefull nodes\n )\n\n with tf.gfile.GFile(export_location, \"wb\") as f:\n f.write(output_graph_def.SerializeToString())",
"def main(num_epoch, max_length, batch_size, model_name):\n # check whether uses gpu or not\n check_gpu()\n # print model info\n print('Start training BERT model.')\n print('Number of epochs: ', num_epoch)\n print('Max input length: ', max_length)\n print('Batch size: ', batch_size)\n # read in data\n df = pd.read_csv(\"s3://msia490project/processed_video_reviews.csv\").head(500000)\n df['reviewText'] = df['reviewText'].astype(str)\n df.head()\n # Encode the classes for BERT. We'll keep using the 3 labels we made earlier.\n encoder = LabelEncoder()\n df['score'] = encoder.fit_transform(df['score'])\n # Set X and y.\n X = df['reviewText']\n y = df['score']\n # Split data into training and test sets.\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n tokenizer = transformers.BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)\n # Encoding the words in the training data into vectors.\n max_length = int(max_length)\n encoded_data_train = tokenizer.batch_encode_plus(\n X_train,\n truncation=True,\n add_special_tokens=True,\n return_attention_mask=True,\n pad_to_max_length=True,\n max_length=max_length,\n return_tensors='pt'\n )\n # Encoding the words in the test data into vectors.\n encoded_data_test = tokenizer.batch_encode_plus(\n X_test,\n truncation=True,\n add_special_tokens=True,\n return_attention_mask=True,\n pad_to_max_length=True,\n max_length=max_length,\n return_tensors='pt'\n )\n # Get inputs and attention masks from previously encoded data.\n input_ids_train = encoded_data_train['input_ids']\n attention_masks_train = encoded_data_train['attention_mask']\n labels_train = torch.tensor(y_train.values)\n input_ids_test = encoded_data_test['input_ids']\n attention_masks_test = encoded_data_test['attention_mask']\n labels_test = torch.tensor(y_test.values)\n # Instantiate TensorDataset\n dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)\n dataset_test = TensorDataset(input_ids_test, attention_masks_test, labels_test)\n # Initialize the model.\n model = transformers.BertForSequenceClassification.from_pretrained(\"bert-base-uncased\",\n num_labels=5,\n output_attentions=False,\n output_hidden_states=False)\n # DataLoaders for running the model\n dataloader_train = DataLoader(dataset_train,\n sampler=RandomSampler(dataset_train),\n batch_size=int(batch_size))\n dataloader_test = DataLoader(dataset_test,\n sampler=SequentialSampler(dataset_test),\n batch_size=int(batch_size))\n # Setting hyper-parameters\n optimizer = AdamW(model.parameters(), lr=1e-5, eps=1e-8)\n epochs = int(num_epoch)\n scheduler = get_linear_schedule_with_warmup(optimizer,\n num_warmup_steps=0,\n num_training_steps=len(dataloader_train) * epochs)\n seed_val = 15\n random.seed(seed_val)\n np.random.seed(seed_val)\n torch.manual_seed(seed_val)\n torch.cuda.manual_seed_all(seed_val)\n device = torch.device('cuda')\n # train the model\n model.to(device)\n for epoch in tqdm(range(1, epochs + 1)):\n model.train()\n loss_train_total = 0\n progress_bar = tqdm(dataloader_train, desc='Epoch {:1d}'.format(epoch), leave=False, disable=False)\n for batch in progress_bar:\n model.zero_grad()\n batch = tuple(b.to(device) for b in batch)\n inputs = {'input_ids': batch[0].to(device),\n 'attention_mask': batch[1].to(device),\n 'labels': batch[2].to(device),\n }\n outputs = model(**inputs)\n loss = outputs[0]\n loss_train_total += loss.item()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n optimizer.step()\n scheduler.step()\n progress_bar.set_postfix({'training_loss': '{:.3f}'.format(loss.item() / len(batch))})\n # progress bar\n tqdm.write(f'\\nEpoch {epoch}')\n loss_train_avg = loss_train_total / len(dataloader_train)\n tqdm.write(f'Training loss: {loss_train_avg}')\n # evaluate the model\n run_evaluation(dataloader_test, model, device, encoder, epoch, model_name)\n # save the model for future use/retrain\n torch.save({\n 'epoch': num_epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n }, model_name + '.tar')",
"def extract_phobert_embeddings(model_name, tokenizer, model, data, device, keep_endpoints, num_layers):\n processed = [] # final product, returns the list of list of word representation\n tokenized_sents = [] # list of sentences, each is a torch tensor with start and end token\n list_tokenized = [] # list of tokenized sentences from phobert\n for idx, sent in enumerate(data):\n\n tokenized, tokenized_sent = tokenize_manual(model_name, sent, tokenizer)\n\n #add tokenized to list_tokenzied for later checking\n list_tokenized.append(tokenized)\n\n if len(tokenized_sent) > tokenizer.model_max_length:\n logger.error(\"Invalid size, max size: %d, got %d %s\", tokenizer.model_max_length, len(tokenized_sent), data[idx])\n raise TextTooLongError(len(tokenized_sent), tokenizer.model_max_length, idx, \" \".join(data[idx]))\n\n #add to tokenized_sents\n tokenized_sents.append(torch.tensor(tokenized_sent).detach())\n\n processed_sent = []\n processed.append(processed_sent)\n\n # done loading bert emb\n\n size = len(tokenized_sents)\n\n #padding the inputs\n tokenized_sents_padded = torch.nn.utils.rnn.pad_sequence(tokenized_sents,batch_first=True,padding_value=tokenizer.pad_token_id)\n\n features = []\n\n # Feed into PhoBERT 128 at a time in a batch fashion. In testing, the loop was\n # run only 1 time as the batch size seems to be 30\n for i in range(int(math.ceil(size/128))):\n with torch.no_grad():\n padded_input = tokenized_sents_padded[128*i:128*i+128]\n start_sentence = i * 128\n end_sentence = start_sentence + padded_input.shape[0]\n attention_mask = torch.zeros(end_sentence - start_sentence, padded_input.shape[1], device=device)\n for sent_idx, sent in enumerate(tokenized_sents[start_sentence:end_sentence]):\n attention_mask[sent_idx, :len(sent)] = 1\n # TODO: is the clone().detach() necessary?\n feature = model(padded_input.clone().detach().to(device), attention_mask=attention_mask, output_hidden_states=True)\n features += cloned_feature(feature, num_layers)\n\n assert len(features)==size\n assert len(features)==len(processed)\n\n #process the output\n #only take the vector of the last word piece of a word/ you can do other methods such as first word piece or averaging.\n # idx2+1 compensates for the start token at the start of a sentence\n offsets = [[idx2+1 for idx2, _ in enumerate(list_tokenized[idx]) if (idx2 > 0 and not list_tokenized[idx][idx2-1].endswith(\"@@\")) or (idx2==0)]\n for idx, sent in enumerate(processed)]\n if keep_endpoints:\n # [0] and [-1] grab the start and end representations as well\n offsets = [[0] + off + [-1] for off in offsets]\n processed = [feature[offset] for feature, offset in zip(features, offsets)]\n\n # This is a list of ltensors\n # Each tensor holds the representation of a sentence extracted from phobert\n return processed",
"def preprocess_bert_input(text):\n input_word_ids = tokenize_text(text)\n input_mask = tf.cast(input_word_ids > 0, tf.int64)\n input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])\n\n zeros_dims = tf.stack(tf.shape(input_mask))\n input_type_ids = tf.fill(zeros_dims, 0)\n input_type_ids = tf.cast(input_type_ids, tf.int64)\n\n return (tf.squeeze(input_word_ids,\n axis=0), tf.squeeze(input_mask, axis=0),\n tf.squeeze(input_type_ids, axis=0))",
"def convert(src: str, dst: str) -> None:\n \"mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375]\"\n assert src.endswith('pkl') or src.endswith('pth'), 'the source Detectron2 checkpoint should endswith `pkl` or `pth`.'\n mm_model = torch.load(src)\n det2_model = pickle.load(open(dst, 'rb'))\n det2_state_dict = det2_model['model']\n state_dict = {}\n print(det2_state_dict.keys())\n for name, value in mm_model['state_dict'].items():\n if 'num_batches_tracked' in name or 'teacher' in name:\n continue\n if not isinstance(value, torch.Tensor):\n value = torch.from_numpy(value)\n for m_key, d_key in map_name:\n name = name.replace('student.', '').replace(m_key, d_key)\n if value.shape != det2_state_dict[name].shape:\n print('MMdet Shape {} Detectron2 Shpae {} does not match!'.format(value.shape, det2_state_dict[name].shape))\n state_dict[name] = value\n\n ordered_state_dict = OrderedDict()\n for k in det2_state_dict.keys():\n if k not in list(state_dict.keys()):\n print('{} does not exists in MMdet!'.format(k))\n ordered_state_dict[k] = det2_state_dict[k]\n else:\n print('{}: {} in mmdet, {} in detectron2!'.format(k, torch.norm(state_dict[k]), torch.norm(torch.from_numpy(det2_state_dict[k]))))\n ordered_state_dict[k] = state_dict[k]\n\n torch.save(ordered_state_dict, './models/{}_student_converted_detectron2_style.pth'.format(os.path.basename(src).split('.')[0]))\n return",
"def compute_bert_tokenized_rep(\n context,\n target_word,\n raw_bert,\n tf_idf_weighting,\n tf_idf_dicts,\n context_idx,\n subtract_context,\n bert_cls,\n):\n\n if bert_cls:\n excluded_features = [\"SEP]\"]\n else:\n excluded_features = [\"[CLS]\", \"[SEP]\"]\n\n raw_context_rep = eval(raw_bert)\n features = raw_context_rep[\"features\"]\n\n context_token_reps_excl_target = []\n\n target_rep = None\n\n # for each word, average hidden layers\n for feature in features:\n token = feature[\"token\"]\n # print(token)\n\n if token not in excluded_features:\n if bert_cls and token == \"[CLS]\":\n cls_rep = get_bert_token_rep(\n token,\n feature,\n tf_idf_weighting,\n tf_idf_dicts,\n context_idx,\n bert_cls,\n )\n elif token != target_word.lower(): # because BERT is uncased\n token_averaged_layers = get_bert_token_rep(\n token, feature, tf_idf_weighting, tf_idf_dicts, context_idx\n )\n context_token_reps_excl_target.append(token_averaged_layers)\n else:\n target_rep = get_bert_token_rep(\n token, feature, tf_idf_weighting, tf_idf_dicts, context_idx\n )\n\n if target_rep is not None:\n sentence_vec = compute_subtract_context(\n subtract_context, target_rep, context_token_reps_excl_target\n )\n if bert_cls:\n # concat cls token representation to sentence vector\n sentence_vec = np.concatenate((sentence_vec, cls_rep), axis=0)\n\n else:\n print(\"No BERT rep for the target word\")\n sentence_vec = None\n\n return sentence_vec",
"def transformer_block(self, x, masks, scope, train=False):\n n_state = x.shape[-1].value\n\n with tf.variable_scope(scope):\n\n with tf.variable_scope('self_attention'):\n q = self.conv1d(x, 'proj_q', n_state)\n k = self.conv1d(x, 'proj_k', n_state)\n v = self.conv1d(x, 'proj_v', n_state)\n\n q = split_heads(q, self.config.n_head)\n k = split_heads(k, self.config.n_head)\n v = split_heads(v, self.config.n_head)\n\n qk = tf.matmul(q, k, transpose_b=True) # [bs, head, len, len]\n qk += tf.cast(-10000. * (1 - masks), qk.dtype)\n qk = bs.softmax(qk, scale=1.0 / np.sqrt(n_state / self.config.n_head))\n qkv = tf.matmul(qk, v) # [bs, head, len, dim]\n att = merge_heads(qkv) # [bs, len, dim*head]\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n if train and self.config.dropout > 0.0:\n att = tf.nn.dropout(att, rate=self.config.dropout)\n\n # Run a linear projection of `hidden_size` then add a residual\n # with `layer_input`.\n with tf.variable_scope('attention_output'):\n att = self.conv1d(att, 'proj_a', n_state)\n if train and self.config.dropout > 0.0:\n att = tf.nn.dropout(att, rate=self.config.dropout)\n x1 = bs.add(att, x)\n x1 = self.layer_norm(x1, name='LayerNorm_att')\n\n # The activation is only applied to the \"intermediate\" hidden layer.\n with tf.variable_scope('intermediate'):\n x2 = self.conv1d(x1, 'proj_m1', n_state * self.config.mlp_ratio, fast_gelu=True)\n\n with tf.variable_scope('output'):\n x2 = self.conv1d(x2, 'proj_m2', n_state)\n if train and self.config.dropout > 0.0:\n x2 = tf.nn.dropout(x2, rate=self.config.dropout)\n x = bs.add(x2, x1)\n x = self.layer_norm(x, name='LayerNorm_output')\n\n return x",
"def rename_key_and_reshape_tensor(pt_tuple_key, pt_tensor, random_flax_state_dict):\n\n # conv norm or layer norm\n renamed_pt_tuple_key = pt_tuple_key[:-1] + (\"scale\",)\n if (\n any(\"norm\" in str_ for str_ in pt_tuple_key)\n and (pt_tuple_key[-1] == \"bias\")\n and (pt_tuple_key[:-1] + (\"bias\",) not in random_flax_state_dict)\n and (pt_tuple_key[:-1] + (\"scale\",) in random_flax_state_dict)\n ):\n renamed_pt_tuple_key = pt_tuple_key[:-1] + (\"scale\",)\n return renamed_pt_tuple_key, pt_tensor\n elif pt_tuple_key[-1] in [\"weight\", \"gamma\"] and pt_tuple_key[:-1] + (\"scale\",) in random_flax_state_dict:\n renamed_pt_tuple_key = pt_tuple_key[:-1] + (\"scale\",)\n return renamed_pt_tuple_key, pt_tensor\n\n # embedding\n if pt_tuple_key[-1] == \"weight\" and pt_tuple_key[:-1] + (\"embedding\",) in random_flax_state_dict:\n pt_tuple_key = pt_tuple_key[:-1] + (\"embedding\",)\n return renamed_pt_tuple_key, pt_tensor\n\n # conv layer\n renamed_pt_tuple_key = pt_tuple_key[:-1] + (\"kernel\",)\n if pt_tuple_key[-1] == \"weight\" and pt_tensor.ndim == 4:\n pt_tensor = pt_tensor.transpose(2, 3, 1, 0)\n return renamed_pt_tuple_key, pt_tensor\n\n # linear layer\n renamed_pt_tuple_key = pt_tuple_key[:-1] + (\"kernel\",)\n if pt_tuple_key[-1] == \"weight\":\n pt_tensor = pt_tensor.T\n return renamed_pt_tuple_key, pt_tensor\n\n # old PyTorch layer norm weight\n renamed_pt_tuple_key = pt_tuple_key[:-1] + (\"weight\",)\n if pt_tuple_key[-1] == \"gamma\":\n return renamed_pt_tuple_key, pt_tensor\n\n # old PyTorch layer norm bias\n renamed_pt_tuple_key = pt_tuple_key[:-1] + (\"bias\",)\n if pt_tuple_key[-1] == \"beta\":\n return renamed_pt_tuple_key, pt_tensor\n\n return pt_tuple_key, pt_tensor",
"def preprocess():\n\n def extend_vocab():\n \"\"\".\"\"\"\n ground_truth_vocab = ''\n with open('gt_input.txt', 'r') as f:\n for line in f:\n ground_truth_vocab += line.strip()\n ground_truth_vocab += \" \"\n ground_truth_vocab = ground_truth_vocab[:-1]\n\n text8_vocab = ''\n with open('./text8-phrases', 'r') as f:\n for line in f:\n text8_vocab += line\n\n return text8_vocab + \" \" + ground_truth_vocab\n\n logging.info('Beginning preprocessing:')\n\n #covert text8 vocabulary to include bigram phrases\n word2vec.word2phrase('./text8', './text8-phrases', verbose=True, min_count=1)\n\n logging.info('Done creating test8-phrases.')\n\n #extend text8-phrases vocab with ground truth vocab then write to file\n full_vocab = extend_vocab()\n with open ('./text8-phrases-extra', 'w') as f:\n f.write(full_vocab)\n\n logging.info('Done creating test8-phrases-extra')\n logging.info('Done preprocessing')",
"def ewt_embed():\n import rsa.pretrained as Pre\n from sklearn.feature_extraction.text import CountVectorizer\n def container():\n return dict(test=dict(random=dict(), trained=dict()), \n ref=dict(random=dict(), trained=dict()))\n data = json.load(open(\"data/out/ewt.json\"))\n emb = dict(bow={}, bert=container(), bert24=container(), infersent=container())\n # BOW \n v = CountVectorizer(tokenizer=lambda x: x.split())\n sent_ref = [s['sent'] for s in data['ref'] ]\n sent_test = [s['sent'] for s in data['test'] ]\n v.fit( sent_ref + sent_test ) \n emb['bow']['test'] = torch.tensor(v.transform(sent_test).toarray(), dtype=torch.float)\n emb['bow']['ref'] = torch.tensor(v.transform(sent_ref).toarray(), dtype=torch.float)\n\n for split in ['test', 'ref']:\n sent = [ datum['sent'] for datum in data[split] ]\n for mode in [\"random\", \"trained\"]:\n if mode == \"random\":\n rep24 = list(Pre.encode_bert(sent, trained=False, large=True))\n rep = list(Pre.encode_bert(sent, trained=False))\n emb['infersent'][split][mode] = Pre.encode_infersent(sent, trained=False)\n else:\n rep24 = list(Pre.encode_bert(sent, trained=True, large=True))\n rep = list(Pre.encode_bert(sent, trained=True))\n emb['infersent'][split][mode] = Pre.encode_infersent(sent, trained=True)\n \n pooled24 = torch.cat([ pooled for _, pooled in rep24 ])\n pooled = torch.cat([ pooled for _, pooled in rep ])\n emb['bert24'][split][mode]['pooled'] = pooled24\n emb['bert'][split][mode]['pooled'] = pooled\n for i in range(len(rep24[0][0])):\n emb['bert24'][split][mode][i] = {}\n emb['bert24'][split][mode][i]['summed'] = torch.cat([ layers[i].sum(dim=1) for layers, _ in rep24 ], dim=0)\n emb['bert24'][split][mode][i]['first'] = torch.cat([ layers[i][:,0,:] for layers, _ in rep24], dim=0)\n emb['bert24'][split][mode][i]['last'] = torch.cat([ layers[i][:,-1,:] for layers, _ in rep24], dim=0)\n\n for i in range(len(rep[0][0])):\n emb['bert'][split][mode][i] = {}\n emb['bert'][split][mode][i]['summed'] = torch.cat([ layers[i].sum(dim=1) for layers, _ in rep ], dim=0)\n emb['bert'][split][mode][i]['first'] = torch.cat([ layers[i][:,0,:] for layers, _ in rep], dim=0)\n emb['bert'][split][mode][i]['last'] = torch.cat([ layers[i][:,-1,:] for layers, _ in rep], dim=0)\n torch.save(emb, \"data/out/ewt_embed.pt\")",
"def preprocess(self):\n # reshape the embedding layer\n # TODO:\n if self.shard_config.enable_tensor_parallelism:\n vocab_size = self.model.config.vocab_size\n world_size = self.shard_config.tensor_parallel_size\n if vocab_size % world_size != 0:\n new_vocab_size = vocab_size + world_size - vocab_size % world_size\n self.model.resize_token_embeddings(new_vocab_size)\n return self.model",
"def modify_ckpt_for_enc_adapter(ckpt):\n keys_need_modified_enc = []\n for k in list(ckpt['model'].keys()):\n if ('output' in k):\n keys_need_modified_enc.append(k)\n for mk in keys_need_modified_enc:\n ckpt['model'] = OrderedDict([\n (mk.replace('output', 'output.self_output'),\n v) if k == mk else (k, v)\n for k, v in ckpt['model'].items()\n ])",
"def infer_transformer_encoder(\n input,\n q_weight,\n q_bias,\n k_weight,\n k_bias,\n v_weight,\n v_bias,\n attn_out_weight,\n attn_out_bias,\n attn_mask,\n attn_ln_weight,\n attn_ln_bias,\n out_ln_weight,\n out_ln_bias,\n ffn_inter_weight,\n ffn_inter_bias,\n ffn_out_weight,\n ffn_out_bias,\n # sequence_id_offset,\n # trt_seqlen_offset,\n # amax_list,\n n_head,\n size_per_head,\n n_layer=12,\n is_gelu=True,\n remove_padding=False,\n int8_mode=0,\n layer_idx=0,\n allow_gemm_test=False,\n use_trt_kernel=False):\n helper = LayerHelper('fusion_encoder', **locals())\n inputs = {\n 'Input': input,\n 'SelfQueryWeight': q_weight,\n 'SelfQueryBias': q_bias,\n 'SelfKeyWeight': k_weight,\n 'SelfKeyBias': k_bias,\n 'SelfValueWeight': v_weight,\n 'SelfValueBias': v_bias,\n 'SelfAttnOutputWeight': attn_out_weight,\n 'SelfAttnOutputBias': attn_out_bias,\n \"SelfAttnMask\": attn_mask,\n 'SelfAttnOutputLayernormWeight': attn_ln_weight,\n 'SelfAttnOutputLayernormBias': attn_ln_bias,\n 'OutputLayernormWeight': out_ln_weight,\n 'OutputLayernormBias': out_ln_bias,\n 'FFNInterWeight': ffn_inter_weight,\n 'FFNInterBias': ffn_inter_bias,\n 'FFNOutputWeight': ffn_out_weight,\n 'FFNOutputBias': ffn_out_bias,\n # \"SequenceIdOffset\": sequence_id_offset,\n # \"TRTSeqLenOffset\": trt_seqlen_offset,\n # 'AmaxList': amax_list\n }\n attrs = {\n 'head_num': n_head,\n 'size_per_head': size_per_head,\n 'is_gelu': is_gelu,\n \"remove_padding\": remove_padding,\n 'int8_mode': int8_mode,\n 'num_layer': n_layer,\n 'layer_idx': layer_idx,\n 'allow_gemm_test': allow_gemm_test,\n 'use_trt_kernel': use_trt_kernel,\n }\n encoder_out = helper.create_variable(dtype=input.dtype)\n outputs = {\"EncoderOut\": encoder_out}\n\n helper.append_op(\n type='fusion_encoder', inputs=inputs, outputs=outputs, attrs=attrs)\n return encoder_out",
"def load_bert_model(output_dir,\n bert_config_file='./model/uncased_L-12_H-768_A-12/bert_config.json',\n init_checkpoint='./tuned_model/model.ckpt-2461',\n num_labels=2,\n attn_processor_fn=None):\n bert_config = modeling.BertConfig.from_json_file(bert_config_file)\n tf.logging.info('Setting output dir to {} ...'.format(output_dir))\n # I don't expect to be running this model on a TPU so whatever...\n is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2\n run_config = tf.contrib.tpu.RunConfig(\n cluster=None,\n master=None,\n model_dir=output_dir,\n save_checkpoints_steps=1000,\n tpu_config=tf.contrib.tpu.TPUConfig(\n iterations_per_loop=1000,\n num_shards=8,\n per_host_input_for_training=is_per_host))\n\n model_fn = model_fn_builder(\n bert_config=bert_config,\n num_labels=num_labels,\n init_checkpoint=init_checkpoint,\n learning_rate=1e-3,\n num_train_steps=2,\n num_warmup_steps=1,\n use_tpu=False,\n use_one_hot_embeddings=False)\n\n estimator = tf.contrib.tpu.TPUEstimator(\n use_tpu=False,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=32,\n eval_batch_size=8,\n predict_batch_size=8,\n export_to_tpu=False,\n params={'attn_processor_fn': attn_processor_fn})\n\n return estimator",
"def text_net(inputs,\r\n\t\t\t feat_layers=TextboxNet.default_params.feat_layers,\r\n\t\t\t anchor_sizes=TextboxNet.default_params.anchor_sizes,\r\n\t\t\t anchor_ratios = TextboxNet.default_params.anchor_ratios,\r\n\t\t\t normalizations=TextboxNet.default_params.normalizations,\r\n\t\t\t is_training=True,\r\n\t\t\t dropout_keep_prob=0.5,\r\n\t\t\t reuse=None,\r\n\t\t\t scope='text_box_384',\r\n\t\t\t update_feat_shapes=False):\r\n\t# End_points collect relevant activations for external use.\r\n\tend_points = {}\r\n\twith tf.variable_scope(scope, 'text_box_300', [inputs], reuse=reuse): # 300*300 384*384\r\n\t\t######################################\r\n\t\t# 前五个 Blocks,首先照搬 VGG16 架构 #\r\n\t\t# 注意这里使用 end_points 标注中间结果 #\r\n\t\t######################################\r\n\t\t# ——————————————————Original VGG-16 blocks (total 13 conv layers)———————————————————————\r\n\t\t# Block 1.\r\n\t\tnet = slim.repeat(inputs, 2, slim.conv2d, 64, [3, 3], scope='conv1') # 300 384\r\n\t\tend_points['conv1'] = net\r\n\t\tnet = slim.max_pool2d(net, [2, 2], scope='pool1') # 150\r\n\t\t# Block 2.\r\n\t\tnet = slim.repeat(net, 2, slim.conv2d, 128, [3, 3], scope='conv2') # 150 192\r\n\t\tend_points['conv2'] = net\r\n\t\tnet = slim.max_pool2d(net, [2, 2], scope='pool2') # 75\r\n\t\t# Block 3.\r\n\t\tnet = slim.repeat(net, 3, slim.conv2d, 256, [3, 3], scope='conv3') # 75 81\r\n\t\tend_points['conv3'] = net\r\n\t\tnet = slim.max_pool2d(net, [2, 2], scope='pool3') # 38\r\n\t\t# Block 4.\r\n\t\tend_point = 'conv4'\r\n\t\tnet = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], scope='conv4') # 38 40\r\n\t\tend_points[end_point] = net\r\n\t\tnet = slim.max_pool2d(net, [2, 2], scope='pool4') # 19\r\n\t\t# Block 5.\r\n\t\tnet = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], scope='conv5') # 19\r\n\t\tend_points['conv5'] = net\r\n\t\tnet = slim.max_pool2d(net, [3, 3], stride=1, scope='pool5') # 19 Pooling size 2 -> 3\r\n\r\n\t\t####################################\r\n\t\t# 后六个 Blocks,使用额外卷积层 #\r\n\t\t####################################\r\n\t\t# ————————————Additional SSD blocks.——————————————————————\r\n\t\t# Block 6: let's dilate the hell out of it! dilation -> 6\r\n\t\tnet = slim.conv2d(net, 1024, [3, 3], rate=6, scope='conv6') # 19\r\n\t\tend_points['conv6'] = net\r\n\t\t# Block 7: 1x1 conv. Because the fuck.\r\n\t\tend_point = 'conv7'\r\n\t\tnet = slim.conv2d(net, 1024, [1, 1], scope='conv7') # 19\r\n\t\tend_points[end_point] = net\r\n\r\n\t\t# Block 8/9/10/11: 1x1 and 3x3 convolutions stride 2 (except lasts).\r\n\t\tend_point = 'conv8'\r\n\t\twith tf.variable_scope(end_point):\r\n\t\t\tnet = slim.conv2d(net, 256, [1, 1], scope='conv1x1')\r\n\t\t\tnet = custom_layers.pad2d(net, pad=(1, 1))\r\n\t\t\tnet = slim.conv2d(net, 512, [3, 3], stride=2, scope='conv3x3', padding='VALID')\r\n\t\tend_points[end_point] = net # 10\r\n\r\n\t\tend_point = 'conv9'\r\n\t\twith tf.variable_scope(end_point):\r\n\t\t\tnet = slim.conv2d(net, 128, [1, 1], scope='conv1x1')\r\n\t\t\tnet = custom_layers.pad2d(net, pad=(1, 1))\r\n\t\t\tnet = slim.conv2d(net, 256, [3, 3], stride=2, scope='conv3x3', padding='VALID')\r\n\t\tend_points[end_point] = net # 5\r\n\r\n\t\tend_point = 'conv10'\r\n\t\twith tf.variable_scope(end_point):\r\n\t\t\tnet = slim.conv2d(net, 128, [1, 1], scope='conv1x1')\r\n\t\t\tnet = slim.conv2d(net, 256, [3, 3], scope='conv3x3', padding='VALID')\r\n\t\tend_points[end_point] = net # 3\r\n\r\n\t\tend_point = 'conv11'\r\n\t\twith tf.variable_scope(end_point):\r\n\t\t\tnet = slim.conv2d(net, 128, [1, 1], scope='conv1x1')\r\n\t\t\tnet = slim.conv2d(net, 256, [3, 3], scope='conv3x3', padding='VALID')\r\n\t\tend_points[end_point] = net #\r\n\r\n\t\t######################################\r\n\t\t# 每个中间层 end_points 返回中间结果 #\r\n\t\t# 将各层预测结果存入列表,返回给优化函数 #\r\n\t\t######################################\r\n\t\t# Prediction and localisations layers.\r\n\t\tpredictions = []\r\n\t\tlogits = []\r\n\t\tlocalisations = []\r\n\t\tshape_list = []\r\n\t\t# feat_layers=['conv4', 'conv7', 'conv8', 'conv9', 'conv10', 'conv11']\r\n\t\tfor i, layer in enumerate(feat_layers):\r\n\t\t\twith tf.variable_scope(layer + '_box'):\r\n\t\t\t\tcls, loc, shape = text_multibox_layer(layer,\r\n\t\t\t\t\t\t\t\t\t\t\t end_points[layer],\r\n\t\t\t\t\t\t\t\t\t\t\t anchor_sizes[i],\r\n\t\t\t\t\t\t\t\t\t\t\t anchor_ratios[i],\r\n\t\t\t\t\t\t\t\t\t\t\t normalizations[i])\r\n\t\t\tprediction_fn = slim.softmax\r\n\t\t\t# Prediction of conference and bbox location of each textbox layer.\r\n\t\t\tpredictions.append(prediction_fn(cls))\r\n\t\t\tlogits.append(cls)\r\n\t\t\tlocalisations.append(loc)\r\n\t\t\tshape_list.append(shape)\r\n\r\n\t\tif update_feat_shapes is True:\r\n\t\t\treturn predictions, localisations, logits, end_points, shape_list\r\n\t\telse:\r\n\t\t\treturn predictions, localisations, logits, end_points",
"def _get_assignment_map_from_checkpoint2(tvars, init_checkpoint):\n initialized_variable_names = {}\n\n name_to_variable = collections.OrderedDict()\n for var in tvars:\n name = var.name\n m = re.match(\"^(.*):\\\\d+$\", name)\n if m is not None:\n name = m.group(1)\n name_to_variable[name] = var\n assignment_map = {\n 'bert/embeddings/word_embeddings': 'bert_decoder/word_embeddings/w',\n 'bert/embeddings/position_embeddings':'bert_decoder/transformer_decoder/position_embedder/w',\n }\n for check_name, model_name in assignment_map.items():\n initialized_variable_names[model_name] = 1\n initialized_variable_names[model_name + \":0\"] = 1\n return (assignment_map, initialized_variable_names)",
"def upgrade_state_dict_named(self, state_dict, name):\n if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):\n weights_key = \"{}.embed_positions.weights\".format(name)\n if weights_key in state_dict:\n del state_dict[weights_key]\n state_dict[\n \"{}.embed_positions._float_tensor\".format(name)\n ] = torch.FloatTensor(1)\n\n if f\"{name}.output_projection.weight\" not in state_dict:\n if self.share_input_output_embed:\n embed_out_key = f\"{name}.embed_tokens.weight\"\n else:\n embed_out_key = f\"{name}.embed_out\"\n if embed_out_key in state_dict:\n state_dict[f\"{name}.output_projection.weight\"] = state_dict[\n embed_out_key\n ]\n if not self.share_input_output_embed:\n del state_dict[embed_out_key]\n\n for i in range(self.num_layers):\n # update layer norms\n layer_norm_map = {\n \"0\": \"self_attn_layer_norm\",\n \"1\": \"encoder_attn_layer_norm\",\n \"2\": \"final_layer_norm\",\n }\n for old, new in layer_norm_map.items():\n for m in (\"weight\", \"bias\"):\n k = \"{}.layers.{}.layer_norms.{}.{}\".format(name, i, old, m)\n if k in state_dict:\n state_dict[\n \"{}.layers.{}.{}.{}\".format(name, i, new, m)\n ] = state_dict[k]\n del state_dict[k]\n\n version_key = \"{}.version\".format(name)\n if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) <= 2:\n # earlier checkpoints did not normalize after the stack of layers\n self.layer_norm = None\n self.normalize = False\n state_dict[version_key] = torch.Tensor([1])\n\n return state_dict",
"def build_bert_classifier(bert_layer: tf.keras.layers.Layer,\n max_len: int,\n num_classes: int,\n dropout: float = 0.1,\n activation: Optional[str] = None):\n input_layer_names = [\"input_word_ids\", \"input_mask\", \"segment_ids\"]\n\n input_layers = [\n keras.layers.Input(shape=(max_len,), dtype=tf.int64, name=name)\n for name in input_layer_names\n ]\n\n converted_layers = [tf.cast(k, tf.int32) for k in input_layers]\n\n pooled_output, _ = bert_layer(converted_layers)\n output = keras.layers.Dropout(dropout)(pooled_output)\n output = keras.layers.Dense(num_classes, activation=activation)(output)\n model = keras.Model(input_layers, output)\n return model"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test simple remote submission with one pilot.
|
def test__remote_simple_submission(self):
session = rp.Session()
c = rp.Context('ssh')
c.user_id = self.test_ssh_uid
c.user_key = self.test_ssh_key
session.add_context(c)
pm = rp.PilotManager(session=session)
cpd = rp.ComputePilotDescription()
cpd.resource = self.test_resource
cpd.cores = self.test_cores
cpd.runtime = 15
cpd.sandbox = self.test_workdir
pilot = pm.submit_pilots(descriptions=cpd)
um = rp.UnitManager(session=session, scheduler='round_robin')
um.add_pilots(pilot)
cudescs = []
for _ in range(0,int(self.test_num_cus)):
cudesc = rp.ComputeUnitDescription()
cudesc.cores = 1
cudesc.executable = "/bin/sleep"
cudesc.arguments = ['10']
cudescs.append(cudesc)
cus = um.submit_units(cudescs)
for cu in cus:
assert cu is not None
assert cu.start_time is None
assert cu.stop_time is None
ret = um.wait_units(timeout=5*60)
print "Return states from wait: %s" % ret
for cu in cus:
assert cu.state == rp.DONE, "state: %s" % cu.state
assert cu.stop_time is not None
pm.cancel_pilots()
session.close()
|
[
"def test__remote_pilot_wait(self):\n session = rp.Session()\n c = rp.Context('ssh')\n c.user_id = self.test_ssh_uid\n c.user_key = self.test_ssh_key\n\n session.add_context(c)\n\n pm = rp.PilotManager(session=session)\n\n cpd = rp.ComputePilotDescription()\n cpd.resource = self.test_resource\n cpd.cores = self.test_cores\n cpd.runtime = 2\n cpd.sandbox = self.test_workdir\n\n pilot = pm.submit_pilots(descriptions=cpd)\n\n assert pilot is not None\n #assert cu.start_time is None\n #assert cu.start_time is None\n\n pilot.wait(state=rp.PMGR_ACTIVE, timeout=5*60)\n assert pilot.state == rp.PMGR_ACTIVE\n assert pilot.start_time is not None\n assert pilot.submission_time is not None\n\n\n # the pilot should finish after it has reached run_time\n pilot.wait(timeout=5*60)\n assert pilot.state == rp.DONE\n assert pilot.stop_time is not None\n\n session.close()",
"def test_post_and_get_pilot(self):\n self.create_user_and_set_token_credentials()\n new_pilot_name = 'Gaston'\n new_pilot_gender = Pilot.MALE\n new_pilot_races_count = 5\n response = self.post_pilot(\n new_pilot_name,\n new_pilot_gender,\n new_pilot_races_count)\n print(\"nPK {0}n\".format(Pilot.objects.get().pk))\n assert response.status_code == status.HTTP_201_CREATED\n assert Pilot.objects.count() == 1\n saved_pilot = Pilot.objects.get()\n assert saved_pilot.name == new_pilot_name\n assert saved_pilot.gender == new_pilot_gender\n assert saved_pilot.races_count == new_pilot_races_count\n url = reverse(\n views.PilotDetail.name,\n None,\n {saved_pilot.pk})\n authorized_get_response = self.client.get(url, format='json')\n assert authorized_get_response.status_code == status.HTTP_200_OK\n assert authorized_get_response.data['name'] == new_pilot_name\n # Clean up credentials\n self.client.credentials()\n unauthorized_get_response = self.client.get(url, format='json')\n assert unauthorized_get_response.status_code == status.HTTP_401_UNAUTHORIZED",
"def test_try_to_post_pilot_without_token(self):\n new_pilot_name = 'Unauthorized Pilot'\n new_pilot_gender = Pilot.MALE\n new_pilot_races_count = 5\n response = self.post_pilot(\n new_pilot_name,\n new_pilot_gender,\n new_pilot_races_count)\n print(response)\n print(Pilot.objects.count())\n assert response.status_code == status.HTTP_401_UNAUTHORIZED\n assert Pilot.objects.count() == 0",
"def test_send_submissions_actually_sending(self, mock_api_submitter):\n self.submitter.send_submissions = True\n measurement_set = get_measurement_set()\n self.submitter._send_submissions('tin', 'npi', measurement_set)\n mock_api_submitter.submit_to_measurement_sets_api.assert_called_once_with(\n measurement_set, patch_update=False\n )",
"def _submit(self, script):",
"def test_plan_using_post(self):\n pass",
"def test_remotehosts_post(self):\n pass",
"async def proxy_submit_submission(uuid: str, submission: list[dict[str, Union[dict, list]]]):\n credentials = redis.get(uuid)\n if credentials is None:\n raise HTTPError(401, \"Unauthorised request\")\n app_key, poll_id = credentials.decode(\"utf-8\").split(\"-\") # Get back our credentials.\n reply = put(f\"https://api.jotform.com/form/\" +\n f\"{poll_id}/submissions?apiKey={app_key}\", \n json=submission)\n return Response(content=reply.content,\n media_type=getattr(reply,\"media_type\", \"application/json\"))",
"def test_load_submission(tmp_path: Path) -> None:\n executor = local.LocalExecutor(tmp_path)\n job = executor.submit(f66, 67, y=68)\n\n submission = local.LocalJob(tmp_path, job.job_id).submission()\n # It's important that f66 isn't a local function for the equality to work\n assert submission.function is f66\n assert submission.args == (67,)\n assert submission.kwargs == {\"y\": 68}\n # Loading submission doesn't evaluate them.\n assert submission._result is None",
"def test_post_job(self):\n pass",
"def submit_problem_solution(l):\n username = login(l)\n if not username:\n l.interrupt()\n simulate_loading_problems_page(l)\n\n unlocked_problems = l.client.get(PROBLEMS_ENDPOINT).json()\n problem = random.choice(unlocked_problems)\n # Select a flag from the pool of possible instance flags:\n # probability of a correct submission is 1/(num instances)\n flag = random.choice(get_problem_flags(problem[\"pid\"]))\n l.client.post(\n SUBMISSIONS_ENDPOINT,\n json={\"pid\": problem[\"pid\"], \"key\": flag, \"method\": \"testing\"},\n headers={\"X-CSRF-Token\": l.client.cookies[\"token\"]},\n )\n release_user(username)\n l.interrupt()",
"def test_pickmup_set_paket_status_post(self):\n pass",
"def test_jsonrpc(self):\n try:\n self._run_test(\"pelix.remote.json_rpc\",\n pelix.remote.FACTORY_TRANSPORT_JSONRPC_EXPORTER,\n pelix.remote.FACTORY_TRANSPORT_JSONRPC_IMPORTER)\n except queue.Empty:\n # Process error\n self.fail(\"Remote framework took to long to reply\")",
"def testPostSubmitWork(self):\n self.data.createStudent()\n\n self.task.status = 'Claimed'\n self.task.student = self.data.profile\n # set deadline to far future\n self.task.deadline = datetime.datetime.utcnow() + datetime.timedelta(days=1)\n self.task.put()\n\n no_work = self.task.workSubmissions()\n self.assertLength(no_work, 0)\n\n work_url = 'http://www.example.com/'\n work_data = {\n 'url_to_work': work_url\n }\n\n url = '%s?submit_work' %self._taskPageUrl(self.task)\n response = self.post(url, work_data)\n\n self.assertResponseRedirect(response)\n\n one_work = self.task.workSubmissions()\n self.assertLength(one_work, 1)\n\n work = one_work[0]\n self.assertEqual(work_url, work.url_to_work)",
"def submit(self, call: \"Call\") -> \"Call\":",
"def test_new_submit_logged_in_required(self):\n\n # login to the website\n self.utils.account.login_as(self.username,self.password)\n\n po = self.catalog.load_pageobject('SupportTicketNewPage')\n po.goto_page()\n\n # name, email and description are required\n data = {\n 'name' : self.username,\n 'email' : 'hubchecktest@hubzero.org',\n 'problem' : \"hubcheck test ticket\\n%s\" % (self.fnbase),\n }\n\n # submit the ticket\n po.submit_ticket(data)\n\n po = self.catalog.load_pageobject('SupportTicketSavePage')\n self.ticket_number = po.get_ticket_number()\n\n info = po.get_error_info()\n assert len(info) == 0, \"received unexpected error: %s\" % (info)\n assert self.ticket_number is not None, \"no ticket number returned\"\n assert int(self.ticket_number) > 0, \\\n \"invalid ticket number returned: %s\" % (self.ticket_number)",
"def test_request_work_for_plugin(self):\n latest_version = _t_update_client(self.client_file)\n\n pl_1, pv_1 = _t_add_plugin(\n 'test_pl_1_name',\n os.path.join(self.plugin_dir, 'pl1_file_test.tar.gz')\n )\n pl_2, pv_2 = _t_add_plugin(\n 'test_pl_2_name',\n os.path.join(self.plugin_dir, 'pl2_file_test.tar.gz')\n )\n\n tc_fname = os.path.join(self.test_dir, 'test_case_name.dat')\n tc_data = os.urandom(8)\n tc = _t_add_test(tc_fname, tc_data)\n\n _t_add_plugin_test(pl_1, tc)\n _t_add_plugin_test(pl_2, tc)\n\n cl_plugins = json.dumps({pl_1.name:pv_1.name, pl_2.name:pv_2.name})\n\n cr = _t_client_request(plugins=cl_plugins, version=latest_version)\n _t_add_client(mac=cr['mac'])\n cr['plugin_request'] = pl_1.name\n response = self.client.post('/csserver/workrequest/', cr)\n self.assertEqual(response.status_code, 200)\n self.assertIsNone(response.get('client_version', None))\n self.assertEqual(response.get('plugin_name'), pl_1.name)\n self.assertIsNone(response.get('plugin_version', None))\n self.assertEqual(response.get('test_name', None), os.path.basename(tc_fname))\n self.assertEqual(response.get('test_hash', None), hashlib.sha1(tc_data).hexdigest())\n self.assertEqual(response.content, tc_data)\n self.assertEqual(response.get('allow_fuzzing', None), '1')\n self.assertEqual(response.get('iterations', None), '0')\n self.assertGreater(int(response.get('duration')), 0)\n\n cr['plugin_request'] = pl_2.name\n response = self.client.post('/csserver/workrequest/', cr)\n self.assertEqual(response.status_code, 200)\n self.assertIsNone(response.get('client_version', None))\n self.assertEqual(response.get('plugin_name'), pl_2.name)\n self.assertIsNone(response.get('plugin_version', None))\n self.assertEqual(response.get('test_name', None), os.path.basename(tc_fname))\n self.assertEqual(response.get('test_hash', None), hashlib.sha1(tc_data).hexdigest())\n self.assertEqual(response.content, tc_data)\n self.assertEqual(response.get('allow_fuzzing', None), '1')\n self.assertEqual(response.get('iterations', None), '0')\n self.assertGreater(int(response.get('duration')), 0)",
"def testPostButtonAssign(self):\n self.data.createMentor(self.org)\n\n profile_helper = GCIProfileHelper(self.gci, self.dev_test)\n profile_helper.createOtherUser('student@example.com').createStudent()\n student = profile_helper.profile\n\n self.task.status = 'ClaimRequested'\n self.task.student = student\n self.task.put()\n\n url = self._taskPageUrl(self.task)\n response = self.buttonPost(url, 'button_assign')\n\n # check if the task is properly assigned and a deadline has been set\n task = GCITask.get(self.task.key())\n self.assertResponseRedirect(response)\n self.assertEqual(task.status, 'Claimed')\n self.assertEqual(task.student.key(), student.key())\n self.assertTrue(task.deadline)\n\n # check if a comment has been created\n comments = self.task.comments()\n self.assertLength(comments, 1)\n self.assertMailSentToSubscribers(comments[0])\n\n # check if the update task has been enqueued\n self.assertTasksInQueue(n=1, url=self._taskUpdateUrl(task))",
"def test_submit_spam(self):\n self._mock_request(\n \"submit_spam\",\n akismet.Akismet.SUBMIT_SPAM_URL,\n akismet.Akismet.SUBMIT_SUCCESS_RESPONSE,\n {\"comment_content\": \"Bad comment\", \"comment_author\": \"viagra-test-123\"},\n )"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Test if we can wait for different pilot states.
|
def test__remote_pilot_wait(self):
session = rp.Session()
c = rp.Context('ssh')
c.user_id = self.test_ssh_uid
c.user_key = self.test_ssh_key
session.add_context(c)
pm = rp.PilotManager(session=session)
cpd = rp.ComputePilotDescription()
cpd.resource = self.test_resource
cpd.cores = self.test_cores
cpd.runtime = 2
cpd.sandbox = self.test_workdir
pilot = pm.submit_pilots(descriptions=cpd)
assert pilot is not None
#assert cu.start_time is None
#assert cu.start_time is None
pilot.wait(state=rp.PMGR_ACTIVE, timeout=5*60)
assert pilot.state == rp.PMGR_ACTIVE
assert pilot.start_time is not None
assert pilot.submission_time is not None
# the pilot should finish after it has reached run_time
pilot.wait(timeout=5*60)
assert pilot.state == rp.DONE
assert pilot.stop_time is not None
session.close()
|
[
"def wait(self, state=None, timeout=None):\n\n if not state : states = rps.FINAL\n elif not isinstance(state, list): states = [state]\n else : states = state\n\n\n if self.state in rps.FINAL:\n # we will never see another state progression. Raise an error\n # (unless we waited for this)\n if self.state in states:\n return\n\n # FIXME: do we want a raise here, really? This introduces a race,\n # really, on application level\n # raise RuntimeError(\"can't wait on a pilot in final state\")\n return self.state\n\n start_wait = time.time()\n while self.state not in states:\n\n time.sleep(0.1)\n if timeout and (timeout <= (time.time() - start_wait)):\n break\n\n if self._pmgr._terminate.is_set():\n break\n\n return self.state",
"def are_callbacks_ready(self):\n condition = True\n\n for robot_state in self.robots_state:\n condition = condition and robot_state.is_ready\n\n condition = condition and self.boxstate.is_ready\n #self.irbumper.is_ready and self.boxstate.is_ready\n\n return condition",
"def _wait_for_state(self, pid: int, state: ProcedureState, timeout=1.0, tick=0.01):\n deadline = time.time() + timeout\n sleep_secs = tick\n while self.states.get(pid, None) != state and sleep_secs > 0:\n time.sleep(sleep_secs)\n sleep_secs = mptools._sleep_secs( # pylint: disable=protected-access\n tick, deadline\n )",
"def check_waiting(self, waiting: Dict[int, List[Person]]) -> bool:\n no_people_waiting = True\n for floor in waiting:\n if len(waiting[floor]) > 0:\n no_people_waiting = False\n break\n return no_people_waiting",
"def is_ready_to_start(self):\n is_left_resolved = self.__left_participant.get_competitor() is not None\n is_right_resolved = self.__right_participant.get_competitor() is not None\n is_winner_resolved = self.__winner.get_competitor() is not None\n return is_left_resolved and is_right_resolved and not is_winner_resolved",
"def in_game(self):\n try:\n if self.p.poll() is None:\n return True\n else:\n return False\n except:\n return False",
"def isHacktoberfestCompleted(countOfPR):\n\n if (countOfPR < 4):\n print(\"You have incomplete PR's, let me do it for you\")\n while(countOfPR < 4):\n countOfPR = makePR(countOfPR)\n time.sleep(2)\n print(\"\\nYou have successfully completed 4 PR's :)\")\n return True\n return False",
"def waiting_precondition(self):\n return self._wait_precondition is True and self.triggered is False",
"def poll(cls, context):\n return super().poll(context) and (context.material.pbrtv3_material.type in cls.PBRTv3_COMPAT) and (\n not context.material.pbrtv3_material.nodetree)",
"def test_status_particles(self):\n self.assert_enter_command_mode()\n self.assert_particle_polled(Capability.ACQUIRE_STATUS, self.assert_status_particle,\n DataParticleType.TRHPH_STATUS, timeout=200)",
"def checkAvailable():\n # Need to check for R and quadprog?\n return True",
"def check_conditions(self, part=None):\n assert part is not None, 'must specify what to check'\n\n # check the BSP itself?\n if part == 'bright_star_pipeline':\n # force redo requested?\n _force_redo = self.db_entry['pipelined'][self.name]['status']['force_redo']\n # pipeline done?\n _done = self.db_entry['pipelined'][self.name]['status']['done']\n # how many times tried?\n _num_tries = self.db_entry['pipelined'][self.name]['status']['retries']\n\n go = _force_redo or ((not _done) and (_num_tries <= self.config['misc']['max_retries']))\n\n return go\n\n # Preview generation for the results of BSP processing?\n elif part == 'bright_star_pipeline:preview':\n\n # pipeline done?\n _pipe_done = self.db_entry['pipelined'][self.name]['status']['done']\n\n # failed?\n _pipe_failed = self.db_entry['pipelined'][self.name]['classified_as'] == 'failed'\n\n # preview generated?\n _preview_done = self.db_entry['pipelined'][self.name]['preview']['done']\n\n # last_modified == pipe_last_modified?\n _outdated = abs((self.db_entry['pipelined'][self.name]['preview']['last_modified'] -\n self.db_entry['pipelined'][self.name]['last_modified']).total_seconds()) > 1.0\n\n # how many times tried?\n _num_tries = self.db_entry['pipelined'][self.name]['preview']['retries']\n\n # if self.db_entry['_id'] == '3_J1144+6946_VIC_Si_o_20170607_043349.042103':\n # print(_pipe_done, _pipe_failed, _preview_done, _outdated)\n # input('WAIT!!')\n\n # print(_pipe_done, _pipe_failed, _preview_done, _outdated)\n go = (_pipe_done and (not _pipe_failed)) and ((not _preview_done) or _outdated) \\\n and (_num_tries <= self.config['misc']['max_retries'])\n\n return go\n\n # Strehl calculation for the results of BSP processing?\n elif part == 'bright_star_pipeline:strehl':\n\n # pipeline done?\n _pipe_done = self.db_entry['pipelined'][self.name]['status']['done']\n\n # failed?\n _pipe_failed = self.db_entry['pipelined'][self.name]['classified_as'] == 'failed'\n\n # Strehl calculated?\n _strehl_done = self.db_entry['pipelined'][self.name]['strehl']['status']['done']\n\n # last_modified == pipe_last_modified?\n _outdated = abs((self.db_entry['pipelined'][self.name]['strehl']['last_modified'] -\n self.db_entry['pipelined'][self.name]['last_modified']).total_seconds()) > 1.0\n\n # how many times tried?\n _num_tries = self.db_entry['pipelined'][self.name]['strehl']['status']['retries']\n\n # print(_pipe_done, _pipe_failed, _preview_done, _outdated)\n go = (_pipe_done and (not _pipe_failed)) and ((not _strehl_done) or _outdated) \\\n and (_num_tries <= self.config['misc']['max_retries'])\n\n return go\n\n # Run PCA high-contrast processing pipeline?\n elif part == 'bright_star_pipeline:pca':\n\n # pipeline done?\n _pipe_done = self.db_entry['pipelined'][self.name]['status']['done']\n\n # failed?\n _pipe_failed = self.db_entry['pipelined'][self.name]['classified_as'] == 'failed'\n\n # pca done?\n _pca_done = self.db_entry['pipelined'][self.name]['pca']['status']['done']\n\n # last_modified == pipe_last_modified?\n _outdated = abs((self.db_entry['pipelined'][self.name]['pca']['last_modified'] -\n self.db_entry['pipelined'][self.name]['last_modified']).total_seconds()) > 1.0\n\n # how many times tried?\n _num_tries = self.db_entry['pipelined'][self.name]['pca']['status']['retries']\n\n # print(_pipe_done, _pipe_failed, _preview_done, _outdated)\n go = (_pipe_done and (not _pipe_failed)) and ((not _pca_done) or _outdated) \\\n and (_num_tries <= self.config['misc']['max_retries'])\n\n return go\n\n elif part == 'bright_star_pipeline:pca:preview':\n\n # pipeline done?\n _pipe_done = self.db_entry['pipelined'][self.name]['status']['done']\n\n # failed?\n _pipe_failed = self.db_entry['pipelined'][self.name]['classified_as'] == 'failed'\n\n # pca done?\n _pca_done = self.db_entry['pipelined'][self.name]['pca']['status']['done']\n\n # pca preview done?\n _pca_preview_done = self.db_entry['pipelined'][self.name]['pca']['preview']['done']\n\n # last_modified == pipe_last_modified? (or old DB entry)\n _outdated = 'last_modified' not in self.db_entry['pipelined'][self.name]['pca']['preview'] or \\\n (abs((self.db_entry['pipelined'][self.name]['pca']['preview']['last_modified'] -\n self.db_entry['pipelined'][self.name]['last_modified']).total_seconds()) > 1.0)\n\n # how many times tried?\n _num_tries = self.db_entry['pipelined'][self.name]['pca']['preview']['retries']\n\n go = (_pipe_done and (not _pipe_failed) and _pca_done) and ((not _pca_preview_done) or _outdated) \\\n and (_num_tries <= self.config['misc']['max_retries'])\n\n return go",
"def wait_interpolation(self, controller_type=None, timeout=0):\n super(PR2TMPRobotInterface, self).wait_interpolation(\n controller_type, timeout)\n while not rospy.is_shutdown():\n self.update_robot_state(wait_until_update=True)\n if all(map(lambda j: j.name in self.ignore_joint_list or\n abs(j.joint_velocity) < 0.05\n if isinstance(j, RotationalJoint) else\n abs(j.joint_velocity) < 0.001,\n self.robot.joint_list)):\n break\n # TODO(Fix return value)\n return True",
"async def test_wait_for_checkboxes_no_pr(\n mocker, doof, test_repo, mock_labels, sleep_sync_mock\n): # pylint: disable=unused-argument\n org, repo = get_org_and_repo(test_repo.repo_url)\n mock_set, mock_get = mock_labels # pylint: disable=unused-variable\n mock_set(label=WAITING_FOR_CHECKBOXES)\n\n pr = ReleasePR(\n \"version\",\n f\"https://github.com/{org}/{repo}/pulls/123456\",\n \"body\",\n 123456,\n False,\n )\n mocker.async_patch(\"bot.get_release_pr\", side_effect=ReleaseException())\n mocker.async_patch(\"lib.get_release_pr\", side_effect=ReleaseException())\n\n me = \"mitodl_user\"\n await doof.run_release_lifecycle(\n manager=me,\n repo_info=test_repo,\n release_pr=pr,\n )\n sleep_sync_mock.assert_called_once_with(10)",
"def _is_paradox(self) -> bool:\n return (\n np.min(np.sum(self._state, axis=0)) <= 0\n or np.min(np.sum(self._state, axis=1)) <= 0\n )",
"def check_for_police(self):\n #print(\"Are there any police around?\")\n neighbors = self.environment.grid.get_neighbors(self.pos, moore=True, include_center=True, radius=self.vision)\n\n for neighbor in neighbors:\n if type(neighbor) is Police:\n # There are Police\n #print(\"Police are present, abort crime.\")\n return True\n # No police\n return False",
"def _wait_pri_launched(self):\n\n print('Waiting for spp_primary is ready ...',\n end='', flush=True)\n wait_cnt = self.WAIT_PRI_TIMEOUT / self.WAIT_PRI_INTERVAL\n cnt = 0\n is_pri_ready = False\n while cnt < wait_cnt:\n res = self.spp_ctl_cli.get('processes')\n if res is not None:\n if res.status_code == 200:\n pri_obj = None\n try:\n proc_objs = res.json()\n for proc_obj in proc_objs:\n if proc_obj['type'] == 'primary':\n pri_obj = proc_obj\n except KeyError as e:\n print('Error: {} is not defined!'.format(e))\n\n if pri_obj is not None:\n is_pri_ready = True\n break\n time.sleep(self.WAIT_PRI_INTERVAL)\n print('.', end='', flush=True)\n cnt += 1\n\n t = cnt * self.WAIT_PRI_INTERVAL\n if is_pri_ready is True:\n print(' OK! ({}[sec])'.format(t))\n else:\n print(' Timeout! ({}[sec])'.format(t))",
"def test_status(self):\n self.assert_initialize_driver()\n\n # test acquire_status particles\n self.assert_particle_generation(ProtocolEvent.ACQUIRE_STATUS,\n DataParticleType.TRHPH_STATUS,\n self.assert_status_particle,\n delay=60)",
"def _waitForLiveEpochs(self):\n return not not (self.ourEpoch or self.masterEpoch)"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Clean the member and request index to match database state. Use this function when your tests depends on having a clean index state. This is an "expensive" fixture to run, thus only use it if your tests really doesn't work without.
|
def clean_index(member_service, requests_service, db):
list(
current_search.delete(
index_list=[
Request.index._name,
Member.index._name,
ArchivedInvitation.index._name,
]
)
)
list(
current_search.create(
index_list=[
Request.index._name,
Member.index._name,
ArchivedInvitation.index._name,
]
)
)
member_service.rebuild_index(system_identity)
requests_service.rebuild_index(system_identity)
member_service.indexer.process_bulk_queue()
requests_service.indexer.process_bulk_queue()
Member.index.refresh()
Request.index.refresh()
ArchivedInvitation.index.refresh()
return True
|
[
"def setUp(self):\n self.indices_client = IndicesClient(client=self.es)\n self.indices_client.delete(index='_all')",
"def clean(self):\n # Load elastic search class\n es_instance = es.ESIntegration()\n\n # Remove indice\n es_instance.indice = 'lbdf'\n es_instance.indice_remove()",
"def test_index_delete_mock(self):\n self.es.indices.delete(index='random index')",
"def test_clean_index(self):\n tests = [\n {\n \"test_calls\": [{\"method\": httpretty.GET,\n \"uri\": \"/1\",\n \"status\": HTTPStatus.OK,\n },\n {\"method\": httpretty.GET,\n \"uri\": \"/1/_search?scroll=5m&size=1000\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rq\": utils.get_fixture(\n self.search_not_merged_logs_for_delete),\n \"rs\": utils.get_fixture(\n self.one_hit_search_rs),\n },\n {\"method\": httpretty.POST,\n \"uri\": \"/_bulk?refresh=true\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rs\": utils.get_fixture(\n self.delete_logs_rs),\n },\n {\"method\": httpretty.GET,\n \"uri\": \"/1/_search?scroll=5m&size=1000\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rq\": utils.get_fixture(self.search_merged_logs),\n \"rs\": utils.get_fixture(\n self.one_hit_search_rs),\n },\n {\"method\": httpretty.POST,\n \"uri\": \"/_bulk?refresh=true\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rs\": utils.get_fixture(self.delete_logs_rs),\n },\n {\"method\": httpretty.GET,\n \"uri\": \"/1/_search?scroll=5m&size=1000\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rq\": utils.get_fixture(self.search_not_merged_logs),\n \"rs\": utils.get_fixture(\n self.one_hit_search_rs),\n },\n {\"method\": httpretty.POST,\n \"uri\": \"/_bulk?refresh=true\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rs\": utils.get_fixture(self.index_logs_rs),\n }, ],\n \"rq\": launch_objects.CleanIndex(ids=[1], project=1),\n \"expected_count\": 1\n },\n {\n \"test_calls\": [{\"method\": httpretty.GET,\n \"uri\": \"/2\",\n \"status\": HTTPStatus.NOT_FOUND,\n }, ],\n \"rq\": launch_objects.CleanIndex(ids=[1], project=2),\n \"expected_count\": 0\n },\n {\n \"test_calls\": [{\"method\": httpretty.GET,\n \"uri\": \"/rp_1\",\n \"status\": HTTPStatus.OK,\n },\n {\"method\": httpretty.GET,\n \"uri\": \"/rp_1/_search?scroll=5m&size=1000\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rq\": utils.get_fixture(\n self.search_not_merged_logs_for_delete),\n \"rs\": utils.get_fixture(\n self.one_hit_search_rs),\n },\n {\"method\": httpretty.POST,\n \"uri\": \"/_bulk?refresh=true\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rs\": utils.get_fixture(\n self.delete_logs_rs),\n },\n {\"method\": httpretty.GET,\n \"uri\": \"/rp_1/_search?scroll=5m&size=1000\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rq\": utils.get_fixture(self.search_merged_logs),\n \"rs\": utils.get_fixture(\n self.one_hit_search_rs),\n },\n {\"method\": httpretty.POST,\n \"uri\": \"/_bulk?refresh=true\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rs\": utils.get_fixture(self.delete_logs_rs),\n },\n {\"method\": httpretty.GET,\n \"uri\": \"/rp_1/_search?scroll=5m&size=1000\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rq\": utils.get_fixture(self.search_not_merged_logs),\n \"rs\": utils.get_fixture(\n self.one_hit_search_rs),\n },\n {\"method\": httpretty.POST,\n \"uri\": \"/_bulk?refresh=true\",\n \"status\": HTTPStatus.OK,\n \"content_type\": \"application/json\",\n \"rq\": utils.get_fixture(self.index_logs_rq),\n \"rs\": utils.get_fixture(self.index_logs_rs),\n }],\n \"rq\": launch_objects.CleanIndex(ids=[1], project=1),\n \"app_config\": {\n \"esHost\": \"http://localhost:9200\",\n \"esUser\": \"\",\n \"esPassword\": \"\",\n \"esVerifyCerts\": False,\n \"esUseSsl\": False,\n \"esSslShowWarn\": False,\n \"turnOffSslVerification\": True,\n \"esCAcert\": \"\",\n \"esClientCert\": \"\",\n \"esClientKey\": \"\",\n \"appVersion\": \"\",\n \"minioRegion\": \"\",\n \"minioBucketPrefix\": \"\",\n \"filesystemDefaultPath\": \"\",\n \"esChunkNumber\": 1000,\n \"binaryStoreType\": \"minio\",\n \"minioHost\": \"\",\n \"minioAccessKey\": \"\",\n \"minioSecretKey\": \"\",\n \"esProjectIndexPrefix\": \"rp_\"\n },\n \"expected_count\": 1\n },\n {\n \"test_calls\": [{\"method\": httpretty.GET,\n \"uri\": \"/rp_2\",\n \"status\": HTTPStatus.NOT_FOUND,\n }],\n \"rq\": launch_objects.CleanIndex(ids=[1], project=2),\n \"app_config\": {\n \"esHost\": \"http://localhost:9200\",\n \"esUser\": \"\",\n \"esPassword\": \"\",\n \"esVerifyCerts\": False,\n \"esUseSsl\": False,\n \"esSslShowWarn\": False,\n \"turnOffSslVerification\": True,\n \"esCAcert\": \"\",\n \"esClientCert\": \"\",\n \"esClientKey\": \"\",\n \"appVersion\": \"\",\n \"minioRegion\": \"\",\n \"minioBucketPrefix\": \"\",\n \"filesystemDefaultPath\": \"\",\n \"esChunkNumber\": 1000,\n \"binaryStoreType\": \"minio\",\n \"minioHost\": \"\",\n \"minioAccessKey\": \"\",\n \"minioSecretKey\": \"\",\n \"esProjectIndexPrefix\": \"rp_\"\n },\n \"expected_count\": 0\n }\n ]\n\n for idx, test in enumerate(tests):\n try:\n self._start_server(test[\"test_calls\"])\n app_config = self.app_config\n if \"app_config\" in test:\n app_config = test[\"app_config\"]\n es_client = esclient.EsClient(app_config=app_config,\n search_cfg=self.get_default_search_config())\n es_client.es_client.scroll = MagicMock(return_value=json.loads(\n utils.get_fixture(self.no_hits_search_rs)))\n\n response = es_client.delete_logs(test[\"rq\"])\n\n assert test[\"expected_count\"] == response\n\n TestEsClient.shutdown_server(test[\"test_calls\"])\n except AssertionError as err:\n raise AssertionError(f'Error in the test case number: {idx}').\\\n with_traceback(err.__traceback__)",
"def test_prune_index(\n self,\n mock_client,\n mock_models,\n mock_actions,\n mock_prune,\n mock_scan,\n mock_helpers,\n ):\n # this forces one single evaluation of the outer and inner for loop\n mock_models.return_value = [ExampleModel]\n mock_scan.return_value = [\"hit\"]\n\n # _prune_hit returns an object, so bulk should be called\n mock_prune.return_value = ExampleModel()\n # should return a list with one item in it\n assert prune_index(\"foo\") == [mock_helpers.bulk.return_value]\n # should have called actions and bulk once each\n mock_actions.assert_called_once()\n mock_helpers.bulk.assert_called_once()\n\n mock_actions.reset_mock()\n mock_helpers.bulk.reset_mock()\n # if there are no objects to prune\n mock_prune.return_value = None\n # should return an empty list\n assert prune_index(\"foo\") == []\n # shouldn't call either actions or bulk (as there's no need)\n mock_actions.assert_not_called()\n mock_helpers.bulk.assert_not_called()",
"def _compact_indexes(self):\n for index in self.indexes:\n self.compact_index(index)",
"def clear_index(cls):\n index = cls.get_index()\n try:\n while True:\n doc_ids = [\n document.doc_id for document in index.get_range(ids_only=True)]\n if not doc_ids:\n break\n index.delete(doc_ids)\n except search.DeleteError:\n logging.exception('Error removing documents: ')",
"def mixed_reset(self):\n if self.repository.reset_head():\n self.index.reset(self.repository.head)",
"def test_delete_index(self):\n index = self.client.get_index(uid=\"movies_uid\")\n response = index.delete()\n assert isinstance(response, object)",
"def remove_data_from_index():\n\n from debra.models import Influencer\n to_remove = Influencer.objects.filter(\n validated_on__isnull=False,\n ).exclude(\n show_on_search=True\n ).values_list(\n 'id', flat=True\n ).order_by(\n 'id'\n )\n\n influencer_index_url = \"%s/%s/influencer/_query\" % (ELASTICSEARCH_URL, ELASTICSEARCH_INDEX)\n post_index_url = \"%s/%s/post/_query\" % (ELASTICSEARCH_URL, ELASTICSEARCH_INDEX)\n product_index_url = \"%s/%s/product/_query\" % (ELASTICSEARCH_URL, ELASTICSEARCH_INDEX)\n is_index_url = \"%s/%s/influencer_score/_query\" % (ELASTICSEARCH_URL, ELASTICSEARCH_INDEX)\n\n chunk_length = 1000\n\n ctr = 0\n\n for chunk_num in range(0, (len(to_remove) / chunk_length + (0 if len(to_remove) % chunk_length == 0 else 1) )):\n t = time.time()\n inf_ids = to_remove[chunk_num*chunk_length:(chunk_num+1)*chunk_length]\n\n # deleting postinteractions\n is_query = {\n \"query\": {\n \"filtered\": {\n \"filter\": {\n \"terms\": {\n \"_parent\": inf_ids\n }\n },\n \"query\": {\n \"match_all\": {}\n }\n }\n }\n }\n rq1 = make_es_delete_request(\n es_url=is_index_url,\n es_query_string=json.dumps(is_query)\n )\n\n # deleting products\n\n products_query = {\n \"query\": {\n \"filtered\": {\n \"filter\": {\n \"terms\": {\n \"influencer_id\": inf_ids\n }\n },\n \"query\": {\n \"match_all\": {}\n }\n }\n }\n }\n\n rq2 = make_es_delete_request(\n es_url=product_index_url,\n es_query_string=json.dumps(products_query)\n )\n\n # deleting posts\n posts_query = {\n \"query\": {\n \"filtered\": {\n \"filter\": {\n \"terms\": {\n \"_parent\": inf_ids\n }\n },\n \"query\": {\n \"match_all\": {}\n }\n }\n }\n }\n\n rq3 = make_es_delete_request(\n es_url=post_index_url,\n es_query_string=json.dumps(posts_query)\n )\n\n # deleting influencers\n influencers_query = {\n \"query\": {\n \"filtered\": {\n \"filter\": {\n \"terms\": {\n \"_id\": inf_ids\n }\n },\n \"query\": {\n \"match_all\": {}\n }\n }\n }\n }\n\n rq4 = make_es_delete_request(\n es_url=influencer_index_url,\n es_query_string=json.dumps(influencers_query)\n )\n\n ctr += len(inf_ids)\n print('Removed %s influencers, chunk (%s...%s) statuses: (%s %s %s %s), took %s seconds' % (\n ctr,\n inf_ids[0],\n inf_ids[-1],\n rq1.status_code,\n rq2.status_code,\n rq3.status_code,\n rq4.status_code,\n (time.time() - t))\n )\n\n print('Done, removed %s influencers total.' % ctr)",
"def clean_house(self):\n #if self.do_clean_house:\n # self.db_context.connection.queries = self.db_context.connection.queries[:-1]\n pass",
"def setUp(self):\n mongo.remove()",
"def _delete_from_indices(self, pipeline):\r\n s = Set(self.key()['_indices'])\r\n z = Set(self.key()['_zindices'])\r\n for index in s.members:\r\n pipeline.srem(index, self.id)\r\n for index in z.members:\r\n pipeline.zrem(index, self.id)\r\n pipeline.delete(s.key)\r\n pipeline.delete(z.key)",
"def clear_old_indexes():\n for f in os.listdir(CLUSTER_RESULT_DIR):\n if f.endswith('.idx'):\n os.remove(os.path.join(CLUSTER_RESULT_DIR, f))",
"def clean(self):\n _clean_docs(prefix=self.prefix, db=self.rdb)\n _clean_dbs(prefix=self.prefix + \"-\", srv=self.repsrv)\n _clean_dbs(prefix=self.prefix + \"-\", srv=self.srcsrv)\n _clean_dbs(prefix=self.prefix + \"-\", srv=self.tgtsrv)",
"def save_index_off(self):\r\n\t\tself.save_index = False",
"def unindex(subscriber, item_uid):",
"def _resetMatchIndex(self):\n self.schedule.reset_index(inplace=True,drop=True)",
"def delete_index(self):\n import os\n self._check_mode_is_write('delete an index')\n\n if self.has_index:\n names = [\n self.index_filename,\n self.index1_filename,\n self.sorted_filename,\n ]\n for name in names:\n if os.path.exists(name):\n print(\"Removing: %s\" % name)\n os.remove(name)\n\n self._init_index()"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.