Esempio n. 1
0
 def _compare_dirs_with_tfs_comparator(self, valid_dir, to_check_dir):
     ignore_names = ["L", "NAME"]
     for item in os.listdir(valid_dir):
         if not item.startswith("sbs"):  # Only check the SbS files
             continue
         valid_item = os.path.join(valid_dir, item)
         to_check_item = os.path.join(to_check_dir, item)
         self.assertTrue(os.path.isfile(to_check_item),
                         "File " + str(to_check_item) + " doesn't exist.")
         if os.path.isfile(valid_item) and os.path.isfile(to_check_item):
             try:
                 syserr = sys.stderr
                 sys.stderr = open(os.devnull, "w")
                 valid_twiss = metaclass.twiss(valid_item)
                 to_check_twiss = metaclass.twiss(to_check_item)
                 sys.stderr = syserr
                 self.assertTrue(
                     Utilities.tfs_comparator.compare_tfs(
                         valid_twiss,
                         to_check_twiss,
                         _MAX_RELATIVE_ERROR,
                         ignore_names=ignore_names),
                     "Difference found in file: " + to_check_item)
             except:
                 raise
             finally:
                 sys.stderr = syserr
Esempio n. 2
0
def justtwiss():
#########################
    global dictionary
    system('madx < job.ORM.madx > scum')
    x=twiss('twiss.orbit.dat')
    y=twiss('twiss.all.dat')
    return x, y
Esempio n. 3
0
def writeparams(deltafamilie, variables, accel_path, app=0, path="./"):
    if (app == 0):
        mode = 'w'
    if (app == 1):
        mode = 'a'
    a = datetime.datetime.fromtimestamp(time.time())
    if accel_path[-5:] == "LHCB1":
        path_B1tfs = os.path.join(accel_path, "varsKLvsK_B1.tfs")
        twiss_kl = metaclass.twiss(path_B1tfs)
    if accel_path[-5:] == "LHCB2":
        path_B2tfs = os.path.join(accel_path, "varsKLvsK_B2.tfs")
        twiss_kl = metaclass.twiss(path_B2tfs)
    g = open(path + '/changeparameters', mode)
    f = open(path + '/changeparameters.tfs', mode)
    print >> f, "@", "APP", "%le", app
    print >> f, "@", "PATH", "%s", path
    print >> f, "@", "DATE", "%s", a.ctime()
    print >> f, "*", "NAME", "DELTA"
    print >> f, "$", "%s", "%le"
    for i, var in enumerate(variables):
        if var[0] == "l":
            g.write(var[1:] + ' = ' + var[1:] + ' + ( ' +
                    str((deltafamilie[i] /
                         twiss_kl.LENGTH[twiss_kl.indx[var]])) + ' );\n')
            f.write(var[1:] + '   ' +
                    str((deltafamilie[i] /
                         twiss_kl.LENGTH[twiss_kl.indx[var]])) + '\n')
        else:
            g.write(var + ' = ' + var + ' + ( ' + str(deltafamilie[i]) +
                    ' );\n')
            f.write(var + '   ' + str(deltafamilie[i]) + '\n')
    g.close()
    f.close()
Esempio n. 4
0
    def _compare_output_betas(self, output_path):
        print "Comparing output..."
        if len(self._errors[output_path]) == 0:
            beta_x_twiss = metaclass.twiss(
                os.path.join(output_path, "getbetax.out"))
            beta_y_twiss = metaclass.twiss(
                os.path.join(output_path, "getbetay.out"))

            for index in range(len(beta_x_twiss.NAME)):
                rel_error = abs(
                    (beta_x_twiss.BETX[index] - beta_x_twiss.BETXMDL[index]) /
                    beta_x_twiss.BETXMDL[index])
                self.assertTrue(
                    rel_error < MAX_BETA_REL_ERR,
                    "Relative error too big found in: " +
                    beta_x_twiss.NAME[index] + " (" + str(rel_error) + ")")
            for index in range(len(beta_y_twiss.NAME)):
                rel_error = abs(
                    (beta_y_twiss.BETY[index] - beta_y_twiss.BETYMDL[index]) /
                    beta_y_twiss.BETYMDL[index])
                self.assertTrue(
                    rel_error < MAX_BETA_REL_ERR,
                    "Relative error too big found in: " +
                    beta_y_twiss.NAME[index] + " (" + str(rel_error) + ")")
        else:
            print "Manual errors in the madx job: skipping betas check"
Esempio n. 5
0
def writeparams(deltafamilie, variables, accel_path, app=0, path="./"):
    if (app == 0):
        mode = 'w'
    if (app == 1):
        mode = 'a'
    a = datetime.datetime.fromtimestamp(time.time())
    if accel_path[-5:] == "LHCB1":
        path_B1tfs = os.path.join(accel_path, "varsKLvsK_B1.tfs")
        twiss_kl = metaclass.twiss(path_B1tfs)
    if accel_path[-5:] == "LHCB2":
        path_B2tfs = os.path.join(accel_path, "varsKLvsK_B2.tfs")
        twiss_kl = metaclass.twiss(path_B2tfs)
    g = open (path+'/changeparameters', mode)
    f = open (path+'/changeparameters.tfs', mode)
    print >> f, "@", "APP", "%le", app
    print >> f, "@", "PATH", "%s", path
    print >> f, "@", "DATE", "%s", a.ctime()
    print >> f, "*", "NAME", "DELTA"
    print >> f, "$", "%s", "%le"
    for i, var in enumerate(variables):
        if var[0]=="l":
            g.write(var[1:]+' = '+ var[1:] +' + ( '+str((deltafamilie[i]/twiss_kl.LENGTH[twiss_kl.indx[var]]))+' );\n')
            f.write(var[1:]+'   '+str((deltafamilie[i]/twiss_kl.LENGTH[twiss_kl.indx[var]]))+'\n')
        else:    
            g.write(var+' = '+ var+' + ( '+str(deltafamilie[i])+' );\n')
            f.write(var+'   '+str(deltafamilie[i])+'\n')
    g.close()
    f.close()
Esempio n. 6
0
def _get_tunes(fileslist):
    '''
    Reads in the driven tunes from the
    file with dpp=0
    Reads in the model tunes from the
    twiss model (twiss.dat)

    :param fileslist: dictionary of files, dpp used as key
    :returns: (
    :raise ValueError: If fileslist[0] does not exist
    '''
    if fileslist[0][0].endswith(".gz"):
        fname = fileslist[0][0].replace(".gz", "")
        end = '.gz'
    else:
        fname = fileslist[0][0]
        end = ''
    tw_x = metaclass.twiss(fname + '_linx' + end)
    tw_y = metaclass.twiss(fname + '_liny' + end)
    tw = metaclass.twiss(_InputData.twissfile)

    qdx = tw_x.TUNEX[0]
    qdy = tw_y.TUNEY[0]
    qx = tw.Q1 % 1
    qy = tw.Q2 % 1
    qmx = tw.Q1
    qmy = tw.Q2

    return (qx, qy, qdx, qdy, qmx, qmy)
Esempio n. 7
0
 def plot(self):
     if 1 in self._matcher_model._matcher.get_beams():
         figure_b1_x = self._figures[0][0]
         figure_b1_x.clear()
         file_beam1_horizontal = metaclass.twiss(os.path.join(
             self._matcher_model.get_beam1_output_path(), "sbs",
             "sbsphasext_IP" + str(self._matcher_model.get_ip()) + ".out")
         )
         self._plot_match(figure_b1_x, file_beam1_horizontal, "X")
         figure_b1_y = self._figures[0][1]
         figure_b1_y.clear()
         file_beam1_vertical = metaclass.twiss(os.path.join(
             self._matcher_model.get_beam1_output_path(), "sbs",
             "sbsphaseyt_IP" + str(self._matcher_model.get_ip()) + ".out")
         )
         self._plot_match(figure_b1_y, file_beam1_vertical, "Y")
     if 2 in self._matcher_model._matcher.get_beams():
         figure_b2_x = self._figures[1][0]
         figure_b2_x.clear()
         file_beam2_horizontal = metaclass.twiss(os.path.join(
             self._matcher_model.get_beam2_output_path(), "sbs",
             "sbsphasext_IP" + str(self._matcher_model.get_ip()) + ".out")
         )
         self._plot_match(figure_b2_x, file_beam2_horizontal, "X")
         figure_b2_y = self._figures[1][1]
         figure_b2_y.clear()
         file_beam2_vertical = metaclass.twiss(os.path.join(
             self._matcher_model.get_beam2_output_path(), "sbs",
             "sbsphaseyt_IP" + str(self._matcher_model.get_ip()) + ".out")
         )
         self._plot_match(figure_b2_y, file_beam2_vertical, "Y")
