+[docs]
+defsingle_action_analysis(kick_df:tfs.TfsDataFrame,kick_plane:str,detuning_order:int=1,corrected:bool=False)->tfs.TfsDataFrame:"""Performs the fit one action and tune pane at a time."""LOG.info(f"Performing amplitude detuning ODR for single-plane kicks in {kick_plane}.")
@@ -560,7 +568,10 @@
+[docs]
+defdouble_action_analysis(kick_df:tfs.TfsDataFrame,detuning_order:int=1,corrected:bool=False)->tfs.TfsDataFrame:"""Performs the full 2D/4D fitting of the data."""ifdetuning_order>1:
@@ -601,7 +612,10 @@
+[docs]
+defget_approx_bbq_interval(bbq_df:TfsDataFrame,time_array:Sequence[CERNDatetime],window:int)->Tuple[CERNDatetime,CERNDatetime]:"""Get approximate start and end times for averaging, based on window length and kick interval."""bbq_tmp=bbq_df.dropna()
@@ -625,6 +639,7 @@
+[docs]
+@entrypoint(get_params())defcorrection_test_entrypoint(opt:DotDict,accel_opt)->None:""" Entrypoint function to test the given corrections.
@@ -566,6 +568,7 @@
+[docs]
+deffilter_measurement(keys:Sequence[str],meas:Dict[str,pd.DataFrame],model:pd.DataFrame,opt:DotDict)->dict:"""Filters measurements in `keys` based on the dict-entries (keys as in `keys`)
@@ -255,6 +257,7 @@
Source code for omc3.correction.filters
returnnew
+
def_get_measurement_filters()->defaultdict:"""Returns a dict with the respective `_get_*` filter-functions that defaults to `~_get_filtered_generic`. Some columns might need to have extra steps for
@@ -370,7 +373,9 @@
+[docs]
+deffilter_response_index(response:Dict,measurement:Dict,keys:Sequence[str]):"""Filters the index of the response matrices `response` by the respective entries in `measurement`."""# rename MU to PHASE as we create a PHASE-Response afterwards# easier to do here, than to check eveywhere below. (jdilly)
@@ -390,6 +395,7 @@
Source code for omc3.correction.filters
returnnew_response
+
def_get_response_filters()->Dict[str,Callable]:""" Returns a dict with the respective `_get_*_response` functions that defaults
diff --git a/_modules/omc3/correction/handler.html b/_modules/omc3/correction/handler.html
index dfbb4508..89ac962e 100644
--- a/_modules/omc3/correction/handler.html
+++ b/_modules/omc3/correction/handler.html
@@ -11,11 +11,11 @@
-
-
-
-
-
+
+
+
+
+
@@ -241,7 +241,9 @@
+[docs]
+defcorrect(accel_inst:Accelerator,opt:DotDict)->None:""" Perform global correction as described in :mod:`omc3.global_correction`. Args:
@@ -314,6 +316,7 @@
+[docs]
+defadd_coupling_to_model(model:pd.DataFrame)->pd.DataFrame:""" Computes the coupling RDTs from the input model TfsDataFrame and returns a copy of said TfsDataFrame with columns for the real and imaginary parts of the computed coupling RDTs.
@@ -331,6 +336,7 @@
+[docs]
+defdiff_twiss_parameters(model_a:tfs.TfsDataFrame,model_b:tfs.TfsDataFrame,parameters:Sequence[str]=None)->tfs.TfsDataFrame:"""Create a TfsDataFrame containing of the given parameters between
@@ -255,6 +257,7 @@
+[docs]
+defread_fullresponse(path:Path,optics_parameters:Sequence[str]=None)->Dict[str,pd.DataFrame]:"""Load the response matrices from disk. Beware: As empty DataFrames are skipped on write, default for not found entries are empty DataFrames.
@@ -249,7 +251,10 @@
+[docs]
+defread_varmap(path:Path,k_values:Sequence[str]=None)->Dict[str,Dict[str,pd.Series]]:"""Load the variable mapping file from disk. Beware: As empty DataFrames are skipped on write, default for not found entries are empty Series.
@@ -285,7 +293,10 @@
+[docs]
+ defget_response_for(self,observables=None)->dict:# Dict[str, ???]""" Calculates and returns only desired response matrices """# calling functions for the getters to call functions only if neededdefcaller(func,plane):
@@ -990,13 +1015,17 @@
Source code for omc3.correction.response_twiss
# response[key] = obs_map[key][0](*obs_map[key][1:3])
# I still don't know why there is a sign-change between B1 and B2 (jdilly, 2021)response[key]=self._beam_sign*obs_map[key][0](*obs_map[key][1:3])
- returnresponse
+[docs]
+defresponse_add(*args)->pd.DataFrame:""" Merges two or more Response Matrix DataFrames """base_df=args[0]fordfinargs[1:]:
@@ -1004,12 +1033,18 @@
+[docs]
+defget_phase_advances(twiss_df:pd.DataFrame)->Dict[str,pd.DataFrame]:""" Calculate phase advances between all elements
@@ -1032,20 +1067,29 @@
+[docs]
+defdphi(data,q):"""Return dphi from phase advances in data, see Eq. 7 in [#DillyUpdatedGlobalOpticsCorrection2018]_"""returndata+np.where(data<=0,q,0)# '<=' seems to be what MAD-X does
+[docs]
+deftau(data,q):"""Return tau from phase advances in data, see Eq. 8 in [#DillyUpdatedGlobalOpticsCorrection2018]_"""returndata+np.where(data<=0,q/2,-q/2)# '<=' seems to be what MAD-X does
+[docs]
+defcheck_varmap_file(accel_inst:Accelerator,vars_categories):""" Checks on varmap file and creates it if not in model folder. """ifaccel_inst.modifiersisNone:
@@ -509,6 +514,7 @@
Source code for omc3.correction.sequence_evaluation
+[docs]
+defget_config_filename(script):"""Default Filename for config-files. Call from script with ``__file__``."""returnCONFIG_FILENAME.format(script=Path(script).name.split('.')[0],time=datetime.utcnow().strftime(TIME))
+[docs]
+@entrypoint(correction_params())defglobal_correction_entrypoint(opt:DotDict,accel_opt)->None:"""Do the global correction. Iteratively."""LOG.info("Starting Iterative Global Correction.")
@@ -496,6 +498,7 @@
Source code for omc3.global_correction
handler.correct(accel_inst,opt)
+
def_check_opt_add_dicts(opt:dict)->dict:# acts inplace...""" Check on options and put in missing values """def_dict=_get_default_values()
diff --git a/_modules/omc3/harpy/clean.html b/_modules/omc3/harpy/clean.html
index 87c70a9f..41c3a63f 100644
--- a/_modules/omc3/harpy/clean.html
+++ b/_modules/omc3/harpy/clean.html
@@ -11,11 +11,11 @@
-
-
-
-
-
+
+
+
+
+
@@ -222,7 +222,9 @@
+[docs]
+defclean(harpy_input,bpm_data,model):""" Cleans BPM TbT matrix: removes BPMs not present in the model and based on specified cuts. Also cleans the noise using singular value decomposition.
@@ -248,6 +250,7 @@
+[docs]
+defsvd_decomposition(matrix,num_singular_values,dominance_limit=None,num_iter=None):""" Computes reduced (K largest values) singular value decomposition of a matrix. Requiring K singular values from MxN matrix results in matrices sized:
@@ -413,6 +418,7 @@
+[docs]
+defharpy_per_plane(harpy_input,bpm_matrix,usv,tunes,plane):""" Calculates the spectra of TbT data, finds the main lines and cleans the BPMs for which the main line hasn't been found or is too far from its average over BPMs.
@@ -327,7 +332,10 @@
+[docs]
+defclean_by_tune(tunes:pd.Series,tune_clean_limit:Number)->pd.Series:""" Looks for outliers in the tunes pandas Series and returns their indices.
@@ -407,6 +418,7 @@
Source code for omc3.harpy.frequency
returnbad_bpms_names
+
def_get_bad_bpms_summary(not_tune_bpms,cleaned_by_tune_bpms):return([f"{bpm_name} The main resonance has not been found"forbpm_nameinnot_tune_bpms]+[f"{bpm_name} tune is too far from average"forbpm_nameincleaned_by_tune_bpms])
@@ -464,7 +476,9 @@
+[docs]
+defwindowed_padded_rfft(harpy_input,matrix,tunes,svd=None):""" Calculates the spectra using specified windowing function and zero-padding.
@@ -502,7 +516,10 @@
+[docs]
+defaverage_beta_from_Tune(Q,TdQ,l,Dk):"""Calculates average beta function in quadrupole from tune change ``TdQ`` and ``delta K``."""beta_av=2*(1/np.tan(2*np.pi*Q)*
@@ -373,6 +378,7 @@
+[docs]
+defget_state(ldb,time:datetime)->Dict[str,str]:""" Standalone function to gather and log state data from the StateTracker.
@@ -491,6 +502,7 @@
Source code for omc3.knob_extractor
returnstate_dict
+
def_get_state_as_df(state_dict:Dict[str,str],time:datetime)->tfs.TfsDataFrame:""" Convert extracted StateTracker state-data into a TfsDataFrame
@@ -514,7 +526,9 @@
+[docs]
+defextract(ldb,knobs:Sequence[str],time:datetime)->Dict[str,float]:""" Standalone function to gather data from the StateTracker. Extracts data via pytimber's LoggingDB for the knobs given
@@ -559,7 +573,10 @@
+[docs]
+defcheck_for_undefined_knobs(knobs_definitions:pd.DataFrame,knob_categories:Sequence[str]):""" Check that all knobs are actually defined in the knobs-definitions.
@@ -580,6 +597,7 @@
+[docs]
+defload_knobs_definitions(file_path:Union[Path,str])->pd.DataFrame:""" Load the knobs-definition file and convert into a DataFrame. Each line in this file should consist of at least three comma separated entries in the following order: madx-name, lsa-name, scaling factor.
@@ -694,6 +714,7 @@
Source code for omc3.knob_extractor
return_to_knobs_dataframe(df)
+
def_to_knobs_dataframe(df:pd.DataFrame)->pd.DataFrame:""" Adapts a DataFrame to the conventions used here: StateTracker variable name as index, all columns lower-case.
@@ -786,16 +807,22 @@
Source code for omc3.knob_extractor
# Other tools ------------------------------------------------------------------
-
+[docs]
+defrun_file(input_file:Path,output_file:Path=None,log_file:Path=None,madx_path:Path=MADX_PATH,cwd:Path=None):""" Runs ``MAD-X`` on a given script in a subprocess.
@@ -299,7 +304,10 @@
+[docs]
+ @classmethoddefget_element_types_mask(cls,list_of_elements:List[str],types)->numpy.ndarray:""" Returns a boolean mask for elements in ``list_of_elements`` that belong to any of the
@@ -434,7 +441,10 @@
Source code for omc3.model.accelerators.accelerator
+[docs]
+ @classmethoddefget_variables(cls,frm=None,to=None,classes=None):""" Gets the variables with elements in the given range and the given classes. ``None`` means
@@ -442,7 +452,10 @@
Source code for omc3.model.accelerators.accelerator
"""
raiseNotImplementedError("A function should have been overwritten, check stack trace.")
+[docs]
+ @classmethoddefget_correctors_variables(cls,frm=None,to=None,classes=None):""" Returns the set of corrector variables between ``frm`` and ``to``, with classes in
@@ -450,6 +463,7 @@
Source code for omc3.model.accelerators.accelerator
"""
raiseNotImplementedError("A function should have been overwritten, check stack trace.")
+[docs]
+ defverify_object(self):""" Verifies that this instance of an `Accelerator` is properly instantiated. """raiseNotImplementedError("A function should have been overwritten, check stack trace.")
+[docs]
+ defget_exciter_bpm(self,plane:str,commonbpms:List[str]):""" Returns the BPM next to the exciter. The `Accelerator` instance knows already which excitation method is used.
@@ -480,6 +499,7 @@
Source code for omc3.model.accelerators.accelerator
"""
raiseNotImplementedError("A function should have been overwritten, check stack trace.")
+[docs]
+ @classmethoddefget_dir(cls)->Path:"""Default directory for accelerator. Should be overwritten if more specific."""dir_path=CURRENT_DIR/cls.NAME
@@ -497,7 +519,10 @@
Source code for omc3.model.accelerators.accelerator
return dir_pathraiseNotImplementedError(f"No directory for accelerator {cls.NAME} available.")
+[docs]
+ @classmethoddefget_file(cls,filename:str)->Path:"""Default location for accelerator files. Should be overwritten if more specific."""file_path=CURRENT_DIR/cls.NAME/filename
@@ -507,25 +532,35 @@
Source code for omc3.model.accelerators.accelerator
f"File {file_path.name} not available for accelerator {cls.NAME}.")
+
# Jobs ###################################################################
-
+[docs]
+ defget_update_correction_script(self,outpath:Union[Path,str],corr_files:Sequence[Union[Path,str]])->str:""" Returns job (string) to create an updated model from changeparameters input (used in iterative correction). """raiseNotImplementedError("A function should have been overwritten, check stack trace.")
+[docs]
+ defget_base_madx_script(self,best_knowledge=False):""" Returns job (string) to create the basic accelerator sequence. """
- raiseNotImplementedError("A function should have been overwritten, check stack trace.")
+ raiseNotImplementedError("A function should have been overwritten, check stack trace.")
+[docs]
+classVariable:""" Generic corrector variable class that holds `name`, `position (s)` and physical elements it affects. These variables should be logical variables that have and effect in the model if
@@ -538,7 +573,10 @@
Source code for omc3.model.accelerators.accelerator
+[docs]
+classElement:""" Generic corrector element class that holds `name` and `position (s)` of the corrector. This element should represent a physical element of the accelerator.
@@ -549,7 +587,10 @@
Source code for omc3.model.accelerators.accelerator
+[docs]
+classAcceleratorDefinitionError(Exception):""" Raised when an `Accelerator` instance is wrongly used, for example by calling a method that should have been overwritten.
@@ -558,6 +599,7 @@
Source code for omc3.model.accelerators.accelerator
[docs]defverify_object(self)->None:# TODO: Maybe more checks?
+
+[docs]
+ defverify_object(self)->None:# TODO: Maybe more checks?""" Verifies if everything is defined which should be defined. Will Raise an ``AcceleratorDefinitionError`` if one of the checks is invalid.
@@ -389,6 +393,7 @@
+[docs]
+ defsort_variables_by_location(self,variables:Iterable[str],frm:float=None,to:str=None)->List[str]:""" Sorts the variables by location and filters them between `frm` and `to`. If `frm` is larger than `to` it loops back around to the start the accelerator. This is a useful function for the LHC that's why it is "public"
@@ -465,7 +475,10 @@
+
deflog_status(self)->None:LOGGER.info(f" model dir = {self.model_dir}")LOGGER.info(f"Natural Tune X [{self.nat_tunes[0]:10.3f}]")
@@ -523,7 +537,9 @@
+[docs]
+classPetra(Accelerator):NAME="petra"# Public Methods ##########################################################
-
[docs]defverify_object(self):# TODO: Maybe more checks?
+
+[docs]
+ defverify_object(self):# TODO: Maybe more checks?ifself.model_dirisNone:# is the class is used to create full response?raiseAcceleratorDefinitionError("PETRA doesn't have a model creation yet, calling it this ""way is most probably wrong.")
+[docs]
+ defget_base_madx_script(self,best_knowledge=False):ifbest_knowledge:raiseNotImplementedError(f"Best knowledge model not implemented for accelerator {self.NAME}")
@@ -351,7 +367,9 @@
+[docs]
+classPsbooster(Accelerator):"""Parent Class for Psbooster-types."""NAME="psbooster"RE_DICT={AccElementTypes.BPMS:r"BR\d\.BPM[^T]",
@@ -314,13 +316,18 @@
Source code for omc3.model.accelerators.psbooster
raise AcceleratorDefinitionError("Ring parameter has to be one of (1, 2, 3, 4)")self._ring=value
-
+[docs]
+ defget_base_madx_script(self,best_knowledge=False):ifbest_knowledge:raiseNotImplementedError(f"Best knowledge model not implemented for accelerator {self.NAME}")
@@ -348,7 +358,9 @@
+[docs]
+ defverify_object(self):ifself.model_dirisNone:# is the class is used to create full response?raiseAcceleratorDefinitionError("SuperKEKB doesn't have a model creation, "
- "calling it this way is most probably wrong.")
+[docs]
+@entrypoint(_get_params())defget_accelerator(opt,other_opt):""" Returns the `Accelerator` instance of the desired accelerator, as given at the commandline.
@@ -246,13 +248,17 @@
+[docs]
+@entrypoint(_get_params())defget_parsed_opt(opt,other_opt):"""Get all accelerator related options as a `dict`."""accel=ACCELS[opt.accel]parser=EntryPoint(accel.get_parameters(),strict=True)accel_opt=parser.parse(other_opt)return{**opt,**accel_opt}