Forked from Gaetano Raffaele / moringa
Source project has a limited visibility.
classificationWorkflow.py 18.90 KiB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
import ogr
import sys
import subprocess
import platform
import numpy as np
import os
import csv

from mtdUtils import queuedProcess, cloneVectorDataStructure, fieldToArray, mergeShapefiles

def getFeaturesFields(shp,flds_pref):

    ds = ogr.Open(shp, 0)
    ly = ds.GetLayer(0)

    flds = []
    ldfn = ly.GetLayerDefn()
    for n in range(ldfn.GetFieldCount()):
        fn = ldfn.GetFieldDefn(n).name
        if fn.startswith(tuple(flds_pref)):
            flds.append(fn)

    ds = None

    return flds

def roughFix(shp,flds):

    ds = ogr.Open(shp,1)
    ly = ds.GetLayer(0)

    arr = np.empty([ly.GetFeatureCount(), len(flds)])
    i = 0
    for f in ly:
        j = 0
        for fld in flds:
            arr[i,j] = f.GetFieldAsDouble(fld)
            j += 1
        i += 1

    #R-like rough fix
    arr[np.where(arr==-9999.0)] = np.nan
    mns = np.tile(np.nanmean(arr,axis=0),[ly.GetFeatureCount(),1])
    arr[np.isnan(arr)] = mns[np.isnan(arr)]

    ly.ResetReading()
    i = 0
    for f in ly:
        j = 0
        for fld in flds:
            f.SetField(fld,arr[i, j])
            ly.SetFeature(f)
            j += 1
        i += 1

    ds = None

    return

def baseTrainingCmd(shp,stat_file,code,flds,params,model_file,confmat_file):

    # Platform dependent parameters
    if platform.system() == 'Linux':
        sh = False
    elif platform.system() == 'Windows':
        sh = True
    else:
        sys.exit("Platform not supported!")
    if type(shp) == str:
        shp = [shp]

    if platform.system() == 'Linux':
        cmd = ['otbcli_TrainVectorClassifier', '-io.vd'] + shp + ['-io.stats', stat_file, '-io.confmatout', confmat_file, '-cfield', code, '-io.out', model_file, '-feat'] + flds + params
        subprocess.call(cmd,shell=sh)
    elif platform.system() == 'Windows':
        import otbApplication
        app = otbApplication.Registry.CreateApplication('TrainVectorClassifier')
        app.SetParameterStringList('io.vd', shp)
        app.SetParameterString('io.stats', stat_file)
        app.SetParameterString('io.confmatout', confmat_file)
        app.SetParameterString('io.out', model_file)
        app.UpdateParameters()
        app.SetParameterStringList('cfield', [code])
        app.SetParameterStringList('feat', flds)
        # Parse classification parameters string
        # WARNING: works for all classifier with single value parameters
        # (surely hangs on <string list> classification parameter types - e.g. -classifier.ann.sizes)
        cl_param_keys = params[0::2]
        cl_param_vals = params[1::2]
        for prk,prv in zip(cl_param_keys,cl_param_vals):
            app.SetParameterString(prk[1:],prv)
        app.UpdateParameters()
        app.ExecuteAndWriteOutput()
    else:
        sys.exit("Platform not supported!")

def baseClassifyCmd(shp,stat_file,model_file,code,flds,out_file,compute_confidence=False):
    # Platform dependent parameters
    if platform.system() == 'Linux':
        sh = False
    elif platform.system() == 'Windows':
        sh = True
    else:
        sys.exit("Platform not supported!")

    if platform.system() == 'Linux':
        cmd = ['otbcli_VectorClassifier', '-in', shp, '-instat', stat_file, '-model', model_file, '-cfield', code, '-feat'] + flds
        if out_file is not None:
            cmd += ['-out', out_file]
        if compute_confidence:
            cmd += ['-confmap', 1]
        subprocess.call(cmd,sh)
    elif platform.system() == 'Windows':
        import otbApplication
        app = otbApplication.Registry.CreateApplication('VectorClassifier')
        app.SetParameterString('in', shp)
        app.SetParameterString('instat', stat_file)
        app.SetParameterString('model', model_file)
        if out_file is not None:
            app.SetParameterString('out', out_file)
        if compute_confidence:
            app.SetParameterInt('confmap', 1)
        app.SetParameterString('cfield', code)
        app.UpdateParameters()
        app.SetParameterStringList('feat', flds)
        app.UpdateParameters()
        app.ExecuteAndWriteOutput()
    else:
        sys.exit('Platform not supported!')

