Skip to content

Commit

Permalink
Update codata.py to replace negative values with np.nan
Browse files Browse the repository at this point in the history
  • Loading branch information
sarahshi committed May 15, 2024
1 parent 267de50 commit 58329ee
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 20 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
__pycache__/
*.py[cod]
*$py.class
.DS_Store

# C extensions
*.so
Expand Down
37 changes: 17 additions & 20 deletions pyrolite/comp/codata.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
__sympy_protected_variables__ = {"S": "Ss"}


def close(X, sumf=np.sum):
def close(X: np.ndarray, sumf=np.sum):
"""
Closure operator for compositional data.
Parameters
-----------
X : :class:`numpy.ndarray`
Expand Down Expand Up @@ -74,27 +76,22 @@ def renormalise(df: pd.DataFrame, components: list = [], scale=100.0):

dfc = df.copy(deep=True)
if components:
# Ensure specified components are in DataFrame columns
if not all(col in dfc.columns for col in components):
raise ValueError("Not all specified components exist in the DataFrame.")
# Check for non-positive entries in specified components and warn if found
if (dfc[components] <= 0).any().any():
warnings.warn("Non-positive entries found in specified components. "
"Renormalisation assumes all positive entries.", UserWarning)
# Renormalise specified components
sum_rows = dfc[components].sum(axis=1)
sum_rows.replace(0, np.nan, inplace=True) # Handle division by zero by replacing zeros with NaN
dfc.loc[:, components] = dfc.loc[:, components].divide(sum_rows, axis=0) * scale
else:
# Check for non-positive entries in all columns and warn if found
if (dfc <= 0).any().any():
warnings.warn("Non-positive entries found in specified components. "
"Renormalisation assumes all positive entries.", UserWarning)

# Renormalise all columns if no components are specified
sum_rows = dfc.sum(axis=1)
sum_rows.replace(0, np.nan, inplace=True) # Handle division by zero by replacing zeros with NaN
dfc = dfc.divide(sum_rows, axis=0) * scale
dfc = dfc[components]

# Replace negative values with NaN
dfc[dfc < 0] = np.nan

if (dfc <= 0).any().any():
warnings.warn("Non-positive entries found in specified components. "
"Negative values have been replaced with NaN. "
"Renormalisation assumes all positive entries.", UserWarning)

# Renormalise all columns if no components are specified
sum_rows = dfc.sum(axis=1)
sum_rows.replace(0, np.nan, inplace=True) # Handle division by zero by replacing zeros with NaN
dfc = dfc.divide(sum_rows, axis=0) * scale

return dfc

Expand Down

0 comments on commit 58329ee

Please sign in to comment.