Skip to content

Commit

Permalink
Address pytest warnings (#2745)
Browse files Browse the repository at this point in the history
* Fix pandas inplace warnings

* Use ruff again to fix invalid-escape-sequence warnings

* Close regression data after yielding it

* Close files in test_complete_plasma

* Add a backlash for the docstring

* Remove extra backslash

* Use raw strings

* Use raw strings
  • Loading branch information
atharva-2001 committed Jul 29, 2024
1 parent 17ee287 commit 56a9dbc
Show file tree
Hide file tree
Showing 17 changed files with 52 additions and 54 deletions.
2 changes: 1 addition & 1 deletion .ci-helpers/update_credits.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def generate_zenodo():
f"https://zenodo.org/api/records/{CONCEPT_DOI}", headers=headers
)
response.encoding = "utf-8"
citation = re.findall("@software{(.*)\,", response.text)
citation = re.findall(r"@software{(.*)\,", response.text)
specific_doi = citation[0].lstrip(f"kerzendorf_wolfgang_{year}_")
doi_org_url = f"https://doi.org/10.5281/zenodo.{specific_doi}"
doi_badge = f"https://img.shields.io/badge/DOI-10.5281/zenodo.{specific_doi}-blue"
Expand Down
4 changes: 2 additions & 2 deletions docs/physics/pyplot/plot_mu_in_out_packet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
mu_out = y / 500.0 - 1
v = 1.1e4 * u.km / u.s
doppler_fac = (1 - mu_in * v / const.c) / (1 - mu_out * v / const.c)
xlabel("$\mu_{\\rm in}$")
ylabel("$\mu_{\\rm out}$")
xlabel("$\\mu_{\\rm in}$")
ylabel("$\\mu_{\\rm out}$")
imshow(np.rot90(doppler_fac), extent=[-1, 1, -1, 1], cmap="bwr")
colorbar()
show()
8 changes: 4 additions & 4 deletions tardis/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ def update_last_interaction_filter(self):
]
]
self.last_line_in_table["count"] = last_line_in_count
self.last_line_in_table.sort_values(
by="count", ascending=False, inplace=True
self.last_line_in_table = self.last_line_in_table.sort_values(
by="count", ascending=False
)
self.last_line_out_table = self.last_line_out.reset_index()[
[
Expand All @@ -219,8 +219,8 @@ def update_last_interaction_filter(self):
]
]
self.last_line_out_table["count"] = last_line_out_count
self.last_line_out_table.sort_values(
by="count", ascending=False, inplace=True
self.last_line_out_table = self.last_line_out_table.sort_values(
by="count", ascending=False
)

def plot_wave_in_out(self, fig, do_clf=True, plot_resonance=True):
Expand Down
12 changes: 6 additions & 6 deletions tardis/analysis/opacities.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,11 +285,11 @@ def _calc_expansion_opacity(self):
The expansion opacity formalism, in the particular version of Blinnikov
et al. 1998, is used. In the supernova ejecta case (assuming perfect
homologous expansion), the formula for the expansion opacity in the
interval $[\nu, \nu+\Delta \nu]$ simplifies to
\[
\chi_{\mathrm{exp}} = \frac{\nu}{\Delta \nu} \frac{1}{c t} \sum_j
\left(1 - \exp(-\tau_{\mathrm{S},j})\right)
\]
interval $[\nu, \nu+\\Delta \nu]$ simplifies to
\\[
\\chi_{\\mathrm{exp}} = \frac{\nu}{\\Delta \nu} \frac{1}{c t} \\sum_j
\\left(1 - \\exp(-\tau_{\\mathrm{S},j})\right)
\\]
The summation involves all lines in the frequency bin.
Returns
Expand Down Expand Up @@ -326,7 +326,7 @@ def _calc_expansion_opacity(self):
return kappa_exp.to("1/cm")

def _calc_thomson_scattering_opacity(self):
"""Calculate the Thomson scattering opacity for each grid cell
r"""Calculate the Thomson scattering opacity for each grid cell
\[
\chi_{\mathrm{Thomson}} = n_{\mathrm{e}} \sigma_{\mathrm{T}}
Expand Down
2 changes: 1 addition & 1 deletion tardis/io/atom_data/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ def prepare_atom_data(
)
]

self.lines.sort_values(by="wavelength", inplace=True)
self.lines = self.lines.sort_values(by="wavelength")

self.lines_index = pd.Series(
np.arange(len(self.lines), dtype=int),
Expand Down
4 changes: 2 additions & 2 deletions tardis/io/model/readers/blondin_toymodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def read_blondin_toymodel(fname):
header=None,
names=columns,
)
raw_blondin_csv.set_index("idx", inplace=True)
raw_blondin_csv = raw_blondin_csv.set_index("idx")

blondin_csv = raw_blondin_csv.loc[
:,
Expand All @@ -76,7 +76,7 @@ def read_blondin_toymodel(fname):
}
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 = blondin_csv.rename(columns=rename_col_dict)
blondin_csv.iloc[:, 3:] = blondin_csv.iloc[:, 3:].divide(
blondin_csv.iloc[:, 3:].sum(axis=1), axis=0
)
Expand Down
2 changes: 1 addition & 1 deletion tardis/io/tests/test_decay.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def test_simple_decay(simple_abundance_model):
@pytest.fixture
def raw_abundance_simple():
abundances = pd.DataFrame([[0.2, 0.2], [0.1, 0.1]], index=[28, 30])
abundances.index.rename("atomic_number", inplace=True)
abundances.index = abundances.index.rename("atomic_number")
return abundances


Expand Down
2 changes: 1 addition & 1 deletion tardis/model/matter/decay.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def decay(self, t):
)
decayed_inventories = [item.decay(t_second) for item in inventories]
df = IsotopicMassFraction.from_inventories(decayed_inventories)
df.sort_index(inplace=True)
df = df.sort_index()
assert (
df.ge(0.0).all().all()
), "Negative abundances detected. Please make sure your input abundances are correct."
Expand Down
2 changes: 1 addition & 1 deletion tardis/plasma/properties/atomic.py
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ def _filter_atomic_property(self, zeta_data, selected_atoms):
updated_index = pd.DataFrame(updated_index)
updated_dataframe["atomic_number"] = np.array(updated_index[0])
updated_dataframe["ion_number"] = np.array(updated_index[1])
updated_dataframe.fillna(1.0, inplace=True)
updated_dataframe = updated_dataframe.fillna(1.0)
return updated_dataframe

def _set_index(self, zeta_data):
Expand Down
5 changes: 3 additions & 2 deletions tardis/plasma/tests/test_complete_plasmas.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,9 @@ def plasma(
):
config["atom_data"] = str(chianti_he_db_fpath)
sim = Simulation.from_config(config)
self.regression_data.sync_hdf_store(sim.plasma, update_fname=False)
return sim.plasma
data = self.regression_data.sync_hdf_store(sim.plasma, update_fname=False)
yield sim.plasma
data.close()

@pytest.mark.parametrize("attr", combined_properties)
def test_plasma_properties(self, plasma, attr):
Expand Down
2 changes: 1 addition & 1 deletion tardis/spectrum/formal_integral_cuda.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def cuda_formal_integral(
pp : array(float64, 1d, C)
Impact parameter arrays
exp_tau : array(float64, 1d, C)
$\exp{-tau}$ array to speed up computation
$\\exp{-tau}$ array to speed up computation
I_nu array(floatt64, 2d, C)
Radiative intensity per unit frequency per impact parameter
z : array(float64, 2d, C)
Expand Down
6 changes: 3 additions & 3 deletions tardis/transport/montecarlo/packet_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,8 @@ def create_packet_nus(self, no_of_packets, l_samples=1000):

def create_packet_mus(self, no_of_packets):
"""
Create zero-limb-darkening packet :math:`\mu` distributed
according to :math:`\\mu=\\sqrt{z}, z \isin [0, 1]`
Create zero-limb-darkening packet :math:`\\mu` distributed
according to :math:`\\mu=\\sqrt{z}, z \\isin [0, 1]`
Parameters
----------
Expand Down Expand Up @@ -340,7 +340,7 @@ def create_packets(self, no_of_packets):

def create_packet_mus(self, no_of_packets):
"""
Create zero-limb-darkening packet :math:`\mu^\prime` distributed
Create zero-limb-darkening packet :math:`\\mu^\\prime` distributed
according to :math:`\\mu^\\prime=2 \\frac{\\mu^\\prime + \\beta}{2 \\beta + 1}`.
The complicated distribution is due to the fact that the inner boundary
on which the packets are initialized is not comoving with the material.
Expand Down
2 changes: 1 addition & 1 deletion tardis/util/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ def convert_abundances_format(fname, delimiter=r"\s+"):
"""
df = pd.read_csv(fname, delimiter=delimiter, comment="#", header=None)
# Drop shell index column
df.drop(df.columns[0], axis=1, inplace=True)
df = df.drop(df.columns[0], axis=1)
# Assign header row
df.columns = [Z_DICT[i] for i in range(1, df.shape[1] + 1)]
return df
Expand Down
2 changes: 1 addition & 1 deletion tardis/visualization/plot_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def axis_label_in_latex(label_text, unit, only_text=True):
# If present, place s^{-1} just after erg
if "erg" in unit_in_latex and "s^{-1}" in unit_in_latex:
constituent_units = (
re.compile("\\\mathrm\{(.*)\}")
re.compile(r"\\mathrm\{(.*)\}")
.findall(unit_in_latex)[0]
.split("\\,")
)
Expand Down
22 changes: 10 additions & 12 deletions tardis/visualization/tools/sdec_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,8 +746,8 @@ def _calculate_plotting_data(
),
)
# Then drop all of the individual columns for species included in 'other'
self.total_luminosities_df.drop(
sorted_list.keys()[~mask], inplace=True, axis=1
self.total_luminosities_df = self.total_luminosities_df.drop(
sorted_list.keys()[~mask], axis=1
)
# Repeat this for the emission and absorption dfs
# This will require creating a temporary list that includes 'noint' and 'escatter'
Expand All @@ -770,9 +770,8 @@ def _calculate_plotting_data(
# Need to add a new value to the mask array for the 'other' column just added
mask = np.insert(mask, 0, True)
# Then drop all of the individual columns for species included in 'other'
self.emission_luminosities_df.drop(
self.emission_luminosities_df = self.emission_luminosities_df.drop(
self.emission_luminosities_df.keys()[~mask],
inplace=True,
axis=1,
)

Expand All @@ -792,9 +791,8 @@ def _calculate_plotting_data(
# Need to add a new value to the mask array for the 'other' column just added
mask = np.insert(mask, 0, True)
# Then drop all of the individual columns for species included in 'other'
self.absorption_luminosities_df.drop(
self.absorption_luminosities_df = self.absorption_luminosities_df.drop(
self.absorption_luminosities_df.keys()[~mask],
inplace=True,
axis=1,
)

Expand All @@ -813,8 +811,8 @@ def _calculate_plotting_data(
].sum(axis=1),
)
# Then drop all of the individual columns for elements included in 'other'
self.total_luminosities_df.drop(
sorted_list.keys()[nelements:], inplace=True, axis=1
self.total_luminosities_df = self.total_luminosities_df.drop(
sorted_list.keys()[nelements:], axis=1
)
# If nelements is included then create a new column which is the sum
# of all other elements, i.e. those that aren't in the top contributing nelements
Expand All @@ -826,8 +824,8 @@ def _calculate_plotting_data(
].sum(axis=1),
)
# Then drop all of the individual columns for elements included in 'other'
self.emission_luminosities_df.drop(
sorted_list.keys()[nelements:], inplace=True, axis=1
self.emission_luminosities_df = self.emission_luminosities_df.drop(
sorted_list.keys()[nelements:], axis=1
)
# If nelements is included then create a new column which is the sum
# of all other elements, i.e. those that aren't in the top contributing nelements
Expand All @@ -839,8 +837,8 @@ def _calculate_plotting_data(
].sum(axis=1),
)
# Then drop all of the individual columns for elements included in 'other'
self.absorption_luminosities_df.drop(
sorted_list.keys()[nelements:], inplace=True, axis=1
self.absorption_luminosities_df = self.absorption_luminosities_df.drop(
sorted_list.keys()[nelements:], axis=1
)
# Get the list of species in the model
# Index from 1: to avoid the 'other' column
Expand Down
23 changes: 11 additions & 12 deletions tardis/visualization/widgets/custom_abundance.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,9 @@ def from_csvy(cls, fpath):

# Combine elements and isotopes to one DataFrame
abundance["mass_number"] = ""
abundance.set_index("mass_number", append=True, inplace=True)
abundance = abundance.set_index("mass_number", append=True)
abundance = pd.concat([abundance, isotope_abundance])
abundance.sort_index(inplace=True)
abundance = abundance.sort_index()

return cls(
density_t_0=time_0,
Expand Down Expand Up @@ -222,9 +222,9 @@ def from_yml(cls, fpath, atom_data=None):

# Combine elements and isotopes to one DataFrame
abundance["mass_number"] = ""
abundance.set_index("mass_number", append=True, inplace=True)
abundance = abundance.set_index("mass_number", append=True)
abundance = pd.concat([abundance, isotopic_mass_fraction])
abundance.sort_index(inplace=True)
abundance = abundance.sort_index()

return cls(
density_t_0=density_t_0,
Expand Down Expand Up @@ -259,7 +259,7 @@ def from_hdf(cls, fpath):
velocity = np.append(v_inner, v_outer[len(v_outer) - 1]) * u.cm / u.s

abundance["mass_number"] = ""
abundance.set_index("mass_number", append=True, inplace=True)
abundance = abundance.set_index("mass_number", append=True)

return cls(
density_t_0=density_t_0,
Expand Down Expand Up @@ -288,9 +288,9 @@ def from_simulation(cls, sim):

# integrate element and isotope to one DataFrame
abundance["mass_number"] = ""
abundance.set_index("mass_number", append=True, inplace=True)
abundance = abundance.set_index("mass_number", append=True)
abundance = pd.concat([abundance, isotope_abundance])
abundance.sort_index(inplace=True)
abundance = abundance.sort_index()

velocity = sim.simulation_state.velocity
density_t_0 = sim.simulation_state.time_explosion
Expand Down Expand Up @@ -787,7 +787,7 @@ def on_btn_add_shell(self, obj):
if end_index < len(v_vals) and np.isclose(v_vals[end_index], v_end):
# New shell will overwrite the original shell that ends at v_end.
v_vals = np.delete(v_vals, end_index)
self.data.abundance.drop(max(0, end_index - 1), 1, inplace=True)
self.data.abundance = self.data.abundance.drop(max(0, end_index - 1), 1)

# Insert new velocities calculate new densities according
# to new velocities through interpolation.
Expand All @@ -807,10 +807,9 @@ def on_btn_add_shell(self, obj):
# Change abundances after adding new shell.
if start_index != end_index:
self.data.abundance.insert(start_index, "", new_shell_abundances)
self.data.abundance.drop(
self.data.abundance = self.data.abundance.drop(
self.data.abundance.iloc[:, start_index : end_index - 1],
1,
inplace=True,
)
else:
if start_index == 0:
Expand Down Expand Up @@ -1046,7 +1045,7 @@ def on_btn_add_element(self, obj):
z = nuc.Z
self.data.abundance.loc[(z, mass_no), :] = 0

self.data.abundance.sort_index(inplace=True)
self.data.abundance = self.data.abundance.sort_index()

# Add new BoundedFloatText control and Checkbox control.
item = ipw.BoundedFloatText(min=0, max=1, step=0.01)
Expand Down Expand Up @@ -1466,7 +1465,7 @@ def write_csv_portion(self, path):
first_row = [0] * self.no_of_elements
data.loc[-1] = first_row
data.index += 1 # shifting index
data.sort_index(inplace=True)
data = data.sort_index()

formatted_v = pd.Series(self.data.velocity.value).apply(
lambda x: "%.3e" % x
Expand Down
6 changes: 3 additions & 3 deletions tardis/visualization/widgets/shell_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def element_count(self, shell_num):
"""
element_count_data = self.abundance[shell_num - 1].copy()
element_count_data.index.name = "Z"
element_count_data.fillna(0, inplace=True)
element_count_data = element_count_data.fillna(0)
return pd.DataFrame(
{
"Element": element_count_data.index.map(
Expand Down Expand Up @@ -128,7 +128,7 @@ def ion_count(self, atomic_num, shell_num):
element_num_density = self.number_density.loc[atomic_num, shell_num - 1]
ion_count_data = ion_num_density / element_num_density # Normalization
ion_count_data.index.name = "Ion"
ion_count_data.fillna(0, inplace=True)
ion_count_data = ion_count_data.fillna(0)
return pd.DataFrame(
{
"Species": ion_count_data.index.map(
Expand Down Expand Up @@ -170,7 +170,7 @@ def level_count(self, ion, atomic_num, shell_num):
level_count_data = level_num_density / ion_num_density # Normalization
level_count_data.index.name = "Level"
level_count_data.name = f"Frac. Ab. (Ion={ion})"
level_count_data.fillna(0, inplace=True)
level_count_data = level_count_data.fillna(0)
return level_count_data.map("{:.6e}".format).to_frame()


Expand Down

0 comments on commit 56a9dbc

Please sign in to comment.