Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev environmental exposure #1455

Open
wants to merge 105 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 83 commits
Commits
Show all changes
105 commits
Select commit Hold shift + click to select a range
cf59df2
dev-Environmental-Exposure: add buffer creater for test purpose
jc2341 Dec 8, 2024
fce3b37
dev-Environmental-Exposure: add consolidated env_features obda
jc2341 Dec 8, 2024
c3dbfed
dev-Environmental-Exposure: add food hygiene rating query template fo…
jc2341 Dec 9, 2024
9c2556f
dev-Environmental-Exposure: add greenspace query template for env_fea…
jc2341 Dec 9, 2024
ad6eea0
devEnvironmental-Exposure: correct the naming typo
jc2341 Dec 9, 2024
5f38521
devEnvironmental-Exposure: tested OBDA and sparql to extract attribut…
jc2341 Dec 9, 2024
a714893
dev-Environmental-Exposure: optimise query efficiency for greenspace …
jc2341 Dec 9, 2024
adb9191
dev-Environmental-Exposure: add food hygiene extrator
jc2341 Dec 9, 2024
3fcbdb6
dev-Environmental-Exposure: create food hygiene rating extractor func…
jc2341 Dec 10, 2024
2c3f3bd
dev-Environmental-Exposure: create greenspace extractor function for …
jc2341 Dec 10, 2024
c3d84f8
dev-Environmental-Exposure: add exposure calculator
jc2341 Dec 11, 2024
2587533
dev-Environmental-Exposure: add a robust tool to extract trajectory m…
jc2341 Dec 12, 2024
d2e3392
dev-Environmental-Exposure: add config-properties file, summarise env…
jc2341 Dec 14, 2024
30381f2
dev-Environmental-Exposure: route file for exposure goal-based agent
jc2341 Dec 14, 2024
bc92f41
dev-Environmental-Exposure: tested http request with generic dataIRI
jc2341 Dec 17, 2024
50bce42
dev-Environmental-Exposure: correct typos or http filensme
jc2341 Dec 17, 2024
83cd8ba
dev-Environmental-Exposure: consolidate featuretype and domain name q…
jc2341 Dec 17, 2024
67dc338
dev-Environmental-Exposure: add feature type query templates
jc2341 Dec 17, 2024
ba1294f
dev-Environmental-Exposure: add function to fetch trajectory metedata…
jc2341 Dec 27, 2024
1ef3877
dev-Environmental-Exposure: update db connection function
jc2341 Dec 27, 2024
b80589f
dev-Environmental-Exposure: update package import info
jc2341 Dec 27, 2024
039cf0d
dev-Environmental-Exposure: update table name fetch function
jc2341 Dec 27, 2024
4c56e4d
dev-Environmental-Exposure: get time series data function
jc2341 Dec 28, 2024
d50b8ee
dev-Environmental-Exposure: add typing package and execute_query func…
jc2341 Dec 28, 2024
84cc9c8
dev-Environmental-Exposure: consolidate OBDA mapping for test purpose
jc2341 Dec 28, 2024
bf35330
dev-Environmental-Exposure: tested version of OBDA, support feature t…
jc2341 Jan 10, 2025
0735d1d
dev-Environmental-Exposure: add CORS package in deployment process
jc2341 Jan 10, 2025
06578dc
dev-Environmental-Exposure: add SPARQLWrapper package in deployment p…
jc2341 Jan 10, 2025
9f6d216
dev-Environmental-Exposure: app.py under testing
jc2341 Jan 13, 2025
65d8114
dev-Environmental-Exposure: generic query for env_feature type and do…
jc2341 Jan 13, 2025
2cebc10
dev-Environmental-Exposure: add AREA type of feature in http request …
jc2341 Jan 13, 2025
f1b6b3a
dev-Environmental-Exposure: tested version for generic query of Point…
jc2341 Jan 13, 2025
f374c4c
dev-Environmental-Exposure: generic query command use geosparql
jc2341 Jan 13, 2025
2b7fca9
dev-Environmental-Exposure: successful version: query feature type ge…
jc2341 Jan 14, 2025
59305a8
dev-Environmental-Exposure: debug settings(tasks.json) for vscode deb…
jc2341 Jan 14, 2025
99cdd0e
dev-Environmental-Exposure: debug settings(launch.json)
jc2341 Jan 14, 2025
f432d77
dev-Environmental-Exposure: remove comments in json file
jc2341 Jan 14, 2025
5b8cecb
dev-Environmental-Exposure: successful app: query feature type generi…
jc2341 Jan 15, 2025
4cd8d3f
dev-Environmental-Exposure: add geopandas package in docker settings
jc2341 Jan 15, 2025
3d1b841
dev-Environmental-Exposure: successful case for updating to db
jc2341 Jan 16, 2025
49bc202
dev-Environmental-Exposure: add fallbacks for env_extractor, increase…
jc2341 Jan 16, 2025
bf98694
dev-Environmental-Exposure: staticbuffer and greenpace query, source sql
jc2341 Jan 17, 2025
8a20389
dev-Environmental-Exposure: CumulativeTrajectoryQuery, source sql
jc2341 Jan 17, 2025
dacf35a
dev-Environmental-Exposure: optimised version by cache
jc2341 Jan 19, 2025
1c8ee45
dev-Environmental-Exposure: add equivalent sql command for trajectory…
jc2341 Jan 19, 2025
399d267
dev-Environmental-Exposure: placeholder explanation of equivalent sql…
jc2341 Jan 19, 2025
b94e3b3
dev-Environmental-Exposure: add equivalent sql command for trajectory…
jc2341 Jan 19, 2025
e57ad42
dev-Environmental-Exposure: link source table name to env feature nam…
jc2341 Jan 20, 2025
3e0fc5b
dev-Environmental-Exposure: sparql query for dataSourceName extraction
jc2341 Jan 20, 2025
0053cb5
dev-Environmental-Exposure: tested equivalent sql for instantiated gp…
jc2341 Jan 20, 2025
f04e405
dev-Environmental-Exposure: tested equivalent sql for greenspace and …
jc2341 Jan 20, 2025
dc653dd
dev-Environmental-Exposure: basic version for adding simplified expos…
jc2341 Jan 21, 2025
bd6c99e
dev-Environmental-Exposure: add fetch source table name function
jc2341 Jan 21, 2025
75f489d
dev-Environmental-Exposure: testing route for simplified exposure cal…
jc2341 Jan 21, 2025
3899a60
dev-Environmental-Exposure: add List and Dict pack for parameter tran…
jc2341 Jan 21, 2025
140133b
dev-Environmental-Exposure: recorded point: valid dataSourceName fetch
jc2341 Jan 21, 2025
f42930d
dev-Environmental-Exposure: tested route for environmental exposure c…
jc2341 Jan 21, 2025
c5cccab
dev-Environmental-Exposure: add time count for each critical step
jc2341 Jan 21, 2025
44afd37
dev-Environmental-Exposure: old version remove execute_qury function
jc2341 Jan 21, 2025
ec9f501
dev-Environmental-Exposure: new http request template for exposure ca…
jc2341 Jan 21, 2025
9ec6b1b
dev-Environmental-Exposure: add multiple trajectory IRI in example ht…
jc2341 Jan 22, 2025
9c19ce4
dev-Environmental-Exposure: rename template to exposure_count for bet…
jc2341 Jan 22, 2025
57c983f
dev-Environmental-Exposure: tested curl file for launch exposure count
jc2341 Jan 22, 2025
58edf14
dev-Environmental-Exposure: add curl command for exposure_count route
jc2341 Jan 22, 2025
bc75cb4
dev-Environmental-Exposure: amend the description section of agent ma…
jc2341 Jan 23, 2025
62c9045
dev-Environmental-Exposure: create hyperlink for tools mentioned in r…
jc2341 Jan 23, 2025
775824e
dev-Environmental-Exposure: create count-based exposure module, revis…
jc2341 Jan 23, 2025
b50809d
dev-Environmental-Exposure: add guildance for executing exposure_coun…
jc2341 Jan 23, 2025
c6e848a
dev-Environmental-Exposure: create hyperlink for config.properties
jc2341 Jan 23, 2025
3ed7656
dev-Environmental-Exposure: test the exposure route with remote servi…
jc2341 Jan 24, 2025
77abeda
dev-Environmental-Exposure: import tested route files
jc2341 Jan 24, 2025
4a9a53d
dev-Environmental-Exposure: correct the url_prefix for register_bluep…
jc2341 Jan 24, 2025
135c9eb
dev-Environmental-Exposure: correct the url in route.py
jc2341 Jan 24, 2025
5d6dae9
dev-Environmental-Exposure: Clean up the project history files and ke…
jc2341 Jan 24, 2025
4c73c92
dev-Environmental-Exposure: Corrected indexing of config.properties file
jc2341 Jan 24, 2025
baf62af
dev-Environmental-Exposure: Simplified OBDA statement in resources fo…
jc2341 Jan 24, 2025
5e7d093
dev-Environmental-Exposure: Create link for CURL and HTTP POST
jc2341 Jan 24, 2025
2694be3
dev-Environmental-Exposure: Adjust the logical order of the narrative…
jc2341 Jan 24, 2025
f8a63ea
dev-Environmental-Exposure: remove old-version config file placed und…
jc2341 Jan 24, 2025
3ca8108
dev-Environmental-Exposure: Enhance the explanation of ENV_DATA_ENDPO…
jc2341 Jan 24, 2025
69efbed
dev-Environmental-Exposure: Manage query commands by exposure type
jc2341 Jan 26, 2025
991771c
dev-Environmental-Exposure: add and test area query adapted to trajec…
jc2341 Jan 26, 2025
55b2c82
dev-Environmental-Exposure: add connect db function with try-execept …
jc2341 Jan 29, 2025
c162738
dev-Environmental-Exposure: remove outdated buffer creator
jc2341 Jan 31, 2025
bace66b
dev-Environmental-Exposure: remove area folder that stores tested que…
jc2341 Jan 31, 2025
9bf4912
dev-Environmental-Exposure: reset the Post url to localhost
jc2341 Jan 31, 2025
7df2488
dev-Environmental-Exposure: reset the Post url to localhost for prepr…
jc2341 Jan 31, 2025
d2f725e
dev-Environmental-Exposure: hide sensitive info in config property fi…
jc2341 Feb 1, 2025
9da73d4
dev-Environmental-Exposure: remove duplicated config.properties file
jc2341 Feb 2, 2025
ddba2a3
dev-Environmental-Exposure: remove test case, use sql template for be…
jc2341 Feb 3, 2025
73192f4
dev-Environmental-Exposure: remove test case, employ sparql template,…
jc2341 Feb 3, 2025
a5c6da1
dev-Environmental-Exposure: create exposure_utilities, use class to m…
jc2341 Feb 3, 2025
da67fc4
dev-Environmental-Exposure: reduce duplicated function syntax, import…
jc2341 Feb 4, 2025
5c3bcf5
dev-Environmental-Exposure: create SQL templates which are impoted in…
jc2341 Feb 4, 2025
c5b3747
dev-Environmental-Exposure: polish exposure utilities, employ the que…
jc2341 Feb 4, 2025
abb46d5
dev-Environmental-Exposure: sparql twmplate for food hygiene, greensp…
jc2341 Feb 4, 2025
acbee28
dev-Environmental-Exposure: remove outdated test_and_debug.py
jc2341 Feb 4, 2025
bcffed7
dev-Environmental-Exposure: correct the route url, remove unnecessary…
jc2341 Feb 4, 2025
fa87c5f
dev-Environmental-Exposure: tested version with modularised sql/sparq…
jc2341 Feb 4, 2025
729e4ec
dev-Environmental-Exposure: clean resource folder, remove outdated ob…
jc2341 Feb 6, 2025
75c576c
dev-Environmental-Exposure: import DB_URL, DB_USER and DATABASE Name …
jc2341 Feb 6, 2025
942974b
dev-Environmental-Exposure: remove redundant list of config.properties
jc2341 Feb 6, 2025
f74f1e1
dev-Environmental-Exposure: Upgrade numpy version to >=1.22 to meet r…
jc2341 Feb 7, 2025
71ec883
dev-Environmental-Exposure: sync pandas version to >=1.4.0 used on l…
jc2341 Feb 7, 2025
2b65963
dev-Environmental-Exposure: Adjust config file pointer
jc2341 Feb 7, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Agents/FenlandTrajectoryAgent/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ build/
dist/
*~*
.idea/
!.vscode/
py4jps/
coverage.xml
.coverage
Expand Down
68 changes: 68 additions & 0 deletions Agents/FenlandTrajectoryAgent/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
{

"version": "0.2.0",
"configurations": [
{
"type": "python",
"name": "Build and Debug (Flask)",
"request": "attach",
"host": "localhost",
"port": "${input:debug.port}",
"preLaunchTask": "compose-build-deploy",
"pathMappings": [
{
"localRoot": "${workspaceFolder}/agent",
"remoteRoot": "/app/agent"
}
]
},
{
"type": "python",
"name": "Debug (Flask)",
"request": "attach",
"host": "localhost",
"port": "${input:debug.port}",
"preLaunchTask": "compose-deploy",
"pathMappings": [
{
"localRoot": "${workspaceFolder}/agent",
"remoteRoot": "/app/agent"
}
]
},

{
"type": "python",
"name": "Reattach and Debug (Flask)",
"request": "attach",
"host": "localhost",
"port": "${input:debug.port.read}",
"pathMappings": [
{
"localRoot": "${workspaceFolder}/agent",
"remoteRoot": "/app/agent"
}
]
}
],
"inputs": [
{
"id": "debug.port",
"type": "command",
"command": "shellCommand.execute",
"args": {
"command": "bash ./stack.sh ports write",
"useFirstResult": true
}
},
{
"id": "debug.port.read",
"type": "command",
"command": "shellCommand.execute",
"args": {
"command": "bash ./stack.sh ports read",
"useFirstResult": true
}
}
]
}
76 changes: 76 additions & 0 deletions Agents/FenlandTrajectoryAgent/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "compose-build",
"command": "./stack.sh",
"args": ["build", "--debug-port", "${input:debug.port}"],
"group": {
"kind": "build",
"isDefault": true
},
"windows": {
"options": {
"shell": {
"executable": "bash"
}
}
}
},
{
"type": "shell",
"label": "compose-deploy-internal",
"command": "./stack.sh",
"args": [
"start",
"${input:stackName}",
"--debug-port",
"${input:debug.port}"
],
"windows": {
"options": {
"shell": {
"executable": "bash"
}
}
}
},
{
"type": "shell",
"label": "compose-deploy",
"command": "sleep 1",
"dependsOn": ["compose-deploy-internal"],
"windows": {
"options": {
"shell": {
"executable": "powershell"
}
}
}
},
{
"type": "shell",
"label": "compose-build-deploy",
"dependsOn": ["compose-build", "compose-deploy"],
"dependsOrder": "sequence"
}
],
"inputs": [
{
"id": "stackName",
"type": "promptString",
"description": "Name your stack.",
"default": "CEW-DT"
},
{
"id": "debug.port",
"type": "command",
"command": "shellCommand.execute",
"args": {
"command": "bash ./stack.sh ports read",
"useFirstResult": true
}
}
]
}
53 changes: 44 additions & 9 deletions Agents/FenlandTrajectoryAgent/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
# 1. Description

