Skip to content

Commit

Permalink
Lots of delinting with pylint
Browse files Browse the repository at this point in the history
  • Loading branch information
eacharles committed Nov 21, 2023
1 parent 499c244 commit 83dd137
Show file tree
Hide file tree
Showing 43 changed files with 1,194 additions and 937 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ disable = [
"abstract-method",
"invalid-name",
"too-many-statements",
"too-many-arguments",
"missing-module-docstring",
"missing-class-docstring",
"missing-function-docstring",
Expand Down
28 changes: 14 additions & 14 deletions src/rail/cli/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,50 +11,50 @@ def cli() -> None:


@cli.command()
@options.outdir(default='docs')
@options.outdir(default="docs")
@options.clear_output()
@options.dry_run()
@options.inputs()
@options.skip()
def render_nb(outdir, clear_output, dry_run, inputs, skip, **kwargs):
def render_nb(outdir, clear_output, dry_run, inputs, skip, **_kwargs):
"""Render jupyter notebooks"""
return scripts.render_nb(outdir, clear_output, dry_run, inputs, skip)


@cli.command()
@options.outdir(default='..')
@options.outdir(default="..")
@options.git_mode()
@options.dry_run()
@options.package_file()
def clone_source(outdir, git_mode, dry_run, package_file, **kwargs):
def clone_source(outdir, git_mode, dry_run, package_file, **_kwargs):
"""Install packages from source"""
scripts.clone_source(outdir, git_mode, dry_run, package_file)
return 0


@cli.command()
@options.outdir(default='..')
@options.outdir(default="..")
@options.dry_run()
@options.package_file()
def update_source(outdir, dry_run, package_file, **kwargs):
def update_source(outdir, dry_run, package_file, **_kwargs):
"""Update packages from source"""
scripts.update_source(outdir, dry_run, package_file)
return 0


@cli.command()
@options.outdir(default='..')
@options.outdir(default="..")
@options.dry_run()
@options.from_source()
@options.package_file()
def install(outdir, dry_run, from_source, package_file, **kwargs):
def install(outdir, dry_run, from_source, package_file, **_kwargs):
"""Install rail packages one by one, to be fault tolerant"""
scripts.install(outdir, from_source, dry_run, package_file)
return 0


@cli.command()
@options.outdir(default='..')
@options.outdir(default="..")
@options.print_all()
@options.print_packages()
@options.print_namespaces()
Expand Down
38 changes: 19 additions & 19 deletions src/rail/cli/options.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import enum
from functools import partial, wraps
from typing import Any, Callable, Type, TypeVar, cast
from functools import partial
from typing import Any, Type, TypeVar

import click

Expand All @@ -20,12 +20,13 @@
"package_file",
"skip",
"inputs",
"verbose_download"
"verbose_download",
]


class GitMode(enum.Enum):
"""Choose git clone mode"""

ssh = 0
https = 1
cli = 2
Expand All @@ -37,9 +38,9 @@ class GitMode(enum.Enum):
class EnumChoice(click.Choice):
"""A version of click.Choice specialized for enum types"""

def __init__(self, enum: EnumType_co, case_sensitive: bool = True) -> None:
self._enum = enum
super().__init__(list(enum.__members__.keys()), case_sensitive=case_sensitive)
def __init__(self, the_enum: EnumType_co, case_sensitive: bool = True) -> None:
self._enum = the_enum
super().__init__(list(the_enum.__members__.keys()), case_sensitive=case_sensitive)

def convert(self, value: Any, param, ctx) -> EnumType_co:
converted_str = super().convert(value, param, ctx)
Expand All @@ -50,7 +51,9 @@ class PartialOption:
"""Wraps click.option with partial arguments for convenient reuse"""

def __init__(self, *param_decls: Any, **kwargs: Any) -> None:
self._partial = partial(click.option, *param_decls, cls=partial(click.Option), **kwargs)
self._partial = partial(
click.option, *param_decls, cls=partial(click.Option), **kwargs
)

def __call__(self, *args: Any, **kwargs: Any) -> Any:
return self._partial(*args, **kwargs)
Expand All @@ -60,7 +63,9 @@ class PartialArgument:
"""Wraps click.argument with partial arguments for convenient reuse"""

def __init__(self, *param_decls: Any, **kwargs: Any) -> None:
self._partial = partial(click.argument, *param_decls, cls=partial(click.Argument), **kwargs)
self._partial = partial(
click.argument, *param_decls, cls=partial(click.Argument), **kwargs
)