Esempio n. 8
0
def justtwiss():
    #########################
    global dictionary
    system('madx < job.ORM.madx > scum')
    x = twiss('twiss.orbit.dat')
    y = twiss('twiss.all.dat')
    return x, y
Esempio n. 9
0
def lin_fit_data(path):
    file_path_R = path+'R.dat'
    file_path_L = path+'L.dat'
    right_data = metaclass.twiss(file_path_R)
    left_data  = metaclass.twiss(file_path_L)

    cleaned_xR = start_cleaning_data(right_data.K, right_data.TUNEX,right_data.TUNEX_ERR)
    cleaned_yR = start_cleaning_data(right_data.K, right_data.TUNEY,right_data.TUNEY_ERR)
    cleaned_xL = start_cleaning_data(left_data.K, left_data.TUNEX,left_data.TUNEX_ERR)
    cleaned_yL = start_cleaning_data(left_data.K, left_data.TUNEY,left_data.TUNEY_ERR)

    fitx_R, covx_r = np.polyfit(cleaned_xR[:,0], cleaned_xR[:,1], 1, cov=True, w = 1/cleaned_xR[:,2]**2)
    fity_R, covy_r = np.polyfit(cleaned_yR[:,0], cleaned_yR[:,1], 1, cov=True, w = 1/cleaned_yR[:,2]**2)
    fitx_L, covx_l = np.polyfit(cleaned_xL[:,0], cleaned_xL[:,1], 1, cov=True, w = 1/cleaned_xL[:,2]**2)
    fity_L, covy_l = np.polyfit(cleaned_yL[:,0], cleaned_yL[:,1], 1, cov=True, w = 1/cleaned_yL[:,2]**2)

    plot_fitting(fitx_L,fitx_R,fity_L,fity_R,left_data,right_data,path)

    dK = 1.0e-5
    K = np.average(left_data.K)
    Q1 = np.average(right_data.TUNEX)
    Q2 = np.average(right_data.TUNEY)

    errx_r = np.sqrt(np.diag(covx_r)[0]) * dK
    erry_r = np.sqrt(np.diag(covy_r)[0]) * dK
    errx_l = np.sqrt(np.diag(covx_l)[0]) * dK
    erry_l = np.sqrt(np.diag(covy_l)[0]) * dK

    return fitx_L[0], fitx_R[0], fity_L[0], fity_R[0], errx_r, erry_r, errx_l, erry_l, K, dK, Q1, Q2 #kmod_data  # Array with all dQ's (slopes of fit scaled with dK) and the dK spread. [xR, xL, yR, yL, dK ]
Esempio n. 10
0
def _get_tunes(fileslist):
    """
    Reads in the driven tunes from the
    file with dpp=0
    Reads in the model tunes from the
    twiss model (twiss.dat)

    :param fileslist: dictionary of files, dpp used as key
    :returns: (
    :raise ValueError: If fileslist[0] does not exist
    """
    if fileslist[0][0].endswith(".gz"):
        fname = fileslist[0][0].replace(".gz", "")
        end = ".gz"
    else:
        fname = fileslist[0][0]
        end = ""
    tw_x = metaclass.twiss(fname + "_linx" + end)
    tw_y = metaclass.twiss(fname + "_liny" + end)
    tw = metaclass.twiss(_InputData.twissfile)

    qdx = tw_x.TUNEX[0]
    qdy = tw_y.TUNEY[0]
    qx = tw.Q1 % 1
    qy = tw.Q2 % 1

    return (qx, qy, qdx, qdy)
Esempio n. 11
0
def _get_twiss_for_one_of(directory, *file_names):
    for file_name in file_names:
        file_path = os.path.join(directory, file_name)
        if os.path.isfile(file_path):
            file_name_amplitude = "getampbeta" + file_name[7:]
            file_path_amplitude = os.path.join(directory, file_name_amplitude)
            return (metaclass.twiss(file_path), metaclass.twiss(file_path_amplitude))
    raise IOError("None of the files exist:\n\t" + "\n\t".join(file_names))
Esempio n. 12
0
def _get_kmod_files():
    try:
        kmod_path_x = twiss(_join_output_with("getkmodbetax.out"))
        kmod_path_y = twiss(_join_output_with("getkmodbetay.out"))
    except IOError:
        kmod_path_x = None
        kmod_path_y = None
    return kmod_path_x, kmod_path_y
def _get_twiss_for_one_of(directory, *file_names):
    for file_name in file_names:
        file_path = os.path.join(directory, file_name)
        if os.path.isfile(file_path):
            file_name_amplitude = "getampbeta" + file_name[7:]
            file_path_amplitude = os.path.join(directory, file_name_amplitude)
            return (metaclass.twiss(file_path), metaclass.twiss(file_path_amplitude))
    raise IOError("None of the files exist:\n\t" + "\n\t".join(file_names))
Esempio n. 14
0
def _handle_data_for_lhc():
    #.knob should always exist to be sent to LSA!
    src = os.path.join(
        os.path.join(_InputData.output_path, "changeparameters_couple.tfs"))
    dst = os.path.join(
        os.path.join(_InputData.output_path, "changeparameters_couple.knob"))
    Utilities.iotools.copy_item(src, dst)

    ##### for bumps
    if "bumps" in _InputData.variables_list:
        print "passing trough bumps loop"
        v = metaclass.twiss(
            os.path.join(_InputData.output_path,
                         "changeparameters_couple.tfs"))  # @UnusedVariable
        # v will be used in Bumps.py. Don't do such things again!(vimaier)
        Utilities.iotools.delete_item(
            os.path.join(_InputData.output_path,
                         "changeparameters_couple.tfs"))
        corrs = None  # Will be assigned in exec Bumps.py (vimaier)
        execfile(os.path.join(_InputData.path_to_optics_files_dir, "Bumps.py"))
        execfile(
            os.path.join(_InputData.path_to_optics_files_dir,
                         "mydictionary.py"))
        tfs_file_writer = Utilities.tfs_file_writer.TfsFileWriter(
            "changeparameters_couple.tfs", _InputData.output_path)
        tfs_file_writer.add_column_names("NAME DELTA".split())
        tfs_file_writer.add_column_datatypes("%s %le".split())
        for vcorr in corrs:
            tfs_file_writer.add_table_row([vcorr, corrs[vcorr]])
        tfs_file_writer.write_to_file()
    #####

    v = metaclass.twiss(
        os.path.join(_InputData.output_path, "changeparameters_couple.tfs"))
    mad_script = open(
        os.path.join(_InputData.output_path, "changeparameters_couple.madx"),
        "w")
    names = getattr(v, "NAME", [])
    delta = getattr(v, "DELTA", [])

    for i in range(len(names)):
        if "bumps" in _InputData.variables_list:
            if cmp(delta[i], 0) == 1:
                mad_script.write(names[i] + "->KICK:=" + str(-delta[i]) +
                                 ";\n")
            else:
                mad_script.write(names[i] + "->KICK:=" + str(-delta[i]) +
                                 ";\n")
        else:
            if cmp(delta[i], 0) == 1:
                mad_script.write(names[i] + " = " + names[i] + " " +
                                 str(-delta[i]) + ";\n")
            else:
                mad_script.write(names[i] + " = " + names[i] + " + " +
                                 str(-delta[i]) + ";\n")

    mad_script.write("return;")
    mad_script.close()
