Ejemplo n.º 1
0
def tuple_to_name(tup, config_file):
    """ Reverse function to reaction_from_string, returns name given a tuple. """

    part_in, part_out = tup
    s = ','.join([sb.pdg_to_name(x, config_file) for x in part_in]) + ':'
    s += ','.join([sb.pdg_to_name(x, config_file) for x in part_out])
    return s
Ejemplo n.º 2
0
def get_descr(clebsch, part_in, part_out, arrow):
    """Return text description of a reaction in->out."""
    descr = u''
    for i in xrange(part_in.shape[0]):
        descr += sb.pdg_to_name(part_in[i], config_file)
    descr += arrow
    for i in xrange(part_out.shape[0]):
        descr += sb.pdg_to_name(part_out[i], config_file)
    if (clebsch_from_str(clebsch) != 1.0):
        descr = clebsch.replace(' ', '') + '$\\times$(' + descr + ')'
    return descr
Ejemplo n.º 3
0
def isospin_form(react):
    lhs = sorted([
        sb.pdg_to_name(x,
                       config_file).translate(None,
                                              '0+-⁺⁰⁻\^{}$').replace('p', 'n')
        for x in react[0]
    ])
    rhs = sorted([
        sb.pdg_to_name(x,
                       config_file).translate(None,
                                              '0+-⁺⁰⁻\^{}$').replace('p', 'n')
        for x in react[1]
    ])
    return ' '.join(lhs) + '-' + ' '.join(rhs)
Ejemplo n.º 4
0
def plot_spectra_ratio(input1, input2, output_file):
    """ Writes ratio of spectra from files input1 and input2 to output_file. """
    r1 = read_spectrum(input1)
    r2 = read_spectrum(input2)
    if (not (r1['nevents'] == r2['nevents'] and
        r1['t0'] == r2['t0'] and
        r1['pdg_list'] == r2['pdg_list'])):
        sys.exit("Files have to be obtained for equal conditions")

    plt.xlabel("E, GeV", fontsize = '20')
    plt.ylabel("$\\frac{dN_{Pauli}/dE}{dN_{no Pauli}/dE}$", fontsize = '20')
    plt.title("Pauli blocking: spectra ratio, %d events" % r1['nevents'], fontsize = '20')

    for i in xrange(len(r1['pdg_list'])):
        plt.errorbar(r1['spectra'][2*i], r1['spectra'][2*i+1]/r2['spectra'][2*i+1],
                     yerr = np.sqrt(2.0/r1['spectra'][2*i+1]),
                     label=sb.pdg_to_name(int(r1['pdg_list'][i]))+", m = 0.1 GeV, T = 1 GeV")
    plt.legend(fontsize = '20')
    plt.savefig(output_file)
