"""Unpenalized binomial logistic regression, probabilities, odds ratios and ROC."""
# ---------------- SETTINGS: edit these before running ----------------
DATA_FILE = "data/challengerLaunch.csv"  # For telecom, see the README example.
DELIMITER = None
Y_COLUMN = "isDistress"                  # A two-class response.
X_COLUMNS = ["temperature", "pressure"]  # Exclude distress_ct: it defines Y!
CATEGORICAL_COLUMNS = []
POSITIVE_CLASS = 1                       # yes/true/1 are equivalent; custom labels work.
PROBABILITY_CUTOFF = 0.5                 # Probability >= cutoff predicts class 1.
TEST_FRACTION = 0.0                     # Same as Shiny: no holdout by default.
RANDOM_SEED = 9                          # Reproducible optional random holdout.

from pathlib import Path
import numpy as np
import pandas as pd
from model_tools import (prepare, output_folder, design, fit_model, stepwise,
                         write_summary, classification_report)


def main():
    folder = output_folder(__file__)
    data, y, X, groups, train, can_predict, status = prepare(
        Path(__file__).resolve().parent / DATA_FILE, DELIMITER, Y_COLUMN,
        X_COLUMNS, CATEGORICAL_COLUMNS, test_fraction=TEST_FRACTION,
        seed=RANDOM_SEED, classification=True, positive_class=POSITIVE_CLASS)
    selected = list(groups)
    model = fit_model(y, X, groups, selected, train, logistic=True)
    write_summary(model, folder, groups)
    # Odds ratio: exp(beta), with a confidence interval on the odds-ratio scale.
    interval = model.conf_int()
    pd.DataFrame({"odds_ratio": np.exp(model.params),
                  "lower_95": np.exp(interval[0]), "upper_95": np.exp(interval[1])}).to_csv(
                      folder / "odds_ratios.csv", index_label="term")
    null = fit_model(y, X, groups, [], train, logistic=True)
    print("McFadden pseudo R-squared:", 1 - model.llf / null.llf)
    (folder / "pseudo_r_squared.txt").write_text(str(1 - model.llf / null.llf))
    probability = pd.Series(np.nan, index=data.index)
    probability.loc[can_predict] = model.predict(design(X, groups, selected).loc[can_predict])
    classification_report(data, y, probability, status, PROBABILITY_CUTOFF, folder)


if __name__ == "__main__":
    main()
