Ejemplo n.º 1
0
    def test_MHRWParams(self):
        # default constructor
        mhrw = tomographer.MHRWParams()
        # constructor with parameters
        mhrw = tomographer.MHRWParams({'step_size': 0.01}, 100, 500, 32768)
        # constructor with keyword arguments
        mhrw = tomographer.MHRWParams(step_size=0.01,
                                      n_sweep=100,
                                      n_therm=500,
                                      n_run=32768)

        # make sure params are stored correctly
        self.assertAlmostEqual(mhrw.mhwalker_params["step_size"], 0.01)
        self.assertEqual(mhrw.n_sweep, 100)
        self.assertEqual(mhrw.n_therm, 500)
        self.assertEqual(mhrw.n_run, 32768)

        # attributes should be writable
        mhrw.mhwalker_params = {'step_size': 0.06}
        self.assertAlmostEqual(mhrw.mhwalker_params["step_size"], 0.06)
        mhrw.n_sweep = 200
        self.assertEqual(mhrw.n_sweep, 200)
        mhrw.n_therm = 1024
        self.assertEqual(mhrw.n_therm, 1024)
        mhrw.n_run = 8192
        self.assertEqual(mhrw.n_run, 8192)
Ejemplo n.º 2
0
    def test_rand_walk(self):

        r = None
        with tomographer.jpyutil.RandWalkProgressBar(
                "random walk in progress") as prg:
            # just run tomorun on some arbitrary data to get some stuff to check
            mhrw_params = tomographer.MHRWParams(step_size=0.04,
                                                 n_sweep=25,
                                                 n_run=8192,
                                                 n_therm=500)
            hist_params = tomographer.UniformBinsHistogramParams(0.985, 1, 20)
            binning_num_levels = 7
            r = tomographer.tomorun.tomorun(
                dim=2,
                Emn=[
                    np.array([[0.5, -0.5j], [0.5j, 0.5]]),
                    np.array([[0.5, 0.5j], [-0.5j, 0.5]])
                ],
                Nm=np.array([500, 0]),
                fig_of_merit="obs-value",
                observable=np.array([[0.5, -0.5j], [0.5j, 0.5]]),
                num_repeats=2,
                binning_num_levels=binning_num_levels,
                mhrw_params=mhrw_params,
                hist_params=hist_params,
                progress_fn=prg.progress_fn,
            )
            prg.displayFinalInfo(r['final_report_runs'])
Ejemplo n.º 3
0
    def test_custom_figofmerit(self):

        print("test_custom_figofmerit()")

        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.99, 1, 20)

        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit=lambda T: npl.norm(np.dot(T, T.T.conj())),  # purity
            ref_state=self.rho_ref,
            num_repeats=num_repeats,
            mhrw_params=tomographer.MHRWParams(step_size=0.04,
                                               n_sweep=25,
                                               n_run=8192,
                                               n_therm=1024),
            hist_params=hist_params,
            progress_fn=lambda report: print(report.getHumanReport()),
            progress_interval_ms=100)

        print(r['final_report'])
        # just make sure that less than 1% of points are out of [0.99,1]
        self.assertLess(r['final_histogram'].off_chart, 0.01)
Ejemplo n.º 4
0
def do_tomorun():

    d = {}

    d['result'] = tomographer.tomorun.tomorun(
        dim=2,
        Emn=[
            # +Y
            np.array([[0.5, -0.5j], [0.5j, 0.5]]),
            # -Y
            np.array([[0.5, 0.5j], [-0.5j, 0.5]])
        ],
        Nm=np.array([423, 87]),
        fig_of_merit="obs-value",
        observable=np.array([[0.5, -0.5j], [0.5j, 0.5]]),
        mhrw_params=tomographer.MHRWParams(step_size=0.1,
                                           n_sweep=10,
                                           n_run=32768,
                                           n_therm=500),
        hist_params=tomographer.UniformBinsHistogramParams(0.7, 0.9, 20),
        progress_fn=lambda x: print(x.getHumanReport()))

    # save all of this stuff as a pickle
    with open(os.path.join(pickledatadir, 'tomorun.pickle'), 'wb') as f:
        pickle.dump(d, f, 2)
