Prechádzať zdrojové kódy

⚡️ update features silently

+barebone for enabling both index and clustering
jmacura 4 rokov pred
rodič
commit
b9f47b2083
3 zmenil súbory, kde vykonal 124 pridanie a 35 odobranie
  1. 102 20
      src/adjuster/adjuster.service.ts
  2. 1 1
      src/app.config.ts
  3. 21 14
      src/app.service.ts

+ 102 - 20
src/adjuster/adjuster.service.ts

@@ -1,17 +1,20 @@
 import {HttpClient} from '@angular/common/http';
 import {Injectable} from '@angular/core';
+import {Vector as VectorLayer} from 'ol/layer';
+import {Vector as VectorSource} from 'ol/source';
 
+import {HsLayerManagerMetadataService} from 'hslayers-ng/components/layermanager/layermanager-metadata.service';
 import {HsLayerManagerService} from 'hslayers-ng/components/layermanager';
 import {HsUtilsService} from 'hslayers-ng/components/utils/utils.service';
 
 import clusteringMethods from '../data/clustering_methods.json';
-import {obce, osmLayer} from '../app.config';
+import {obce, obceLayer, osmLayer} from '../app.config';
 
 @Injectable({providedIn: 'root'})
 export class AdjusterService {
   serviceBaseUrl: string;
   factors = [];
-  clusters = [];
+  //clusters = [];
   numberOfClusters;
   method: string;
   methods: Array<{
@@ -20,9 +23,11 @@ export class AdjusterService {
     type: string;
   }>;
   private _clusteringInProcess: boolean;
+  private _loadInProcess: boolean;
   private _raiInProcess: boolean;
 
   constructor(
+    public hsLayerMetadataService: HsLayerManagerMetadataService,
     public hsLayerManagerService: HsLayerManagerService,
     public hsUtilsService: HsUtilsService,
     public $http: HttpClient
@@ -43,8 +48,8 @@ export class AdjusterService {
    * and applies the returned values
    */
   apply(): void {
-    //this.calculateIndex();
-    this.calculateClusters();
+    this.calculateIndex();
+    //this.calculateClusters();
   }
 
   calculateIndex(): void {
@@ -108,7 +113,7 @@ export class AdjusterService {
             }
             Object.keys(featureData).forEach((key, index) => {
               if (key !== 'lau2') {
-                feature.set(key, featureData[key]);
+                feature.set(key, featureData[key], true); //true stands for "silent" - important!
               }
             });
             /*feature.set(
@@ -134,6 +139,8 @@ export class AdjusterService {
               );
             });*/
           });
+          // Since we are updating the features silently, we now have to refresh manually
+          obce.getFeatures()[0].dispatchEvent('change');
           console.timeEnd('forEachObce');
           this._raiInProcess = false;
         })
@@ -168,6 +175,29 @@ export class AdjusterService {
           let logs = 0;
           let errs = 0;
           const clusterData = data.response;
+          console.log(obceLayer);
+          /*let sublayers = [];
+          const oldSublayers = obceLayer.get('Layer');
+          if (oldSublayers !== undefined && Array.isArray(oldSublayers)) {
+            for (const sublyr of oldSublayers) {
+              sublyr.getSource().clear();
+            }
+            if (oldSublayers.length > this.numberOfClusters) {
+              sublayers = oldSublayers.slice(0, this.numberOfClusters);
+            }
+          }
+          let i = sublayers.length;
+          while (sublayers.length < this.numberOfClusters) {
+            const sublyr = new VectorLayer({
+              title: `Cluster ${i + 1}`,
+              name: i + 1 + '',
+              source: new VectorSource({}),
+            });
+            sublayers.push(sublyr);
+            sublyr.Title = `Cluster ${i + 1}`;
+            sublyr.Name = `c${i + 1}`;
+            i++;
+          }*/
           console.time('forEachObceCluster');
           obce.forEachFeature((feature) => {
             // Pair each feature with its clustering data
@@ -175,10 +205,14 @@ export class AdjusterService {
               // NOTE: Do NOT add triple equal sign!
               (item) => item['lau2'] == feature.get('nationalCode')
             );
-            if (!featureData && errs < 20) {
-              errs++;
-              console.warn(`No data for feature ${feature.get('nationalCode')}`);
-              console.log(feature);
+            if (!featureData) {
+              if (errs < 20) {
+                errs++;
+                console.warn(
+                  `No data for feature ${feature.get('nationalCode')}`
+                );
+                console.log(feature);
+              }
               return;
             }
             logs++;
@@ -187,19 +221,49 @@ export class AdjusterService {
             }
             Object.keys(featureData).forEach(function (key, index) {
               if (key !== 'lau2') {
-                feature.set(key, featureData[key]);
+                feature.set(key, featureData[key], true);
               }
             });
           });
-          const clusters = [];
-          for (const region of clusterData) {
+          //const clusters = [];
+          //const obceFeatures: Array<any> = obce.getFeatures();
+          /*for (const region of clusterData) {
             if (!clusters.includes(region[this.method])) {
               clusters.push(region[this.method]);
             }
-          }
+            const feature = obceFeatures.find(
+              // NOTE: Do NOT add triple equal sign!
+              (f) => f.get('nationalCode') == region['lau2']
+            );
+            if (!feature) {
+              if (errs < 20) {
+                errs++;
+                console.warn(`No feature matches region ${region['lau2']}`);
+                console.log(region);
+              }
+              continue;
+            }
+            logs++;
+            if (logs % 100 == 0) {
+              console.log(`processed ${logs} items`);
+            }
+            Object.keys(region).forEach(function (key, index) {
+              if (key !== 'lau2') {
+                feature.set(key, region[key], true);
+              }
+            });
+            if (logs % 100 == 0) {
+              //sublayers[0].getSource().addFeature(feature);
+            }
+            //sublayers[region[this.method] - 1].getSource().addFeature(feature);
+          }*/
+          //obceLayer.set('Layer', sublayers);
+          //this.hsLayerMetadataService.fillMetadata(obceLayer);
+          //console.log(sublayers[0].getSource().getFeatures());
+          console.log(obceLayer);
           console.timeEnd('forEachObceCluster');
           console.log('clustering done!');
-          this.clusters = clusters;
+          //this.clusters = clusters;
           this._clusteringInProcess = false;
           //this.adjusterEventService.clustersLoaded.next({success: true});
         })
@@ -217,13 +281,17 @@ export class AdjusterService {
   }
 
   init(): void {
-    this._raiInProcess = true;
+    this._loadInProcess = true;
     this.$http
       .get(this.serviceBaseUrl + 'datasets/cz')
       .toPromise()
       .then((data: any) => {
         this.factors = data.map((dataset) => {
-          return {name: dataset.Factor, weight: 1, datasets: []};
+          return {
+            name: dataset.Factor,
+            weight: dataset.Factor == 'Udržitelná města a obce' ? 1 : 0,
+            datasets: [],
+          };
         });
         this.factors = this.hsUtilsService.removeDuplicates(
           this.factors,
@@ -240,21 +308,35 @@ export class AdjusterService {
               };
             });
         });
-        this._raiInProcess = false;
+        this._loadInProcess = false;
         this.apply();
         this.hsLayerManagerService.setGreyscale(osmLayer);
       })
       .catch((error) => {
         console.warn(`Web service at ${this.serviceBaseUrl} unavailable!`);
         console.log(error);
-        this._raiInProcess = false;
+        this._loadInProcess = false;
       });
   }
 
   /**
-   * @returns {boolean} true if clustering or index processing is in process, false otherwise
+   * @returns {boolean} true if clustering or index processing is in process or loading data, false otherwise
    */
   isInProcess(): boolean {
-    return this._clusteringInProcess || this._raiInProcess;
+    return (
+      this._loadInProcess || this._clusteringInProcess || this._raiInProcess
+    );
+  }
+
+  isLoading(): boolean {
+    return this._loadInProcess;
+  }
+
+  isClustering(): boolean {
+    return this._clusteringInProcess;
+  }
+
+  isCalculatingRAI(): boolean {
+    return this._raiInProcess;
   }
 }