def __call__(self, *args: Any, **kwargs: Any) -> Any:
return self._partial(*args, **kwargs)
Expand Down Expand Up @@ -94,7 +99,7 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any:
git_mode = PartialOption(
"--git-mode",
type=EnumChoice(GitMode),
default='ssh',
default="ssh",
help="Git Clone mode",
)

Expand Down Expand Up @@ -148,20 +153,15 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any:
help="Skip files",
)

inputs = PartialArgument(
"inputs",
nargs=-1
)
inputs = PartialArgument("inputs", nargs=-1)

verbose_download = PartialOption(
"-v",
"--verbose",
help="Verbose output when downloading",
is_flag=True
"-v", "--verbose", help="Verbose output when downloading", is_flag=True
)

bpz_demo_data = PartialOption(
"--bpz-demo-data",
help="Download data that is explicitly only for use in the bpz demo and nowhere else (it is dummy data that will not make sense)",
is_flag=True
help="Download data that is explicitly only for use in the bpz demo and nowhere else"
"(it is dummy data that will not make sense)",
is_flag=True,
)
77 changes: 39 additions & 38 deletions src/rail/cli/scripts.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import sys
import os
import glob
import yaml

import rail.stages
Expand All @@ -9,8 +7,7 @@
from rail.core.utils import RAILDIR


def render_nb(outdir, clear_output, dry_run, inputs, skip, **kwargs):

def render_nb(outdir, clear_output, dry_run, inputs, skip, **_kwargs):
command = "jupyter nbconvert"
options = "--to html"

Expand All @@ -19,10 +16,10 @@ def render_nb(outdir, clear_output, dry_run, inputs, skip, **kwargs):
for nb_file in inputs:
if nb_file in skip:
continue
subdir = os.path.dirname(nb_file).split('/')[-1]
subdir = os.path.dirname(nb_file).split("/")[-1]
basename = os.path.splitext(os.path.basename(nb_file))[0]
outfile = os.path.join('..', '..', outdir, f"{subdir}/{basename}.html")
relpath = os.path.join(outdir, f'{subdir}')
outfile = os.path.join("..", "..", outdir, f"{subdir}/{basename}.html")
relpath = os.path.join(outdir, f"{subdir}")

try:
print(relpath)
Expand Down Expand Up @@ -50,18 +47,17 @@ def render_nb(outdir, clear_output, dry_run, inputs, skip, **kwargs):

if failed_notebooks:
raise ValueError(f"The following notebooks failed {str(failed_notebooks)}")


def clone_source(outdir, git_mode, dry_run, package_file):

with open(package_file) as pfile:
def clone_source(outdir, git_mode, dry_run, package_file):
with open(package_file, encoding='utf-8') as pfile:
package_dict = yaml.safe_load(pfile)

for key, val in package_dict.items():
for key, _val in package_dict.items():
if os.path.exists(f"{outdir}/{key}"):
print(f"Skipping existing {outdir}/{key}")
continue

if git_mode == GitMode.ssh:
com_line = f"git clone https://github.com/LSSTDESC/{key}.git {outdir}/{key}"
elif git_mode == GitMode.https:
Expand All @@ -74,92 +70,93 @@ def clone_source(outdir, git_mode, dry_run, package_file):
else:
os.system(com_line)


def update_source(outdir, dry_run, package_file):

with open(package_file) as pfile:
def update_source(outdir, dry_run, package_file):
with open(package_file, encoding='utf-8') as pfile:
package_dict = yaml.safe_load(pfile)

currentpath = os.path.abspath('.')
for key, val in package_dict.items():
currentpath = os.path.abspath(".")
for key, _val in package_dict.items():
abspath = os.path.abspath(f"{outdir}/{key}")

if os.path.exists(f"{outdir}/{key}") is not True:
print(f"Package {outdir}/{key} does not exist!")
continue
continue

com_line = f"cd {abspath} && git pull && cd {currentpath}"

if dry_run:
print(com_line)
else:
os.system(com_line)


def install(outdir, from_source, dry_run, package_file):

with open(package_file) as pfile:
def install(outdir, from_source, dry_run, package_file):
with open(package_file, encoding='utf-8') as pfile:
package_dict = yaml.safe_load(pfile)

for key, val in package_dict.items():

if not from_source:
com_line = f"pip install {val}"
else:
else:
if not os.path.exists(f"{outdir}/{key}"):
print(f"Skipping missing {outdir}/{key}")
continue
com_line = f"pip install -e {outdir}/{key}"