Ejemplo n.º 5
0
    def test_mhwalker_param_2(self):

        print("test_mhwalker_param_2()")
        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.99, 1, 10)
        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit="fidelity",
            ref_state=self.rho_ref,
            num_repeats=num_repeats,
            # understands step size given as keyword argument? ---
            mhrw_params=tomographer.MHRWParams(step_size=0.04,
                                               n_sweep=25,
                                               n_therm=1024,
                                               n_run=1024),
            # ---
            hist_params=hist_params,
            ctrl_step_size_params={'enabled': False},
            ctrl_converged_params={'enabled': False},
        )
        print(r['final_report'])
        for rw in r['runs_results']:
            self.assertAlmostEqual(rw.mhrw_params.mhwalker_params["step_size"],
                                   0.04)
Ejemplo n.º 6
0
    def test_error_in_callback(self):

        print("test_error_in_callback()")

        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.985, 1, 200)

        class Ns:
            pass

        #
        # Make sure an error in the callback raises an Exception
        #
        def progress_callback(fullstatusreport):
            error - xxx(xyz)  # error -- raises a Python exception
            print(fullstatusreport.getHumanReport())

        intvl_ms = 200

        with self.assertRaises(Exception):
            r = tomographer.tomorun.tomorun(
                dim=2,
                Emn=self.Emn,
                Nm=self.Nm,
                fig_of_merit="obs-value",
                observable=self.rho_ref,
                num_repeats=num_repeats,
                mhrw_params=tomographer.MHRWParams(step_size=0.04,
                                                   n_sweep=25,
                                                   n_run=4 * 32768,
                                                   n_therm=1024),
                hist_params=hist_params,
                progress_fn=progress_callback,
                progress_interval_ms=intvl_ms,
            )
Ejemplo n.º 7
0
    def test_mhwalker_param_5(self):

        print("test_mhwalker_param_5()")
        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.99, 1, 10)
        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit="fidelity",
            ref_state=self.rho_ref,
            num_repeats=num_repeats,
            # understands missing key? ---
            mhrw_params=tomographer.MHRWParams({}, 25, 500, 1024),
            # ---
            hist_params=hist_params,
            ctrl_step_size_params={'enabled': True},  # auto-adjust
            ctrl_converged_params={'enabled': False},
        )
        print(r['final_report'])
        for rw in r['runs_results']:
            self.assertLessEqual(rw.mhrw_params.mhwalker_params["step_size"],
                                 0.1)
            self.assertGreaterEqual(
                rw.mhrw_params.mhwalker_params["step_size"], 0.005)
Ejemplo n.º 8
0
    def test_fields(self):
        def prg_callback(x):
            print(x.getHumanReport())

        # just run tomorun on some arbitrary data to get some stuff to check
        mhrw_params = tomographer.MHRWParams(step_size=0.04,
                                             n_sweep=25,
                                             n_run=8192,
                                             n_therm=500)
        hist_params = tomographer.HistogramParams(0.985, 1, 20)
        binning_num_levels = 7
        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=[
                np.array([[0.5, -0.5j], [0.5j, 0.5]]),
                np.array([[0.5, 0.5j], [-0.5j, 0.5]])
            ],
            Nm=np.array([500, 0]),
            fig_of_merit="obs-value",
            observable=np.array([[0.5, -0.5j], [0.5j, 0.5]]),
            num_repeats=2,
            binning_num_levels=binning_num_levels,
            mhrw_params=mhrw_params,
            hist_params=hist_params,
            ctrl_step_size_params={'enable': False},
            progress_interval_ms=500,
            progress_fn=prg_callback,
        )

        # check that all fields are there and display meaningful values

        runres = r['runs_results'][0]
        self.assertAlmostEqual(runres.mhrw_params.mhwalker_params["step_size"],
                               mhrw_params.mhwalker_params["step_size"])
        self.assertEqual(runres.mhrw_params.n_sweep, mhrw_params.n_sweep)
        self.assertEqual(runres.mhrw_params.n_therm, mhrw_params.n_therm)
        self.assertEqual(runres.mhrw_params.n_run, mhrw_params.n_run)

        self.assertGreater(runres.acceptance_ratio, 0.2)
        self.assertLess(runres.acceptance_ratio, 0.4)

        stats_results = runres.stats_results

        self.assertEqual(stats_results.histogram.numBins(),
                         hist_params.num_bins)

        npt.assert_array_equal(stats_results.error_levels.shape,
                               [hist_params.num_bins, binning_num_levels + 1])
        # the last error level should be the reported error bar:
        npt.assert_array_almost_equal(
            stats_results.error_levels[:, binning_num_levels],
            stats_results.histogram.delta)

        for c in stats_results.converged_status:
            self.assertIn(c, (tomographer.BinningAnalysis.CONVERGED,
                              tomographer.BinningAnalysis.NOT_CONVERGED,
                              tomographer.BinningAnalysis.UNKNOWN_CONVERGENCE))