The `Fenland Trajectory Agent` is a specialized tool for batch instantiation of structured time-series GPS trajectory data. This agent is capable of receiving HTTP POST requests or CURL commands to load GPS trajectory files, which it subsequently instantiates into triples before uploading them into the knowledge graph.

Presently, the agent focuses on data from the Fenland Study to analyze the interaction between GPS trajectories and environmental features within the context of a digital twin. Example data can be found at Dropbox/CoMo_shared/_Projects/c4e-AI-for-public-health/sample_gps_data.csv. By default, the data instantiated from the Fenland Study using this agent encompasses Speed, Height, Distance, Heading, Latitude, and Longitude. This method is also applicable to other categories of time-series structured data in Fenland Study by replacing or adding the relevant column names. The information instantiated into the knowledge graph adheres to the Ontology of Devices [OntoDevice] in [TheWorldAvatar] project. The instantiation process is executed based on the [TimeSeriesClient]. This agent is implemented as a Docker container, designed for deployment within a stack managed by the [Stack Manager]
The `Fenland Trajectory Agent` is a specialised tool designed to both instantiate structured time-series GPS trajectory data into a knowledge graph and perform quantitative exposure calculations between these trajectories and environmental features. This agent is implemented as a Docker container, designed for deployment within a stack managed by the [Stack Manager]. The agent receives [HTTP POST] requests or Client URL ([CURL]) commands to perform specified tasks. These include loading GPS trajectory files, mapping them into RDF triples, and uploading them to the stack. Additionally, for an exposure radius of interest, the agent can interpret environmental features and perform corresponding exposure calculations automatically. Examples of these calculations include determining the number of food retail locations or greenspace objects within the defined radius.

