import csv
import numpy as np
from TOVsolver.unit import g_cm_3, dyn_cm_2
from TOVsolver.constant import c, G
[docs]
def EOS_import(file_name="", density=0, pressure=0):
"""EOS_import
Imports density and pressure from csv or array, checks them, and returns them.
Args:
file_name (string, optional): string. CSV file to be opened.
density (array, optional): numpy 1Darray. Passed into a check function and returned if valid.
pressure (array, optional): numpy 1Darray. Passed into a check function and returned if valid.
Returns:
array: checked density and pressure.
"""
if not file_name:
density_checked, pressure_checked = EOS_check(density, pressure)
return density_checked, pressure_checked
input_file = file_name
density, pressure = file_read(input_file)
density, pressure = EOS_check(density, pressure)
# tzzhou: migrating to new units
density *= c**2 / G * g_cm_3
pressure *= c**4 / G * dyn_cm_2
return density, pressure
[docs]
def file_read(input_file):
"""file_read
Reads a csv file of denisty and pressure given by the user.
Args:
input_file (string): string. File to be opened and parsed.
Returns:
array: two 1Darray numpy arrays, one corresponding to density and one corresponding to pressrure.
"""
data_list = []
density_list = []
pressure_list = []
with open(input_file) as csvfile:
file_read = csv.reader(csvfile, delimiter=",")
data_list = [row for row in file_read]
for row in data_list:
density_list.append(float(row[0]))
pressure_list.append(float(row[1]))
# Make the lists numpy arrays
density_array = np.array(density_list)
pressure_array = np.array(pressure_list)
return density_array, pressure_array
[docs]
def EOS_check(density, pressure):
"""Return finite 1D EOS arrays with increasing density and stable pressure.
Repeated pressure values are allowed for first-order phase transitions.
Invalid tables raise ``ValueError`` before interpolation or division.
"""
density = np.asarray(density, dtype=float)
pressure = np.asarray(pressure, dtype=float)
if density.ndim != 1 or pressure.ndim != 1 or density.shape != pressure.shape:
raise ValueError("Density and pressure must be matching one-dimensional arrays")
if density.size < 2 or not np.all(np.isfinite(density)) or not np.all(np.isfinite(pressure)):
raise ValueError("EOS tables must contain at least two finite points")
if np.any(density < 0) or np.any(pressure < 0):
raise ValueError("Density and pressure must be nonnegative")
if np.any(np.diff(density) <= 0):
raise ValueError("Energy density must be strictly increasing")
if np.any(np.diff(pressure) < 0):
raise ValueError("Pressure must be nondecreasing")
return density, pressure