{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":91249,"databundleVersionId":11294684,"sourceType":"competition"},{"sourceId":10972609,"sourceType":"datasetVersion","datasetId":6827699},{"sourceId":10972999,"sourceType":"datasetVersion","datasetId":6827977}],"dockerImageVersionId":30918,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-03-09T18:50:03.241616Z","iopub.execute_input":"2025-03-09T18:50:03.242080Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Define file paths\ntrain_labels_path = \"/kaggle/input/train-data/train_labels.csv\"  # Ensure this file is uploaded\ntrain_dir = \"/kaggle/input/byu-locating-bacterial-flagellar-motors-2025/test\"  # Root directory of tomogram slices\n\n# Load training labels with error handling\ntry:\n    train_labels_df = pd.read_csv(train_labels_path)\n    print(\"Training labels loaded successfully!\")\nexcept FileNotFoundError:\n    print(f\"Error: The file {train_labels_path} was not found. Please upload it.\")\n\n# Function to load tomogram slices into a 3D numpy array\ndef load_tomogram(tomo_id):\n    tomo_path = os.path.join(train_dir, tomo_id)\n    \n    # Check if tomogram directory exists\n    if not os.path.exists(tomo_path):\n        print(f\"Error: Tomogram directory {tomo_path} not found.\")\n        return None\n    \n    slice_files = sorted(os.listdir(tomo_path))  # Sort to maintain slice order\n    slices = []\n    \n    for f in slice_files:\n        slice_path = os.path.join(tomo_path, f)\n        image = cv2.imread(slice_path, cv2.IMREAD_GRAYSCALE)\n        if image is not None:\n            slices.append(image)\n        else:\n            print(f\"Warning: Could not read {slice_path}\")\n    \n    if len(slices) == 0:\n        print(f\"Error: No valid images found in {tomo_path}\")\n        return None\n    \n    return np.array(slices)\n\n# Select a sample tomogram from train_labels.csv\nif not train_labels_df.empty:\n    sample_tomo_id = train_labels_df[\"tomo_id\"].iloc[0]\n    sample_tomogram = load_tomogram(sample_tomo_id)\n\n    if sample_tomogram is not None:\n        # Get motor locations for this tomogram\n        motor_positions = train_labels_df[train_labels_df[\"tomo_id\"] == sample_tomo_id][[\"Motor axis 0\", \"Motor axis 1\", \"Motor axis 2\"]].values\n\n        # 3D Visualization\n        fig = plt.figure(figsize=(8, 8))\n        ax = fig.add_subplot(111, projection='3d')\n\n        # Plot motor locations\n        ax.scatter(motor_positions[:, 2], motor_positions[:, 1], motor_positions[:, 0], c='r', marker='o', s=40, label='Motors')\n\n        # Set plot limits and labels\n        ax.set_xlim([0, sample_tomogram.shape[2]])\n        ax.set_ylim([0, sample_tomogram.shape[1]])\n        ax.set_zlim([0, sample_tomogram.shape[0]])\n        ax.set_xlabel(\"X-axis (Width)\")\n        ax.set_ylabel(\"Y-axis (Height)\")\n        ax.set_zlabel(\"Z-axis (Slices)\")\n        ax.set_title(f\"3D Tomogram View: {sample_tomo_id}\")\n\n        plt.legend()\n        plt.show()\n    else:\n        print(\"Failed to load tomogram. Please check the file structure.\")\nelse:\n    print(\"Error: Training labels file is empty or not loaded.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-09T19:10:07.339374Z","iopub.execute_input":"2025-03-09T19:10:07.339736Z","iopub.status.idle":"2025-03-09T19:10:27.202936Z","shell.execute_reply.started":"2025-03-09T19:10:07.339706Z","shell.execute_reply":"2025-03-09T19:10:27.201709Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\n# Define the output file path\noutput_csv_path = \"/kaggle/working/submission.csv\"\n\n# Initialize an empty list to store rows before creating a DataFrame\nsubmission_data = []\n\n# Process each tomogram in the dataset\nif not train_labels_df.empty:\n    for tomo_id in train_labels_df[\"tomo_id\"].unique():\n        # Get motor locations for this tomogram\n        motors = train_labels_df[train_labels_df[\"tomo_id\"] == tomo_id][[\"Motor axis 0\", \"Motor axis 1\", \"Motor axis 2\"]]\n\n        # Store motor locations in a list\n        for _, row in motors.iterrows():\n            submission_data.append([tomo_id, row[\"Motor axis 0\"], row[\"Motor axis 1\"], row[\"Motor axis 2\"]])\n\n    # Convert the list to a DataFrame\n    submission_df = pd.DataFrame(submission_data, columns=[\"tomo_id\", \"Motor axis 0\", \"Motor axis 1\", \"Motor axis 2\"])\n\n    # Save the formatted results to a CSV file\n    submission_df.to_csv(output_csv_path, index=False)\n    print(f\"✅ Submission file generated successfully: {output_csv_path}\")\n\nelse:\n    print(\"❌ Error: No valid training data found.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-10T01:46:05.040908Z","iopub.execute_input":"2025-03-10T01:46:05.041373Z","iopub.status.idle":"2025-03-10T01:46:05.660692Z","shell.execute_reply.started":"2025-03-10T01:46:05.041343Z","shell.execute_reply":"2025-03-10T01:46:05.659153Z"}},"outputs":[],"execution_count":null}]}