diff --git a/docs/research/code_comparison/toy_models/reading blondin toymodel.ipynb b/docs/research/code_comparison/toy_models/reading blondin toymodel.ipynb index 3769031248d..0f92a754bc1 100644 --- a/docs/research/code_comparison/toy_models/reading blondin toymodel.ipynb +++ b/docs/research/code_comparison/toy_models/reading blondin toymodel.ipynb @@ -9,18 +9,9 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 26, "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/Users/wkerzend/miniconda/envs/tardis3/lib/python3.6/site-packages/tqdm/autonotebook/__init__.py:14: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n", - " \" (e.g. in jupyter console)\", TqdmExperimentalWarning)\n" - ] - } - ], + "outputs": [], "source": [ "import pandas as pd\n", "import re\n", @@ -28,15 +19,40 @@ "import numpy as np\n", "import yaml\n", "from tardis import run_tardis\n", - "from astropy import units as u" + "from astropy import units as u\n", + "import base64\n", + "from IPython.display import HTML\n", + "\n" ] }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 27, "metadata": {}, "outputs": [], "source": [ + "\n", + "def create_df_download_link( df, title=\"Download CSV file\", filename=\"data.csv\", type='zip'):\n", + " if type != 'zip':\n", + " csv = df.to_csv()\n", + " b64 = base64.b64encode(csv.encode())\n", + " payload = b64.decode()\n", + " else:\n", + " payload = df.decode()\n", + " html = '{title}'\n", + " html = html.format(payload=payload,title=title,filename=filename)\n", + " return HTML(html)\n", + "\n", + "def create_download_link(download_data, title=\"Download CSV file\", filename=\"data.csv\", type='zip'):\n", + " if type != 'zip':\n", + " csv = df.to_csv()\n", + " b64 = base64.b64encode(csv.encode())\n", + " payload = b64.decode()\n", + " else:\n", + " payload = df.decode()\n", + " html = '{title}'\n", + " html = html.format(payload=payload,title=title,filename=filename)\n", + " return HTML(html)\n", "\n", "pattern_remove_bracket = re.compile('\\[.+\\]')\n", "t0_pattern = re.compile('tend = (.+)\\n')\n", @@ -117,6 +133,26 @@ "csvy_file = '---\\n{0}\\n---\\n{1}'.format(yaml.dump(blondin_dict, default_flow_style=False), blondin_csv.to_csv(index=False))" ] }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'5e-05 km / s'" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "str(u.Quantity(5 * u.cm/u.s, u.km / u.s))" + ] + }, { "cell_type": "code", "execution_count": 6, @@ -2603,6 +2639,32 @@ "xlim(0, 1e15)\n" ] }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "Download Spectrum" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "spectrum = pd.DataFrame(data = sim.runner.spectrum_integrated.frequency.value, columns=['frequency'])\n", + "spectrum['luminosity'] = sim.runner.spectrum_integrated.luminosity_density_nu.value\n", + "\n", + "create_df_download_link(spectrum, title='Download Spectrum', filename='spectrum.csv', type='csv')" + ] + }, { "cell_type": "code", "execution_count": null, diff --git a/tardis/io/parsers/blondin_toymodel.py b/tardis/io/parsers/blondin_toymodel.py new file mode 100644 index 00000000000..fe8280d65ed --- /dev/null +++ b/tardis/io/parsers/blondin_toymodel.py @@ -0,0 +1,117 @@ +import re + +import yaml + +import numpy as np +import pandas as pd + +from astropy import units as u + +from tardis.util.base import parse_quantity + + + +PATTERN_REMOVE_BRACKET = re.compile('\[.+\]') +T0_PATTERN = re.compile('tend = (.+)\n') + +def read_blondin_toymodel(fname): + """ + Reading the Blondin toy-model format and returns a dictionary and a + dataframe + + Parameters + ---------- + fname: str + path or filename to blondin toymodel + + Returns + ------- + + blondin_dict: dict + dictionary containing most of the meta data of the model + + blondin_csv: pandas.DataFrame + DataFrame containing the csv part of the toymodel + + """ + with open(fname, 'r') as fh: + for line in fh: + if line.startswith("#idx"): + break + else: + raise ValueError( + 'File {0} does not conform to Toy Model format as it does ' + 'not contain #idx') + columns = [PATTERN_REMOVE_BRACKET.sub('', item) for item in + line[1:].split()] + + raw_blondin_csv = pd.read_csv(fname, delim_whitespace=True, comment='#', + header=None, names=columns) + raw_blondin_csv.set_index('idx', inplace=True) + + blondin_csv = raw_blondin_csv.loc[:, + ['vel', 'dens', 'temp', 'X_56Ni0', 'X_Ti', 'X_Ca', 'X_S', + 'X_Si', 'X_O', 'X_C']] + rename_col_dict = {'vel': 'velocity', 'dens': 'density', + 'temp': 't_electron'} + rename_col_dict.update({item: item[2:] for item in blondin_csv.columns[3:]}) + rename_col_dict['X_56Ni0'] = 'Ni56' + blondin_csv.rename(columns=rename_col_dict, inplace=True) + blondin_csv.iloc[:, 3:] = blondin_csv.iloc[:, 3:].divide( + blondin_csv.iloc[:, 3:].sum(axis=1), axis=0) + + # changing velocities to outer boundary + new_velocities = 0.5 * (blondin_csv.velocity.iloc[ + :-1].values + blondin_csv.velocity.iloc[1:].values) + new_velocities = np.hstack( + (new_velocities, [2 * new_velocities[-1] - new_velocities[-2]])) + blondin_csv['velocity'] = new_velocities + + with open(fname, 'r') as fh: + t0_string = T0_PATTERN.findall(fh.read())[0] + + t0 = parse_quantity(t0_string.replace('DAYS', 'day')) + blondin_dict = {} + blondin_dict['model_density_time_0'] = str(t0) + blondin_dict['description'] = 'Converted {0} to csvy format'.format(fname) + blondin_dict['tardis_model_config_version'] = 'v1.0' + blondin_dict_fields = [dict(name='velocity', unit='km/s', + desc='velocities of shell outer bounderies.')] + blondin_dict_fields.append( + dict(name='density', unit='g/cm^3', desc='mean density of shell.')) + blondin_dict_fields.append( + dict(name='t_electron', unit='K', desc='electron temperature.')) + + for abund in blondin_csv.columns[3:]: + blondin_dict_fields.append( + dict(name=abund, desc='Fraction {0} abundance'.format(abund))) + blondin_dict['datatype'] = {'fields': blondin_dict_fields} + + return blondin_dict, blondin_csv + + +def convert_blondin_toymodel(in_fname, out_fname, v_inner, v_outer): + """ + + Parameters + ---------- + in_fname + out_fname + v_inner + v_outer + + Returns + ------- + + """ + blondin_dict, blondin_csv = read_blondin_toymodel(in_fname) + blondin_dict['v_inner_boundary'] = str(u.Quantity(v_inner, u.km / u.s)) + blondin_dict['v_outer_boundary'] = str(u.Quantity(v_outer, u.km / u.s)) + + csvy_file = '---\n{0}\n---\n{1}'.format( + yaml.dump(blondin_dict, default_flow_style=False), + blondin_csv.to_csv(index=False)) + + with open(out_fname, 'w') as fh: + fh.write(csvy_file) +