Commit 2fd57f15 authored by Tero Ojanen's avatar Tero Ojanen
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading

.env.example

0 → 100644
+27 −0
Changes for .env.example: 27 added lines, 0 removed lines.
Original line number Diff line number Diff line
FMI_BASE_URL=https://opendata.fmi.fi/wfs # Base URL for Finnish Meteorological Institute
DEBUG_MODE=False # Toggle debug mode

# Even if you change this variable, you have to adjust the code to actually be able to adjust the amount of hours we process.
# This relates to MVP_toteuma.py, how many hours of actualized data (from the past) do we fetch.
LOOKBACK_HOURS=2 # How many hours back to fetch actual precipitation data

# Determine how many hours of predictions we are interested in seeing.
PREDICTION_HOURS=12

# Thresholds for giving warnings
# Precipitation thresholds when looking at the whole time period
THRESHOLD_MILD_TOTAL=30.0
THRESHOLD_MODERATE_TOTAL=35.0
THRESHOLD_SEVERE_TOTAL=40.0

# Precipitation thresholds when looking at a short time period, e.g. 1 hour
THRESHOLD_MILD_PEAK=25.0
THRESHOLD_MODERATE_PEAK=30.0
THRESHOLD_SEVERE_PEAK=35.0

# Bounding box for Mikkeli city center area [used for predictions]
FMI_BBOX=27.2575,61.6775,27.28,61.7


# Station IDs and names (used for actualized data)
STATIONS_JSON={"150168": "Puumala", "101398": "Mikkeli lentoasema", "101196": "Heinola Asemantaus", "101219": "Kouvola Utti Lentoportintie", "101237": "Lappeenranta lentoasema", "101421": "Varkaus Kosulanniemi", "101367": "Joutsa Savenaho"}

.gitignore

0 → 100644
+3 −0
Changes for .gitignore: 3 added lines, 0 removed lines.
Original line number Diff line number Diff line
__pycache__/
venv/
.env

LICENSE

0 → 100644
+21 −0
Changes for LICENSE: 21 added lines, 0 removed lines.
Original line number Diff line number Diff line
MIT License

Copyright (c) 2025 South-Eastern Finland University of Applied Sciences (Xamk)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 No newline at end of file

MVP_ennuste.py

0 → 100644
+131 −0
Changes for MVP_ennuste.py: 131 added lines, 0 removed lines.
Original line number Diff line number Diff line
import datetime as dt # For working with dates and times
from fmiopendata.wfs import download_stored_query # FMI Open data API client
import os # For accessing environmental variables from .env 
import traceback # For printing detailed error traces
from dotenv import load_dotenv # To Load environment variables from .env file

# Load environment variables
load_dotenv()

# Get bounding box for Mikkeli
FMI_BBOX = os.getenv("FMI_BBOX")

# Load how many hours of predictions we want to fetch
RAW_PREDICTION_HOURS = int(os.getenv("PREDICTION_HOURS"))

# Adjust prediction hours to get the actual hours requested by the variable.
# e.g. If you want 6 hours of predictions, you need to adjust the value to be 5.
ADJUSTED_PREDICTION_HOURS = (RAW_PREDICTION_HOURS - 1)

# Load threshold values for warnings
THRESHOLDS = {
    "total": {
        "mild": float(os.getenv("THRESHOLD_MILD_TOTAL")),
        "moderate": float(os.getenv("THRESHOLD_MODERATE_TOTAL")),
        "severe": float(os.getenv("THRESHOLD_SEVERE_TOTAL"))
    }
}

# Function to classify precipitation value into warning levels
def classify_precipitation(value):
    thresholds = THRESHOLDS["total"]
    if value >= thresholds["severe"]:
        return "Severe Warning"
    elif value >= thresholds["moderate"]:
        return "Moderate Warning"
    elif value >= thresholds["mild"]:
        return "Mild Warning"
    else:
        return "No Warning"

