Example #1
0
def read_dat_table(table_name):
    path = "./"
    sFile, array_size = check_old_file(path, table_name)
    if (not sFile):
        path = "../src/fluids/cosmicrays/"
        sFile, array_size = check_old_file(path, table_name)
        if (not sFile):
            die("Failed to load solution map file with " + table_name)

    dataArray = []
    data_to_plot = [[0.0 for i in range(array_size)]
                    for j in range(array_size)]
    i = 0

    with open(path + table_name + ".dat", "r") as sFile:
        next(sFile)
        next(sFile)
        next(sFile)
        for line in sFile:
            data_in_line = []
            for item in line.split(' '):
                if item != '':
                    data_in_line.append(float(item))
                data_to_plot[i][:] = data_in_line
            i = i + 1
        table = data_to_plot

    return table
Example #2
0
def crs_initialize(parameter_names, parameter_values):

    try:
        for i in range(len(parameter_names)):
            exec("%s = %s" % (parameter_names[i], parameter_values[i]),
                 globals())
    except:
        die("Exiting: len(names) not equal len(values)")

    global p_fix_ratio, p_fix

    edges = []
    p_fix = []
    edges[0:ncre] = range(0, ncre + 1, 1)
    p_fix[0:ncre] = zeros(ncre + 1)
    log_width = (log10(p_max_fix / p_min_fix)) / (ncre - 2.0)
    for i in range(0, ncre - 1):
        p_fix[i + 1] = p_min_fix * 10.0**(log_width * edges[i])
        p_fix_ratio = 10.0**log_width
        p_fix[0] = (sqrt(p_fix[1] * p_fix[2])) / p_fix_ratio
        p_fix[ncre] = (sqrt(p_fix[ncre - 2] * p_fix[ncre - 1])) * p_fix_ratio
        p_fix = asfarray(p_fix)

    p_mid_fix = zeros(ncre)
    p_mid_fix[1:ncre - 1] = sqrt(p_fix[1:ncre - 1] * p_fix[2:ncre])
    p_mid_fix[0] = p_mid_fix[1] / p_fix_ratio
    p_mid_fix[ncre - 1] = p_mid_fix[ncre - 2] * p_fix_ratio
    p_mid_fix = asfarray(p_mid_fix)

    p_fix = tuple(p_fix)
    p_mid_fix = tuple(p_mid_fix)
    global clean_plot
    clean_plot = True
Example #3
0
def initialize_pf_arrays(h5fname, pf_initialized=False):
    global p_ratios_lo, f_ratios_lo, p_ratios_up, f_ratios_up, alpha_tab_lo, n_tab_lo, alpha_tab_up, n_tab_up, size
    h5f = h5py.File(h5fname, "r")
    if ("/cresp" in h5f):
        p_ratios_lo = h5f["cresp/smaps_LO/p_ratios"]
        f_ratios_lo = h5f["cresp/smaps_LO/f_ratios"]
        p_ratios_up = h5f["cresp/smaps_UP/p_ratios"]
        f_ratios_up = h5f["cresp/smaps_UP/f_ratios"]
        # Use whatever values are saved in h5 file
        a_min_lo = h5f["cresp"]["smaps_LO"].attrs["a_min"]
        a_max_lo = h5f["cresp"]["smaps_LO"].attrs["a_max"]
        n_min_lo = h5f["cresp"]["smaps_LO"].attrs["n_min"]
        n_max_lo = h5f["cresp"]["smaps_LO"].attrs["n_max"]

        a_min_up = h5f["cresp"]["smaps_UP"].attrs["a_min"]
        a_max_up = h5f["cresp"]["smaps_UP"].attrs["a_max"]
        n_min_up = h5f["cresp"]["smaps_UP"].attrs["n_min"]
        n_max_up = h5f["cresp"]["smaps_UP"].attrs["n_max"]

        if (h5f["cresp"]["smaps_LO"].attrs["dims"][0] !=
                h5f["cresp"]["smaps_UP"].attrs["dims"][0]):
            die("Error, different sizes of solution maps!")
        else:
            size = h5f["cresp"]["smaps_UP"].attrs["dims"][0]
    else:
        # Try load old dat files
        p_ratios_lo = read_dat_table("p_ratios_lo")
        f_ratios_lo = read_dat_table("f_ratios_lo")

        p_ratios_up = read_dat_table("p_ratios_up")
        f_ratios_up = read_dat_table("f_ratios_up")
        # Assume the same values as in cresp_NR_method before d0c434e0322db2bf9c4123a5f938ba3fdd51414d
        a_min_lo = 0.2
        a_max_lo = 0.999999
        a_min_up = 1.000005
        a_max_up = 200.0

        n_min_lo = 1.0e-11
        n_max_lo = 5000.0
        n_min_up = 1.0e-12
        n_max_up = 1000.0

        size = int(len(p_ratios_lo))

    alpha_tab_lo = zeros(size)
    n_tab_lo = zeros(size)
    alpha_tab_up = zeros(size)
    n_tab_up = zeros(size)

    for i in range(size):
        alpha_tab_lo[i] = ind_to_flog(i, a_min_lo, a_max_lo, size)
        alpha_tab_up[i] = ind_to_flog(i, a_min_up, a_max_up, size)
        n_tab_lo[i] = ind_to_flog(i, n_min_lo, n_max_lo, size)
        n_tab_up[i] = ind_to_flog(i, n_min_up, n_max_up, size)

    pf_initialized = True

    # initialized
    return
