nuts-data.js 7.3 KB

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