-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathconfig.py
More file actions
1984 lines (1727 loc) · 81.5 KB
/
config.py
File metadata and controls
1984 lines (1727 loc) · 81.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import ChainMap, defaultdict
from collections.abc import Mapping, Sequence
import copy
import functools
from importlib.resources import contents, read_text
import inspect
import logging
import numbers
import pathlib
import pandas as pd
from nnpdf_data import legacy_to_new_map
from reportengine import configparser, report
from reportengine.configparser import ConfigError, _parse_func, element_of, record_from_defaults
from reportengine.environment import Environment as reEnvironment
from reportengine.environment import EnvironmentError_
from reportengine.helputils import get_parser_type
from reportengine.namespaces import NSList
from validphys.core import (
PDF,
CutsPolicy,
DataGroupSpec,
DataSetInput,
ExperimentInput,
MatchedCuts,
SimilarCuts,
ThCovMatSpec,
)
from validphys.filters import (
AddedFilterRule,
FilterDefaults,
FilterRule,
Rule,
RuleProcessingError,
default_filter_rules_input,
default_filter_settings_input,
)
from validphys.fitdata import fitted_replica_indexes, match_datasets_by_name, num_fitted_replicas
from validphys.gridvalues import LUMI_CHANNELS
from validphys.loader import (
DataNotFoundError,
FallbackLoader,
InconsistentMetaDataError,
Loader,
LoaderError,
LoadFailedError,
PDFNotFound,
)
from validphys.plotoptions.core import get_info
import validphys.scalevariations
from validphys.utils import yaml_safe
log = logging.getLogger(__name__)
class Environment(reEnvironment):
"""Container for information to be filled at run time"""
def __init__(self, *, this_folder=None, net=True, upload=False, dry=False, **kwargs):
if this_folder:
self.this_folder = pathlib.Path(this_folder)
if not net:
loader_class = Loader
elif dry and net:
log.warning(
"The --dry flag overrides the --net flag. No resources will be downloaded "
"while executing a dry run"
)
loader_class = Loader
else:
loader_class = FallbackLoader
try:
self.loader = loader_class()
except LoaderError as e:
log.error("Failed to find the paths. These are configured " "in the nnprofile settings")
raise EnvironmentError_(e) from e
self.results_path = self.loader.resultspath
self.data_paths = self.loader.commondata_folders
self.upload = upload
super().__init__(**kwargs)
def _id_with_label(f):
f = _parse_func(f)
def parse_func(self, item, **kwargs):
if not isinstance(item, dict):
return f(self, item, **kwargs)
keydiff = item.keys() - {"id", "label"}
if keydiff or not "id" in item:
unrecognized = f" Unrecognized: {keydiff}" if keydiff else ""
raise ConfigError(
f"'{item}' must be a single id, or a mapping "
f"with keys 'id', 'label.{unrecognized}'"
)
id = item["id"]
val = f(self, id, **kwargs)
if "label" in item:
val.label = str(item["label"])
return val
currsig = inspect.signature(parse_func)
origsig = inspect.signature(f)
parse_func = functools.wraps(f)(parse_func)
params = [*list(currsig.parameters.values())[:2], *list(origsig.parameters.values())[2:]]
parse_func.__signature__ = inspect.Signature(parameters=params)
labeldoc = (" Either just an id %s, or a mapping " "with 'id' and 'label'.") % (
get_parser_type(f),
)
if parse_func.__doc__ is None:
parse_func.__doc__ = labeldoc
else:
parse_func.__doc__ += labeldoc
return parse_func
class CoreConfig(configparser.Config):
@property
def loader(self):
return self.environment.loader
def _check_pdf_usable(self, pdf_name: str):
"""Check that the given PDF can be loaded and the error type
is understood before continuing"""
try:
pdf = self.loader.check_pdf(pdf_name)
except PDFNotFound as e:
raise ConfigError(
f"Bad PDF: {pdf_name} not installed", pdf_name, self.loader.available_pdfs
) from e
except LoaderError as e:
raise ConfigError(e) from e
# Check that we know how to compute errors
try:
pdf.stats_class
except NotImplementedError as e:
raise ConfigError(str(e))
return pdf
@element_of("pdfs")
@_id_with_label
def parse_pdf(self, name, unpolarized_bc=None):
"""A PDF set installed in LHAPDF.
If an unpolarized boundary condition it defined, it will be registered as part of the PDF.
If ``name`` is already an instance of a vp PDF object, return it unchanged.
"""
# NB: for reportengine to check the inputs, name should have type: Union[str, PDF]
# to be changed when support for older versions of python is dropped
if isinstance(name, PDF):
return name
pdf = self._check_pdf_usable(name)
if unpolarized_bc is not None:
pdf.register_boundary(unpolarized_bc=unpolarized_bc)
return pdf
def produce_load_weights_dict(self, load_weights_from_fit=None):
if load_weights_from_fit is None:
return None
try:
fit_object = self.loader.check_fit(load_weights_from_fit)
fit_folder = fit_object.path / "nnfit"
weights_name = fit_object.as_input().get("save")
if weights_name is None:
raise LoadFailedError(f"{load_weights_from_fit} does not have saved weights")
# Correct for extension already included
if weights_name.endswith(".h5"):
weights_name = weights_name[:-3]
weights_dict = {}
for p in fit_folder.glob(f"replica_*/{weights_name}.weights.h5"):
replica_folder = p.parent.name
replica_index = int(replica_folder.split("_")[1])
weights_dict[replica_index] = p
if not weights_dict:
raise LoadFailedError(f"No weights found for: {load_weights_from_fit}")
return weights_dict
except LoadFailedError as e:
raise ConfigError(str(e), load_weights_from_fit, self.loader.available_fits) from e
@element_of("unpolarized_bcs")
@_id_with_label
def parse_unpolarized_bc(self, name):
"""Unpolarised PDF used as a Boundary Condition to impose positivity of pPDFs."""
return self.parse_pdf(name)
@element_of("theoryids")
@_id_with_label
def parse_theoryid(self, theoryID: (str, int)):
"""A number corresponding to the database theory ID where the
corresponding theory folder is installed in the data directory."""
try:
return self.loader.check_theoryID(theoryID)
except LoaderError as e:
raise ConfigError(
str(e), theoryID, self.loader.available_theories, display_alternatives="all"
)
def parse_use_cuts(self, use_cuts: (bool, str)):
"""Whether to filter the points based on the cuts applied in the fit,
or the whole data in the dataset. The possible options are:
- internal: Calculate the cuts based on the existing rules. This is
the default.
- fromfit: Read the cuts stored in the fit.
- nocuts: Use the whole dataset.
"""
# The lower is an aesthetic preference...
valid_cuts = {c.value for c in CutsPolicy}
if isinstance(use_cuts, bool):
if use_cuts:
res = CutsPolicy.FROMFIT
else:
res = CutsPolicy.NOCUTS
log.warning(
"Setting a boolean for `use_cuts` is deprecated. "
f"The available values are {valid_cuts} and the default "
f"value is 'internal'. Your input ('{use_cuts}') is "
f"equivalent to '{res}'."
)
elif isinstance(use_cuts, str) and use_cuts in valid_cuts:
res = CutsPolicy(use_cuts)
else:
raise ConfigError(f"Invalid use_cuts setting: '{use_cuts}'.", use_cuts, valid_cuts)
return res
def produce_replicas(self, nreplica: int):
"""Produce a replicas array"""
return NSList(range(1, nreplica + 1), nskey="replica")
def parse_point_prescriptions(self, point_prescriptions):
return NSList(point_prescriptions, nskey="point_prescription")
# TODO: load fit config from here
@element_of("fits")
@_id_with_label
def parse_fit(self, fit: str):
"""A fit in the results folder, containing at least a valid filter result."""
try:
return self.loader.check_fit(fit)
except LoadFailedError as e:
raise ConfigError(str(e), fit, self.loader.available_fits)
def produce_fitreplicas(self, fit):
"""Production rule mapping the ``replica`` key to each Monte Carlo
fit replica.
"""
num_replicas = num_fitted_replicas(fit)
return NSList(range(1, num_replicas + 1), nskey="replica")
def produce_pdfreplicas(self, fitpdf):
"""Production rule mapping the ``replica`` key to each postfit
replica.
"""
pdf = fitpdf["pdf"]
replicas = fitted_replica_indexes(pdf)
return NSList(replicas, nskey="replica")
def produce_fitcontextwithcuts(self, fit, fitinputcontext):
"""Like fitinputcontext but setting the cuts policy."""
theoryid = fitinputcontext["theoryid"]
data_input = fitinputcontext["data_input"]
return {"dataset_inputs": data_input, "theoryid": theoryid, "use_cuts": CutsPolicy.FROMFIT}
def produce_fitenvironment(self, fit, fitinputcontext):
"""Like fitcontext, but additionally forcing various other
parameters, such as the cuts policy and Monte Carlo seeding to be
the same as the fit.
Notes
-----
- This production rule is designed to be used as a namespace
to collect over, for use with
:py:func:`validphys.pseudodata.recreate_fit_pseudodata` and
can be added to freely, e.g by setting trvlseed to be from
the fit runcard.
"""
log.warning(f"Using mcseed and trvlseed from fit: {fit}")
theoryid = fitinputcontext["theoryid"]
data_input = fitinputcontext["data_input"]
runcard = fit.as_input()
trvlseed = runcard["trvlseed"]
mcseed = runcard["mcseed"]
genrep = runcard["genrep"]
# The default for >= 4.1.X is `True`, the key didn't exist for 4.0.Y
use_t0_sampling = runcard.get("use_t0_sampling", True)
use_t0 = use_t0_sampling
t0pdfset = self.parse_t0pdfset(runcard["datacuts"].get("t0pdfset")) if use_t0 else None
return {
"dataset_inputs": data_input,
"theoryid": theoryid,
"use_cuts": CutsPolicy.FROMFIT,
"mcseed": mcseed,
"trvlseed": trvlseed,
"genrep": genrep,
"use_t0_sampling": use_t0_sampling,
"use_t0": use_t0,
"t0pdfset": t0pdfset,
}
def produce_fitcontext(self, fitinputcontext, fitpdf):
"""Set PDF, theory ID and data input from the fit config"""
return dict(**fitinputcontext, **fitpdf)
def produce_fitinputcontext(self, fit):
"""Like ``fitcontext`` but without setting the PDF"""
_, theory = self.parse_from_("fit", "theory", write=False)
thid = theory["theoryid"]
data_input = self._parse_data_input_from_("fit", {"theoryid": thid})
return {"theoryid": thid, "data_input": data_input}
def produce_fitpdf(self, fit):
"""Like ``fitcontext`` only setting the PDF"""
with self.set_context(ns=self._curr_ns.new_child({"fit": fit})):
_, pdf = self.parse_from_("fit", "pdf", write=False)
# Register possible boundaries
try:
_, boundary = self.parse_from_("fit", "positivity_bound", write=False)
pdf.register_boundary(unpolarized_bc=boundary["unpolarized_bc"])
except ConfigError:
pass
return {"pdf": pdf}
def produce_fitunderlyinglaw(self, fit):
"""Reads closuretest: fakepdf from fit config file and passes as
pdf
"""
with self.set_context(ns=self._curr_ns.new_child({"fit": fit})):
_, datacuts = self.parse_from_("fit", "closuretest", write=False)
underlyinglaw = datacuts["fakepdf"]
return {"pdf": underlyinglaw}
@element_of("hyperscans")
def parse_hyperscan(self, hyperscan):
"""A hyperscan in the hyperscan_results folder, containing at least one tries.json file"""
try:
return self.loader.check_hyperscan(hyperscan)
except LoadFailedError as e:
raise ConfigError(str(e), hyperscan, self.loader.available_hyperscans) from e
def parse_hyperscan_config(self, hyperscan_config, hyperopt=None):
"""Configuration of the hyperscan"""
if "from_hyperscan" in hyperscan_config:
hyperscan = self.parse_hyperscan(hyperscan_config["from_hyperscan"])
log.info("Using previous hyperscan: '%s' to generate the search space", hyperscan)
return hyperscan.as_input().get("hyperscan_config")
if "use_tries_from" in hyperscan_config:
hyperscan = self.parse_hyperscan(hyperscan_config["use_tries_from"])
log.info("Reusing tries from: %s", hyperscan)
return {"parameters": hyperscan.sample_trials(n=hyperopt)}
return hyperscan_config
def produce_multiclosure_underlyinglaw(self, fits):
"""Produce the underlying law for a set of fits. This allows a single t0
like covariance matrix to be loaded for all fits, for use with
statistical estimators on multiple closure fits. If the fits don't all
have the same underlying law then an error is raised, offending fit is
identified.
"""
# could use comprehension here but more useful to find offending fit
laws = set()
for fit in fits:
try:
closuretest_spec = fit.as_input()["closuretest"]
except KeyError as e:
raise ConfigError(
f"fit: {fit} does not have a `closuretest` namespace in " "runcard"
) from e
try:
laws.add(closuretest_spec["fakepdf"])
except KeyError as e:
raise ConfigError(
f"fit: {fit} does not have `fakepdf` specified in the "
"closuretest namespace in runcard."
) from e
if len(laws) != 1:
raise ConfigError(
"Did not find unique underlying law from fits, " f"instead found: {laws}"
)
return self.parse_pdf(laws.pop())
def produce_fitq0fromfit(self, fitinputcontext):
"""Given a fit, return the fitting scale according to the theory"""
theory = fitinputcontext["theoryid"]
return theory.get_description()["Q0"]
def produce_basisfromfit(self, fit):
"""Set the basis from fit config. In the fit config file the basis
is set using the key ``fitbasis``, but it is exposed to validphys
as ``basis``.
The name of this production rule is intentionally
set to not conflict with the existing ``fitbasis`` runcard key.
"""
with self.set_context(ns=self._curr_ns.new_child({"fit": fit})):
_, fitting = self.parse_from_("fit", "fitting", write=False)
basis = fitting["fitbasis"]
return {"basis": basis}
def produce_fitpdfandbasis(self, fitpdf, basisfromfit):
"""Set the PDF and basis from the fit config."""
return {**fitpdf, **basisfromfit}
@element_of("dataset_inputs")
def parse_dataset_input(self, dataset: Mapping, allow_legacy_names: bool = True):
"""The mapping that corresponds to the dataset specifications in the fit files
This mapping is such that
dataset: str
name of the dataset to load
variant: str
variant of the dataset to load
cfac: list
list of cfactors to apply
frac: float
fraction of the data to consider for training purposes
weight: float
extra weight to give to the dataset
custom_group: str
custom group to apply to the dataset
Old-format names-sys will be translated to the new version in this function.
"""
accepted_keys = {"dataset", "sys", "cfac", "frac", "weight", "custom_group", "variant"}
try:
name = dataset["dataset"]
if not isinstance(name, str):
raise ConfigError(f"'dataset' must be a string, not {type(name)}")
# Check whether this is an integrability or positivity dataset (in the only way we know?)
if name.startswith(("NNPDF_INTEG", "NNPDF_POS", "POS", "INTEG")):
if name.startswith(("INTEG", "NNPDF_INTEG")):
raise ConfigError("Please, use `integdataset` for integrability")
if name.startswith(("POS", "NNPDF_POS")):
raise ConfigError("Please, use `posdataset` for positivity")
except KeyError:
raise ConfigError("'dataset' must be a mapping with " "'dataset' and 'sysnum'")
# Ensure that we can actually read the `dataset_input` before failure
kdiff = dataset.keys() - accepted_keys
for k in kdiff:
# Abuse ConfigError to get the suggestions.
log.warning(
ConfigError(f"Key '{k}' in dataset_input not known ({name}).", k, accepted_keys)
)
cfac = dataset.get("cfac", tuple())
custom_group = str(dataset.get("custom_group", "unset"))
frac = dataset.get("frac", 1)
if not isinstance(frac, numbers.Real):
raise ConfigError(f"'frac' must be a number, not '{frac}' ({name})")
if frac < 0 or frac > 1:
raise ConfigError(f"'frac' must be between 0 and 1 not '{frac}' ({name})")
weight = dataset.get("weight", 1)
if not isinstance(weight, numbers.Real):
raise ConfigError(f"'weight' must be a number, not '{weight}' ({name})")
if weight < 0:
raise ConfigError(f"'weight' must be greater than zero not '{weight}' ({name})")
variant = dataset.get("variant")
sysnum = dataset.get("sys")
if variant is not None and sysnum is not None:
raise ConfigError(f"The 'variant' and 'sys' keys cannot be used together ({name})")
# The old -> new name mapping can only be used with allow_legacy_names = True
# which from 4.1 will default to False.
# It can be used in order to be able to use old runcard but it is not recommended.
if allow_legacy_names:
name, map_variant = legacy_to_new_map(name, sysnum)
# legacy_dw trumps everything
if variant is None or map_variant == "legacy_dw":
variant = map_variant
if sysnum is not None:
log.warning(
f"The key 'sys' is deprecated and only used for variant discovery: {variant}"
)
return DataSetInput(
name=name,
cfac=cfac,
frac=frac,
weight=weight,
custom_group=custom_group,
variant=variant,
)
def parse_inconsistent_data_settings(self, settings):
"""
Parse the inconsistent data settings from the yaml file.
Known keys:
-----------
- treatment_names: list
list of the names of the treatments that should be rescaled
possible values are: MULT, ADD.
- names_uncertainties: list
list of the names of the uncertainties that should be rescaled
possible values are: CORR, UNCORR, THEORYCORR, THEORYUNCORR, SPECIAL
SPECIAL is used for intra-dataset systematics.
- inconsistent_datasets: list
list of the datasets for which an inconsistency should be introduced.
- sys_rescaling_factor: float, int
the factor by which the systematics should be rescaled.
"""
known_keys = {
"treatment_names",
"names_uncertainties",
"inconsistent_datasets",
"sys_rescaling_factor",
}
kdiff = settings.keys() - known_keys
if kdiff:
raise ConfigError(f"Remove these unknown / bad keys from dataset: {kdiff}")
ict_data_settings = {}
ict_data_settings["treatment_names"] = settings.get("treatment_names", [])
ict_data_settings["names_uncertainties"] = settings.get("names_uncertainties", [])
ict_data_settings["inconsistent_datasets"] = settings.get("inconsistent_datasets", [])
ict_data_settings["sys_rescaling_factor"] = settings.get("sys_rescaling_factor", 1)
return ict_data_settings
def parse_use_fitcommondata(self, do_use: bool):
"""Use the commondata files in the fit instead of those in the data
directory."""
return do_use
def produce_commondata(self, *, dataset_input, use_fitcommondata=False, fit=None):
"""Produce a CommondataSpec from a dataset input"""
name = dataset_input.name
try:
return self.loader.check_commondata(
setname=name,
use_fitcommondata=use_fitcommondata,
fit=fit,
variant=dataset_input.variant,
)
except DataNotFoundError as e:
raise ConfigError(str(e), name, self.loader.available_datasets) from e
except LoadFailedError as e:
raise ConfigError(e) from e
except InconsistentMetaDataError as e:
raise ConfigError(e) from e
def parse_cut_similarity_threshold(self, th: numbers.Real):
"""Maximum relative ratio when using `fromsimilarpredictons` cuts."""
return th
def _produce_fit_cuts(self, commondata):
"""Produce fit and then attempt to load cuts from that fit."""
_, fit = self.parse_from_(None, "fit", write=False)
try:
return self.loader.check_fit_cuts(commondata, fit)
except LoadFailedError as e:
raise ConfigError(e) from e
def _produce_internal_cuts(self, commondata):
"""Produce internal cut rules and then load cuts from those rules."""
_, rules = self.parse_from_(None, "rules", write=False)
return self.loader.check_internal_cuts(commondata, rules)
def _produce_matched_cuts(self, commondata):
"""Compute the internal cuts as per `use_cuts: 'internal'` within each
namespace in a namespace list called `cuts_intersection_spec` and take
the intersection of the results as the cuts for the given dataset. This
is useful for example for requiring the common subset of points that
pass the cuts at NLO and NNLO.
"""
cut_list = []
_, nss = self.parse_from_(None, "cuts_intersection_spec", write=False)
self._check_dataspecs_type(nss)
if not nss:
raise ConfigError("'cuts_intersection_spec' must contain at least one namespace.")
for ns in nss:
with self.set_context(
ns=self._curr_ns.new_child(ns).new_child({"use_cuts": CutsPolicy.INTERNAL})
):
# Note: Do not call _produce_internal_cuts directly here:
# That doesn't correctly set the namespace in a way that `rules`
# can be recovered, as there is no dataset_input object.
cut_list.append(self.parse_from_(None, "cuts", write=False)[1])
ndata = commondata.ndata
return MatchedCuts(cut_list, ndata=ndata)
def _produce_similarity_cuts(self, commondata):
"""Compute the intersection between two namespaces (similar to
`fromintersection`) but additionally require that the predictions
computed for each dataset across the namespaces are *similar*,
specifically that the ratio between the absolute difference in the
predictions and the total experimental uncertainty is smaller than a
given value, `cut_similarity_threshold` that must be provided. Note
that for this to work with different cfactors across the namespaces,
one must provide a different `dataset_inputs` list for each.
This mechanism can be sidetracked selectively for specific datasets.
To do that, add their names to a list called
`do_not_require_similarity_for`. The datasets in the list do not need
to appear in the `cuts_intersection_spec` name space and will be filtered
according to the internal cuts unconditionally.
"""
_, nss = self.parse_from_(None, "cuts_intersection_spec", write=False)
if len(nss) != 2:
raise ConfigError("Can only work with two namespaces")
_, cut_similarity_threshold = self.parse_from_(
None, "cut_similarity_threshold", write=False
)
try:
_, exclusion_list = self.parse_from_(None, "do_not_require_similarity_for", write=False)
except configparser.InputNotFoundError:
exclusion_list = []
name = commondata.name
# slightly circular here, since matched cuts will re-produce nss
if name in exclusion_list:
with self.set_context(ns=self._curr_ns.new_child({"use_cuts": CutsPolicy.INTERNAL})):
return self.parse_from_(None, "cuts", write=False)[1]
matched_cuts = self._produce_matched_cuts(commondata)
inps = []
for i, ns in enumerate(nss):
with self.set_context(ns=self._curr_ns.new_child({**ns})):
# TODO: find a way to not duplicate this and use a dict
# instead of a linear search
_, dins = self.parse_from_(None, "dataset_inputs", write=False)
try:
di = next(d for d in dins if d.name == name)
except StopIteration as e:
raise ConfigError(
f"cuts_intersection_spec namespace {i}: dataset inputs must define {name}"
) from e
with self.set_context(
ns=self._curr_ns.new_child(
{
"dataset_input": di,
"use_cuts": CutsPolicy.FROM_CUT_INTERSECTION_NAMESPACE,
"cuts": matched_cuts,
**ns,
}
)
):
_, ds = self.parse_from_(None, "dataset", write=False)
_, pdf = self.parse_from_(None, "pdf", write=False)
inps.append((ds, pdf))
return SimilarCuts(tuple(inps), cut_similarity_threshold)
def produce_cuts(self, *, commondata, use_cuts):
"""Obtain cuts for a given dataset input, based on the
appropriate policy.
"""
if use_cuts is CutsPolicy.NOCUTS:
return None
elif use_cuts is CutsPolicy.FROMFIT:
return self._produce_fit_cuts(commondata)
elif use_cuts is CutsPolicy.INTERNAL:
return self._produce_internal_cuts(commondata)
elif use_cuts is CutsPolicy.FROM_CUT_INTERSECTION_NAMESPACE:
return self._produce_matched_cuts(commondata)
elif use_cuts is CutsPolicy.FROM_SIMILAR_PREDICTIONS_NAMESPACE:
return self._produce_similarity_cuts(commondata)
raise TypeError("Wrong use_cuts")
def produce_dataset(
self,
*,
dataset_input,
theoryid,
cuts,
use_fitcommondata=False,
fit=None,
check_plotting: bool = False,
):
"""Dataset specification from the theory and CommonData.
Use the cuts from the fit, if provided. If check_plotting is set to
True, attempt to lod and check the PLOTTING files
(note this may cause a noticeable slowdown in general)."""
name = dataset_input.name
cfac = dataset_input.cfac
frac = dataset_input.frac
weight = dataset_input.weight
variant = dataset_input.variant
try:
ds = self.loader.check_dataset(
name=name,
theoryid=theoryid,
cfac=cfac,
cuts=cuts,
frac=frac,
use_fitcommondata=use_fitcommondata,
fit=fit,
weight=weight,
variant=variant,
)
except DataNotFoundError as e:
raise ConfigError(str(e), name, self.loader.available_datasets)
except LoadFailedError as e:
raise ConfigError(e)
if check_plotting:
# normalize=True should check for more stuff
get_info(ds, normalize=True)
if not ds.commondata.plotfiles:
log.warning(f"Plotting files not found for: {ds}")
return ds
def produce_t0dataset(
self,
*,
dataset_input,
t0id,
cuts,
use_fitcommondata=False,
fit=None,
check_plotting: bool = False,
):
"""
Same as produce_dataset, but if a ``t0theoryid`` has been defined in the
runcard then those corresponding fktables will be linked.
"""
ds = self.produce_dataset(
dataset_input=dataset_input,
theoryid=t0id,
cuts=cuts,
use_fitcommondata=use_fitcommondata,
fit=fit,
check_plotting=check_plotting,
)
return ds
@configparser.element_of("experiments")
def parse_experiment(self, experiment: dict):
"""A set of datasets where correlated systematics are taken
into account. It is a mapping where the keys are the experiment
name 'experiment' and a list of datasets."""
try:
name, datasets = experiment["experiment"], experiment["datasets"]
except KeyError as e:
raise ConfigError(
"'experiment' must be a mapping with "
"'experiment' and 'datasets', but %s is missing" % e
) from e
dsinputs = [self.parse_dataset_input(ds) for ds in datasets]
return self.produce_data(group_name=name, data_input=dsinputs)
@configparser.element_of("experiment_inputs")
def parse_experiment_input(self, ei: dict):
"""The mapping that corresponds to the experiment specification in the
fit config files. Currently, this needs to be combined with
``experiment_from_input`` to yield an useful result."""
try:
name = ei["experiment"]
except KeyError as e:
raise ConfigError(f"experiment_input must have an 'experiment' key") from e
try:
datasets = ei["datasets"]
except KeyError as e:
raise ConfigError(f"experiment_input must have an 'datasets' key") from e
return ExperimentInput(name=name, datasets=datasets)
# TODO: Do away with the mapping and make the conversion implicitly
def produce_experiment_from_input(self, experiment_input, theoryid, use_cuts, fit=None):
"""Return a mapping containing a single experiment from an experiment
input. NOTE: This might be deprecated in the future."""
return {
"experiment": self.parse_experiment(
experiment_input.as_dict(), theoryid=theoryid, use_cuts=use_cuts, fit=fit
)
}
@configparser.explicit_node
def produce_dataset_inputs_fitting_covmat(self, use_thcovmat_in_fitting=False):
"""
Produces the correct covmat to be used in fitting_data_dict according
to some options: whether to include the theory covmat, whether to
separate the multiplcative errors and whether to compute the
experimental covmat using the t0 prescription.
"""
from validphys import covmats
if use_thcovmat_in_fitting:
return covmats.dataset_inputs_t0_total_covmat
return covmats.dataset_inputs_t0_exp_covmat
def produce_sep_mult(self, separate_multiplicative=False):
if separate_multiplicative is False:
return False
return True
@configparser.explicit_node
def produce_dataset_inputs_sampling_covmat(
self, sep_mult=False, use_thcovmat_in_sampling=False, use_t0_sampling=True
):
"""
Produces the correct MC replica method sampling covmat to be used in
make_replica according to some options: whether to sample using a t0
covariance matrix, include the theory covmat and whether to
separate the multiplcative errors.
Parameters
----------
sep_mult : bool, default=False
Whether to separate the multiplicative errors.
use_thcovmat_in_sampling : bool, default=False
Whether to include the theory covariance matrix.
use_t0_sampling : bool, default=True
Whether to sample using a t0 covariance matrix.
Returns
-------
Callable
"""
from validphys import covmats
if use_t0_sampling:
if use_thcovmat_in_sampling:
if sep_mult:
return covmats.dataset_inputs_t0_total_covmat_separate
else:
return covmats.dataset_inputs_t0_total_covmat
else:
if sep_mult:
return covmats.dataset_inputs_t0_exp_covmat_separate
else:
return covmats.dataset_inputs_t0_exp_covmat
else:
if use_thcovmat_in_sampling:
if sep_mult:
return covmats.dataset_inputs_total_covmat_separate
else:
return covmats.dataset_inputs_total_covmat
else:
if sep_mult:
return covmats.dataset_inputs_exp_covmat_separate
else:
return covmats.dataset_inputs_exp_covmat
def produce_loaded_theory_covmat(
self,
output_path,
data_input,
user_covmat_path=None,
point_prescriptions=None,
use_thcovmat_in_sampling=False,
use_thcovmat_in_fitting=False,
):
"""
Loads the theory covmat from the correct file according to how it
was generated by vp-setupfit.
"""
if not use_thcovmat_in_sampling and not use_thcovmat_in_fitting:
return 0.0
# Load correct file according to how the thcovmat was generated by vp-setupfit
generic_path = "datacuts_theory_theorycovmatconfig_theory_covmat_custom.csv"
if user_covmat_path is not None:
if point_prescriptions is not None and point_prescriptions != []:
generic_path = "datacuts_theory_theorycovmatconfig_total_theory_covmat.csv"
else:
generic_path = "datacuts_theory_theorycovmatconfig_user_covmat.csv"
theorypath = output_path / "tables" / generic_path
theory_covmat = pd.read_csv(
theorypath, index_col=[0, 1, 2], header=[0, 1, 2], sep="\t|,", engine="python"
).fillna(0)
# change ordering according to exp_covmat (so according to runcard order)
tmp = theory_covmat.droplevel(0, axis=0).droplevel(0, axis=1)
bb = [str(i) for i in data_input]
return tmp.reindex(index=bb, columns=bb, level=0).values
@configparser.explicit_node
def produce_covmat_t0_considered(self, use_t0: bool = False):
"""Modifies which action is used as covariance_matrix depending on
the flag `use_t0`
"""
from validphys import covmats
if use_t0:
return covmats.t0_covmat_from_systematics
else:
return covmats.covmat_from_systematics
@configparser.explicit_node
def produce_dataset_inputs_covmat_t0_considered(self, use_t0: bool = False):
"""Modifies which action is used as experiment_covariance_matrix
depending on the flag `use_t0`
"""
from validphys import covmats
if use_t0:
return covmats.dataset_inputs_t0_covmat_from_systematics
else:
return covmats.dataset_inputs_covmat_from_systematics
@configparser.explicit_node
def produce_masks(self, diagonal_basis: bool = True):
"""Modifies which action is used as masks depending on the flag
`diagonal_basis`
"""
from validphys import n3fit_data
if diagonal_basis:
return n3fit_data.diagonal_masks
else:
return n3fit_data.standard_masks
@configparser.explicit_node
def produce_covariance_matrix(self, use_pdferr: bool = False):
"""Modifies which action is used as covariance_matrix depending on
the flag `use_pdferr`
"""
from validphys import covmats
if use_pdferr:
return covmats.pdferr_plus_covmat
else:
return covmats._covmat_t0_considered
@configparser.explicit_node
def produce_dataset_inputs_covariance_matrix(self, use_pdferr: bool = False):
"""Modifies which action is used as experiment_covariance_matrix
depending on the flag `use_pdferr`
"""
from validphys import covmats
if use_pdferr:
return covmats.pdferr_plus_dataset_inputs_covmat
else:
return covmats._dataset_inputs_covmat_t0_considered
# TODO: Do this better and elsewhere
@staticmethod
def _check_dataspecs_type(dataspecs):
if not isinstance(dataspecs, Sequence):
raise ConfigError(
"dataspecs should be a sequence of mappings, not " f"{type(dataspecs).__name__}"
)
for spec in dataspecs:
if not isinstance(spec, Mapping):
raise ConfigError(
"dataspecs should be a sequence of mappings, "
f" but {spec} is {type(spec).__name__}"
)
def produce_matched_datasets_from_dataspecs(self, dataspecs):
"""Take an arbitrary list of mappings called dataspecs and
return a new list of mappings called dataspecs constructed as follows.
From each of the original dataspecs, resolve the key `process`, and
all the experiments and datasets therein.
Compute the intersection of the dataset names, and for each element in
the intersection construct a mapping with the follwing keys:
- process : A string with the common process name.
- experiment_name : A string with the common experiment name.
- dataset_name : A string with the common dataset name.
- dataspecs : A list of mappinngs matching the original
"dataspecs". Each mapping contains:
* dataset: A dataset with the name data_set name and the
properties (cuts, theory, etc) corresponding to the original
dataspec.
* dataset_input: The input line used to build dataset.
* All the other keys in the original dataspec.