-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
71 lines (52 loc) · 2.22 KB
/
lambda_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
import boto3
historical_temperature_data = []
historical_pressure_data = []
def handle_outliers(value, data, replace_high_value=0):
if not data:
return value, 'real'
sorted_data = sorted(data)
n = len(sorted_data)
lower_percentile_index = int(0.25 * n)
upper_percentile_index = int(0.75 * n)
lower_percentile_value = sorted_data[lower_percentile_index]
upper_percentile_value = sorted_data[upper_percentile_index]
iqr = upper_percentile_value - lower_percentile_value
outlier_multiplier = 1.5
lower_threshold = lower_percentile_value - outlier_multiplier * iqr
upper_threshold = upper_percentile_value + outlier_multiplier * iqr
if value is None:
return None, 'real' # Handle case where value is None separately
if value > upper_threshold or value > replace_high_value:
return value, 'real' # If the value is an outlier, processed value is the same as real value
else:
return value, 'real'
def lambda_handler(event, context):
global historical_temperature_data, historical_pressure_data
client = boto3.client('dynamodb')
timestamp = event['timestamp']
site = event['site']
temperature = event.get('temperature', None)
pressure = event.get('pressure', None)
if temperature is not None:
temperature = float(temperature)
historical_temperature_data.append(temperature)
if pressure is not None:
pressure = float(pressure)
historical_pressure_data.append(pressure)
temperature_value, temperature_type = handle_outliers(temperature, historical_temperature_data)
pressure_value, pressure_type = handle_outliers(pressure, historical_pressure_data)
dynamodb_item = {
'timestamp': {'S': timestamp},
'site': {'S': site},
}
if temperature is not None:
dynamodb_item['temperature_real'] = {'N': str(temperature)}
dynamodb_item['temperature_processed'] = {'N': str(temperature_value)}
if pressure is not None:
dynamodb_item['pressure_real'] = {'N': str(pressure)}
dynamodb_item['pressure_processed'] = {'N': str(pressure_value)}
response = client.put_item(
TableName='table_v3',
Item=dynamodb_item
)
return 0