nuts-data.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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 = function(filePath, dataLoadedCallback) {
  6. //console.log('Datasets structure loading.');
  7. var datasets = [];
  8. let columns = undefined;
  9. fs.createReadStream(filePath)
  10. .pipe(csv({ separator: ';' }))
  11. .on('data', (row) => {
  12. if (!columns) {
  13. columns = row;
  14. }
  15. else {
  16. let ds = {};
  17. for (let i = 0; i < columns.length; i++) {
  18. ds[columns[i]] = row[i];
  19. }
  20. datasets.push(ds);
  21. }
  22. })
  23. .on('end', () => {
  24. //console.log('Datasets structure loaded.');
  25. dataLoadedCallback(datasets);
  26. });
  27. }
  28. /* Load all the attractivness data from CSV into a server object.
  29. The data don't need to be loaded for each request then. */
  30. module.exports.loadRuralData = function (filePath, datasets, dataLoadedCallback) {
  31. console.log('Reading rural data file processing started.');
  32. var ruralData = [];
  33. let columns = undefined;
  34. fs.createReadStream(filePath)
  35. .pipe(csv())
  36. .on('data', (row) => {
  37. if (!columns) {
  38. columns = row;
  39. }
  40. else {
  41. let item = {};
  42. for (let i = 0; i < columns.length; i++) {
  43. let colName = columns[i].toLowerCase();
  44. if (colName == "nuts_id") // ID of the NUTS region
  45. item.nuts = row[i];
  46. else if (colName == "datasets") // empty datasets count
  47. item.availableDS = datasets.length - row[i];
  48. else if (colName == "quality")
  49. item.quality = row[i];
  50. else {
  51. let factor = getDataSetFactor(datasets, colName);
  52. if (factor) {
  53. if (!item[factor])
  54. item[factor] = {};
  55. //item[factor].push({ dataset: columns[i], value: row[i] });
  56. item[factor][columns[i]] = Number(row[i]);
  57. }
  58. }
  59. }
  60. ruralData.push(item);
  61. }
  62. })
  63. .on('end', () => {
  64. //console.log('Rural data file processing finished.');
  65. dataLoadedCallback(ruralData);
  66. });
  67. }
  68. /**
  69. * Resolves with an array representing rows of CSV file
  70. * @param {string} inputFileName path to the CSV file with input data for clustering calculation
  71. */
  72. module.exports.loadClusteringInput = async function (inputFileName) {
  73. const clusteringData = [];
  74. /*
  75. * The parsed CSV array keeps the native csv-parser structure
  76. * for future easier serialization back to CSV file
  77. */
  78. return new Promise((resolve, reject) => {
  79. fs.createReadStream(inputFileName)
  80. .pipe(csv())
  81. .on('data', (row) => {
  82. clusteringData.push(row);
  83. })
  84. .on('end', () => {
  85. resolve(clusteringData);
  86. })
  87. .on('error', reject);
  88. });
  89. }
  90. /**
  91. * Resolves once the modified CSV file is written to fs
  92. */
  93. module.exports.modifyClusteringData = async function ({datasets, data, params, outputFileName}) {
  94. let allowedDatasets = ['NUTS_ID']; // NUTS_ID must be copied to the output as well
  95. for (const factor of params.factors) {
  96. allowedDatasets = [...allowedDatasets, ...factor.datasets];
  97. }
  98. const factorMultipliers = data[0].map((dataset) => {
  99. if (dataset === 'NUTS_ID') return 1;
  100. const factor = datasets.find(ds => ds.Name === dataset);
  101. if (!factor) {
  102. /* If the factor is unknown for this dataset, it will effectivelly turn it off */
  103. console.log(`Undefined factor for dataset ${dataset}`);
  104. return 0;
  105. } else if (!allowedDatasets.includes(dataset)) {
  106. return 0;
  107. } else {
  108. return params.factors.find(f => f.factor === factor.Factor).weight;
  109. }
  110. })
  111. //console.log(factorMultipliers);
  112. /* The actual modification logic resides here */
  113. const modifiedData = data.map((row, idx) => {
  114. return row.map((value, i) => {
  115. if (idx == 0) {
  116. /* These are the headers */
  117. /* Have to check for both allowed datasets and zero multiplications */
  118. return allowedDatasets.includes(value) && factorMultipliers[i] !== 0 ? value : null;
  119. } else if (isNaN(value)) {
  120. /* This is the NUTS ID record at the beginning of each line */
  121. return value;
  122. }
  123. return factorMultipliers[i] === 0 ? null : value*factorMultipliers[i];
  124. }).filter(val => val !== null);
  125. });
  126. //console.log(modifiedData);
  127. return new Promise((resolve, reject) => {
  128. stringify(modifiedData, (err, output) => {
  129. if (err) return reject(err);
  130. fs.writeFile(outputFileName, output, (err) => {
  131. if (err) reject(err);
  132. else resolve();
  133. //console.log('Data modification finished.');
  134. })
  135. })
  136. });
  137. }
  138. /**
  139. * Reads the out_file.csv created by R script and saves it into an object
  140. */
  141. module.exports.loadClusters = function (filePath, dataLoadedCallback) {
  142. //console.log('Reading clustering data file processing started.');
  143. let clusters = [];
  144. let columns = undefined;
  145. fs.createReadStream(filePath)
  146. .pipe(csv())
  147. .on('data', (row) => {
  148. if (!columns) {
  149. columns = row;
  150. }
  151. else {
  152. let item = {};
  153. for (let i = 0; i < columns.length; i++) {
  154. const colName = columns[i].length > 0 ? columns[i].toLowerCase() : 'nuts_id';
  155. item[colName] = row[i];
  156. }
  157. clusters.push(item);
  158. }
  159. })
  160. .on('end', () => {
  161. //console.log('Rural data file processing finished.');
  162. dataLoadedCallback(clusters);
  163. });
  164. }
  165. module.exports.getFactorIndex = function (region, factor) {
  166. //console.log('getFactorIndex');
  167. //console.log('region: ' + region.nuts);
  168. //console.log('factor: ' + JSON.stringify(factor, null, 4));
  169. sumValue = 0;
  170. count = 0;
  171. factor.datasets.forEach(ds => {
  172. //console.log('factor: ' + factor.factor);
  173. let value = region[factor.factor][ds];
  174. if (value) {
  175. sumValue += value;
  176. count++;
  177. }
  178. });
  179. return { index: sumValue / count, sumValue: sumValue, sumWeight: count * factor.weight };
  180. }
  181. function getDataSetFactor(datasets, colName) {
  182. for (let i = 0; i < datasets.length; i++) {
  183. if (datasets[i].Name.toLowerCase() == colName)
  184. return datasets[i].Factor;
  185. }
  186. return undefined;
  187. }