index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. const express = require('express');
  2. const helpers = require('./helpers.js');
  3. const nutsData = require('./nuts-data.js');
  4. const cors = require('cors');
  5. const R = require('r-script');
  6. var where = require('lodash.where');
  7. const app = express();
  8. const _datasetsEuFilePath = 'data/datasets.csv';
  9. const _datasetsCzFilePath = 'data/datasets-cz.csv';
  10. const _dataEuFilePath = 'data/data.csv';
  11. const _dataCzFilePath = 'data/cz/data-input-CZ_LAU2_37_cols.csv';
  12. //const _clusteringEuInputFilePath = 'data/clustering/input_all.csv';
  13. const _clusteringCzInputFilePath = 'data/cz/clusters-input-CZ_LAU2_37_cols.csv';
  14. const _clusteringEuModifiedFilePath = 'data/clustering/input_modified.csv';
  15. const _clusteringCzModifiedFilePath = 'data/cz/input_modified.csv';
  16. const _clustersEuFilePath = 'data/clustering/out_file.csv';
  17. const _clustersCzFilePath = 'data/cz/out_file_cz.csv';
  18. const _ontologyFilePath = 'data/rural_attractiveness.owl.json';
  19. var _datasetsEU = undefined;
  20. var _datasetsCZ = undefined;
  21. var _ruralDataEU = undefined;
  22. var _ruralDataCZ = undefined;
  23. // parse incoming POST requests body to JSON
  24. app.use(express.json());
  25. // handle CORS
  26. app.use(cors())
  27. // serve static files from the /static directory
  28. app.use(express.static('static'))
  29. // set PUG as default rendering engine
  30. app.set('view engine', 'pug')
  31. /* Dummy web service call without the method specified */
  32. app.get('/', (req, res) => {
  33. helpers.describeSelf(req, res)
  34. });
  35. /* Makes refresh of the data loaded to the server objects.
  36. Must be called after the CSV data has changed */
  37. app.get('/refresh', async (req, res, next) => {
  38. try {
  39. _datasetsEU = await nutsData.loadDatasets(_datasetsEuFilePath)
  40. _datasetsCZ = await nutsData.loadDatasets(_datasetsCzFilePath)
  41. //console.log('Datasets loaded succesfully');
  42. _ruralDataEU = await nutsData.loadRuralData(_dataEuFilePath, _datasetsEU)
  43. _ruralDataCZ = await nutsData.loadRuralData(_datasetsCzFilePath, _datasetsCZ)
  44. //console.log('Rural data loaded succesfully');
  45. } catch (e) {
  46. res.send(e.toString() || e)
  47. }
  48. res.send('Data refreshed')
  49. });
  50. /* Returns JSON array with the list of all the datasets */
  51. app.get('/:aoi?/datasets/', async (req, res, next) => {
  52. const aoi = req.params.aoi || 'eu'
  53. const datasets = await loadDatasetsIfNeeded(req, res, aoi)
  54. helpers.formatResponse(datasets, req, res)
  55. });
  56. /* Returns attractivity data for the region with ID equal to the 'nuts' parameter */
  57. app.get('/:aoi?/scores/:nuts', async (req, res, next) => {
  58. if (!_datasetsEU) { // datasets must be loaded prior to data loading
  59. try {
  60. _datasetsEU = await nutsData.loadDatasets(_datasetsEuFilePath)
  61. } catch (e) {
  62. res.send(e.toString() || e)
  63. }
  64. }
  65. if (!_ruralDataEU) {
  66. try {
  67. _ruralDataEU = await nutsData.loadRuralData(_dataEuFilePath, _datasetsEU)
  68. } catch (e) {
  69. res.send(e.toString() || e)
  70. }
  71. }
  72. returnRegionScores(req.params.nuts, req, res)
  73. });
  74. /* Returns attractivity data for all the regions in source CSV data. */
  75. app.get('/:aoi?/scores', async (req, res, next) => {
  76. const aoi = req.params.aoi || 'eu'
  77. await loadDatasetsIfNeeded(req, res, aoi)
  78. const ruralData = await loadRuralDataIfNeeded(req, res, aoi)
  79. helpers.formatResponse(ruralData, req, res)
  80. });
  81. /* Computes and returns attractivity data for all the NUTS regions based on the
  82. incomming datasets and factor weights. */
  83. app.post('/:aoi?/scores', async (req, res, next) => {
  84. //console.log("query: " + JSON.stringify(req.body.factors, null, 4));
  85. const aoi = req.params.aoi || 'eu'
  86. await loadDatasetsIfNeeded(req, res, aoi)
  87. await loadRuralDataIfNeeded(req, res, aoi)
  88. returnAllScores(req, res, aoi)
  89. });
  90. /*
  91. Only testing purposes
  92. */
  93. app.get('/:aoi?/runR/', (req, res, next) => {
  94. let aoi = req.params.aoi;
  95. const filename = aoi == 'cz' ? './r/CZ_clusters.r' :'./r/selected_data.r';
  96. console.log('calling R... for ' + aoi);
  97. //console.log(req)
  98. R(filename).data(9).call(
  99. function (err, data) {
  100. console.log('R done');
  101. if (err) {
  102. console.log(err.toString('utf8'));
  103. data = { result: err.toString('utf8') };
  104. }
  105. else {
  106. console.log(data);
  107. data = { result: 'R call succesful' };
  108. }
  109. helpers.formatResponse({ response: data }, req, res);
  110. }
  111. );
  112. });
  113. /*
  114. Just informative response. POST with JSON data is required.
  115. */
  116. app.get('/:aoi?/clusters/', (req, res, next) => {
  117. const data = { response: '/clusters methods are only available under POST' }
  118. helpers.formatResponse(data, req, res)
  119. });
  120. /*
  121. Modifies input CSV file, calls R script, loads the resulting CSV file and returns it
  122. */
  123. app.post('/:aoi?/clusters/', async (req, res, next) => {
  124. const aoi = req.params.aoi || 'eu'
  125. const datasets = await loadDatasetsIfNeeded(req, res, aoi)
  126. const dataFilePath = aoi == 'cz' ? _clusteringCzInputFilePath : _dataEuFilePath
  127. const clusteringModifiedFilePath = aoi == 'cz' ? _clusteringCzModifiedFilePath : _clusteringEuModifiedFilePath
  128. const idString = aoi == 'cz' ? 'LAU2' : 'NUTS_ID'
  129. try {
  130. //console.log(req.body);
  131. const clusteringData = await nutsData.loadClusteringInput(
  132. dataFilePath
  133. );
  134. await nutsData.modifyClusteringData({
  135. datasets: datasets,
  136. data: clusteringData,
  137. params: req.body,
  138. idString: idString,
  139. outputFileName: clusteringModifiedFilePath
  140. });
  141. handleRCall(req, res, aoi)
  142. } catch (error) { // Catch errors in async functions
  143. next(error.toString())
  144. }
  145. });
  146. /*
  147. * Reads the ontology file and sends its content
  148. * This ensures that both backend and frontend are using the same version of the ontology
  149. */
  150. app.get('/ontology/', async (req, res, next) => {
  151. const onto = await nutsData.loadOntology(_ontologyFilePath)
  152. helpers.formatResponse(onto, req, res)
  153. });
  154. app.get('/georeport/:nuts', async (req, res, next) => {
  155. if (!_datasetsEU) { // datasets must be loaded prior to data loading
  156. try {
  157. _datasetsEU = await nutsData.loadDatasets(_datasetsEuFilePath)
  158. } catch (e) {
  159. res.send(e.toString() || e)
  160. }
  161. }
  162. if (!_ruralDataEU) {
  163. try {
  164. _ruralDataEU = await nutsData.loadRuralData(_dataEuFilePath, _datasetsEU)
  165. } catch (e) {
  166. res.send(e.toString() || e)
  167. }
  168. }
  169. renderPugReport(req.params.nuts, req, res);
  170. });
  171. // start the service on the port xxxx
  172. app.listen(3000, () => console.log('Rural attractivity WS listening on port 3000...'));
  173. function renderPugReport(nuts, req, res) {
  174. let found = false;
  175. _ruralDataEU.forEach(region => {
  176. if (region.nuts == nuts) {
  177. let nutsGeoJson = helpers.loadJSON('static/NUTS3_4326.json');
  178. let filterednutsGeoJson = where(nutsGeoJson.features, { "properties": { "NUTS_ID": nuts } });
  179. let pilots = helpers.loadJSON('static/pilots.json');
  180. region.metadata = {
  181. name: filterednutsGeoJson[0].properties.NUTS_NAME,
  182. code: nuts,
  183. centroid: helpers.getCentroid(filterednutsGeoJson[0].geometry),
  184. pilot: helpers.getPilotRegion(nuts, pilots)
  185. };
  186. res.render('nuts', { region: region, datasets: _datasetsEU });
  187. found = true;
  188. }
  189. });
  190. if (!found)
  191. res.render('err', {});
  192. }
  193. function returnAllScores(req, res, aoi = 'eu') {
  194. let resData = []
  195. const ruralData = aoi == 'cz' ? _ruralDataCZ : _ruralDataEU
  196. const regionIdString = aoi == 'cz' ? 'lau2' : 'nuts'
  197. ruralData.forEach(region => {
  198. //var region = _ruralData[0];
  199. let sumWeight = 0;
  200. let sumValue = 0;
  201. let regionIndexes = { code: region[regionIdString] };
  202. req.body.factors.forEach(f => {
  203. let fi = nutsData.getFactorIndex(region, f);
  204. //console.log("f: " + JSON.stringify(f));
  205. //console.log("fi: " + JSON.stringify(fi));
  206. regionIndexes[f.factor] = fi.index;
  207. sumValue += fi.sumValue * f.weight;
  208. sumWeight += fi.sumWeight;
  209. });
  210. regionIndexes.aggregate = sumValue / sumWeight;
  211. resData.push(regionIndexes);
  212. });
  213. helpers.formatResponse(resData, req, res);
  214. }
  215. function returnRegionScores(nuts, req, res) {
  216. var found = false;
  217. res.header("Content-Type", 'application/json');
  218. _ruralDataEU.forEach(region => {
  219. if (region.nuts == nuts) {
  220. helpers.formatResponse(region, req, res);
  221. found = true;
  222. }
  223. });
  224. if (!found)
  225. // NUTS region not found
  226. res.status(404).send('NUTS region not found.');
  227. }
  228. function handleRCall(req, res, aoi = 'eu') {
  229. const numberOfClusters = req.body.numberOfClusters || 12;
  230. //console.log('calling R...', numberOfClusters)
  231. const rScriptInputFileName = aoi == 'cz' ? './r/CZ_clusters.r' :'./r/selected_data.r';
  232. const rScriptResultsFileName = aoi == 'cz' ? _clustersCzFilePath : _clustersEuFilePath;
  233. const idString = aoi == 'cz' ? 'lau2' : 'nuts_id';
  234. R(rScriptInputFileName).data(numberOfClusters).call(
  235. function (err, data) {
  236. //console.log('R done');
  237. if (err) {
  238. console.log(err.toString('utf8'));
  239. data = { result: err.toString('utf8') };
  240. res.status(204).send({ response: data });
  241. }
  242. else {
  243. //console.log(data);
  244. nutsData.loadClusters(rScriptResultsFileName, idString, function (clusterData) {
  245. data = clusterData;
  246. helpers.formatResponse({ response: data }, req, res);
  247. });
  248. }
  249. }
  250. );
  251. }
  252. async function loadDatasetsIfNeeded(req, res, aoi) {
  253. let datasets = aoi == 'cz' ? _datasetsCZ : _datasetsEU
  254. if (!datasets) {
  255. try {
  256. if (aoi == 'cz') {
  257. _datasetsCZ = await nutsData.loadDatasets(_datasetsCzFilePath)
  258. datasets = _datasetsCZ
  259. } else {
  260. _datasetsEU = await nutsData.loadDatasets(_datasetsEuFilePath)
  261. datasets = _datasetsEU
  262. }
  263. } catch (e) {
  264. res.send(e.toString() || e)
  265. }
  266. }
  267. return datasets
  268. }
  269. async function loadRuralDataIfNeeded(req, res, aoi) {
  270. let ruralData = aoi == 'cz' ? _ruralDataCZ : _ruralDataEU
  271. const datasets = aoi == 'cz' ? _datasetsCZ : _datasetsEU
  272. if (!ruralData) {
  273. try {
  274. if (aoi == 'cz') {
  275. _ruralDataCZ = await nutsData.loadRuralData(_dataCzFilePath, datasets)
  276. ruralData = _ruralDataCZ
  277. } else {
  278. _ruralDataEU = await nutsData.loadRuralData(_dataEuFilePath, datasets)
  279. ruralData = _ruralDataEU
  280. }
  281. } catch (e) {
  282. res.send(e.toString() || e)
  283. }
  284. }
  285. return ruralData
  286. }