nuts-data.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. const fs = require('fs');
  2. const csv = require('csv-parse');
  3. const stringify = require('csv-stringify');
  4. /* Helper method to load the datasets from CSV and store it in server object */
  5. module.exports.loadDatasets = async function(filePath) {
  6. //console.log('Datasets structure loading.')
  7. let datasets = undefined
  8. return new Promise((resolve, reject) => {
  9. const stream = fs.createReadStream(filePath).pipe(csv({to_line: 1}))
  10. stream
  11. .on('data', (row) => {
  12. if (!datasets) {
  13. datasets = row
  14. }
  15. })
  16. .on('end', () => {
  17. datasets = datasets.slice(2) //TODO: FIXME: unify this number (only one ID column in the beginning)
  18. console.log('Datasets structure loaded.')
  19. resolve(datasets)
  20. })
  21. .on('error', reject)
  22. })
  23. }
  24. /* Load all the attractiveness data from CSV into a server object.
  25. The data don't need to be loaded for each request then. */
  26. module.exports.loadRuralData = async function (filePath) {
  27. //console.log('Reading rural data file processing started.')
  28. let ruralData = []
  29. let columns
  30. return new Promise((resolve, reject) => {
  31. fs.createReadStream(filePath)
  32. .pipe(csv())
  33. .on('data', (row) => {
  34. if (!columns) {
  35. columns = row
  36. return
  37. }
  38. let item = {
  39. values: {}
  40. }
  41. for (let i = 0; i < columns.length; i++) {
  42. let colName = columns[i].toLowerCase()
  43. if (colName == "nuts_id") // ID of the NUTS region (EU)
  44. item.nuts = row[i]
  45. // else if (colName == "datasets") // empty datasets count
  46. // item.availableDS = datasets.length - row[i];
  47. // else if (colName == "quality")
  48. // item.quality = row[i];
  49. else if (colName == "lau2") // ID of the municipality (CZ)
  50. item.lau2 = row[i]
  51. else if (colName == "district_code") // ID of the district (Kenya+Uganda)
  52. item.district = row[i]
  53. else if (colName == "eurostat_code" || colName == "name")
  54. continue
  55. else {
  56. item.values[colName] = Number(row[i])
  57. }
  58. }
  59. ruralData.push(item)
  60. })
  61. .on('end', () => {
  62. console.log('Rural data file processing finished.');
  63. resolve(ruralData);
  64. })
  65. .on('error', reject);
  66. })
  67. }
  68. module.exports.loadOntology = async function(filePath) {
  69. return new Promise((resolve, reject) => {
  70. fs.readFile(filePath, (err, data) => {
  71. if (err) reject(err)
  72. const ontology = JSON.parse(data)
  73. resolve(ontology)
  74. })
  75. })
  76. }
  77. module.exports.parseDatasetsMetadata = function(ontology) {
  78. return ontology
  79. .filter((entity) => entity['@type'] ? entity['@type'].includes('http://www.semanticweb.org/attractiveness/Dataset') : null)
  80. .filter(
  81. (entity) => entity['http://www.semanticweb.org/attractiveness/hasCoverage']
  82. .some((coverage) => coverage['@id'] == 'http://www.semanticweb.org/attractiveness/Europe')
  83. )
  84. .filter(
  85. (entity) => entity['http://www.semanticweb.org/attractiveness/hasLoD']
  86. .some((lod) => lod['@id'] == 'http://www.semanticweb.org/attractiveness/NUTS3')
  87. )
  88. .map((entity) => {
  89. return {
  90. name: entity['@id'].split('/').splice(-1).pop(),
  91. //FIXME: instead of [0] search for "@language"="en"
  92. description: entity['http://www.semanticweb.org/attractiveness#description'] ? entity['http://www.semanticweb.org/attractiveness#description'][0]['@value'] : '',
  93. factor: entity['http://www.semanticweb.org/attractiveness/isDatasetOf'] ? entity['http://www.semanticweb.org/attractiveness/isDatasetOf'][0]['@id'].split('/').splice(-1).pop() : ''
  94. }
  95. })
  96. }
  97. /**
  98. * Resolves with an array representing rows of CSV file
  99. * @param {string} inputFileName path to the CSV file with input data for clustering calculation
  100. */
  101. module.exports.loadClusteringInput = async function (inputFileName) {
  102. const clusteringData = [];
  103. /*
  104. * The parsed CSV array keeps the native csv-parser structure
  105. * for future easier serialization back to CSV file
  106. */
  107. return new Promise((resolve, reject) => {
  108. fs.createReadStream(inputFileName)
  109. .pipe(csv())
  110. .on('data', (row) => {
  111. row = [row[0], ...row.slice(2)]
  112. clusteringData.push(row);
  113. })
  114. .on('end', () => {
  115. resolve(clusteringData);
  116. })
  117. .on('error', reject);
  118. });
  119. }
  120. /**
  121. * Resolves once the modified CSV file is written to fs
  122. */
  123. module.exports.modifyClusteringData = async function ({datasets, data, params, idString, outputFileName}) {
  124. // regional ID must be copied to the output as well
  125. const allowedDatasets = [idString, ...params.datasets.map(ds => ds.id)]
  126. const factorMultipliers = data[0].map((dataset) => {
  127. if (dataset === idString) return 1
  128. if (!allowedDatasets.includes(dataset)) {
  129. return 0
  130. } else {
  131. return params.datasets.find(ds => ds.id === dataset).weight
  132. }
  133. })
  134. /* The actual modification logic resides here */
  135. const modifiedData = data.map((row, idx) => {
  136. return row.map((value, i) => {
  137. if (idx == 0) {
  138. /* These are the headers */
  139. /* Have to check for both allowed datasets and zero multiplications */
  140. return allowedDatasets.includes(value) && factorMultipliers[i] !== 0 ? value : null;
  141. } else if (isNaN(value)) {
  142. /* This is the NUTS ID record at the beginning of each line */
  143. return value;
  144. }
  145. return factorMultipliers[i] === 0 ? null : value*factorMultipliers[i];
  146. }).filter(val => val !== null);
  147. });
  148. //console.log(modifiedData);
  149. if (modifiedData[0].length <= 1) {
  150. throw new Error('All datasets turned off. No data to create clusters.');
  151. }
  152. return new Promise((resolve, reject) => {
  153. stringify(modifiedData, (err, output) => {
  154. if (err) return reject(err);
  155. fs.writeFile(outputFileName, output, (err) => {
  156. if (err) reject(err);
  157. else resolve();
  158. console.log('Data modification finished.');
  159. })
  160. })
  161. });
  162. }
  163. /**
  164. * Reads the out_file.csv created by R script and saves it into an object
  165. */
  166. module.exports.loadClusters = function (filePath, idString, dataLoadedCallback) {
  167. //console.log('Reading clustering data file processing started.');
  168. let clusters = [];
  169. let columns = undefined;
  170. fs.createReadStream(filePath)
  171. .pipe(csv())
  172. .on('data', (row) => {
  173. if (!columns) {
  174. columns = row;
  175. }
  176. else {
  177. let item = {};
  178. for (let i = 0; i < columns.length; i++) {
  179. const colName = columns[i].length > 0 ? columns[i].toLowerCase() : idString;
  180. item[colName] = row[i];
  181. }
  182. clusters.push(item);
  183. }
  184. })
  185. .on('end', () => {
  186. console.log('Cluster data file processing finished.');
  187. dataLoadedCallback(clusters);
  188. });
  189. }
  190. module.exports.getFactorIndex = function (region, factor) {
  191. //console.log('getFactorIndex');
  192. //console.log('region: ' + JSON.stringify(region, null, 4));
  193. //console.log('factor: ' + JSON.stringify(factor, null, 4));
  194. let sumValue = 0;
  195. let count = 0;
  196. factor.datasets.forEach(ds => {
  197. const dataset = ds.split('/').slice(-1).pop()
  198. //console.log('factor: ' + factor.factor);
  199. const value = region.values[dataset];
  200. if (value) {
  201. sumValue += value;
  202. count++;
  203. }
  204. });
  205. return { index: sumValue / count, sumValue: sumValue, sumWeight: count * factor.weight };
  206. }
  207. /* Unused */
  208. function getDatasetFactor(datasets, colName) {
  209. for (let i = 0; i < datasets.length; i++) {
  210. if (datasets[i].Name.toLowerCase() == colName)
  211. return datasets[i].Factor;
  212. }
  213. return undefined;
  214. }