Skip to content

Commit

Permalink
merge formatted files
Browse files Browse the repository at this point in the history
  • Loading branch information
lcvl41 committed Dec 2, 2024
2 parents 549d8ce + df21188 commit f7a4d41
Show file tree
Hide file tree
Showing 15 changed files with 951 additions and 653 deletions.
152 changes: 152 additions & 0 deletions .github/scripts/generate_pip_deps_from_conda.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""
(Copied from pandas:
https://github.com/pandas-dev/pandas/blob/main/scripts/generate_pip_deps_from_conda.py)
Convert the conda environment.yml to the pip requirements-dev.txt, or
check that they have the same packages (for the CI)
Usage:
Generate `requirements-dev.txt`
$ python scripts/generate_pip_deps_from_conda.py
Compare and fail (exit status != 0) if `requirements-dev.txt` has not been
generated with this script:
$ python scripts/generate_pip_deps_from_conda.py --compare
"""
import argparse
import pathlib
import re
import sys

if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
import yaml

EXCLUDE = {"python"}
REMAP_VERSION = {"tzdata": "2022.1"}
RENAME = {}


def conda_package_to_pip(package: str):
"""
Convert a conda package to its pip equivalent.
In most cases they are the same, those are the exceptions:
- Packages that should be excluded (in `EXCLUDE`)
- Packages that should be renamed (in `RENAME`)
- A package requiring a specific version, in conda is defined with a single
equal (e.g. ``pandas=1.0``) and in pip with two (e.g. ``pandas==1.0``)
"""
package = re.sub("(?<=[^<>])=", "==", package).strip()
print(package)

for compare in ("<=", ">=", "=="):
if compare in package:
pkg, version = package.split(compare)
if pkg in EXCLUDE:
return
if pkg in REMAP_VERSION:
return "".join((pkg, compare, REMAP_VERSION[pkg]))
if pkg in RENAME:
return "".join((RENAME[pkg], compare, version))

if package in EXCLUDE:
return

if package in RENAME:
return RENAME[package]

return package


def generate_pip_from_conda(
conda_path: pathlib.Path, pip_path: pathlib.Path, compare: bool = False
) -> bool:
"""
Generate the pip dependencies file from the conda file, or compare that
they are synchronized (``compare=True``).
Parameters
----------
conda_path : pathlib.Path
Path to the conda file with dependencies (e.g. `environment.yml`).
pip_path : pathlib.Path
Path to the pip file with dependencies (e.g. `requirements-dev.txt`).
compare : bool, default False
Whether to generate the pip file (``False``) or to compare if the
pip file has been generated with this script and the last version
of the conda file (``True``).
Returns
-------
bool
True if the comparison fails, False otherwise
"""
with conda_path.open() as file:
deps = yaml.safe_load(file)["dependencies"]

pip_deps = []
for dep in deps:
if isinstance(dep, str):
conda_dep = conda_package_to_pip(dep)
if conda_dep:
pip_deps.append(conda_dep)
elif isinstance(dep, dict) and len(dep) == 1 and "pip" in dep:
pip_deps.extend(dep["pip"])
else:
raise ValueError(f"Unexpected dependency {dep}")

header = (
f"# This file is auto-generated from {conda_path.name}, do not modify.\n"
"# See that file for comments about the need/usage of each dependency.\n\n"
)
pip_content = header + "\n".join(pip_deps) + "\n"

# Add setuptools to requirements-dev.txt

# with open(pathlib.Path(conda_path.parent, "pyproject.toml"), "rb") as fd:
# meta = tomllib.load(fd)
# for requirement in meta["build-system"]["requires"]:
# if "setuptools" in requirement:
# pip_content += requirement
# pip_content += "\n"

if compare:
with pip_path.open() as file:
return pip_content != file.read()

with pip_path.open("w") as file:
file.write(pip_content)
return False


if __name__ == "__main__":
argparser = argparse.ArgumentParser(
description="convert (or compare) conda file to pip"
)
argparser.add_argument(
"--compare",
action="store_true",
help="compare whether the two files are equivalent",
)
args = argparser.parse_args()

conda_fname = "dev-environment.yml"
pip_fname = "requirements-dev.txt"
repo_path = pathlib.Path(__file__).parent.parent.parent.absolute()
res = generate_pip_from_conda(
pathlib.Path(repo_path, conda_fname),
pathlib.Path(repo_path, pip_fname),
compare=args.compare,
)
if res:
msg = (
f"`{pip_fname}` has to be generated with `{__file__}` after "
f"`{conda_fname}` is modified.\n"
)
sys.stderr.write(msg)
sys.exit(res)
20 changes: 9 additions & 11 deletions app/Intro.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,22 @@
st.markdown(
"""
Snowlaps is an open-source python package to study the albedo reducing
effect of red snow algae, mineral dust and black carbon on melting snow
effect of red snow algae, mineral dust and black carbon on melting snow
surfaces. The package is built on a deep-learning emulator of the radiative
transfer model [biosnicar](https://biosnicar.vercel.app/) and can be used
in forward and inverse mode.
In forward mode, the albedo of a snow surface is predicted from the solar
zenith angle, snow grain size, liquid water content, and abundance of
algae, mineral dust and black carbon. In inverse mode, the surface
zenith angle, snow grain size, liquid water content, and abundance of
algae, mineral dust and black carbon. In inverse mode, the surface
properties are retrieved from prescribed spectral measurements. Snowlaps
also directly calculates the albedo-reduction caused by each type of
surface particles.
also directly calculates the albedo-reduction caused by each type of
surface particles.
More details and performance evaluation of the model were presented in a
[recent scientific publication](https://doi.org/10.5194/egusphere-2024-2583).
**👈 Select a mode from the sidebar** to start working with Snowlaps!
"""
)


73 changes: 46 additions & 27 deletions app/pages/1_Snowlaps_forward.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import streamlit as st
import pandas as pd
import plotly.express as px
import streamlit as st

from snowlaps.snowlaps import SnowlapsEmulator

st.markdown(
f"""
"""
### Try snowlaps as a fast two-stream radiative transfer model for snow! :zap:
:point_left: Feed the sidebar with your desired inputs and check the corresponding albedo
spectrum on the graph below, which you can also directly download locally.
:hourglass_flowing_sand: We are working on directly displaying the BBA
reduction associated with each light absorbing particle on the graph!
*Note that impurities are assumed to exist in the upper 2 cm of the snow
:point_left: Feed the sidebar with your desired inputs and check the corresponding albedo
spectrum on the graph below, which you can also directly download locally.
:hourglass_flowing_sand: We are working on directly displaying the BBA
reduction associated with each light absorbing particle on the graph!
*Note that impurities are assumed to exist in the upper 2 cm of the snow
only, and that the snow grain shape is set to spherical.*
"""
)
Expand All @@ -37,10 +38,17 @@
placeholder_button = st.sidebar.empty()


default_values = {"SZA": 42.0, "SOR": 500.0, "AC": 110000.0, "BCC": 800.0, "MDC": 78000.0, "LWC": 0.015}
default_values = {
"SZA": 42.0,
"SOR": 500.0,
"AC": 110000.0,
"BCC": 800.0,
"MDC": 78000.0,
"LWC": 0.015,
}


if placeholder_button.button('Reset'):
if placeholder_button.button("Reset"):
st.session_state.SZA = default_values["SZA"]
st.session_state.SOR = default_values["SOR"]
st.session_state.AC = default_values["AC"]
Expand All @@ -50,42 +58,51 @@


with st.sidebar:

placeholder_title_1.header("Solar geometry")


SZA = placeholder_num_1.number_input(
"Solar Zenith Angle (SZA; degrees)", 0.0, 90.0, value=default_values["SZA"], key="SZA"
"Solar Zenith Angle (SZA; degrees)",
0.0,
90.0,
value=default_values["SZA"],
key="SZA",
)

placeholder_title_2.header("Snow structure ")

optical_radius = placeholder_num_2.number_input(
"Snow optical radius (µm)", 0.0, 1000.0, value=default_values["SOR"], key="SOR"
)

liquid_water_content = placeholder_num_3.number_input(
"Liquid water content (%)", 0.0, 0.1, value=default_values["LWC"], key="LWC"
)

placeholder_title_3.header("Light Absorbing Particles (LAPs)")


algae_concentration = placeholder_num_4.number_input(
"Algae concentration (cells/mL)", 0.0, 1000000.0, value=default_values["AC"], key="AC"
"Algae concentration (cells/mL)",
0.0,
1000000.0,
value=default_values["AC"],
key="AC",
)
black_carbon_concentration = placeholder_num_5.number_input(
"Black carbon concentration (ppb)", 0.0, 10000.0, value=default_values["BCC"], key="BCC"
"Black carbon concentration (ppb)",
0.0,
10000.0,
value=default_values["BCC"],
key="BCC",
)
mineral_dust_concentration = placeholder_num_6.number_input(
"Mineral dust concentration (ppb)", 0.0, 780000.0, value=default_values["MDC"], key="MDC"
"Mineral dust concentration (ppb)",
0.0,
780000.0,
value=default_values["MDC"],
key="MDC",
)






def run_snowlaps(
SZA,
optical_radius,
Expand Down Expand Up @@ -129,6 +146,7 @@ def run_snowlaps(
),
}


def plot_albedo(albedo: pd.Series):
fig = px.line(
result["albedo"],
Expand All @@ -139,6 +157,7 @@ def plot_albedo(albedo: pd.Series):
fig.update_layout(showlegend=False)
return fig


result = run_snowlaps(
SZA,
optical_radius,
Expand Down
Loading

0 comments on commit f7a4d41

Please sign in to comment.