Exemplo n.º 1
0
def _progress(job, temp, code_mapping=code_api.NameMapping()):
    fn = code_mapping.stdout_file(temp, state="excited")
    if job.isfile(fn):
        last_line = read_last_line(job.fn(fn)).decode("UTF-8")
        if "pa1 = " in last_line:
            percentage = last_line.split()[-1]
        else:  # already finished the matrix calculation
            percentage = "100.00"
    else:  # didn't yet start the matrix calculation
        percentage = "0.00"

    return "run_{}_temp_excited_state: {:.2f}%".format(temp, float(percentage))
Exemplo n.º 2
0
def _run_code(job,
              temp,
              state,
              codepath="../../bin",
              code_mapping=code_api.NameMapping()):
    code_cmd = os.path.join(codepath, code_mapping.exec_file(temp, state))
    assert os.path.isfile(code_cmd), f"{code_cmd} not found!"

    stdout_file = job.fn(code_mapping.stdout_file(temp, state))
    stderr_file = job.fn(code_mapping.stderr_file(temp, state))

    run_command = f"{code_cmd} {job.ws} > {stdout_file} 2> {stderr_file}"
    command = f"echo {run_command} >> {logfname} ; {run_command}"

    return command
Exemplo n.º 3
0
def _extract_transitions(job, temp, code_mapping=code_api.NameMapping()):
    first_marker = "1=n/2=p       E/hole      E/particle  XX-YY/%"
    last_marker = "Sum XX-YY after normalization *"
    #
    infn = job.fn(code_mapping.stdout_file(temp, state="excited"))
    outfn = job.fn("dipole_transitions.txt")
    #
    with open(infn, "r") as infile, open(outfn, "w") as outfile:
        copy = False
        for line in infile:
            if first_marker in line.strip():
                copy = True
            elif last_marker in line.strip():
                copy = False
            elif copy:
                outfile.write(line)
Exemplo n.º 4
0
def _generate_talys_input(job, temp, code_mapping=code_api.NameMapping()):
    job_mass_number = job.sp.proton_number + job.sp.neutron_number
    fn = job.fn(
        code_mapping.out_file(temp=temp,
                              skalvec="isovector",
                              lorexc="lorentzian"))

    lorvec_df = talys.lorvec_to_df(fname=fn,
                                   Z=job.sp.proton_number,
                                   A=job_mass_number)

    talys_dict = talys.fn_to_dict(
        fname=talys_api.template_photon_strength_function_path(job),
        proton_number=job.sp.proton_number,
    )
    talys_df = talys.dict_to_df(talys_dict)

    mass_numbers = talys.atomic_mass_numbers(talys_df)
    logger.info("{} contains atomic mass numbers from A={} to A={}.".format(
        talys_api.template_photon_strength_function_path(job),
        mass_numbers.min(),
        mass_numbers.max(),
    ))

    if job_mass_number in mass_numbers:
        talys_df_new = talys.replace_table(Z=job.sp.proton_number,
                                           A=job_mass_number,
                                           talys=talys_df,
                                           lorvec=lorvec_df)
        new_talys_dict = talys.df_to_dict(talys_df_new)
        talys.dict_to_fn(
            new_talys_dict,
            fname=job.fn(talys.psf_fn(job)),
            proton_number=job.sp.proton_number,
        )
        job.doc.setdefault("photon_strength_function", talys.psf_fn(job))
    else:
        logger.warning("(Z,A)=({},{}) not found in {}!".format(
            job.sp.proton_number,
            job_mass_number,
            talys_api.template_photon_strength_function_path(job),
        ))
Exemplo n.º 5
0
def _prepare_run(job, temp, code_mapping=code_api.NameMapping()):
    my_filter = {
        param: job.sp[param]
        for param in (
            "proton_number",
            "neutron_number",
            "angular_momentum",
            "parity",
            "temperature",
        )
    }

    project = get_project()
    jobs_for_restart = [
        job for job in project.find_jobs(my_filter)
        if bin_files_exist(job, temp)
    ]
    assert job not in jobs_for_restart
    try:
        job_for_restart = random.choice(jobs_for_restart)
    except IndexError:  # prepare full calculation
        logger.info("Full calculation required.")
        code_input = code_api.GenerateInputs(out_path=job.ws,
                                             mapping=code_mapping,
                                             **dict(job.sp))
        code_input.write_param_files(temp)
        # job.doc[f'run_{temp}_temp_ground_state'] = True
    else:  # prepare restart
        logger.info("Restart possible.")
        code_input = code_api.GenerateInputs(**job.sp,
                                             out_path=job.ws,
                                             mapping=code_mapping,
                                             load_matrix=True)
        code_input.write_param_files(temp, state="excited")
        dotwelfn = code_mapping.wel_file(temp)
        shutil.copy(job_for_restart.fn(dotwelfn), job.fn(dotwelfn))
        for fn in code_mapping.bin_files(temp):
            shutil.copy(job_for_restart.fn(fn), job.fn(fn))
        job.doc["restarted_from"] = job_for_restart.get_id()
