holosphere 1.1.7 → 1.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,147 +0,0 @@
1
- import HoloSphere from '../holosphere.js';
2
- import * as h3 from 'h3-js';
3
-
4
- /**
5
- * Example demonstrating how to query environmental data from HoloSphere
6
- * This shows how to access data across federated holons at different scales
7
- */
8
- async function queryEnvironmentalData() {
9
- // Initialize HoloSphere with the same appname used to store the data
10
- const holosphere = new HoloSphere('environmental-data');
11
-
12
- try {
13
- // Example coordinates (Rome, Italy)
14
- const lat = 41.9;
15
- const lon = 12.5;
16
-
17
- // Get the holons at different resolutions
18
- const cityHolon = await holosphere.getHolon(lat, lon, 7); // City level
19
- const regionHolon = await holosphere.getHolon(lat, lon, 5); // Region level
20
- const countryHolon = await holosphere.getHolon(lat, lon, 3); // Country level
21
-
22
- console.log(`Querying environmental data for location (${lat}, ${lon})`);
23
- console.log(` - City: ${cityHolon}`);
24
- console.log(` - Region: ${regionHolon}`);
25
- console.log(` - Country: ${countryHolon}`);
26
-
27
- // Query 1: Get air quality data from the city level
28
- console.log('\n=== CITY LEVEL: Air Quality Data ===');
29
- const airQualityData = await holosphere.getAll(cityHolon, 'air-quality');
30
- if (airQualityData.length > 0) {
31
- const latest = airQualityData.sort((a, b) => b.timestamp - a.timestamp)[0];
32
- console.log(`Latest Air Quality Index: ${latest.airQualityIndex}`);
33
- console.log('Pollutant levels:');
34
- Object.entries(latest.pollutants).forEach(([pollutant, value]) => {
35
- console.log(` - ${pollutant}: ${value}`);
36
- });
37
- } else {
38
- console.log('No air quality data available for this location');
39
- }
40
-
41
- // Query 2: Use federation to get soil data referenced at the region level
42
- console.log('\n=== REGION LEVEL: Soil Carbon Data ===');
43
- const soilData = await holosphere.getAll(regionHolon, 'soil-data');
44
- if (soilData.length > 0) {
45
- const latest = soilData.sort((a, b) => b.timestamp - a.timestamp)[0];
46
- console.log(`Soil Carbon: ${latest.soilCarbon} g/kg`);
47
- console.log(`Soil Type: ${latest.soilType}`);
48
- console.log(`Soil Depth: ${latest.soilDepth}`);
49
- } else {
50
- console.log('No soil data available for this region');
51
- }
52
-
53
- // Query 3: Get carbon sequestration data at region level
54
- console.log('\n=== REGION LEVEL: Carbon Sequestration ===');
55
- const carbonData = await holosphere.getAll(regionHolon, 'carbon-sequestration');
56
- if (carbonData.length > 0) {
57
- const latest = carbonData.sort((a, b) => b.timestamp - a.timestamp)[0];
58
- console.log(`Carbon Sequestration: ${latest.carbonSequestration} tons/hectare/year`);
59
- console.log(`Temperature: ${latest.temperature}°C`);
60
- console.log(`Precipitation: ${latest.precipitation} mm`);
61
- } else {
62
- console.log('No carbon sequestration data available for this region');
63
- }
64
-
65
- // Query 4: Get biodiversity data at country level
66
- console.log('\n=== COUNTRY LEVEL: Biodiversity ===');
67
- const biodiversityData = await holosphere.getAll(countryHolon, 'biodiversity');
68
- if (biodiversityData.length > 0) {
69
- const latest = biodiversityData.sort((a, b) => b.timestamp - a.timestamp)[0];
70
- console.log(`Biodiversity Count: ${latest.biodiversityCount} species`);
71
- console.log(`Country Code: ${latest.countryCode}`);
72
- console.log(`Top 5 Species:`);
73
-
74
- // Sort species by count and show top 5
75
- const topSpecies = latest.species.sort((a, b) => b.count - a.count).slice(0, 5);
76
- topSpecies.forEach((species, index) => {
77
- console.log(` ${index + 1}. ${species.scientificName}: ${species.count} occurrences`);
78
- });
79
- } else {
80
- console.log('No biodiversity data available for this country');
81
- }
82
-
83
- // Query 5: Get federated data across all levels
84
- console.log('\n=== FEDERATED DATA: Environmental Metrics ===');
85
- const federatedData = await holosphere.getFederated(countryHolon, 'environmental-metrics', {
86
- resolveReferences: true,
87
- aggregate: true,
88
- idField: 'id'
89
- });
90
-
91
- if (federatedData.length > 0) {
92
- console.log('Aggregated Environmental Metrics:');
93
- federatedData.forEach(data => {
94
- if (data.metrics) {
95
- Object.entries(data.metrics).forEach(([metric, value]) => {
96
- console.log(` - ${metric}: ${value}`);
97
- });
98
- } else {
99
- console.log('No metrics available in federated data');
100
- }
101
- });
102
- } else {
103
- console.log('No federated environmental metrics available');
104
- }
105
-
106
- // Query 6: Get references to air quality data from the region level
107
- // This demonstrates accessing data via federation references
108
- console.log('\n=== FEDERATION REFERENCES: Air Quality Data from Region ===');
109
- const airQualityRefs = await holosphere.getAll(regionHolon, 'air-quality');
110
- if (airQualityRefs.length > 0) {
111
- console.log(`Found ${airQualityRefs.length} air quality references in region`);
112
-
113
- // Get the first reference and resolve it
114
- const ref = airQualityRefs[0];
115
- console.log('Reference details:');
116
-
117
- if (ref.soul) {
118
- console.log(` - Soul path: ${ref.soul}`);
119
-
120
- // Resolve reference manually to show the process
121
- const resolvedData = await holosphere.getNodeBySoul(ref.soul);
122
- if (resolvedData) {
123
- console.log('Successfully resolved reference to original air quality data:');
124
- console.log(` - Air Quality Index: ${resolvedData.airQualityIndex}`);
125
- console.log(` - Source Holon: ${resolvedData.holon}`);
126
- } else {
127
- console.log('Could not resolve reference - original data not found');
128
- }
129
- } else {
130
- console.log('Not a soul reference:', ref);
131
- }
132
- } else {
133
- console.log('No air quality references found at region level');
134
- }
135
-
136
- } catch (error) {
137
- console.error('Error querying environmental data:', error);
138
- } finally {
139
- // Always close the HoloSphere instance
140
- await holosphere.close();
141
- }
142
- }
143
-
144
- // Execute the example
145
- queryEnvironmentalData()
146
- .then(() => console.log('\nEnvironmental data query example completed'))
147
- .catch(error => console.error('Error in environmental data query example:', error));
@@ -1,415 +0,0 @@
1
- import axios from 'axios';
2
- import dotenv from 'dotenv';
3
-
4
- dotenv.config();
5
-
6
- const logError = (service, error) => {
7
- const status = error.response?.status;
8
- const message = error.response?.data?.message || error.message;
9
- console.error(`${service} API Error:`, { status, message });
10
- };
11
-
12
- // Mock data responses (for testing without API keys)
13
- const mockData = {
14
- airQuality: {
15
- coord: { lat: 41.9, lon: 12.5 },
16
- list: [
17
- {
18
- main: { aqi: 2 },
19
- components: {
20
- co: 201.94,
21
- no2: 0.78,
22
- o3: 68.64,
23
- pm2_5: 0.5,
24
- pm10: 0.82,
25
- so2: 0.52
26
- }
27
- }
28
- ]
29
- },
30
- carbonSequestration: {
31
- properties: {
32
- parameter: {
33
- T2M: { '20230701': 28.5 },
34
- PRECTOT: { '20230701': 1.2 },
35
- PS: { '20230701': 1013.25 },
36
- WS2M: { '20230701': 3.5 }
37
- }
38
- },
39
- geometry: {
40
- coordinates: [12.5, 41.9]
41
- }
42
- },
43
- soilCarbon: {
44
- properties: {
45
- soilGrids: {
46
- properties: {
47
- soc: { mean: 78.4 }
48
- }
49
- },
50
- soilType: 'Clay Loam'
51
- },
52
- geometry: {
53
- coordinates: [12.5, 41.9]
54
- }
55
- },
56
- biodiversity: {
57
- results: [
58
- { scientificName: 'Quercus ilex', countryCode: 'ITA' },
59
- { scientificName: 'Pinus pinea', countryCode: 'ITA' },
60
- { scientificName: 'Olea europaea', countryCode: 'ITA' },
61
- { scientificName: 'Quercus ilex', countryCode: 'ITA' },
62
- { scientificName: 'Pinus pinea', countryCode: 'ITA' },
63
- { scientificName: 'Laurus nobilis', countryCode: 'ITA' },
64
- { scientificName: 'Quercus ilex', countryCode: 'ITA' },
65
- { scientificName: 'Platanus orientalis', countryCode: 'ITA' },
66
- { scientificName: 'Cupressus sempervirens', countryCode: 'ITA' },
67
- { scientificName: 'Cupressus sempervirens', countryCode: 'ITA' }
68
- ]
69
- }
70
- };
71
-
72
- // Flag to use mock data instead of making real API calls
73
- const USE_MOCK_DATA = true;
74
-
75
- /**
76
- * Fetch Carbon Sequestration Data (Using NASA POWER API)
77
- */
78
- export async function getCarbonSequestration(lat = 41.9, lon = 12.5) {
79
- // Return mock data if flag is set
80
- if (USE_MOCK_DATA) {
81
- console.log('Using mock carbon sequestration data');
82
- return mockData.carbonSequestration;
83
- }
84
-
85
- try {
86
- const response = await axios.default.get(
87
- `https://power.larc.nasa.gov/api/temporal/daily/point?parameters=T2M,PRECTOT,PS,WS2M&community=RE&longitude=${lon}&latitude=${lat}&start=20230101&end=20231231&format=JSON`
88
- );
89
- return response.data;
90
- } catch (error) {
91
- logError('Carbon Sequestration', error);
92
- return null;
93
- }
94
- }
95
-
96
- /**
97
- * Fetch Soil Carbon Data (Using ISRIC World Soil Information)
98
- */
99
- export async function getSoilCarbon(lat = 41.9, lon = 12.5) {
100
- // Return mock data if flag is set
101
- if (USE_MOCK_DATA) {
102
- console.log('Using mock soil carbon data');
103
- return mockData.soilCarbon;
104
- }
105
-
106
- try {
107
- const response = await axios.default.get(
108
- `https://rest.isric.org/soilgrids/v2.0/properties/query?lat=${lat}&lon=${lon}&property=soc&depth=0-30cm&value=mean`
109
- );
110
- return response.data;
111
- } catch (error) {
112
- logError('Soil Carbon', error);
113
- return null;
114
- }
115
- }
116
-
117
- /**
118
- * Fetch Biodiversity Data (GBIF API)
119
- */
120
- export async function getBiodiversityData(countryCode = "ITA") {
121
- // Return mock data if flag is set
122
- if (USE_MOCK_DATA) {
123
- console.log('Using mock biodiversity data');
124
- return mockData.biodiversity;
125
- }
126
-
127
- try {
128
- const response = await axios.default.get(`https://api.gbif.org/v1/occurrence/search?country=${countryCode}&limit=100`);
129
- return response.data;
130
- } catch (error) {
131
- logError('Biodiversity', error);
132
- return null;
133
- }
134
- }
135
-
136
- /**
137
- * Fetch Vegetation Cover Data (Using NASA MODIS Vegetation Index)
138
- */
139
- export async function getVegetationCover(lat = 41.9, lon = 12.5) {
140
- // Return mock data if flag is set
141
- if (USE_MOCK_DATA) {
142
- console.log('Using mock vegetation cover data');
143
- return { ndvi: 0.75 };
144
- }
145
-
146
- try {
147
- const response = await axios.default.get(
148
- `https://modis.ornl.gov/rst/api/v1/MOD13Q1/subset?latitude=${lat}&longitude=${lon}&band=NDVI&startDate=2023-01-01&endDate=2023-12-31`,
149
- {
150
- headers: {
151
- 'Accept': 'application/json'
152
- }
153
- }
154
- );
155
- return response.data;
156
- } catch (error) {
157
- logError('Vegetation Cover', error);
158
- return null;
159
- }
160
- }
161
-
162
- /**
163
- * Fetch Air Quality Data (OpenWeather API)
164
- */
165
- export async function getAirQuality(lat = 41.9, lon = 12.5) {
166
- // Return mock data if flag is set
167
- if (USE_MOCK_DATA) {
168
- console.log('Using mock air quality data');
169
- return mockData.airQuality;
170
- }
171
-
172
- try {
173
- const response = await axios.default.get(
174
- `https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${process.env.OPENWEATHER_API_KEY}`
175
- );
176
- return response.data;
177
- } catch (error) {
178
- logError('Air Quality', error);
179
- return null;
180
- }
181
- }
182
-
183
- /**
184
- * Fetch Water Retention Data (Using USGS Water Services)
185
- */
186
- export async function getWaterRetention(lat = 41.9, lon = 12.5) {
187
- // Return mock data if flag is set
188
- if (USE_MOCK_DATA) {
189
- console.log('Using mock water retention data');
190
- return { waterRetention: 85.2 };
191
- }
192
-
193
- try {
194
- const response = await axios.default.get(
195
- `https://waterservices.usgs.gov/nwis/iv/?format=json&sites=11447650&siteStatus=active`,
196
- {
197
- headers: {
198
- 'Accept': 'application/json'
199
- }
200
- }
201
- );
202
- return response.data;
203
- } catch (error) {
204
- logError('Water Retention', error);
205
- return null;
206
- }
207
- }
208
-
209
- /**
210
- * Fetch Deforestation Data (Using World Bank Forest Data)
211
- */
212
- export async function getDeforestationData(countryCode = "ITA") {
213
- // Return mock data if flag is set
214
- if (USE_MOCK_DATA) {
215
- console.log('Using mock deforestation data');
216
- return { forestAreaPercentage: 31.6, year: 2020 };
217
- }
218
-
219
- try {
220
- const response = await axios.default.get(
221
- `https://api.worldbank.org/v2/country/${countryCode}/indicator/AG.LND.FRST.ZS?format=json`
222
- );
223
- return response.data;
224
- } catch (error) {
225
- logError('Deforestation', error);
226
- return null;
227
- }
228
- }
229
-
230
- /**
231
- * Fetch Flood Risk Data (Using USGS Water Services)
232
- */
233
- export async function getFloodRisk(lat = 41.9, lon = 12.5) {
234
- // Return mock data if flag is set
235
- if (USE_MOCK_DATA) {
236
- console.log('Using mock flood risk data');
237
- return { floodRiskLevel: 'low', probability: 0.15 };
238
- }
239
-
240
- try {
241
- const response = await axios.default.get(
242
- `https://waterservices.usgs.gov/nwis/iv/?format=json&stateCd=CA&parameterCd=00065&siteStatus=active`,
243
- {
244
- headers: {
245
- 'Accept': 'application/json'
246
- }
247
- }
248
- );
249
- return response.data;
250
- } catch (error) {
251
- logError('Flood Risk', error);
252
- return null;
253
- }
254
- }
255
-
256
- /**
257
- * Fetch Food Security Data (World Bank API)
258
- */
259
- export async function getFoodSecurity(countryCode = "ITA") {
260
- // Return mock data if flag is set
261
- if (USE_MOCK_DATA) {
262
- console.log('Using mock food security data');
263
- return { prevalenceOfUndernourishment: 2.5, year: 2020 };
264
- }
265
-
266
- try {
267
- const response = await axios.default.get(
268
- `https://api.worldbank.org/v2/country/${countryCode}/indicator/SN.ITK.DEFC.ZS?format=json`
269
- );
270
- return response.data;
271
- } catch (error) {
272
- logError('Food Security', error);
273
- return null;
274
- }
275
- }
276
-
277
- /**
278
- * Fetch Local Employment Rate (World Bank API)
279
- */
280
- export async function getEmploymentRate(countryCode = "ITA") {
281
- // Return mock data if flag is set
282
- if (USE_MOCK_DATA) {
283
- console.log('Using mock employment rate data');
284
- return { employmentRate: 58.2, year: 2020 };
285
- }
286
-
287
- try {
288
- const response = await axios.default.get(
289
- `https://api.worldbank.org/v2/country/${countryCode}/indicator/SL.EMP.TOTL.SP.ZS?format=json`
290
- );
291
- return response.data;
292
- } catch (error) {
293
- logError('Employment Rate', error);
294
- return null;
295
- }
296
- }
297
-
298
- /**
299
- * Fetch Governance Score (World Bank API)
300
- */
301
- export async function getTransparencyScore(countryCode = "ITA") {
302
- // Return mock data if flag is set
303
- if (USE_MOCK_DATA) {
304
- console.log('Using mock transparency score data');
305
- return { governanceEffectivenessScore: 0.45, year: 2020 };
306
- }
307
-
308
- try {
309
- const response = await axios.default.get(
310
- `https://api.worldbank.org/v2/country/${countryCode}/indicator/GE.EST?format=json`
311
- );
312
- return response.data;
313
- } catch (error) {
314
- logError('Transparency Score', error);
315
- return null;
316
- }
317
- }
318
-
319
- /**
320
- * Fetch Blockchain Transactions (Etherscan API)
321
- */
322
- export async function getBlockchainTransactions(address = "0x0000000000000000000000000000000000000000") {
323
- // Return mock data if flag is set
324
- if (USE_MOCK_DATA) {
325
- console.log('Using mock blockchain transactions data');
326
- return {
327
- result: [
328
- { hash: '0x123...', value: '0.5', timeStamp: '1620000000' },
329
- { hash: '0x456...', value: '1.2', timeStamp: '1620100000' }
330
- ]
331
- };
332
- }
333
-
334
- try {
335
- const response = await axios.default.get(
336
- `https://api.etherscan.io/api?module=account&action=txlist&address=${address}&startblock=0&endblock=99999999&sort=desc&apikey=${process.env.ETHERSCAN_API_KEY}`
337
- );
338
- return response.data;
339
- } catch (error) {
340
- logError('Blockchain Transactions', error);
341
- return null;
342
- }
343
- }
344
-
345
- /**
346
- * Fetch Circular Economy Data (Using World Bank Development Indicators)
347
- */
348
- export async function getCircularEconomyData(countryCode = "ITA") {
349
- // Return mock data if flag is set
350
- if (USE_MOCK_DATA) {
351
- console.log('Using mock circular economy data');
352
- return { recyclingRate: 51.3, wasteGeneration: 499.0, year: 2020 };
353
- }
354
-
355
- try {
356
- const response = await axios.default.get(
357
- `https://api.worldbank.org/v2/country/${countryCode}/indicator/EN.ATM.GHGT.KT.CE?format=json`
358
- );
359
- return response.data;
360
- } catch (error) {
361
- logError('Circular Economy', error);
362
- return null;
363
- }
364
- }
365
-
366
- /**
367
- * Fetch Renewable Energy Data (World Bank API)
368
- */
369
- export async function getRenewableEnergyData(countryCode = "ITA") {
370
- // Return mock data if flag is set
371
- if (USE_MOCK_DATA) {
372
- console.log('Using mock renewable energy data');
373
- return { renewableEnergyPercentage: 18.2, year: 2020 };
374
- }
375
-
376
- try {
377
- const response = await axios.default.get(
378
- `https://api.worldbank.org/v2/country/${countryCode}/indicator/EG.FEC.RNEW.ZS?format=json`
379
- );
380
- return response.data;
381
- } catch (error) {
382
- logError('Renewable Energy', error);
383
- return null;
384
- }
385
- }
386
-
387
- /**
388
- * Fetch Climate Change Data (NOAA Climate API)
389
- */
390
- export async function getClimateChangeData(lat = 41.9, lon = 12.5) {
391
- // Return mock data if flag is set
392
- if (USE_MOCK_DATA) {
393
- console.log('Using mock climate change data');
394
- return {
395
- temperatureTrend: '+1.2C over 50 years',
396
- extremeWeatherEvents: 5,
397
- year: 2020
398
- };
399
- }
400
-
401
- try {
402
- const response = await axios.default.get(
403
- `https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&latitude=${lat}&longitude=${lon}&startdate=2023-01-01&enddate=2023-12-31&limit=1000`,
404
- {
405
- headers: {
406
- 'token': process.env.NOAA_API_KEY
407
- }
408
- }
409
- );
410
- return response.data;
411
- } catch (error) {
412
- logError('Climate Change', error);
413
- return null;
414
- }
415
- }