# Main function to fetch forecasted precipitation data from FMI
def fetch_fmi_precipitation_predictions():
    try:

        # We subtract one hour to get the current hours predictions. 
        # Example 1: If we make an API-request with 15:05, it only gives predictions starting from 16:00 onwards.
        # Example 2: If we make an API-request with 14:55, it gives predictions starting from 15:00 onwards.
        now = dt.datetime.utcnow() - dt.timedelta(hours=1)

        # Define start and end time for forecast query (currently next 6 hours)
        start_time = now.strftime('%Y-%m-%dT%H:%M:%SZ')
        end_time = (now + dt.timedelta(hours=ADJUSTED_PREDICTION_HOURS)).strftime('%Y-%m-%dT%H:%M:%SZ')

        # Query FMI for grid-based surface forecast data
        model_data = download_stored_query(
            "fmi::forecast::harmonie::surface::grid",
            args=[
                f"starttime={start_time}",
                f"endtime={end_time}",
                f"bbox={FMI_BBOX}"
            ]
        )

        # Get the latest model run (most recent forecast)
        latest_run = max(model_data.data.keys())
        data = model_data.data[latest_run]

        # Parse the data to clean up memory
        data.parse(delete=True)

        # Extract valid forecast times
        valid_times = sorted(data.data.keys())
        last_precip = 0.0

        # Dead code - variable end_time is used instead.
        last_time = None

        # Loop through forecast times in order
        # Note: Code has been changed from original.
        #       Current form of the code just gets the last item from the data
        #       Kept looking like original, in case we want to revert back and add features.
        for t in valid_times[-ADJUSTED_PREDICTION_HOURS:]:
            for level in data.data[t]:
                datasets = data.data[t][level]

                # Loop through dataset names to find precipitation data
                # In current implementation, we are interested in only the total precipitation amount.
                # The total precipitation amount can be found from the last hour in the forecast data.
                # NOTE: 
                # The structure of the data is unintuitive. E.g. if hour 1 shows 0.1 mm and hour 2 shows 0.1 mm,
                # then it means that on hour 1 it rained 0.1 mm, but on hour 2 it didn't rain, and the total is still 0.1 mm.
                # The value on the hour shows the "total rain so far", not "rain during the lats hour". 
                # If on hour 3 it shows 0.3 mm, and on hour 2 it shows 0.1 mm, it means that on hour 3 it predicts 0.2 mm of rain.
                # As a general comment, ALL the data relating to the precipitation amounts is quite unintuitive, and double checking is recommended.
                for dset in datasets:
                    if "prec" in dset.lower():
                        values = datasets[dset]["data"]
                        flat = [v for row in values for v in row]

                        # Calculate average precipitation for the grid
                        # Note: Grid consists of many values, we take the average of these values.
                        avg_prec = round(sum(flat) / len(flat), 1) if flat else 0.0
                        last_precip = avg_prec

                        # Dead code - variable end_time is used instead.
                        last_time = t.strftime('%Y-%m-%dT%H:%M:%SZ')
                        break
                else:
                    continue
                break

        # Creates the warning: did the precipitation value exceed a threshold value
        warning = classify_precipitation(last_precip)

        # Return the values we have found, which are then used in the frontend
        return {
            "city_name": "Mikkeli", # Currently we are only doing precipitation predictions for Mikkeli
            "total_precipitation": last_precip,
            "total_precipitation_warning": warning,
            "total_precipitation_time_range": {
                "start": start_time,
                "end": end_time
            }
        }

    except Exception as e:
        # Print error message and traceback for debugging
        print(f"Failed to fetch or process FMI data: {e}")

        traceback.print_exc()
        return None

MVP_toteuma.py

0 → 100644
+109 −0
Changes for MVP_toteuma.py: 109 added lines, 0 removed lines.
Original line number Diff line number Diff line
import requests # For making HTTP requests to FMI API
from xml.etree import ElementTree as ET # For parsing XML responses
from datetime import datetime, timedelta # For handling time ranges
import traceback # For printing detailed error messages
import os # For accessing environment variables
import json # For parsing station data from JSON
from dotenv import load_dotenv # To load environment variables from .env file

