File size: 16,729 Bytes
f54e1d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
from modules.datafact_generator.util import DataFact, DataFactGenerator
from modules.datafact_generator.value_fact import ValueFact
from statistics import mean, stdev
from scipy.special import expit

class DifferenceFact(DataFact):
    """ 单个 difference fact """
    def __init__(self):
        super().__init__()
        self.type = "difference"
        self.types = [
            # 不同 group 之间 value 比较
            "maximum_large",
            "maximum_small",
            "minimum_large",
            "minimum_small",
            "average_large",
            "average_small",

            # temporal
            "sudden_increase", # 相邻时间相差很多
            "sudden_decrease",

            # categorical
            "sudden_change" # 按照值排序后,相邻的相差很多
        ]

class DifferenceFactGenerator(DataFactGenerator):
    def __init__(self, data: dict, value_facts: list[ValueFact]):
        super().__init__(data)

        self.value_facts = value_facts

        self.max_facts: list[ValueFact] = []
        self.min_facts: list[ValueFact] = []
        self.avg_facts: list[ValueFact] = []

        for fact in self.value_facts:
            if fact.subtype == "max":
                self.max_facts.append(fact)
            if fact.subtype == "min":
                self.min_facts.append(fact)
            if fact.subtype == "avg":
                self.avg_facts.append(fact)

    def extract_difference_facts(self) -> list[DifferenceFact]:
        proportion_facts: list[DifferenceFact] = []

        # 不同 group 之间 value 比较
        if len(self.max_facts) > 1:
            max_large_fact, max_small_fact = self._extract_max_based_facts(self.max_facts)
            min_large_fact, min_small_fact = self._extract_min_based_facts(self.min_facts)
            avg_large_fact, avg_small_fact = self._extract_avg_based_facts(self.avg_facts)

            proportion_facts.extend([max_large_fact, max_small_fact, min_large_fact, min_small_fact, avg_large_fact, avg_small_fact])

        # sudden
        for group_value in self.grouped_data.keys():
            indices = self.grouped_data[group_value]["indices"]
            y_list = self.grouped_data[group_value]["y_list"]
            if self.is_temporal:
                increase_difference_fact, decrease_difference_fact = self._extract_temporal_sudden(group_value, indices, y_list)
                proportion_facts.append(increase_difference_fact)
                proportion_facts.append(decrease_difference_fact)
            else:
                difference_fact = self._extract_categorical_sudden(group_value, indices, y_list)
                proportion_facts.append(difference_fact)

        return proportion_facts

    def _extract_facts_base(self, fact_type: str, facts: list[ValueFact]):
        """ 模版函数 """
        max_differencen_fact, min_difference_fact = DifferenceFact(), DifferenceFact()
        max_subtype, min_subtype = f"{fact_type}_large", f"{fact_type}_small"

        # value fact 的处理中, max, min, avg 统一地会把那个值放在 data_points[*][y_column] 中
        max_val = max(facts, key=lambda x: x.data_points[0][self.y_column]).data_points[0][self.y_column] 
        min_val = min(facts, key=lambda x: x.data_points[0][self.y_column]).data_points[0][self.y_column] 

        all_val = [fact.data_points[0][self.y_column] for fact in facts]

        max_facts: list[ValueFact] = []
        min_facts: list[ValueFact] = []

        max_data_points, min_data_points = [], []

        for fact in facts:
            if fact.data_points[0][self.y_column] == max_val:
                max_facts.append(fact)
                max_data_points.extend(fact.data_points)
            if fact.data_points[0][self.y_column] == min_val:
                min_facts.append(fact)
                min_data_points.extend(fact.data_points)

        def generate_score():
            """ 统一使用单边 z 检验 """
            mu = mean(all_val)
            sigma = stdev(all_val)
            if sigma == 0:
                max_score = 1.0 if max_val > mu else 0.0
                min_score = 1.0 if min_val < mu else 0.0
                return max_score, min_score
            k = 2.0
            z0 = 0.8
            
            z = (max_val - mu) / sigma
            max_score = expit(k * (z - z0))

            z = (mu - min_val) / sigma  
            min_score = expit(k * (z - z0))

            return max_score, min_score
        
        def generate_annotation_and_reason():
            max_annotation, max_reason = "", ""
            min_annotation, min_reason = "", ""

            max_group_value_str = ", ".join([max_data_point[self.group_column] for max_data_point in max_data_points])
            min_group_value_str = ", ".join([min_data_point[self.group_column] for min_data_point in min_data_points])
            
            if len(max_data_points) == 1:
                max_annotation = f"The {fact_type} value of {max_group_value_str} is the largest in all groups."
                max_reason = (
                    f"The {fact_type} value of {self.y_column} of {max_group_value_str} has a value of {max_val}, "
                    f"which is larger than all other {self.group_column}."
                )
            else:
                max_annotation = f"The {fact_type} value of {max_group_value_str} are all the largest in all groups."
                max_reason = (
                    f"The {fact_type} value of {self.y_column} of {max_group_value_str} all have a value of {max_val}, "
                    f"which is larger than all other {self.group_column}."
                )

            if len(min_data_points) == 1:
                min_annotation = f"The {fact_type} value of {min_group_value_str} is the smallest in all groups."
                min_reason = (
                    f"The {fact_type} value of {self.y_column} of {min_group_value_str} has a value of {min_val}, "
                    f"which is smaller than all other {self.group_column}."
                )
            else:
                min_annotation = f"The {fact_type} value of {min_group_value_str} are all the smallest in all groups."
                min_reason = (
                    f"The {fact_type} value of {self.y_column} of {min_group_value_str} all have a value of {max_val}, "
                    f"which is smaller than all other {self.group_column}."
                )

            return max_annotation, max_reason, min_annotation, min_reason

        max_score, min_score = generate_score()
        max_annotation, max_reason, min_annotation, min_reason = generate_annotation_and_reason()

        max_differencen_fact.set_value(
            max_subtype, max_data_points, max_score, max_annotation, max_reason
        )

        min_difference_fact.set_value(
            min_subtype, min_data_points, min_score, min_annotation, min_reason
        )

        return max_differencen_fact, min_difference_fact

    def _extract_max_based_facts(self, max_facts: list[ValueFact]):
        return self._extract_facts_base("maximum", max_facts)

    def _extract_min_based_facts(self, min_facts: list[ValueFact]):
        return self._extract_facts_base("minimum", min_facts)

    def _extract_avg_based_facts(self, avg_facts: list[ValueFact]):
        return self._extract_facts_base("average", avg_facts)

    def _extract_temporal_sudden(self, group_value: str, indices: list[int], y_list: list):
        """ 选择一个 group 中最显著的上升 / 下降 """

        # 找到相邻值中绝对值相差最大的

        max_diff_idx_increase = []
        max_diff_increase = 0
        
        max_diff_idx_decrease = []
        max_diff_decrease = 0
        
        for idx in range(len(y_list)-1):
            diff = abs(y_list[idx] - y_list[idx+1])

            if y_list[idx] < y_list[idx+1]: # sudden increase
                if diff > max_diff_increase:
                    max_diff_increase = diff
                    max_diff_idx_increase = [idx]
                elif diff == max_diff_increase:
                    max_diff_idx_increase.append(idx)
            
            else: # sudden decrease
                if diff < max_diff_decrease:
                    max_diff_decrease = diff
                    max_diff_idx_decrease = [idx]
                elif diff == max_diff_decrease:
                    max_diff_idx_decrease.append(idx)
        
        increase_difference_fact, decrease_difference_fact = DifferenceFact(), DifferenceFact()
        increase_subtype, decrease_subtype = "sudden_increase", "sudden_decrease"

        before_increase_data_points = [self.tabular_data[indices[i]] for i in max_diff_idx_increase]
        before_decrease_data_points = [self.tabular_data[indices[i]] for i in max_diff_idx_decrease]

        after_increase_data_points = [self.tabular_data[indices[i+1]] for i in max_diff_idx_increase]
        after_decrease_data_points = [self.tabular_data[indices[i+1]] for i in max_diff_idx_decrease]

        def generate_score():
            max_val = max(y_list)
            min_val = min(y_list)

            k = 4.0
            z0 = 0.1

            increase_ratio = max_diff_increase / (max_val - min_val)
            decrease_ratio = max_diff_decrease / (max_val - min_val)

            increase_score = expit(k * (increase_ratio - z0)) if max_diff_increase else 0.0
            decrease_score = expit(k * (decrease_ratio - z0)) if max_diff_decrease else 0.0

            return increase_score, decrease_score

        def generate_annotation_and_reason():
            increase_annotation, increase_reason = "", ""
            decrease_annotation, decrease_reason = "", ""

            increase_positions = [data_point.get(self.x_column) for data_point in after_increase_data_points]
            increase_positions_str = ", ".join(increase_positions)
            after_increase_values = [str(data_point.get(self.y_column)) for data_point in after_increase_data_points]
            after_increase_values_str = ", ".join(after_increase_values)
            before_increase_values = [str(data_point.get(self.y_column)) for data_point in before_increase_data_points]
            before_increase_values_str = ", ".join(before_increase_values)

            decrease_positions = [data_point.get(self.x_column) for data_point in after_decrease_data_points]
            decrease_positions_str = ", ".join(decrease_positions)
            after_decrease_values = [str(data_point.get(self.y_column)) for data_point in after_decrease_data_points]
            after_decrease_values_str = ", ".join(after_decrease_values)
            before_decrease_values = [str(data_point.get(self.y_column)) for data_point in before_decrease_data_points]
            before_decrease_values_str = ", ".join(before_decrease_values)
            
            if len(max_diff_idx_increase) == 1:
                increase_annotation = f"The {group_value} shows a sudden increase at {increase_positions_str}."
                increase_reason = (
                    f"The {self.y_column} for {group_value} at {increase_positions_str} is {after_increase_values_str}, "
                    f"which is significantly higher than the previous value of {before_increase_values_str}."
                )
            else:
                increase_annotation = f"The {group_value} exhibits sudden increases at multiple points: {increase_positions_str}."
                increase_reason = (
                    f"At these positions, the {self.y_column} values for {group_value} are {after_increase_values_str}, "
                    f"which are significantly higher than the preceding values of {before_increase_values_str}."
                )

            if len(max_diff_idx_decrease) == 1:
                decrease_annotation = f"The {group_value} shows a sudden decrease at {decrease_positions_str}."
                decrease_reason = (
                    f"The {self.y_column} for {group_value} at {decrease_positions_str} is {after_decrease_values_str}, "
                    f"which is significantly lower than the previous value of {before_decrease_values_str}."
                )
            else:
                decrease_annotation = f"The {group_value} exhibits sudden decreases at multiple points: {decrease_positions_str}."
                decrease_reason = (
                    f"At these positions, the {self.y_column} values for {group_value} are {after_decrease_values_str}, "
                    f"which are significantly lower than the preceding values of {before_decrease_values_str}."
                )

            return increase_annotation, increase_reason, decrease_annotation, decrease_reason
        
        increase_score, decrease_score = generate_score()
        increase_annotation, increase_reason, decrease_annotation, decrease_reason = generate_annotation_and_reason()

        increase_difference_fact.set_value(
            increase_subtype, after_increase_data_points, increase_score, increase_annotation, increase_reason
        )

        decrease_difference_fact.set_value(
            decrease_subtype, after_decrease_data_points, decrease_score, decrease_annotation, decrease_reason
        )

        return increase_difference_fact, decrease_difference_fact

    def _extract_categorical_sudden(self, group_value: str, indices: list[int], y_list: list):
        difference_fact = DifferenceFact()
        subtype = "sudden_change"

        sorted_pairs = sorted(zip(y_list, indices), key=lambda x: x[0]) 
        sorted_y_list, sorted_indices = zip(*sorted_pairs)

        y_list = list(sorted_y_list)
        indices = list(sorted_indices)

        max_diff_idx = []
        max_diff = 0
        
        for idx in range(len(y_list)-1):
            diff = y_list[idx+1] - y_list[idx]

            if diff > max_diff:
                max_diff = diff
                max_diff_idx = [idx]
            elif diff == max_diff:
                max_diff_idx.append(idx)

        before_change_data_points = [self.tabular_data[indices[i]] for i in max_diff_idx]
        after_change_data_points = [self.tabular_data[indices[i+1]] for i in max_diff_idx]

        def generate_score():
            max_val = max(y_list)
            min_val = min(y_list)

            k = 4.0
            z0 = 0.1

            ratio = max_diff / (max_val - min_val)
            score = expit(k * (ratio - z0)) if max_diff else 0

            return score
        
        def generate_annotation_and_reason():
            annotation, reason = "", ""

            before_change_positions = [data_point.get(self.x_column) for data_point in before_change_data_points]
            after_change_positions = [data_point.get(self.x_column) for data_point in after_change_data_points]
            before_change_positions_str = ", ".join(before_change_positions)
            after_change_positions_str = ", ".join(after_change_positions)

            after_change_values = [str(data_point.get(self.y_column)) for data_point in after_change_data_points]
            after_change_values_str = ", ".join(after_change_values)
            before_change_values = [str(data_point.get(self.y_column)) for data_point in before_change_data_points]
            before_change_values_str = ", ".join(before_change_values)
            
            if len(max_diff_idx) == 1:
                annotation = (
                    f"The {group_value} shows a sudden jump in {self.y_column} from {before_change_positions_str} "
                    f"to {after_change_positions_str}."
                )
                reason = (
                    f"The {self.y_column} for {group_value} differs significantly between {before_change_values_str} at "
                    f"{before_change_positions_str} and {after_change_values_str} at {after_change_positions_str}."
                )
            else:
                annotation = (
                    f"The {group_value} exhibits multiple sudden jumps in {self.y_column}, transitioning from "
                    f"{before_change_positions_str} to {after_change_positions_str}."
                )
                reason = (
                    f"Across these points, the {self.y_column} for {group_value} differs significantly between "
                    f"{before_change_values_str} at {before_change_positions_str} and "
                    f"{after_change_values_str} at {after_change_positions_str}."
                )

            return annotation, reason
        
        score = generate_score()
        annotation, reason = generate_annotation_and_reason()

        difference_fact.set_value(
            subtype, after_change_data_points, score, annotation, reason
        )

        return difference_fact