Skip to content

Commit e8673ac

Browse files
committed
run.sh v0
1 parent e9aceef commit e8673ac

12 files changed

Lines changed: 794 additions & 2542 deletions

File tree

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,3 +165,6 @@ cython_debug/
165165
#developement
166166
notes.md
167167
debug.md
168+
tests/api_logs.json
169+
170+
docker-compose.yml

README.md

Lines changed: 8 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,35 @@
1-
# PG_MFSERVER
2-
1+
# MobilityAPI
32
This server is a Python API that allows GET, POST, PUT, and DELETE operations on MobilityDB. The server utilizes the [PyMEOS](https://github.com/MobilityDB/PyMEOS) library.
4-
53
This implementation follows the OGC API - Moving Features Standard
64

75
## Introduction
8-
96
This Python API server provides endpoints for interacting with MobilityDB, a temporal extension for PostgreSQL. It allows users to perform CRUD operations (Create, Read, Update, Delete) on MobilityDB data using HTTP methods.
107

118
## Features
12-
139
- Supports GET, POST, PUT, and DELETE operations.
1410
- Integrates the PyMEOS library for seamless interaction with MobilityDB.
1511
- Provides endpoints for managing data stored in MobilityDB.
16-
## To test
17-
- create env from requirements.txt
18-
- docker pull --platform=linux/amd64 mobilitydb/mobilitydb
19-
- docker volume create mobilitydb_data
20-
- docker run --name mobilitydb -e POSTGRES_PASSWORD=mysecretpassword -p 25431:5432 -v mobilitydb_data:/var/lib/postgresql -d mobilitydb/mobilitydb
21-
- python server.py
22-
- pytest -v -s
12+
2313
## Prerequisites
2414
- Linux (ubuntu)
2515
- A recent version of Pyhton
26-
- A MobilityDB running locally or on a server
27-
28-
## Installation
2916

30-
To install and run the server, follow these steps:
3117

32-
1. Download the server.py and utils.py file in the same folder.
33-
2. Dowload the rest-clients and change the queries to match your MOBILITYDB collections.
34-
3. Change the connection parameters in the server.py file.
35-
4. Install [PyMEOS](https://github.com/MobilityDB/PyMEOS)
36-
```bash
37-
python3 server.py
38-
6. Enjoy !
18+
## RUN SERVER
19+
- Make script executable: chmod +x run.sh
20+
- Run only the server: ./run.sh
21+
#### RUN SERVER WITH TESTS
22+
- Download ships datasets from: [Denmark Ships DataSets](http://aisdata.ais.dk/?prefix=2024/) aisdk_2024-08-07.zip in data folder
23+
- Run with integration tests: ./run.sh --with-tests (note: this takes a while due to data preprocessing - expect 23 min )
3924

4025
## Usage
41-
4226
Send http requests to the api using any http service.
43-
4427
As an example, your can use the ais.sql that will create ships and ship2 tables containing ships data.
4528
To do that you will have to change the path in the script to the path of your .csv file.
46-
4729
Here is a link to download ships datasets: [Denmark Ships DataSets](http://aisdata.ais.dk/?prefix=2024/)
48-
4930
## Developement
50-
5131
This project is in progress.
52-
5332
## License
54-
55-
56-
5733
##Poetry
5834
poetry install
5935

data/ais_to_json.py

Lines changed: 19 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,24 @@
77
import geopandas as gpd
88
import pandas as pd
99
import numpy as np
10-
1110
from utils import get_csv_from_zip
12-
# Load database configuration from config.json
13-
with open("../config.json", "r") as file:
11+
12+
script_dir = os.path.dirname(os.path.abspath(__file__))
13+
output_file= os.path.join(script_dir, ".", "trajectories_mf1.json")
14+
config_path = os.path.join(script_dir, "..", "config.json")
15+
with open(config_path, "r") as file:
1416
config = json.load(file)
1517

16-
# Construct the database URL for SQLAlchemy
18+
1719
database_url = (
1820
f"postgresql://{config['DB_USER']}:{config['DB_PASS']}@"
1921
f"{config['DB_HOST']}:{config['DB_PORT']}/{config['DB_NAME']}"
2022
)
2123

2224
# Create the SQLAlchemy engine
2325
engine = create_engine(database_url)
24-
data_csv_path = get_csv_from_zip("aisdk-2024-08-07.zip")
26+
zip_path = os.path.join(script_dir, "aisdk-2024-08-07.zip")
27+
data_csv_path = get_csv_from_zip(zip_path,script_dir)
2528
data_csv_path=os.path.abspath(data_csv_path)
2629
print(data_csv_path)
2730
#update this based on whether you're running your db from docker or local/ this is a docker version, otherwise comment it out
@@ -33,64 +36,52 @@
3336

3437
# Data collection and 9.3 Cleaning Static Attribute +9.4 Voyage related Attribbutes:
3538
try:
36-
# Read the SQL file CleaningStaticAttributes.sql
37-
with open("init.sql", "r") as sql_file:
39+
init_sql= os.path.join(script_dir, ".", "init.sql")
40+
with open(init_sql, "r") as sql_file:
3841
sql_query = sql_file.read()
3942

40-
# Create a text object with parameters
4143
stmt = text(sql_query).bindparams(data_csv_path=data_csv_path)
4244

43-
# Execute with parameter
4445
with engine.connect() as conn:
45-
# Start a transaction
46+
4647
with conn.begin():
47-
# Execute the COPY command with parameter
4848
conn.execute(stmt)
4949
print(f"Successfully loaded data from {data_csv_path}")
5050

5151
except Exception as e:
5252
print(f"Error loading data: {e}")
5353
raise
5454

55-
56-
# After your existing data loading code, add this:
57-
58-
def export_json_from_view(engine, output_file="trajectories_mf1.json"):
55+
def export_json_from_view(engine, output_file=output_file):
5956
query = "SELECT json_data FROM ships_json ORDER BY mmsi;"
6057

6158
try:
62-
# Fetch all JSON data from the view
63-
# for df in pd.read_sql(query, engine,chunksize=686):
64-
59+
6560
df = pd.read_sql(query, engine)
6661

6762
if df.empty:
6863
print("No data found in ships_json view")
6964
return []
7065

71-
# Extract the json_data column as a list of dicts
66+
7267
json_ready = df['json_data'].tolist()
73-
print('777777777777777777777777777777777777777777777')
74-
# Ensure output directory exists
75-
# os.makedirs(os.path.dirname(output_file), exist_ok=True)
76-
77-
# Write to JSON file
68+
7869
with open(output_file, "w") as f:
7970
json.dump(json_ready, f, indent=2, default=str)
8071

81-
print(f"Successfully exported {len(json_ready)} vessels to {output_file}")
72+
print(f"Successfully exported {len(json_ready)} ais vessels to {output_file}")
8273
return json_ready
8374

8475
except Exception as e:
8576
print(f"Error exporting JSON: {e}")
8677
raise
8778

88-
# Call the function after your data loading
79+
8980
if __name__ == "__main__":
9081

9182

92-
# Export to JSON
93-
export_json_from_view(engine, "trajectories_mf1.json")
83+
#to JSON
84+
export_json_from_view(engine, output_file=output_file)
9485

9586

9687
# DROP VIEW IF EXISTS ships_json CASCADE;

data/init.sql

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
-- ACTIVITY 2: VESSELS - Complete Processing Pipeline
33
-- Based on Assignment 2 solutions from ULB
44
-- ============================================================================
5-
6-
-- 1. Create the MobilityDB extension if not exists
5+
SET DATESTYLE = 'ISO, DMY';
6+
-- 1. Create the MobilityDB extension if not exists
77
CREATE EXTENSION IF NOT EXISTS MobilityDB CASCADE;
88

99
-- 2. Create the raw AIS input table (based on PDF page 2)
@@ -198,7 +198,7 @@ FROM ShipsBelt;
198198
-- Envelope: ST_MakeEnvelope(644339, 6042108, 644896, 6042487, 25832)
199199

200200
-- 14. Find ships traveling between Rodby and Puttgarden
201-
SELECT s.MMSI, s.Name, length(s.Trip)/1000 AS length_km
202-
FROM Ships s
203-
WHERE eintersects(s.Trip, ST_MakeEnvelope(651135, 6058230, 651422, 6058548, 25832))
204-
AND eintersects(s.Trip, ST_MakeEnvelope(644339, 6042108, 644896, 6042487, 25832));
201+
-- SELECT s.MMSI, s.Name, length(s.Trip)/1000 AS length_km
202+
-- FROM Ships s
203+
-- WHERE eintersects(s.Trip, ST_MakeEnvelope(651135, 6058230, 651422, 6058548, 25832))
204+
-- AND eintersects(s.Trip, ST_MakeEnvelope(644339, 6042108, 644896, 6042487, 25832));

data/trajectories_mf1.json

Lines changed: 549 additions & 549 deletions
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)