+ 1 - 1
src/app.config.ts

@@ -84,7 +84,7 @@ export const obce = new VectorSource({
   overlaps: false,
 });
 
-const obceLayer = new VectorLayer({
+export const obceLayer = new VectorLayer({
   source: obce,
   editor: {editable: false},
   visible: true,

+ 21 - 14
src/app.service.ts

@@ -8,6 +8,7 @@ import {HsPanelContainerService} from 'hslayers-ng/components/layout/panels/pane
 import {HsSidebarService} from 'hslayers-ng/components/sidebar/sidebar.service';
 
 import {AdjusterComponent} from './adjuster/adjuster.component';
+import {obce} from './app.config';
 
 @Injectable({providedIn: 'root'})
 export class AppService {
@@ -19,23 +20,29 @@ export class AppService {
     public hsPanelContainerService: HsPanelContainerService,
     public hsSidebarService: HsSidebarService
   ) {
-    this.init();
+    this.hsEventBus.layoutLoads.subscribe(() => {
+      this.init();
+    });
+    obce.getParams = () => {
+      return {LAYERS: []};
+    };
+    obce.updateParams = (params) => {
+      null;
+    };
   }
 
   init(): void {
-    this.hsEventBus.layoutLoads.subscribe(() => {
-      this.hsLanguageService.setLanguage('cs');
-      this.hsSidebarService.buttons.push({
-        panel: 'adjuster',
-        module: 'pra.adjuster',
-        order: 0,
-        title: () =>
-          this.hsLanguageService.getTranslation('ADJUSTER.adjustFactors'),
-        description: 'Adjust factors for computation',
-        icon: 'icon-analytics-piechart',
-      });
-      this.hsPanelContainerService.create(AdjusterComponent, {});
-      this.hsLayoutService.setDefaultPanel('adjuster');
+    this.hsLanguageService.setLanguage('cs');
+    this.hsSidebarService.buttons.push({
+      panel: 'adjuster',
+      module: 'pra.adjuster',
+      order: 0,
+      title: () =>
+        this.hsLanguageService.getTranslation('ADJUSTER.adjustFactors'),
+      description: 'Adjust factors for computation',
+      icon: 'icon-analytics-piechart',
     });
+    this.hsPanelContainerService.create(AdjusterComponent, {});
+    this.hsLayoutService.setDefaultPanel('adjuster');
   }
 }