Ejemplo n.º 9
0
    def test_values_light(self):

        print("test_values_light()")

        num_repeats = 8
        hist_params = tomographer.HistogramParams(0.985, 1, 200)

        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit="fidelity",
            ref_state=self.rho_ref,
            num_repeats=num_repeats,
            mhrw_params=tomographer.MHRWParams(step_size=0.04,
                                               n_sweep=25,
                                               n_run=32768,
                                               n_therm=1024),
            jumps_method="light",
            hist_params=hist_params,
            progress_fn=lambda report: print(report.getHumanReport()),
            progress_interval_ms=500,
            ctrl_converged_params={
                'max_allowed_not_converged': 1,
                'max_allowed_unknown_notisolated': 1,
                'max_allowed_unknown': 3,
            })
        print("Final report of runs :\n{}".format(r['final_report_runs']))
        print("Final report of everything :\n{}".format(r['final_report']))

        final_histogram = r['final_histogram']
        self.assertTrue(
            isinstance(final_histogram, tomographer.AveragedErrorBarHistogram))
        simple_final_histogram = r['simple_final_histogram']
        self.assertTrue(
            isinstance(simple_final_histogram,
                       tomographer.AveragedSimpleRealHistogram))

        print("Tomorun completed in {} seconds".format(r['elapsed_seconds']))

        for k in range(num_repeats):
            runres = r['runs_results'][k]
            self.assertTrue(
                isinstance(runres,
                           tomographer.mhrwtasks.MHRandomWalkTaskResult))

        # now, check the actual values of the result
        pok = AnalyticalSolutionFn(np.sum(self.Nm))

        # can't be too picky on chi2, because this test will run many times (so it's bound
        # to fail at some point!)
        self.assertLess(pok.get_histogram_chi2_red(final_histogram), 5)
        npt.assert_array_almost_equal(final_histogram.bins,
                                      simple_final_histogram.bins)
Ejemplo n.º 10
0
    def test_pickle(self):
        hist = tomographer.HistogramWithErrorBars(0, 1, 3)
        stats_results = tomographer.ValueHistogramWithBinningMHRWStatsCollectorResult(
            hist, np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]),
            np.array([
                tomographer.BinningAnalysis.CONVERGED,
                tomographer.BinningAnalysis.NOT_CONVERGED,
                tomographer.BinningAnalysis.UNKNOWN_CONVERGENCE
            ]))
        mhrw_task_result = tomographer.mhrwtasks.MHRandomWalkTaskResult(
            stats_results, tomographer.MHRWParams(0.03, 37, 400, 65538), 0.27)
        # see http://pybind11.readthedocs.io/en/master/advanced/classes.html#pickling-support
        try:
            import cPickle as pickle
        except:
            import pickle
        s = pickle.dumps(mhrw_task_result, 2)
        print("PICKLE:\n" + str(s))
        mhrw_task_result2 = pickle.loads(s)

        m = mhrw_task_result
        m2 = mhrw_task_result2
        self.assertAlmostEqual(m.acceptance_ratio, m2.acceptance_ratio)
        self.assertAlmostEqual(m.mhrw_params.mhwalker_params,
                               m2.mhrw_params.mhwalker_params)
        self.assertEqual(m.mhrw_params.n_sweep, m2.mhrw_params.n_sweep)
        self.assertEqual(m.mhrw_params.n_therm, m2.mhrw_params.n_therm)
        self.assertEqual(m.mhrw_params.n_run, m2.mhrw_params.n_run)
        npt.assert_array_almost_equal(m.stats_results.histogram.bins,
                                      m2.stats_results.histogram.bins)
        npt.assert_array_almost_equal(m.stats_results.histogram.delta,
                                      m2.stats_results.histogram.delta)
        npt.assert_array_almost_equal(m.stats_results.error_levels,
                                      m2.stats_results.error_levels)
        npt.assert_array_equal(m.stats_results.converged_status,
                               m2.stats_results.converged_status)

        summary = m2.stats_results.errorBarConvergenceSummary()
        self.assertEqual(summary.n_bins, m.stats_results.histogram.numBins())
        self.assertEqual(summary.n_converged, 1)
        self.assertEqual(summary.n_unknown, 1)
        self.assertEqual(summary.n_unknown_isolated, 0)
        self.assertEqual(summary.n_not_converged, 1)

        # pickle the summary itself?
        s2 = pickle.dumps(summary, 2)
        print("PICKLE OF SUMMARY:\n" + str(s2))
        summary2 = pickle.loads(s2)
        self.assertEqual(summary2.n_bins, m.stats_results.histogram.numBins())
        self.assertEqual(summary2.n_converged, 1)
        self.assertEqual(summary2.n_unknown, 1)
        self.assertEqual(summary2.n_unknown_isolated, 0)
        self.assertEqual(summary2.n_not_converged, 1)