def training(shp,code,model_fld,params,feat,feat_mode = 'list'):

    # Platform dependent parameters
    if platform.system() == 'Linux':
        sh = False
    elif platform.system() == 'Windows':
        sh = True
    else:
        sys.exit("Platform not supported!")

    if '-classifier' in params:
        classifier = params[params.index('-classifier') + 1]
    else:
        classifier = 'libsvm'
    model_file = model_fld + '/' + classifier + '_' + code + '.model'
    confmat_file = model_fld + '/' + classifier + '_' + code + '.confmat.txt'
    stat_file = model_fld + '/GT_stats.xml'

    if feat_mode == 'prefix':
        flds = getFeaturesFields(shp, feat)
    elif feat_mode == 'list':
        flds = feat
    else:
        sys.exit('ERROR: mode ' + feat_mode + ' not valid.')

    if platform.system() == 'Linux':
        cmd = ['otbcli_ComputeVectorFeaturesStatistics','-io.vd',shp,'-io.stats',stat_file,'-feat'] + flds
        subprocess.call(cmd,shell=sh)
    elif platform.system() == 'Windows':
        import otbApplication
        app = otbApplication.Registry.CreateApplication('ComputeVectorFeaturesStatistics')
        app.SetParameterStringList('io.vd', [shp])
        app.SetParameterString('io.stats', model_fld + '/GT_stats.xml')
        app.UpdateParameters()
        app.SetParameterStringList('feat',flds)
        app.ExecuteAndWriteOutput()
    else:
        sys.exit("Platform not supported!")

    if platform.system() == 'Linux':
        cmd = ['otbcli_TrainVectorClassifier', '-io.vd', shp, '-io.stats', model_fld + '/GT_stats.xml', '-io.confmatout', confmat_file, '-cfield', code, '-io.out', model_file, '-feat'] + flds + params
        subprocess.call(cmd,shell=sh)
    elif platform.system() == 'Windows':
        import otbApplication
        app = otbApplication.Registry.CreateApplication('TrainVectorClassifier')
        app.SetParameterStringList('io.vd', [shp])
        app.SetParameterString('io.stats', model_fld + '/GT_stats.xml')
        app.SetParameterString('io.confmatout', confmat_file)
        app.SetParameterString('io.out', model_file)
        app.UpdateParameters()
        app.SetParameterStringList('cfield', [code])
        app.SetParameterStringList('feat', flds)
        # Parse classification parameters string
        # WARNING: works for all classifier with single value parameters
        # (surely hangs on <string list> classification parameter types - e.g. -classifier.ann.sizes)
        cl_param_keys = params[0::2]
        cl_param_vals = params[1::2]
        for prk,prv in zip(cl_param_keys,cl_param_vals):
            app.SetParameterString(prk[1:],prv)
        app.UpdateParameters()
        app.ExecuteAndWriteOutput()
    else:
        sys.exit("Platform not supported!")

    return stat_file, model_file