Ejemplo n.º 5
0
def plotting(data1, data2, config_file, smash_code_version, output_folder):
    quantities = data1.quantities.union(data2.quantities)
    pdglist = data1.pdglist.union(data2.pdglist)
    pdglist_abs = np.unique(np.abs(np.array(list(pdglist))))
    colliding_systems = data1.colliding_systems.union(data2.colliding_systems)
    colliding_systems_list = list(colliding_systems)
    energies = sorted(list(data1.energies.union(data2.energies)))

    for quantity in quantities:
        if ('spectra' in quantity): continue
        collected_results_pp = [[], [], []]
        collected_results_AuAuPbPb = [[], [], []]
        for pdg_abs in pdglist_abs:
            # Sigma0 is added to Lambda plots
            if (pdg_abs == 3212): continue
            # We do not want the Deuteron plots to be displayed, because SMASH
            # needs to be modified for useful results (cross section cut off)
            if (pdg_abs == 1000010020): continue
            pdg_one_sort = []
            if (pdg_abs in pdglist): pdg_one_sort.append(pdg_abs)
            if (-pdg_abs in pdglist): pdg_one_sort.append(-pdg_abs)
            for pdg in pdg_one_sort:
                for colliding_system in colliding_systems:
                    if (pdg == pdg_abs):
                        plot_format = '-'
                        plot_label = colliding_system
                        exp_fmt = 'o'
                    else:
                        plot_format = '--'
                        plot_label = ''
                        exp_fmt = 's'

                    if (colliding_system == 'pp'):
                        linewidth = 5
                        plot_color = 'midnightblue'
                    else:
                        linewidth = 5
                        plot_color = 'darkred'
                    if data1.is_in_dict([quantity, colliding_system, pdg]):
                        theory_vs_energy = data1.the_dict[quantity][
                            colliding_system][pdg]
                        x, y = zip(*sorted(theory_vs_energy.iteritems()))
                        plt.plot(x,
                                 y,
                                 plot_format,
                                 label=plot_label,
                                 color=plot_color,
                                 lw=linewidth)

                        # store results in list to later save it for future comparison
                        if (colliding_system == 'pp'):
                            collected_results_pp[0].append(pdg)
                            if (collected_results_pp[1] == []):
                                collected_results_pp[1].append(x)
                            collected_results_pp[2].append(y)
                        if (colliding_system == 'AuAu/PbPb'):
                            collected_results_AuAuPbPb[0].append(pdg)
                            if (collected_results_AuAuPbPb[1] == []):
                                collected_results_AuAuPbPb[1].append(x)
                            collected_results_AuAuPbPb[2].append(y)

                        if args.comp_prev_version:
                            import comp_to_prev_version as cpv
                            # read and plot results from previous version
                            filename_prev = quantity + '_' + colliding_system.replace(
                                '/', '')
                            prev_SMASH_version = cpv.plot_previous_results(
                                'energy_scan',
                                '',
                                filename_prev + '.txt',
                                plot_color=plot_color,
                                pdg=pdg,
                                plot_style=plot_format)

                    if data2.is_in_dict([quantity, colliding_system, pdg]):
                        exp_vs_energy = data2.the_dict[quantity][
                            colliding_system][pdg]
                        x_exp, y_exp = zip(*sorted(exp_vs_energy.iteritems()))
                        y_exp_values, y_exp_errors = zip(*y_exp)
                        plt.errorbar(x_exp, y_exp_values, yerr = y_exp_errors, fmt = exp_fmt,\
                                     color = plot_color, elinewidth = 2, markeredgewidth = 0)

            if args.comp_prev_version:
                #dummy, for combined legend entry of previous results.
                plt.plot(1,
                         0.0,
                         linestyle='-',
                         linewidth=10,
                         zorder=1,
                         alpha=0.2,
                         color='dimgrey',
                         label=prev_SMASH_version)

            plt.xlabel('$\sqrt{s_{NN}} [GeV]$')
            plt.xscale('log')

            if (quantity in ['total_multiplicity', 'midrapidity_yield']):
                if np.all(y == 0):
                    print 'No positive values encountered in ' + str(quantity) + ' for ' + str(pdg) +\
                          '. Cannot log-scale the y axis, scale will be linear.'
                else:
                    plt.yscale('log', nonposy='clip')
            hadron_name = sb.pdg_to_name(pdg_abs, config_file).decode("utf-8")
            antihadron_name = sb.pdg_to_name(-pdg_abs,
                                             config_file).decode("utf-8")
            plot_title = hadron_name
            if not pdg_abs in [111, 333]:  # antiparticle of itself
                plot_title += ' (' + antihadron_name + ' dashed, squares)'
            title_dict = {
                'total_multiplicity': ' $4\pi$ multiplicity',
                'midrapidity_yield': ' $dN/dy|_{y = 0}$',
                'meanmt0_midrapidity':
                ' $<m_{T}>|_{y = 0}$, $m_{T} = \sqrt{p_T^2 + m^2} - m$',
                'meanpt_midrapidity': ' $<p_{T}>|_{y = 0}$'
            }
            plt.title(plot_title)
            plt.ylabel(title_dict[quantity])
            plt.legend()
            plt.figtext(0.8, 0.94, " SMASH code:      %s\n SMASH analysis: %s" % \
                         (smash_code_version, sb.analysis_version_string()), \
                         color = "gray", fontsize = 10)
            plt.savefig(output_folder + '/' + quantity + str(pdg_abs) + '.pdf')
            plt.clf()

        # Save results plotted above for future comparison
        filename_AuAuPbPb = quantity + '_' + 'AuAuPbPb' + '.txt'
        filename_pp = quantity + '_' + 'pp' + '.txt'

        store_results(output_folder + '/' + filename_AuAuPbPb,
                      collected_results_AuAuPbPb, smash_code_version, quantity)
        store_results(output_folder + '/' + filename_pp, collected_results_pp,
                      smash_code_version, quantity)

    # Plotting spectra, only those, where some data is present
    for quantity in quantities:
        if (quantity
                not in ['yspectra', 'mtspectra', 'ptspectra', 'v2spectra']):
            continue
        if (quantity == 'v2spectra' and not args.with_v2): continue
        for pdg in pdglist:
            if (abs(pdg) == 3212): continue
            if (abs(pdg) == 1000010020): continue
            collected_results_pp = [[], [], []]
            collected_results_AuAuPbPb = [[], [], []]
            for colliding_system in colliding_systems:
                #if not data2.is_in_dict([quantity, colliding_system, pdg]): continue
                #if not data1.is_in_dict([quantity, colliding_system, pdg]): continue

                # colors list for plotting
                col = cycle(colours)
                # to scale curves in mT and pT spectra by powers of 10 -> readability
                scaling_counter = -1
                for element, energy in enumerate(energies):
                    collider = determine_collider(energy)
                    in_theory = data1.is_in_dict(
                        [quantity, colliding_system, pdg, energy])
                    in_experiment = data2.is_in_dict(
                        [quantity, colliding_system, pdg, energy])
                    #if (not in_experiment): continue
                    if (in_experiment and not in_theory):
                        print energy, colliding_system, pdg, in_theory, in_experiment, \
                              ': there is experimental data, but no SMASH calculation!'
                    if (in_theory):
                        plot_color = next(col)
                        bin_edges, y = data1.the_dict[quantity][
                            colliding_system][pdg][energy]
                        bin_edges = np.array(bin_edges)
                        bin_width = bin_edges[1:] - bin_edges[:-1]
                        x = 0.5 * (bin_edges[1:] + bin_edges[:-1])
                        y = np.array(y)
                        # dN/dy
                        if (quantity == 'yspectra'):
                            y /= bin_width
                            plt.plot(x,
                                     y,
                                     '-',
                                     lw=4,
                                     color=plot_color,
                                     label=str(energy))
                        # dN/dmT
                        pole_masses = {
                            111: 0.138,
                            211: 0.138,
                            321: 0.495,
                            2212: 0.938,
                            3122: 1.116,
                            3312: 1.321,
                            3334: 1.672,
                            1000010020: 1.8756,
                            3212: 1.189
                        }
                        m0 = pole_masses[abs(pdg)]
                        if (quantity == 'mtspectra'):
                            scaling_counter += 1
                            y /= ((x + m0) * bin_width) * (
                                2.0 * data1.midrapidity_cut
                            )  # factor 2 because [-y_cut; y_cut]
                            if np.all(
                                    y == 0
                            ):  # rescale y-axis to be linear if mtspectra of current energy are 0, but those
                                plt.yscale(
                                    'linear'
                                )  # of the previous energy were not, so that the scale was already set to log scale.
                            plt.plot(x,
                                     y * 10**scaling_counter,
                                     '-',
                                     lw=4,
                                     color=plot_color,
                                     label=str(energy) +
                                     r' $\times \ $10$^{\mathsf{' +
                                     str(scaling_counter) + r'}}$')
                        # dN/dpT
                        if (quantity == 'ptspectra'):
                            scaling_counter += 1
                            y /= (bin_width * x) * (
                                2.0 * data1.midrapidity_cut
                            )  # factor 2 because [-y_cut; y_cut]
                            if np.all(
                                    y == 0
                            ):  # rescale y-axis to be linear if ptspectra of current energy are 0, but those
                                plt.yscale(
                                    'linear'
                                )  # of the previous energy were not, so that the scale was already set to log scale.
                            plt.plot(x,
                                     y * 10**scaling_counter,
                                     '-',
                                     lw=4,
                                     color=plot_color,
                                     label=str(energy) +
                                     r' $\times \ $10$^{\mathsf{' +
                                     str(scaling_counter) + r'}}$')
                        # v2
                        if (quantity == 'v2spectra'):
                            y /= (bin_width) * (
                                2.0 * data1.midrapidity_cut
                            )  # factor 2 because [-y_cut; y_cut]
                            plt.plot(x,
                                     y,
                                     '-',
                                     lw=4,
                                     color=plot_color,
                                     label=str(energy))

                        # store results in list to later save for future comparison
                        if (colliding_system == 'pp'):
                            collected_results_pp[0].append(energy)
                            if (collected_results_pp[1] == []):
                                collected_results_pp[1].append(x)
                            collected_results_pp[2].append(y)
                        if (colliding_system == 'AuAu/PbPb'):
                            collected_results_AuAuPbPb[0].append(energy)
                            if (collected_results_AuAuPbPb[1] == []):
                                collected_results_AuAuPbPb[1].append(x)
                            collected_results_AuAuPbPb[2].append(y)

                        # read and plot results from previous version
                        if args.comp_prev_version and quantity != 'v2spectra':
                            #v2 is not regularly run, old results are neither produced nor stored
                            filename_prev = quantity + '_' + colliding_system.replace(
                                '/', '') + '_' + str(pdg)
                            prev_SMASH_version = cpv.plot_previous_results(
                                'energy_scan',
                                '',
                                filename_prev + '.txt',
                                energy=energy,
                                plot_color=plot_color,
                                scaling_counter=scaling_counter)

                    if (in_experiment):
                        x, y, y_err = data2.the_dict[quantity][
                            colliding_system][pdg][energy]
                        if (quantity == 'mtspectra'):
                            plt.errorbar(x,
                                         y * 10**scaling_counter,
                                         yerr=y_err,
                                         fmt='o',
                                         color=plot_color)
                        elif (quantity == 'ptspectra'):
                            plt.errorbar(x,
                                         y * 10**scaling_counter,
                                         yerr=y_err,
                                         fmt='o',
                                         color=plot_color)
                        elif (quantity == 'v2spectra'):
                            plt.errorbar(x,
                                         y,
                                         yerr=y_err,
                                         fmt='o',
                                         color=plot_color)
                        else:  # yspectra
                            plt.errorbar(x,
                                         y,
                                         yerr=y_err,
                                         fmt='o',
                                         color=plot_color)
                    title_dict = {
                        'yspectra': '$dN/dy$',
                        'mtspectra': '$1/m_{T} \ d^2N/dm_{T} dy$ [GeV$^{-2}$]',
                        'ptspectra': '$1/p_{T} \ d^2N/dp_{T} dy$ [GeV$^{-2}$]',
                        'v2spectra': '$v_2$',
                    }

                    plot_title = sb.pdg_to_name(pdg,
                                                config_file).decode("utf-8")
                    plot_title += ' in ' + colliding_system + ' collisions'
                    plt.title(plot_title)
                    plt.figtext(0.15, 0.94, " SMASH code:      %s\n SMASH analysis: %s" % \
                        (smash_code_version, sb.analysis_version_string()), \
                        color = "gray", fontsize = 10)
                    if (quantity == 'mtspectra' or quantity == 'ptspectra'):
                        if np.all(y == 0):
                            print 'No positive values encountered in ' + str(quantity) + ' for ' + str(pdg) +\
                                  '. Cannot log-scale the y axis, scale will be linear.'
                        else:
                            plt.yscale('log', nonposy='clip')
                        if (quantity == 'mtspectra'):
                            plt.xlabel('$m_{T} - m_{0}$ [GeV]')
                        else:
                            plt.xlabel('$p_{T}$ [GeV]')
                    elif (quantity == 'yspectra'):
                        plt.xlabel('$y$')
                    else:
                        plt.xlabel('$p_{T}$ [GeV]')

                    plt.ylabel(title_dict[quantity])
                    if (determine_collider(energy) != determine_collider(
                            energies[(element + 1) % len(energies)])):
                        if args.comp_prev_version:
                            #dummy for legend entry of combined previous results.
                            plt.plot(1,
                                     0.0,
                                     linestyle='-',
                                     linewidth=10,
                                     zorder=1,
                                     color='dimgrey',
                                     label=prev_SMASH_version,
                                     alpha=0.2)
                        plt.legend(loc='upper right',
                                   title='$\sqrt{s} \ $ [GeV] =',
                                   ncol=1,
                                   fontsize=26)
                        plt.savefig(output_folder + '/' + quantity + '_' +
                                    colliding_system.replace('/', '') + '_' +
                                    str(determine_collider(energy)) + '_' +
                                    str(pdg) + '.pdf')
                        plt.clf()
                        plt.close()
                        scaling_counter = -1  #re-initialize as generating a new plot

            # Save results plotted above for future comparison
            filename_AuAuPbPb = quantity + '_AuAuPbPb_' + str(pdg) + '.txt'
            filename_pp = quantity + '_pp_' + str(pdg) + '.txt'

            store_results(output_folder + '/' + filename_AuAuPbPb,
                          collected_results_AuAuPbPb, smash_code_version,
                          quantity)
            store_results(output_folder + '/' + filename_pp,
                          collected_results_pp, smash_code_version, quantity)