Ejemplo n.º 11
0
    def test_custom_figofmerit_parallel(self):

        print("test_custom_figofmerit_parallel()")

        num_repeats = 8
        hist_params = tomographer.HistogramParams(0.99, 1, 20)

        mhrw_params = tomographer.MHRWParams(step_size=0.04,
                                             n_sweep=25,
                                             n_run=8192,
                                             n_therm=1024)

        class Ns:
            pass

        glob = Ns()
        glob.saw_parallel_runs = False

        def is_running(w):
            if w is None:
                return False
            return w.data['kstep'] > (mhrw_params.n_therm +
                                      2) * mhrw_params.n_sweep

        def prg_fn(report):
            print(report.getHumanReport())
            num_running = sum([(1 if is_running(w) else 0)
                               for w in report.workers])
            if num_running > 1:
                glob.saw_parallel_runs = num_running
                raise Exception("Done, test passed.")

        try:
            r = tomographer.tomorun.tomorun(
                dim=2,
                Emn=self.Emn,
                Nm=self.Nm,
                fig_of_merit=lambda T: npl.norm(np.dot(T, T.T.conj())
                                                ),  # purity
                ref_state=self.rho_ref,
                num_repeats=num_repeats,
                mhrw_params=mhrw_params,
                hist_params=hist_params,
                progress_fn=prg_fn,
                progress_interval_ms=50,
                ctrl_step_size_params={'enabled': False},
            )
        except Exception as e:
            if 'Done, test passed' not in str(e):
                raise

        self.assertGreaterEqual(glob.saw_parallel_runs, 2)
Ejemplo n.º 12
0
    def test_base_seed(self):

        print("test_base_seed()")

        hist_params = tomographer.HistogramParams(0.985, 1, 50)

        samples = []

        def save_sample(T):
            samples.append(T)
            return 0

        # momentarily disable warnings because tomorun will warn about binning levels too low
        oldlevel = logging.getLogger("tomographer").level
        try:
            logging.getLogger("tomographer").level = logging.ERROR

            runs_samples = []
            for n in range(64):
                # reset samples list, go
                print("Tomorun run #", n)
                samples = []
                res = tomographer.tomorun.tomorun(
                    dim=2,
                    Emn=self.Emn,
                    Nm=self.Nm,
                    fig_of_merit=save_sample,
                    num_repeats=1,
                    mhrw_params=tomographer.MHRWParams(
                        step_size=0.04,
                        n_sweep=25,
                        n_therm=10,  # don't let it thermalize too much
                        n_run=1024,
                    ),
                    hist_params=hist_params,
                    ctrl_step_size_params={'enabled': False},
                    ctrl_converged_params={'enabled': False},
                    rng_base_seed=n)
                runs_samples.append(samples[10])
        finally:
            logging.getLogger("tomographer").level = oldlevel

        avgT = sum(runs_samples) / len(runs_samples)
        print("avgT = ", repr(avgT))
        spread = np.prod([npl.norm(T - avgT) for T in runs_samples])
        print("spread = ", repr(spread))

        self.assertGreater(spread, 0.2)
Ejemplo n.º 13
0
    def test_errbar_convergence(self):

        print("test_errbar_convergence()")

        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.995, 1, 100)

        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit="fidelity",
            ref_state=self.rho_ref,
            num_repeats=num_repeats,
            mhrw_params=tomographer.MHRWParams(
                step_size=0.04,
                n_sweep=25,
                n_run=8192,  # controller will keep running as necessary
                n_therm=1024),
            hist_params=hist_params,
            ctrl_converged_params={
                'max_allowed_unknown': 2,
                'max_allowed_unknown_notisolated': 2,
                'max_allowed_not_converged': 0,
                # run as long as necessary
                'max_add_run_iters': -1
            },
            progress_fn=lambda report: print(report.getHumanReport()),
            progress_interval_ms=50)

        print("Final report of runs :\n{}".format(r['final_report_runs']))

        # inspect the task runs
        for k in range(num_repeats):
            runres = r['runs_results'][k]
            # check that bins have converged as required
            self.assertLessEqual(
                (runres.stats_results.converged_status ==
                 tomographer.BinningAnalysis.NOT_CONVERGED *
                 np.ones([hist_params.num_bins], dtype=int)).sum(), 0)
            self.assertLessEqual(
                (runres.stats_results.converged_status ==
                 tomographer.BinningAnalysis.UNKNOWN_CONVERGENCE *
                 np.ones([hist_params.num_bins], dtype=int)).sum(), 2)
