Spaces:
Sleeping
Sleeping
File size: 16,161 Bytes
d18c1bd fd4a87f d18c1bd 0fd765e d18c1bd 0fd765e d18c1bd 0fd765e d18c1bd 0fd765e d18c1bd 0fd765e d18c1bd 0fd765e d18c1bd fd4a87f d18c1bd 0fd765e d18c1bd 0fd765e d18c1bd fd4a87f d18c1bd fd4a87f d18c1bd fd4a87f d18c1bd 0fd765e d18c1bd fd4a87f d18c1bd | 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 | import pandas as pd
import numpy as np
from cmap import Colormap, Color
from sklearn import preprocessing, decomposition, manifold
def filter_valid_sentences(
df,
min_nwords,
):
# filter for only valid sentences
df = df.merge(
(
df
.filter(['source__model','source__unq_sentence_id','source__est_nwords'])
.drop_duplicates()
.query('source__est_nwords >= @min_nwords')
.groupby('source__model')
['source__unq_sentence_id'].count()
.to_frame('source__model_num_valid_length')
.reset_index()
),
how='left'
)
return df
def process_progression(
df,
min_nwords,
thres_ratio,
min_high_sim_num_sents,
min_high_sim_pct_sim,
):
main_groupbys = [
'source__model',
'source__model_num_valid_length',
'target__doc_id',
'target__doc_rank',
'target__is_most_recent_doc',
'target__bill',
'target__bill_id',
'target__state',
'target__type',
'target__url',
]
prog_high_sim_df = (
# select valid model sentences and only consider bills
df.query(
'source__est_nwords >= @min_nwords '
'and (not target__is_model)'
)
.reset_index(drop=True)
# high similar model sentences
.assign(
source__thres_met = lambda x: x['ratio'] > thres_ratio
)
)
prog_high_sim_df = (
prog_high_sim_df
# count similar model sentences
.groupby(main_groupbys)
.agg(
num_high_sim_src_seg = ('source__thres_met', 'sum')
)
.join(
# get similar sections
(
prog_high_sim_df
.query('source__thres_met')
.groupby(main_groupbys)
.agg(
source_sections = ('source__section_label', 'unique')
)
),
how='left'
)
.reset_index()
# get % of similar model sentences
.assign(
pct_src_sim = lambda x: (
100 * x['num_high_sim_src_seg'] / x['source__model_num_valid_length']
),
)
# threshold to determine that a bill is similar to a model
.assign(
ver_has_high_sim = lambda x: (
(x['num_high_sim_src_seg'] >= min_high_sim_num_sents) |
(x['pct_src_sim'] >= min_high_sim_pct_sim)
)
)
)
prog_high_sim_df['source_sections'] = prog_high_sim_df['source_sections'].apply(
lambda x: list(x) if hasattr(x, '__len__') else []
)
# find bills with at least one version considered as similar to a model
bills_with_atleast_one_ver_sim = (
prog_high_sim_df
.query('ver_has_high_sim')
.filter(['source__model','target__bill_id'])
.drop_duplicates()
.assign(bill_has_1ver_sim=True)
)
prog_high_sim_df = (
prog_high_sim_df.merge(
bills_with_atleast_one_ver_sim,
how='left'
)
.fillna({'bill_has_1ver_sim':False})
.astype({'bill_has_1ver_sim':'bool'})
)
# version of bills with max similarity
max_sim_ver_of_bills = (
prog_high_sim_df
.query('ver_has_high_sim')
.sort_values(['pct_src_sim','target__doc_rank'])
.groupby([
'source__model',
'target__bill_id',
])
.tail(1)
.filter([
'source__model',
'target__bill_id',
'target__doc_id',
'target__doc_rank',
])
.assign(bill_max_sim_ver = True)
)
prog_high_sim_df = (
prog_high_sim_df.merge(
max_sim_ver_of_bills,
how='left'
)
.fillna({'bill_max_sim_ver':False})
.astype({'bill_max_sim_ver':'bool'})
)
return prog_high_sim_df
def construct_dfs_to_display(sim_df):
# add some display columns
sim_df['disp_model_pct_sim'] = sim_df.apply(
lambda x: '{source__model} ({pct_src_sim:.0f}%)'.format(**x),
axis=1
)
sim_df['disp_% similar'] = sim_df['pct_src_sim'].round(1)
sim_df['disp_# sentences'] = sim_df.apply(
lambda x: '{num_high_sim_src_seg} / {source__model_num_valid_length}'.format(**x),
axis=1
)
sim_df['disp_bill'] = sim_df.apply(
lambda x: '{target__bill} ({target__type})'.format(
**x,
), axis=1
)
sim_df['disp_version'] = sim_df.apply(
lambda x: 'ver. {target__doc_rank}/{target__nvers}'.format(**x),
axis=1
)
# finalize display df per model
disp_sim_df = (
sim_df
.filter(
regex='disp|source__model|source_sections|target__bill_id|target__doc_id|target__url|progress_pct_src_sim'
)
.drop(columns='source__model_num_valid_length')
)
disp_sim_df.columns = (
disp_sim_df.columns
.str.replace('disp_','')
.str.replace('source__','')
.str.replace('target__','')
)
disp_sim_df = (
disp_sim_df
.filter([
'model',
'bill',
'doc_id',
'bill_id',
'version',
'% similar',
'# sentences',
'progress_pct_src_sim',
'source_sections',
'url',
])
)
# bills similar to multiple models
multimodel_bills = (
sim_df
.groupby(['disp_bill','disp_version','target__url'])
['disp_model_pct_sim'].unique().apply(list)
.reset_index()
)
multi_model_bills = (
multimodel_bills.loc[
multimodel_bills['disp_model_pct_sim'].apply(len) > 1
]
.reset_index(drop=True)
)
multi_model_bills.columns = (
multimodel_bills.columns
.str.replace('disp_','')
.str.replace('source__','')
.str.replace('target__','')
)
sim_df.drop(
columns=sim_df.filter(regex='^disp_').columns.to_list(),
inplace=True
)
return disp_sim_df, multi_model_bills
def count_similar_bills(sim_df):
# count bills
sim_bill_counts = (
sim_df
.value_counts('source__model',ascending=True)
.reset_index()
.rename(columns={'source__model':'model'})
)
# count states
sim_state_counts = (
sim_df.pivot_table(
index='target__state',
columns='source__model',
values='target__bill',
aggfunc='nunique',
dropna=False
)
.fillna(0)
.melt(value_name='count',ignore_index=False)
.reset_index()
)
sim_state_counts.columns = (
sim_state_counts.columns
.str.replace('target__','')
.str.replace('source__','')
)
return sim_bill_counts, sim_state_counts
def count_model_sections(sim_df, section_idf):
sec_counts = (
sim_df
.filter(['source__model','source_sections', 'target__bill_id'])
.explode('source_sections')
.drop_duplicates(ignore_index=True)
.astype({'source_sections':'str','source__model':'str'})
.groupby(['source__model','source_sections'])
['target__bill_id'].nunique()
.to_frame('count')
.reset_index()
.rename(columns={
'source__model': 'model',
'source_sections':'section'
})
.merge(
section_idf,
how='right'
)
.fillna({'count':0})
)
return sec_counts
def project_bills(
df,
colored_target_bills,
min_nwords,
thres_ratio,
version_to_count,
projector='PCA'
):
projector = projector.upper()
assert projector in ['PCA','MDS']
source_cols = ['source__model']
target_cols = [
'target__bill',
'target__bill_id',
'target__is_model',
]
tgt_ver_cols = [
'target__doc_id',
'target__doc_rank',
'target__is_most_recent_doc',
]
# construct features per billver-model pair
agg_df = (
df.query('source__est_nwords >= @min_nwords')
.reset_index(drop=True)
.assign(
source__thres_met = lambda x: x['ratio'] > thres_ratio
)
.groupby(source_cols + target_cols + tgt_ver_cols)
.agg(
feat__max_ratio = ("ratio", "max"),
feat__mean_ratio = ("ratio", "mean"),
feat__pct_high_sim = ("source__thres_met", "mean"),
feat__n_seg = ("ratio", "count"),
)
.reset_index()
)
permod_feat_cols = agg_df.filter(regex='feat__').columns.to_list()
# select version to visualize
if version_to_count == 'latest':
agg_df = agg_df.query('target__is_most_recent_doc')
if version_to_count == 'max':
agg_df = (
agg_df
.sort_values('feat__pct_high_sim')
.groupby(source_cols + target_cols)
.tail(1)
)
agg_df = (
agg_df
.sort_values(['source__model','feat__pct_high_sim'])
.reset_index(drop=True)
)
# assign label
label_df = (
agg_df
.query('target__bill in @colored_target_bills')
.sort_values('feat__pct_high_sim')
.groupby(['target__bill'])
.tail(1)
.filter(['source__model', 'target__bill'])
.drop_duplicates(ignore_index=True)
.rename(columns={'source__model': 'label'})
.merge(
agg_df.filter(['target__bill','target__is_model']).drop_duplicates(ignore_index=True),
how='right'
)
.sort_values('target__bill', ignore_index=True)
)
label_df['label'] = label_df.apply(
lambda x: (
x['target__bill'] if x['target__is_model']
else x['label'] if not pd.isna(x['label'])
else 'none'
), axis=1
)
label_df['type'] = label_df.apply(
lambda x: (
'model bill' if x['target__is_model']
else 'legis. sim. to model' if x['target__bill'] in colored_target_bills
else 'legis. w/o sim.'
), axis=1
)
label_df['is-model'] = label_df.apply(
lambda x: (
'model bill' if x['target__is_model']
else 'legislation'
), axis=1
)
# construct features per bill
feat_df = agg_df.pivot(
index='target__bill',
columns='source__model',
values=permod_feat_cols
).fillna(0).astype(float)
feat_df.columns = feat_df.columns.map(
lambda x: f'{x[0]}_{x[1]}'
)
# projection
X = feat_df.values
zscore = preprocessing.StandardScaler()
Xz = zscore.fit_transform(X)
if projector == 'PCA':
proj_fn = decomposition.PCA(whiten=True)
if projector == 'MDS':
proj_fn = manifold.MDS()
X_proj = proj_fn.fit_transform(Xz)
# finalize
proj_df = pd.DataFrame({
'bill': feat_df.index.to_list(),
'PC 1': X_proj[:,0],
'PC 2': X_proj[:,1],
})
proj_df = proj_df.merge(
label_df,
how='left',
left_on='bill',
right_on='target__bill'
)
return proj_df
def process_comparisons(
df,
seg_df,
min_nwords,
thres_ratio,
min_high_sim_num_sents,
min_high_sim_pct_sim,
version_to_count
):
vercnt_alias_map = {
'Latest version': 'latest',
'Max. similar version': 'max'
}
assert version_to_count in vercnt_alias_map.keys()
version_to_count = vercnt_alias_map[version_to_count]
# valid model sentences
df = filter_valid_sentences(
df, min_nwords,
)
# similarity progress
prog_high_sim_df = process_progression(
df,
min_nwords,
thres_ratio,
min_high_sim_num_sents,
min_high_sim_pct_sim,
)
# select version
sim_df = None
if version_to_count == 'latest':
sim_df = prog_high_sim_df.query(
'target__is_most_recent_doc '
'and ver_has_high_sim'
)
if version_to_count == 'max':
sim_df = prog_high_sim_df.query(
'bill_max_sim_ver == True '
'and ver_has_high_sim'
)
assert sim_df is not None
# append the similarity progress
_prog_sim = (
prog_high_sim_df
.sort_values('target__doc_rank')
.groupby(['source__model','target__bill_id'])
['pct_src_sim'].agg(list)
.to_frame('progress_pct_src_sim')
.reset_index()
)
_prog_sim['target__nvers'] = _prog_sim['progress_pct_src_sim'].apply(len)
sim_df = sim_df.merge(_prog_sim, how='left')
# data frame to analyze
sim_df = (
sim_df
.sort_values(
['source__model','pct_src_sim'],
ascending=[True,False]
)
.reset_index(drop=True)
)
# data frames to display
disp_sim_df, multi_model_bills = construct_dfs_to_display(sim_df)
# count bills and states
sim_bill_counts, sim_state_counts = count_similar_bills(sim_df)
# counts sections
section_idf = (
seg_df
.filter(['model','section_label'])
.drop_duplicates()
.rename(columns={
'section_label':'section'
})
.astype({'section':'str','model':'str'})
)
sec_counts = count_model_sections(sim_df, section_idf)
# project bills
colored_target_bills = sim_df['target__bill'].unique()
proj_df = project_bills(
df,
colored_target_bills,
min_nwords,
thres_ratio,
version_to_count
)
return (
sim_df,
proj_df,
disp_sim_df,
multi_model_bills,
sim_bill_counts,
sim_state_counts,
sec_counts
)
def process_model_sentences(
df,
seg_df,
min_nwords,
thres_ratio,
count_ceiling=30,
cmap_name='colorbrewer:Blues'
):
cm = Colormap(cmap_name)
model_sent_df = (
df
.query(
'ratio > @thres_ratio '
'and source__est_nwords >= @min_nwords '
'and (not target__is_model)'
)
.sort_values('ratio')
.groupby([
'source__model',
'source__model_sent_idx',
'target__bill_id'
])
.tail(1)
.groupby([
'source__model',
'source__model_sent_idx'
])
['target__bill_id'].nunique()
.to_frame('bill_count')
.reset_index()
)
model_sent_df.columns = model_sent_df.columns.str.replace('source__','')
model_sent_df = (
model_sent_df
.merge(seg_df, how='right')
.fillna({'bill_count':0})
.astype({'bill_count':'int'})
)
model_sent_df = model_sent_df.merge(
model_sent_df.groupby('model')
['bill_count'].max()
.to_frame('max_count')
.reset_index()
)
model_sent_df['norm_value'] = model_sent_df.apply(
lambda x: min(
1,
x['bill_count'] / (
x['max_count'] if count_ceiling is None
else min(x['max_count'], count_ceiling)
)
), axis=1
)
model_sent_df['sentence'] = model_sent_df['sentence'].apply(
lambda x: x.replace('$',r'\$')
)
model_sent_df['color'] = [Color(x) for x in cm(model_sent_df['norm_value'])]
model_sent_df['annotations'] = model_sent_df.apply(
lambda x: (
x['sentence'] if x['bill_count'] == 0 or x['est_nwords'] < min_nwords
else (
x['sentence'],
str(x['bill_count']),
x['color'].hex,
'#ffffff' if x['color'].hsl.l < 0.5 else '#000000'
)
), axis=1
)
model_sent_df = (
model_sent_df
.groupby([
'model',
'section_idx',
'section_label',
])
['annotations'].agg(list)
.reset_index()
)
return model_sent_df
|