Esempio n. 15
0
def generate_constraints_coupling(ip, use_errors, sbs_data_b1_path, sbs_data_b2_path, constraints_path=os.path.join(CURRENT_PATH, "match"), exclude_string=""):
    sbs_coupling_data_beam1 = twiss(os.path.join(sbs_data_b1_path, 'sbs', 'sbscouple_IP' + ip + '.out'))
    sbs_coupling_data_beam2 = twiss(os.path.join(sbs_data_b2_path, 'sbs', 'sbscouple_IP' + ip + '.out'))

    constr_file_beam1 = open(os.path.join(constraints_path, 'constraintsb1.seqx'), 'w')
    constr_file_beam2 = open(os.path.join(constraints_path, 'constraintsb2.seqx'), 'w')
    exclude_list = _parse_exclude_string(exclude_string)

    _write_constraints_file_coupling(sbs_coupling_data_beam1, constr_file_beam1, ip, 1, exclude_list, use_errors)
    _write_constraints_file_coupling(sbs_coupling_data_beam2, constr_file_beam2, ip, 2, exclude_list, use_errors)
Esempio n. 16
0
def run_gen_f_terms(ip, match_temporary_path, sbs_data_b1_path, sbs_data_b2_path):
    sbs_coupling_data_beam1 = twiss(os.path.join(sbs_data_b1_path, 'sbs', 'sbscouple_IP' + ip + '.out'))
    sbs_coupling_data_beam2 = twiss(os.path.join(sbs_data_b2_path, 'sbs', 'sbscouple_IP' + ip + '.out'))
    fterms_b1_path = os.path.join(match_temporary_path, "f_terms_beam1.madx")
    fterms_b2_path = os.path.join(match_temporary_path, "f_terms_beam2.madx")
    with open(fterms_b1_path, "w") as fterms_b1_file:
        for bpm_name in sbs_coupling_data_beam1.NAME:
            fterms_b1_file.write("exec, get_f_terms_for(twiss, " + bpm_name + ");\n")
    with open(fterms_b2_path, "w") as fterms_b2_file:
        for bpm_name in sbs_coupling_data_beam2.NAME:
            fterms_b2_file.write("exec, get_f_terms_for(twiss, " + bpm_name + ");\n")
Esempio n. 17
0
def _parse_twiss_files(file_name):
    startturn, endturn = _get_turns(file_name)
    twx = metaclass.twiss(file_name + "_linx")
    twy = metaclass.twiss(file_name + "_liny")
    twx.keys.append("SDDS")
    twy.keys.append("SDDS")
    empty_list = numpy.empty([len(twx.NAME), endturn - startturn])
    setattr(twx, "SDDS", empty_list)
    empty_list = numpy.empty([len(twy.NAME), endturn - startturn])
    setattr(twy, "SDDS", empty_list)
    update_twisses_with_sdds(file_name, twx, twy)
    return twx, twy
Esempio n. 18
0
def merge_data(working_directory,  ip ,beam):
    IR =  ip + beam
    planes = ['X','Y']
    sides  = ['L','R']
    for side in sides:
        result = {'X':[],'Y':[]}
        tdatax = metaclass.twiss(os.path.join(working_directory,IR+side+'X.tfs'))
        tdatay = metaclass.twiss(os.path.join(working_directory,IR+side+'Y.tfs'))
        kdata= metaclass.twiss(os.path.join(working_directory,ip+side+'K.tfs'))
        K, Qx, Qxrms, Qy, Qyrms = pair(tdatax,tdatay,kdata)
        
        write_tfs_files(K, Qx, Qxrms, Qy, Qyrms, working_directory, IR, side)
Esempio n. 19
0
def _parse_twiss_files(file_name):
    startturn, endturn = _get_turns(file_name)
    twx = metaclass.twiss(file_name + "_linx")
    twy = metaclass.twiss(file_name + "_liny")
    twx.keys.append("SDDS")
    twy.keys.append("SDDS")
    empty_list = numpy.empty([len(twx.NAME),endturn-startturn])
    setattr(twx, "SDDS", empty_list)
    empty_list = numpy.empty([len(twy.NAME),endturn-startturn])
    setattr(twy, "SDDS", empty_list)
    update_twisses_with_sdds(file_name, twx, twy)
    return twx,twy
Esempio n. 20
0
def _parse_twiss_files(model, files):
    model_twiss = metaclass.twiss(model)
    lin_x_twiss_list = []
    file_list = [file_name.strip() for file_name in files.strip("\"").split(",")]
    for file_name in file_list:
        if not file_name.endswith("_linx"):
            file_name += "_linx"
        if not os.path.isfile(file_name):
            print >> sys.stderr, "Cannot find file_name: " + file_name + ". Aborting."
            sys.exit()
        else:
            lin_x_twiss_list.append(metaclass.twiss(file_name))
    return model_twiss, lin_x_twiss_list
Esempio n. 21
0
def _get_twiss_instance_of_getcouple():
    """ Loads either getcouple_free.out or getcouple.out or raises an Exception """
    file_path_free = os.path.join(_InputData.output_path, "getcouple_free.out")
    file_path = os.path.join(_InputData.output_path, "getcouple.out")
    if os.path.isfile(file_path_free):
        couple = metaclass.twiss(file_path_free)
        print "Will use free coupling"
    elif os.path.isfile(file_path):
        couple = metaclass.twiss(file_path)
        print "WARN: Free coupling not found!"
    else:
        raise ValueError("path", _InputData.output_path, " does not contain a getcouple_free.out or getcouple.out file")
    return couple
def _get_twiss_instance_of_getcouple():
    """ Loads either getcouple_free.out or getcouple.out or raises an Exception """
    file_path_free = os.path.join(_InputData.output_path, "getcouple_free.out")
    file_path = os.path.join(_InputData.output_path, "getcouple.out")
    if os.path.isfile(file_path_free):
        couple = metaclass.twiss(file_path_free)
        print "Will use free coupling"
    elif os.path.isfile(file_path):
        couple = metaclass.twiss(file_path)
        print "WARN: Free coupling not found!"
    else:
        raise ValueError("path", _InputData.output_path, " does not contain a getcouple_free.out or getcouple.out file")
    return couple
Esempio n. 23
0
def write_global_files(beam, kmod_dir, res_dir, mod_path):
    bpms = np.array([])
    betx = np.array([])
    bety = np.array([])
    betx_std = np.array([])
    bety_std = np.array([])

    IPs = ['ip1', 'ip5', 'ip8']
    for ip in IPs:
        pathx, pathy = get_paths(kmod_dir, beam, ip)
        try:
            datax = metaclass.twiss(pathx)
            datay = metaclass.twiss(pathy)
        except IOError:
            print "Cannot find " + ip + " kmod data, won't copy those files."
            continue
        bpms = np.concatenate((bpms, datax.NAME))
        betx = np.concatenate((betx, datax.BETX))
        bety = np.concatenate((bety, datay.BETY))
        betx_std = np.concatenate((betx_std, datax.BETXSTD))
        bety_std = np.concatenate((bety_std, datay.BETYSTD))

    betx_mod, bety_mod = get_model_beta(bpms, mod_path)

    xdata = tfs_file_writer.TfsFileWriter.open(
        os.path.join(res_dir, 'getkmodbetax.out'))
    xdata.set_column_width(20)
    xdata.add_column_names([
        'NAME', 'S', 'COUNT', 'BETX', 'STDBETX', 'BETXMDL', 'ERRBETX',
        'BETXRES', 'BETXSTDRES'
    ])
    xdata.add_column_datatypes(
        ['%s', '%le', '%le', '%le', '%le', '%le', '%le', '%le', '%le'])

    ydata = tfs_file_writer.TfsFileWriter.open(
        os.path.join(res_dir, 'getkmodbetay.out'))
    ydata.set_column_width(20)
    ydata.add_column_names([
        'NAME', 'S', 'COUNT', 'BETY', 'STDBETY', 'BETYMDL', 'ERRBETY',
        'BETYRES', 'BETYSTDRES'
    ])
    ydata.add_column_datatypes(
        ['%s', '%le', '%le', '%le', '%le', '%le', '%le', '%le', '%le'])

    for i in range(len(bpms)):
        xdata.add_table_row(
            [bpms[i], 0, 0, betx[i], betx_std[i], betx_mod[i], 0, 0, 0])
        ydata.add_table_row(
            [bpms[i], 0, 0, bety[i], bety_std[i], bety_mod[i], 0, 0, 0])
    xdata.write_to_file()
    ydata.write_to_file()