Ejemplo n.º 14
0
    def test_too_few_runs(self):

        print("test_too_few_runs()")
        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.99, 1, 10)

        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit="fidelity",
            ref_state=self.rho_ref,
            num_repeats=num_repeats,
            mhrw_params=tomographer.MHRWParams(0.04, 25, 500,
                                               100),  # 100 is too few runs
            hist_params=hist_params,
            ctrl_step_size_params={'enabled': False},
            ctrl_converged_params={'enabled': False},
        )
Ejemplo n.º 15
0
    def test_callback(self):

        print("test_callback()")

        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.985, 1, 200)

        class Ns:
            pass

        glob = Ns()
        glob.num_callback_calls = 0

        def progress_callback(fullstatusreport):
            glob.num_callback_calls += 1
            print(fullstatusreport.getHumanReport())

        intvl_ms = 200

        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit="obs-value",
            observable=self.rho_ref,
            num_repeats=num_repeats,
            mhrw_params=tomographer.MHRWParams(step_size=0.04,
                                               n_sweep=25,
                                               n_run=4 * 32768,
                                               n_therm=1024),
            hist_params=hist_params,
            progress_fn=progress_callback,
            progress_interval_ms=intvl_ms,
            ctrl_converged_params={'enabled': False},
        )

        # we have the total elapsed time in r['elapsed_seconds']

        print("Total elapsed: {:.2g} seconds".format(r['elapsed_seconds']))

        nc = 1000 * r['elapsed_seconds'] / intvl_ms
        self.assertGreaterEqual(glob.num_callback_calls, 1)
        self.assertLessEqual(glob.num_callback_calls, nc + 2)
Ejemplo n.º 16
0
    def test_convergence_control_2(self):

        print("test_convergence_control_2()")

        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.985, 1, 50)

        class Ns:
            pass

        glob = Ns()
        glob.num_callback_calls = 0

        def check_prg(report):
            glob.num_callback_calls += 1
            for r in report.workers:
                if r is not None and r.fraction_done > 1:
                    raise AssertionError(
                        "Control is disabled, random walk should not go past 100%"
                    )

        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit="obs-value",
            observable=self.rho_ref,
            num_repeats=num_repeats,
            mhrw_params=tomographer.MHRWParams(
                step_size=0.1,  # too high
                n_sweep=100,
                n_run=1024,  # little
                n_therm=1024),  # little
            hist_params=hist_params,
            progress_fn=check_prg,
            progress_interval_ms=1,
            ctrl_converged_params={'enabled': False},
            # keep step size a little off, to prevent bins from converging too nicely:
            ctrl_step_size_params={'enabled': False},
        )

        # make sure progress reporter was called often enough
        self.assertGreaterEqual(glob.num_callback_calls, 10)
Ejemplo n.º 17
0
def sampling(d, mmts, data, N, samplesize=2000):
    #r = None # global variable
    samples = []

    def store_sample_figofmerit(T):
        samples.append(T)
        return 0

    with tomographer.jpyutil.RandWalkProgressBar() as prg:
        r = tomographer.tomorun.tomorun(
            # the dimension of the quantum system
            dim=d,
            # the tomography data
            Emn=mmts,
            Nm=data * N,
            # Random Walk parameters: step size, sweep size, number of thermalization sweeps, number of live sweeps
            mhrw_params=tomographer.MHRWParams(0.01, 100, 2000, samplesize),
            fig_of_merit=store_sample_figofmerit,
            rng_base_seed=None,
            progress_fn=prg.progress_fn)
        prg.displayFinalInfo(r['final_report_runs'])
    return samples
Ejemplo n.º 18
0
    def test_chokes_on_extra_args(self):

        # just make sure that tomorun() raises an exception if unexpected arguments are
        # provided.
        with self.assertRaises(tomographer.tomorun.TomorunInvalidInputError):
            res = tomographer.tomorun.tomorun(
                dim=2,
                Emn=self.Emn,
                Nm=self.Nm,
                fig_of_merit='obs-value',
                observable=self.rho_ref,
                num_repeats=1,
                mhrw_params=tomographer.MHRWParams(
                    step_size=0.04,
                    n_sweep=25,
                    n_therm=1024,
                    n_run=1024,
                ),
                hist_params=tomographer.HistogramParams(),
                base_seed=1234567890,  # misspelled, should be "rng_base_seed"
                abc_wrong={'x': 'y'}  # just an additional arg
            )
