Best Python code snippet using molecule_python
test_sparse_gpr.py
Source:test_sparse_gpr.py
...30 else:31 outputs = outputs[:, np.newaxis] if outputs.ndim == 1 else outputs32 return outputs33 return wrapped34def _get_matrix(name):35 return np.loadtxt(os.path.join(_data_dir, name + ".dat"))36class _InducingData(object):37 """38 A few pieces in common with these models39 """40 @staticmethod41 @atleast_col42 def _xy():43 return _get_matrix("x"), _get_matrix("y")44 @staticmethod45 @atleast_col46 def _x_test():47 return _get_matrix("x_test")48 @staticmethod49 @atleast_col50 def _z():51 return _get_matrix("z")52class TestVFE(_InducingData):53 def test_init(self):54 x, y = _InducingData._xy()55 kernel = Matern32(x.shape[1], ARD=True)56 VFE(x, y, kernel)57 VFE(x, y, kernel, inducing_points=_InducingData._z())58 # TODO mean59 def test_compute_loss(self):60 x, y = _InducingData._xy()61 z = _InducingData._z()62 kernel = Matern32(1)63 kernel.length_scales.data = torch.zeros(1, dtype=torch_dtype)64 kernel.variance.data = torch.zeros(1, dtype=torch_dtype)65 likelihood = likelihoods.Gaussian(variance=1.0)66 model = VFE(67 x,68 y,69 kernel,70 inducing_points=z,71 likelihood=likelihood,72 mean_function=mean_functions.Zero(1),73 )74 loss = model.loss()75 assert isinstance(loss, torch.Tensor)76 assert loss.ndimension() == 077 # Computed while I trust the result.78 assert loss.item() == pytest.approx(8.842242323920674)79 # Test ability to specify x and y80 loss_xy = model.loss(x=TensorType(x), y=TensorType(y))81 assert isinstance(loss_xy, torch.Tensor)82 assert loss_xy.item() == loss.item()83 with pytest.raises(ValueError):84 # Size mismatch85 model.loss(x=TensorType(x[: x.shape[0] // 2]))86 @needs_cuda87 def test_compute_loss_cuda(self):88 model = self._get_model()89 model.cuda()90 loss = model.loss()91 assert loss.is_cuda92 def test_predict(self):93 """94 Just the ._predict() method95 """96 x, y = _InducingData._xy()97 z = _InducingData._z()98 kernel = Matern32(1)99 kernel.length_scales.data = torch.zeros(1, dtype=torch_dtype)100 kernel.variance.data = torch.zeros(1, dtype=torch_dtype)101 likelihood = likelihoods.Gaussian(variance=1.0)102 model = VFE(103 x,104 y,105 kernel,106 inducing_points=z,107 likelihood=likelihood,108 mean_function=mean_functions.Zero(1),109 )110 x_test = torch.Tensor(_InducingData._x_test())111 mu, s = TestVFE._y_pred()112 gaussian_predictions(model, x_test, mu, s)113 @needs_cuda114 def test_predict_cuda(self):115 model = self._get_model()116 model.cuda()117 x_test = torch.randn(4, model.input_dimension, dtype=torch_dtype).cuda()118 for t in model._predict(x_test):119 assert t.is_cuda120 @staticmethod121 @atleast_col122 def _y_pred():123 return _get_matrix("vfe_y_mean"), _get_matrix("vfe_y_cov")124 @staticmethod125 def _get_model():126 x, y = _InducingData._xy()127 z = _InducingData._z()128 kernel = Matern32(1)129 kernel.length_scales.data = torch.zeros(1, dtype=torch_dtype)130 kernel.variance.data = torch.zeros(1, dtype=torch_dtype)131 likelihood = likelihoods.Gaussian(variance=1.0)132 model = VFE(133 x,134 y,135 kernel,136 inducing_points=z,137 likelihood=likelihood,138 mean_function=mean_functions.Zero(1),139 )140 return model141class TestSVGP(_InducingData):142 def test_init(self):143 x, y = _InducingData._xy()144 kernel = Matern32(x.shape[1], ARD=True)145 SVGP(x, y, kernel)146 SVGP(x, y, kernel, inducing_points=_InducingData._z())147 SVGP(x, y, kernel, mean_function=mean_functions.Constant(y.shape[1]))148 SVGP(149 x,150 y,151 kernel,152 mean_function=torch.nn.Linear(x.shape[1], y.shape[1], dtype=torch_dtype),153 )154 def test_compute_loss(self):155 x, y = _InducingData._xy()156 z = _InducingData._z()157 u_mu, u_l_s = TestSVGP._induced_outputs()158 kernel = Matern32(1)159 kernel.length_scales.data = torch.zeros(1, dtype=torch_dtype)160 kernel.variance.data = torch.zeros(1, dtype=torch_dtype)161 likelihood = likelihoods.Gaussian(variance=1.0)162 model = SVGP(163 x,164 y,165 kernel,166 inducing_points=z,167 likelihood=likelihood,168 mean_function=mean_functions.Zero(1),169 )170 model.induced_output_mean.data = TensorType(u_mu)171 model.induced_output_chol_cov.data = model.induced_output_chol_cov._transform.inv(172 TensorType(u_l_s)173 )174 loss = model.loss()175 assert isinstance(loss, torch.Tensor)176 assert loss.ndimension() == 0177 # Computed while I trust the result.178 assert loss.item() == pytest.approx(9.534628739243518)179 # Test ability to specify x and y180 loss_xy = model.loss(x=TensorType(x), y=TensorType(y))181 assert isinstance(loss_xy, torch.Tensor)182 assert loss_xy.item() == loss.item()183 with pytest.raises(ValueError):184 # Size mismatch185 model.loss(x=TensorType(x[: x.shape[0] // 2]), y=TensorType(y))186 model_minibatch = SVGP(x, y, kernel, batch_size=1)187 loss_mb = model_minibatch.loss()188 assert isinstance(loss_mb, torch.Tensor)189 assert loss_mb.ndimension() == 0190 model_full_mb = SVGP(191 x,192 y,193 kernel,194 inducing_points=z,195 likelihood=likelihood,196 mean_function=mean_functions.Zero(1),197 batch_size=x.shape[0],198 )199 model_full_mb.induced_output_mean.data = TensorType(u_mu)200 model_full_mb.induced_output_chol_cov.data = model_full_mb.induced_output_chol_cov._transform.inv(201 TensorType(u_l_s)202 )203 loss_full_mb = model_full_mb.loss()204 assert isinstance(loss_full_mb, torch.Tensor)205 assert loss_full_mb.ndimension() == 0206 assert loss_full_mb.item() == pytest.approx(loss.item())207 model.loss(model.X, model.Y) # Just make sure it works!208 @needs_cuda209 def test_compute_loss_cuda(self):210 model = self._get_model()211 model.cuda()212 loss = model.loss()213 assert loss.is_cuda214 def test_predict(self):215 """216 Just the ._predict() method217 """218 x, y = _InducingData._xy()219 z = _InducingData._z()220 u_mu, u_l_s = TestSVGP._induced_outputs()221 kernel = Matern32(1)222 kernel.length_scales.data = torch.zeros(1, dtype=torch_dtype)223 kernel.variance.data = torch.zeros(1, dtype=torch_dtype)224 likelihood = likelihoods.Gaussian(variance=1.0)225 model = SVGP(226 x,227 y,228 kernel,229 inducing_points=z,230 likelihood=likelihood,231 mean_function=mean_functions.Zero(1),232 )233 model.induced_output_mean.data = TensorType(u_mu)234 model.induced_output_chol_cov.data = model.induced_output_chol_cov._transform.inv(235 TensorType(u_l_s)236 )237 x_test = TensorType(_InducingData._x_test())238 mu, s = TestSVGP._y_pred()239 gaussian_predictions(model, x_test, mu, s)240 @needs_cuda241 def test_predict_cuda(self):242 model = self._get_model()243 model.cuda()244 x_test = torch.randn(4, model.input_dimension, dtype=torch_dtype).cuda()245 for t in model._predict(x_test):246 assert t.is_cuda247 @staticmethod248 @atleast_col249 def _induced_outputs():250 return _get_matrix("q_mu"), _get_matrix("l_s")251 @staticmethod252 @atleast_col253 def _y_pred():254 return _get_matrix("svgp_y_mean"), _get_matrix("svgp_y_cov")255 @staticmethod256 def _get_model():257 x, y = _InducingData._xy()258 z = _InducingData._z()259 u_mu, u_l_s = TestSVGP._induced_outputs()260 kernel = Matern32(1)261 kernel.length_scales.data = torch.zeros(1, dtype=torch_dtype)262 kernel.variance.data = torch.zeros(1, dtype=torch_dtype)263 likelihood = likelihoods.Gaussian(variance=1.0)264 model = SVGP(265 x,266 y,267 kernel,268 inducing_points=z,...
transforms.py
Source:transforms.py
...24 return morphology.dilation(img, disk)25 else:26 return morphology.erosion(img, disk)27class LinearDeformation(Deformation):28 def _get_matrix(self, moments: ImageMoments, morph: ImageMorphology) -> np.ndarray:29 raise NotImplementedError30 def warp(self, xy: np.ndarray, morph: ImageMorphology) -> np.ndarray:31 moments = ImageMoments(morph.binary_image)32 centroid = np.array(moments.centroid)33 matrix = self._get_matrix(moments, morph)34 xy_ = (xy - centroid) @ matrix.T + centroid35 return xy_36class SetSlant(LinearDeformation):37 def __init__(self, target_slant_rad: float):38 self.target_shear = -np.tan(target_slant_rad)39 def _get_matrix(self, moments: ImageMoments, morph: ImageMorphology) -> np.ndarray:40 source_shear = moments.horizontal_shear41 delta = self.target_shear - source_shear42 return np.array([[1., -delta], [0., 1.]])43def _measure_width(morph: ImageMorphology, frac=.02, moments: ImageMoments = None):44 top_left, top_right = bounding_parallelogram(morph.hires_image,45 frac=frac, moments=moments)[:2]46 return (top_right[0] - top_left[0]) / morph.scale47class SetWidth(LinearDeformation):48 _tolerance = 1.49 def __init__(self, target_width: float, validate=False):50 self.target_width = target_width51 self._validate = validate52 def _get_matrix(self, moments: ImageMoments, morph: ImageMorphology) -> np.ndarray:53 source_width = _measure_width(morph, moments=moments)54 factor = source_width / self.target_width55 shear = moments.horizontal_shear56 return np.array([[factor, shear * (1. - factor)], [0., 1.]])57 def __call__(self, morph: ImageMorphology) -> np.ndarray:58 pert_hires_image = super().__call__(morph)59 pert_image = morph.downscale(pert_hires_image)60 if self._validate:61 pert_morph = ImageMorphology(pert_image, threshold=morph.threshold, scale=morph.scale)62 width = _measure_width(pert_morph)63 if abs(width - self.target_width) > self._tolerance:64 print(f"!!! Incorrect width after transformation: {width:.1f}, "65 f"expected {self.target_width:.1f}.")66 pert_hires_image = self(pert_morph)...
__init__.py
Source:__init__.py
1from qulacs_core import *2import qulacs.observable._get_matrix3Observable.get_matrix = \4 lambda obs: qulacs.observable._get_matrix._get_matrix(obs)5GeneralQuantumOperator.get_matrix = \...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!