if dry_run:
print(com_line)
else:
os.system(com_line)


def info(**kwargs):

rail.stages.import_and_attach_all()

print_all = kwargs.get('print_all', False)
if kwargs.get('print_packages') or print_all:
print_all = kwargs.get("print_all", False)
if kwargs.get("print_packages") or print_all:
print("======= Printing RAIL packages ==============")
RailEnv.print_rail_packages()
print("\n\n")
if kwargs.get('print_namespaces') or print_all:
if kwargs.get("print_namespaces") or print_all:
print("======= Printing RAIL namespaces ==============")
RailEnv.print_rail_namespaces()
print("\n\n")
if kwargs.get('print_modules') or print_all:
if kwargs.get("print_modules") or print_all:
print("======= Printing RAIL modules ==============")
RailEnv.print_rail_modules()
print("\n\n")
if kwargs.get('print_tree') or print_all:
if kwargs.get("print_tree") or print_all:
print("======= Printing RAIL source tree ==============")
RailEnv.print_rail_namespace_tree()
print("\n\n")
if kwargs.get('print_stages') or print_all:
if kwargs.get("print_stages") or print_all:
print("======= Printing RAIL stages ==============")
RailEnv.print_rail_stage_dict()
print("\n\n")


def get_data(verbose, **kwargs): # pragma: no cover
if kwargs.get("bpz_demo_data"):
# The bpz demo data is quarantined into its own flag, as it contains some
# The bpz demo data is quarantined into its own flag, as it contains some
# non-physical features that would add systematics if run on any real data.
# This data should NOT be used for any science with real data!
bpz_local_abs_path = os.path.join(
RAILDIR, "rail/examples_data/estimation_data/data/nonphysical_dc2_templates.tar"
RAILDIR,
"rail/examples_data/estimation_data/data/nonphysical_dc2_templates.tar",
)
bpz_remote_path = (
"https://portal.nersc.gov/cfs/lsst/PZ/nonphysical_dc2_templates.tar"
)
bpz_remote_path = "https://portal.nersc.gov/cfs/lsst/PZ/nonphysical_dc2_templates.tar"
print(f"Check for bpz demo data: {bpz_local_abs_path}")
if not os.path.exists(bpz_local_abs_path):
os.system(f"curl -o {bpz_local_abs_path} {bpz_remote_path} --create-dirs")
print("Downloaded bpz demo data.")
else:
print("Already have bpz demo data.")
print("\n(Note: you can run get-data without the bpz-demo-data flag to download standard data.)")
print(
"\n(Note: you can run get-data without the bpz-demo-data flag to download standard data.)"
)

else:
data_files = [
Expand All @@ -171,6 +168,10 @@ def get_data(verbose, **kwargs): # pragma: no cover
for data_file in data_files:
local_abs_path = os.path.join(RAILDIR, data_file["local_path"])
if verbose:
print(f"Check file exists: {local_abs_path} ({os.path.exists(local_abs_path)})")
print(
f"Check file exists: {local_abs_path} ({os.path.exists(local_abs_path)})"
)
if not os.path.exists(local_abs_path):
os.system(f'curl -o {local_abs_path} {data_file["remote_path"]} --create-dirs')
os.system(
f'curl -o {local_abs_path} {data_file["remote_path"]} --create-dirs'
)
22 changes: 13 additions & 9 deletions src/rail/core/__init__.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
"""Core code for RAIL"""
import pkgutil
import os
import setuptools
import rail
import os

from .stage import RailPipeline, RailStage

# from .utilPhotometry import PhotormetryManipulator, HyperbolicSmoothing, HyperbolicMagnitudes
from .util_stages import ColumnMapper, RowSelector, TableConverter
from .introspection import RailEnv
from .point_estimation import PointEstimationMixin


def find_version():
"""Find the version"""
# setuptools_scm should install a
# file _version alongside this one.
from . import _version
from . import _version # pylint: disable=import-outside-toplevel

return _version.version


try:
__version__ = find_version()
except ImportError: # pragma: no cover
except ImportError: # pragma: no cover
__version__ = "unknown"

from .stage import RailPipeline, RailStage
#from .utilPhotometry import PhotormetryManipulator, HyperbolicSmoothing, HyperbolicMagnitudes
from .util_stages import ColumnMapper, RowSelector, TableConverter
from .introspection import RailEnv
from .point_estimation import PointEstimationMixin
Loading

0 comments on commit 83dd137

Please sign in to comment.