Example #4
0
def get_interpolated_ratios(bnd, alpha_val, n_val, interpolation_error,
                            **kwargs):
    verbose = kwargs.get("verbose", "False")

    loc1 = [1, 1]
    loc2 = [2, 2]

    pf_ratio = [1.0, 1.0]
    if bnd == "up":
        p_p = p_ratios_up
        p_f = f_ratios_up
        p_a = alpha_tab_up
        p_n = n_tab_up
    elif bnd == "lo":
        p_p = p_ratios_lo
        p_f = f_ratios_lo
        p_a = alpha_tab_lo
        p_n = n_tab_lo
    else:
        die("Provided bnd not supported: %s" % bnd)

    loc1[0] = inverse_f_to_ind(n_val, p_n[0], p_n[size - 1], size - 1)
    loc1[1] = inverse_f_to_ind(alpha_val, p_a[0], p_a[size - 1], size - 1)

    if min(loc1[:]) > 0 and max(loc1[:]) <= size - 1:
        loc2[0] = loc1[0] + 1
        loc2[1] = loc1[1] + 1
    else:
        if (verbose):
            prtwarn("(ERROR) Obtained indices (%s): [%i, %i] -> [%f, %f]" %
                    (bnd, loc1[0], loc1[1], pf_ratio[0], pf_ratio[1]))
        interpolation_error = True
        return pf_ratio, interpolation_error

    pf_ratio[0] = bilin_interpol(
        p_p[loc1[0]][loc1[1]], p_p[loc2[0]][loc1[1]], p_p[loc1[0]][loc2[1]],
        p_p[loc2[0]][loc2[1]], bl_in_tu(p_a[loc1[1]], alpha_val, p_a[loc2[1]]),
        bl_in_tu(p_n[loc1[0]], n_val, p_n[loc2[0]]))

    pf_ratio[1] = bilin_interpol(
        p_f[loc1[0]][loc1[1]], p_f[loc2[0]][loc1[1]], p_f[loc1[0]][loc2[1]],
        p_f[loc2[0]][loc2[1]], bl_in_tu(p_a[loc1[1]], alpha_val, p_a[loc2[1]]),
        bl_in_tu(p_n[loc1[0]], n_val, p_n[loc2[0]]))

    if min(pf_ratio[:]) <= 0.0:
        if (verbose):
            prtwarn("(ERROR) Obtained p & f (%s) ratios: [%f, %f]" %
                    (bnd, pf_ratio[0], pf_ratio[1]))
        return pf_ratio, interpolation_error
    else:
        if (verbose):
            prtinfo("        Obtained indices (%s): [%i, %i] -> [%f, %f]" %
                    (bnd, loc1[0], loc1[1], pf_ratio[0], pf_ratio[1]))
        interpolation_error = False

    return pf_ratio, interpolation_error
def add_cree_tot_to(h5_dataset):
    try:
        if (h5ds.all_data()["cree01"].units is "dimensionless"):
            h5ds.add_field(("gdf", "cree_tot"),
                           units="",
                           function=_total_cree,
                           display_name="Total CR electron energy density",
                           sampling_type="cell")
        else:
            h5ds.add_field(("gdf", "cree_tot"),
                           units="Msun/(Myr**2*pc)",
                           function=_total_cree,
                           display_name="Total CR electron energy density",
                           dimensions=dimensions.energy / dimensions.volume,
                           sampling_type="cell")
    except:
        die("Failed to construct field 'cree_tot'")
    return h5_dataset
def add_cren_tot_to(h5_dataset):
    try:
        if (h5ds.all_data()["cren01"].units is "dimensionless"):
            h5ds.add_field(("gdf", "cren_tot"),
                           units="",
                           function=_total_cren,
                           display_name="Total CR electron number density",
                           sampling_type="cell")
        else:
            h5ds.add_field(("gdf", "cren_tot"),
                           units="1/(pc**3)",
                           function=_total_cren,
                           display_name="Total CR electron number density",
                           dimensions=dimensions.energy / dimensions.volume,
                           sampling_type="cell",
                           take_log=True)
    except:
        die("Failed to construct field 'cren_tot'")
    return h5_dataset
Example #7
0
def crs_plot_main_fpq(parameter_names, parameter_values, plot_var, fcrs, qcrs,
                      pcrs, field_max, time, location, **kwargs):
    global first_run, got_q_tabs, e_small, p_min_fix, p_max_fix, ncre, cre_eff, i_plot, marker, par_plotted_src

    marker = kwargs.get("marker", "x")
    i_plot = kwargs.get("i_plot", 0)

    try:
        for i in range(len(parameter_names)):
            exec("%s = %s" % (parameter_names[i], parameter_values[i]),
                 globals())
    except:
        die(" len(names) not equal len(values) at input.")

