Skip to content

Commit e77f99c

Browse files
committed
remove the MyClass.builder(...) method for MyClass subclasses of MDCObjectiveFunction. In-line equivalent code of the form builder = ObjectiveFunctionBuilder(MyClass)
1 parent b5ed48e commit e77f99c

File tree

11 files changed

+50
-104
lines changed

11 files changed

+50
-104
lines changed

pygsti/objectivefns/objectivefns.py

Lines changed: 11 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ def cast(obj):
178178

179179
# This was a classmethod, but I made it static because this class has no derived classes.
180180
@staticmethod
181-
def create_from(objective='logl', freq_weighted_chi2=False):
181+
def create_from(objective='logl', freq_weighted_chi2=False, penalty_callable=None):
182182
"""
183183
Creates common :class:`ObjectiveFunctionBuilder` from a few arguments.
184184
@@ -193,37 +193,23 @@ def create_from(objective='logl', freq_weighted_chi2=False):
193193
Returns
194194
-------
195195
ObjectiveFunctionBuilder
196-
197-
Notes
198-
-----
199-
This function's implementation calls relies on various "builder" classmethods of other classes.
200-
There is a default implementation of `.builder` that's triggered in most codepaths. That
201-
default is to just return
202-
203-
ObjectiveFunctionBuilder(cls, name, description, regularization, penalties, **kwargs).
204-
205-
In these cases, the kwargs that we pass to `.builder` functions get seen as **kwargs
206-
for a call to the ObjectiveFunctionBuilder constructor. Those kwargs are stored in the
207-
`.additional_args` member of the returned ObjectiveFunctionBuilder object. That member
208-
is passed as **kwargs to the constructor for the input `cls` when we call `.build()` on
209-
the ObjectiveFunctionBuilder instance.
210196
"""
211197
if objective == "chi2":
212198
if freq_weighted_chi2:
213-
builder = FreqWeightedChi2Function.builder(
199+
builder = ObjectiveFunctionBuilder(FreqWeightedChi2Function,
214200
name='fwchi2',
215201
description="Freq-weighted sum of Chi^2",
216202
regularization={'min_freq_clip_for_weighting': 1e-4}
217203
)
218204
else:
219-
builder = Chi2Function.builder(
205+
builder = ObjectiveFunctionBuilder(Chi2Function,
220206
name='chi2',
221207
description="Sum of Chi^2",
222208
regularization={'min_prob_clip_for_weighting': 1e-4}
223209
)
224210

225211
elif objective == "logl":
226-
builder = PoissonPicDeltaLogLFunction.builder(
212+
builder = ObjectiveFunctionBuilder(PoissonPicDeltaLogLFunction,
227213
name='dlogl',
228214
description="2*Delta(log(L))",
229215
regularization={'min_prob_clip': 1e-4,
@@ -239,15 +225,19 @@ def create_from(objective='logl', freq_weighted_chi2=False):
239225
assert objective == 'normalized tvd'
240226
else:
241227
assert objective == 'tvd'
242-
builder = TVDFunction.builder(name=objective, description=descr)
228+
builder = ObjectiveFunctionBuilder(TVDFunction, name=objective, description=descr)
243229

244230
elif isinstance(objective, tuple) and objective[0] == 'Lp^p':
245231
power = objective[1]
246-
builder = LpNormToPowerP.builder(name='Lp^p', description=f"L_{power} norm to the power {power}.", power=objective[1])
232+
builder = ObjectiveFunctionBuilder(LpNormToPowerP,
233+
name='Lp^p',
234+
description=f"L_{power} norm to the power {power}.",
235+
power=objective[1]
236+
)
247237

248238
else:
249239
raise ValueError("Invalid objective: %s" % objective)
250-
assert(isinstance(builder, ObjectiveFunctionBuilder)), "This function should always return an ObjectiveFunctionBuilder!"
240+
251241
return builder
252242

253243
def __init__(self, cls_to_build, name=None, description=None, regularization=None, penalties=None, **kwargs):
@@ -4259,31 +4249,6 @@ class TimeIndependentMDCObjectiveFunction(MDCObjectiveFunction):
42594249
%s
42604250
"""
42614251

4262-
@classmethod
4263-
def builder(cls, name=None, description=None, regularization=None, penalties=None, **kwargs):
4264-
"""
4265-
Create an :class:`ObjectiveFunctionBuilder` that builds an objective function of this type.
4266-
4267-
Parameters
4268-
----------
4269-
name : str, optional
4270-
A name for the built objective function (can be anything).
4271-
4272-
description : str, optional
4273-
A description for the built objective function (can be anything)
4274-
4275-
regularization : dict, optional
4276-
Regularization values.
4277-
4278-
penalties : dict, optional
4279-
Penalty values.
4280-
4281-
Returns
4282-
-------
4283-
ObjectiveFunctionBuilder
4284-
"""
4285-
return ObjectiveFunctionBuilder(cls, name, description, regularization, penalties, **kwargs)
4286-
42874252
@classmethod
42884253
def _create_mdc_store(cls, model, dataset, circuits, resource_alloc,
42894254
method_names=('fn',), array_types=(), verbosity=0):
@@ -5173,31 +5138,6 @@ class TimeDependentMDCObjectiveFunction(MDCObjectiveFunction):
51735138
Level of detail to print to stdout.
51745139
"""
51755140

5176-
@classmethod
5177-
def builder(cls, name=None, description=None, regularization=None, penalties=None, **kwargs):
5178-
"""
5179-
Create an :class:`ObjectiveFunctionBuilder` that builds an objective function of this type.
5180-
5181-
Parameters
5182-
----------
5183-
name : str, optional
5184-
A name for the built objective function (can be anything).
5185-
5186-
description : str, optional
5187-
A description for the built objective function (can be anything)
5188-
5189-
regularization : dict, optional
5190-
Regularization values.
5191-
5192-
penalties : dict, optional
5193-
Penalty values.
5194-
5195-
Returns
5196-
-------
5197-
ObjectiveFunctionBuilder
5198-
"""
5199-
return ObjectiveFunctionBuilder(cls, name, description, regularization, penalties, **kwargs)
5200-
52015141
#This objective function can handle time-dependent circuits - that is, circuits are treated as
52025142
# potentially time-dependent and mdl as well. For now, we don't allow any regularization or penalization
52035143
# in this case.

pygsti/protocols/estimate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ def __init__(self, parent, models=None, parameters=None, extra_parameters=None):
163163
self.profiler = parameters.get('profiler', None)
164164
self._final_mdc_store = parameters.get('final_mdc_store', None)
165165
self._final_objfn_cache = parameters.get('final_objfn_cache', None)
166-
self.final_objfn_builder = parameters.get('final_objfn_builder', _objfns.PoissonPicDeltaLogLFunction.builder())
166+
self.final_objfn_builder = parameters.get('final_objfn_builder', _objfns.ObjectiveFunctionBuilder(_objfns.PoissonPicDeltaLogLFunction))
167167
self._final_objfn = parameters.get('final_objfn', None)
168168

169169
self.extra_parameters = extra_parameters if (extra_parameters is not None) else {}

pygsti/protocols/gst.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1654,7 +1654,7 @@ def run(self, data, memlimit=None, comm=None):
16541654
parameters['protocol'] = self # Estimates can hold sub-Protocols <=> sub-results
16551655
parameters['profiler'] = profiler
16561656
parameters['final_mdc_store'] = final_store
1657-
parameters['final_objfn_builder'] = _objfns.PoissonPicDeltaLogLFunction.builder()
1657+
parameters['final_objfn_builder'] = _objfns.ObjectiveFunctionBuilder(_objfns.PoissonPicDeltaLogLFunction)
16581658
# just set final objective function as default logl objective (for ease of later comparison)
16591659

16601660
ret = ModelEstimateResults(data, self)

test/performance/mpi_2D_scaling/run_me_with_mpirun.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,14 @@
3131
ds = ds_ref
3232

3333
MINCLIP = 1e-4
34-
chi2_builder = pygsti.objectivefns.Chi2Function.builder(
35-
'chi2', regularization={'min_prob_clip_for_weighting': MINCLIP}, penalties={'cptp_penalty_factor': 0.0})
36-
mle_builder = pygsti.objectivefns.PoissonPicDeltaLogLFunction.builder(
37-
'logl', regularization={'min_prob_clip': MINCLIP, 'radius': MINCLIP})
34+
chi2_builder = pygsti.objectivefns.ObjectiveFunctionBuilder(
35+
pygsti.objectivefns.Chi2Function,
36+
'chi2', regularization={'min_prob_clip_for_weighting': MINCLIP}, penalties={'cptp_penalty_factor': 0.0}
37+
)
38+
mle_builder = pygsti.objectivefns.ObjectiveFunctionBuilder(
39+
pygsti.objectivefns.PoissonPicDeltaLogLFunction,
40+
'logl', regularization={'min_prob_clip': MINCLIP, 'radius': MINCLIP}
41+
)
3842
iteration_builders = [chi2_builder]; final_builders = [mle_builder]
3943
builders = pygsti.protocols.GSTObjFnBuilders(iteration_builders, final_builders)
4044

test/test_packages/drivers/test_timedep.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import logging
2+
3+
import pygsti.objectivefns
24
mpl_logger = logging.getLogger('matplotlib')
35
mpl_logger.setLevel(logging.WARNING)
46

@@ -109,7 +111,8 @@ def test_time_dependent_gst_staticdata(self):
109111
target_model.sim = pygsti.forwardsims.MapForwardSimulator(max_cache_size=0) # No caching allowed for time-dependent calcs
110112
self.assertEqual(ds.degrees_of_freedom(aggregate_times=False), 57)
111113

112-
builders = pygsti.protocols.GSTObjFnBuilders([pygsti.objectivefns.TimeDependentPoissonPicLogLFunction.builder()], [])
114+
builder = pygsti.objectivefns.ObjectiveFunctionBuilder(pygsti.objectivefns.TimeDependentPoissonPicLogLFunction)
115+
builders = pygsti.protocols.GSTObjFnBuilders([builder], [])
113116
gst = pygsti.protocols.GateSetTomography(target_model, gaugeopt_suite=None,
114117
objfn_builders=builders,
115118
optimizer={'maxiter':2,'tol': 1e-4})
@@ -162,7 +165,8 @@ def test_time_dependent_gst(self):
162165
target_model.operations['Gi',0] = MyTimeDependentIdle(0) # start assuming no time dependent decay
163166
target_model.sim = pygsti.forwardsims.MapForwardSimulator(max_cache_size=0) # No caching allowed for time-dependent calcs
164167

165-
builders = pygsti.protocols.GSTObjFnBuilders([pygsti.objectivefns.TimeDependentPoissonPicLogLFunction.builder()], [])
168+
builder = pygsti.objectivefns.ObjectiveFunctionBuilder(pygsti.objectivefns.TimeDependentPoissonPicLogLFunction)
169+
builders = pygsti.protocols.GSTObjFnBuilders([builder], [])
166170
gst = pygsti.protocols.GateSetTomography(target_model, gaugeopt_suite=None,
167171
objfn_builders=builders, optimizer={'maxiter':10,'tol': 1e-4})
168172
data = pygsti.protocols.ProtocolData(edesign, ds)

test/test_packages/objects/test_hessian.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ def test_confidenceRegion(self):
130130
res = proto.ModelEstimateResults(data, proto.StandardGST(modes="full TP"))
131131

132132
#Add estimate for hessian-based CI --------------------------------------------------
133-
builder = pygsti.objectivefns.PoissonPicDeltaLogLFunction.builder()
133+
builder = pygsti.objectivefns.ObjectiveFunctionBuilder(pygsti.objectivefns.PoissonPicDeltaLogLFunction)
134134
res.add_estimate(
135135
proto.estimate.Estimate.create_gst_estimate(
136136
res, smq1Q_XY.target_model(), smq1Q_XY.target_model(),

test/unit/algorithms/test_core.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from pygsti.baseobjs import Label
77
from pygsti.circuits import Circuit, CircuitList
88
from pygsti.objectivefns import Chi2Function, FreqWeightedChi2Function, \
9-
PoissonPicDeltaLogLFunction
9+
PoissonPicDeltaLogLFunction, ObjectiveFunctionBuilder
1010
from . import fixtures
1111
from ..util import BaseCase
1212

@@ -117,7 +117,7 @@ def test_do_mc2gst(self):
117117
# TODO assert correctness
118118

119119
def test_do_mc2gst_regularize_factor(self):
120-
obj_builder = Chi2Function.builder(
120+
obj_builder = ObjectiveFunctionBuilder(Chi2Function,
121121
name='chi2',
122122
description="Sum of chi^2",
123123
regularization={'min_prob_clip_for_weighting': 1e-4},
@@ -130,7 +130,7 @@ def test_do_mc2gst_regularize_factor(self):
130130
# TODO assert correctness
131131

132132
def test_do_mc2gst_CPTP_penalty_factor(self):
133-
obj_builder = Chi2Function.builder(
133+
obj_builder = ObjectiveFunctionBuilder(Chi2Function,
134134
name='chi2',
135135
description="Sum of chi^2",
136136
regularization={'min_prob_clip_for_weighting': 1e-4},
@@ -143,7 +143,7 @@ def test_do_mc2gst_CPTP_penalty_factor(self):
143143
# TODO assert correctness
144144

145145
def test_do_mc2gst_SPAM_penalty_factor(self):
146-
obj_builder = Chi2Function.builder(
146+
obj_builder = ObjectiveFunctionBuilder(Chi2Function,
147147
name='chi2',
148148
description="Sum of chi^2",
149149
regularization={'min_prob_clip_for_weighting': 1e-4},
@@ -156,7 +156,7 @@ def test_do_mc2gst_SPAM_penalty_factor(self):
156156
# TODO assert correctness
157157

158158
def test_do_mc2gst_CPTP_SPAM_penalty_factor(self):
159-
obj_builder = Chi2Function.builder(
159+
obj_builder = ObjectiveFunctionBuilder(Chi2Function,
160160
name='chi2',
161161
description="Sum of chi^2",
162162
regularization={'min_prob_clip_for_weighting': 1e-4},
@@ -202,7 +202,7 @@ def test_do_iterative_mc2gst(self):
202202
# TODO assert correctness
203203

204204
def test_do_iterative_mc2gst_regularize_factor(self):
205-
obj_builder = Chi2Function.builder(
205+
obj_builder = ObjectiveFunctionBuilder(Chi2Function,
206206
name='chi2',
207207
description="Sum of chi^2",
208208
regularization={'min_prob_clip_for_weighting': 1e-4},
@@ -218,7 +218,7 @@ def test_do_iterative_mc2gst_regularize_factor(self):
218218
# TODO assert correctness
219219

220220
def test_do_iterative_mc2gst_use_freq_weighted_chi2(self):
221-
obj_builder = FreqWeightedChi2Function.builder(
221+
obj_builder = ObjectiveFunctionBuilder(FreqWeightedChi2Function,
222222
name='freq-weighted-chi2',
223223
description="Sum of chi^2",
224224
regularization={'min_freq_clip_for_weighting': 1e-4}
@@ -269,7 +269,7 @@ def test_do_mlgst(self):
269269
# TODO assert correctness
270270

271271
def test_do_mlgst_CPTP_penalty_factor(self):
272-
obj_builder = PoissonPicDeltaLogLFunction.builder(
272+
obj_builder = ObjectiveFunctionBuilder(PoissonPicDeltaLogLFunction,
273273
name='logl',
274274
description="2*DeltaLogL",
275275
regularization={'min_prob_clip': 1e-4},
@@ -283,7 +283,7 @@ def test_do_mlgst_CPTP_penalty_factor(self):
283283
# TODO assert correctness
284284

285285
def test_do_mlgst_SPAM_penalty_factor(self):
286-
obj_builder = PoissonPicDeltaLogLFunction.builder(
286+
obj_builder = ObjectiveFunctionBuilder(PoissonPicDeltaLogLFunction,
287287
name='logl',
288288
description="2*DeltaLogL",
289289
regularization={'min_prob_clip': 1e-4},
@@ -302,7 +302,7 @@ def test_do_mlgst_CPTP_SPAM_penalty_factor(self):
302302
# FUTURE: see what we can do in custom LM about scaling large
303303
# jacobians...
304304
#self.skipTest("Ignore for now.")
305-
obj_builder = PoissonPicDeltaLogLFunction.builder(
305+
obj_builder = ObjectiveFunctionBuilder(PoissonPicDeltaLogLFunction,
306306
name='logl',
307307
description="2*DeltaLogL",
308308
regularization={'min_prob_clip': 1e-4},
@@ -356,7 +356,7 @@ def test_do_iterative_mlgst(self):
356356
# )
357357

358358
def test_do_iterative_mlgst_use_freq_weighted_chi2(self):
359-
obj_builder = FreqWeightedChi2Function.builder(
359+
obj_builder = ObjectiveFunctionBuilder(FreqWeightedChi2Function,
360360
name='freq-weighted-chi2',
361361
description="Sum of chi^2",
362362
regularization={'min_freq_clip_for_weighting': 1e-4}
@@ -404,7 +404,7 @@ def test_do_mlgst_raises_on_out_of_memory(self):
404404
# XXX if this function needs explicit coverage, it should be public!
405405
def test_do_mlgst_base_forcefn_grad(self):
406406
forcefn_grad = np.ones((1, self.mdl_clgst.num_params), 'd')
407-
obj_builder = PoissonPicDeltaLogLFunction.builder(
407+
obj_builder = ObjectiveFunctionBuilder(PoissonPicDeltaLogLFunction,
408408
name='logl',
409409
description="2*DeltaLogL",
410410
regularization={'min_prob_clip': 1e-4},

test/unit/objects/fixtures.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,11 @@ def lsgstStructs(self):
6565

6666
@ns.memo
6767
def mdl_lsgst(self):
68-
chi2_builder = pygsti.objectivefns.Chi2Function.builder(
68+
from pygsti.objectivefns.objectivefns import ObjectiveFunctionBuilder, Chi2Function
69+
chi2_builder = ObjectiveFunctionBuilder(Chi2Function,
6970
regularization={'min_prob_clip_for_weighting': 1e-6},
70-
penalties={'prob_clip_interval': (-1e6, 1e6)})
71+
penalties={'prob_clip_interval': (-1e6, 1e6)}
72+
)
7173
models, _, _ = pygsti.algorithms.core.run_iterative_gst(
7274
self.dataset, self.mdl_clgst, self.lsgstStrings,
7375
optimizer=None,

test/unit/objects/test_objectivefns.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -270,12 +270,6 @@ def setUp(self):
270270
super().setUp()
271271
self.objfns = self.build_objfns()
272272

273-
def test_builder(self):
274-
#All objective function should be of the same type
275-
cls = self.objfns[0].__class__
276-
builder = cls.builder("test_name", "test_description")
277-
self.assertTrue(isinstance(builder, _objfns.ObjectiveFunctionBuilder))
278-
279273
def test_value(self):
280274
for objfn in self.objfns:
281275
terms = objfn.terms().copy()

test/unit/protocols/test_gst.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from pygsti.forwardsims.mapforwardsim import MapForwardSimulator
33
from pygsti.modelpacks import smq1Q_XYI
44
from pygsti.modelpacks.legacy import std1Q_XYI, std2Q_XYICNOT
5-
from pygsti.objectivefns.objectivefns import PoissonPicDeltaLogLFunction
5+
from pygsti.objectivefns.objectivefns import PoissonPicDeltaLogLFunction, ObjectiveFunctionBuilder
66
from pygsti.models.gaugegroup import TrivialGaugeGroup
77
from pygsti.objectivefns import FreqWeightedChi2Function
88
from pygsti.optimize.simplerlm import SimplerLMOptimizer
@@ -64,7 +64,7 @@ def test_gaugeopt_suite_raises_on_bad_suite(self):
6464
GSTGaugeOptSuite("foobar").to_dictionary(model_1Q, verbosity=1)
6565

6666
def test_add_badfit_estimates(self):
67-
builder = PoissonPicDeltaLogLFunction.builder()
67+
builder = ObjectiveFunctionBuilder(PoissonPicDeltaLogLFunction)
6868
opt = SimplerLMOptimizer()
6969
badfit_opts = gst.GSTBadFitOptions(threshold=-10, actions=("robust", "Robust", "robust+", "Robust+",
7070
"wildcard", "do nothing"))

test/unit/tools/fixtures.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,11 @@ def lsgstStrings(self):
5858

5959
@ns.memo
6060
def mdl_lsgst(self):
61-
chi2_builder = pygsti.objectivefns.Chi2Function.builder(
61+
from pygsti.objectivefns.objectivefns import ObjectiveFunctionBuilder, Chi2Function
62+
chi2_builder = ObjectiveFunctionBuilder(Chi2Function,
6263
regularization={'min_prob_clip_for_weighting': 1e-6},
63-
penalties={'prob_clip_interval': (-1e6, 1e6)})
64+
penalties={'prob_clip_interval': (-1e6, 1e6)}
65+
)
6466
models, _, _ = pygsti.algorithms.core.run_iterative_gst(
6567
self.dataset, self.mdl_clgst, self.lsgstStrings,
6668
optimizer=None,

0 commit comments

Comments
 (0)