Esempio n. 24
0
def _parse_twiss_files(model, files):
    model_twiss = metaclass.twiss(model)
    lin_x_twiss_list = []
    file_list = [
        file_name.strip() for file_name in files.strip("\"").split(",")
    ]
    for file_name in file_list:
        if not file_name.endswith("_linx"):
            file_name += "_linx"
        if not os.path.isfile(file_name):
            print >> sys.stderr, "Cannot find file_name: " + file_name + ". Aborting."
            sys.exit()
        else:
            lin_x_twiss_list.append(metaclass.twiss(file_name))
    return model_twiss, lin_x_twiss_list
Esempio n. 25
0
def _parallel_get_systematic_errors_binary_file(model_twiss_path, run_data_path, output_path, pool, num_simulations, num_processes):
    model_twiss = metaclass.twiss(model_twiss_path)

    list_of_bpm = []
    for i in model_twiss.NAME:
        if "BPM" in i and i not in list_of_bpm:
            list_of_bpm.append(i)

    final_list = [{}, {}, 0]  # This list is used to pass the parameters "by reference" to the callback method

    chunksize = _compute_chunksize(num_simulations, num_processes)
    print "Using chunk size:", chunksize
    args = [(run_data_path, model_twiss, list_of_bpm, range(1, num_simulations + 1)[x:x + chunksize]) for x in xrange(0, num_simulations, chunksize)]
    for run_data_path, model_twiss, list_of_bpm, sim_nums in args:
        pool.apply_async(_get_error_bar_for_single_simulation, (run_data_path, model_twiss, list_of_bpm, sim_nums),
                         callback=lambda result: _merge_betas_dict(final_list, result))
    pool.close()
    pool.join()

    sys.stdout.write("\n")

    final_beta_hor, final_beta_ver, final_num_valid_data = final_list

    for key, value in final_beta_hor.iteritems():
        final_beta_hor[key] = value / final_num_valid_data
    for key, value in final_beta_ver.iteritems():
        final_beta_ver[key] = value / final_num_valid_data

    np.save(os.path.join(output_path, 'bet_deviations'), [final_beta_hor, final_beta_ver])
Esempio n. 26
0
    def define_constraints(self):
        constr_string = ""
        for plane in ["x", "y"]:
            sbs_data = metaclass.twiss(
                os.path.join(
                    self.get_matcher_path(), "sbs", 'sbsphase' + plane + 't_' +
                    str(self._segment.label) + '.out'))

            is_back = "b" in self._front_or_back
            for index in range(0, len(sbs_data.NAME)):
                name = sbs_data.NAME[index]
                if name not in self._excluded_constraints_list:
                    if is_back is not True:
                        phase = sbs_data.PROPPHASEX[
                            index] if plane == "x" else sbs_data.PROPPHASEY[
                                index]
                        error = sbs_data.ERRPROPPHASEX[
                            index] if plane == "x" else sbs_data.ERRPROPPHASEY[
                                index]
                    else:
                        phase = sbs_data.BACKPHASEX[
                            index] if plane == "x" else sbs_data.BACKPHASEY[
                                index]
                        error = sbs_data.ERRBACKPHASEX[
                            index] if plane == "x" else sbs_data.ERRBACKPHASEY[
                                index]
                    constr_string += self._get_constraint_instruction(
                        self._name + '.dmu' + plane + name, phase, error)
        return constr_string
Esempio n. 27
0
def _get_tunes(model_file, fileslist):
    """
    Reads in the driven tunes from the
    file with dpp=0
    Reads in the model tunes from the
    twiss model (twiss.dat)

    Args:
        fileslist: dictionary of files, dpp used as key

    Returns:
        (qx, qy, qdx, qdy, qmx, qmy)

    Raises:
        ValueError: If fileslist[0] does not exist
    """
    tw_x, tw_y = _load_from_file(fileslist[0][0])
    tw = metaclass.twiss(model_file)

    exp_qx = tw_x.Q1
    exp_qy = tw_y.Q2
    mdl_qx = tw.Q1
    mdl_qy = tw.Q2

    return (exp_qx, exp_qy, mdl_qx, mdl_qy)
Esempio n. 28
0
    def get_segment(cls, label, first_elem, last_elem, optics_file,
                    twiss_file):
        segment_cls = type(cls.__name__ + "Segment",
                           (_PsboosterSegmentMixin, cls), {})

        LOGGER.debug('twiss_file is <%s>', twiss_file)
        tw = twiss(twiss_file)

        LOGGER.debug('twiss_file has tunes %f %f ', tw.Q1, tw.Q2)
        ring = _get_ring_from_seqname(tw.SEQUENCE)

        #ring = cls.get_ring()

        segment_inst = segment_cls()

        bpms_file = _get_file_for_ring(ring)
        bpms_file_data = tfs_pandas.read_tfs(bpms_file).set_index("NAME")
        first_elem_s = bpms_file_data.loc[first_elem, "S"]
        last_elem_s = bpms_file_data.loc[last_elem, "S"]
        segment_inst.label = label
        segment_inst.start = Element(first_elem, first_elem_s)
        segment_inst.end = Element(last_elem, last_elem_s)
        segment_inst.optics_file = optics_file
        segment_inst.fullresponse = None

        segment_inst.nat_tune_x = tw.Q1
        segment_inst.nat_tune_y = tw.Q2
        segment_inst.energy = tw.ENERGY
        segment_inst.sequence = tw.SEQUENCE
        segment_inst.ring = ring
        segment_inst.kind = ''  # '' means beta from phase, can be 'betaamp', in the future 'betakmod'

        return segment_inst
Esempio n. 29
0
    def get_segment(cls, label, first_elem, last_elem, optics_file, twiss_file):
        # this creates a new class called PsSegment
        segment_cls = type(cls.__name__ + "Segment",
                          (_PsSegmentMixin,cls),
                          {})
        segment_inst = segment_cls()
        
        bpms_file = os.path.join(PS_DIR,str(CURRENT_YEAR),"sequence/bpms.tfs")
        bpms_file_data = tfs_pandas.read_tfs(bpms_file).set_index("NAME")
        first_elem_s = bpms_file_data.loc[first_elem, "S"]
        last_elem_s = bpms_file_data.loc[last_elem, "S"]
        segment_inst.label = label
        segment_inst.start = Element(first_elem, first_elem_s)
        segment_inst.end = Element(last_elem, last_elem_s)
        segment_inst.optics_file = optics_file
        segment_inst.fullresponse = None
        
        LOGGER.debug('twiss_file is <%s>',twiss_file)
        tw = twiss(twiss_file)
        
        LOGGER.debug('twiss_file has tunes %f %f ',tw.Q1,tw.Q2)

        segment_inst.nat_tune_x = tw.Q1
        segment_inst.nat_tune_y = tw.Q2
        segment_inst.energy = tw.ENERGY
        segment_inst.kind = '' # '' means beta from phase, can be 'betaamp', in the future 'betakmod'
        
        return segment_inst    
def _get_beta_amp_data(directory, plane, free=True):
    suffix = PLANE_SUFFIX[plane]
    getampbeta = os.path.join(directory, "getampbeta" + suffix + ".out")
    getampbetafree = os.path.join(directory, "getampbeta" + suffix + "_free.out")
    if not free:
        return metaclass.twiss(getampbeta)
    return _get_twiss_for_one_of(getampbetafree, getampbeta)
