index.js 11 KB

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