from tempfile import tempdir import firebase_admin from firebase_admin import credentials from firebase_admin import db from find_s1_image2 import find_img_value import pandas as pdf from sklearn.metrics import classification_report, confusion_matrix, accuracy_score import statsmodels.api as sm import seaborn as sns sns.set() import traceback from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split import csv import time import json from find_modis_ndvi import find_modis_ndvi import numpy as np from sklearn.cluster import KMeans from sentinelhub import WebFeatureService, BBox, CRS, MimeType, CRS, BBox, WmsRequest,DataCollection import traceback from get_mask import get_mask from PIL import Image import numpy as np from google.cloud import storage import requests from simplify_coordinates import simplify_coordinates cred = credentials.Certificate('servicekey.json') x = 0.0003 y = 0.0003 fromdate = '20220701' todate = '20220715' s1_images = ['IW-VH-DB'] s2_images = [] import json # s1_images = ["B02", "B03", "B04", "B05"] #s2_images = ["RVI-NEW"] try: firebase_admin.initialize_app(cred, {'databaseURL': 'https://farmbase-b2f7e-31c0c.firebaseio.com/'}) except: print('fire running') #get all non_gt farms #uid = 'lnR1AGuLgmPWk5ZzEtFS3FlGRj42' # field_ids = [1679967002882, 1679966729923, 1679564467926, 1676093083960, 1676092753184, 1676092238980, 1676092127138, 1676092080769, 1675836972336, 1675836874915, 1675836770812, 1675836706947, 1675224126040, 1675223688824, 1675223584847, 1675222777316, 1675222680174, 1675220202897, 1675219711420, 1675219573442, 1675219344911] # for fieldid in field_ids: # fieldid = str(fieldid) # field_obj = db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('SensedDays').delete() # time.sleep(0.1) #uid = 'qL4tgUcl1ggqLRFFgxTNbTgP3uk1' uid = 'M53J9SImW9My4vghlCaaWLYxsc22' #uid ='3slpdq65yYXR6M9zDU2I3Ng6kRD2' uid = 'sAiJIWRbNOR5grDmRabVxW5BXp03' uid = '4bsSM4efIGhVVmOUyJv8DshNxYG3' uid = 'ENLgcB9pl2fH7MjsEH7oc72YBRh2' uid = 'b0oOOCM3jFUHMy9CsL2RYENMAHC3' uid = 'cO3iCeT1cYfPpmq35RYVE9nWTFz1' uid = 'hbPx8Vep5OTxnouajuHKkg0PXvw2' uid = 'XSzwRsmzu4OeCm8UvllGn7xsnOk1' uid = 'D4xU2QGhooXfK6qiEeHdAlp0wk53' from math import radians, sin, cos, atan2, sqrt def haversine(lat1, lon1, lat2, lon2): """ Calculate the haversine distance between two points on the sphere. Parameters: - lat1, lon1: Latitude and longitude of the first point in degrees. - lat2, lon2: Latitude and longitude of the second point in degrees. Returns: - distance: Haversine distance in meters. """ R = 6371000.0 # Radius of the Earth in meters dlat = radians(lat2 - lat1) dlon = radians(lon2 - lon1) a = sin(dlat / 2) ** 2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c return distance def calculate_polygon_area(coords): """ Calculate the area of a polygon defined by latitude and longitude coordinates. Parameters: - coords: List of coordinate pairs in the format [[longitude1, latitude1], [longitude2, latitude2], ...] Returns: - area: Area of the polygon in square meters. """ if len(coords) < 3: raise ValueError("Polygon must have at least 3 vertices.") # Convert coordinates to radians coords_rad = [(radians(lat), radians(lon)) for lon, lat in coords] # Calculate the haversine distances distances = [haversine(lat1, lon1, lat2, lon2) for (lat1, lon1), (lat2, lon2) in zip(coords_rad, coords_rad[1:] + [coords_rad[0]])] # Calculate the area using the shoelace formula area = 0.5 * sum(distances) return area def make_coords_array(coords_obj): p_num = 0 coords_arr = [] for key,val in coords_obj.items(): #print(val) if p_num == 0: coords_arr.append([float(coords_obj["a"]["Longitude"]), float(coords_obj["a"]["Latitude"])]) else: coords_arr.append([float(coords_obj[("P_"+str(p_num))]["Longitude"]), float(coords_obj[("P_"+str(p_num))]["Latitude"])]) p_num = p_num +1 coords_arr.append([float(coords_obj["a"]["Longitude"]), float(coords_obj["a"]["Latitude"])]) #print(coords_arr) return coords_arr # Example usage #coordinates = [[80.79032187811988, 27.700518612355072], [80.79072902097701, 27.700518612355072], [80.79087366383416, 27.70043798013237], [80.79087098526273, 27.699932841616832], [80.7904825924056, 27.69993047006898], [80.79028437811989, 27.700044304307212], [80.79032187811988, 27.700518612355072]] #print(f"The area of the polygon is approximately {area:.2f} square meters.") #test_uid = 'MtO6G7AvlnPgQxAajMP6NtLS8fN2' uid = 'lnR1AGuLgmPWk5ZzEtFS3FlGRj42' uid = 'TCXcp5VIsfhHZrh0nm2VsgBtcGy2' with open('Downloads/new_field_data_with_palm_tree_count.json', 'r') as file: # Parse the JSON data data = json.load(file) with open('Downloads/polygon_data_all.json') as file: data2 = json.load(file) for polygon_id, polygon_obj in data2.items(): data2[polygon_id]["field_area"] = data[polygon_id]["field_area"] with open('Downloads/new_polygon_data_all.json', 'w') as json_file: json.dump(data2, json_file, indent=4) print('dump done') time.sleep(10000) all_polygon_ids_obj = db.reference('PaidPolygonsByPolygonID').child('PMF').child(uid).get(False,True) current_field_ids = [] total_units = 0 unit_cost = 250 total_cost = 0 main_arr = [] for (polygon_id, val) in all_polygon_ids_obj.items(): polygon_obj = db.reference('PaidPolygonsByPolygonID').child('PMF').child(uid).child(polygon_id).get() try: area = polygon_obj["Area"] points_obj = polygon_obj["Coordinates"] points_obj["a"] = points_obj["P_0"] del points_obj["P_0"] # Replace the URL with the actual endpoint you want to send the POST request to url = "https://us-central1-farmbase-b2f7e.cloudfunctions.net/getFieldAreaByBoundaryPoints" # Replace this dictionary with your JSON data req_data = { "UID": uid, "Points": points_obj } # Convert the dictionary to a JSON string json_data = json.dumps(req_data) # Set the headers to indicate that you are sending JSON data headers = { "Content-Type": "application/json", } # Make the POST request response = requests.post(url, data=json_data, headers=headers) res_obj = response.json() # print(response.text) field_area = res_obj.get("FieldArea") db.reference('PaidPolygonsByPolygonID').child('PMF').child(uid).child(polygon_id).child('Area').set(field_area) db.reference('PaidMonitoredFields').child('PMF').child(uid).child(polygon_obj["fieldID"]).child('Polygons').child(polygon_id).child('Area').set(field_area) #polygon_obj["Area"] = field_area # print(polygon_id, area, field_area) # tree_count_obj = data[str(polygon_id)] # tree_count_obj["field_area"] = field_area # tree_count_obj["area_hectares"] = round(field_area/10000,2) # tree_count_obj["area_acres"] = round(field_area/4047,2) # tree_count_obj["tree_count_per_hectare"] = round(tree_count_obj.get('total_tree_count',0)/tree_count_obj.get("area_hectares",0),2) # tree_count_obj["tree_count_per_acre"] = round(tree_count_obj.get('total_tree_count',0)/tree_count_obj.get("area_acres",0),2) # data[polygon_id] = tree_count_obj #db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('FieldArea').set(field_area) #time.sleep(0.1) except: print(traceback.format_exc()) # with open('Downloads/new_field_data_with_palm_tree_count.json', 'w') as json_file: # json.dump(data, json_file, indent=4)