nuts-data.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. const factor = datasets.find(ds => ds.Name === dataset);
  100. if (!factor) {
  101. /* If the factor is unknown for this dataset, it will effectivelly turn it off */
  102. console.log(`Undefined factor for dataset ${dataset}`);
  103. allowedDatasets.filter(ds => ds !== 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. return allowedDatasets.includes(value) ? value : null;
  118. } else if (isNaN(value)) {
  119. /* This is the NUTS ID record */
  120. return value;
  121. }
  122. return factorMultipliers[i] === 0 ? null : value*factorMultipliers[i];
  123. }).filter(val => val !== null);
  124. });
  125. //console.log(modifiedData);
  126. return new Promise((resolve, reject) => {
  127. stringify(modifiedData, (err, output) => {
  128. if (err) return reject(err);
  129. fs.writeFile(outputFileName, output, (err) => {
  130. if (err) reject(err);
  131. else resolve();
  132. //console.log('Data modification finished.');
  133. })
  134. })
  135. });
  136. }
  137. /**
  138. * Reads the out_file.csv created by R script and saves it into an object
  139. */
  140. module.exports.loadClusters = function (filePath, dataLoadedCallback) {
  141. //console.log('Reading clustering data file processing started.');
  142. let clusters = [];
  143. let columns = undefined;
  144. fs.createReadStream(filePath)
  145. .pipe(csv())
  146. .on('data', (row) => {
  147. if (!columns) {
  148. columns = row;
  149. }
  150. else {
  151. let item = {};
  152. for (let i = 0; i < columns.length; i++) {
  153. const colName = columns[i].length > 0 ? columns[i].toLowerCase() : 'nuts_id';
  154. item[colName] = row[i];
  155. }
  156. clusters.push(item);
  157. }
  158. })
  159. .on('end', () => {
  160. //console.log('Rural data file processing finished.');
  161. dataLoadedCallback(clusters);
  162. });
  163. }
  164. module.exports.getFactorIndex = function (region, factor) {
  165. //console.log('getFactorIndex');
  166. //console.log('region: ' + region.nuts);
  167. //console.log('factor: ' + JSON.stringify(factor, null, 4));
  168. sumValue = 0;
  169. count = 0;
  170. factor.datasets.forEach(ds => {
  171. //console.log('factor: ' + factor.factor);
  172. let value = region[factor.factor][ds];
  173. if (value) {
  174. sumValue += value;
  175. count++;
  176. }
  177. });
  178. return { index: sumValue / count, sumValue: sumValue, sumWeight: count * factor.weight };
  179. }
  180. function getDataSetFactor(datasets, colName) {
  181. for (let i = 0; i < datasets.length; i++) {
  182. if (datasets[i].Name.toLowerCase() == colName)
  183. return datasets[i].Factor;
  184. }
  185. return undefined;
  186. }