source: trunk/zoo-project/zoo-kernel/service_internal_saga.c @ 653

Last change on this file since 653 was 653, checked in by djay, 9 years ago

Small fixes for building on GNU/Linux.

  • Property svn:keywords set to Id
File size: 34.2 KB
Line 
1/*
2 * Author : Gérald FENOY
3 *
4 * Copyright (c) 2015 GeoLabs SARL
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
25#include <stdlib.h>
26#include <limits.h>
27#include <locale.h>
28#include <wx/string.h>
29#include <wx/app.h>
30#include <api_core.h>
31#include <data_manager.h>
32#include <module_library.h>
33#define _ZOO_SAGA
34#include "service_internal_saga.h"
35#include "server_internal.h"
36#include "mimetypes.h"
37
38/**
39 * Global SAGA-GIS output counter
40 */
41int sagaOutputCounter=0;
42
43/**
44 * Observer used to access the ongoing status of a running OTB Application
45 */
46class SagaWatcher
47{
48 public:
49  static int Callback(TSG_UI_Callback_ID ID, CSG_UI_Parameter &Param_1, CSG_UI_Parameter &Param_2);
50  /**
51   * Define the message value
52   *
53   * @param conf the maps pointer to copy
54   */
55  static void SetMessage(const char *mess)
56  {
57    FreeMessage();
58    message=zStrdup(mess);
59  }
60  /**
61   * Free the message value
62   *
63   */
64  static void FreeMessage()
65  {
66    if(message!=NULL)
67      free(message);
68    message=NULL;
69  }
70  /**
71   * Copy the original conf in the m_conf property
72   *
73   * @param conf the maps pointer to copy
74   */
75  void SetConf(maps **conf)
76  {
77    m_conf=dupMaps(conf);
78  }
79  /** 
80   * Get Configuration maps (m_conf)
81   * @return the m_conf property
82   */
83  const maps& GetConf()
84  {
85    return *m_conf;
86  }
87  /** 
88   * Free Configuration maps (m_Conf)
89   */
90  void FreeConf(){
91    freeMaps(&m_conf);
92    free(m_conf);
93  }
94 private:
95  /** Main conf maps */
96  static maps* m_conf;
97  /** Status */
98  static int status;
99  /** Message */
100  static char* message;
101};
102
103maps* SagaWatcher::m_conf;
104char* SagaWatcher::message=zStrdup("No message left");
105int SagaWatcher::status=1;
106
107/**
108 * The callback function called at any SAGA-GIS module step
109 *
110 * @param id a TSG_UI_Callback_ID as defined in api_core.h (line 1290)
111 * @param param1
112 * @param param2
113 */
114int
115SagaWatcher::
116Callback(TSG_UI_Callback_ID id, CSG_UI_Parameter &param1, CSG_UI_Parameter &param2)
117{
118
119  int res = 1;
120  switch( id )
121    {
122    default:
123      return 0;
124      break;
125
126    case CALLBACK_DLG_ERROR:
127      return 1;
128      break;
129
130    case CALLBACK_DLG_PARAMETERS:
131    case CALLBACK_PROCESS_SET_OKAY:
132    case CALLBACK_DATAOBJECT_COLORS_GET:
133    case CALLBACK_DATAOBJECT_COLORS_SET:
134    case CALLBACK_DATAOBJECT_PARAMS_GET:
135    case CALLBACK_DATAOBJECT_PARAMS_SET:
136    case CALLBACK_DATAOBJECT_UPDATE:
137    case CALLBACK_DATAOBJECT_SHOW:
138    case CALLBACK_DLG_CONTINUE:
139    case CALLBACK_PROCESS_SET_READY:
140    case CALLBACK_PROCESS_GET_OKAY:
141      return res;
142      break;
143
144    case CALLBACK_PROCESS_SET_PROGRESS:
145      {
146        int cPercent= param2.Number != 0.0 ? 1 + (int)(100.0 * param1.Number / param2.Number) : 100 ;
147        if( cPercent != status ){
148          status=cPercent;
149        }else
150          return res;
151      }
152      break;
153
154    case CALLBACK_PROCESS_SET_TEXT:
155      SetMessage(param1.String.b_str());
156      break;
157
158    case CALLBACK_MESSAGE_ADD:
159      SetMessage(param1.String.b_str());
160      break;
161
162    case CALLBACK_MESSAGE_ADD_ERROR:
163      SetMessage(param1.String.b_str());
164      break;
165
166    case CALLBACK_MESSAGE_ADD_EXECUTION:
167      SetMessage(param1.String.b_str());
168      break;
169
170    case CALLBACK_DLG_MESSAGE:
171      SetMessage((param2.String + ": " + param1.String).b_str());
172      break;
173
174    case CALLBACK_DATAOBJECT_ADD:
175      if(SG_Get_Data_Manager().Add((CSG_Data_Object *)param1.Pointer))
176        res = 1 ;
177      else
178        res = 0;
179      return res;
180      break;
181
182    }
183  updateStatus(m_conf,status,message);
184  return( res );
185}
186
187TSG_PFNC_UI_Callback Get_Callback (SagaWatcher watcher){
188  return( &(watcher.Callback) );
189}
190
191
192/**
193 * Get the default file extension for SAGA-GIS parameter type.
194 * Extensions are the following:
195 *  - sgrd for grid and data_object
196 *  - shp for shapes and tin
197 *  - csv for tables
198 *  - spc for points
199 *
200 * @param param a SAGA-GIS Parameter
201 */ 
202const char* sagaGetDefaultExt(CSG_Parameter* param){
203  if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("grid"))
204     || CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("data_object"))){
205    return "sgrd";
206  }
207  else if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("shapes")) ||
208          CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("tin"))){
209    return "shp";
210  }
211  else if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("table"))){
212    return "csv";
213  }
214  else if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("points"))){
215    return "spc";
216  }
217  return "unknown";
218}
219
220/**
221 * Load a datasource in the SAGA-GIS Data Manager.
222 *
223 * @param param a SAGA-GIS Parameter
224 * @param arg the arguments map passed to a SAGA-GIS module
225 * @return false on failure, true in case of success
226 */
227bool sagaLoadInput(CSG_Parameter* param,map* arg){
228  if(!param->is_Input() || !param->is_Enabled()){
229    return true;
230  }
231  map* carg=getMap(arg,CSG_String(param->Get_Identifier()).b_str());
232  if(carg!=NULL){
233    wxString fileName(carg->value);
234    if(param->is_DataObject()){
235      // In case it there is a single datasource
236      if(!SG_Get_Data_Manager().Find(&fileName) && !SG_Get_Data_Manager().Add(&fileName) && !param->is_Optional() ){
237        return false;
238      }
239      return( param->Set_Value(SG_Get_Data_Manager().Find(&fileName)) );
240    }
241    else
242      if(param->is_DataObject_List()){
243        // In case there are multiple datasources
244        param->asList()->Del_Items();
245        wxString fileNames(fileName);
246        while( fileNames.Length() > 0 ){
247          fileName = fileNames.BeforeFirst(';').Trim(false);
248          fileNames = fileNames.AfterFirst (';');           
249          if( !SG_Get_Data_Manager().Find(&fileName) ){
250            SG_Get_Data_Manager().Add(&fileName);
251          }
252          param->asList()->Add_Item(SG_Get_Data_Manager().Find(&fileName));
253        }
254      }
255  }
256  return true;
257}
258
259/**
260 * Extract all SAGA-GIS parameters from a parameters list and set its values to
261 * the one defined in the map.
262 *
263 * @parap params the parameters list
264 * @parap argument the argument map containing the value to use
265 * @return true in success, false in other case
266 */
267bool sagaSetParameters(CSG_Parameters *params,map* argument){
268
269  int pc=params->Get_Count();
270  params->Restore_Defaults();
271
272  for(int k=0;k<pc;k++){
273    CSG_Parameter * param=params->Get_Parameter(k);
274    if( param->is_Output() ){
275      map* omap=getMap(argument,CSG_String(param->Get_Identifier()).b_str());
276      if( param->is_DataObject() && param->is_Optional() && !param->asDataObject() && omap!=NULL){
277        param->Set_Value(DATAOBJECT_CREATE);
278      }
279    }
280    else
281      if( param->is_Option() && !param->is_Information() ){
282        map* inmap=getMap(argument,CSG_String(param->Get_Identifier()).b_str());
283        if(inmap!=NULL){
284            switch( param->Get_Type() ){
285            case PARAMETER_TYPE_Bool:
286              if(strncasecmp(inmap->value,"true",4)==0 || strncasecmp(inmap->value,"1",1)==0){
287                param->Set_Value(1);
288              }else
289                param->Set_Value(0);
290              break;
291            case PARAMETER_TYPE_Parameters:
292              // TODO: nested inputs gesture
293              break;
294            case PARAMETER_TYPE_Int:
295              param->Set_Value((int)strtol(inmap->value,NULL,10));
296              break;
297            case PARAMETER_TYPE_Double:
298            case PARAMETER_TYPE_Degree:
299              param->Set_Value((double)strtod(inmap->value,NULL));
300              break;
301            case PARAMETER_TYPE_String:
302              param->Set_Value(CSG_String(inmap->value));
303              break;
304            case PARAMETER_TYPE_FilePath:
305              param->Set_Value(CSG_String(inmap->value));
306              break;
307            case PARAMETER_TYPE_FixedTable:
308              {
309                CSG_Table Table(inmap->value);
310                param->asTable()->Assign_Values(&Table);
311              }
312              break;
313            case PARAMETER_TYPE_Choice:
314              {
315                int val=(int)strtol(inmap->value,(char**)NULL,10);
316                if(val==0 && strncasecmp(inmap->value,"0",1)!=0)
317                  param->Set_Value(CSG_String(inmap->value));
318                else
319                  param->Set_Value(val);
320              }
321              break;
322            default:
323              break;
324            }
325        }else{
326          if(param->Get_Type()==PARAMETER_TYPE_Range){
327            inmap=getMap(argument,(CSG_String(param->Get_Identifier())+"_MIN").b_str());
328            if(inmap!=NULL)
329              param->asRange()->Set_LoVal(strtod(inmap->value,NULL));
330            inmap=getMap(argument,(CSG_String(param->Get_Identifier())+"_MAX").b_str());
331            if(inmap!=NULL)
332              param->asRange()->Set_HiVal(strtod(inmap->value,NULL));       
333          }
334          if(inmap==NULL){
335            param->Restore_Default();
336          }
337        }
338      }
339  }
340
341  for(int k=0;k<pc;k++){
342    CSG_Parameter * param=params->Get_Parameter(k);
343    if( param->is_Input() )
344      if(!sagaLoadInput(param,argument)){
345        fprintf(stderr,"%s %d \n",__FILE__,__LINE__);
346        return false;
347      }
348  }
349  return true;
350}
351
352/**
353 * Save all values outputed by a SAGA-GIS module invocation to files
354 *
355 * @param params the parameters list
356 * @param main_conf the conf maps containing the main.cfg settings
357 * @param outputs the maps to set the generated_file for each output
358 */
359bool sagaSaveOutputs(CSG_Parameters *params,maps* main_conf,maps** outputs)
360{
361  for(int j=0; j<params->Get_Count(); j++)
362    {
363      CSG_Parameter *param = params->Get_Parameter(j);
364      maps* cMaps=getMaps(*outputs,CSG_String(param->Get_Identifier()).b_str());
365      // Specific TIN case
366      if(cMaps==NULL && CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("tin")))
367        cMaps=getMaps(*outputs,(CSG_String(param->Get_Identifier())+"_POINTS").b_str());
368      if(cMaps!=NULL){
369        map* tmpPath=getMapFromMaps(main_conf,"main","tmpPath");
370        map* sid=getMapFromMaps(main_conf,"lenv","usid");
371        const char *file_ext=sagaGetDefaultExt(param);
372
373        if( param->is_Input() )
374          {
375            if( param->is_DataObject() )
376              {
377                CSG_Data_Object *pObject = param->asDataObject();
378               
379                if( pObject && pObject->is_Modified() && SG_File_Exists(pObject->Get_File_Name()) )
380                  {
381                    pObject->Save(pObject->Get_File_Name());
382                    addToMap(cMaps->content,"generated_file",CSG_String(pObject->Get_File_Name()).b_str());
383                  }
384              }
385           
386            else if( param->is_DataObject_List() )
387              {
388                for(int i=0; i<param->asList()->Get_Count(); i++)
389                  {
390                    CSG_Data_Object *pObject = param->asList()->asDataObject(i);
391                   
392                    if( pObject->is_Modified() && SG_File_Exists(pObject->Get_File_Name()) )
393                      {
394                        pObject->Save(pObject->Get_File_Name());
395                        setMapArray(cMaps->content,"generated_file",i,CSG_String(pObject->Get_File_Name()).b_str());
396                      }
397                  }
398              }
399          }
400        else
401          if( param->is_Output() )
402            {
403              char *realFileName=(char*)malloc((strlen(file_ext)+strlen(sid->value)+strlen(cMaps->name)+14)*sizeof(char));
404              char *fullFileName=(char*)malloc((strlen(file_ext)+strlen(sid->value)+strlen(cMaps->name)+strlen(tmpPath->value)+16)*sizeof(char));
405              sprintf(realFileName,"Output_%s_%s_%d",cMaps->name,sid->value,sagaOutputCounter);
406              sprintf(fullFileName,"%s/Output_%s_%s_%d.%s",tmpPath->value,cMaps->name,sid->value,sagaOutputCounter,file_ext);
407              sagaOutputCounter+=1;
408              wxString fileName(fullFileName);
409              addToMap(cMaps->content,"generated_name",realFileName);
410              free(realFileName);
411              free(fullFileName);
412
413              if( param->is_DataObject() )
414                {
415                  if( param->asDataObject() )
416                    {
417                      param->asDataObject()->Save(&fileName);
418                      addToMap(cMaps->content,"generated_file",CSG_String(param->asDataObject()->Get_File_Name()).b_str());
419                    }
420                }
421           
422              else if( param->is_DataObject_List() )
423                {
424                  CSG_Strings   fileNames;
425               
426                  while( fileName.Length() > 0 )
427                    {
428                      CSG_String current_file(&fileName);
429                      current_file = current_file.BeforeFirst(';');
430                      if( current_file.Length() > 0 )
431                        {
432                          fileNames += current_file;
433                          fileName = fileName.AfterFirst(';');
434                        }
435                      else
436                        {
437                          fileNames += &fileName;
438                          fileName.Clear();
439                        }
440                    }
441                 
442                  int nFileNames = param->asList()->Get_Count() <= fileNames.Get_Count() ? fileNames.Get_Count() : fileNames.Get_Count() - 1;
443                  for(int i=0; i<param->asList()->Get_Count(); i++)
444                    {
445                      fileNames[i].Trim();
446                      if( i < nFileNames )
447                        {
448                          param->asList()->asDataObject(i)->Save(fileNames[i]);
449                        }
450                      else
451                        {
452                          param->asList()->asDataObject(i)->Save(CSG_String::Format(SG_T("%s_%0*d"),
453                                                                                    fileNames[fileNames.Get_Count() - 1].c_str(),
454                                                                                    SG_Get_Digit_Count(param->asList()->Get_Count()),
455                                                                                    1 + i - nFileNames
456                                                                                    ));
457                        }
458                      setMapArray(cMaps->content,"generated_file",i,
459                                  CSG_String(param->asList()->asDataObject(i)->Get_File_Name()).b_str());
460                    }
461                }
462            }
463      }
464    }
465  return( true );
466}
467
468/**
469 * Invoke the execution of a SAGA-GIS module.
470 *
471 * @param main_conf the conf maps containing the main.cfg settings
472 * @param lib_name the SAGA-GIS library name
473 * @param module_name the SAGA-GIS module name
474 * @param arguments the map containing the arguments to pass to the module
475 * @param outputs default to NULL, contains the maps to fill with the result
476 */
477int sagaExecuteCmd(maps** main_conf,const char* lib_name,const char* module_name,map* arguments,maps** outputs=NULL){
478  int res=SERVICE_FAILED;
479
480  CSG_Module_Library * library=SG_Get_Module_Library_Manager().Get_Library(CSG_String(lib_name),true);
481  if( library == NULL){
482    char tmp[255];
483    sprintf(tmp,"Counld not load the %s SAGA library",lib_name);
484    setMapInMaps(*main_conf,"lenv","message",tmp);
485    res=SERVICE_FAILED;
486    return res;
487  }
488
489  CSG_Module * module=library->Get_Module(atoi(module_name));
490  if(module == NULL){
491    char tmp[255];
492    sprintf(tmp,"Counld not load the %s module from the %s SAGA library",module_name,lib_name);
493    setMapInMaps(*main_conf,"lenv","message",tmp);
494    res=SERVICE_FAILED;
495    return res;
496  }
497
498  CSG_Parameters * params=module->Get_Parameters();
499  if(!params){
500    char tmp[255];
501    sprintf(tmp,"Counld not find any param for the %s module from the %s SAGA library",module_name,lib_name);
502    setMapInMaps(*main_conf,"lenv","message",tmp);
503    res=SERVICE_FAILED;
504    return res;
505  }
506 
507  sagaSetParameters(params,arguments);
508
509  module->Update_Parameter_States();
510
511  bool retval=false;
512  if(module->On_Before_Execution()){
513    retval=module->Execute();
514    module->On_After_Execution();
515  }
516 
517  if(retval && outputs!=NULL){
518    sagaSaveOutputs(module->Get_Parameters(),*main_conf,outputs);
519    SG_Get_Data_Manager().Delete_Unsaved();
520    return SERVICE_SUCCEEDED;
521  }
522
523  return SERVICE_FAILED;
524
525}
526
527/**
528 * Export a SAGA-GIS Shapes to a file in a specific format (GML,KML,GeoJSON).
529 * saga_cmd io_gdal 4 -FILE my.format -SHAPES my.shp -FORMAT XXX
530 *
531 * @param main_conf the conf maps containing the main.cfg settings
532 * @param in the output maps to fill with the resulting file
533 */
534int sagaExportOGR(maps** conf, maps** in){
535  map* mtype=getMap((*in)->content,"mimeType");
536  map* gfile=getMap((*in)->content,"generated_file");
537  char* fext=NULL;
538  map* arg=NULL;
539  if(strncasecmp(mtype->value,"text/xml",8)==0){
540    fext=zStrdup("xml");
541  }
542  else if(strncasecmp(mtype->value,"application/json",16)==0){
543    fext=zStrdup("json");
544  }
545  else{
546    fext=zStrdup("kml");
547  }
548  char* tmpName=(char*)malloc((strlen(gfile->value)+2)*sizeof(char));
549  strncpy(tmpName,gfile->value,(strlen(gfile->value)-3)*sizeof(char));
550  strncpy(&tmpName[0]+(strlen(gfile->value)-3),fext,(strlen(fext))*sizeof(char));
551  tmpName[strlen(fext)+(strlen(gfile->value)-3)]=0;
552  arg=createMap("SHAPES",gfile->value);
553  addToMap(arg,"FILE",tmpName);
554  if(strncasecmp(mtype->value,"text/xml",8)==0){
555    addToMap(arg,"FORMAT","GML");
556  }
557  else if(strncasecmp(mtype->value,"application/json",16)==0){
558    addToMap(arg,"FORMAT","GeoJSON");
559  }
560  else{
561    addToMap(arg,"FORMAT","LIBKML");
562  }
563  free(fext);
564  free(gfile->value);
565  gfile->value=zStrdup(tmpName);
566  free(tmpName);
567 
568  sagaExecuteCmd(conf,"io_gdal","4",arg);
569  freeMap(&arg);
570  free(arg);
571}
572
573/**
574 * Export a SAGA-GIS pointcloud to a las file.
575 * saga_cmd io_shapes_las 0 -POINTS my.spc -FILE my.las
576 *
577 * @param main_conf the conf maps containing the main.cfg settings
578 * @param in the output maps to fill with the resulting file
579 */
580void sagaExportPC(maps** conf, maps** in){
581  map* mtype=getMap((*in)->content,"mimeType");
582  map* gfile=getMap((*in)->content,"generated_file");
583  char* fext="las";
584  map* arg=NULL;
585  char* tmpName=(char*)malloc((strlen(gfile->value)+2)*sizeof(char));
586  strncpy(tmpName,gfile->value,(strlen(gfile->value)-3)*sizeof(char));
587  strncpy(&tmpName[0]+(strlen(gfile->value)-3),fext,(strlen(fext))*sizeof(char));
588  tmpName[strlen(fext)+(strlen(gfile->value)-3)]=0;
589  arg=createMap("POINTS",gfile->value);
590  addToMap(arg,"FILE",tmpName);
591  free(gfile->value);
592  gfile->value=zStrdup(tmpName);
593  sagaExecuteCmd(conf,"io_shapes_las","0",arg);
594  freeMap(&arg);
595  free(arg);
596  free(tmpName);
597}
598
599/**
600 * Export a SAGA-GIS Grid to a file in a specific format (tiff,hdr,aa).
601 * saga_cmd io_gdal 1 -FILE my.format -GRIDS my.sgrd -FORMAT XXX
602 *
603 * @param main_conf the conf maps containing the main.cfg settings
604 * @param in the output maps to fill with the resulting file
605 */
606int sagaExportGDAL(maps** conf, maps** in/*,CSG_Parameter* param*/){
607  map* mtype=getMap((*in)->content,"extension");
608  map* gfile=getMap((*in)->content,"generated_file");
609  char* fext=NULL;
610  map* arg;
611
612  if(mtype!=NULL)
613    fext=zStrdup(mtype->value);
614  else{
615    fext=zStrdup("tiff");
616  }
617
618  mtype=getMap((*in)->content,"mimeType");
619  if(strncasecmp(mtype->value,"image/tiff",10)==0){
620    arg=createMap("FORMAT","1");
621  }
622  else if(strncasecmp(mtype->value,"application/x-ogc-envi",22)==0){
623    arg=createMap("FORMAT","ENVI .hdr Labelled");
624  }
625  else{
626    arg=createMap("FORMAT","ARC Digitized Raster Graphics");
627  }
628
629  if(gfile!=NULL){
630    char* tmpName=(char*)malloc((strlen(gfile->value)+1)*sizeof(char));
631    strncpy(tmpName,gfile->value,(strlen(gfile->value)-4)*sizeof(char));
632    strncpy(&tmpName[0]+(strlen(gfile->value)-4),fext,(strlen(fext))*sizeof(char));
633    tmpName[strlen(fext)+(strlen(gfile->value)-4)]=0;
634    addToMap(arg,"FILE",tmpName);
635    addToMap(arg,"GRIDS",gfile->value);
636    free(tmpName);
637    free(fext);
638    free(gfile->value);
639    map* tmp=getMap(arg,"FILE");
640    gfile->value=zStrdup(tmp->value);
641    sagaExecuteCmd(conf,"io_gdal","1",arg);
642  }
643  else{
644    // Empty result
645    return true;
646  }
647  freeMap(&arg);
648  free(arg);
649}
650
651/**
652 * Export a SAGA-GIS TIN to a file in a specific format (GML,KML,GeoJSON).
653 * Exporting TIN produce 5 separated files (POINTS, CENTER, EDGES, TRIANGLES
654 * and POLYGONS). Even if a client can choose which result it want to have,
655 * SAGA-GIS module will be invoked in a way that it will produce in any case
656 * each possible outputs. The selection of a specific output is made in the
657 * ZOO-Kernel itself and not specifically at this level.
658 * saga_cmd tin_tools 3 -TIN my.shp -POINTS p.shp ...
659 *
660 * @param conf the conf maps containing the main.cfg settings
661 * @param in the output maps to fill with the resulting file
662 * @see sagaExportOGR
663 */
664int sagaExportTIN(maps** conf, maps** in,const char* tname/*,CSG_Parameter* param*/){
665  map* mtype=getMap((*in)->content,"mimeType");
666  map* gfile=getMap((*in)->content,"generated_file");
667  char* fext="shp";
668  map* arg=createMap("TIN",gfile->value);
669
670  char* tinOut[5]={
671    "POINTS",
672    "CENTER",
673    "EDGES",
674    "TRIANGLES",
675    "POLYGONS"
676  };
677  maps* resouts=NULL;
678
679  int i=0;
680  for(i=0;i<5;i++){
681    char* tmpName=(char*)malloc((strlen(gfile->value)+strlen(tinOut[i])+4)*sizeof(char));
682    strncpy(tmpName,gfile->value,(strlen(gfile->value)-3)*sizeof(char));
683    char *tmpSubName=(char*) malloc((strlen(tinOut[i])+3)*sizeof(char));
684    sprintf(tmpSubName,"_%s.",tinOut[i]);
685    strncpy(&tmpName[0]+(strlen(gfile->value)-4),tmpSubName,(strlen(tmpSubName))*sizeof(char));
686    strncpy(&tmpName[0]+(strlen(gfile->value)+strlen(tmpSubName)-4),fext,(strlen(fext))*sizeof(char));
687    tmpName[strlen(fext)+(strlen(gfile->value)+strlen(tmpSubName)-4)]=0;
688
689    maps* louts=(maps*)malloc(MAPS_SIZE);
690    louts->name=zStrdup(tinOut[i]);
691    louts->content=createMap("mimeType","UNKOWN");
692    louts->next=NULL;
693   
694    addToMap(arg,tinOut[i],tmpName);
695   
696    free(tmpName);
697    if(resouts==NULL)
698      resouts=dupMaps(&louts);
699    else
700      addMapsToMaps(&resouts,louts);
701    freeMaps(&louts);
702    free(louts);
703  }
704 
705  sagaExecuteCmd(conf,"tin_tools","3",arg,&resouts);
706
707  for(i=0;i<5;i++){
708    map* generatedFile=getMapFromMaps(resouts,tinOut[i],"generated_file");
709    setMapInMaps(*in,(CSG_String(tname)+"_"+tinOut[i]).b_str(),"generated_file",generatedFile->value);
710    maps* cout=getMaps(*in,(CSG_String(tname)+"_"+tinOut[i]).b_str());
711    sagaExportOGR(conf,&cout);
712  }
713  return true;
714}
715
716/**
717 * Import GDAL Datasource into SAGA-GIS.
718 * saga_cmd io_gdal 0 -TRANSFORM 0 -FILES my.format -GRIDS /tmpPath/MyGridXXX.sgrd
719 *
720 * @param conf the conf maps containing the main.cfg settings
721 * @param in in the inputs maps
722 */
723int sagaImportGDAL(maps** conf, maps** in){
724  map* l=getMap((*in)->content,"length");
725  bool shouldClean=false;
726  if(l==NULL){
727    l=createMap("length","1");
728    shouldClean=true;
729  }
730  int len=strtol(l->value,NULL,10);
731  int i=0;
732  for(i=0;i<len;i++){
733    map* arg=createMap("TRANSFORM","0");
734    addToMap(arg,"INTERPOL","4");
735    map* v=getMapArray((*in)->content,"cache_file",i);
736    if(v!=NULL)
737      addToMap(arg,"FILES",v->value);
738    addToMap(arg,"GRIDS","");
739
740    maps* louts=(maps*)malloc(MAPS_SIZE);
741    louts->name=zStrdup("GRIDS");
742    louts->content=createMap("mimeType","UNKOWN");
743    louts->next=NULL;
744
745    sagaExecuteCmd(conf,"io_gdal","0",arg,&louts);
746
747    map* tmp=getMapFromMaps(louts,"GRIDS","generated_file");
748    setMapArray((*in)->content,"saga_value",i,tmp->value);
749
750    freeMaps(&louts);
751    free(louts);
752    freeMap(&arg);
753    free(arg);
754  }
755  if(shouldClean){
756    freeMap(&l);
757    free(l);
758  }
759}
760
761/**
762 * Import OGR Datasource into SAGA-GIS.
763 * saga_cmd io_gdal 3 -SHAPES my.shp -FILES my.format
764 *
765 * @param conf the conf maps containing the main.cfg settings
766 * @param in in the inputs maps
767 */
768int sagaImportOGR(maps** conf, maps** in){
769  char *ext;
770  map* arg;
771  map* l=getMap((*in)->content,"length");
772  bool shouldClean=false;
773  if(l==NULL){
774    l=createMap("length","1");
775    shouldClean=true;
776  }
777  int len=strtol(l->value,NULL,10);
778  int i=0;
779  for(i=0;i<len;i++){
780    map* v=getMapArray((*in)->content,"cache_file",i);
781    arg=createMap("SHAPES","");
782    if(v!=NULL)
783      addToMap(arg,"FILES",v->value);
784
785    maps* louts=(maps*)malloc(MAPS_SIZE);
786    louts->name=zStrdup("SHAPES");
787    louts->content=createMap("mimeType","UNKOWN");
788    louts->next=NULL;
789
790    sagaExecuteCmd(conf,"io_gdal","3",arg,&louts);
791
792    map* tmp=getMapFromMaps(louts,"SHAPES","generated_file");
793    setMapArray((*in)->content,"saga_value",i,tmp->value);
794
795    freeMaps(&louts);
796    free(louts);
797    freeMap(&arg);
798    free(arg);
799  }
800  if(shouldClean){
801    freeMap(&l);
802    free(l);
803  }
804}
805
806/**
807 * Import TIN into SAGA-GIS. Calling this function suppose that sagaImportOGR
808 * was called first.
809 * saga_cmd tin_tools 2 -SHAPES myShapes.shp -TIN myTin.shp
810 *
811 * @param conf the conf maps containing the main.cfg settings
812 * @param in in the inputs maps
813 * @see sagaImportOGR
814 */
815bool sagaImportTIN(maps** conf, maps** in){
816  char *ext;
817  map* arg;
818  map* l=getMap((*in)->content,"length");
819  bool shouldClean=false;
820  if(l==NULL){
821    l=createMap("length","1");
822    shouldClean=true;
823  }
824  int len=strtol(l->value,NULL,10);
825  int i=0;
826  for(i=0;i<len;i++){
827    map* v=getMapArray((*in)->content,"saga_value",i);
828    arg=createMap("TIN","");
829    if(v!=NULL)
830      addToMap(arg,"SHAPES",v->value);
831    maps* louts=(maps*)malloc(MAPS_SIZE);
832    louts->name=zStrdup("TIN");
833    louts->content=createMap("mimeType","UNKOWN");
834    louts->next=NULL;
835    sagaExecuteCmd(conf,"tin_tools","2",arg,&louts);
836    map* tmp=getMapFromMaps(louts,"TIN","generated_file");
837    v=getMapArray((*in)->content,"saga_value",i);
838    if(tmp!=NULL){
839      if(v!=NULL){
840        free(v->value);
841        v->value=zStrdup(tmp->value);
842      }
843      else
844        setMapArray((*in)->content,"saga_value",i,tmp->value);
845    }
846    freeMaps(&louts);
847    free(louts);
848    freeMap(&arg);
849    free(arg);
850  }
851  if(shouldClean){
852    freeMap(&l);
853    free(l);
854  }
855  return true;
856}
857
858/**
859 * Import table into SAGA-GIS.
860 * saga_cmd io_table 1 -TABLE myTable -FILENAME myFile -SEPARATOR 2
861 *
862 * @param conf the conf maps containing the main.cfg settings
863 * @param in in the inputs maps
864 */
865int sagaImportTable(maps** conf, maps** in){
866  char *ext;
867  map* arg;
868  map* l=getMap((*in)->content,"length");
869  bool shouldClean=false;
870  if(l==NULL){
871    l=createMap("length","1");
872    shouldClean=true;
873  }
874  int len=strtol(l->value,NULL,10);
875  int i=0;
876  for(i=0;i<len;i++){
877
878    // Create and fill arg map
879    arg=createMap("SEPARATOR","2");
880    addToMap(arg,"TABLE","");
881    map* v=getMapArray((*in)->content,"cache_file",i);
882    if(v!=NULL)
883      addToMap(arg,"FILENAME",v->value);
884
885    // Create the output maps
886    maps* louts=(maps*)malloc(MAPS_SIZE);
887    louts->name=zStrdup("TABLE");
888    louts->content=createMap("mimeType","UNKOWN");
889    louts->next=NULL;
890
891    // Execute the saga command
892    sagaExecuteCmd(conf,"io_table","1",arg,&louts);
893
894    // Fetch result and add it to the original map as saga_value
895    map* tmp=getMapFromMaps(louts,"TABLE","generated_file");
896    setMapArray((*in)->content,"saga_value",i,tmp->value);
897
898    // Cleanup
899    freeMaps(&louts);
900    free(louts);
901    freeMap(&arg);
902    free(arg);
903
904  }
905  // Cleanup if required
906  if(shouldClean){
907    freeMap(&l);
908    free(l);
909  }
910}
911
912/**
913 * Import las file as pointcloud into SAGA-GIS.
914 * saga_cmd io_shapes_las 1 -POINTS my.spc -FILENAME my.las
915 *
916 * @param conf the conf maps containing the main.cfg settings
917 * @param in in the inputs maps
918 */
919int sagaImportPC(maps** conf, maps** in){
920  char *ext;
921  map* arg;
922  map* l=getMap((*in)->content,"length");
923  bool shouldClean=false;
924  if(l==NULL){
925    l=createMap("length","1");
926    shouldClean=true;
927  }
928  int len=strtol(l->value,NULL,10);
929  int i=0;
930  for(i=0;i<len;i++){
931
932    // Create and fill arg map
933    arg=createMap("POINTS","");
934    map* v=getMapArray((*in)->content,"cache_file",i);
935    if(v!=NULL)
936      addToMap(arg,"FILES",v->value);
937
938    // Create the output maps
939    maps* louts=(maps*)malloc(MAPS_SIZE);
940    louts->name=zStrdup("POINTS");
941    louts->content=createMap("mimeType","UNKOWN");
942    louts->next=NULL;
943
944    // Execute the saga command
945    sagaExecuteCmd(conf,"io_shapes_las","1",arg,&louts);
946
947    // Fetch result and add it to the original map as saga_value
948    map* tmp=getMapFromMaps(louts,"POINTS","generated_file");
949    setMapArray((*in)->content,"saga_value",i,tmp->value);
950
951    // Cleanup
952    freeMaps(&louts);
953    free(louts);
954    freeMap(&arg);
955    free(arg);
956
957  }
958  // Cleanup if required
959  if(shouldClean){
960    freeMap(&l);
961    free(l);
962  }
963}
964
965/**
966 * Load and invoke a SAGA-GIS module defined in a service metadata definitions.
967 * Load all the input data into SAGA-GIS using io_gdal, io_tables and
968 * io_shapes_las for SAGA grids/shapes, tables and pointcloud respectively.
969 * Load and run the module from its library and invoke it using the data
970 * imported in SAGA-GIS at first stage. After the execution, export the outputs
971 * to files using io_gdal and io_shapes_las for grids/shapes and pointcloud
972 * respectively.
973 *
974 * @param main_conf the conf maps containing the main.cfg settings
975 * @param request the map containing the HTTP request
976 * @param s the service structure
977 * @param inputs the maps containing the inputs
978 * @param outputs the maps containing the outputs
979 */
980int zoo_saga_support(maps** main_conf,map* request,service* s,maps** inputs,maps** outputs){
981  int res=SERVICE_FAILED;
982  if( !wxInitialize() ){
983    fprintf(stderr,"initialisation failed");
984    return SERVICE_FAILED;
985  }
986  setlocale(LC_NUMERIC, "C");
987  static bool g_bShow_Messages = false;
988
989  dumpMapsValuesToFiles(main_conf,inputs);
990
991  SagaWatcher watcher=SagaWatcher();
992  watcher.SetConf(main_conf);
993
994  SG_Set_UI_Callback(Get_Callback(watcher));
995
996  int n = SG_Get_Module_Library_Manager().Add_Directory(wxT(MODULE_LIBRARY_PATH),false);
997  if( SG_Get_Module_Library_Manager().Get_Count() <= 0 ){
998    setMapInMaps(*main_conf,"lenv","message","Could not load any SAGA tool library");
999    res=SERVICE_FAILED;
1000    return res;
1001  }
1002
1003  map* serviceProvider=getMap(s->content,"serviceProvider");
1004
1005  // Load the SAGA-GIS library corresponding to the serviceProvider
1006  CSG_Module_Library * library=SG_Get_Module_Library_Manager().Get_Library(CSG_String(serviceProvider->value),true);
1007  if( library == NULL){
1008    char tmp[255];
1009    sprintf(tmp,"Counld not load the %s SAGA library",serviceProvider->value);
1010    setMapInMaps(*main_conf,"lenv","message",tmp);
1011    res=SERVICE_FAILED;
1012    return res;
1013  }
1014 
1015  // Load the SAGA-GIS module corresponding to the service name from the library
1016  CSG_Module * module=library->Get_Module(atoi(s->name));
1017  if(module == NULL){
1018    char tmp[255];
1019    sprintf(tmp,"Counld not load the %s module from the %s SAGA library",
1020            s->name,serviceProvider->value);
1021    setMapInMaps(*main_conf,"lenv","message",tmp);
1022    res=SERVICE_FAILED;
1023    return res;
1024  }
1025
1026  // Load all the parameters defined for the module
1027  CSG_Parameters * params=module->Get_Parameters();
1028  int pc=params->Get_Count();
1029  if(!params){
1030    char tmp[255];
1031    sprintf(tmp,"Counld not find any param for the %s module from the %s SAGA library",
1032            s->name,serviceProvider->value);
1033    setMapInMaps(*main_conf,"lenv","message",tmp);
1034    res=SERVICE_FAILED;
1035    return res;
1036  }
1037
1038  // Loop over each inputs to transform raster files to grid when needed,
1039  // import tables, shapes or point clouds
1040  for(int k=0;k<pc;k++){
1041    CSG_Parameter * param=params->Get_Parameter(k);
1042    if(param!=NULL && !param->is_Output()){
1043      maps* inmap=getMaps(*inputs,CSG_String(param->Get_Identifier()).b_str());
1044      if(inmap!=NULL){
1045        map* tmp=getMap(inmap->content,"value");
1046        if(tmp==NULL || strncasecmp(tmp->value,"NULL",4)!=0){
1047          if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("grid"))){
1048            sagaImportGDAL(main_conf,&inmap);
1049          }
1050          else if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("tin"))){
1051            sagaImportOGR(main_conf,&inmap);
1052            sagaImportTIN(main_conf,&inmap);
1053          }
1054          else if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("shapes"))){
1055            sagaImportOGR(main_conf,&inmap);
1056          }
1057          else{
1058            if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("table"))){
1059              sagaImportTable(main_conf,&inmap);
1060            }
1061            else
1062              if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("points"))){
1063                sagaImportPC(main_conf,&inmap);
1064              }
1065          }
1066        }
1067      }
1068    }
1069  }
1070
1071  // Create a map conraining arguments to pass to the SAGA-GIS module
1072  // Fetch all input value (specifically for data imported into SAGA-GIS)
1073  maps* inp=*inputs;
1074  int k=0;
1075  map* cParams=NULL;
1076  while(inp!=NULL){
1077    map* len=getMap(inp->content,"length");
1078    bool shouldClean=false;
1079    if(len==NULL){
1080      len=createMap("length","1");
1081      shouldClean=true;
1082    }
1083    int len0=strtol(len->value,NULL,10);
1084    int i=0;
1085    char *cinput=NULL;
1086    int clen=0;
1087    for(i=0;i<len0;i++){
1088      map* val=getMapArray(inp->content,"saga_value",i);
1089      if(val==NULL)
1090        val=getMapArray(inp->content,"value",i);
1091      if(val!=NULL && strncasecmp(val->value,"NULL",4)!=0){
1092        if(cinput==NULL){
1093          cinput=zStrdup(val->value);
1094        }
1095        else{
1096          cinput=(char*)realloc(cinput,(clen+strlen(val->value)+1)*sizeof(char));
1097          strncpy(&cinput[0]+clen,";",1);
1098          strncpy(&cinput[0]+(clen+1),val->value,strlen(val->value));
1099          clen+=1;
1100        }
1101        clen+=strlen(val->value);
1102        cinput[clen]=0;
1103      }
1104    }
1105    if(cinput!=NULL && strncasecmp(cinput,"NULL",4)!=0){
1106      if(cParams==NULL)
1107        cParams=createMap(inp->name,cinput);
1108      else
1109        addToMap(cParams,inp->name,cinput);
1110      free(cinput);
1111    }
1112    inp=inp->next;
1113  }
1114
1115  // Fetch all output and define a resulting filename
1116  inp=*outputs;
1117  map* tmpPath=getMapFromMaps(*main_conf,"main","tmpPath");
1118  map* sid=getMapFromMaps(*main_conf,"lenv","usid");
1119  while(inp!=NULL){
1120    for(int k=0;k<pc;k++){
1121      CSG_Parameter * param=params->Get_Parameter(k);
1122      if(CSG_String(param->Get_Identifier()).Cmp(inp->name)==0){
1123        const char *file_ext=sagaGetDefaultExt(param);
1124        char *fileName=(char*)malloc((strlen(file_ext)+strlen(sid->value)+strlen(inp->name)+strlen(tmpPath->value)+11)*sizeof(char));
1125        sprintf(fileName,"%s/Output_%s_%s.%s",tmpPath->value,inp->name,sid->value,file_ext);
1126        if(cParams==NULL)
1127          cParams=createMap(inp->name,fileName);
1128        else
1129          addToMap(cParams,inp->name,fileName);
1130      }
1131    }
1132    inp=inp->next;
1133  }
1134
1135  sagaSetParameters(params,cParams);
1136
1137  module->Update_Parameter_States();
1138 
1139  bool retval=false;
1140  if(module->On_Before_Execution()){
1141    retval=module->Execute();
1142    module->On_After_Execution();
1143  }
1144
1145  sagaSaveOutputs(params,*main_conf,outputs);
1146
1147  // Loop over each outputs to transform grid to raster file when needed,
1148  // export tables, shapes or point clouds
1149  for(int k=0;k<pc;k++){
1150    CSG_Parameter * param=params->Get_Parameter(k);
1151    if(param!=NULL && param->is_Output()){
1152      maps* inmap=getMaps(*outputs,CSG_String(param->Get_Identifier()).b_str());
1153      if(inmap!=NULL){
1154        if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("grid"))
1155           || CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("data_object"))){
1156          sagaExportGDAL(main_conf,&inmap);
1157        }else{
1158          if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("shapes"))){
1159            sagaExportOGR(main_conf,&inmap);
1160          }
1161          else{
1162            if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("table"))){
1163            }
1164            else{
1165              if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("tin"))){
1166                sagaExportTIN(main_conf,&inmap,"TIN");
1167              }
1168              else
1169                if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("points"))){
1170                  sagaExportPC(main_conf,&inmap);
1171              }
1172            }
1173          }
1174        }
1175      }
1176      else if(CSG_String(param->Get_Type_Identifier()).Contains(CSG_String("tin"))){
1177        sagaExportTIN(main_conf,outputs,CSG_String(param->Get_Identifier()).b_str());
1178      }
1179             
1180    }
1181  }
1182
1183  wxUninitialize();
1184
1185  return SERVICE_SUCCEEDED;
1186}
Note: See TracBrowser for help on using the repository browser.

Search

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png