Pular para conteúdo

Utils

polygonFromKML(kmlFile)

Essa função extrai um polygono (gee object) a partir de um kml

Source code in geedar_lib/utils.py
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
def polygonFromKML(kmlFile):
    """
    Essa função extrai um polygono (gee object) a partir de um kml
    """
    try:
        # Read the file as a string.
        with open(kmlFile, 'rt', encoding="utf-8") as file:
            doc = file.read()   
        # Create the KML object to store the parsed result.
        k = kml.KML()
        # Read the KML string.
        k.from_string(doc)
        structDict = {0: list(k.features())}
    except:
        return []

    # Search for polygons.
    polygons = []
    idList = [0]
    curID = 0
    lastID = 0
    try:
        while curID <= lastID:
            curFeatures = structDict[curID]
            for curFeature in curFeatures:
                if "_features" in [*vars(curFeature)]:
                    lastID = idList[-1] + 1
                    idList.append(lastID)
                    structDict[lastID] = list(curFeature.features())
                elif "_geometry" in [*vars(curFeature)]:
                    geom = curFeature.geometry
                    if geom.geom_type == "Polygon":
                        coords = [list(point[0:2]) for point in geom.exterior.coords]
                        if coords == []:
                            coords = [list(point[0:2]) for point in geom.interiors.coords]
                        if coords != []:
                            polygons.append([coords])
            curID = curID + 1
    except:
        pass

    return polygons

unfoldProcessingCode(fullCode, silent=False)

Desempacota o código de processamento no ID dos produtos na seleção de pixels e no algorítmo de inversão.

Parameters:

Name Type Description Default
fullCode int

Código de execução GEEDaR.

required

Returns:

Type Description

Uma tupla com os códigos de processamento, ID dos produtos, algoritmos de processamento e estimação e redutores.

Examples:

>>> unfoldProcessingCode(90114001)
([90114001], [901], [14], [0], [1])
Source code in geedar_lib/utils.py
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
def unfoldProcessingCode(fullCode:int, silent:bool = False):
    """
    Desempacota o código de processamento no ID dos produtos na 
    seleção de pixels e no algorítmo de inversão.

    Args:
        fullCode: Código de execução GEEDaR.

    Returns:
        Uma tupla com os códigos de processamento, ID dos produtos, algoritmos de processamento e estimação e redutores.

    Examples:
        >>> unfoldProcessingCode(90114001)
        ([90114001], [901], [14], [0], [1])
    """
    failValues = (None, None, None, None, None)
    fullCode = str(fullCode)

    if len(fullCode) < 8:
        if not silent:
            raise Exception("Unrecognized processing code: '" 
                + fullCode 
                + "'. It must be a list of integers in the form PPPSSRRA '"
                + "'(PPP is one of the product IDs listed by '-h:products';'"
                + "' SS is the code of the pixel selection algorithm; '"
                + "' RR, the code of the processing algorithm; '"
                + "' and A, the code of the reducer.)."
                )
        else:
            return failValues

    if fullCode[0] == "[" and fullCode[-1] == "]":
        fullCode = fullCode[1:-1]

    strCodes = fullCode.replace(" ", "").split(",")

    processingCodes = []
    productIDs = []
    imgProcAlgos = []
    estimationAlgos = []
    reducers = []

    for strCode in strCodes:
        try:
            code = int(strCode)
        except:
            if not silent:
                print("(!)")
                raise Exception("Unrecognized processing code: '" 
                    + strCode 
                    + "'. It should be an integer in the form PPPSSRRA '"
                    + "'(PPP is one of the product IDs listed by '-h:products';'"
                    + "' SS is the code of the pixel selection algorithm; RR, '"
                    + "' the code of the processing algorithm; and A, the code of the reducer.)."
                    )
            else:
                return failValues
        if code < 10000000:
            if not silent:
                print("(!)")
                raise Exception("Unrecognized processing code: '" 
                    + strCode 
                    + "'."
                    )
            else:
                return failValues

        processingCodes.append(code)

        productID = int(strCode[0:3])
        if not productID in AVAILABLE_PRODUCTS:
            if not silent:
                print("(!)")
                raise Exception("The product ID '" 
                    + str(productID) 
                    + "' derived from the processing code '" 
                    + strCode 
                    + "' was not recognized."
                    )
            else:
                return failValues
        productIDs.append(productID)

        imgProcAlgo = int(strCode[3:5])
        if not imgProcAlgo in IMG_PROC_ALGO_LIST:
            if not silent:
                print("(!)")
                raise Exception("The image processing algorithm ID '" 
                    + str(imgProcAlgo) 
                    + "' derived from the processing code '" 
                    + strCode 
                    + "' was not recognized."
                    )
            else:
                return failValues
        imgProcAlgos.append(imgProcAlgo)

        estimationAlgo = int(strCode[5:7])
        if not estimationAlgo in ESTIMATION_ALGO_LIST:
            if not silent:
                print("(!)")
                raise Exception("The estimation algorithm ID '" 
                    + str(estimationAlgo) 
                    + "' derived from the processing code '" 
                    + strCode 
                    + "' was not recognized."
                    )
            else:
                return failValues
        estimationAlgos.append(estimationAlgo)       
        reducer = int(strCode[-1])

        if not reducer in range(len(REDUCER_LIST)):
            if not silent:
                print("(!)")
                raise Exception("The reducer code '" 
                    + str(reducer) 
                    + "' in the processing code '" 
                    + strCode 
                    + "' was not recognized. The reducer code must correspond to an index of the reducer list: " 
                    + str(REDUCER_LIST) + "."
                    )

            else:
                return failValues
        reducers.append(reducer)

    return processingCodes, productIDs, imgProcAlgos, estimationAlgos, reducers

which(self)

Essa função é uma adaptação da função "with" da linguagem R

Source code in geedar_lib/utils.py
680
681
682
683
684
685
686
687
688
689
690
def which(self):
    """
    Essa função é uma adaptação da função "with" da linguagem R
    """
    try:
        self = list(iter(self))
    except TypeError as e:
        raise Exception("""'which' method can only be applied to iterables.
        {}""".format(str(e)))
    indices = [i for i, x in enumerate(self) if bool(x) == True]
    return(indices)

writeToLogFile(lines, entryType, identifier)

Essa função escreve um log file

Source code in geedar_lib/utils.py
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
def writeToLogFile(lines, entryType, identifier):
    """
    Essa função escreve um log file
    """

    log_file = "GEEDaR_log.txt"

    if not isinstance(lines, list):
        lines = [lines]
    try:
        dateAndTime = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M")
        f = open(log_file, "a")
        for line in lines:
            f.write(dateAndTime + "," + str(entryType) + "," + str(identifier) + "," + line + "\n")
        f.close()
    except:
        print("(!)")
        print("The message(s) below could not be written to the log file (" + log_file + "):")
        for line in lines:
            print(line)
        print("(.)")