Compare commits
593
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc4193316f | ||
|
|
c26c3f33f5 | ||
|
|
88e0b44d54 | ||
|
|
96d63b95a2 | ||
|
|
40f44932b6 | ||
|
|
9c1ae2737e | ||
|
|
4c8255e600 | ||
|
|
99dbd3ba47 | ||
|
|
4701f1ee87 | ||
|
|
6a929588c6 | ||
|
|
da63bff8d3 | ||
|
|
f790b2cb3e | ||
|
|
eb61f1a8b0 | ||
|
|
04c4f033f7 | ||
|
|
27433efe72 | ||
|
|
05eb4c49f7 | ||
|
|
ab87b87072 | ||
|
|
2878667727 | ||
|
|
68f1cae4d9 | ||
|
|
bd4305e0eb | ||
|
|
46bf66c910 | ||
|
|
1bfa0f113d | ||
|
|
1482e3fdc5 | ||
|
|
3f4b032e34 | ||
|
|
56ada07d97 | ||
|
|
2f509fbbfe | ||
|
|
2c03f53604 | ||
|
|
6609b64076 | ||
|
|
a1889f13f6 | ||
|
|
0854c16a0b | ||
|
|
50ff313a57 | ||
|
|
84073854bf | ||
|
|
9440605a6f | ||
|
|
24b7364894 | ||
|
|
767f532e6f | ||
|
|
a21d5eaea4 | ||
|
|
d8de0c2156 | ||
|
|
ba1c53b642 | ||
|
|
ef00947786 | ||
|
|
9a4a4de379 | ||
|
|
04e3f97b8b | ||
|
|
2bf8e03117 | ||
|
|
1219970ba8 | ||
|
|
5c50c29760 | ||
|
|
5343c3204d | ||
|
|
613640a730 | ||
|
|
3147de9fcb | ||
|
|
7d3792c7b4 | ||
|
|
eb5d6830a5 | ||
|
|
7da36d8777 | ||
|
|
21482f3c6f | ||
|
|
b772b100d5 | ||
|
|
bbce780609 | ||
|
|
d719a34ab0 | ||
|
|
57d0daa21b | ||
|
|
1ca3db5c78 | ||
|
|
c85d3fa03f | ||
|
|
ffc02a4e59 | ||
|
|
6c20dc2b58 | ||
|
|
24cc476dbe | ||
|
|
b2f55bd05a | ||
|
|
e153e2d74a | ||
|
|
171b296c2a | ||
|
|
435c4ae3db | ||
|
|
ac6b5aa72b | ||
|
|
e8be0ae8aa | ||
|
|
17e0909d69 | ||
|
|
3aa4c478f6 | ||
|
|
9ef9e334fd | ||
|
|
e7269c6bd2 | ||
|
|
5aff658c16 | ||
|
|
a40aca3dbe | ||
|
|
95662119b1 | ||
|
|
5b59aca4e6 | ||
|
|
83c809983c | ||
|
|
f5cd79a718 | ||
|
|
81b7e04b66 | ||
|
|
25cf39ff69 | ||
|
|
9a6bae2df4 | ||
|
|
6eb159cc03 | ||
|
|
6b7a036128 | ||
|
|
da70af9163 | ||
|
|
09e5af0016 | ||
|
|
203d9cb6d4 | ||
|
|
dde38bb680 | ||
|
|
e7b6255e54 | ||
|
|
0f9991b618 | ||
|
|
ac97c9f496 | ||
|
|
8261de4a02 | ||
|
|
f69b3cf871 | ||
|
|
6e7a8237ef | ||
|
|
c8e5a65f5d | ||
|
|
a6c4668d13 | ||
|
|
4338b1cc0e | ||
|
|
d5164f9863 | ||
|
|
86fc87f507 | ||
|
|
156e31643c | ||
|
|
dbe8f2449a | ||
|
|
9c593a0d09 | ||
|
|
a21030309e | ||
|
|
a8db8194cf | ||
|
|
ce218cbfa1 | ||
|
|
ae80f0f812 | ||
|
|
df5f131320 | ||
|
|
2f22240d94 | ||
|
|
77095c8549 | ||
|
|
c733442300 | ||
|
|
fed1e56c81 | ||
|
|
e0d1f0df5c | ||
|
|
27301bf6a5 | ||
|
|
bbd4ff8685 | ||
|
|
dbc53a9a49 | ||
|
|
0f0f30f08c | ||
|
|
6c3c43ef4f | ||
|
|
a5f6ccc75b | ||
|
|
cfa2c768eb | ||
|
|
54e0701698 | ||
|
|
4a61c00642 | ||
|
|
49c45cb924 | ||
|
|
ad14f60a2c | ||
|
|
2bcd1d4586 | ||
|
|
5d2d694a20 | ||
|
|
dc31b21dac | ||
|
|
d28a662da3 | ||
|
|
8a418a99b4 | ||
|
|
17100024e5 | ||
|
|
9b95728c7b | ||
|
|
4937889968 | ||
|
|
36773c4ae2 | ||
|
|
353d938d3e | ||
|
|
f02e510847 | ||
|
|
6e0acb9cde | ||
|
|
a0fdc8799b | ||
|
|
f4656fcf39 | ||
|
|
d73ee592ea | ||
|
|
c6e1051059 | ||
|
|
014364ec03 | ||
|
|
024724b51d | ||
|
|
7798cdaea5 | ||
|
|
a1b9f5a084 | ||
|
|
6f79733b3e | ||
|
|
9cb01cab45 | ||
|
|
fc30865f34 | ||
|
|
b2a8af532d | ||
|
|
bee9b6e8fd | ||
|
|
8d7323a387 | ||
|
|
6a6ec8662c | ||
|
|
c70e6bf489 | ||
|
|
82fa2e816b | ||
|
|
fbcee778d2 | ||
|
|
1758227f1e | ||
|
|
cbd2e902a7 | ||
|
|
2cb6d1f660 | ||
|
|
ae2230ff0e | ||
|
|
12914208cd | ||
|
|
abb11077de | ||
|
|
ef1a5ad7a1 | ||
|
|
ed919832d8 | ||
|
|
ef2ea46882 | ||
|
|
da9516331e | ||
|
|
bd581e6004 | ||
|
|
e37f636236 | ||
|
|
0ec47e42e4 | ||
|
|
1369a2bf29 | ||
|
|
e0704bc8a5 | ||
|
|
d8041751c5 | ||
|
|
87b283ccfb | ||
|
|
16d44a0b88 | ||
|
|
07f8e8bcca | ||
|
|
cbfa60ae46 | ||
|
|
89ce894066 | ||
|
|
66487c20e7 | ||
|
|
08bc87e764 | ||
|
|
22afd0fbb5 | ||
|
|
5633b412d4 | ||
|
|
bd030ccb9f | ||
|
|
41037efd6f | ||
|
|
81c4094708 | ||
|
|
6382987990 | ||
|
|
3276bf46a7 | ||
|
|
da1a5b732d | ||
|
|
5702223716 | ||
|
|
21da33be11 | ||
|
|
545f38bc3d | ||
|
|
92e421a61c | ||
|
|
15f55af4c4 | ||
|
|
8b150a81a0 | ||
|
|
91efbdffeb | ||
|
|
c8fa70e7f0 | ||
|
|
934c49bf49 | ||
|
|
70d6b3d698 | ||
|
|
e6e9628837 | ||
|
|
0dd2a5743d | ||
|
|
f8678af87e | ||
|
|
5e7f968808 | ||
|
|
e1b3318e68 | ||
|
|
4d8a7405ca | ||
|
|
f1a6c32e0c | ||
|
|
cf5a3e7d3d | ||
|
|
89f45082fb | ||
|
|
0ad6ac70ff | ||
|
|
e8e0decc6c | ||
|
|
57aaf77162 | ||
|
|
a3eebedb02 | ||
|
|
f8e5cd90a5 | ||
|
|
07ce24143b | ||
|
|
3d092b02f3 | ||
|
|
bf5e065520 | ||
|
|
08178e74d2 | ||
|
|
c66fcff906 | ||
|
|
b0dd0e509d | ||
|
|
719da6e921 | ||
|
|
e4b3d0a9a9 | ||
|
|
c0e231a32b | ||
|
|
af9f9a25da | ||
|
|
0a465bc7e1 | ||
|
|
aec735e09e | ||
|
|
9ce6d5f26e | ||
|
|
f4b4fb0562 | ||
|
|
aa22fad67d | ||
|
|
548bb4ce70 | ||
|
|
b6871b3618 | ||
|
|
fe5e816551 | ||
|
|
20d2a281b1 | ||
|
|
e2ae0c660a | ||
|
|
9e8ae16597 | ||
|
|
e5284a79c9 | ||
|
|
79dad5dfb0 | ||
|
|
a511c16fb1 | ||
|
|
98a1214a4d | ||
|
|
be459c45cf | ||
|
|
328ef2938c | ||
|
|
21f3f49078 | ||
|
|
882ad3b8cf | ||
|
|
d8b7d8bc2e | ||
|
|
c1692535a5 | ||
|
|
af0e326747 | ||
|
|
6cdaa9738a | ||
|
|
1e5d0c4517 | ||
|
|
127f5ca287 | ||
|
|
f51b775fd9 | ||
|
|
0015b92591 | ||
|
|
37e1f1811f | ||
|
|
deb6448739 | ||
|
|
bfb3224684 | ||
|
|
aed1f33935 | ||
|
|
33192efa33 | ||
|
|
d48435b948 | ||
|
|
daa4f79ea0 | ||
|
|
07bb754566 | ||
|
|
c70a566514 | ||
|
|
b99d3a7ff1 | ||
|
|
30cbb080b0 | ||
|
|
d8eec59d5d | ||
|
|
be89e2986b | ||
|
|
916af84651 | ||
|
|
567b5ecd4f | ||
|
|
b21d8d3e88 | ||
|
|
4e5ab529de | ||
|
|
3b1ffda3b2 | ||
|
|
cdf58044a8 | ||
|
|
727c3fde67 | ||
|
|
de880fb9f0 | ||
|
|
e9fdf7d538 | ||
|
|
57f221868d | ||
|
|
ae7d1a54cb | ||
|
|
71b075b365 | ||
|
|
c054cf99fe | ||
|
|
98a742f024 | ||
|
|
fb40bc548e | ||
|
|
d06c1954a5 | ||
|
|
545d487fea | ||
|
|
62f0812aae | ||
|
|
e0dda3ea0c | ||
|
|
7628f219e2 | ||
|
|
1d7a54c866 | ||
|
|
6c55493acb | ||
|
|
42bcac251b | ||
|
|
bb791138cd | ||
|
|
1fc509ea13 | ||
|
|
90a1b930a3 | ||
|
|
9011d58355 | ||
|
|
f2c0f203f6 | ||
|
|
3f5746dd7d | ||
|
|
adce95ead4 | ||
|
|
84d7ca0122 | ||
|
|
053af573fc | ||
|
|
06f34bec45 | ||
|
|
c1641fdb38 | ||
|
|
9115af350e | ||
|
|
77cf3612d9 | ||
|
|
07c7343f94 | ||
|
|
530f751f02 | ||
|
|
9a005cabe9 | ||
|
|
f7eb502d9d | ||
|
|
a407cfb514 | ||
|
|
ff43d07b6d | ||
|
|
340b5f22b7 | ||
|
|
b4a90131bb | ||
|
|
90149ddb4e | ||
|
|
1f09f0cf68 | ||
|
|
8035e7aecb | ||
|
|
cea32deba2 | ||
|
|
b02358e3a0 | ||
|
|
79320f27c9 | ||
|
|
52ca2f7339 | ||
|
|
78e54248e3 | ||
|
|
fc82604947 | ||
|
|
40bb0feaf8 | ||
|
|
0afb6a9481 | ||
|
|
57f72a473f | ||
|
|
876fbb9980 | ||
|
|
bee09f7c29 | ||
|
|
c31aef4131 | ||
|
|
53a36e7974 | ||
|
|
60e74c4916 | ||
|
|
1d24f912ae | ||
|
|
f9591c512c | ||
|
|
f74396e97b | ||
|
|
1127eeebb8 | ||
|
|
e9590e8b04 | ||
|
|
fd0bc89771 | ||
|
|
32a38b46fe | ||
|
|
e5f9d8cfdf | ||
|
|
0b6a74a8e3 | ||
|
|
da59e8137f | ||
|
|
ecd6b30626 | ||
|
|
31da701fe7 | ||
|
|
9d875b3935 | ||
|
|
8cab4ffb42 | ||
|
|
61aeb5bf86 | ||
|
|
0821008d6e | ||
|
|
a4a24b77b9 | ||
|
|
897edab3cf | ||
|
|
a25d70466f | ||
|
|
4270dafd6a | ||
|
|
fc3baef406 | ||
|
|
be20407238 | ||
|
|
26c4dc8fe7 | ||
|
|
4dd124d003 | ||
|
|
ee40f1386a | ||
|
|
4f116d3ca2 | ||
|
|
9ef1ce7ce1 | ||
|
|
641f40ff45 | ||
|
|
6f0d17a991 | ||
|
|
2d1155d46b | ||
|
|
a1cf6e06af | ||
|
|
2e4a861e9c | ||
|
|
70e4ad71a6 | ||
|
|
dc27b49f63 | ||
|
|
b8707c7619 | ||
|
|
b251abb79f | ||
|
|
14be6c1a6c | ||
|
|
7addfe2a71 | ||
|
|
2474700473 | ||
|
|
0150f81a24 | ||
|
|
8a801d0bb5 | ||
|
|
496d2c88f0 | ||
|
|
9d8b287c13 | ||
|
|
94e0cad2d0 | ||
|
|
8be123bf3a | ||
|
|
570da1b47c | ||
|
|
02dd286d55 | ||
|
|
58199760de | ||
|
|
17b59213d3 | ||
|
|
06e2785914 | ||
|
|
0aea390e5e | ||
|
|
c33a900c66 | ||
|
|
f36e9a7d54 | ||
|
|
7259e3a0c0 | ||
|
|
b0581ad452 | ||
|
|
813953f1f5 | ||
|
|
288b21d407 | ||
|
|
01453f73dc | ||
|
|
410f1ade01 | ||
|
|
621a9dd2a1 | ||
|
|
18b9b8bf67 | ||
|
|
3f1ea0a418 | ||
|
|
211f7b82dc | ||
|
|
6675976feb | ||
|
|
034d3ee453 | ||
|
|
faa866f4e1 | ||
|
|
9c3e36930c | ||
|
|
d4daecd921 | ||
|
|
9f10e9e7af | ||
|
|
fa9def349c | ||
|
|
4073214131 | ||
|
|
03fac2a656 | ||
|
|
a204584ddd | ||
|
|
25de01c7be | ||
|
|
176235689f | ||
|
|
f27ee8b295 | ||
|
|
32616fe6aa | ||
|
|
9a5cb9e9b0 | ||
|
|
d11869c70b | ||
|
|
abb8c9dbb5 | ||
|
|
b8442213f8 | ||
|
|
0d19abb293 | ||
|
|
74587f5c6d | ||
|
|
6ea3e79087 | ||
|
|
ba72b146a2 | ||
|
|
0f360c86b2 | ||
|
|
ecf7a6f905 | ||
|
|
345dffaa9b | ||
|
|
7b912196e9 | ||
|
|
6e4742206f | ||
|
|
a28ecc9d02 | ||
|
|
53397f844e | ||
|
|
818398ccda | ||
|
|
a6c7068ca6 | ||
|
|
4785bb4d40 | ||
|
|
1a9f9496fd | ||
|
|
78f35daa58 | ||
|
|
b2e70c2bb3 | ||
|
|
3d8ceeb5b6 | ||
|
|
0b8540d70b | ||
|
|
e9ccfe6796 | ||
|
|
e20f2732b3 | ||
|
|
4da4ea1bff | ||
|
|
93ba39f9b0 | ||
|
|
0642a3704d | ||
|
|
57e1bafa8b | ||
|
|
3d5eb524aa | ||
|
|
c15afed0aa | ||
|
|
b133ce80c9 | ||
|
|
ae8332dc3d | ||
|
|
026a35dd90 | ||
|
|
5fdc1cdce3 | ||
|
|
02bb8b8fb8 | ||
|
|
27f289f4a0 | ||
|
|
6af1747477 | ||
|
|
401b82c226 | ||
|
|
9d128e18b6 | ||
|
|
a6a78bb556 | ||
|
|
bc59c3f563 | ||
|
|
8b7ac08192 | ||
|
|
4fe78c2b88 | ||
|
|
2e8dd00aa6 | ||
|
|
127eed5c49 | ||
|
|
7a84fc2b12 | ||
|
|
96e0925054 | ||
|
|
730ee7f89a | ||
|
|
e62d1ca458 | ||
|
|
6bca5643ee | ||
|
|
db20b23ff3 | ||
|
|
66f34668a9 | ||
|
|
ceadc26741 | ||
|
|
3a74dc9b7b | ||
|
|
4a47d752cb | ||
|
|
1bca6648bd | ||
|
|
af00bc4635 | ||
|
|
def210b4b9 | ||
|
|
89bdab0a26 | ||
|
|
448922d907 | ||
|
|
3ef8c28191 | ||
|
|
46aee46ea3 | ||
|
|
e57875d2a5 | ||
|
|
28726cf4c7 | ||
|
|
b0e4ad639e | ||
|
|
1810918e43 | ||
|
|
a736539851 | ||
|
|
591233e255 | ||
|
|
c2a2a31fb9 | ||
|
|
d4a4bfa2c7 | ||
|
|
3a127450e3 | ||
|
|
c2f9a6381a | ||
|
|
7adf12912f | ||
|
|
0b2b05ae85 | ||
|
|
127c32dce7 | ||
|
|
652ff8db15 | ||
|
|
79c1076272 | ||
|
|
d29028a5bd | ||
|
|
8cba5387c7 | ||
|
|
bdb546db12 | ||
|
|
59ed0ad1a4 | ||
|
|
3d57dda846 | ||
|
|
6cdf5f4704 | ||
|
|
9f4bb77208 | ||
|
|
aa05beb594 | ||
|
|
6c2e3fab04 | ||
|
|
be556f09ad | ||
|
|
2fc9722914 | ||
|
|
9e39650899 | ||
|
|
1860e7c371 | ||
|
|
e5283543a1 | ||
|
|
bf5d626209 | ||
|
|
424649ecdc | ||
|
|
11ac6525c1 | ||
|
|
8a684c8b57 | ||
|
|
4805fe9c3c | ||
|
|
90ec5c2c8d | ||
|
|
cbbcaa2325 | ||
|
|
e6eabf08c9 | ||
|
|
b616d061bb | ||
|
|
3a78519655 | ||
|
|
c6de85d4a0 | ||
|
|
71fe4a54e7 | ||
|
|
02b498f829 | ||
|
|
18f661e3b4 | ||
|
|
22bfb2feba | ||
|
|
358a47bbf5 | ||
|
|
ceed96102f | ||
|
|
467f40a625 | ||
|
|
e8b5dcfd5b | ||
|
|
f0caacd696 | ||
|
|
e7afd7e68a | ||
|
|
9d24c0a9bb | ||
|
|
f25c5cd222 | ||
|
|
0b5c6bed37 | ||
|
|
2d485263d1 | ||
|
|
103b6180d0 | ||
|
|
6edca93c1c | ||
|
|
a7548d59c0 | ||
|
|
8b1f7d6eb3 | ||
|
|
ff3ac03520 | ||
|
|
e51d3095bc | ||
|
|
d19003d531 | ||
|
|
6d5dd88e50 | ||
|
|
de70973296 | ||
|
|
2a5f104739 | ||
|
|
71bd10b303 | ||
|
|
82d2c508b8 | ||
|
|
97b7fe6a6f | ||
|
|
ddbf000213 | ||
|
|
eb84d3014f | ||
|
|
2bdee21169 | ||
|
|
ee98b589c9 | ||
|
|
4e0afc12ed | ||
|
|
fa68c338c2 | ||
|
|
0712d3f3fa | ||
|
|
a278ad300f | ||
|
|
3d78ec900e | ||
|
|
fc134dad8e | ||
|
|
59a1f765d0 | ||
|
|
6cccd6d19f | ||
|
|
16f7e665fe | ||
|
|
e78b406d6d | ||
|
|
292c02cac8 | ||
|
|
ff322fc29b | ||
|
|
1a01ff5198 | ||
|
|
c47d5ee170 | ||
|
|
afaa840d48 | ||
|
|
fb44e9db3c | ||
|
|
762e3f9a15 | ||
|
|
0dd2023224 | ||
|
|
d4880b417b | ||
|
|
a7ced052dd | ||
|
|
0b3be35885 | ||
|
|
5323797c71 | ||
|
|
9ac618ebec | ||
|
|
de6339586f | ||
|
|
97c9e2eec3 | ||
|
|
167913aa85 | ||
|
|
85e79aeb3e | ||
|
|
83ed0bcaee | ||
|
|
807adbd6e4 | ||
|
|
18c9785325 | ||
|
|
8db323d605 | ||
|
|
f4e0888ce2 | ||
|
|
712fcbb749 | ||
|
|
cb5a887d12 | ||
|
|
755f83f65a | ||
|
|
4bd4a015f1 | ||
|
|
d3266ee50e | ||
|
|
55d0b7918f | ||
|
|
b22f16809d | ||
|
|
b9c4067250 | ||
|
|
90860230f4 | ||
|
|
d005162a80 | ||
|
|
0f65a0f589 | ||
|
|
410bcdec4b | ||
|
|
b39daba561 | ||
|
|
53155d4e53 | ||
|
|
8583f6622e | ||
|
|
93481bf9c5 | ||
|
|
a76789f34b | ||
|
|
2566fa9208 | ||
|
|
577b9f4557 | ||
|
|
e92b450e5b | ||
|
|
5d72140758 | ||
|
|
bee19dfa39 | ||
|
|
3b4d0b3339 | ||
|
|
e5f28f2143 | ||
|
|
069566d71d | ||
|
|
07278b3f65 | ||
|
|
3684a5acf5 | ||
|
|
5ce97e6854 | ||
|
|
8bb0cf18ad | ||
|
|
19933d69b6 | ||
|
|
9aeb8171a7 | ||
|
|
f4542d21b8 | ||
|
|
532c94b00b | ||
|
|
5d1d62acb8 |
@@ -0,0 +1,15 @@
|
||||
*
|
||||
!background-jobs
|
||||
!service
|
||||
service/*
|
||||
!service/scripts
|
||||
|
||||
# Data-only folders that do not belong in the job image.
|
||||
service/scripts/multipliers
|
||||
|
||||
**/__pycache__
|
||||
**/*.pyc
|
||||
**/.venv
|
||||
**/.env
|
||||
**/.env.*
|
||||
**/out
|
||||
+3
-1
@@ -19,4 +19,6 @@ angular-app/.angular
|
||||
# Ignore sentence-transformer local model cache
|
||||
service/sentence_transformer/models/
|
||||
|
||||
llm_evaluations/bio_generation/.venv
|
||||
llm_evaluations/bio_generation/.venv
|
||||
|
||||
.devcontainer
|
||||
|
||||
@@ -5,7 +5,6 @@ from typing import Any
|
||||
|
||||
from openalex_client import get_all_author_works
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_sample.csv"
|
||||
OUTPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Callable, Literal
|
||||
from typing import Literal
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
PLOTS_DIR = BASE_DIR / "plots"
|
||||
|
||||
@@ -4,7 +4,6 @@ from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
OPENALEX_WORKS_URL = "https://api.openalex.org/works"
|
||||
REQUEST_TIMEOUT_SECONDS = 30
|
||||
PER_PAGE = 200
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
.env
|
||||
.env.*
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
@@ -0,0 +1,7 @@
|
||||
# Copy this file to `.env` and fill in the real values.
|
||||
# `.env` is gitignored and is NOT baked into the image.
|
||||
INSE_ELASTIC_URL=https://inse.nes.uni-due.de/elastic
|
||||
INSE_ELASTIC_API_KEY=your-elastic-api-key-here
|
||||
INSE_LLM_BASE_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||
INSE_LLM_API_KEY=your-llm-api-key-here
|
||||
INSE_LLM_MODEL=gemma4-e4b
|
||||
@@ -0,0 +1,5 @@
|
||||
# Local secrets – never commit
|
||||
.env
|
||||
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -0,0 +1,95 @@
|
||||
# Background Jobs
|
||||
|
||||
Background Jobs sind Docker-Container, die regelmäßig oder manuell Elasticsearch-Daten verarbeiten. Sie werden vom Backend über den Docker-Socket gestartet.
|
||||
|
||||
**Wichtig:** Jobs sind in der **Datenbank**, nicht im Image. Das Image enthält nur die ausführbaren Skripte.
|
||||
|
||||
## Jobs anlegen
|
||||
|
||||
**Frontend** (`/jobs`):
|
||||
|
||||
- "Neuer Job" → Name + Command + optionales Image + Zeitplan
|
||||
|
||||
**API**:
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: Bearer $TOKEN" \
|
||||
-d '{"name": "Sync", "command": "python sync.py --sync-delta", "schedule": "0 3 * * *"}' \
|
||||
http://localhost:8000/api/background-jobs/tasks
|
||||
```
|
||||
|
||||
Command-Beispiele:
|
||||
|
||||
```
|
||||
python service/scripts/demo/demo.py 20
|
||||
python sync.py --sync-delta
|
||||
python service/scripts/news/ude/run_pipeline.py --skip-upload --max-items 5
|
||||
python -m service.scripts.news.topic_mapper.map_news_topics --output-index docker-job_test --max-docs 50
|
||||
python -m service.scripts.projects.topic_mapper.map_project_topics --dry-run
|
||||
sh -c "cd service/scripts/projects/bund && python gpc.data.py --skip-upload"
|
||||
```
|
||||
|
||||
**Neue Jobs = kein Image-Rebuild.** Die Skripte sind bereits im Image; der Command wird direkt an Docker übergeben.
|
||||
|
||||
## Image & Dockerfile
|
||||
|
||||
Das [Dockerfile](../service/scripts/jobs-image/Dockerfile) kopiert den kompletten `service/scripts/`-Baum (Pfade im Container = Pfade im Repo) plus `background-jobs/app/` (sync.py) und hat keinen ENTRYPOINT. Neue Skripte unter `service/scripts` landen automatisch im nächsten Build — ohne Dockerfile-Änderung. Der Backend startet Container direkt:
|
||||
|
||||
```python
|
||||
docker.run(image="...", command="python sync.py --sync-delta")
|
||||
```
|
||||
|
||||
**Skripte hinzugefügt oder geändert?** → Image neu bauen + pushen:
|
||||
|
||||
```bash
|
||||
docker build -f service/scripts/jobs-image/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest .
|
||||
docker push docker.nes.uni-due.de/inse/background-jobs:latest
|
||||
```
|
||||
|
||||
Lokal testen ohne Pull:
|
||||
|
||||
```bash
|
||||
export BACKGROUND_JOBS_PULL_BEFORE_RUN=false
|
||||
```
|
||||
|
||||
## Scheduling
|
||||
|
||||
Job mit `schedule: "0 3 * * *"` und `enabled: true` läuft automatisch täglich um 3:00 UTC. Manuell starten: "Jetzt ausführen" Button oder API.
|
||||
|
||||
## Logs
|
||||
|
||||
Während Laufzeit: Live vom Container. Nach Beendigung: Letzte 200 Zeilen in der DB. Frontend: "Logs anzeigen" Button.
|
||||
|
||||
## Docker-Socket (Deployment)
|
||||
|
||||
```yaml
|
||||
# docker-compose
|
||||
backend:
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
```
|
||||
|
||||
Ohne Socket-Mount funktioniert nichts.
|
||||
|
||||
## Env-Variablen
|
||||
|
||||
Standard-Image erhält automatisch:
|
||||
|
||||
- `INSE_ELASTIC_URL`, `INSE_ELASTIC_API_KEY`
|
||||
- `INSE_LLM_*`, `ELASTICSEARCH_INSE_*`, `SENTENCE_TRANSFORMERS_MODEL_NAME`
|
||||
|
||||
Plus `env` aus der Job-Definition.
|
||||
|
||||
**Eigene Images** bekommen nur die `env`-Variablen (Sicherheit).
|
||||
|
||||
## API
|
||||
|
||||
- `GET /api/background-jobs/tasks` — Jobs auflisten
|
||||
- `POST /api/background-jobs/tasks` — Job anlegen
|
||||
- `DELETE /api/background-jobs/tasks/{id}` — Job löschen
|
||||
- `POST /api/background-jobs/tasks/{id}/run` — Run starten
|
||||
- `PATCH /api/background-jobs/tasks/{id}` — Schedule ändern
|
||||
- `GET /api/background-jobs/runs/{id}/logs` — Logs abrufen
|
||||
- `POST /api/background-jobs/runs/{id}/stop` — Run stoppen
|
||||
|
||||
Alle Endpoints erfordern Superadmin-Auth.
|
||||
@@ -0,0 +1,152 @@
|
||||
import os
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
load_dotenv()
|
||||
|
||||
INSE_URL = os.getenv("INSE_ELASTIC_URL", "https://inse.nes.uni-due.de/elastic")
|
||||
INSE_API_KEY = os.getenv("INSE_ELASTIC_API_KEY")
|
||||
if not INSE_API_KEY:
|
||||
raise RuntimeError(
|
||||
"INSE_ELASTIC_API_KEY is not set. Copy .env.example to .env and fill it in, "
|
||||
"or pass it as an environment variable."
|
||||
)
|
||||
|
||||
ES_HEADERS = {
|
||||
"Authorization": f"ApiKey {INSE_API_KEY}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
_session = requests.Session()
|
||||
_session.headers.update(ES_HEADERS)
|
||||
_adapter = HTTPAdapter(pool_connections=32, pool_maxsize=32)
|
||||
_session.mount("https://", _adapter)
|
||||
_session.mount("http://", _adapter)
|
||||
|
||||
def _send_es_request(method: str, url: str, payload: dict = None) -> dict:
|
||||
|
||||
try:
|
||||
response = _session.request(
|
||||
method=method,
|
||||
url=url,
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as error:
|
||||
print(f"Send Request failed: ({method} {url}): {error}")
|
||||
raise
|
||||
|
||||
def add_entry(index: str, entry: dict):
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_doc"
|
||||
|
||||
document_body = {
|
||||
"news_id": entry["news_id"],
|
||||
"relevant": int(entry["relevant"]),
|
||||
"authors": entry["authors"],
|
||||
"keywords": entry.get("keywords", []),
|
||||
}
|
||||
|
||||
response_data = _send_es_request("POST", endpoint, payload=document_body)
|
||||
|
||||
created_id = response_data["_id"]
|
||||
entry["_id"] = created_id
|
||||
|
||||
return created_id
|
||||
|
||||
def index_entry(index: str, document_id: str, entry: dict):
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
|
||||
|
||||
document_body = {
|
||||
"news_id": entry["news_id"],
|
||||
"relevant": int(entry["relevant"]),
|
||||
"authors": entry["authors"],
|
||||
"keywords": entry.get("keywords", []),
|
||||
}
|
||||
|
||||
return _send_es_request("PUT", endpoint, payload=document_body)
|
||||
|
||||
def update_entry(index: str, document_id: str, partial_doc: dict):
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}"
|
||||
|
||||
return _send_es_request("POST", endpoint, payload={"doc": partial_doc})
|
||||
|
||||
def get_entry(index: str, document_id: str) -> dict:
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
|
||||
|
||||
return _send_es_request("GET", endpoint)
|
||||
|
||||
def delete_entry(index: str, document_id: str):
|
||||
|
||||
encoded_document_id = quote(document_id, safe="")
|
||||
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
|
||||
|
||||
return _send_es_request("DELETE", endpoint)
|
||||
|
||||
def get_all_entries(index: str, fields: list = None) -> list:
|
||||
|
||||
if not fields:
|
||||
source_fields = True
|
||||
else:
|
||||
source_fields = fields
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_search"
|
||||
|
||||
page_size = 1000
|
||||
results = []
|
||||
last_sort_value = None
|
||||
|
||||
while True:
|
||||
payload = {
|
||||
"query": {"match_all": {}},
|
||||
"size": page_size,
|
||||
"sort": [{"_doc": "asc"}],
|
||||
"_source": source_fields,
|
||||
}
|
||||
if last_sort_value is not None:
|
||||
payload["search_after"] = last_sort_value
|
||||
|
||||
response_data = _send_es_request("POST", endpoint, payload=payload)
|
||||
results_list = response_data["hits"]["hits"]
|
||||
|
||||
if not results_list:
|
||||
break
|
||||
|
||||
results.extend(results_list)
|
||||
last_sort_value = results_list[-1]["sort"]
|
||||
|
||||
return results
|
||||
|
||||
def delete_all_entries(index: str):
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_delete_by_query"
|
||||
|
||||
payload = {
|
||||
"query": {"match_all": {}}
|
||||
}
|
||||
|
||||
return _send_es_request("POST", endpoint, payload=payload)
|
||||
|
||||
def remove_field_all(index: str, field: str):
|
||||
|
||||
endpoint = f"{INSE_URL}/{index}/_update_by_query"
|
||||
|
||||
payload = {
|
||||
"query": {"exists": {"field": field}},
|
||||
"script": {
|
||||
"source": f"ctx._source.remove('{field}')",
|
||||
"lang": "painless",
|
||||
},
|
||||
}
|
||||
|
||||
return _send_es_request("POST", endpoint, payload=payload)
|
||||
@@ -0,0 +1,95 @@
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
load_dotenv()
|
||||
|
||||
LLM_BASE_URL = os.getenv("INSE_LLM_BASE_URL", "https://project.nes.uni-due.de/llm2/v1/")
|
||||
LLM_API_KEY = os.getenv("INSE_LLM_API_KEY")
|
||||
if not LLM_API_KEY:
|
||||
raise RuntimeError(
|
||||
"INSE_LLM_API_KEY is not set. Copy .env.example to .env and fill it in, "
|
||||
"or pass it as an environment variable."
|
||||
)
|
||||
LLM_MODEL = os.getenv("INSE_LLM_MODEL", "gemma4-e4b")
|
||||
|
||||
SYSTEM_PROMPT_RELEVANT = ("""
|
||||
Du bewertest Nachrichtenartikel aus dem Campus-Aktuell-Bereich der Universität Duisburg-Essen.
|
||||
Entscheide, ob der Artikel inhaltlich über eine konkrete Person berichtet, also über deren Werdegang, Forschung, Leistung, Auszeichnung oder Tätigkeit.
|
||||
Falls du dir unsicher bist, ob eine Person im Mittelpunkt steht, dann entscheide dich bitte für die positivere Option (also 1), damit die Namensextraktion auf keinen Fall bei Artikeln mit Personenbezug versäumt wird.
|
||||
Antworte mit 1, wenn eine konkrete Person im Mittelpunkt steht.
|
||||
Antworte mit 0, wenn es sich um allgemeine Mitteilungen handelt, die keine einzelne Person in den Mittelpunkt stellen, zum Beispiel Veranstaltungs- und Terminhinweise, Spendenaufrufe, organisatorische Ankündigungen, allgemeine Universitätsinformationen oder Pressemitteilungen ohne Personenbezug.
|
||||
Die bloße Nennung von Namen (etwa als Autor oder Ansprechpartner) reicht für eine 1 nicht aus; die Person muss inhaltlich Thema des Artikels sein.
|
||||
Antworte ausschließlich mit einer einzigen Ziffer: 0 oder 1.
|
||||
""")
|
||||
|
||||
SYSTEM_PROMPT_NAMES = ("""
|
||||
Aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen: Nenne die Namen aller konkreten Personen, um die es im Artikel inhaltlich geht.
|
||||
Es können mehrere Personen sein. Bitte achte darauf dass du nur die Namen der Personen nennst, die tatsächlich im Mittelpunkt des Artikels stehen.
|
||||
Insbesondere am Ende von Artikeln werden oft Personen genannt, die nur als Ansprechpartner oder Organisator und sollen deshalb nicht genannt werden.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"person\": [\"Vorname Nachname\", \"Vorname Nachname\"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
SYSTEM_PROMPT_KEYWORDS = ("""
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
_client = OpenAI(
|
||||
base_url=LLM_BASE_URL,
|
||||
api_key=LLM_API_KEY,
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.95):
|
||||
try:
|
||||
response = _client.chat.completions.create(
|
||||
model=model,
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
extra_body={"top_k": 64},
|
||||
)
|
||||
except APIConnectionError:
|
||||
return None
|
||||
|
||||
return response.choices[0].message.content or None
|
||||
|
||||
def is_news_relevant(text: str) -> bool:
|
||||
result = call(SYSTEM_PROMPT_RELEVANT, text)
|
||||
if result is None:
|
||||
return False
|
||||
return result.strip() == "1"
|
||||
|
||||
def extract_names(text: str) -> list[str]:
|
||||
result = call(SYSTEM_PROMPT_NAMES, text)
|
||||
if result is None:
|
||||
return []
|
||||
try:
|
||||
import json
|
||||
data = json.loads(result)
|
||||
return data.get("person", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
def extract_keywords(text: str) -> list[str]:
|
||||
result = call(SYSTEM_PROMPT_KEYWORDS, text)
|
||||
if result is None:
|
||||
return []
|
||||
try:
|
||||
import json
|
||||
data = json.loads(result)
|
||||
return data.get("keywords", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
@@ -0,0 +1,247 @@
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
import elastic.client as es_client
|
||||
import llm.client as llm_client
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
POSTPROC_INDEX = "aktuell_postproc"
|
||||
|
||||
def print_pretty_json(data):
|
||||
logger.info(json.dumps(data, indent=2))
|
||||
|
||||
def sync_single_news(news_id, max_retries=3):
|
||||
attempt = 0
|
||||
while attempt < max_retries:
|
||||
try:
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
is_news_relevant = llm_client.is_news_relevant(news_text)
|
||||
authors = llm_client.extract_names(news_text)
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
new_entry = {
|
||||
"news_id": news_id,
|
||||
"relevant": is_news_relevant,
|
||||
"authors": authors,
|
||||
"keywords": keywords,
|
||||
}
|
||||
es_client.add_entry("aktuell_postproc", new_entry)
|
||||
return True
|
||||
except Exception as error:
|
||||
attempt += 1
|
||||
logger.warning(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})")
|
||||
if attempt < max_retries:
|
||||
time.sleep(1)
|
||||
else:
|
||||
logger.error(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retries=3):
|
||||
doc_id = postproc_entry["_id"]
|
||||
source = postproc_entry["_source"]
|
||||
news_id = source["news_id"]
|
||||
attempt = 0
|
||||
while attempt < max_retries:
|
||||
try:
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
if not keywords:
|
||||
# Empty article or unparseable LLM answer: writing an empty list
|
||||
# would look like a success and block a later retry.
|
||||
logger.info(f"Skipped {news_id}: no keywords extracted.")
|
||||
return False
|
||||
if target_index == POSTPROC_INDEX:
|
||||
es_client.update_entry(POSTPROC_INDEX, doc_id, {"keywords": keywords})
|
||||
else:
|
||||
# Key the target doc on news_id so re-runs update it in place
|
||||
# instead of piling up a new document each time.
|
||||
es_client.index_entry(
|
||||
target_index,
|
||||
news_id,
|
||||
{
|
||||
"news_id": news_id,
|
||||
"relevant": source.get("relevant", 0),
|
||||
"authors": source.get("authors", []),
|
||||
"keywords": keywords,
|
||||
},
|
||||
)
|
||||
return True
|
||||
except Exception as error:
|
||||
attempt += 1
|
||||
logger.warning(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})")
|
||||
if attempt < max_retries:
|
||||
time.sleep(1)
|
||||
else:
|
||||
logger.error(f"Error: {news_id} - {error}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
|
||||
|
||||
parser.add_argument(
|
||||
"--delete-all",
|
||||
action="store_true",
|
||||
help="Delete all entries from index 'aktuell_postproc'.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--sync-delta",
|
||||
action="store_true",
|
||||
help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--update-keywords",
|
||||
action="store_true",
|
||||
help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--reset-keywords",
|
||||
action="store_true",
|
||||
help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--stats",
|
||||
action="store_true",
|
||||
help="Print statistics about the entries in 'aktuell_postproc' and 'aktuell'.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--threads",
|
||||
type=int,
|
||||
default=4,
|
||||
help="Number of threads for --sync-delta (Default: 4).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--target-index",
|
||||
default=POSTPROC_INDEX,
|
||||
help=(
|
||||
f"Index that --update-keywords writes to (default: {POSTPROC_INDEX}). Any other "
|
||||
"index gets new documents instead of in-place updates, and every entry is "
|
||||
"re-extracted rather than only those missing keywords."
|
||||
),
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.delete_all:
|
||||
es_client.delete_all_entries("aktuell_postproc")
|
||||
|
||||
if args.reset_keywords:
|
||||
result = es_client.remove_field_all("aktuell_postproc", "keywords")
|
||||
logger.info(f"Removed 'keywords' from {result.get('updated', 0)} entries.")
|
||||
|
||||
if args.sync_delta:
|
||||
start_time = time.time()
|
||||
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
postproc_ids_raw = es_client.get_all_entries("aktuell_postproc", fields=["news_id"])
|
||||
|
||||
source_ids = set(entry["_id"] for entry in aktuell_ids_raw)
|
||||
target_ids = set(entry["_source"]["news_id"] for entry in postproc_ids_raw)
|
||||
missing_ids = source_ids - target_ids
|
||||
|
||||
logger.info(f"Number of missing IDs: {len(missing_ids)}")
|
||||
|
||||
missing_ids = list(missing_ids)
|
||||
total = len(missing_ids)
|
||||
|
||||
processed = 0
|
||||
succeeded = 0
|
||||
progress_lock = threading.Lock()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.threads) as executor:
|
||||
futures = [executor.submit(sync_single_news, news_id) for news_id in missing_ids]
|
||||
for future in as_completed(futures):
|
||||
was_successful = future.result()
|
||||
with progress_lock:
|
||||
processed += 1
|
||||
if was_successful:
|
||||
succeeded += 1
|
||||
logger.info(f"Sync: {processed} / {total}")
|
||||
|
||||
end_time = time.time()
|
||||
logger.info(f"Sync DONE: {succeeded} entries synced.")
|
||||
logger.info(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
if args.update_keywords:
|
||||
start_time = time.time()
|
||||
postproc_entries = es_client.get_all_entries(
|
||||
POSTPROC_INDEX, fields=["news_id", "keywords", "relevant", "authors"]
|
||||
)
|
||||
|
||||
if args.target_index == POSTPROC_INDEX:
|
||||
pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")]
|
||||
logger.info(f"Number of entries without keywords: {len(pending)}")
|
||||
else:
|
||||
# Writing elsewhere never marks the postproc entries, so the "missing
|
||||
# keywords" filter would select the same entries on every run. Pick
|
||||
# entries that already have keywords instead: those are known to come
|
||||
# from articles with actual content, unlike the empty archive stubs.
|
||||
pending = [entry for entry in postproc_entries if entry["_source"].get("keywords")]
|
||||
logger.info(f"Re-extracting keywords into '{args.target_index}': {len(pending)} candidates.")
|
||||
|
||||
if args.limit is not None:
|
||||
pending = pending[:args.limit]
|
||||
|
||||
total = len(pending)
|
||||
logger.info(f"Processing {total} entries.")
|
||||
|
||||
processed = 0
|
||||
succeeded = 0
|
||||
progress_lock = threading.Lock()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.threads) as executor:
|
||||
futures = [
|
||||
executor.submit(update_keywords_single, entry, args.target_index)
|
||||
for entry in pending
|
||||
]
|
||||
for future in as_completed(futures):
|
||||
was_successful = future.result()
|
||||
with progress_lock:
|
||||
processed += 1
|
||||
if was_successful:
|
||||
succeeded += 1
|
||||
logger.info(f"Update keywords: {processed} / {total}")
|
||||
|
||||
end_time = time.time()
|
||||
logger.info(f"Update keywords DONE: {succeeded} entries updated.")
|
||||
logger.info(f"Time taken: {end_time - start_time} seconds.")
|
||||
|
||||
if args.stats:
|
||||
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||
logger.info(f"Total entries in 'aktuell': {len(aktuell_entries)}")
|
||||
|
||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"])
|
||||
total_entries = len(postproc_entries)
|
||||
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
|
||||
irrelevant_count = total_entries - relevant_count
|
||||
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
|
||||
news_without_extracted_names = total_entries - news_with_extracted_names
|
||||
news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords"))
|
||||
news_without_keywords = total_entries - news_with_keywords
|
||||
|
||||
logger.info(f"Total entries in 'aktuell_postproc': {total_entries}")
|
||||
logger.info(f"Relevant entries: {relevant_count}")
|
||||
logger.info(f"Irrelevant entries: {irrelevant_count}")
|
||||
logger.info(f"Entries with extracted names: {news_with_extracted_names}")
|
||||
logger.info(f"Entries without extracted names: {news_without_extracted_names}")
|
||||
logger.info(f"Entries with keywords: {news_with_keywords}")
|
||||
logger.info(f"Entries without keywords: {news_without_keywords}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -3,7 +3,6 @@ from pathlib import Path
|
||||
|
||||
from llama_parse import LlamaParse
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
|
||||
AD_PATH = BASE_DIR / "AD.pdf"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pymupdf4llm
|
||||
|
||||
AD_PATH = "188274\AD.pdf"
|
||||
CD_PATH = "188274\СD.pdf"
|
||||
AD_PATH = r"188274\AD.pdf"
|
||||
CD_PATH = r"188274\СD.pdf"
|
||||
|
||||
ad_md = pymupdf4llm.to_markdown(AD_PATH)
|
||||
cd_md = pymupdf4llm.to_markdown(CD_PATH)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf
|
||||
import requests
|
||||
@@ -206,7 +206,7 @@ def make_debug_data(
|
||||
) -> dict:
|
||||
choice = {}
|
||||
|
||||
if "choices" in data and data["choices"]:
|
||||
if data.get("choices"):
|
||||
choice = data["choices"][0]
|
||||
|
||||
message = choice.get("message", {})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
@@ -181,7 +181,7 @@ def make_debug_data(
|
||||
):
|
||||
choice = {}
|
||||
|
||||
if "choices" in data and data["choices"]:
|
||||
if data.get("choices"):
|
||||
choice = data["choices"][0]
|
||||
|
||||
message = choice.get("message", {})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
ROOT_DIR = SCRIPT_DIR
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf # PyMuPDF
|
||||
|
||||
try:
|
||||
@@ -7,7 +8,7 @@ except ImportError:
|
||||
MarkItDown = None
|
||||
|
||||
|
||||
AD_PATH = Path("154115\AD.pdf")
|
||||
AD_PATH = Path(r"154115\AD.pdf")
|
||||
OUT_DIR = Path("ad_extraction_outputs3")
|
||||
OUT_DIR.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
from collections import Counter
|
||||
from statistics import mean, median
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from statistics import mean, median
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
@@ -17,7 +17,7 @@ SERVICE_SOURCE_ROOT = ROOT.parents[1] / "service" / "src" / "main"
|
||||
if str(SERVICE_SOURCE_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(SERVICE_SOURCE_ROOT))
|
||||
|
||||
from inse.authors.institution_membership_query import ( # noqa: E402
|
||||
from inse.authors.institution_membership_query import (
|
||||
build_institution_membership_query,
|
||||
current_affiliation_year_cutoff,
|
||||
)
|
||||
@@ -852,9 +852,7 @@ def validate(result: dict[str, Any]) -> list[str]:
|
||||
if score is None:
|
||||
errors.append("basic_research_score_missing")
|
||||
elif score_is_usable:
|
||||
if quadrant == "pure_basic" and not 0 <= score <= 30:
|
||||
errors.append("basic_research_quadrant_score_mismatch")
|
||||
elif quadrant == "use_inspired_basic" and not 25 <= score <= 45:
|
||||
if quadrant == "pure_basic" and not 0 <= score <= 30 or quadrant == "use_inspired_basic" and not 25 <= score <= 45:
|
||||
errors.append("basic_research_quadrant_score_mismatch")
|
||||
if quadrant not in {"pure_basic", "use_inspired_basic"}:
|
||||
errors.append("basic_research_quadrant_mismatch")
|
||||
|
||||
@@ -26,12 +26,12 @@ import json
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
DEFAULT_AUTHOR_ID = "A5034365278"
|
||||
DEFAULT_WORK_YEAR_GTE = 1950
|
||||
SOURCE_INDEX = "openalex-works*"
|
||||
|
||||
@@ -373,8 +373,8 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
|
||||
|
||||
|
||||
def safe_rate(
|
||||
numerator: int | float,
|
||||
denominator: int | float,
|
||||
numerator: float,
|
||||
denominator: float,
|
||||
) -> float | None:
|
||||
if not denominator:
|
||||
return None
|
||||
|
||||
+1
-2
@@ -13,7 +13,6 @@ from typing import Any
|
||||
|
||||
from openai import OpenAI
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
PROMPT_FILE = ROOT.parent / "prompt_frascati_hard_ranges_v2.txt"
|
||||
CONSENSUS_FILE = ROOT / "consensus_reference.json"
|
||||
@@ -282,7 +281,7 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
|
||||
return 0.0
|
||||
|
||||
|
||||
def safe_rate(numerator: int | float, denominator: int | float) -> float | None:
|
||||
def safe_rate(numerator: float, denominator: float) -> float | None:
|
||||
if not denominator:
|
||||
return None
|
||||
return numerator / denominator
|
||||
|
||||
+2
-2
@@ -3,13 +3,13 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
from collections import Counter
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
ES_BASE_URL = "https://project.nes.uni-due.de/elastic"
|
||||
|
||||
@@ -8,7 +8,6 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
from ollama import Client
|
||||
|
||||
|
||||
ENDPOINT = os.environ.get("OLLAMA_HOST", "https://project.nes.uni-due.de/llm2/")
|
||||
MODEL = os.environ.get("OLLAMA_MODEL", "gemma4:e4b-it-bf16")
|
||||
DATA_FOLDER = "data"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from time import time
|
||||
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
BATCH_SIZE = 6
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import requests, json
|
||||
import json
|
||||
|
||||
import helpers
|
||||
import requests
|
||||
|
||||
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
|
||||
#AUTHOR_OPEN_ALEXID = ["A5047117780"]
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import requests, json
|
||||
import json
|
||||
|
||||
import helpers
|
||||
import requests
|
||||
|
||||
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
|
||||
#AUTHOR_OPEN_ALEXID = ["A5093075883", "A5047117780", "A5007170803"]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
ELASTICSEARCH_URL = os.environ.get("ELASTICSEARCH_URL", "https://project.nes.uni-due.de/elastic")
|
||||
|
||||
@@ -2,8 +2,8 @@ import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from time import time
|
||||
|
||||
from openai import OpenAI, APIConnectionError
|
||||
import helpers
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
BATCH_SIZE = 6
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
from typing import Any, Iterator
|
||||
from elasticsearch import Elasticsearch
|
||||
from collections import defaultdict
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from elasticsearch import NotFoundError
|
||||
from typing import Any
|
||||
|
||||
from elasticsearch import Elasticsearch, NotFoundError
|
||||
|
||||
# elasticseach library required. Here used elasticsearch==8.0.0
|
||||
# estimated execution time: 3-5 Minutes
|
||||
|
||||
|
||||
@@ -15,10 +15,11 @@ The objective is to measure match coverage and determine which ID-matching strat
|
||||
|
||||
Source: `cordis_eu_fp7_project_iprs`
|
||||
Patents tested: 5196(total) - 2270(others) -> 2926 (EP and US patents)
|
||||
| Prefix | Count |
|
||||
|
||||
| Prefix | Count |
|
||||
| --------- | --------: |
|
||||
| EP | 1,952 |
|
||||
| US | 974 |
|
||||
| EP | 1,952 |
|
||||
| US | 974 |
|
||||
| **Total** | **2,926** |
|
||||
|
||||
## Matching Strategies
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
from time import time
|
||||
|
||||
from llm_classify_news import call, parse_label, parse_persons
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Baut aus den JSON-Dateien in data2/ eine eigenstaendige viewer.html.
|
||||
|
||||
@@ -8,8 +7,8 @@ mit Vor/Zurueck durch die News blaettern. Oben stehen _id, llm_label und
|
||||
llm_persons, darunter der full_content als reiner Text (kein Parsing).
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
|
||||
DATA_FOLDER = "validation_data"
|
||||
OUTPUT_FILE = "viewer.html"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import requests
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import requests
|
||||
from openai import OpenAI, APIConnectionError
|
||||
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
INSE_URL = "https://inse.nes.uni-due.de/elastic"
|
||||
INDEX_URL = f"{INSE_URL}/aktuell"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
result_files = [
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib.parse import quote
|
||||
|
||||
INSE_URL = "https://inse.nes.uni-due.de/elastic"
|
||||
INSE_API_KEY = "bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw=="
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import requests
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
LLM_BASE_URL = "https://project.nes.uni-due.de/llm2/v1/"
|
||||
LLM_API_KEY = "c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212"
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import argparse
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
import elastic.client as es_client
|
||||
import llm.client as llm_client
|
||||
import json
|
||||
import argparse
|
||||
import time
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
|
||||
def print_pretty_json(data):
|
||||
print(json.dumps(data, indent=2))
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
Perhaps not the final version. I did not find the files inside my local git branch. I most likely did not save them, however i made backups sometimes, so i hope these versions are the final ones.
|
||||
@@ -0,0 +1,429 @@
|
||||
#!/usr/bin/env python3
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import numpy as np
|
||||
|
||||
# Load service environment config
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
|
||||
from inse.config import settings
|
||||
from inse.util import get_model
|
||||
|
||||
ELASTIC_URL = settings.elasticsearch_url
|
||||
if ELASTIC_URL and not ELASTIC_URL.endswith("/"):
|
||||
ELASTIC_URL += "/"
|
||||
API_KEY = settings.elasticsearch_api_key
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
FIELDS = [
|
||||
"Social Sciences", "Medicine", "Engineering", "Computer Science",
|
||||
"Arts and Humanities", "Biochemistry, Genetics and Molecular Biology",
|
||||
"Agricultural and Biological Sciences", "Environmental Science",
|
||||
"Business, Management and Accounting", "Psychology", "Materials Science",
|
||||
"Economics, Econometrics and Finance", "Health Professions",
|
||||
"Physics and Astronomy", "Chemistry", "Mathematics", "Neuroscience",
|
||||
"Decision Sciences", "Earth and Planetary Sciences", "Immunology and Microbiology",
|
||||
"Energy", "Pharmacology, Toxicology and Pharmaceutics", "Nursing",
|
||||
"Chemical Engineering", "Dentistry", "Veterinary"
|
||||
]
|
||||
|
||||
QUERIES_FILE = current_dir / "evaluation_queries.json"
|
||||
|
||||
def load_queries():
|
||||
if QUERIES_FILE.exists():
|
||||
print(f"Loading cached queries from {QUERIES_FILE}...")
|
||||
with open(QUERIES_FILE, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
else:
|
||||
raise FileNotFoundError(f"Evaluation queries file not found at {QUERIES_FILE}")
|
||||
|
||||
def make_es_payload(query_vector, query_str, config_type, limit=10):
|
||||
if config_type == "display_name":
|
||||
clause = {
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "description":
|
||||
clause = {
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "keywords":
|
||||
clause = {
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "display_name_and_keywords":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "display_name_and_description":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "combined":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "lexical_only":
|
||||
query_body = {
|
||||
"query": {
|
||||
"multi_match": {
|
||||
"query": query_str,
|
||||
"fields": ["display_name^3", "keywords^2", "description^1"]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "hybrid":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"multi_match": {
|
||||
"query": query_str,
|
||||
"fields": ["display_name^3", "keywords^2", "description^1"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
else:
|
||||
raise ValueError(f"Unknown config_type: {config_type}")
|
||||
|
||||
query_body["_source"] = {
|
||||
"excludes": ["display_name_vector", "description_vector", "keyword_vectors", "description"]
|
||||
}
|
||||
query_body["size"] = limit
|
||||
return query_body
|
||||
|
||||
async def evaluate():
|
||||
queries_by_field = load_queries()
|
||||
|
||||
# 1. Warm up model and connection
|
||||
print("\nWarming up model and Elasticsearch connection...")
|
||||
model = get_model()
|
||||
model.encode("warmup search term")
|
||||
|
||||
# Run a dummy check on ES
|
||||
dummy_vector = [0.1] * 768
|
||||
dummy_payload = make_es_payload(dummy_vector, "warmup search term", "display_name")
|
||||
try:
|
||||
with httpx.Client(timeout=10.0) as client:
|
||||
client.post(f"{ELASTIC_URL}topicvectors/_search", json=dummy_payload, headers=headers)
|
||||
print("Warmup complete.")
|
||||
except Exception as exc:
|
||||
print(f"Warmup query failed: {exc}")
|
||||
|
||||
results = []
|
||||
print("\nRunning comprehensive latency evaluation on 520 queries...")
|
||||
query_count = 0
|
||||
|
||||
config_list = [
|
||||
"display_name", "description", "keywords",
|
||||
"display_name_and_keywords", "display_name_and_description",
|
||||
"combined", "lexical_only", "hybrid"
|
||||
]
|
||||
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
for field, queries in queries_by_field.items():
|
||||
for q in queries:
|
||||
query_count += 1
|
||||
if query_count % 50 == 0:
|
||||
print(f"Processed {query_count} / 520 queries...")
|
||||
|
||||
# Measure encoding latency
|
||||
t0 = time.perf_counter()
|
||||
query_vector = model.encode(q).tolist()
|
||||
t1 = time.perf_counter()
|
||||
encode_time = (t1 - t0) * 1000.0 # ms
|
||||
|
||||
latencies = {}
|
||||
|
||||
# Benchmark each configuration
|
||||
for config in config_list:
|
||||
payload = make_es_payload(query_vector, q, config)
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
resp = client.post(f"{ELASTIC_URL}topicvectors/_search", json=payload, headers=headers)
|
||||
resp.raise_for_status()
|
||||
except Exception:
|
||||
# Log error but don't crash
|
||||
pass
|
||||
t1 = time.perf_counter()
|
||||
latencies[config] = (t1 - t0) * 1000.0 # ms
|
||||
|
||||
results.append({
|
||||
"query": q,
|
||||
"field": field,
|
||||
"encode_latency_ms": encode_time,
|
||||
"display_name_latency_ms": latencies.get("display_name", 0.0),
|
||||
"description_latency_ms": latencies.get("description", 0.0),
|
||||
"keywords_latency_ms": latencies.get("keywords", 0.0),
|
||||
"display_name_and_keywords_latency_ms": latencies.get("display_name_and_keywords", 0.0),
|
||||
"display_name_and_description_latency_ms": latencies.get("display_name_and_description", 0.0),
|
||||
"combined_latency_ms": latencies.get("combined", 0.0),
|
||||
"lexical_only_latency_ms": latencies.get("lexical_only", 0.0),
|
||||
"hybrid_latency_ms": latencies.get("hybrid", 0.0)
|
||||
})
|
||||
|
||||
# Calculate global stats
|
||||
encode_l = [r["encode_latency_ms"] for r in results]
|
||||
display_name_l = [r["display_name_latency_ms"] for r in results]
|
||||
description_l = [r["description_latency_ms"] for r in results]
|
||||
keywords_l = [r["keywords_latency_ms"] for r in results]
|
||||
display_name_and_keywords_l = [r["display_name_and_keywords_latency_ms"] for r in results]
|
||||
display_name_and_description_l = [r["display_name_and_description_latency_ms"] for r in results]
|
||||
combined_l = [r["combined_latency_ms"] for r in results]
|
||||
lexical_only_l = [r["lexical_only_latency_ms"] for r in results]
|
||||
hybrid_l = [r["hybrid_latency_ms"] for r in results]
|
||||
|
||||
summary = {
|
||||
"total_queries": len(results),
|
||||
"encode": {
|
||||
"mean": np.mean(encode_l), "median": np.median(encode_l),
|
||||
"p90": np.percentile(encode_l, 90), "p95": np.percentile(encode_l, 95)
|
||||
},
|
||||
"display_name": {
|
||||
"mean": np.mean(display_name_l), "median": np.median(display_name_l),
|
||||
"p90": np.percentile(display_name_l, 90), "p95": np.percentile(display_name_l, 95)
|
||||
},
|
||||
"description": {
|
||||
"mean": np.mean(description_l), "median": np.median(description_l),
|
||||
"p90": np.percentile(description_l, 90), "p95": np.percentile(description_l, 95)
|
||||
},
|
||||
"keywords": {
|
||||
"mean": np.mean(keywords_l), "median": np.median(keywords_l),
|
||||
"p90": np.percentile(keywords_l, 90), "p95": np.percentile(keywords_l, 95)
|
||||
},
|
||||
"display_name_and_keywords": {
|
||||
"mean": np.mean(display_name_and_keywords_l), "median": np.median(display_name_and_keywords_l),
|
||||
"p90": np.percentile(display_name_and_keywords_l, 90), "p95": np.percentile(display_name_and_keywords_l, 95)
|
||||
},
|
||||
"display_name_and_description": {
|
||||
"mean": np.mean(display_name_and_description_l), "median": np.median(display_name_and_description_l),
|
||||
"p90": np.percentile(display_name_and_description_l, 90), "p95": np.percentile(display_name_and_description_l, 95)
|
||||
},
|
||||
"combined": {
|
||||
"mean": np.mean(combined_l), "median": np.median(combined_l),
|
||||
"p90": np.percentile(combined_l, 90), "p95": np.percentile(combined_l, 95)
|
||||
},
|
||||
"lexical_only": {
|
||||
"mean": np.mean(lexical_only_l), "median": np.median(lexical_only_l),
|
||||
"p90": np.percentile(lexical_only_l, 90), "p95": np.percentile(lexical_only_l, 95)
|
||||
},
|
||||
"hybrid": {
|
||||
"mean": np.mean(hybrid_l), "median": np.median(hybrid_l),
|
||||
"p90": np.percentile(hybrid_l, 90), "p95": np.percentile(hybrid_l, 95)
|
||||
}
|
||||
}
|
||||
|
||||
# Save full report to json
|
||||
report_json_path = current_dir / "evaluation_report.json"
|
||||
with open(report_json_path, "w", encoding="utf-8") as f:
|
||||
json.dump({"summary": summary, "results": results}, f, indent=2, ensure_ascii=False)
|
||||
print(f"\nSaved detailed JSON report to {report_json_path}")
|
||||
|
||||
# Generate and save markdown report
|
||||
md_report_path = current_dir / "evaluation_report.md"
|
||||
md_content = f"""# Vector Search Configuration Latency Report
|
||||
Generated on: {time.strftime('%Y-%m-%d %H:%M:%S')}
|
||||
|
||||
This report documents the latency breakdown for different Elasticsearch query configurations across 520 queries, measuring flat vector searches, nested searches, multi-field combinations, pure lexical searches, and full hybrid queries.
|
||||
|
||||
## Latency Summary Table (ms)
|
||||
|
||||
| Query Configuration | Mean | Median | p90 | p95 |
|
||||
| :--- | :---: | :---: | :---: | :---: |
|
||||
| **Embedding Encode** | {summary["encode"]["mean"]:.2f} | {summary["encode"]["median"]:.2f} | {summary["encode"]["p90"]:.2f} | {summary["encode"]["p95"]:.2f} |
|
||||
| **Pure Lexical Search (`multi_match`)** | {summary["lexical_only"]["mean"]:.2f} | {summary["lexical_only"]["median"]:.2f} | {summary["lexical_only"]["p90"]:.2f} | {summary["lexical_only"]["p95"]:.2f} |
|
||||
| **Description Only (`description_vector`)** | {summary["description"]["mean"]:.2f} | {summary["description"]["median"]:.2f} | {summary["description"]["p90"]:.2f} | {summary["description"]["p95"]:.2f} |
|
||||
| **Display Name Only (`display_name_vector`)** | {summary["display_name"]["mean"]:.2f} | {summary["display_name"]["median"]:.2f} | {summary["display_name"]["p90"]:.2f} | {summary["display_name"]["p95"]:.2f} |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | {summary["keywords"]["mean"]:.2f} | {summary["keywords"]["median"]:.2f} | {summary["keywords"]["p90"]:.2f} | {summary["keywords"]["p95"]:.2f} |
|
||||
| **Display Name & Description** | {summary["display_name_and_description"]["mean"]:.2f} | {summary["display_name_and_description"]["median"]:.2f} | {summary["display_name_and_description"]["p90"]:.2f} | {summary["display_name_and_description"]["p95"]:.2f} |
|
||||
| **Display Name & Keywords (Nested)** | {summary["display_name_and_keywords"]["mean"]:.2f} | {summary["display_name_and_keywords"]["median"]:.2f} | {summary["display_name_and_keywords"]["p90"]:.2f} | {summary["display_name_and_keywords"]["p95"]:.2f} |
|
||||
| **Combined (All 3 vector fields)** | {summary["combined"]["mean"]:.2f} | {summary["combined"]["median"]:.2f} | {summary["combined"]["p90"]:.2f} | {summary["combined"]["p95"]:.2f} |
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | {summary["hybrid"]["mean"]:.2f} | {summary["hybrid"]["median"]:.2f} | {summary["hybrid"]["p90"]:.2f} | {summary["hybrid"]["p95"]:.2f} |
|
||||
|
||||
---
|
||||
|
||||
## 💡 Latency Bottleneck & Configuration Analysis
|
||||
|
||||
1. **Lexical Baseline**: **Pure Lexical Search** has extremely low latency (mean: **{summary["lexical_only"]["mean"]:.2f} ms**), representing standard BM25 keyword matching speed.
|
||||
2. **Impact of Nested Fields**:
|
||||
- Compares **Keywords Only (Nested)** (mean: **{summary["keywords"]["mean"]:.2f} ms**) with **Description Only (Flat)** (mean: **{summary["description"]["mean"]:.2f} ms**).
|
||||
- Combining Display Name with the flat Description (**Display Name & Description**: **{summary["display_name_and_description"]["mean"]:.2f} ms**) is faster than combining Display Name with nested Keywords (**Display Name & Keywords**: **{summary["display_name_and_keywords"]["mean"]:.2f} ms**), demonstrating that nested vector joins add a steady latency premium.
|
||||
3. **Compound Parallel Execution**:
|
||||
- Adding lexical queries to the 3 combined vector queries (**Hybrid Search**: **{summary["hybrid"]["mean"]:.2f} ms**) introduces virtually no latency overhead compared to **Combined** vector-only search (mean: **{summary["combined"]["mean"]:.2f} ms**), proving that standard lexical match is executed concurrently with HNSW vector retrieval.
|
||||
"""
|
||||
with open(md_report_path, "w", encoding="utf-8") as f:
|
||||
f.write(md_content)
|
||||
print(f"Saved Markdown report summary to {md_report_path}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(evaluate())
|
||||
@@ -0,0 +1,391 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Professional evaluation pipeline to benchmark different Sentence Transformer models
|
||||
on the OpenAlex topics dataset. Measures Information Retrieval (IR) metrics,
|
||||
Taxonomy Clustering metrics, and operational performance metrics.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Add service/src/main to python path to load settings
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
from inse.config import settings
|
||||
|
||||
ELASTIC_URL = settings.elasticsearch_url
|
||||
API_KEY = settings.elasticsearch_api_key
|
||||
|
||||
# Import evaluation libraries
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from sentence_transformers.evaluation import InformationRetrievalEvaluator
|
||||
from sklearn import metrics
|
||||
from sklearn.cluster import KMeans
|
||||
|
||||
DEFAULT_MODELS = [
|
||||
"paraphrase-multilingual-mpnet-base-v2",
|
||||
"BAAI/bge-m3",
|
||||
"google/embeddinggemma-300m",
|
||||
"intfloat/multilingual-e5-small",
|
||||
"intfloat/multilingual-e5-base",
|
||||
"intfloat/multilingual-e5-large",
|
||||
"sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
||||
#english
|
||||
"sentence-transformers/all-MiniLM-L6-v2",
|
||||
"intfloat/e5-large-v2",
|
||||
"BAAI/bge-large-en-v1.5"
|
||||
]
|
||||
|
||||
def fetch_all_topics():
|
||||
topics = []
|
||||
size = 1000
|
||||
offset = 0
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
with httpx.Client(timeout=60.0) as client:
|
||||
while True:
|
||||
payload = {
|
||||
"query": {"match_all": {}},
|
||||
"from": offset,
|
||||
"size": size
|
||||
}
|
||||
resp = client.post(
|
||||
f"{ELASTIC_URL.rstrip('/')}/openalex-topics/_search",
|
||||
json=payload,
|
||||
headers=headers
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
topics.extend(hits)
|
||||
offset += len(hits)
|
||||
print(f"Fetched {len(topics)} topics...")
|
||||
if len(hits) < size:
|
||||
break
|
||||
|
||||
print(f"Total topics loaded: {len(topics)}")
|
||||
return topics
|
||||
|
||||
def prepare_data(topics, sample_size=None):
|
||||
"""
|
||||
Formulate the IR dataset and clustering taxonomy ground truth labels.
|
||||
"""
|
||||
corpus = {}
|
||||
queries = {}
|
||||
relevant_docs = {}
|
||||
|
||||
# Clustering labels
|
||||
topic_ids = []
|
||||
names_for_clustering = []
|
||||
descriptions_for_clustering = []
|
||||
labels_subfield = []
|
||||
labels_field = []
|
||||
labels_domain = []
|
||||
|
||||
# Build complete corpus dictionary of documents
|
||||
for t in topics:
|
||||
source = t["_source"]
|
||||
doc_id = source["id"]
|
||||
display_name = source.get("display_name") or ""
|
||||
description = source.get("description") or ""
|
||||
doc_text = f"{display_name} {description}".strip()
|
||||
|
||||
corpus[doc_id] = doc_text
|
||||
|
||||
# Taxonomy labels
|
||||
topic_ids.append(doc_id)
|
||||
names_for_clustering.append(display_name.strip())
|
||||
descriptions_for_clustering.append(description.strip())
|
||||
labels_subfield.append(source.get("subfield", {}).get("id") or "unknown_subfield")
|
||||
labels_field.append(source.get("field", {}).get("id") or "unknown_field")
|
||||
labels_domain.append(source.get("domain", {}).get("id") or "unknown_domain")
|
||||
|
||||
sampled_topics = topics
|
||||
if sample_size and sample_size < len(topics):
|
||||
print(f"Sampling {sample_size} topics for query/keyword generation...")
|
||||
sampled_topics = random.sample(topics, sample_size)
|
||||
|
||||
query_count = 0
|
||||
for t in sampled_topics:
|
||||
source = t["_source"]
|
||||
doc_id = source["id"]
|
||||
keywords = source.get("keywords") or []
|
||||
|
||||
for keyword in keywords:
|
||||
if not keyword.strip():
|
||||
continue
|
||||
query_id = f"q_{query_count}"
|
||||
queries[query_id] = keyword
|
||||
|
||||
# Ground truth relevant documents: topic name
|
||||
rel_docs = {doc_id}
|
||||
relevant_docs[query_id] = rel_docs
|
||||
query_count += 1
|
||||
|
||||
print(f"Dataset Formulated: {len(corpus)} corpus documents, {len(queries)} queries.")
|
||||
|
||||
return {
|
||||
"corpus": corpus,
|
||||
"queries": queries,
|
||||
"relevant_docs": relevant_docs,
|
||||
"clustering": {
|
||||
"ids": topic_ids,
|
||||
"names": names_for_clustering,
|
||||
"descriptions": descriptions_for_clustering,
|
||||
"subfield": labels_subfield,
|
||||
"field": labels_field,
|
||||
"domain": labels_domain
|
||||
}
|
||||
}
|
||||
|
||||
def evaluate_model(model_name, data, output_dir):
|
||||
"""
|
||||
Load a model, measure operational speed, and calculate IR + clustering quality.
|
||||
"""
|
||||
model_safe_name = model_name.replace("/", "_").replace("-", "_")
|
||||
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
||||
|
||||
print("\n==================================================")
|
||||
print(f"Evaluating Model: '{model_name}'")
|
||||
print("==================================================")
|
||||
|
||||
start_load = time.time()
|
||||
try:
|
||||
model = SentenceTransformer(model_name)
|
||||
except Exception as exc:
|
||||
print(f"ERROR: Failed to load model '{model_name}': {exc}")
|
||||
return None
|
||||
|
||||
load_time = time.time() - start_load
|
||||
print(f"Model loaded in {load_time:.2f} seconds.")
|
||||
|
||||
num_params = sum(p.numel() for p in model.parameters())
|
||||
param_count_m = num_params / 1_000_000
|
||||
vector_dim = model.get_sentence_embedding_dimension()
|
||||
print(f"Parameters: {param_count_m:.1f}M, Vector Dimension: {vector_dim}")
|
||||
|
||||
# --- FIXED: Perform a warm-up to initialize computation graphs ---
|
||||
print("Warming up model...")
|
||||
_ = model.encode(["warmup sentence"])
|
||||
|
||||
# 2. Measure Query Latency
|
||||
sample_queries = list(data["queries"].values())[:100]
|
||||
if not sample_queries:
|
||||
sample_queries = ["artificial intelligence", "machine learning"]
|
||||
|
||||
start_lat = time.time()
|
||||
for q in sample_queries:
|
||||
_ = model.encode(q)
|
||||
latency_ms = ((time.time() - start_lat) / len(sample_queries)) * 1000
|
||||
print(f"Average Query Latency: {latency_ms:.2f} ms")
|
||||
|
||||
# 3. Measure Ingestion Throughput
|
||||
sample_docs = list(data["corpus"].values())[:200]
|
||||
start_batch = time.time()
|
||||
_ = model.encode(sample_docs, batch_size=32)
|
||||
batch_time = time.time() - start_batch
|
||||
throughput_docs_sec = len(sample_docs) / batch_time
|
||||
print(f"Ingestion Throughput: {throughput_docs_sec:.2f} docs/sec")
|
||||
|
||||
# 4. Information Retrieval Evaluation
|
||||
print("Running Information Retrieval evaluation (NDCG, MRR, Recall)...")
|
||||
|
||||
# --- FIXED: Use precision_recall_at_k for true recall metrics ---
|
||||
evaluator = InformationRetrievalEvaluator(
|
||||
data["queries"],
|
||||
data["corpus"],
|
||||
data["relevant_docs"], # The evaluator natively accepts sets, no need to cast to lists
|
||||
name=model_safe_name,
|
||||
mrr_at_k=[10],
|
||||
ndcg_at_k=[10],
|
||||
precision_recall_at_k=[10] # This ensures true Recall is calculated across multiple sibling matches
|
||||
)
|
||||
|
||||
ir_results = evaluator(model)
|
||||
|
||||
# Extract keys safely
|
||||
ndcg_key = f"{model_safe_name}_cosine_ndcg@10"
|
||||
mrr_key = f"{model_safe_name}_cosine_mrr@10"
|
||||
recall_key = f"{model_safe_name}_cosine_recall@10" # Changed from accuracy to recall
|
||||
|
||||
ndcg_score = ir_results.get(ndcg_key, 0.0)
|
||||
mrr_score = ir_results.get(mrr_key, 0.0)
|
||||
recall_score = ir_results.get(recall_key, 0.0)
|
||||
|
||||
print(f"NDCG@10: {ndcg_score:.4f}, MRR@10: {mrr_score:.4f}, Recall@10: {recall_score:.4f}")
|
||||
|
||||
# 5. Clustering evaluation against ground-truth taxonomy
|
||||
print("Running Taxonomy Clustering evaluation (NMI)...")
|
||||
|
||||
unique_subfields = list(set(data["clustering"]["subfield"]))
|
||||
n_clusters = len(unique_subfields)
|
||||
|
||||
# Topic Names Clustering
|
||||
print("Clustering Topic Names...")
|
||||
clustering_names = data["clustering"]["names"]
|
||||
name_embeddings = model.encode(clustering_names, show_progress_bar=False, batch_size=64)
|
||||
|
||||
nmi_name = 0.0
|
||||
ari_name = 0.0
|
||||
if n_clusters > 1 and len(name_embeddings) > n_clusters:
|
||||
kmeans_name = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
|
||||
assignments_name = kmeans_name.fit_predict(name_embeddings)
|
||||
nmi_name = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_name)
|
||||
ari_name = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_name)
|
||||
print(f"Names - Subfield Clustering NMI: {nmi_name:.4f}, ARI: {ari_name:.4f}")
|
||||
|
||||
# Topic Descriptions Clustering
|
||||
print("Clustering Topic Descriptions...")
|
||||
clustering_descs = data["clustering"]["descriptions"]
|
||||
desc_embeddings = model.encode(clustering_descs, show_progress_bar=False, batch_size=64)
|
||||
|
||||
nmi_desc = 0.0
|
||||
ari_desc = 0.0
|
||||
if n_clusters > 1 and len(desc_embeddings) > n_clusters:
|
||||
kmeans_desc = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
|
||||
assignments_desc = kmeans_desc.fit_predict(desc_embeddings)
|
||||
nmi_desc = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_desc)
|
||||
ari_desc = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_desc)
|
||||
print(f"Descriptions - Subfield Clustering NMI: {nmi_desc:.4f}, ARI: {ari_desc:.4f}")
|
||||
|
||||
report = {
|
||||
"model_name": model_name,
|
||||
"parameters_m": param_count_m,
|
||||
"vector_dim": vector_dim,
|
||||
"latency_ms": latency_ms,
|
||||
"throughput_docs_sec": throughput_docs_sec,
|
||||
"ndcg_at_10": ndcg_score,
|
||||
"mrr_at_10": mrr_score,
|
||||
"recall_at_10": recall_score,
|
||||
"name_nmi": nmi_name,
|
||||
"name_ari": ari_name,
|
||||
"desc_nmi": nmi_desc,
|
||||
"desc_ari": ari_desc
|
||||
}
|
||||
|
||||
with open(report_file, "w", encoding="utf-8") as f:
|
||||
json.dump(report, f, indent=2, ensure_ascii=False)
|
||||
print(f"Saved model report to {report_file}")
|
||||
|
||||
return report
|
||||
|
||||
def generate_consolidated_report(output_dir, reports):
|
||||
if not reports:
|
||||
print("No reports to consolidate.")
|
||||
return
|
||||
|
||||
report_file = output_dir / "model_evaluation_report.md"
|
||||
print(f"\nCompiling consolidated report into {report_file}...")
|
||||
|
||||
sorted_reports = sorted(reports, key=lambda x: x["ndcg_at_10"], reverse=True)
|
||||
|
||||
lines = [
|
||||
"# Sentence Transformer Model Evaluation Report",
|
||||
"",
|
||||
"This report aggregates performance metrics and accuracy benchmarks for different Sentence Transformer models evaluated against the OpenAlex topic keywords dataset.",
|
||||
"",
|
||||
"## Overall Leaderboard",
|
||||
"",
|
||||
"| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |",
|
||||
"| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |"
|
||||
]
|
||||
|
||||
for idx, r in enumerate(sorted_reports):
|
||||
name_nmi = r.get("name_nmi", 0.0)
|
||||
desc_nmi = r.get("desc_nmi", 0.0)
|
||||
lines.append(
|
||||
f"| {idx+1} | `{r['model_name']}` | {r['vector_dim']} | {r['parameters_m']:.1f}M | {r['latency_ms']:.2f}ms | {r['throughput_docs_sec']:.1f} | **{r['ndcg_at_10']:.4f}** | {r['mrr_at_10']:.4f} | {r['recall_at_10']:.4f} | {name_nmi:.4f} | {desc_nmi:.4f} |"
|
||||
)
|
||||
|
||||
lines.extend([
|
||||
"",
|
||||
"### Metric Definitions:",
|
||||
"* **NDCG@10**: Normalized Discounted Cumulative Gain. Measures how well the query maps to the target topic at the top 10 positions.",
|
||||
"* **MRR@10**: Mean Reciprocal Rank. Looks at the average of `1 / rank` for the first correctly matched topic.",
|
||||
"* **Recall@10**: Percentage of times the target document (excluding sibling topics) was successfully retrieved in the top 10.",
|
||||
"* **Name NMI**: Normalized Mutual Information of K-Means clusters of topic display names against ground truth OpenAlex subfields.",
|
||||
"* **Desc NMI**: Normalized Mutual Information of K-Means clusters of topic descriptions against ground truth OpenAlex subfields.",
|
||||
"* **Query Latency**: Time to encode a single search keyword.",
|
||||
"* **Throughput**: Ingestion batch encoding speed."
|
||||
])
|
||||
|
||||
with open(report_file, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines))
|
||||
print(f"Report compiled successfully at {report_file}")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Evaluate Sentence Transformer models on OpenAlex topics.")
|
||||
parser.add_argument("--model", type=str, help="Specific model to evaluate (skips others).")
|
||||
parser.add_argument("--sample-size", type=int, help="Sample size of topics to evaluate keywords for (faster run).")
|
||||
parser.add_argument("--all", action="store_true", help="Evaluate all topics/keywords (default if sample-size omitted).")
|
||||
parser.add_argument("--output-dir", type=str, help="Custom directory to save reports.")
|
||||
parser.add_argument("--force-refresh", action="store_true", help="Force reload topics from Elasticsearch instead of cache.")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if Path("/data").is_dir():
|
||||
data_dir = Path("/data")
|
||||
else:
|
||||
project_root = Path(__file__).parent.parent.parent.parent.parent.resolve()
|
||||
data_dir = project_root / "service" / "src" / "data"
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
output_dir = Path(args.output_dir) if args.output_dir else data_dir
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
cache_file = data_dir / "raw_topics_cache.json"
|
||||
if cache_file.exists() and not args.force_refresh:
|
||||
print(f"Loading topics from local cache: {cache_file}")
|
||||
with open(cache_file, "r", encoding="utf-8") as f:
|
||||
topics = json.load(f)
|
||||
else:
|
||||
topics = fetch_all_topics()
|
||||
with open(cache_file, "w", encoding="utf-8") as f:
|
||||
json.dump(topics, f, indent=2, ensure_ascii=False)
|
||||
print(f"Cached {len(topics)} topics to {cache_file}")
|
||||
|
||||
if not topics:
|
||||
print("Error: No topics dataset available. Make sure Elasticsearch is running or cache exists.")
|
||||
sys.exit(1)
|
||||
|
||||
data = prepare_data(topics, sample_size=args.sample_size)
|
||||
|
||||
models_to_evaluate = DEFAULT_MODELS
|
||||
if args.model:
|
||||
models_to_evaluate = [args.model]
|
||||
|
||||
print(f"Models scheduled for evaluation: {models_to_evaluate}")
|
||||
|
||||
reports = []
|
||||
for m in models_to_evaluate:
|
||||
model_safe_name = m.replace("/", "_").replace("-", "_")
|
||||
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
||||
|
||||
if report_file.exists() and not args.model:
|
||||
print(f"Loading cached evaluation report for '{m}' from {report_file}")
|
||||
with open(report_file, "r", encoding="utf-8") as f:
|
||||
reports.append(json.load(f))
|
||||
else:
|
||||
rep = evaluate_model(m, data, output_dir)
|
||||
if rep:
|
||||
reports.append(rep)
|
||||
|
||||
generate_consolidated_report(output_dir, reports)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,159 @@
|
||||
# Performance Summary
|
||||
|
||||
520 Keywords as query against hybrid & semantic search
|
||||
|
||||
- Search fields:
|
||||
- display name (Keyword & single vector)
|
||||
- description (Keyword & single vector)
|
||||
- keywords (Keyword & nested vectors)
|
||||
|
||||
- 26 Fields: 20 examples each
|
||||
| # | OpenAlex Field Name | Complete Test Queries |
|
||||
|---|---------------------|-----------------------------------------|
|
||||
| 01 | **Social Sciences** | `sociology, gender inequality in workplace, urbanization trends, political polarization, human rights law, social mobility, qualitative research methods, demographic shifts, cultural anthropology, criminal justice reform, public policy analysis, indigenous languages, voter behavior, globalization effects, community development, media studies, social movements, migration patterns, welfare systems, family dynamics` |
|
||||
| 02 | **Medicine** | `cardiology, diabetes management, oncology treatment options, clinical trials, pediatric care, chronic pain relief, cardiovascular disease prevention, surgical procedures, infectious disease outbreak, medical imaging techniques, hypertension guidelines, patient outcomes, immunotherapy for cancer, epidemiology study, stroke rehabilitation, genetic disorders, telemedicine adoption, internal medicine, diagnostic accuracy, palliative care` |
|
||||
| 03 | **Engineering** | `civil engineering, structural integrity, aerospace propulsion, mechanical design, robotics automation, geotechnical analysis, bridge construction, renewable energy grid, fluid mechanics, electrical circuits, thermodynamics applications, manufacturing optimization, control systems engineering, materials fatigue, hvac design, biomedical devices, transportation infrastructure, signal processing, solid mechanics, industrial engineering` |
|
||||
| 04 | **Computer Science** | `machine learning, natural language processing, cybersecurity protocols, cloud computing architecture, neural networks, database optimization, software engineering practices, computer vision algorithms, blockchain technology, artificial intelligence ethics, human computer interaction, operating systems, distributed ledgers, compiler design, data mining techniques, cryptographic keys, quantum computing algorithms, web development frameworks, reinforcement learning, graph databases` |
|
||||
| 05 | **Arts and Humanities** | `art history, literary criticism, philosophy of mind, renaissance architecture, linguistics morphology, creative writing, musical composition, theater history, postmodern literature, ethics and morality, historical archives, film analysis, religious studies, classical archaeology, metaphysics, cultural heritage preservation, comparative literature, linguistic semantics, medieval art, epistemology` |
|
||||
| 06 | **Biochemistry, Genetics and Molecular Biology** | `dna replication, crispr gene editing, protein folding, rna sequencing, enzyme kinetics, cellular signaling pathways, metabolic pathways, genomic sequencing, molecular cloning, apoptosis mechanism, mitochondrial DNA, epigenetic modifications, proteomics analysis, gene expression regulation, chromatin remodeling, amino acid synthesis, nucleic acids, cellular differentiation, lipid metabolism, transcription factors` |
|
||||
| 07 | **Agricultural and Biological Sciences** | `crop yield optimization, plant physiology, marine biology, soil microbiology, entomology study, botany research, sustainable agriculture, animal behavior, ecology systems, pest management, forestry conservation, photosynthesis mechanism, biodiversity preservation, aquaculture techniques, agronomy practices, seed germination, horticulture science, wildlife ecology, plant pathology, livestock breeding` |
|
||||
| 08 | **Environmental Science** | `climate change mitigation, renewable resource management, air pollution monitoring, microplastics in oceans, deforestation rates, waste management systems, carbon footprint reduction, biodiversity loss, global warming impacts, ecosystem restoration, water quality analysis, urban sustainability, environmental impact assessment, glacier melting, conservation biology, greenhouse gas emissions, soil erosion control, renewable energy transition, climate adaptation strategies, acid rain causes` |
|
||||
| 09 | **Business, Management and Accounting** | `corporate strategy, supply chain logistics, financial auditing, marketing analytics, human resource management, organizational behavior, consumer behavior trends, risk assessment framework, entrepreneurship ecosystems, project management methodologies, accounting principles, brand equity, leadership styles, business ethics, digital transformation strategy, operations management, corporate governance, market segmentation, strategic planning, financial reporting standards` |
|
||||
| 10 | **Psychology** | `cognitive behavioral therapy, developmental psychology, social anxiety disorder, memory retention techniques, neuropsychology assessment, human behavior analysis, mental health counseling, personality traits theory, child development stages, addiction recovery mechanisms, emotional intelligence, perception and sensation, group dynamics psychology, depression treatment outcomes, stress management interventions, motivation theories, cognitive dissonance, behavioral psychology, mindfulness practices, sleep disorders psychology` |
|
||||
| 11 | **Materials Science** | `nanomaterials synthesis, graphene applications, polymers characterization, metallurgy engineering, semiconductor fabrication, composite materials design, biomaterials tissue engineering, thin film deposition, corrosion resistance, superconductors properties, ceramic engineering, alloy development, material degradation, photovoltaic materials, mechanical testing of alloys, smart materials technology, crystal structure analysis, carbon nanotubes research, thermal conductivity materials, magnetic materials applications` |
|
||||
| 12 | **Economics, Econometrics and Finance** | `macroeconomic policy, econometric modeling, financial market analysis, monetary theory, microeconomics principles, game theory applications, inflation rates forecast, labor economics, behavioral finance, portfolio optimization, international trade agreements, fiscal policy impact, time series analysis, asset pricing models, poverty reduction strategies, economic growth models, corporate finance theory, cryptocurrency economics, market equilibrium, public finance management` |
|
||||
| 13 | **Health Professions** | `physical therapy techniques, occupational therapy interventions, speech language pathology, radiologic technology, emergency medical services, healthcare administration, audiology assessments, rehabilitation sciences, clinical nutrition, paramedic protocols, respiratory therapy management, health informatics systems, dietetics practice, patient care quality, medical laboratory technology, orthotics and prosthetics, interprofessional healthcare collaboration, community health education, sports medicine rehabilitation, physician assistant training` |
|
||||
| 14 | **Physics and Astronomy** | `quantum mechanics, astrophysics research, dark matter detection, particle physics collision, general relativity theory, cosmology evolution, exoplanet discovery, nuclear fusion energy, condensed matter physics, string theory concepts, optics and photonics, black hole thermodynamics, gravitational waves detection, statistical mechanics, plasma physics applications, stellar evolution models, high energy physics, quantum entanglement experiments, spectroscopy techniques, thermodynamics principles` |
|
||||
| 15 | **Chemistry** | `organic synthesis, analytical chemistry methods, inorganic compounds coordination, physical chemistry thermodynamics, spectroscopy chemical analysis, catalysis mechanism design, polymer chemistry polymerization, electrochemistry batteries, medicinal chemistry design, chromatography separation techniques, chemical kinetics reactions, mass spectrometry profiling, computational chemistry modeling, environmental chemistry monitoring, photochemistry solar conversion, biophysical chemistry structure, green chemistry principles, molecular orbital theory, supramolecular architecture, crystallography structure determination` |
|
||||
| 16 | **Mathematics** | `linear algebra, differential equations solution, algebraic topology, number theory cryptography, calculus fundamentals, probability and statistics, discrete mathematics structures, numerical analysis algorithms, complex analysis functions, geometry axiom theories, combinatorics counting techniques, mathematical modeling simulation, set theory foundations, graph theory applications, real analysis limits, partial differential equations, abstract algebra groups, optimization theory algorithms, stochastic processes modeling, chaos theory dynamics` |
|
||||
| 17 | **Neuroscience** | `synaptic plasticity, neurodegenerative diseases mechanisms, brain mapping fmri, cognitive neuroscience memory, neurotransmitter receptors pathways, neural network architecture, behavioral neuroscience addiction, neurogenesis adult brain, axon guidance development, spinal cord injury, sensory processing systems, motor control pathways, alzheimer disease pathology, parkinson motor deficits, neuroimmunology inflammation, sleep neural circuits, epilepsy seizure mechanisms, computational neuroscience models, neuropharmacology drugs action, brain computer interface` |
|
||||
| 18 | **Decision Sciences** | `operations research optimization, decision analysis models, multi criteria decision making, game theory strategies, risk analysis management, linear programming applications, forecasting methods business, supply chain optimization, stochastic modeling systems, queuing theory performance, decision tree classification, predictive analytics framework, statistical decision theory, heuristic search optimization, inventory control models, simulation optimization methods, behavioral decision making, utility theory choices, data driven decision support, dynamic programming problems` |
|
||||
| 19 | **Earth and Planetary Sciences** | `plate tectonics geology, seismology earthquake prediction, volcanology eruption monitoring, paleoclimatology proxy data, planetary geology mars, mineralogy crystal structures, sedimentology deposition environments, stratigraphy rock layers, geomorphology landscape evolution, hydrology water cycle, meteorology weather forecasting, oceanography ocean currents, geochemistry isotopic analysis, remote sensing earth, petrology rock formation, impact cratering planetary, paleontology fossil records, glaciology ice sheets, geophysics magnetic fields, environmental geology hazards` |
|
||||
| 20 | **Immunology and Microbiology** | `t cell activation, antibody response mechanics, bacterial resistance antibiotics, viral replication cycle, autoimmune disease pathogenesis, innate immunity defense, vaccine development strategies, microbiome gut health, macrophage polarization function, pathogen virulence factors, cytokine storm response, mycology fungal infections, parasitology host interaction, adaptive immune system, antigen presentation pathway, bacteriophage therapy applications, immunotherapy cancer treatment, microbial biofilms formation, virology host defense, inflammation signaling pathways` |
|
||||
| 21 | **Energy** | `solar cell efficiency, wind turbine aerodynamics, battery energy storage, hydrogen fuel cells, nuclear power generation, biofuel production technologies, geothermal energy extraction, energy grid optimization, fossil fuel alternative, hydroelectric power systems, energy efficiency buildings, carbon capture storage, renewable energy policy, smart grid infrastructure, tidal energy conversion, thermal energy storage, power electronics converters, microgrid energy systems, biomass combustion processes, energy consumption forecasting` |
|
||||
| 22 | **Pharmacology, Toxicology and Pharmaceutics** | `drug delivery systems, pharmacokinetics modeling analysis, pharmacodynamics receptor binding, toxicology safety assessment, pharmaceutical formulation design, bioavailability drug absorption, cytotoxicity assays testing, clinical pharmacology trials, neuropharmacology drug effects, cardiotoxicity drug evaluation, nanoparticle drug carriers, pharmacogenomics personalized medicine, drug metabolism enzymes, adverse drug reactions, controlled release tablets, heavy metal toxicology, target identification drug, natural product pharmacology, dosage form optimization, endocrine disruptors toxicology` |
|
||||
| 23 | **Nursing** | `patient care management, nursing education curriculum, clinical nursing practice, geriatric nursing care, pediatric nursing interventions, critical care nursing, palliative nursing care, nursing leadership styles, community health nursing, evidence based nursing, mental health nursing, maternal newborn nursing, wound care management, nurse practitioner roles, patient safety protocols, nursing burnout prevention, oncology nursing practices, chronic disease management, telehealth nursing care, infection control nursing` |
|
||||
| 24 | **Chemical Engineering** | `process systems engineering, chemical reactor design, transport phenomena fluid, separation processes distillation, catalytic reaction engineering, bioprocess engineering fermentation, thermodynamics chemical mixtures, heat exchanger network, polymer processing extrusion, mass transfer operations, process safety management, fluidized bed reactor, chemical plant optimization, multi phase flow, computational fluid dynamics, industrial scale synthesis, green chemical engineering, adsorption separation kinetics, process control loops, materials processing chemical` |
|
||||
| 25 | **Dentistry** | `endodontic treatment procedures, periodontal disease therapy, orthodontic alignment techniques, dental implant surgery, prosthodontics crown design, pediatric dentistry prevention, oral maxillofacial surgery, dental caries prevention, restorative dentistry materials, oral pathology diagnosis, laser dentistry applications, dental biomaterials wear, cone beam ct, salivary diagnostics biomarkers, aesthetic dentistry veneers, root canal morphology, gingival recession treatment, fluoride treatment efficacy, dental pulp stem cells, temporomandibular joint disorders` |
|
||||
| 26 | **Veterinary** | `veterinary medicine diagnosis, canine parvovirus treatment, feline leukemia virus, equine sports medicine, bovine mastitis control, veterinary surgery techniques, animal nutrition guidelines, zoonotic disease transmission, veterinary oncology treatment, avian medicine care, small animal internal, livestock herd health, veterinary pharmacology drugs, animal welfare assessment, veterinary radiology imaging, feline behavior issues, canine hip dysplasia, veterinary epidemiology outbreaks, companion animal care, exotic pet medicine` |
|
||||
|
||||
## Latency results
|
||||
|
||||
| Query Configuration | Mean | Median | p95 |
|
||||
| :-------------------------------------- | :---: | :----: | :---: |
|
||||
| **Embedding Encode** | 35.81 | 35.11 | 42.98 |
|
||||
| **Pure Lexical Search (`multi_match`)** | 44.03 | 43.21 | 52.12 |
|
||||
|
||||
|
|
||||
| **Description Only (`description_vector`)** | 27.11 | 24.83 | 40.23 |
|
||||
| **Display Name Only (`display_name_vector`)** | 42.71 | 45.33 | 55.51 |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | 47.65 | 47.06 | 56.88 |
|
||||
| **Display Name & Description** | 46.62 | 49.22 | 59.43 |
|
||||
| **Display Name & Keywords (Nested)** | 52.11 | 51.36 | 61.22 |
|
||||
| **Combined (All 3 vector fields)** | 57.06 | 55.65 | 67.32 |
|
||||
|
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | 58.65 | 57.09 | 69.10 |
|
||||
|
||||
- should query runs hybrid and semantic concurrently => nested Keyword vector search bottleneck
|
||||
- Hybrid returns more results overall due to partailly matching words in display name & Keywords
|
||||
- Query: "Cell Adhesion Molecules Research"
|
||||
- Low rank return: "Q Methodology Applications"
|
||||
- because: ["**Research** Methods", "Qualitative **Research**"] Keywords
|
||||
|
||||
- Changed k & num_candidates to 500 (fixed bug, where not all keywords were considered):
|
||||
| Query Configuration | Mean | Median | p95 |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| **Embedding Encode** | 38.25 | 37.41 | 45.48 |
|
||||
| **Pure Lexical Search (`multi_match`)** | 44.98 | 43.69 | 55.21 |
|
||||
| **Description Only (`description_vector`)** | 29.69 | 27.76 | 45.46 |
|
||||
| **Display Name Only (`display_name_vector`)** | 45.20 | 46.68 | 59.47 |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | 50.00 | 48.89 | 60.61 |
|
||||
| **Display Name & Description** | 49.84 | 51.16 | 66.37 |
|
||||
| **Display Name & Keywords (Nested)** | 55.50 | 54.16 | 66.12 |
|
||||
| **Combined (All 3 vector fields)** | 61.81 | 59.74 | 75.30 |
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | 63.25 | 61.05 | 76.39 |
|
||||
|
||||
# Search Score Breakdown & Weight Analysis Report
|
||||
|
||||
---
|
||||
|
||||
## Global Score Contribution
|
||||
|
||||
| Weight Component | Boost | Avg. Score Contribution | Percentage of Total Score |
|
||||
| :-------------------------------------------- | :---: | :---------------------: | :-----------------------: |
|
||||
| **Lexical Match (`multi_match`)** | 1.0 | 36.2275 | 54.31% |
|
||||
| **Title Vector (`display_name_vector`)** | 30.0 | 17.9748 | 26.95% |
|
||||
| **Description Vector (`description_vector`)** | 15.0 | 2.5502 | 3.82% |
|
||||
| **Nested Keywords (`keyword_vectors`)** | 25.0 | 9.9531 | 14.92% |
|
||||
|
||||
| After fix:
|
||||
| **Lexical Match (`multi_match`)** | 1.0 | 38.2910 | 44.79% |
|
||||
| **Title Vector (`display_name_vector`)** | 30.0 | 22.5727 | 26.40% |
|
||||
| **Description Vector (`description_vector`)** | 15.0 | 3.3518 | 3.92% |
|
||||
| **Nested Keywords (`keyword_vectors`)** | 25.0 | 21.2808 | 24.89% |
|
||||
|
||||
---
|
||||
|
||||
## Contribution Breakdown by Field
|
||||
|
||||
| Field | Avg. Score | Lexical % | Title Vector % | Description Vector % | Keywords Vector % |
|
||||
| :------------------------------------------- | :--------: | :-------: | :------------: | :------------------: | :---------------: |
|
||||
| Social Sciences | 76.10 | 42.6% | 27.0% | 6.2% | 24.2% |
|
||||
| Medicine | 71.58 | 43.9% | 26.5% | 4.1% | 25.5% |
|
||||
| Engineering | 67.73 | 43.8% | 27.6% | 3.5% | 25.2% |
|
||||
| Computer Science | 69.63 | 47.3% | 23.4% | 4.0% | 25.3% |
|
||||
| Arts and Humanities | 75.38 | 40.2% | 28.7% | 5.9% | 25.1% |
|
||||
| Biochemistry, Genetics and Molecular Biology | 64.32 | 43.5% | 26.7% | 1.6% | 28.1% |
|
||||
| Agricultural and Biological Sciences | 70.48 | 38.0% | 30.7% | 4.2% | 27.1% |
|
||||
| Environmental Science | 72.92 | 44.3% | 26.3% | 5.0% | 24.3% |
|
||||
| Business, Management and Accounting | 75.14 | 47.1% | 25.8% | 2.7% | 24.5% |
|
||||
| Psychology | 67.50 | 40.8% | 28.5% | 4.9% | 25.8% |
|
||||
| Materials Science | 75.99 | 40.4% | 28.5% | 6.4% | 24.7% |
|
||||
| Economics, Econometrics and Finance | 67.58 | 43.0% | 25.3% | 5.7% | 25.9% |
|
||||
| Health Professions | 62.96 | 41.9% | 28.4% | 3.2% | 26.5% |
|
||||
| Physics and Astronomy | 70.10 | 47.5% | 24.4% | 3.6% | 24.5% |
|
||||
| Chemistry | 73.17 | 44.6% | 26.8% | 4.2% | 24.4% |
|
||||
| Mathematics | 74.83 | 48.1% | 24.7% | 4.4% | 22.9% |
|
||||
| Neuroscience | 68.20 | 45.2% | 24.6% | 5.2% | 25.0% |
|
||||
| Decision Sciences | 67.13 | 49.5% | 23.3% | 2.4% | 24.8% |
|
||||
| Earth and Planetary Sciences | 64.59 | 41.3% | 28.9% | 2.4% | 27.3% |
|
||||
| Immunology and Microbiology | 68.62 | 44.9% | 25.7% | 3.6% | 25.9% |
|
||||
| Energy | 80.04 | 50.3% | 22.8% | 5.4% | 21.6% |
|
||||
| Pharmacology, Toxicology and Pharmaceutics | 64.61 | 45.2% | 26.1% | 2.4% | 26.2% |
|
||||
| Nursing | 75.86 | 47.8% | 26.5% | 2.8% | 22.8% |
|
||||
| Chemical Engineering | 59.12 | 48.5% | 26.0% | 1.1% | 24.4% |
|
||||
| Dentistry | 62.51 | 44.1% | 28.1% | 3.1% | 24.7% |
|
||||
| Veterinary | 53.56 | 49.2% | 26.9% | 1.9% | 22.0% |
|
||||
|
||||
---
|
||||
|
||||
## Score Breakdown Examples (Top Match per Field Sample)
|
||||
|
||||
| Field & Query | Fixed Variant Performance | Bug Variant Performance |
|
||||
| :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| **Social Sciences**<br>`"sociology"` | **Topic**: Emile Durkheim and Sociology<br>**Total Score**: 80.7964<br><br>• Lexical: 33.6289<br>• Title KNN: 25.3876<br>• Desc KNN: 12.1561<br>• Key KNN: 24.9897<br><br>**Keywords**:<br>• 'sociology' (0.9996)<br>• 'social conditions' (0.8254) | **Topic**: Emile Durkheim and Sociology<br>**Total Score**: 55.4088<br><br>• Lexical: 33.6289<br>• Title KNN: 0.0000<br>• Desc KNN: 12.1561<br>• Key KNN: 24.9897<br><br>**Keywords**:<br>• 'sociology' (0.9996)<br>• 'social conditions' (0.8254) |
|
||||
| **Medicine**<br>`"cardiology"` | **Topic**: Cardiomyopathy and Myosin Studies<br>**Total Score**: 62.3436<br><br>• Lexical: 0.0000<br>• Title KNN: 26.0134<br>• Desc KNN: 12.4090<br>• Key KNN: 23.9212<br><br>**Keywords**:<br>• 'Cardiomyopathies' (0.9568)<br>• 'Cardiac Imaging' (0.9192) | **Topic**: Cardiac Imaging and Diagnostics<br>**Total Score**: 27.6677<br><br>• Lexical: 0.0000<br>• Title KNN: 27.6677<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Cardiac Imaging' (0.9192)<br>• 'Myocardial Infarction' (0.8564) |
|
||||
| **Engineering**<br>`"civil engineering"` | **Topic**: Civil and Structural Engineering Research<br>**Total Score**: 97.2652<br><br>• Lexical: 60.8415<br>• Title KNN: 28.1018<br>• Desc KNN: 12.3099<br>• Key KNN: 24.8941<br><br>**Keywords**:<br>• 'Civil Engineering' (0.9958)<br>• 'Construction' (0.8388) | **Topic**: Civil and Structural Engineering Research<br>**Total Score**: 97.2652<br><br>• Lexical: 60.8415<br>• Title KNN: 28.1018<br>• Desc KNN: 12.3099<br>• Key KNN: 24.8941<br><br>**Keywords**:<br>• 'Civil Engineering' (0.9958)<br>• 'Construction' (0.8388) |
|
||||
| **Computer Science**<br>`"machine learning"` | **Topic**: Machine Learning and Algorithms<br>**Total Score**: 99.2549<br><br>• Lexical: 55.5562<br>• Title KNN: 29.2590<br>• Desc KNN: 12.5187<br>• Key KNN: 24.9693<br><br>**Keywords**:<br>• 'Machine Learning' (0.9988)<br>• 'Deep Learning' (0.9119) | **Topic**: Machine Learning and Algorithms<br>**Total Score**: 74.2856<br><br>• Lexical: 55.5562<br>• Title KNN: 29.2590<br>• Desc KNN: 12.5187<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Machine Learning' (0.9988)<br>• 'Deep Learning' (0.9119) |
|
||||
| **Arts and Humanities**<br>`"art history"` | **Topic**: Art, Politics, and Modernism<br>**Total Score**: 79.6751<br><br>• Lexical: 41.4462<br>• Title KNN: 26.8390<br>• Desc KNN: 12.2412<br>• Key KNN: 23.1472<br><br>**Keywords**:<br>• 'Contemporary Art' (0.9259)<br>• 'Art Theory' (0.8902) | **Topic**: Art History and Market Analysis<br>**Total Score**: 54.6477<br><br>• Lexical: 44.3255<br>• Title KNN: 27.6256<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Art Market' (0.8499) |
|
||||
| **Biochemistry, Genetics...**<br>`"dna replication"` | **Topic**: DNA Repair Mechanisms<br>**Total Score**: 69.5873<br><br>• Lexical: 37.9645<br>• Title KNN: 25.5676<br>• Desc KNN: 0.0000<br>• Key KNN: 21.2950<br><br>**Keywords**:<br>• 'Homologous Recombination' (0.8518) | **Topic**: DNA Repair Mechanisms<br>**Total Score**: 48.2923<br><br>• Lexical: 37.9645<br>• Title KNN: 25.5676<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Homologous Recombination' (0.8518) |
|
||||
| **Agricultural Sciences**<br>`"crop yield optimization"` | **Topic**: Crop Yield and Soil Fertility<br>**Total Score**: 86.9026<br><br>• Lexical: 72.9192<br>• Title KNN: 25.6184<br>• Desc KNN: 0.0000<br>• Key KNN: 21.9673<br><br>**Keywords**:<br>• 'Crop Management' (0.8787)<br>• 'Maize Yield' (0.8515) | **Topic**: Soil Management and Crop Yield<br>**Total Score**: 65.6488<br><br>• Lexical: 58.5754<br>• Title KNN: 26.3319<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'No-till Crop Production' (0.8136) |
|
||||
| **Environmental Science**<br>`"climate change mitigation"` | **Topic**: Climate Change, Adaptation, Migration<br>**Total Score**: 95.6090<br><br>• Lexical: 55.1717<br>• Title KNN: 24.9003<br>• Desc KNN: 12.3419<br>• Key KNN: 23.2867<br><br>**Keywords**:<br>• 'Climate Change' (0.9315) | **Topic**: Climate Change and Sustainable Development<br>**Total Score**: 72.0562<br><br>• Lexical: 52.0331<br>• Title KNN: 27.6359<br>• Desc KNN: 12.3920<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Climate Change' (0.9314)<br>• 'Environmental Policy' (0.8447) |
|
||||
| **Business & Accounting**<br>`"corporate strategy"` | **Topic**: Political Influence and Corporate Strategies<br>**Total Score**: 70.1485<br><br>• Lexical: 43.3796<br>• Title KNN: 25.4050<br>• Desc KNN: 0.0000<br>• Key KNN: 23.5512<br><br>**Keywords**:<br>• 'Business Strategy' (0.9420)<br>• 'Corporate Governance' (0.8537) | **Topic**: Corporate Management and Leadership<br>**Total Score**: 44.0634<br><br>• Lexical: 18.0385<br>• Title KNN: 26.0249<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
| **Psychology**<br>`"cognitive behavioral therapy"` | **Topic**: Psychological Treatments and Assessments<br>**Total Score**: 74.0625<br><br>• Lexical: 33.9552<br>• Title KNN: 26.3648<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8575<br><br>**Keywords**:<br>• 'Cognitive Behavioral Therapy' (0.9943)<br>• 'Rational Emotive Behavior Therapy' (0.8906) | **Topic**: Psychological Treatments and Assessments<br>**Total Score**: 74.0625<br><br>• Lexical: 33.9552<br>• Title KNN: 26.3648<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8575<br><br>**Keywords**:<br>• 'Cognitive Behavioral Therapy' (0.9943)<br>• 'Rational Emotive Behavior Therapy' (0.8906) |
|
||||
| **Materials Science**<br>`"nanomaterials synthesis"` | **Topic**: Copper-based nanomaterials and applications<br>**Total Score**: 79.3170<br><br>• Lexical: 31.3198<br>• Title KNN: 25.5626<br>• Desc KNN: 12.8334<br>• Key KNN: 23.2389<br><br>**Keywords**:<br>• 'Nanostructures' (0.9296)<br>• 'Nanocrystals' (0.8989) | **Topic**: Nanoparticles: synthesis and applications<br>**Total Score**: 51.4193<br><br>• Lexical: 41.6580<br>• Title KNN: 28.1196<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Nanomaterials' (0.9593)<br>• 'Nanoparticles' (0.9017) |
|
||||
| **Economics & Finance**<br>`"macroeconomic policy"` | **Topic**: Monetary Policy and Economic Impact<br>**Total Score**: 77.2466<br><br>• Lexical: 33.6052<br>• Title KNN: 27.9601<br>• Desc KNN: 12.7554<br>• Key KNN: 23.1466<br><br>**Keywords**:<br>• 'Monetary Policy' (0.9259)<br>• 'Fiscal Policy' (0.8719) | **Topic**: Monetary Policy and Economic Impact<br>**Total Score**: 54.1000<br><br>• Lexical: 33.6052<br>• Title KNN: 27.9601<br>• Desc KNN: 12.7554<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Monetary Policy' (0.9259)<br>• 'Fiscal Policy' (0.8719) |
|
||||
| **Health Professions**<br>`"physical therapy techniques"` | **Topic**: Physical Activity and Health<br>**Total Score**: 63.6719<br><br>• Lexical: 35.4732<br>• Title KNN: 24.8417<br>• Desc KNN: 0.0000<br>• Key KNN: 21.5571<br><br>**Keywords**:<br>• 'Physical Fitness' (0.8623)<br>• 'Exercise' (0.8567) | **Topic**: Physical Education and Training Studies<br>**Total Score**: 41.6865<br><br>• Lexical: 34.0993<br>• Title KNN: 25.9162<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Physical Education' (0.8518)<br>• 'Athletic Training' (0.8386) |
|
||||
| **Physics and Astronomy**<br>`"quantum mechanics"` | **Topic**: Quantum Mechanics and Applications<br>**Total Score**: 100.0179<br><br>• Lexical: 62.6773<br>• Title KNN: 29.4806<br>• Desc KNN: 12.8902<br>• Key KNN: 23.1009<br><br>**Keywords**:<br>• 'Quantum Interpretations' (0.9240)<br>• 'Quantum Measurement' (0.9195) | **Topic**: Quantum Mechanics and Non-Hermitian Physics<br>**Total Score**: 82.1469<br><br>• Lexical: 59.7515<br>• Title KNN: 28.2917<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8390<br><br>**Keywords**:<br>• 'Quantum Mechanics' (0.9936)<br>• 'Non-Hermitian Physics' (0.8265) |
|
||||
| **Chemistry**<br>`"organic synthesis"` | **Topic**: Organic Chemistry Synthesis Methods<br>**Total Score**: 93.3478<br><br>• Lexical: 51.1392<br>• Title KNN: 28.8346<br>• Desc KNN: 12.8016<br>• Key KNN: 21.2545<br><br>**Keywords**:<br>• 'Total Synthesis' (0.8502) | **Topic**: Organic Chemistry Synthesis Methods<br>**Total Score**: 72.0932<br><br>• Lexical: 51.1392<br>• Title KNN: 28.8346<br>• Desc KNN: 12.8016<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Total Synthesis' (0.8502) |
|
||||
| **Mathematics**<br>`"linear algebra"` | **Topic**: Advanced Algebra and Logic<br>**Total Score**: 69.1804<br><br>• Lexical: 21.0841<br>• Title KNN: 26.3365<br>• Desc KNN: 0.0000<br>• Key KNN: 21.7598<br><br>**Keywords**:<br>• 'MV-algebras' (0.8704)<br>• 'Algebraic Semantics' (0.8542) | **Topic**: Matrix Theory and Algorithms<br>**Total Score**: 51.1267<br><br>• Lexical: 42.7259<br>• Title KNN: 0.0000<br>• Desc KNN: 0.0000<br>• Key KNN: 24.3482<br><br>**Keywords**:<br>• 'Numerical Linear Algebra' (0.9739) |
|
||||
| **Neuroscience**<br>`"synaptic plasticity"` | **Topic**: Neuroscience and Neuropharmacology Research<br>**Total Score**: 59.8949<br><br>• Lexical: 34.7332<br>• Title KNN: 0.0000<br>• Desc KNN: 13.1294<br>• Key KNN: 24.0698<br><br>**Keywords**:<br>• 'Synaptic Plasticity' (0.9628)<br>• 'Neuronal Circuits' (0.8298) | **Topic**: Neuroscience and Neuropharmacology Research<br>**Total Score**: 59.8949<br><br>• Lexical: 34.7332<br>• Title KNN: 0.0000<br>• Desc KNN: 13.1294<br>• Key KNN: 24.0698<br><br>**Keywords**:<br>• 'Synaptic Plasticity' (0.9628)<br>• 'Neuronal Circuits' (0.8298) |
|
||||
| **Decision Sciences**<br>`"operations research optimization"` | **Topic**: Operations Management Techniques<br>**Total Score**: 72.2617<br><br>• Lexical: 45.7187<br>• Title KNN: 25.8359<br>• Desc KNN: 0.0000<br>• Key KNN: 20.3829<br><br>**Keywords**:<br>• 'Operations Management' (0.8153) | **Topic**: Management and Optimization Techniques<br>**Total Score**: 67.5272<br><br>• Lexical: 38.2684<br>• Title KNN: 27.0016<br>• Desc KNN: 0.0000<br>• Key KNN: 22.7133<br><br>**Keywords**:<br>• 'Operations Research' (0.9085) |
|
||||
| **Earth Sciences**<br>`"plate tectonics geology"` | **Topic**: Geological and Geochemical Analysis<br>**Total Score**: 81.4082<br><br>• Lexical: 47.1954<br>• Title KNN: 24.9384<br>• Desc KNN: 0.0000<br>• Key KNN: 24.0854<br><br>**Keywords**:<br>• 'Plate Tectonics' (0.9634)<br>• 'Tectonics' (0.9412) | **Topic**: Geological and Geophysical Studies<br>**Total Score**: 76.8806<br><br>• Lexical: 33.5170<br>• Title KNN: 25.9864<br>• Desc KNN: 0.0000<br>• Key KNN: 24.0846<br><br>**Keywords**:<br>• 'Plate Tectonics' (0.9634)<br>• 'Tectonic Model' (0.8970) |
|
||||
| **Immunology & Micro.**<br>`"t cell activation"` | **Topic**: T-cell and B-cell Immunology<br>**Total Score**: 101.7294<br><br>• Lexical: 58.5911<br>• Title KNN: 26.2074<br>• Desc KNN: 12.7561<br>• Key KNN: 22.2172<br><br>**Keywords**:<br>• 'Memory T Cells' (0.8887)<br>• 'TGF-ß' (0.8379) | **Topic**: T-cell and B-cell Immunology<br>**Total Score**: 79.5122<br><br>• Lexical: 58.5911<br>• Title KNN: 26.2074<br>• Desc KNN: 12.7561<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Memory T Cells' (0.8887)<br>• 'TGF-ß' (0.8379) |
|
||||
| **Energy**<br>`"solar cell efficiency"` | **Topic**: solar cell performance optimization<br>**Total Score**: 100.7331<br><br>• Lexical: 69.7479<br>• Title KNN: 28.9188<br>• Desc KNN: 12.4518<br>• Key KNN: 21.6075<br><br>**Keywords**:<br>• 'Energy Conversion Efficiency' (0.8643)<br>• 'Multijunction Solar Cells' (0.8636) | **Topic**: solar cell performance optimization<br>**Total Score**: 79.1256<br><br>• Lexical: 69.7479<br>• Title KNN: 28.9188<br>• Desc KNN: 12.4518<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Energy Conversion Efficiency' (0.8643)<br>• 'Multijunction Solar Cells' (0.8636) |
|
||||
| **Pharmacology & Tox.**<br>`"drug delivery systems"` | **Topic**: Advanced Drug Delivery Systems<br>**Total Score**: 101.0864<br><br>• Lexical: 82.7073<br>• Title KNN: 29.0884<br>• Desc KNN: 0.0000<br>• Key KNN: 23.9235<br><br>**Keywords**:<br>• 'Drug Delivery' (0.9569) | **Topic**: Advanced Drug Delivery Systems<br>**Total Score**: 77.1629<br><br>• Lexical: 82.7073<br>• Title KNN: 29.0884<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Drug Delivery' (0.9569) |
|
||||
| **Nursing**<br>`"patient care management"` | **Topic**: Family and Patient Care in ICU<br>**Total Score**: 81.2835<br><br>• Lexical: 62.5713<br>• Title KNN: 25.2221<br>• Desc KNN: 0.0000<br>• Key KNN: 23.3629<br><br>**Keywords**:<br>• 'Patient-Centered Care' (0.9345)<br>• 'Critical Care' (0.8654) | **Topic**: Health Services Management and Policy<br>**Total Score**: 49.0703<br><br>• Lexical: 44.9180<br>• Title KNN: 0.0000<br>• Desc KNN: 0.0000<br>• Key KNN: 24.1204<br><br>**Keywords**:<br>• 'patient care' (0.9648)<br>• 'hospital management' (0.9044) |
|
||||
| **Chemical Engineering**<br>`"process systems engineering"` | **Topic**: Systems Engineering Methodologies<br>**Total Score**: 69.4196<br><br>• Lexical: 46.7857<br>• Title KNN: 27.1586<br>• Desc KNN: 0.0000<br>• Key KNN: 21.4144<br><br>**Keywords**:<br>• 'Interdisciplinary System Eng.' (0.8566)<br>• 'Model-Based Systems Eng.' (0.8462) | **Topic**: Control Systems in Engineering<br>**Total Score**: 48.0307<br><br>• Lexical: 30.2824<br>• Title KNN: 25.1976<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
| **Dentistry**<br>`"endodontic treatment procedures"` | **Topic**: Endodontics and Root Canal Treatments<br>**Total Score**: 85.0595<br><br>• Lexical: 33.2248<br>• Title KNN: 27.3373<br>• Desc KNN: 12.9073<br>• Key KNN: 24.7433<br><br>**Keywords**:<br>• 'Endodontic Treatment' (0.9897)<br>• 'Regenerative Endodontics' (0.9185) | **Topic**: Endodontics and Root Canal Treatments<br>**Total Score**: 85.0595<br><br>• Lexical: 33.2248<br>• Title KNN: 27.3373<br>• Desc KNN: 12.9073<br>• Key KNN: 24.7433<br><br>**Keywords**:<br>• 'Endodontic Treatment' (0.9897)<br>• 'Regenerative Endodontics' (0.9185) |
|
||||
| **Veterinary**<br>`"veterinary medicine diagnosis"` | **Topic**: Animal health and immunology<br>**Total Score**: 70.5398<br><br>• Lexical: 36.6445<br>• Title KNN: 24.4738<br>• Desc KNN: 0.0000<br>• Key KNN: 24.6649<br><br>**Keywords**:<br>• 'Veterinary Diagnosis' (0.9866) | **Topic**: Veterinary Medicine and Surgery<br>**Total Score**: 63.5579<br><br>• Lexical: 36.3745<br>• Title KNN: 27.1833<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
+31375
File diff suppressed because it is too large
Load Diff
+28540
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,64 @@
|
||||
# Approach
|
||||
|
||||
**NDCG@10**, **MRR@10**, **Recall@10** :
|
||||
|
||||
- Topic: Document
|
||||
- OpenAlex: "display_name": "Impact of Light on Environment and Health",
|
||||
- Keyword: Query
|
||||
- OpenAlex: "keywords": [
|
||||
"Nighttime Light Data",
|
||||
"Economic Growth",
|
||||
"Light Pollution",
|
||||
"Remote Sensing",
|
||||
"Population Mapping",
|
||||
"Urbanization Dynamics",
|
||||
"Artificial Light",
|
||||
"Satellite Imagery",
|
||||
"Poverty Prediction",
|
||||
"Ecological Impacts" ]
|
||||
|
||||
Each Keyword is searched in the Topic display name Vector space
|
||||
|
||||
# Overall Leaderboard
|
||||
|
||||
> **Note** First round is invalid
|
||||
|
||||
First round (all topics, but included sibling topics messed up metrics)
|
||||
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Subfield NMI |
|
||||
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
||||
| 1 | `intfloat/e5-large-v2` | 1024 | 335.1M | 96.63ms | 5.7 | **0.2304** | 0.5054 | 0.0691 | 0.5917 |
|
||||
| 2 | `BAAI/bge-large-en-v1.5` | 1024 | 335.1M | 96.24ms | 5.8 | **0.2292** | 0.4944 | 0.0691 | 0.5921 |
|
||||
| 3 | `intfloat/multilingual-e5-large` | 1024 | 559.9M | 104.13ms | 4.8 | **0.2131** | 0.4789 | 0.0636 | 0.5900 |
|
||||
| 4 | `google/embeddinggemma-300m` | 768 | 307.6M | 47.11ms | 14.0 | **0.2121** | 0.4479 | 0.0637 | 0.6054 |
|
||||
| 5 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 29.11ms | 16.3 | **0.2100** | 0.4641 | 0.0620 | 0.5919 |
|
||||
| 6 | `intfloat/multilingual-e5-small` | 384 | 117.7M | 12.15ms | 55.3 | **0.2021** | 0.4446 | 0.0594 | 0.5880 |
|
||||
| 7 | `BAAI/bge-m3` | 1024 | 567.8M | 96.92ms | 4.8 | **0.1879** | 0.4219 | 0.0544 | 0.5929 |
|
||||
| 8 | `paraphrase-multilingual-mpnet-base-v2` | 768 | 278.0M | 29.65ms | 17.0 | **0.1792** | 0.3565 | 0.0520 | 0.6010 |
|
||||
| 9 | `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 384 | 117.7M | 12.12ms | 58.1 | **0.1748** | 0.3494 | 0.0514 | 0.5940 |
|
||||
|
||||
Second adjusted round (500 topics sample size)(seperated clustering into name and description fields)
|
||||
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |
|
||||
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
||||
| 1 | `intfloat/e5-large-v2` | 1024 | 335.1M | 101.71ms | 5.6 | **0.4261** | 0.3797 | 0.5758 | 0.5254 | 0.5947 |
|
||||
| 2 | `BAAI/bge-large-en-v1.5` | 1024 | 335.1M | 98.38ms | 5.6 | **0.4084** | 0.3628 | 0.5546 | 0.5591 | 0.5961 |
|
||||
| 3 | `intfloat/multilingual-e5-large` | 1024 | 559.9M | 111.27ms | 4.8 | **0.3956** | 0.3501 | 0.5424 | 0.5171 | 0.5845 |
|
||||
| 4 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 28.86ms | 17.9 | **0.3807** | 0.3357 | 0.5256 | 0.5374 | 0.5851 |
|
||||
| 5 | `google/embeddinggemma-300m` | 768 | 307.6M | 45.55ms | 15.7 | **0.3558** | 0.3121 | 0.4976 | 0.5485 | 0.6148 |
|
||||
| 6 | `intfloat/multilingual-e5-small` | 384 | 117.7M | 11.74ms | 57.6 | **0.3531** | 0.3050 | 0.5078 | 0.5450 | 0.5914 |
|
||||
| 7 | `sentence-transformers/all-MiniLM-L6-v2` | 384 | 22.7M | 7.07ms | 117.0 | **0.3471** | 0.3034 | 0.4882 | 0.5636 | 0.5936 |
|
||||
| 8 | `BAAI/bge-m3` | 1024 | 567.8M | 96.19ms | 4.9 | **0.3221** | 0.2829 | 0.4484 | 0.5246 | 0.5885 |
|
||||
| 9 | `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 384 | 117.7M | 12.63ms | 58.0 | **0.2350** | 0.2005 | 0.3468 | 0.5544 | 0.5984 |
|
||||
| 10 | `paraphrase-multilingual-mpnet-base-v2` | 768 | 278.0M | 24.67ms | 22.2 | **0.2347** | 0.1999 | 0.3480 | 0.5638 | 0.6043 |
|
||||
Baseline with all topics for second round:
|
||||
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |
|
||||
| 1 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 32.83ms | 16.5 | **0.3751** | 0.3290 | 0.5234 | 0.5374 | 0.5851 |
|
||||
|
||||
## Metric Definitions:
|
||||
|
||||
- **NDCG@10**: Normalized Discounted Cumulative Gain. Measures how well the query maps to the target topic at the top 10 positions.
|
||||
- **MRR@10**: Mean Reciprocal Rank. Looks at the average of `1 / rank` for the first correctly matched topic.
|
||||
- **Recall@10**: Percentage of times the target document (excluding sibling topics) was successfully retrieved in the top 10.
|
||||
- **Name NMI**: Normalized Mutual Information of K-Means clusters of topic display names against ground truth OpenAlex subfields.
|
||||
- **Desc NMI**: Normalized Mutual Information of K-Means clusters of topic descriptions against ground truth OpenAlex subfields.
|
||||
- **Query Latency**: Time to encode a single search keyword.
|
||||
- **Throughput**: Ingestion batch encoding speed.
|
||||
+3
-1
@@ -20,7 +20,9 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
|
||||
"sqlmodel~=0.0.33" \
|
||||
"argon2-cffi~=25.1.0" \
|
||||
"pandas~=2.3.3" \
|
||||
"pypdf==6.14.2"
|
||||
"pypdf==6.14.2"\
|
||||
"docker~=7.1.0" \
|
||||
"croniter~=6.0.0"
|
||||
|
||||
COPY [ "src/main", "/home" ]
|
||||
COPY [ "src/data", "/data" ]
|
||||
|
||||
+10
-1
@@ -6,5 +6,14 @@ RUN mkdir /test && \
|
||||
pip install --root-user-action=ignore --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu && \
|
||||
pip install --root-user-action=ignore --no-cache-dir "sentence-transformers~=5.5.1"
|
||||
|
||||
ARG MODEL_NAME=intfloat/multilingual-e5-base
|
||||
ENV MODEL_NAME=${MODEL_NAME}
|
||||
ENV SENTENCE_TRANSFORMERS_HOME=/models
|
||||
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('intfloat/multilingual-e5-base')"
|
||||
ENV HF_HOME=/models
|
||||
|
||||
RUN python -c "import os, sentence_transformers; sentence_transformers.SentenceTransformer(os.environ['MODEL_NAME'])"
|
||||
|
||||
ENV HF_HUB_OFFLINE=1
|
||||
ENV TRANSFORMERS_OFFLINE=1
|
||||
ENV HF_DATASETS_OFFLINE=1
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ task exportOpenApiSpec(type: Exec) {
|
||||
|
||||
task runServeContainer(type: Exec) {
|
||||
dependsOn createImage
|
||||
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
|
||||
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-v', '/var/run/docker.sock:/var/run/docker.sock', '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
|
||||
}
|
||||
|
||||
task stopServeContainer(type: Exec) {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
seconds = int(sys.argv[1]) if len(sys.argv) > 1 else 20
|
||||
logger.info(f"Demo job started, running for {seconds} seconds.")
|
||||
for elapsed in range(1, seconds + 1):
|
||||
time.sleep(1)
|
||||
if elapsed % 5 == 0:
|
||||
logger.info(f"Progress: {elapsed}/{seconds} seconds.")
|
||||
logger.info("Demo job finished successfully.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,21 @@
|
||||
# Background-jobs worker image. Build from the repo root:
|
||||
# docker build -f service/scripts/jobs-image/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest .
|
||||
FROM python:3.13-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Headless Chrome for the bund foerderportal crawler (Selenium).
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends chromium chromium-driver \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
ENV CHROME_BIN=/usr/bin/chromium \
|
||||
CHROMEDRIVER_PATH=/usr/bin/chromedriver
|
||||
|
||||
# Install dependencies
|
||||
COPY service/scripts/jobs-image/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy the job code.
|
||||
COPY background-jobs/app/ ./
|
||||
|
||||
COPY service/scripts/ ./service/scripts/
|
||||
@@ -0,0 +1,137 @@
|
||||
# Job Images
|
||||
|
||||
## Anlegen und Bearbeiten eines Jobs (UI)
|
||||
|
||||
Ein Job im Frontend ist nur eine **Definition** in der Datenbank, die auf ein
|
||||
Image zeigt. Der eigentliche Job-Code steckt im Image. Reihenfolge daher immer:
|
||||
**erst das Image nach Nexus pushen, dann den Job in der UI anlegen.**
|
||||
|
||||
### 1. Image bauen und pushen
|
||||
|
||||
Aus dem Repo-Root (Build-Kontext = Root), Beispiel News-Crawler (jedes
|
||||
Dockerfile nennt in seinem Kopf den eigenen Build-Befehl):
|
||||
|
||||
```bash
|
||||
docker build -f service/scripts/jobs-image/news-crawl/Dockerfile \
|
||||
-t docker.nes.uni-due.de/inse/jobs/news-crawl:latest .
|
||||
docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest
|
||||
```
|
||||
|
||||
Login zu Nexus vorher, falls nötig: `docker login docker.nes.uni-due.de`
|
||||
(Zugangsdaten wie in der Backend-`.env`, `BACKGROUND_JOBS_REGISTRY_*`).
|
||||
|
||||
Erst wenn Push erfolgreich war, taucht das Image in der Image-Auswahl der UI auf.
|
||||
|
||||
### 2. Job anlegen
|
||||
|
||||
1. Als **Superadmin** anmelden und die Seite **Jobs** öffnen.
|
||||
2. Oben rechts prüfen, dass die Karten **Docker-Daemon** und **Nexus-Registry**
|
||||
grün („Erreichbar") sind. Ist Nexus rot, bleibt die Image-Auswahl leer —
|
||||
dann Registry/`.env` prüfen, bevor es weitergeht.
|
||||
3. Auf **Neuer Job** klicken. Im Dialog:
|
||||
- **Name** – Pflichtfeld, muss eindeutig sein (sonst 409).
|
||||
- **Beschreibung**, **Ziel-Index** – optional, nur zur Anzeige.
|
||||
- **Image** – Pflichtfeld. In das Feld tippen und aus der
|
||||
Nexus-Autovervollständigung den passenden Tag wählen, z. B.
|
||||
`docker.nes.uni-due.de/inse/jobs/news-crawl:latest`. Leer = Fehler.
|
||||
- **Befehl** – optional. Wird an den `ENTRYPOINT` des Images **angehängt**
|
||||
(z. B. `--max-items 50`). Leer lassen, wenn die Image-Defaults reichen.
|
||||
- **Umgebungsvariablen** – optional, `KEY=VALUE` pro Zeile. Bei
|
||||
Nexus-Images werden die INSE-Zugangsdaten (Elasticsearch/LLM) ohnehin
|
||||
automatisch ergänzt; hier nur Zusätzliches/Overrides.
|
||||
4. **Speichern**. Der Job erscheint in der Tabelle, zunächst ohne Zeitplan
|
||||
(= nur manuell).
|
||||
|
||||
### 3. Job ausführen und beobachten
|
||||
|
||||
- **▶ Jetzt ausführen** startet einen Lauf. Das Backend pullt das Image und
|
||||
startet einen Container namens `<job-slug>-run-<id>`.
|
||||
- **⏹ Stoppen** bricht einen laufenden Lauf ab.
|
||||
- **🗎 Logs** zeigt die Container-Logs (live während des Laufs, danach die in der
|
||||
DB gespeicherten letzten Zeilen) sowie Dauer bzw. „läuft seit".
|
||||
- Schlägt der Pull fehl (Image gelöscht/nicht gepusht), wird der Lauf
|
||||
**fehlgeschlagen** mit `failed to pull image …` im Log — dann Image neu pushen.
|
||||
|
||||
### 4. Job bearbeiten
|
||||
|
||||
- In der **Name**-Spalte erscheint beim Hovern ein **Stift**-Symbol → öffnet den
|
||||
Bearbeiten-Dialog. Dort lassen sich **Name, Beschreibung, Ziel-Index, Image,
|
||||
Befehl und Env** ändern (gleiche Validierung wie beim Anlegen).
|
||||
- Das **Kalender**-Symbol in der Aktionsspalte öffnet den **Zeitplan**-Dialog:
|
||||
Cron-Ausdruck setzen (5 Felder) und Job aktiv/inaktiv schalten. Ein Zeitplan
|
||||
macht aus einem manuellen Job einen automatisch laufenden.
|
||||
- Bearbeiten ist gesperrt, solange ein Lauf des Jobs läuft.
|
||||
|
||||
### 5. Job löschen
|
||||
|
||||
Das **Papierkorb**-Symbol entfernt die Job-Definition. Das Image in Nexus bleibt
|
||||
davon unberührt (siehe unten zum Image-Löschen).
|
||||
|
||||
One Docker image per job script. Each image installs only its own dependencies
|
||||
and bakes its script as the `ENTRYPOINT`. Most jobs then run with no `command`
|
||||
override — the job definition just points `image` at the matching tag. Where
|
||||
several jobs share one script (the demos), they point at the same image and
|
||||
differ only by their `command`.
|
||||
|
||||
## Images
|
||||
|
||||
| Job (DB name) | Image | Entrypoint | Notes |
|
||||
| ----------------------- | --------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------- |
|
||||
| News-Crawler | `jobs/news-crawl` | `run_pipeline.py` | scrapy<2.13, Twisted<24.7; uploads to `NEWS_UPLOAD_INDEX` |
|
||||
| Bund-Crawler | `jobs/bund-crawl` | `gpc.data.py --max-rows 200` | headless Chrome; uploads to `BUND_UPLOAD_INDEX`; capped, full export is ~300k rows |
|
||||
| Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend |
|
||||
| News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend |
|
||||
| News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index |
|
||||
| Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows |
|
||||
|
||||
Each image is its own repository under the `jobs/` path namespace, prefixed
|
||||
`docker.nes.uni-due.de/inse/` (e.g. `docker.nes.uni-due.de/inse/jobs/news-crawl:latest`).
|
||||
The three demo jobs share the single `jobs/demo` repository.
|
||||
|
||||
The entrypoints carry no run limits: anything set in the job's `command` field is
|
||||
appended to the entrypoint, so limits (`--max-items`, `--max-docs`, `--limit`) are
|
||||
passed per run from the UI. The one exception is the Bund-Crawler, which keeps a
|
||||
`--max-rows` cap in the image because its full export is ~300k rows.
|
||||
|
||||
## Build
|
||||
|
||||
From the repo root (the build context must be the repo root so the Dockerfiles
|
||||
can copy `service/scripts/…` and `background-jobs/app/`):
|
||||
|
||||
```bash
|
||||
docker build -f service/scripts/jobs-image/news-crawl/Dockerfile \
|
||||
-t docker.nes.uni-due.de/inse/jobs/news-crawl:latest .
|
||||
docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest
|
||||
```
|
||||
|
||||
Each image's Dockerfile header lists its own build command.
|
||||
|
||||
## Running locally without pushing
|
||||
|
||||
Before each run the backend pulls the job's image from the registry when it is a
|
||||
registry image (host `docker.nes.uni-due.de`). **There is no fallback to a local
|
||||
copy:** if the pull fails, the run is marked _failed_ and the error is written to
|
||||
the run log — a stale local image is never used silently. To run a locally built
|
||||
image without pushing it, skip the pull attempt entirely:
|
||||
|
||||
```bash
|
||||
export BACKGROUND_JOBS_PULL_BEFORE_RUN=false
|
||||
```
|
||||
|
||||
With the pull disabled the backend uses whatever image with that tag exists on
|
||||
the Docker host, so `docker build -t docker.nes.uni-due.de/inse/jobs/<name>:latest .`
|
||||
is enough for local runs.
|
||||
|
||||
## Env vars
|
||||
|
||||
Because every tag lives under the `docker.nes.uni-due.de` registry host, the
|
||||
backend treats these as registry images and injects the INSE Elasticsearch / LLM
|
||||
credentials automatically (plus any per-job `env`).
|
||||
|
||||
Most images write to the test index by default: the crawlers upload into the
|
||||
index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to
|
||||
`docker-job_test` in their Dockerfile), and the project mapper and the keyword
|
||||
extraction write to `docker-job_test` via `--output-index` / `--target-index`.
|
||||
The exception is News-Topic-Mapping, which writes to `aktuell_openalex_topics`.
|
||||
To not contact Elasticsearch at all, pass `--skip-upload` (crawlers) or
|
||||
`--dry-run` (mappers) through the job's command field.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Bund-Crawler (foerderportal export via headless Chrome). Build from the repo root:
|
||||
# docker build -f service/scripts/jobs-image/bund-crawl/Dockerfile -t docker.nes.uni-due.de/inse/jobs/bund-crawl:latest .
|
||||
FROM python:3.13-slim
|
||||
|
||||
WORKDIR /app
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
# Upload the crawled projects into the shared test index (gpc.data.py reads
|
||||
# ELASTICSEARCH_INSE_* creds + BUND_UPLOAD_INDEX from the env).
|
||||
ENV BUND_UPLOAD_INDEX=docker-job_test
|
||||
|
||||
# Headless Chrome for the Selenium crawler.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends chromium chromium-driver \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
ENV CHROME_BIN=/usr/bin/chromium \
|
||||
CHROMEDRIVER_PATH=/usr/bin/chromedriver
|
||||
|
||||
COPY service/scripts/jobs-image/bund-crawl/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY service/scripts/projects/bund/ ./service/scripts/projects/bund/
|
||||
|
||||
WORKDIR /app/service/scripts/projects/bund
|
||||
|
||||
# Capped on purpose: the full export is ~300k rows, so an uncapped run would
|
||||
# write that entire volume into BUND_UPLOAD_INDEX. Raise or drop the cap by
|
||||
# passing --max-rows N through the job's command field.
|
||||
ENTRYPOINT ["python", "gpc.data.py", "--max-rows", "200"]
|
||||
@@ -0,0 +1,3 @@
|
||||
selenium~=4.20
|
||||
pandas~=2.2
|
||||
requests~=2.32
|
||||
@@ -0,0 +1,21 @@
|
||||
# News-Crawler (UDE 'aktuell'). Build from the repo root:
|
||||
# docker build -f service/scripts/jobs-image/news-crawl/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-crawl:latest .
|
||||
#
|
||||
# scrapy<2.13 + Twisted<24.7 are load-bearing: the spiders use the removed
|
||||
# start_requests() hook, and newer versions silently crawl 0 items.
|
||||
FROM python:3.13-slim
|
||||
|
||||
WORKDIR /app
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
# Upload the crawled articles into the shared test index (see upload_aktuell.py,
|
||||
# which reads ELASTICSEARCH_INSE_* creds + NEWS_UPLOAD_INDEX from the env).
|
||||
ENV NEWS_UPLOAD_INDEX=docker-job_test
|
||||
|
||||
COPY service/scripts/jobs-image/news-crawl/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY service/scripts/news/ude/ ./service/scripts/news/ude/
|
||||
|
||||
# Uncapped: crawls every article and uploads to NEWS_UPLOAD_INDEX. Limit a run by
|
||||
# passing --max-items N through the job's command field.
|
||||
ENTRYPOINT ["python", "service/scripts/news/ude/run_pipeline.py"]
|
||||
@@ -0,0 +1,3 @@
|
||||
scrapy>=2.11,<2.13
|
||||
Twisted>=22.10,<24.7
|
||||
requests~=2.32
|
||||
@@ -0,0 +1,21 @@
|
||||
# News keyword extraction (LLM keyword extraction into docker-job_test).
|
||||
# Build from the repo root:
|
||||
# docker build -f service/scripts/jobs-image/news-keywords/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-keywords:latest .
|
||||
#
|
||||
# Needs Elasticsearch + LLM creds (injected as env vars by the backend for
|
||||
# registry images). Calls the LLM once per entry.
|
||||
FROM python:3.13-slim
|
||||
|
||||
WORKDIR /app
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
COPY service/scripts/jobs-image/news-keywords/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY background-jobs/app/ ./
|
||||
|
||||
# Writes into docker-job_test, leaving production aktuell_postproc untouched.
|
||||
# A non-postproc target re-extracts entries that already have keywords (real
|
||||
# content) and updates them in place, keyed on news_id (re-runs overwrite, no
|
||||
# duplicates). Cap a run by appending --limit N via the job's command field.
|
||||
ENTRYPOINT ["python", "sync.py", "--update-keywords", "--target-index", "docker-job_test"]
|
||||
@@ -0,0 +1,3 @@
|
||||
requests~=2.32
|
||||
openai~=2.41
|
||||
python-dotenv~=1.0
|
||||
@@ -0,0 +1,24 @@
|
||||
# News-Topic-Mapping (news keywords -> OpenAlex topics). Build from the repo root:
|
||||
# docker build -f service/scripts/jobs-image/news-topics/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-topics:latest .
|
||||
#
|
||||
# map_news_topics imports map_project_topics as its "base", so both topic_mapper
|
||||
# packages must be present. Needs a reachable backend and Elasticsearch creds
|
||||
# (injected as env vars by the backend for registry images).
|
||||
FROM python:3.13-slim
|
||||
|
||||
WORKDIR /app
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
COPY service/scripts/jobs-image/news-topics/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY service/scripts/news/topic_mapper/ ./service/scripts/news/topic_mapper/
|
||||
COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/
|
||||
|
||||
# Writes topic mappings into aktuell_openalex_topics. Only maps (article, keyword)
|
||||
# pairs not already present in the output index; pass --overwrite to re-map all.
|
||||
# Uncapped: limit a run by passing --max-docs N through the job's command field.
|
||||
# host.docker.internal reaches the host backend for vector search.
|
||||
ENTRYPOINT ["python", "-m", "service.scripts.news.topic_mapper.map_news_topics", \
|
||||
"--output-index", "aktuell_openalex_topics", \
|
||||
"--api-base-url", "http://host.docker.internal:8000"]
|
||||
@@ -0,0 +1,2 @@
|
||||
httpx>=0.27
|
||||
python-dotenv>=1.0
|
||||
@@ -0,0 +1,25 @@
|
||||
# Projekt-Topic-Mapping (bund keywords -> OpenAlex topics). Build from the repo root:
|
||||
# docker build -f service/scripts/jobs-image/project-topics/Dockerfile -t docker.nes.uni-due.de/inse/jobs/project-topics:latest .
|
||||
#
|
||||
# Needs a reachable backend (vector search) and Elasticsearch creds. The creds
|
||||
# arrive as env vars injected by the backend for registry images.
|
||||
FROM python:3.13-slim
|
||||
|
||||
WORKDIR /app
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
COPY service/scripts/jobs-image/project-topics/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/
|
||||
|
||||
# Writes topic mappings into docker-job_test. Only maps (project, keyword) pairs
|
||||
# not already present in the output index, so an interrupted run can be resumed.
|
||||
# There is no overwrite flag: to re-map all, point --output-index at a fresh index.
|
||||
# Uncapped: limit a run by passing --max-docs N through the job's command field.
|
||||
# host.docker.internal reaches the host backend for vector search.
|
||||
ENTRYPOINT ["python", "-m", "service.scripts.projects.topic_mapper.map_project_topics", \
|
||||
"--source-index", "projects_bund_v1", \
|
||||
"--text-field", "Leistungsplansystematik_fullname", \
|
||||
"--output-index", "docker-job_test", \
|
||||
"--api-base-url", "http://host.docker.internal:8000"]
|
||||
@@ -0,0 +1,2 @@
|
||||
httpx>=0.27
|
||||
python-dotenv>=1.0
|
||||
@@ -0,0 +1,9 @@
|
||||
requests~=2.32
|
||||
openai~=2.41
|
||||
python-dotenv~=1.0
|
||||
scrapy>=2.11,<2.13
|
||||
Twisted>=22.10,<24.7
|
||||
httpx~=0.27
|
||||
selenium~=4.20
|
||||
pandas~=2.2
|
||||
elasticsearch>=7.17,<8
|
||||
@@ -0,0 +1,5 @@
|
||||
# extracted person-level data + generated artifacts — never commit
|
||||
cache/
|
||||
reports/
|
||||
*.log
|
||||
__pycache__/
|
||||
@@ -0,0 +1,518 @@
|
||||
# Multiplicator detection — offline pipeline
|
||||
|
||||
Detects **multiplicators** among an institution's researchers — *bridgers* (connect
|
||||
disconnected research communities), *mentors* (bring up junior/debutant co-authors), and
|
||||
*amplifiers* (patents, industry co-authorship, news visibility) — from OpenAlex plus the
|
||||
patent/project/news sources, and writes per-author scores + tags + evidence to a derived
|
||||
Elasticsearch index.
|
||||
|
||||
Follows the repo's offline pattern (`scripts/patents/index_org_patents.py`): all analysis
|
||||
and joining happen **offline**, the result lands in a **separate, institution-parameterised
|
||||
ES index**, and a thin read-only backend router is added only once the UI needs it.
|
||||
|
||||
**New here? Read [ROADMAP.md](docs/ROADMAP.md) first** — a ground-up explanation of the
|
||||
concept, every index field, the related work behind the metrics, and what's next.
|
||||
|
||||
## Status
|
||||
|
||||
**M0 — spike: done. M1 — metrics core: done** (exit check PASS). **M2 — pipeline +
|
||||
`multiplicators_v1` index: done** (idempotency verified). **M3 — amplifier signal
|
||||
joins: wired and indexed** (patents / news / CORDIS; results below) — remaining:
|
||||
the coach calibration session. **M4 — read router:** pending, once the UI needs it.
|
||||
All results per milestone are documented in the sections below.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
cd service/scripts/multipliers
|
||||
python -m venv .venv && source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Credentials are read from `service/src/main/inse/.env`:
|
||||
- `ELASTICSEARCH_URL` / `ELASTICSEARCH_API_KEY` — NES cluster (OpenAlex).
|
||||
- `ELASTICSEARCH_INSE_URL` / `ELASTICSEARCH_INSE_API_KEY` — INSE cluster (patents, news).
|
||||
|
||||
## Run the spike
|
||||
|
||||
```bash
|
||||
# Extract + audit for University of Duisburg-Essen (writes cache/ + report json)
|
||||
python spike_audit.py --institution-id I62318514
|
||||
|
||||
# Re-audit from the cache without re-hitting ES
|
||||
python spike_audit.py --institution-id I62318514 --skip-extract
|
||||
|
||||
# Also test write/delete permissions on the INSE cluster (throwaway index)
|
||||
python spike_audit.py --institution-id I62318514 --probe-writes
|
||||
```
|
||||
|
||||
Outputs land in `cache/`:
|
||||
- `authors_<ID>.jsonl.gz` — the two-group author union.
|
||||
- `works_<ID>.jsonl.gz` — full-authorship works (external co-authors + institutions).
|
||||
- `spike_report_<ID>.json` — the audit report.
|
||||
|
||||
The report answers: reproduction (author/work counts), field coverage
|
||||
(`author_position` / `is_corresponding` / institution `type`), scale (authors-per-work
|
||||
histogram, pair counts at caps 20/50/100), career quality (suspicious-profile %,
|
||||
`active_years` distribution), signal reachability (`org_patents` match-type breakdown),
|
||||
and write permissions.
|
||||
|
||||
`cache/` is disposable and should not be committed (it can be hundreds of MB and contains
|
||||
extracted person data).
|
||||
|
||||
---
|
||||
|
||||
## M0 spike results (I62318514, run 2026-07-15)
|
||||
|
||||
The spike existed to answer six questions the whole design was betting on. Full raw
|
||||
numbers in `cache/spike_report_I62318514.json`; this section explains each stat, why it
|
||||
was measured, and which downstream metric it feeds.
|
||||
|
||||
### 1. Reproduction — is the extraction correct?
|
||||
|
||||
| Stat | Value | Meaning |
|
||||
|---|---|---|
|
||||
| Author count | **4,921** | Exactly reproduces the audited seed extraction (`llm_evaluations/basic_applied_experimental/ude_audit_report.json`). Our port of the query is faithful. |
|
||||
| — `backend_compatible` group | 4,740 | Authors with `last_known_institutions == UDE` **and** a recent UDE affiliation. |
|
||||
| — `empty_last_known_recent` group | 181 | Authors with a recent UDE affiliation but **no** `last_known_institutions` at all. Without this second query group, 3.7% of the cohort would silently vanish — this is why the author set is a *union of two queries*, not one. |
|
||||
| Work count | **183,661** | All works by those 4,921 authors, globally, unrestricted by institution or year. Matches the seed audit. |
|
||||
|
||||
**Contributes to:** everything. This is the corpus. The "all works globally" property is
|
||||
load-bearing for the career metrics: it means `active_years` is *exact* for in-set
|
||||
authors (we see their complete history), while for external co-authors we only see works
|
||||
shared with UDE — which is why mentor metrics are restricted to UDE-internal pairs.
|
||||
|
||||
### 2. Field coverage — are the fields the metrics need actually populated?
|
||||
|
||||
The OpenAlex Pydantic models declare these fields, but that says nothing about whether
|
||||
the ES index actually populates them. Two sub-scores would have died silently.
|
||||
|
||||
| Stat | Value | Feeds | Verdict |
|
||||
|---|---|---|---|
|
||||
| Authorships total | 3,805,507 | — | denominator |
|
||||
| `author_position` populated | **100%** | `last_author_with_junior_first` (mentor): the classic supervision signature — PI last, junior first. | ✅ computable |
|
||||
| `is_corresponding` populated | **100%** | reserved for later refinement (corresponding-author weighting). | ✅ available |
|
||||
| `institutions.type` populated | **99.91%** | `cross_sector_share` / `industry_coauthor_share` (bridger + amplifier): share of works with a co-author at `type == "company"`. | ✅ computable |
|
||||
| Company-institution occurrences | **67,131** | same | dense enough to rank on — this is the strongest *ID-linked* industry signal we have, stronger than any name-matched source. |
|
||||
|
||||
**Contributes to:** confirms the metric set needs no fallbacks. Had `institutions.type`
|
||||
been empty, the amplifier would have collapsed onto 123 high-confidence patents (see §6).
|
||||
|
||||
### 3. Scale — where does the pair explosion land, and what cap do we need?
|
||||
|
||||
Co-author pair generation is quadratic per work: a work with *n* authors yields
|
||||
*n·(n−1)/2* pairs. The distribution of authors-per-work decides whether the self-join is
|
||||
feasible locally and where to cap it.
|
||||
|
||||
| Stat | Value |
|
||||
|---|---|
|
||||
| Authors per work p50 / p90 / p99 / max | **5 / 17 / 144 / 4,839** |
|
||||
| Works with > 100 authors | **2,459** (1.3%) |
|
||||
| Pair instances at cap 20 / 50 / 100 | **3.9M / 8.0M / 13.9M** |
|
||||
|
||||
**Why `max_authors_per_work` matters** (the cap): the max-4,839-author work alone would
|
||||
generate ~11.7M pairs — more than the *entire rest of the corpus* at cap 50 — and a
|
||||
hyperauthored consortium paper (CERN/medical mega-trials) carries no real collaboration
|
||||
signal: being 1 of 4,839 names says nothing about who actually works with whom, but it
|
||||
*would* create a giant artificial clique that inflates betweenness and strength for
|
||||
everyone on it, poisoning the bridger score. The cap drops works above the threshold
|
||||
from **graph construction only** — they still count for publication years / `active_years`.
|
||||
|
||||
**Chosen: `max_authors_per_work = 50`.** Rationale: p90 = 17, so a cap of 50 keeps ≥ 99%
|
||||
of works (cap sits well above p90, below p99 = 144) while excluding only true
|
||||
hyperauthorship; the resulting 8.0M pair instances collapse to ~1–2M distinct edges,
|
||||
comfortably in-memory for polars. It's a config value (`extraction.max_authors_per_work`),
|
||||
not code — tunable per institution.
|
||||
|
||||
**Contributes to:** graph construction (Stage C); confirms the "pure local compute, no
|
||||
DuckDB/warehouse" bet.
|
||||
|
||||
### 4. Career quality — can we bucket careers, and how bad is profile merging?
|
||||
|
||||
Background: `analysis/career_stage/` established that `first_publication_year` is
|
||||
unreliable at UDE (merged OpenAlex profiles → debut years of 1893/1906 for active
|
||||
professors) and that `active_years` (distinct years with ≥ 1 publication) is robust.
|
||||
The pipeline therefore buckets by `active_years` and uses prefix-counted
|
||||
`active_years_at(A, Y)` instead of debut years for the mentor metrics.
|
||||
|
||||
| Stat | Value | Meaning / use |
|
||||
|---|---|---|
|
||||
| Suspicious profiles | **225 (4.6%)** | `first_year < 1970 or career_span > 60` (same flag as `persons/logic.py`). These are likely *merged identities*. They are **not dropped** — their `active_years` is still fine — but their evidence is marked `low_confidence`. Especially important for the **bridger** score: a merged profile is one node standing in for two people and *systematically* fakes bridging. |
|
||||
| `active_years` p50 / p90 / max / mean | **4 / 25 / 60 / 8.9** | p50 = 4 means **half the cohort is career-stage "Early" (≤ 4)**. This is why percentile normalization happens *within career buckets* (Early/Emerging/Established/Senior via `_classify_career_stage`): institution-wide percentiles would just rank seniority, and no early-career person could ever surface as a multiplicator. |
|
||||
|
||||
**Contributes to:** career bucketing (scoring), mentor junior/senior thresholds,
|
||||
confidence flags on evidence.
|
||||
|
||||
### 5. Permissions — can we ship the result anywhere?
|
||||
|
||||
Initial spike: `PUT` to create an index on the INSE cluster → **403** (key can read, not
|
||||
create). Resolved 2026-07-15: **`multiplicators_v1` was created by the cluster admin**,
|
||||
and the standard INSE key can now write to it (verified: doc create + delete both
|
||||
succeed). The build step must therefore *never* try to create/re-create the index — only
|
||||
delete-by-institution + bulk-index into the existing one (same constraint as
|
||||
`org_patents`, whose key also rejects `_delete_by_query`; use the search + bulk-delete
|
||||
loop from `patents/org/elastic_search_client.py`).
|
||||
|
||||
**Contributes to:** M2 index/build design.
|
||||
|
||||
### 6. Signal reachability — which amplifier sources are real?
|
||||
|
||||
| Stat | Value | Meaning |
|
||||
|---|---|---|
|
||||
| `org_patents` docs for UDE | **436** | The patent→OpenAlex-author link index exists and is populated. |
|
||||
| — `match_type: name` | 313 | Name-only match. **Evidence only, weight 0** — name matching is the weakest link type. |
|
||||
| — `match_type: both` | 65 | Institution assignee **and** name match — highest confidence. **Scores.** |
|
||||
| — `match_type: institution` | 58 | Institution-assignee match. **Scores.** |
|
||||
|
||||
**Contributes to:** amplifier sub-score. Only 123 patents are high-confidence, so patents
|
||||
are a *secondary* amplifier signal; the primary is `industry_coauthor_share` (67k
|
||||
ID-linked company co-authorships, §2). News (`aktuell_postproc`, exact-string person
|
||||
match) enters at low weight; DFG (token containment) and Bund (no person link) are
|
||||
excluded entirely.
|
||||
|
||||
### Spike exit criteria — all met (see below for M1)
|
||||
|
||||
- ✅ Extraction reproduces the audited counts exactly.
|
||||
- ✅ Every planned metric is confirmed computable — no fallbacks needed.
|
||||
- ✅ `max_authors_per_work = 50` chosen from measured data.
|
||||
- ✅ Write path to `multiplicators_v1` verified end-to-end.
|
||||
- ✅ Amplifier signal priorities re-ordered based on measured density
|
||||
(industry co-authorship primary, patents secondary).
|
||||
|
||||
---
|
||||
|
||||
## M1 results (metrics core, run 2026-07-15)
|
||||
|
||||
Modules: `graph.py` (co-author graph via polars self-join, decay weights, hyperauthorship
|
||||
cap), `metrics.py` (Brandes betweenness with inverted weights, Burt constraint on the
|
||||
full graph incl. externals, field entropy, industry co-author share, debut-year-free
|
||||
mentor metrics on `active_years_at`), `scoring.py` + `multipliers.yaml`
|
||||
(within-career-bucket percentiles → weighted sub-scores → tags). 26 unit tests
|
||||
(`pytest`), including exact agreement with networkx oracles for betweenness/constraint
|
||||
and the planted-1893-outlier regression guard for `active_years_at`.
|
||||
|
||||
Run with:
|
||||
|
||||
```bash
|
||||
python build.py --institution-id I62318514 # scores + summary from the cache
|
||||
python validate_sample.py --institution-id I62318514 # 60-person exit check
|
||||
```
|
||||
|
||||
### Full-corpus run (I62318514)
|
||||
|
||||
| Stat | Value |
|
||||
|---|---|
|
||||
| Runtime end-to-end | **2.6 min** (load 15s, graph 31s, metrics 112s) — exit criterion was < 15 min |
|
||||
| Graph | 639,544 nodes (4,921 focal + externals), 4,143,499 edges |
|
||||
| Works used / capped | 160,396 / 4,823 (`max_authors_per_work = 50`) |
|
||||
| Tags at threshold 0.85 | bridger 66, mentor 91, amplifier 609 |
|
||||
|
||||
The amplifier tag count is inflated for now: only `industry_coauthor_share` exists at M1
|
||||
(patents/news/CORDIS join in M3), so weight redistribution makes it a single-metric
|
||||
sub-score. Ignore amplifier tags until M3.
|
||||
|
||||
### M1 exit check — PASS
|
||||
|
||||
Against the 60 hand-labeled researchers in `analysis/career_stage/career_stage_sample.csv`
|
||||
(31 Professor / 29 Researcher), mentor scores must concentrate on professors:
|
||||
|
||||
| known status | n | median mentor score |
|
||||
|---|---|---|
|
||||
| Professor | 25 | **0.715** |
|
||||
| Researcher | 18 | 0.493 |
|
||||
|
||||
Top of the list is face-valid: senior professors with 30–50 mentored juniors and strong
|
||||
last-author-with-junior-first signatures (Bacher, Sures, Hering, Gunzer, …). The two
|
||||
high-scoring "Researchers" are informative, not embarrassing: e.g. a core-facility
|
||||
scientist with 37 juniors but **zero** last-author works — the independent supervision
|
||||
signature correctly separates "publishes with many juniors" from "supervises them".
|
||||
|
||||
### ⚠ Cohort-coverage finding (must be decided in M2)
|
||||
|
||||
17 of the 60 sample people are missing from the 4,921-author cohort. Diagnosed causes:
|
||||
|
||||
1. **University-hospital clinicians are systematically excluded.** Prominent UDE
|
||||
medicine professors (e.g. Witzke, Bingel) have
|
||||
`last_known_institutions = Essen University Hospital (I4210119759)`, and the
|
||||
hospital is **not** in UDE's OpenAlex lineage — OpenAlex models it as a *related*
|
||||
institution, not a child. **2,437 active (2025+) authors** sit behind this gap —
|
||||
roughly half a cohort. Fix: make the cohort definition accept a list of
|
||||
institution IDs (`I62318514` + `I4210119759` + …) per deployment, sourced from
|
||||
`associated_institutions` and confirmed by a human.
|
||||
2. **Stale affiliation years exclude current staff.** E.g. Saccà has
|
||||
`last_known = UDE` but no `affiliations.years >= 2025` entry, so the recency
|
||||
filter drops her. Fix candidates: widen the window (>= 2023), or accept
|
||||
`last_known = UDE` alone with a works-recency check.
|
||||
|
||||
Both are extraction-time cohort decisions with precision/recall tradeoffs — they belong
|
||||
to the coaches/product owner, not to code defaults.
|
||||
|
||||
---
|
||||
|
||||
## M1 validation in detail (what was checked, against what ground truth)
|
||||
|
||||
### The ground truth
|
||||
|
||||
`analysis/career_stage/career_stage_sample.csv` — 60 UDE researchers with manually
|
||||
researched **role labels** (`known_status`: 31 Professor / 29 Researcher incl. doctoral),
|
||||
across five discipline groups (Biology, CS, Engineering, Medicine, Sociology), each with
|
||||
an OpenAlex author ID (so the join to our scores is exact — no name matching involved).
|
||||
The sample was originally built for the career-stage analysis; it does **not** label
|
||||
anyone as a "multiplicator" — no such ground truth exists yet (that is the M3 golden set
|
||||
the innovation coaches will provide).
|
||||
|
||||
### What exactly was evaluated
|
||||
|
||||
One directional sanity check on the riskiest sub-score: *supervision is part of the
|
||||
professor role, so if the mentor sub-score measures anything like real mentorship,
|
||||
professors must score systematically higher than researchers.* Defined check:
|
||||
professors' **median mentor sub-score > researchers'**.
|
||||
|
||||
The check is stronger than it looks because scores are percentiles **within career
|
||||
buckets**: a Senior researcher is compared against Senior professors, not against PhD
|
||||
students, so a trivial "older people score higher" effect is largely normalized away —
|
||||
the gap has to come from mentor behaviour (juniors mentored, last-author-with-junior-
|
||||
first works), not raw seniority.
|
||||
|
||||
### Results (UDE-only cohort, 2026-07-15; archived as `cache/*_I62318514.udeonly.json`)
|
||||
|
||||
43 of 60 matched (17 missing — see the cohort-coverage finding above). Medians:
|
||||
|
||||
| sub-score | Professor (n=25) | Researcher (n=18) | check |
|
||||
|---|---|---|---|
|
||||
| **mentor** | **0.715** | **0.493** | **PASS** |
|
||||
| bridger | 0.603 | 0.508 | (informational) |
|
||||
| amplifier | 0.655 | 0.413 | (single-metric until M3 — ignore) |
|
||||
|
||||
Ranking detail, more convincing than the medians:
|
||||
|
||||
- Top = senior professors with strong dual signals: Gerd Bacher (37 juniors, 16
|
||||
last-author-junior-first works), Bernd Sures (52, 24), Daniel Hering (35, 25),
|
||||
Matthias Gunzer (54 juniors).
|
||||
- Bottom = early-career researchers with 0 juniors.
|
||||
- The two high-scoring "Researchers" are the system working, not failing:
|
||||
Birte Möhlendick (0.924, 12 juniors) — plausibly a group leader whose formal title
|
||||
lags her role; Farnusch Kaschani (0.714, **37 juniors but 0 last-author works**) —
|
||||
the classic core-facility-scientist profile: on many students' papers without
|
||||
supervising them. The two mentor signals disagreeing on exactly this person is why
|
||||
`last_author_with_junior_first` exists as an independent cross-check.
|
||||
|
||||
### What this does NOT show
|
||||
|
||||
It validates the *direction* of the mentor proxy, not that top-ranked people are good
|
||||
mentors or multiplicators: professor-vs-researcher is a coarse label, n=43 is small,
|
||||
bridger has no ground truth in this sample, and amplifier is a single-metric score until
|
||||
M3. The real validation is the coach golden set (M3). This check is kept as a
|
||||
regression: re-run `validate_sample.py` after every weight change or dump refresh.
|
||||
|
||||
---
|
||||
|
||||
## Cohort fix + re-run (2026-07-15, config version 2)
|
||||
|
||||
The hospital gap above is fixed by a **configurable cohort list**: `cohorts.<primary-ID>.
|
||||
institution_ids` in `multipliers.yaml`. **How the list was discovered — and how to
|
||||
build one for another university — is documented in
|
||||
[ASSOCIATED_INSTITUTIONS.md](docs/ASSOCIATED_INSTITUTIONS.md).** For UDE it holds 9 institutions — UDE, Essen
|
||||
University Hospital, the West German Heart Center, the Erwin L. Hahn Institute, and the
|
||||
five OpenAlex lineage children (RISP, DTNW, KWI, ZBT, IUTA) — with the deliberate
|
||||
exclusions (Kliniken Essen-Mitte, the independent An-Institute) documented inline for
|
||||
the coaches to revisit. Candidates were sourced from `associated_institutions` in
|
||||
`openalex-institutions`; the extractor now matches `last_known_institutions` /
|
||||
`affiliations` by **institution ID terms** over the whole list.
|
||||
|
||||
### Before / after (UDE-only → 9-institution cohort)
|
||||
|
||||
| | UDE-only | cohort | note |
|
||||
|---|---|---|---|
|
||||
| Authors | 4,921 | **6,583** | +1,662, mostly hospital clinicians |
|
||||
| Works | 183,661 | **221,603** | |
|
||||
| Graph | 640k nodes / 4.14M edges | 764k / 5.26M | |
|
||||
| Pipeline runtime | 2.6 min | **4.5 min** | still far under the 15-min criterion |
|
||||
| Sample matched | 43/60 | **45/60** | Witzke + Bingel recovered |
|
||||
| Mentor exit check | 0.715 vs 0.493 PASS | **0.699 vs 0.493 PASS** | stable |
|
||||
| Tags (bridger/mentor/amplifier) | 66/91/609 | 96/131/763 | scales with cohort |
|
||||
|
||||
Face validity of the fix: both recovered professors immediately tag as mentors with
|
||||
strong evidence — Witzke (Senior, 73 juniors mentored), Bingel (Senior, 34 juniors,
|
||||
21 last-author-with-junior-first works).
|
||||
|
||||
### The remaining 15 missing, fully diagnosed
|
||||
|
||||
- **9 × correctly excluded** — they left UDE (`last_known` now Halle, Würzburg,
|
||||
Greifswald, OU Netherlands, ISG, or none). The sample is older than the corpus;
|
||||
these are not gaps.
|
||||
- **6 × stale-affiliation cases** — `last_known` IS in the cohort but their most
|
||||
recent cohort affiliation year is 2021–2024, so the `affiliation_years_gte: 2025`
|
||||
recency filter drops them. At least one (Saccà, last seen 2024) is a current
|
||||
professor — publication lag alone can push someone out of a 1-year window.
|
||||
**Recommendation for M2:** set `extraction.affiliation_years_gte: 2023` (already
|
||||
config) — captures normal publication lag while still excluding long-departed
|
||||
authors. Decide with the coaches; it trades a little precision for recall.
|
||||
|
||||
---
|
||||
|
||||
## M2 — pipeline + ES index (done 2026-07-15)
|
||||
|
||||
New modules: `extract.py` (canonical cohort-aware extraction, config-driven),
|
||||
`index.py` (`MultiplicatorsIndexClient` for `multiplicators_v1` on the INSE cluster),
|
||||
`build.py` (single entry point: extract → graph → metrics → scoring → index).
|
||||
`spike_audit.py` remains self-contained for auditing any institution.
|
||||
|
||||
```bash
|
||||
python build.py --institution-id I62318514 # full run (reuses cache)
|
||||
python build.py --institution-id I62318514 --force-extract # refresh from ES
|
||||
python build.py --institution-id I62318514 --no-index # local artifacts only
|
||||
```
|
||||
|
||||
### Index contract (`multiplicators_v1`, INSE cluster)
|
||||
|
||||
- Doc `_id` = `<institution_short>_<author_short>` (e.g. `I62318514_A5087456839`);
|
||||
one doc per author per institution.
|
||||
- Every doc: raw metrics, per-bucket percentiles, sub-scores, tags, career bucket,
|
||||
`suspicious_profile`, evidence (junior ids), `config_hash`, `computed_at`,
|
||||
`cohort_institution_ids`. Explicit mapping is PUT on every run (additive).
|
||||
- Idempotent re-runs: collect the institution's doc ids → bulk-delete → bulk-index →
|
||||
poll `_count` until the expected count is visible. **Verified: delete 9,474 →
|
||||
index 9,474 → count 9,474.**
|
||||
|
||||
### Key-permission gotchas (learned the hard way, encoded in `index.py`)
|
||||
|
||||
The admin-created index + standard INSE key allows: read, `_bulk` index/delete,
|
||||
`_mapping` updates, `_count`. It does **not** allow: index create/delete,
|
||||
`_delete_by_query` (same as org_patents), and — new finding — **`_refresh`
|
||||
(`indices:admin/refresh` → 403)**. A first client version silently relied on refresh
|
||||
and saw phantom docs during delete (stale visibility inflated the delete count) and a
|
||||
too-early post-index count. The client now never calls `_refresh`: it collects all doc
|
||||
ids BEFORE deleting, and verifies by polling `_count` (auto-refresh ≈ 1s) instead.
|
||||
|
||||
### Run with `affiliation_years_gte: 2023` (config v2 → v3)
|
||||
|
||||
| | 2025 cutoff | 2023 cutoff |
|
||||
|---|---|---|
|
||||
| Authors / works | 6,583 / 221,603 | **9,475 / 267,467** |
|
||||
| Graph | 764k nodes / 5.26M edges | 865k / 5.82M |
|
||||
| Full runtime (incl. extract + index) | — | **~14.5 min** |
|
||||
| Sample matched | 45/60 | **51/60** |
|
||||
| Mentor exit check | 0.699 vs 0.493 PASS | **0.740 vs 0.494 PASS** (wider gap) |
|
||||
|
||||
The 9 still-missing sample people are exactly the 9 confirmed leavers (last_known now
|
||||
Halle, Würzburg, Greifswald, …) — correct exclusions, zero unexplained gaps. All six
|
||||
stale-affiliation cases were recovered (some via 2023+ affiliations with the hospital /
|
||||
institute cohort members rather than UDE itself).
|
||||
|
||||
Career-bucket distribution in the index: Early 5,361 / Emerging 1,591 /
|
||||
Established 777 / Senior 1,745. Tags: bridger 133, mentor 161, amplifier 1,107
|
||||
(amplifier still single-metric until M3 — ignore).
|
||||
|
||||
### Next (M3)
|
||||
|
||||
Wire the signal joins into the amplifier score (`org_patents` match_type
|
||||
institution/both, news with name normalization at low weight, CORDIS DOI-join),
|
||||
then calibrate the YAML weights with the innovation coaches against their golden set.
|
||||
M4 (read router in `inse/`) once the UI needs it.
|
||||
|
||||
---
|
||||
|
||||
## M3 — amplifier signal joins (done 2026-07-15)
|
||||
|
||||
Before wiring, a live-index audit showed the amplifier was degenerate: its only input
|
||||
(`industry_coauthor_share`) was 0 for 61.5% of the cohort, and the "top amplifiers"
|
||||
were small-denominator ratio artifacts (share = 1.0 with 2 typed works). Two fixes:
|
||||
|
||||
1. **Shrinkage**: scoring now uses `industry_coauthor_share_shrunk = company/(typed+k)`
|
||||
(k=5, config `signals.industry_share_shrinkage_k`); the raw share stays in the doc.
|
||||
2. **Three independent signal joins** (`signals.py`), weights in YAML
|
||||
(shrunk share 0.50 / patents 0.25 / CORDIS 0.15 / news 0.10):
|
||||
|
||||
| signal | join mechanism | UDE yield (9,474 authors) |
|
||||
|---|---|---|
|
||||
| `patent_count` | `org_patents.matched_authors` author IDs, `match_type ∈ {institution, both}`; name-only kept as `patent_count_name_only` evidence, never scored | 55 authors (17 more name-only) |
|
||||
| `news_mentions` | `aktuell_postproc` LLM-extracted names, normalized-exact match (casefold + diacritic fold); a normalized name shared by >1 cohort authors credits NO ONE | 1,369 authors; **839 ambiguous names skipped** (precision over recall) |
|
||||
| `cordis_eu_projects` | DOI overlap with `cordis_eu_*_publications` → distinct projectIDs. **Case-insensitive term matching** — 21% of CORDIS DOIs contain uppercase and a plain `terms` query silently misses them | 1,342 authors |
|
||||
|
||||
Signal join runtime ≈ 9 min (the case-insensitive CORDIS batches dominate); total
|
||||
pipeline ≈ 20 min. Mentor/bridger untouched: validation unchanged (51/60, mentor
|
||||
check PASS 0.740 vs 0.494).
|
||||
|
||||
### Effect on the amplifier tag
|
||||
|
||||
Tags went **1,107 → 10**. With four independent inputs, a ≥0.85 *weighted mean* of
|
||||
within-bucket percentiles requires being near the top on most channels — the tag now
|
||||
means something. The new top-10 is face-valid (Wiltfang, Erbel, Kaiser, Schierning —
|
||||
patent-holding, industry-connected, media-visible seniors). Two open calibration
|
||||
questions for the coaches:
|
||||
|
||||
- **Threshold per tag?** 0.85 yields 133 bridgers / 161 mentors / 10 amplifiers.
|
||||
If more amplifier candidates are wanted, either lower a per-tag threshold
|
||||
(currently one global `tags.threshold`) or re-weight.
|
||||
- **Split-profile artifact**: an Early-bucket author with 1 active year made top-10
|
||||
amplifier — almost certainly a split OpenAlex profile of a senior professor
|
||||
(patents/news land on the fragment). Bucket-relative ranking amplifies fragments;
|
||||
the `suspicious_profile` flag does not catch splits (only merges). Known
|
||||
limitation — ORCID-based resolution is the deferred fix.
|
||||
|
||||
### M3 remaining
|
||||
|
||||
The **coach calibration session**: golden set of 10–20 known multiplicators, tune the
|
||||
YAML (weights, per-tag thresholds), re-run `validate_sample.py` as regression.
|
||||
|
||||
---
|
||||
|
||||
## Network visualization index (`multiplicator_networks_v1`, added 2026-07-16)
|
||||
|
||||
The scores index answers *what did this person score*; this companion index answers
|
||||
*who are they connected to and how* — everything a frontend needs to draw the
|
||||
ego-network figures (force layout, role colors, tooltips) without recomputing
|
||||
anything. Materialized by `build.py` (`networks.py`) while the full graph is in
|
||||
memory, because the **neighbor-neighbor edges** that make graph shape readable
|
||||
(dense mesh = one community; spokes with gaps = brokered structural holes) come from
|
||||
works that do NOT include the ego — no request-time query can reconstruct them.
|
||||
|
||||
One doc per focal author, `_id = <institution>_<author>` (same scheme as scores):
|
||||
|
||||
| field | content |
|
||||
|---|---|
|
||||
| `nodes[]` | `{id, name, role, inst, active_years, suspicious, company_insts?}`; role ∈ ego / mentee / cohort / industry / external. **`industry` is tie-level**: assigned only when a company affiliation of the neighbour appears on a work *shared with the ego* (matching what `industry_coauthor_share` counts), and `company_insts` names the triggering companies — a lifetime-flag version painted predominantly-academic people orange over a single old dual affiliation. `inst` is the author's most frequent institution. |
|
||||
| `edges[]` | `{a, b, w, n_works, cross, first_year, last_year}` — `w` = decayed tie strength, `cross` = mostly cross-institution |
|
||||
| `ego{}` | header duplicate (bucket, tags, sub_scores, max_sub_score) so a network endpoint renders standalone |
|
||||
| totals | `total_coauthors`, `cohort_coauthors`, `mentee_count`, `shown`, `shown_mentees` |
|
||||
| provenance | `config_hash`, `computed_at`, `cohort_institution_ids` |
|
||||
|
||||
Selection: strongest `network.max_nodes` (42) co-authors by tie weight with up to
|
||||
`network.max_forced_mentees` (14) mentees force-included first — mentees' ties are
|
||||
decayed and team-size-divided, so a pure top-by-weight cut hides exactly the people
|
||||
the mentor score is about. Positions are NOT stored: the webapp's echarts `graph`
|
||||
series (force layout) lays out at render time; map role → color, active_years →
|
||||
symbol size, `cross` → dashed line.
|
||||
|
||||
`nodes`/`edges` are mapped `"enabled": false` (stored, never indexed) — the index
|
||||
stays small and fast for the queryable header fields (`institution_id`, `author_id`,
|
||||
`ego.tags`, `computed_at`, …). Skip building with `--no-network`.
|
||||
|
||||
### Regenerating the HTML report
|
||||
|
||||
`make_report.py` renders a self-contained HTML report of four contrasting cases
|
||||
straight from the two live ES indices — no local cache required, so it works on any
|
||||
machine with cluster access after a build has run:
|
||||
|
||||
```bash
|
||||
python make_report.py --institution-id I62318514
|
||||
# -> reports/multiplier_networks.html (open in any browser; light/dark toggle)
|
||||
|
||||
python make_report.py --institution-id I62318514 \
|
||||
--author-ids A5113304257,A5043495754,A5007801159,A5123934012 # explicit cast
|
||||
```
|
||||
|
||||
The cast is pinned in `report.featured_author_ids` (config) so the report is
|
||||
reproducible across weight tunes and dump refreshes; `--author-ids` overrides it and
|
||||
`--auto` falls back to selecting the current top bridger / mentor / amplifier plus the
|
||||
highest-scoring person who carries **no** tag — the last one exposes where the
|
||||
thresholds bite (and, when that person's best sub-score is *above* 0.85, the
|
||||
`tags.min_active_years` guard that withholds tags from one-year profiles, which are
|
||||
usually **split** OpenAlex identities — the case `suspicious_profile` cannot catch,
|
||||
since that flag detects merges).
|
||||
|
||||
The page layout lives in `report_template.html` (tracked); `reports/` and `cache/` are
|
||||
gitignored, so a `git clean -fdx` or fresh checkout wipes generated reports and
|
||||
extracts — re-run the command above to rebuild the report, and `build.py` only if the
|
||||
indices themselves need refreshing.
|
||||
@@ -0,0 +1,277 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
build.py — single entry point for the multiplicator pipeline (M2).
|
||||
|
||||
extract (cached) -> graph -> metrics -> scoring -> local artifacts -> ES index.
|
||||
|
||||
python build.py --institution-id I62318514 # full run
|
||||
python build.py --institution-id I62318514 --force-extract # refresh the ES extract
|
||||
python build.py --institution-id I62318514 --no-index # skip the ES write
|
||||
|
||||
Artifacts in --cache-dir:
|
||||
authors_<ID>.jsonl.gz / works_<ID>.jsonl.gz the extract (reused unless --force-extract)
|
||||
scores_<ID>.jsonl.gz one scored row per focal author
|
||||
build_summary_<ID>.json stage timings + tag counts + top lists
|
||||
|
||||
The ES write targets `multiplicators_v1` on the INSE cluster (admin-created; the API
|
||||
key cannot create indices). Doc _id = <institution>_<author>; every run deletes the
|
||||
institution's docs first, so re-runs are idempotent.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from extract import extract_to_cache, read_jsonl_gz
|
||||
from graph import build_graph, short_id
|
||||
from index import NETWORK_MAPPING, NETWORKS_INDEX, MultiplicatorsIndexClient
|
||||
from metrics import compute_all_metrics, incident_edges
|
||||
from networks import build_network_docs
|
||||
from scoring import load_config, score_rows
|
||||
from signals import collect_signals, normalize_doi
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--institution-id", required=True)
|
||||
parser.add_argument("--config", default=str(SCRIPT_DIR / "multipliers.yaml"))
|
||||
parser.add_argument("--cache-dir", default=str(SCRIPT_DIR / "cache"))
|
||||
parser.add_argument(
|
||||
"--force-extract", action="store_true",
|
||||
help="Re-extract from ES even if a cache exists.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-index", action="store_true",
|
||||
help="Compute and write local artifacts but skip the ES indexing step.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-signals", action="store_true",
|
||||
help="Skip the patents/news/CORDIS signal joins (amplifier falls back to "
|
||||
"industry co-authorship alone).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-network", action="store_true",
|
||||
help="Skip materializing the per-author ego-network visualization docs.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
short = args.institution_id.strip().rsplit("/", 1)[-1]
|
||||
cache_dir = Path(args.cache_dir)
|
||||
config = load_config(args.config)
|
||||
timings: dict[str, float] = {}
|
||||
|
||||
# ---- extract (cache-aware) ----
|
||||
t0 = time.time()
|
||||
authors_path, works_path, insts = extract_to_cache(
|
||||
args.institution_id, config, cache_dir, force=args.force_extract
|
||||
)
|
||||
cohort_short_ids = [i["short_id"] for i in insts]
|
||||
timings["extract_s"] = round(time.time() - t0, 1)
|
||||
|
||||
# ---- load ----
|
||||
t0 = time.time()
|
||||
focal_ids = {a["id"] for a in read_jsonl_gz(authors_path)}
|
||||
works = list(read_jsonl_gz(works_path))
|
||||
timings["load_cache_s"] = round(time.time() - t0, 1)
|
||||
print(f"Loaded {len(works)} works, {len(focal_ids)} focal authors "
|
||||
f"({timings['load_cache_s']}s)")
|
||||
|
||||
# ---- single pass over works before they are freed: DOIs per focal author
|
||||
# (CORDIS join), per-author institution counts (modal label), and per-WORK
|
||||
# company affiliations (tie-level industry roles in the network docs)
|
||||
focal_short_ids = {short_id(a) for a in focal_ids}
|
||||
max_authors = int(config["extraction"]["max_authors_per_work"])
|
||||
dois_by_author: dict[str, set[str]] = {}
|
||||
inst_counts: dict[str, dict[str, int]] = {}
|
||||
company_by_author_work: dict[str, dict[str, list[str]]] = {}
|
||||
company_work_authors: dict[str, set[str]] = {}
|
||||
for w in works:
|
||||
doi = normalize_doi(w.get("doi"))
|
||||
wid = short_id(w.get("id"))
|
||||
work_authors: set[str] = set()
|
||||
work_companies: dict[str, list[str]] = {}
|
||||
for a in w.get("authorships") or []:
|
||||
aid = short_id((a.get("author") or {}).get("id"))
|
||||
if not aid:
|
||||
continue
|
||||
work_authors.add(aid)
|
||||
if doi and aid in focal_short_ids:
|
||||
dois_by_author.setdefault(aid, set()).add(doi)
|
||||
for inst in a.get("institutions") or []:
|
||||
name = inst.get("display_name")
|
||||
if name:
|
||||
counts = inst_counts.setdefault(aid, {})
|
||||
counts[name] = counts.get(name, 0) + 1
|
||||
if inst.get("type") == "company":
|
||||
work_companies.setdefault(aid, []).append(name)
|
||||
# company evidence only for works that also enter the graph (same cap)
|
||||
if wid and work_companies and 2 <= len(work_authors) <= max_authors:
|
||||
company_work_authors[wid] = work_authors
|
||||
for aid, names in work_companies.items():
|
||||
company_by_author_work.setdefault(aid, {})[wid] = names
|
||||
inst_by_author = {
|
||||
aid: max(counts, key=counts.get) for aid, counts in inst_counts.items()
|
||||
}
|
||||
del inst_counts
|
||||
|
||||
# ---- graph ----
|
||||
t0 = time.time()
|
||||
graph = build_graph(
|
||||
works,
|
||||
focal_ids,
|
||||
max_authors_per_work=config["extraction"]["max_authors_per_work"],
|
||||
decay=config["graph"]["decay"],
|
||||
)
|
||||
del works
|
||||
timings["build_graph_s"] = round(time.time() - t0, 1)
|
||||
print(f"Graph: {len(graph.nodes)} nodes, {len(graph.edges)} edges, "
|
||||
f"{graph.n_works_used} works used, {graph.n_works_capped} capped, "
|
||||
f"ref_year={graph.ref_year} ({timings['build_graph_s']}s)")
|
||||
|
||||
# ---- metrics ----
|
||||
t0 = time.time()
|
||||
metric_rows = compute_all_metrics(
|
||||
graph,
|
||||
junior_active_years_max=config["mentor"]["junior_active_years_max"],
|
||||
senior_active_years_min=config["mentor"]["senior_active_years_min"],
|
||||
progressed_active_years_min=config["mentor"]["progressed_active_years_min"],
|
||||
industry_share_shrinkage_k=config.get("signals", {}).get(
|
||||
"industry_share_shrinkage_k", 5
|
||||
),
|
||||
)
|
||||
timings["metrics_s"] = round(time.time() - t0, 1)
|
||||
print(f"Metrics for {len(metric_rows)} focal authors ({timings['metrics_s']}s)")
|
||||
|
||||
# ---- signal joins (patents / news / CORDIS) ----
|
||||
if args.no_signals:
|
||||
print("Skipping signal joins (--no-signals).")
|
||||
timings["signals_s"] = 0.0
|
||||
else:
|
||||
t0 = time.time()
|
||||
signals_cfg = config.get("signals") or {}
|
||||
display_names = {
|
||||
aid: row.get("display_name") or "" for aid, row in metric_rows.items()
|
||||
}
|
||||
signal_counts = collect_signals(
|
||||
short,
|
||||
display_names,
|
||||
{a: d for a, d in dois_by_author.items() if a in metric_rows},
|
||||
scored_match_types=tuple(
|
||||
signals_cfg.get("patent_match_types", ["institution", "both"])
|
||||
),
|
||||
news_require_relevant=signals_cfg.get("news_require_relevant", True),
|
||||
)
|
||||
for metric, counts in signal_counts.items():
|
||||
for aid, row in metric_rows.items():
|
||||
row[metric] = counts.get(aid, 0)
|
||||
timings["signals_s"] = round(time.time() - t0, 1)
|
||||
print(f"Signal joins done ({timings['signals_s']}s)")
|
||||
|
||||
# ---- scoring ----
|
||||
t0 = time.time()
|
||||
scored = score_rows(metric_rows, config)
|
||||
timings["scoring_s"] = round(time.time() - t0, 1)
|
||||
|
||||
scores_path = cache_dir / f"scores_{short}.jsonl.gz"
|
||||
with gzip.open(scores_path, "wt", encoding="utf-8", newline="\n") as f:
|
||||
for row in scored:
|
||||
f.write(json.dumps(row, ensure_ascii=True) + "\n")
|
||||
print(f"Scores -> {scores_path} ({timings['scoring_s']}s)")
|
||||
|
||||
# ---- index into ES ----
|
||||
docs_written = 0
|
||||
if args.no_index:
|
||||
print("Skipping ES indexing (--no-index).")
|
||||
else:
|
||||
t0 = time.time()
|
||||
es = MultiplicatorsIndexClient()
|
||||
es.ensure_mapping()
|
||||
docs_written = es.index_rows(short, cohort_short_ids, scored)
|
||||
count = es.count_for_institution(short)
|
||||
timings["index_s"] = round(time.time() - t0, 1)
|
||||
print(f"Indexed {docs_written} docs into {es.index} "
|
||||
f"(count for {short}: {count}) ({timings['index_s']}s)")
|
||||
if count != len(scored):
|
||||
raise RuntimeError(
|
||||
f"Post-index count mismatch: expected {len(scored)}, index has {count}"
|
||||
)
|
||||
|
||||
# ---- ego-network visualization docs ----
|
||||
network_docs_written = 0
|
||||
if args.no_index or args.no_network:
|
||||
print("Skipping network materialization.")
|
||||
else:
|
||||
t0 = time.time()
|
||||
network_cfg = config.get("network") or {}
|
||||
network_docs = build_network_docs(
|
||||
graph,
|
||||
metric_rows,
|
||||
scored,
|
||||
incident_edges(graph),
|
||||
inst_by_author,
|
||||
company_by_author_work,
|
||||
company_work_authors,
|
||||
max_nodes=int(network_cfg.get("max_nodes", 42)),
|
||||
max_forced_mentees=int(network_cfg.get("max_forced_mentees", 14)),
|
||||
)
|
||||
net_es = MultiplicatorsIndexClient(index=NETWORKS_INDEX)
|
||||
net_es.ensure_mapping(NETWORK_MAPPING)
|
||||
network_docs_written = net_es.index_rows(short, cohort_short_ids, network_docs)
|
||||
timings["network_s"] = round(time.time() - t0, 1)
|
||||
print(f"Indexed {network_docs_written} network docs into {net_es.index} "
|
||||
f"({timings['network_s']}s)")
|
||||
|
||||
# ---- summary ----
|
||||
tag_counts: dict[str, int] = {}
|
||||
for row in scored:
|
||||
for tag in row["tags"]:
|
||||
tag_counts[tag] = tag_counts.get(tag, 0) + 1
|
||||
|
||||
def top(sub: str, k: int = 10):
|
||||
rows = sorted(scored, key=lambda r: r["sub_scores"].get(sub, 0), reverse=True)
|
||||
return [
|
||||
{
|
||||
"author_id": r["author_id"],
|
||||
"name": r["display_name"],
|
||||
"score": r["sub_scores"][sub],
|
||||
"bucket": r["career_bucket"],
|
||||
"active_years": r["active_years"],
|
||||
"suspicious": r["suspicious_profile"],
|
||||
}
|
||||
for r in rows[:k]
|
||||
]
|
||||
|
||||
summary = {
|
||||
"institution": short,
|
||||
"cohort": cohort_short_ids,
|
||||
"config_hash": config["_config_hash"],
|
||||
"counts": {
|
||||
"focal_authors_scored": len(scored),
|
||||
"nodes": len(graph.nodes),
|
||||
"edges": len(graph.edges),
|
||||
"works_used": graph.n_works_used,
|
||||
"works_capped": graph.n_works_capped,
|
||||
"tags": tag_counts,
|
||||
"suspicious_profiles": sum(1 for r in scored if r["suspicious_profile"]),
|
||||
"es_docs_written": docs_written,
|
||||
"es_network_docs_written": network_docs_written,
|
||||
},
|
||||
"timings": timings,
|
||||
"top_bridgers": top("bridger"),
|
||||
"top_mentors": top("mentor"),
|
||||
"top_amplifiers": top("amplifier"),
|
||||
}
|
||||
summary_path = cache_dir / f"build_summary_{short}.json"
|
||||
with open(summary_path, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(summary, f, ensure_ascii=False, indent=2)
|
||||
print(json.dumps(summary["counts"], ensure_ascii=False, indent=2))
|
||||
print(f"Summary -> {summary_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Make the module root importable from tests/ (pytest inserts this dir via conftest)."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
@@ -0,0 +1,116 @@
|
||||
# Cohort discovery: finding a university's associated institutions in OpenAlex
|
||||
|
||||
How the `cohorts.<ID>.institution_ids` list in `multipliers.yaml` was built for the
|
||||
University of Duisburg-Essen (I62318514), and how to repeat the process for another
|
||||
university. Context: the multiplicator pipeline's author set is only as good as this
|
||||
list — matching UDE alone silently excluded ~2,400 active clinicians, including
|
||||
prominent medicine professors (found via the M1 validation, where 17/60 hand-labeled
|
||||
people were missing).
|
||||
|
||||
## Why this is necessary: `lineage` vs `associated_institutions`
|
||||
|
||||
Every institution document in OpenAlex (index `openalex-institutions`) carries two
|
||||
relationship fields:
|
||||
|
||||
- **`lineage`** — the strict parent hierarchy: a list of institution IDs including the
|
||||
institution itself and its parents. This is what ID-based filters normally use
|
||||
(e.g. `company_connections/logic.py` checks `UDE_OPENALEX_ID in lineage`).
|
||||
- **`associated_institutions`** — a looser list of linked institutions, each with a
|
||||
`relationship` label: `child`, `parent`, or `related`.
|
||||
|
||||
The trap: **OpenAlex models German university hospitals as `related`, not as lineage
|
||||
children.** Essen University Hospital's own `lineage` contains only itself. Any filter
|
||||
built on UDE's ID or lineage therefore can never match hospital-affiliated authors —
|
||||
the entire clinical medical faculty — no matter how the query is written.
|
||||
|
||||
## The discovery method (3 steps)
|
||||
|
||||
### Step 1 — read the university's `associated_institutions`
|
||||
|
||||
Query the `openalex-institutions` document for the primary ID and list its
|
||||
`associated_institutions`. For UDE (I62318514):
|
||||
|
||||
| ID | relationship | name | authors (all-time last_known) |
|
||||
|---|---|---|---|
|
||||
| I4210090139 | child | Rhein-Ruhr Institut für Sozialforschung | 11 |
|
||||
| I4210092428 | child | Deutsches Textilforschungszentrum Nord-West | 170 |
|
||||
| I4210110714 | child | Institute for Advanced Study in the Humanities (KWI) | 81 |
|
||||
| I4210146441 | child | Hydrogen and Fuel Cell Center (ZBT) | 98 |
|
||||
| I4210154243 | child | Institut für Energie- und Umwelttechnik (IUTA) | 233 |
|
||||
| **I4210119759** | **related** | **Essen University Hospital** | **7,484** |
|
||||
| I4210146447 | related | Kliniken Essen-Mitte | 788 |
|
||||
| I2799342142 | related | Salomon Ludwig Steinheim-Institut | — |
|
||||
| I4210124583 | related | IWW Water Centre | — |
|
||||
|
||||
(For comparison: UDE itself has 14,388 all-time last_known authors.)
|
||||
|
||||
### Step 2 — follow one hop into any `related` hospital
|
||||
|
||||
The hospital's own `associated_institutions` revealed a member invisible from UDE's
|
||||
record: the **West German Heart and Vascular Center Essen (I4210161917)** is a `child`
|
||||
of the hospital (1,021 authors) — two hops from UDE.
|
||||
|
||||
### Step 3 — validate against real people (this catches what no query can)
|
||||
|
||||
The **Erwin L. Hahn Institute for MRI (I127668822)** was NOT found by any metadata
|
||||
walk: in OpenAlex it is completely isolated — `lineage` contains only itself,
|
||||
`associated_institutions` is empty. It surfaced only when diagnosing why a specific
|
||||
hand-labeled professor (Ulrike Bingel) was missing from the cohort: it appeared in her
|
||||
affiliation list. Lesson: after building the list from metadata, always check a set of
|
||||
known current researchers against the extracted cohort — the misses point to
|
||||
institutions the graph walk cannot reach.
|
||||
|
||||
## Inclusion decisions for UDE (documented in `multipliers.yaml`)
|
||||
|
||||
**Included (9):**
|
||||
|
||||
- `I62318514` UDE (primary)
|
||||
- `I4210119759` Essen University Hospital — it *is* the university medical centre;
|
||||
its `related` label is an OpenAlex modelling choice, not an organisational fact
|
||||
- `I4210161917` West German Heart and Vascular Center (child of the hospital)
|
||||
- `I127668822` Erwin L. Hahn Institute (joint UDE institute; isolated in OpenAlex)
|
||||
- The five lineage children: RISP, DTNW, KWI, ZBT, IUTA — small but unambiguous
|
||||
|
||||
**Excluded by default (revisit with the coaches):**
|
||||
|
||||
- `I4210146447` Kliniken Essen-Mitte — an independent hospital group; `related`
|
||||
reflects collaboration, not membership; its staff are not UDE researchers
|
||||
- `I2799342142` Salomon Ludwig Steinheim-Institut and `I4210124583` IWW Water
|
||||
Centre — *An-Institute*: legally independent institutes **at** UDE, not **of** it
|
||||
|
||||
The borderline cases are exactly the German-institutional-law ones (An-Institute,
|
||||
municipal hospital groups). These are human judgment calls, which is why the list
|
||||
lives in config with the reasoning inline, not in code.
|
||||
|
||||
## Effect on the cohort (measured)
|
||||
|
||||
| | UDE ID only | 9-institution cohort |
|
||||
|---|---|---|
|
||||
| Authors (affiliation ≥ 2023) | ~7,100¹ | 9,475 |
|
||||
| Hand-labeled sample matched | 43/60² | 51/60 |
|
||||
| Unexplained misses | 17 | **0** (the 9 remaining all verifiably left UDE) |
|
||||
|
||||
¹ approximate — the single-ID number was measured at the 2025 cutoff (4,921); scaled here for context.
|
||||
² at the 2025 cutoff; the cohort fix and the 2023 affiliation window each contributed.
|
||||
|
||||
Recovered by the fix, as a face-validity check: Oliver Witzke (Senior, 73 juniors
|
||||
mentored → tagged mentor) and Ulrike Bingel (Senior, 34 juniors, 21
|
||||
last-author-with-junior-first works → tagged mentor).
|
||||
|
||||
## Repeating this for another university
|
||||
|
||||
1. Fetch `associated_institutions` from `openalex-institutions` for the primary ID;
|
||||
collect all `child` entries and every `related` entry.
|
||||
2. For any `related` hospital / medical centre, fetch ITS `associated_institutions`
|
||||
and collect its children.
|
||||
3. For each candidate, count authors
|
||||
(`last_known_institutions.id == <candidate>` on `openalex-authors`) — size tells
|
||||
you what an inclusion decision is worth.
|
||||
4. Decide inclusions with a human: university hospitals in; independent hospital
|
||||
groups and An-Institute out unless the institution says otherwise.
|
||||
5. Write the `cohorts.<primary-ID>` block in `multipliers.yaml` with the reasoning
|
||||
as inline comments.
|
||||
6. Run the extraction, then validate against a list of known current researchers
|
||||
(professors from several faculties, especially medicine). Every unexplained miss
|
||||
is either a missing cohort member (like the Hahn Institute) or a stale-affiliation
|
||||
case (tune `extraction.affiliation_years_gte`).
|
||||
@@ -0,0 +1,239 @@
|
||||
# Multiplicator Detection — Concept, Technical Walkthrough & Roadmap
|
||||
|
||||
A ground-up explanation of what this module does, how every field in the
|
||||
`multiplicators_v1` index is computed and what it means, where the ideas come from,
|
||||
and where the project stands. Written for a reader with no prior context.
|
||||
|
||||
Companion docs: [README.md](../README.md) (per-milestone results and stats),
|
||||
[ASSOCIATED_INSTITUTIONS.md](ASSOCIATED_INSTITUTIONS.md) (cohort discovery method).
|
||||
|
||||
---
|
||||
|
||||
## 1. What problem this solves
|
||||
|
||||
The university's innovation coaches want to find **multiplicators**: people whose value
|
||||
isn't only their own research output, but their effect on the system around them — they
|
||||
connect groups that otherwise wouldn't talk, they grow junior researchers into
|
||||
independent scientists, they carry research out of academia into industry and the
|
||||
public. These people are invisible in classic rankings (citations, h-index), which
|
||||
measure individual output, not systemic effect.
|
||||
|
||||
The core bet of the whole project: **these behaviors leave measurable traces in
|
||||
publication metadata.** Who you publish with, when, in what role, and across which
|
||||
institutional boundaries is recorded in OpenAlex for every paper. So instead of asking
|
||||
"who is influential?" we ask three narrower, checkable questions, each an archetype:
|
||||
|
||||
- **Bridger** — do your collaborations span otherwise-disconnected communities,
|
||||
fields, institutions, sectors?
|
||||
- **Mentor** — do junior people repeatedly start their careers publishing with you,
|
||||
in the role configuration typical of supervision?
|
||||
- **Amplifier** — does your work escape academia: patents, industry co-authorship,
|
||||
EU projects, press coverage?
|
||||
|
||||
Everything else is machinery for answering those three questions honestly at the
|
||||
scale of ~9,500 people.
|
||||
|
||||
## 2. The pipeline, step by step
|
||||
|
||||
**Step 1 — Define who "the university" is (cohort).** OpenAlex models Essen University
|
||||
Hospital as merely *related* to UDE, not part of it, so filtering by UDE's ID alone
|
||||
silently loses the entire clinical faculty (~2,400 active people). The cohort is
|
||||
therefore an explicit list of 9 institution IDs (UDE + hospital + heart center +
|
||||
affiliated institutes) — the `cohort_institution_ids` array on every document. An
|
||||
author belongs if their last-known institution is in that list **and** they have an
|
||||
affiliation year ≥ 2023 (publication lag makes a 1-year window drop current staff).
|
||||
Details: [ASSOCIATED_INSTITUTIONS.md](ASSOCIATED_INSTITUTIONS.md).
|
||||
|
||||
**Step 2 — Extract.** For those ~9,475 authors we pull **all their works globally** —
|
||||
not just university-affiliated ones — with the *complete* author list of every paper,
|
||||
including external co-authors and each co-author's institution (with its type:
|
||||
education, company, healthcare…). Result: ~267k works, ~3.8M authorship records.
|
||||
The "all works globally" property matters: it makes career histories *exact* for
|
||||
cohort members, while external co-authors' histories are truncated to shared works —
|
||||
a fact the mentor metrics must respect (see §3).
|
||||
|
||||
**Step 3 — Build the co-authorship graph.** Every paper connects each pair of its
|
||||
authors with an edge. Three refinements:
|
||||
|
||||
- **Team-size weighting**: a pair on a 3-author paper gets weight 1/(n−1) = 0.5; on a
|
||||
40-author paper, 1/39. Being 2 of 3 authors is strong evidence you actually work
|
||||
together; being 2 of 40 is weak evidence.
|
||||
- **Time decay**: each paper's contribution is multiplied by 0.8^(years ago). A 2025
|
||||
collaboration counts full; a 2010 one counts ~3%. We're looking for *current*
|
||||
multiplicators.
|
||||
- **Hyperauthorship cap**: papers with >50 authors (CERN-style consortia; the corpus
|
||||
max is 4,839 authors on one paper) are excluded from the graph entirely — that one
|
||||
paper alone would create ~11.7M fake "collaboration" edges and a giant artificial
|
||||
clique. Those papers still count for career metrics.
|
||||
|
||||
Result: ~865k nodes (cohort + all their external co-authors), ~5.8M weighted edges.
|
||||
|
||||
**Step 4 — Compute metrics on that graph** (§3, field by field).
|
||||
|
||||
**Step 5 — Normalize fairly and score.** Raw metrics aren't comparable between a PhD
|
||||
student and a 30-year professor, so every metric becomes a **percentile within the
|
||||
person's career stage**, then three weighted sub-scores, then tags above a threshold
|
||||
(§4).
|
||||
|
||||
**Step 6 — Join external signals** (patents, news, EU projects) and **write everything
|
||||
to `multiplicators_v1`** — one document per person, containing raw values, percentiles,
|
||||
scores, tags, and evidence, so a coach can always see *why* someone scored what they
|
||||
scored.
|
||||
|
||||
## 3. A real document, field by field
|
||||
|
||||
Example: Tabea M. G. Pakull, `_id = I62318514_A5043360678` (institution + author —
|
||||
the same person at another university would be a separate doc). An ES `_version: 8`
|
||||
just means the doc was overwritten 8 times by re-runs; the `fields` block ES returns
|
||||
alongside `_source` is its internal columnar echo — ignore it.
|
||||
|
||||
### Career context
|
||||
|
||||
| field | example value | meaning |
|
||||
|---|---|---|
|
||||
| `active_years` | 3 | Distinct calendar years with ≥1 publication — our seniority measure. We deliberately do **not** use "years since first publication": the repo's career-stage analysis found merged OpenAlex profiles give active professors debut years like 1893. One wrong old paper distorts career span by decades but moves `active_years` by exactly +1. |
|
||||
| `career_bucket` | "Early" | Early ≤4, Emerging ≤9, Established ≤14, Senior >14 active years — thresholds taken unchanged from the backend's `_classify_career_stage`, empirically validated against 60 known professors/researchers. **All percentiles are computed against the same bucket only.** |
|
||||
| `n_works` | 12 | Works in the extract. |
|
||||
| `suspicious_profile` | false | Merged-identity flag (first year <1970 or span >60). True ⇒ treat evidence as low-confidence; ~18% of Seniors carry it. |
|
||||
|
||||
### Bridger metrics (network structure)
|
||||
|
||||
| field | example | what it measures |
|
||||
|---|---|---|
|
||||
| `betweenness` | 0 | **Betweenness centrality** on the cohort-internal graph: how often the strongest connection paths between other cohort members run *through you*. High = the network's traffic must pass you = you connect groups. Edge weights are "closeness", so paths use inverted weights as distances. A 0 is normal early-career; the percentile can still be ~0.44 because most of the bucket is also 0 and ties share their average rank. |
|
||||
| `constraint` → `brokerage` | 0.085 → 0.915 | **Burt's constraint** looks only at your *ego network* (you + your co-authors): do your contacts also know each other? High constraint = you sit inside one dense clique. Low = your contacts live in separate worlds and *you* are the only link — you span "structural holes". Stored as `brokerage = 1 − constraint` so higher = more bridging. Computed on the **full graph including external co-authors**, so it sees outward bridging that internal betweenness can't. In the example: 82 co-authors who barely know each other — 90th percentile of the Early bucket. |
|
||||
| `field_entropy` | 0.98 | Shannon entropy over the scientific fields of the person's papers. 0 = monodisciplinary; 1.0 bit ≈ two fields evenly; 2.0 ≈ four. Topical breadth as a proxy for interdisciplinary bridging (OpenAlex has no faculty structure, so this is the honest substitute — it must never be presented as "bridges faculties"). |
|
||||
| `cross_institution_share` | 0.85 | Share of collaboration weight with co-authors sharing *no* institution with the person — external orientation. |
|
||||
| `strength`, `n_coauthors` | 8.25, 82 | Total decayed edge weight and distinct co-author count — "reach", context only, not scored directly. |
|
||||
|
||||
### Mentor metrics
|
||||
|
||||
OpenAlex has no supervision records and debut years are unreliable, so the mentor
|
||||
signals are built on **`active_years_at(person, year)`** — how many active years
|
||||
someone had accumulated *as of a given year* — which inherits the robustness of
|
||||
`active_years` (a spurious 1893 paper shifts it by exactly 1, not 120).
|
||||
|
||||
| field | definition |
|
||||
|---|---|
|
||||
| `juniors_mentored` | Count of cohort co-authors who, in the year of their *first* joint paper, had ≤4 active years (Early) **while the focal person had ≥10** (Established+). A seniority-*gap* criterion — two PhD students co-publishing never counts. |
|
||||
| `junior_progression_rate` | Of those juniors, the fraction who later reached ≥5 active years — separates "grew them up" from "co-signed once". `null` = no juniors = not applicable (excluded from scoring, not counted against the person). |
|
||||
| `last_author_with_junior_first` | Papers where the person is **last author** with an Early-career **first author** — the classic supervision signature (student first, PI last). Deliberately independent of the gap logic: when the two disagree (37 "juniors" but zero last-author papers) that's the core-facility-scientist pattern, not a mentor. |
|
||||
| `mentoring_rate` | juniors ÷ own active years. Without a rate, prolific seniors win on volume alone (professor median 224 papers vs 11 for researchers). |
|
||||
|
||||
Mentor metrics are computed **only between cohort members**: external co-authors'
|
||||
histories are truncated to shared works, so an external senior would masquerade as a
|
||||
junior. This scope restriction is a data-correctness requirement, not a choice.
|
||||
|
||||
### Amplifier metrics
|
||||
|
||||
| field | source & link quality |
|
||||
|---|---|
|
||||
| `industry_coauthor_share` | Share of typed works with ≥1 company-affiliated co-author. The strongest industry signal available because it's **institution-ID-linked** — no name matching. Kept raw for transparency. |
|
||||
| `industry_coauthor_share_shrunk` | The **scored** variant: company ÷ (typed + 5). Why: with raw shares, someone with 2-of-2 company papers gets share 1.0 and beats someone with 40-of-80 — before this fix, the index's entire top-10 "amplifiers" were such small-denominator artifacts. The +5 makes small samples humble. |
|
||||
| `patent_count` | From `org_patents`, which links patents to OpenAlex author IDs. Only high-confidence matches (`match_type` = institution/both) are scored. |
|
||||
| `patent_count_name_only` | Name-only patent matches — **evidence only, never scored**. |
|
||||
| `news_mentions` | University press corpus, LLM-extracted names, matched after normalizing case and diacritics (René = rene). If a normalized name belongs to *two* cohort people, **nobody** gets credit (839 names skipped at UDE) — miscrediting is worse than missing. Hence the low weight. |
|
||||
| `cordis_eu_projects` | Distinct EU projects joined by **DOI overlap** (the person's paper DOIs ∩ DOIs attached to CORDIS project publications) — no name matching. Matching is case-insensitive because 21% of CORDIS DOIs contain uppercase. |
|
||||
|
||||
### Scoring plumbing
|
||||
|
||||
| field | meaning |
|
||||
|---|---|
|
||||
| `percentiles.*` | Each raw metric's mean-rank percentile *within the career bucket*. Ties share their average rank — that's why a metric at 0 in a mostly-zero bucket shows ~0.44–0.50, not 1.0: a mass of zeros must not be rewarded. `null` metrics are excluded, and their weight is redistributed. |
|
||||
| `sub_scores.{bridger,mentor,amplifier}` | Weighted means of the percentiles. Weights live in `multipliers.yaml`, never in code — coaches retune them. Current amplifier weights: shrunk share 0.50, patents 0.25, CORDIS 0.15, news 0.10. |
|
||||
| `tags` | Sub-score ≥ `tags.threshold` (0.85) ⇒ tag; a person can hold 0–3. Current yield at UDE: 133 bridgers, 161 mentors, 10 amplifiers. |
|
||||
| `max_sub_score` | Best sub-score — the default ranking key. |
|
||||
| `evidence.junior_ids` | Receipts (which people count as mentees) — a coach never sees a bare number. |
|
||||
| `config_hash`, `computed_at` | Which YAML weighting produced the score, and when. Scores are cohort-relative and weight-dependent; without this they'd be unfalsifiable after the next retune. |
|
||||
| `institution_id`, `cohort_institution_ids` | Which university this doc belongs to and which 9 institutions defined its cohort. |
|
||||
|
||||
Worked example (the Pakull doc): amplifier = 0.50·0.99 (shrunk share) + 0.25·0.50
|
||||
(patents, tie-mass) + 0.15·0.98 (one EU project — 98th percentile *for an
|
||||
Early-career person*) + 0.10·0.47 (news) = **0.8131** — high, but under 0.85 ⇒ no
|
||||
tag. Mentor 0.494 ≈ bucket median: all-zero mentor metrics in a bucket where nearly
|
||||
everyone is zero lands exactly mid-pack.
|
||||
|
||||
## 4. related work
|
||||
|
||||
- **Co-authorship graphs as collaboration networks** — Mark Newman's early-2000s
|
||||
studies of scientific collaboration networks, which also introduced the 1/(n−1)
|
||||
team-size weighting. The warning that huge author lists break co-authorship
|
||||
semantics is Blaise Cronin's "hyperauthorship" critique — the basis for the
|
||||
50-author cap.
|
||||
- **Bridger, theory** — Granovetter's "strength of weak ties" (1973): novel
|
||||
information flows across bridges between groups, not within dense cliques.
|
||||
- **Bridger, operationalization** — *betweenness centrality* (Linton Freeman, 1977),
|
||||
computed with Ulrik Brandes' 2001 algorithm (implemented in `metrics.py`, tested
|
||||
against networkx); *structural holes and constraint* (Ronald Burt, 1992; his 2004
|
||||
"Structural holes and good ideas" showed brokers produce more good ideas). The
|
||||
weights-are-distances inversion for betweenness is a standard weighted-network
|
||||
practice. Shannon entropy as a diversity/interdisciplinarity indicator follows
|
||||
standard scientometrics usage (Stirling-style diversity).
|
||||
- **Mentor** — reading mentorship from publication genealogies is established in
|
||||
scientometrics (e.g. Malmgren, Ottino & Amaral's Nature study of mentor–protégé
|
||||
networks). The first-author-student / last-author-PI convention is a documented
|
||||
authorship norm in the life sciences — credible at a medicine-heavy university.
|
||||
Shipped caveat: co-authorship ≠ supervision; it's a proxy, validated directionally
|
||||
against 60 hand-labeled people (professors' median mentor score 0.740 vs
|
||||
researchers' 0.494).
|
||||
- **Amplifier** — the university "third mission" / knowledge-transfer literature
|
||||
(Etzkowitz & Leydesdorff's Triple Helix line): patents, industry co-publication,
|
||||
joint projects as measurable transfer channels. Industry co-authorship as primary
|
||||
indicator is pragmatic: it's the only channel linked by institution IDs rather
|
||||
than names.
|
||||
- **Fair comparison** — percentile indicators within reference groups are the modern
|
||||
bibliometrics standard (compare like with like). Our reference group is the career
|
||||
bucket; the buckets come from this repo's own `analysis/career_stage/` work, which
|
||||
is also the empirical source for the most important design decision: rejecting
|
||||
`first_publication_year` in favor of `active_years`. `active_years_at(A, Y)` is our
|
||||
small extension of that finding.
|
||||
- **Data-quality corrections** (all found by measuring, not assumed): the hospital
|
||||
cohort gap (OpenAlex `related` vs lineage), ratio shrinkage, tie-sharing
|
||||
percentiles, the news ambiguity rule, merged/split-profile flags — responses to
|
||||
the well-known author-disambiguation weaknesses of bibliographic databases.
|
||||
|
||||
## 5. What was achieved (status)
|
||||
|
||||
Three falsifiable behavioral definitions instead of a vague label; a decay- and
|
||||
team-size-weighted collaboration graph over the complete global publication history
|
||||
of a correctly-defined 9-institution cohort; established network-science and
|
||||
bibliometric measures, made robust against the two dominant data pathologies (merged
|
||||
profiles, hyperauthorship); within-career-stage normalization; three independent
|
||||
external evidence channels joined at their honest link quality; and a queryable index
|
||||
where every person carries raw values, percentiles, scores, tags, and receipts —
|
||||
validated against hand-labeled ground truth, every tunable in config, every score
|
||||
stamped with the config that produced it.
|
||||
|
||||
| Milestone | Status |
|
||||
|---|---|
|
||||
| M0 — de-risking spike against the real cluster | ✅ done |
|
||||
| M1 — graph + metrics + scoring core, 60-person validation | ✅ done (PASS) |
|
||||
| M2 — cohort fix, extraction module, idempotent `multiplicators_v1` indexing | ✅ done |
|
||||
| M3 — amplifier signal joins (patents / news / CORDIS) + shrinkage fix | ✅ wired & indexed |
|
||||
|
||||
## 6. Roadmap — what's next
|
||||
|
||||
1. **M3 calibration session (human, next).** Coaches provide a golden set of 10–20
|
||||
known multiplicators, ideally labeled by type. Tune `multipliers.yaml`
|
||||
(sub-score weights, per-tag thresholds — 0.85 currently yields 133/161/10
|
||||
bridger/mentor/amplifier tags; if more amplifier candidates are wanted, introduce
|
||||
per-tag thresholds). Re-run `validate_sample.py` after every change as regression.
|
||||
2. **M4 — read-only serving layer**, once the UI needs it: thin FastAPI router in
|
||||
`inse/multiplicators/` over BOTH indices — `multiplicators_v1` for list views
|
||||
(by tag/bucket/score + per-person evidence) and `multiplicator_networks_v1` for
|
||||
the ego-network visualization (one doc per author: nodes with roles, edges with
|
||||
tie strength/cross-institution flags, ego header — render with echarts force
|
||||
layout; see README "Network visualization index"). Then
|
||||
`./gradlew :service:exportOpenApiSpec` to regenerate the Angular client.
|
||||
3. **Scheduling** — re-run `build.py` per dump refresh (Airflow, like the other
|
||||
crawlers); scores are batch-computed, serving is read-only.
|
||||
4. **Deferred improvements**, in value order:
|
||||
- **ORCID / `ude_persons_1.0` bridge** — the single highest-value follow-up: fixes
|
||||
news linking, catches *split* profiles (the `suspicious_profile` flag only
|
||||
catches merges; one split-profile artifact sits in the current amplifier
|
||||
top-10), and would enable faculty-level bridging via the staff directory.
|
||||
- Per-field percentile cohorts (biologist baselines ≠ sociologist baselines) —
|
||||
decide with coaches.
|
||||
- Project layer as graph edges (consortium co-membership), DFG/Bund signals if a
|
||||
real person-link ever exists.
|
||||
- Committing the module (currently untracked on `feature/find-multipliers`).
|
||||
@@ -0,0 +1,395 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
extract.py — cohort-aware extraction of the author + work sets from Elasticsearch.
|
||||
|
||||
Canonical home of the extraction logic (spike_audit.py and build.py both use it).
|
||||
|
||||
The author set is a UNION OF TWO QUERIES (a correctness requirement found during the
|
||||
seed audit — group 2 recovers ~4% of authors that group 1 silently drops):
|
||||
|
||||
1. backend_compatible last_known_institutions in the cohort AND a recent
|
||||
cohort affiliation (years >= extraction.affiliation_years_gte)
|
||||
2. empty_last_known_recent recent cohort affiliation but NO last_known_institutions
|
||||
|
||||
The cohort is the list of OpenAlex institution IDs from `cohorts.<primary>.institution_ids`
|
||||
in multiplicators.yaml (falling back to the primary ID alone). This exists because
|
||||
OpenAlex does NOT model university hospitals as lineage children — matching only the
|
||||
primary institution excluded ~2,400 active UDE clinicians.
|
||||
|
||||
The work set is ALL works by those authors, globally (full authorship lists incl.
|
||||
external co-authors — required for the bridging signals), paginated with
|
||||
search_after over an id sort, batched ~250 author IDs per terms query.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable, Iterator
|
||||
|
||||
import httpx
|
||||
import yaml
|
||||
from dotenv import load_dotenv
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
ENV_PATH = SCRIPT_DIR.parent.parent / "src" / "main" / "inse" / ".env"
|
||||
load_dotenv(dotenv_path=ENV_PATH)
|
||||
|
||||
NES_URL = (os.environ.get("ELASTICSEARCH_URL") or "").rstrip("/")
|
||||
NES_KEY = os.environ.get("ELASTICSEARCH_API_KEY") or ""
|
||||
INSE_URL = (os.environ.get("ELASTICSEARCH_INSE_URL") or "").rstrip("/")
|
||||
INSE_KEY = os.environ.get("ELASTICSEARCH_INSE_API_KEY") or ""
|
||||
|
||||
AUTHOR_PAGE_SIZE = 1000
|
||||
AUTHOR_BATCH_SIZE = 250
|
||||
WORK_PAGE_SIZE = 1000
|
||||
REQUEST_TIMEOUT = 180.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# ES helpers
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _headers(api_key: str) -> dict[str, str]:
|
||||
return {
|
||||
"Authorization": f"ApiKey {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
|
||||
def es_request(
|
||||
client: httpx.Client,
|
||||
method: str,
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
path: str,
|
||||
body: dict[str, Any] | None = None,
|
||||
) -> httpx.Response:
|
||||
url = f"{base_url}/{path.lstrip('/')}"
|
||||
return client.request(
|
||||
method, url, headers=_headers(api_key), json=body, timeout=REQUEST_TIMEOUT
|
||||
)
|
||||
|
||||
|
||||
def es_search(
|
||||
client: httpx.Client, base_url: str, api_key: str, index: str, body: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
response = es_request(client, "POST", base_url, api_key, f"{index}/_search", body)
|
||||
if not response.is_success:
|
||||
raise RuntimeError(
|
||||
f"ES error {response.status_code} for {index}:\n{response.text[:1000]}"
|
||||
)
|
||||
return response.json()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Config / cohort
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def load_config(path: str | Path) -> dict[str, Any]:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
|
||||
|
||||
def cohort_ids_for(config: dict[str, Any], primary_short_id: str) -> list[str]:
|
||||
cohort = (config.get("cohorts") or {}).get(primary_short_id) or {}
|
||||
ids = cohort.get("institution_ids")
|
||||
return [str(i) for i in ids] if ids else [primary_short_id]
|
||||
|
||||
|
||||
def resolve_institution(client: httpx.Client, institution_id: str) -> dict[str, Any]:
|
||||
"""Look up ror + display_name from openalex-institutions."""
|
||||
short = institution_id.strip().rsplit("/", 1)[-1]
|
||||
full = f"https://openalex.org/{short}"
|
||||
result = es_search(
|
||||
client, NES_URL, NES_KEY, "openalex-institutions",
|
||||
{"size": 1, "query": {"term": {"id": full}}},
|
||||
)
|
||||
hits = result["hits"]["hits"]
|
||||
if not hits:
|
||||
raise SystemExit(f"Institution {full} not found in openalex-institutions.")
|
||||
source = hits[0]["_source"]
|
||||
return {
|
||||
"id": full,
|
||||
"short_id": short,
|
||||
"ror": source.get("ror"),
|
||||
"display_name": source.get("display_name"),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Author queries
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def recent_affiliation_filter(
|
||||
insts: list[dict[str, Any]], year_gte: int
|
||||
) -> dict[str, Any]:
|
||||
"""Recent affiliation with ANY cohort institution (matched by id, ror as backup)."""
|
||||
ids = [i["id"] for i in insts]
|
||||
shoulds: list[dict[str, Any]] = [{"terms": {"affiliations.institution.id": ids}}]
|
||||
rors = [i["ror"] for i in insts if i.get("ror")]
|
||||
if rors:
|
||||
shoulds.append({"terms": {"affiliations.institution.ror": rors}})
|
||||
return {
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"bool": {"should": shoulds, "minimum_should_match": 1}},
|
||||
{"range": {"affiliations.years": {"gte": year_gte}}},
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def last_known_filter(insts: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {
|
||||
"terms": {"last_known_institutions.id": [i["id"] for i in insts]}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def last_known_exists_filter() -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {"exists": {"field": "last_known_institutions.display_name"}},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
AUTHOR_SOURCE = [
|
||||
"id",
|
||||
"display_name",
|
||||
"orcid",
|
||||
"works_count",
|
||||
"cited_by_count",
|
||||
"last_known_institutions",
|
||||
"affiliations",
|
||||
]
|
||||
|
||||
|
||||
def collect_authors(
|
||||
client: httpx.Client,
|
||||
insts: list[dict[str, Any]],
|
||||
affiliation_year_gte: int,
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
groups = {
|
||||
"backend_compatible": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
last_known_filter(insts),
|
||||
recent_affiliation_filter(insts, affiliation_year_gte),
|
||||
]
|
||||
}
|
||||
},
|
||||
"empty_last_known_recent": {
|
||||
"bool": {
|
||||
"filter": [recent_affiliation_filter(insts, affiliation_year_gte)],
|
||||
"must_not": [last_known_exists_filter()],
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
authors: dict[str, dict[str, Any]] = {}
|
||||
for group_name, query in groups.items():
|
||||
search_after = None
|
||||
total = None
|
||||
read = 0
|
||||
while True:
|
||||
body: dict[str, Any] = {
|
||||
"size": AUTHOR_PAGE_SIZE,
|
||||
"track_total_hits": True,
|
||||
"_source": AUTHOR_SOURCE,
|
||||
"query": query,
|
||||
"sort": [{"id": {"order": "asc"}}],
|
||||
}
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
result = es_search(client, NES_URL, NES_KEY, "openalex-authors", body)
|
||||
hits = result["hits"]["hits"]
|
||||
if total is None:
|
||||
total = result["hits"]["total"]["value"]
|
||||
print(f" [{group_name}] expected {total}")
|
||||
if not hits:
|
||||
break
|
||||
for hit in hits:
|
||||
src = hit["_source"]
|
||||
aid = src.get("id")
|
||||
if not aid:
|
||||
continue
|
||||
if aid not in authors:
|
||||
authors[aid] = {
|
||||
"id": aid,
|
||||
"display_name": src.get("display_name"),
|
||||
"orcid": src.get("orcid"),
|
||||
"works_count": src.get("works_count"),
|
||||
"cited_by_count": src.get("cited_by_count"),
|
||||
"source_sets": [group_name],
|
||||
}
|
||||
elif group_name not in authors[aid]["source_sets"]:
|
||||
authors[aid]["source_sets"].append(group_name)
|
||||
read += 1
|
||||
search_after = hits[-1]["sort"]
|
||||
print(f" [{group_name}] read {read}/{total}")
|
||||
time.sleep(0.05)
|
||||
return authors
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Work queries — FULL authorships, no inner_hits
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
WORK_SOURCE = [
|
||||
"id",
|
||||
"doi",
|
||||
"publication_year",
|
||||
"type",
|
||||
"cited_by_count",
|
||||
"primary_topic.id",
|
||||
"primary_topic.display_name",
|
||||
"primary_topic.field.id",
|
||||
"primary_topic.field.display_name",
|
||||
"authorships.author.id",
|
||||
"authorships.author.display_name",
|
||||
"authorships.author_position",
|
||||
"authorships.is_corresponding",
|
||||
"authorships.institutions.id",
|
||||
"authorships.institutions.display_name",
|
||||
"authorships.institutions.type",
|
||||
"authorships.institutions.country_code",
|
||||
"authorships.institutions.lineage",
|
||||
]
|
||||
|
||||
|
||||
def collect_works(
|
||||
client: httpx.Client, author_ids: list[str], work_year_gte: int
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
works: dict[str, dict[str, Any]] = {}
|
||||
total_batches = (len(author_ids) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
|
||||
for i in range(0, len(author_ids), AUTHOR_BATCH_SIZE):
|
||||
batch = author_ids[i : i + AUTHOR_BATCH_SIZE]
|
||||
batch_no = i // AUTHOR_BATCH_SIZE + 1
|
||||
search_after = None
|
||||
while True:
|
||||
body: dict[str, Any] = {
|
||||
"size": WORK_PAGE_SIZE,
|
||||
"track_total_hits": True,
|
||||
"_source": WORK_SOURCE,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"publication_year": {"gte": work_year_gte}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"terms": {"authorships.author.id": batch}
|
||||
},
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
"sort": [{"id": {"order": "asc"}}],
|
||||
}
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
result = es_search(client, NES_URL, NES_KEY, "openalex-works*", body)
|
||||
hits = result["hits"]["hits"]
|
||||
if not hits:
|
||||
break
|
||||
for hit in hits:
|
||||
src = hit["_source"]
|
||||
wid = src.get("id")
|
||||
if wid and wid not in works:
|
||||
works[wid] = src
|
||||
search_after = hits[-1]["sort"]
|
||||
print(f" work batch {batch_no}/{total_batches}: unique works {len(works)}")
|
||||
time.sleep(0.05)
|
||||
return works
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Cache IO
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def write_jsonl_gz(path: Path, records: Iterable[dict[str, Any]]) -> None:
|
||||
with gzip.open(path, "wt", encoding="utf-8", newline="\n") as f:
|
||||
for record in records:
|
||||
f.write(json.dumps(record, ensure_ascii=True) + "\n")
|
||||
|
||||
|
||||
def read_jsonl_gz(path: Path) -> Iterator[dict[str, Any]]:
|
||||
with gzip.open(path, "rt", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line:
|
||||
yield json.loads(line)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Top-level: extract to cache
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def extract_to_cache(
|
||||
institution_id: str,
|
||||
config: dict[str, Any],
|
||||
cache_dir: Path,
|
||||
force: bool = False,
|
||||
) -> tuple[Path, Path, list[dict[str, Any]]]:
|
||||
"""Extract authors + works for the cohort to jsonl.gz caches.
|
||||
|
||||
Returns (authors_path, works_path, resolved cohort institutions). Reuses an
|
||||
existing cache unless force=True.
|
||||
"""
|
||||
if not NES_URL or not NES_KEY:
|
||||
raise SystemExit(f"Missing NES credentials. Checked {ENV_PATH}")
|
||||
|
||||
short = institution_id.strip().rsplit("/", 1)[-1]
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
authors_path = cache_dir / f"authors_{short}.jsonl.gz"
|
||||
works_path = cache_dir / f"works_{short}.jsonl.gz"
|
||||
|
||||
extraction_cfg = config.get("extraction") or {}
|
||||
affiliation_year_gte = int(extraction_cfg.get("affiliation_years_gte", 2023))
|
||||
work_year_gte = int(extraction_cfg.get("work_year_gte", 1950))
|
||||
|
||||
with httpx.Client() as client:
|
||||
insts = [
|
||||
resolve_institution(client, i) for i in cohort_ids_for(config, short)
|
||||
]
|
||||
print(f"Cohort ({len(insts)} institutions, affiliation years >= {affiliation_year_gte}):")
|
||||
for inst in insts:
|
||||
print(f" {inst['short_id']:<14} {inst['display_name']}")
|
||||
|
||||
if not force and authors_path.exists() and works_path.exists():
|
||||
print("Reusing cached extract (use --force-extract to refresh).")
|
||||
return authors_path, works_path, insts
|
||||
|
||||
print("\nExtracting authors...")
|
||||
authors = collect_authors(client, insts, affiliation_year_gte)
|
||||
write_jsonl_gz(authors_path, authors.values())
|
||||
print(f"Authors: {len(authors)} -> {authors_path}")
|
||||
|
||||
print("\nExtracting works (full authorships)...")
|
||||
works_map = collect_works(client, sorted(authors.keys()), work_year_gte)
|
||||
write_jsonl_gz(works_path, works_map.values())
|
||||
print(f"Works: {len(works_map)} -> {works_path}")
|
||||
|
||||
return authors_path, works_path, insts
|
||||
@@ -0,0 +1,259 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
graph.py — co-author graph construction for multiplicator detection (M1, Stage C).
|
||||
|
||||
Input: the cached work extract (see spike_audit.py) as plain dicts.
|
||||
Output: plain-Python structures the metrics module consumes:
|
||||
|
||||
- edges: dict[(src, dst)] -> EdgeStats (undirected, src < dst, SHORT author ids)
|
||||
- nodes: dict[author_id] -> NodeStats (per-author aggregates over their works)
|
||||
|
||||
Design constraints (from the M0 spike):
|
||||
- Works with more than `max_authors_per_work` authors (default 50, chosen from the
|
||||
measured p90=17 / p99=144 distribution) are excluded from GRAPH construction only —
|
||||
a 4,839-author consortium paper is not a collaboration signal, but it still counts
|
||||
toward publication years, which are aggregated here in NodeStats for ALL works.
|
||||
- Edge weights follow the plan: sum of decay^(ref_year - year) / (n_authors - 1)
|
||||
per shared work, so recent, small-team collaborations weigh most.
|
||||
- All author/institution ids are shortened ("https://openalex.org/A5..." -> "A5...")
|
||||
to keep the adjacency structures small.
|
||||
|
||||
Everything here is pure computation over plain data — no I/O, no ES — so it is unit
|
||||
testable with hand-built fixtures.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterable
|
||||
|
||||
import polars as pl
|
||||
|
||||
OPENALEX_PREFIX = "https://openalex.org/"
|
||||
|
||||
|
||||
def short_id(raw: str | None) -> str | None:
|
||||
if not raw:
|
||||
return None
|
||||
return raw.rsplit("/", 1)[-1] if "/" in raw else raw
|
||||
|
||||
|
||||
@dataclass
|
||||
class EdgeStats:
|
||||
weight: float = 0.0 # decay- and team-size-weighted collaboration strength
|
||||
n_works: int = 0 # raw shared-work count
|
||||
cross_inst_weight: float = 0.0 # weight portion where the pair shared NO institution
|
||||
first_joint_year: int | None = None
|
||||
last_joint_year: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class NodeStats:
|
||||
display_name: str | None = None
|
||||
is_focal: bool = False # member of the institution author set
|
||||
publication_years: set[int] = field(default_factory=set) # ALL works (uncapped)
|
||||
n_works: int = 0 # ALL works (uncapped)
|
||||
field_counts: dict[str, int] = field(default_factory=dict) # primary_topic.field
|
||||
n_company_works: int = 0 # works with >=1 co-author institution type=company
|
||||
n_typed_works: int = 0 # works where >=1 institution has a non-null type
|
||||
# supervision signature inputs (per work, position-aware; capped works only)
|
||||
n_last_author_works: int = 0
|
||||
last_author_junior_first: list[tuple[str, int]] = field(default_factory=list)
|
||||
# ^ (first_author_id, year) for works where THIS node was last author
|
||||
|
||||
|
||||
@dataclass
|
||||
class Graph:
|
||||
edges: dict[tuple[str, str], EdgeStats]
|
||||
nodes: dict[str, NodeStats]
|
||||
n_works_used: int # works that entered pair generation
|
||||
n_works_capped: int # works excluded by max_authors_per_work
|
||||
ref_year: int # decay reference year
|
||||
|
||||
|
||||
def _work_author_rows(
|
||||
works: Iterable[dict[str, Any]],
|
||||
) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||
"""Flatten works into one row per (work, author) plus per-work metadata."""
|
||||
rows: list[dict[str, Any]] = []
|
||||
work_meta: dict[str, dict[str, Any]] = {}
|
||||
for w in works:
|
||||
wid = short_id(w.get("id"))
|
||||
year = w.get("publication_year")
|
||||
if not wid or not isinstance(year, int):
|
||||
continue
|
||||
authorships = w.get("authorships") or []
|
||||
seen: set[str] = set()
|
||||
work_rows = []
|
||||
has_company = False
|
||||
has_typed = False
|
||||
first_author: str | None = None
|
||||
last_author: str | None = None
|
||||
for a in authorships:
|
||||
aid = short_id((a.get("author") or {}).get("id"))
|
||||
if not aid or aid in seen:
|
||||
continue
|
||||
seen.add(aid)
|
||||
insts = a.get("institutions") or []
|
||||
inst_ids = frozenset(
|
||||
short_id(i.get("id")) for i in insts if i.get("id")
|
||||
)
|
||||
for i in insts:
|
||||
itype = i.get("type")
|
||||
if itype:
|
||||
has_typed = True
|
||||
if itype == "company":
|
||||
has_company = True
|
||||
position = a.get("author_position")
|
||||
if position == "first" and first_author is None:
|
||||
first_author = aid
|
||||
if position == "last":
|
||||
last_author = aid
|
||||
work_rows.append(
|
||||
{
|
||||
"work_id": wid,
|
||||
"year": year,
|
||||
"author_id": aid,
|
||||
"display_name": (a.get("author") or {}).get("display_name"),
|
||||
"inst_ids": inst_ids,
|
||||
}
|
||||
)
|
||||
n_authors = len(seen)
|
||||
field_id = short_id(((w.get("primary_topic") or {}).get("field") or {}).get("id"))
|
||||
work_meta[wid] = {
|
||||
"year": year,
|
||||
"n_authors": n_authors,
|
||||
"field_id": field_id,
|
||||
"has_company": has_company,
|
||||
"has_typed": has_typed,
|
||||
"first_author": first_author,
|
||||
"last_author": last_author,
|
||||
}
|
||||
rows.extend(work_rows)
|
||||
return rows, work_meta
|
||||
|
||||
|
||||
def build_graph(
|
||||
works: Iterable[dict[str, Any]],
|
||||
focal_author_ids: set[str],
|
||||
max_authors_per_work: int = 50,
|
||||
decay: float = 0.8,
|
||||
ref_year: int | None = None,
|
||||
) -> Graph:
|
||||
"""Build the weighted co-author graph and per-author aggregates.
|
||||
|
||||
`focal_author_ids` may contain full URLs or short ids; both are normalized.
|
||||
`ref_year` defaults to the max publication year in the corpus so results are
|
||||
deterministic for a given extract (never wall-clock dependent).
|
||||
"""
|
||||
focal = {short_id(a) for a in focal_author_ids}
|
||||
rows, work_meta = _work_author_rows(works)
|
||||
|
||||
if ref_year is None:
|
||||
ref_year = max((m["year"] for m in work_meta.values()), default=0)
|
||||
|
||||
# ---- node aggregates over ALL works (uncapped) ----
|
||||
nodes: dict[str, NodeStats] = {}
|
||||
for row in rows:
|
||||
aid = row["author_id"]
|
||||
node = nodes.get(aid)
|
||||
if node is None:
|
||||
node = nodes[aid] = NodeStats(
|
||||
display_name=row["display_name"], is_focal=aid in focal
|
||||
)
|
||||
meta = work_meta[row["work_id"]]
|
||||
node.publication_years.add(row["year"])
|
||||
node.n_works += 1
|
||||
if meta["field_id"]:
|
||||
node.field_counts[meta["field_id"]] = (
|
||||
node.field_counts.get(meta["field_id"], 0) + 1
|
||||
)
|
||||
if meta["has_typed"]:
|
||||
node.n_typed_works += 1
|
||||
if meta["has_company"]:
|
||||
node.n_company_works += 1
|
||||
|
||||
# supervision signature (uses author_position; only meaningful on capped works —
|
||||
# "last author" on a 500-author consortium paper is not a supervision signal)
|
||||
for wid, meta in work_meta.items():
|
||||
if not (2 <= meta["n_authors"] <= max_authors_per_work):
|
||||
continue
|
||||
la, fa = meta["last_author"], meta["first_author"]
|
||||
if la and la in nodes:
|
||||
nodes[la].n_last_author_works += 1
|
||||
if fa and fa != la:
|
||||
nodes[la].last_author_junior_first.append((fa, meta["year"]))
|
||||
|
||||
# ---- pair generation via polars self-join (capped works only) ----
|
||||
usable_work_ids = {
|
||||
wid
|
||||
for wid, meta in work_meta.items()
|
||||
if 2 <= meta["n_authors"] <= max_authors_per_work
|
||||
}
|
||||
n_capped = sum(
|
||||
1 for meta in work_meta.values() if meta["n_authors"] > max_authors_per_work
|
||||
)
|
||||
|
||||
pair_rows = [r for r in rows if r["work_id"] in usable_work_ids]
|
||||
edges: dict[tuple[str, str], EdgeStats] = {}
|
||||
if pair_rows:
|
||||
df = pl.DataFrame(
|
||||
{
|
||||
"work_id": [r["work_id"] for r in pair_rows],
|
||||
"author_id": [r["author_id"] for r in pair_rows],
|
||||
}
|
||||
)
|
||||
pairs = (
|
||||
df.join(df, on="work_id", suffix="_b")
|
||||
.filter(pl.col("author_id") < pl.col("author_id_b"))
|
||||
.select("work_id", "author_id", "author_id_b")
|
||||
)
|
||||
# institution sets are tiny per row; resolve shared-institution in Python
|
||||
inst_by_work_author: dict[tuple[str, str], frozenset] = {
|
||||
(r["work_id"], r["author_id"]): r["inst_ids"] for r in pair_rows
|
||||
}
|
||||
for wid, a, b in pairs.iter_rows():
|
||||
meta = work_meta[wid]
|
||||
year = meta["year"]
|
||||
w = (decay ** (ref_year - year)) / (meta["n_authors"] - 1)
|
||||
key = (a, b)
|
||||
e = edges.get(key)
|
||||
if e is None:
|
||||
e = edges[key] = EdgeStats()
|
||||
e.weight += w
|
||||
e.n_works += 1
|
||||
insts_a = inst_by_work_author[(wid, a)]
|
||||
insts_b = inst_by_work_author[(wid, b)]
|
||||
if not (insts_a & insts_b):
|
||||
e.cross_inst_weight += w
|
||||
if e.first_joint_year is None or year < e.first_joint_year:
|
||||
e.first_joint_year = year
|
||||
if e.last_joint_year is None or year > e.last_joint_year:
|
||||
e.last_joint_year = year
|
||||
|
||||
return Graph(
|
||||
edges=edges,
|
||||
nodes=nodes,
|
||||
n_works_used=len(usable_work_ids),
|
||||
n_works_capped=n_capped,
|
||||
ref_year=ref_year,
|
||||
)
|
||||
|
||||
|
||||
def adjacency(graph: Graph) -> dict[str, dict[str, float]]:
|
||||
"""Symmetric weighted adjacency over ALL nodes (focal + external)."""
|
||||
adj: dict[str, dict[str, float]] = {}
|
||||
for (a, b), e in graph.edges.items():
|
||||
adj.setdefault(a, {})[b] = e.weight
|
||||
adj.setdefault(b, {})[a] = e.weight
|
||||
return adj
|
||||
|
||||
|
||||
def focal_subgraph(graph: Graph) -> dict[str, dict[str, float]]:
|
||||
"""Adjacency restricted to focal (institution-internal) nodes only."""
|
||||
adj: dict[str, dict[str, float]] = {}
|
||||
for (a, b), e in graph.edges.items():
|
||||
na, nb = graph.nodes.get(a), graph.nodes.get(b)
|
||||
if na and nb and na.is_focal and nb.is_focal:
|
||||
adj.setdefault(a, {})[b] = e.weight
|
||||
adj.setdefault(b, {})[a] = e.weight
|
||||
return adj
|
||||
@@ -0,0 +1,272 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
index.py — idempotent indexing of scored multiplicator rows into Elasticsearch.
|
||||
|
||||
Target: the `multiplicators_v1` index on the INSE cluster. The index was created by
|
||||
the cluster admin — the standard API key can read/write/update-mapping but NOT
|
||||
create or delete indices, so this module must never attempt index creation.
|
||||
|
||||
Idempotency: doc _id = "<institution_short>_<author_short>", and every run first
|
||||
deletes the institution's existing docs via a search + bulk-delete-by-id loop.
|
||||
That loop (not _delete_by_query) is deliberate: the same cluster rejects
|
||||
_delete_by_query with 403 for the org_patents key — see
|
||||
inse/patents/org/elastic_search_client.py for the precedent.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from extract import INSE_KEY, INSE_URL, _headers
|
||||
|
||||
MULTIPLICATORS_INDEX = "multiplicators_v1"
|
||||
NETWORKS_INDEX = "multiplicator_networks_v1"
|
||||
REQUEST_TIMEOUT = 120.0
|
||||
BULK_CHUNK = 500
|
||||
|
||||
MAPPING = {
|
||||
"properties": {
|
||||
"institution_id": {"type": "keyword"},
|
||||
"cohort_institution_ids": {"type": "keyword"},
|
||||
"author_id": {"type": "keyword"},
|
||||
"display_name": {
|
||||
"type": "text",
|
||||
"fields": {"keyword": {"type": "keyword", "ignore_above": 256}},
|
||||
},
|
||||
"career_bucket": {"type": "keyword"},
|
||||
"active_years": {"type": "integer"},
|
||||
"n_works": {"type": "integer"},
|
||||
"suspicious_profile": {"type": "boolean"},
|
||||
"tags": {"type": "keyword"},
|
||||
"max_sub_score": {"type": "float"},
|
||||
"sub_scores": {
|
||||
"properties": {
|
||||
"bridger": {"type": "float"},
|
||||
"mentor": {"type": "float"},
|
||||
"amplifier": {"type": "float"},
|
||||
}
|
||||
},
|
||||
# M3 signal counts
|
||||
"patent_count": {"type": "integer"},
|
||||
"patent_count_name_only": {"type": "integer"}, # evidence only, never scored
|
||||
"news_mentions": {"type": "integer"},
|
||||
"cordis_eu_projects": {"type": "integer"},
|
||||
"industry_coauthor_share_shrunk": {"type": "float"},
|
||||
# raw metrics + percentiles kept as dynamic float objects (calibration needs them)
|
||||
"percentiles": {"type": "object", "dynamic": True},
|
||||
"evidence": {
|
||||
"properties": {"junior_ids": {"type": "keyword"}},
|
||||
},
|
||||
"config_hash": {"type": "keyword"},
|
||||
"computed_at": {"type": "date"},
|
||||
}
|
||||
}
|
||||
|
||||
# Visualization docs: nodes/edges live in _source only ("enabled": false — never
|
||||
# indexed/queried per-field, the frontend GETs whole docs by _id or author filter),
|
||||
# which keeps the index small despite ~900 edge objects per doc.
|
||||
NETWORK_MAPPING = {
|
||||
"properties": {
|
||||
"institution_id": {"type": "keyword"},
|
||||
"cohort_institution_ids": {"type": "keyword"},
|
||||
"author_id": {"type": "keyword"},
|
||||
"display_name": {
|
||||
"type": "text",
|
||||
"fields": {"keyword": {"type": "keyword", "ignore_above": 256}},
|
||||
},
|
||||
"ego": {
|
||||
"properties": {
|
||||
"career_bucket": {"type": "keyword"},
|
||||
"active_years": {"type": "integer"},
|
||||
"n_works": {"type": "integer"},
|
||||
"suspicious_profile": {"type": "boolean"},
|
||||
"tags": {"type": "keyword"},
|
||||
"max_sub_score": {"type": "float"},
|
||||
"sub_scores": {
|
||||
"properties": {
|
||||
"bridger": {"type": "float"},
|
||||
"mentor": {"type": "float"},
|
||||
"amplifier": {"type": "float"},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
"total_coauthors": {"type": "integer"},
|
||||
"cohort_coauthors": {"type": "integer"},
|
||||
"mentee_count": {"type": "integer"},
|
||||
"shown": {"type": "integer"},
|
||||
"shown_mentees": {"type": "integer"},
|
||||
"nodes": {"type": "object", "enabled": False},
|
||||
"edges": {"type": "object", "enabled": False},
|
||||
"config_hash": {"type": "keyword"},
|
||||
"computed_at": {"type": "date"},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class MultiplicatorsIndexClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
index: str = MULTIPLICATORS_INDEX,
|
||||
transport: httpx.BaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or INSE_URL).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else INSE_KEY
|
||||
self.index = index
|
||||
self.client = httpx.Client(transport=transport, timeout=REQUEST_TIMEOUT)
|
||||
if not self.base_url or not self.api_key:
|
||||
raise SystemExit("Missing INSE cluster credentials (ELASTICSEARCH_INSE_*).")
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
|
||||
return self.client.request(
|
||||
method,
|
||||
f"{self.base_url}/{path.lstrip('/')}",
|
||||
headers=_headers(self.api_key),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def ensure_mapping(self, mapping: dict[str, Any] | None = None) -> None:
|
||||
"""PUT the explicit mapping (additive; safe on every run). Never creates the index."""
|
||||
response = self._request(
|
||||
"PUT", f"{self.index}/_mapping", json=mapping or MAPPING
|
||||
)
|
||||
if not response.is_success:
|
||||
raise RuntimeError(
|
||||
f"Mapping update failed ({response.status_code}): {response.text[:500]}"
|
||||
)
|
||||
|
||||
def count_for_institution(self, institution_short_id: str) -> int:
|
||||
response = self._request(
|
||||
"POST",
|
||||
f"{self.index}/_count",
|
||||
json={"query": {"term": {"institution_id": institution_short_id}}},
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()["count"]
|
||||
|
||||
def _wait_for_count(self, institution_short_id: str, expected: int,
|
||||
timeout_s: float = 30.0) -> int:
|
||||
"""Poll _count until it reaches `expected` or timeout.
|
||||
|
||||
The API key is NOT allowed to call _refresh (indices:admin/refresh -> 403),
|
||||
so visibility of deletes/writes depends on the index's auto-refresh
|
||||
(default 1s). Polling is the only verification available to this key."""
|
||||
deadline = time.time() + timeout_s
|
||||
count = -1
|
||||
while time.time() < deadline:
|
||||
count = self.count_for_institution(institution_short_id)
|
||||
if count == expected:
|
||||
return count
|
||||
time.sleep(1.0)
|
||||
return count
|
||||
|
||||
def _collect_ids_for_institution(self, institution_short_id: str) -> list[str]:
|
||||
"""All doc _ids for the institution, paginated with search_after (collected
|
||||
BEFORE any deletes, so stale-visibility cannot inflate or loop the delete)."""
|
||||
ids: list[str] = []
|
||||
search_after = None
|
||||
while True:
|
||||
body: dict[str, Any] = {
|
||||
"size": 1000,
|
||||
"_source": False,
|
||||
"query": {"term": {"institution_id": institution_short_id}},
|
||||
"sort": [{"author_id": {"order": "asc"}}],
|
||||
}
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
response = self._request("POST", f"{self.index}/_search", json=body)
|
||||
response.raise_for_status()
|
||||
hits = response.json()["hits"]["hits"]
|
||||
if not hits:
|
||||
break
|
||||
ids.extend(h["_id"] for h in hits)
|
||||
search_after = hits[-1]["sort"]
|
||||
return ids
|
||||
|
||||
def delete_for_institution(self, institution_short_id: str) -> int:
|
||||
"""Collect ids, then bulk-delete-by-id (the key rejects _delete_by_query
|
||||
with 403). Returns the number of docs actually deleted."""
|
||||
ids = self._collect_ids_for_institution(institution_short_id)
|
||||
deleted = 0
|
||||
for start in range(0, len(ids), BULK_CHUNK):
|
||||
chunk = ids[start : start + BULK_CHUNK]
|
||||
lines = "".join(
|
||||
json.dumps({"delete": {"_index": self.index, "_id": doc_id}}) + "\n"
|
||||
for doc_id in chunk
|
||||
)
|
||||
bulk = self.client.post(
|
||||
f"{self.base_url}/_bulk",
|
||||
headers={**_headers(self.api_key), "Content-Type": "application/x-ndjson"},
|
||||
content=lines,
|
||||
)
|
||||
bulk.raise_for_status()
|
||||
for item in bulk.json()["items"]:
|
||||
result = item.get("delete", {})
|
||||
if result.get("result") == "deleted":
|
||||
deleted += 1
|
||||
elif result.get("error"):
|
||||
raise RuntimeError(f"Bulk delete error: {result['error']}")
|
||||
if ids:
|
||||
remaining = self._wait_for_count(institution_short_id, 0)
|
||||
if remaining != 0:
|
||||
raise RuntimeError(
|
||||
f"{remaining} docs for {institution_short_id} still visible "
|
||||
f"after delete (expected 0)"
|
||||
)
|
||||
return deleted
|
||||
|
||||
def index_rows(
|
||||
self,
|
||||
institution_short_id: str,
|
||||
cohort_short_ids: list[str],
|
||||
scored_rows: list[dict[str, Any]],
|
||||
) -> int:
|
||||
"""Delete-then-bulk-index all rows for the institution. Returns docs written."""
|
||||
computed_at = datetime.now(timezone.utc).isoformat()
|
||||
deleted = self.delete_for_institution(institution_short_id)
|
||||
print(f"Deleted {deleted} existing docs for {institution_short_id}")
|
||||
|
||||
written = 0
|
||||
for start in range(0, len(scored_rows), BULK_CHUNK):
|
||||
chunk = scored_rows[start : start + BULK_CHUNK]
|
||||
lines = []
|
||||
for row in chunk:
|
||||
doc = {
|
||||
**row,
|
||||
"institution_id": institution_short_id,
|
||||
"cohort_institution_ids": cohort_short_ids,
|
||||
"computed_at": computed_at,
|
||||
}
|
||||
doc_id = f"{institution_short_id}_{row['author_id']}"
|
||||
lines.append(
|
||||
json.dumps({"index": {"_index": self.index, "_id": doc_id}})
|
||||
)
|
||||
lines.append(json.dumps(doc, ensure_ascii=True))
|
||||
bulk = self.client.post(
|
||||
f"{self.base_url}/_bulk",
|
||||
headers={**_headers(self.api_key), "Content-Type": "application/x-ndjson"},
|
||||
content="\n".join(lines) + "\n",
|
||||
)
|
||||
bulk.raise_for_status()
|
||||
result = bulk.json()
|
||||
if result.get("errors"):
|
||||
first_error = next(
|
||||
(i["index"].get("error") for i in result["items"]
|
||||
if i.get("index", {}).get("error")),
|
||||
None,
|
||||
)
|
||||
raise RuntimeError(f"Bulk indexing reported errors, first: {first_error}")
|
||||
written += len(chunk)
|
||||
visible = self._wait_for_count(institution_short_id, written)
|
||||
if visible != written:
|
||||
raise RuntimeError(
|
||||
f"Post-index count mismatch for {institution_short_id}: "
|
||||
f"wrote {written}, index shows {visible} after 30s"
|
||||
)
|
||||
return written
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
make_report.py — render the ego-network HTML report from the LIVE ES indices.
|
||||
|
||||
Reads `multiplicators_v1` (scores) + `multiplicator_networks_v1` (nodes/edges) —
|
||||
the same two documents a frontend service would fetch — and writes a single
|
||||
self-contained HTML file to reports/. No local cache needed: the report can be
|
||||
regenerated any time after a build, on any machine with cluster access.
|
||||
|
||||
python make_report.py --institution-id I62318514
|
||||
python make_report.py --institution-id I62318514 \
|
||||
--author-ids A5113304257,A5043495754 # explicit cast instead of auto-pick
|
||||
|
||||
By default it picks one showcase per tag (highest bridger / mentor / amplifier)
|
||||
plus the highest-scoring person who just misses the tag threshold — the four
|
||||
contrasting cases that make the metrics legible.
|
||||
|
||||
The force-directed layout is computed here and baked into the file so the report
|
||||
stays dependency-free; a real frontend should instead let echarts' `graph` series
|
||||
lay out the same nodes/edges live.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import yaml
|
||||
from dotenv import load_dotenv
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
ENV_PATH = SCRIPT_DIR.parent.parent / "src" / "main" / "inse" / ".env"
|
||||
load_dotenv(dotenv_path=ENV_PATH)
|
||||
|
||||
INSE_URL = (os.environ.get("ELASTICSEARCH_INSE_URL") or "").rstrip("/")
|
||||
INSE_KEY = os.environ.get("ELASTICSEARCH_INSE_API_KEY") or ""
|
||||
SCORES_INDEX = "multiplicators_v1"
|
||||
NETWORKS_INDEX = "multiplicator_networks_v1"
|
||||
|
||||
SCORE_FIELDS = (
|
||||
"author_id", "display_name", "career_bucket", "active_years", "n_works",
|
||||
"suspicious_profile", "tags", "sub_scores", "percentiles", "betweenness",
|
||||
"brokerage", "constraint", "field_entropy", "cross_institution_share",
|
||||
"strength", "n_coauthors", "industry_coauthor_share",
|
||||
"industry_coauthor_share_shrunk", "juniors_mentored",
|
||||
"junior_progression_rate", "mentoring_rate", "last_author_with_junior_first",
|
||||
"patent_count", "news_mentions", "cordis_eu_projects",
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# ES access
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _headers() -> dict[str, str]:
|
||||
return {"Authorization": f"ApiKey {INSE_KEY}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
def es_get(client: httpx.Client, index: str, doc_id: str) -> dict | None:
|
||||
r = client.get(f"{INSE_URL}/{index}/_doc/{doc_id}", headers=_headers(), timeout=30)
|
||||
if r.status_code == 404:
|
||||
return None
|
||||
r.raise_for_status()
|
||||
return r.json()["_source"]
|
||||
|
||||
|
||||
def es_search(client: httpx.Client, index: str, body: dict) -> dict:
|
||||
r = client.post(f"{INSE_URL}/{index}/_search", headers=_headers(), json=body, timeout=60)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
|
||||
def pick_showcase(client: httpx.Client, institution: str) -> list[tuple[str, str]]:
|
||||
"""(author_id, kind) for the top bridger / mentor / amplifier + top near-miss."""
|
||||
picks: list[tuple[str, str]] = []
|
||||
seen: set[str] = set()
|
||||
for tag in ("bridger", "mentor", "amplifier"):
|
||||
res = es_search(client, SCORES_INDEX, {
|
||||
"size": 5,
|
||||
"_source": ["author_id"],
|
||||
"query": {"bool": {"filter": [
|
||||
{"term": {"institution_id": institution}},
|
||||
{"term": {"tags": tag}},
|
||||
]}},
|
||||
"sort": [{f"sub_scores.{tag}": {"order": "desc"}}],
|
||||
})
|
||||
for hit in res["hits"]["hits"]:
|
||||
aid = hit["_source"]["author_id"]
|
||||
if aid not in seen:
|
||||
picks.append((aid, tag))
|
||||
seen.add(aid)
|
||||
break
|
||||
# highest scorer that carries no tag — shows where the threshold bites
|
||||
res = es_search(client, SCORES_INDEX, {
|
||||
"size": 5,
|
||||
"_source": ["author_id"],
|
||||
"query": {"bool": {
|
||||
"filter": [{"term": {"institution_id": institution}}],
|
||||
"must_not": [{"exists": {"field": "tags"}}],
|
||||
}},
|
||||
"sort": [{"max_sub_score": {"order": "desc"}}],
|
||||
})
|
||||
for hit in res["hits"]["hits"]:
|
||||
aid = hit["_source"]["author_id"]
|
||||
if aid not in seen:
|
||||
picks.append((aid, "example"))
|
||||
seen.add(aid)
|
||||
break
|
||||
return picks
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Layout
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def fr_layout(node_ids, edge_list, w=760, h=560, iters=350, seed=7):
|
||||
"""Fruchterman-Reingold with the ego pinned to the centre (deterministic seed)."""
|
||||
rng = random.Random(seed)
|
||||
pos = {n: [rng.uniform(0, w), rng.uniform(0, h)] for n in node_ids}
|
||||
ego = node_ids[0]
|
||||
pos[ego] = [w / 2, h / 2]
|
||||
k = math.sqrt(w * h / max(len(node_ids), 1)) * 0.9
|
||||
t = w / 8
|
||||
wmax = max((e[2] for e in edge_list), default=1.0)
|
||||
for _ in range(iters):
|
||||
disp = {n: [0.0, 0.0] for n in node_ids}
|
||||
for i, a in enumerate(node_ids):
|
||||
for b in node_ids[i + 1:]:
|
||||
dx = pos[a][0] - pos[b][0]
|
||||
dy = pos[a][1] - pos[b][1]
|
||||
d = max(math.hypot(dx, dy), 0.01)
|
||||
f = k * k / d
|
||||
disp[a][0] += dx / d * f; disp[a][1] += dy / d * f
|
||||
disp[b][0] -= dx / d * f; disp[b][1] -= dy / d * f
|
||||
for a, b, wt in edge_list:
|
||||
dx = pos[a][0] - pos[b][0]
|
||||
dy = pos[a][1] - pos[b][1]
|
||||
d = max(math.hypot(dx, dy), 0.01)
|
||||
f = d * d / k * (0.3 + 0.7 * wt / wmax)
|
||||
disp[a][0] -= dx / d * f; disp[a][1] -= dy / d * f
|
||||
disp[b][0] += dx / d * f; disp[b][1] += dy / d * f
|
||||
for n in node_ids:
|
||||
if n == ego:
|
||||
continue
|
||||
dx, dy = disp[n]
|
||||
d = max(math.hypot(dx, dy), 0.01)
|
||||
pos[n][0] = min(w - 20, max(20, pos[n][0] + dx / d * min(d, t)))
|
||||
pos[n][1] = min(h - 20, max(20, pos[n][1] + dy / d * min(d, t)))
|
||||
t *= 0.97
|
||||
return pos
|
||||
|
||||
|
||||
def compose(client: httpx.Client, institution: str, picks: list[tuple[str, str]]) -> dict:
|
||||
out: dict[str, dict] = {}
|
||||
for author_id, kind in picks:
|
||||
doc_id = f"{institution}_{author_id}"
|
||||
net = es_get(client, NETWORKS_INDEX, doc_id)
|
||||
score = es_get(client, SCORES_INDEX, doc_id)
|
||||
if not net or not score:
|
||||
print(f" skip {author_id}: missing doc", file=sys.stderr)
|
||||
continue
|
||||
node_ids = [n["id"] for n in net["nodes"]]
|
||||
pos = fr_layout(node_ids, [(e["a"], e["b"], e["w"]) for e in net["edges"]])
|
||||
nodes = []
|
||||
for n in net["nodes"]:
|
||||
entry = {
|
||||
"id": n["id"], "name": n["name"], "role": n["role"],
|
||||
"inst": n.get("inst", ""), "active_years": n["active_years"],
|
||||
"x": round(pos[n["id"]][0], 1), "y": round(pos[n["id"]][1], 1),
|
||||
}
|
||||
if n.get("company_insts"):
|
||||
entry["company_insts"] = n["company_insts"]
|
||||
nodes.append(entry)
|
||||
out[author_id] = {
|
||||
"kind": kind,
|
||||
"score_row": {k: score[k] for k in SCORE_FIELDS if k in score},
|
||||
"total_coauthors": net["total_coauthors"],
|
||||
"shown": net["shown"],
|
||||
"nodes": nodes,
|
||||
"edges": [
|
||||
{"a": e["a"], "b": e["b"], "w": e["w"], "n": e["n_works"],
|
||||
"cross": e["cross"], "y0": e["first_year"]}
|
||||
for e in net["edges"]
|
||||
],
|
||||
"config_hash": score.get("config_hash", ""),
|
||||
"computed_at": (score.get("computed_at") or "")[:10],
|
||||
}
|
||||
roles: dict[str, int] = {}
|
||||
for n in nodes:
|
||||
roles[n["role"]] = roles.get(n["role"], 0) + 1
|
||||
print(f" {kind:<10} {score.get('display_name')}: {roles}", file=sys.stderr)
|
||||
return out
|
||||
|
||||
|
||||
TEMPLATE_PATH = SCRIPT_DIR / "report_template.html"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--institution-id", required=True)
|
||||
parser.add_argument(
|
||||
"--author-ids", default="",
|
||||
help="Comma-separated author IDs to feature. Overrides report.featured_author_ids "
|
||||
"in the config; pass --auto to force automatic selection instead.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--auto", action="store_true",
|
||||
help="Ignore the pinned cast and auto-select the current top scorer per tag.",
|
||||
)
|
||||
parser.add_argument("--config", default=str(SCRIPT_DIR / "multipliers.yaml"))
|
||||
parser.add_argument("--out", default=str(SCRIPT_DIR / "reports" / "multiplier_networks.html"))
|
||||
args = parser.parse_args()
|
||||
|
||||
if not INSE_URL or not INSE_KEY:
|
||||
raise SystemExit(f"Missing INSE credentials. Checked {ENV_PATH}")
|
||||
|
||||
institution = args.institution_id.strip().rsplit("/", 1)[-1]
|
||||
|
||||
# cast precedence: --author-ids > --auto > config pin > automatic
|
||||
pinned: list[str] = []
|
||||
if not args.auto and not args.author_ids:
|
||||
config_path = Path(args.config)
|
||||
if config_path.exists():
|
||||
config = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
|
||||
pinned = [
|
||||
str(a) for a in ((config.get("report") or {}).get("featured_author_ids") or [])
|
||||
]
|
||||
|
||||
with httpx.Client() as client:
|
||||
ids = [a.strip() for a in args.author_ids.split(",") if a.strip()] or pinned
|
||||
if ids:
|
||||
kinds = ["bridger", "mentor", "amplifier", "example"]
|
||||
picks = [(a, kinds[i] if i < len(kinds) else "example")
|
||||
for i, a in enumerate(ids)]
|
||||
source = "config-pinned" if pinned and not args.author_ids else "explicit"
|
||||
print(f"Cast ({source}): {[p[0] for p in picks]}", file=sys.stderr)
|
||||
else:
|
||||
picks = pick_showcase(client, institution)
|
||||
print(f"Auto-selected showcase: {[p[0] for p in picks]}", file=sys.stderr)
|
||||
data = compose(client, institution, picks)
|
||||
|
||||
if not data:
|
||||
raise SystemExit("No documents found — has build.py run for this institution?")
|
||||
|
||||
template = TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||
payload = json.dumps(data, ensure_ascii=True)
|
||||
assert "</script" not in payload, "data would break out of the script tag"
|
||||
html = template.replace("__DATA__", payload)
|
||||
|
||||
out_path = Path(args.out)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(html, encoding="utf-8")
|
||||
print(f"Report -> {out_path} ({len(html):,} bytes, {len(data)} cases)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,341 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
metrics.py — bridger / mentor metrics for multiplicator detection (M1, Stage D).
|
||||
|
||||
All functions are pure computations over the structures produced by graph.py.
|
||||
|
||||
Career-age foundation (see analysis/career_stage/README.md): first_publication_year is
|
||||
UNRELIABLE at UDE (merged OpenAlex profiles -> debut years like 1893), so nothing here
|
||||
uses it. The robust primitive is the prefix-counted active-year count
|
||||
|
||||
active_years_at(A, Y) = |{ y in distinct_publication_years(A) : y <= Y }|
|
||||
|
||||
which a single misattributed old work moves by exactly 1. It inherits the empirically
|
||||
validated career-stage thresholds from inse/persons/logic.py unchanged.
|
||||
|
||||
Mentor metrics are computed over FOCAL (institution-internal) pairs only: the extract
|
||||
contains the complete global history of focal authors, so their year-sets are exact,
|
||||
while external co-authors' year-sets are truncated to shared works (an external senior
|
||||
would look junior). This scope restriction is a data-correctness requirement, not a
|
||||
modelling choice.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
import math
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from graph import EdgeStats, Graph, adjacency, focal_subgraph
|
||||
|
||||
|
||||
def incident_edges(graph: Graph) -> dict[str, list[tuple[str, EdgeStats]]]:
|
||||
"""One pass over the edge dict -> per-author incident edge lists.
|
||||
|
||||
Every per-author metric must use this instead of scanning graph.edges —
|
||||
a full-edge scan per focal author is O(E * authors) and does not finish."""
|
||||
incident: dict[str, list[tuple[str, EdgeStats]]] = {}
|
||||
for (a, b), e in graph.edges.items():
|
||||
incident.setdefault(a, []).append((b, e))
|
||||
incident.setdefault(b, []).append((a, e))
|
||||
return incident
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Career primitives
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def active_years_at(publication_years: set[int], year: int) -> int:
|
||||
"""Distinct publication years up to and including `year` (robust seniority)."""
|
||||
return sum(1 for y in publication_years if y <= year)
|
||||
|
||||
|
||||
def is_suspicious_profile(publication_years: set[int]) -> bool:
|
||||
"""Merged-profile flag, same rule as inse/persons/logic.py."""
|
||||
if not publication_years:
|
||||
return False
|
||||
first = min(publication_years)
|
||||
span = max(publication_years) - first + 1
|
||||
return first < 1970 or span > 60
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Betweenness — Brandes (2001), weighted variant with Dijkstra.
|
||||
# Weights are collaboration STRENGTHS; shortest paths need DISTANCES, so we
|
||||
# pass 1/weight (strong ties = short distances). Pure stdlib.
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def betweenness_centrality(
|
||||
adj: dict[str, dict[str, float]], normalized: bool = True
|
||||
) -> dict[str, float]:
|
||||
nodes = list(adj.keys())
|
||||
bc = {v: 0.0 for v in nodes}
|
||||
|
||||
for s in nodes:
|
||||
# single-source shortest paths (Dijkstra on 1/weight distances).
|
||||
# All per-source state is lazy (touched nodes only) — a per-source init
|
||||
# over all V nodes would make the whole thing O(V^2) before any work.
|
||||
dist: dict[str, float] = {s: 0.0}
|
||||
sigma: dict[str, float] = {s: 1.0}
|
||||
preds: dict[str, list[str]] = {}
|
||||
done: set[str] = set()
|
||||
order: list[str] = []
|
||||
heap: list[tuple[float, str]] = [(0.0, s)]
|
||||
while heap:
|
||||
d, v = heapq.heappop(heap)
|
||||
if v in done:
|
||||
continue
|
||||
done.add(v)
|
||||
order.append(v)
|
||||
sigma_v = sigma[v]
|
||||
for u, w in adj[v].items():
|
||||
if w <= 0:
|
||||
continue
|
||||
nd = d + 1.0 / w
|
||||
old = dist.get(u)
|
||||
if old is None or nd < old - 1e-12:
|
||||
dist[u] = nd
|
||||
sigma[u] = sigma_v
|
||||
preds[u] = [v]
|
||||
heapq.heappush(heap, (nd, u))
|
||||
elif abs(nd - old) <= 1e-12 and u not in done:
|
||||
sigma[u] += sigma_v
|
||||
preds.setdefault(u, []).append(v)
|
||||
# accumulation, reverse order of discovery
|
||||
delta: dict[str, float] = {}
|
||||
for v in reversed(order):
|
||||
dv = delta.get(v, 0.0)
|
||||
coeff = (1.0 + dv) / sigma[v]
|
||||
for p in preds.get(v, ()):
|
||||
delta[p] = delta.get(p, 0.0) + sigma[p] * coeff
|
||||
if v != s:
|
||||
bc[v] += dv
|
||||
|
||||
# undirected: each pair counted twice
|
||||
for v in bc:
|
||||
bc[v] /= 2.0
|
||||
if normalized and len(nodes) > 2:
|
||||
scale = 1.0 / ((len(nodes) - 1) * (len(nodes) - 2) / 2.0)
|
||||
for v in bc:
|
||||
bc[v] *= scale
|
||||
return bc
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Burt's constraint — low constraint == structural-hole spanner (bridger).
|
||||
# Computed on the FULL graph (external co-authors included): someone whose
|
||||
# UDE-internal network is dense but who alone connects to industry/abroad
|
||||
# is a bridger that internal betweenness cannot see.
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def burt_constraint(
|
||||
adj: dict[str, dict[str, float]], nodes: list[str] | None = None
|
||||
) -> dict[str, float]:
|
||||
"""Constraint c_i = sum_j (p_ij + sum_q p_iq * p_qj)^2 over neighbours j of i.
|
||||
|
||||
p_ij = w_ij / sum_k w_ik. Isolates get constraint 1.0 (fully constrained).
|
||||
"""
|
||||
# strength totals once — recomputing sum(neigh.values()) inside the O(d^2)
|
||||
# inner loop makes this O(d^3) and unusable on hub nodes
|
||||
totals = {v: sum(neigh.values()) for v, neigh in adj.items()}
|
||||
|
||||
result: dict[str, float] = {}
|
||||
targets = nodes if nodes is not None else list(adj.keys())
|
||||
for i in targets:
|
||||
neigh = adj.get(i) or {}
|
||||
total = totals.get(i, 0.0)
|
||||
if total <= 0:
|
||||
result[i] = 1.0
|
||||
continue
|
||||
p_i = {j: w / total for j, w in neigh.items()}
|
||||
c = 0.0
|
||||
for j, p_ij in p_i.items():
|
||||
indirect = 0.0
|
||||
for q, p_iq in p_i.items():
|
||||
if q == j:
|
||||
continue
|
||||
q_neigh = adj.get(q)
|
||||
if not q_neigh:
|
||||
continue
|
||||
w_qj = q_neigh.get(j)
|
||||
if w_qj:
|
||||
indirect += p_iq * (w_qj / totals[q])
|
||||
c += (p_ij + indirect) ** 2
|
||||
result[i] = c
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Simple per-node shares
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def field_entropy(field_counts: dict[str, int]) -> float:
|
||||
"""Shannon entropy (bits) over primary_topic.field of an author's works."""
|
||||
total = sum(field_counts.values())
|
||||
if total <= 0:
|
||||
return 0.0
|
||||
ent = 0.0
|
||||
for c in field_counts.values():
|
||||
if c > 0:
|
||||
p = c / total
|
||||
ent -= p * math.log2(p)
|
||||
return ent
|
||||
|
||||
|
||||
def cross_institution_share(
|
||||
graph: Graph,
|
||||
author_id: str,
|
||||
incident: dict[str, list[tuple[str, EdgeStats]]] | None = None,
|
||||
) -> float:
|
||||
"""Share of an author's edge weight where the pair shared no institution."""
|
||||
if incident is None:
|
||||
incident = incident_edges(graph)
|
||||
total = 0.0
|
||||
cross = 0.0
|
||||
for _, e in incident.get(author_id, ()):
|
||||
total += e.weight
|
||||
cross += e.cross_inst_weight
|
||||
return cross / total if total > 0 else 0.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Mentor metrics — debut-year-free (see module docstring)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class MentorMetrics:
|
||||
juniors_mentored: int = 0
|
||||
junior_progression_rate: float | None = None # None if no juniors
|
||||
last_author_with_junior_first: int = 0
|
||||
mentoring_rate: float = 0.0
|
||||
junior_ids: list[str] = field(default_factory=list) # evidence
|
||||
|
||||
|
||||
def mentor_metrics(
|
||||
graph: Graph,
|
||||
focal_author_id: str,
|
||||
junior_active_years_max: int = 4,
|
||||
senior_active_years_min: int = 10,
|
||||
progressed_active_years_min: int = 5,
|
||||
incident: dict[str, list[tuple[str, EdgeStats]]] | None = None,
|
||||
) -> MentorMetrics:
|
||||
"""Seniority-gap mentorship over focal-internal pairs.
|
||||
|
||||
A co-author J counts as "mentored" when, at the year Y of the FIRST joint work:
|
||||
active_years_at(J, Y) <= junior_active_years_max (J was Early-career)
|
||||
active_years_at(focal, Y) >= senior_active_years_min (focal was Established+)
|
||||
Progression: J later reached >= progressed_active_years_min total active years.
|
||||
"""
|
||||
focal_node = graph.nodes.get(focal_author_id)
|
||||
if focal_node is None:
|
||||
return MentorMetrics()
|
||||
if incident is None:
|
||||
incident = incident_edges(graph)
|
||||
|
||||
juniors: list[str] = []
|
||||
progressed = 0
|
||||
for other, e in incident.get(focal_author_id, ()):
|
||||
if e.first_joint_year is None:
|
||||
continue
|
||||
other_node = graph.nodes.get(other)
|
||||
if other_node is None or not other_node.is_focal or not focal_node.is_focal:
|
||||
continue # internal pairs only — external year-sets are truncated
|
||||
y = e.first_joint_year
|
||||
if (
|
||||
active_years_at(other_node.publication_years, y) <= junior_active_years_max
|
||||
and active_years_at(focal_node.publication_years, y) >= senior_active_years_min
|
||||
):
|
||||
juniors.append(other)
|
||||
if len(other_node.publication_years) >= progressed_active_years_min:
|
||||
progressed += 1
|
||||
|
||||
# supervision signature: focal last author, junior (at that work's year) first author
|
||||
last_author_junior_first = 0
|
||||
for first_author, year in focal_node.last_author_junior_first:
|
||||
fa_node = graph.nodes.get(first_author)
|
||||
if fa_node is None or not fa_node.is_focal:
|
||||
continue
|
||||
if active_years_at(fa_node.publication_years, year) <= junior_active_years_max:
|
||||
last_author_junior_first += 1
|
||||
|
||||
total_active = len(focal_node.publication_years)
|
||||
return MentorMetrics(
|
||||
juniors_mentored=len(juniors),
|
||||
junior_progression_rate=(progressed / len(juniors)) if juniors else None,
|
||||
last_author_with_junior_first=last_author_junior_first,
|
||||
mentoring_rate=(len(juniors) / total_active) if total_active else 0.0,
|
||||
junior_ids=juniors,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Orchestration: all raw metrics for every focal author
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def compute_all_metrics(
|
||||
graph: Graph,
|
||||
junior_active_years_max: int = 4,
|
||||
senior_active_years_min: int = 10,
|
||||
progressed_active_years_min: int = 5,
|
||||
industry_share_shrinkage_k: int = 5,
|
||||
) -> dict[str, dict]:
|
||||
"""Raw (un-normalized) metric rows keyed by focal author id."""
|
||||
internal = focal_subgraph(graph)
|
||||
full_adj = adjacency(graph)
|
||||
incident = incident_edges(graph)
|
||||
focal_ids = [aid for aid, n in graph.nodes.items() if n.is_focal]
|
||||
|
||||
bc = betweenness_centrality(internal) if internal else {}
|
||||
constraint = burt_constraint(full_adj, nodes=[a for a in focal_ids if a in full_adj])
|
||||
|
||||
rows: dict[str, dict] = {}
|
||||
for aid in focal_ids:
|
||||
node = graph.nodes[aid]
|
||||
mm = mentor_metrics(
|
||||
graph,
|
||||
aid,
|
||||
junior_active_years_max=junior_active_years_max,
|
||||
senior_active_years_min=senior_active_years_min,
|
||||
progressed_active_years_min=progressed_active_years_min,
|
||||
incident=incident,
|
||||
)
|
||||
strength = sum(full_adj.get(aid, {}).values())
|
||||
rows[aid] = {
|
||||
"author_id": aid,
|
||||
"display_name": node.display_name,
|
||||
"active_years": len(node.publication_years),
|
||||
"n_works": node.n_works,
|
||||
"suspicious_profile": is_suspicious_profile(node.publication_years),
|
||||
# bridger
|
||||
"betweenness": bc.get(aid, 0.0),
|
||||
"constraint": constraint.get(aid, 1.0),
|
||||
"brokerage": 1.0 - constraint.get(aid, 1.0), # higher = more bridging
|
||||
"field_entropy": field_entropy(node.field_counts),
|
||||
"cross_institution_share": cross_institution_share(graph, aid, incident),
|
||||
"strength": strength,
|
||||
"n_coauthors": len(full_adj.get(aid, {})),
|
||||
# amplifier inputs available from OpenAlex alone
|
||||
"industry_coauthor_share": (
|
||||
node.n_company_works / node.n_typed_works if node.n_typed_works else 0.0
|
||||
),
|
||||
# shrunk variant for SCORING: n_company/(n_typed+k) damps the small-
|
||||
# denominator artifact where 2-of-2 company works outranks 40-of-80 —
|
||||
# the live index's top "amplifiers" were exactly such ratio artifacts
|
||||
"industry_coauthor_share_shrunk": (
|
||||
node.n_company_works / (node.n_typed_works + industry_share_shrinkage_k)
|
||||
if node.n_typed_works
|
||||
else 0.0
|
||||
),
|
||||
# mentor
|
||||
"juniors_mentored": mm.juniors_mentored,
|
||||
"junior_progression_rate": mm.junior_progression_rate,
|
||||
"last_author_with_junior_first": mm.last_author_with_junior_first,
|
||||
"mentoring_rate": mm.mentoring_rate,
|
||||
"junior_ids": mm.junior_ids,
|
||||
}
|
||||
return rows
|
||||
@@ -0,0 +1,121 @@
|
||||
# Multiplicator detection — all tunables live here.
|
||||
# Coaches will retune weights/thresholds; every output doc carries a config_hash
|
||||
# of this file so scores stay attributable to the weighting that produced them.
|
||||
|
||||
version: 2
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cohorts — which OpenAlex institutions constitute "the university".
|
||||
#
|
||||
# Keyed by the primary institution ID passed as --institution-id. If a cohort
|
||||
# entry exists, the author set is extracted over ALL listed IDs; otherwise the
|
||||
# primary ID alone is used. Needed because OpenAlex does NOT model university
|
||||
# hospitals as lineage children: Essen University Hospital is only "related"
|
||||
# to UDE, which silently excluded ~2,437 active clinicians (incl. prominent
|
||||
# medicine professors) from the cohort — found via the M1 validation, where
|
||||
# 17/60 hand-labeled people were missing.
|
||||
#
|
||||
# Source of candidates: openalex-institutions `associated_institutions` of the
|
||||
# primary ID (children + related), one hop deep. Every inclusion/exclusion is
|
||||
# a human judgment call — document the reason next to each entry.
|
||||
# ---------------------------------------------------------------------------
|
||||
cohorts:
|
||||
I62318514:
|
||||
name: University of Duisburg-Essen
|
||||
institution_ids:
|
||||
- I62318514 # UDE itself (primary)
|
||||
- I4210119759 # Essen University Hospital — the university medical centre;
|
||||
# "related" in OpenAlex, NOT lineage, hence the coverage gap
|
||||
- I4210161917 # West German Heart and Vascular Center Essen — child of the hospital
|
||||
- I127668822 # Erwin L. Hahn Institute for MRI — joint UDE institute,
|
||||
# isolated in OpenAlex (no lineage/associated links at all)
|
||||
- I4210090139 # Rhein-Ruhr Institut für Sozialforschung (child of UDE)
|
||||
- I4210092428 # Deutsches Textilforschungszentrum Nord-West (child of UDE)
|
||||
- I4210110714 # Institute for Advanced Study in the Humanities Essen / KWI (child)
|
||||
- I4210146441 # The Hydrogen and Fuel Cell Center / ZBT (child of UDE)
|
||||
- I4210154243 # Institut für Energie- und Umwelttechnik / IUTA (child of UDE)
|
||||
# Deliberately EXCLUDED (decide with the coaches before enabling):
|
||||
# - I4210146447 Kliniken Essen-Mitte — independent hospital group, only
|
||||
# "related"; staff are not UDE researchers (~788 authors)
|
||||
# - I2799342142 Salomon Ludwig Steinheim-Institut — independent An-Institut
|
||||
# - I4210124583 IWW Water Centre — independent An-Institut
|
||||
|
||||
extraction:
|
||||
# "Recent affiliation" cutoff for the author set. 2023 (not the current year):
|
||||
# publication lag pushes current staff out of a 1-year window — the M1 validation
|
||||
# found 6 current-ish people (incl. an active professor) with newest affiliation
|
||||
# year 2021-2024. 2023 captures normal lag while still excluding long-departed.
|
||||
affiliation_years_gte: 2023
|
||||
work_year_gte: 1950
|
||||
# Chosen from the M0 spike (authors/work p50=5, p90=17, p99=144, max=4839):
|
||||
# cap 50 keeps >=99% of works and excludes only true hyperauthorship, which
|
||||
# carries no collaboration signal but would create giant artificial cliques.
|
||||
max_authors_per_work: 50
|
||||
|
||||
graph:
|
||||
decay: 0.8 # per-year edge weight decay (ref = newest corpus year)
|
||||
|
||||
career:
|
||||
# active_years bucket thresholds — mirror inse/persons/logic.py _classify_career_stage.
|
||||
# Buckets: Early <= 4, Emerging <= 9, Established <= 14, Senior > 14.
|
||||
buckets: [4, 9, 14]
|
||||
bucket_names: [Early, Emerging, Established, Senior]
|
||||
|
||||
mentor:
|
||||
junior_active_years_max: 4 # junior == Early-career at first joint work
|
||||
senior_active_years_min: 10 # focal must be Established+ at first joint work
|
||||
progressed_active_years_min: 5
|
||||
|
||||
signals:
|
||||
# org_patents match_types that count toward the score; "name"-only matches are
|
||||
# carried as evidence (patent_count_name_only) but never scored.
|
||||
patent_match_types: [institution, both]
|
||||
news_require_relevant: true # only aktuell_postproc docs the LLM marked relevant
|
||||
# Shrinkage constant for industry_coauthor_share_shrunk = company/(typed+k):
|
||||
# damps small denominators (2-of-2 works with a company co-author is not a
|
||||
# stronger industry signal than 40-of-80). Found via the live-index audit,
|
||||
# where all top-10 "amplifiers" were such ratio artifacts.
|
||||
industry_share_shrinkage_k: 5
|
||||
|
||||
network:
|
||||
# Per-author ego-network docs for the visualization frontend
|
||||
# (index multiplicator_networks_v1). Nodes shown = strongest co-authors by tie
|
||||
# weight, with mentees force-included first — their decayed, team-size-divided
|
||||
# ties otherwise never make the cut (a 100-mentee professor had ZERO mentees
|
||||
# in his unforced top 42).
|
||||
max_nodes: 42
|
||||
max_forced_mentees: 14
|
||||
|
||||
# Sub-score weights over WITHIN-BUCKET percentiles of the raw metrics.
|
||||
# Weights within each sub-score should sum to 1.
|
||||
weights:
|
||||
bridger:
|
||||
betweenness: 0.35
|
||||
brokerage: 0.25 # 1 - Burt constraint, full graph incl. externals
|
||||
field_entropy: 0.20
|
||||
cross_institution_share: 0.20
|
||||
mentor:
|
||||
juniors_mentored: 0.35
|
||||
mentoring_rate: 0.25
|
||||
last_author_with_junior_first: 0.25
|
||||
junior_progression_rate: 0.15
|
||||
amplifier:
|
||||
industry_coauthor_share_shrunk: 0.50 # primary: ID-linked company co-authorship, shrunk
|
||||
patent_count: 0.25 # high-confidence org_patents (institution/both)
|
||||
cordis_eu_projects: 0.15 # DOI-join, no name matching
|
||||
news_mentions: 0.10 # normalized-exact name match — lossy; keep low
|
||||
|
||||
tags:
|
||||
threshold: 0.85 # tag fires when sub-score >= threshold (multiple allowed)
|
||||
min_active_years: 2 # never tag someone with <2 active years (no history)
|
||||
|
||||
report:
|
||||
# Cast for make_report.py, in order: bridger, mentor, amplifier, near-miss.
|
||||
# Pinned so the report is reproducible — without this the script auto-picks the
|
||||
# current top scorer per tag, which changes with every weight tune or dump refresh.
|
||||
# Remove/empty the list to fall back to automatic selection.
|
||||
featured_author_ids:
|
||||
- A5113304257 # Jan Egger — top bridger
|
||||
- A5043495754 # Cornelius Deuschl — top mentor
|
||||
- A5007801159 # Jens Wiltfang — top amplifier
|
||||
- A5043360678 # Tabea M. G. Pakull — strong profile just below the tag line
|
||||
@@ -0,0 +1,161 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
networks.py — materialize per-author ego-network documents for visualization.
|
||||
|
||||
The scores index answers "what did this person score"; the network index answers
|
||||
"who are they connected to and how" — the data a frontend needs to draw the
|
||||
ego-network figures (force layout, role colors, tooltips). The neighbor-neighbor
|
||||
edges that make graph shape readable (dense mesh = one community, spokes with gaps
|
||||
= brokered structural holes) come from works that do NOT include the ego, so they
|
||||
can only be materialized here, while the full graph is in memory — no request-time
|
||||
query can reconstruct them.
|
||||
|
||||
Doc shape (one per focal author, _id = <institution>_<author>):
|
||||
|
||||
nodes[] {id, name, role, inst, active_years, suspicious}
|
||||
role: ego | mentee | cohort | industry | external
|
||||
edges[] {a, b, w, n_works, cross, first_year, last_year}
|
||||
w = decayed collaboration strength; cross = mostly cross-institution
|
||||
ego{} small header duplicate (bucket, tags, sub_scores) so the network
|
||||
endpoint can render standalone
|
||||
totals total_coauthors, cohort_coauthors, shown
|
||||
|
||||
Node selection: the ego's strongest `max_nodes` co-authors by tie weight, with up
|
||||
to `max_forced_mentees` mentees force-included first — mentees' ties are decayed
|
||||
and team-size-divided, so a pure top-by-weight cut hides exactly the people the
|
||||
mentor score is about (empirically: a 100-mentee professor had zero mentees in his
|
||||
unforced top 42). Positions are NOT stored — the frontend's force layout
|
||||
(e.g. echarts `graph` series) lays out at render time.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from graph import Graph
|
||||
from metrics import is_suspicious_profile
|
||||
|
||||
|
||||
def build_network_docs(
|
||||
graph: Graph,
|
||||
metric_rows: dict[str, dict[str, Any]],
|
||||
scored_rows: list[dict[str, Any]],
|
||||
incident: dict[str, list],
|
||||
inst_by_author: dict[str, str],
|
||||
company_by_author_work: dict[str, dict[str, list[str]]],
|
||||
company_work_authors: dict[str, set[str]],
|
||||
max_nodes: int = 42,
|
||||
max_forced_mentees: int = 14,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""One visualization doc per focal author.
|
||||
|
||||
metric_rows must still carry the FULL `junior_ids` (pre-scoring; the scored
|
||||
rows' evidence list is capped). scored_rows supply the ego header fields.
|
||||
|
||||
Industry roles are TIE-LEVEL, not lifetime: a neighbour is marked `industry`
|
||||
only if a company affiliation of theirs appears on a work SHARED with the ego
|
||||
— matching what `industry_coauthor_share` counts. (The first version flagged
|
||||
anyone who ever had a company affiliation anywhere in the corpus, which
|
||||
painted predominantly-academic people orange over one dual affiliation from
|
||||
years ago, with a university name in the tooltip contradicting the colour.)
|
||||
The triggering company names ship on the node as `company_insts`, and
|
||||
`inst_by_author` should be the author's MOST FREQUENT institution so the
|
||||
default label matches reality.
|
||||
"""
|
||||
scored_by_id = {r["author_id"]: r for r in scored_rows}
|
||||
docs: list[dict[str, Any]] = []
|
||||
|
||||
for ego_id, mrow in metric_rows.items():
|
||||
srow = scored_by_id.get(ego_id)
|
||||
if srow is None:
|
||||
continue
|
||||
mentees = set(mrow.get("junior_ids") or [])
|
||||
ranked = sorted(
|
||||
incident.get(ego_id, []), key=lambda kv: kv[1].weight, reverse=True
|
||||
)
|
||||
|
||||
mentee_picks = [n for n, _ in ranked if n in mentees][:max_forced_mentees]
|
||||
forced = set(mentee_picks)
|
||||
others = [n for n, _ in ranked if n not in forced]
|
||||
selected = [ego_id] + mentee_picks + others[: max_nodes - len(mentee_picks)]
|
||||
idset = set(selected)
|
||||
|
||||
nodes = []
|
||||
for nid in selected:
|
||||
node = graph.nodes[nid]
|
||||
# company evidence ON WORKS SHARED WITH THE EGO only
|
||||
shared_companies: set[str] = set()
|
||||
for wid, names in (company_by_author_work.get(nid) or {}).items():
|
||||
if ego_id in company_work_authors.get(wid, ()):
|
||||
shared_companies.update(names)
|
||||
if nid == ego_id:
|
||||
role = "ego"
|
||||
elif nid in mentees:
|
||||
role = "mentee"
|
||||
elif shared_companies and not node.is_focal:
|
||||
role = "industry"
|
||||
elif node.is_focal:
|
||||
role = "cohort"
|
||||
else:
|
||||
role = "external"
|
||||
entry = {
|
||||
"id": nid,
|
||||
"name": node.display_name,
|
||||
"role": role,
|
||||
"inst": inst_by_author.get(nid, ""),
|
||||
"active_years": len(node.publication_years),
|
||||
"suspicious": is_suspicious_profile(node.publication_years),
|
||||
}
|
||||
if shared_companies:
|
||||
# the receipts for the industry colour (also kept on cohort/
|
||||
# mentee nodes so tooltips can show the industry link)
|
||||
entry["company_insts"] = sorted(shared_companies)
|
||||
nodes.append(entry)
|
||||
|
||||
# all corpus edges among the selected nodes — pair lookups against the
|
||||
# edge dict (~900 per ego), NOT a scan of the 5.8M-edge dict per ego
|
||||
edges = []
|
||||
for i, a in enumerate(selected):
|
||||
for b in selected[i + 1:]:
|
||||
e = graph.edges.get((a, b) if a < b else (b, a))
|
||||
if e is None:
|
||||
continue
|
||||
edges.append(
|
||||
{
|
||||
"a": a,
|
||||
"b": b,
|
||||
"w": round(e.weight, 3),
|
||||
"n_works": e.n_works,
|
||||
"cross": bool(
|
||||
e.weight > 0 and e.cross_inst_weight / e.weight > 0.5
|
||||
),
|
||||
"first_year": e.first_joint_year,
|
||||
"last_year": e.last_joint_year,
|
||||
}
|
||||
)
|
||||
|
||||
cohort_coauthors = sum(
|
||||
1 for n, _ in ranked if graph.nodes[n].is_focal
|
||||
)
|
||||
docs.append(
|
||||
{
|
||||
"author_id": ego_id,
|
||||
"display_name": srow.get("display_name"),
|
||||
"ego": {
|
||||
"career_bucket": srow.get("career_bucket"),
|
||||
"active_years": srow.get("active_years"),
|
||||
"n_works": srow.get("n_works"),
|
||||
"suspicious_profile": srow.get("suspicious_profile"),
|
||||
"tags": srow.get("tags", []),
|
||||
"sub_scores": srow.get("sub_scores", {}),
|
||||
"max_sub_score": srow.get("max_sub_score"),
|
||||
},
|
||||
"total_coauthors": len(ranked),
|
||||
"cohort_coauthors": cohort_coauthors,
|
||||
"mentee_count": len(mentees),
|
||||
"shown": len(selected) - 1,
|
||||
"shown_mentees": len(mentee_picks),
|
||||
"nodes": nodes,
|
||||
"edges": edges,
|
||||
}
|
||||
)
|
||||
return docs
|
||||
@@ -0,0 +1,461 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Multipliers, drawn as networks</title>
|
||||
<style>
|
||||
:root {
|
||||
--surface: #fcfcfb;
|
||||
--surface-2: #f4f3f0;
|
||||
--ink: #0b0b0b;
|
||||
--ink-2: #52514e;
|
||||
--ink-3: #8a8983;
|
||||
--line: #e4e2dc;
|
||||
--ego: #e87ba4;
|
||||
--cohort: #2a78d6;
|
||||
--mentee: #1baf7a;
|
||||
--industry: #eb6834;
|
||||
--external: #b5b4ac;
|
||||
--bar: #2a78d6;
|
||||
--node-stroke: rgba(11,11,11,.35);
|
||||
color-scheme: light;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) {
|
||||
--surface: #1a1a19;
|
||||
--surface-2: #232322;
|
||||
--ink: #ffffff;
|
||||
--ink-2: #c3c2b7;
|
||||
--ink-3: #8a8983;
|
||||
--line: #3a3936;
|
||||
--ego: #d55181;
|
||||
--cohort: #3987e5;
|
||||
--mentee: #199e70;
|
||||
--industry: #d95926;
|
||||
--external: #55544f;
|
||||
--bar: #3987e5;
|
||||
--node-stroke: rgba(255,255,255,.35);
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--surface: #1a1a19;
|
||||
--surface-2: #232322;
|
||||
--ink: #ffffff;
|
||||
--ink-2: #c3c2b7;
|
||||
--ink-3: #8a8983;
|
||||
--line: #3a3936;
|
||||
--ego: #d55181;
|
||||
--cohort: #3987e5;
|
||||
--mentee: #199e70;
|
||||
--industry: #d95926;
|
||||
--external: #55544f;
|
||||
--bar: #3987e5;
|
||||
--node-stroke: rgba(255,255,255,.35);
|
||||
color-scheme: dark;
|
||||
}
|
||||
:root[data-theme="light"] {
|
||||
--surface: #fcfcfb;
|
||||
--surface-2: #f4f3f0;
|
||||
--ink: #0b0b0b;
|
||||
--ink-2: #52514e;
|
||||
--ink-3: #8a8983;
|
||||
--line: #e4e2dc;
|
||||
--ego: #e87ba4;
|
||||
--cohort: #2a78d6;
|
||||
--mentee: #1baf7a;
|
||||
--industry: #eb6834;
|
||||
--external: #b5b4ac;
|
||||
--bar: #2a78d6;
|
||||
--node-stroke: rgba(11,11,11,.35);
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--surface);
|
||||
color: var(--ink);
|
||||
font-family: Charter, Georgia, 'Times New Roman', serif;
|
||||
line-height: 1.55;
|
||||
margin: 0;
|
||||
}
|
||||
.wrap { max-width: 1160px; margin: 0 auto; padding: 40px 24px 80px; }
|
||||
|
||||
header.page { max-width: 70ch; margin-bottom: 12px; }
|
||||
.eyebrow {
|
||||
font-family: -apple-system, 'Segoe UI', sans-serif;
|
||||
font-size: 11px; letter-spacing: .14em; text-transform: uppercase;
|
||||
color: var(--ink-3); margin: 0 0 10px;
|
||||
}
|
||||
h1 { font-size: 34px; line-height: 1.15; margin: 0 0 12px; text-wrap: balance; font-weight: 700; }
|
||||
.lede { color: var(--ink-2); font-size: 16.5px; margin: 0; }
|
||||
|
||||
.legend {
|
||||
position: sticky; top: 0; z-index: 5;
|
||||
background: var(--surface);
|
||||
border-block: 1px solid var(--line);
|
||||
margin: 28px 0 0;
|
||||
padding: 10px 2px;
|
||||
display: flex; flex-wrap: wrap; gap: 14px 22px; align-items: center;
|
||||
font-family: -apple-system, 'Segoe UI', sans-serif; font-size: 12.5px; color: var(--ink-2);
|
||||
}
|
||||
.legend .li { display: inline-flex; align-items: center; gap: 7px; }
|
||||
.dot { width: 11px; height: 11px; border-radius: 50%; border: 1px solid var(--node-stroke); flex: none; }
|
||||
.dot.ego { outline: 2px solid var(--ink); outline-offset: 1.5px; }
|
||||
.edge-sample { width: 26px; height: 0; border-top: 2px solid var(--ink-3); flex: none; }
|
||||
.edge-sample.dashed { border-top-style: dashed; }
|
||||
|
||||
section.case { margin-top: 52px; }
|
||||
.case-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 10px 14px; margin-bottom: 4px; }
|
||||
.case-eyebrow { font-family: -apple-system,'Segoe UI',sans-serif; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; margin: 0; }
|
||||
h2 { font-size: 26px; margin: 0; font-weight: 700; }
|
||||
.pill {
|
||||
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 11.5px; font-weight: 600;
|
||||
padding: 2.5px 10px; border-radius: 999px; letter-spacing: .04em;
|
||||
border: 1px solid var(--line); color: var(--ink-2); background: var(--surface-2);
|
||||
}
|
||||
.pill.tag { color: var(--surface); border: none; }
|
||||
.meta-line { font-family: -apple-system,'Segoe UI',sans-serif; font-size: 13px; color: var(--ink-3); margin: 2px 0 18px; }
|
||||
|
||||
.case-grid { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(280px, 1fr); gap: 26px; align-items: start; }
|
||||
@media (max-width: 900px) { .case-grid { grid-template-columns: 1fr; } }
|
||||
|
||||
.netbox { border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); overflow: hidden; }
|
||||
.netbox svg { display: block; width: 100%; height: auto; }
|
||||
.netfoot { font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12px; color: var(--ink-3); padding: 8px 12px; border-top: 1px solid var(--line); }
|
||||
|
||||
.panel { display: flex; flex-direction: column; gap: 18px; }
|
||||
.panel h3 {
|
||||
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 11px; letter-spacing: .12em;
|
||||
text-transform: uppercase; color: var(--ink-3); margin: 0 0 8px; font-weight: 600;
|
||||
}
|
||||
.scorebar { display: grid; grid-template-columns: 74px 1fr 44px; align-items: center; gap: 10px; margin-bottom: 7px;
|
||||
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12.5px; }
|
||||
.scorebar .nm { color: var(--ink-2); }
|
||||
.scorebar .val { font-variant-numeric: tabular-nums; text-align: right; color: var(--ink); }
|
||||
.track { position: relative; height: 10px; background: var(--surface-2); border-radius: 4px; border: 1px solid var(--line); }
|
||||
.fill { position: absolute; inset: 0 auto 0 0; border-radius: 4px 3px 3px 4px; background: var(--bar); opacity: .55; }
|
||||
.fill.lead { opacity: 1; }
|
||||
.thresh { position: absolute; top: -3px; bottom: -3px; left: 85%; width: 0; border-left: 2px dashed var(--ink-3); }
|
||||
|
||||
table.mx { border-collapse: collapse; width: 100%; font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12.5px; }
|
||||
table.mx th { text-align: left; font-weight: 600; color: var(--ink-3); font-size: 11px; letter-spacing: .06em; text-transform: uppercase; padding: 8px 0 4px; }
|
||||
table.mx td { padding: 3.5px 0; border-top: 1px solid var(--line); color: var(--ink-2); }
|
||||
table.mx td.num { font-variant-numeric: tabular-nums; text-align: right; color: var(--ink); white-space: nowrap; }
|
||||
table.mx td.num.hot { font-weight: 700; }
|
||||
|
||||
.reading { max-width: 72ch; margin-top: 18px; font-size: 15.5px; color: var(--ink-2); }
|
||||
.reading strong { color: var(--ink); }
|
||||
|
||||
.tooltip {
|
||||
position: fixed; pointer-events: none; z-index: 20; display: none;
|
||||
background: var(--ink); color: var(--surface);
|
||||
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12px; line-height: 1.45;
|
||||
padding: 8px 11px; border-radius: 7px; max-width: 260px; box-shadow: 0 4px 14px rgba(0,0,0,.25);
|
||||
}
|
||||
.tooltip .t-name { font-weight: 700; }
|
||||
.tooltip .t-dim { opacity: .75; }
|
||||
|
||||
footer.page { margin-top: 60px; border-top: 1px solid var(--line); padding-top: 16px;
|
||||
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12.5px; color: var(--ink-3); max-width: 78ch; }
|
||||
svg .node { cursor: pointer; }
|
||||
#themeToggle {
|
||||
position: fixed; top: 14px; right: 14px; z-index: 30;
|
||||
font-family: -apple-system,'Segoe UI',sans-serif; font-size: 12px; padding: 6px 12px;
|
||||
border-radius: 999px; border: 1px solid var(--line); background: var(--surface-2);
|
||||
color: var(--ink-2); cursor: pointer;
|
||||
}
|
||||
#themeToggle:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="wrap">
|
||||
<header class="page">
|
||||
<p class="eyebrow" id="topline">Smart-Guide · Multiplier detection</p>
|
||||
<h1>Four researchers, drawn as the networks that scored them</h1>
|
||||
<p class="lede">
|
||||
Each figure shows one person (ringed) and their strongest co-authors, with every
|
||||
collaboration the corpus records <em>among</em> those co-authors. The shape is the
|
||||
metric: spokes that don't touch are brokered structural holes; a dense mesh is a
|
||||
tight community; green marks the juniors a mentor brought up; orange marks a
|
||||
company link on the works shared with that person. Hover any node for its details.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div class="legend" id="legend">
|
||||
<span class="li"><span class="dot ego" style="background:var(--ego)"></span>the person (ego)</span>
|
||||
<span class="li"><span class="dot" style="background:var(--cohort)"></span>cohort co-author</span>
|
||||
<span class="li"><span class="dot" style="background:var(--mentee)"></span>their mentee (junior at first joint paper)</span>
|
||||
<span class="li"><span class="dot" style="background:var(--industry)"></span>company link on works shared with the ego</span>
|
||||
<span class="li"><span class="dot" style="background:var(--external)"></span>external academic</span>
|
||||
<span class="li"><span class="edge-sample"></span>collaboration (width = decayed strength)</span>
|
||||
<span class="li"><span class="edge-sample dashed"></span>mostly cross-institution</span>
|
||||
<span class="li">node size = active years</span>
|
||||
</div>
|
||||
|
||||
<div id="cases"></div>
|
||||
|
||||
<footer class="page">
|
||||
Data: OpenAlex works of the institution cohort (works ≤ 50 authors enter the graph;
|
||||
edge strength decays 0.8/year), read from the <code>multiplicators_v1</code> and
|
||||
<code>multiplicator_networks_v1</code> indices. Networks show each ego's strongest
|
||||
co-authors — totals are given per figure. Scores are percentile-normalized within
|
||||
career buckets; tag threshold 0.85. Config <span id="cfg"></span>, computed
|
||||
<span id="ts"></span>. Mentee marking uses the seniority-gap rule and is restricted
|
||||
to cohort members; external co-authors' histories are truncated to shared works, so
|
||||
their node size is a lower bound. An orange node means a company affiliation appeared
|
||||
on a work shared with the ego — the company is named in the tooltip.
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<div class="tooltip" id="tip"></div>
|
||||
<button id="themeToggle" aria-label="Toggle color theme">theme</button>
|
||||
|
||||
<script>
|
||||
const DATA = __DATA__;
|
||||
|
||||
const ROLE = { ego:'--ego', cohort:'--cohort', mentee:'--mentee', industry:'--industry', external:'--external' };
|
||||
const ORDER = ['bridger','mentor','amplifier','example'];
|
||||
const EYEBROW = {
|
||||
bridger: ['Case 1 — the bridger archetype', '--cohort'],
|
||||
mentor: ['Case 2 — the mentor archetype', '--mentee'],
|
||||
amplifier:['Case 3 — the amplifier archetype', '--industry'],
|
||||
example: ['Case 4 — a strong profile below the tag line', '--ego'],
|
||||
};
|
||||
const ROLE_LABEL = {
|
||||
ego: 'This case’s subject',
|
||||
cohort: 'Cohort co-author',
|
||||
mentee: 'Mentee — junior at first joint paper',
|
||||
industry: 'Company link on shared works',
|
||||
external: 'External academic',
|
||||
};
|
||||
|
||||
const fmt = (v, d=2) => v == null ? '—' : (+v).toFixed(d);
|
||||
const pct = v => v == null ? '—' : Math.round(v*100) + '%';
|
||||
|
||||
function readingFor(kind, r, d) {
|
||||
const p = r.percentiles || {};
|
||||
if (kind === 'bridger') return `
|
||||
<strong>${r.display_name}</strong> holds the cohort's highest bridger score
|
||||
(<strong>${fmt(r.sub_scores.bridger,3)}</strong>). The picture explains it: the
|
||||
${d.total_coauthors} co-authors split into groups that barely touch except through
|
||||
the ego — brokerage ${fmt(r.brokerage,2)} (${pct(p.brokerage)} of the career
|
||||
bucket), ${pct(r.cross_institution_share)} of collaboration weight crosses
|
||||
institutions (dashed edges), and betweenness sits at the ${pct(p.betweenness)}
|
||||
percentile. Where the mentor's figure below is one dense mesh, this one is spokes
|
||||
and gaps — the gaps <em>are</em> the structural holes.`;
|
||||
if (kind === 'mentor') return `
|
||||
<strong>${r.display_name}</strong> tops the mentor ranking
|
||||
(<strong>${fmt(r.sub_scores.mentor,3)}</strong>) with ${r.juniors_mentored} cohort
|
||||
co-authors who were Early-career at their first joint paper while the ego was
|
||||
already Established — the green nodes — plus ${r.last_author_with_junior_first}
|
||||
papers in the classic supervision configuration (ego last author, a junior first).
|
||||
The mesh is dense: this is one connected group, the opposite structure of the
|
||||
bridger above. Only the ${d.shown} strongest ties of ${d.total_coauthors} are drawn.`;
|
||||
if (kind === 'amplifier') return `
|
||||
<strong>${r.display_name}</strong> tops the amplifier ranking
|
||||
(<strong>${fmt(r.sub_scores.amplifier,3)}</strong>) on converging independent
|
||||
channels: ${r.patent_count} high-confidence patent${r.patent_count===1?'':'s'},
|
||||
${r.cordis_eu_projects} EU project${r.cordis_eu_projects===1?'':'s'} via DOI
|
||||
overlap, ${r.news_mentions} press mention${r.news_mentions===1?'':'s'}, and a
|
||||
shrunk industry co-authorship share of ${fmt(r.industry_coauthor_share_shrunk,2)}
|
||||
(${pct(p.industry_coauthor_share_shrunk)} of the bucket). With
|
||||
${d.total_coauthors.toLocaleString('en')} total co-authors only the strongest
|
||||
${d.shown} are drawn — orange nodes carry a company affiliation on the shared work.`;
|
||||
const best = Math.max(...Object.values(r.sub_scores));
|
||||
const bestName = Object.entries(r.sub_scores).sort((a,b)=>b[1]-a[1])[0][0];
|
||||
const gated = best >= 0.85;
|
||||
return `
|
||||
<strong>${r.display_name}</strong> is the system's honest edge case: the
|
||||
highest-scoring person who still carries <strong>no tag</strong>. The ${bestName}
|
||||
sub-score reaches ${fmt(best,3)} ${gated
|
||||
? `— <em>above</em> the 0.85 line. The tag is withheld by the
|
||||
<code>min_active_years</code> guard: ${r.active_years} active
|
||||
year${r.active_years===1?'':'s'} is too thin a history to rank on, and a
|
||||
high score on one year is the signature of a <em>split</em> OpenAlex profile
|
||||
— a fragment of someone's record carrying a share of their patents, press or
|
||||
industry ties. The guard catches what <code>suspicious_profile</code> cannot:
|
||||
that flag detects merged identities, not split ones.`
|
||||
: `— just under the 0.85 line, on ${r.active_years} active
|
||||
year${r.active_years===1?'':'s'}. Thresholds are meant to surface the top of
|
||||
each bucket, and this profile sits one weight-tune away from either side.`}
|
||||
Either way it is the case coaches should see: ${d.total_coauthors} co-authors,
|
||||
brokerage ${fmt(r.brokerage,2)} (${pct(p.brokerage)} of the bucket),
|
||||
${pct(r.cross_institution_share)} cross-institution weight — a real profile that
|
||||
the ranking deliberately holds back.`;
|
||||
}
|
||||
|
||||
function svgNet(d) {
|
||||
const W = 760, H = 560, ns = 'http://www.w3.org/2000/svg';
|
||||
const svg = document.createElementNS(ns, 'svg');
|
||||
svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
|
||||
svg.setAttribute('role', 'img');
|
||||
svg.setAttribute('aria-label', `Co-author network of ${d.score_row.display_name}`);
|
||||
const byId = {};
|
||||
d.nodes.forEach(n => byId[n.id] = n);
|
||||
const ego = d.nodes[0];
|
||||
const wmax = Math.max(...d.edges.map(e => e.w), 0.01);
|
||||
|
||||
const eg = document.createElementNS(ns, 'g');
|
||||
d.edges.forEach(e => {
|
||||
const a = byId[e.a], b = byId[e.b];
|
||||
if (!a || !b) return;
|
||||
const ln = document.createElementNS(ns, 'line');
|
||||
ln.setAttribute('x1', a.x); ln.setAttribute('y1', a.y);
|
||||
ln.setAttribute('x2', b.x); ln.setAttribute('y2', b.y);
|
||||
const touchesEgo = (e.a === ego.id || e.b === ego.id);
|
||||
ln.setAttribute('stroke', 'currentColor');
|
||||
ln.setAttribute('stroke-opacity', touchesEgo ? 0.42 : 0.16);
|
||||
ln.setAttribute('stroke-width', Math.max(0.6, Math.min(4.5, 2.8*Math.sqrt(e.w/wmax))));
|
||||
if (e.cross) ln.setAttribute('stroke-dasharray', '4 3');
|
||||
eg.appendChild(ln);
|
||||
});
|
||||
eg.setAttribute('color', 'var(--ink-3)');
|
||||
svg.appendChild(eg);
|
||||
|
||||
const edgeToEgo = {};
|
||||
d.edges.forEach(e => {
|
||||
if (e.a === ego.id) edgeToEgo[e.b] = e;
|
||||
if (e.b === ego.id) edgeToEgo[e.a] = e;
|
||||
});
|
||||
|
||||
const ng = document.createElementNS(ns, 'g');
|
||||
d.nodes.forEach(n => {
|
||||
const c = document.createElementNS(ns, 'circle');
|
||||
const isEgo = n.role === 'ego';
|
||||
const r = isEgo ? 13 : Math.max(4, Math.min(9, 3 + 1.1*Math.sqrt(n.active_years)));
|
||||
c.setAttribute('class', 'node');
|
||||
c.setAttribute('cx', n.x); c.setAttribute('cy', n.y); c.setAttribute('r', r);
|
||||
c.setAttribute('fill', `var(${ROLE[n.role]})`);
|
||||
c.setAttribute('stroke', isEgo ? 'var(--ink)' : 'var(--node-stroke)');
|
||||
c.setAttribute('stroke-width', isEgo ? 2.5 : 1);
|
||||
c.addEventListener('pointerenter', ev => {
|
||||
const e = edgeToEgo[n.id];
|
||||
showTip(ev, `
|
||||
<div class="t-name">${n.name || n.id}</div>
|
||||
<div>${ROLE_LABEL[n.role] || n.role}</div>
|
||||
${n.inst ? `<div class="t-dim">${n.inst}</div>` : ''}
|
||||
${n.company_insts ? `<div>Industry link: ${n.company_insts.join(', ')}</div>` : ''}
|
||||
<div class="t-dim">${n.active_years} active year${n.active_years===1?'':'s'}${
|
||||
e ? ` · tie strength ${e.w.toFixed(2)} · ${e.n} joint work${e.n===1?'':'s'} · since ${e.y0}` : ''}</div>`);
|
||||
});
|
||||
c.addEventListener('pointermove', moveTip);
|
||||
c.addEventListener('pointerleave', hideTip);
|
||||
ng.appendChild(c);
|
||||
});
|
||||
svg.appendChild(ng);
|
||||
|
||||
const label = document.createElementNS(ns, 'text');
|
||||
label.setAttribute('x', ego.x); label.setAttribute('y', ego.y + 30);
|
||||
label.setAttribute('text-anchor', 'middle');
|
||||
label.setAttribute('style', 'font-family:-apple-system,Segoe UI,sans-serif;font-size:12.5px;font-weight:700;fill:var(--ink);paint-order:stroke;stroke:var(--surface);stroke-width:3px;');
|
||||
label.textContent = ego.name;
|
||||
svg.appendChild(label);
|
||||
return svg;
|
||||
}
|
||||
|
||||
const tip = document.getElementById('tip');
|
||||
function showTip(ev, html) { tip.innerHTML = html; tip.style.display = 'block'; moveTip(ev); }
|
||||
function moveTip(ev) {
|
||||
const pad = 14;
|
||||
let x = ev.clientX + pad, y = ev.clientY + pad;
|
||||
const r = tip.getBoundingClientRect();
|
||||
if (x + r.width > innerWidth - 8) x = ev.clientX - r.width - pad;
|
||||
if (y + r.height > innerHeight - 8) y = ev.clientY - r.height - pad;
|
||||
tip.style.left = x + 'px'; tip.style.top = y + 'px';
|
||||
}
|
||||
function hideTip() { tip.style.display = 'none'; }
|
||||
|
||||
function metricRows(r) {
|
||||
const p = r.percentiles || {};
|
||||
const groups = [
|
||||
['Bridging', [
|
||||
['Betweenness', fmt(r.betweenness, r.betweenness && r.betweenness < 0.01 ? 4 : 3), p.betweenness],
|
||||
['Brokerage (1−constraint)', fmt(r.brokerage), p.brokerage],
|
||||
['Field entropy', fmt(r.field_entropy), p.field_entropy],
|
||||
['Cross-institution share', fmt(r.cross_institution_share), p.cross_institution_share],
|
||||
]],
|
||||
['Mentoring', [
|
||||
['Juniors mentored', r.juniors_mentored, p.juniors_mentored],
|
||||
['Last-author + junior first', r.last_author_with_junior_first, p.last_author_with_junior_first],
|
||||
['Mentoring rate', fmt(r.mentoring_rate), p.mentoring_rate],
|
||||
]],
|
||||
['Amplification', [
|
||||
['Industry share (shrunk)', fmt(r.industry_coauthor_share_shrunk), p.industry_coauthor_share_shrunk],
|
||||
['Patents (high-confidence)', r.patent_count, p.patent_count],
|
||||
['EU projects (DOI join)', r.cordis_eu_projects, p.cordis_eu_projects],
|
||||
['News mentions', r.news_mentions, p.news_mentions],
|
||||
]],
|
||||
];
|
||||
let html = '<table class="mx"><tr><th>Metric</th><th style="text-align:right">Raw</th><th style="text-align:right">Bucket pctl</th></tr>';
|
||||
for (const [g, rows] of groups) {
|
||||
html += `<tr><td colspan="3" style="border-top:none;padding-top:10px;font-weight:600;color:var(--ink-3);font-size:11px;letter-spacing:.06em;text-transform:uppercase">${g}</td></tr>`;
|
||||
for (const [nm, raw, pc] of rows) {
|
||||
const hot = pc != null && pc >= 0.9;
|
||||
html += `<tr><td>${nm}</td><td class="num">${raw == null ? '—' : raw}</td><td class="num${hot?' hot':''}">${pc==null?'—':pct(pc)}</td></tr>`;
|
||||
}
|
||||
}
|
||||
return html + '</table>';
|
||||
}
|
||||
|
||||
const container = document.getElementById('cases');
|
||||
let firstCase = null;
|
||||
for (const kind of ORDER) {
|
||||
const key = Object.keys(DATA).find(k => DATA[k].kind === kind);
|
||||
if (!key) continue;
|
||||
const d = DATA[key], r = d.score_row;
|
||||
if (!firstCase) firstCase = d;
|
||||
const [eyebrow, hue] = EYEBROW[kind];
|
||||
const lead = Object.entries(r.sub_scores).sort((a,b)=>b[1]-a[1])[0][0];
|
||||
|
||||
const sec = document.createElement('section');
|
||||
sec.className = 'case';
|
||||
sec.innerHTML = `
|
||||
<p class="case-eyebrow" style="color:var(${hue})">${eyebrow}</p>
|
||||
<div class="case-head">
|
||||
<h2>${r.display_name}</h2>
|
||||
${(r.tags||[]).map(t => `<span class="pill tag" style="background:var(${hue})">${t}</span>`).join('')}
|
||||
${(r.tags||[]).length === 0 ? '<span class="pill">no tag</span>' : ''}
|
||||
<span class="pill">${r.career_bucket} · ${r.active_years} active years</span>
|
||||
${r.suspicious_profile ? '<span class="pill">low-confidence profile</span>' : ''}
|
||||
</div>
|
||||
<p class="meta-line">${r.n_works} works · ${d.total_coauthors.toLocaleString('en')} co-authors
|
||||
(strongest ${d.shown} drawn) · author ${r.author_id}</p>
|
||||
<div class="case-grid">
|
||||
<div class="netbox">
|
||||
<div class="svg-slot"></div>
|
||||
<div class="netfoot">Edges among the drawn co-authors are the corpus's actual
|
||||
collaborations — their density (or absence) is what constraint/brokerage measures.</div>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<div>
|
||||
<h3>Sub-scores <span style="letter-spacing:0;text-transform:none">(dashed line = 0.85 tag threshold)</span></h3>
|
||||
${['bridger','mentor','amplifier'].map(s => `
|
||||
<div class="scorebar">
|
||||
<span class="nm">${s}</span>
|
||||
<span class="track"><span class="fill${s===lead?' lead':''}" style="width:${(r.sub_scores[s]*100).toFixed(1)}%"></span><span class="thresh"></span></span>
|
||||
<span class="val">${fmt(r.sub_scores[s],3)}</span>
|
||||
</div>`).join('')}
|
||||
</div>
|
||||
<div>${metricRows(r)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="reading">${readingFor(kind, r, d)}</p>`;
|
||||
sec.querySelector('.svg-slot').appendChild(svgNet(d));
|
||||
container.appendChild(sec);
|
||||
}
|
||||
if (firstCase) {
|
||||
document.getElementById('cfg').textContent = firstCase.config_hash || '—';
|
||||
document.getElementById('ts').textContent = firstCase.computed_at || '—';
|
||||
}
|
||||
|
||||
document.getElementById('themeToggle').addEventListener('click', () => {
|
||||
const root = document.documentElement;
|
||||
const dark = root.getAttribute('data-theme') === 'dark' ||
|
||||
(!root.getAttribute('data-theme') && matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
root.setAttribute('data-theme', dark ? 'light' : 'dark');
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,7 @@
|
||||
httpx>=0.27
|
||||
python-dotenv>=1.0
|
||||
polars>=1.0
|
||||
pyyaml>=6.0
|
||||
|
||||
# test-only (never in the service image):
|
||||
# pip install pytest networkx
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
scoring.py — normalization, sub-scores and tags (M1, Stage F).
|
||||
|
||||
Procedure (per plan §3/§6):
|
||||
1. Bucket every focal author by career stage from `active_years`
|
||||
(Early/Emerging/Established/Senior — thresholds mirror inse/persons/logic.py).
|
||||
2. Percentile-rank every raw metric WITHIN its bucket, so early-career people
|
||||
compete against early-career people. The M0 spike found median active_years = 4:
|
||||
half the cohort is "Early", and institution-wide percentiles would simply rank
|
||||
seniority.
|
||||
3. Sub-scores = weighted mean of the percentiles (weights from multiplicators.yaml).
|
||||
4. Tag anyone >= tags.threshold on a sub-score (multiple tags allowed).
|
||||
|
||||
Raw values, percentiles, and sub-scores are ALL persisted — coaches and calibration
|
||||
both need the intermediates. None/NaN raw values are excluded from percentile ranking
|
||||
and contribute 0 to the weighted mean (weight is redistributed over present metrics).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
def load_config(path: str) -> dict[str, Any]:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
config = yaml.safe_load(f)
|
||||
config["_config_hash"] = hashlib.sha256(
|
||||
json.dumps(config, sort_keys=True, default=str).encode()
|
||||
).hexdigest()[:12]
|
||||
return config
|
||||
|
||||
|
||||
def career_bucket(active_years: int, thresholds: list[int], names: list[str]) -> str:
|
||||
"""Bucket by active_years. thresholds=[4,9,14] -> Early/Emerging/Established/Senior."""
|
||||
for threshold, name in zip(thresholds, names):
|
||||
if active_years <= threshold:
|
||||
return name
|
||||
return names[len(thresholds)]
|
||||
|
||||
|
||||
def percentile_ranks(values: dict[str, float | None]) -> dict[str, float]:
|
||||
"""Mean-rank percentiles in (0, 1] over the non-None values.
|
||||
|
||||
Ties share their mean rank, so a metric where most values are 0 (e.g.
|
||||
juniors_mentored for Early authors) does not hand everyone a high percentile.
|
||||
"""
|
||||
present = [(aid, v) for aid, v in values.items() if v is not None]
|
||||
if not present:
|
||||
return {}
|
||||
present.sort(key=lambda kv: kv[1])
|
||||
n = len(present)
|
||||
ranks: dict[str, float] = {}
|
||||
i = 0
|
||||
while i < n:
|
||||
j = i
|
||||
while j + 1 < n and present[j + 1][1] == present[i][1]:
|
||||
j += 1
|
||||
mean_rank = (i + j) / 2 + 1 # 1-based mean rank of the tie group
|
||||
for k in range(i, j + 1):
|
||||
ranks[present[k][0]] = mean_rank / n
|
||||
i = j + 1
|
||||
return ranks
|
||||
|
||||
|
||||
def score_rows(
|
||||
metric_rows: dict[str, dict[str, Any]], config: dict[str, Any]
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Turn raw metric rows into scored, tagged, bucket-normalized output rows."""
|
||||
career_cfg = config["career"]
|
||||
weights: dict[str, dict[str, float]] = config["weights"]
|
||||
tag_threshold: float = config["tags"]["threshold"]
|
||||
min_active_years: int = config["tags"].get("min_active_years", 0)
|
||||
|
||||
# 1. bucket assignment
|
||||
buckets: dict[str, list[str]] = {}
|
||||
for aid, row in metric_rows.items():
|
||||
bucket = career_bucket(
|
||||
row["active_years"], career_cfg["buckets"], career_cfg["bucket_names"]
|
||||
)
|
||||
row["career_bucket"] = bucket
|
||||
buckets.setdefault(bucket, []).append(aid)
|
||||
|
||||
# 2. within-bucket percentiles for every metric used by any sub-score
|
||||
metric_names = sorted({m for w in weights.values() for m in w})
|
||||
percentiles: dict[str, dict[str, float]] = {aid: {} for aid in metric_rows}
|
||||
for bucket_members in buckets.values():
|
||||
for metric in metric_names:
|
||||
values = {
|
||||
aid: metric_rows[aid].get(metric)
|
||||
for aid in bucket_members
|
||||
if isinstance(metric_rows[aid].get(metric), (int, float))
|
||||
}
|
||||
for aid, pctl in percentile_ranks(values).items():
|
||||
percentiles[aid][metric] = pctl
|
||||
|
||||
# 3+4. weighted sub-scores and tags
|
||||
out: list[dict[str, Any]] = []
|
||||
for aid, row in metric_rows.items():
|
||||
sub_scores: dict[str, float] = {}
|
||||
for sub, metric_weights in weights.items():
|
||||
total_weight = 0.0
|
||||
acc = 0.0
|
||||
for metric, weight in metric_weights.items():
|
||||
pctl = percentiles[aid].get(metric)
|
||||
if pctl is not None:
|
||||
acc += weight * pctl
|
||||
total_weight += weight
|
||||
sub_scores[sub] = round(acc / total_weight, 4) if total_weight > 0 else 0.0
|
||||
|
||||
tags = (
|
||||
[s for s, v in sub_scores.items() if v >= tag_threshold]
|
||||
if row["active_years"] >= min_active_years
|
||||
else []
|
||||
)
|
||||
|
||||
out.append(
|
||||
{
|
||||
**{k: v for k, v in row.items() if k != "junior_ids"},
|
||||
"percentiles": {
|
||||
m: round(p, 4) for m, p in percentiles[aid].items()
|
||||
},
|
||||
"sub_scores": sub_scores,
|
||||
"tags": tags,
|
||||
"max_sub_score": max(sub_scores.values()) if sub_scores else 0.0,
|
||||
"evidence": {"junior_ids": row.get("junior_ids", [])[:25]},
|
||||
"config_hash": config["_config_hash"],
|
||||
}
|
||||
)
|
||||
|
||||
out.sort(key=lambda r: r["max_sub_score"], reverse=True)
|
||||
return out
|
||||
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
signals.py — M3 amplifier signal joins: patents, news, EU CORDIS projects.
|
||||
|
||||
Link quality differs per source and dictates how each is used (plan §4):
|
||||
|
||||
PATENTS org_patents.matched_authors carries real OpenAlex author IDs with a
|
||||
doc-level match_type. Only {institution, both} count toward the score;
|
||||
name-only matches are kept as a separate evidence count.
|
||||
NEWS aktuell_postproc holds LLM-extracted person names. Matching is
|
||||
normalized-exact (casefold + diacritic fold): "René Müller" == "rene
|
||||
muller". A normalized name shared by MULTIPLE cohort authors is skipped
|
||||
entirely (precision over recall) — crediting the wrong person is worse
|
||||
than missing a mention. Low YAML weight by design.
|
||||
CORDIS DOI-overlap join (no name matching): the author's work DOIs from the
|
||||
extract intersected with cordis_eu_*_publications DOIs -> distinct
|
||||
project IDs per author.
|
||||
|
||||
All functions return plain dict[author_short_id, count] and are independent of the
|
||||
graph/scoring modules.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import unicodedata
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from extract import INSE_KEY, INSE_URL, es_search
|
||||
|
||||
PAGE_SIZE = 1000
|
||||
DOI_BATCH = 500
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Patents — org_patents (already author-ID-linked by index_org_patents.py)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def patent_counts(
|
||||
client: httpx.Client,
|
||||
institution_short_id: str,
|
||||
scored_match_types: tuple[str, ...] = ("institution", "both"),
|
||||
) -> tuple[dict[str, int], dict[str, int]]:
|
||||
"""Per-author patent counts from org_patents.
|
||||
|
||||
Returns (scored, name_only): scored counts only docs whose match_type is in
|
||||
`scored_match_types`; name_only is kept as evidence and never enters the score.
|
||||
"""
|
||||
scored: dict[str, int] = defaultdict(int)
|
||||
name_only: dict[str, int] = defaultdict(int)
|
||||
search_after = None
|
||||
while True:
|
||||
body: dict[str, Any] = {
|
||||
"size": PAGE_SIZE,
|
||||
"_source": ["match_type", "matched_authors.openalex_author_id"],
|
||||
"query": {"term": {"institution_id": institution_short_id}},
|
||||
"sort": [{"patent_id": {"order": "asc"}}],
|
||||
}
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
result = es_search(client, INSE_URL, INSE_KEY, "org_patents", body)
|
||||
hits = result["hits"]["hits"]
|
||||
if not hits:
|
||||
break
|
||||
for hit in hits:
|
||||
src = hit["_source"]
|
||||
target = scored if src.get("match_type") in scored_match_types else name_only
|
||||
for author in src.get("matched_authors") or []:
|
||||
aid = author.get("openalex_author_id")
|
||||
if aid:
|
||||
target[aid] += 1
|
||||
search_after = hits[-1]["sort"]
|
||||
return dict(scored), dict(name_only)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# News — aktuell_postproc (LLM-extracted names, normalized-exact match)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def normalize_name(name: str) -> str:
|
||||
"""casefold + strip diacritics + collapse whitespace ("René Müller" -> "rene muller")."""
|
||||
decomposed = unicodedata.normalize("NFKD", name)
|
||||
stripped = "".join(c for c in decomposed if not unicodedata.combining(c))
|
||||
return " ".join(stripped.casefold().split())
|
||||
|
||||
|
||||
def news_mention_counts(
|
||||
client: httpx.Client,
|
||||
display_names: dict[str, str],
|
||||
require_relevant: bool = True,
|
||||
) -> tuple[dict[str, int], int]:
|
||||
"""Per-author news mention counts.
|
||||
|
||||
display_names: author_short_id -> display_name for the whole cohort.
|
||||
Returns (counts, ambiguous_names_skipped). Names that normalize identically for
|
||||
more than one cohort author are skipped entirely.
|
||||
"""
|
||||
by_norm: dict[str, list[str]] = defaultdict(list)
|
||||
for aid, name in display_names.items():
|
||||
if name:
|
||||
by_norm[normalize_name(name)].append(aid)
|
||||
ambiguous = {norm for norm, aids in by_norm.items() if len(aids) > 1}
|
||||
|
||||
counts: dict[str, int] = defaultdict(int)
|
||||
search_after = None
|
||||
while True:
|
||||
body: dict[str, Any] = {
|
||||
"size": PAGE_SIZE,
|
||||
"_source": ["authors", "relevant"],
|
||||
"query": {"exists": {"field": "authors"}},
|
||||
"sort": [{"news_id.keyword": {"order": "asc"}}],
|
||||
}
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
result = es_search(client, INSE_URL, INSE_KEY, "aktuell_postproc", body)
|
||||
hits = result["hits"]["hits"]
|
||||
if not hits:
|
||||
break
|
||||
for hit in hits:
|
||||
src = hit["_source"]
|
||||
if require_relevant and not src.get("relevant"):
|
||||
continue
|
||||
for name in src.get("authors") or []:
|
||||
norm = normalize_name(name)
|
||||
if norm in ambiguous:
|
||||
continue
|
||||
aids = by_norm.get(norm)
|
||||
if aids:
|
||||
counts[aids[0]] += 1
|
||||
search_after = hits[-1]["sort"]
|
||||
return dict(counts), len(ambiguous)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# EU CORDIS — DOI-overlap join
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def normalize_doi(doi: str | None) -> str | None:
|
||||
if not doi:
|
||||
return None
|
||||
doi = doi.strip().casefold()
|
||||
for prefix in ("https://doi.org/", "http://doi.org/", "doi.org/", "doi:"):
|
||||
if doi.startswith(prefix):
|
||||
doi = doi[len(prefix):]
|
||||
return doi or None
|
||||
|
||||
|
||||
def cordis_project_counts(
|
||||
client: httpx.Client,
|
||||
dois_by_author: dict[str, set[str]],
|
||||
) -> dict[str, int]:
|
||||
"""Distinct CORDIS project count per author via DOI overlap.
|
||||
|
||||
dois_by_author values must already be normalized (normalize_doi).
|
||||
"""
|
||||
all_dois = sorted({d for dois in dois_by_author.values() for d in dois})
|
||||
projects_by_doi: dict[str, set[str]] = defaultdict(set)
|
||||
|
||||
for start in range(0, len(all_dois), DOI_BATCH):
|
||||
batch = all_dois[start : start + DOI_BATCH]
|
||||
# NOT a terms query: 21% of CORDIS DOIs contain uppercase, and `terms` on a
|
||||
# keyword field is case-sensitive. Per-term case_insensitive matching instead.
|
||||
result = es_search(
|
||||
client, INSE_URL, INSE_KEY, "cordis_eu_*_publications",
|
||||
{
|
||||
"size": len(batch) * 4, # a DOI can appear in several frameworks
|
||||
"_source": ["doi", "projectID"],
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"doi": {"value": d, "case_insensitive": True}}}
|
||||
for d in batch
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
for hit in result["hits"]["hits"]:
|
||||
src = hit["_source"]
|
||||
doi = normalize_doi(src.get("doi"))
|
||||
project = src.get("projectID")
|
||||
if doi and project is not None:
|
||||
projects_by_doi[doi].add(str(project))
|
||||
|
||||
counts: dict[str, int] = {}
|
||||
for aid, dois in dois_by_author.items():
|
||||
projects: set[str] = set()
|
||||
for doi in dois:
|
||||
projects |= projects_by_doi.get(doi, set())
|
||||
if projects:
|
||||
counts[aid] = len(projects)
|
||||
return counts
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Orchestration
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def collect_signals(
|
||||
institution_short_id: str,
|
||||
display_names: dict[str, str],
|
||||
dois_by_author: dict[str, set[str]],
|
||||
scored_match_types: tuple[str, ...] = ("institution", "both"),
|
||||
news_require_relevant: bool = True,
|
||||
) -> dict[str, dict[str, int]]:
|
||||
"""All signal joins. Returns per-metric dicts keyed by author_short_id."""
|
||||
with httpx.Client() as client:
|
||||
patents_scored, patents_name_only = patent_counts(
|
||||
client, institution_short_id, scored_match_types
|
||||
)
|
||||
news, ambiguous_skipped = news_mention_counts(
|
||||
client, display_names, require_relevant=news_require_relevant
|
||||
)
|
||||
cordis = cordis_project_counts(client, dois_by_author)
|
||||
print(
|
||||
f"Signals: patents scored for {len(patents_scored)} authors "
|
||||
f"(name-only evidence: {len(patents_name_only)}), "
|
||||
f"news mentions for {len(news)} (ambiguous names skipped: {ambiguous_skipped}), "
|
||||
f"CORDIS projects for {len(cordis)}"
|
||||
)
|
||||
return {
|
||||
"patent_count": patents_scored,
|
||||
"patent_count_name_only": patents_name_only,
|
||||
"news_mentions": news,
|
||||
"cordis_eu_projects": cordis,
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
spike_audit.py — M0 de-risking spike for the multiplicator-detection module.
|
||||
|
||||
Extracts the institution's OpenAlex author set (two-group union) and the FULL-authorship
|
||||
work set for those authors, caches both as gzipped JSONL, and prints an audit report that
|
||||
answers the six questions the rest of the pipeline is betting on:
|
||||
|
||||
1. Reproduction — author / work counts vs the known 4,921 / 183,661 for UDE.
|
||||
2. Field coverage — % of authorships with author_position / is_corresponding, and
|
||||
% of institutions with a non-null `type`. Decides whether the
|
||||
mentorship (last-author) and cross-sector signals are computable.
|
||||
3. Scale — authors-per-work histogram and distinct co-author pair counts at
|
||||
caps of 20 / 50 / 100. Picks max_authors_per_work; confirms the
|
||||
"pure Python / polars, no DuckDB" sizing bet.
|
||||
4. Quality — % of authors flagged has_suspicious_publication_years (merged
|
||||
profiles) and the active_years distribution.
|
||||
5. Permissions — can we create / bulk-write / delete on the INSE cluster, and does
|
||||
_delete_by_query 403 there as it does for org_patents?
|
||||
6. Signals — does org_patents carry matched_authors for this institution, and
|
||||
what is the match_type breakdown?
|
||||
|
||||
Unlike the seed (llm_evaluations/.../build_ude_author_work_set.py) this drops inner_hits
|
||||
and pulls every authorship (external co-authors + their institutions) — without that
|
||||
there is no bridging signal.
|
||||
|
||||
Usage:
|
||||
python service/scripts/multipliers/spike_audit.py --institution-id I62318514
|
||||
|
||||
Credentials are read from service/src/main/inse/.env (ELASTICSEARCH_* for the NES/OpenAlex
|
||||
cluster, ELASTICSEARCH_INSE_* for patents/news). Nothing is written to the real cluster
|
||||
unless --probe-writes is passed (it creates and deletes a throwaway index).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import gzip
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable, Iterator
|
||||
|
||||
import httpx
|
||||
import yaml
|
||||
from dotenv import load_dotenv
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
ENV_PATH = SCRIPT_DIR.parent.parent / "src" / "main" / "inse" / ".env"
|
||||
load_dotenv(dotenv_path=ENV_PATH)
|
||||
|
||||
# --- clusters -------------------------------------------------------------
|
||||
|
||||
NES_URL = (os.environ.get("ELASTICSEARCH_URL") or "").rstrip("/")
|
||||
NES_KEY = os.environ.get("ELASTICSEARCH_API_KEY") or ""
|
||||
INSE_URL = (os.environ.get("ELASTICSEARCH_INSE_URL") or "").rstrip("/")
|
||||
INSE_KEY = os.environ.get("ELASTICSEARCH_INSE_API_KEY") or ""
|
||||
|
||||
# --- extraction knobs (spike-only; the real build reads these from YAML) --
|
||||
|
||||
AFFILIATION_YEAR_GTE = 2025
|
||||
WORK_YEAR_GTE = 1950
|
||||
AUTHOR_PAGE_SIZE = 1000
|
||||
AUTHOR_BATCH_SIZE = 250
|
||||
WORK_PAGE_SIZE = 1000
|
||||
PAIR_CAPS = (20, 50, 100)
|
||||
REQUEST_TIMEOUT = 180.0
|
||||
PROBE_INDEX = "multiplicators_spike_probe"
|
||||
|
||||
|
||||
# ES helpers
|
||||
|
||||
|
||||
def _headers(api_key: str) -> dict[str, str]:
|
||||
return {
|
||||
"Authorization": f"ApiKey {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
|
||||
def es_request(
|
||||
client: httpx.Client,
|
||||
method: str,
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
path: str,
|
||||
body: dict[str, Any] | None = None,
|
||||
) -> httpx.Response:
|
||||
url = f"{base_url}/{path.lstrip('/')}"
|
||||
return client.request(
|
||||
method, url, headers=_headers(api_key), json=body, timeout=REQUEST_TIMEOUT
|
||||
)
|
||||
|
||||
|
||||
def es_search(
|
||||
client: httpx.Client, base_url: str, api_key: str, index: str, body: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
response = es_request(client, "POST", base_url, api_key, f"{index}/_search", body)
|
||||
if not response.is_success:
|
||||
raise RuntimeError(
|
||||
f"ES error {response.status_code} for {index}:\n{response.text[:1000]}"
|
||||
)
|
||||
return response.json()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Institution resolution (parameterised — no hardcoded UDE)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def resolve_institution(client: httpx.Client, institution_id: str) -> dict[str, Any]:
|
||||
"""Look up ror + display_name for --institution-id from openalex-institutions."""
|
||||
raw = institution_id.strip()
|
||||
short = raw.rsplit("/", 1)[-1]
|
||||
full = f"https://openalex.org/{short}"
|
||||
|
||||
result = es_search(
|
||||
client,
|
||||
NES_URL,
|
||||
NES_KEY,
|
||||
"openalex-institutions",
|
||||
{"size": 1, "query": {"term": {"id": full}}},
|
||||
)
|
||||
hits = result["hits"]["hits"]
|
||||
if not hits:
|
||||
raise SystemExit(f"Institution {full} not found in openalex-institutions.")
|
||||
|
||||
source = hits[0]["_source"]
|
||||
return {
|
||||
"id": full,
|
||||
"short_id": short,
|
||||
"ror": source.get("ror"),
|
||||
"display_name": source.get("display_name"),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Author queries (two-group union — group 2 recovers empty-last-known authors)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def recent_affiliation_filter(insts: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""Recent affiliation with ANY cohort institution (matched by id, ror as backup)."""
|
||||
ids = [i["id"] for i in insts]
|
||||
shoulds: list[dict[str, Any]] = [{"terms": {"affiliations.institution.id": ids}}]
|
||||
rors = [i["ror"] for i in insts if i.get("ror")]
|
||||
if rors:
|
||||
shoulds.append({"terms": {"affiliations.institution.ror": rors}})
|
||||
return {
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"bool": {"should": shoulds, "minimum_should_match": 1}},
|
||||
{"range": {"affiliations.years": {"gte": AFFILIATION_YEAR_GTE}}},
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def last_known_filter(insts: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""last_known_institutions membership in the cohort, matched by ID.
|
||||
|
||||
(The seed script matched the display_name string; ID terms are equivalent for a
|
||||
single institution and the only sane option for a multi-institution cohort.)"""
|
||||
return {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {
|
||||
"terms": {"last_known_institutions.id": [i["id"] for i in insts]}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def last_known_exists_filter() -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {"exists": {"field": "last_known_institutions.display_name"}},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
AUTHOR_SOURCE = [
|
||||
"id",
|
||||
"display_name",
|
||||
"orcid",
|
||||
"works_count",
|
||||
"cited_by_count",
|
||||
"last_known_institutions",
|
||||
"affiliations",
|
||||
]
|
||||
|
||||
|
||||
def author_query(query: dict[str, Any], search_after: Any) -> dict[str, Any]:
|
||||
body = {
|
||||
"size": AUTHOR_PAGE_SIZE,
|
||||
"track_total_hits": True,
|
||||
"_source": AUTHOR_SOURCE,
|
||||
"query": query,
|
||||
"sort": [{"id": {"order": "asc"}}],
|
||||
}
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
return body
|
||||
|
||||
|
||||
def collect_authors(
|
||||
client: httpx.Client, insts: list[dict[str, Any]]
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
groups = {
|
||||
"backend_compatible": {
|
||||
"bool": {
|
||||
"filter": [last_known_filter(insts), recent_affiliation_filter(insts)]
|
||||
}
|
||||
},
|
||||
"empty_last_known_recent": {
|
||||
"bool": {
|
||||
"filter": [recent_affiliation_filter(insts)],
|
||||
"must_not": [last_known_exists_filter()],
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
authors: dict[str, dict[str, Any]] = {}
|
||||
for group_name, query in groups.items():
|
||||
search_after = None
|
||||
total = None
|
||||
read = 0
|
||||
while True:
|
||||
result = es_search(
|
||||
client, NES_URL, NES_KEY, "openalex-authors",
|
||||
author_query(query, search_after),
|
||||
)
|
||||
hits = result["hits"]["hits"]
|
||||
if total is None:
|
||||
total = result["hits"]["total"]["value"]
|
||||
print(f" [{group_name}] expected {total}")
|
||||
if not hits:
|
||||
break
|
||||
for hit in hits:
|
||||
src = hit["_source"]
|
||||
aid = src.get("id")
|
||||
if not aid:
|
||||
continue
|
||||
if aid not in authors:
|
||||
authors[aid] = {
|
||||
"id": aid,
|
||||
"display_name": src.get("display_name"),
|
||||
"orcid": src.get("orcid"),
|
||||
"works_count": src.get("works_count"),
|
||||
"cited_by_count": src.get("cited_by_count"),
|
||||
"source_sets": [group_name],
|
||||
}
|
||||
elif group_name not in authors[aid]["source_sets"]:
|
||||
authors[aid]["source_sets"].append(group_name)
|
||||
read += 1
|
||||
search_after = hits[-1]["sort"]
|
||||
print(f" [{group_name}] read {read}/{total}")
|
||||
time.sleep(0.05)
|
||||
return authors
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Work queries — FULL authorships, no inner_hits
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
WORK_SOURCE = [
|
||||
"id",
|
||||
"doi",
|
||||
"publication_year",
|
||||
"type",
|
||||
"cited_by_count",
|
||||
"primary_topic.id",
|
||||
"primary_topic.display_name",
|
||||
"primary_topic.field.id",
|
||||
"primary_topic.field.display_name",
|
||||
"authorships.author.id",
|
||||
"authorships.author.display_name",
|
||||
"authorships.author_position",
|
||||
"authorships.is_corresponding",
|
||||
"authorships.institutions.id",
|
||||
"authorships.institutions.display_name",
|
||||
"authorships.institutions.type",
|
||||
"authorships.institutions.country_code",
|
||||
"authorships.institutions.lineage",
|
||||
]
|
||||
|
||||
|
||||
def works_batch_query(author_ids: list[str], search_after: Any) -> dict[str, Any]:
|
||||
body = {
|
||||
"size": WORK_PAGE_SIZE,
|
||||
"track_total_hits": True,
|
||||
"_source": WORK_SOURCE,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"publication_year": {"gte": WORK_YEAR_GTE}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"terms": {"authorships.author.id": author_ids}},
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
"sort": [{"id": {"order": "asc"}}],
|
||||
}
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
return body
|
||||
|
||||
|
||||
def collect_works(
|
||||
client: httpx.Client, author_ids: list[str]
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
works: dict[str, dict[str, Any]] = {}
|
||||
total_batches = (len(author_ids) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE
|
||||
for i in range(0, len(author_ids), AUTHOR_BATCH_SIZE):
|
||||
batch = author_ids[i : i + AUTHOR_BATCH_SIZE]
|
||||
batch_no = i // AUTHOR_BATCH_SIZE + 1
|
||||
search_after = None
|
||||
while True:
|
||||
result = es_search(
|
||||
client, NES_URL, NES_KEY, "openalex-works*",
|
||||
works_batch_query(batch, search_after),
|
||||
)
|
||||
hits = result["hits"]["hits"]
|
||||
if not hits:
|
||||
break
|
||||
for hit in hits:
|
||||
src = hit["_source"]
|
||||
wid = src.get("id")
|
||||
if wid and wid not in works:
|
||||
works[wid] = src
|
||||
search_after = hits[-1]["sort"]
|
||||
print(f" work batch {batch_no}/{total_batches}: unique works {len(works)}")
|
||||
time.sleep(0.05)
|
||||
return works
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Cache IO
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def write_jsonl_gz(path: Path, records: Iterable[dict[str, Any]]) -> None:
|
||||
with gzip.open(path, "wt", encoding="utf-8", newline="\n") as f:
|
||||
for record in records:
|
||||
f.write(json.dumps(record, ensure_ascii=True) + "\n")
|
||||
|
||||
|
||||
def read_jsonl_gz(path: Path) -> Iterator[dict[str, Any]]:
|
||||
with gzip.open(path, "rt", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line:
|
||||
yield json.loads(line)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Audit computations
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _percentile(sorted_vals: list[int], q: float) -> int:
|
||||
if not sorted_vals:
|
||||
return 0
|
||||
idx = min(len(sorted_vals) - 1, int(math.ceil(q * len(sorted_vals)) - 1))
|
||||
return sorted_vals[max(0, idx)]
|
||||
|
||||
|
||||
def audit_field_coverage(works: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
n_authorships = 0
|
||||
with_position = 0
|
||||
with_corresponding = 0
|
||||
n_institutions = 0
|
||||
with_inst_type = 0
|
||||
company_institutions = 0
|
||||
|
||||
for w in works:
|
||||
for a in w.get("authorships", []) or []:
|
||||
n_authorships += 1
|
||||
if a.get("author_position"):
|
||||
with_position += 1
|
||||
if a.get("is_corresponding") is not None:
|
||||
with_corresponding += 1
|
||||
for inst in a.get("institutions", []) or []:
|
||||
n_institutions += 1
|
||||
itype = inst.get("type")
|
||||
if itype:
|
||||
with_inst_type += 1
|
||||
if itype == "company":
|
||||
company_institutions += 1
|
||||
|
||||
def pct(x: int, n: int) -> float:
|
||||
return round(100.0 * x / n, 2) if n else 0.0
|
||||
|
||||
return {
|
||||
"authorships_total": n_authorships,
|
||||
"author_position_pct": pct(with_position, n_authorships),
|
||||
"is_corresponding_pct": pct(with_corresponding, n_authorships),
|
||||
"institutions_total": n_institutions,
|
||||
"institution_type_pct": pct(with_inst_type, n_institutions),
|
||||
"company_institutions": company_institutions,
|
||||
}
|
||||
|
||||
|
||||
def audit_scale(works: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
sizes: list[int] = []
|
||||
pairs_at_cap = {cap: 0 for cap in PAIR_CAPS}
|
||||
for w in works:
|
||||
author_ids = {
|
||||
a["author"]["id"]
|
||||
for a in (w.get("authorships") or [])
|
||||
if a.get("author", {}).get("id")
|
||||
}
|
||||
n = len(author_ids)
|
||||
sizes.append(n)
|
||||
for cap in PAIR_CAPS:
|
||||
if 2 <= n <= cap:
|
||||
pairs_at_cap[cap] += n * (n - 1) // 2
|
||||
sizes_sorted = sorted(sizes)
|
||||
return {
|
||||
"works": len(sizes),
|
||||
"authors_per_work": {
|
||||
"p50": _percentile(sizes_sorted, 0.50),
|
||||
"p90": _percentile(sizes_sorted, 0.90),
|
||||
"p99": _percentile(sizes_sorted, 0.99),
|
||||
"max": sizes_sorted[-1] if sizes_sorted else 0,
|
||||
},
|
||||
"hyperauthorship_works_gt_100": sum(1 for s in sizes if s > 100),
|
||||
"pair_instances_at_cap": pairs_at_cap,
|
||||
}
|
||||
|
||||
|
||||
def audit_career(
|
||||
author_ids: set[str], works: list[dict[str, Any]]
|
||||
) -> dict[str, Any]:
|
||||
"""active_years and suspicious-profile flags for in-set authors (exact history)."""
|
||||
years_by_author: dict[str, set[int]] = collections.defaultdict(set)
|
||||
for w in works:
|
||||
year = w.get("publication_year")
|
||||
if not isinstance(year, int):
|
||||
continue
|
||||
for a in w.get("authorships", []) or []:
|
||||
aid = a.get("author", {}).get("id")
|
||||
if aid in author_ids:
|
||||
years_by_author[aid].add(year)
|
||||
|
||||
active_years_list: list[int] = []
|
||||
suspicious = 0
|
||||
for aid in author_ids:
|
||||
years = years_by_author.get(aid)
|
||||
if not years:
|
||||
continue
|
||||
active_years_list.append(len(years))
|
||||
first_year = min(years)
|
||||
span = max(years) - first_year + 1
|
||||
if first_year < 1970 or span > 60:
|
||||
suspicious += 1
|
||||
|
||||
ay_sorted = sorted(active_years_list)
|
||||
return {
|
||||
"authors_with_works": len(ay_sorted),
|
||||
"suspicious_profile_count": suspicious,
|
||||
"suspicious_profile_pct": (
|
||||
round(100.0 * suspicious / len(ay_sorted), 2) if ay_sorted else 0.0
|
||||
),
|
||||
"active_years": {
|
||||
"p50": _percentile(ay_sorted, 0.50),
|
||||
"p90": _percentile(ay_sorted, 0.90),
|
||||
"max": ay_sorted[-1] if ay_sorted else 0,
|
||||
"mean": round(statistics.fmean(ay_sorted), 2) if ay_sorted else 0.0,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def audit_signals(client: httpx.Client, inst: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Probe org_patents (INSE cluster) for matched_authors + match_type breakdown."""
|
||||
if not INSE_URL or not INSE_KEY:
|
||||
return {"error": "INSE cluster credentials missing"}
|
||||
try:
|
||||
result = es_search(
|
||||
client, INSE_URL, INSE_KEY, "org_patents",
|
||||
{
|
||||
"size": 0,
|
||||
"track_total_hits": True,
|
||||
"query": {"term": {"institution_id": inst["short_id"]}},
|
||||
"aggs": {"by_match_type": {"terms": {"field": "match_type"}}},
|
||||
},
|
||||
)
|
||||
except RuntimeError as exc:
|
||||
return {"error": str(exc)[:300]}
|
||||
buckets = (
|
||||
result.get("aggregations", {}).get("by_match_type", {}).get("buckets", [])
|
||||
)
|
||||
return {
|
||||
"org_patents_for_institution": result["hits"]["total"]["value"],
|
||||
"match_type_breakdown": {b["key"]: b["doc_count"] for b in buckets},
|
||||
}
|
||||
|
||||
|
||||
def audit_permissions(client: httpx.Client, probe_writes: bool) -> dict[str, Any]:
|
||||
"""Test create / bulk / delete-by-query / delete on the INSE cluster."""
|
||||
if not probe_writes:
|
||||
return {"skipped": "pass --probe-writes to test index create/bulk/delete"}
|
||||
if not INSE_URL or not INSE_KEY:
|
||||
return {"error": "INSE cluster credentials missing"}
|
||||
|
||||
out: dict[str, Any] = {}
|
||||
create = es_request(
|
||||
client, "PUT", INSE_URL, INSE_KEY, PROBE_INDEX,
|
||||
{"mappings": {"properties": {"institution_id": {"type": "keyword"}}}},
|
||||
)
|
||||
out["create_index"] = create.status_code
|
||||
if create.is_success:
|
||||
bulk_body = (
|
||||
json.dumps({"index": {"_index": PROBE_INDEX, "_id": "probe_1"}})
|
||||
+ "\n"
|
||||
+ json.dumps({"institution_id": "PROBE"})
|
||||
+ "\n"
|
||||
)
|
||||
bulk = client.post(
|
||||
f"{INSE_URL}/_bulk",
|
||||
headers={**_headers(INSE_KEY), "Content-Type": "application/x-ndjson"},
|
||||
content=bulk_body,
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
)
|
||||
out["bulk_index"] = bulk.status_code
|
||||
client.post(f"{INSE_URL}/{PROBE_INDEX}/_refresh", headers=_headers(INSE_KEY))
|
||||
dbq = es_request(
|
||||
client, "POST", INSE_URL, INSE_KEY, f"{PROBE_INDEX}/_delete_by_query",
|
||||
{"query": {"term": {"institution_id": "PROBE"}}},
|
||||
)
|
||||
out["delete_by_query"] = dbq.status_code # expect 403 if it mirrors org_patents
|
||||
drop = es_request(client, "DELETE", INSE_URL, INSE_KEY, PROBE_INDEX)
|
||||
out["delete_index"] = drop.status_code
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Main
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--institution-id", required=True)
|
||||
parser.add_argument(
|
||||
"--config", default=str(SCRIPT_DIR / "multipliers.yaml"),
|
||||
help="YAML config; its cohorts.<ID>.institution_ids extends the author set "
|
||||
"beyond the primary institution (e.g. the university hospital).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--cache-dir", default=str(SCRIPT_DIR / "cache"),
|
||||
help="Where to read/write the extracted author/work JSONL.gz",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--skip-extract", action="store_true",
|
||||
help="Reuse cached JSONL.gz instead of hitting ES for author/work extraction.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--probe-writes", action="store_true",
|
||||
help="Create+bulk+delete a throwaway index on INSE to test write permissions.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not NES_URL or not NES_KEY:
|
||||
raise SystemExit(f"Missing NES credentials. Checked {ENV_PATH}")
|
||||
|
||||
cache_dir = Path(args.cache_dir)
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
short = args.institution_id.strip().rsplit("/", 1)[-1]
|
||||
authors_path = cache_dir / f"authors_{short}.jsonl.gz"
|
||||
works_path = cache_dir / f"works_{short}.jsonl.gz"
|
||||
|
||||
cohort_ids = [short]
|
||||
config_path = Path(args.config)
|
||||
if config_path.exists():
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
cfg = yaml.safe_load(f) or {}
|
||||
cohort_cfg = (cfg.get("cohorts") or {}).get(short) or {}
|
||||
if cohort_cfg.get("institution_ids"):
|
||||
cohort_ids = [str(i) for i in cohort_cfg["institution_ids"]]
|
||||
|
||||
with httpx.Client() as client:
|
||||
insts = [resolve_institution(client, i) for i in cohort_ids]
|
||||
inst = insts[0] # primary
|
||||
print(f"Cohort ({len(insts)} institutions):")
|
||||
for i in insts:
|
||||
print(f" {i['short_id']:<14} {i['display_name']}")
|
||||
|
||||
if args.skip_extract and authors_path.exists() and works_path.exists():
|
||||
print("Reusing cached extract.")
|
||||
authors = {a["id"]: a for a in read_jsonl_gz(authors_path)}
|
||||
works = list(read_jsonl_gz(works_path))
|
||||
else:
|
||||
print("\nExtracting authors...")
|
||||
authors = collect_authors(client, insts)
|
||||
write_jsonl_gz(authors_path, authors.values())
|
||||
print(f"Authors: {len(authors)} -> {authors_path}")
|
||||
|
||||
print("\nExtracting works (full authorships)...")
|
||||
author_ids = sorted(authors.keys())
|
||||
works_map = collect_works(client, author_ids)
|
||||
works = list(works_map.values())
|
||||
write_jsonl_gz(works_path, works)
|
||||
print(f"Works: {len(works)} -> {works_path}")
|
||||
|
||||
author_id_set = set(authors.keys())
|
||||
|
||||
print("\nComputing audit...")
|
||||
report = {
|
||||
"institution": inst,
|
||||
"cohort": [
|
||||
{"id": i["short_id"], "display_name": i["display_name"]} for i in insts
|
||||
],
|
||||
"reproduction": {
|
||||
"author_count": len(authors),
|
||||
"work_count": len(works),
|
||||
"group_breakdown": dict(
|
||||
collections.Counter(
|
||||
tuple(sorted(a["source_sets"])) and "+".join(sorted(a["source_sets"]))
|
||||
for a in authors.values()
|
||||
)
|
||||
),
|
||||
},
|
||||
"field_coverage": audit_field_coverage(works),
|
||||
"scale": audit_scale(works),
|
||||
"career_quality": audit_career(author_id_set, works),
|
||||
"signals": audit_signals(client, inst),
|
||||
"permissions": audit_permissions(client, args.probe_writes),
|
||||
}
|
||||
|
||||
report_path = cache_dir / f"spike_report_{short}.json"
|
||||
with open(report_path, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(report, f, ensure_ascii=False, indent=2)
|
||||
|
||||
print("\n=== SPIKE AUDIT REPORT ===")
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
print(f"\nWritten: {report_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Tests for graph construction (pair generation, weights, caps, node aggregates)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from graph import build_graph, focal_subgraph, short_id
|
||||
|
||||
|
||||
def make_work(wid, year, authors, field_id=None):
|
||||
"""authors: list of (author_id, institutions[(id,type)], position)."""
|
||||
return {
|
||||
"id": f"https://openalex.org/{wid}",
|
||||
"publication_year": year,
|
||||
"primary_topic": (
|
||||
{"field": {"id": f"https://openalex.org/fields/{field_id}"}}
|
||||
if field_id
|
||||
else None
|
||||
),
|
||||
"authorships": [
|
||||
{
|
||||
"author": {"id": f"https://openalex.org/{aid}", "display_name": aid},
|
||||
"author_position": pos,
|
||||
"institutions": [
|
||||
{"id": f"https://openalex.org/{iid}", "type": itype}
|
||||
for iid, itype in insts
|
||||
],
|
||||
}
|
||||
for aid, insts, pos in authors
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
UDE = [("I1", "education")]
|
||||
COMPANY = [("I9", "company")]
|
||||
|
||||
|
||||
def test_short_id():
|
||||
assert short_id("https://openalex.org/A5023888391") == "A5023888391"
|
||||
assert short_id("A5023888391") == "A5023888391"
|
||||
assert short_id(None) is None
|
||||
|
||||
|
||||
def test_edge_weight_decay_and_team_size():
|
||||
works = [
|
||||
make_work("W1", 2026, [("A1", UDE, "first"), ("A2", UDE, "last")]),
|
||||
make_work("W2", 2025, [("A1", UDE, "first"), ("A2", UDE, "last")]),
|
||||
]
|
||||
g = build_graph(works, {"A1", "A2"}, decay=0.8)
|
||||
assert g.ref_year == 2026
|
||||
e = g.edges[("A1", "A2")]
|
||||
# W1: 0.8^0 / 1 = 1.0 ; W2: 0.8^1 / 1 = 0.8
|
||||
assert e.weight == pytest.approx(1.8)
|
||||
assert e.n_works == 2
|
||||
assert e.first_joint_year == 2025
|
||||
assert e.last_joint_year == 2026
|
||||
|
||||
|
||||
def test_team_size_divides_weight():
|
||||
works = [
|
||||
make_work(
|
||||
"W1", 2026,
|
||||
[("A1", UDE, "first"), ("A2", UDE, "middle"), ("A3", UDE, "last")],
|
||||
)
|
||||
]
|
||||
g = build_graph(works, {"A1", "A2", "A3"})
|
||||
# n_authors=3 -> each pair gets 1/(3-1) = 0.5
|
||||
assert g.edges[("A1", "A2")].weight == pytest.approx(0.5)
|
||||
assert len(g.edges) == 3
|
||||
|
||||
|
||||
def test_hyperauthorship_cap_excludes_pairs_but_keeps_years():
|
||||
big = make_work(
|
||||
"W1", 2020, [(f"A{i}", UDE, "middle") for i in range(1, 61)]
|
||||
)
|
||||
small = make_work("W2", 2021, [("A1", UDE, "first"), ("A2", UDE, "last")])
|
||||
g = build_graph([big, small], {"A1", "A2"}, max_authors_per_work=50)
|
||||
assert g.n_works_capped == 1
|
||||
assert g.n_works_used == 1
|
||||
assert set(g.edges) == {("A1", "A2")}
|
||||
# capped work still contributes publication years
|
||||
assert 2020 in g.nodes["A1"].publication_years
|
||||
assert 2021 in g.nodes["A1"].publication_years
|
||||
|
||||
|
||||
def test_cross_institution_weight():
|
||||
works = [
|
||||
make_work("W1", 2026, [("A1", UDE, "first"), ("A2", COMPANY, "last")]),
|
||||
make_work("W2", 2026, [("A1", UDE, "first"), ("A3", UDE, "last")]),
|
||||
]
|
||||
g = build_graph(works, {"A1", "A2", "A3"})
|
||||
assert g.edges[("A1", "A2")].cross_inst_weight == pytest.approx(1.0)
|
||||
assert g.edges[("A1", "A3")].cross_inst_weight == pytest.approx(0.0)
|
||||
|
||||
|
||||
def test_company_share_and_fields():
|
||||
works = [
|
||||
make_work("W1", 2026, [("A1", UDE, "first"), ("A2", COMPANY, "last")], "F11"),
|
||||
make_work("W2", 2026, [("A1", UDE, "first"), ("A3", UDE, "last")], "F22"),
|
||||
]
|
||||
g = build_graph(works, {"A1"})
|
||||
n = g.nodes["A1"]
|
||||
assert n.n_company_works == 1 and n.n_typed_works == 2
|
||||
assert n.field_counts == {"F11": 1, "F22": 1}
|
||||
|
||||
|
||||
def test_focal_subgraph_excludes_externals():
|
||||
works = [
|
||||
make_work("W1", 2026, [("A1", UDE, "first"), ("EXT", COMPANY, "last")]),
|
||||
make_work("W2", 2026, [("A1", UDE, "first"), ("A2", UDE, "last")]),
|
||||
]
|
||||
g = build_graph(works, {"A1", "A2"})
|
||||
internal = focal_subgraph(g)
|
||||
assert "EXT" not in internal
|
||||
assert set(internal["A1"].keys()) == {"A2"}
|
||||
|
||||
|
||||
def test_last_author_junior_first_recorded():
|
||||
works = [
|
||||
make_work("W1", 2026, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")]),
|
||||
]
|
||||
g = build_graph(works, {"JUNIOR", "PROF"})
|
||||
assert g.nodes["PROF"].last_author_junior_first == [("JUNIOR", 2026)]
|
||||
assert g.nodes["JUNIOR"].last_author_junior_first == []
|
||||
|
||||
|
||||
def test_duplicate_authorships_deduped():
|
||||
w = make_work("W1", 2026, [("A1", UDE, "first"), ("A1", UDE, "last"), ("A2", UDE, "middle")])
|
||||
g = build_graph([w], {"A1", "A2"})
|
||||
# A1 duplicated -> counts once; n_authors=2 -> weight divisor 1
|
||||
assert g.edges[("A1", "A2")].weight == pytest.approx(1.0)
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Tests for metrics: betweenness vs networkx oracle, constraint on a star,
|
||||
active_years_at robustness (the planted-1893-outlier regression guard), mentor logic."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from graph import build_graph
|
||||
from metrics import (
|
||||
active_years_at,
|
||||
betweenness_centrality,
|
||||
burt_constraint,
|
||||
compute_all_metrics,
|
||||
field_entropy,
|
||||
is_suspicious_profile,
|
||||
mentor_metrics,
|
||||
)
|
||||
from test_graph import UDE, make_work
|
||||
|
||||
networkx = pytest.importorskip("networkx")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# active_years_at — THE regression guard for the whole design premise
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_active_years_at_unmoved_by_planted_1893_outlier():
|
||||
"""A single misattributed 1893 work must shift active_years_at by exactly 1,
|
||||
unlike first_pub_year-based career age, which it would shift by ~120 years."""
|
||||
clean = set(range(2010, 2026)) # 16 active years
|
||||
poisoned = clean | {1893} # merged-profile artifact
|
||||
|
||||
assert active_years_at(clean, 2025) == 16
|
||||
assert active_years_at(poisoned, 2025) == 17 # +1, not +120
|
||||
# seniority classification at the time of an early collaboration is unaffected
|
||||
assert active_years_at(clean, 2013) == 4 # still "Early" in 2013
|
||||
assert active_years_at(poisoned, 2013) == 5 # off by exactly one year
|
||||
|
||||
# the poisoned profile IS flagged for evidence confidence
|
||||
assert not is_suspicious_profile(clean)
|
||||
assert is_suspicious_profile(poisoned)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# betweenness — barbell fixture + networkx oracle
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _nx_graph(adj):
|
||||
g = networkx.Graph()
|
||||
for a, neigh in adj.items():
|
||||
g.add_node(a)
|
||||
for b, w in neigh.items():
|
||||
g.add_edge(a, b, weight=w, distance=1.0 / w)
|
||||
return g
|
||||
|
||||
|
||||
def test_betweenness_barbell_bridge_dominates():
|
||||
"""Two triangles joined by one bridge node: the bridge has max betweenness."""
|
||||
adj = {}
|
||||
|
||||
def add(a, b, w=1.0):
|
||||
adj.setdefault(a, {})[b] = w
|
||||
adj.setdefault(b, {})[a] = w
|
||||
|
||||
for x, y in [("A", "B"), ("B", "C"), ("A", "C")]:
|
||||
add(x, y)
|
||||
for x, y in [("D", "E"), ("E", "F"), ("D", "F")]:
|
||||
add(x, y)
|
||||
add("C", "M")
|
||||
add("M", "D")
|
||||
|
||||
bc = betweenness_centrality(adj)
|
||||
assert bc["M"] == max(bc.values())
|
||||
assert bc["A"] == pytest.approx(0.0)
|
||||
|
||||
oracle = networkx.betweenness_centrality(
|
||||
_nx_graph(adj), weight="distance", normalized=True
|
||||
)
|
||||
for node, value in bc.items():
|
||||
assert value == pytest.approx(oracle[node], abs=1e-9), node
|
||||
|
||||
|
||||
def test_betweenness_weighted_paths_vs_oracle():
|
||||
"""Weighted graph where the shortest path is NOT the fewest-hops path."""
|
||||
adj = {}
|
||||
|
||||
def add(a, b, w):
|
||||
adj.setdefault(a, {})[b] = w
|
||||
adj.setdefault(b, {})[a] = w
|
||||
|
||||
# strong two-hop route A-X-B (distance 0.2+0.2) beats direct weak A-B (distance 2)
|
||||
add("A", "B", 0.5)
|
||||
add("A", "X", 5.0)
|
||||
add("X", "B", 5.0)
|
||||
add("B", "C", 1.0)
|
||||
|
||||
bc = betweenness_centrality(adj)
|
||||
oracle = networkx.betweenness_centrality(
|
||||
_nx_graph(adj), weight="distance", normalized=True
|
||||
)
|
||||
for node, value in bc.items():
|
||||
assert value == pytest.approx(oracle[node], abs=1e-9), node
|
||||
assert bc["X"] > 0.0 # X sits on the A->B shortest path
|
||||
|
||||
|
||||
def test_betweenness_random_graph_vs_oracle():
|
||||
"""Randomized (but seeded) graph, full oracle comparison."""
|
||||
rng = networkx.gnm_random_graph(24, 60, seed=7)
|
||||
adj = {}
|
||||
for a, b in rng.edges():
|
||||
w = ((a * 31 + b * 17) % 9 + 1) / 3.0 # deterministic pseudo-weights
|
||||
adj.setdefault(str(a), {})[str(b)] = w
|
||||
adj.setdefault(str(b), {})[str(a)] = w
|
||||
for n in rng.nodes():
|
||||
adj.setdefault(str(n), {})
|
||||
|
||||
bc = betweenness_centrality(adj)
|
||||
oracle = networkx.betweenness_centrality(
|
||||
_nx_graph(adj), weight="distance", normalized=True
|
||||
)
|
||||
for node, value in bc.items():
|
||||
assert value == pytest.approx(oracle[node], abs=1e-7), node
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Burt constraint — star fixture
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_constraint_star_center_is_unconstrained():
|
||||
"""Star: the hub bridges structural holes (low constraint); each spoke is
|
||||
fully dependent on the hub (constraint 1.0). Clique members sit in between."""
|
||||
star = {}
|
||||
for spoke in ["S1", "S2", "S3", "S4"]:
|
||||
star.setdefault("HUB", {})[spoke] = 1.0
|
||||
star[spoke] = {"HUB": 1.0}
|
||||
c = burt_constraint(star)
|
||||
assert c["HUB"] == pytest.approx(0.25) # sum of (1/4)^2 * 4
|
||||
for spoke in ["S1", "S2", "S3", "S4"]:
|
||||
assert c[spoke] == pytest.approx(1.0)
|
||||
|
||||
triangle = {
|
||||
"A": {"B": 1.0, "C": 1.0},
|
||||
"B": {"A": 1.0, "C": 1.0},
|
||||
"C": {"A": 1.0, "B": 1.0},
|
||||
}
|
||||
c3 = burt_constraint(triangle)
|
||||
# closed triad: everyone highly constrained, more than the star hub
|
||||
assert c3["A"] > c["HUB"]
|
||||
oracle = networkx.constraint(_nx_graph(triangle), weight="weight")
|
||||
assert c3["A"] == pytest.approx(oracle["A"], abs=1e-9)
|
||||
|
||||
|
||||
def test_field_entropy():
|
||||
assert field_entropy({}) == 0.0
|
||||
assert field_entropy({"F1": 10}) == 0.0
|
||||
assert field_entropy({"F1": 5, "F2": 5}) == pytest.approx(1.0)
|
||||
assert field_entropy({"F1": 1, "F2": 1, "F3": 1, "F4": 1}) == pytest.approx(2.0)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Mentor metrics
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _career(aid, years, wid_prefix):
|
||||
"""Solo-ish works giving `aid` a publication history (paired with a throwaway
|
||||
co-author so the works survive the n_authors >= 2 filter)."""
|
||||
return [
|
||||
make_work(f"{wid_prefix}{y}", y, [(aid, UDE, "first"), (f"X_{aid}_{y}", [], "last")])
|
||||
for y in years
|
||||
]
|
||||
|
||||
|
||||
def test_mentor_seniority_gap_and_progression():
|
||||
works = []
|
||||
# PROF: established since 2000 (>=10 active years by 2015)
|
||||
works += _career("PROF", range(2000, 2026), "P")
|
||||
# JUNIOR: first-ever activity 2015 (active_years_at(2015)=1), then progresses
|
||||
works += [
|
||||
make_work("J1", 2015, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")]),
|
||||
]
|
||||
works += _career("JUNIOR", range(2016, 2022), "J") # 6 more years -> progressed
|
||||
# PEER: senior colleague, first joint work 2020 when both are senior
|
||||
works += _career("PEER", range(2000, 2026), "Q")
|
||||
works += [make_work("JP", 2020, [("PEER", UDE, "first"), ("PROF", UDE, "last")])]
|
||||
|
||||
g = build_graph(works, {"PROF", "JUNIOR", "PEER"})
|
||||
mm = mentor_metrics(g, "PROF")
|
||||
|
||||
assert mm.juniors_mentored == 1
|
||||
assert mm.junior_ids == ["JUNIOR"]
|
||||
assert mm.junior_progression_rate == pytest.approx(1.0)
|
||||
# PROF was last author on J1 with a junior first author
|
||||
assert mm.last_author_with_junior_first == 1
|
||||
# the senior PEER never counts
|
||||
assert "PEER" not in mm.junior_ids
|
||||
|
||||
|
||||
def test_mentor_excludes_external_coauthors():
|
||||
"""External co-authors have truncated year-sets and must never count as juniors."""
|
||||
works = _career("PROF", range(2000, 2026), "P")
|
||||
works += [make_work("E1", 2020, [("EXT", [], "first"), ("PROF", UDE, "last")])]
|
||||
g = build_graph(works, {"PROF"}) # EXT not focal
|
||||
mm = mentor_metrics(g, "PROF")
|
||||
assert mm.juniors_mentored == 0
|
||||
assert mm.last_author_with_junior_first == 0
|
||||
|
||||
|
||||
def test_mentor_requires_focal_seniority_at_first_joint_year():
|
||||
"""Two juniors co-publishing: neither mentors the other."""
|
||||
works = [
|
||||
make_work("W1", 2020, [("J1", UDE, "first"), ("J2", UDE, "last")]),
|
||||
make_work("W2", 2021, [("J1", UDE, "first"), ("J2", UDE, "last")]),
|
||||
]
|
||||
g = build_graph(works, {"J1", "J2"})
|
||||
assert mentor_metrics(g, "J2").juniors_mentored == 0
|
||||
|
||||
|
||||
def test_compute_all_metrics_shapes():
|
||||
works = _career("PROF", range(2000, 2026), "P")
|
||||
works += [make_work("J1", 2015, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")])]
|
||||
g = build_graph(works, {"PROF", "JUNIOR"})
|
||||
rows = compute_all_metrics(g)
|
||||
assert set(rows) == {"PROF", "JUNIOR"}
|
||||
prof = rows["PROF"]
|
||||
assert prof["juniors_mentored"] == 1
|
||||
assert prof["active_years"] == 26
|
||||
assert 0.0 <= prof["industry_coauthor_share"] <= 1.0
|
||||
assert prof["suspicious_profile"] is False
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Property-style tests for scoring: percentile bounds, tie handling, bucket isolation,
|
||||
weight redistribution for missing metrics, tagging rules."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from scoring import career_bucket, percentile_ranks, score_rows
|
||||
|
||||
CONFIG = {
|
||||
"_config_hash": "testhash",
|
||||
"career": {"buckets": [4, 9, 14], "bucket_names": ["Early", "Emerging", "Established", "Senior"]},
|
||||
"weights": {
|
||||
"bridger": {"betweenness": 0.5, "field_entropy": 0.5},
|
||||
"mentor": {"juniors_mentored": 1.0},
|
||||
},
|
||||
"tags": {"threshold": 0.85, "min_active_years": 2},
|
||||
}
|
||||
|
||||
|
||||
def row(aid, active_years, betweenness=0.0, entropy=0.0, juniors=0):
|
||||
return {
|
||||
"author_id": aid,
|
||||
"active_years": active_years,
|
||||
"betweenness": betweenness,
|
||||
"field_entropy": entropy,
|
||||
"juniors_mentored": juniors,
|
||||
"junior_ids": [],
|
||||
}
|
||||
|
||||
|
||||
def test_career_bucket_thresholds_match_backend():
|
||||
names = ["Early", "Emerging", "Established", "Senior"]
|
||||
assert career_bucket(1, [4, 9, 14], names) == "Early"
|
||||
assert career_bucket(4, [4, 9, 14], names) == "Early"
|
||||
assert career_bucket(5, [4, 9, 14], names) == "Emerging"
|
||||
assert career_bucket(9, [4, 9, 14], names) == "Emerging"
|
||||
assert career_bucket(10, [4, 9, 14], names) == "Established"
|
||||
assert career_bucket(14, [4, 9, 14], names) == "Established"
|
||||
assert career_bucket(15, [4, 9, 14], names) == "Senior"
|
||||
|
||||
|
||||
def test_percentiles_in_zero_one_and_ties_share_mean_rank():
|
||||
p = percentile_ranks({"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
|
||||
assert all(0.0 < v <= 1.0 for v in p.values())
|
||||
assert p["d"] == pytest.approx(1.0)
|
||||
assert p["a"] == pytest.approx(0.25)
|
||||
|
||||
# a metric that is 0 for most people must not hand out high percentiles
|
||||
p = percentile_ranks({"a": 0, "b": 0, "c": 0, "d": 5})
|
||||
assert p["a"] == pytest.approx(0.5) # mean rank of the 3-way tie: (1+2+3)/3 / 4
|
||||
assert p["d"] == pytest.approx(1.0)
|
||||
# None values are excluded entirely
|
||||
p = percentile_ranks({"a": None, "b": 1.0})
|
||||
assert "a" not in p and p["b"] == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_percentiles_computed_within_buckets_not_across():
|
||||
rows = {
|
||||
# Early bucket: modest raw values
|
||||
"e1": row("e1", 2, betweenness=0.1, entropy=0.5),
|
||||
"e2": row("e2", 3, betweenness=0.0, entropy=0.0),
|
||||
# Senior bucket: huge raw values
|
||||
"s1": row("s1", 20, betweenness=0.9, entropy=3.0),
|
||||
"s2": row("s2", 25, betweenness=0.8, entropy=2.0),
|
||||
}
|
||||
scored = {r["author_id"]: r for r in score_rows(rows, CONFIG)}
|
||||
# e1 tops the EARLY bucket despite raw values far below the seniors
|
||||
assert scored["e1"]["percentiles"]["betweenness"] == pytest.approx(1.0)
|
||||
assert scored["s1"]["percentiles"]["betweenness"] == pytest.approx(1.0)
|
||||
assert scored["e1"]["career_bucket"] == "Early"
|
||||
assert scored["s1"]["career_bucket"] == "Senior"
|
||||
|
||||
|
||||
def test_monotonicity_more_bridging_never_lowers_score():
|
||||
base = {
|
||||
"a": row("a", 3, betweenness=0.1, entropy=1.0),
|
||||
"b": row("b", 3, betweenness=0.2, entropy=1.0),
|
||||
"c": row("c", 3, betweenness=0.3, entropy=1.0),
|
||||
}
|
||||
improved = {
|
||||
"a": row("a", 3, betweenness=0.25, entropy=1.0), # a gains betweenness
|
||||
"b": row("b", 3, betweenness=0.2, entropy=1.0),
|
||||
"c": row("c", 3, betweenness=0.3, entropy=1.0),
|
||||
}
|
||||
s_base = {r["author_id"]: r for r in score_rows(base, CONFIG)}
|
||||
s_improved = {r["author_id"]: r for r in score_rows(improved, CONFIG)}
|
||||
assert (
|
||||
s_improved["a"]["sub_scores"]["bridger"]
|
||||
>= s_base["a"]["sub_scores"]["bridger"]
|
||||
)
|
||||
|
||||
|
||||
def test_missing_metric_weight_redistributed():
|
||||
rows = {
|
||||
"a": {**row("a", 3, entropy=2.0), "betweenness": None},
|
||||
"b": {**row("b", 3, entropy=1.0), "betweenness": None},
|
||||
}
|
||||
scored = {r["author_id"]: r for r in score_rows(rows, CONFIG)}
|
||||
# bridger falls back to entropy alone; the top entropy holder gets 1.0
|
||||
assert scored["a"]["sub_scores"]["bridger"] == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_tags_fire_above_threshold_and_respect_min_active_years():
|
||||
rows = {
|
||||
# 8-person Early bucket: m ranks 7/8 = 0.875 >= 0.85 threshold
|
||||
**{f"x{i}": row(f"x{i}", 3, juniors=0) for i in range(6)},
|
||||
"m": row("m", 3, juniors=7),
|
||||
"newbie": {**row("newbie", 1, juniors=9), "active_years": 1},
|
||||
}
|
||||
scored = {r["author_id"]: r for r in score_rows(rows, CONFIG)}
|
||||
assert "mentor" in scored["m"]["tags"]
|
||||
assert scored["newbie"]["tags"] == [] # min_active_years=2 gate
|
||||
|
||||
|
||||
def test_output_carries_raw_percentile_subscore_and_hash():
|
||||
scored = score_rows({"a": row("a", 3, betweenness=0.5)}, CONFIG)[0]
|
||||
assert scored["betweenness"] == 0.5 # raw
|
||||
assert "betweenness" in scored["percentiles"] # percentile
|
||||
assert "bridger" in scored["sub_scores"] # sub-score
|
||||
assert scored["config_hash"] == "testhash"
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Tests for the pure parts of the signal joins: name/DOI normalization and
|
||||
the ambiguity rule for news matching."""
|
||||
from __future__ import annotations
|
||||
|
||||
from signals import normalize_doi, normalize_name
|
||||
|
||||
|
||||
def test_normalize_name_diacritics_case_whitespace():
|
||||
assert normalize_name("René Müller") == "rene muller"
|
||||
assert normalize_name("CHRISTOPH GILLE") == "christoph gille" # news is often ALL-CAPS
|
||||
assert normalize_name(" Anna-Lena Giesecke ") == "anna-lena giesecke"
|
||||
assert normalize_name("Barbara Saccà") == normalize_name("Barbara Sacca")
|
||||
assert normalize_name("Bülent Eken") == "bulent eken"
|
||||
|
||||
|
||||
def test_normalize_doi_prefixes_and_case():
|
||||
assert normalize_doi("https://doi.org/10.1371/journal.pone.0018216") == \
|
||||
"10.1371/journal.pone.0018216"
|
||||
assert normalize_doi("DOI:10.1016/J.CELL.2020.01.001") == "10.1016/j.cell.2020.01.001"
|
||||
assert normalize_doi("doi.org/10.1/x") == "10.1/x"
|
||||
assert normalize_doi("10.1/x") == "10.1/x"
|
||||
assert normalize_doi("") is None
|
||||
assert normalize_doi(None) is None
|
||||
|
||||
|
||||
def test_ambiguous_name_rule():
|
||||
"""Two cohort authors normalizing to the same name -> both excluded from news."""
|
||||
from collections import defaultdict
|
||||
names = {"A1": "Wei Zhang", "A2": "Wei ZHANG", "A3": "Unique Person"}
|
||||
by_norm = defaultdict(list)
|
||||
for aid, n in names.items():
|
||||
by_norm[normalize_name(n)].append(aid)
|
||||
ambiguous = {k for k, v in by_norm.items() if len(v) > 1}
|
||||
assert normalize_name("Wei Zhang") in ambiguous
|
||||
assert normalize_name("Unique Person") not in ambiguous
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
validate_sample.py — M1 exit check against the 60-person hand-labeled sample.
|
||||
|
||||
analysis/career_stage/career_stage_sample.csv holds 60 UDE researchers with
|
||||
manually verified status (31 Professor / 29 Researcher incl. doctoral). The
|
||||
mentor sub-score is a proxy for supervision with no ground truth in OpenAlex,
|
||||
so the cheapest sanity check is: mentor scores must concentrate on the
|
||||
professors. If they don't, the proxy is wrong and M2 waits (plan §5, M1 exit).
|
||||
|
||||
Usage:
|
||||
python validate_sample.py --institution-id I62318514
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import gzip
|
||||
import json
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
REPO_ROOT = SCRIPT_DIR.parent.parent.parent
|
||||
SAMPLE_CSV = REPO_ROOT / "analysis" / "career_stage" / "career_stage_sample.csv"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--institution-id", required=True)
|
||||
parser.add_argument("--cache-dir", default=str(SCRIPT_DIR / "cache"))
|
||||
args = parser.parse_args()
|
||||
|
||||
short = args.institution_id.strip().rsplit("/", 1)[-1]
|
||||
scores_path = Path(args.cache_dir) / f"scores_{short}.jsonl.gz"
|
||||
if not scores_path.exists():
|
||||
raise SystemExit(f"Run build.py first — missing {scores_path}")
|
||||
|
||||
scores: dict[str, dict] = {}
|
||||
with gzip.open(scores_path, "rt", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
row = json.loads(line)
|
||||
scores[row["author_id"]] = row
|
||||
|
||||
sample: list[dict] = []
|
||||
with open(SAMPLE_CSV, newline="", encoding="utf-8-sig") as f:
|
||||
for rec in csv.DictReader(f):
|
||||
sample.append(rec)
|
||||
|
||||
by_status: dict[str, list[dict]] = {}
|
||||
missing: list[str] = []
|
||||
for rec in sample:
|
||||
aid = rec["openalex_author_id"].strip()
|
||||
row = scores.get(aid)
|
||||
if row is None:
|
||||
missing.append(f"{rec['name']} ({aid})")
|
||||
continue
|
||||
by_status.setdefault(rec["known_status"], []).append(
|
||||
{"name": rec["name"], "discipline": rec["discipline_group"], **row}
|
||||
)
|
||||
|
||||
print(f"Sample: {len(sample)} people, matched in scores: "
|
||||
f"{sum(len(v) for v in by_status.values())}, missing: {len(missing)}")
|
||||
for m in missing:
|
||||
print(f" MISSING: {m}")
|
||||
|
||||
report: dict = {"missing": missing, "by_status": {}}
|
||||
for sub in ("mentor", "bridger", "amplifier"):
|
||||
print(f"\n=== {sub} sub-score by known status ===")
|
||||
for status, rows in sorted(by_status.items()):
|
||||
vals = [r["sub_scores"][sub] for r in rows]
|
||||
entry = {
|
||||
"n": len(vals),
|
||||
"median": round(statistics.median(vals), 3),
|
||||
"mean": round(statistics.fmean(vals), 3),
|
||||
"min": round(min(vals), 3),
|
||||
"max": round(max(vals), 3),
|
||||
}
|
||||
report["by_status"].setdefault(status, {})[sub] = entry
|
||||
print(f" {status:<12} n={entry['n']:>2} median={entry['median']:.3f} "
|
||||
f"mean={entry['mean']:.3f} range=[{entry['min']:.3f}, {entry['max']:.3f}]")
|
||||
|
||||
# headline check: professors' median mentor score > researchers'
|
||||
prof = report["by_status"].get("Professor", {}).get("mentor", {})
|
||||
res = report["by_status"].get("Researcher", {}).get("mentor", {})
|
||||
if prof and res:
|
||||
ok = prof["median"] > res["median"]
|
||||
print(f"\nM1 exit check — professors' median mentor score "
|
||||
f"({prof['median']}) > researchers' ({res['median']}): "
|
||||
f"{'PASS' if ok else 'FAIL'}")
|
||||
report["m1_exit_mentor_check"] = "PASS" if ok else "FAIL"
|
||||
|
||||
# per-person detail for eyeballing
|
||||
print("\n=== per-person (sorted by mentor score) ===")
|
||||
everyone = [r for rows in by_status.values() for r in rows]
|
||||
for r in sorted(everyone, key=lambda x: x["sub_scores"]["mentor"], reverse=True):
|
||||
status = next(s for s, rows in by_status.items() if r in rows)
|
||||
print(f" {r['sub_scores']['mentor']:.3f} {status:<11} {r['career_bucket']:<12}"
|
||||
f" juniors={r['juniors_mentored']:>3} laj={r['last_author_with_junior_first']:>3}"
|
||||
f" {r['name']} ({r['discipline']})")
|
||||
|
||||
out = Path(args.cache_dir) / f"validation_{short}.json"
|
||||
with open(out, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(report, f, ensure_ascii=False, indent=2)
|
||||
print(f"\nReport -> {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,80 @@
|
||||
# News → OpenAlex topic mapping
|
||||
|
||||
Batch counterpart to `news.logic._match_topics_for_keywords`, which matches an
|
||||
article's keywords on every detail request without persisting the result. This
|
||||
script maps the LLM-extracted `keywords` of the enriched articles in
|
||||
`aktuell_postproc` to OpenAlex topics via the backend's
|
||||
`/api/topics/vector-search` endpoint, and persists one document per
|
||||
(article, keyword) pair into an output index with the explicit mapping from
|
||||
`news_mapping.py`:
|
||||
|
||||
```json
|
||||
{
|
||||
"news_id": "...",
|
||||
"keyword": "<one of the article's keywords>",
|
||||
"source_index": "aktuell_postproc",
|
||||
"source_field": "keywords",
|
||||
"topic_matches": [
|
||||
{
|
||||
"rank": 1,
|
||||
"topic_id": "...",
|
||||
"topic_display_name": "...",
|
||||
"subfield": "...",
|
||||
"field": "...",
|
||||
"domain": "...",
|
||||
"match_score": null
|
||||
}
|
||||
],
|
||||
"match_method": "sentence_transformer",
|
||||
"model_name": "...",
|
||||
"built_at": "..."
|
||||
}
|
||||
```
|
||||
|
||||
`match_score` is `null` because the endpoint does not expose Elasticsearch
|
||||
scores; `rank` preserves the search result order.
|
||||
|
||||
This script only ever **reads** `aktuell_postproc` and writes into the separate test index. Caching the topics back into `aktuell_postproc` is done by the news detail endpoint (`news/logic.py`), not here.
|
||||
|
||||
Keywords are **not** extracted here. `background-jobs/app/sync.py` (job `news`)
|
||||
writes them into `aktuell_postproc` first, the same way the bund projects
|
||||
already carry their keyword field before `map_project_topics.py` runs.
|
||||
|
||||
The Elasticsearch plumbing (point-in-time scan, batched topic search, bulk
|
||||
indexing, retries) is imported from
|
||||
`service/scripts/projects/topic_mapper/map_project_topics.py` rather than
|
||||
duplicated — that directory must stay next to this one.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Credentials are read from `service/src/main/inse/.env` by default (override
|
||||
with `--env-file`), and the backend must be running (e.g. `./gradlew serve`)
|
||||
because the topic search goes through its API.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
python map_news_topics.py --output-index docker-job_test
|
||||
```
|
||||
|
||||
Test run against a few articles without writing anything:
|
||||
|
||||
```bash
|
||||
python map_news_topics.py --output-index docker-job_test --dry-run --max-docs 50
|
||||
```
|
||||
|
||||
Runs are resumable: (article, keyword) pairs already present in the output
|
||||
index are skipped, and each unique keyword is searched only once across all
|
||||
articles that use it. Pairs whose search failed are left unwritten so the next
|
||||
run retries them.
|
||||
|
||||
## As a background job
|
||||
|
||||
Packaged as the `news-topics` registry image (see
|
||||
`service/scripts/jobs-image/news-topics/Dockerfile`), writing into
|
||||
`aktuell_openalex_topics`. The run is uncapped; limit a run by passing
|
||||
`--max-docs N` through the job's command field.
|
||||
@@ -0,0 +1,329 @@
|
||||
|
||||
"""
|
||||
map_news_topics.py — Map news keywords to OpenAlex topics.
|
||||
|
||||
Batch counterpart to news.logic._match_topics_for_keywords. This script streams
|
||||
the enriched articles from aktuell_postproc, reads their LLM-extracted
|
||||
'keywords', matches every unique keyword against OpenAlex topics and persists
|
||||
one document per (article, keyword) pair into a separate output index:
|
||||
|
||||
{news_id, keyword, source_index, source_field, topic_matches[],
|
||||
match_method, model_name, built_at}
|
||||
|
||||
The source index is only ever read. Writing the topics back into
|
||||
aktuell_postproc is the job of the news detail endpoint, not of this script.
|
||||
|
||||
Keywords are not extracted here — sync.py (job 'news') writes them into
|
||||
aktuell_postproc, the same way the bund projects already carry their keyword
|
||||
field before map_project_topics.py runs.
|
||||
|
||||
The run is resumable: (article, keyword) pairs already present in the output
|
||||
index are skipped, so an interrupted run can simply be restarted. Each unique
|
||||
keyword is searched only once, across all articles that use it.
|
||||
|
||||
Usage:
|
||||
python map_news_topics.py --output-index docker-job_test
|
||||
|
||||
Requires ELASTICSEARCH_INSE_URL/ELASTICSEARCH_INSE_API_KEY in the environment
|
||||
or in the service .env, plus a running backend serving
|
||||
/api/topics/vector-search (e.g. ./gradlew serve).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "projects" / "topic_mapper"))
|
||||
import map_project_topics as base
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from news_mapping import NEWS_TOPICS_MAPPING
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SOURCE_INDEX = "aktuell_postproc"
|
||||
KEYWORD_FIELD = "keywords"
|
||||
NEWS_ID_FIELD = "news_id"
|
||||
|
||||
|
||||
async def ensure_index(index: str, cluster: str) -> None:
|
||||
"""Creates the output index with the explicit mapping if it does not exist."""
|
||||
url, headers = base.es_headers(cluster)
|
||||
client = base.get_http_client()
|
||||
|
||||
response = await client.head(f"{url}/{index}", headers=headers)
|
||||
if response.status_code == 200:
|
||||
logger.info("Output index '%s' already exists.", index)
|
||||
return
|
||||
|
||||
response = await client.put(
|
||||
f"{url}/{index}", json={"mappings": NEWS_TOPICS_MAPPING}, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
logger.info("Created output index '%s' with explicit mapping.", index)
|
||||
|
||||
|
||||
def output_doc_id(news_id: str, keyword: str) -> str:
|
||||
"""Stable id per (article, keyword) pair.
|
||||
|
||||
Derived from news_id rather than the aktuell_postproc document id, so a
|
||||
reindex of the postproc index does not duplicate the mappings.
|
||||
"""
|
||||
digest = hashlib.sha1(keyword.encode("utf-8")).hexdigest()[:12]
|
||||
return f"{news_id}::{digest}"
|
||||
|
||||
|
||||
async def fetch_source_entries(cluster: str, max_docs: int | None) -> dict[str, tuple[str, str]]:
|
||||
"""Returns output_doc_id -> (news_id, keyword) for every enriched article."""
|
||||
entries: dict[str, tuple[str, str]] = {}
|
||||
total = 0
|
||||
docs_with_keywords = 0
|
||||
|
||||
async for hit in base.scan(
|
||||
index=SOURCE_INDEX,
|
||||
cluster=cluster,
|
||||
query={"exists": {"field": KEYWORD_FIELD}},
|
||||
source=[NEWS_ID_FIELD, KEYWORD_FIELD],
|
||||
):
|
||||
total += 1
|
||||
doc_source = hit.get("_source", {})
|
||||
keywords = base.extract_text_values(doc_source, KEYWORD_FIELD)
|
||||
news_id = doc_source.get(NEWS_ID_FIELD)
|
||||
if keywords and news_id:
|
||||
docs_with_keywords += 1
|
||||
for keyword in keywords:
|
||||
entries[output_doc_id(news_id, keyword)] = (news_id, keyword)
|
||||
if total % 50000 == 0:
|
||||
logger.info("Scanned %d source documents...", total)
|
||||
if max_docs and total >= max_docs:
|
||||
logger.info("Stopping scan at --max-docs=%d.", max_docs)
|
||||
break
|
||||
|
||||
logger.info(
|
||||
"Scanned %d documents from '%s', %d with non-empty '%s' (%d article/keyword pairs).",
|
||||
total,
|
||||
SOURCE_INDEX,
|
||||
docs_with_keywords,
|
||||
KEYWORD_FIELD,
|
||||
len(entries),
|
||||
)
|
||||
return entries
|
||||
|
||||
|
||||
async def run(args: argparse.Namespace) -> None:
|
||||
built_at = datetime.now(UTC).isoformat()
|
||||
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
|
||||
|
||||
await base.check_backend(args.api_base_url)
|
||||
|
||||
if not args.dry_run:
|
||||
await ensure_index(index=args.output_index, cluster=args.output_cluster)
|
||||
|
||||
entries = await fetch_source_entries(cluster=args.source_cluster, max_docs=args.max_docs)
|
||||
if not entries:
|
||||
logger.warning("No keywords in '%s' — run the 'news' job first.", SOURCE_INDEX)
|
||||
return
|
||||
|
||||
if args.overwrite:
|
||||
logger.info("--overwrite: re-mapping every pair, existing documents are replaced.")
|
||||
covered = set()
|
||||
else:
|
||||
covered = await base.fetch_covered_doc_ids(
|
||||
index=args.output_index, cluster=args.output_cluster
|
||||
)
|
||||
pending = {doc_id: entry for doc_id, entry in entries.items() if doc_id not in covered}
|
||||
logger.info(
|
||||
"Coverage: %d/%d pairs already in '%s', %d still to be processed.",
|
||||
len(entries) - len(pending),
|
||||
len(entries),
|
||||
args.output_index,
|
||||
len(pending),
|
||||
)
|
||||
if not pending:
|
||||
logger.info("Nothing left to process.")
|
||||
return
|
||||
|
||||
docs_by_keyword: dict[str, list[tuple[str, str]]] = {}
|
||||
for doc_id, (news_id, keyword) in pending.items():
|
||||
docs_by_keyword.setdefault(keyword, []).append((doc_id, news_id))
|
||||
unique_keywords = sorted(docs_by_keyword)
|
||||
logger.info(
|
||||
"%d unique keywords cover the %d pending pairs.", len(unique_keywords), len(pending)
|
||||
)
|
||||
|
||||
backup_docs: list[dict] = []
|
||||
docs_done = 0
|
||||
keywords_done = 0
|
||||
|
||||
for start in range(0, len(unique_keywords), args.text_batch_size):
|
||||
chunk = unique_keywords[start : start + args.text_batch_size]
|
||||
matches_by_keyword = await base.match_keywords(
|
||||
chunk,
|
||||
api_base_url=args.api_base_url,
|
||||
top_k=args.top_k,
|
||||
search_type=args.search_type,
|
||||
)
|
||||
|
||||
documents = []
|
||||
for keyword in chunk:
|
||||
if keyword not in matches_by_keyword:
|
||||
continue # search failed — left for the next run
|
||||
for doc_id, news_id in docs_by_keyword[keyword]:
|
||||
documents.append(
|
||||
(
|
||||
doc_id,
|
||||
{
|
||||
"news_id": news_id,
|
||||
"keyword": keyword,
|
||||
"source_index": SOURCE_INDEX,
|
||||
"source_field": KEYWORD_FIELD,
|
||||
"topic_matches": matches_by_keyword[keyword],
|
||||
"match_method": base.MATCH_METHOD,
|
||||
"model_name": model_name,
|
||||
"built_at": built_at,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
if documents and not args.dry_run:
|
||||
await base.bulk_index(
|
||||
index=args.output_index, cluster=args.output_cluster, documents=documents
|
||||
)
|
||||
if args.output:
|
||||
backup_docs.extend(doc for _, doc in documents)
|
||||
|
||||
keywords_done += len(chunk)
|
||||
docs_done += len(documents)
|
||||
logger.info(
|
||||
"Progress: %d/%d keywords, %d/%d pending pairs indexed into '%s'.",
|
||||
keywords_done,
|
||||
len(unique_keywords),
|
||||
docs_done,
|
||||
len(pending),
|
||||
args.output_index,
|
||||
)
|
||||
|
||||
skipped = len(pending) - docs_done
|
||||
if skipped:
|
||||
logger.warning(
|
||||
"%d pairs were NOT indexed due to failed searches — rerun the script to retry.",
|
||||
skipped,
|
||||
)
|
||||
|
||||
if args.output:
|
||||
output_path = Path(args.output)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
output_path.write_text(
|
||||
json.dumps(backup_docs, indent=2, ensure_ascii=False), encoding="utf-8"
|
||||
)
|
||||
logger.info("Wrote local JSON backup (%d documents) to %s", len(backup_docs), output_path)
|
||||
|
||||
logger.info(
|
||||
"Done. %d documents indexed this run, %d covered in total.",
|
||||
docs_done,
|
||||
len(covered) + docs_done,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Map the keywords of enriched news articles to OpenAlex topics.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=(
|
||||
"Examples:\n"
|
||||
" python map_news_topics.py --output-index docker-job_test\n"
|
||||
" python map_news_topics.py --output-index docker-job_test --dry-run --max-docs 50"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-index", required=True, help="Index to persist the topic mappings into"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--source-cluster",
|
||||
default="inse",
|
||||
choices=["inse", "nes"],
|
||||
help=f"Cluster holding '{SOURCE_INDEX}' (default: inse)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-cluster",
|
||||
default="inse",
|
||||
choices=["inse", "nes"],
|
||||
help="Cluster of the output index (default: inse)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--api-base-url",
|
||||
default=base.DEFAULT_API_BASE_URL,
|
||||
help=f"Base URL of the running backend (default: {base.DEFAULT_API_BASE_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--top-k",
|
||||
type=int,
|
||||
default=1,
|
||||
help=(
|
||||
"Number of topic matches per keyword (default: 1, matching the single "
|
||||
"match the news detail endpoint shows). Only truncates the result list; "
|
||||
"ranking is unaffected."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--search-type",
|
||||
default="hybrid",
|
||||
choices=["hybrid", "semantic"],
|
||||
help="Topic search type, mirrors vector_search_topics (default: hybrid)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--text-batch-size",
|
||||
type=int,
|
||||
default=base.TEXT_BATCH_SIZE,
|
||||
help=f"Unique keywords searched per chunk (default: {base.TEXT_BATCH_SIZE})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--env-file",
|
||||
default=str(base.DEFAULT_ENV_FILE),
|
||||
help=f"Path to a .env with Elasticsearch credentials (default: {base.DEFAULT_ENV_FILE})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-docs",
|
||||
type=int,
|
||||
default=None,
|
||||
help=f"Stop scanning '{SOURCE_INDEX}' after N documents (for test runs)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
default=None,
|
||||
help="Optional path for a local JSON backup of the documents built this run",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--overwrite",
|
||||
action="store_true",
|
||||
help=(
|
||||
"Re-map pairs that are already in the output index instead of skipping "
|
||||
"them; document ids are deterministic, so they are replaced in place "
|
||||
"(use after changing --top-k or --search-type)"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Build the mapping without creating/writing the output index",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.env_file and Path(args.env_file).exists():
|
||||
load_dotenv(dotenv_path=args.env_file)
|
||||
|
||||
asyncio.run(run(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Elasticsearch mapping for news -> OpenAlex topic mapping indices.
|
||||
|
||||
One document per (news article, keyword) pair. Articles in aktuell_postproc
|
||||
carry up to KEYWORD_LIMIT keywords each, so an article normally yields
|
||||
several documents.
|
||||
"""
|
||||
|
||||
NEWS_TOPICS_MAPPING = {
|
||||
"properties": {
|
||||
"news_id": {"type": "keyword"},
|
||||
"keyword": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
||||
"source_index": {"type": "keyword"},
|
||||
"source_field": {"type": "keyword"},
|
||||
"topic_matches": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"rank": {"type": "integer"},
|
||||
"topic_id": {"type": "keyword"},
|
||||
"topic_display_name": {"type": "keyword"},
|
||||
"subfield": {"type": "keyword"},
|
||||
"field": {"type": "keyword"},
|
||||
"domain": {"type": "keyword"},
|
||||
"match_score": {"type": "float"},
|
||||
},
|
||||
},
|
||||
"match_method": {"type": "keyword"},
|
||||
"model_name": {"type": "keyword"},
|
||||
"built_at": {"type": "date"},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
httpx>=0.27
|
||||
python-dotenv>=1.0
|
||||
@@ -3,10 +3,8 @@
|
||||
# See documentation in:
|
||||
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
|
||||
|
||||
from scrapy import signals
|
||||
|
||||
# useful for handling different item types with a single interface
|
||||
from itemadapter import is_item, ItemAdapter
|
||||
from scrapy import signals
|
||||
|
||||
|
||||
class AktuellSpiderMiddleware:
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
|
||||
# useful for handling different item types with a single interface
|
||||
from itemadapter import ItemAdapter
|
||||
|
||||
|
||||
class AktuellPipeline:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import scrapy
|
||||
|
||||
|
||||
class LinksCrawler(scrapy.Spider):
|
||||
name = "aktuell-links"
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import scrapy
|
||||
import json
|
||||
from scrapy.linkextractors import LinkExtractor
|
||||
import os
|
||||
|
||||
import scrapy
|
||||
from scrapy.linkextractors import LinkExtractor
|
||||
|
||||
|
||||
class MetaDataCrawler(scrapy.Spider):
|
||||
name = "aktuell-metadata"
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.webdriver.firefox.options import Options
|
||||
from random import randint
|
||||
import time
|
||||
import sys
|
||||
import time
|
||||
from random import randint
|
||||
|
||||
from elasticsearch import Elasticsearch
|
||||
from selenium import webdriver
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.firefox.options import Options
|
||||
|
||||
es = Elasticsearch()
|
||||
|
||||
@@ -32,7 +33,7 @@ def getLinks(link, driver):
|
||||
elem = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b").text
|
||||
if elem == "Zurück zum Gesamtüberblick":
|
||||
break
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
break
|
||||
|
||||
# get date
|
||||
@@ -45,7 +46,7 @@ def getLinks(link, driver):
|
||||
link = ""
|
||||
try:
|
||||
link = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b/a").get_attribute('href')
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
continue
|
||||
|
||||
links.append(link)
|
||||
@@ -67,17 +68,17 @@ def getData(driver, link, date, date_year, date_num):
|
||||
subtitle = ""
|
||||
try:
|
||||
subtitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h3").text
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
maintitle = ""
|
||||
try:
|
||||
maintitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h2").text
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
redaktion = ""
|
||||
try:
|
||||
redaktion = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[2]").text
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
author = ""
|
||||
if redaktion != "":
|
||||
@@ -86,7 +87,7 @@ def getData(driver, link, date, date_year, date_num):
|
||||
main_content = ""
|
||||
try:
|
||||
main_content = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[1]").text
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
|
||||
full_content = main_content
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def run_command(command, cwd=None):
|
||||
"""Run a shell command and exit if it fails."""
|
||||
result = subprocess.run(command,
|
||||
@@ -12,11 +18,27 @@ def run_command(command, cwd=None):
|
||||
#capture_output=True, #supresses output from subprocess
|
||||
text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"Command failed: {command}")
|
||||
print("Error output:\n", result.stderr)
|
||||
logger.error(f"Command failed: {command}")
|
||||
logger.error(f"Error output:\n{result.stderr}")
|
||||
sys.exit(result.returncode)
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Crawl the UDE 'aktuell' news pages and upload the articles to Elasticsearch."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--skip-upload",
|
||||
action="store_true",
|
||||
help="Only crawl into out/*.json and never connect to Elasticsearch",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-items",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Stop each spider after N items (for short test runs)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
base_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
@@ -31,19 +53,27 @@ if __name__ == "__main__":
|
||||
output_file_meta = os.path.join(out_dir, "meta.json")
|
||||
|
||||
|
||||
print("Running Scrapy link crawler...")
|
||||
run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"", cwd=crawler_dir)
|
||||
limit = f" -s CLOSESPIDER_ITEMCOUNT={args.max_items}" if args.max_items else ""
|
||||
|
||||
print("Running Scrapy meta crawler...")
|
||||
run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"", cwd=crawler_dir)
|
||||
logger.info("Running Scrapy link crawler...")
|
||||
run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"{limit}", cwd=crawler_dir)
|
||||
|
||||
print("Running upload script")
|
||||
run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir)
|
||||
logger.info("Running Scrapy meta crawler...")
|
||||
run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"{limit}", cwd=crawler_dir)
|
||||
|
||||
if args.skip_upload:
|
||||
logger.info("Skipping upload (--skip-upload): Elasticsearch was not contacted.")
|
||||
else:
|
||||
logger.info("Running upload script")
|
||||
run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir)
|
||||
|
||||
end_time = time.time()
|
||||
runtime_seconds = end_time - start_time
|
||||
runtime_hours = runtime_seconds / 3600
|
||||
|
||||
print(f"Runtime: {runtime_hours:.2f} hours")
|
||||
print("Finished crawling and uploading UDE news articles.")
|
||||
runtime_hours = runtime_seconds / 3600
|
||||
|
||||
logger.info(f"Runtime: {runtime_hours:.2f} hours")
|
||||
if args.skip_upload:
|
||||
logger.info("Finished crawling UDE news articles (no upload).")
|
||||
else:
|
||||
logger.info("Finished crawling and uploading UDE news articles.")
|
||||
|
||||
|
||||
@@ -1,231 +1,39 @@
|
||||
from elasticsearch import Elasticsearch
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
from datetime import datetime
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
|
||||
# elasticsearch-connection should be adjusted
|
||||
# uni-server
|
||||
es = Elasticsearch()
|
||||
import requests
|
||||
|
||||
index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# The INSE key is index-scoped and can't hit cluster endpoints (e.g. GET /), so
|
||||
# the elasticsearch client's ping/product-check would 403. We talk to the index
|
||||
# endpoint directly over HTTP with the ApiKey header, like the other jobs do.
|
||||
ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200").rstrip("/")
|
||||
ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY")
|
||||
# Default is a test index — you lack rights to push to the production index;
|
||||
# contact the ES admin for that. Override via NEWS_UPLOAD_INDEX.
|
||||
# The target index is never created here: an index that doesn't exist yet gets
|
||||
# ES dynamic mapping, without the searchabilityAnalyzer the search relies on.
|
||||
# Create it with the proper mapping before pointing a run at a new index.
|
||||
INDEX_NAME = os.getenv("NEWS_UPLOAD_INDEX", "aktuell-test")
|
||||
|
||||
# checks if elastic is up and creates the index if not already done
|
||||
def check_elastic():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
_session = requests.Session()
|
||||
_session.headers.update({"Content-Type": "application/json"})
|
||||
if ES_API_KEY:
|
||||
_session.headers.update({"Authorization": f"ApiKey {ES_API_KEY}"})
|
||||
|
||||
if not es.indices.exists(index=index_name):
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"searchabilityAnalyzer": {
|
||||
"type": "custom",
|
||||
"tokenizer": "standard",
|
||||
"filter": [
|
||||
"lowercase",
|
||||
"asciifolding"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mappings = {
|
||||
"properties": {
|
||||
"subtitle": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"maintitle": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"author": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"date": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"date_year": {
|
||||
"type": "long",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"date_full": {
|
||||
"type": "long",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"intro_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"main_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"further_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"redaktion": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"full_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags_nested": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"tag": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 250
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
#"links": {
|
||||
# "type": "text",
|
||||
# "analyzer": "searchabilityAnalyzer",
|
||||
# "search_analyzer": "searchabilityAnalyzer",
|
||||
# "fields": {
|
||||
# "keyword": {
|
||||
# "type": "keyword",
|
||||
# "ignore_above": 256
|
||||
# }
|
||||
# }
|
||||
#},
|
||||
"links_nested": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"url": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 250
|
||||
}
|
||||
}
|
||||
},
|
||||
"text": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 250
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
|
||||
def upload(path):
|
||||
with open(path, "r", encoding='utf-8') as json_file:
|
||||
|
||||
with open(path, "r", encoding="utf-8") as json_file:
|
||||
try:
|
||||
json_loaded = json.load(json_file)
|
||||
|
||||
uploaded = 0
|
||||
for news in json_loaded:
|
||||
time.sleep(10 / 1000)
|
||||
id = (str(news["date"]) + "_" + str(news["author"]) + "_" + str(news["maintitle"])).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "")
|
||||
@@ -241,7 +49,7 @@ def upload(path):
|
||||
for p in range(len(tags)):
|
||||
tags_nested.append({"tag": tags[p]})
|
||||
|
||||
dict = {
|
||||
document = {
|
||||
"subtitle": news["subtitle"],
|
||||
"maintitle": news["maintitle"],
|
||||
"tags": news["tags"],
|
||||
@@ -255,21 +63,25 @@ def upload(path):
|
||||
"tags_nested": tags_nested,
|
||||
"date_year": news["date_year"],
|
||||
"date_full": news["date_full"],
|
||||
#"links": news["links"],
|
||||
"links_nested": links_nested,
|
||||
"url": news["url"]
|
||||
}
|
||||
|
||||
es.index(index=index_name, id=id, document=dict)
|
||||
response = _session.put(
|
||||
f"{ES_URL}/{INDEX_NAME}/_doc/{quote(id, safe='')}",
|
||||
json=document,
|
||||
)
|
||||
response.raise_for_status()
|
||||
uploaded += 1
|
||||
|
||||
logger.info(f"Uploaded {uploaded} news articles to '{INDEX_NAME}'.")
|
||||
|
||||
except Exception as e:
|
||||
print("--- Failed to upload news.")
|
||||
print(e)
|
||||
logger.error(f"Failed to upload news: {e}")
|
||||
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
check_elastic()
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit("No path given.")
|
||||
upload(sys.argv[1])
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user