Ejemplo n.º 19
0
def do_numerics():
    r = None
    with tomographer.jpyutil.RandWalkProgressBar() as prg:
        r = tomographer.tomorun.tomorun(
            dim=dim,
            Emn=Emn,
            Nm=Nm,
            jumps_method='light',
            fig_of_merit='obs-value',
            observable=proj_W,
            hist_params=tomographer.HistogramParams(0.99908, 0.99911, 200),
            mhrw_params=tomographer.MHRWParams(0.1, 50, 4096, 65536),
            binning_num_levels=12,
            ctrl_converged_params={
                'enabled': True,
                'max_allowed_not_converged': 20,
                'max_allowed_unknown': 20,
                'max_allowed_unknown_notisolated': 30
            },
            progress_fn=prg.progress_fn,
            progress_interval_ms=2000,
        )
        prg.displayFinalInfo(r['final_report_runs'])

    run_data = {
        'd': {
            'dim': dim,
            'Emn': Emn,
            'Nm': Nm,
            'psi_W': psi_W,
            'proj_W': proj_W
        },
        'r': r
    }
    with open(CACHE_FILE_NAME, 'wb') as f:
        pickle.dump(run_data, f, 2)

    return run_data
Ejemplo n.º 20
0
    def test_verbose_logging_2(self):

        print("test_verbose_logging_2()")

        oldlevel = tomographer.cxxlogger.level
        try:
            logging.getLogger().setLevel(1)  # LONGDEBUG
            tomographer.cxxlogger.level = 1  # LONGDEBUG

            def raise_stop_iter(T):
                raise StopIteration

            def prg_fn(report):
                logging.getLogger("prg_fn").debug(report.getHumanReport())

            # test: gets interrupted (test fix for some SEGFAULT I'm getting?)
            with self.assertRaises(StopIteration):
                r = tomographer.tomorun.tomorun(
                    dim=2,
                    Emn=self.Emn,
                    Nm=self.Nm,
                    fig_of_merit=raise_stop_iter,
                    num_repeats=4,
                    hist_params=tomographer.HistogramParams(0.99, 1, 20),
                    mhrw_params=tomographer.MHRWParams(
                        step_size=0.04,
                        # keep it REAL SHORT because we'll have tons of messages
                        n_sweep=5,
                        n_run=10,
                        n_therm=20),
                    progress_fn=prg_fn,
                    progress_interval_ms=50,
                    ctrl_step_size_params={'enabled': False},
                )
        finally:
            # restore level
            logging.getLogger().setLevel(oldlevel)
            tomographer.cxxlogger.level = oldlevel
Ejemplo n.º 21
0
    def test_stepsize_control_2(self):

        print("test_stepsize_control_2()")

        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.985, 1, 50)

        orig_step_size = 0.5
        orig_n_therm = 2

        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit="obs-value",
            observable=self.rho_ref,
            num_repeats=num_repeats,
            mhrw_params=tomographer.MHRWParams(
                step_size=orig_step_size,  # must be adjusted
                n_sweep=2,
                n_run=1024,
                n_therm=orig_n_therm),
            hist_params=hist_params,
            progress_fn=lambda report: print(report.getHumanReport()),
            progress_interval_ms=100,
            ctrl_step_size_params={'enabled': False},
            ctrl_converged_params={'enabled': False},
        )

        for runres in r['runs_results']:
            print("Step size is ",
                  runres.mhrw_params.mhwalker_params['step_size'])
            print("and n_therm is ", runres.mhrw_params.n_therm)
            # make sure it wasn't adjusted
            self.assertAlmostEqual(
                runres.mhrw_params.mhwalker_params['step_size'],
                orig_step_size)
            self.assertEqual(runres.mhrw_params.n_therm, orig_n_therm)
Ejemplo n.º 22
0
    def test_stepsize_control_1(self):

        print("test_stepsize_control_1()")

        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.985, 1, 50)

        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit="obs-value",
            observable=self.rho_ref,
            num_repeats=num_repeats,
            mhrw_params=tomographer.MHRWParams(
                step_size=0.5,  # must be adjusted
                n_sweep=2,
                n_run=1024,
                n_therm=1),
            hist_params=hist_params,
            progress_fn=lambda report: print(report.getHumanReport()),
            progress_interval_ms=100,
            ctrl_step_size_params={'enabled': True},
            ctrl_converged_params={'enabled': False},
        )

        for runres in r['runs_results']:
            print("Step size is ",
                  runres.mhrw_params.mhwalker_params['step_size'])
            print("and n_therm is ", runres.mhrw_params.n_therm)
            self.assertLessEqual(
                runres.mhrw_params.mhwalker_params['step_size'], 0.1)
            self.assertGreaterEqual(
                runres.mhrw_params.mhwalker_params['step_size'], 0.01)
            self.assertGreaterEqual(runres.acceptance_ratio, 0.2)
            self.assertLessEqual(runres.acceptance_ratio, 0.4)
            self.assertGreaterEqual(runres.mhrw_params.n_therm,
                                    20)  # make sure it was adjusted