Esempio n. 31
0
def _get_calibrated_betas(plane):
    amplitude_beta = None
    calibration_data = None
    try:
        amplitude_beta = _get_twiss_for_one_of(
            "getampbeta" + plane + "_free.out", "getampbeta" + plane + ".out")
        calibration_data = twiss(
            _join_output_with("calibration_" + plane + ".out"))
    except IOError:
        return None
    calibrated_betas = CalibratedBetas(plane)
    index_counter = 0
    for bpm_name in calibration_data.NAME:
        if bpm_name in amplitude_beta.NAME:
            amp_index = amplitude_beta.indx[bpm_name]
            amp_beta = getattr(amplitude_beta,
                               "BET" + plane.upper())[amp_index]
            calibrated_betas.NAME.append(bpm_name)
            calibrated_betas.S.append(amplitude_beta.S[amp_index])
            calibrated_betas.indx[bpm_name] = index_counter
            index_counter += 1
            getattr(calibrated_betas, "BET" + plane.upper()).append(amp_beta)
            try:
                err_amp_beta = getattr(amplitude_beta,
                                       "STDBET" + plane.upper())[amp_index]
            except AttributeError:
                err_amp_beta = getattr(amplitude_beta, "BET" + plane.upper() +
                                       "STD")[amp_index]
            getattr(calibrated_betas,
                    "BET" + plane.upper() + "STD").append(err_amp_beta)
            mdl_amp_beta = getattr(amplitude_beta,
                                   "BET" + plane.upper() + "MDL")[amp_index]
            getattr(calibrated_betas,
                    "BET" + plane.upper() + "MDL").append(mdl_amp_beta)
    return calibrated_betas
Esempio n. 32
0
 def __try_to_load_twiss_from_output(self, file_name):
     try:
         twiss_data = twiss(_join_output_with(file_name))
     except ValueError:
         print("Imposible to read twiss file ", file_name, file=sys.stderr)
         return None
     return twiss_data
Esempio n. 33
0
def _get_tunes(model_file, fileslist):
    """
    Reads in the driven tunes from the
    file with dpp=0
    Reads in the model tunes from the
    twiss model (twiss.dat)

    Args:
        fileslist: dictionary of files, dpp used as key

    Returns:
        (qx, qy, qdx, qdy, qmx, qmy)

    Raises:
        ValueError: If fileslist[0] does not exist
    """
    tw_x, tw_y = _load_from_file(fileslist[0][0])
    tw = metaclass.twiss(model_file)

    exp_qx = tw_x.Q1
    exp_qy = tw_y.Q2
    mdl_qx = tw.Q1
    mdl_qy = tw.Q2

    return (exp_qx, exp_qy, mdl_qx, mdl_qy)
Esempio n. 34
0
 def _get_beta_beat_file(self, beam, plane):
     bb_path = getattr(self._matcher_model, "get_beam" + str(beam) + "_output_path")()
     file_data = metaclass.twiss(os.path.join(
         bb_path, "sbs",
         "sbsbetabeat" + plane.lower() + "_IP" + str(self._matcher_model.get_ip()) + ".out")
     )
     return file_data
def _handle_data_for_sps():
    v = metaclass.twiss(os.path.join(_InputData.output_path, "changeparameters_couple.tfs"))  # @UnusedVariable
        # v will be used in VBumps.py. Don't do such things again!(vimaier)
    print '\nFor SPS, vertical bump file is imported:'
    print os.path.join(_InputData.accel_path, "Coupling/VBumps.py")
    vcorrs = None # Will be assigned in exec VBumps.py (vimaier)
    vcorrsYASP = None # Will be assigned in exec VBumpsYASP.py (vimaier)
    execfile(os.path.join(_InputData.accel_path, "Coupling", "VBumps.py")) # LOADS vcorrs
    execfile(os.path.join(_InputData.accel_path, "Coupling", "VBumpsYASP.py")) # LOADS vcorrsYASP
    #Output for YASP...
    f = open(os.path.join(_InputData.output_path, "Coupling", "changeparameters_couple.yasp"), "w")
    f.write("#PLANE V\n")
    f.write("#UNIT RAD\n")
    for vcorr in vcorrsYASP:
        print >> f, "#SETTING", vcorr,  vcorrsYASP[vcorr]
    f.close()

    #Output for Knob...
    g = open(os.path.join(_InputData.output_path, "Coupling", "changeparameters_couple.knob"), "w")
    h = open(os.path.join(_InputData.output_path, "Coupling", "changeparameters_couple.madx"), "w")
    g.write("* NAME  DELTA \n")
    g.write("$ %s    %le   \n")
    for vcorr in vcorrs:
        print >> g, "K"+vcorr, vcorrs[vcorr]
        print >> h, vcorr, "->KICK:=", vcorrs[vcorr], ";"
    h.write('return;')
    g.close()
    h.close()
Esempio n. 36
0
def MagnetSpecs(magnetname, beam):

    if beam == 'B1':
        twissfile = twissfilenameb1
    else:
        twissfile = twissfilenameb2

    twiss = metaclass.twiss(twissfile)

    if magnetname in twiss.NAME:
        index = twiss.NAME.index(magnetname)
        position = twiss.S[index]
        k = twiss.K1L[index]
        length = twiss.L[index]
        Polarity = twiss.POLARITY[index]

    elif magnetname+'.'+beam in twiss.NAME:
        index = twiss.NAME.index(magnetname+'.'+beam)
        position = twiss.S[index]
        k = twiss.K1L[index]
        length = twiss.L[index]
        Polarity = twiss.POLARITY[index]


    return position, k, length, Polarity
def run_gen_f_terms(ip, match_temporary_path, sbs_data_b1_path,
                    sbs_data_b2_path):
    sbs_coupling_data_beam1 = twiss(
        os.path.join(sbs_data_b1_path, 'sbs', 'sbscouple_IP' + ip + '.out'))
    sbs_coupling_data_beam2 = twiss(
        os.path.join(sbs_data_b2_path, 'sbs', 'sbscouple_IP' + ip + '.out'))
    fterms_b1_path = os.path.join(match_temporary_path, "f_terms_beam1.madx")
    fterms_b2_path = os.path.join(match_temporary_path, "f_terms_beam2.madx")
    with open(fterms_b1_path, "w") as fterms_b1_file:
        for bpm_name in sbs_coupling_data_beam1.NAME:
            fterms_b1_file.write("exec, get_f_terms_for(twiss, " + bpm_name +
                                 ");\n")
    with open(fterms_b2_path, "w") as fterms_b2_file:
        for bpm_name in sbs_coupling_data_beam2.NAME:
            fterms_b2_file.write("exec, get_f_terms_for(twiss, " + bpm_name +
                                 ");\n")
Esempio n. 38
0
def ReturnDataofBPMinBetweenMagnets(magnetname1, magnetname2, BPMKeyword, beam):

    results_name = []
    results_pos = []

    if beam == 'B1':
        twissfile = twissfilenameb1
    else:
        twissfile = twissfilenameb2

    twiss = metaclass.twiss(twissfile)

    if IsInTwiss(magnetname1,beam) ==True:
        index1 = twiss.NAME.index(magnetname1)
    elif IsInTwiss(magnetname1+'.'+beam ,beam) ==True:
        index1 = twiss.NAME.index(magnetname1+'.'+beam)

    if IsInTwiss(magnetname2, beam) == True:
        index2 = twiss.NAME.index(magnetname2)
    elif IsInTwiss(magnetname2 + '.' + beam, beam) == True:
        index2 = twiss.NAME.index(magnetname2 + '.' + beam)

    for key, name, pos in zip(twiss.KEYWORD[min(index1, index2): max(index1, index2)], twiss.NAME[min(index1, index2): max(index1, index2)], twiss.S[min(index1, index2): max(index1, index2)]) :
        if key == BPMKeyword:
            results_name.append(name)
            results_pos.append(pos)

    return results_name, results_pos
Esempio n. 39
0
    def define_aux_vars(self):
        phases_str = ""
        variables_s_str = ""

        sign = ""
        if "b" in self._front_or_back:
            sign = "-"
        for beam in self.get_beams():
            for plane in ["x", "y"]:
                sbs_data_path = os.path.join(
                    self.get_match_data(beam).get_beam_match_sbs_path(),
                    "sbsphase" + plane + "t_IP" + str(self._ip) + ".out",
                )
                sbs_data = metaclass.twiss(sbs_data_path)
                for name in sbs_data.NAME:
                    phases_str += self._name + ".dmu" + plane + name + " := "
                    phases_str += sign + "(table(twiss, " + name + ", mu" + plane + ") - "
                    phases_str += "table(" + self._get_nominal_table_name(beam) + ", " + name + ", mu" + plane + "));\n"

        for variable in self.get_all_variables():
            variables_s_str += self._name + "." + variable + "_0" + " = " + variable + ";\n"

        return PhaseMatcher.DEF_CONSTR_AUX_VALUES_TEMPLATE % {
            "SEQ_B1": "lhcb1_" + self._front_or_back + "_" + self._name,
            "SEQ_B2": "lhcb2_" + self._front_or_back + "_" + self._name,
            "INIT_VALS_B1": "b1_" + self._ini_end + "_" + self._name,
            "INIT_VALS_B2": "b2_" + self._ini_end + "_" + self._name,
            "B1_TABLE_NAME": self._get_nominal_table_name(1),
            "B2_TABLE_NAME": self._get_nominal_table_name(2),
            "PHASES": phases_str,
            "S_VARIABLES": variables_s_str,
        }
