Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format code #29

Merged
merged 8 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for
everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity
and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion,
or sexual identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take
appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits,
issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for
moderation decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing
the community in public spaces. Examples of representing our community include using an official e-mail address, posting
via an official social media account, or acting as an appointed representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible
for enforcement at
[INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem
in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the
community.

**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation
and an explanation of why the behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of actions.

**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including
unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding
interactions in community spaces as well as external channels like social media. Violating these terms may lead to a
temporary or permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified
period of time. No public or private interaction with the people involved, including unsolicited interaction with those
enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate
behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at
[https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0].

Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].

For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available
at [https://www.contributor-covenant.org/translations][translations].

[homepage]: https://www.contributor-covenant.org

[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html

[Mozilla CoC]: https://github.com/mozilla/diversity

[FAQ]: https://www.contributor-covenant.org/faq

[translations]: https://www.contributor-covenant.org/translations
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
BSD 2-Clause License

Copyright (c) 2023, IHME Math Sciences
Copyright (c) 2025, IHME Math Sciences
All rights reserved.

Redistribution and use in source and binary forms, with or without
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[![build](https://github.com/ihmeuw-msca/modrover/workflows/build/badge.svg)](https://github.com/ihmeuw-msca/modrover/actions)

# ModRover: Model Space Explorer

## Installation

```shell
pip install git+https://github.com/ihmeuw-msca/modrover.git@main
```

## Documentation

https://ihmeuw-msca.github.io/modrover/
21 changes: 0 additions & 21 deletions README.rst

This file was deleted.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
name = "modrover"
version = "0.1.3"
description = "Model space explorer for inference and prediction"
readme = "README.rst"
readme = "README.md"
requires-python = ">=3.10"
license = { file = "LICENSE" }
authors = [
Expand Down
8 changes: 8 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
line-length = 80
src = ["src"]

[format]
docstring-code-format = true

[lint.pydocstyle]
convention = "numpy"
2 changes: 2 additions & 0 deletions src/modrover/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from .rover import Rover

__all__ = ["Rover"]
2 changes: 0 additions & 2 deletions src/modrover/api.py

This file was deleted.

2 changes: 1 addition & 1 deletion src/modrover/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ class NotFittedError(Exception):


class InvalidConfigurationError(Exception):
"""Raised if a provided configuration parameter violates a rule."""
"""Raised if a provided configuration parameter violates a rule."""
16 changes: 7 additions & 9 deletions src/modrover/globals.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
from typing import Optional

import numpy as np
from numpy.typing import ArrayLike
from regmod.models import (BinomialModel, GaussianModel, PoissonModel,
TobitModel)
from regmod.models import BinomialModel, GaussianModel, PoissonModel, TobitModel

model_type_dict = {
"gaussian": GaussianModel,
Expand All @@ -13,17 +10,18 @@
}


def get_r2(obs: ArrayLike, pred: ArrayLike,
obs_mean: Optional[float] = None) -> float:
ss_residual = np.sum((obs - pred)**2)
def get_r2(
obs: ArrayLike, pred: ArrayLike, obs_mean: float | None = None
) -> float:
ss_residual = np.sum((obs - pred) ** 2)
if obs_mean is None:
obs_mean = obs.mean()
ss_total = np.sum((obs - obs_mean)**2)
ss_total = np.sum((obs - obs_mean) ** 2)
return float(min(max(0.0, 1 - ss_residual / ss_total), 1.0))


def get_rmse(obs: ArrayLike, pred: ArrayLike) -> float:
metric = np.sqrt(np.mean((obs - pred)**2))
metric = np.sqrt(np.mean((obs - pred) ** 2))
metric = np.exp(-metric)
return float(metric)

Expand Down
32 changes: 20 additions & 12 deletions src/modrover/learner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from collections import defaultdict
from enum import Enum
from typing import Callable, Optional
from typing import Callable

import numpy as np
from numpy.typing import NDArray
Expand Down Expand Up @@ -50,7 +50,7 @@ def __init__(
main_param: str,
param_specs: dict[str, dict],
weights: str = "weights",
get_score: Optional[Callable] = None,
get_score: Callable | None = None,
) -> None:
self.model_class = model_class
self.obs = obs
Expand All @@ -60,7 +60,9 @@ def __init__(

# convert str to Variable
for param_spec in param_specs.values():
param_spec["variables"] = list(map(Variable, param_spec["variables"]))
param_spec["variables"] = list(
map(Variable, param_spec["variables"])
)
self.param_specs = param_specs

# initialize null model
Expand All @@ -74,7 +76,7 @@ def __init__(
self._cv_status = defaultdict(lambda: ModelStatus.NOT_FITTED)

@property
def coef(self) -> Optional[NDArray]:
def coef(self) -> NDArray | None:
"""Coefficients in the regmod model."""
return self.model.opt_coefs

Expand All @@ -85,7 +87,7 @@ def coef(self, coef: NDArray):
self.model.opt_coefs = coef

@property
def vcov(self) -> Optional[NDArray]:
def vcov(self) -> NDArray | None:
"""Variance-covarianace matrix for the coefficients in the regmod model."""
return self.model.opt_vcov

Expand All @@ -98,7 +100,7 @@ def vcov(self, vcov: NDArray):
def fit(
self,
data: DataFrame,
holdouts: Optional[list[str]] = None,
holdouts: list[str] | None = None,
**optimizer_options,
) -> None:
"""
Expand Down Expand Up @@ -160,7 +162,7 @@ def fit(
def predict(
self,
data: DataFrame,
model: Optional[RegmodModel] = None,
model: RegmodModel | None = None,
return_ui: bool = False,
alpha: float = 0.05,
) -> NDArray:
Expand Down Expand Up @@ -204,7 +206,9 @@ def predict(
raise ValueError("`alpha` has to be between 0 and 0.5")
vcov = model.opt_vcov[coef_index, coef_index]
lin_param_sd = np.sqrt((mat.dot(vcov) * mat).sum(axis=1))
lin_param_lower = norm.ppf(0.5 * alpha, loc=lin_param, scale=lin_param_sd)
lin_param_lower = norm.ppf(
0.5 * alpha, loc=lin_param, scale=lin_param_sd
)
lin_param_upper = norm.ppf(
1 - 0.5 * alpha, loc=lin_param, scale=lin_param_sd
)
Expand All @@ -219,7 +223,9 @@ def predict(
model.data.detach_df()
return pred

def evaluate(self, data: DataFrame, model: Optional[RegmodModel] = None) -> float:
def evaluate(
self, data: DataFrame, model: RegmodModel | None = None
) -> float:
"""Given a model and a test set, generate a performance score.

Score is based on the provided evaluation metric, comparing the
Expand All @@ -237,7 +243,9 @@ def evaluate(self, data: DataFrame, model: Optional[RegmodModel] = None) -> floa
model = model or self.model
if self.get_score is None:
model.attach_df(data)
score = np.exp(-model.objective(model.opt_coefs) / model.data.weights.sum())
score = np.exp(
-model.objective(model.opt_coefs) / model.data.weights.sum()
)
model = _detach_df(model)
else:
score = self.get_score(
Expand Down Expand Up @@ -265,7 +273,7 @@ def _get_model(self) -> RegmodModel:
def _fit(
self,
data: DataFrame,
model: Optional[RegmodModel] = None,
model: RegmodModel | None = None,
**optimizer_options,
) -> ModelStatus:
model = model or self.model
Expand All @@ -277,7 +285,7 @@ def _fit(
try:
model.fit(**optimizer_options)
status = ModelStatus.SUCCESS
except:
except Exception:
status = ModelStatus.SOLVER_FAILED
model = _detach_df(model)
return status
Expand Down
Loading
Loading