File size: 42,119 Bytes
a81729c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import set_seed\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from collections import Counter\n",
"import numpy as np\n",
"import random\n",
"import torch"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"three fields in each prompt: question, bot, task\n",
"\n",
"input to the model is:\n",
"```\n",
"<s>human\n",
"[question]\n",
"<s>bot\n",
"[bot]\n",
"```\n",
"where a question is\n",
"```\n",
"[program]\n",
"\n",
"[question]\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"debug = ''\n",
"in_dir = f\"/Users/zzy/Documents/graph{debug}\"\n",
"out_dir = f\"/Users/zzy/Documents/graph{debug}/instruction\"\n",
"no_return_sample_num = 20 if len(debug) > 0 else 40000\n",
"\n",
"figsize = (24, 16)\n",
"fontsize = 28\n",
"fontsize_tick = 16\n",
"\n",
"def filter_df(df, n=None):\n",
" try:\n",
" n = n if n is not None else no_return_sample_num\n",
" return pd.concat([df[df.source.apply(lambda x: 'return ' in x)], df[df.source.apply(lambda x: 'return ' not in x)].sample(n)]).reset_index(drop=True)\n",
" except:\n",
" return df\n",
"\n",
"def capitalize(s: str):\n",
" return s[0].upper() + s[1:]\n",
"\n",
"def replace_digit(s: str):\n",
" return s.replace('10', 'ten').replace('1', 'one').replace('2', 'two').replace('3', 'three').replace('4', 'four').replace('5', 'five').replace('6', 'six').replace('7', 'seven').replace('8', 'eight').replace('9', 'nine')\n",
"\n",
"def print_df(df, n=10):\n",
" for i in range(n):\n",
" print(df.loc[i].question)\n",
" print(df.loc[i].bot)\n",
" print('---'*10)\n",
"\n",
"graph_type_map = {'AST': 'abstract syntax tree', 'DFG': 'data flow graph'}\n",
"NODE_TYPES = [\n",
" 'assignment expression',\n",
" 'basic block',\n",
" 'binary expression',\n",
" 'break statement',\n",
" 'call expression',\n",
" 'catch clause',\n",
" 'class expression',\n",
" 'compile unit',\n",
" 'conditional expression',\n",
" 'continue statement',\n",
" 'export statement',\n",
" 'for statement',\n",
" 'function expression',\n",
" 'identifier expression', \n",
" 'if statement',\n",
" 'import expression',\n",
" 'key value parameter',\n",
" 'literal expression',\n",
" 'member access',\n",
" 'new expression',\n",
" 'new with type expression',\n",
" 'object expression',\n",
" 'object property',\n",
" 'parameter',\n",
" 'Python delete',\n",
" 'Python with',\n",
" 'Python with expression clause',\n",
" 'Python yield expression',\n",
" 'range statement',\n",
" 'return statement',\n",
" 'scope',\n",
" 'spread collection expression',\n",
" 'spread dictionary expression',\n",
" 'super expression',\n",
" 'switch case',\n",
" 'switch statement',\n",
" 'this expression',\n",
" 'throw statement',\n",
" 'try statement',\n",
" 'tuple expression',\n",
" 'unary expression',\n",
" 'variable declaration',\n",
" 'while statement'\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ph stands for place holder\n",
"ph1 = 'aohg981thgboir2bnjosi1839r8g9udnfv,mqwfo'\n",
"ph2 = 'io12i3ru9ginal90109ja-efi1-3gasd130gn0wa9'\n",
"ph3 = '2091rng09wegnb2p09jojmpzf,k[2e00-jmaa]'\n",
"ph4 = '0391gnea-g0-jr0aegbm[afk0-249jgps]waeg0'\n",
"ph5 = 'io1hngi0enriqgpgv]139gonpiamofj10onem;alf'\n",
"ph_list = [ph1, ph2, ph3, ph4, ph5]\n",
"punc_list = [\",\", \"?\", \".\", \";\", \"'s\"]\n",
"\n",
"def replace_place_holder(s, node_text, placeholder=\"{node}\"):\n",
" # this function injects a multi-line code snippet into the template\n",
"\n",
" if placeholder not in s:\n",
" return s\n",
"\n",
" # 1. remove the white spaces around {node} placeholder\n",
" s = s.replace(f\"{placeholder} \", f\"{placeholder}\").replace(f\" {placeholder}\", f\"{placeholder}\")\n",
" for punc in punc_list:\n",
" s = s.replace(f\"{placeholder}{punc} \", f\"{placeholder}{punc}\")\n",
" \n",
" # 2. injects the code, but first replace patterns like '\\n.' in both the code and template (the template may contain previously injected code)\n",
" for ph, punc in zip(ph_list, punc_list):\n",
" node_text = node_text.replace(f\"\\n{punc}\", ph)\n",
" s = s.replace(f\"\\n{punc}\", ph)\n",
" s = s.replace(placeholder, node_text)\n",
"\n",
" # 3. replace patterns like \"\\n.\" caused by the template\n",
" for punc in punc_list:\n",
" s = s.replace(f\"\\n{punc}\", f\"{punc}\\n\")\n",
"\n",
" # 4. replace the placerholders inserted in step 2\n",
" for ph, punc in zip(ph_list, punc_list):\n",
" s = s.replace(ph, f\"\\n{punc}\")\n",
" return s"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## node classification"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"questions = [\n",
" 'In the {graph} of this {lang} program, what is the type of this node: {node}.',\n",
" 'Tell me the node type of {node} in the {graph} of this {lang} program.',\n",
" 'What is the node type of {node} in the {graph} of this {lang} program',\n",
" \"In the {graph} of the provided {lang} program, could you identify the type of the node {node}?\",\n",
" \"What kind of node is {node} in the {graph} of this {lang} program?\",\n",
" \"Can you classify the node {node} in the {graph} of this {lang} program?\",\n",
" \"What category does the node {node} fall under in the {graph} of this {lang} program?\",\n",
" \"Regarding the {graph} of this {lang} program, what is the classification of the node {node}?\",\n",
" \"In the context of the {graph} of this {lang} program, what is the nature of the node identified as {node}?\",\n",
" \"Could you tell me what the node {node} represents in the {graph} of this {lang} program?\",\n",
" \"I'm curious, what type of node is {node} in the {graph} of the {lang} program presented?\",\n",
" \"What is the designation of the node {node} within the {graph} of this {lang} program?\",\n",
" \"Could you specify the node type for {node} in the {graph} of this particular {lang} program?\",\n",
" 'Determine the node type of {node} in the {graph} of this {lang} program.',\n",
"]\n",
"answers = [\n",
" \"This node, {node}, is classified as a {answer}.\",\n",
" \"The node {node} is a {answer}.\",\n",
" \"This node is identified as a {answer}.\",\n",
" \"It's a {answer}.\",\n",
" \"Regarding the node {node}, it falls under the category of a {answer}.\",\n",
" \"{node} is classified as a {answer} in the {graph} of this program.\",\n",
" \"The classification of the node {node} is a {answer}.\",\n",
" \"Within the {graph} of this program, {node} is a {answer} type of node.\",\n",
" \"As for the node identified as {node}, it's considered a {answer}.\",\n",
" \"The node {node} is of the {answer} variety.\",\n",
" 'The type of this node is {answer}.',\n",
" 'The given node is a {answer}.',\n",
" \"{answer}.\",\n",
" \"{answer}\",\n",
"]\n",
"print(len(questions), len(set(questions)))\n",
"print(len(answers), len(set(answers)))\n",
"assert all(a.count('{answer}') == 1 for a in answers)\n",
"assert all(a.count('{graph}') == 1 for a in questions)\n",
"assert all(a.count('{lang}') == 1 for a in questions)\n",
"\n",
"bots = [a for a in answers]\n",
"prompts = [[q, b] for q in questions for b in bots]\n",
"print(len(prompts))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"set_seed(0)\n",
"results = {}\n",
"for lang in ['Java', 'Python']:\n",
" for graph in ['DFG', 'AST']:\n",
" result = []\n",
" df = pd.read_json(f\"{in_dir}/{lang}_{graph}.jsonl\", lines=True)\n",
" if lang == 'Python':\n",
" df = filter_df(df)\n",
"\n",
" question, bot = [], []\n",
" for i in range(len(df)):\n",
"\n",
" # filter out nodes that occur multiple times in the source code\n",
" node_texts = df.loc[i]['text']\n",
" node_ids = df.loc[i]['node_ids']\n",
" source = df.loc[i]['source']\n",
" assert len(node_ids) == len(node_texts)\n",
"\n",
" occurrences = np.array([source.count(t) for t in node_texts])\n",
" nodes_single_occurrence = np.where(occurrences == 1)[0]\n",
"\n",
" # we sample 1 node from each program\n",
" nodes = np.random.choice(nodes_single_occurrence, 1)\n",
" for node in nodes:\n",
" node_text = node_texts[node]\n",
" node_id = node_ids[node]\n",
" node_type = NODE_TYPES[node_id]\n",
"\n",
" p = random.sample(prompts, 1)[0]\n",
" p = [s.replace('{graph}', f\"{graph_type_map[graph]}\").replace('{lang}', f\"{lang}\") for s in p]\n",
" \n",
" response = p[1]\n",
" # deal with answer first in the response before plugging in the node text to avoid replacing something in the code\n",
" if any(node_type.startswith(l) for l in 'aeio'):\n",
" response = response.replace(' a ', ' an ')\n",
" response = response.replace('{answer}', node_type)\n",
" response = capitalize(response)\n",
" \n",
" if '\\n' in node_text:\n",
" node_text = f\"\\n```\\n{node_text}\\n```\\n\"\n",
" assert ph1 not in node_text and ph2 not in node_text and ph3 not in node_text and ph4 not in node_text and ph5 not in node_text\n",
" q = replace_place_holder(p[0], node_text)\n",
" response = replace_place_holder(response, node_text)\n",
" else:\n",
" node_text = f\"`{node_text}`\"\n",
" q = p[0].replace('{node}', node_text)\n",
" response = response.replace('{node}', node_text)\n",
"\n",
" source = source.strip('\\n')\n",
" q = f\"```\\n{source}\\n```\\n\\n{q}\"\n",
" question.append(q)\n",
" bot.append(response)\n",
" result.append(node_id)\n",
"\n",
" df['question'] = question\n",
" df['bot'] = bot\n",
" df = df.drop(columns={'text', 'source', 'node_ids', 'edge_index'})\n",
" df.to_json(f\"{out_dir}/Node_Classification_{lang}_{graph}.jsonl\", orient='records', lines=True)\n",
" results[f\"{lang}-{graph}\"] = result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## parent node"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"questions = [\n",
" 'In the {graph} of this {lang} program, what is the parent node of this {node_type}: {node}.',\n",
" 'What is the parent of {node_type} {node} in the {graph} of this {lang} program?',\n",
" 'What is the parent node of {node_type} {node} in the {graph} of this {lang} program?',\n",
" 'Based on the {graph} of this {lang} program, identify the parent of {node_type} {node}.',\n",
" 'Based on the {graph} of this {lang} program, identify the parent of this {node_type}: {node}.',\n",
" 'Identify the parent of {node_type} {node} in the {graph} of this {lang} program.',\n",
" \"In the {graph} of the {lang} program presented, what is the predecessor of {node_type} {node}?\",\n",
" \"What node acts as the parent to {node_type} {node} in the {graph} of the displayed {lang} program?\",\n",
" \"Can you determine the parent node of {node_type} {node} in the {graph} of this {lang} program?\",\n",
" \"Which node is directly above {node_type} {node} in the hierarchy of the {graph} of the provided {lang} program?\",\n",
" \"Whose child is {node_type} {node} within the {graph} of this {lang} program?\",\n",
" \"What is the immediate ancestor of the {node_type} {node} in the {graph} of this {lang} program?\",\n",
" \"Regarding the {graph} of this {lang} program, can you point out the parent of {node_type} {node}?\",\n",
" \"In terms of graph theory, what is the parent of the {node_type} {node} in the {graph} of this {lang} program?\",\n",
" \"Who has the parental role for {node_type} {node} in the {graph}'s topology of this {lang} program?\",\n",
" \"For {node_type} {node} in the {graph} of the given {lang} program, which node supplies the incoming edge?\",\n",
"]\n",
"answers1 = [\n",
" \"In the {graph} of the given {lang} program, the parent of the given {node_type} is {parent}, which is a {parent_type}.\",\n",
" \"This {node_type}'s parent is the {parent_type} {parent}.\",\n",
" \"The given {node_type}'s parent in the {graph} of this {lang} program is the {parent_type} {parent}.\",\n",
" \"The parent of {node_type} {node} in the {graph} of this {lang} program is identified as {parent}, categorized as a {parent_type}.\",\n",
" \"In the structure of the {graph} of this {lang} program, {node_type} {node} finds its parent in node {parent}, which is a {parent_type}.\",\n",
" \"Node {parent}, a {parent_type}, serves as the parent to {node_type} {node} in the {graph} of this {lang} program.\",\n",
" \"As per the hierarchy in the {graph}, the {parent_type} node {parent} is the direct predecessor to {node_type} {node}.\",\n",
" \"Upon inspection, it is clear that the parent of {node_type} {node} is the {parent_type} {parent}.\",\n",
" \"The {node_type} {node} is immediately descended from {parent}, a {parent_type} in the {graph} of this {lang} program.\",\n",
" \"{node_type} {node}'s parental node is determined to be {parent}, which falls into the category of {parent_type}.\",\n",
" \"For {node_type} {node}, its lineage traces back to the {parent_type} node {parent} as its parent.\",\n",
" \"Within the nodal arrangement of the {graph}, {parent} is the progenitor to {node_type} {node}, having the classification of a {parent_type}.\",\n",
" \"Tracing the edges leads to confirming {parent}, a {parent_type}, as the parent of {node_type} {node}.\"\n",
"]\n",
"answers2 = [\n",
" 'This {node_type} has no parent in the {graph} of this {lang} program.',\n",
" 'This {node_type} has no parent in the {graph} of the given {lang} program.',\n",
" 'There is no edge pointing to this {node_type} in the {graph}. Therefore it does not have any parent.',\n",
" 'There is no edge pointing to this {node_type} in the {graph} of the given {lang} program. Therefore it does not have any parent.',\n",
" \"Within the confines of the {graph} of this {lang} program, {node_type} {node} does not have a parent node.\",\n",
" \"{node_type} {node} stands without a parent in the {graph}'s structure.\",\n",
" \"No parent node is associated with {node_type} {node} in the {graph} of the provided {lang} program.\",\n",
" \"A review of the code establishes that there is no preceding node to {node_type} {node} in the {graph}; it has no parent.\",\n",
" \"The {node_type} designated as {node} appears to lack a parental connection within the {graph} of this code.\",\n",
" \"In terms of graph topology, {node_type} {node} is an orphan node with no parent.\",\n",
" \"There is no edge incoming to {node_type} {node}, indicating the absence of a parent in the {graph} of this {lang} program.\",\n",
" \"After analyzing the code, it becomes evident that {node_type} {node} lacks a directly linked parent node in the {graph}.\",\n",
" \"The {graph} denotes that {node_type} {node} is disconnected from any parental lineage.\",\n",
" \"As depicted in the code, {node_type} {node} exists without a parent node to claim in the {graph}.\",\n",
"]\n",
"answers3 = [\n",
" \"There are multiple parents of this {node_type} in the {graph}:\\n\",\n",
" \"This {node_type} has more than one parent in the {graph}:\\n\"\n",
"]\n",
"print(len(questions), len(set(questions)))\n",
"print(len(answers1), len(set(answers1)))\n",
"print(len(answers2), len(set(answers2)))\n",
"print(len(answers3), len(set(answers3)))\n",
"assert all(a.count('{graph}') == 1 for a in questions)\n",
"assert all(a.count('{lang}') == 1 for a in questions)\n",
"\n",
"bots = [a for a in answers1]\n",
"bots_none = [a for a in answers2]\n",
"bots_multiple = [a for a in answers3]\n",
"prompts = [[q, b] for q in questions for b in bots]\n",
"print(len(prompts))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"set_seed(1)\n",
"\n",
"results = {}\n",
"for lang in ['Java', 'Python']:\n",
" for graph in ['DFG', 'AST']:\n",
" result = []\n",
" df = pd.read_json(f\"{in_dir}/{lang}_{graph}.jsonl\", lines=True)\n",
" if lang == 'Python':\n",
" df = filter_df(df)\n",
" \n",
" question, bot = [], []\n",
" for i in range(len(df)):\n",
"\n",
" # filter out nodes that occur multiple times in the source code\n",
" node_texts = df.loc[i]['text']\n",
" node_ids = df.loc[i]['node_ids']\n",
" source = df.loc[i]['source']\n",
" edge_index = torch.tensor(df.loc[i]['edge_index'])\n",
" assert len(node_ids) == len(node_texts)\n",
"\n",
" occurrences = np.array([source.count(t) for t in node_texts])\n",
" nodes_single_occurrence = np.where(occurrences == 1)[0]\n",
" nodes_with_parents = [n for n in nodes_single_occurrence if n in edge_index[:, 1]]\n",
" nodes_without_parents = [n for n in nodes_single_occurrence if n not in edge_index[:, 1]]\n",
" \n",
" # we roughly maintain a balanced distribution\n",
" if random.random() < 0.75 and len(nodes_with_parents) > 0:\n",
" node = random.sample(nodes_with_parents, 1)[0]\n",
" elif len(nodes_without_parents) > 0:\n",
" node = random.sample(nodes_without_parents, 1)[0]\n",
" else:\n",
" node = np.random.choice(nodes_single_occurrence, 1)[0]\n",
" \n",
" node_text = node_texts[node]\n",
" node_id = node_ids[node]\n",
" node_type = NODE_TYPES[node_id]\n",
" edge_to_node = [edge for edge in edge_index if edge[1] == node]\n",
"\n",
" p = (random.sample(prompts, 1)[0] + random.sample(bots_none, 1) + random.sample(bots_multiple, 1)).copy()\n",
" assert p[2] in bots_none\n",
" p = [s.replace('{graph}', f\"{graph_type_map[graph]}\").replace('{lang}', f\"{lang}\") for s in p]\n",
"\n",
" # deal with answer first in the response before plugging in the node text to avoid replacing something in the code\n",
" num_parents = len(edge_to_node)\n",
" response = p[2] if num_parents == 0 else (p[1] if num_parents == 1 else p[3])\n",
" response = capitalize(response.replace('{node_type}', node_type))\n",
"\n",
" if num_parents > 1:\n",
" # no problem here\n",
" for j in range(num_parents):\n",
" parent_node = edge_to_node[j][0]\n",
" parent_text = node_texts[parent_node]\n",
" parent_id = node_ids[parent_node]\n",
" parent_type = NODE_TYPES[parent_id]\n",
" if '\\n' in parent_text:\n",
" parent_text = f\"\\n```\\n{parent_text}\\n```\\n\"\n",
" response += f\"{parent_type}:{parent_text}\"\n",
" else:\n",
" parent_text = f\"`{parent_text}`\"\n",
" response += f\"{parent_type}: {parent_text}\\n\"\n",
" elif num_parents == 1:\n",
" parent_node = edge_to_node[0][0]\n",
" parent_text = node_texts[parent_node]\n",
" parent_id = node_ids[parent_node]\n",
" parent_type = NODE_TYPES[parent_id]\n",
" if any(parent_type.startswith(l) for l in 'aeio'):\n",
" response = response.replace(' a ', ' an ')\n",
" if '\\n' in parent_text:\n",
" parent_text = f\"\\n```\\n{parent_text}\\n```\\n\"\n",
" response = replace_place_holder(response, parent_text, \"{parent}\")\n",
" else:\n",
" parent_text = f\"`{parent_text}`\"\n",
" response = response.replace('{parent}', parent_text)\n",
" response = response.replace('{parent_type}', parent_type) \n",
" \n",
" # now deal with node text\n",
" assert response.count('{node}') <= 1\n",
" if '\\n' in node_text:\n",
" node_text = f\"\\n```\\n{node_text}\\n```\\n\"\n",
" # note that now response may contain \"\\n,\" patterns\n",
" q = replace_place_holder(p[0].replace('{node_type}', node_type), node_text)\n",
" response = replace_place_holder(response, node_text)\n",
" else:\n",
" node_text = f\"`{node_text}`\"\n",
" q = p[0].replace('{node_type}', node_type).replace('{node}', node_text)\n",
" response = response.replace('{node}', node_text)\n",
"\n",
" source = source.strip('\\n')\n",
" q = f\"```\\n{source}\\n```\\n\\n{q}\"\n",
" question.append(q)\n",
" bot.append(response)\n",
" result.append(num_parents)\n",
"\n",
" df['question'] = question\n",
" df['bot'] = bot\n",
" df = df.drop(columns={'text', 'source', 'node_ids', 'edge_index'})\n",
" df.to_json(f\"{out_dir}/Parent_{lang}_{graph}.jsonl\", orient='records', lines=True)\n",
" results[f\"{lang}-{graph}\"] = result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Children"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"questions = [\n",
" 'In the {graph} of this {lang} program, what are the children of this {node_type}: {node}.',\n",
" 'Identify all children of {node_type} {node} in the {graph} of this {lang} program.',\n",
" 'Find the child nodes of {node_type} {node} in the {graph} of this {lang} program.',\n",
" 'In the {graph} of this {lang} program, how many children does the {node_type} {node} have? What are they?',\n",
" \"How many children does {node_type} {node} have in the {graph} of this {lang} program? What are they?\",\n",
" 'Please find all children of {node_type} {node} in the {graph} of this {lang} program.',\n",
" 'Can you find all children of {node_type} {node} in the {graph} of this {lang} program?',\n",
" \"List all the descendant nodes of {node_type} {node} in the {graph} of this {lang} program.\",\n",
" \"What are the direct children of the {node_type} {node} in the {graph} of this {lang} program?\",\n",
" \"Can you enumerate the offspring of {node_type} {node} within the {graph} of this {lang} program?\",\n",
" \"Could you provide the list of child nodes attached to {node_type} {node} in the {graph} of this {lang} program?\",\n",
" \"Please identify the child nodes emanating from {node_type} {node} in the {graph} of this {lang} program.\",\n",
" \"Show me the child nodes of {node_type} {node} in the {graph} of this {lang} program.\",\n",
" \"What nodes are directly connected to {node_type} {node} as its children in the {graph} of this {lang} program?\",\n",
" \"I need to know all the child elements of {node_type} {node} in the {graph} of this {lang} program. Can you provide that?\",\n",
" \"Are there any nodes that directly derive from {node_type} {node} in the {graph} of this {lang} program?\",\n",
" \"Which nodes act as successors to the node tagged as {node_type} {node} in the {graph} of this {lang} program?\",\n",
" \"What are the adjacent nodes that are children of {node_type} {node} in the {graph} of this {lang} program?\",\n",
" \"Identify the nodes that are immediate successors of {node_type} {node} in the {graph} of this {lang} program.\",\n",
" \"Detail the nodes branching from {node_type} {node} in the {graph} of this {lang} program.\",\n",
" \"Reveal all nodes that are directly beneath {node_type} {node} in the topology of the {graph} of this {lang} program.\",\n",
"]\n",
"answers1 = [\n",
" \"The given {node_type} has {child_num} children in the {graph}, they are:\\n\",\n",
" \"This {node_type} has {child_num} children:\\n\",\n",
" \"{node_type} {node} has a total of {child_num} children in the {graph}, which are:\\n\",\n",
" \"There are {child_num} child nodes of {node_type} {node}, specifically:\\n\",\n",
" \"As for the children of {node_type} {node}, you will find {child_num} direct descendants:\\n\",\n",
" \"The count of {node_type} {node}'s children amounts to {child_num}. They include:\\n\",\n",
" \"Upon identification, {node_type} {node} appears to have {child_num} offspring, namely:\\n\",\n",
" \"{node_type} {node} is parent to the following {child_num} nodes:\\n\",\n",
" \"A list of the {child_num} children under {node_type} {node} is as follows:\\n\",\n",
" \"Directly under {node_type} {node}, there are {child_num} children listed as:\\n\",\n",
" \"{node_type} {node} holds the hierarchy over {child_num} child nodes, which are:\\n\",\n",
" \"{child_num} children spring from {node_type} {node}, which are given below:\\n\",\n",
"]\n",
"answers2 = [\n",
" \"This {node_type} does not have any child nodes in the {graph}.\",\n",
" \"This {node_type} does not have any children in the {graph}.\",\n",
" \"There are no children of this {node_type} in the {graph} of the given code.\",\n",
" \"The given {node_type} does not have any children in the {graph}.\",\n",
" \"After examining the code, it's determined that in the {graph} this {node_type} has no children.\",\n",
" \"{node_type} {node} stands alone with zero child nodes descending from it.\",\n",
" \"I've checked the {node_type} {node} and found it has no direct descendants.\",\n",
" \"There are no child nodes attached to {node_type} {node} in the {graph} of this program.\",\n",
" \"No descendants can be traced from this {node_type}.\",\n",
" \"The {node_type} {node} is devoid of child nodes within the {graph} of the code.\",\n",
" \"Upon inspection, no nodes emerge as children of {node_type} {node}.\",\n",
" \"{node_type} {node} exists without progeny in the hierarchical layout.\",\n",
" \"It appears {node_type} {node} has no children.\",\n",
"]\n",
"\n",
"print(len(questions), len(set(questions)))\n",
"print(len(answers1), len(set(answers1)))\n",
"print(len(answers2), len(set(answers2)))\n",
"assert all(a.count('{answer}') == 1 for a in answers)\n",
"assert all(a.count('{graph}') == 1 for a in questions)\n",
"assert all(a.count('{lang}') == 1 for a in questions)\n",
"\n",
"bots = [a for a in answers1]\n",
"bots_none = [a for a in answers2]\n",
"prompts = [[q, b] for q in questions for b in bots]\n",
"print(len(prompts))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"set_seed(2)\n",
"\n",
"results = {}\n",
"for lang in ['Java', 'Python']:\n",
" for graph in ['DFG', 'AST']:\n",
" result = []\n",
" df = pd.read_json(f\"{in_dir}/{lang}_{graph}.jsonl\", lines=True)\n",
" if lang == 'Python':\n",
" df = filter_df(df)\n",
" \n",
" question, bot = [], []\n",
" selected_idx = []\n",
" for i in range(len(df)):\n",
"\n",
" # filter out nodes that occur multiple times in the source code\n",
" node_texts = df.loc[i]['text']\n",
" node_ids = df.loc[i]['node_ids']\n",
" source = df.loc[i]['source']\n",
" edge_index = torch.tensor(df.loc[i]['edge_index'])\n",
"\n",
" occurrences = np.array([source.count(t) for t in node_texts])\n",
" nodes_single_occurrence = np.where(occurrences == 1)[0]\n",
" nodes_with_children = [n for n in nodes_single_occurrence if n in edge_index[:, 0]]\n",
" nodes_without_children = [n for n in nodes_single_occurrence if n not in edge_index[:, 0]]\n",
" \n",
" # we roughly maintain a balanced distribution\n",
" if random.random() < 0.85 and len(nodes_with_children) > 0:\n",
" node = random.sample(nodes_with_children, 1)[0]\n",
" elif len(nodes_without_children) > 0:\n",
" node = random.sample(nodes_without_children, 1)[0]\n",
" else:\n",
" node = np.random.choice(nodes_single_occurrence, 1)[0]\n",
" \n",
" node_text = node_texts[node]\n",
" node_id = node_ids[node]\n",
" node_type = NODE_TYPES[node_id]\n",
" edge_from_node = [edge for edge in edge_index if edge[0] == node]\n",
"\n",
" p = (random.sample(prompts, 1)[0] + random.sample(bots_none, 1)).copy()\n",
" assert p[1] in bots\n",
" p = [s.replace('{graph}', f\"{graph_type_map[graph]}\").replace('{lang}', f\"{lang}\") for s in p]\n",
"\n",
" num_children = len(edge_from_node)\n",
" if num_children > 10:\n",
" continue\n",
" else:\n",
" selected_idx.append(i)\n",
" response = p[2] if num_children == 0 else p[1]\n",
" response = capitalize(response.replace('{node_type}', node_type))\n",
" if num_children == 1:\n",
" response = response.replace('{child_num}', \"1\").replace('children', 'child').replace('nodes', 'node').replace('they are', 'it is').replace(' are', ' is').replace('descendants', 'descendant').replace('They include', 'It is').replace(' spring ', ' springs ')\n",
" else:\n",
" response = response.replace('{child_num}', f\"{num_children}\")\n",
" \n",
" if '\\n' in node_text:\n",
" node_text = f\"\\n```\\n{node_text}\\n```\\n\"\n",
" q = replace_place_holder(p[0].replace('{node_type}', node_type), node_text)\n",
" response = replace_place_holder(response, node_text)\n",
" else:\n",
" node_text = f\"`{node_text}`\"\n",
" q = p[0].replace('{node_type}', node_type).replace('{node}', node_text)\n",
" response = response.replace('{node}', node_text)\n",
" \n",
" for j in range(num_children):\n",
" child_node = edge_from_node[j][1]\n",
" child_text = node_texts[child_node]\n",
" child_id = node_ids[child_node]\n",
" child_type = NODE_TYPES[child_id]\n",
"\n",
" if '\\n' in child_text:\n",
" child_text = f\"\\n```\\n{child_text}\\n```\\n\"\n",
" response += f\"{child_type}:{child_text}\"\n",
" else:\n",
" child_text = f\"`{child_text}`\"\n",
" response += f\"{child_type}: {child_text}\\n\"\n",
" if num_children != len(set((node_ids[e[1]], node_texts[e[1]]) for e in edge_from_node)):\n",
" response += \"Note that there are multiple children with the same node type and literal representation.\"\n",
"\n",
" source = source.strip('\\n')\n",
" q = f\"```\\n{source}\\n```\\n\\n{q}\"\n",
" question.append(q)\n",
" bot.append(response)\n",
" result.append(num_children)\n",
"\n",
" df = df.loc[selected_idx].reset_index(drop=True)\n",
" df['question'] = question\n",
" df['bot'] = bot\n",
" df = df.drop(columns={'text', 'source', 'node_ids', 'edge_index'})\n",
" df.to_json(f\"{out_dir}/Children_{lang}_{graph}.jsonl\", orient='records', lines=True)\n",
" results[f\"{lang}-{graph}\"] = result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Edge prediction"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"questions = [\n",
" \"In the {graph} of this {lang} program, is there {edge_or_link} from {node_type1} {node1} to {node_type2} {node2}?\",\n",
" 'In the {graph} of this {lang} program, is there {edge_or_link} pointing from {node_type1} {node1} to {node_type2} {node2}?',\n",
" \"Please tell me if there is {edge_or_link} pointing from {node_type1} {node1} to {node_type2} {node2} in the {graph} of this {lang} program.\",\n",
" 'Is there {edge_or_link} from {node_type1} {node1} to {node_type2} {node2} in the {graph} of this {lang} program?',\n",
" \"Does a connection exist from {node_type1} {node1} to {node_type2} {node2} in the {graph} of this {lang} program?\",\n",
" \"In the {graph} of this {lang} program, do we have an arrow leading from {node_type1} {node1} to {node_type2} {node2}?\",\n",
" \"Is it true that {node_type1} {node1} is a predecessor of {node_type2} {node2} in the {graph} of this {lang} program?\",\n",
"]\n",
"answers1 = [\n",
" \"Yes, that is the case.\",\n",
" \"Yes, there is {edge_or_link} from {node_type1} {node1} to {node_type2} {node2}.\",\n",
" \"Yes, there is {edge_or_link} from {node_type1} {node1} to {node_type2} {node2} in the {graph} of this code.\",\n",
" \"Yes, there is {edge_or_link} pointing from {node_type1} {node1} to {node_type2} {node2} in the {graph}.\",\n",
" \"Affirmative, there exists {edge_or_link} from {node_type1} {node1} to {node_type2} {node2}.\",\n",
" \"Yes, that is the case. {node1} is directly connected to {node2}.\",\n",
"]\n",
"answers2 = [\n",
" \"No, that is not the case.\",\n",
" \"No, {node_type1} {node1} is not linked to {node_type2} {node2} by any edge in the {graph} of the given code.\",\n",
" \"No, there is no {edge_or_link} from {node_type1} {node1} to {node_type2} {node2}.\",\n",
" \"No, such {edge_or_link} is absent from the {graph}.\",\n",
" \"The code does not show {node_type1} {node1} as a predecessor to {node_type2} {node2} in the {graph}.\",\n",
"]\n",
"\n",
"print(len(questions), len(set(questions)))\n",
"print(len(answers1), len(set(answers1)))\n",
"print(len(answers2), len(set(answers2)))\n",
"assert all(a.count('{graph}') == 1 for a in questions)\n",
"assert all(a.count('{lang}') == 1 for a in questions)\n",
"\n",
"bots = [a for a in answers1]\n",
"bots_none = [a for a in answers2]\n",
"prompts = [[q, b] for q in questions for b in bots]\n",
"print(len(prompts))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"set_seed(3)\n",
"results = {}\n",
"for lang in ['Java', 'Python']:\n",
" for graph in ['DFG', 'AST']:\n",
" result = []\n",
" df = pd.read_json(f\"{in_dir}/{lang}_{graph}.jsonl\", lines=True)\n",
" if lang == 'Python':\n",
" df = filter_df(df)\n",
" \n",
" question, bot = [], []\n",
" for i in range(len(df)):\n",
"\n",
" # filter out nodes that occur multiple times in the source code\n",
" node_texts = df.loc[i]['text']\n",
" node_ids = df.loc[i]['node_ids']\n",
" source = df.loc[i]['source']\n",
" edge_index = df.loc[i]['edge_index']\n",
"\n",
" occurrences = np.array([source.count(t) for t in node_texts])\n",
" nodes_single_occurrence = np.where(occurrences == 1)[0]\n",
" edge_index_elligible = [e for e in edge_index if (e[0] in nodes_single_occurrence and e[1] in nodes_single_occurrence)]\n",
" if graph == 'AST' and random.random() > 0.1:\n",
" edge_index_elligible = [e for e in edge_index_elligible if (node_texts[e[1]] not in node_texts[e[0]])]\n",
" \n",
" # we make sure at least half the problems have positive answer\n",
" if random.random() < 0.75 and len(edge_index_elligible) > 0:\n",
" n1, n2 = random.sample(edge_index_elligible, 1)[0]\n",
" else:\n",
" n1, n2 = np.random.choice(nodes_single_occurrence, 2)\n",
" \n",
" n1_text, n2_text = node_texts[n1], node_texts[n2]\n",
" n1_type, n2_type = NODE_TYPES[node_ids[n1]], NODE_TYPES[node_ids[n2]]\n",
"\n",
" p = random.sample(prompts, 1)[0] + random.sample(bots_none, 1)\n",
" p = [s.replace('{graph}', f\"{graph_type_map[graph]}\").replace('{lang}', f\"{lang}\") for s in p]\n",
" edge_or_link = 'an edge' if random.random() < 0.5 else 'a link'\n",
" p = [s.replace('{edge_or_link}', edge_or_link) for s in p[:-1]] + [p[-1].replace('such {edge_or_link}', f\"such {edge_or_link}\").replace('{edge_or_link}', edge_or_link.split()[-1])]\n",
" \n",
" q, b = '', ''\n",
" b = p[1] if [n1, n2] in edge_index else p[2]\n",
" b = b.replace('{node_type1}', n1_type).replace('{node_type2}', n2_type)\n",
"\n",
" if '\\n' in n1_text:\n",
" n1_text = f\"\\n```\\n{n1_text}\\n```\\n\"\n",
" q = replace_place_holder(p[0].replace('{node_type1}', n1_type).replace('{node_type2}', n2_type), n1_text, \"{node1}\")\n",
" b = replace_place_holder(b, n1_text, \"{node1}\")\n",
" else:\n",
" n1_text = f\"`{n1_text}`\"\n",
" q = p[0].replace('{node_type1}', n1_type).replace('{node_type2}', n2_type).replace('{node1}', n1_text)\n",
" b = b.replace('{node1}', n1_text)\n",
" \n",
" if '\\n' in n2_text:\n",
" n2_text = f\"\\n```\\n{n2_text}\\n```\\n\"\n",
" q = replace_place_holder(q, n2_text, \"{node2}\")\n",
" b = replace_place_holder(b, n2_text, \"{node2}\")\n",
" else:\n",
" n2_text = f\"`{n2_text}`\"\n",
" q = q.replace('{node2}', n2_text)\n",
" b = b.replace('{node2}', n2_text)\n",
" \n",
" source = source.strip('\\n')\n",
" q = f\"```\\n{source}\\n```\\n\\n{q}\"\n",
" question.append(q)\n",
" bot.append(b)\n",
" result.append(int([n1, n2] in edge_index))\n",
"\n",
" df['question'] = question\n",
" df['bot'] = bot\n",
" df = df.drop(columns={'text', 'source', 'node_ids', 'edge_index'})\n",
" df.to_json(f\"{out_dir}/Edge_Prediction_{lang}_{graph}.jsonl\", orient='records', lines=True)\n",
" results[f\"{lang}-{graph}\"] = result"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "py39",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.17"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|