Ejemplo n.º 6
0
 def get_name(self, pdg):
     """Get the name of a particle given the PDG ID."""
     return smash.pdg_to_name(pdg, self.args.config_file)
contents = np.loadtxt(input_file, skiprows=6)
time = contents[0]
n_pdgs = len(pdg_list)

plt.xlabel("t [fm/c]", fontsize=36)
plt.ylabel("number of particles", fontsize=36)

plt.title("Box: chemical equilibration")
smash_code_version, analysis_version = smash_version.split()
plt.figtext(0.8, 0.94, " %d events\n SMASH code:      %s\n SMASH analysis: %s" % \
             (total_events, smash_code_version, analysis_version), \
             color = "gray", fontsize = 10)

for i in np.arange(n_pdgs):
    label = sb.pdg_to_name(int(pdg_list[i]), config_file).decode("utf-8")
    plt.plot(time, contents[2 * i + 1], label=label, lw=3)
    x = time[time > tstart]
    y = contents[2 * i + 1][time > tstart]
    A = np.polyfit(x, y, 0)
    plt.axhline(y=A[0],
                xmin=tstart / x.max(),
                linewidth=1,
                color='k',
                linestyle='-')
plt.axvline(x=tstart, linewidth=3, color='k', linestyle='--')

plt.legend(ncol=3, fontsize=30)

plt.savefig(output_file)
Ejemplo n.º 8
0
parser = argparse.ArgumentParser()
# options and arguments
parser.add_argument("-v",
                    "--verbose",
                    action="store_true",
                    help="print additional output")
parser.add_argument("pdg1", help="PDG code of the first particle")
parser.add_argument("pdg2", help="PDG code of the second particle")
parser.add_argument("config_file", help="config file")
parser.add_argument("filename",
                    nargs='+',
                    help="binary file(s) containing collision history")
args = parser.parse_args()

initial_pdgs.append(smash.pdg_to_name(int(args.pdg1), args.config_file))
initial_pdgs.append(smash.pdg_to_name(int(args.pdg2), args.config_file))
initial_pdgs.sort()


def abs3(p):
    "given a 4-vector p, determine the absolute value of its spatial 3-vector"
    return math.sqrt(p[1]**2 + p[2]**2 + p[3]**2)


def sqr4(p):
    "square a 4-vector p"
    return p[0]**2 - p[1]**2 - p[2]**2 - p[3]**2


def abs4(p):