<jupyter_start><jupyter_text><jupyter_code>!pip install earthengine-api geehydro geemap
!earthengine authenticate

from google.colab import drive
drive.mount('/content/drive')

# Import the Earth Engine API and initialize it.
import ee
ee.Initialize()
import geehydro
import folium

# Load a Landsat 8 ImageCollection for a single path-row.
table = ee.FeatureCollection("FAO/GAUL/2015/level1").filter(ee.Filter.eq('ADM0_NAME', 'Ukraine'))
nighttimeLights = ee.ImageCollection('NOAA/DMSP-OLS/CALIBRATED_LIGHTS_V4').filterDate('2010-01-01', '2019-12-31').filterBounds(ee.Geometry.Rectangle(49.9398,  49.7572, 23.8752, 24.2065))
nighttimeLights = nighttimeLights.select('avg_vis')
image = ee.Image(nighttimeLights.median()).clip(table);

Map = folium.Map(location=[49.3022,32.1675], zoom_start=6)# To see a google satellite view as a basemap
Map.setOptions('HYBRID')

nighttimeLightsVis = {
  min: 3.0,
  max: 60.0,
};

Map.addLayer(image, nighttimeLightsVis, 'Night Ligth')
# Map.addLayer(table, {}, 'admin')

training = image.sample(**{
    'region': table,
    'scale': 30,
    'numPixels': 5000,
    'seed': 0,
    'geometries': True  # Set this to False to ignore geometries
})


n_clusters = 5
clusterer = ee.Clusterer.wekaKMeans(n_clusters).train(training)
# Cluster the input using the trained clusterer.
result = image.cluster(clusterer)

legend_keys = ['One', 'Two', 'Three', 'Four', 'ect']
legend_colors = ['#F0F8FF', '#FFFFB3', '#BEBADA', '#FB8072', '#80B1D3']

# Reclassify the map
result = result.remap([0, 1, 2, 3, 4], [1, 2, 3, 4, 5])

Map.addLayer(result, {'min': 1, 'max': 5, 'palette': legend_colors}, 'Labelled clusters')

Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map
# import branca

# colormap = branca.colormap.linear.YlOrRd_09.scale(0, 8500)
# colormap = colormap.to_step(index=[0, 1000, 3000, 5000, 8500])
# colormap.caption = 'Incidents of Crime in Victoria (year ending June 2018)'
# # colormap.colors=legend_colors
# colormap.add_to(Map)

# Map
import folium
from ipyleaflet import *
from bqplot import pyplot as plt


Map = folium.Map(location=[49.3022,32.1675], zoom_start=7)
Map.default_style = {'cursor': 'crosshair'}

# Compute the trend of nighttime lights from DMSP.
# Add a band containing image date as years since 1990.
def createTimeBand(img):
  year = img.date().difference(ee.Date('1991-01-01'), 'year')
  return ee.Image(year).float().addBands(img)

NTL = ee.ImageCollection('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS') \
    .select('stable_lights')

# Fit a linear trend to the nighttime lights collection.
collection = NTL.map(createTimeBand)
fit = collection.reduce(ee.Reducer.linearFit())

image = NTL.toBands()

figure = plt.figure(1, title='Nighttime Light Trend', layout={'max_height': '250px', 'max_width': '400px'})
count = collection.size().getInfo()
start_year = 1992
end_year = 2013
x = range(1, count+1)

coordinates = []
markers = []
# marker_cluster = MarkerCluster(name="Marker Cluster")
# Map.addLayer(marker_cluster)

def handle_interaction(**kwargs):
    latlon = kwargs.get('coordinates')
    if kwargs.get('type') == 'click':
        coordinates.append(latlon)
        markers.append(Marker(location=latlon))
        marker_cluster.markers = markers
        xy = ee.Geometry.Point(latlon[::-1])
        y = image.sample(xy, 500).first().toDictionary().values().getInfo()
        plt.clear()
        plt.plot(x, y)
#         plt.xticks(range(start_year, end_year, 5))
# Map.on_interaction(handle_interaction)

# Display a single image
Map.addLayer(ee.Image(collection.select('stable_lights').first()), {'min': 0, 'max': 63}, 'First image')

# Display trend in red/blue, brightness in green.
Map.setCenter(30, 45, 4)
Map.addLayer(fit,
         {'min': 0, 'max': [0.18, 20, -0.18], 'bands': ['scale', 'offset', 'scale']},
         'stable lights trend')

# fig_control = WidgetControl(widget=figure, position='bottomright')
# Map.add_control(fig_control)

Map<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1557397638784225, 'fraction_numerical': 0.04747550866616428, 'mean_word_length': 5.0608828006088284, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '213398', 'license': 'MIT', 'n_tokens_mistral': 1570, 'n_tokens_neox': 1429, 'n_words': 315, 'path': 'night_light.ipynb', 'repo_name': 'shliakhtas/ASCM', 'size': '3981'}