def test_loss(self, monkeypatch, adj): """Test if function correctly creates the SF program for lossy GBS.""" mock_eng_run = mock.MagicMock() with monkeypatch.context() as m: m.setattr(sf.Engine, "run", mock_eng_run) sample.sample(A=adj, n_mean=1, threshold=False, loss=0.5) p_func = mock_eng_run.call_args[0][0] assert isinstance(p_func.circuit[-2].op, sf.ops.LossChannel)
def test_threshold(self, monkeypatch, adj): """Test if function correctly creates the SF program for threshold GBS.""" mock_eng_run = mock.MagicMock() with monkeypatch.context() as m: m.setattr(sf.Engine, "run", mock_eng_run) sample.sample(A=adj, n_mean=1, threshold=True) p_func = mock_eng_run.call_args[0][0] assert isinstance(p_func.circuit[-1].op, sf.ops.MeasureThreshold)
def test_no_loss(self, monkeypatch, adj): """Test if function correctly creates the SF program for GBS without loss.""" mock_eng_run = mock.MagicMock() with monkeypatch.context() as m: m.setattr(sf.Engine, "run", mock_eng_run) sample.sample(A=adj, n_mean=1, threshold=False) p_func = mock_eng_run.call_args[0][0] assert not all([isinstance(op, sf.ops.LossChannel) for op in p_func.circuit])
def test_seed(dim, adj): """Test for the function ``strawberryfields.gbs.sample.seed``. Checks that samples are identical after repeated initialization of ``seed``.""" sample.seed(1968) q_s_1 = sample.sample(A=adj, n_mean=2, n_samples=10, threshold=False) sample.seed(1968) q_s_2 = sample.sample(A=adj, n_mean=2, n_samples=10, threshold=False) assert np.array_equal(q_s_1, q_s_2)
def test_threshold_postselect(self, adj, monkeypatch, valid_backends): """Test if function returns samples when threshold detection is used and postselection. With threshold detection, all non-zero elements of a sample are set to 1. Postselection only returns samples with a total click number (number of 1's) not less than the parameter specified. """ def dummy_sample_sf(*args, **kwargs): """Dummy ``_sample_sf`` function""" return sample_pnr_postselect with monkeypatch.context() as m: m.setattr(sample, "_sample_sf", dummy_sample_sf) samples = np.array( sample.sample( A=adj, n_mean=1.0, samples=sample_number, backend_options={ "backend": valid_backends, "threshold": True, "postselect": 1 }, )) samples_target = np.array( [sample_pnr_postselect[0] for _ in range(sample_number)]) samples_target[samples_target >= 1] = 1 assert np.allclose(samples, samples_target)
def test_pnr_postselect(self, adj, monkeypatch, valid_backends): """Test if function returns samples when photon-number resolving detection is used and postselection. Postselection only returns samples with a total photon number not less than the parameter specified. """ def dummy_sample_sf(*args, **kwargs): """Dummy ``_sample_sf`` function""" return sample_pnr_postselect with monkeypatch.context() as m: m.setattr(sample, "_sample_sf", dummy_sample_sf) samples = np.array( sample.sample( A=adj, n_mean=1.0, samples=sample_number, backend_options={ "backend": valid_backends, "threshold": False, "postselect": 1, }, )) samples_target = np.array( [sample_pnr_postselect[0] for _ in range(sample_number)]) assert np.allclose(samples, samples_target)
def test_threshold_nopostselect(self, adj, monkeypatch, valid_backends): """Test if function returns correct samples when threshold detection is used and no postselection on samples. With threshold detection, all non-zero elements of a sample are set to 1. """ samples_threshold_nopostselect = samples_pnr_nopostselect.copy() samples_threshold_nopostselect[samples_threshold_nopostselect >= 1] = 1 def dummy_sample_sf(*args, **kwargs): """Dummy ``_sample_sf`` function""" return samples_pnr_nopostselect with monkeypatch.context() as m: m.setattr(sample, "_sample_sf", dummy_sample_sf) samples = np.array( sample.sample( A=adj, n_mean=1.0, samples=sample_number, backend_options={ "backend": valid_backends, "threshold": True, "postselect": 0 }, )) assert set(tuple(samples.flatten())) == {0, 1} assert np.allclose(samples, samples_threshold_nopostselect)
def test_all_loss(self, monkeypatch, adj, dim): """Test if function samples from the vacuum when maximum loss is applied.""" mock_eng_run = mock.MagicMock() with monkeypatch.context() as m: m.setattr(sf.Engine, "run", mock_eng_run) sample.sample(A=adj, n_mean=1, threshold=False, loss=1) p_func = mock_eng_run.call_args[0][0] eng = sf.LocalEngine(backend="gaussian") state = eng.run(p_func).state cov = state.cov() disp = state.displacement() assert np.allclose(cov, 0.5 * state.hbar * np.eye(2 * dim)) assert np.allclose(disp, np.zeros(dim))
def test_seed(dim, adj): """Test for the function ``strawberryfields.gbs.sample.seed``. Checks that samples are identical after repeated initialization of ``seed``.""" sample.seed(1968) q_s_1 = sample.sample(A=adj, n_mean=2, samples=10, backend_options={"threshold": False}) u_s_1 = sample.uniform(modes=dim, sampled_modes=2, samples=10) sample.seed(1968) q_s_2 = sample.sample(A=adj, n_mean=2, samples=10, backend_options={"threshold": False}) u_s_2 = sample.uniform(modes=dim, sampled_modes=2, samples=10) assert np.array_equal(q_s_1, q_s_2) assert np.array_equal(u_s_1, u_s_2)
def test_pnr_integration(self, adj): """Integration test to check if function returns samples of correct form, i.e., correct number of samples, correct number of modes, all non-negative integers """ samples = np.array( sample.sample(A=adj, n_mean=1.0, n_samples=integration_sample_number, threshold=False) ) dims = samples.shape assert len(dims) == 2 assert dims == (integration_sample_number, len(adj)) assert samples.dtype == "int" assert (samples >= 0).all()
def test_threshold_integration(self, adj, integration_sample_number): """Integration test to check if function returns samples of correct form, i.e., correct number of samples, correct number of modes, all integers of zeros and ones """ samples = np.array( sample.sample(A=adj, n_mean=1.0, n_samples=integration_sample_number, threshold=True) ) dims = samples.shape assert len(dims) == 2 assert dims == (integration_sample_number, len(adj)) assert samples.dtype == "int" assert (samples >= 0).all() assert (samples <= 1).all()
def test_pnr_nopostselect_integration(self, adj): """Integration test to check if function returns samples of correct form, i.e., correct number of samples, correct number of modes, all non-negative integers """ samples = np.array( sample.sample( A=adj, n_mean=1.0, samples=integration_sample_number, backend_options={ "threshold": False, "postselect": 0 }, )) dims = samples.shape assert len(dims) == 2 assert dims[0] == integration_sample_number assert dims[1] == len(adj) assert samples.dtype == "int" assert (samples >= 0).all()
def test_pnr_nopostselect(self, adj, monkeypatch, valid_backends): """Test if function returns correct samples with no additional manipulation, i.e., no postselection or threshold detection """ def dummy_sample_sf(*args, **kwargs): """Dummy ``_sample_sf`` function""" return samples_pnr_nopostselect with monkeypatch.context() as m: m.setattr(sample, "_sample_sf", dummy_sample_sf) samples = sample.sample( A=adj, n_mean=1.0, samples=sample_number, backend_options={ "backend": valid_backends, "threshold": False, "postselect": 0 }, ) assert np.allclose(samples_pnr_nopostselect, samples)
def test_threshold_postselect_integration(self, adj): """Integration test to check if function returns samples of correct form, i.e., correct number of samples, correct number of modes, all integers of zeros and ones with total click number not less than 1 """ samples = np.array( sample.sample( A=adj, n_mean=1.0, samples=integration_sample_number, backend_options={ "threshold": True, "postselect": 1 }, )) dims = samples.shape assert len(dims) == 2 assert dims[0] == integration_sample_number assert dims[1] == len(adj) assert samples.dtype == "int" assert (samples >= 0).all() assert (samples <= 1).all() assert (np.sum(samples, axis=1) >= 1).all()
def test_invalid_loss(self, adj): """Test if function raises a ``ValueError`` when the loss parameter is specified outside of range""" with pytest.raises(ValueError, match="Loss parameter must take a value between zero and"): sample.sample(A=adj, n_mean=1.0, n_samples=1, loss=2)
def test_invalid_samples(self, adj, monkeypatch): """Test if function raises a ``ValueError`` when a number of samples less than one is requested """ with pytest.raises(ValueError, match="Number of samples must be at least one"): sample.sample(A=adj, n_mean=1.0, samples=0)
def test_invalid_adjacency(self, dim): """Test if function raises a ``ValueError`` for a matrix that is not symmetric""" with pytest.raises(ValueError, match="Input must be a NumPy array"): adj_asym = np.triu(np.ones((dim, dim))) sample.sample(A=adj_asym, n_mean=1.0)
Let's take a look at both types of sampling methods. We can generate samples from a random 5-dimensional symmetric matrix: """ from strawberryfields.gbs import sample import numpy as np modes = 5 n_mean = 6 samples = 5 A = np.random.normal(0, 1, (modes, modes)) A = A + A.T s_thresh = sample.sample(A, n_mean, samples, threshold=True) s_pnr = sample.sample(A, n_mean, samples, threshold=False) print(s_thresh) print(s_pnr) ############################################################################## # In each case, a sample is a sequence of integers of length five, i.e., ``len(modes) = 5``. # Threshold samples are ``0``'s and ``1``'s, corresponding to whether or not photons were # detected in a mode. A ``1`` here is conventionally called a "click". PNR samples are # non-negative integers counting the number of photons detected in each mode. For example, # suppose a PNR sample is ``[2, 1, 1, 0, 0]``, meaning that 2 photons were detected in mode 0, # 1 photons were detected in modes 1 and 2, and 0 photons were detected in modes 3 and 4. If # threshold detectors were used instead, the sample would be: ``[1, 1, 1, 0, 0]``. # # Sampling subgraphs
def test_invalid_n_mean(self, adj): """Test if function raises a ``ValueError`` when the mean photon number is specified to be negative.""" with pytest.raises(ValueError, match="Mean photon number must be non-negative"): sample.sample(A=adj, n_mean=-1.0, n_samples=1)