def test_HistogramParams(self): # constructors params = tomographer.HistogramParams(2.0, 3.0, 5) self.assertAlmostEqual(params.min, 2.0) self.assertAlmostEqual(params.max, 3.0) self.assertEqual(params.num_bins, 5) npt.assert_array_almost_equal(params.values_lower, np.array([2.0, 2.2, 2.4, 2.6, 2.8])) npt.assert_array_almost_equal(params.values_upper, np.array([2.2, 2.4, 2.6, 2.8, 3.0])) npt.assert_array_almost_equal(params.values_center, np.array([2.1, 2.3, 2.5, 2.7, 2.9])) # default constructor paramsdflt = tomographer.HistogramParams() self.assertTrue(paramsdflt.min < paramsdflt.max and paramsdflt.num_bins > 0) # w/ keyword arguments params = tomographer.HistogramParams(min=2.0, max=3.0, num_bins=5) self.assertAlmostEqual(params.min, 2.0) self.assertAlmostEqual(params.max, 3.0) self.assertEqual(params.num_bins, 5) # binCenterValue() self.assertAlmostEqual(params.binCenterValue(0), 2.1) self.assertAlmostEqual(params.binCenterValue(4), 2.9) with self.assertRaises(tomographer.TomographerCxxError): x = params.binCenterValue(999) with self.assertRaises(tomographer.TomographerCxxError): x = params.binCenterValue(5) # binLowerValue() self.assertAlmostEqual(params.binLowerValue(0), 2.0) self.assertAlmostEqual(params.binLowerValue(4), 2.8) with self.assertRaises(tomographer.TomographerCxxError): x = params.binLowerValue(999) with self.assertRaises(tomographer.TomographerCxxError): x = params.binLowerValue(5) # binUpperValue() self.assertAlmostEqual(params.binUpperValue(0), 2.2) self.assertAlmostEqual(params.binUpperValue(4), 3.0) with self.assertRaises(tomographer.TomographerCxxError): x = params.binUpperValue(999) with self.assertRaises(tomographer.TomographerCxxError): x = params.binUpperValue(5) # self.assertAlmostEqual(params.binResolution(), 0.2) self.assertTrue(params.isWithinBounds(2.0)) self.assertTrue(params.isWithinBounds(2.2)) self.assertFalse(params.isWithinBounds(3.0001)) self.assertFalse(params.isWithinBounds(1.99)) # repr() self.assertEqual(repr(params), 'HistogramParams(min=2,max=3,num_bins=5)')
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)
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, )
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)
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)
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))
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)
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)
def do_histogram(): d = {} if tveri < (5, 0): # Tomographer < 5.0 p = tomographer.UniformBinsHistogramParams(0.0, 1.0, 5) d["UniformBinsHistogramParams"] = p else: # Tomographer >= 5.0 p = tomographer.HistogramParams(0.0, 1.0, 5) d["HistogramParams"] = p def load_values_maybe_error_bars(h, values, errors, off_chart=0): if not h.has_error_bars: h.load(values, off_chart) else: h.load(values, errors, off_chart) if tveri < (5, 0): # Tomographer < 5.0 klasses = [ (tomographer.UniformBinsHistogram, 'UniformBinsHistogram'), (tomographer.UniformBinsRealHistogram, 'UniformBinsRealHistogram'), (tomographer.UniformBinsHistogramWithErrorBars, 'UniformBinsHistogramWithErrorBars'), (tomographer.AveragedSimpleHistogram, 'AveragedSimpleHistogram'), (tomographer.AveragedSimpleRealHistogram, 'AveragedSimpleRealHistogram'), (tomographer.AveragedErrorBarHistogram, 'AveragedErrorBarHistogram'), ] else: # Tomographer >= 5.0 klasses = [ (tomographer.Histogram, 'Histogram'), (tomographer.HistogramWithErrorBars, 'HistogramWithErrorBars'), ] for c, n in klasses: x = c(p) load_values_maybe_error_bars(x, np.array([10, 20, 30, 40, 50]), np.array([1, 2, 3, 4, 5]), 28) d[n] = x # save all of this stuff as a pickle with open(os.path.join(pickledatadir, 'histograms.pickle'), 'wb') as f: pickle.dump(d, f, 2)
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)
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)
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}, )
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)
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)
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 )
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)
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
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)
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
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
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
# ## 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=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, 125, 2048, 32768), progress_fn=prg.progress_fn) 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]:
def do_test_avghist(self, AvgHCl, BaseHCl, cnttyp, base_has_error_bars): # # test that the AvgHCl can average histograms correctly. Use the same test cases # as in the C++ test. # print("do_test_avghist()") param = tomographer.HistogramParams(0.0, 1.0, 4) # constructor & histogram-related methods already tested in do_test_hist avghist = AvgHCl(param) self.assertEqual(avghist.num_histograms, 0) if not base_has_error_bars: OFF_IDX = 1 data = [ (np.array([15, 45, 42, 12]), 36), (np.array([17, 43, 40, 18]), 32), (np.array([20, 38, 47, 10]), 35), (np.array([18, 44, 43, 13]), 32), ] else: OFF_IDX = 2 data = [ (np.array([15, 45, 42, 12]), np.array([1, 1, 1, 1]), 36), (np.array([17, 43, 40, 18]), np.array([2, 2, 5, 2]), 32), (np.array([20, 38, 47, 10]), np.array([1, 2, 13, 4]), 35), (np.array([18, 44, 43, 13]), np.array([2, 1, 24, 3]), 32), ] k = 0 for dat in data: h = BaseHCl(param) h.load(*dat) avghist.addHistogram(h) k += 1 self.assertEqual(avghist.num_histograms, k) avghist.finalize() avgdata = np.array([ sum([float(data[k][0][n]) for k in range(len(data))]) / avghist.num_histograms for n in range(4) ]) if not base_has_error_bars: avgerr = np.array([ np.sqrt(( sum([float(data[k][0][n])**2 for k in range(len(data))]) / avghist.num_histograms - (avgdata[n])**2) / (avghist.num_histograms - 1)) for n in range(4) ]) else: avgerr = np.array([ np.sqrt( sum([float(data[k][1][n])**2 for k in range(len(data))])) / avghist.num_histograms for n in range(4) ]) avgoff = sum([float(data[k][OFF_IDX]) for k in range(len(data))]) / avghist.num_histograms npt.assert_array_almost_equal(avghist.bins, avgdata) npt.assert_array_almost_equal(avghist.delta, avgerr) self.assertAlmostEqual(avghist.off_chart, avgoff) self.assertAlmostEqual(np.sum(avghist.bins) + avghist.off_chart, 150) # check for reset(param) param2 = tomographer.HistogramParams(1.0, 2.0, 20) avghist.reset(param2) self.assertEqual(avghist.num_histograms, 0) npt.assert_array_almost_equal(avghist.bins, np.zeros(20)) self.assertAlmostEqual(avghist.off_chart, 0) self.assertAlmostEqual(avghist.params.min, param2.min) self.assertAlmostEqual(avghist.params.max, param2.max) self.assertEqual(avghist.params.num_bins, param2.num_bins) # dummy -- add a histogram again ... h = BaseHCl(param2) if not base_has_error_bars: h.load(np.array(range(20))) else: h.load(np.array(range(20)), np.array(range(20)) / 10.0) avghist.addHistogram(h) # ... and check for reset() avghist.reset() self.assertEqual(avghist.num_histograms, 0) npt.assert_array_almost_equal(avghist.bins, np.zeros(20)) self.assertAlmostEqual(avghist.off_chart, 0) # make sure that params have been kept self.assertAlmostEqual(avghist.params.min, param2.min) self.assertAlmostEqual(avghist.params.max, param2.max) self.assertEqual(avghist.params.num_bins, param2.num_bins) # test pickling # see http://pybind11.readthedocs.io/en/master/advanced/classes.html#pickling-support try: import cPickle as pickle except: import pickle avghist = AvgHCl(param2) # add some histograms h = BaseHCl(param2) if not base_has_error_bars: h.load(np.array(range(20))) else: h.load(np.array(range(20)), np.array(range(20)) / 10.0) avghist.addHistogram(h) h = BaseHCl(param2) if not base_has_error_bars: h.load(np.array(range(20))) else: h.load(np.array(range(20)), np.array(range(20)) / 10.0) avghist.addHistogram(h) # and now do the pickling s = pickle.dumps(avghist, 2) avghist2 = pickle.loads(s) self.assertAlmostEqual(avghist2.params.min, avghist.params.min) self.assertAlmostEqual(avghist2.params.max, avghist.params.max) self.assertEqual(avghist2.params.num_bins, avghist.params.num_bins) npt.assert_array_almost_equal(avghist2.bins, avghist.bins) npt.assert_array_almost_equal(avghist2.delta, avghist.delta) self.assertEqual(avghist2.num_histograms, avghist.num_histograms)
def do_test_hist(self, HCl, cnttype, has_error_bars): print("do_test_hist()") # constructor & params member self.assertAlmostEqual(HCl(2.0, 3.0, 5).params.min, 2.0) self.assertAlmostEqual(HCl(2.0, 3.0, 5).params.max, 3.0) self.assertEqual(HCl(2.0, 3.0, 5).params.num_bins, 5) self.assertAlmostEqual( HCl(tomographer.HistogramParams(2.0, 3.0, 5)).params.min, 2.0) self.assertAlmostEqual( HCl(tomographer.HistogramParams(2.0, 3.0, 5)).params.max, 3.0) self.assertEqual( HCl(tomographer.HistogramParams(2.0, 3.0, 5)).params.num_bins, 5) h = HCl() # has default constructor print("Default histogram parameters: ", h.params.min, h.params.max, h.params.num_bins) # values_center, values_lower, values_upper npt.assert_array_almost_equal( HCl(2.0, 3.0, 5).values_lower, np.array([2.0, 2.2, 2.4, 2.6, 2.8])) npt.assert_array_almost_equal( HCl(2.0, 3.0, 5).values_upper, np.array([2.2, 2.4, 2.6, 2.8, 3.0])) npt.assert_array_almost_equal( HCl(2.0, 3.0, 5).values_center, np.array([2.1, 2.3, 2.5, 2.7, 2.9])) # constructor sets zero bin values & off_chart h = HCl() npt.assert_array_almost_equal(h.bins, np.zeros(h.numBins())) self.assertAlmostEqual(h.off_chart, 0) # almost-equal in case cnttype=float if has_error_bars: npt.assert_array_almost_equal(h.delta, np.zeros(h.numBins())) h = HCl(2.0, 3.0, 5) npt.assert_array_almost_equal(h.bins, np.array([0, 0, 0, 0, 0])) self.assertAlmostEqual(h.off_chart, 0) # almost-equal in case cnttype=float if has_error_bars: npt.assert_array_almost_equal(h.delta, np.zeros(h.numBins())) h = HCl(tomographer.HistogramParams(2.0, 3.0, 5)) npt.assert_array_almost_equal(h.bins, np.array([0, 0, 0, 0, 0])) self.assertAlmostEqual(h.off_chart, 0) # almost-equal in case cnttype=float if has_error_bars: npt.assert_array_almost_equal(h.delta, np.zeros(h.numBins())) # has_error_bars h = HCl(2.0, 3.0, 5) self.assertTrue(h.has_error_bars == has_error_bars) # numBins() h = HCl(2.0, 3.0, 5) self.assertEqual(h.numBins(), 5) # bins, off_chart h = HCl(2.0, 3.0, 5) h.bins = np.array([1, 4, 9, 5, 2]) npt.assert_array_almost_equal(h.bins, np.array([1, 4, 9, 5, 2])) h.off_chart = 156 self.assertAlmostEqual(h.off_chart, 156) # almost-equal in case cnttype=float # delta [if error bars] if has_error_bars: h = HCl(2.0, 3.0, 5) h.delta = np.array([1, 2, 3, 4, 0.25]) npt.assert_array_almost_equal(h.delta, np.array([1, 2, 3, 4, 0.25])) # count() h = HCl(2.0, 3.0, 5) h.bins = np.array([1, 4, 9, 5, 2]) h.off_chart = 17 for i in range(h.numBins()): self.assertAlmostEqual(h.bins[i], h.count(i)) with self.assertRaises(IndexError): n = h.count(9999) # out of range # errorBar() [if error bars] if has_error_bars: h = HCl(2.0, 3.0, 5) h.delta = np.array([1, 2, 3, 4, 0.25]) for i in range(h.numBins()): self.assertAlmostEqual(h.delta[i], h.errorBar(i)) with self.assertRaises(IndexError): n = h.errorBar(9999) # out of range # load() def load_values_maybe_error_bars(h, values, errors, off_chart=None): if off_chart is None: if not has_error_bars: h.load(values) else: h.load(values, errors) else: if not has_error_bars: h.load(values, off_chart) else: h.load(values, errors, off_chart) # load(x[, e]) h = HCl(2.0, 3.0, 5) h.bins = np.array([1, 4, 9, 5, 2]) load_values_maybe_error_bars(h, np.array([10, 20, 30, 40, 50]), np.array([1, 2, 3, 4, 5])) npt.assert_array_almost_equal(h.bins, np.array([10, 20, 30, 40, 50])) if has_error_bars: npt.assert_array_almost_equal(h.delta, np.array([1, 2, 3, 4, 5])) self.assertAlmostEqual(h.off_chart, 0) # almost-equal in case cnttype=float # load(x[, e], off_chart) h = HCl(2.0, 3.0, 5) h.bins = np.array([1, 4, 9, 5, 2]) load_values_maybe_error_bars(h, np.array([10, 20, 30, 40, 50]), np.array([1, 2, 3, 4, 5]), 28) npt.assert_array_almost_equal(h.bins, np.array([10, 20, 30, 40, 50])) if has_error_bars: npt.assert_array_almost_equal(h.delta, np.array([1, 2, 3, 4, 5])) self.assertAlmostEqual(h.off_chart, 28) # almost-equal in case cnttype=float # load(x, e) error if wrong signature if has_error_bars: with self.assertRaises(Exception): h.load(np.array([10, 20, 30, 40, 50])) with self.assertRaises(Exception): h.load(np.array([10, 20, 30, 40, 50]), 10.0) else: with self.assertRaises(Exception): h.load(np.array([10, 20, 30, 40, 50]), np.array([1, 2, 3, 4, 5])) with self.assertRaises(Exception): h.load(np.array([10, 20, 30, 40, 50]), np.array([1, 2, 3, 4, 5]), 10.0) # add() if not has_error_bars: h = HCl(2.0, 3.0, 5) h.bins = np.array([1, 4, 9, 5, 2]) h.add(np.array([10, 20, 30, 40, 50])) npt.assert_array_almost_equal(h.bins, np.array([11, 24, 39, 45, 52])) self.assertAlmostEqual(h.off_chart, 0) # almost-equal in case cnttype=float # add() if not has_error_bars: h = HCl(2.0, 3.0, 5) h.bins = np.array([1, 4, 9, 5, 2]) h.off_chart = 4 h.add(np.array([10, 20, 30, 40, 50]), 28) npt.assert_array_almost_equal(h.bins, np.array([11, 24, 39, 45, 52])) self.assertAlmostEqual(h.off_chart, 32) # almost-equal in case cnttype=float # reset() h = HCl(2.0, 3.0, 5) load_values_maybe_error_bars(h, np.array([10, 20, 30, 40, 50]), np.array([1, 2, 3, 4, 5]), 28) h.reset() npt.assert_array_almost_equal(h.bins, np.array([0, 0, 0, 0, 0])) self.assertAlmostEqual(h.off_chart, 0) # almost-equal in case cnttype=float # record() if not has_error_bars: h = HCl(2.0, 3.0, 5) load_values_maybe_error_bars(h, np.array([10, 20, 30, 40, 50]), np.array([1, 2, 3, 4, 5]), 28) h.record(2.569) self.assertAlmostEqual(h.count(2), 31) h.record(2.569, cnttype(2)) self.assertAlmostEqual(h.count(2), 33) h.record(2.981) self.assertAlmostEqual(h.count(4), 51) h.record(2.981, cnttype(7)) self.assertAlmostEqual(h.count(4), 58) # normalization(), normalized() h = HCl(2.0, 3.0, 5) load_values_maybe_error_bars(h, np.array([10, 20, 30, 40, 50]), np.array([1, 2, 3, 4, 5]), 28) #print("BINS=",repr(h.bins), repr(h.off_chart)) n = h.normalization() #print("NORMALIZATION=",n) self.assertAlmostEqual( n, np.sum(np.array([10, 20, 30, 40, 50])) / 5.0 + 28) hn = h.normalized() npt.assert_array_almost_equal(hn.bins, h.bins / n) self.assertAlmostEqual(hn.off_chart, h.off_chart / n) if has_error_bars: npt.assert_array_almost_equal(hn.delta, h.delta / n) self.assertAlmostEqual(hn.normalization(), 1.0) # totalCounts(), normalizedCounts() c = h.totalCounts() print("TOTALCOUNTS=", c) self.assertAlmostEqual(c, np.sum(np.array([10, 20, 30, 40, 50])) + 28) hc = h.normalizedCounts() npt.assert_array_almost_equal(hc.bins, np.true_divide(h.bins, c)) self.assertAlmostEqual(hc.off_chart, np.true_divide(h.off_chart, c)) if has_error_bars: npt.assert_array_almost_equal(hc.delta, np.true_divide(h.delta, c)) self.assertAlmostEqual(hc.totalCounts(), 1.0) # prettyPrint() h = HCl(2.0, 3.0, 5) load_values_maybe_error_bars(h, np.array([10, 20, 30, 40, 50]), np.array([1, 2, 3, 4, 5]), 28) s = h.prettyPrint() print(s) s = h.prettyPrint(120) for line in s.split('\n'): if line: self.assertEqual(len(line), 120) # see http://pybind11.readthedocs.io/en/master/advanced/classes.html#pickling-support try: import cPickle as pickle except: import pickle h = HCl(2.0, 3.0, 5) load_values_maybe_error_bars(h, np.array([10, 20, 30, 40, 50]), np.array([1, 2, 3, 4, 5]), 28) s = pickle.dumps(h, 2) print("PICKLE:\n" + str(s)) h2 = pickle.loads(s) self.assertAlmostEqual(h2.params.min, h.params.min) self.assertAlmostEqual(h2.params.max, h.params.max) self.assertEqual(h2.params.num_bins, h.params.num_bins) npt.assert_array_almost_equal(h2.bins, h.bins) if has_error_bars: npt.assert_array_almost_equal(h2.delta, h.delta)
dim=2, # POVM effects and frequencies -- Pauli measurements on a qubit, 500x/axis Emn=[ np.array([[.5, .5], [.5, .5]]), # +X 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']
[ 0, 0.05, 0, 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()