def __init__(self, barDeg=60, spaceDeg=60, rotateDegHz=0) -> None: if (barDeg < 0 or spaceDeg < 0): warnings.war("bar size or space is negative") if (360 % (barDeg + spaceDeg) != 0): warnings.warn( f"Spatial pattern is not seamless with bar {barDeg}° and space {spaceDeg}" ) if (rotateDegHz is None): warnings.warn("temporal components needs to be set.") self.barDeg = barDeg self.spaceDeg = spaceDeg self.rotateDegHz = rotateDegHz
def k_nearest(data, predict, k=3): if len(data) >= k: warnings.war('k value less than something') distances = [] for group in data: for features in data[group]: euclidean_distance = np.linalg.norm( np.array(features) - np.array(predict)) distances.append([euclidean_distance, group]) votes = [i[1] for i in sorted(distances)[:k]] vote_result = Counter(votes).most_common(1)[0][0] confidence = Counter(votes).most_common(1)[0][1] / k return vote_result, confidence
def ez_bolus_indices( df: pd.DataFrame, kind: Optional[str] = None) -> pd.core.indexes.datetimes.DatetimeIndex: """""" _kind_dict = { "meal": ["BWZ Carb Input (grams)"], "correction": ["BWZ Correction Estimate (U)"], "both": ["BWZ Correction Estimate (U)", "BWZ Carb Input (grams)"], } if kind not in _kind_dict.keys(): warnings.warn(f"Invalid kind, use of {list(_kind_dict.keys())}.") warnings.war("Defaulted to 'both'") kind = "both" columns = _kind_dict[kind] _nonull = partial(nonull_indices, df) indices_ls = list(map(_nonull, columns)) return reduce(lambda x, y: x.union(y), indices_ls)
def bolus_only( df: pd.DataFrame, column: str = "Sensor Glucose (mg/dL)", time_window: Dict[str, int] = { "hours": 2, "minutes": 30 }, kind: Optional[str] = None, ) -> pd.DataFrame: """ kind: 'meal' 'correction' 'both' defaults to 'both' """ bolus = df.copy() bolus["save"] = False _kind_dict = { "meal": ["BWZ Carb Input (grams)"], "correction": ["BWZ Correction Estimate (U)"], "both": ["BWZ Correction Estimate (U)", "BWZ Carb Input (grams)"], } if kind not in _kind_dict.keys(): warnings.warn(f"Invalid kind, use of {list(_kind_dict.keys())}.") warnings.war("Defaulted to 'both'") kind = "both" _td = dt.timedelta(**time_window) for uid in bolus_indices_explicit(bolus, columns=_kind_dict[kind]): real = uid + _td closest = df.index[df.index.searchsorted(real) - 1] # Otherwise it goes out of bounds ! bolus.loc[uid:closest, "save"] = True bolus.loc[bolus.save == False, "Sensor Glucose (mg/dL)"] = np.nan return bolus
def from_cnv(fname): """ DataFrame constructor to open Seabird CTD CNV-ASCII format. Examples -------- >>> from pathlib import Path >>> import ctd >>> data_path = Path(__file__).parents[1].joinpath("tests", "data") >>> cast = ctd.from_cnv(data_path.joinpath('CTD_big.cnv.bz2')) >>> downcast, upcast = cast.split() >>> ax = downcast['t090C'].plot_cast() """ f = _read_file(fname) metadata = _parse_seabird(f.readlines(), ftype="cnv") f.seek(0) df = pd.read_fwf( f, header=None, index_col=None, names=metadata["names"], skiprows=metadata["skiprows"], delim_whitespace=True, widths=[11] * len(metadata["names"]), ) f.close() prkeys = ["prM ", "prE", "prDM", "pr50M", "pr50M1", "prSM", "prdM", "pr", "depSM"] prkey = [key for key in prkeys if key in df.columns] if len(prkey) != 1: raise ValueError(f"Expected one pressure/depth column, got {prkey}.") df.set_index(prkey, drop=True, inplace=True) df.index.name = "Pressure [dbar]" if prkey == "depSM": lat = metadata.get("lat", None) if lat is not None: df.index = gsw.p_from_z( df.index, lat, geo_strf_dyn_height=0, sea_surface_geopotential=0, ) else: warnings.war( f"Missing latitude information. Cannot compute pressure! Your index is {prkey}, " "please compute pressure manually with `gsw.p_from_z` and overwrite your index.", ) df.index.name = prkey name = _basename(fname)[1] dtypes = {"bpos": int, "pumps": bool, "flag": bool} for column in df.columns: if column in dtypes: df[column] = df[column].astype(dtypes[column]) else: try: df[column] = df[column].astype(float) except ValueError: warnings.warn("Could not convert %s to float." % column) metadata["name"] = str(name) setattr(df, "_metadata", metadata) return df