Skip to content

Convert Process Control Data Model to Honeywell APM Json

PCDMToHoneywellAPMTransformer

Bases: TransformerInterface

Converts a Spark Dataframe in PCDM format to Honeywell APM format.

Example

from rtdip_sdk.pipelines.transformers import PCDMToHoneywellAPMTransformer

pcdm_to_honeywell_apm_transformer = PCDMToHoneywellAPMTransformer(
    data=df,
    quality="Good",
    history_samples_per_message=1,
    compress_payload=True
)

result = pcdm_to_honeywell_apm_transformer.transform()

Parameters:

Name Type Description Default
data Dataframe

Spark Dataframe in PCDM format

required
quality str

Value for quality inside HistorySamples

'Good'
history_samples_per_message int

The number of HistorySamples for each row in the DataFrame (Batch Only)

1
compress_payload bool

If True compresses CloudPlatformEvent with gzip compression

True
Source code in src/sdk/python/rtdip_sdk/pipelines/transformers/spark/pcdm_to_honeywell_apm.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
class PCDMToHoneywellAPMTransformer(TransformerInterface):
    """
    Converts a Spark Dataframe in PCDM format to Honeywell APM format.

    Example
    --------
    ```python
    from rtdip_sdk.pipelines.transformers import PCDMToHoneywellAPMTransformer

    pcdm_to_honeywell_apm_transformer = PCDMToHoneywellAPMTransformer(
        data=df,
        quality="Good",
        history_samples_per_message=1,
        compress_payload=True
    )

    result = pcdm_to_honeywell_apm_transformer.transform()
    ```

    Parameters:
        data (Dataframe): Spark Dataframe in PCDM format
        quality (str): Value for quality inside HistorySamples
        history_samples_per_message (int): The number of HistorySamples for each row in the DataFrame (Batch Only)
        compress_payload (bool): If True compresses CloudPlatformEvent with gzip compression
    """

    data: DataFrame
    quality: str
    history_samples_per_message: int
    compress_payload: bool

    def __init__(
        self,
        data: DataFrame,
        quality: str = "Good",
        history_samples_per_message: int = 1,
        compress_payload: bool = True,
    ) -> None:
        self.data = data
        self.quality = quality
        self.history_samples_per_message = history_samples_per_message
        self.compress_payload = compress_payload

    @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):
        return True

    def post_transform_validation(self):
        return True

    def transform(self) -> DataFrame:
        """
        Returns:
            DataFrame: A dataframe with with rows in Honeywell APM format
        """

        @udf("string")
        def _compress_payload(data):
            compressed_data = gzip.compress(data.encode("utf-8"))
            encoded_data = base64.b64encode(compressed_data).decode("utf-8")
            return encoded_data

        if self.data.isStreaming == False and self.history_samples_per_message > 1:
            w = Window.partitionBy("TagName").orderBy("TagName")
            cleaned_pcdm_df = (
                self.data.withColumn(
                    "index",
                    floor(
                        (row_number().over(w) - 0.01) / self.history_samples_per_message
                    ),
                )
                .withColumn(
                    "HistorySamples",
                    struct(
                        col("TagName").alias("ItemName"),
                        lit(self.quality).alias("Quality"),
                        col("EventTime").alias("Time"),
                        col("Value").alias("Value"),
                    ).alias("HistorySamples"),
                )
                .groupBy("TagName", "index")
                .agg(collect_list("HistorySamples").alias("HistorySamples"))
                .withColumn("guid", sha2(col("TagName"), 256).cast("string"))
                .withColumn(
                    "value",
                    struct(
                        col("guid").alias("SystemGuid"), col("HistorySamples")
                    ).alias("value"),
                )
            )
        else:
            cleaned_pcdm_df = self.data.withColumn(
                "guid", sha2(col("TagName"), 256).cast("string")
            ).withColumn(
                "value",
                struct(
                    col("guid").alias("SystemGuid"),
                    array(
                        struct(
                            col("TagName").alias("ItemName"),
                            lit(self.quality).alias("Quality"),
                            col("EventTime").alias("Time"),
                            col("Value").alias("Value"),
                        ),
                    ).alias("HistorySamples"),
                ),
            )

        df = (
            cleaned_pcdm_df.withColumn(
                "CloudPlatformEvent",
                struct(
                    lit(datetime.now(tz=pytz.UTC)).alias("CreatedTime"),
                    lit(expr("uuid()")).alias("Id"),
                    col("guid").alias("CreatorId"),
                    lit("CloudPlatformSystem").alias("CreatorType"),
                    lit(None).alias("GeneratorId"),
                    lit("CloudPlatformTenant").alias("GeneratorType"),
                    col("guid").alias("TargetId"),
                    lit("CloudPlatformTenant").alias("TargetType"),
                    lit(None).alias("TargetContext"),
                    struct(
                        lit("TextualBody").alias("type"),
                        to_json(col("value")).alias("value"),
                        lit("application/json").alias("format"),
                    ).alias("Body"),
                    array(
                        struct(
                            lit("SystemType").alias("Key"),
                            lit("apm-system").alias("Value"),
                        ),
                        struct(
                            lit("SystemGuid").alias("Key"), col("guid").alias("Value")
                        ),
                    ).alias("BodyProperties"),
                    lit("DataChange.Update").alias("EventType"),
                ),
            )
            .withColumn("AnnotationStreamIds", lit(","))
            .withColumn("partitionKey", col("guid"))
        )
        if self.compress_payload:
            return df.select(
                _compress_payload(to_json("CloudPlatformEvent")).alias(
                    "CloudPlatformEvent"
                ),
                "AnnotationStreamIds",
                "partitionKey",
            )
        else:
            return df.select(
                "CloudPlatformEvent", "AnnotationStreamIds", "partitionKey"
            )