Esempio n. 40
0
def _get_beta_data(directory, plane, free=True):
    suffix = PLANE_SUFFIX[plane]
    getbeta = os.path.join(directory, "getbeta" + suffix + ".out")
    getbetafree = os.path.join(directory, "getbeta" + suffix + "_free.out")
    if not free:
        return metaclass.twiss(getbeta)
    return _get_twiss_for_one_of(getbetafree, getbeta)
Esempio n. 41
0
    def define_aux_vars(self):
        phases_str = ""
        variables_s_str = ""

        sign = ""
        if "b" in self._front_or_back:
            sign = "-"
        for plane in ["x", "y"]:
            sbs_data_path = os.path.join(
                os.path.join(self.get_matcher_path(), "sbs"),
                'sbsphase' + plane + 't_' + str(self._segment.label) + '.out')
            sbs_data = metaclass.twiss(sbs_data_path)
            for name in sbs_data.NAME:
                phases_str += self._name + '.dmu' + plane + name + ' := '
                phases_str += sign + "(table(twiss, " + name + ", mu" + plane + ") - "
                phases_str += "table(" + self._get_nominal_table_name(
                ) + ", " + name + ", mu" + plane + "));\n"

        for variable in self.get_variables():
            variables_s_str += self._name + '.' + variable + '_0' + ' = ' + variable + ';\n'
        beam = str(self.get_segment().get_beam())
        return PhaseMatcher.DEF_CONSTR_AUX_VALUES_TEMPLATE % {
            "SEQ":
            "lhcb" + beam + "_" + self._front_or_back + "_" + self._name,
            "INIT_VALS": "b" + beam + "_" + self._ini_end + "_" + self._name,
            "TABLE_NAME": self._get_nominal_table_name(),
            "PHASES": phases_str,
            "S_VARIABLES": variables_s_str,
        }
Esempio n. 42
0
def _handle_data_for_sps():
    v = metaclass.twiss(os.path.join(_InputData.output_path, "changeparameters_couple.tfs"))  # @UnusedVariable
        # v will be used in VBumps.py. Don't do such things again!(vimaier)
    print '\nFor SPS, vertical bump file is imported:'
    print os.path.join(_InputData.accel_path, "Coupling/VBumps.py")
    vcorrs = None # Will be assigned in exec VBumps.py (vimaier)
    vcorrsYASP = None # Will be assigned in exec VBumpsYASP.py (vimaier)
    execfile(os.path.join(_InputData.accel_path, "Coupling", "VBumps.py")) # LOADS vcorrs
    execfile(os.path.join(_InputData.accel_path, "Coupling", "VBumpsYASP.py")) # LOADS vcorrsYASP
    #Output for YASP...
    f = open(os.path.join(_InputData.output_path, "Coupling", "changeparameters_couple.yasp"), "w")
    f.write("#PLANE V\n")
    f.write("#UNIT RAD\n")
    for vcorr in vcorrsYASP:
        print >> f, "#SETTING", vcorr,  vcorrsYASP[vcorr]
    f.close()

    #Output for Knob...
    g = open(os.path.join(_InputData.output_path, "Coupling", "changeparameters_couple.knob"), "w")
    h = open(os.path.join(_InputData.output_path, "Coupling", "changeparameters_couple.madx"), "w")
    g.write("* NAME  DELTA \n")
    g.write("$ %s    %le   \n")
    for vcorr in vcorrs:
        print >> g, "K"+vcorr, vcorrs[vcorr]
        print >> h, vcorr, "->KICK:=", vcorrs[vcorr], ";"
    h.write('return;')
    g.close()
    h.close()
Esempio n. 43
0
def main(input_path, input_path_model, output_path):
    utils.iotools.create_dirs(output_path)
    (beta_from_phase_x,
     beta_from_amp_x) = _get_twiss_for_one_of(input_path, "getbetax_free.out",
                                              "getbetax.out")
    (beta_from_phase_y,
     beta_from_amp_y) = _get_twiss_for_one_of(input_path, "getbetay_free.out",
                                              "getbetay.out")
    nominal_model = metaclass.twiss(input_path_model)
    _configure_plots()
    files_phase = (beta_from_phase_x, beta_from_phase_y)
    files_amplitude = (beta_from_amp_x, beta_from_amp_y)
    beam = _get_beam_from_model(nominal_model)
    for i in range(len(PLANES)):
        tfs_file = _get_tfs_file(output_path, PLANES[i], beam)
        for ip in IPS:
            (names_range, positions_range, amplitude_ratio_phasefit,
             error_amplitude_ratio_phasefit, amplitude_ratio_measured,
             error_amplitude_ratio_measured, beta_ratio_phasefit,
             error_beta_ratio_phasefit
             ) = _compute_calibration_for_ip_and_plane(ip, PLANES[i],
                                                       files_phase[i],
                                                       files_amplitude[i],
                                                       nominal_model, beam,
                                                       output_path)
            print_files(names_range, positions_range, amplitude_ratio_phasefit,
                        error_amplitude_ratio_phasefit,
                        amplitude_ratio_measured,
                        error_amplitude_ratio_measured, beta_ratio_phasefit,
                        error_beta_ratio_phasefit, beta_ratio_phasefit,
                        error_beta_ratio_phasefit, tfs_file)
        tfs_file.write_to_file()
Esempio n. 44
0
def FindKeywordBetweenMagnets(magnetname1, magnetname2, name, beam):

    if beam == 'B1':
        twissfile = twissfilenameb1
    else:
        twissfile = twissfilenameb2

    twiss = metaclass.twiss(twissfile)

    if IsInTwiss(magnetname1,beam) ==True:
        index1 = twiss.NAME.index(magnetname1)
    elif IsInTwiss(magnetname1+'.'+beam ,beam) ==True:
        index1 = twiss.NAME.index(magnetname1+'.'+beam)

    if IsInTwiss(magnetname2, beam) == True:
        index2 = twiss.NAME.index(magnetname2)
    elif IsInTwiss(magnetname2 + '.' + beam, beam) == True:
        index2 = twiss.NAME.index(magnetname2 + '.' + beam)



    if name in twiss.KEYWORD[min(index1, index2):max(index1, index2)]:
        return True
    else:
        return False
Esempio n. 45
0
    def get_segment(cls, label, first_elem, last_elem, optics_file,
                    twiss_file):
        # this creates a new class called PsSegment
        segment_cls = type(cls.__name__ + "Segment", (_PsSegmentMixin, cls),
                           {})
        segment_inst = segment_cls()

        bpms_file = os.path.join(PS_DIR, str(CURRENT_YEAR),
                                 "sequence/bpms.tfs")
        bpms_file_data = tfs_pandas.read_tfs(bpms_file).set_index("NAME")
        first_elem_s = bpms_file_data.loc[first_elem, "S"]
        last_elem_s = bpms_file_data.loc[last_elem, "S"]
        segment_inst.label = label
        segment_inst.start = Element(first_elem, first_elem_s)
        segment_inst.end = Element(last_elem, last_elem_s)
        segment_inst.optics_file = optics_file
        segment_inst.fullresponse = None

        LOGGER.debug('twiss_file is <%s>', twiss_file)
        tw = twiss(twiss_file)

        LOGGER.debug('twiss_file has tunes %f %f ', tw.Q1, tw.Q2)

        segment_inst.nat_tune_x = tw.Q1
        segment_inst.nat_tune_y = tw.Q2
        segment_inst.energy = tw.ENERGY
        segment_inst.kind = ''  # '' means beta from phase, can be 'betaamp', in the future 'betakmod'

        return segment_inst
