{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":87793,"databundleVersionId":11553390,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":10855324,"sourceType":"datasetVersion","datasetId":6742586},{"sourceId":11368074,"sourceType":"datasetVersion","datasetId":7116127},{"sourceId":224830487,"sourceType":"kernelVersion"},{"sourceId":330649,"sourceType":"modelInstanceVersion","isSourceIdPinned":false,"modelInstanceId":277383,"modelId":298274}],"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"MODEL_TYPE='RFAA'\nVALIDATION=False","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T14:37:37.616409Z","iopub.execute_input":"2025-04-11T14:37:37.617321Z","iopub.status.idle":"2025-04-11T14:37:37.627244Z","shell.execute_reply.started":"2025-04-11T14:37:37.617286Z","shell.execute_reply":"2025-04-11T14:37:37.626031Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Install requirements ","metadata":{}},{"cell_type":"code","source":"if MODEL_TYPE=='RFAA' and VALIDATION:\n    !pip install torch==2.1\n    !pip install torchdata==0.7.0 \n    !pip install dgl -f https://data.dgl.ai/wheels/torch-2.1/cu121/repo.html\n    !pip install biopython\n    !pip install e3nn==0.5.6\n    !pip install omegaconf\n    !pip install hydra-core\n    !pip install icecream\n    !pip install assertpy\n    !pip install openbabel-wheel","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T14:37:37.629559Z","iopub.execute_input":"2025-04-11T14:37:37.629882Z","iopub.status.idle":"2025-04-11T14:41:54.982995Z","shell.execute_reply.started":"2025-04-11T14:37:37.629856Z","shell.execute_reply":"2025-04-11T14:41:54.981259Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Helper scripts","metadata":{}},{"cell_type":"code","source":"\nfrom copy import deepcopy\nimport pandas as pd\n\nimport os, sys\nimport re\nimport numpy as np\nimport torch\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nimport Bio\nfrom Bio.PDB import Atom, Model, Chain, Residue, Structure, PDBParser\nfrom Bio import SeqIO\n\nprint('IMPORT OK !!!!')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2025-04-11T14:41:54.984972Z","iopub.execute_input":"2025-04-11T14:41:54.985431Z","iopub.status.idle":"2025-04-11T14:41:58.379236Z","shell.execute_reply.started":"2025-04-11T14:41:54.985391Z","shell.execute_reply":"2025-04-11T14:41:58.378197Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sys.path.append('/kaggle/input/rosettafold-all-atom/pytorch/default/1/rf2aa/SE3Transformer')\nsys.path.append('/kaggle/input/rosettafold-all-atom/pytorch/default/1/')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T14:41:58.380307Z","iopub.execute_input":"2025-04-11T14:41:58.381404Z","iopub.status.idle":"2025-04-11T14:41:58.385897Z","shell.execute_reply.started":"2025-04-11T14:41:58.381360Z","shell.execute_reply":"2025-04-11T14:41:58.384977Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"PYTHON = sys.executable\nprint('PYTHON',PYTHON)\n\n\nUSALIGN = \\\n'/kaggle/working//USalign'\n#'<your us align path>/USalign'\n\nos.system('cp /kaggle/input/usalign/USalign /kaggle/working/')\nos.system('sudo chmod u+x /kaggle/working//USalign')\n\n\nDATA_KAGGLE_DIR = '/kaggle/input/stanford-rna-3d-folding'\n\n\n# helper ----\nclass dotdict(dict):\n\t__setattr__ = dict.__setitem__\n\t__delattr__ = dict.__delitem__\n\n\tdef __getattr__(self, name):\n\t\ttry:\n\t\t\treturn self[name]\n\t\texcept KeyError:\n\t\t\traise AttributeError(name)\n\n# visualisation helper ----\ndef set_aspect_equal(ax):\n\tx_limits = ax.get_xlim()\n\ty_limits = ax.get_ylim()\n\tz_limits = ax.get_zlim()\n\n\t# Compute the mean of each axis\n\tx_middle = np.mean(x_limits)\n\ty_middle = np.mean(y_limits)\n\tz_middle = np.mean(z_limits)\n\n\t# Compute the max range across all axes\n\tmax_range = max(x_limits[1] - x_limits[0],\n\t\t\t\t\ty_limits[1] - y_limits[0],\n\t\t\t\t\tz_limits[1] - z_limits[0]) / 2.0\n\n\t# Set the new limits to ensure equal scaling\n\tax.set_xlim(x_middle - max_range, x_middle + max_range)\n\tax.set_ylim(y_middle - max_range, y_middle + max_range)\n\tax.set_zlim(z_middle - max_range, z_middle + max_range)\n\n\n\n\n# xyz df helper --------------------\ndef get_truth_df(target_id):\n    truth_df = LABEL_DF[LABEL_DF['target_id'] == target_id]\n    truth_df = truth_df.reset_index(drop=True)\n    return truth_df\n\ndef parse_output_to_df(output, seq, target_id):\n    df = []\n    chain_data = []\n    for i, res in enumerate(seq):\n        d=dict(ID = target_id,\n                    resname=res,\n                    resid=i+1)\n        for n in range(len(output)):\n            d={**d, f'x_{n+1}': round(output[n,i,0].item(),3),\n                     f'y_{n+1}': round(output[n,i,1].item(),3),\n                     f'z_{n+1}': round(output[n,i,2].item(),3)}\n        chain_data.append(d)\n\n    if len(chain_data)!=0:\n        chain_df = pd.DataFrame(chain_data)\n        df.append(chain_df)\n        ##print(chain_df)\n    return df\n\ndef parse_pdb_to_df(pdb_file, target_id):\n    parser = PDBParser()\n    structure = parser.get_structure('', pdb_file)\n\n    df = []\n    for model in structure:\n        for chain in model:\n            print(chain)\n            chain_data = []\n            for residue in chain:\n                # print(residue)\n                if residue.get_resname() in ['A', 'U', 'G', 'C']:\n                    # Check if the residue has a C1' atom\n                    if 'C1\\'' in residue:\n                        atom = residue['C1\\'']\n                        xyz = atom.get_coord()\n                        resname = residue.get_resname()\n                        resid = residue.get_id()[1]\n\n                        #todo detect discontinous: resid = prev_resid+1\n                        #ID\tresname\tresid\tx_1\ty_1\tz_1\n                        chain_data.append(dict(\n                            ID = target_id+'_'+str(resid),\n                            resname=resname,\n                            resid=resid,\n                            x_1=xyz[0],\n                            y_1=xyz[1],\n                            z_1=xyz[2],\n                        ))\n                        ##print(f\"Residue {resname} {resid}, Atom: {atom.get_name()}, xyz: {xyz}\")\n\n            if len(chain_data)!=0:\n                chain_df = pd.DataFrame(chain_data)\n                df.append(chain_df)\n                ##print(chain_df)\n    return df\n\n# usalign helper --------------------\ndef write_target_line(\n    atom_name, atom_serial, residue_name, chain_id, residue_num, x_coord, y_coord, z_coord, occupancy=1.0, b_factor=0.0, atom_type='P'\n):\n    \"\"\"\n    Writes a single line of PDB format based on provided atom information.\n\n    Args:\n        atom_name (str): Name of the atom (e.g., \"N\", \"CA\").\n        atom_serial (int): Atom serial number.\n        residue_name (str): Residue name (e.g., \"ALA\").\n        chain_id (str): Chain identifier.\n        residue_num (int): Residue number.\n        x_coord (float): X coordinate.\n        y_coord (float): Y coordinate.\n        z_coord (float): Z coordinate.\n        occupancy (float, optional): Occupancy value (default: 1.0).\n        b_factor (float, optional): B-factor value (default: 0.0).\n\n    Returns:\n        str: A single line of PDB string.\n    \"\"\"\n    return f'ATOM  {atom_serial:>5d}  {atom_name:<5s} {residue_name:<3s} {residue_num:>3d}    {x_coord:>8.3f}{y_coord:>8.3f}{z_coord:>8.3f}{occupancy:>6.2f}{b_factor:>6.2f}           {atom_type}\\n'\n\ndef write_xyz_to_pdb(df, pdb_file, xyz_id = 1):\n    resolved_cnt = 0\n    with open(pdb_file, 'w') as target_file:\n        for _, row in df.iterrows():\n            x_coord = row[f'x_{xyz_id}']\n            y_coord = row[f'y_{xyz_id}']\n            z_coord = row[f'z_{xyz_id}']\n\n            if x_coord > -1e17 and y_coord > -1e17 and z_coord > -1e17:\n                resolved_cnt += 1\n                target_line = write_target_line(\n                    atom_name=\"C1'\",\n                    atom_serial=int(row['resid']),\n                    residue_name=row['resname'],\n                    chain_id='0',\n                    residue_num=int(row['resid']),\n                    x_coord=x_coord,\n                    y_coord=y_coord,\n                    z_coord=z_coord,\n                    atom_type='C',\n                )\n                target_file.write(target_line)\n    return resolved_cnt\n\ndef parse_usalign_for_tm_score(output):\n    # Extract TM-score based on length of reference structure (second)\n    tm_score_match = re.findall(r'TM-score=\\s+([\\d.]+)', output)[1]\n    if not tm_score_match:\n        raise ValueError('No TM score found')\n    return float(tm_score_match)\n\ndef parse_usalign_for_transform(output):\n    # Locate the rotation matrix section\n    matrix_lines = []\n    found_matrix = False\n\n    for line in output.splitlines():\n        if \"The rotation matrix to rotate Structure_1 to Structure_2\" in line:\n            found_matrix = True\n        elif found_matrix and re.match(r'^\\d+\\s+[-\\d.]+\\s+[-\\d.]+\\s+[-\\d.]+\\s+[-\\d.]+$', line):\n            matrix_lines.append(line)\n        elif found_matrix and not line.strip():\n            break  # Stop parsing if an empty line is encountered after the matrix\n\n    # Parse the rotation matrix values\n    rotation_matrix = []\n    for line in matrix_lines:\n        parts = line.split()\n        row_values = list(map(float, parts[1:]))  # Skip the first column (index)\n        rotation_matrix.append(row_values)\n\n    return np.array(rotation_matrix)\n\ndef call_usalign(predict_df, truth_df, verbose=1):\n    truth_pdb = '~truth.pdb'\n    predict_pdb = '~predict.pdb'\n    write_xyz_to_pdb(predict_df, predict_pdb, xyz_id=1)\n    write_xyz_to_pdb(truth_df, truth_pdb, xyz_id=1)\n\n    command = f'{USALIGN} {predict_pdb} {truth_pdb} -atom \" C1\\'\" -m -'\n    output = os.popen(command).read()\n    if verbose==1:\n        print(output)\n    tm_score = parse_usalign_for_tm_score(output)\n    transform = parse_usalign_for_transform(output)\n    return tm_score, transform\n\nprint('HELPER OK!!!')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T14:41:58.387038Z","iopub.execute_input":"2025-04-11T14:41:58.387355Z","iopub.status.idle":"2025-04-11T14:41:58.537740Z","shell.execute_reply.started":"2025-04-11T14:41:58.387323Z","shell.execute_reply":"2025-04-11T14:41:58.536861Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!echo '1234' > pdb100_pdb.ffdata\n!touch pdb100_pdb.ffindex","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T14:41:58.538994Z","iopub.execute_input":"2025-04-11T14:41:58.539275Z","iopub.status.idle":"2025-04-11T14:41:58.806332Z","shell.execute_reply.started":"2025-04-11T14:41:58.539253Z","shell.execute_reply":"2025-04-11T14:41:58.804941Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from rf2aa.chemical import initialize_chemdata\nfrom rf2aa.ffindex import *\nfrom rf2aa.util_module import XYZConverter\nimport json\nimport string\nfrom rf2aa.data.data_loader_utils import blank_template\nfrom rf2aa.data.data_loader import RawInputData\nfrom rf2aa.util import get_protein_bond_feats\nfrom rf2aa.data.merge_inputs import merge_all\nfrom run_inference import ModelRunner   \n\n\nclass MyRunner(ModelRunner):\n    def __init__(self, config) -> None:\n        self.config = config\n        initialize_chemdata(self.config.chem_params)\n        FFindexDB = namedtuple(\"FFindexDB\", \"index, data\")\n        self.ffdb = FFindexDB(read_index('/kaggle/working/pdb100_pdb.ffindex'),\n                              read_data('/kaggle/working/pdb100_pdb.ffdata'))\n        self.device = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n        self.xyz_converter = XYZConverter()\n        self.deterministic = config.get(\"deterministic\", False)     \n        with open('/kaggle/input/rosettafold-all-atom/pytorch/default/1/rf2aa/ligands.json','rt') as file:\n            self.molecule_db = json.load(file)\n    def load_rna_seq(self, seq, target_id='query'):\n        residues_to_atomize = [] # chain letter, residue number, residue name\n        chains = []\n        protein_inputs = {}\n        \n        na_inputs = {}\n        loader_params = self.config.loader_params\n\n        msa = []\n        ins = []\n\n        table = str.maketrans(dict.fromkeys(string.ascii_lowercase))\n    \n        L_s = []\n        seq = seq.rstrip()\n        msa_i = seq.translate(table)\n        msa_i = msa_i.replace('B','D') # hacky...\n        if L_s == []:\n            L_s = [len(x) for x in msa_i.split('/')]\n        msa_i = msa_i.replace('/','')\n        msa.append(msa_i)\n\n        L = len(msa[-1])\n\n        i = np.zeros((L))\n        ins.append(i)\n\n        alphabet = np.array(list(\"00000000000000000000-000000ACGUN\"), dtype='|S1').view(np.uint8)\n        msa = np.array([list(s) for s in msa], dtype='|S1').view(np.uint8)\n    \n        for i in range(alphabet.shape[0]):\n            msa[msa == alphabet[i]] = i\n\n        ins = np.array(ins, dtype=np.uint8)\n\n        L=L_s\n        L = L[0]\n        xyz_t, t1d, mask_t, _ = blank_template(loader_params[\"n_templ\"], L)\n    \n\n        bond_feats = get_protein_bond_feats(L)\n        chirals = torch.zeros(0, 5)\n        atom_frames = torch.zeros(0, 3, 2)\n    \n        na_input = RawInputData(\n                torch.from_numpy(msa),\n                torch.from_numpy(ins),\n                bond_feats,\n                xyz_t,\n                mask_t,\n                t1d,\n                chirals,\n                atom_frames,\n                taxids=None,\n            )\n        na_inputs['A'] = na_input\n\n        sm_inputs = {} \n      \n        raw_data = merge_all(protein_inputs, na_inputs, sm_inputs, residues_to_atomize, deterministic=self.deterministic)\n        self.raw_data = raw_data\n\n    def predict_rna_seq(self, seq, target_id='query'):\n        self.load_rna_seq(seq, target_id)\n        input_feats = self.construct_features()\n        outputs = self.run_model_forward(input_feats)\n        logits, logits_aa, logits_pae, logits_pde, p_bind, \\\n                xyz, alpha_s, xyz_allatom, lddt, _, _, _ \\\n                = outputs\n        c1=xyz_allatom[:,:,10,:]\n        return c1\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T14:41:58.809519Z","iopub.execute_input":"2025-04-11T14:41:58.809902Z","iopub.status.idle":"2025-04-11T14:42:04.725315Z","shell.execute_reply.started":"2025-04-11T14:41:58.809869Z","shell.execute_reply":"2025-04-11T14:42:04.724372Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if MODEL_TYPE=='RFAA':\n    import omegaconf\n    cfg = omegaconf.OmegaConf.load('/kaggle/input/rosettafold-all-atom/pytorch/default/1/rf2aa/config/inference/base.yaml')\n    cfg.checkpoint_path='/kaggle/input/rosettafoldaa-checkpoints/RFAA_paper_weights.pt'\n\n    runner = MyRunner(cfg)\n    runner.load_model()\n\nprint('Model OK')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T14:42:04.726343Z","iopub.execute_input":"2025-04-11T14:42:04.726953Z","iopub.status.idle":"2025-04-11T14:42:27.014371Z","shell.execute_reply.started":"2025-04-11T14:42:04.726920Z","shell.execute_reply":"2025-04-11T14:42:27.013404Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if VALIDATION:\n    LABEL_DF = pd.read_csv('/kaggle/input/stanford-rna-3d-folding/train_labels.csv')\n    LABEL_DF['target_id'] = LABEL_DF['ID'].apply(lambda x: '_'.join(x.split('_')[:-1]))\n    train_df=pd.read_csv('/kaggle/input/stanford-rna-3d-folding/train_sequences.csv')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T14:42:27.015479Z","iopub.execute_input":"2025-04-11T14:42:27.015857Z","iopub.status.idle":"2025-04-11T14:42:27.021629Z","shell.execute_reply.started":"2025-04-11T14:42:27.015825Z","shell.execute_reply":"2025-04-11T14:42:27.020711Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if MODEL_TYPE=='RFAA' and VALIDATION:\n\n    train_df['rfaa_tm_score']=None\n    num_data=len(train_df)\n\n    for i, seq in tqdm(enumerate(train_df.sequence),total=num_data):\n        if len(seq)>300:\n            continue\n        target_id=train_df.target_id[i]\n        truth_df = get_truth_df(target_id)\n        if sum(~np.isnan(truth_df.x_1))<3:\n            continue\n        try:\n            prediction = runner.predict_rna_seq(seq)\n        except KeyboardInterrupt:\n            break\n        except:\n            continue   \n        result = parse_output_to_df(prediction, seq, target_id)[0]\n        try:\n            tm_score, transform = call_usalign(result, truth_df, verbose=0)\n            train_df.loc[i,'rfaa_tm_score']=tm_score\n        except KeyboardInterrupt:\n            break\n        except:\n            pass\n    train_df.to_csv('rfaa_tm_scores.csv', index=False)\n    display(train_df.rfaa_tm_score.hist())\n    print(train_df.rfaa_tm_score.mean())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T14:42:27.022988Z","iopub.execute_input":"2025-04-11T14:42:27.023397Z","iopub.status.idle":"2025-04-11T14:42:27.055205Z","shell.execute_reply.started":"2025-04-11T14:42:27.023366Z","shell.execute_reply":"2025-04-11T14:42:27.054202Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if MODEL_TYPE=='RFAA' and not VALIDATION:\n    test_df=pd.read_csv('/kaggle/input/stanford-rna-3d-folding/test_sequences.csv')\n\n    num_data = len(test_df)\n    for i, seq in tqdm(enumerate(test_df.sequence),total=num_data):\n        try:\n            target_id=test_df.target_id[i]\n            prediction=[]\n            for k in range(5):\n                p = runner.predict_rna_seq(seq)\n                prediction.append(p[0])\n            prediction=torch.stack(prediction,axis=0)\n            result = parse_output_to_df(prediction, seq, target_id)[0]\n        except KeyboardInterrupt:\n            break\n        except:\n            target_id==test_df.target_id[i]\n            print('Failed to predict', target_id)\n            result=pd.DataFrame(columns=['ID', 'resname', 'resid', \n                                         'x_1', 'y_1', 'z_1', \n                                         'x_2', 'y_2', 'z_2',\n                                         'x_3', 'y_3', 'z_3', \n                                         'x_4', 'y_4', 'z_4', \n                                         'x_5', 'y_5', 'z_5'], \n                                         data=[[target_id, x, j+1] + [0.0]*15 for j, x in enumerate(seq)])\n            \n        result['ID']=result.apply(lambda x: x.ID + '_' + str(x.resid), axis=1)\n        result.to_csv('submission.csv', index=False, mode='a', header=(i==0))\n        torch.cuda.empty_cache()\n\n    display(pd.read_csv('submission.csv'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T14:46:46.924630Z","iopub.execute_input":"2025-04-11T14:46:46.925696Z","iopub.status.idle":"2025-04-11T14:50:25.749664Z","shell.execute_reply.started":"2025-04-11T14:46:46.925658Z","shell.execute_reply":"2025-04-11T14:50:25.747780Z"}},"outputs":[],"execution_count":null}]}