abapr 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
abapr/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ from .snippets import SNIPPETS
2
+
3
+
4
+ def _make(name, code):
5
+ def f():
6
+ try:
7
+ ip = get_ipython() # noqa: F821
8
+ ip.set_next_input(code) # writes code into a new cell below
9
+ except NameError:
10
+ print(code)
11
+ f.__name__ = name
12
+ f.__doc__ = "\n" + code
13
+ return f
14
+
15
+
16
+ for _n, _c in SNIPPETS.items():
17
+ globals()[_n] = _make(_n, _c)
18
+
19
+ __all__ = list(SNIPPETS)
abapr/snippets.py ADDED
@@ -0,0 +1,20 @@
1
+ SNIPPETS = {
2
+ "z": "import math\nimport numpy as np\nfrom scipy.stats import norm\n\ndef z_test(sample_mean, pop_mean, std_dev, n, alpha, tail):\n z_calculated = (sample_mean - pop_mean) / (std_dev / math.sqrt(n))\n \n if tail == \"right\":\n z_critical = norm.ppf(1 - alpha)\n decision = \"Reject H0\" if z_calculated > z_critical else \"Accept H0\"\n elif tail == \"left\":\n z_critical = norm.ppf(alpha)\n decision = \"Reject H0\" if z_calculated < z_critical else \"Accept H0\"\n else:\n z_critical = norm.ppf(1 - alpha/2)\n decision = \"Reject H0\" if abs(z_calculated) > z_critical else \"Accept H0\"\n \n print(f\"{z_calculated:.2f}\")\n print(f\"{z_critical:.2f}\")\n print(f\"{decision}\")",
3
+ "t": "import math\nimport numpy as np\nfrom scipy.stats import t\n\ndef t_test(sample_mean, pop_mean, sample_std, n, alpha, tail):\n df = n - 1\n se = sample_std / math.sqrt(n) \n t_calc = (sample_mean - pop_mean) / se \n \n if tail == \"twosided\":\n t_crit_right = t.ppf(1 - alpha/2, df)\n t_crit_left = -t_crit_right\n decision = \"Reject H0\" if (t_calc < t_crit_left or t_calc > t_crit_right) else \"Accept H0\"\n critical = f\"Left = {t_crit_left:.2f}, Right = {t_crit_right:.2f}\"\n elif tail == \"left\":\n t_crit = t.ppf(alpha, df)\n decision = \"Reject H0\" if t_calc < t_crit else \"Accept H0\"\n critical = f\"Left = {t_crit:.2f}\"\n elif tail == \"right\":\n t_crit = t.ppf(1 - alpha, df)\n decision = \"Reject H0\" if t_calc > t_crit else \"Accept H0\"\n critical = f\"Right = {t_crit:.2f}\"\n else:\n pass\n \n print(f\"n = {n}, df = {df}, alpha = {alpha}, tail = {tail}\")\n print(f\"Sample mean = {sample_mean}, Population mean = {pop_mean}, Sample standard deviation = {sample_std}\")\n print(f\"Calculated value = {t_calc:.2f}\")\n print(f\"Tabular value = {critical}\")\n print(f\"Decision: {decision}\")",
4
+ "chi": "import numpy as np\nfrom scipy.stats import chi2\n\ndef chi_square(data, alpha):\n data = np.array(data)\n \n row_totals = data.sum(axis=1)\n col_totals = data.sum(axis=0)\n grand_total = data.sum()\n \n expected = np.outer(row_totals, col_totals) / grand_total\n \n chi_calculated = ((data - expected) ** 2 / expected).sum()\n\n df = (data.shape[0] - 1) * (data.shape[1] - 1)\n \n chi_critical = chi2.ppf(1 - alpha, df)\n \n decision = \"Reject H0\" if chi_calculated > chi_critical else \"Accept H0\"\n print(data)\n print(\"\\nExpected Frequencies\")\n print(np.round(expected, 2))\n print(f\"{chi_calculated:.2f}\")\n print(f\"{chi_critical:.2f}\")\n print(f\"{decision}\")",
5
+ "anova": "import numpy as np\nfrom scipy.stats import f\n\ndef one_way_anova(*groups, alpha):\n k = len(groups) \n N = sum(len(g) for g in groups) \n grand_mean = np.mean([x for g in groups for x in g])\n\n ssb = sum(len(g) * (np.mean(g) - grand_mean) ** 2 for g in groups)\n\n ssw = sum(sum((x - np.mean(g)) ** 2 for x in g) for g in groups)\n\n dfb = k - 1\n dfw = N - k\n\n msb = ssb / dfb\n msw = ssw / dfw\n\n f_calc = msb / msw\n\n f_crit = f.ppf(1 - alpha, dfb, dfw)\n\n decision = \"Reject H0\" if f_calc > f_crit else \"Accept H0\"\n print(f\"{f_calc:.2f}\")\n print(f\"{f_crit:.2f}\")\n print(f\"{decision}\")",
6
+ "b1": "from scipy.stats import binom\n\n# Parameters\nn = 12 # Number of coin tosses\nk = 7 # Number of heads (successes)\np = 0.5 # Probability of getting heads in each toss\n\n# Probability of exactly 7 heads\nprob_7_heads = binom.pmf(k, n, p)\nprint(f\"The probability of getting exactly 7 heads is: {prob_7_heads:.4f}\")",
7
+ "b2": "from scipy.stats import binom\n\n# Parameters\nn = 5 # Number of tries\np = 3/4 # Probability of success\n\n# Probability of attaining the target at least 3 times (k = 3, 4, or 5)\nprob_at_least_3 = binom.pmf(3, n, p) + binom.pmf(4, n, p) + binom.pmf(5, n, p)\n\n# Print the result\nprint(f\"The probability of achieving the target at least 3 times is: {prob_at_least_3:.4f}\")",
8
+ "p1": "from scipy.stats import poisson\n\n# Parameters\nlambda_ = 3 # Average number of students (based on today's attendance)\nk = 4 # We are interested in the probability of exactly 4 students attending\n\n# Calculate the Poisson probability for k = 4\nprob_4_students = poisson.pmf(k, lambda_)\n\n# Print the result\nprint(f\"The probability of exactly 4 students attending the class tomorrow is: {prob_4_students:.4f}\")",
9
+ "p2": "from scipy.stats import poisson\n\n# Parameters\nlambda_ = 2 # Average number of emails sent per hour\nk = 0 # We want the probability of sending no emails\n\n# Calculate the Poisson probability for k = 0\nprob_no_email = poisson.pmf(k, lambda_)\n\n# Print the result\nprint(f\"The probability that no email is sent in a given hour is: {prob_no_email:.4f}\")\n",
10
+ "p3": "# Given parameters\nn = 20 # Number of trials\np = 0.6 # Probability of success\n\n# Calculate the mean (lambda) for the Poisson distribution\nlambda_ = n * p\n\n# Print the result\nprint(f\"The mean of the Poisson distribution is: {lambda_:.2f}\")",
11
+ "n1": "from scipy.stats import norm\n\n# Parameters\nmu = 50 # Mean of the distribution\nsigma = 15 # Standard deviation of the distribution\nlower_bound = 50\nupper_bound = 70\n\n# Calculate the CDF values for the bounds\ncdf_lower = norm.cdf(lower_bound, mu, sigma)\ncdf_upper = norm.cdf(upper_bound, mu, sigma)\n\n# Probability that the time period is between 50 and 70 hours\nprobability = cdf_upper - cdf_lower\n\n# Print the result\nprint(f\"The probability that the time period is between 50 and 70 hours is: {probability:.4f}\")",
12
+ "n2": "from scipy.stats import norm\n\n# Parameters\nmu = 90 # Mean of the distribution\nsigma = 10 # Standard deviation of the distribution\nthreshold = 100\n\n# Calculate the CDF value for the threshold\ncdf_value = norm.cdf(threshold, mu, sigma)\n\n# Probability that the speed is more than 100 km/hr\nprobability_more_than_100 = 1 - cdf_value\n\n# Print the result\nprint(f\"The probability that a car is moving at more than 100 km/hr is: {probability_more_than_100:.4f}\")",
13
+ "imports": "import math\nimport re\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom scipy.stats import norm, t, chi2, f, binom, poisson\n\nfrom sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler, OneHotEncoder, LabelEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer, KNNImputer\n\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC, SVR\nfrom sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\nfrom xgboost import XGBClassifier, XGBRegressor\nfrom sklearn.cluster import KMeans\n\nfrom sklearn.metrics import (accuracy_score, precision_score, recall_score, f1_score,\n roc_auc_score, confusion_matrix, classification_report,\n mean_squared_error, mean_absolute_error, r2_score,\n silhouette_score)\n",
14
+ "IQR": "import matplotlib.pyplot as plt\nimport seaborn as sns\n\ncols = [c for c in df.select_dtypes(include=\"number\").columns\n if df[c].nunique() > 2 and c != \"target\"] # skips binary columns; change \"target\" to your target column\n\n# 1. detect\nfor col in cols:\n Q1, Q3 = df[col].quantile(0.25), df[col].quantile(0.75)\n IQR = Q3 - Q1\n lower, upper = Q1 - 1.5 * IQR, Q3 + 1.5 * IQR\n n_out = ((df[col] < lower) | (df[col] > upper)).sum()\n print(f\"{col}: lower={lower:.2f}, upper={upper:.2f}, outliers={n_out}\")\n\n# 2. boxplot before\nfor col in cols:\n sns.boxplot(x=df[col]); plt.title(f\"Before: {col}\"); plt.show()\n\n# 3. remove\ndf_clean = df.copy()\nfor col in cols:\n Q1, Q3 = df_clean[col].quantile(0.25), df_clean[col].quantile(0.75)\n IQR = Q3 - Q1\n df_clean = df_clean[(df_clean[col] >= Q1 - 1.5 * IQR) & (df_clean[col] <= Q3 + 1.5 * IQR)]\nprint(\"shape before:\", df.shape, \"after:\", df_clean.shape)\n\n# 4. boxplot after\nfor col in cols:\n sns.boxplot(x=df_clean[col]); plt.title(f\"After: {col}\"); plt.show()\n",
15
+ "graphs": "# set up: import matplotlib.pyplot as plt, seaborn as sns\nsns.histplot(df[\"col\"], kde=True) # histogram\nsns.kdeplot(df[\"col\"]) # density\nsns.boxplot(x=df[\"col\"]) # boxplot (single)\nsns.boxplot(x=\"cat\", y=\"num\", data=df) # boxplot by category\nsns.violinplot(x=\"cat\", y=\"num\", data=df) # violin\nsns.countplot(x=\"cat\", data=df) # count of categories\nsns.countplot(x=\"cat\", hue=\"target\", data=df) # count split by target\nsns.barplot(x=\"cat\", y=\"num\", data=df) # bar (mean)\nsns.scatterplot(x=\"a\", y=\"b\", hue=\"target\", data=df) # scatter\nsns.lineplot(x=\"a\", y=\"b\", data=df) # line\nsns.regplot(x=\"a\", y=\"b\", data=df) # scatter + regression line\nsns.heatmap(df.select_dtypes(\"number\").corr(), annot=True, cmap=\"coolwarm\") # correlation heatmap\nsns.heatmap(confusion_matrix(y_test, y_pred), annot=True, fmt=\"d\", cmap=\"Blues\") # confusion matrix\nsns.pairplot(df, hue=\"target\") # pairplot\ndf.hist(figsize=(12, 8)) # all histograms\ndf[\"cat\"].value_counts().plot(kind=\"pie\", autopct=\"%1.1f%%\") # pie\nplt.show()\n",
16
+ "pipeline": "# ---------- CLASSIFICATION PIPELINE ----------\n# needs: df (dataframe), TARGET (name of target column)\nimport numpy as np, pandas as pd, matplotlib.pyplot as plt, seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler, OneHotEncoder, LabelEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import (accuracy_score, precision_score, recall_score, f1_score,\n roc_auc_score, confusion_matrix, classification_report)\n\nTARGET = \"target\" # <-- change this\n\n# 1. split X / y (label-encode y if it is text)\nX = df.drop(columns=[TARGET])\ny = df[TARGET]\nif y.dtype == \"object\":\n y = LabelEncoder().fit_transform(y)\n\n# 2. train / test split\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.2, random_state=42, stratify=y)\n\n# 3. preprocessing: missing values + scaling (numeric), missing values + one-hot (categorical)\nnum_cols = X_train.select_dtypes(include=\"number\").columns.tolist()\ncat_cols = X_train.select_dtypes(exclude=\"number\").columns.tolist()\n\nnum_tf = Pipeline([\n (\"imputer\", SimpleImputer(strategy=\"median\")),\n (\"scaler\", StandardScaler()), # or MinMaxScaler() / RobustScaler()\n])\ncat_tf = Pipeline([\n (\"imputer\", SimpleImputer(strategy=\"most_frequent\")),\n (\"onehot\", OneHotEncoder(handle_unknown=\"ignore\", sparse_output=False)),\n])\npreprocessor = ColumnTransformer([\n (\"num\", num_tf, num_cols),\n (\"cat\", cat_tf, cat_cols),\n])\n\n# 4. all models\nmodels = {\n \"Logistic Regression\": LogisticRegression(max_iter=1000),\n \"Naive Bayes\": GaussianNB(),\n \"SVM\": SVC(probability=True, random_state=42),\n \"KNN\": KNeighborsClassifier(n_neighbors=5),\n \"Decision Tree\": DecisionTreeClassifier(random_state=42),\n \"Random Forest\": RandomForestClassifier(n_estimators=200, random_state=42),\n \"XGBoost\": XGBClassifier(random_state=42, eval_metric=\"logloss\"),\n}\n\n# 5. evaluate\ndef evaluate(y_true, y_pred, y_prob=None):\n avg = \"binary\" if len(np.unique(y_true)) == 2 else \"weighted\"\n out = {\n \"Accuracy\": accuracy_score(y_true, y_pred),\n \"Precision\": precision_score(y_true, y_pred, average=avg),\n \"Recall\": recall_score(y_true, y_pred, average=avg),\n \"F1\": f1_score(y_true, y_pred, average=avg),\n }\n if y_prob is not None and avg == \"binary\":\n out[\"ROC-AUC\"] = roc_auc_score(y_true, y_prob)\n return out\n\nfitted, rows = {}, []\nfor name, model in models.items():\n pipe = Pipeline([(\"preprocessor\", preprocessor), (\"model\", model)])\n pipe.fit(X_train, y_train)\n y_pred = pipe.predict(X_test)\n y_prob = pipe.predict_proba(X_test)[:, 1] if hasattr(pipe, \"predict_proba\") else None\n rows.append({\"Model\": name, **evaluate(y_test, y_pred, y_prob)})\n fitted[name] = pipe\n\n# 6. results\nresults = pd.DataFrame(rows).set_index(\"Model\").round(3).sort_values(\"F1\", ascending=False)\nprint(results)\n\nbest = results.index[0]\nprint(\"\\nBest model:\", best)\ny_pred = fitted[best].predict(X_test)\nprint(classification_report(y_test, y_pred))\nsns.heatmap(confusion_matrix(y_test, y_pred), annot=True, fmt=\"d\", cmap=\"Blues\")\nplt.title(f\"Confusion Matrix - {best}\"); plt.show()\n",
17
+ "pipeline_reg": "# ---------- REGRESSION PIPELINE ----------\n# needs: df (dataframe), TARGET (name of target column)\nimport numpy as np, pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom xgboost import XGBRegressor\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\n\nTARGET = \"target\" # <-- change this\n\nX = df.drop(columns=[TARGET])\ny = df[TARGET]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\nnum_cols = X_train.select_dtypes(include=\"number\").columns.tolist()\ncat_cols = X_train.select_dtypes(exclude=\"number\").columns.tolist()\n\npreprocessor = ColumnTransformer([\n (\"num\", Pipeline([(\"imputer\", SimpleImputer(strategy=\"median\")),\n (\"scaler\", StandardScaler())]), num_cols),\n (\"cat\", Pipeline([(\"imputer\", SimpleImputer(strategy=\"most_frequent\")),\n (\"onehot\", OneHotEncoder(handle_unknown=\"ignore\", sparse_output=False))]), cat_cols),\n])\n\nmodels = {\n \"Linear Regression\": LinearRegression(),\n \"KNN\": KNeighborsRegressor(n_neighbors=5),\n \"Decision Tree\": DecisionTreeRegressor(random_state=42),\n \"Random Forest\": RandomForestRegressor(n_estimators=200, random_state=42),\n \"XGBoost\": XGBRegressor(random_state=42),\n}\n\nrows = []\nfor name, model in models.items():\n pipe = Pipeline([(\"preprocessor\", preprocessor), (\"model\", model)])\n pipe.fit(X_train, y_train)\n y_pred = pipe.predict(X_test)\n rows.append({\"Model\": name,\n \"RMSE\": np.sqrt(mean_squared_error(y_test, y_pred)),\n \"MAE\": mean_absolute_error(y_test, y_pred),\n \"R2\": r2_score(y_test, y_pred)})\n\nresults = pd.DataFrame(rows).set_index(\"Model\").round(3).sort_values(\"R2\", ascending=False)\nprint(results)\n",
18
+ "knn": "import numpy as np\n\ndef e_d(x, y):\n return np.sqrt(np.sum((x - y) ** 2))\n\ndef max_num(z):\n v, c = np.unique(z, return_counts=True)\n return v[np.argmax(c)]\n\ndef knn_predict(X_train, y_train, x_test, k):\n distances = [e_d(x_test, x) for x in X_train]\n k_idx = np.argsort(distances)[:k]\n k_labels = [y_train[i] for i in k_idx]\n return max_num(k_labels)\n\n# usage:\n# X = df[[\"Height\", \"Weight\"]].values\n# y = df[\"Class\"].values\n# x_new = np.array([170, 57])\n# pred = knn_predict(X, y, x_new, k=5)\n# print(pred)\n",
19
+ "kmeans": "import matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import silhouette_score\n\ncols = [\"col1\", \"col2\", \"col3\"] # <-- features to cluster on\nXk = StandardScaler().fit_transform(df[cols])\n\n# elbow + silhouette\nwcss, sil = [], []\nfor k in range(2, 11):\n km = KMeans(n_clusters=k, random_state=42, n_init=10).fit(Xk)\n wcss.append(km.inertia_)\n sil.append(silhouette_score(Xk, km.labels_))\n\nfig, ax = plt.subplots(1, 2, figsize=(12, 4))\nax[0].plot(range(2, 11), wcss, marker=\"o\"); ax[0].set_title(\"Elbow (WCSS)\")\nax[1].plot(range(2, 11), sil, marker=\"o\"); ax[1].set_title(\"Silhouette\")\nplt.show()\n\n# fit with chosen k\nk = int(input(\"Enter number of clusters: \"))\nkm = KMeans(n_clusters=k, random_state=42, n_init=10)\ndf[\"Cluster\"] = km.fit_predict(Xk)\n\nprint(df[\"Cluster\"].value_counts())\nprint(df.groupby(\"Cluster\")[cols].mean().round(1))\n"
20
+ }
@@ -0,0 +1,6 @@
1
+ Metadata-Version: 2.1
2
+ Name: abapr
3
+ Version: 0.2.0
4
+ Summary: Code snippets via Shift+Tab
5
+ Requires-Python: >=3.8
6
+
@@ -0,0 +1,6 @@
1
+ abapr/__init__.py,sha256=YLMn6kN0oJJyxeadvETvF6_YBWynf5Zi7_OLZpy_ltA,407
2
+ abapr/snippets.py,sha256=DRz6PRHDMfAZnXaT2opWaOcelmc8rIFn0Jz_tQxhZoc,17926
3
+ abapr-0.2.0.dist-info/METADATA,sha256=ZCsi1ewEmpNDxegq1fsvc3FXv9_bRbnGRJdYl5m203g,110
4
+ abapr-0.2.0.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
5
+ abapr-0.2.0.dist-info/top_level.txt,sha256=WN5sBLqIu8SKpFQHx8AfK0WGytQ5ism6FQQc0FdEDoQ,6
6
+ abapr-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ abapr