Esempio n. 46
0
    def __init__(self, measurement_path, w_path=None):
        _set_output_path(measurement_path)
        self.beta_x = _get_twiss_for_one_of("getbetax_free.out",
                                            "getbetax.out")
        self.QXX = self.beta_x.Q1
        self.QYY = self.beta_x.Q2

        self.beta_y = _get_twiss_for_one_of("getbetay_free.out",
                                            "getbetay.out")

        self.amplitude_beta_x = _get_calibrated_betas("x")
        self.amplitude_beta_y = _get_calibrated_betas("y")

        self.phase_x = _get_twiss_for_one_of("getphasex_free.out",
                                             "getphasex.out")
        self.phase_y = _get_twiss_for_one_of("getphasey_free.out",
                                             "getphasey.out")

        self.total_phase_x = _get_twiss_for_one_of("getphasetotx_free.out",
                                                   "getphasetotx.out")
        self.total_phase_y = _get_twiss_for_one_of("getphasetoty_free.out",
                                                   "getphasetoty.out")

        self.has_dispersion = False
        self.has_coupling = False
        self.couple_method = "_free"

        ### check if dispersion exist
        if self.__try_to_load_dispersion_files():
            self.has_dispersion = True
            print("Dispersion files OK", self.dispersion_x.DX[0],
                  self.dispersion_x.NAME[0])
        else:
            self.has_dispersion = False
            print(
                "No dispersion files... will continue without taking into account dispersion"
            )

        ### check if coupling exist
        if self.__try_to_load_coupling_files():
            self.has_coupling = True
            self.couple_method = "driven"
        else:
            self.has_coupling = False

        if _exists(_join_output_with("getcouple_free.out")):
            self.couple = twiss(_join_output_with("getcouple_free.out"))
            self.couple_method = "_free"
            self.has_coupling = True
            print("Free coupling found")
        if not self.has_coupling:
            print(
                "No coupling file... will continue without taking into account coupling"
            )

        ### check if chromatic exists
        if w_path is None:
            w_path = measurement_path
        self.has_chromatic = self.__try_to_load_chromatic_files(w_path)
Esempio n. 47
0
def calc_BPM_beta(path, ip, beam):
    if ip == 'ip1' or ip == 'ip5':
        L_ip2bpm = 21.564  # Length between IP and first BPM:  BPMSW.1L1.B1, BPMSW.1R1.B1, BPMSW.1L5.B1, BPMSW.1R5.B1
    elif ip == 'ip8' or ip == 'ip2':
        L_ip2bpm = 21.595    
    ip_data = metaclass.twiss(os.path.join(path,'%s.results' %(ip+beam)))
    bw     = ip_data.BETAWAIST
    bw_err = ip_data.BETAWAIST_ERR
    w      = ip_data.WAIST
    w_err  = ip_data.WAIST_ERR
    label  = ip_data.LABEL
    
    IR = ip + beam 

    if IR_definitions[IR+'.X'][0] == 'foc':
        w[0] = -w[0] 
    elif IR_definitions[IR+'.Y'][0] == 'foc':
        w[1] = -w[1]


    b_bpmR = bw + (L_ip2bpm - w)**2/bw
    b_bpmL = bw + (L_ip2bpm + w)**2/bw

    b_bpmR_err = []
    b_bpmL_err = []
    count = 0

    for l in range(len(label)):
        count += 1
        rerr = []
        lerr = []
        we  = np.linspace(-w_err[l] , w_err[l] ,2) + w[l]
        bwe = np.linspace(-bw_err[l], bw_err[l],2) + bw[l]
        for i in range(2):
            for j in range(2):
                rerr.append(bwe[i] + (L_ip2bpm - we[j])**2/bwe[i])
                lerr.append(bwe[i] + (L_ip2bpm + we[j])**2/bwe[i])
        b_bpmR_err.append((max(rerr)-min(rerr))/2.)
        b_bpmL_err.append((max(lerr)-min(lerr))/2.)

    beta_bpm = np.transpose(np.vstack((b_bpmL,b_bpmR)))
    beta_bpm_err = np.transpose(np.vstack((b_bpmL_err,b_bpmR_err)))
    bpms = which_bpms(ip+beam)

    xdata = tfs_file_writer.TfsFileWriter.open(os.path.join(path, 'getkmodbetax_%s.out' %ip))
    xdata.set_column_width(20)
    xdata.add_column_names(['NAME', 'S'  , 'COUNT',   'BETX',    'BETXSTD',       'BETXMDL'    ,        'MUXMDL'     ,      'BETXRES'    ,    'BETXSTDRES' ])
    xdata.add_column_datatypes(['%s', '%le','%le','%le', '%le', '%le', '%le', '%le', '%le'])

    ydata = tfs_file_writer.TfsFileWriter.open(os.path.join(path, 'getkmodbetay_%s.out' %ip))
    ydata.set_column_width(20)
    ydata.add_column_names(['NAME', 'S'  , 'COUNT',    'BETY',    'BETYSTD',   'BETYMDL'      ,      'MUYMDL'    ,       'BETYRES'    ,    'BETYSTDRES'])
    ydata.add_column_datatypes(['%s', '%le','%le','%le', '%le', '%le', '%le', '%le', '%le'])

    for i in range(len(bpms)):
        xdata.add_table_row([bpms[i], 0, 0, beta_bpm[0][i], beta_bpm_err[0][i], 0, 0, 0, 0 ])
        ydata.add_table_row([bpms[i], 0, 0, beta_bpm[1][i], beta_bpm_err[1][i], 0, 0, 0, 0 ])
    xdata.write_to_file()  
    ydata.write_to_file()  
Esempio n. 48
0
def __file_not_valid(name_twiss):
    ''' Checks if the given twiss file is empty, thus not valid. '''
    try:
        tw_f = metaclass.twiss(name_twiss)
        return tw_f.has_no_bpm_data()
    except ValueError:
        # Probably empty file
        return True
Esempio n. 49
0
def __file_not_valid(name_twiss):
    ''' Checks if the given twiss file is empty, thus not valid. '''
    try:
        tw_f = metaclass.twiss(name_twiss)
        return tw_f.has_no_bpm_data()
    except ValueError:
        # Probably empty file
        return True
def _get_tune_data(directory, plane, free=True):
    har_data = metaclass.twiss(_get_harmonic_path(directory, plane))
    plane_index = {HOR: "1", VER: "2"}
    if not free:
        return (getattr(har_data, "Q" + plane_index[plane]),
                getattr(har_data, "Q" + plane_index[plane] + "RMS"))
    return (getattr(har_data, "NATQ" + plane_index[plane]),
            getattr(har_data, "NATQ" + plane_index[plane] + "RMS"))
Esempio n. 51
0
def _get_tune_data(directory, plane, free=True):
    har_data = metaclass.twiss(_get_harmonic_path(directory, plane))
    plane_index = {HOR: "1", VER: "2"}
    if not free:
        return (getattr(har_data, "Q" + plane_index[plane]),
                getattr(har_data, "Q" + plane_index[plane] + "RMS"))
    return (getattr(har_data, "NATQ" + plane_index[plane]),
            getattr(har_data, "NATQ" + plane_index[plane] + "RMS"))
def _get_phase_data(directory, plane, free=True):
    suffix = PLANE_SUFFIX[plane]
    getphase = os.path.join(directory,
                            "getphasetot" + suffix + ".out")
    getphasefree = os.path.join(directory,
                                "getphasetot" + suffix + "_free.out")
    if not free:
        return metaclass.twiss(getphase)
    return _get_twiss_for_one_of(getphasefree, getphase)