def classify(shp_list,code,stat_file,model_file,out_fld,out_ext,feat,feat_mode = 'list',Nproc=1,compute_confidence=False):

    # Platform dependent parameters
    if platform.system() == 'Linux':
        sh = False
    elif platform.system() == 'Windows':
        sh = True
    else:
        sys.exit("Platform not supported!")

    if feat_mode == 'prefix':
        flds = getFeaturesFields(shp_list[0], feat)
    elif feat_mode == 'list':
        flds = feat
    else:
        sys.exit('ERROR: mode ' + feat_mode + ' not valid.')

    '''
    for shp in shp_list:
        #roughFix(shp, flds)
        if platform.system() == 'Linux':
            cmd = ['otbcli_VectorClassifier','-in',shp,'-instat',stat_file,'-model',model_file,'-out',out_file,'-cfield',code,'-feat'] + flds
            subprocess.call(cmd,shell=sh)
        elif platform.system() == 'Windows':
            import otbApplication
            app = otbApplication.Registry.CreateApplication('VectorClassifier')
            app.SetParameterString('in',shp)
            app.SetParameterString('instat', stat_file)
            app.SetParameterString('model', model_file)
            app.SetParameterString('out', out_file)
            app.SetParameterString('cfield', code)
            app.UpdateParameters()
            app.SetParameterStringList('feat',flds)
            app.UpdateParameters()
            app.ExecuteAndWriteOutput()
        else:
            sys.exit('Platform not supported!')

    return
    '''

    if platform.system() == 'Linux':
        cmd_list = []
        out_file_list = []
        for shp in shp_list:
            out_file = out_fld + '/' + os.path.basename(shp).replace('.shp', out_ext + '.shp')
            cmd = ['otbcli_VectorClassifier', '-in', shp, '-instat', stat_file, '-model', model_file, '-out', out_file,
                   '-cfield', code, '-feat'] + flds
            if compute_confidence:
                cmd += ['-confmap','1']
            cmd_list.append(cmd)
            out_file_list.append(out_file)
        queuedProcess(cmd_list,Nproc,shell=sh)
        return out_file_list
    elif platform.system() == 'Windows':
        out_file_list = []
        for shp in shp_list:
            out_file = out_fld + '/' + os.path.basename(shp).replace('.shp', out_ext + '.shp')
            import otbApplication
            app = otbApplication.Registry.CreateApplication('VectorClassifier')
            app.SetParameterString('in', shp)
            app.SetParameterString('instat', stat_file)
            app.SetParameterString('model', model_file)
            app.SetParameterString('out', out_file)
            app.SetParameterString('cfield', code)
            app.UpdateParameters()
            app.SetParameterStringList('feat', flds)
            if compute_confidence:
                app.SetParameterInt('confmap', 1)
            app.UpdateParameters()
            app.ExecuteAndWriteOutput()
            out_file_list.append(out_file)
        return out_file_list
    else:
        sys.exit('Platform not supported!')

def addField(filein, nameField, valueField, valueType=None,
             driver_name="ESRI Shapefile", fWidth=None):


    driver = ogr.GetDriverByName(driver_name)
    source = driver.Open(filein, 1)
    layer = source.GetLayer()
    layer_name = layer.GetName()
    layer_defn = layer.GetLayerDefn()
    field_names = [layer_defn.GetFieldDefn(i).GetName() for i in range(layer_defn.GetFieldCount())]
    if not valueType:
        try :
            int(valueField)
            new_field1 = ogr.FieldDefn(nameField, ogr.OFTInteger)
        except :
            new_field1 = ogr.FieldDefn(nameField, ogr.OFTString)
    elif valueType == str:
        new_field1 = ogr.FieldDefn(nameField, ogr.OFTString)
        sqlite_type = 'varchar'
    elif valueType == int:
        new_field1 = ogr.FieldDefn(nameField, ogr.OFTInteger)
        sqlite_type = 'int'
    elif valueType == float:
        new_field1 = ogr.FieldDefn(nameField, ogr.OFTFLOAT)
        sqlite_type = 'float'
    if fWidth:
        new_field1.SetWidth(fWidth)

    layer.CreateField(new_field1)
    for feat in layer:
        layer.SetFeature(feat)
        feat.SetField(nameField, valueField)
        layer.SetFeature(feat)

