{"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":"gpu","dataSources":[{"sourceId":91249,"databundleVersionId":11294684,"sourceType":"competition"},{"sourceId":11036126,"sourceType":"datasetVersion","datasetId":6873934},{"sourceId":11044741,"sourceType":"datasetVersion","datasetId":6880023},{"sourceId":11195676,"sourceType":"datasetVersion","datasetId":6989638},{"sourceId":227202990,"sourceType":"kernelVersion"}],"dockerImageVersionId":30919,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<h1 style=\"color: #6cb4e4;  text-align: center;  padding: 0.25em;  border-top: solid 2.5px #6cb4e4;  border-bottom: solid 2.5px #6cb4e4;  background: -webkit-repeating-linear-gradient(-45deg, #f0f8ff, #f0f8ff 3px,#e9f4ff 3px, #e9f4ff 7px);  background: repeating-linear-gradient(-45deg, #f0f8ff, #f0f8ff 3px,#e9f4ff 3px, #e9f4ff 7px);height:45px;\">\n<b>\nOnly Submission(LoadLocalTrainModel)\n</b></h1> ","metadata":{}},{"cell_type":"markdown","source":"### **ℹ️INFO**\n* First of all, I'm grateful to the host for sharing such a great bass line.\n* This notebook is an inference notebook that performed a unique LocalTrain based on the Train/Inference published by the host.\n    * https://www.kaggle.com/code/andrewjdarley/train-yolo\n    * https://www.kaggle.com/code/andrewjdarley/submission-notebook","metadata":{}},{"cell_type":"markdown","source":"---","metadata":{}},{"cell_type":"markdown","source":"### **ℹ️2025/03/28 MyLocalTrainResult**\n* **ExpNmae: BYU-D-301-yolov10x-DAexp(NotebookVersion10)**\n    * **LB: 0.732**\n    * **mAP: 0.948**\n    * F1: 0.88\n    * Val Loss: 0.8242\n    * ModelWeight: https://www.kaggle.com/datasets/hideyukizushi/byu-d-301","metadata":{}},{"cell_type":"code","source":"from PIL import Image\nim1 = Image.open('/kaggle/input/byu-d-301/F1_curve.png')\nim2 = Image.open('/kaggle/input/byu-d-301/PR_curve.png')\nim3 = Image.open('/kaggle/input/byu-d-301/dfl_loss_curve.png')\ndef get_concat_h_multi_resize(im_list, resample=Image.BICUBIC):\n    min_height = min(im.height for im in im_list)\n    im_list_resize = [im.resize((int(im.width * min_height / im.height), min_height),resample=resample)\n                      for im in im_list]\n    total_width = sum(im.width for im in im_list_resize)\n    dst = Image.new('RGB', (total_width, min_height))\n    pos_x = 0\n    for im in im_list_resize:\n        dst.paste(im, (pos_x, 0))\n        pos_x += im.width\n    return dst\nget_concat_h_multi_resize([im3, im2, im1])","metadata":{"trusted":true,"_kg_hide-output":false,"execution":{"iopub.status.busy":"2025-04-11T01:08:50.184924Z","iopub.execute_input":"2025-04-11T01:08:50.185206Z","iopub.status.idle":"2025-04-11T01:08:50.633868Z","shell.execute_reply.started":"2025-04-11T01:08:50.185175Z","shell.execute_reply":"2025-04-11T01:08:50.632777Z"},"_kg_hide-input":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### **ℹ️2025/03/20 MyLocalTrainResult**\n* **ExpNmae: BYU-C-301-yolov9e-DAexp-MixUp-HPexp(NotebookVersion4)**\n    * **LB: 0.666**\n    * **mAP: 0.9420**\n    * F1: 0.91\n    * Val Loss: 1.8854\n    * ModelWeight: https://www.kaggle.com/datasets/hideyukizushi/byu-c-301-yolov9e-daexp-mixup-hpexp/data","metadata":{}},{"cell_type":"code","source":"from PIL import Image\nim1 = Image.open('/kaggle/input/byu-c-301-yolov9e-daexp-mixup-hpexp/F1_curve.png')\nim2 = Image.open('/kaggle/input/byu-c-301-yolov9e-daexp-mixup-hpexp/PR_curve.png')\nim3 = Image.open('/kaggle/input/byu-c-301-yolov9e-daexp-mixup-hpexp/dfl_loss_curve.png')\ndef get_concat_h_multi_resize(im_list, resample=Image.BICUBIC):\n    min_height = min(im.height for im in im_list)\n    im_list_resize = [im.resize((int(im.width * min_height / im.height), min_height),resample=resample)\n                      for im in im_list]\n    total_width = sum(im.width for im in im_list_resize)\n    dst = Image.new('RGB', (total_width, min_height))\n    pos_x = 0\n    for im in im_list_resize:\n        dst.paste(im, (pos_x, 0))\n        pos_x += im.width\n    return dst\nget_concat_h_multi_resize([im3, im2, im1])","metadata":{"trusted":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2025-04-11T01:08:50.634867Z","iopub.execute_input":"2025-04-11T01:08:50.635194Z","iopub.status.idle":"2025-04-11T01:08:50.973829Z","shell.execute_reply.started":"2025-04-11T01:08:50.635162Z","shell.execute_reply":"2025-04-11T01:08:50.972717Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### **ℹ️2025/03/10 MyLocalTrainResult**\n* **ExpNmae: BYU-A-106-yolov8l-DAexp-MixUpExp(NotebookVersion1)**\n    * **LB: 0.634**\n    * **mAP: 0.93**\n    * F1: 0.87\n    * Val Loss: 0.8292\n    * ModelWeight: https://www.kaggle.com/datasets/hideyukizushi/byu-a-106-yolov8l-daexp-mixupexp","metadata":{}},{"cell_type":"code","source":"from PIL import Image\nim1 = Image.open('/kaggle/input/byu-a-106-yolov8l-daexp-mixupexp/F1_curve.png')\nim2 = Image.open('/kaggle/input/byu-a-106-yolov8l-daexp-mixupexp/PR_curve.png')\nim3 = Image.open('/kaggle/input/byu-a-106-yolov8l-daexp-mixupexp/dfl_loss_curve.png')\ndef get_concat_h_multi_resize(im_list, resample=Image.BICUBIC):\n    min_height = min(im.height for im in im_list)\n    im_list_resize = [im.resize((int(im.width * min_height / im.height), min_height),resample=resample)\n                      for im in im_list]\n    total_width = sum(im.width for im in im_list_resize)\n    dst = Image.new('RGB', (total_width, min_height))\n    pos_x = 0\n    for im in im_list_resize:\n        dst.paste(im, (pos_x, 0))\n        pos_x += im.width\n    return dst\nget_concat_h_multi_resize([im3, im2, im1])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T01:08:50.974828Z","iopub.execute_input":"2025-04-11T01:08:50.975105Z","iopub.status.idle":"2025-04-11T01:08:51.376446Z","shell.execute_reply.started":"2025-04-11T01:08:50.975081Z","shell.execute_reply":"2025-04-11T01:08:51.375454Z"},"_kg_hide-input":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<h1 style=\"color: #6cb4e4;  text-align: center;  padding: 0.25em;  border-top: solid 2.5px #6cb4e4;  border-bottom: solid 2.5px #6cb4e4;  background: -webkit-repeating-linear-gradient(-45deg, #f0f8ff, #f0f8ff 3px,#e9f4ff 3px, #e9f4ff 7px);  background: repeating-linear-gradient(-45deg, #f0f8ff, #f0f8ff 3px,#e9f4ff 3px, #e9f4ff 7px);height:45px;\">\n<b>\nInference Pipeline\n</b></h1> ","metadata":{}},{"cell_type":"markdown","source":"## **》》》 [IMPORTANT] Env Params**","metadata":{}},{"cell_type":"code","source":"\"\"\" Train Model \"\"\"\nmodel_path = \"/kaggle/input/byu-d-301/best.pt\"\n\n\"\"\" [IMPORTANT]\n* This parameter has a significant impact on the value of LB since it is the threshold for the prediction score inferred by the model.\n* In my experiments, 0.5 to 0.55 is optimal for local CV, but when submitting, 0.35 to 0.45 seems to give better results, so there is a difference.\n\"\"\"\nCONFIDENCE_THRESHOLD = 0.40\n\nMAX_DETECTIONS_PER_TOMO = 3\nNMS_IOU_THRESHOLD = 0.2\nCONCENTRATION = 1\nBATCH_SIZE = 8 ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T01:08:51.378233Z","iopub.execute_input":"2025-04-11T01:08:51.378475Z","iopub.status.idle":"2025-04-11T01:08:51.382608Z","shell.execute_reply.started":"2025-04-11T01:08:51.378454Z","shell.execute_reply":"2025-04-11T01:08:51.381839Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **》》》 Ultralytics Offline Install**(v8.3.88[2025/03/11 ReleaseVersion])","metadata":{}},{"cell_type":"code","source":"\"\"\"[INFO]\n* This notebookinstall Ultralytics v8.3.88(2025/03/11 ReleaseVersion)\n  Can use YOLO12 is latest family version. \n* If you need a newer version, you can make it available by running and attaching the notebook.\n  https://www.kaggle.com/code/hideyukizushi/ultralytics-offlineinstall-yolo12-weights\n\"\"\"\n!tar xfvz /kaggle/input/ultralytics-offlineinstall-yolo12-weights/archive.tar.gz\n!pip install --no-index --find-links=./packages ultralytics\n!rm -rf ./packages","metadata":{"trusted":true,"_kg_hide-input":false,"scrolled":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2025-04-11T01:08:51.383786Z","iopub.execute_input":"2025-04-11T01:08:51.384017Z","iopub.status.idle":"2025-04-11T01:10:00.559540Z","shell.execute_reply.started":"2025-04-11T01:08:51.383991Z","shell.execute_reply":"2025-04-11T01:10:00.558595Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **》》》 Import Libs**","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport torch\nimport cv2\nfrom tqdm.notebook import tqdm\nfrom ultralytics import YOLO\nimport threading\nimport time\nfrom contextlib import nullcontext\nfrom concurrent.futures import ThreadPoolExecutor","metadata":{"trusted":true,"_kg_hide-input":false,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2025-04-11T01:10:00.560596Z","iopub.execute_input":"2025-04-11T01:10:00.560997Z","iopub.status.idle":"2025-04-11T01:10:07.454394Z","shell.execute_reply.started":"2025-04-11T01:10:00.560960Z","shell.execute_reply":"2025-04-11T01:10:07.453530Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **》》》 Seed Fix**","metadata":{}},{"cell_type":"code","source":"np.random.seed(42)\ntorch.manual_seed(42)","metadata":{"trusted":true,"_kg_hide-input":false,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2025-04-11T01:10:07.455240Z","iopub.execute_input":"2025-04-11T01:10:07.455692Z","iopub.status.idle":"2025-04-11T01:10:07.464113Z","shell.execute_reply.started":"2025-04-11T01:10:07.455661Z","shell.execute_reply":"2025-04-11T01:10:07.463381Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## **》》》 Inference&Submission**","metadata":{}},{"cell_type":"markdown","source":"* Dataset","metadata":{}},{"cell_type":"code","source":"data_path = \"/kaggle/input/byu-locating-bacterial-flagellar-motors-2025/\"\ntest_dir = os.path.join(data_path, \"test\")\nsubmission_path = \"/kaggle/working/submission.csv\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T01:10:07.464970Z","iopub.execute_input":"2025-04-11T01:10:07.465254Z","iopub.status.idle":"2025-04-11T01:10:07.478149Z","shell.execute_reply.started":"2025-04-11T01:10:07.465226Z","shell.execute_reply":"2025-04-11T01:10:07.477385Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"* GPU Init","metadata":{}},{"cell_type":"code","source":"class GPUProfiler:\n    def __init__(self, name):\n        self.name = name\n        self.start_time = None\n        \n    def __enter__(self):\n        if torch.cuda.is_available():\n            torch.cuda.synchronize()\n        self.start_time = time.time()\n        return self\n        \n    def __exit__(self, *args):\n        if torch.cuda.is_available():\n            torch.cuda.synchronize()\n        elapsed = time.time() - self.start_time\n        # print(f\"[PROFILE] {self.name}: {elapsed:.3f}s\")\n\n\ndevice = 'cuda:0' if torch.cuda.is_available() else 'cpu'\nif device.startswith('cuda'):\n    # Set CUDA optimization flags\n    torch.backends.cudnn.benchmark = True\n    torch.backends.cudnn.deterministic = False\n    torch.backends.cuda.matmul.allow_tf32 = True  # Allow TF32 on Ampere GPUs\n    torch.backends.cudnn.allow_tf32 = True\n    \n    # Print GPU info\n    gpu_name = torch.cuda.get_device_name(0)\n    gpu_mem = torch.cuda.get_device_properties(0).total_memory / 1e9  # Convert to GB\n    print(f\"Using GPU: {gpu_name} with {gpu_mem:.2f} GB memory\")\n    \n    # Get available GPU memory and set batch size accordingly\n    free_mem = gpu_mem - torch.cuda.memory_allocated(0) / 1e9\n    BATCH_SIZE = max(8, min(32, int(free_mem * 4)))  # 4 images per GB as rough estimate\n    print(f\"Dynamic batch size set to {BATCH_SIZE} based on {free_mem:.2f}GB free memory\")\nelse:\n    print(\"GPU not available, using CPU\")\n    BATCH_SIZE = 4  # Reduce batch size for CPU","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-11T01:10:07.478984Z","iopub.execute_input":"2025-04-11T01:10:07.479190Z","iopub.status.idle":"2025-04-11T01:10:07.592947Z","shell.execute_reply.started":"2025-04-11T01:10:07.479171Z","shell.execute_reply":"2025-04-11T01:10:07.592116Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"* Inference","metadata":{}},{"cell_type":"code","source":"def normalize_slice(slice_data):\n    \"\"\"\n    Normalize slice data using 2nd and 98th percentiles for better contrast\n    \"\"\"\n    p2 = np.percentile(slice_data, 2)\n    p98 = np.percentile(slice_data, 98)\n    clipped_data = np.clip(slice_data, p2, p98)\n    normalized = 255 * (clipped_data - p2) / (p98 - p2)\n    return np.uint8(normalized)\n\ndef preload_image_batch(file_paths):\n    \"\"\"Preload a batch of images to CPU memory\"\"\"\n    images = []\n    for path in file_paths:\n        img = cv2.imread(path)\n        if img is None:\n            # Try with PIL as fallback\n            img = np.array(Image.open(path))\n        images.append(img)\n    return images\n\ndef process_tomogram(tomo_id, model, index=0, total=1):\n    \"\"\"\n    Process a single tomogram and return the most confident motor detection\n    \"\"\"\n    # print(f\"Processing tomogram {tomo_id} ({index}/{total})\")\n    \n    # Get all slice files for this tomogram\n    tomo_dir = os.path.join(test_dir, tomo_id)\n    slice_files = sorted([f for f in os.listdir(tomo_dir) if f.endswith('.jpg')])\n    \n    # Apply CONCENTRATION to reduce the number of slices processed\n    # This will process approximately CONCENTRATION fraction of all slices\n    selected_indices = np.linspace(0, len(slice_files)-1, int(len(slice_files) * CONCENTRATION))\n    selected_indices = np.round(selected_indices).astype(int)\n    slice_files = [slice_files[i] for i in selected_indices]\n    \n\n    all_detections = []\n    if device.startswith('cuda'):\n        streams = [torch.cuda.Stream() for _ in range(min(4, BATCH_SIZE))]\n    else:\n        streams = [None]\n    \n    # Variables for preloading\n    next_batch_thread = None\n    next_batch_images = None\n    \n    # Process slices in batches\n    for batch_start in range(0, len(slice_files), BATCH_SIZE):\n        # Wait for previous preload thread if it exists\n        if next_batch_thread is not None:\n            next_batch_thread.join()\n            next_batch_images = None\n            \n        batch_end = min(batch_start + BATCH_SIZE, len(slice_files))\n        batch_files = slice_files[batch_start:batch_end]\n        \n        # Start preloading next batch\n        next_batch_start = batch_end\n        next_batch_end = min(next_batch_start + BATCH_SIZE, len(slice_files))\n        next_batch_files = slice_files[next_batch_start:next_batch_end] if next_batch_start < len(slice_files) else []\n        \n        if next_batch_files:\n            next_batch_paths = [os.path.join(tomo_dir, f) for f in next_batch_files]\n            next_batch_thread = threading.Thread(target=preload_image_batch, args=(next_batch_paths,))\n            next_batch_thread.start()\n        else:\n            next_batch_thread = None\n        \n        # Split batch across streams for parallel processing\n        sub_batches = np.array_split(batch_files, len(streams))\n        sub_batch_results = []\n        \n        for i, sub_batch in enumerate(sub_batches):\n            if len(sub_batch) == 0:\n                continue\n                \n            stream = streams[i % len(streams)]\n            with torch.cuda.stream(stream) if stream and device.startswith('cuda') else nullcontext():\n                # Process sub-batch\n                sub_batch_paths = [os.path.join(tomo_dir, slice_file) for slice_file in sub_batch]\n                sub_batch_slice_nums = [int(slice_file.split('_')[1].split('.')[0]) for slice_file in sub_batch]\n                \n                # Run inference with profiling\n                with GPUProfiler(f\"Inference batch {i+1}/{len(sub_batches)}\"):\n                    sub_results = model(sub_batch_paths, verbose=False)\n                \n                # Process each result in this sub-batch\n                for j, result in enumerate(sub_results):\n                    if len(result.boxes) > 0:\n                        boxes = result.boxes\n                        for box_idx, confidence in enumerate(boxes.conf):\n                            if confidence >= CONFIDENCE_THRESHOLD:\n                                # Get bounding box coordinates\n                                x1, y1, x2, y2 = boxes.xyxy[box_idx].cpu().numpy()\n                                \n                                # Calculate center coordinates\n                                x_center = (x1 + x2) / 2\n                                y_center = (y1 + y2) / 2\n                                \n                                # Store detection with 3D coordinates\n                                all_detections.append({\n                                    'z': round(sub_batch_slice_nums[j]),\n                                    'y': round(y_center),\n                                    'x': round(x_center),\n                                    'confidence': float(confidence)\n                                })\n        \n        # Synchronize streams\n        if device.startswith('cuda'):\n            torch.cuda.synchronize()\n    \n    # Clean up thread if still running\n    if next_batch_thread is not None:\n        next_batch_thread.join()\n    \n    # 3D Non-Maximum Suppression to merge nearby detections across slices\n    final_detections = perform_3d_nms(all_detections, NMS_IOU_THRESHOLD)\n    \n    # Sort detections by confidence (highest first)\n    final_detections.sort(key=lambda x: x['confidence'], reverse=True)\n    \n    # If there are no detections, return NA values\n    if not final_detections:\n        return {\n            'tomo_id': tomo_id,\n            'Motor axis 0': -1,\n            'Motor axis 1': -1,\n            'Motor axis 2': -1\n        }\n    \n    # Take the detection with highest confidence\n    best_detection = final_detections[0]\n    \n    # Return result with integer coordinates\n    return {\n        'tomo_id': tomo_id,\n        'Motor axis 0': round(best_detection['z']),\n        'Motor axis 1': round(best_detection['y']),\n        'Motor axis 2': round(best_detection['x'])\n    }\n\ndef perform_3d_nms(detections, iou_threshold):\n    \"\"\"\n    Perform 3D Non-Maximum Suppression on detections to merge nearby motors\n    \"\"\"\n    if not detections:\n        return []\n    \n    # Sort by confidence (highest first)\n    detections = sorted(detections, key=lambda x: x['confidence'], reverse=True)\n    \n    # List to store final detections after NMS\n    final_detections = []\n    \n    # Define 3D distance function\n    def distance_3d(d1, d2):\n        return np.sqrt((d1['z'] - d2['z'])**2 + \n                       (d1['y'] - d2['y'])**2 + \n                       (d1['x'] - d2['x'])**2)\n    \n    # Maximum distance threshold (based on box size and slice gap)\n    box_size = 24  # Same as annotation box size\n    distance_threshold = box_size * iou_threshold\n    \n    # Process each detection\n    while detections:\n        # Take the detection with highest confidence\n        best_detection = detections.pop(0)\n        final_detections.append(best_detection)\n        \n        # Filter out detections that are too close to the best detection\n        detections = [d for d in detections if distance_3d(d, best_detection) > distance_threshold]\n    \n    return final_detections\n\ndef debug_image_loading(tomo_id):\n    \"\"\"\n    Debug function to check image loading\n    \"\"\"\n    tomo_dir = os.path.join(test_dir, tomo_id)\n    slice_files = sorted([f for f in os.listdir(tomo_dir) if f.endswith('.jpg')])\n    \n    if not slice_files:\n        print(f\"No image files found in {tomo_dir}\")\n        return\n        \n    sample_file = slice_files[len(slice_files)//2]  # Middle slice\n    img_path = os.path.join(tomo_dir, sample_file)\n    \n    # Try different loading methods\n    try:\n        # Method 1: PIL\n        img_pil = Image.open(img_path)\n        img_array_pil = np.array(img_pil)\n        \n        # Method 2: OpenCV\n        img_cv2 = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n        # print(f\"OpenCV Image shape: {img_cv2.shape}, dtype: {img_cv2.dtype}\")\n        \n        # Method 3: Convert to RGB\n        img_rgb = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)\n    except Exception as e:\n        print(f\"Error loading image {img_path}: {e}\")\n        \n    # Also test with YOLO's built-in loader\n    try:\n        test_model = YOLO(model_path)\n        test_results = test_model([img_path], verbose=False)\n        # print(\"YOLO model successfully processed the test image\")\n    except Exception as e:\n        print(f\"Error with YOLO processing: {e}\")\n\ndef generate_submission():\n    \"\"\"\n    Main function to generate the submission file\n    \"\"\"\n    test_tomos = sorted([d for d in os.listdir(test_dir) if os.path.isdir(os.path.join(test_dir, d))])\n    total_tomos = len(test_tomos)\n    \n    if test_tomos:\n        debug_image_loading(test_tomos[0])\n    \n    if torch.cuda.is_available():\n        torch.cuda.empty_cache()\n    \n    model = YOLO(model_path)\n    model.to(device)\n    \n    # Additional optimizations for inference\n    if device.startswith('cuda'):\n        # Fuse conv and bn layers for faster inference\n        model.fuse()\n        \n        # Enable model half precision (FP16) if on compatible GPU\n        if torch.cuda.get_device_capability(0)[0] >= 7:  # Volta or newer\n            model.model.half()\n    \n    # Process tomograms with parallelization\n    results = []\n    motors_found = 0\n\n    with ThreadPoolExecutor(max_workers=1) as executor:\n        future_to_tomo = {}\n        \n        # Submit all tomograms for processing\n        for i, tomo_id in enumerate(test_tomos, 1):\n            future = executor.submit(process_tomogram, tomo_id, model, i, total_tomos)\n            future_to_tomo[future] = tomo_id\n        \n        # Process completed futures as they complete\n        for future in future_to_tomo:\n            tomo_id = future_to_tomo[future]\n            try:\n                # Clear CUDA cache between tomograms\n                if torch.cuda.is_available():\n                    torch.cuda.empty_cache()\n                    \n                result = future.result()\n                results.append(result)\n                \n                # Update motors found count\n                has_motor = not pd.isna(result['Motor axis 0'])\n                if has_motor:\n                    motors_found += 1\n                    print(f\"Motor found in {tomo_id} at position: \"\n                          f\"z={result['Motor axis 0']}, y={result['Motor axis 1']}, x={result['Motor axis 2']}\")\n                else:\n                    print(f\"No motor detected in {tomo_id}\")\n                    \n                print(f\"Current detection rate: {motors_found}/{len(results)} ({motors_found/len(results)*100:.1f}%)\")\n            \n            except Exception as e:\n                print(f\"Error processing {tomo_id}: {e}\")\n                # Create a default entry for failed tomograms\n                results.append({\n                    'tomo_id': tomo_id,\n                    'Motor axis 0': -1,\n                    'Motor axis 1': -1,\n                    'Motor axis 2': -1\n                })\n    \n    # Create submission dataframe\n    submission_df = pd.DataFrame(results)\n    \n    # Ensure proper column order\n    submission_df = submission_df[['tomo_id', 'Motor axis 0', 'Motor axis 1', 'Motor axis 2']]\n    \n    # Save the submission file\n    submission_df.to_csv(submission_path, index=False)\n    print(\"=\"*50)\n    print(\"= Submission preview:\")\n    print(\"=\"*50)\n    print(submission_df.head())\n    \n    return submission_df\n\n# Run the submission pipeline\nif __name__ == \"__main__\":\n    # Time entire process\n    start_time = time.time()\n    \n    # Generate submission\n    submission = generate_submission()\n    \n    # Print total execution time\n    elapsed = time.time() - start_time\n    print(f\"\\nTotal execution time: {elapsed:.2f} seconds ({elapsed/60:.2f} minutes)\")","metadata":{"trusted":true,"scrolled":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2025-04-11T01:10:07.593854Z","iopub.execute_input":"2025-04-11T01:10:07.594101Z","iopub.status.idle":"2025-04-11T01:12:37.028001Z","shell.execute_reply.started":"2025-04-11T01:10:07.594081Z","shell.execute_reply":"2025-04-11T01:12:37.027100Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}