{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7fb53556",
   "metadata": {},
   "source": [
    "# Workflow for Marine Litter Targets Identification from Bathymetry        \n",
    "#### ArcGis PRO with Spatial Analysis is required"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f8b20c7",
   "metadata": {},
   "source": [
    "**<span style='color:green'>Import necessary libraries</span>**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a6aeb2d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Importing arcpy library\n",
    "import arcpy\n",
    "from arcpy import env\n",
    "from arcpy.sa import *\n",
    "import shutil\n",
    "import os\n",
    "# Check out any necessary licenses\n",
    "arcpy.CheckOutExtension(\"spatial\")\n",
    "# Allow to overwrite existing output\n",
    "arcpy.env.overwriteOutput = True"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa1e50c6",
   "metadata": {},
   "source": [
    "**<span style='color:green'>Define some inputs</span>**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "db247fb9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define input, output and temporary folders (temporary folder will be deleted at the end)\n",
    "#FolderInp must exist, FolderOut and FolderTemp will be created if not existing\n",
    "FolderInp = \"d:/MarGnet/tool/tool/inp/\"\n",
    "FolderOut = \"d:/MarGnet/tool/tool/out/\"\n",
    "FolderTemp = \"d:/MarGnet/tool/tool/temp/\"\n",
    "# Define input raster and output name\n",
    "rasterInput = \"test_2021.tif\"\n",
    "shapeOutput = \"OBJ_2021.shp\"\n",
    "#_______________________________\n",
    "# Define some parameters used in Arcgis toolboxes\n",
    "AreaLimit = \"0.25\"\n",
    "neighborhood = NbrRectangle(3, 3, \"CELL\")\n",
    "remap = RemapRange([[-100,-.02,1],[-0.02,0,0]]) #[[-100,-.02,1],[-0.02,0,0]]\n",
    "reclassField = \"Value\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d687cf6",
   "metadata": {},
   "source": [
    "**<span style='color:green'>Run next cells recursively</span>**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0521981f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "check done\n"
     ]
    }
   ],
   "source": [
    "#check folders\n",
    "# ...temporary folder\n",
    "if os.path.isdir(FolderTemp) == False:\n",
    "    os.mkdir(FolderTemp)\n",
    "# ... output folder\n",
    "if os.path.isdir(FolderOut) == False:\n",
    "    os.mkdir(FolderOut)\n",
    "# ... input folder\n",
    "error = False\n",
    "if os.path.isdir(FolderInp) == False:\n",
    "    print('Error...input folder is missing')\n",
    "    error = True\n",
    "if os.path.exists(FolderInp + rasterInput) == False:\n",
    "    print('Error...input raster is missing')\n",
    "    error = True\n",
    "\n",
    "if error == False:\n",
    "    # defining some local variables\n",
    "    InputRaster0 = FolderInp + rasterInput\n",
    "    InputRaster = FolderTemp + \"negate\"\n",
    "    S1_Focal = FolderTemp + \"s1_focal\"\n",
    "    S2_Fill = FolderTemp + \"s2_fill\"\n",
    "    S3_Minus = FolderTemp + \"s3_minus\"\n",
    "    S4_Reclass = FolderTemp + \"S4_Reclass\"\n",
    "    S5_ToPolygons_shp = FolderTemp + \"S4_Reclass.shp\"\n",
    "    S5_ToPolygons_shp__2_ = FolderTemp + \"S4_Reclass_2.shp\"\n",
    "    S6_Poly_Filtered_shp = FolderTemp + \"S6_Filtered.shp\"\n",
    "    S7_MinimumBoundary_shp = FolderOut + shapeOutput    \n",
    "    \n",
    "    print('check done')\n",
    "else:\n",
    "    print('check input folder/file')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "de6cfe96",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 - checking values...\n",
      "values checked\n",
      "1a - applying Negate...\n",
      "Negate applied\n",
      "2 - applying Focal Statistics...\n",
      "Focal Statistics applied\n",
      "3 - applying Fill...\n",
      "Fill applied\n",
      "4 - applying Minus...\n",
      "Minus applied\n",
      "5 - applying Reclassify...\n",
      "Reclassify applied\n",
      "6 - applying Raster To Polygon...\n",
      "Raster To Polygon applied\n",
      "7 - classifying objects\n",
      "     .adding Geometry Attributes\n",
      "     .filtering for area\n",
      "     .calculating Minimum Bounding Geometry\n",
      "     .classifying objects\n",
      "Done\n"
     ]
    }
   ],
   "source": [
    "# Start workflow\n",
    "print(\"1 - checking values...\")\n",
    "arcpy.CalculateStatistics_management(InputRaster0)\n",
    "rast = arcpy.Raster (InputRaster0)\n",
    "mi = rast.minimum\n",
    "del rast\n",
    "if mi < 0:\n",
    "    print(\"values checked\")\n",
    "    print(\"1a - applying Negate...\")\n",
    "    # Process: Negate\n",
    "    outNegate = Negate(InputRaster0)\n",
    "    outNegate.save(InputRaster)\n",
    "    del outNegate\n",
    "    print(\"Negate applied\")\n",
    "    # Process: Focal Statistics\n",
    "    print(\"2 - applying Focal Statistics...\")\n",
    "    outFocalStatistics = FocalStatistics(InputRaster, neighborhood, \"MEAN\",\"DATA\")\n",
    "    print(\"Focal Statistics applied\")\n",
    "else:\n",
    "    # Process: Focal Statistics\n",
    "    print(\"2 - applying Focal Statistics...\")\n",
    "    outFocalStatistics = FocalStatistics(InputRaster0, neighborhood, \"MEAN\",\"DATA\")\n",
    "    print(\"Focal Statistics applied\")\n",
    "\n",
    "outFocalStatistics.save(S1_Focal)\n",
    "del outFocalStatistics\n",
    "# Process: Fill\n",
    "print(\"3 - applying Fill...\")\n",
    "outFill = Fill(S1_Focal, \"\")\n",
    "outFill.save(S2_Fill)\n",
    "del outFill\n",
    "print(\"Fill applied\")\n",
    "# Process: Minus\n",
    "print(\"4 - applying Minus...\")\n",
    "outMinus = Minus(S1_Focal, S2_Fill)\n",
    "outMinus.save(S3_Minus)\n",
    "del outMinus\n",
    "print(\"Minus applied\")\n",
    "# Process: Reclassify\n",
    "print(\"5 - applying Reclassify...\")\n",
    "outReclassify = Reclassify(S3_Minus, reclassField, remap, \"NODATA\")\n",
    "    outReclassify.save(S4_Reclass)\n",
    "del outReclassify\n",
    "print(\"Reclassify applied\")\n",
    "# Process: Raster to Polygon\n",
    "print(\"6 - applying Raster To Polygon...\")\n",
    "arcpy.RasterToPolygon_conversion(S4_Reclass, S5_ToPolygons_shp, \"SIMPLIFY\", \"VALUE\")\n",
    "print(\"Raster To Polygon applied\")\n",
    "print(\"7 - classifying objects\")\n",
    "# Process: Add Geometry Attributes\n",
    "print('     .adding Geometry Attributes')\n",
    "arcpy.AddGeometryAttributes_management(S5_ToPolygons_shp, \"AREA\", \"\", \"\", \"\")\n",
    "# Process: Select_Class_1_Area_025\n",
    "print('     .filtering for area')\n",
    "arcpy.Select_analysis(S5_ToPolygons_shp, S6_Poly_Filtered_shp, \"GRIDCODE = 1 AND POLY_AREA >= \" + AreaLimit)\n",
    "# Process: Minimum Bounding Geometry\n",
    "print('     .calculating Minimum Bounding Geometry')\n",
    "arcpy.MinimumBoundingGeometry_management(S6_Poly_Filtered_shp, S7_MinimumBoundary_shp, \"RECTANGLE_BY_WIDTH\", \"NONE\", \"\", \"MBG_FIELDS\")\n",
    "# Process: Delete Field\n",
    "print('     .classifying objects')\n",
    "arcpy.DeleteField_management(S7_MinimumBoundary_shp, \"POLY_AREA\")\n",
    "# Process: Add Field_Ratio\n",
    "#print('   .')\n",
    "arcpy.AddField_management(S7_MinimumBoundary_shp, \"ratio\", \"DOUBLE\", \"\", \"\", \"\", \"\", \"NULLABLE\", \"NON_REQUIRED\", \"\")\n",
    "# Process: Calculate Field\n",
    "#print('   .')\n",
    "arcpy.CalculateField_management(S7_MinimumBoundary_shp, \"ratio\", \"CalcRatio(!MBG_Length!,!MBG_Width!)\",\"PYTHON_9.3\",\"def CalcRatio(MBG_Length,MBG_Width): \\r\\n return MBG_Length/MBG_Width\")\n",
    "#Process: Add Field_Type\n",
    "#print('   .classifying objects')\n",
    "arcpy.CalculateField_management(S7_MinimumBoundary_shp, \"Type\", \"Reclass(!ratio! )\", \"PYTHON_9.3\", \"def Reclass(ratio):\\r\\n  if (ratio <= 1.35):\\r\\n    return \\\"Tyre\\\"\\r\\n  elif (ratio >= 4.3):\\r\\n    return \\\"Poles\\\"\\r\\n  else:\\r\\n    return \\\"Others\\\"\\r\\n\")\n",
    "print(\"Done\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46760353",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Remove the temporary folder\n",
    "shutil.rmtree(FolderTemp)\n",
    "print('Temporary folder deleted')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96e69d76",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_raster = arcpy.sa.Reclassify(\"04_minus\", \"Value\", \"-0.635702 -0.020000 1;-0.020000 0 0\", \"NODATA\"); out_raster.save(r\"D:\\MarGnet\\tool\\tool\\FromGis\\04_clas\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
