-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathevaluate_novelty.py
More file actions
1643 lines (1292 loc) · 69 KB
/
evaluate_novelty.py
File metadata and controls
1643 lines (1292 loc) · 69 KB
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import csv
import pickle5 as p
import pandas as pd
from naive_search_Novelty import NaiveSearcherNovelty
from nltk.tokenize import RegexpTokenizer
from nltk.stem import PorterStemmer
import numpy as np
import utilities as utl
import itertools
import time
import multiprocessing as mp
import os
# Set the multiprocessing start method to spawn to avoid CUDA reinitialization issues.
mp.set_start_method('spawn', force=True)
# from pyspark.sql import SparkSession
# from pyspark.sql.functions import col, lit
# from pyspark.sql.types import StructType, StructField, StringType, ArrayType
# import pyspark.sql.functions as F
#This file containes all the metrics used in our paper to evalute the novelty/diversity
#of the reranking
def Avg_executiontime_by_k(resultfile, outputfile):
file_path = resultfile
df = pd.read_csv(file_path, usecols=[0, 1, 2, 3])
# Extract column names for reference
column_names = df.columns.tolist()
# Assuming 'k', 'query_name', and 'tables' are part of the loaded columns
k_column = column_names[3] # Replace with the actual column name for k
time_column=column_names[2]
grouped = df.groupby(k_column)[time_column].mean()
result_df = grouped.reset_index()
# Rename the columns to 'k' and 'exec_time'
result_df.columns = ['k', 'exec_time']
# Write the DataFrame to a CSV file named 'outputfile.csv' without the index
result_df.to_csv(outputfile, index=False)
# Print the results
for k, avg_time in grouped.items():
print(f"k: {k}, Average execution time is: {avg_time}")
def contains_query(row):
tables = row['tables']
if pd.isna(tables):
return False
# split on commas, strip whitespace
parts = [x.strip() for x in tables.split(',')]
return row['query_name'] in parts
def compute_counts(dataframe, k_column,query_name_column, tables_column):
exclude=set()
print("numebr of row before excluding two queries"+ str(len(dataframe)))
dataframe = dataframe[~dataframe[query_name_column].isin(exclude)]
print("numebr of row after excluding two queries"+ str(len(dataframe)))
result = []
unique_k_values = dataframe[k_column].unique()
for k in unique_k_values:
filtered_df = dataframe[dataframe[k_column] == k]
# count = filtered_df.apply(
# lambda row: row[query_name_column] in [x.strip() for x in row[tables_column].split(',')],
# axis=1
# ).sum()
count = filtered_df.apply(contains_query, axis=1).sum()
result.append({'k': k, 'count': count})
return pd.DataFrame(result)
def query_duplicate_returned_exclude(result_file, output_file, exc_queris):
# Load the CSV file and read the first four columns, using the first row as column names
file_path = result_file # Replace with the path to your CSV file
df = pd.read_csv(file_path, usecols=[0, 1, 2, 3])
# Extract column names for reference
column_names = df.columns.tolist()
# Assuming 'k', 'query_name', and 'tables' are part of the loaded columns
k_column = column_names[3] # Replace with the actual column name for k
query_name_column = column_names[0] # Replace with the actual column name for query name
tables_column = column_names[1] # Replace with the actual column name for tables
# Filter out excluded queries
df = df[~df[query_name_column].isin(exc_queris)]
# Compute the results
results_df = compute_counts(df, k_column,query_name_column, tables_column)
# Output the results
results_df.to_csv(output_file, index=False)
def query_duplicate_returned(result_file, output_file):
# Load the CSV file and read the first four columns, using the first row as column names
file_path = result_file # Replace with the path to your CSV file
df = pd.read_csv(file_path, usecols=[0, 1, 2, 3])
# Extract column names for reference
column_names = df.columns.tolist()
# Assuming 'k', 'query_name', and 'tables' are part of the loaded columns
k_column = column_names[3] # Replace with the actual column name for k
query_name_column = column_names[0] # Replace with the actual column name for query name
tables_column = column_names[1] # Replace with the actual column name for tables
# Compute the results
results_df = compute_counts(df, k_column,query_name_column, tables_column)
# Output the results
results_df.to_csv(output_file, index=False)
def analyse(file_penalize,file_gmc):
# Load the CSV files into DataFrames
x1 = pd.read_csv(file_penalize) # Replace with your first CSV file name
x2 = pd.read_csv(file_gmc) # Replace with your second CSV file name
# Find common queries
common_queries = set(x1['query']).intersection(set(x2['query']))
# Keep only rows with common queries
x1_filtered = x1[x1['query'].isin(common_queries)]
x2_filtered = x2[x2['query'].isin(common_queries)]
# Merge filtered DataFrames on 'query' and 'k' to align rows for comparison
merged = pd.merge(x1_filtered, x2_filtered, on=['query', 'k'], suffixes=('_x1', '_x2'))
# Compare precision values and group by 'k' to count queries with greater precision in x1
result = merged.groupby('k').apply(lambda df: (df['Prec_x1'] >= df['Prec_x2']).sum())
# Display the result
print("Number of queries with greater or equal precision in "+file_penalize+" for each k:")
print(result)
# Compare precision values and group by 'k' to count queries with greater precision in x1
result2 = merged.groupby('k').apply(lambda df: (df['Recall_x1'] >= df['Recall_x2']).sum())
# Display the result
print("Number of queries with greater or equal recall in "+file_penalize+" for each k:")
print(result2)
# Group by 'k' and compute statistics for Prec, Recall, and Ideal Recall
stats_x1 = x1_filtered.groupby('k').agg({
'Prec': ['mean', 'median', 'std'],
'Recall': ['mean', 'median', 'std'],
'Ideal Recall': ['mean', 'median', 'std']
})
# Rename columns for clarity
stats_x1.columns = ['_'.join(col).strip() for col in stats_x1.columns.values]
# Display the statistics
print("Grouped Statistics for x1_filtered by k:")
print(stats_x1)
stats_x2 = x2_filtered.groupby('k').agg({
'Prec': ['mean', 'median', 'std'],
'Recall': ['mean', 'median', 'std'],
'Ideal Recall': ['mean', 'median', 'std']
})
# Rename columns for clarity
stats_x2.columns = ['_'.join(col).strip() for col in stats_x2.columns.values]
# Display the statistics
print("Grouped Statistics for x2_filtered by k:")
print(stats_x2)
def loadDictionaryFromPickleFile(dictionaryPath):
''' Load the pickle file as a dictionary
Args:
dictionaryPath: path to the pickle file
Return: dictionary from the pickle file
'''
filePointer=open(dictionaryPath, 'rb')
dictionary = p.load(filePointer)
filePointer.close()
return dictionary
# a function to calculate precision recall and MAP per query
def Cal_P_R_Map(resultFile, gtPath, output_file_):
''' Calculate and log the performance metrics: MAP, Precision@k, Recall@k
Args:
max_k: the maximum K value (e.g. for SANTOS benchmark, max_k = 10. For TUS benchmark, max_k = 60)
k_range: different k s that are reported in the result
gtPath: file path to the groundtruth
resPath: file path to the raw results from the model
Return: MAP, P@K, R@K'''
groundtruth = loadDictionaryFromPickleFile(gtPath)
# resultFile = loadDictionaryFromPickleFile(resPath)
file_path = resultFile
df = pd.read_csv(file_path, usecols=[0, 1, 2, 3])
# Extract column names for reference
column_names = df.columns.tolist()
# Assuming 'k', 'query_name', and 'tables' are part of the loaded columns
k_column = column_names[3] # Replace with the actual column name for k
query_name_column = column_names[0] # Replace with the actual column name for query name
tables_column = column_names[1] # Replace with the actual column name for tables
unique_k_values = df[k_column].unique() # existing k
precision_array = []
recall_array = []
ideal_recall=[]
result_query_k={}
for k in unique_k_values:
# for this k go through the df and create a dictionary from query to list of returned tables
filtered_df = df[df['k'] == k]
# Initialize the dictionary
resultFile = {}
# Iterate over filtered rows
for _, row in filtered_df.iterrows():
query_name = row['query_name']
tablenames_set = set(row['tables'].split(',')) # Split and convert to set for uniqueness
# Add or update the dictionary
if query_name not in resultFile:
resultFile[query_name] = list(tablenames_set)
else:
resultFile[query_name] = list(set(resultFile[query_name]) | tablenames_set)
true_positive = 0
false_positive = 0
false_negative = 0
rec = 0
for table in resultFile:
# t28 tables have less than 60 results. So, skipping them in the analysis.
if table in groundtruth:
groundtruth_set = set(groundtruth[table])
groundtruth_set = {x.split(".")[0] for x in groundtruth_set}
result_set = resultFile[table][:k]
result_set = [x.split(".")[0] for x in result_set]
result_set = [item.strip() for item in result_set]
result_set = [item.replace("]", '') for item in result_set]
# find_intersection = true positives
find_intersection = set(result_set).intersection(groundtruth_set)
tp = len(find_intersection)
fp = k - tp
fn = len(groundtruth_set) - tp
if len(groundtruth_set)>=k:
true_positive += tp
false_positive += fp
false_negative += fn
rec += tp / (tp+fn)
pecs_q_k= tp/(tp+fp) # prec for k for query
rec_q_k=tp / (tp+fn)
if(k<len(groundtruth[table])):
ideal_recall_q_k=k/len(groundtruth[table])
else:
ideal_recall_q_k=1
result_query_k[(k, table)]=[pecs_q_k,rec_q_k,ideal_recall_q_k]
ideal_recall.append(k/float(len(groundtruth[table])))
precision = true_positive / (true_positive + false_positive)
recall = rec/len(resultFile)
precision_array.append(precision)
recall_array.append(recall)
print("k values:")
print(unique_k_values)
print("precision_array")
print(precision_array)
print("ideal_recall")
print(ideal_recall)
print("recall_array")
print(recall_array)
# Output CSV file name
output_file = output_file_
# Write data to CSV
with open(output_file, mode="w", newline="") as file:
writer = csv.writer(file)
# Write the header
writer.writerow(["k", "query", "Prec", "Recall", "Ideal Recall"])
# Write the rows
for (k1, k2), values in result_query_k.items():
writer.writerow([k1, k2] + values)
print(f"Data successfully written to {output_file}")
#return mean_avg_pr, precision_array[max_k-1], recall_array[max_k-1]
return None
def compute_syntactic_novelty_measure_simplified(groundtruth_file, search_result, snm_avg_result_path_, snm_whole_result_path_, remove_dup=0):
"""
this function only makes sense to be run over diluted dataset
we assume 2 things: 1- the list of dl_tables for each query is sorted descending bu unionability score
2- search_result file is a csv has atleast these columns: query_name, tables, execution_time, k
groundtruth: is the gound truth havinf unionable tables for each query
"""
if('csv' in groundtruth_file ):
groundtruth = utl.loadDictionaryFromCsvFile(groundtruth_file)
else:
groundtruth = loadDictionaryFromPickleFile(groundtruth_file)
input_file = search_result
columns_to_load = ['query_name', 'tables', 'k']
df = pd.read_csv(input_file, usecols=columns_to_load)
# Get the unique values of 'k' in the dataframe
unique_k_values = df['k'].unique()
# Initialize an empty list to collect the results
results = []
results_whole=[]
# Iterate over each unique 'k' and process the dataframe
for k in unique_k_values:
# Filter the dataframe for the current value of 'k'
subset_df = df[df['k'] == k]
# Calculate the average SNM using the custom function
print("k is: "+str(k))
avg_snm, invalid_snm = get_ssnm_average(subset_df, groundtruth, remove_dup)
temp_whole=get_ssnm_whole(subset_df, groundtruth, k, remove_dup)
results_whole.extend(temp_whole)
# Append the result as a dictionary
results.append({'k': k, 'avg_snm': avg_snm, 'q_invalid_snm:':invalid_snm})
# Convert the results into a dataframe
result_df = pd.DataFrame(results)
# Write the result dataframe to a new CSV file
output_file_agv = snm_avg_result_path_
result_df.to_csv(output_file_agv, index=False)
result_whole=pd.DataFrame(results_whole)
result_whole.to_csv(snm_whole_result_path_, index=False)
print("caluculate Simplified SNM for the input result file for different k")
def compute_syntactic_novelty_measure_simplified_with_exclude(
groundtruth_file,
search_result,
snm_avg_result_path_,
snm_whole_result_path_,
exclude_queries=None,
remove_dup=0, ):
"""
Compute the simplified SNM, excluding specified queries before aggregation.
Assumptions:
1) For each query, the list of diluted tables (dl_tables) is sorted in
descending order by unionability score.
2) `search_result` is a CSV with at least these columns:
['query_name', 'tables', 'k'].
3) `groundtruth_file` is either a CSV (loaded via utl.loadDictionaryFromCsvFile)
or a pickle (loaded via loadDictionaryFromPickleFile).
Args:
groundtruth_file (str): Path to ground-truth file (csv or pickle).
search_result (str): Path to search results CSV.
snm_avg_result_path_ (str): Output path for the per-k averages CSV.
snm_whole_result_path_ (str): Output path for the whole results CSV.
exclude_queries (list[str] | None): Query names to exclude entirely
before computing SNM. Exact string match on 'query_name'.
remove_dup (int): Passed through to get_ssnm_* helpers.
Side effects:
Writes two CSVs to the provided output paths.
"""
# Load ground truth
if 'csv' in groundtruth_file:
groundtruth = utl.loadDictionaryFromCsvFile(groundtruth_file)
else:
groundtruth = loadDictionaryFromPickleFile(groundtruth_file)
# Read the minimal columns needed
columns_to_load = ['query_name', 'tables', 'k']
df = pd.read_csv(search_result, usecols=columns_to_load)
# Apply exclusion if provided
if exclude_queries:
exclude_set = set(exclude_queries)
before_cnt = len(df)
df = df[~df['query_name'].isin(exclude_set)].copy()
after_cnt = len(df)
print(f"Excluded {before_cnt - after_cnt} rows for queries: {sorted(exclude_set)}")
if df.empty:
# Nothing to compute; still emit empty-but-well-formed outputs
pd.DataFrame(columns=['k', 'avg_snm', 'q_invalid_snm:']).to_csv(snm_avg_result_path_, index=False)
pd.DataFrame().to_csv(snm_whole_result_path_, index=False)
print("No rows left after exclusion; wrote empty result files.")
return
# Compute per-k results
unique_k_values = df['k'].unique()
results = []
results_whole = []
for k in unique_k_values:
subset_df = df[df['k'] == k]
print(f"k is: {k}")
avg_snm, invalid_snm = get_ssnm_average(subset_df, groundtruth, remove_dup)
temp_whole = get_ssnm_whole(subset_df, groundtruth, k, remove_dup)
results_whole.extend(temp_whole)
results.append({'k': k, 'avg_snm': avg_snm, 'q_invalid_snm:': invalid_snm})
# Write outputs
pd.DataFrame(results).to_csv(snm_avg_result_path_, index=False)
pd.DataFrame(results_whole).to_csv(snm_whole_result_path_, index=False)
print("Calculated Simplified SNM (with exclusions) for the input result file across different k.")
def get_ssnm_average(df_k, groundtruth_dic, remove_dup):
"""we go through all queries except for these two that do not exist in dust alignment
workforce_management_information_a.csv
workforce_management_information_b.csv
"""
exclude=set()
queries = df_k['query_name'].unique()
number_queries=0
snm_total=0.0
q_not_valid_snm=set()
for q in queries:
if q not in exclude:
df_k_q = df_k[df_k['query_name'] == q]
groundtruth_dic_q=groundtruth_dic[q]
q_snm,L, G=get_ssnm_query(df_k_q, groundtruth_dic_q, remove_dup)
if(q_snm==-1):
q_not_valid_snm.add(q)
else:
number_queries=number_queries+1
snm_total=snm_total+q_snm
else:
print("excluded query is found")
return (float(snm_total)/ float(number_queries), q_not_valid_snm)
def get_ssnm_whole(df_k, groundtruth_dic, k, remove_duplicates):
"""we go through all queries except for these two that do not exist in dust alignment:
workforce_management_information_a.csv
workforce_management_information_b.csv
"""
exclude=set()
queries = df_k['query_name'].unique()
results_k = []
for q in queries:
if q not in exclude:
df_k_q = df_k[df_k['query_name'] == q]
groundtruth_dic_q=groundtruth_dic[q]
q_snm, L, G=get_ssnm_query(df_k_q, groundtruth_dic_q, remove_duplicates)
results_k.append({'k': k, 'query': q,'snm': q_snm, 'L':L, 'G':G})
else:
print("excluded query is found")
return results_k
def get_ssnm_query(df_q, groundtruth_tables, remove_duplicates):
# list of unionable tables in groundtruth
df_q.dropna(subset=['tables'], inplace=True)
if len(df_q)==0:
return 0, 0, 0
tables_result_list=[x.strip() for x in df_q['tables'].tolist()[0].split(',')]
tables_result_list = [ item.replace("[", "").replace("'", "").replace("]", "") for item in tables_result_list ]
tables_result_set=set(tables_result_list)
#these two holds the expected pair name of the visited file names which are not yet paired
visited_diluted_waiting_for_set=set()
# the not deluted seen so far
visited_no_diluted_waiting_for_set=set()
groundtruth_tables_set=set(groundtruth_tables)
groundtruth_tables_set = { item.replace("[", "").replace("'", "").replace("]","") for item in groundtruth_tables_set }
tables_result_set = { item.replace("[", "").replace("'", "").replace("]","") for item in tables_result_set }
G=len(tables_result_set.intersection(groundtruth_tables_set))
L=0.0 #number of unionable diluted comes alone in result
if (G==0):
print("no unionable tables in the results")
return -1, L, G # not valid snm exists for this query
else:
for t in tables_result_list:
if t in groundtruth_tables_set: # is unionable
deluted_=is_diluted_version(t)
if(deluted_==-1):
# check whther you have seen its diluted pair or not
if(t in visited_diluted_waiting_for_set):
visited_diluted_waiting_for_set.remove(t) # pair is seen so remove from waiting list
else:
visited_no_diluted_waiting_for_set.add(t)
else:
if deluted_ in visited_no_diluted_waiting_for_set:
visited_no_diluted_waiting_for_set.remove(deluted_) # good pair original came before dilutes
else:
visited_diluted_waiting_for_set.add(deluted_) #
L= len(visited_diluted_waiting_for_set) # not paired with original
if remove_duplicates==1:
#consider blatant duplicates in the computation
query_name=df_q['query_name'].tolist()[0]
dilutedname_query_name=query_name.replace('.csv', '_dlt.csv')
if(query_name in tables_result_list and dilutedname_query_name in tables_result_list):
L=L+1
if(query_name in tables_result_list and dilutedname_query_name not in tables_result_list):
L=L+1
ssnm= 1-(float(L)/G)
return ssnm, L, G
def is_diluted_version(fname):
"""if it has _dlt showes is diluted then retrun original file name
else retrun -1"""
if('_dlt' in fname) :
return fname.replace('_dlt', '')
else:
return -1
def compute_syntactic_novelty_measure(groundtruth_file, search_result, snm_avg_result_path_, snm_whole_result_path_, remove_duplicate=0):
"""
this function only makes sense to be run over diluted dataset
we assume 2 things: 1- the list of dl_tables for each query is sorted descending bu unionability score
2- search_result file is a csv has atleast these columns: query_name, tables, execution_time, k
groundtruth: is the gound truth having unionable tables for each query
"""
if('csv' in groundtruth_file ):
groundtruth = utl.loadDictionaryFromCsvFile(groundtruth_file)
else:
groundtruth = loadDictionaryFromPickleFile(groundtruth_file)
input_file = search_result
columns_to_load = ['query_name', 'tables', 'k']
df = pd.read_csv(input_file, usecols=columns_to_load)
# Get the unique values of 'k' in the dataframe
unique_k_values = df['k'].unique()
# Initialize an empty list to collect the results
results = []
results_whole=[]
# Iterate over each unique 'k' and process the dataframe
for k in unique_k_values:
# Filter the dataframe for the current value of 'k'
subset_df = df[df['k'] == k]
# Calculate the average SNM using the custom function
print("k is: "+str(k))
avg_snm, invalid_snm = get_snm_average(subset_df, groundtruth, remove_duplicate)
temp_whole=get_snm_whole(subset_df, groundtruth, k, remove_duplicate)
results_whole.extend(temp_whole)
# Append the result as a dictionary
results.append({'k': k, 'avg_snm': avg_snm, 'q_invalid_snm:':invalid_snm})
# Convert the results into a dataframe
result_df = pd.DataFrame(results)
# Write the result dataframe to a new CSV file
output_file_agv = snm_avg_result_path_
result_df.to_csv(output_file_agv, index=False)
result_whole=pd.DataFrame(results_whole)
result_whole.to_csv(snm_whole_result_path_, index=False)
print("caluculate SNM for the input result file for different k")
def compute_syntactic_novelty_measure_with_exclude(
groundtruth_file,
search_result,
snm_avg_result_path_,
snm_whole_result_path_,
remove_duplicate=0,
exclude_queries=None,
):
"""
Same as compute_syntactic_novelty_measure, but excludes queries whose names
appear in `exclude_queries` before computing results.
Parameters
----------
groundtruth_file : str
Path to ground-truth file (CSV or pickle). If CSV, we call
utl.loadDictionaryFromCsvFile; otherwise loadDictionaryFromPickleFile.
search_result : str
CSV with at least columns: ['query_name', 'tables', 'k'].
snm_avg_result_path_ : str
Output CSV path for aggregated (avg) SNM per k.
snm_whole_result_path_ : str
Output CSV path for per-query SNM details.
remove_duplicate : int
Passed through to get_snm_average / get_snm_whole.
exclude_queries : list[str] | None
Query names to exclude exactly (string match on 'query_name').
"""
# Load ground truth
if ('csv' in groundtruth_file):
groundtruth = utl.loadDictionaryFromCsvFile(groundtruth_file)
else:
groundtruth = loadDictionaryFromPickleFile(groundtruth_file)
# Load search results
input_file = search_result
columns_to_load = ['query_name', 'tables', 'k']
df = pd.read_csv(input_file, usecols=columns_to_load)
# Exclude queries if requested
if exclude_queries:
excl = set(map(str, exclude_queries))
before = len(df)
df = df[~df['query_name'].astype(str).isin(excl)].copy()
print(f"Excluded {before - len(df)} rows by query_name from {len(excl)} excluded queries.")
# If everything got filtered out, write empty outputs and exit gracefully
if df.empty:
pd.DataFrame(columns=['k', 'avg_snm', 'q_invalid_snm:']).to_csv(snm_avg_result_path_, index=False)
pd.DataFrame().to_csv(snm_whole_result_path_, index=False)
print("No rows left after exclusion. Wrote empty result files.")
return
# Proceed as in the original
unique_k_values = df['k'].unique()
results = []
results_whole = []
for k in unique_k_values:
subset_df = df[df['k'] == k]
print("k is: " + str(k))
avg_snm, invalid_snm = get_snm_average(subset_df, groundtruth, remove_duplicate)
temp_whole = get_snm_whole(subset_df, groundtruth, k, remove_duplicate)
results_whole.extend(temp_whole)
results.append({'k': k, 'avg_snm': avg_snm, 'q_invalid_snm:': invalid_snm})
# Write outputs
result_df = pd.DataFrame(results)
result_df.to_csv(snm_avg_result_path_, index=False)
result_whole = pd.DataFrame(results_whole)
result_whole.to_csv(snm_whole_result_path_, index=False)
print("Calculated SNM for the input result file for different k (with exclusions applied).")
def get_snm_average(df_k, groundtruth_dic, remove_duplicate):
"""we go through all queries except for these two that do not exist in dust alignment
workforce_management_information_a.csv
workforce_management_information_b.csv
"""
exclude=set()
queries = df_k['query_name'].unique()
number_queries=0
snm_total=0.0
q_not_valid_snm=set()
for q in queries:
if q not in exclude:
df_k_q = df_k[df_k['query_name'] == q]
groundtruth_dic_q=groundtruth_dic[q]
q_snm, B, L, G=get_snm_query(df_k_q, groundtruth_dic_q, remove_duplicate)
if(q_snm==-1):
q_not_valid_snm.add(q)
else:
number_queries=number_queries+1
snm_total=snm_total+q_snm
else:
print("excluded query is found")
return (float(snm_total)/ float(number_queries), q_not_valid_snm)
def get_snm_query(df_q, groundtruth_tables, remove_duplicates):
# list of unionable tables in groundtruth
df_q.dropna(subset=['tables'], inplace=True)
if len(df_q)==0: return 0,0,0,0
tables_result_list=[x.strip() for x in df_q['tables'].tolist()[0].split(',')]
tables_result_list = [ item.replace("[", "").replace("'", "").replace("]", "") for item in tables_result_list ]
tables_result_set=set(tables_result_list)
#these two holds the expected pair name of the visited file names which are not yet paired
visited_diluted_waiting_for_set=set()
# the not deluted seen so far
visited_no_diluted_waiting_for_set=set()
groundtruth_tables_set=set(groundtruth_tables)
groundtruth_tables_set = { item.replace("[", "").replace("'", "").replace("]", "") for item in groundtruth_tables_set }
tables_result_set = { item.replace("[", "").replace("'", "").replace("]", "") for item in tables_result_set }
G=len(tables_result_set.intersection(groundtruth_tables_set))
L=0.0 #number of unionable diluted comes alone in result
B=00.0 # diluted item comes before its original peer
if (G==0):
print("no unionable tables in the results")
return -1,B, L, G # not valid snm exists for this query
else:
for t in tables_result_list:
if t in groundtruth_tables_set: # is unionable
deluted_=is_diluted_version(t)
if(deluted_==-1):
# check whther you have seen its diluted pair or not
if(t in visited_diluted_waiting_for_set):
B=B+1 #update B
visited_diluted_waiting_for_set.remove(t) # pair is seen so remove from waiting list
else:
visited_no_diluted_waiting_for_set.add(t)
else:
if deluted_ in visited_no_diluted_waiting_for_set:
visited_no_diluted_waiting_for_set.remove(deluted_) # good pair original came before dilutes
else:
visited_diluted_waiting_for_set.add(deluted_) #
L= len(visited_diluted_waiting_for_set) # not paired with original
if remove_duplicates==1:
#consider blatant duplicates in the computation
query_name=df_q['query_name'].tolist()[0]
dilutedname_query_name=query_name.replace('.csv', '_dlt.csv')
if(query_name in tables_result_list and dilutedname_query_name in tables_result_list):
if(tables_result_list.index(query_name) < tables_result_list.index(dilutedname_query_name)):
B=B+1
if(query_name in tables_result_list and dilutedname_query_name not in tables_result_list):
L=L+1
snm= 1-((float(B)+float(L))/G)
return snm, B, L, G
def get_snm_whole(df_k, groundtruth_dic, k, remove_duplicate):
"""we go through all queries except for these two that do not exist in dust alignment:
workforce_management_information_a.csv
workforce_management_information_b.csv
"""
exclude=set()
queries = df_k['query_name'].unique()
results_k = []
for q in queries:
if q not in exclude:
df_k_q = df_k[df_k['query_name'] == q]
groundtruth_dic_q=groundtruth_dic[q]
q_snm, B, L, G=get_snm_query(df_k_q, groundtruth_dic_q, remove_duplicate)
results_k.append({'k': k, 'query': q,'snm': q_snm, 'B':B, 'L':L, 'G':G})
else:
print("excluded query is found")
return results_k
def can_merge_sequential(row1, row2):
"""
Determine if two rows can be merged.
"""
for val1, val2 in zip(row1, row2):
if pd.notna(val1) and pd.notna(val2) and val1 != val2:
return False
return True
def merge_rows_sequential(row1, row2):
"""
Merge two rows into one.
"""
return [val1 if pd.notna(val1) else val2 for val1, val2 in zip(row1, row2)]
def merge_dataframe_sequential(df):
"""
Merge rows in a DataFrame based on the given logic.
"""
print("performing merge of original size " +str(len(df)))
rows = df.values.tolist() # Convert to a list of rows for easier manipulation
merged = True
while merged:
merged = False
skip_indices = set()
new_rows = []
# Process rows efficiently
for i in range(len(rows)):
print("# number of merged so far "+ str(len(skip_indices)))
if i in skip_indices:
continue
merged_row = rows[i]
for j in range(i + 1, len(rows)): # Only compare rows after the current one
if j not in skip_indices and can_merge_sequential(merged_row, rows[j]):
merged_row = merge_rows_sequential(merged_row, rows[j])
skip_indices.add(j) # Skip merged row
merged = True
new_rows.append(merged_row)
rows = new_rows # Update the rows for the next iteration
# Convert back to a DataFrame
print("return from merger")
return pd.DataFrame(rows, columns=df.columns)
def can_merge_rowwise(row):
"""
Row-wise merge logic for Cartesian join.
Returns True if two rows can be merged, False otherwise.
"""
row1 = row['row1']
row2 = row['row2']
for val1, val2 in zip(row1, row2):
if pd.notna(val1) and pd.notna(val2) and val1 != val2:
return False
return True
def merge_rows(row1, row2):
"""
Merge two rows into one.
"""
return [val1 if pd.notna(val1) else val2 for val1, val2 in zip(row1, row2)]
def merge_dataframe(df):
"""
Merge rows in a DataFrame using a Cartesian join for efficiency.
"""
print(f"Performing merge for original DataFrame of size: {len(df)}")
rows = df.values.tolist()
merged = True
while merged:
merged = False
print(f"Performing merge for original DataFrame of size: {len(rows)}")
# Create a DataFrame for the Cartesian product
cartesian_df = pd.DataFrame({
'row1': rows,
}).merge(pd.DataFrame({
'row2': rows,
}), how='cross')
# Apply merge logic row-wise
cartesian_df['can_merge'] = cartesian_df.apply(can_merge_rowwise, axis=1)
# Identify mergeable pairs
mergeable_pairs = cartesian_df[cartesian_df['can_merge']]
if not mergeable_pairs.empty:
merged = True
# Take the first mergeable pair and merge
merged_rows = set()
new_rows = []
for _, row in mergeable_pairs.iterrows():
if tuple(row['row1']) not in merged_rows and tuple(row['row2']) not in merged_rows:
new_row = merge_rows(row['row1'], row['row2'])
new_rows.append(new_row)
merged_rows.add(tuple(row['row1']))
merged_rows.add(tuple(row['row2']))
# Add rows that were not merged
for row in rows:
if tuple(row) not in merged_rows:
new_rows.append(row)
rows = new_rows
# Convert back to a DataFrame
print(f"Returning merged DataFrame of size: {len(rows)}")
return pd.DataFrame(rows, columns=df.columns)
def merge_dataframe_spark(df, spark_session=None):
"""
Merges rows in a DataFrame using PySpark. Accepts either pandas or PySpark DataFrame and
includes conversion logic.
:param df: Input DataFrame (pandas or PySpark)
:param spark_session: SparkSession instance (required if input is pandas DataFrame)
:return: Merged PySpark DataFrame
"""
# Ensure the input is a Spark DataFrame
if spark_session is None:
spark_session = SparkSession.builder.appName("MergeRows").master("local[10]"). config("spark.driver.memory", "60g") \
.config("spark.executor.memory", "40g") \
.config("spark.driver.maxResultSize", "40g")\
.getOrCreate()
df = spark_session.createDataFrame(df)
def merge_rows(row1, row2):
"""
Custom logic for merging two rows.
"""
merged_row = []
for val1, val2 in zip(row1, row2):
if val1 is None and val2 is None:
merged_row.append(None)
elif val1 is None:
merged_row.append(val2)
elif val2 is None:
merged_row.append(val1)
elif val1 == val2:
merged_row.append(val1)
else:
# Return None if values conflict (no merge)
return None
return merged_row
# Define a UDF to apply merge_rows logic
def merge_udf(row1, row2):
merged = merge_rows(row1, row2)
return merged
merge_udf_spark = F.udf(merge_udf, ArrayType(StringType()))
merged = True
while merged:
# Perform Cartesian join
cartesian_df = df.alias("row1").crossJoin(df.alias("row2"))
# Apply merge_rows logic row-wise
cartesian_df = cartesian_df.withColumn(
"merged",
merge_udf_spark(
F.struct(*[col(f"row1.{c}") for c in df.columns]),
F.struct(*[col(f"row2.{c}") for c in df.columns])
)
)
print("merged ")
# Separate merged rows and unmerged rows
merged_rows_ = cartesian_df.filter(cartesian_df["merged"].isNotNull()).select("merged").distinct()
merged_rows=merged_rows_.collect()
unmerged_rows = df.subtract(
merged_rows.selectExpr([f"merged[{i}] AS {col}" for i, col in enumerate(df.columns)])
)
# Combine merged and unmerged rows
df = merged_rows.union(unmerged_rows)
# If no new merges occurred, stop the loop
if merged_rows.count() == 0:
merged = False
# Convert back to PySpark DataFrame format
return df.select([F.col(f"merged[{i}]").alias(df.columns[i]) for i in range(len(df.columns))])
def perform_concat(q_name,dl_t_name,filtered_align,df_query,df_dl, normalized):
"""This function do a special concat and retrun the result as dataframe"""
print("performing concat for datalake table: "+dl_t_name)