ソースを参照

♻️ Cleanup code and move stuff

jmacura 4 年 前
コミット
cf695587fa
3 ファイル変更47 行追加67 行削除
  1. 26 56
      src/adjuster/adjuster.service.ts
  2. 6 11
      src/app.service.ts
  3. 15 0
      src/attractiveness.config.json

+ 26 - 56
src/adjuster/adjuster.service.ts

@@ -7,12 +7,18 @@ import {HsLayerManagerMetadataService} from 'hslayers-ng/components/layermanager
 import {HsLayerManagerService} from 'hslayers-ng/components/layermanager';
 import {HsUtilsService} from 'hslayers-ng/components/utils/utils.service';
 
+import attractivenessConfig from '../attractiveness.config.json';
 import clusteringMethods from '../data/clustering_methods.json';
 import {AdjusterEventService} from './adjuster-event.service';
 import {obce, obceIndexLayer, osmLayer} from '../app.config';
 
 @Injectable({providedIn: 'root'})
 export class AdjusterService {
+  /** To be read from a config file */
+  allowedClusteringMethods: Array<string>;
+  /** To be read from a config file */
+  initialWeights;
+  /** To be read from a config file */
   serviceBaseUrl: string;
   factors = [];
   //clusters = [];
@@ -36,14 +42,18 @@ export class AdjusterService {
     public hsUtilsService: HsUtilsService,
     public $http: HttpClient
   ) {
+    // First safely set configurable properties
+    this.allowedClusteringMethods =
+      attractivenessConfig?.allowedClusteringMethods ?? [];
+    this.initialWeights = attractivenessConfig?.initialWeights ?? {};
     this.serviceBaseUrl =
-      window.location.hostname === 'localhost'
-        ? 'https://jmacura.ml/ws/' // 'http://localhost:3000/'
-        : 'https://publish.lesprojekt.cz/nodejs/';
-    this.methods = clusteringMethods.filter(
-      (m) => m.codename == 'haclustwd2' || m.codename == 'km50l.cluster'
+      attractivenessConfig?.serviceBaseUrl ??
+      'https://publish.lesprojekt.cz/nodejs/';
+    // 'https://jmacura.ml/ws/' // 'http://localhost:3000/'
+
+    this.methods = clusteringMethods.filter((m) =>
+      this.allowedClusteringMethods.includes(m.codename)
     );
-    //this.method = 'haclustwd2';
     this.numberOfClusters = 9;
   }
 
@@ -57,7 +67,6 @@ export class AdjusterService {
   }
 
   calculateIndex(): void {
-    //const f = () => {
     this._raiInProcess = true;
     this.$http
       .post(this.serviceBaseUrl + 'scores/cz', {
@@ -74,13 +83,6 @@ export class AdjusterService {
       .toPromise()
       .then((attractivenessData: any[]) => {
         console.log(attractivenessData);
-        //this.attractivity = attractivenessData;
-        /*let max = 0;
-          attractivenessData.forEach((a) => {
-            if (a.aggregate > max) {
-              max = a.aggregate;
-            }
-          });*/
         // Spread the 'aggregate' value between 0 and 1
         const min = attractivenessData.reduce((a, b) =>
           a.aggregate < b.aggregate ? a : b
@@ -94,22 +96,18 @@ export class AdjusterService {
           a.aggregate *= coefficient;
           a.aggregate += constant;
         });
-        console.log(attractivenessData);
         // Store relation between region and its data in a hash-table-like structure
+        // more memory consuming, but faster then find()
         const codeRecordRelations = {};
         attractivenessData.forEach((a) => {
           codeRecordRelations[a.code] = a;
         });
         let errs = 0;
-        let logs = 0;
-        console.time('forEachObce');
+        //let logs = 0;
+        console.time('forEach-Index');
         obce.forEachFeature((feature) => {
           // Pair each feature with its attractivity data
           const featureData = codeRecordRelations[feature.get('nationalCode')];
-          /*const featureData = attractivenessData.find(
-              // NOTE: Do NOT add triple equal sign!
-              (item) => item['code'] == feature.get('nationalCode')
-            );*/
           if (!featureData) {
             if (errs < 20) {
               errs++;
@@ -120,41 +118,19 @@ export class AdjusterService {
             }
             return;
           }
-          logs++;
+          /*logs++;
           if (logs % 100 == 0) {
             console.log(`processed ${logs} items`);
-          }
+          }*/
           Object.keys(featureData).forEach((key, index) => {
             if (key !== 'lau2') {
-              feature.set(key, featureData[key], true); //true stands for "silent" - important!
+              feature.set(key, featureData[key], true); //true stands for "silent" - important for performance!
             }
           });
-          /*feature.set(
-              'total',
-              this.nutsCodeRecordRelations[feature.get('nationalCode')]
-                .aggregate
-            );*/
-          /*feature.set(
-              'totalForHumans',
-              (
-                this.nutsCodeRecordRelations[feature.get('nationalCode')]
-                  .aggregate * 100
-              ).toFixed(2)
-            );*/
-          /*this.factors.forEach((factor) => {
-              feature.set(
-                factor.name,
-                (
-                  this.nutsCodeRecordRelations[feature.get('nationalCode')][
-                    factor.name
-                  ] * 100
-                ).toFixed(2)
-              );
-            });*/
         });
         // Since we are updating the features silently, we now have to refresh manually
         obce.getFeatures()[0].dispatchEvent('change');
-        console.timeEnd('forEachObce');
+        console.timeEnd('forEach-Index');
         this._raiInProcess = false;
         this.adjusterEventService.loaded.next({
           success: true,
@@ -171,12 +147,9 @@ export class AdjusterService {
           err: error,
         });
       });
-    //};
-    //this.hsUtilsService.debounce(f, 300, false, this)();
   }
 
   calculateClusters(): void {
-    //const f = () => {
     this._clusteringInProcess = true;
     this.$http
       .post(this.serviceBaseUrl + 'clusters/cz', {
@@ -220,7 +193,7 @@ export class AdjusterService {
             sublyr.Name = `c${i + 1}`;
             i++;
           }*/
-        console.time('forEachObceCluster');
+        console.time('forEach-Cluster');
         obce.forEachFeature((feature) => {
           // Pair each feature with its clustering data
           const featureData = clusterData.find(
@@ -282,8 +255,7 @@ export class AdjusterService {
         //obceLayer.set('Layer', sublayers);
         //this.hsLayerMetadataService.fillMetadata(obceLayer);
         //console.log(sublayers[0].getSource().getFeatures());
-        console.log(obceIndexLayer);
-        console.timeEnd('forEachObceCluster');
+        console.timeEnd('forEach-Cluster');
         console.log('clustering done!');
         //this.clusters = clusters;
         this._clusteringInProcess = false;
@@ -302,8 +274,6 @@ export class AdjusterService {
           err: error,
         });
       });
-    //};
-    //this.hsUtilsService.debounce(f, 300, false, this)();
   }
 
   init(): void {
@@ -315,7 +285,7 @@ export class AdjusterService {
         this.factors = data.map((dataset) => {
           return {
             name: dataset.Factor,
-            weight: dataset.Factor == 'Udržitelná města a obce' ? 1 : 0,
+            weight: this.initialWeights[dataset.Factor] ?? 1,
             datasets: [],
           };
         });

+ 6 - 11
src/app.service.ts

@@ -48,22 +48,15 @@ export class AppService {
   ) {
     this.adjusterEventService.loaded.subscribe(({success}) => {
       if (success) {
-        //console.log(this.adjusterService.methods[0].layer.getSource().getFeatures());
         this.colorPalette = this.generateRandomColorPalette(
           this.adjusterService.numberOfClusters
         );
       }
     });
-    this.prepareLayers();
     this.hsEventBus.layoutLoads.subscribe(() => {
       this.init();
     });
-    /*obce.getParams = () => {
-      return {LAYERS: []};
-    };
-    obce.updateParams = (params) => {
-      null;
-    };*/
+    this.prepareLayers();
   }
 
   init(): void {
@@ -81,6 +74,9 @@ export class AppService {
     this.hsLayoutService.setDefaultPanel('adjuster');
   }
 
+  /**
+   * Create separate layer fo each clustering method and add it to default_layers
+   */
   prepareLayers(): void {
     for (const method of this.adjusterService.methods) {
       method.layer = new VectorLayer({
@@ -88,14 +84,13 @@ export class AppService {
         editor: {editable: false},
         visible: true,
         style: this.generateStyle(method.codename),
-        title: `Obce ČR: ${method.name} clusters`,
+        title: `Obce ČR: ${method.name.replaceAll(/\((.+?)\)/g, '')} clusters`,
         attributions: ['CC-BY ČÚZK, 2021'],
       });
       this.hsConfig.default_layers.push(method.layer);
     }
     // obceIndexLayer must be pushed last so it will be on top
     this.hsConfig.default_layers.push(obceIndexLayer);
-    //console.log(this.adjusterService.methods[0].layer.getSource().getFeatures());
   }
 
   /**
@@ -123,7 +118,7 @@ export class AppService {
 
   /**
    * @description Function factory for generating style functions based on different clustering methods
-   * @param {string} method currently selected method
+   * @param {string} method selected method
    * @returns {function} style function
    */
   private generateStyle(method: string) {

+ 15 - 0
src/attractiveness.config.json

@@ -0,0 +1,15 @@
+{
+  "allowedClusteringMethods": [
+    "haclustwd2",
+    "km50l.cluster"
+  ],
+  "initialWeights": {
+    "Konec chudoby": 0,
+    "Zdraví a kvalitní život": 0,
+    "Kvalitní vzdělání": 0,
+    "Důstojná práce a ekonomický růst": 0,
+    "Udržitelná města a obce": 1,
+    "Ostatní": 0
+  },
+  "serviceBaseUrl": "https://publish.lesprojekt.cz/nodejs/"
+}