def splitShapefileByClasses(shp,code):
    ds = ogr.Open(shp)
    ly = ds.GetLayer(0)

    sep = {}
    for f in ly:
        cl = f.GetField(code)
        if cl not in sep.keys():
            sep[cl] = []
        sep[cl].append(f)

    ds_dict = {}
    for cl in sep.keys():
        fn = shp.replace('.shp','_' + code + '_' + str(cl) + '.shp')
        ds_dict[cl] = fn
        dsi = cloneVectorDataStructure(ds,fn)
        lyi = dsi.GetLayer(0)
        for f in sep[cl]:
            lyi.CreateFeature(f)
        dsi = None

    ds = None

    return ds_dict

def retrieveClassHierarchy(shp,code_list):
    nomen = []
    for code in code_list:
        nomen.append(fieldToArray(shp,code).astype(int))

    ds_dict = splitShapefileByClasses(shp, code_list[-1])

    h_dict = {}
    h_dict[code_list[0]] = ([0],[[ds_dict[x] for x in list(np.unique(nomen[-1]))]])
    for i in range(1,len(code_list)):
        cls = np.unique(nomen[i - 1])
        h_dict[code_list[i]] = (list(cls),[])
        for cl in cls:
            clist = list(np.unique(nomen[-1][np.where(nomen[i - 1] == cl)[0]]))
            h_dict[code_list[i]][1].append([ds_dict[x] for x in clist])

    return h_dict,ds_dict.values()

def Htraining(shp,code_list,model_fld,params,feat,feat_mode = 'list'):
    '''
    Hierarchical classification
    ---------------------------
    Input
    -----
    shp: str
        path of the training shapefile
    code_list: list
        list of the fields names for the different classification levels
    model_fld: str
        path to the folder where model files will be saved
    params: list
        list of parameter model to use with otbVectorTraining application
    feat: list or str
        features to use for classification
    feat_mode: list/prefix
        selection mode of the features
    ----------------------------------------------
    Output
    ------
    stat_file: str
        path to a stat_file to use to unskew model
    h_model_fld: str
        path to the folder where model files are
    '''
    # Platform dependent parameters
    if platform.system() == 'Linux':
        sh = False
    elif platform.system() == 'Windows':
        sh = True
    else:
        sys.exit("Platform not supported!")

    if '-classifier' in params:
        classifier = params[params.index('-classifier') + 1]
    else:
        classifier = 'libsvm'
    h_model_fld = model_fld + '/' + 'H-MODEL_' + '_'.join(code_list)
    if not os.path.exists(h_model_fld):
        os.mkdir(h_model_fld)
    stat_file = model_fld + '/GT_stats.xml'

    if feat_mode == 'prefix':
        flds = getFeaturesFields(shp, feat)
    elif feat_mode == 'list':
        flds = feat
    else:
        sys.exit('ERROR: mode ' + feat_mode + ' not valid.')

    # Statistics unskew
    if platform.system() == 'Linux':
        cmd = ['otbcli_ComputeVectorFeaturesStatistics','-io.vd',shp,'-io.stats',stat_file,'-feat'] + flds
        subprocess.call(cmd,shell=sh)
    elif platform.system() == 'Windows':
        import otbApplication
        app = otbApplication.Registry.CreateApplication('ComputeVectorFeaturesStatistics')
        app.SetParameterStringList('io.vd', [shp])
        app.SetParameterString('io.stats', stat_file)
        app.UpdateParameters()
        app.SetParameterStringList('feat',flds)
        app.ExecuteAndWriteOutput()
    else:
        sys.exit("Platform not supported!")

    # Computes classes hierarchy in a dictionnary
    h_dict, ds_list = retrieveClassHierarchy(shp,code_list)
    # Create models for each level
    with open(h_model_fld + '/h-model.csv',mode='wb') as h_model_file:
        writer = csv.writer(h_model_file)
        level = 'ROOT'
        last = h_dict.keys()[-1]
        for code in h_dict.keys():
            Nsb = len(h_dict[code][0])
            for i in range(Nsb):
                model_file = h_model_fld + '/' + classifier + '_' + code + '_' + str(h_dict[code][0][i]) + '.model'
                confmat_file = h_model_fld + '/' + classifier + '_' + code + '_' + str(h_dict[code][0][i]) + '.confmat.txt'
                baseTrainingCmd(h_dict[code][1][i],stat_file,code,feat,params,model_file,confmat_file)
                writer.writerow([level,str(h_dict[code][0][i]),model_file,code,str(code!=last)])
            level = code

    drv = ogr.GetDriverByName('ESRI Shapefile')
    for fn in ds_list:
        drv.DeleteDataSource(fn)

    return stat_file, h_model_fld

