Пример #1
0
def _create_output_df(phase_advances, model, plane, tot=False):
    meas = phase_advances["MEAS"]
    mod = phase_advances["MODEL"]
    err = phase_advances["ERRMEAS"]
    if tot:
        output_data = model.loc[:, ["S", f"MU{plane}"]].iloc[:, :]
        output_data["NAME"] = output_data.index
        output_data = output_data.assign(S2=model.at[model.index[0], "S"],
                                         NAME2=model.index[0])
        output_data[f"PHASE{plane}"] = meas.to_numpy()[0, :]
        output_data[f"{ERR}PHASE{plane}"] = err.to_numpy()[0, :]
        output_data[f"PHASE{plane}{MDL}"] = mod.to_numpy()[0, :]
    else:
        output_data = model.loc[:, ["S", f"MU{plane}"]].iloc[:-1, :]
        output_data["NAME"] = output_data.index
        output_data = output_data.assign(S2=model.loc[:, "S"].to_numpy()[1:],
                                         NAME2=model.index[1:].to_numpy())
        output_data[f"PHASE{plane}"] = np.diag(meas.to_numpy(), k=1)
        output_data[f"{ERR}PHASE{plane}"] = np.diag(err.to_numpy(), k=1)
        output_data[f"PHASE{plane}{MDL}"] = np.diag(mod.to_numpy(), k=1)
    output_data.rename(columns={f"MU{plane}": f"MU{plane}{MDL}"}, inplace=True)
    output_data[f"{DELTA}PHASE{plane}"] = df_ang_diff(output_data,
                                                      f"PHASE{plane}",
                                                      f"PHASE{plane}{MDL}")
    output_data[
        f"{ERR}{DELTA}PHASE{plane}"] = output_data.loc[:,
                                                       f"{ERR}PHASE{plane}"].to_numpy(
                                                       )
    return output_data
def test_ang():
    a, b = _arand(), _arand()
    diff = toolbox.df_ang_diff(*_df(a, b))
    sum_angles = toolbox.ang_sum(a, b)
    for res in (diff, sum_angles):
        assert len(res) == len(a)
        assert all(-0.5 <= res)
        assert all(res <= 0.5)
Пример #3
0
def convert_old_total_phase(
    inputdir: Union[Path, str],
    outputdir: Union[Path, str],
    suffix: str,
    plane: str,
    old_file_name: str = "phasetot",
    new_file_name: str = TOTAL_PHASE_NAME,
) -> None:
    """
    Looks in the provided directory for expected total phase file from ``BetaBeat.src`` for a given
    plane, converts it to the output format used by ``omc3`` and  write them to the new location.

    The file naming should be getphasetot(x,y).out, with the following expected columns: NAME, NAME2, S,
    S1, COUNT, PHASEX, STDPHX, PHXMDL, MUXMDL.

    Args:
        inputdir (Union[Path, str]): Location of the directory with BetaBeat.src output files.
        outputdir (Union[Path, str]): Location of the output directory for converted files.
        suffix (str): Compensation suffix used in the provided BetaBeat.src output files.
        plane (str): the transverse plane for which to look for the output file.
        old_file_name (str): the standard naming for the old output file.
        new_file_name (str): the standard naming for the new converted file.
    """
    LOGGER.info("Converting old total phase file")
    old_file_path = Path(
        inputdir) / f"get{old_file_name}{plane.lower()}{suffix}{OLD_EXT}"
    if not old_file_path.is_file():
        LOGGER.debug(
            f"Expected BetaBeat.src output at '{old_file_path.absolute()}' is not a file, skipping"
        )
        return

    dframe = tfs.read(old_file_path)
    dframe = dframe.rename(columns={
        f"STDPH{plane}": f"{ERR}{PHASE}{plane}",
        f"PH{plane}{MDL}": f"{PHASE}{plane}{MDL}",
        "S1": "S2",
    }, )
    dframe[f"{DELTA}{PHASE}{plane}"] = df_ang_diff(dframe, f"{PHASE}{plane}",
                                                   f"{PHASE}{plane}{MDL}")
    dframe[
        f"{ERR}{DELTA}{PHASE}{plane}"] = dframe.loc[:,
                                                    f"{ERR}{PHASE}{plane}"].to_numpy(
                                                    )
    tfs.write(Path(outputdir) / f"{new_file_name}{plane.lower()}{EXT}", dframe)
