pyMoove 0.1.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.
pyMoove/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ from pyMoove.io import load_processed_dataset
2
+ from pyMoove.plotting import plot_replacement_example
3
+ from pyMoove.features import build_feature_table
4
+ from pyMoove.calculations import calculate_bin_position_statistics
5
+
6
+ __all__ = [
7
+ "load_processed_dataset",
8
+ "plot_replacement_example",
9
+ "build_feature_table",
10
+ "calculate_bin_position_statistics"
11
+ ]
@@ -0,0 +1,262 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ from scipy.stats import chi2
4
+ from sklearn.covariance import MinCovDet
5
+
6
+ def calculate_bin_position_statistics(
7
+ data: dict[str, pd.DataFrame],
8
+ bins: list[int] | int | range,
9
+ outlier_confidence: float = 0.9999,
10
+ ) -> pd.DataFrame:
11
+ """Calculate the spatial centroid and standard deviation for each bin during feeding.
12
+
13
+ For each specified bin, finds all feeding visits, retrieves the cow's
14
+ position fixes during each visit, and computes the spatial centroid
15
+ (mean x, mean y) and standard deviation (std x, std y).
16
+
17
+ Parameters
18
+ ----------
19
+ data:
20
+ Processed dataset containing 'feeding' and 'positions' DataFrames.
21
+ bins:
22
+ A bin number, list of bin numbers, or range of bin numbers.
23
+ tz:
24
+ Timezone of the feeder timestamps (default: 'Europe/Stockholm').
25
+
26
+ Returns
27
+ -------
28
+ pd.DataFrame
29
+ DataFrame with columns:
30
+ - 'bin': Bin number
31
+ - 'centroid_x': Mean X coordinate in meters
32
+ - 'centroid_y': Mean Y coordinate in meters
33
+ - 'std_x': Standard deviation in X (meters)
34
+ - 'std_y': Standard deviation in Y (meters)
35
+ - 'num_fixes': Total number of position fixes during visits to this bin
36
+ - 'num_visits': Total feeding visits recorded at this bin
37
+ - 'num_cows': Number of unique cows that visited this bin
38
+ """
39
+ if isinstance(bins, (int, str)):
40
+ bin_list = [int(bins)]
41
+ else:
42
+ bin_list = [int(b) for b in bins]
43
+
44
+ feeding_df = data["feeding"]
45
+ positions_df = data["positions"]
46
+
47
+ # Filter feeding events for the requested bins
48
+ target_events = feeding_df.loc[feeding_df["bin"].isin(bin_list)].copy()
49
+ if target_events.empty:
50
+ return pd.DataFrame(
51
+ columns=[
52
+ "bin",
53
+ "centroid_x",
54
+ "centroid_y",
55
+ "std_x",
56
+ "std_y",
57
+ "num_fixes",
58
+ "num_visits",
59
+ "num_cows",
60
+ "num_inliers",
61
+ "num_outliers",
62
+ ]
63
+ )
64
+
65
+ # Pre-filter positions by the cows that visited these bins for high query speed
66
+ cows_at_bins = set(target_events["cow"].astype(str).unique())
67
+ pos_subset = positions_df.loc[
68
+ positions_df["IDs"].astype(str).isin(cows_at_bins)
69
+ ].copy()
70
+ date_str = str(positions_df["datetime"].min().date())
71
+
72
+ # Group positions by cow ID for fast lookups
73
+ pos_by_cow = dict(tuple(pos_subset.groupby(pos_subset["IDs"].astype(str))))
74
+
75
+ results = []
76
+ for bin_id in bin_list:
77
+ b_events = target_events.loc[target_events["bin"] == bin_id]
78
+ if b_events.empty:
79
+ results.append({
80
+ "bin": bin_id,
81
+ "centroid_x": None,
82
+ "centroid_y": None,
83
+ "std_x": None,
84
+ "std_y": None,
85
+ "num_fixes": 0,
86
+ "num_visits": 0,
87
+ "num_cows": 0,
88
+ "num_inliers": 0,
89
+ "num_outliers": 0,
90
+ })
91
+ continue
92
+
93
+ b_fixes = []
94
+ for _, event in b_events.iterrows():
95
+ cow_id = str(event["cow"])
96
+ if cow_id not in pos_by_cow:
97
+ continue
98
+ cow_pos = pos_by_cow[cow_id]
99
+
100
+ start_str = str(event["start_time"])
101
+ start_dt = pd.Timestamp(f"{date_str} {start_str}")
102
+ start_dt_utc = start_dt.tz_convert("UTC")
103
+
104
+ if "duration" in event and pd.notna(event["duration"]):
105
+ end_dt_utc = start_dt_utc + pd.Timedelta(seconds=float(event["duration"]))
106
+ else:
107
+ end_str = str(event["end_time"])
108
+ end_dt = pd.Timestamp(f"{date_str} {end_str}")
109
+ end_dt_utc = end_dt.tz_convert("UTC")
110
+
111
+ pts = cow_pos.loc[cow_pos["datetime"].between(start_dt_utc, end_dt_utc)]
112
+ if not pts.empty:
113
+ b_fixes.append(pts[["x", "y"]])
114
+
115
+ if b_fixes:
116
+ all_b = pd.concat(b_fixes, ignore_index=True)
117
+ inliers, outliers, _, _ = filter_bin_position_outliers(
118
+ all_b, confidence=outlier_confidence
119
+ )
120
+ results.append({
121
+ "bin": bin_id,
122
+ "centroid_x": float(inliers["x"].mean()) if not inliers.empty else None,
123
+ "centroid_y": float(inliers["y"].mean()) if not inliers.empty else None,
124
+ "std_x": float(inliers["x"].std()) if len(inliers) > 1 else None,
125
+ "std_y": float(inliers["y"].std()) if len(inliers) > 1 else None,
126
+ "num_fixes": len(all_b),
127
+ "num_visits": len(b_events),
128
+ "num_cows": b_events["cow"].nunique(),
129
+ "num_inliers": len(inliers),
130
+ "num_outliers": len(outliers),
131
+ })
132
+ else:
133
+ results.append({
134
+ "bin": bin_id,
135
+ "centroid_x": None,
136
+ "centroid_y": None,
137
+ "std_x": None,
138
+ "std_y": None,
139
+ "num_fixes": 0,
140
+ "num_visits": len(b_events),
141
+ "num_cows": b_events["cow"].nunique(),
142
+ "num_inliers": 0,
143
+ "num_outliers": 0,
144
+ })
145
+
146
+ return pd.DataFrame(results)
147
+
148
+ def get_bin_feeding_positions(
149
+ data: dict[str, pd.DataFrame],
150
+ bin_id: int,
151
+ tz: str = "Europe/Stockholm",
152
+ outlier_confidence: float = 0.9999,
153
+ ) -> pd.DataFrame:
154
+ """Extract all positional records across all feeding events at a specific bin.
155
+
156
+ Parameters
157
+ ----------
158
+ data:
159
+ Processed dataset containing 'feeding' and 'positions' DataFrames.
160
+ bin_id:
161
+ Bin/gate number (e.g. 21, 24).
162
+ tz:
163
+ Timezone of the feeder timestamps (default: 'Europe/Stockholm').
164
+
165
+ Returns
166
+ -------
167
+ pd.DataFrame
168
+ Position fixes across all visits to this bin, with extra columns
169
+ 'cow_id', 'bin', and 'visit_idx'.
170
+ """
171
+ feeding_df = data["feeding"]
172
+ positions_df = data["positions"]
173
+
174
+ bin_events = feeding_df.loc[feeding_df["bin"] == bin_id].copy()
175
+ if bin_events.empty:
176
+ print(f"Warning: No feeding events found for bin {bin_id}")
177
+ return pd.DataFrame()
178
+
179
+ cows_at_bin = set(bin_events["cow"].astype(str).unique())
180
+ # Pre-filter positions by the set of cows who visited this bin for efficiency
181
+ pos_subset = positions_df.loc[positions_df["IDs"].astype(str).isin(cows_at_bin)].copy()
182
+ date_str = str(positions_df["datetime"].min().date())
183
+
184
+ collected = []
185
+ for visit_idx, event in bin_events.iterrows():
186
+ cow_id = str(event["cow"])
187
+ start_str = str(event["start_time"])
188
+ start_dt = pd.Timestamp(f"{date_str} {start_str}")
189
+ if start_dt.tzinfo is None:
190
+ print('Time zone assumed to be tz!!!!!______!!!!!!!!')
191
+ start_dt = start_dt.tz_localize(tz)
192
+ start_dt_utc = start_dt.tz_convert("UTC")
193
+
194
+ if "duration" in event and pd.notna(event["duration"]):
195
+ end_dt_utc = start_dt_utc + pd.Timedelta(seconds=float(event["duration"]))
196
+ else:
197
+ end_str = str(event["end_time"])
198
+ end_dt = pd.Timestamp(f"{date_str} {end_str}")
199
+ if end_dt.tzinfo is None:
200
+ print('Time zone assumed to be tz!!!!!______!!!!!!!!')
201
+ end_dt = end_dt.tz_localize(tz)
202
+ end_dt_utc = end_dt.tz_convert("UTC")
203
+
204
+ fixes = pos_subset.loc[
205
+ pos_subset["IDs"].astype(str).eq(cow_id)
206
+ & pos_subset["datetime"].between(start_dt_utc, end_dt_utc)
207
+ ].copy()
208
+
209
+ if not fixes.empty:
210
+ fixes["cow_id"] = cow_id
211
+ fixes["bin"] = bin_id
212
+ fixes["visit_idx"] = visit_idx
213
+ collected.append(fixes)
214
+
215
+ if not collected:
216
+ print(f"Warning: No position fixes found during feeding events for bin {bin_id}")
217
+ return pd.DataFrame()
218
+
219
+ return pd.concat(collected, ignore_index=True)
220
+
221
+ def filter_bin_position_outliers(
222
+ positions: pd.DataFrame,
223
+ confidence: float = 0.9999,
224
+ ) -> tuple[pd.DataFrame, pd.DataFrame, np.ndarray | None, np.ndarray | None]:
225
+ """Filter 2D positional outliers using robust MCD covariance and Mahalanobis distance.
226
+
227
+ Returns (inliers, outliers, robust_center, robust_covariance). If there are
228
+ too few valid points or the covariance is degenerate, all valid points are
229
+ retained rather than risking removal of good observations.
230
+ """
231
+ if not 0 < confidence < 1:
232
+ raise ValueError("confidence must be between 0 and 1")
233
+
234
+ valid = positions.dropna(subset=["x", "y"]).copy()
235
+ coords = valid[["x", "y"]].to_numpy(dtype=float)
236
+ finite = np.isfinite(coords).all(axis=1)
237
+ valid = valid.loc[finite].copy()
238
+ coords = coords[finite]
239
+
240
+ if len(coords) < 5 or np.unique(coords, axis=0).shape[0] < 3:
241
+ valid["mahalanobis_sq"] = np.nan
242
+ valid["is_inlier"] = True
243
+ return valid, valid.iloc[0:0].copy(), None, None
244
+
245
+ try:
246
+ estimator = MinCovDet(random_state=42).fit(coords)
247
+ distances_sq = estimator.mahalanobis(coords)
248
+ threshold = float(chi2.ppf(confidence, df=2))
249
+ is_inlier = distances_sq <= threshold
250
+
251
+ valid["mahalanobis_sq"] = distances_sq
252
+ valid["is_inlier"] = is_inlier
253
+ return (
254
+ valid.loc[is_inlier].copy(),
255
+ valid.loc[~is_inlier].copy(),
256
+ estimator.location_.copy(),
257
+ estimator.covariance_.copy(),
258
+ )
259
+ except (ValueError, np.linalg.LinAlgError):
260
+ valid["mahalanobis_sq"] = np.nan
261
+ valid["is_inlier"] = True
262
+ return valid, valid.iloc[0:0].copy(), None, None
pyMoove/cleaning.py ADDED
@@ -0,0 +1,50 @@
1
+ import pandas as pd
2
+ import pyMoove.validation as mooveValidate
3
+
4
+
5
+ def filter_replacement_events(replacements: pd.DataFrame, stats: pd.DataFrame)->pd.DataFrame:
6
+ """Replacement events are assoicated to an actor cow and a reactor cow. For some events positional data may only be available for
7
+ one of the cows. This function removes these from the dataset.
8
+
9
+ Inputs:
10
+ replacements: pd.DataFrame
11
+ Replacement events and their information
12
+ stats: pd.DataFrame
13
+ Statistics derived from replacement events, positions and feeding bin information using
14
+ statistics.compute_replacement_event_statistics()
15
+ Outputs:
16
+ replacements_cleaned: pd.DataFrame
17
+ The same replacements df with invalid events filtered out.
18
+ """
19
+
20
+ #NOTE: This function requires the statistics derived earlier
21
+ #NOTE: Maybe one should only cosnider the replacements and the positions,
22
+ #TODO: Maybe it is better to keep events in which all positions have matching timestamps for both cows,
23
+ #TODO: I.e. it is not enough to onyl consider events where atleast one of the position timestamps are synchronized.
24
+ #NOTE: Related function: summarize_event_coverage()
25
+
26
+ mooveValidate.check_replacement_dataframe_structure(replacements)
27
+ mooveValidate.check_replacement_statistics_dataframe_structure(stats)
28
+ mooveValidate.check_replacement_ids(replacements)
29
+ mooveValidate.check_replacement_ids(stats)
30
+ if set(replacements["repl_id"]) != set(stats["repl_id"]):
31
+ raise ValueError(
32
+ "Replacement events and statistics have different repl_id values."
33
+ )
34
+
35
+ events_before = len(replacements)
36
+ print(f"Total events before cleaning: {events_before}")
37
+
38
+ valid_ids_mask = (stats["n_matches"] > 0)
39
+ valid_ids = stats[valid_ids_mask]["repl_id"]
40
+
41
+ replacements_cleaned_mask = replacements["repl_id"].isin(valid_ids)
42
+ replacements_cleaned = replacements[replacements_cleaned_mask].copy()
43
+
44
+ events_after = len(replacements_cleaned)
45
+ n_removed = events_before - events_after
46
+
47
+ print(f"Events retained: {events_after}")
48
+ print(f"Events removed: {n_removed}")
49
+
50
+ return replacements_cleaned
@@ -0,0 +1,17 @@
1
+ """Model evaluation helpers."""
2
+
3
+ from .metrics import evaluate_binary_classifier
4
+ from .plots import (
5
+ plot_confusion_matrix,
6
+ plot_precision_recall_curve,
7
+ plot_roc_curve,
8
+ plot_recall_sensitivity_curve,
9
+ )
10
+
11
+ __all__ = [
12
+ "evaluate_binary_classifier",
13
+ "plot_confusion_matrix",
14
+ "plot_precision_recall_curve",
15
+ "plot_roc_curve",
16
+ "plot_recall_sensitivity_curve",
17
+ ]
@@ -0,0 +1,102 @@
1
+ """Metrics for evaluating binary classifiers."""
2
+
3
+ import numpy as np
4
+ from numpy.typing import ArrayLike
5
+ from sklearn.metrics import (
6
+ average_precision_score,
7
+ balanced_accuracy_score,
8
+ confusion_matrix,
9
+ f1_score,
10
+ precision_score,
11
+ recall_score,
12
+ roc_auc_score,
13
+ )
14
+ from sklearn.utils.multiclass import type_of_target
15
+
16
+
17
+ def evaluate_binary_classifier(
18
+ y_true: ArrayLike,
19
+ y_probability: ArrayLike,
20
+ *,
21
+ threshold: float = 0.5,
22
+ positive_label: object = 1,
23
+ ) -> dict[str, int | float]:
24
+ """Calculate threshold-based and ranking metrics for binary predictions.
25
+
26
+ ``y_probability`` must contain the predicted probability for the positive
27
+ class, not the classifier's predicted labels or a two-column probability
28
+ matrix.
29
+
30
+ Parameters
31
+ ----------
32
+ y_true:
33
+ Ground-truth binary labels.
34
+ y_probability:
35
+ Predicted probabilities for the positive class, in the range [0, 1].
36
+ threshold:
37
+ Probability threshold used to classify a sample as positive.
38
+ positive_label:
39
+ Value representing the positive class in ``y_true``.
40
+
41
+ Returns
42
+ -------
43
+ dict[str, int | float]
44
+ Sample and confusion-matrix counts, threshold-based metrics
45
+ (precision, recall, specificity, F1, and balanced accuracy), ROC-AUC,
46
+ and average precision.
47
+
48
+ Raises
49
+ ------
50
+ ValueError
51
+ If the labels or probabilities are empty, not one-dimensional, have
52
+ different lengths, are not binary, or contain invalid probabilities.
53
+ """
54
+ true_labels = np.asarray(y_true)
55
+ probabilities = np.asarray(y_probability, dtype=float)
56
+
57
+ if true_labels.ndim != 1 or probabilities.ndim != 1:
58
+ raise ValueError("y_true and y_probability must be one-dimensional")
59
+ if len(true_labels) == 0:
60
+ raise ValueError("y_true and y_probability must not be empty")
61
+ if len(true_labels) != len(probabilities):
62
+ raise ValueError("y_true and y_probability must have the same length")
63
+ if type_of_target(true_labels) != "binary":
64
+ raise ValueError("y_true must contain exactly two non-missing classes")
65
+ if positive_label not in np.unique(true_labels):
66
+ raise ValueError("positive_label must be present in y_true")
67
+ if not np.isfinite(probabilities).all() or (
68
+ (probabilities < 0) | (probabilities > 1)
69
+ ).any():
70
+ raise ValueError("y_probability values must be finite and in [0, 1]")
71
+ if not np.isfinite(threshold) or not 0 <= threshold <= 1:
72
+ raise ValueError("threshold must be finite and in [0, 1]")
73
+
74
+ binary_labels = (true_labels == positive_label).astype(np.uint8)
75
+ predictions = (probabilities >= threshold).astype(np.uint8)
76
+ tn, fp, fn, tp = confusion_matrix(
77
+ binary_labels,
78
+ predictions,
79
+ labels=[0, 1],
80
+ ).ravel()
81
+
82
+ return {
83
+ "n_samples": int(len(true_labels)),
84
+ "n_positive": int(np.count_nonzero(binary_labels)),
85
+ "n_negative": int(len(binary_labels) - np.count_nonzero(binary_labels)),
86
+ "threshold": float(threshold),
87
+ "tn": int(tn),
88
+ "fp": int(fp),
89
+ "fn": int(fn),
90
+ "tp": int(tp),
91
+ "precision": float(precision_score(binary_labels, predictions, zero_division=0)),
92
+ "recall": float(recall_score(binary_labels, predictions, zero_division=0)),
93
+ "specificity": float(tn / (tn + fp)),
94
+ "f1": float(f1_score(binary_labels, predictions, zero_division=0)),
95
+ "balanced_accuracy": float(
96
+ balanced_accuracy_score(binary_labels, predictions)
97
+ ),
98
+ "roc_auc": float(roc_auc_score(binary_labels, probabilities)),
99
+ "average_precision": float(
100
+ average_precision_score(binary_labels, probabilities)
101
+ ),
102
+ }
@@ -0,0 +1,101 @@
1
+ """Plots for evaluating binary classifiers."""
2
+
3
+ import matplotlib.pyplot as plt
4
+ from matplotlib.axes import Axes
5
+ from numpy.typing import ArrayLike
6
+ from sklearn.metrics import (
7
+ ConfusionMatrixDisplay,
8
+ PrecisionRecallDisplay,
9
+ RocCurveDisplay,
10
+ precision_recall_curve,
11
+ )
12
+
13
+
14
+ def _get_axes(ax: Axes | None) -> Axes:
15
+ if ax is None:
16
+ _, ax = plt.subplots()
17
+ return ax
18
+
19
+
20
+ def plot_confusion_matrix(
21
+ y_true: ArrayLike,
22
+ y_pred: ArrayLike,
23
+ *,
24
+ ax: Axes | None = None,
25
+ labels: ArrayLike | None = None,
26
+ display_labels: ArrayLike | None = None,
27
+ ) -> Axes:
28
+ """Plot a confusion matrix and return its Matplotlib axes.
29
+
30
+ ``y_pred`` should contain predicted class labels, for example probabilities
31
+ converted to labels using the chosen decision threshold.
32
+ """
33
+ ax = _get_axes(ax)
34
+ ConfusionMatrixDisplay.from_predictions(
35
+ y_true,
36
+ y_pred,
37
+ labels=labels,
38
+ display_labels=display_labels,
39
+ cmap="Blues",
40
+ values_format="d",
41
+ colorbar=False,
42
+ ax=ax,
43
+ )
44
+ return ax
45
+
46
+
47
+ def plot_precision_recall_curve(
48
+ y_true: ArrayLike,
49
+ y_score: ArrayLike,
50
+ *,
51
+ positive_label: object = 1,
52
+ ax: Axes | None = None,
53
+ ) -> Axes:
54
+ """Plot precision against recall over score thresholds."""
55
+ ax = _get_axes(ax)
56
+ PrecisionRecallDisplay.from_predictions(
57
+ y_true,
58
+ y_score,
59
+ pos_label=positive_label,
60
+ ax=ax,
61
+ )
62
+ return ax
63
+
64
+
65
+ def plot_recall_sensitivity_curve(
66
+ y_true: ArrayLike,
67
+ y_score: ArrayLike,
68
+ *,
69
+ positive_label: object = 1,
70
+ ax: Axes | None = None,
71
+ ) -> Axes:
72
+ """Plot recall (sensitivity) against score thresholds."""
73
+ ax = _get_axes(ax)
74
+ recall, thresholds = precision_recall_curve(
75
+ y_true,
76
+ y_score,
77
+ pos_label=positive_label,
78
+ )[1:]
79
+ ax.plot(thresholds, recall[:-1])
80
+ ax.set_xlabel("Threshold")
81
+ ax.set_ylabel("Recall (sensitivity)")
82
+ ax.set_title("Recall (sensitivity) by threshold")
83
+ return ax
84
+
85
+
86
+ def plot_roc_curve(
87
+ y_true: ArrayLike,
88
+ y_score: ArrayLike,
89
+ *,
90
+ positive_label: object = 1,
91
+ ax: Axes | None = None,
92
+ ) -> Axes:
93
+ """Plot the true-positive rate against the false-positive rate."""
94
+ ax = _get_axes(ax)
95
+ RocCurveDisplay.from_predictions(
96
+ y_true,
97
+ y_score,
98
+ pos_label=positive_label,
99
+ ax=ax,
100
+ )
101
+ return ax