system_type() staticmethod

Attributes:

Name Type Description
SystemType Environment

Requires PYSPARK

Source code in src/sdk/python/rtdip_sdk/pipelines/transformers/spark/pcdm_to_honeywell_apm.py
83
84
85
86
87
88
89
@staticmethod
def system_type():
    """
    Attributes:
        SystemType (Environment): Requires PYSPARK
    """
    return SystemType.PYSPARK

transform()

Returns:

Name Type Description
DataFrame DataFrame

A dataframe with with rows in Honeywell APM format

Source code in src/sdk/python/rtdip_sdk/pipelines/transformers/spark/pcdm_to_honeywell_apm.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def transform(self) -> DataFrame:
    """
    Returns:
        DataFrame: A dataframe with with rows in Honeywell APM format
    """

    @udf("string")
    def _compress_payload(data):
        compressed_data = gzip.compress(data.encode("utf-8"))
        encoded_data = base64.b64encode(compressed_data).decode("utf-8")
        return encoded_data

    if self.data.isStreaming == False and self.history_samples_per_message > 1:
        w = Window.partitionBy("TagName").orderBy("TagName")
        cleaned_pcdm_df = (
            self.data.withColumn(
                "index",
                floor(
                    (row_number().over(w) - 0.01) / self.history_samples_per_message
                ),
            )
            .withColumn(
                "HistorySamples",
                struct(
                    col("TagName").alias("ItemName"),
                    lit(self.quality).alias("Quality"),
                    col("EventTime").alias("Time"),
                    col("Value").alias("Value"),
                ).alias("HistorySamples"),
            )
            .groupBy("TagName", "index")
            .agg(collect_list("HistorySamples").alias("HistorySamples"))
            .withColumn("guid", sha2(col("TagName"), 256).cast("string"))
            .withColumn(
                "value",
                struct(
                    col("guid").alias("SystemGuid"), col("HistorySamples")
                ).alias("value"),
            )
        )
    else:
        cleaned_pcdm_df = self.data.withColumn(
            "guid", sha2(col("TagName"), 256).cast("string")
        ).withColumn(
            "value",
            struct(
                col("guid").alias("SystemGuid"),
                array(
                    struct(
                        col("TagName").alias("ItemName"),
                        lit(self.quality).alias("Quality"),
                        col("EventTime").alias("Time"),
                        col("Value").alias("Value"),
                    ),
                ).alias("HistorySamples"),
            ),
        )

    df = (
        cleaned_pcdm_df.withColumn(
            "CloudPlatformEvent",
            struct(
                lit(datetime.now(tz=pytz.UTC)).alias("CreatedTime"),
                lit(expr("uuid()")).alias("Id"),
                col("guid").alias("CreatorId"),
                lit("CloudPlatformSystem").alias("CreatorType"),
                lit(None).alias("GeneratorId"),
                lit("CloudPlatformTenant").alias("GeneratorType"),
                col("guid").alias("TargetId"),
                lit("CloudPlatformTenant").alias("TargetType"),
                lit(None).alias("TargetContext"),
                struct(
                    lit("TextualBody").alias("type"),
                    to_json(col("value")).alias("value"),
                    lit("application/json").alias("format"),
                ).alias("Body"),
                array(
                    struct(
                        lit("SystemType").alias("Key"),
                        lit("apm-system").alias("Value"),
                    ),
                    struct(
                        lit("SystemGuid").alias("Key"), col("guid").alias("Value")
                    ),
                ).alias("BodyProperties"),
                lit("DataChange.Update").alias("EventType"),
            ),
        )
        .withColumn("AnnotationStreamIds", lit(","))
        .withColumn("partitionKey", col("guid"))
    )
    if self.compress_payload:
        return df.select(
            _compress_payload(to_json("CloudPlatformEvent")).alias(
                "CloudPlatformEvent"
            ),
            "AnnotationStreamIds",
            "partitionKey",
        )
    else:
        return df.select(
            "CloudPlatformEvent", "AnnotationStreamIds", "partitionKey"
        )