Ejemplo n.º 23
0
    def test_convergence_control_1(self):

        print("test_convergence_control_1()")

        num_repeats = 2
        hist_params = tomographer.HistogramParams(0.985, 1, 50)

        r = tomographer.tomorun.tomorun(
            dim=2,
            Emn=self.Emn,
            Nm=self.Nm,
            fig_of_merit="obs-value",
            observable=self.rho_ref,
            num_repeats=num_repeats,
            mhrw_params=tomographer.MHRWParams(
                step_size=0.04,
                n_sweep=25,
                n_run=1024,  # ridicoulously low
                n_therm=200),
            hist_params=hist_params,
            progress_fn=lambda report: print(report.getHumanReport()),
            progress_interval_ms=100,
            ctrl_converged_params={
                'enabled': True,
                'max_allowed_unknown': 1,
                'max_allowed_unknown_notisolated': 1,
                'max_allowed_not_converged': 1,
                # run as long as is necessary
                'max_add_run_iters': -1
            },
        )

        for runres in r['runs_results']:
            summary = runres.stats_results.errorBarConvergenceSummary()
            self.assertLessEqual(summary.n_unknown, 1)
            self.assertLessEqual(
                summary.n_unknown - summary.n_unknown_isolated, 1)
            self.assertLessEqual(summary.n_not_converged, 1)
Ejemplo n.º 24
0
    def test_verbose_logging(self):

        print("test_verbose_logging()")

        oldlevel = tomographer.cxxlogger.level
        try:
            logging.getLogger().setLevel(1)  # LONGDEBUG
            tomographer.cxxlogger.level = 1  # LONGDEBUG

            def prg_fn(report):
                logging.getLogger("prg_fn").debug(report.getHumanReport())

            r = tomographer.tomorun.tomorun(
                dim=2,
                Emn=self.Emn,
                Nm=self.Nm,
                fig_of_merit=lambda T: npl.norm(np.dot(T, T.T.conj())
                                                ),  # purity
                ref_state=self.rho_ref,
                num_repeats=4,
                hist_params=tomographer.HistogramParams(0.99, 1, 20),
                mhrw_params=tomographer.MHRWParams(
                    step_size=0.04,
                    # keep it REAL SHORT because we'll have tons of messages
                    n_sweep=5,
                    n_run=10,
                    n_therm=20),
                progress_fn=prg_fn,
                progress_interval_ms=50,
                ctrl_step_size_params={'enabled': False},
            )

        finally:
            # restore level
            logging.getLogger().setLevel(oldlevel)
            tomographer.cxxlogger.level = oldlevel
Ejemplo n.º 25
0
            np.array([[.5, -.5], [-.5, .5]]),  # -X
            np.array([[.5, -.5j], [.5j, .5]]),  # +Y
            np.array([[.5, .5j], [-.5j, .5]]),  # -Y
            np.array([[1, 0], [0, 0]]),  # +Z
            np.array([[0, 0], [0, 1]])
        ],  # -Z
        Nm=np.array([262, 238, 231, 269, 483, 17]),  # plug in real data here
        # figure of merit: fidelity-squared to pure |0> state
        fig_of_merit="obs-value",
        observable=np.array([[1, 0], [0, 0]]),
        # histogram parameters
        hist_params=tomographer.HistogramParams(min=0.9, max=1.0, num_bins=40),
        # settings of the random walk
        mhrw_params=tomographer.MHRWParams(
            step_size=0.035,  # adjust such that accept. ratio ~ 0.25
            n_sweep=30,  # set such that step_size*n_sweep ~ 1
            n_therm=500,
            n_run=32768),
        # our progress callback
        progress_fn=prg.progress_fn)
    # Check the final report of runs to make sure error bars have (mostly all) converged,
    # and to verify the acceptance ratio is more or less in the range [0.2, 0.4]
    prg.displayFinalInfo(r['final_report_runs'])

