repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
socks
socks-main/gym_socks/envs/world.py
from abc import ABC, abstractmethod from collections.abc import MutableSequence from gym_socks.envs.core import BaseDynamicalObject import numpy as np from scipy.integrate import solve_ivp class _WorldObjectMeta(type): """_WorldObject meta class. The meta class defines a virtual interface for world objects...
5,627
27.281407
88
py
socks
socks-main/gym_socks/envs/cwh.py
from abc import abstractmethod import gym from gym_socks.envs.dynamical_system import DynamicalSystem import numpy as np from scipy.constants import gravitational_constant class BaseCWH(object): """CWH base class. This class holds the shared parameters for the CWH systems, which include: * orbital ra...
12,307
29.540943
110
py
socks
socks-main/gym_socks/envs/dynamical_system.py
from abc import ABC, abstractmethod import gym from gym.utils import seeding import numpy as np from scipy.integrate import solve_ivp from gym_socks.envs.core import BaseDynamicalObject class DynamicalSystem(BaseDynamicalObject, ABC): r"""Base class for dynamical system models. Bases: :py:class:`gym_socks...
10,845
33.106918
88
py
socks
socks-main/gym_socks/envs/obstacle.py
from abc import ABC, abstractmethod from gym_socks.envs.core import BaseDynamicalObject class BaseObstacle(BaseDynamicalObject, ABC): """Base obstacle class. This class is ABSTRACT, meaning it is not meant to be instantiated directly. Instead, define a new class that inherits from BaseObstacle. All...
1,424
35.538462
197
py
socks
socks-main/gym_socks/envs/nonholonomic.py
"""Nonholonomic vehicle system.""" import gym from gym_socks.envs.dynamical_system import DynamicalSystem import numpy as np from scipy.integrate import solve_ivp class NonholonomicVehicleEnv(DynamicalSystem): """Nonholonomic vehicle system. Bases: :py:class:`gym_socks.envs.dynamical_system.DynamicalSyste...
2,827
28.768421
87
py
socks
socks-main/gym_socks/envs/__init__.py
__all__ = [ # Systems "cwh", "integrator", "nonholonomic", "point_mass", "QUAD20", "tora", # Classes "policy", ] from gym_socks.envs.cwh import CWH4DEnv from gym_socks.envs.cwh import CWH6DEnv from gym_socks.envs.integrator import NDIntegratorEnv from gym_socks.envs.nonholonomic i...
1,542
18.049383
62
py
socks
socks-main/gym_socks/envs/integrator.py
r"""ND Integrator system. An integrator system is an extremely simple dynamical system model, typically used to model a single variable and its higher order derivatives, where the input is applied to the highest derivative term, and is "integrated" upwards. .. tab-set:: .. tab-item:: Continuous Time .. ...
4,363
28.093333
83
py
socks
socks-main/gym_socks/envs/tests/test_core.py
import unittest from unittest.mock import patch import gym from gym_socks.envs import NDIntegratorEnv from gym_socks.envs.core import BaseWrapper, pre_hook_wrapper from gym_socks.envs.core import post_hook_wrapper import numpy as np def custom_pre_hook(): # print("PRE") pass def custom_post_hook(): #...
1,062
20.26
67
py
socks
socks-main/gym_socks/envs/tests/test_world.py
import unittest from unittest.mock import Base, patch import gym from gym_socks.envs import NDIntegratorEnv from gym_socks.envs.core import BaseDynamicalObject from gym_socks.policies import RandomizedPolicy from gym_socks.envs.obstacle import BaseObstacle from gym_socks.envs.world import World import numpy as np ...
1,337
21.677966
64
py
socks
socks-main/gym_socks/envs/tests/test_cwh.py
import unittest from unittest import mock from unittest.mock import patch import gym from gym_socks.envs.cwh import CWH4DEnv from gym_socks.envs.cwh import CWH6DEnv import numpy as np from scipy.constants import gravitational_constant class Test4DCWHSystem(unittest.TestCase): @classmethod def setUpClass(c...
5,142
28.728324
101
py
socks
socks-main/gym_socks/envs/tests/test_envs.py
import unittest from unittest.mock import patch import gym from gym_socks.envs.dynamical_system import DynamicalSystem from gym_socks.envs import NDIntegratorEnv from gym_socks.envs import NDPointMassEnv from gym_socks.envs import NonholonomicVehicleEnv from gym_socks.envs import PlanarQuadrotorEnv from gym_socks.en...
4,341
30.693431
88
py
socks
socks-main/gym_socks/envs/tests/test_integrator.py
import unittest from unittest.mock import patch import gym from gym_socks.envs.integrator import NDIntegratorEnv import numpy as np class TestIntegratorSystem(unittest.TestCase): @classmethod def setUpClass(cls): cls.env = NDIntegratorEnv(2) @patch.object(NDIntegratorEnv, "generate_disturbance...
2,894
26.836538
75
py
socks
socks-main/gym_socks/envs/tests/test_nonholonomic.py
import unittest from unittest.mock import patch import gym from gym_socks.envs.nonholonomic import NonholonomicVehicleEnv import numpy as np class TestNonholonomicSystem(unittest.TestCase): def test_corrects_angle(cls): system = NonholonomicVehicleEnv() system.disturbance_space = gym.spaces.Box...
631
26.478261
88
py
socks
socks-main/gym_socks/envs/tests/__init__.py
0
0
0
py
socks
socks-main/gym_socks/envs/tests/test_tora.py
import unittest from unittest.mock import patch import gym from gym_socks.envs.tora import TORAEnv import numpy as np class TestToraSystem(unittest.TestCase): def test_set_damping_coefficient(cls): env = TORAEnv() cls.assertEqual(TORAEnv._damping_coefficient, 0.1) cls.assertEqual(env.d...
438
20.95
58
py
socks
socks-main/gym_socks/policies/policy.py
"""Control policies. Note: Policies ccan be either time-invariant or time-varying, and can be either open- or closed-loop. Thus, the arguments to the :py:meth:`__call__` method should allow for ``time`` and ``state`` to be specified (if needed), and should be optional kwargs:: >>> def __call__(sel...
2,788
23.901786
87
py
socks
socks-main/gym_socks/policies/__init__.py
from gym_socks.policies.policy import BasePolicy from gym_socks.policies.policy import ConstantPolicy from gym_socks.policies.policy import RandomizedPolicy from gym_socks.policies.policy import ZeroPolicy __all__ = [ "BasePolicy", "ConstantPolicy", "RandomizedPolicy", "ZeroPolicy", ]
305
20.857143
54
py
socks
socks-main/gym_socks/policies/tests/__init__.py
0
0
0
py
socks
socks-main/gym_socks/policies/tests/test_policy.py
import unittest from unittest.mock import patch import gym import gym_socks.envs from gym_socks.policies import BasePolicy from gym_socks.policies import ConstantPolicy from gym_socks.policies import RandomizedPolicy from gym_socks.policies import ZeroPolicy import numpy as np class TestBasePolicy(unittest.TestC...
1,631
28.142857
88
py
socks
socks-main/gym_socks/algorithms/base.py
from abc import ABC, abstractmethod import numpy as np class ClassifierMixin(ABC): """Base class for algorithms. This class is ABSTRACT, meaning it is not meant to be instantiated directly. Instead, define a new class that inherits from ClassifierMixin. The ClassifierMixin is meant to mimic the skl...
2,167
25.765432
87
py
socks
socks-main/gym_socks/algorithms/__init__.py
__all__ = ["control", "identification", "reach"]
49
24
48
py
socks
socks-main/gym_socks/algorithms/kernel.py
from abc import ABC, abstractmethod import numpy as np from numpy.linalg import inv from scipy.linalg import block_diag from functools import partial from gym_socks.algorithms.base import RegressorMixin from sklearn.preprocessing import normalize def _regression_score(y_true, y_pred): return np.abs(np.asarray...
2,357
24.912088
85
py
socks
socks-main/gym_socks/algorithms/reach/separating_kernel.py
"""Separating kernel classifier. Separating kernel classifier, useful for forward stochastic reachability analysis. """ from functools import partial from gym_socks.algorithms.base import ClassifierMixin from gym_socks.kernel.metrics import abel_kernel from gym_socks.kernel.metrics import regularized_inverse impor...
3,278
27.513043
265
py
socks
socks-main/gym_socks/algorithms/reach/common.py
import gym import numpy as np from gym_socks.utils import indicator_fn def _fht_step(Y, V, constraint_set, target_set): r"""First-hitting time problem backward recursion step. This function implements the backward recursion step for the first-hitting time problem, given by: .. math:: V_{t...
3,153
30.54
87
py
socks
socks-main/gym_socks/algorithms/reach/kernel_sr_max.py
"""Kernel-based stochastic reachability. Maximal stochastic reachability. """ from functools import partial import numpy as np from gym_socks.algorithms.base import RegressorMixin from gym_socks.algorithms.reach.common import _fht_step from gym_socks.algorithms.reach.common import _tht_step from gym_socks.kernel....
11,711
29.185567
88
py
socks
socks-main/gym_socks/algorithms/reach/__init__.py
__all__ = [ "maximally_safe", "monte_carlo", "random_fourier_features", "stochastic_reachability", ] from gym_socks.algorithms.reach.kernel_sr_max import KernelMaximalSR from gym_socks.algorithms.reach.kernel_sr_max import kernel_sr_max from gym_socks.algorithms.reach.kernel_sr import KernelSR from gym...
455
34.076923
83
py
socks
socks-main/gym_socks/algorithms/reach/kernel_sr.py
"""Kernel-based stochastic reachability. Stochastic reachability seeks to compute the likelihood that a system will satisfy pre-specified safety constraints. """ from functools import partial import numpy as np from gym_socks.algorithms.base import RegressorMixin from gym_socks.algorithms.reach.common import _fht_...
10,706
29.767241
88
py
socks
socks-main/gym_socks/algorithms/reach/monte_carlo.py
"""Stochastic reachability using Monte-Carlo.""" import numpy as np from gym_socks.algorithms.base import RegressorMixin from gym_socks.algorithms.reach.common import _tht_step, _fht_step from gym_socks.envs.dynamical_system import DynamicalSystem from gym_socks.policies import BasePolicy from gym_socks.sampling im...
8,471
30.494424
88
py
socks
socks-main/gym_socks/algorithms/reach/tests/__init__.py
0
0
0
py
socks
socks-main/gym_socks/algorithms/reach/tests/test_monte_carlo.py
import unittest from unittest import mock from unittest.mock import patch import gym import gym_socks from scipy.constants.codata import unit from gym_socks.envs.integrator import NDIntegratorEnv from gym_socks.envs.dynamical_system import DynamicalSystem from gym_socks.policies import ZeroPolicy from gym_socks.poli...
4,912
30.292994
86
py
socks
socks-main/gym_socks/algorithms/control/kernel_control_bwd.py
r"""Backward in time stochastic optimal control. The backward in time (dynamic programming) stochastic optimal control algorithm computes the control actions working backward in time from the terminal time step to the current time step. It computes a sequence of "value" functions, and then as the system evolves forwar...
13,508
29.632653
326
py
socks
socks-main/gym_socks/algorithms/control/common.py
"""Common functions for kernel control algorithms. This file contains common functions used by the kernel optimal control algorithms, and implements an LP solver to compute the probability vector :math:`\gamma`. This functionality is accessed via the :py:func:``compute_solution`` function, which serves as a single ent...
5,934
32.531073
151
py
socks
socks-main/gym_socks/algorithms/control/kernel_control_fwd.py
r"""Forward in time stochastic optimal control. The policy is specified as a sequence of stochastic kernels :math:`\pi = \lbrace \pi_{0}, \pi_{1}, \ldots, \pi_{N-1} \rbrace`. At each time step, the problem seeks to solve a constrained optimization problem. .. math:: :label: optimization_problem \min_{\pi_{t}...
7,516
30.451883
88
py
socks
socks-main/gym_socks/algorithms/control/__init__.py
__all__ = ["kernel_control_bwd", "kernel_control_fwd"] from gym_socks.algorithms.control.kernel_control_bwd import KernelControlBwd from gym_socks.algorithms.control.kernel_control_bwd import kernel_control_bwd from gym_socks.algorithms.control.kernel_control_fwd import KernelControlFwd from gym_socks.algorithms.cont...
369
45.25
78
py
socks
socks-main/gym_socks/algorithms/control/tests/__init__.py
0
0
0
py
socks
socks-main/gym_socks/algorithms/identification/kernel_linear_id.py
"""Kernel-based linear system identification. The algorithm uses a concatenated state space representation to compute the state and input matrices given a sample of system observations. Uses the matrix inversion lemma and a linear kernel to compute the linear relationship between observations. """ from functools imp...
5,311
27.10582
88
py
socks
socks-main/gym_socks/algorithms/identification/__init__.py
__all__ = ["kernel_linear_id"] from gym_socks.algorithms.identification.kernel_linear_id import kernel_linear_id from gym_socks.algorithms.identification.kernel_linear_id import KernelLinearId
194
38
81
py
socks
socks-main/gym_socks/algorithms/identification/tests/test_kernel_linear_id.py
import unittest from unittest import mock from unittest.mock import patch import gym import numpy as np from gym_socks.algorithms.identification.kernel_linear_id import KernelLinearId from gym_socks.envs import CWH4DEnv from gym_socks.envs import CWH6DEnv from gym_socks.policies import RandomizedPolicy from gym_soc...
2,288
28.346154
86
py
socks
socks-main/gym_socks/algorithms/identification/tests/__init__.py
0
0
0
py
socks
socks-main/gym_socks/sampling/sample.py
"""Sampling methods.""" from inspect import isgeneratorfunction from functools import partial, wraps from itertools import islice import gym from gym_socks.envs.dynamical_system import DynamicalSystem def sample_generator(fun): """Sample generator decorator. Converts a sample function into a generator fun...
4,838
22.837438
87
py
socks
socks-main/gym_socks/sampling/transform.py
import numpy as np def transpose_sample(sample): """Transpose the sample. By default, a sample should be a list of tuples of the form:: S = [(x_1, y_1), ..., (x_n, y_n)] For most algorithms, we need to isolate the sample components (e.g. all x's). This function converts a sample from a list...
1,312
24.745098
87
py
socks
socks-main/gym_socks/sampling/__init__.py
"""Sampling methods. This module contains a collection of sampling methods. The core principle is to define a function that returns a single observation (either via return or yield) from a probability measure. Then, using the decorator ``sample_generator``, a function that returns a single observation can be converted...
1,748
32.634615
88
py
socks
socks-main/gym_socks/sampling/tests/__init__.py
0
0
0
py
socks
socks-main/gym_socks/sampling/tests/test_sample.py
import unittest from unittest.mock import patch import gym from gym_socks.envs import NDIntegratorEnv from gym_socks.policies import ConstantPolicy from gym_socks.policies import RandomizedPolicy from gym_socks.sampling.sample import sample_generator from gym_socks.sampling.sample import sample from gym_socks.sampli...
8,707
27.644737
87
py
socks
socks-main/gym_socks/kernel/probability.py
import numpy as np from functools import partial from gym_socks.kernel.metrics import regularized_inverse from gym_socks.kernel.metrics import rbf_kernel def maximum_mean_discrepancy( X, Y, kernel_fn=None, biased: bool = False, squared: bool = False ): r"""Maximum mean discrepancy between two empirical dist...
6,172
27.845794
88
py
socks
socks-main/gym_socks/kernel/metrics.py
""" Kernel functions and helper utilities for kernel-based calculations. Most of the commonly-used kernel functions are already implemented in sklearn.metrics.pairwise. The RBF kernel and pairwise Euclidean distance function is re-implemented here as an alternative, in case sklearn is unavailable. Most, if not all of ...
7,441
25.483986
87
py
socks
socks-main/gym_socks/kernel/__init__.py
__all__ = ["metrics", "probability"]
37
18
36
py
socks
socks-main/gym_socks/kernel/tests/test_kernel.py
import unittest from functools import partial import gym import gym_socks.kernel.metrics import numpy as np from sklearn.metrics.pairwise import linear_kernel from sklearn.metrics.pairwise import polynomial_kernel from sklearn.metrics.pairwise import rbf_kernel from sklearn.metrics.pairwise import laplacian_kernel...
4,816
31.547297
86
py
socks
socks-main/gym_socks/kernel/tests/__init__.py
0
0
0
py
socks
socks-main/gym_socks/utils/batch.py
def generate_batches(num_elements, batch_size): """Generate batches. Batch generation function to split a list into smaller batches (slices). Generates `slice` objects, which can be iterated over in a for loop. Args: num_elements: Length of the list. batch_size: Maximum size of the bat...
733
24.310345
86
py
socks
socks-main/gym_socks/utils/logging.py
from tqdm.auto import tqdm _progress_fmt = "|{bar:30}| {elapsed_ms}" """The format of the tqdm progress bar. The format of the progress bar used by the `ms_tqdm` custom progress bar class. """ class ms_tqdm(tqdm): """A custom tqdm progress bar implementation. This is a simple modification to the tqdm progr...
856
24.969697
84
py
socks
socks-main/gym_socks/utils/space.py
import gym import numpy as np from numpy.core.numeric import isscalar def subspace( space: gym.spaces.Box, low, high, shape: tuple = None, seed: int = None ) -> gym.spaces.Box: # if shape is not None: # shape = tuple(shape) # # assert same as space or less than # assert space.shape ...
813
22.257143
79
py
socks
socks-main/gym_socks/utils/grid.py
import gym import numpy as np from functools import reduce from operator import mul def make_grid_from_ranges(xi: list) -> list: """Create a grid of points from a list of ranges. Args: xi: List of ranges. Returns: Grid of points (the product of all points in ranges). Example: ...
3,138
24.942149
88
py
socks
socks-main/gym_socks/utils/__init__.py
__all__ = ["logging", "normalize", "indicator_fn", "generate_batches"] import gym import numpy as np def normalize(v: np.ndarray) -> np.ndarray: """Normalize. Small utility function for normalizing a matrix or a vector. Divides the matrix (vector) by the sum of the matrix rows (vector). Used primarily ...
1,489
26.090909
88
py
socks
socks-main/gym_socks/utils/tests/test_batch.py
import unittest import gym from gym_socks.utils.batch import generate_batches import numpy as np class TestGenerateBatches(unittest.TestCase): """Test generate_batches.""" def test_generate_batches(cls): """Test generate batches.""" idx = np.arange(10) batches = generate_batches(n...
1,349
31.142857
80
py
socks
socks-main/gym_socks/utils/tests/test_grid.py
import unittest import gym import gym_socks.utils import numpy as np from gym_socks.utils.grid import make_grid_from_ranges from gym_socks.utils.grid import make_grid_from_space from gym_socks.utils.grid import grid_size_from_ranges from gym_socks.utils.grid import grid_size_from_space class TestGrid(unittest.Tes...
2,189
27.815789
83
py
socks
socks-main/gym_socks/utils/tests/__init__.py
0
0
0
py
socks
socks-main/gym_socks/utils/tests/test_utils.py
import unittest import gym import gym_socks.utils import numpy as np class TestNormalize(unittest.TestCase): def test_normalize(cls): """Test normalize function.""" # Single point. points = [1.0, 2.0] groundTruth = [0.33333333, 0.66666667] normalize_result = gym_socks.u...
2,014
35.636364
86
py
ndcurves
ndcurves-master/python/test/optimization.py
import unittest from numpy import array, matrix, zeros from numpy.linalg import norm from ndcurves.optimization import ( constraint_flag, generate_integral_problem, integral_cost_flag, problem_definition, setup_control_points, ) class TestProblemDefinition(unittest.TestCase): # generate prob...
1,337
31.634146
82
py
ndcurves
ndcurves-master/python/test/test.py
import os import unittest from math import sqrt import numpy as np from numpy import array, array_equal, isclose, random, zeros from numpy.linalg import norm import pickle from ndcurves import ( CURVES_WITH_PINOCCHIO_SUPPORT, Quaternion, SE3Curve, SO3Linear, bezier, bezier3, convert_to_bezi...
66,945
39.721411
88
py
ndcurves
ndcurves-master/python/test/test-sinusoidal.py
# Copyright (c) 2020, CNRS # Authors: Pierre Fernbach <pfernbac@laas.fr> import unittest from ndcurves import sinusoidal import numpy as np from numpy import array, isclose class SinusoidalCurveTest(unittest.TestCase): def test_constructor(self): # default constructor c = sinusoidal() sel...
6,764
33.515306
88
py
ndcurves
ndcurves-master/python/test/test-constant.py
# Copyright (c) 2020, CNRS # Authors: Pierre Fernbach <pfernbac@laas.fr> import unittest from ndcurves import constant, constant3 import numpy as np from numpy import array, array_equal class ConstantCurveTest(unittest.TestCase): def test_constructor(self): # default constructor c = constant() ...
5,146
29.636905
67
py
ndcurves
ndcurves-master/python/test/test-curve-constraints.py
# Copyright (c) 2020, CNRS # Authors: Pierre Fernbach <pfernbac@laas.fr> import unittest from ndcurves import curve_constraints import pickle from numpy import array class CurveConstraintsTest(unittest.TestCase): def test_operator_equal(self): c = curve_constraints(3) c.init_vel = array([[0.0, 1....
2,298
35.492063
71
py
ndcurves
ndcurves-master/python/test/test-minjerk.py
# Copyright (c) 2020, CNRS # Authors: Pierre Fernbach <pfernbac@laas.fr> import unittest from ndcurves import polynomial import numpy as np from numpy import array, isclose class MinJerkCurveTest(unittest.TestCase): def test_constructors(self): # constructor from two points init = array([1, 23.0,...
1,835
33.641509
62
py
ndcurves
ndcurves-master/python/test/registration.py
import unittest class TestRegistration(unittest.TestCase): """Check registration incompatibilities. ref https://github.com/stack-of-tasks/eigenpy/issues/83 ref https://gitlab.laas.fr/loco-3d/curves/-/issues/6 """ def test_pinocchio_then_curves(self): import pinocchio import ndcur...
697
23.928571
59
py
ndcurves
ndcurves-master/python/test/notebook.py
import unittest from numpy import array, dot, identity, zeros # importing the bezier curve class from ndcurves import bezier # dummy methods def plot(*karrgs): pass class TestNotebook(unittest.TestCase): # def print_str(self, inStr): # print inStr # return def test_notebook(self): ...
6,327
32.13089
88
py
ndcurves
ndcurves-master/python/test/sandbox/fit.py
import numpy as np from numpy import array, identity from curves import bezier, curve_constraints from curves.optimization import ( constraint_flag, problem_definition, setup_control_points, ) from .plot_bezier import plotBezier, plt from qp import quadprog_solve_qp, to_least_square np.set_printoptions(fo...
3,253
27.051724
86
py
ndcurves
ndcurves-master/python/test/sandbox/test_var.py
from numpy import array from curves import bezierVar __EPS = 1e-6 waypointsA = array( [ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], ] ).transpose() waypointsb = array([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]])...
673
23.071429
69
py
ndcurves
ndcurves-master/python/test/sandbox/varBezier.py
from numpy import array, zeros from curves import bezier, bezierVar __EPS = 1e-6 _zeroMat = array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]).transpose() _I3 = array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]).transpose() _zeroVec = array([[0.0, 0.0, 0.0]]).transpose() def createControlPoint(val...
2,375
31.108108
81
py
ndcurves
ndcurves-master/python/test/sandbox/qp_traj/convex_hull.py
import numpy as np from numpy import array, cross from numpy.linalg import norm from scipy.spatial import ConvexHull def genConvexHullLines(points): hull = ConvexHull(points) lineList = [points[el] for el in hull.vertices] + [points[hull.vertices[0]]] lineList = [array(el[:2].tolist() + [0.0]) for el in l...
1,398
27.55102
80
py
ndcurves
ndcurves-master/python/test/sandbox/qp_traj/test_cord.py
import uuid import matplotlib.pyplot as plt import numpy as np from numpy import array, cross, identity, vstack, zeros from numpy.linalg import norm from .convex_hull import genFromLine from .plot_cord import plotBezier, plotControlPoints, plotPoly from .qp import quadprog_solve_qp from .qp_cord import accelerationco...
4,459
27.961039
84
py
ndcurves
ndcurves-master/python/test/sandbox/qp_traj/qp_cord.py
from numpy import array, vstack, zeros from .varBezier import varBezier __EPS = 1e-6 # ### helpers for stacking matrices #### def concat(m1, m2): if m1 is None: return m2 return vstack([m1, m2]).reshape([-1, m2.shape[-1]]) def concatvec(m1, m2): if m1 is None: return m2 return arra...
2,674
29.397727
82
py
ndcurves
ndcurves-master/python/test/sandbox/qp_traj/plot_cord.py
import matplotlib.pyplot as plt import numpy as np def plotBezier(bez, color): step = 100.0 points1 = np.array( [ (bez(i / step * bez.max())[0][0], bez(i / step * bez.max())[1][0]) for i in range(int(step)) ] ) x = points1[:, 0] y = points1[:, 1] plt.plo...
889
23.054054
79
py
ndcurves
ndcurves-master/python/test/sandbox/qp_traj/varBezier.py
from numpy import array, zeros from curves import bezier, bezierVar __EPS = 1e-6 _zeroMat = array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]).transpose() _I3 = array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]).transpose() _zeroVec = array([[0.0, 0.0, 0.0]]).transpose() def createControlPoint(val...
2,375
30.68
81
py
ndcurves
ndcurves-master/python/test/sandbox/qp_traj/qp.py
from numpy import array, dot, hstack, identity, vstack import quadprog def quadprog_solve_qp(P, q, G=None, h=None, C=None, d=None): """ min (1/2)x' P x + q' x subject to G x <= h subject to C x = d """ qp_G = 0.5 * (P + P.T) # make sure P is symmetric qp_a = -q if C is not None: ...
1,905
24.413333
68
py
ndcurves
ndcurves-master/python/ndcurves/optimization.py
#!/usr/bin/env python # Copyright (c) 2019 CNRS # Author : Steve Tonneau from .ndcurves.optimization import * # noqa
119
19
44
py
ndcurves
ndcurves-master/python/ndcurves/plot.py
import matplotlib.pyplot as plt import numpy as np from numpy import array from .ndcurves import bezier def plotControlPoints2D(bez, axes=[0, 1], color="r", ax=None): wps = [bez.waypointAtIndex(i) for i in range(bez.nbWaypoints)] x = np.array([wp[axes[0]] for wp in wps]) y = np.array([wp[axes[1]] for wp ...
2,604
27.944444
79
py
ndcurves
ndcurves-master/python/ndcurves/__init__.py
#!/usr/bin/env python # Copyright (c) 2019 CNRS # Author : Steve Tonneau from .ndcurves import * # noqa
106
16.833333
31
py
perm_hmm
perm_hmm-master/setup.py
import setuptools with open("README.md", "r") as fh: long_desc = fh.read() setuptools.setup( name="perm_hmm", version="0.0.1", author="Shawn Geller", author_email="shawn.geller@colorado.edu", description="Computes misclassification rates for repeated measurement" " schemes", ...
603
26.454545
75
py
perm_hmm
perm_hmm-master/adapt_hypo_test/__init__.py
r"""Computes optimal policies for a two state model with transition matrix equal to identity. Because the transition matrix is trivial, this reduces to an adaptive hypothesis testing problem. To solve it, we observe that the number of possible belief states is polynomial in the number of steps. We use :math:`\Pr(E)` ...
4,854
43.541284
125
py
perm_hmm
perm_hmm-master/adapt_hypo_test/tests/util_tests.py
import pytest from adapt_hypo_test.two_states.util import * @pytest.mark.parametrize("p",[ (.1,), (np.arange(0, 1, .1)) ]) def test_log_odds_to_log_probs(p): p = .1 x = np.log(p/(1-p)) lps = log_odds_to_log_probs(x) lps2 = np.log([1-p, p]) assert np.allclose(lps, lps2) #%% @pytest.mark.p...
529
19.384615
52
py
perm_hmm
perm_hmm-master/adapt_hypo_test/two_states/util.py
r"""Provides utility functions for the computation of optimal policies for two states, two outcomes and trivial transition matrix. """ #%% import itertools import numpy as np from scipy.special import softmax, expm1, log1p #%% def log_odds_to_log_probs(x): r"""Converts log odds to log probs. .. math:: ...
7,861
33.331878
109
py
perm_hmm
perm_hmm-master/adapt_hypo_test/two_states/__init__.py
r"""Computes optimal policies for a two state model with transition matrix equal to identity. See :py:mod:`adapt_hypo_test` for discussion of notation. """
157
30.6
76
py
perm_hmm
perm_hmm-master/adapt_hypo_test/two_states/no_transitions.py
r"""Main module that computes the optimal policy. """ import numpy as np from adapt_hypo_test.two_states import util from adapt_hypo_test.two_states.util import (nx_to_log_odds, m_to_r, pq_to_m, x_grid, lp_grid, log_p_log_q_to_m) from scipy.special import logsumexp def nop_reward(log_cond_reward, m, lp): r"""Co...
12,407
41.934256
216
py
perm_hmm
perm_hmm-master/example_scripts/plot_binned_histograms.py
import os parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0, parentdir) import fire import numpy as np from scipy.special import logsumexp import matplotlib.pyplot as plt import torch import pyro.distributions as dist from example_systems.beryllium import dimensionful_gamma, ...
3,662
34.563107
151
py
perm_hmm
perm_hmm-master/example_scripts/beryllium_plot.py
import os import sys parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, parentdir) parentdir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parentdir) import fire import numpy as np import matplotlib.pyplot as plt import torch import pyro.distributions as dist ...
9,318
38.155462
226
py
perm_hmm
perm_hmm-master/example_scripts/plot_transition_matrices.py
import os parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0, parentdir) import fire import numpy as np import matplotlib.pyplot as plt from example_systems.beryllium import dimensionful_gamma, l_to_fmf from example_systems import beryllium def plot_tmats( data_dire...
2,396
32.291667
80
py
perm_hmm
perm_hmm-master/example_scripts/exhaustive_three_states.py
import os import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0, parentdir) import fire import numpy as np import torch from perm_hmm.simulator import HMMSimulator from perm_hmm.util import log1me...
7,615
35.792271
170
py
perm_hmm
perm_hmm-master/perm_hmm/loss_functions.py
r"""Loss functions for the :py:class:`~perm_hmm.postprocessing.ExactPostprocessor` and :py:class:`~perm_hmm.postprocessing.EmpiricalPostprocessor` classes. """ import torch from perm_hmm.util import ZERO def log_zero_one(state, classification): r"""Log zero-one loss. Returns ``log(int(classification != stat...
2,495
27.363636
80
py
perm_hmm
perm_hmm-master/perm_hmm/simulator.py
""" Simulates the initial state discrimination experiment using different methods, to compare the resulting error rates. """ import torch from perm_hmm.util import num_to_data from perm_hmm.postprocessing import ExactPostprocessor, EmpiricalPostprocessor from perm_hmm.classifiers.perm_classifier import PermClassifier...
7,817
38.887755
104
py
perm_hmm
perm_hmm-master/perm_hmm/log_cost.py
r"""Log costs to be used with the :py:class:`~perm_hmm.policies.min_tree.MinTreePolicy` class. """ import torch def log_initial_entropy(log_probs: torch.Tensor): """ Calculates the log of the initial state posterior entropy from log_probs, with dimensions -1: s_k, -2: s_1 :param log_probs: :retur...
1,155
23.595745
97
py
perm_hmm
perm_hmm-master/perm_hmm/util.py
"""This module includes a few utility functions. """ from functools import reduce from operator import mul import torch import numpy as np from scipy.special import logsumexp, expm1, log1p ZERO = 10**(-14) def bin_ent(logits_tensor): """Computes the binary entropy of a tensor of independent log probabilities. ...
8,762
29.217241
127
py
perm_hmm
perm_hmm-master/perm_hmm/__init__.py
""" Provides the functions for computing exact and approximate misclassification rates of various repeated measurement schemes. Aims to demonstrate when a strategy which involves applying permutations between observations yields an appreciable advantage. """ import perm_hmm.policies import perm_hmm.policies.min_tree i...
368
29.75
76
py
perm_hmm
perm_hmm-master/perm_hmm/binning.py
import warnings import torch from pyro.distributions import Categorical from itertools import combinations from perm_hmm.models.hmms import ExpandedHMM, DiscreteHMM from perm_hmm.simulator import HMMSimulator def bin_histogram(base_hist, bin_edges): r"""Given a histogram, bins it using the given bin edges. B...
7,504
45.32716
133
py
perm_hmm
perm_hmm-master/perm_hmm/rate_comparisons.py
import torch from perm_hmm.models.hmms import PermutedDiscreteHMM from perm_hmm.simulator import HMMSimulator from perm_hmm.loss_functions import log_zero_one def exact_rates(phmm: PermutedDiscreteHMM, num_steps, perm_policy, classifier=None, verbosity=0, log_loss=None): r"""Provides plumbing for comparing the m...
3,152
39.948052
146
py
perm_hmm
perm_hmm-master/perm_hmm/postprocessing.py
""" Classes to be used for postprocessing data after a simulation. """ import warnings import numpy as np import torch from scipy.stats import beta from perm_hmm.util import ZERO from perm_hmm.loss_functions import zero_one, log_zero_one def clopper_pearson(alpha, num_successes, total_trials): """ Computes ...
15,799
39.306122
170
py
perm_hmm
perm_hmm-master/perm_hmm/return_types.py
from typing import NamedTuple import torch hmm_fields = [ ('states', torch.Tensor), ('observations', torch.Tensor), ] HMMOutput = NamedTuple('HMMOutput', hmm_fields)
180
11.928571
47
py
perm_hmm
perm_hmm-master/perm_hmm/policies/belief_tree.py
r"""Provides functions used by strategies that use a tree to select the permutation. To compute optimal permutations, we use the belief states .. math:: b(y^{k-1}) := \mathbb{P}(s_0, s_k|y^{k-1}), where the :math:`s_k` are the states of the HMM at step :math:`k`, and the superscript :math:`y^{k-1}` is the sequen...
12,770
45.44
130
py
perm_hmm
perm_hmm-master/perm_hmm/policies/exhaustive.py
r"""Exhaustively searches the best permutations for all possible observations. This is a policy that exhaustively searches the best permutations for all possible observations. This method is very slow and should only be used for testing purposes. The complexity of this method is O((n*p)**t), where n is the number of p...
12,317
42.373239
188
py
perm_hmm
perm_hmm-master/perm_hmm/policies/belief.py
r"""Computes belief states of HMMs with permutations. This module contains the :py:class:`~perm_hmm.policies.belief.HMMBeliefState` class, which computes belief states of HMMs with permutations in a tree-like manner. This module also contains the :py:class:`~perm_hmm.policies.belief.BeliefStatePolicy` class, which is...
21,372
43.807128
138
py