Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Minh Khue Tran committed Nov 27, 2024
2 parents 7bebc8e + 742adcb commit 39d242e
Show file tree
Hide file tree
Showing 6 changed files with 500 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,27 @@ class DuplicateDetection(WranglerBaseInterface):
from rtdip_sdk.pipelines.monitoring.spark.data_quality.duplicate_detection import DuplicateDetection
from pyspark.sql import SparkSession
from pyspark.sql.dataframe import DataFrame
from pyspark.sql.functions import desc
duplicate_detection_monitor = DuplicateDetection(df)
duplicate_detection_monitor = DuplicateDetection(df, primary_key_columns=["TagName", "EventTime"])
result = duplicate_detection_monitor.filter()
```
Parameters:
df (DataFrame): PySpark DataFrame to be converted
df (DataFrame): PySpark DataFrame to be cleansed.
primary_key_columns (list): List of column names that serve as primary key for duplicate detection.
"""

df: PySparkDataFrame
primary_key_columns: list

def __init__(self, df: PySparkDataFrame) -> None:
def __init__(self, df: PySparkDataFrame, primary_key_columns: list) -> None:
if not primary_key_columns or not isinstance(primary_key_columns, list):
raise ValueError(
"primary_key_columns must be a non-empty list of column names."
)
self.df = df
self.primary_key_columns = primary_key_columns

@staticmethod
def system_type():
Expand All @@ -64,10 +70,9 @@ def settings() -> dict:
def filter(self) -> PySparkDataFrame:
"""
Returns:
DataFrame: A cleansed PySpark DataFrame from all the duplicates.
DataFrame: A cleansed PySpark DataFrame from all duplicates based on primary key columns.
"""

cleansed_df = self.df.dropDuplicates(["TagName", "EventTime"]).orderBy(
cleansed_df = self.df.dropDuplicates(self.primary_key_columns).orderBy(
desc("EventTime")
)
return cleansed_df
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,27 @@
from datetime import timedelta

import pandas as pd
from pyspark.sql.types import StringType
from pyspark.sql import functions as F
from pyspark.sql import SparkSession
from pyspark.sql import DataFrame


from ...._pipeline_utils.models import Libraries, SystemType
from ...interfaces import WranglerBaseInterface


class IntervalFiltering(WranglerBaseInterface):
"""
Cleanses a DataFrame by removing rows outside a specified interval window.
Example:
Cleanses a DataFrame by removing rows outside a specified interval window. Supported time stamp columns are DateType and StringType.
Parameters:
spark (SparkSession): A SparkSession object.
df (DataFrame): PySpark DataFrame to be converted
interval (int): The interval length for cleansing.
interval_unit (str): 'hours', 'minutes', 'seconds' or 'milliseconds' to specify the unit of the interval.
interval_unit (str): 'hours', 'minutes', 'seconds' or 'milliseconds' to specify the unit of the interval.
time_stamp_column_name (str): The name of the column containing the time stamps. Default is 'EventTime'.
tolerance (int): The tolerance for the interval. Default is None.
"""

""" Default time stamp column name if not set in the constructor """
Expand All @@ -57,6 +59,68 @@ def __init__(
else:
self.time_stamp_column_name = time_stamp_column_name

def filter(self) -> DataFrame:
"""
Filters the DataFrame based on the interval
"""

if self.time_stamp_column_name not in self.df.columns:
raise ValueError(
f"Column {self.time_stamp_column_name} not found in the DataFrame."
)
is_string_time_stamp = isinstance(
self.df.schema[self.time_stamp_column_name].dataType, StringType
)

original_schema = self.df.schema
self.df = self.convert_column_to_timestamp().orderBy(
self.time_stamp_column_name
)

self.df.show()

tolerance_in_ms = None
if self.tolerance is not None:
tolerance_in_ms = self.get_time_delta(self.tolerance).total_seconds() * 1000
print(tolerance_in_ms)

time_delta_in_ms = self.get_time_delta(self.interval).total_seconds() * 1000

rows = self.df.collect()
last_time_stamp = rows[0][self.time_stamp_column_name]
first_row = rows[0].asDict()

first_row[self.time_stamp_column_name] = (
self.format_date_time_to_string(first_row[self.time_stamp_column_name])
if is_string_time_stamp
else first_row[self.time_stamp_column_name]
)

cleansed_df = [first_row]

for i in range(1, len(rows)):
current_row = rows[i]
current_time_stamp = current_row[self.time_stamp_column_name]

if self.check_if_outside_of_interval(
current_time_stamp, last_time_stamp, time_delta_in_ms, tolerance_in_ms
):
current_row_dict = current_row.asDict()
current_row_dict[self.time_stamp_column_name] = (
self.format_date_time_to_string(
current_row_dict[self.time_stamp_column_name]
)
if is_string_time_stamp
else current_row_dict[self.time_stamp_column_name]
)

cleansed_df.append(current_row_dict)
last_time_stamp = current_time_stamp

result_df = self.spark.createDataFrame(cleansed_df, schema=original_schema)

return result_df

@staticmethod
def system_type():
"""
Expand All @@ -82,6 +146,7 @@ def convert_column_to_timestamp(self) -> DataFrame:
except Exception as e:
raise ValueError(
f"Error converting column {self.time_stamp_column_name} to timestamp: {e}"
f"{self.df.schema[self.time_stamp_column_name].dataType} might be unsupported!"
)

def get_time_delta(self, value: int) -> timedelta:
Expand Down Expand Up @@ -121,54 +186,3 @@ def format_date_time_to_string(self, time_stamp: pd.Timestamp) -> str:
return time_stamp.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
except Exception as e:
raise ValueError(f"Error converting timestamp to string: {e}")

def filter(self) -> DataFrame:
"""
Filters the DataFrame based on the interval
"""

if self.time_stamp_column_name not in self.df.columns:
raise ValueError(
f"Column {self.time_stamp_column_name} not found in the DataFrame."
)

original_schema = self.df.schema
self.df = self.convert_column_to_timestamp().orderBy(
self.time_stamp_column_name
)

tolerance_in_ms = None
if self.tolerance is not None:
tolerance_in_ms = self.get_time_delta(self.tolerance).total_seconds() * 1000
print(tolerance_in_ms)

time_delta_in_ms = self.get_time_delta(self.interval).total_seconds() * 1000

rows = self.df.collect()
last_time_stamp = rows[0][self.time_stamp_column_name]
first_row = rows[0].asDict()
first_row[self.time_stamp_column_name] = self.format_date_time_to_string(
first_row[self.time_stamp_column_name]
)

cleansed_df = [first_row]

for i in range(1, len(rows)):
current_row = rows[i]
current_time_stamp = current_row[self.time_stamp_column_name]

if self.check_if_outside_of_interval(
current_time_stamp, last_time_stamp, time_delta_in_ms, tolerance_in_ms
):
current_row_dict = current_row.asDict()
current_row_dict[self.time_stamp_column_name] = (
self.format_date_time_to_string(
current_row_dict[self.time_stamp_column_name]
)
)
cleansed_df.append(current_row_dict)
last_time_stamp = current_time_stamp

result_df = self.spark.createDataFrame(cleansed_df, schema=original_schema)

return result_df
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# Copyright 2022 RTDIP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pyspark.sql import DataFrame as PySparkDataFrame
from pyspark.sql import functions as F
from ...interfaces import TransformerInterface
from ...._pipeline_utils.models import Libraries, SystemType


class OneHotEncoding(TransformerInterface):
"""
Performs One-Hot Encoding on a specified column of a PySpark DataFrame.
Example
--------
```python
from src.sdk.python.rtdip_sdk.pipelines.data_wranglers.spark.data_quality.one_hot_encoding import OneHotEncoding
from pyspark.sql import SparkSession
spark = ... # SparkSession
df = ... # Get a PySpark DataFrame
one_hot_encoder = OneHotEncoding(df, "column_name", ["list_of_distinct_values"])
result_df = one_hot_encoder.encode()
result_df.show()
```
Parameters:
df (DataFrame): The PySpark DataFrame to apply encoding on.
column (str): The name of the column to apply the encoding to.
values (list, optional): A list of distinct values to encode. If not provided,
the distinct values from the data will be used.
"""

df: PySparkDataFrame
column: str
values: list

def __init__(self, df: PySparkDataFrame, column: str, values: list = None) -> None:
self.df = df
self.column = column
self.values = values

@staticmethod
def system_type():
"""
Attributes:
SystemType (Environment): Requires PYSPARK
"""
return SystemType.PYSPARK

@staticmethod
def libraries():
libraries = Libraries()
return libraries

@staticmethod
def settings() -> dict:
return {}

def pre_transform_validation(self):
"""
Validate the input data before transformation.
- Check if the specified column exists in the DataFrame.
- If no values are provided, check if the distinct values can be computed.
- Ensure the DataFrame is not empty.
"""
if self.df is None or self.df.count() == 0:
raise ValueError("The DataFrame is empty.")

if self.column not in self.df.columns:
raise ValueError(f"Column '{self.column}' does not exist in the DataFrame.")

if not self.values:
distinct_values = [
row[self.column]
for row in self.df.select(self.column).distinct().collect()
]
if not distinct_values:
raise ValueError(f"No distinct values found in column '{self.column}'.")
self.values = distinct_values

def post_transform_validation(self):
"""
Validate the result after transformation.
- Ensure that new columns have been added based on the distinct values.
- Verify the transformed DataFrame contains the expected number of columns.
"""
expected_columns = [
f"{self.column}_{value if value is not None else 'None'}"
for value in self.values
]
missing_columns = [
col for col in expected_columns if col not in self.df.columns
]

if missing_columns:
raise ValueError(
f"Missing columns in the transformed DataFrame: {missing_columns}"
)

if self.df.count() == 0:
raise ValueError("The transformed DataFrame is empty.")

def transform(self) -> PySparkDataFrame:
if not self.values:
self.values = [
row[self.column]
for row in self.df.select(self.column).distinct().collect()
]

for value in self.values:
self.df = self.df.withColumn(
f"{self.column}_{value if value is not None else 'None'}",
F.when(F.col(self.column) == value, 1).otherwise(0),
)
return self.df
Loading

0 comments on commit 39d242e

Please sign in to comment.