def Hclassify(shp_list,stat_file,h_model_fld,feat,out_fld,out_ext,feat_mode = 'list'):
    '''
    Hierarchical classification
    ---------------------------
    Input
    -----
    shp_list: list
        list of shapefile path to classify
    stat_file: str
        path to a stat_file to use to unskew model
    h_model_fld: str
        path to the folder where model files are
    feat: list or str
        features to use for classification
    out_fld: str
        path to the output folder
    out_ext: str
        output suffix
    feat_mode: list/prefix
        selection mode of the features
    ----------------------------------------------
    Output
    ------
    out_file_list : list
        list of the output shapefile paths
    '''
    if feat_mode == 'prefix':
        flds = getFeaturesFields(shp_list[0], feat)
    elif feat_mode == 'list':
        flds = feat
    else:
        sys.exit('ERROR: mode ' + feat_mode + ' not valid.')

    if not os.path.exists(h_model_fld):
        sys.exit('Folder ' + h_model_fld + ' not exists!')

    out_file_list = []
    for shp in shp_list:
        with open(h_model_fld + '/h-model.csv', mode='rb') as h_model_file:
            toProcess = []
            toDelete = []
            toMerge = []
            rdr = csv.reader(h_model_file)
            for row in rdr:
                if row[0] == 'ROOT':
                    in_shp = shp
                elif len(toProcess) > 0:
                    for i,process in enumerate(toProcess):
                        if process.endswith('_p' + row[0] + '_' + row[1] + '.shp') :
                            in_shp = toProcess.pop(i)
                else:
                    continue
                if os.path.exists(in_shp):
                    out_shp = in_shp.replace('.shp','_ROOT.shp') if row[0] == 'ROOT' else None
                    split_shp = out_shp if row[0] == 'ROOT' else in_shp
                    # Classification attempt with only one class raised an error,
                    # if so, apply the value class in consequence
                    with open(row[2]) as model:
                        lines = model.readlines()
                        to_classify = int(lines[1].split(' ')[0]) != 1
                    if to_classify :
                        baseClassifyCmd(in_shp,stat_file,row[2],'p'+row[3],flds,out_shp)
                    else :
                        addField(in_shp,'p'+row[3],int(lines[1].split(' ')[1]))
                    if out_shp is not None:
                        toDelete.append(out_shp)
                    #if there is a more detailed level than the current one, split the current 
                    #classification by classes to use as bases for next level 
                    if row[4] == 'True':
                        ds_dict = splitShapefileByClasses(split_shp,'p'+row[3])
                        [toProcess.insert(0,x) for x in ds_dict.values()]
                        toDelete.extend(ds_dict.values())
                    #last level of hierarchy classes, to merge
                    elif row[4] == 'False':
                        toMerge.append(in_shp)
        # Merge all resulting shapefiles, or rename if there is only one
        if len(toMerge) > 1 :
            out_file = out_fld + '/' + os.path.basename(shp).replace('.shp', out_ext + '.shp')
            mergeShapefiles(toMerge,out_file)
            out_file_list.append(out_file)
        elif len(toMerge) == 1 :
            out_file = out_fld + '/' + os.path.basename(shp).replace('.shp', out_ext + '.shp')
            os.rename(toMerge[0],out_file)
            out_file_list.append(out_file)
        drv = ogr.GetDriverByName('ESRI Shapefile')
        # Drop tmp files
        for fn in toDelete:
           drv.DeleteDataSource(fn)

    return out_file_list