index.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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(_dataCzFilePath)
  41. //console.log('Datasets loaded succesfully');
  42. _ruralDataEU = await nutsData.loadRuralData(_dataEuFilePath)
  43. _ruralDataCZ = await nutsData.loadRuralData(_dataCzFilePath)
  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)
  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. const resData = returnAllScores(req, res, aoi)
  89. helpers.formatResponse(resData, req, res);
  90. });
  91. /*
  92. Only testing purposes
  93. */
  94. app.get('/:aoi?/runR/', (req, res, next) => {
  95. let aoi = req.params.aoi;
  96. const filename = aoi == 'cz' ? './r/CZ_clusters.r' :'./r/selected_data.r';
  97. console.log('calling R... for ' + aoi);
  98. //console.log(req)
  99. R(filename).data(9).call(
  100. function (err, data) {
  101. console.log('R done');
  102. if (err) {
  103. console.log(err.toString('utf8'));
  104. data = { result: err.toString('utf8') };
  105. }
  106. else {
  107. console.log(data);
  108. data = { result: 'R call succesful' };
  109. }
  110. helpers.formatResponse({ response: data }, req, res);
  111. }
  112. );
  113. });
  114. /*
  115. Just informative response. POST with JSON data is required.
  116. */
  117. app.get('/:aoi?/clusters/', (req, res, next) => {
  118. const data = { response: '/clusters methods are only available under POST' }
  119. helpers.formatResponse(data, req, res)
  120. });
  121. /*
  122. Modifies input CSV file, calls R script, loads the resulting CSV file and returns it
  123. */
  124. app.post('/:aoi?/clusters/', async (req, res, next) => {
  125. const aoi = req.params.aoi || 'eu'
  126. const datasets = await loadDatasetsIfNeeded(req, res, aoi)
  127. const dataFilePath = aoi == 'cz' ? _clusteringCzInputFilePath : _dataEuFilePath
  128. const clusteringModifiedFilePath = aoi == 'cz' ? _clusteringCzModifiedFilePath : _clusteringEuModifiedFilePath
  129. const idString = aoi == 'cz' ? 'LAU2' : 'NUTS_ID'
  130. try {
  131. //console.log(req.body);
  132. const clusteringData = await nutsData.loadClusteringInput(
  133. dataFilePath
  134. );
  135. await nutsData.modifyClusteringData({
  136. datasets: datasets,
  137. data: clusteringData,
  138. params: req.body,
  139. idString: idString,
  140. outputFileName: clusteringModifiedFilePath
  141. });
  142. handleRCall(req, res, aoi)
  143. } catch (error) { // Catch errors in async functions
  144. next(error.toString())
  145. }
  146. });
  147. /*
  148. * Reads the ontology file and sends its content
  149. * This ensures that both backend and frontend are using the same version of the ontology
  150. */
  151. app.get('/ontology/', async (req, res, next) => {
  152. const onto = await nutsData.loadOntology(_ontologyFilePath)
  153. helpers.formatResponse(onto, req, res)
  154. });
  155. app.get('/georeport/:nuts', async (req, res, next) => {
  156. if (!_datasetsEU) { // datasets must be loaded prior to data loading
  157. try {
  158. _datasetsEU = await nutsData.loadDatasets(_datasetsEuFilePath)
  159. } catch (e) {
  160. res.send(e.toString() || e)
  161. }
  162. }
  163. if (!_ruralDataEU) {
  164. try {
  165. _ruralDataEU = await nutsData.loadRuralData(_dataEuFilePath)
  166. } catch (e) {
  167. res.send(e.toString() || e)
  168. }
  169. }
  170. renderPugReport(req.params.nuts, req, res);
  171. });
  172. // start the service on the port xxxx
  173. app.listen(3000, () => console.log('Rural attractivity WS listening on port 3000...'));
  174. function renderPugReport(nuts, req, res) {
  175. let found = false;
  176. _ruralDataEU.forEach(region => {
  177. if (region.nuts == nuts) {
  178. let nutsGeoJson = helpers.loadJSON('static/NUTS3_4326.json');
  179. let filterednutsGeoJson = where(nutsGeoJson.features, { "properties": { "NUTS_ID": nuts } });
  180. let pilots = helpers.loadJSON('static/pilots.json');
  181. region.metadata = {
  182. name: filterednutsGeoJson[0].properties.NUTS_NAME,
  183. code: nuts,
  184. centroid: helpers.getCentroid(filterednutsGeoJson[0].geometry),
  185. pilot: helpers.getPilotRegion(nuts, pilots)
  186. };
  187. res.render('nuts', { region: region, datasets: _datasetsEU });
  188. found = true;
  189. }
  190. });
  191. if (!found)
  192. res.render('err', {});
  193. }
  194. function returnAllScores(req, res, aoi = 'eu') {
  195. let resData = []
  196. const ruralData = aoi == 'cz' ? _ruralDataCZ : _ruralDataEU
  197. const regionIdString = aoi == 'cz' ? 'lau2' : 'nuts'
  198. ruralData.forEach(region => {
  199. //var region = _ruralData[0];
  200. let sumWeight = 0;
  201. let sumValue = 0;
  202. let regionIndexes = { code: region[regionIdString] };
  203. req.body.factors.forEach(factor => {
  204. let factIndex = nutsData.getFactorIndex(region, factor);
  205. //console.log("f: " + JSON.stringify(factor));
  206. //console.log("fi: " + JSON.stringify(factIndex));
  207. regionIndexes[factor.factor] = factIndex.index;
  208. sumValue += factIndex.sumValue * factor.weight;
  209. sumWeight += factIndex.sumWeight;
  210. });
  211. regionIndexes.aggregate = sumValue / sumWeight;
  212. resData.push(regionIndexes);
  213. });
  214. return resData;
  215. }
  216. function returnRegionScores(nuts, req, res) {
  217. var found = false;
  218. res.header("Content-Type", 'application/json');
  219. _ruralDataEU.forEach(region => {
  220. if (region.nuts == nuts) {
  221. helpers.formatResponse(region, req, res);
  222. found = true;
  223. }
  224. });
  225. if (!found)
  226. // NUTS region not found
  227. res.status(404).send('NUTS region not found.');
  228. }
  229. function handleRCall(req, res, aoi = 'eu') {
  230. const numberOfClusters = req.body.numberOfClusters || 12;
  231. //console.log('calling R...', numberOfClusters)
  232. const rScriptInputFileName = aoi == 'cz' ? './r/CZ_clusters.r' :'./r/selected_data.r';
  233. const rScriptResultsFileName = aoi == 'cz' ? _clustersCzFilePath : _clustersEuFilePath;
  234. const idString = aoi == 'cz' ? 'lau2' : 'nuts_id';
  235. R(rScriptInputFileName).data(numberOfClusters).call(
  236. function (err, data) {
  237. //console.log('R done');
  238. if (err) {
  239. console.log(err.toString('utf8'));
  240. data = { result: err.toString('utf8') };
  241. res.status(204).send({ response: data });
  242. }
  243. else {
  244. //console.log(data);
  245. nutsData.loadClusters(rScriptResultsFileName, idString, function (clusterData) {
  246. data = clusterData;
  247. helpers.formatResponse({ response: data }, req, res);
  248. });
  249. }
  250. }
  251. );
  252. }
  253. async function loadDatasetsIfNeeded(req, res, aoi) {
  254. let datasets = aoi == 'cz' ? _datasetsCZ : _datasetsEU
  255. if (!datasets) {
  256. try {
  257. if (aoi == 'cz') {
  258. _datasetsCZ = await nutsData.loadDatasets(_dataCzFilePath)
  259. datasets = _datasetsCZ
  260. } else {
  261. _datasetsEU = await nutsData.loadDatasets(_datasetsEuFilePath)
  262. datasets = _datasetsEU
  263. }
  264. } catch (e) {
  265. res.send(e.toString() || e)
  266. }
  267. }
  268. console.log(datasets)
  269. return datasets
  270. }
  271. async function loadRuralDataIfNeeded(req, res, aoi) {
  272. let ruralData = aoi == 'cz' ? _ruralDataCZ : _ruralDataEU
  273. if (!ruralData) {
  274. try {
  275. if (aoi == 'cz') {
  276. _ruralDataCZ = await nutsData.loadRuralData(_dataCzFilePath)
  277. ruralData = _ruralDataCZ
  278. } else {
  279. _ruralDataEU = await nutsData.loadRuralData(_dataEuFilePath)
  280. ruralData = _ruralDataEU
  281. }
  282. } catch (e) {
  283. res.send(e.toString() || e)
  284. }
  285. }
  286. return ruralData
  287. }