Esempio n. 53
0
def lin_fit_data(path, beam, working_directory, magnet1, magnet2, log, logfile, auto_clean):
    file_path_1 = working_directory + '/' + magnet1 + '.' + beam + '.dat'
    file_path_2 = working_directory + '/' + magnet2 + '.' + beam + '.dat'

    left_data = metaclass.twiss(file_path_1)
    right_data = metaclass.twiss(file_path_2)

    if auto_clean == True:
        cleaned_x1 = start_cleaning_data(left_data.K, left_data.TUNEX, left_data.TUNEX_ERR)
        cleaned_y1 = start_cleaning_data(left_data.K, left_data.TUNEY, left_data.TUNEY_ERR)
        cleaned_x2 = start_cleaning_data(right_data.K, right_data.TUNEX, right_data.TUNEX_ERR)
        cleaned_y2 = start_cleaning_data(right_data.K, right_data.TUNEY, right_data.TUNEY_ERR)
    else:
        cleaned_x1 = automatic_cleaning_data(left_data.K, left_data.TUNEX, left_data.TUNEX_ERR)
        cleaned_y1 = automatic_cleaning_data(left_data.K, left_data.TUNEY, left_data.TUNEY_ERR)
        cleaned_x2 = automatic_cleaning_data(right_data.K, right_data.TUNEX, right_data.TUNEX_ERR)
        cleaned_y2 = automatic_cleaning_data(right_data.K, right_data.TUNEY, right_data.TUNEY_ERR)

    fitx_1, covx_1 = np.polyfit(cleaned_x1[:, 0], cleaned_x1[:, 1], 1, cov=True, w=1 / cleaned_x1[:, 2] ** 2)
    fity_1, covy_1 = np.polyfit(cleaned_y1[:, 0], cleaned_y1[:, 1], 1, cov=True, w=1 / cleaned_y1[:, 2] ** 2)
    fitx_2, covx_2 = np.polyfit(cleaned_x2[:, 0], cleaned_x2[:, 1], 1, cov=True, w=1 / cleaned_x2[:, 2] ** 2)
    fity_2, covy_2 = np.polyfit(cleaned_y2[:, 0], cleaned_y2[:, 1], 1, cov=True, w=1 / cleaned_y2[:, 2] ** 2)

    plot_fitting(fitx_1, fitx_2, fity_1, fity_2, left_data, right_data, path)

    dK = 1.0e-5
    K2 = np.average(cleaned_x2[:, 0])
    K1 = np.average(cleaned_x1[:, 0])

    Qx1 = np.average(cleaned_x1[:, 1])
    Qy1 = np.average(cleaned_y1[:, 1])

    Qx2 = np.average(cleaned_x2[:, 1])
    Qy2 = np.average(cleaned_y2[:, 1])


    errx_1 = np.sqrt(np.diag(covx_1)[0]) * dK
    erry_1 = np.sqrt(np.diag(covy_1)[0]) * dK
    errx_2 = np.sqrt(np.diag(covx_2)[0]) * dK
    erry_2 = np.sqrt(np.diag(covy_2)[0]) * dK


    return fitx_2[0], fitx_1[0], fity_2[0], fity_1[
        0], errx_1, erry_1, errx_2, erry_2, K1, K2, dK, Qx1, Qy1, Qx2, Qy2  # kmod_data  # Array with all dQ's (slopes of fit scaled with dK) and the dK spread. [xR, xL, yR, yL, dK ]
Esempio n. 54
0
 def _read_elements_positions(self):
     self._elements_positions = {}
     for beam in self._matcher.get_beams():
         self._elements_positions[beam] = {}
         segment_model = metaclass.twiss(
             os.path.join(getattr(self, "get_beam" + str(beam) + "_output_path")(),
                          "sbs", "twiss_IP" + str(self.get_ip()) + ".dat")
         )
         for index in range(len(segment_model.NAME)):
             self._elements_positions[beam][segment_model.S[index]] = segment_model.NAME[index]
Esempio n. 55
0
def _handle_data_for_lhc():
    #.knob should always exist to be sent to LSA!
    src = os.path.join(os.path.join(_InputData.output_path, "changeparameters_couple.tfs"))
    dst = os.path.join(os.path.join(_InputData.output_path, "changeparameters_couple.knob"))
    Utilities.iotools.copy_item(src, dst)

    ##### for bumps
    if "bumps" in _InputData.variables_list:
        print "passing trough bumps loop"
        v = metaclass.twiss(os.path.join(_InputData.output_path, "changeparameters_couple.tfs"))  # @UnusedVariable
        # v will be used in Bumps.py. Don't do such things again!(vimaier)
        Utilities.iotools.delete_item(os.path.join(_InputData.output_path, "changeparameters_couple.tfs"))
        corrs = None # Will be assigned in exec Bumps.py (vimaier)
        execfile(os.path.join(_InputData.path_to_optics_files_dir, "Bumps.py"))
        execfile(os.path.join(_InputData.path_to_optics_files_dir, "mydictionary.py"))
        tfs_file_writer = Utilities.tfs_file_writer.TfsFileWriter("changeparameters_couple.tfs", _InputData.output_path)
        tfs_file_writer.add_column_names("NAME DELTA".split())
        tfs_file_writer.add_column_datatypes("%s %le".split())
        for vcorr in corrs:
            tfs_file_writer.add_table_row([vcorr, corrs[vcorr]])
        tfs_file_writer.write_to_file()
    #####

    v = metaclass.twiss(os.path.join(_InputData.output_path, "changeparameters_couple.tfs"))
    mad_script = open(os.path.join(_InputData.output_path, "changeparameters_couple.madx"), "w")
    names = getattr(v, "NAME", [])
    delta = getattr(v, "DELTA", [])

    for i in range(len(names)):
        if "bumps" in _InputData.variables_list:
            if cmp(delta[i], 0) == 1:
                mad_script.write(names[i] + "->KICK:=" + str(delta[i]) + ";\n")
            else:
                mad_script.write(names[i] + "->KICK:=" + str(delta[i]) + ";\n")
        else:
            if cmp(delta[i], 0) == 1:
                mad_script.write(names[i] + " = " + names[i] + " + " + str(delta[i]) + ";\n")
            else:
                mad_script.write(names[i] + " = " + names[i] + " " + str(delta[i]) + ";\n")

    mad_script.write("return;")
    mad_script.close()
Esempio n. 56
0
    def _compare_output_betas(self, output_path):
        print "Comparing output..."
        if len(self._errors[output_path]) == 0:
            beta_x_twiss = metaclass.twiss(os.path.join(output_path, "getbetax.out"))
            beta_y_twiss = metaclass.twiss(os.path.join(output_path, "getbetay.out"))

            for index in range(len(beta_x_twiss.NAME)):
                rel_error = abs((beta_x_twiss.BETX[index] - beta_x_twiss.BETXMDL[index]) / beta_x_twiss.BETXMDL[index])
                self.assertTrue(
                    rel_error < MAX_BETA_REL_ERR,
                    "Relative error too big found in: " + beta_x_twiss.NAME[index] + " (" + str(rel_error) + ")",
                )
            for index in range(len(beta_y_twiss.NAME)):
                rel_error = abs((beta_y_twiss.BETY[index] - beta_y_twiss.BETYMDL[index]) / beta_y_twiss.BETYMDL[index])
                self.assertTrue(
                    rel_error < MAX_BETA_REL_ERR,
                    "Relative error too big found in: " + beta_y_twiss.NAME[index] + " (" + str(rel_error) + ")",
                )
        else:
            print "Manual errors in the madx job: skipping betas check"
Esempio n. 57
0
def _loadtwiss_beta(varandpath):
    (var, path) = varandpath
#    print "Reading twiss." + var
    x = 0
    try:
        x = metaclass.twiss(path + "/twiss." + var)
        os.remove(path + "/twiss." + var)
    except IOError as e:
        print e
        return []
    return var, x
Esempio n. 58
0
 def __init__(self, matcher_name, matcher_dict, match_path):
     super(AmpMatcher, self).__init__(matcher_name, matcher_dict, match_path)
     self._sbs_amp_data = {}
     for beam in self.get_beams():
         self._sbs_amp_data[beam] = {}
         for plane in ["x", "y"]:
             sbs_amp_data_path = os.path.join(
                 self.get_match_data(beam).get_beam_match_sbs_path(),
                 'sbsampbetabeat' + plane + '_IP' + str(self._ip) + '.out'
             )
             self._sbs_amp_data[beam][plane] = metaclass.twiss(sbs_amp_data_path)
Esempio n. 59
0
def _loadtwiss_coup(varandpath):
    var, path = varandpath
#    print "Reading twiss." + var
    x = 0
    try:
        x = metaclass.twiss(path + "/twiss." + var)
        x.Cmatrix()
        os.remove(path + "/twiss." + var)
    except IOError as e:
        print e
        return []
    return var, x