# TODO -------- do it under *args TODO
    fixed_width = True
    # -------------------
    global plot_ymax, p_fix_ratio, p_fix
    plot_ymax = field_max * cre_eff

    if first_run:
        dummyCRSfile = open("crs.dat", "w+")
        dummyCRSfile.close()
        p_fix = []
        edges = []
        edges[0:ncre] = range(0, ncre + 1, 1)
        p_fix[0:ncre] = zeros(ncre + 1)
        log_width = (log10(p_max_fix / p_min_fix)) / (ncre - 2.0)
        for i in range(0, ncre - 1):  # organize p_fix
            p_fix[i + 1] = p_min_fix * 10.0**(log_width * edges[i])
            p_fix_ratio = 10.0**log_width
            p_fix[0] = (sqrt(p_fix[1] * p_fix[2])) / p_fix_ratio
            p_fix[ncre] = (sqrt(
                p_fix[ncre - 2] * p_fix[ncre - 1])) * p_fix_ratio
            p_fix = asfarray(p_fix)

    i_lo = 0
    i_up = ncre
    empty_cell = True

    for i in range(ncre):
        if fcrs[i] > 0.0:
            i_lo = i - 2
            empty_cell = False
            break
    for i in range(ncre, 1, -1):
        if fcrs[i] > 0.0:
            i_up = max(0, i + 1)
            break

    i_cor = 0
    if (fcrs[i_lo] == 0.0):
        i_cor = 1
    fln = array(fcrs[i_lo + i_cor:i_up])
    q = array(qcrs[i_lo + i_cor:i_up])
    pln = p_fix[i_lo + i_cor:i_up]
    prn = p_fix[i_lo + 1 + i_cor:i_up + 1]

    pln[0] = pcrs[0]
    prn[-1] = pcrs[-1]
    plot = False  # dummy variable until plot is made

    prtinfo(
        "\033[44mTime = %6.2f |  i_lo = %2d, i_up = %2d %s" %
        (time, i_lo + i_cor if not empty_cell else 0,
         i_up if not empty_cell else 0, '(empty cell)' if empty_cell else ' '))
    if (i_lo == ncre or i_up == 0):
        empty_cell = True
        return plot, empty_cell

    frn = fln * (prn / pln)**(-q)
    prtinfo(
        "Cutoff indices obtained (lo, up): %i, %i || momenta (lo, up): %f, %f "
        % (i_lo + i_cor, i_up, pcrs[0], pcrs[1]))
    if (verbosity_1):
        fcrs1e3 = []
        for item in fcrs:
            fcrs1e3.append(float('%1.3e' %
                                 item))  # : print ("n = %1.3e" %item)
        prtinfo("f = " + str(fcrs1e3))
        prtinfo("q = " + str(around(qcrs, 3)))

    if (empty_cell is False):

        plot = plot_data(plot_var, pln, prn, fln, frn, q, time, location, i_lo,
                         i_up)
        i_plot = i_plot + 1

    return plot, empty_cell
from crs_pf import initialize_pf_arrays
from math import isnan, pi
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from numpy import array as np_array, log, log10, mean, rot90
from os import getcwd, makedirs, path
from optparse import OptionParser
from re import search
from read_h5 import read_par, input_names_array
from sys import argv, version
from warnings import simplefilter
try:
    import yt
    from yt.units import dimensions
except:
    die("You must make yt available somehow")
if (version[0:3] != "2.7"):
    raw_input = input
    not_py27 = True
else:
    not_py27 = False
# ------- Parse arguments
parser = OptionParser(
    "Usage: %prog FILE [options] [args] or %prog [options] [args] -F FILENAME")
parser.add_option("-F",
                  "--file",
                  dest="filename",
                  default="None",
                  help=u"File to use",
                  type="str")
parser.add_option("-v",
Example #9
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import h5py
from colored_io import die, prtinfo, prtwarn

# This script reads problem.par field from provided
# h5/res file, extracts it and saves it in CWD,
# so it can be used in new run.

if (len(sys.argv) > 1):
    hdf5_filename = sys.argv[1]
    prtinfo("File to process is %s" % hdf5_filename)
else:
    die("No file provided, exiting.")

try:
    fh5 = h5py.File(hdf5_filename, 'r')
    parfile_out = open(
        "problem.par.%s" % hdf5_filename.strip(".res").strip(".h5"), 'w')
except:
    die("Problem opening %s file. " % hdf5_filename)

parameter_object = fh5["problem.par"]
for line in parameter_object:
    # print(line.decode("utf-8"))
    parfile_out.write(line.decode("utf-8") + "\n")

prtinfo(
    "Successfully read parameters from %s file, list of parameters saved to %s"