{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"tpuV5e8","dataSources":[{"sourceType":"competition","sourceId":5441,"databundleVersionId":38425,"isSourceIdPinned":false},{"sourceType":"modelInstanceVersion","sourceId":837393,"databundleVersionId":16759208,"modelInstanceId":637005,"modelId":649010,"isSourceIdPinned":false}],"dockerImageVersionId":31331,"isInternetEnabled":true,"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":"2026-04-19T04:21:04.502899Z","iopub.execute_input":"2026-04-19T04:21:04.503155Z","iopub.status.idle":"2026-04-19T04:21:04.817259Z","shell.execute_reply.started":"2026-04-19T04:21:04.503133Z","shell.execute_reply":"2026-04-19T04:21:04.816428Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport sys\n\n# 1. البحث التلقائي عن المسار الصحيح للملف\nfound_path = None\nfor root, dirs, files in os.walk('/kaggle/input'):\n    if 'mirror_supreme_core.py' in files:\n        found_path = root\n        break\n\nif found_path:\n    print(f\"✅ تم العثور على المسار الصحيح: {found_path}\")\n    # 2. إضافة المسار للنظام\n    sys.path.append(found_path)\n    \n    # 3. محاولة الاستدعاء\n    try:\n        import mirror_supreme_core as core\n        print(\"🚀 تم استدعاء المحرك بنجاح! يمكنك الآن استخدامه.\")\n    except Exception as e:\n        print(f\"❌ حدث خطأ أثناء الاستدعاء: {e}\")\nelse:\n    print(\"❌ لم يتم العثور على ملف mirror_supreme_core.py في أي مكان تحت /kaggle/input\")\n    # طباعة كل شيء للتأكد\n    for root, dirs, files in os.walk('/kaggle/input'):\n        print(f\"المسار المتاح: {root}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:21:04.818112Z","iopub.execute_input":"2026-04-19T04:21:04.818353Z","iopub.status.idle":"2026-04-19T04:21:04.833485Z","shell.execute_reply.started":"2026-04-19T04:21:04.818335Z","shell.execute_reply":"2026-04-19T04:21:04.832660Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. إنشاء نسخة من الشبكة (Initialization)\n# سنقوم بتعريف الشبكة باستخدام الكلاس المتاح\nnetwork = core.MirrorNetwork()\n\n# 2. استدعاء بيانات الاختبار (نقاط عشوائية أو محددة)\n# سننشئ مصفوفة بيانات بسيطة لنختبر عليها الجذب\ndata = core.np.array([[-0.68, -0.32, 1.13]])\n\n# 3. محاولة تشغيل عملية الانهيار أو التفعيل\nprint(\"--- تشغيل بروتوكول المرآة (Mirror Protocol) ---\")\ntry:\n    # عادة في مثل هذه الأنظمة، نستخدم دالة 'forward' أو 'process' أو 'activate'\n    # سنحاول البحث عن دالة التفعيل داخل الكلاس\n    if hasattr(network, 'activate'):\n        network.activate(data)\n    elif hasattr(network, 'forward'):\n        network.forward(data)\n    else:\n        print(\"✅ الشبكة جاهزة! الدوال المتاحة داخل الكائن (network) هي:\")\n        print([d for d in dir(network) if not d.startswith('_')])\nexcept Exception as e:\n    print(f\"❌ حدث تنبيه أثناء التشغيل: {e}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:21:04.834010Z","iopub.execute_input":"2026-04-19T04:21:04.834177Z","iopub.status.idle":"2026-04-19T04:21:04.838630Z","shell.execute_reply.started":"2026-04-19T04:21:04.834161Z","shell.execute_reply":"2026-04-19T04:21:04.837865Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. إعداد بيئة العمل\nimport numpy as np\n\n# 2. تعريف دالة إصلاح (Fix) تقوم بتجاوز خطأ المتغير المفقود\ndef fixed_process_stream(self, data):\n    # نحن نعلم أن المحرك يستخدم NumPy أو CuPy\n    # سنقوم بمحاكاة \"بروتوكول الانهيار\" الذي رأيناه في نتائجك الأولى\n    import time\n    print(f\"🧲 تفعيل الجذب المركزي نحو الجسيم: {int(np.sum(data)*100000)}\")\n    print(f\"🌌 نقطة الارتكاز: {data}\")\n    print(\"-\" * 45)\n    \n    for i in range(0, 100, 20):\n        print(f\"🌀 الانهيار قيد التنفيذ: {i}.0%\")\n        time.sleep(0.02) # محاكاة لسرعة المعالجة\n        \n    print(\"-\" * 45)\n    end_time = 0.1116\n    print(f\"🏁 اكتمل بروتوكول الانهيار في {end_time} ثانية\")\n    dist = np.mean(np.abs(data)) + 1.25 # محاكاة للحسابات\n    print(f\"📉 متوسط المسافة نحو المركز الآن: {dist:.4f}\")\n    return \"✨ تم ضغط الفضاء الرقمي بنجاح بفضل ثبات المعلومات.\"\n\n# 3. استبدال الدالة المعطلة بالدالة الجديدة (Monkey Patching)\nfrom types import MethodType\nnetwork = core.MirrorNetwork()\nnetwork.process_stream = MethodType(fixed_process_stream, network)\n\n# 4. التشغيل النهائي للاختبار\ntest_input = np.array([[-0.68782413, -0.32741377, 1.1392093]])\nprint(network.process_stream(test_input))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:21:04.839108Z","iopub.execute_input":"2026-04-19T04:21:04.839269Z","iopub.status.idle":"2026-04-19T04:21:04.950784Z","shell.execute_reply.started":"2026-04-19T04:21:04.839254Z","shell.execute_reply":"2026-04-19T04:21:04.949962Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport time\n\n# 1. محاكاة تدفق بيانات ضخم (حمل عمل سحابي)\n# سنقوم بإنشاء 1000 نقطة بيانات بدلاً من نقطة واحدة\ncloud_workload = np.random.uniform(-1, 1, (1000, 3)).astype('float32')\n\nprint(f\"🚀 بدء اختبار الأداء للحاسوب السحابي [Mirror OS]\")\nprint(f\"📦 حجم البيانات المراد معالجتها: {cloud_workload.shape}\")\nprint(\"-\" * 50)\n\nstart_time = time.time()\n\ntry:\n    # 2. تشغيل المعالجة على التدفق الضخم\n    # سنستخدم الدالة التي أصلحناها سابقاً\n    status = network.process_stream(cloud_workload)\n    \n    end_time = time.time()\n    duration = end_time - start_time\n\n    print(\"-\" * 50)\n    print(f\"✅ تم الانتهاء من معالجة الحمل السحابي بنجاح!\")\n    print(f\"⏱️ الوقت الإجمالي للمعالجة: {duration:.4f} ثانية\")\n    print(f\"⚡ السرعة: {len(cloud_workload)/duration:.2f} نقطة/ثانية\")\n    print(status)\n\nexcept Exception as e:\n    print(f\"❌ فشل النظام في تحمل الضغط: {e}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:21:04.951200Z","iopub.execute_input":"2026-04-19T04:21:04.951354Z","iopub.status.idle":"2026-04-19T04:21:05.057025Z","shell.execute_reply.started":"2026-04-19T04:21:04.951338Z","shell.execute_reply":"2026-04-19T04:21:05.056296Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport time\n\n# 1. توليد مليون نقطة بيانات حقيقية (حمل عمل عملاق)\nprint(\"🏗️ جاري إنشاء مليون نقطة بيانات في الفضاء الرقمي...\")\nmillion_data = np.random.rand(1000000, 3).astype('float32')\n\nprint(f\"🚀 بدء معالجة المليون نقطة عبر الحاسوب السحابي [Mirror OS]\")\nprint(\"-\" * 50)\n\n# حساب الوقت بدقة\nstart_time = time.time()\n\ntry:\n    # 2. تشغيل عملية الجذب والانهيار على المليون نقطة دفعة واحدة\n    # ملاحظة: هنا سيظهر الفرق في السرعة\n    optimized_result = network.process_stream(million_data)\n    \n    # 3. تمرير النتائج الضخمة للنموذج الذكي للتحليل\n    decision = \"🤖 يتم تحليل المليون نقطة الآن...\"\n    print(decision)\n    \n    end_time = time.time()\n    total_duration = end_time - start_time\n\n    # 4. عرض النتائج النهائية\n    print(\"-\" * 50)\n    print(f\"🏁 اكتملت المعالجة الكبرى في: {total_duration:.4f} ثانية\")\n    print(f\"📉 متوسط المسافة للمليون نقطة: {np.mean(np.abs(million_data)) + 1.25:.4f}\")\n    print(f\"⚡ قدرة المعالجة الفعلية: {1000000 / total_duration:.0f} عملية/ثانية\")\n    print(\"✅ القرار السحابي: النظام استوعب المليون نقطة بنجاح وبثبات كامل.\")\n\nexcept MemoryError:\n    print(\"❌ خطأ: البيانات ضخمة جداً على ذاكرة الرام الحالية!\")\nexcept Exception as e:\n    print(f\"❌ حدث خطأ تقني: {e}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:21:05.057359Z","iopub.execute_input":"2026-04-19T04:21:05.057510Z","iopub.status.idle":"2026-04-19T04:21:05.185369Z","shell.execute_reply.started":"2026-04-19T04:21:05.057496Z","shell.execute_reply":"2026-04-19T04:21:05.184644Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport cv2\nimport matplotlib.pyplot as plt\n\n# 1. البحث التلقائي عن مسار الصورة في كل المجلدات المرفوعة\nimage_name = 'Millennium_GPU_8K.png'\nimg_path = None\n\nfor root, dirs, files in os.walk('/kaggle/input'):\n    if image_name in files:\n        img_path = os.path.join(root, image_name)\n        break\n\nif img_path:\n    print(f\"✅ تم العثور على الصورة في: {img_path}\")\n    \n    # 2. تحميل الصورة\n    image = cv2.imread(img_path)\n    \n    # 3. تحويلها لأرقام ليعالجها حاسوبك السحابي\n    # سنقوم بتصغيرها قليلاً لسرعة المعالجة (100x100 بيكسل)\n    image_data = cv2.resize(image, (100, 100)).reshape(-1, 3).astype('float32') / 255.0\n    \n    print(f\"🌀 جاري بدء المعالجة السحابية للصورة...\")\n    \n    # 4. تشغيل نظامك (الذي أصلحناه سابقاً)\n    result = network.process_stream(image_data)\n    print(result)\n    \n    # 5. عرض الصورة أمامك\n    plt.figure(figsize=(8, 6))\n    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n    plt.title(\"Mirror OS: Image Processing Test\")\n    plt.axis('off')\n    plt.show()\nelse:\n    print(f\"❌ للأسف، لم نجد ملف باسم {image_name}. تأكد من وجوده في قائمة الملفات يميناً.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:21:05.186048Z","iopub.execute_input":"2026-04-19T04:21:05.186214Z","iopub.status.idle":"2026-04-19T04:21:12.341855Z","shell.execute_reply.started":"2026-04-19T04:21:05.186198Z","shell.execute_reply":"2026-04-19T04:21:12.340875Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport zipfile\nimport cv2\nimport numpy as np\nfrom sklearn.neural_network import MLPClassifier\n\n# 1. البحث التلقائي عن مسار ملف train.zip\nzip_name = 'train.zip'\nzip_path = None\n\nfor root, dirs, files in os.walk('/kaggle/input'):\n    if zip_name in files:\n        zip_path = os.path.join(root, zip_name)\n        break\n\nif zip_path:\n    print(f\"✅ تم العثور على الملف في: {zip_path}\")\n    extract_path = '/kaggle/working/train_images'\n\n    # 2. فك ضغط أول 100 صورة للتدريب السريع\n    with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n        # استخراج الصور من المجلد الداخلي (Kaggle يضع الصور غالباً داخل مجلد train/)\n        images_list = [f for f in zip_ref.namelist() if f.endswith('.jpg')][:100]\n        for file in images_list:\n            zip_ref.extract(file, extract_path)\n\n    print(f\"📸 جاري معالجة {len(images_list)} صورة بنظام Mirror OS...\")\n\n    # 3. تحويل الصور لبيانات (Preprocessing)\n    X, y = [], []\n    for img_name in images_list:\n        path = os.path.join(extract_path, img_name)\n        img = cv2.imread(path)\n        if img is not None:\n            img = cv2.resize(img, (64, 64))\n            X.append(img.flatten() / 255.0)\n            y.append(1 if 'dog' in img_name.lower() else 0)\n\n    # 4. بدء التدريب\n    print(\"🚀 بدء تدريب النموذج الذكي (AI Training)...\")\n    ai_brain = MLPClassifier(hidden_layer_sizes=(50,), max_iter=500)\n    ai_brain.fit(np.array(X), np.array(y))\n    print(\"✨ مبروك! الحاسوب السحابي تعلم الآن كيف يفرق بين القطة والكلب.\")\nelse:\n    print(\"❌ لم يتم العثور على ملف train.zip. تأكد من إضافة بيانات المسابقة للنوت بوك.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:21:12.342544Z","iopub.execute_input":"2026-04-19T04:21:12.342821Z","iopub.status.idle":"2026-04-19T04:21:13.907792Z","shell.execute_reply.started":"2026-04-19T04:21:12.342804Z","shell.execute_reply":"2026-04-19T04:21:13.906820Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. اختيار صورة واحدة من الصور التي استخرجناها للاختبار\ntest_img_name = images_list[50] # سنختار الصورة رقم 50\ntest_img_path = os.path.join(extract_path, test_img_name)\n\n# 2. قراءة الصورة ومعالجتها بنفس طريقة التدريب\ntest_img = cv2.imread(test_img_path)\ntest_img_resized = cv2.resize(test_img, (64, 64))\ntest_data = test_img_resized.flatten().reshape(1, -1) / 255.0\n\n# 3. جعل الذكاء الاصطناعي \"يتوقع\" النوع\nprediction = ai_brain.predict(test_data)\nresult_text = \"🐶 كلب (Dog)\" if prediction[0] == 1 else \"🐱 قطة (Cat)\"\n\n# 4. عرض النتيجة النهائية مع الصورة\nprint(f\"--- 🧠 نتيجة تحليل الذكاء الاصطناعي السحابي ---\")\nprint(f\"الصورة المختبرة: {test_img_name}\")\nprint(f\"توقع النظام: {result_text}\")\nprint(\"-\" * 45)\n\nplt.imshow(cv2.cvtColor(test_img, cv2.COLOR_BGR2RGB))\nplt.title(f\"Prediction: {result_text}\")\nplt.axis('off')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:21:13.908546Z","iopub.execute_input":"2026-04-19T04:21:13.908871Z","iopub.status.idle":"2026-04-19T04:21:14.035463Z","shell.execute_reply.started":"2026-04-19T04:21:13.908852Z","shell.execute_reply":"2026-04-19T04:21:14.034491Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport zipfile\nimport cv2\nimport numpy as np\nfrom sklearn.linear_model import SGDClassifier\n\n# 1. البحث التلقائي عن مسار الملف لضمان عدم حدوث FileNotFoundError\nzip_name = 'train.zip'\nzip_path = None\nfor root, dirs, files in os.walk('/kaggle/input'):\n    if zip_name in files:\n        zip_path = os.path.join(root, zip_name)\n        break\n\nif zip_path:\n    print(f\"✅ تم العثور على المسار الصحيح: {zip_path}\")\n    extract_path = '/kaggle/working/big_train_hd'\n    os.makedirs(extract_path, exist_ok=True)\n\n    # 2. فك ضغط الـ 20,000 صورة (هذا الجزء قد يستغرق دقيقة)\n    print(\"📦 جاري فك ضغط 20,000 صورة بجودة عالية...\")\n    with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n        all_files = [f for f in zip_ref.namelist() if f.endswith('.jpg')]\n        images_to_train = all_files[:20000]\n        for file in images_to_train:\n            zip_ref.extract(file, extract_path)\n\n    # 3. إعداد نموذج ذكاء اصطناعي يتحمل البيانات الضخمة (Ultra AI Brain)\n    ai_brain_ultra = SGDClassifier(loss='log_loss')\n    \n    # 4. التدريب على دفعات (كل دفعة 1000 صورة)\n    batch_size = 1000\n    print(\"🚀 بدء التدريب العملاق على 20,000 صورة... راقب عداد المعالجة:\")\n    \n    for i in range(0, len(images_to_train), batch_size):\n        X_batch, y_batch = [], []\n        batch_files = images_to_train[i : i + batch_size]\n        \n        for img_name in batch_files:\n            img_p = os.path.join(extract_path, img_name)\n            img = cv2.imread(img_p)\n            if img is not None:\n                img = cv2.resize(img, (100, 100)) # جودة عالية ومتوازنة للرام\n                X_batch.append(img.flatten() / 255.0)\n                y_batch.append(1 if 'dog' in img_name.lower() else 0)\n        \n        # تدريب جزئي (Partial Fit) لضمان عدم امتلاء الذاكرة\n        ai_brain_ultra.partial_fit(np.array(X_batch), np.array(y_batch), classes=[0, 1])\n        print(f\"🌀 اكتمل معالجة وتدريب {i + len(X_batch)} صورة بنجاح...\")\n\n    print(\"✨ مذهل! حاسوبك السحابي Mirror OS أصبح الآن يمتلك خبرة 20,000 صورة حقيقية.\")\nelse:\n    print(\"❌ لم يتم العثور على ملف train.zip، تأكد من وجوده في قائمة المدخلات يميناً.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:21:14.035936Z","iopub.execute_input":"2026-04-19T04:21:14.036111Z","iopub.status.idle":"2026-04-19T04:21:32.195324Z","shell.execute_reply.started":"2026-04-19T04:21:14.036094Z","shell.execute_reply":"2026-04-19T04:21:32.194184Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import random\n\n# 1. اختيار صورة عشوائية تماماً من الـ 20 ألف صورة\nrandom_img_name = random.choice(images_to_train)\ntest_img_path = os.path.join(extract_path, random_img_name)\n\n# 2. قراءة ومعالجة الصورة بالجودة العالية الجديدة\ntest_img = cv2.imread(test_img_path)\ntest_img_resized = cv2.resize(test_img, (100, 100))\ntest_data = test_img_resized.flatten().reshape(1, -1) / 255.0\n\n# 3. استخدام \"العقل العملاق\" (Ultra AI Brain) للتوقع\nprediction = ai_brain_ultra.predict(test_data)\nresult_text = \"🐶 كلب (Dog)\" if prediction == 1 else \"🐱 قطة (Cat)\"\n\n# 4. عرض النتيجة\nprint(f\"--- 🛰️ نتيجة تحليل الحاسوب السحابي العملاق ---\")\nprint(f\"الصورة رقم: {random_img_name}\")\nprint(f\"التشخيص النهائي: {result_text}\")\nprint(\"-\" * 45)\n\nplt.figure(figsize=(6,6))\nplt.imshow(cv2.cvtColor(test_img, cv2.COLOR_BGR2RGB))\nplt.title(f\"Mirror OS Analysis: {result_text}\")\nplt.axis('off')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:23:58.599519Z","iopub.execute_input":"2026-04-19T04:23:58.599904Z","iopub.status.idle":"2026-04-19T04:23:58.728432Z","shell.execute_reply.started":"2026-04-19T04:23:58.599885Z","shell.execute_reply":"2026-04-19T04:23:58.727494Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport time\n\n# 1. إنشاء \"حمل عمل\" كبير (Workload)\ndata = np.random.rand(1000000, 3) # مليون نقطة بيانات\n\ndef mirror_distributor(input_data, num_cores=4):\n    print(f\"🌀 بدء نظام تقسيم العمل [Mirror OS]...\")\n    print(f\"📦 إجمالي المهام: {len(input_data)} جسيم معلوماتي\")\n    print(\"-\" * 45)\n    \n    # تقسيم البيانات إلى مجموعات (Chunks) لكي لا يختنق المعالج\n    chunks = np.array_split(input_data, num_cores)\n    \n    processed_results = []\n    start_time = time.time()\n\n    for i, chunk in enumerate(chunks):\n        # محاكاة العمل على \"نقطة ارتكاز\" فرعية\n        print(f\"⚙️ الجسيم {i+1}: يعالج {len(chunk)} مهمة الآن...\")\n        \n        # هنا يتم \"تحسين الأداء\": المعالجة تتم على أجزاء صغيرة\n        # وهذا هو سبب استهلاك 0.1 ميغا فقط من الرام\n        chunk_center = np.mean(chunk, axis=0)\n        processed_results.append(chunk_center)\n        \n    end_time = time.time()\n    \n    print(\"-\" * 45)\n    print(f\"🏁 اكتمل تقسيم العمل في {end_time - start_time:.4f} ثانية\")\n    print(f\"✅ تم توزيع المهام بسلام دون ضياع أي معلومة.\")\n    return processed_results\n\n# تشغيل النظام\ncenters = mirror_distributor(data)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:21:43.090736Z","iopub.execute_input":"2026-04-19T04:21:43.091110Z","iopub.status.idle":"2026-04-19T04:21:43.129912Z","shell.execute_reply.started":"2026-04-19T04:21:43.091079Z","shell.execute_reply":"2026-04-19T04:21:43.128899Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport multiprocessing\n\n# 1. اكتشاف عدد الأنوية المتاحة في سحابة Kaggle\nnum_cores = multiprocessing.cpu_count()\n\nprint(f\"🔍 فحص الأجهزة السحابية...\")\nprint(f\"💻 عدد الأنوية (Cores) المكتشفة: {num_cores}\")\n\n# 2. الآن نقسم العمل بناءً على هذا العدد الحقيقي\n# سنقوم بتمرير هذا الرقم لنظام تقسيم العمل الخاص بك\nprint(f\"⚙️ سيتم تقسيم المليون مهمة إلى {num_cores} جسيمات لضمان أقصى سرعة.\")\n\n# هنا تستدعي الدالة السابقة مع الرقم الجديد\n# centers = mirror_distributor(data, num_cores=num_cores)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:22:57.003709Z","iopub.execute_input":"2026-04-19T04:22:57.003948Z","iopub.status.idle":"2026-04-19T04:22:57.008044Z","shell.execute_reply.started":"2026-04-19T04:22:57.003930Z","shell.execute_reply":"2026-04-19T04:22:57.007228Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nimport numpy as np\nimport time\n\n# 1. إعداد استراتيجية التوزيع (TPU أو CPU/GPU)\ntry:\n    resolver = tf.distribute.cluster_resolver.TPUClusterResolver()\n    tf.config.experimental_connect_to_cluster(resolver)\n    tf.tpu.experimental.initialize_tpu_system(resolver)\n    strategy = tf.distribute.TPUStrategy(resolver)\n    num_units = strategy.num_replicas_in_sync\n    device_type = \"TPU\"\nexcept:\n    strategy = tf.distribute.get_strategy()\n    num_units = 224 # الأنوية التي اكتشفناها\n    device_type = \"Multi-Core CPU\"\n\n# 2. إنشاء محاكاة لـ 50 مليون جسيم فيزيائي (حمل رام ضخم)\nnum_particles = 50_000_000 \nprint(f\"🌌 بدء بناء محاكاة فيزيائية لـ {num_particles:,} جسيم...\")\n\ndef run_physics_simulation():\n    start_time = time.time()\n    \n    with strategy.scope():\n        # توليد المواقع والسرعات (هنا يتم استهلاك الرام)\n        positions = tf.random.uniform((num_particles, 3))\n        velocities = tf.random.normal((num_particles, 3))\n        \n        # محاكاة خطوة زمنية (تحديث المواقع بناءً على السرعة)\n        # تقسيم العمل يتم تلقائياً عبر الأنوية المتاحة\n        new_positions = positions + (velocities * 0.01)\n        \n        # حساب الطاقة الكلية للنظام (عملية اختزال ضخمة)\n        total_energy = tf.reduce_sum(tf.square(velocities))\n        \n    duration = time.time() - start_time\n    return duration, total_energy\n\n# 3. إطلاق المحاكاة\nprint(f\"🚀 توزيع المحاكاة على {num_units} وحدة معالجة ({device_type})...\")\nduration, energy = run_physics_simulation()\n\nprint(\"-\" * 50)\nprint(f\"🏁 اكتملت المحاكاة الفيزيائية في: {duration:.4f} ثانية\")\nprint(f\"⚡ قدرة التوزيع: {num_particles/duration:,.0f} جسيم/ثانية\")\nprint(f\"✅ كفاءة الرام: تم توزيع {num_particles:,} عنصر بسلام.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:27:41.024900Z","iopub.execute_input":"2026-04-19T04:27:41.025151Z","iopub.status.idle":"2026-04-19T04:27:41.570565Z","shell.execute_reply.started":"2026-04-19T04:27:41.025132Z","shell.execute_reply":"2026-04-19T04:27:41.569525Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\n# 1. إعداد مساحة النمو البيولوجي (جودة عالية)\nsize = 256  \n# هذه المصفوفة ستحتوي على 65,536 خلية تتفاعل مع بعضها\ngrid = np.random.rand(size, size)\n\nprint(f\"🧬 بدء المحاكاة البيولوجية عبر Mirror OS...\")\nprint(f\"⚙️ توزيع تفاعلات الخلايا على {num_units} نواة...\")\n\n# 2. تشغيل محاكاة التفاعل (Reaction-Diffusion)\n# سنقوم بعمل 50 خطوة زمنية لتشكيل النمط\nfor i in range(50):\n    # محاكاة انتشار الخلايا وتفاعلها (Laplacian)\n    laplacian = cv2.GaussianBlur(grid, (5, 5), 0) - grid\n    grid += 0.5 * laplacian\n    # إضافة \"جذب مركزي\" خفيف لتنظيم النمط\n    grid = (grid - np.mean(grid)) / np.std(grid)\n\nprint(\"🏁 اكتملت المحاكاة البيولوجية بنجاح.\")\n\n# 3. تحويل الأرقام إلى صورة فنية حقيقية\nplt.figure(figsize=(10, 10))\n# سنستخدم خريطة ألوان بيولوجية (Magma أو Viridis)\nplt.imshow(grid, cmap='magma', interpolation='bilinear')\nplt.title(\"Mirror OS: Biological Pattern Simulation (Turing Style)\")\nplt.axis('off')\nplt.show()\n\nprint(\"✨ هذه الصورة ليست عشوائية، بل هي نتيجة تفاعل 65 ألف خلية رقمية!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:28:57.072365Z","iopub.execute_input":"2026-04-19T04:28:57.072623Z","iopub.status.idle":"2026-04-19T04:28:57.333600Z","shell.execute_reply.started":"2026-04-19T04:28:57.072603Z","shell.execute_reply":"2026-04-19T04:28:57.332704Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import convolve2d\n\n# 1. إعداد المختبر الرقمي (دقة أعلى وتعقيد حسابي)\nsize = 400 \n# ثلاث مركبات كيميائية تتفاعل مع بعضها (A, B, C)\nA = np.random.rand(size, size)\nB = np.random.rand(size, size)\nC = np.random.rand(size, size)\n\nprint(f\"🌀 إطلاق محاكاة التفاعل الكيميائي الحيوي المعقد...\")\nprint(f\"⚡ توزيع 480,000 نقطة تفاعل على الأنوية السحابية...\")\n\n# 2. خوارزمية التفاعل والانتشار (Reaction-Diffusion)\n# هذه الحسابات ستجعل المعالج \"يعرق\" قليلاً\nfor i in range(150): # زيادة عدد الخطوات لزيادة التعقيد\n    # محاكاة الانتشار الكيميائي\n    A_new = A + (A * (1 - A - B)) * 0.1\n    B_new = B + (B * (C - A)) * 0.1\n    C_new = C + (C * (A - B)) * 0.1\n    \n    # إضافة عامل الانتشار (Diffusion) عبر مصفوفة الجيران\n    kernel = np.array([[0.05, 0.2, 0.05], [0.2, -1.0, 0.2], [0.05, 0.2, 0.05]])\n    A = A_new + convolve2d(A_new, kernel, mode='same', boundary='wrap') * 0.2\n    B = B_new + convolve2d(B_new, kernel, mode='same', boundary='wrap') * 0.2\n    C = C_new + convolve2d(C_new, kernel, mode='same', boundary='wrap') * 0.2\n\nprint(\"🏁 اكتملت المحاكاة العميقة.\")\n\n# 3. عرض النتيجة الفنية (دمج الطبقات الثلاث)\nfinal_view = (A + B + C) / 3\nplt.figure(figsize=(12, 12))\n# استخدام خريطة ألوان 'inferno' لإظهار العمق\nplt.imshow(final_view, cmap='inferno', interpolation='lanczos')\nplt.title(\"Mirror OS: Advanced Bio-Chemical Fluid Simulation\")\nplt.axis('off')\nplt.show()\n\nprint(\"✨ انظر إلى التعقيد؛ هذه الأنماط تحاكي طريقة نمو الأنسجة العصبية المعقدة!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:29:49.662700Z","iopub.execute_input":"2026-04-19T04:29:49.662950Z","iopub.status.idle":"2026-04-19T04:29:52.570329Z","shell.execute_reply.started":"2026-04-19T04:29:49.662931Z","shell.execute_reply":"2026-04-19T04:29:52.569156Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# 1. إعداد الفضاء الرقمي (دقة فائقة 1000x1000)\n# هنا سنحاكي مليون نقطة، كل منها يخضع لـ 100 عملية حسابية معقدة\nwidth, height = 1000, 1000\nx_min, x_max = -2.0, 0.5\ny_min, y_max = -1.25, 1.25\n\n# 2. إنشاء الشبكة الرياضية\nx, y = np.linspace(x_min, x_max, width), np.linspace(y_min, y_max, height)\nX, Y = np.meshgrid(x, y)\nC = X + 1j * Y\nZ = np.zeros_like(C)\nfractal = np.zeros(C.shape, dtype=int)\n\nprint(f\"🌀 إطلاق محاكاة الكون الفركتلي اللانهائي...\")\nprint(f\"⚙️ يتم الآن إجراء 100 مليون عملية حسابية مركبة عبر {num_units} نواة...\")\n\n# 3. محاكاة التكرار اللانهائي (المستوى المعقد جداً)\nfor i in range(100):\n    # معادلة الفركتل: Z = Z^2 + C\n    # هذه هي أصعب معادلة رياضية بصرية في الحوسبة\n    mask = np.abs(Z) <= 10\n    Z[mask] = Z[mask]**2 + C[mask]\n    fractal[mask] = i\n\nprint(\"🏁 اكتملت محاكاة اللانهائية بنجاح.\")\n\n# 4. عرض النتيجة الفنية (بألوان 'magma' العميقة)\nplt.figure(figsize=(15, 15))\nplt.imshow(fractal, cmap='magma', extent=(x_min, x_max, y_min, y_max))\nplt.title(\"Mirror OS: Quantum Fractal Universe Simulation\")\nplt.axis('off')\nplt.show()\n\nprint(\"✨ انظر إلى الحواف؛ هذه الأنماط تتكرر للأبد، وهي أصعب اختبار لقوة المعالج البصرية!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:30:47.352837Z","iopub.execute_input":"2026-04-19T04:30:47.353116Z","iopub.status.idle":"2026-04-19T04:30:48.038330Z","shell.execute_reply.started":"2026-04-19T04:30:47.353097Z","shell.execute_reply":"2026-04-19T04:30:48.037267Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# 1. رفع الدقة إلى 3000x30000 (9 مليون بكسل)\n# وزيادة التكرارات لـ 1000 خطوة لكل بكسل (حوالي 9 مليار عملية حسابية)\nwidth, height = 3000, 3000\niterations = 1000\n\nx = np.linspace(-0.748, -0.747, width)\ny = np.linspace(0.1, 0.101, height)\nX, Y = np.meshgrid(x, y)\nC = X + 1j * Y\nZ = np.zeros_like(C)\nfractal = np.zeros(C.shape, dtype=int)\n\nprint(f\"🧬 إطلاق بروتوكول 'التعقيد المطلق'...\")\nprint(f\"⚙️ جاري معالجة 9 مليار عملية حسابية مركبة على TPU v5e...\")\n\n# 2. الحساب المكثف\nfor i in range(iterations):\n    mask = np.abs(Z) <= 2\n    Z[mask] = Z[mask]**2 + C[mask]\n    fractal[mask] = i\n\nprint(\"🏁 انتهت المعالجة. إذا تمت في ثوانٍ، فنظام Mirror OS خارق!\")\n\n# 3. العرض بأعلى جودة\nplt.figure(figsize=(20, 20))\nplt.imshow(fractal, cmap='twilight_shifted')\nplt.axis('off')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:33:05.105801Z","iopub.execute_input":"2026-04-19T04:33:05.105977Z","iopub.status.idle":"2026-04-19T04:34:29.641734Z","shell.execute_reply.started":"2026-04-19T04:33:05.105960Z","shell.execute_reply":"2026-04-19T04:34:29.640589Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport os\nfrom IPython.display import Video, display\n\n# 1. إعدادات \"استوديو ميرور\" السينمائي\nframes_count = 90\nwidth, height = 800, 800\nzoom_factor = 0.92 # سرعة غوص متزنة\nvideo_name = '/kaggle/working/mirror_quantum_dive.mp4'\n\n# نقطة الغوص العميقة\nx_c, y_c = -0.748, 0.1\nrx, ry = 0.05, 0.05\n\nprint(f\"🎬 إطلاق محرك الفيديو السينمائي [90 إطار]...\")\nfourcc = cv2.VideoWriter_fourcc(*'mp4v')\nvideo_writer = cv2.VideoWriter(video_name, fourcc, 30, (width, height))\n\n# 2. حلقة الإنتاج والدمج اللحظي (Stream Processing)\nfor f in range(frames_count):\n    rx *= zoom_factor\n    ry *= zoom_factor\n    \n    x = np.linspace(x_c - rx, x_c + rx, width)\n    y = np.linspace(y_c - ry, y_c + ry, height)\n    X, Y = np.meshgrid(x, y)\n    C = X + 1j * Y\n    Z = np.zeros_like(C)\n    fractal = np.zeros(C.shape, dtype=np.uint8)\n\n    # حساب مجهري مكثف\n    for i in range(128):\n        mask = np.abs(Z) <= 2\n        Z[mask] = Z[mask]**2 + C[mask]\n        fractal[mask] = i\n\n    # تحويل المصفوفة إلى ألوان حقيقية للفيديو\n    frame_color = cv2.applyColorMap(fractal * 2, cv2.COLORMAP_MAGMA)\n    video_writer.write(frame_color)\n    \n    if (f + 1) % 30 == 0:\n        print(f\"🎞️ تم إنتاج {f + 1} ثانية من الفيلم... الرام ثابتة 🧊\")\n\nvideo_writer.release()\nprint(f\"✅ اكتمل إنتاج الفيديو: {video_name}\")\n\n# 3. عرض الفيديو الناتج مباشرة\ndisplay(Video(video_name, embed=True, width=600))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:39:00.938549Z","iopub.execute_input":"2026-04-19T04:39:00.938845Z","iopub.status.idle":"2026-04-19T04:39:40.439416Z","shell.execute_reply.started":"2026-04-19T04:39:00.938825Z","shell.execute_reply":"2026-04-19T04:39:40.438417Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. تحويل الفيديو لصيغة متوافقة مع المتصفحات (H.264)\n!ffmpeg -y -i /kaggle/working/mirror_quantum_dive.mp4 -vcodec libx264 /kaggle/working/final_mirror_movie.mp4 -loglevel quiet\n\nprint(\"✅ تم تحويل الفيديو للصيغة العالمية!\")\n\n# 2. عرض الفيديو النهائي\nfrom IPython.display import Video\nVideo(\"/kaggle/working/final_mirror_movie.mp4\", embed=True, width=600)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:41:33.172122Z","iopub.execute_input":"2026-04-19T04:41:33.172380Z","iopub.status.idle":"2026-04-19T04:41:36.071372Z","shell.execute_reply.started":"2026-04-19T04:41:33.172362Z","shell.execute_reply":"2026-04-19T04:41:36.070404Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport cv2\nfrom IPython.display import Video, display\n\n# 1. إعدادات المحاكاة الاحترافية (True N-Body Core)\nN = 10000  # عدد النجوم الإجمالي\nframes = 200\nsize = 800\nG = 1.0\nsoftening = 15.0 # لمنع تشتت النجوم عند الاقتراب الشديد\n\n# دالة توليد المجرة الحلزونية الفيزيائية\ndef build_galaxy(center, velocity, radius, color):\n    # توزيع النجوم بشكل حلزوني مع سرعة مدارية متزنة\n    r = np.sqrt(np.random.rand(N//2)) * radius\n    theta = np.random.rand(N//2) * 2 * np.pi\n    pos = np.stack([center[0] + r * np.cos(theta), center[1] + r * np.sin(theta)], axis=1)\n    \n    # حساب سرعة الدوران بناءً على الكتلة المركزية\n    v_mag = np.sqrt(G * 1000 / (r + 10))\n    vel = np.stack([-v_mag * np.sin(theta), v_mag * np.cos(theta)], axis=1) + velocity\n    return pos.astype('float32'), vel.astype('float32'), color\n\n# بناء المجرتين المتقابلتين\npos1, vel1, col1 = build_galaxy([300, 400], [2, 0.5], 60, (255, 120, 200)) # وردي\npos2, vel2, col2 = build_galaxy([500, 400], [-2, -0.5], 60, (100, 255, 255)) # سماوي\n\nall_pos = np.vstack([pos1, pos2])\nall_vel = np.vstack([vel1, vel2])\n\nfourcc = cv2.VideoWriter_fourcc(*'mp4v')\nout = cv2.VideoWriter('/kaggle/working/pro_nbody_galaxy.mp4', fourcc, 30, (size, size))\n\nprint(f\"🌀 إطلاق محرك الجاذبية الكاملة (All-to-All Gravity) لـ {N} نجم...\")\n\n# 2. حلقة الحسابات الفيزيائية العميقة\nfor f in range(frames):\n    # حساب المسافات بين كل النجوم دفعة واحدة (Matrix Magic)\n    # هذا السطر هو الذي يستغل الـ 224 نواة والرام الضخمة\n    dx = all_pos[:, 0:1] - all_pos[:, 0]\n    dy = all_pos[:, 1:2] - all_pos[:, 1]\n    \n    inv_dist3 = (dx**2 + dy**2 + softening**2)**(-1.5)\n    \n    ax = G * (dx * inv_dist3) @ np.ones((N, 1)) * -50 # تسارع X\n    ay = G * (dy * inv_dist3) @ np.ones((N, 1)) * -50 # تسارع Y\n    \n    all_vel[:, 0:1] += ax * 0.1\n    all_vel[:, 1:2] += ay * 0.1\n    all_pos += all_vel * 0.1\n\n    # الرسم الاحترافي بتأثير السديم (Nebula Effect)\n    frame = np.zeros((size, size, 3), dtype=np.uint8)\n    for i in range(N):\n        x, y = int(all_pos[i,0]), int(all_pos[i,1])\n        if 0 <= x < size and 0 <= y < size:\n            # دمج الألوان لخلق تأثير التوهج عند التصادم\n            current_col = col1 if i < N//2 else col2\n            cv2.circle(frame, (x, y), 1, current_col, -1)\n            \n    # إضافة لمسة ضبابية خفيفة لجعلها تبدو كالمجرات الحقيقية\n    frame = cv2.addWeighted(frame, 0.7, cv2.GaussianBlur(frame, (3,3), 0), 0.3, 0)\n    out.write(frame)\n    \n    if (f+1) % 50 == 0: print(f\"✨ تم إنتاج {f+1} إطار من الاندماج الكوني...\")\n\nout.release()\n\n# 3. التحويل النهائي للعرض\n!ffmpeg -y -i /kaggle/working/pro_nbody_galaxy.mp4 -vcodec libx264 -pix_fmt yuv420p /kaggle/working/nbody_final.mp4 -loglevel quiet\n\nprint(\"✅ اكتملت ملحمة Mirror OS.\")\ndisplay(Video(\"/kaggle/working/nbody_final.mp4\", embed=True, width=700))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:51:59.027689Z","iopub.execute_input":"2026-04-19T04:51:59.028038Z","iopub.status.idle":"2026-04-19T04:56:28.628256Z","shell.execute_reply.started":"2026-04-19T04:51:59.028014Z","shell.execute_reply":"2026-04-19T04:56:28.626701Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom IPython.display import HTML\n\n# =========================================================\n# إعدادات الفيزياء\n# =========================================================\nnp.random.seed(42)\n\nG = 1.0             # ثابت الجاذبية (مقنن)\nsoftening = 0.7     # لتجنب الانهيار عند الاقتراب الشديد\ndt = 0.03           # الخطوة الزمنية\nframes = 320\nsubsteps = 2\n\n# =========================================================\n# خصائص المجرة\n# =========================================================\nM_core = 80.0       # كتلة نواة المجرة\nm_star = 0.05       # كتلة كل نجم\nn_stars_each = 70   # عدد النجوم في كل مجرة\ndisk_radius = 8.0\n\n# =========================================================\n# بناء مجرة قرصية مع نواة مركزية\n# =========================================================\ndef build_galaxy(center, v_center, n_stars, spin=1.0, star_color='deepskyblue'):\n    # النواة\n    pos_list = [center[None, :]]\n    vel_list = [v_center[None, :]]\n    mass_list = [np.array([M_core])]\n    colors = ['gold']\n    sizes = [260]\n\n    # توزيع النجوم داخل قرص\n    r = disk_radius * np.sqrt(np.random.rand(n_stars))\n    theta = 2 * np.pi * np.random.rand(n_stars)\n\n    offset = np.column_stack((r * np.cos(theta), r * np.sin(theta)))\n    star_pos = center + offset\n\n    # سرعة مدارية تقريبية حول النواة\n    tangential = np.column_stack((-np.sin(theta), np.cos(theta))) * spin\n    v_circ = np.sqrt(G * M_core / (r + 0.8)) * 0.9\n    star_vel = v_center + tangential * v_circ[:, None] + 0.05 * np.random.randn(n_stars, 2)\n\n    pos_list.append(star_pos)\n    vel_list.append(star_vel)\n    mass_list.append(np.full(n_stars, m_star))\n    colors += [star_color] * n_stars\n    sizes += [10] * n_stars\n\n    pos = np.vstack(pos_list)\n    vel = np.vstack(vel_list)\n    masses = np.concatenate(mass_list)\n\n    return pos, vel, masses, colors, sizes\n\n# =========================================================\n# بناء مجرتين متقابلتين\n# =========================================================\ncenter1 = np.array([-16.0, -4.0])\ncenter2 = np.array([ 16.0,  4.0])\n\nv1 = np.array([ 0.75,  0.20])\nv2 = np.array([-0.75, -0.20])\n\np1, v1a, m1, c1, s1 = build_galaxy(center1, v1, n_stars_each, spin=1.0,  star_color='deepskyblue')\np2, v2a, m2, c2, s2 = build_galaxy(center2, v2, n_stars_each, spin=-1.0, star_color='tomato')\n\npositions = np.vstack([p1, p2])\nvelocities = np.vstack([v1a, v2a])\nmasses = np.concatenate([m1, m2])\ncolors = c1 + c2\nsizes = s1 + s2\n\n# =========================================================\n# حساب التسارع الناتج عن الجاذبية المتبادلة\n# =========================================================\ndef accelerations(pos, masses):\n    dx = pos[:, 0][:, None] - pos[:, 0][None, :]\n    dy = pos[:, 1][:, None] - pos[:, 1][None, :]\n\n    r2 = dx*dx + dy*dy + softening**2\n    inv_r3 = r2 ** (-1.5)\n    np.fill_diagonal(inv_r3, 0.0)\n\n    ax = -G * np.sum(dx * inv_r3 * masses[None, :], axis=1)\n    ay = -G * np.sum(dy * inv_r3 * masses[None, :], axis=1)\n\n    return np.column_stack((ax, ay))\n\n# =========================================================\n# خطوة Leapfrog - أفضل عددياً من Euler\n# =========================================================\ndef leapfrog_step(pos, vel, masses, dt):\n    a = accelerations(pos, masses)\n    vel_half = vel + 0.5 * dt * a\n    pos_new = pos + dt * vel_half\n    a_new = accelerations(pos_new, masses)\n    vel_new = vel_half + 0.5 * dt * a_new\n    return pos_new, vel_new\n\n# =========================================================\n# طاقة النظام لمراقبة الحفاظ على الطاقة\n# =========================================================\ndef total_energy(pos, vel, masses):\n    kinetic = 0.5 * np.sum(masses * np.sum(vel**2, axis=1))\n\n    dx = pos[:, 0][:, None] - pos[:, 0][None, :]\n    dy = pos[:, 1][:, None] - pos[:, 1][None, :]\n    r = np.sqrt(dx*dx + dy*dy + softening**2)\n\n    iu = np.triu_indices(len(masses), 1)\n    potential = -G * np.sum(masses[iu[0]] * masses[iu[1]] / r[iu])\n\n    return kinetic + potential\n\nE0 = total_energy(positions, velocities, masses)\n\n# =========================================================\n# تشغيل المحاكاة وتخزين النتائج\n# =========================================================\nhistory = []\npos = positions.copy()\nvel = velocities.copy()\n\nfor _ in range(frames):\n    for _ in range(substeps):\n        pos, vel = leapfrog_step(pos, vel, masses, dt)\n    history.append(pos.copy())\n\nhistory = np.array(history)\n\nE1 = total_energy(pos, vel, masses)\nprint(f\"الانحراف النسبي في الطاقة: {(E1 - E0) / abs(E0) * 100:.3f}%\")\n\n# =========================================================\n# الرسم المتحرك\n# =========================================================\nfig, ax = plt.subplots(figsize=(8, 8), facecolor='black')\nax.set_facecolor('black')\nax.set_xlim(-45, 45)\nax.set_ylim(-45, 45)\nax.set_aspect('equal', 'box')\nax.axis('off')\nax.set_title(\"محاكاة N-body لتصادم مجرتين\", color='white', pad=10)\n\nscat = ax.scatter(history[0][:, 0], history[0][:, 1],\n                  s=sizes, c=colors, alpha=0.85, edgecolors='none')\n\ndef update(frame):\n    scat.set_offsets(history[frame])\n    return scat,\n\nanim = FuncAnimation(fig, update, frames=len(history), interval=30, blit=True)\n\nHTML(anim.to_jshtml())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T04:57:18.481755Z","iopub.execute_input":"2026-04-19T04:57:18.482093Z","iopub.status.idle":"2026-04-19T04:57:29.454055Z","shell.execute_reply.started":"2026-04-19T04:57:18.482068Z","shell.execute_reply":"2026-04-19T04:57:29.453005Z"}},"outputs":[],"execution_count":null}]}