# The final histogram, as a `tomographer.AveragedErrorBarHistogram` instance:
final_histogram = r['final_histogram']

# For a quick visual text-based representation of the histogram, use prettyPrint():
#
#print("Finished. Here is the final histogram:")
#print(final_histogram.prettyPrint())
Ejemplo n.º 26
0
logger = logging.getLogger(__name__)

import numpy as np

import my_custom_module
import tomographer

#
# Some minimal example data
#

Emn = [np.array([[1, 0], [0, 0]]), np.array([[0, 0], [0, 1]])]
Nm = np.array([98, 2])

r = my_custom_module.run(
    2,
    Emn=Emn,
    Nm=Nm,
    mhrw_params=tomographer.MHRWParams(step_size=0.01,
                                       n_sweep=100,
                                       n_therm=256,
                                       n_run=8192),
    hist_params=tomographer.HistogramParams(min=0.8, max=1.0, num_bins=40),
    progress_fn=lambda report: print(report.getHumanReport()),
)

print(r['final_report_runs'])

print("... and here is the final histogram:")
print(r['final_histogram'].prettyPrint())
Ejemplo n.º 27
0
# ## Bipartite sampling method

# In[5]:

r_naive = load_from_cache('r_naive')
if r_naive is None:
    # perform calculation
    with tomographer.jpyutil.RandWalkProgressBar() as prg:
        r_naive = QPtomographer.bistates.run(
            dimX=4,
            dimY=4,
            Emn=d.Emn,
            Nm=np.array(d.Nm),
            hist_params=tomographer.UniformBinsHistogramParams(0.1, 0.3, 100),
            mhrw_params=tomographer.MHRWParams(0.001, 1000, 2048, 32768),
            progress_fn=prg.progress_fn,
            progress_interval_ms=2000,
        )
        prg.displayFinalInfo(r_naive['final_report_runs'])
    save_to_cache('r_naive', r_naive)

print_report(r_naive)

# In[6]:

a_naive = do_analysis(r_naive, 'st., std.', plots=True)

# ## Bipartite sampling method, optimized

# In[7]:
Ejemplo n.º 28
0
                                [ 0, 0,    0, 0],
                                [ 0.95, 0, 0, 1],
                               ]), dims=[[2,2],[2,2]])

d = QPtomographer.util.simulate_process_measurements(sigmareal_X, Ereal_XY, PauliMeasSettings, PauliMeasSettings,
                                                 NumSamplesPerSetting)


# Naive, bipartite sampling method

r_naiveopt = None
with tomographer.jpyutil.RandWalkProgressBar() as prg:
    r_naiveopt = QPtomographer.bistates.run(
        dimX=2, dimY=2, Emn=d.Emn, Nm=np.array(d.Nm),
        hist_params=tomographer.HistogramParams(0, 0.2, 50),
        mhrw_params=tomographer.MHRWParams(0.008, 512, 32768, 32768), # thermalize a lot
        progress_fn=prg.progress_fn,
        jumps_method='light' # use optimized random walk
        )
    prg.displayFinalInfo(r_naiveopt['final_report_runs'])
print("Calculation ran for {!s} seconds".format(datetime.timedelta(seconds=r_naiveopt['elapsed_seconds'])))
print(r_naiveopt['final_report_runs'])


analysis_naiveopt = tomographer.querrorbars.HistogramAnalysis(r_naiveopt['final_histogram'],
                                                              threshold_fraction=1e-3)

analysis_naiveopt.plot()


# Channel-space method
Ejemplo n.º 29
0
# Now, we're ready to run our tomography procedure. We'll be estimating
# the expectation value of the entanglement witness.

r = None # global variable

with tomographer.jpyutil.RandWalkProgressBar() as prg:
    r = tomographer.tomorun.tomorun(
        # the dimension of the quantum system
        dim=4,
        # the tomography data
        Nm=Nm,
        Emn=Emn,
        # Histogram: values in [1.6, 2.0] split into 50 bins
        hist_params=tomographer.UniformBinsHistogramParams(1.6,2,50),
        # Random Walk parameters: step size, sweep size, number of thermalization sweeps, number of live sweeps
        mhrw_params=tomographer.MHRWParams(0.009,240,2048,32768),
        # figure of merit:
        fig_of_merit="obs-value",
        observable=EntglWitness.data.toarray(),
        #num_repeats=12, # default value = auto-detect number of CPU's
        progress_fn=prg.progress_fn
    )
    prg.displayFinalInfo(r['final_report_runs'])


# In[14]:

# Collect the histogram
final_histogram = r['final_histogram']