Presently, the agent focuses on data from the Fenland Study to analyze the interaction between GPS trajectories and environmental features within the context of a digital twin. Example gps data can be found at Dropbox/CoMo_shared/_Projects/c4e-AI-for-public-health/sample_gps_data.csv. By default, the data instantiated from the Fenland Study using this agent encompasses Speed, Height, Distance, Heading, Latitude, and Longitude. This method is also applicable to other categories of time-series structured data in Fenland Study by replacing or adding the relevant column names. The information instantiated into the knowledge graph adheres to the Ontology of Devices [OntoDevice] in [TheWorldAvatar] project. The instantiation process is executed based on the [TimeSeriesClient]. In terms of environmental features from the Fenland Study, the raw data is stored in Dropbox/CoMo_shared/_Projects/c4e-AI-for-public-health/Data/Raw data/. Uploading and instantiating environmental data requires the [Stack-data-uploader] tool, and configuration files can be found in the [AI-for-Public-Health] folder.

# 2. Agent Setup

Expand Down Expand Up @@ -81,9 +80,11 @@ To spin up the stack, create `postgis_password` and `geoserver_password` files i

# 4. Using the Agent

The agent will automatically register a task upon startup to assimilate the data from the target GPS folder into the Knowledge Graph (KG). This background task can be triggered via an HTTP request after the agent has started, accessible at http://localhost:{Port}/fenland-trajectory-agent. Please replace {Port} with the numerical value of the port on which your stack is running.
## 4.1 Data Ingestion