Пример #4
0
def create_total_phase(df_twiss: pd.DataFrame, df_model: pd.DataFrame,
                       parameter: str, relative_error: float,
                       randomize: Sequence[str], headers: Dict):
    """ Creates total phase measurements. """
    LOG.debug(f"Creating fake total phase for {parameter}.")
    plane = parameter[-1]
    df_tot = tfs.TfsDataFrame(index=df_twiss.index)
    element0 = df_twiss.index[0]
    df_tot[NAME2] = element0

    values = df_twiss[f"{PHASE_ADV}{plane}"] - df_twiss.loc[
        element0, f"{PHASE_ADV}{plane}"]
    errors = relative_error * np.ones_like(values)
    if ERRORS in randomize:
        errors = _get_random_errors(errors, np.ones_like(values)) % 0.5
    errors[0] = 0.

    if VALUES in randomize:
        rand_val = np.random.normal(values, errors) % 1
        values += ang_diff(rand_val, values)

    df_tot[parameter] = values % 1
    df_tot[f'{ERR}{parameter}'] = errors

    # tot model
    df_tot[S] = df_model[S]
    df_tot[f'{S}2'] = df_model.loc[df_tot.index[0], S]
    df_tot[f'{parameter}{MDL}'] = (
        df_model[f"{PHASE_ADV}{plane}"] -
        df_model.loc[element0, f"{PHASE_ADV}{plane}"]) % 1
    df_tot[f'{PHASE_ADV}{plane}{MDL}'] = df_model[f'{PHASE_ADV}{plane}']

    df_tot[f"{ERR}{DELTA}{parameter}"] = df_tot[f'{ERR}{parameter}']
    df_tot[f"{DELTA}{parameter}"] = df_ang_diff(df_tot, parameter,
                                                f'{parameter}{MDL}')
    df_tot = df_tot.fillna(0)
    df_tot.headers = headers.copy()
    return {f'{TOTAL_PHASE_NAME}{plane.lower()}': df_tot}
Пример #5
0
def create_phase_advance(df_twiss: pd.DataFrame, df_model: pd.DataFrame,
                         parameter: str, relative_error: float,
                         randomize: Sequence[str], headers: Dict):
    """ Creates phase advance measurements. """
    LOG.debug(f"Creating fake phase advance for {parameter}.")
    plane = parameter[-1]
    df_adv = tfs.TfsDataFrame(index=df_twiss.index[:-1])
    df_adv[NAME2] = df_twiss.index[1:].to_numpy()

    def get_phase_advances(df_source):
        return ang_diff(
            df_source.loc[df_adv[NAME2], f"{PHASE_ADV}{plane}"].to_numpy(),
            df_source.loc[df_adv.index, f"{PHASE_ADV}{plane}"].to_numpy())

    values = get_phase_advances(df_twiss)
    errors = relative_error * np.ones_like(values)
    if ERRORS in randomize:
        errors = _get_random_errors(errors, np.ones_like(values)) % 0.5

    if VALUES in randomize:
        values = np.random.normal(values, errors)
        values = ang_interval_check(values)

    df_adv[parameter] = values
    df_adv[f'{ERR}{parameter}'] = errors

    # adv model
    df_adv[S] = df_model.loc[df_adv.index, S]
    df_adv[f'{S}2'] = df_model.loc[df_adv[NAME2], S].to_numpy()
    df_adv[f'{parameter}{MDL}'] = get_phase_advances(df_model)
    df_adv[f'{PHASE_ADV}{plane}{MDL}'] = df_model.loc[df_adv.index,
                                                      f'{PHASE_ADV}{plane}']

    df_adv[f"{ERR}{DELTA}{parameter}"] = df_adv[f'{ERR}{parameter}']
    df_adv[f"{DELTA}{parameter}"] = df_ang_diff(df_adv, parameter,
                                                f'{parameter}{MDL}')
    df_adv.headers = headers.copy()
    return {f'{PHASE_NAME}{plane.lower()}': df_adv}