import requests
import rasterio
import rasterio.plot
import folium
from rasterio.warp import calculate_default_transform, reproject, Resampling
from requests.auth import HTTPBasicAuth
Forecast tool
In this part we will focus on two endpoint:
- “AFS/ForecastVineyard” endpoint, which allow the user to get a raster image where there is the vine yield prediction in tiff format
- “/AFS/ForecastVineyardGeojson” endpoint, which allow the user to get a raster image where there is the vine yield prediction in geojson format
ForecastVineyard
Python
In this example we will test the ForecastVineyard which allow the user to get a raster image where there is the vine yield prediction in tiff format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
- action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
- filterTime, Set the date filter can be onelastmonth, twolastmonth or none
- raster_path, The NDVI to be used to forecast the yield of the vineyard. If you don’t have it please take this raster file at the github repository
With your information and let’s try out the API.
Load Libraries
Setting of the API
# Define the API parameters
="1"
fieldnumber="none"
action="onelastmonth"
filterTime
# Define the url of the endpoint
= "https://www.api.automaticfarmsolutionwebapp.com/AFS/ForecastVineyardNew?"
api_endpoint
# Define the api url
=api_endpoint+"fieldnumber="+fieldnumber+"&action="+action+"&filterTime="+filterTime
api_url
# Set the useremail & Password
="useremail"
USEREMAIL="apikey"
APIKEY
# Set the geojson file to send
= "county.geojson" geojson_file_path
Define python function
def convert_to_wgs84(input_raster_path, output_raster_path):
# Open the input raster
with rasterio.open(input_raster_path) as src:
# Define the target CRS (WGS 84 - EPSG:4326)
= 'EPSG:4326'
target_crs
# Get the affine transformation and dimensions of the new raster
= calculate_default_transform(src.crs, target_crs, src.width, src.height, *src.bounds)
transform, width, height
# Create the options for reprojection
= src.meta.copy()
kwargs
kwargs.update({'crs': target_crs,
'transform': transform,
'width': width,
'height': height
})
# Reproject the raster to WGS 84
with rasterio.open(output_raster_path, 'w', **kwargs) as dst:
for i in range(1, src.count + 1):
reproject(=rasterio.band(src, i),
source=rasterio.band(dst, i),
destination=src.transform,
src_transform=src.crs,
src_crs=transform,
dst_transform=target_crs,
dst_crs=Resampling.nearest
resampling )
def post_request_with_geojson(geojson_file_path, api_url):
# Leggi il file GeoJSON
with open(geojson_file_path, 'r') as file:
= file.read()
geojson_data
# Specifica l'header per la POST request
= {'Content-Type': 'application/json'}
headers
# Effettua la POST request
= requests.post(api_url,
response =geojson_data,
data=headers,
headers=HTTPBasicAuth(USEREMAIL, APIKEY))
auth
if response.status_code == 200:
# Save the response as a temporary raster file
= "temp_raster.tif"
temp_raster_path with open(temp_raster_path, 'wb') as temp_raster_file:
temp_raster_file.write(response.content)
# Convert the raster to WGS 84 (EPSG:4326)
= "temp_raster_wgs84.tif"
wgs84_raster_path
convert_to_wgs84(temp_raster_path, wgs84_raster_path)
# Open the WGS 84 raster using rasterio
= rasterio.open(wgs84_raster_path)
wgs84_raster
# Read the image as a numpy array
= wgs84_raster.read(1)
data
# Get the extent of the image
= wgs84_raster.bounds
xmin, ymin, xmax, ymax
# Create a folium map centered at the center of the extent of the image
= [(ymin+ymax)/2, (xmin+xmax)/2]
center = folium.Map(location=center, zoom_start=16)
m
# Add the tif file as a raster layer
= folium.raster_layers.ImageOverlay(
overlay =data,
image=[[ymin, xmin], [ymax, xmax]],
bounds=lambda x: (0, 0, 0, x/255),
colormap=True)
mercator_project
overlay.add_to(m)
# Visualize the map
return m
else:
print("Error during the request.")
return None
# Make the POST request
= post_request_with_geojson(geojson_file_path, api_url)
m
# Visualize the results
m
R
In this example we will test the ForecastVineyard which allow the user to get a raster image where there is the vine yield prediction in tiff format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
- action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
- filterTime, Set the date filter can be onelastmonth, twolastmonth or none
- raster_path, The NDVI to be used to forecast the yield of the vineyard. If you don’t have it please take this raster file at the github repository
With your information and let’s try out the API.
# import libraries
library(tictoc)
library(httr)
library(gt)
library(tidyverse)
library(raster)
library(mapview)
# Define the API parameters
="1"
fieldnumber="none"
action="onelastmonth"
filterTime
# Define the url of the API
<- "https://www.api.automaticfarmsolutionwebapp.com/AFS/ForecastVineyardNew?"
api_endpoint
# Define the API call
=paste0(api_endpoint, "fieldnumber=", fieldnumber, "&action=",action, "&filterTime=", filterTime)
api_url
# Set the useremail & Password
="useremail"
USEREMAIL="apikey"
APIKEY
# Path to the NDVI tif file
= "county.geojson"
file_path_to_geojson
# Get the start time to API Call
tic()
# Make the POST request
<- POST(
r
api_url,::authenticate(
httruser = Sys.getenv(USEREMAIL),
password = Sys.getenv(APIKEY)
),body=httr::upload_file(file_path_to_geojson)
)
# Print out the seconds needed to get the satellite image
print("The API needed:")
[1] "The API needed:"
toc()
2.46 sec elapsed
# Get the status of the request
::status_code(r) httr
[1] 200
# Visulize the vegetation index
<-readBin(r$content, what = "raw", n=length(r$content))
bin_raster
writeBin(bin_raster, con = "raster.tif")
<- raster::raster("raster.tif")
raster
mapview(raster, layer.name="Yield Map")
Node.js
In this example we will test the ForecastVineyard which allow the user to get a raster image where there is the vine yield prediction in tiff format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
- action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
- filterTime, Set the date filter can be onelastmonth, twolastmonth or none
- raster_path, The NDVI to be used to forecast the yield of the vineyard. If you don’t have it please take this raster file at the github repository
With your information and let’s try out the API.
// load libraries
const axios = require('axios');
const fs = require('fs');
// Set the username & API key
const username = 'XXXXXXXXXXXXXXXXX';
const password = 'XXXXXXXXXXXXXXXXXXX';
// Set the api parameters
const fieldnumber="1";
const action="none";
const filterTime='onelastmonth';
// Set api url
const api_url = 'https://www.api.automaticfarmsolutionwebapp.com/AFS/ForecastVineyardNew?';
// Set api endpoint
const apiendpoint = api_url.concat("fieldnumber=",fieldnumber, "&action=", action, "&filterTime=", filterTime);
// Set the path to the local GeoJson that you want to use
const geojsonFilePath = './county.geojson';
// Set the path to save the raster that we will recive
const rasterFilePath = './file.tif';
async function makePostRequest() {
const geojsonFile = fs.readFileSync(geojsonFilePath, 'utf8');
const authHeader = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
try {
const response = await axios.post(apiendpoint, geojsonFile, {
headers: {
'Content-Type': 'application/json',
'Authorization': authHeader,
,
}responseType: 'arraybuffer',
;
})
.writeFileSync(rasterFilePath, response.data);
fs
console.log('The raster file was locally saved', rasterFilePath);
catch (error) {
} console.error('An error occurred:', error.message);
}
}
makePostRequest();
Java
In this example we will test the ForecastVineyard which allow the user to get a raster image where there is the vine yield prediction.
To use the following example you have to replace:
- USEREMAIL
- fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
- action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
- APIKEY
- raster_path, The NDVI to be used to forecast the yield of the vineyard. If you don’t have it please take this raster file at the github repository
With your information and let’s try out the API.
Working in progress
ForecastVineyardGeojson
Python
In this example we will test the ForecastVineyardGeojson which allow the user to get the latest vegetation index available for the Area of Interest in gejson format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response - action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
- filterTime, Set the date filter can be onelastmonth, twolastmonth or none
- file_path_to_geojson (you can find it here county.geojson the county file of the example)
With your information and let’s try out the API.
# Load the libraries
import requests
import fiona
import geopandas as gpd
from requests.auth import HTTPBasicAuth
# Define the API parameters
="1"
fieldnumber="none"
action="onelastmonth"
filterTime
# Define the url of the endpoint
= "https://www.api.automaticfarmsolutionwebapp.com/AFS/ForecastVineyardGeojsonNew?"
api_endpoint
# Define the api url
=api_endpoint+"fieldnumber="+fieldnumber+"&action="+action+"&filterTime="+filterTime
url
# Set the useremail & Password
="useremail"
USEREMAIL="apikey""
APIKEY
# Path to the GeoJSON file
= "county.geojson"
file_path_to_geojson
# Read the GeoJSON file contents
with open(file_path_to_geojson, "r") as file:
= file.read()
geojson_data
# Set the headers for the request
= {
headers "Content-Type": "application/json"
}
# Make the POST request with the GeoJSON data as the request body
= requests.post(url,
response =geojson_data,
data=headers,
headers=HTTPBasicAuth(USEREMAIL, APIKEY))
auth
= bytes(response.content)
b
with fiona.BytesCollection(b) as f:
= f.crs
crs = gpd.GeoDataFrame.from_features(f, crs=crs)
gdf
# Visualize the data
"Data_2023.07.19") gdf.explore(
R
In this example we will test the ForecastVineyardGeojson which allow the user to get the latest vegetation index available for the Area of Interest in gejson format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
- action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
- file_path_to_geojson (you can find it here county.geojson the county file of the example)
With your information and let’s try out the API.
# Load the libraries
library(tictoc)
library(httr)
library(geojsonio)
library(mapview)
# Define the API parameters
="1"
fieldnumber="none"
action="onelastmonth"
filterTime
# Define the url of the API
<- "https://www.api.automaticfarmsolutionwebapp.com/AFS/ForecastVineyardGeojsonNew?"
api_endpoint
# Define the API call
=paste0(api_endpoint, "fieldnumber=", fieldnumber, "&action=",action, "&filterTime=", filterTime)
url
# Set the useremail & Password
="useremail"
USEREMAIL="apikey"
APIKEY
# Path to the GeoJSON file
= "county.geojson"
file_path_to_geojson
# Get the start time to API Call
tic()
# Make the POST request
<- POST(
api_call
url,::authenticate(
httruser = Sys.getenv(USEREMAIL),
password = Sys.getenv(APIKEY)
),body=httr::upload_file(file_path_to_geojson)
)
# Print out the seconds needed to create the prescription map
print("The API needed:")
[1] "The API needed:"
toc()
2.68 sec elapsed
# Visualize the prescription map
<- content(api_call, as = "text", type = "application/geo+json")
vegetation_index <-geojson_sp(vegetation_index)
vegetation_indexmapview(vegetation_index, zcol=names(vegetation_index)[1], layer.name="Evapotraspiration 2023.07.19")
Node.js
In this example we will test the ForecastVineyardGeojson which allow the user to get the latest vegetation index available for the Area of Interest in gejson format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
- action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
- filterTime, Set the date filter can be onelastmonth, twolastmonth or none
- file_path_to_geojson (you can find it here county.geojson the county file of the example)
With your information and let’s try out the API.
// Load Libraries
const fs = require('fs');
const axios = require('axios');
// Set the useremail & passowrd
const useremail = 'XXXXXXXXXXXXX';
const apikey = 'XXXXXXXXXXXXX';
// Set the api parameters
const fieldnumber="1"
const action="none"
const filterTime="onelastmonth";
// Set api url
const api_url = 'https://www.api.automaticfarmsolutionwebapp.com/AFS/ForecastVineyardGeojsonNew?';
// Set api endpoint
const apiEndpoint = api_url.concat("fieldnumber=",fieldnumber, "&action=",action, "&filterTime=", filterTime);
// Set path to load the geojson to send as body of POST request to the API
const file_path_to_geojson = './county.geojson';
// Set path to save the geojson prescription map
const outputFilePath = './result.geojson';
async () => {
(try {
const geojsonContent = await fs.promises.readFile(file_path_to_geojson, 'utf8');
const geojsonObject = JSON.parse(geojsonContent);
const authHeader = `Basic ${Buffer.from(`${useremail}:${apikey}`).toString('base64')}`;
const response = await axios.post(apiEndpoint, geojsonObject, {
headers: {
'Content-Type': 'application/json',
'Authorization': authHeader
};
})
const resultGeoJSON = response.data;
console.log('Answer From the API:', resultGeoJSON);
await fs.promises.writeFile(outputFilePath, JSON.stringify(resultGeoJSON, null, 2), 'utf8');
catch (err) {
} console.error('Error:', err.message);
}; })()
ForecastVineyardTemporalVarationJson
Python
In this example we will test the ForecastVineyardTemporalVarationJson which allow the user to get a json with the temporal variation of the vegetation index.
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
- action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
- file_path_to_geojson (you can find it here county.geojson the county file of the example)
With your information and let’s try out the API.
# Load the libraries
import requests
import json
import pandas as pd
from requests.auth import HTTPBasicAuth
# Define the API parameters
="1"
fieldnumber="none"
action
# Define the url of the endpoint
= "https://www.api.automaticfarmsolutionwebapp.com/AFS/ForecastVineyardTemporalVarationJsonNew?"
api_endpoint
# Define the api url
=api_endpoint+"fieldnumber="+fieldnumber+"&action="+action
url
# Set the useremail & Password
="XXXXXXXXXXXX"
USEREMAIL="XXXXXXX"
APIKEY
# Path to the GeoJSON file
= "county.geojson"
file_path_to_geojson
# Read the GeoJSON file contents
with open(file_path_to_geojson, "r") as file:
= file.read()
geojson_data
# Set the headers for the request
= {
headers "Content-Type": "application/json"
}
# Make the POST request with the GeoJSON data as the request body
= requests.post(url,
response =geojson_data,
data=headers,
headers=HTTPBasicAuth(USEREMAIL, APIKEY))
auth
=response.content
response_bytes
= response_bytes.decode('utf-8')
response_str
# Parse the JSON string
= json.loads(response_str)
data
# Create a DataFrame
= pd.DataFrame(data)
df
df.head()
R
In this example we will test the ForecastVineyardTemporalVarationJson which allow the user to get a json with the temporal variation of the vegetation index.
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
- action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
- file_path_to_geojson (you can find it here county.geojson the county file of the example)
With your information and let’s try out the API.
# Load the libraries
library(tictoc)
library(httr)
library(geojsonio)
library(mapview)
# Define the API parameters
="1"
fieldnumber="none"
action
# Define the url of the API
<- "https://www.api.automaticfarmsolutionwebapp.com/AFS/ForecastVineyardTemporalVarationJsonNew?"
api_endpoint
# Define the API call
=paste0(api_endpoint, "fieldnumber=", fieldnumber, "&action=",action)
url
# Set the useremail & Password
="useremail"
USEREMAIL="apikey"
APIKEY
# Path to the GeoJSON file
= "county.geojson"
file_path_to_geojson
# Get the start time to API Call
tic()
# Make the POST request
<- POST(
api_call
url,::authenticate(
httruser = Sys.getenv(USEREMAIL),
password = Sys.getenv(APIKEY)
),body=httr::upload_file(file_path_to_geojson)
)
# Print out the seconds needed to create the prescription map
print("The API needed:")
toc()
# Visualize the prescription map
<- httr::content(api_call, as = "text", type = "application/json", encoding="UTF-8")
cont <-jsonlite::fromJSON(cont) %>% as.data.frame
cont cont
Node.js
In this example we will test the ForecastVineyardTemporalVarationJson which allow the user to get a json with the temporal variation of the vegetation index.
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
- action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
- file_path_to_geojson (you can find it here county.geojson the county file of the example)
With your information and let’s try out the API.
// Load Libraries
const fs = require('fs');
const axios = require('axios');
// set the username and apikey
const useremail = 'XXXXXXXXXXXX';
const apikey = 'XXXXXXXXXXXX';
// Set the api parameters
const fieldnumber="1"
const action="none"
// Set api url
const api_url = 'https://www.api.automaticfarmsolutionwebapp.com/AFS/ForecastVineyardTemporalVarationJsonNew?';
// Set api endpoint
const apiUrl = api_url.concat("fieldnumber=",fieldnumber,"&action=",action);
const file_path_to_geojson = './county.geojson';
async function main() {
try {
const geojson = JSON.parse(fs.readFileSync(file_path_to_geojson, 'utf8'));
const authHeader = `Basic ${Buffer.from(`${useremail}:${apikey}`).toString('base64')}`;
const response = await axios.post(apiUrl, geojson, {
headers: {
Authorization: authHeader,
'Content-Type': 'application/json',
,
};
})
// Print the formatted JSON response to the console
console.log(JSON.stringify(response.data, null, 2));
catch (error) {
} console.error('An error occurred:', error.message);
}
}
main();
Java
Work in progress
Easy - Fast - Customizable