# Load environment variables from .env file
load_dotenv()

# Read configuration values from environment
FMI_BASE_URL = os.getenv("FMI_BASE_URL") # Base URL for FMI API
DEBUG_MODE = os.getenv("DEBUG_MODE") == "True" # Enable debug logging if set to true in .env.
LOOKBACK_HOURS = int(os.getenv("LOOKBACK_HOURS")) # How many hours back to fetch data
STATIONS = json.loads(os.getenv("STATIONS_JSON")) # Dictionary of station IDs and names

# Thresholds for warning levels based on total precipitation
THRESHOLDS = {
    "mild": float(os.getenv("THRESHOLD_MILD_TOTAL")),
    "moderate": float(os.getenv("THRESHOLD_MODERATE_TOTAL")),
    "severe": float(os.getenv("THRESHOLD_SEVERE_TOTAL")),
}

# Function to fetch actual precipitation for a specific station
def classify_precipitation(total):
    if total >= THRESHOLDS["severe"]:
        return "Severe Warning"
    elif total >= THRESHOLDS["moderate"]:
        return "Moderate Warning"
    elif total >= THRESHOLDS["mild"]:
        return "Mild Warning"
    else:
        return "No Warning"

# Function to fetch actual precipitation data for a specific station
def fetch_precipitation_for_station(station_id, station_name):
    # Define time range for the query: from LOOKBACK_HOURS ago to now
    end_time = datetime.utcnow()
    start_time = end_time - timedelta(hours=LOOKBACK_HOURS)
    
    # Format times as ISO 8601 strings
    start_str = start_time.strftime("%Y-%m-%dT%H:%M:%SZ")
    end_str = end_time.strftime("%Y-%m-%dT%H:%M:%SZ")

    # Define query parameters for FMI API
    params = {
        "request": "GetFeature",
        "storedquery_id": "fmi::observations::weather::timevaluepair",
        "fmisid": station_id,
        "parameters": "precipitation1h",
        "starttime": start_str,
        "endtime": end_str
    }

    try:
        # Make the API request
        response = requests.get(FMI_BASE_URL, params=params)

        # Parse the XML response
        root = ET.fromstring(response.content)
        ns = {'wml2': 'http://www.opengis.net/waterml/2.0'} # XML namespace for WaterML

        time_rain_pairs = [] # List to store (time, value) pairs

        # Extract precipitation values from XML
        for point in root.findall('.//wml2:point', ns):
            time_str = point.find('.//wml2:time', ns).text
            value_str = point.find('.//wml2:value', ns).text
            try:
                val = float(value_str) # Convert value to float
                time_rain_pairs.append((time_str, val)) # Store time and value
            except ValueError:
                continue # Skip invalid values

        # Extract up to two most recent precipitation values
        # If you want more than two values, this part needs to be revised
        if len(time_rain_pairs) >= 2:
            time1, rain1 = time_rain_pairs[0]
            time2, rain2 = time_rain_pairs[1]
        elif len(time_rain_pairs) == 1:
            time1, rain1 = time_rain_pairs[0]
            time2, rain2 = None, 0.0
        else:
            time1, rain1, time2, rain2 = None, 0.0, None, 0.0

        # Combine the two values
        raincombined = rain1 + rain2

        # Classify the combined precipitation into a warning level
        warninglevel = classify_precipitation(raincombined)

        # Return the structured result
        return {
            "station_name": station_name,
            "time1": time1,
            "rain1": rain1,
            "time2": time2,
            "rain2": rain2,
            "raincombined": raincombined,
            "warninglevel": warninglevel
        }

    except Exception as e:
        # Print error message and traceback if something goes wrong
        print(f"Error fetching or processing data for {station_name}: {e}")
        
        traceback.print_exc()
        return None # Return None on failure
Loading