The agent will automatically register a task upon startup to assimilate the data from the target GPS folder into the Knowledge Graph (KG). This background task can be triggered via an HTTP request after the agent has started, accessible at http://localhost:{Port}/fenland-trajectory-agent. Please replace {Port} with the numerical value of the port on which your stack is running.

## Functionality Description
### Functionality Description

The operation of this agent is streamlined into two key steps: **Preprocess** and **Instantiate**. Here is a brief description of each:

Expand All @@ -95,15 +96,41 @@ Importantly, the preprocessing step must be completed before moving on to the in

In addition to the core functionality, this agent offers a route task called layer_generator that creates GeoServer layers from PostGIS tables for visualisation. Given a table name (formed by UUID) and latitude/longitude column names, the agent deploys the [SQL commands for virtual-table generation], creates vector objects, and communicates with the GeoServer REST API to publish the layer. Please note that this functionality is specialized and typically requires manual examination of SQL commands and layer metadata (such as EPSG) to ensure compatibility with specific requirements. This functionality will be further updated and refined after the AI for Public Health (Fenland) project's visualisation is switched to [TWA-VF] 5.4.0.

## Example HTTP Requests
Example HTTP requests for preprocessing and instantiating data are available in detailed HTTP files. You can access these examples at the [preprocess] file, the [instantiate] file, and the [layer_generator] file.
### Example HTTP Requests
Example requests for preprocessing and instantiating data are available in detailed HTTP files. You can access these examples at the [preprocess] file, the [instantiate] file, and the [layer_generator] file.

