File size: 3,620 Bytes
2edf7af
 
ddd1a18
27ce821
 
 
 
ddd1a18
 
 
35f22e9
27ce821
ddd1a18
 
 
35f22e9
ddd1a18
35f22e9
ddd1a18
 
 
27ce821
ddd1a18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27ce821
 
ddd1a18
 
 
 
27ce821
ddd1a18
 
 
27ce821
ddd1a18
 
27ce821
ddd1a18
 
 
27ce821
ddd1a18
 
27ce821
 
ddd1a18
 
 
 
 
27ce821
ddd1a18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import streamlit as st
import pandas as pd
import geopandas as gpd
import ee
import geemap
import folium
from streamlit_folium import folium_static
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime, timedelta

# Initialize Earth Engine
service_account = 'esmaeil-kiani1387-gmail-com@ee-esmaeilkiani13877.iam.gserviceaccount.com'
credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani13877-9a054809a4bb.json')
ee.Initialize(credentials)

# Load farm data
@st.cache_data
def load_data():
    df = pd.read_csv('tableConvert.com_wftamx (1).csv')
    return df

# Calculate vegetation indices
def calculate_indices(image):
    ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
    evi2 = image.expression(
        '2.5 * ((NIR - RED) / (NIR + 2.4 * RED + 1))',
        {'NIR': image.select('B8'), 'RED': image.select('B4')}
    ).rename('EVI2')
    lai = image.expression(
        '3.618 * EVI - 0.118',
        {'EVI': image.select('EVI2')}
    ).rename('LAI')
    return image.addBands([ndvi, evi2, lai])

# Get Sentinel-2 imagery
def get_sentinel_imagery(geometry, start_date, end_date):
    return (ee.ImageCollection('COPERNICUS/S2_SR')
            .filterBounds(geometry)
            .filterDate(start_date, end_date)
            .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
            .map(calculate_indices)
            .median())

# Main app
def main():
    st.title('Sugarcane Farm Analysis')

    # Load data
    df = load_data()

    # Sidebar
    st.sidebar.title('Farm Selection')
    selected_farm = st.sidebar.selectbox('Select a farm', df['name'])

    # Main content
    col1, col2 = st.columns([1, 2])

    with col1:
        st.subheader('Farm Information')
        farm_data = df[df['name'] == selected_farm].iloc[0]
        st.write(f"Age: {farm_data['age']}")
        st.write(f"Variety: {farm_data['variety']}")

    with col2:
        st.subheader('Farm Location')
        m = folium.Map(location=[farm_data['latitude'], farm_data['longitude']], zoom_start=12)
        folium.Marker(
            [farm_data['latitude'], farm_data['longitude']],
            popup=farm_data['name']
        ).add_to(m)
        folium_static(m)

    # Vegetation indices analysis
    st.subheader('Vegetation Indices Analysis')
    
    # Date range selection
    today = datetime.now()
    start_date = st.date_input('Start date', today - timedelta(days=30))
    end_date = st.date_input('End date', today)

    if start_date and end_date:
        geometry = ee.Geometry.Point([farm_data['longitude'], farm_data['latitude']])
        image = get_sentinel_imagery(geometry, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))

        # Display NDVI map
        ndvi_map = geemap.Map(center=[farm_data['latitude'], farm_data['longitude']], zoom=14)
        ndvi_map.add_layer(image.select('NDVI'), {'min': 0, 'max': 1, 'palette': ['red', 'yellow', 'green']}, 'NDVI')
        ndvi_map.add_child(folium.LayerControl())
        folium_static(ndvi_map)

        # Plot time series of indices
        indices = ['NDVI', 'EVI2', 'LAI']
        fig, ax = plt.subplots(figsize=(10, 6))
        
        for index in indices:
            values = image.select(index).reduceRegion(
                reducer=ee.Reducer.mean(),
                geometry=geometry,
                scale=10
            ).getInfo()[index]
            ax.plot([start_date, end_date], [values, values], label=index)

        ax.set_xlabel('Date')
        ax.set_ylabel('Index Value')
        ax.legend()
        st.pyplot(fig)

if __name__ == '__main__':
    main()