Exemplo n.º 6
0
    def _out_file_plot(
            job,
            axis,
            temperature,
            isoscalar_or_isovector,
            lorentzian_or_excitation,
            codemapping=code_api.NameMapping(),
    ):

        fn = job.fn(
            codemapping.out_file(temperature, isoscalar_or_isovector,
                                 lorentzian_or_excitation))

        dataframe = pd.read_csv(
            fn,
            delim_whitespace=True,
            comment="#",
            skip_blank_lines=True,
            header=None,
            names=["energy", "transition_strength"],
        )

        dataframe = dataframe[dataframe.energy < 30]  # MeV

        if lorentzian_or_excitation == "excitation":
            axis.vlines(dataframe.energy,
                        0.0,
                        dataframe.transition_strength,
                        colors="black")
        elif lorentzian_or_excitation == "lorentzian":
            axis.plot(dataframe.energy,
                      dataframe.transition_strength,
                      color="black")
        else:
            raise ValueError

        return dataframe
Exemplo n.º 7
0
def _plot_iso(job, temp, code_mapping=code_api.NameMapping()):
    def _out_file_plot(
            job,
            axis,
            temperature,
            isoscalar_or_isovector,
            lorentzian_or_excitation,
            codemapping=code_api.NameMapping(),
    ):

        fn = job.fn(
            codemapping.out_file(temperature, isoscalar_or_isovector,
                                 lorentzian_or_excitation))

        dataframe = pd.read_csv(
            fn,
            delim_whitespace=True,
            comment="#",
            skip_blank_lines=True,
            header=None,
            names=["energy", "transition_strength"],
        )

        dataframe = dataframe[dataframe.energy < 30]  # MeV

        if lorentzian_or_excitation == "excitation":
            axis.vlines(dataframe.energy,
                        0.0,
                        dataframe.transition_strength,
                        colors="black")
        elif lorentzian_or_excitation == "lorentzian":
            axis.plot(dataframe.energy,
                      dataframe.transition_strength,
                      color="black")
        else:
            raise ValueError

        return dataframe

    fig = Figure(figsize=(12, 6))
    canvas = FigureCanvas(fig)

    gs = GridSpec(2, 1)
    ax = {
        "isoscalar": fig.add_subplot(gs[0, 0]),
        "isovector": fig.add_subplot(gs[1, 0]),
    }

    for skalvec in "isoscalar", "isovector":
        for sp in ("top", "bottom", "right"):
            ax[skalvec].spines[sp].set_visible(False)
        ax[skalvec].set(ylabel=r"$R \; (e^2fm^2/MeV)$")
        ax[skalvec].set_title(skalvec)
        for lorexc in "excitation", "lorentzian":
            df = _out_file_plot(
                job=job,
                axis=ax[skalvec],
                temperature=temp,
                isoscalar_or_isovector=skalvec,
                lorentzian_or_excitation=lorexc,
                codemapping=code_mapping,
            )
            if lorexc == "excitation" and job.sp.transition_energy != 0:
                df = df[np.isclose(df.energy,
                                   job.sp.transition_energy,
                                   atol=0.01)]
                ax[skalvec].vlines(df.energy,
                                   0.0,
                                   df.transition_strength,
                                   colors="red")

    ax["isovector"].set(xlabel="E (MeV)")
    fig.subplots_adjust(hspace=0.3)

    atomic_symbol, mass_number = util.get_nucleus(job.sp.proton_number,
                                                  job.sp.neutron_number,
                                                  joined=False)
    fig.suptitle((
        fr"Transition strength distribution of ${{}}^{{{mass_number}}} {atomic_symbol} \; "
        fr"{job.sp.angular_momentum}^{{{job.sp.parity}}}$ at T = {job.sp.temperature} MeV"
    ))

    canvas.print_png(job.fn(PNG_FILE))
Exemplo n.º 8
0
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.gridspec import GridSpec
from signac import get_project

import mypackage.code_api as code_api
import mypackage.util as util
import mypackage.talys.api as talys
from mypackage.util import arefiles, file_contains, read_last_line, isemptyfile

logger = logging.getLogger(__name__)
logfname = "project.log"

PNG_FILE = "iso_all.png"

code = code_api.NameMapping()
talys_api = talys.TalysAPI()


class Project(FlowProject):
    pass


####################
# OPERATION LABELS #
####################


@Project.label
def plotted(job):
    return job.isfile(PNG_FILE)