Additionally, services above can be triggered using CURL from a bash terminal. An example CURL command used to load the GPS trajectory files is displayed in [CURL commands folder].

## 4.2 Count-Based Exposure Calculation

The agent is configured to calculate exposure by listening to trajectory IRIs and environmental feature IRIs along with a specified exposure radius.
The calculation can be triggered via an HTTP request after the agent has started, accessible at http://localhost:{Port}/fenland-trajectory-agent.

### Functionality Description

The workflow begins by generating a buffer zone around the trajectory geometry, with the buffer extending outward from the trajectory line by a specified exposure radius. Environmental features, such as food retail locations or greenspaces, are then identified and counted based on their intersections with this buffer zone, providing a quantitative measure of exposure. To accommodate different data storage scenarios, the agent provides two routes for exposure calculations:

- **Exposure_count**:
This route is used when the environmental data and the Fenland Trajectory Agent are deployed in different stacks. In this case, you need to update the [config.properties] file with the following parameters:

```
ENV_DATA_ENDPOINT_URL (a SPARQL endpoint)
TRAJECTORY_DB_HOST
```
sm453 marked this conversation as resolved.
Show resolved Hide resolved

For example, when using an Ontop SPARQL endpoint as `ENV_DATA_ENDPOINT_URL` with data such as Food Retail and Greenspace, the matching [OBDA mappings] should be configured in advance by [Stack-data-uploader]. Once these settings are complete, the agent will fetch the geometry data for both environmental features and trajectories from the specified endpoint and database, temporarily store the data in a dataframe, and perform the calculations within the agent.

