{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# %pip install pykeen" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "import time\n", "import torch\n", "import requests\n", "import pandas as pd\n", "\n", "from pykeen.pipeline import pipeline\n", "from pykeen.triples import TriplesFactory\n", "from bs4 import BeautifulSoup\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "edges_path = 'tsv_files/edges.tsv'\n", "nodes_path = 'tsv_files/nodes.tsv'" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "edges_df = pd.read_csv(\n", " edges_path,\n", " sep='\\t',\n", " usecols=[\"start_id\", \"type\", \"end_id\"],\n", " dtype={\"start_id\": str, \"end_id\": str}\n", ")\n", "edges_df = edges_df[[\"start_id\", \"type\", \"end_id\"]]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "edges_df.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "nodes_df = pd.read_csv(nodes_path, sep='\\t', low_memory=False)\n", "nodes_df.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "for i in nodes_df['identifier']:\n", " if i.startswith('DB'):\n", " print(i)\n", " break" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "import json\n", "\n", "def get_replaced_identifier(row):\n", " properties = row['properties']\n", " try:\n", " properties_dict = json.loads(properties) if isinstance(properties, str) else {}\n", " except json.JSONDecodeError:\n", " properties_dict = {}\n", " \n", " xrefs = properties_dict.get(\"xrefs\", [])\n", " \n", " for xref in xrefs:\n", " if xref.startswith(\"OMIM:\"):\n", " return xref.replace(\"OMIM:\", \"OMIM\")\n", " \n", " return row['identifier']" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "nodes_df['identifier'] = nodes_df.apply(get_replaced_identifier, axis=1)\n", "\n", "entity_to_id = dict(zip(nodes_df['identifier'], nodes_df['node_id']))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "entity2id_df = pd.DataFrame(list(entity_to_id.items()), columns=['Entity', 'Node_ID'])\n", "entity2id_df.to_csv('entity2node.csv', index=None)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "triples_factory = TriplesFactory.from_labeled_triples(edges_df.values, entity_to_id=entity_to_id, create_inverse_triples=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "training_factory, testing_factory = triples_factory.split(\n", " ratios=[0.999999, 0.000001],\n", " random_state=42\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "result = pipeline(\n", " model='CompGCN',\n", " training=training_factory,\n", " testing=testing_factory,\n", " validation=None,\n", " model_kwargs=dict(embedding_dim=64),\n", " training_kwargs=dict(\n", " num_epochs=50,\n", " batch_size=4096000\n", " ),\n", " random_seed=42,\n", " device='cuda:2'\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# result.save_to_directory('pykeen_result')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "model = result.model\n", "training_factory = result.training" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "entity_embeddings = model.entity_representations[0]\n", "entity_tensor = entity_embeddings(indices=None)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "entity_tensor.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "entity_to_id = training_factory.entity_to_id" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "total = 0\n", "omim_ids = []\n", "drugbank_ids = []\n", "for entity_id, entity_label in entity_to_id.items():\n", " print(entity_id, entity_label)\n", " total += 1\n", " if total > 10:\n", " break\n", " # if \"omim\" in entity_label.lower():\n", " # print(1)\n", " # omim_ids.append((entity_label, entity_id))\n", " # elif \"drugbank\" in entity_label.lower():\n", " # print(2)\n", " # drugbank_ids.append((entity_label, entity_id))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "def get_entity_embedding(entity_label, entity_to_id, entity_tensor):\n", " \"\"\"\n", " Return the embedding vector corresponding to an entity label.\n", " \n", " Parameters:\n", " - entity_label: str, the label of the entity (e.g., 'OMIM602371' or 'DB00014')\n", " - entity_to_id: dict, a mapping from entity to ID\n", " - entity_tensor: torch.Tensor, entity embedding matrix of shape [num_entities, embedding_dim]\n", "\n", " Returns:\n", " - embedding_vector: torch.Tensor or None\n", " \"\"\"\n", " # Check if the entity exists in the mapping\n", " if entity_label not in entity_to_id:\n", " print(f\"Entity '{entity_label}' not found in the mapping.\")\n", " return None\n", " \n", " # Get the ID index corresponding to the entity\n", " entity_id = entity_to_id[entity_label]\n", " \n", " # Extract the corresponding embedding vector from entity_tensor\n", " embedding_vector = entity_tensor[entity_id].detach().cpu().numpy() # Move embedding to CPU for easy handling\n", "\n", " return embedding_vector" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "example_entity = 'OMIM102100'\n", "embedding = get_entity_embedding(example_entity, entity_to_id, entity_tensor)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "embedding.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "embedding" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "wdname = pd.read_csv('Wdname.csv', header=None)\n", "wdname.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "wrname = pd.read_csv('Wrname.csv', header=None)\n", "wrname.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "wdname = pd.read_csv('data/other/Wdname.csv', header=None, names=[\"original_id\"]) # OMIM ID\n", "wrname = pd.read_csv('data/other/Wrname.csv', header=None, names=[\"original_id\"]) # DrugBank ID\n", "\n", "id_df = pd.concat([wdname, wrname], ignore_index=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Create the `entity_label` column\n", "def convert_to_entity_label(original_id):\n", " \"\"\"\n", " Convert the original ID to the `entity_label` format used by the model.\n", " \"\"\"\n", " # Handle IDs that start with \"D\": check if the characters after \"D\" are digits (OMIM format)\n", " if original_id.startswith(\"D\") and original_id[1:].isdigit():\n", " return \"OMIM\" + original_id[1:] # Convert to `OMIMxxxx` format\n", " # If the ID starts with \"DB\", retain it as `DBxxxx`\n", " elif original_id.startswith(\"DB\"):\n", " return original_id\n", " else:\n", " return None # Return None if the ID doesn't meet any criteria\n", "\n", "# Apply the conversion function to create the new `entity_label` column\n", "id_df['entity_label'] = id_df['original_id'].apply(convert_to_entity_label)\n", "\n", "# Keep only the rows where `entity_label` is not empty\n", "id_df = id_df.dropna(subset=['entity_label'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "id_df.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "id_df['embedding'] = id_df['entity_label'].apply(lambda x: get_entity_embedding(x, entity_to_id, entity_tensor))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Step 1: Create a dictionary for ID replacements\n", "id_replacement_mapping = {\n", " \"DB00510\": \"DB00313\",\n", " \"DB01258\": \"DB09026\",\n", " \"DB01402\": \"DB01294\",\n", " \"DB01904\": \"DB11195\",\n", " \"DB05073\": \"DB02709\"\n", "}\n", "\n", "def update_entity_label(entity_label, mapping):\n", " \"\"\"\n", " Update the `entity_label` based on the replacement dictionary.\n", " \"\"\"\n", " # If the current ID exists in the mapping, replace it with the new ID; otherwise, keep it unchanged\n", " return mapping.get(entity_label, entity_label)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "id_df['entity_label'] = id_df['entity_label'].apply(lambda x: update_entity_label(x, id_replacement_mapping))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "id_df['embedding'] = id_df['entity_label'].apply(lambda x: get_entity_embedding(x, entity_to_id, entity_tensor))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "extract_omim_ids = [\n", " \"OMIM103470\", \"OMIM106400\", \"OMIM133600\", \"OMIM144400\", \"OMIM153480\", \n", " \"OMIM153640\", \"OMIM159000\", \"OMIM159001\", \"OMIM175505\", \"OMIM182920\", \n", " \"OMIM212110\", \"OMIM232240\", \"OMIM234580\", \"OMIM241500\", \"OMIM241510\", \n", " \"OMIM259660\", \"OMIM300301\", \"OMIM300306\", \"OMIM300455\", \"OMIM300494\", \n", " \"OMIM300497\", \"OMIM300504\", \"OMIM300584\", \"OMIM300640\", \"OMIM300706\", \n", " \"OMIM300910\", \"OMIM304900\", \"OMIM305300\", \"OMIM306700\", \"OMIM600208\", \n", " \"OMIM600309\", \"OMIM600634\", \"OMIM600996\", \"OMIM601696\", \"OMIM601884\", \n", " \"OMIM602025\", \"OMIM603860\", \"OMIM605839\", \"OMIM607447\", \"OMIM607595\", \n", " \"OMIM607636\", \"OMIM607655\", \"OMIM607801\", \"OMIM608355\", \"OMIM608622\", \n", " \"OMIM608902\", \"OMIM609265\", \"OMIM609307\", \"OMIM609338\", \"OMIM609535\", \n", " \"OMIM609886\", \"OMIM609887\", \"OMIM610762\", \"OMIM610799\", \"OMIM611277\", \n", " \"OMIM612052\", \"OMIM612359\", \"OMIM612362\", \"OMIM612460\", \"OMIM612542\", \n", " \"OMIM612556\", \"OMIM612560\", \"OMIM612671\", \"OMIM612797\", \"OMIM612874\", \n", " \"OMIM612975\", \"OMIM613180\", \"OMIM613508\", \"OMIM613875\", \"OMIM614036\", \n", " \"OMIM614157\", \"OMIM614192\", \"OMIM614401\", \"OMIM614408\", \"OMIM614546\", \n", " \"OMIM614696\", \"OMIM615106\", \"OMIM615221\", \"OMIM615311\", \"OMIM615325\", \n", " \"OMIM615457\"\n", "]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Assuming `id_df` is the DataFrame generated earlier with the `entity_label` column to be updated\n", "\n", "# 1. Extract all OMIM IDs that need to be checked\n", "omim_ids = [label[4:] for label in id_df['entity_label'] if label.startswith(\"OMIM\")]\n", "\n", "# 2. Define the OMIM website URL template for entry lookups\n", "OMIM_URL_TEMPLATE = \"https://www.omim.org/entry/{}\"\n", "\n", "# 4. Set headers to mimic a browser visit\n", "headers = {\n", " \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\",\n", " \"Referer\": \"https://www.omim.org/\",\n", " \"Accept-Language\": \"en-US,en;q=0.9\",\n", " \"Accept-Encoding\": \"gzip, deflate, br\",\n", " \"Connection\": \"keep-alive\"\n", "}\n", "\n", "# Use requests.Session() to maintain session\n", "session = requests.Session()\n", "session.headers.update(headers)\n", "\n", "# 3. Create a replacement dictionary for OMIM IDs\n", "omim_replacement_mapping = {}\n", "\n", "# 5. Use a loop to batch retrieve redirect information for each OMIM ID\n", "for omim_id in omim_ids: # Corrected variable name from extract_omim_ids to omim_ids\n", " url = OMIM_URL_TEMPLATE.format(omim_id)\n", " print(f\"Checking OMIM ID: {omim_id}, URL: {url}\")\n", " try:\n", " response = session.get(url, timeout=10) # Set a timeout of 10 seconds per request\n", " \n", " if response.status_code == 200:\n", " # Parse the webpage using BeautifulSoup\n", " soup = BeautifulSoup(response.text, 'html.parser')\n", " \n", " # Find all tags with class 'mim-font' that might contain redirection info\n", " span_tags = soup.find_all('span', class_='mim-font')\n", " for span in span_tags:\n", " # Check if the span text contains \"MOVED TO\"\n", " if \"MOVED TO\" in span.text:\n", " # Extract the list of target IDs after \"MOVED TO\" (e.g., \"MOVED TO 193510, 606952\")\n", " target_ids_text = span.text.strip().replace(\"MOVED TO\", \"\").strip().split(' ')[0]\n", " target_ids = [tid.strip() for tid in target_ids_text.split(\",\")]\n", " \n", " # Use the first target ID as the new ID in the mapping\n", " new_id = target_ids[0]\n", " omim_replacement_mapping[f\"OMIM{omim_id}\"] = f\"OMIM{new_id}\"\n", " print(f\"OMIM{omim_id} has been moved to OMIM{new_id}\")\n", " break # Exit loop after finding the redirection\n", " else:\n", " print(f\"No change record for OMIM{omim_id}\")\n", " else:\n", " print(f\"Failed to query OMIM{omim_id}, status code: {response.status_code}\")\n", " except requests.exceptions.RequestException as e:\n", " print(f\"Request error for OMIM{omim_id}: {e}\")\n", "\n", " # Add a delay to prevent triggering anti-scraping mechanisms\n", " time.sleep(1) # Wait 1 second between requests" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "omim_replacement_mapping" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "id_df['entity_label'] = id_df['entity_label'].apply(lambda x: omim_replacement_mapping.get(x, x))\n", "\n", "id_df['embedding'] = id_df['entity_label'].apply(lambda x: get_entity_embedding(x, entity_to_id, entity_tensor))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "manual_mappings = {\n", " \"OMIM106400\": \"MONDO:0007127\",\n", " \"OMIM232240\": \"MONDO:0009288\",\n", " \"OMIM241500\": \"MONDO:0016605\",\n", " \"OMIM306700\": \"MONDO:0010602\"\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "omim_replacement_mapping.update(manual_mappings)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "id_df['entity_label'] = id_df['entity_label'].apply(lambda x: omim_replacement_mapping.get(x, x))\n", "\n", "id_df['embedding'] = id_df['entity_label'].apply(lambda x: get_entity_embedding(x, entity_to_id, entity_tensor))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "id_df.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "id_df['embedding'] = id_df['embedding'].apply(lambda x: x if x is not None else [0.0] * 64)\n", "embedding_df = pd.DataFrame(id_df['embedding'].tolist())\n", "embedding_df.columns = [f\"embedding_{i}\" for i in range(embedding_df.shape[1])]\n", "id_df_expanded = pd.concat([id_df.drop('embedding', axis=1), embedding_df], axis=1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "id_df_expanded.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "id_df_expanded.to_csv('kg_embeddings.csv', index=None)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "pykeen", "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.12.7" } }, "nbformat": 4, "nbformat_minor": 2 }