A typical example involves using an Ontop SPARQL endpoint as `ENV_DATA_ENDPOINT_URL`, where this Ontop endpoint can originate from any other stack created by the [Stack Manager]. Food Retail and Greenspace datasets can be used as demonstration cases. When uploading these structured datasets to the stack, the [Stack-data-uploader] should be preconfigured with particular [OBDA mapping] files containing key metadata, such as FeatureType and SourceTableName. These mappings are essential, as the exposure calculation relies on this metadata to trigger the appropriate computation methods.

Additionally, services above can be triggered using Client URL (CURL) from a bash terminal. An example CURL command used to load the GPS trajectory files is displayed in [CURL commands folder].
- **Exposure_count_single_stack**: If the environmental data and the Fenland Trajectory Agent are deployed in the same stack.
This route is used when the environmental data and the Fenland Trajectory Agent are deployed in the same stack. In this case, the agent will query the Ontop SPARQL endpoint deployed within the same stack to fetch the datasource table name corresponding to the trajectory IRI. The agent will then populate an query and execute the calculation internally within the stack.

### Example HTTP Requests
Example requests are available in detailed HTTP files. You can access these examples at the [exposure_count] file and the [exposure_count_single_stack] file. Services can also be triggered using CURL from a bash terminal. Examples are displayed in [CURL commands folder].

 
# Authors
Jiying Chen ([email protected]), May 2024
Jiying Chen ([email protected]), Jan 2025


<!-- Links -->
Expand Down Expand Up @@ -140,6 +167,10 @@ Jiying Chen ([email protected]), May 2024
[ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html
[knowledge graph operations guidance]: https://cambridge-cares.github.io/TheWorldAvatar/examples/sparql/
[TWA-VF]: https://github.com/cambridge-cares/TheWorldAvatar/tree/main/web/twa-vis-framework
[Stack-data-uploader]: https://github.com/cambridge-cares/TheWorldAvatar/tree/main/Deploy/stacks/dynamic/stack-data-uploader
[AI-for-Public-Health]: https://github.com/cambridge-cares/TheWorldAvatar/tree/main/Deploy/stacks/AI4PublicHealth
[HTTP POST]: https://www.w3schools.com/tags/ref_httpmethods.asp
[CURL]: https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-web-client-urls

<!-- files -->
[Dockerfile]: ./Dockerfile
Expand All @@ -157,3 +188,7 @@ Jiying Chen ([email protected]), May 2024
[layer_generator]: ./example-requests/SendHTTP/layer_generator.http
[KGClient]: ./agent/kgutils/kgclient.py
[SQL commands for virtual-table generation]: ./agent/layergenerator/virtual_table.sql
[config.properties]:./agent/flaskapp/exposure/config.properties
[exposure_count]: ./example-requests/SendHTTP/exposure_count.http
[exposure_count_single_stack]: ./example-requests/SendHTTP/exposure_count_single_stack.http
[OBDA mapping]: ./resources/ontop.obda
70 changes: 70 additions & 0 deletions Agents/FenlandTrajectoryAgent/agent/buffer_creator/buffer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import psycopg2
import logging
from typing import Optional, Any

def connect_to_database(
host: str, port: int, user: str, password: str, database: str
) -> psycopg2.extensions.connection:
"""
Establish a connection to the PostgreSQL database.
Raises an exception if the connection fails.
"""
try:
logging.info("Starting database connection...")
connection = psycopg2.connect(
host=host,
port=port,
user=user,
password=password,
database=database,
connect_timeout=10
)
logging.info("Connected to the database.")
return connection
except psycopg2.Error as e:
logging.error(f"Error connecting to the database: {e}")
raise e


def execute_query(connection: psycopg2.extensions.connection, query: str, params: Optional[tuple] = None) -> Any:
"""
Execute a query on the database and fetch results.
Returns the results of the query.
"""
try:
with connection.cursor() as cursor:
logging.info(f"Executing query: {query}")
cursor.execute(query, params)
results = cursor.fetchall()
if results:
logging.info(f"Query returned {len(results)} rows.")
else:
logging.info("Query returned no results.")
return results
except psycopg2.Error as e:
logging.error(f"Error executing query: {e}")
raise e


if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)

# Connection details
host = "localhost"
port = 5432
user = "postgres"
password = "1111"
database = "postgres"

# SQL Query
query = 'SELECT "Council" FROM "fr_cambridge";'
sm453 marked this conversation as resolved.
Show resolved Hide resolved

try:
# Connect to database
with connect_to_database(host, port, user, password, database) as conn:
results = execute_query(conn, query)
if results:
for row in results:
print(row[0])
except Exception as e:
logging.error(f"An error occurred: {e}")
Loading