Ejemplo n.º 1
0
class IrregularRunup(BaseDriver):
    def __init__(self, Hs0=None, Tp=None, cottheta=None):
        self.exporter = EXPORTER("output/exportIrregularRunup")

        if Hs0 != None:
            self.isSingleCase = True
            self.defaultValueHs0 = Hs0
        if Tp != None:
            self.isSingleCase = True
            self.defaultValueTp = Tp
        if cottheta != None:
            self.isSingleCase = True
            self.defaultValue_cottheta = cottheta

        super(IrregularRunup, self).__init__()

        self.exporter.close()

    # end __init__

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueHs0"):
            self.inputList.append(BaseField(\
                "Hs0: deepwater significant wave height (%s)" %\
                (self.labelUnitDist), 0.1, 100.0))
        if not hasattr(self, "defaultValueTp"):
            self.inputList.append(BaseField(\
                "Tp: peak energy wave period (sec)", 0.1, 100.0))
        if not hasattr(self, "defaultValue_cottheta"):
            self.inputList.append(BaseField(\
                "cottheta: cotangent of foreshore slope", 0.1, 100.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename="irregular_runup")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueHs0"):
            Hs0 = self.defaultValueHs0
        else:
            Hs0 = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueTp"):
            Tp = self.defaultValueTp
        else:
            Tp = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_cottheta"):
            cottheta = self.defaultValue_cottheta
        else:
            cottheta = caseInputList[currIndex]

        return Hs0, Tp, cottheta

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        Hs0, Tp, cottheta = self.getCalcValues(caseInputList)
        dataDict = {"Hs0": Hs0, "Tp": Tp, "cottheta": cottheta}

        #Coefficients provided by Mase (1989)
        amax = 2.32
        bmax = 0.77
        a2 = 1.86
        b2 = 0.71
        a110 = 1.70
        b110 = 0.71
        a13 = 1.38
        b13 = 0.70
        aavg = 0.88
        bavg = 0.69

        L0 = self.g * (Tp**2) / (2 * math.pi)
        steep = Hs0 / L0
        if not (steep < 0.142):
            self.errorMsg = 'Error: Input wave unstable (Max: 0.142, [H/L] = %0.4f)' % steep

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        tantheta = 1 / cottheta
        I = tantheta / math.sqrt(Hs0 / L0)

        Rmax = Hs0 * amax * (I**bmax)
        R2 = Hs0 * a2 * (I**b2)
        R110 = Hs0 * a110 * (I**b110)
        R13 = Hs0 * a13 * (I**b13)
        Ravg = Hs0 * aavg * (I**bavg)

        print('%s\t\t\t%6.2f %s' % ('Maximum runup', Rmax, self.labelUnitDist))
        print('%s\t%6.2f %s' %
              ('Runup exceeded by 2% of runup', R2, self.labelUnitDist))
        print('%s\t%6.2f %s' %
              ('Avg. of highest 1 / 10 runups', R110, self.labelUnitDist))
        print('%s\t%6.2f %s' %
              ('Avg. of highest 1 / 3 runups', R13, self.labelUnitDist))
        print('%s\t\t\t%6.2f %s' % ('Average runup', Ravg, self.labelUnitDist))

        dataDict.update({"Rmax": Rmax, "R2": R2, "R110": R110, "R13": R13,\
            "Ravg": Ravg})
        self.fileOutputWriteMain(dataDict, caseIndex)

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("Hs0\t\t\t%6.2f %s\n" %\
            (dataDict["Hs0"], self.labelUnitDist))
        self.fileRef.write("Tp\t\t\t%6.2f s\n" % dataDict["Tp"])
        self.fileRef.write("cottheta\t\t%6.2f\n\n" % dataDict["cottheta"])

        if self.errorMsg != None:
            self.fileRef.write("%s\n" % self.errorMsg)
        else:
            self.fileRef.write('%s\t\t\t%6.2f %s\n' %\
                ('Maximum runup', dataDict["Rmax"], self.labelUnitDist))
            self.fileRef.write('%s\t%6.2f %s\n' %\
                ('Runup exceeded by 2% of runup', dataDict["R2"], self.labelUnitDist))
            self.fileRef.write('%s\t%6.2f %s\n' %\
                ('Avg. of highest 1 / 10 runups', dataDict["R110"], self.labelUnitDist))
            self.fileRef.write('%s\t%6.2f %s\n' %\
                ('Avg. of highest 1 / 3 runups', dataDict["R13"], self.labelUnitDist))
            self.fileRef.write('%s\t\t\t%6.2f %s\n' %\
                ('Average runup', dataDict["Ravg"], self.labelUnitDist))

        exportData = [dataDict["Hs0"], dataDict["Tp"], dataDict["cottheta"]]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["Rmax"], dataDict["R2"],\
                dataDict["R110"], dataDict["R13"], dataDict["Ravg"]]
        self.exporter.writeData(exportData)
Ejemplo n.º 2
0
class BreakwaterHudson(BaseDriver):
    def __init__(self, unitwt = None, H = None, Kd = None,\
        kdelt = None, P = None, cotssl = None, n = None):
        self.exporter = EXPORTER("output/exportBreakwaterHudson")

        if unitwt != None:
            self.isSingleCase = True
            self.defaultValue_unitwt = unitwt
        if H != None:
            self.isSingleCase = True
            self.defaultValueH = H
        if Kd != None:
            self.isSingleCase = True
            self.defaultValueKd = Kd
        if kdelt != None:
            self.isSingleCase = True
            self.defaultValue_kdelt = kdelt
        if P != None:
            self.isSingleCase = True
            self.defaultValueP = P
        if cotssl != None:
            self.isSingleCase = True
            self.defaultValue_cotssl = cotssl
        if n != None:
            self.isSingleCase = True
            self.defaultValue_n = n

        super(BreakwaterHudson, self).__init__()

        self.exporter.close()

    # end __init__

    def userInput(self):
        super(BreakwaterHudson, self).userInput()

        self.water, self.rho = USER_INPUT.SALT_FRESH_WATER(self.isMetric)

    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValue_unitwt"):
            self.inputList.append(BaseField(\
                "unitwt: armor specific unit weight (%s/%s^3)" %\
                (self.labelUnitWt, self.labelUnitDist), 1.0, 99999.0))
        if not hasattr(self, "defaultValueH"):
            self.inputList.append(BaseField(\
                "H: wave height (%s)" % self.labelUnitDist, 0.1, 100.0))
        if not hasattr(self, "defaultValueKd"):
            self.inputList.append(BaseField(\
                "Kd: stability coefficient", 0.0, 10.0))
        if not hasattr(self, "defaultValue_kdelt"):
            self.inputList.append(BaseField(\
                "kdelt: layer coefficient", 0.0, 2.0))
        if not hasattr(self, "defaultValueP"):
            self.inputList.append(BaseField(\
                "P: average porosity of armor layer", 0.0, 54.0))
        if not hasattr(self, "defaultValue_cotssl"):
            self.inputList.append(BaseField(\
                "cotssl: cotangent of structure slope", 1.0, 6.0))
        if not hasattr(self, "defaultValue_n"):
            self.inputList.append(BaseField(\
                "n: number of armor units comprising the thickness of the armor layer", 1.0, 3.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename="breakwater_Hudson")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValue_unitwt"):
            unitwt = self.defaultValue_unitwt
        else:
            unitwt = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueH"):
            H = self.defaultValueH
        else:
            H = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueKd"):
            Kd = self.defaultValueKd
        else:
            Kd = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_kdelt"):
            kdelt = self.defaultValue_kdelt
        else:
            kdelt = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueP"):
            P = self.defaultValueP
        else:
            P = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_cotssl"):
            cotssl = self.defaultValue_cotssl
        else:
            cotssl = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_n"):
            n = self.defaultValue_n
        else:
            n = caseInputList[currIndex]

        return unitwt, H, Kd, kdelt, P, cotssl, n

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        unitwt, H, Kd, kdelt, P, cotssl, n =\
            self.getCalcValues(caseInputList)
        dataDict = {"unitwt": unitwt, "H": H, "Kd": Kd,\
            "kdelt": kdelt, "P": P, "cotssl": cotssl, "n": n}

        H20weight = self.rho * self.g  #64 lb/ft^3 for seawater, 62.4 for fresh

        specgrav = unitwt / H20weight

        w = (unitwt * H**3) / (Kd * (specgrav - 1.0)**3 * cotssl)
        if w < 0.0:
            self.errorMsg = "Error: Unit weight must be greater than water weight"

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        r = n * kdelt * (w / unitwt)**(1.0 / 3.0)
        Nr = 1000.0 * n * kdelt * (1.0 - P / 100.0) * (unitwt / w)**(2.0 / 3.0)
        b = 3.0 * kdelt * (w / unitwt)**(1.0 / 3.0)

        if self.isMetric:
            if w > 8000.0:
                w = w / 8896.4  #1 ton = 8896.4 N
                self.labelUnitWtLrg = "tons"
            else:
                self.labelUnitWtLrg = "N"
        else:
            if w > 2000.0:
                w = w / 2000.0
                self.labelUnitWtLrg = "tons"
            else:
                self.labelUnitWtLrg = "lbs"
        # end if

        print("Weight of individual unit\t%6.2f %s" %\
            (w, self.labelUnitWtLrg))
        print("Crest width\t\t\t%6.2f %s" % (b, self.labelUnitDist))
        print("Average cover layer thickness\t%6.2f %s" %\
            (r, self.labelUnitDist))
        print("Number of single armor unit\t%6.2f" % Nr)

        dataDict.update({"w": w, "b": b, "r": r, "Nr": Nr})
        self.fileOutputWriteMain(dataDict, caseIndex)

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("unitwt                             %6.2f %s/%s^3\n" %\
            (dataDict["unitwt"], self.labelUnitWt, self.labelUnitDist))
        self.fileRef.write("H                                  %6.2f %s\n" %\
            (dataDict["H"], self.labelUnitDist))
        self.fileRef.write("Kd                                 %6.2f\n" %
                           dataDict["Kd"])
        self.fileRef.write("kdelt                              %6.2f\n" %
                           dataDict["kdelt"])
        self.fileRef.write("P                                  %6.2f %%\n" %
                           dataDict["P"])
        self.fileRef.write("cotssl                             %6.2f\n" %
                           dataDict["cotssl"])
        self.fileRef.write("n                                  %6.2f\n\n" %
                           dataDict["n"])

        if self.errorMsg != None:
            self.fileRef.write("%s\n" % self.errorMsg)
        else:
            self.fileRef.write("Weight of individual unit\t%6.2f %s\n" %\
                (dataDict["w"], self.labelUnitWtLrg))
            self.fileRef.write("Crest width\t\t\t%6.2f %s\n" %\
                (dataDict["b"], self.labelUnitDist))
            self.fileRef.write("Average cover layer thickness\t%6.2f %s\n" %\
                (dataDict["r"], self.labelUnitDist))
            self.fileRef.write("Number of single armor unit\t%6.2f\n" %
                               dataDict["Nr"])

        exportData = [dataDict["unitwt"], dataDict["H"], dataDict["Kd"],\
            dataDict["kdelt"], dataDict["P"], dataDict["cotssl"],\
            dataDict["n"]]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["w"], dataDict["b"],\
                dataDict["r"], dataDict["Nr"]]
        self.exporter.writeData(exportData)
Ejemplo n.º 3
0
class BeachNourishment(BaseDriver):
    def __init__(self, Vol_i = None, M_R = None, ro_n = None, M_b = None, ro_b = None):
        self.exporter = EXPORTER("output/exportBeachNourishment")
        
        if Vol_i != None:
            self.isSingleCase = True
            self.defaultValueVol_i = Vol_i
        if M_R != None:
            self.isSingleCase = True
            self.defaultValueM_R = M_R
        if ro_n != None:
            self.isSingleCase = True
            self.defaultValue_ro_n = ro_n
        if M_b != None:
            self.isSingleCase = True
            self.defaultValueM_b = M_b
        if ro_b != None:
            self.isSingleCase = True
            self.defaultValue_ro_b = ro_b

        super(BeachNourishment, self).__init__()
        
        self.exporter.close()
    # end __init__

    def defineInputDataList(self):
        if self.isMetric:
            self.labelUnitVolumeRate = "m^3"
            self.labelUnitGrain = "mm"
        else:
            self.labelUnitVolumeRate = "yd^3"
            self.labelUnitGrain = "phi"

        self.inputList = []

        if not hasattr(self, "defaultValueVol_i"):
            self.inputList.append(BaseField(\
                "Vol_i: initial volume (%s)" % (self.labelUnitVolumeRate), 1, 10**8))

        if not hasattr(self, "defaultValueM_R"):
            self.inputList.append(BaseField(\
                "M_R: Native mean (%s)" % (self.labelUnitGrain), -5.0, 5.0))

        if not hasattr(self, "defaultValue_ro_n"):
            self.inputList.append(BaseField(\
                "ro_n: Native standard deviation (phi)", 0.01, 5.0))

        if not hasattr(self, "defaultValueM_b"):
            self.inputList.append(BaseField(\
                "M_b: Borrow mean (%s)" % (self.labelUnitGrain), -5.0, 5.0))

        if not hasattr(self, "defaultValue_ro_b"):
            self.inputList.append(BaseField(\
                "ro_b: Borrow standard deviation (phi)", 0.01, 5.0))
    # end defineInputList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename = "beach_nourishment")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueVol_i"):
            Vol_i = self.defaultValueVol_i
        else:
            Vol_i = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueM_R"):
            M_R = self.defaultValueM_R
        else:
            M_R = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_ro_n"):
            ro_n = self.defaultValue_ro_n
        else:
            ro_n = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueM_b"):
            M_b = self.defaultValueM_b
        else:
            M_b = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_ro_b"):
            ro_b = self.defaultValue_ro_b
        else:
            ro_b = caseInputList[currIndex]

        return Vol_i, M_R, ro_n, M_b, ro_b
    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex = 0):
        Vol_i, M_R, ro_n, M_b, ro_b = self.getCalcValues(caseInputList)
        dataDict = {"Vol_i": Vol_i, "M_R": M_R, "ro_n": ro_n, "M_b": M_b,\
            "ro_b": ro_b}

        catg = 0 # category of the material according to table 6-4-1 in Aces manual

        if self.isMetric: # If Means are entered in mm, convert to phi units for computations.
            M_R = -(math.log(M_R) / math.log(2.0))
            M_b = -(math.log(M_b) / math.log(2.0))

        # Relationships of phi means and pho standard deviations
        if ro_b > ro_n:
            print('Borrow material is more poorly sorted than native material')
            if M_b > M_R:
                print('Borrow material is finer than native material')
                catg = 1
            else:
                print('Borrow material is coarser than native material')
                catg = 2
        else:
            if M_b < M_R:
               print('Borrow material is coarser than native material')
               catg = 3
            else:
               print('Borrow material is finer than native material')
               catg = 4
        # end if

        delta = (M_b-M_R)/ro_n # phi mean difference
        sigma = ro_b/ro_n # phi sorting ratio

        if sigma == 1:
            theta_1 = 0
            theta_2 = float("inf")
        else:
            # defining theta_1 and theta_2
            if catg == 1 or catg == 2:
                theta_1 = max(-1, (-delta/(sigma**2 - 1)))
                theta_2 = float("inf")
            else:
                theta_1 = -1
                theta_2 = max(-1, (1 + (2*delta/(1 - sigma**2))))

        # calculate overfill ratio
        bk1 = (theta_1 - delta)/sigma
        fn1 = BOVERF(bk1)
        ft1 = BOVERF(theta_1)

        if theta_2 == float("inf"):
            fn3 = ((1.0 - ft1)/sigma)*math.exp(0.5*(theta_1**2 - bk1**2))
            R_A = 1.0/(fn1 + fn3)
        else:
            bk2 = (theta_2 - delta)/sigma
            fn2 = BOVERF(bk2)
            ft2 = BOVERF(theta_2)
            fn3 = ((ft2 - ft1)/sigma)*math.exp(0.5*(theta_1**2 - bk1**2))
            R_A = 1.0 / (1 - fn2 + fn1 + fn3)
        # end if

        if R_A < 1.0:
            self.errorMsg = "Error: Overfill ratio (R_A) < 1.0. Respecify data"

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        try:
            R_j = math.exp((delta - 0.5*((ro_b**2 / ro_n**2) - 1)))
        except:
            R_j = float('inf')

        Vol_D = R_A * Vol_i

        print("Overfill Ratio, R_A\t\t\t%6.2f" % (R_A))
        print("Renourishment factor, R_j\t\t%6.2f" % (R_j))
        print("Design Volume, Vol_D\t\t\t%6.2f %s" % (Vol_D, self.labelUnitVolumeRate))

        dataDict.update({"R_A": R_A, "R_j": R_j, "Vol_D": Vol_D })
        self.fileOutputWriteMain(dataDict, caseIndex)
    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("Vol_i\t%6.2f %s\n" %\
            (dataDict["Vol_i"], self.labelUnitVolumeRate))
        self.fileRef.write("M_R\t%6.2f %s\n" % (dataDict["M_R"], self.labelUnitGrain))
        self.fileRef.write("ro_n\t%6.2f\n" % (dataDict["ro_n"]))
        self.fileRef.write("M_b\t%6.2f %s\n" % (dataDict["M_b"], self.labelUnitGrain))
        self.fileRef.write("ro_b\t%6.2f\n\n" % (dataDict["ro_b"]))

        if self.errorMsg != None:
            self.fileRef.write("%s\n" % self.errorMsg)
        else:
            self.fileRef.write("Overfill Ratio, R_A\t\t\t%6.2f\n" % (dataDict["R_A"]))
            self.fileRef.write("Renourishment factor, R_j\t\t%6.2f\n" % (dataDict["R_j"]))
            self.fileRef.write("Design Volume, Vol_D\t\t\t%6.2f %s\n" %\
                (dataDict["Vol_D"], self.labelUnitVolumeRate))
        
        exportData = [dataDict["Vol_i"], dataDict["M_R"], dataDict["ro_n"],\
            dataDict["M_b"], dataDict["ro_b"]]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["R_A"], dataDict["R_j"],\
                dataDict["Vol_D"]]
        self.exporter.writeData(exportData)
Ejemplo n.º 4
0
class WavetransImperm(BaseDriver):
    def __init__(self, H = None, T = None, cotphi = None, ds = None,\
            cottheta = None, hs = None, B = None, R = None, hB = None):
        self.exporter = EXPORTER("output/exportWavetransImperm")

        if H != None:
            self.isSingleCase = True
            self.defaultValueH = H

        if T != None:
            self.isSingleCase = True
            self.defaultValueT = T

        if cotphi != None:
            self.isSingleCase = True
            self.defaultValue_cotphi = cotphi

        if ds != None:
            self.isSingleCase = True
            self.defaultValue_ds = ds

        if cottheta != None:
            self.isSingleCase = True
            self.defaultValue_cottheta = cottheta

        if hs != None:
            self.isSingleCase = True
            self.defaultValue_hs = hs

        if B != None:
            self.isSingleCase = True
            self.defaultValueB = B

        if R != None:
            self.isSingleCase = True
            self.defaultValueR = R

        if hB != None:
            self.isSingleCase = True
            self.defaultValue_hB = hB

        super(WavetransImperm, self).__init__()

        self.exporter.close()

    # end __init__

    def userInput(self):
        msg = "Calculation and slope type options:\n" +\
            "[1] Wave transmission only for smooth slope\n" +\
            "[2] Wave transmission only for vertical wall\n" +\
            "[3] Wave runup and transmission for rough slope\n" + \
            "[4] Wave runup and transmission for smooth slope\n" +\
            "Select option: "
        self.option = USER_INPUT.FINITE_CHOICE(msg, ["1", "2", "3", "4"])
        self.option = int(self.option)

        super(WavetransImperm, self).userInput()

        if self.option == 3:
            runupCoeffDataList = [\
                ['Riprap', 0.956, 0.398],\
                ['Quarrystone (Impermeable Base)', 0.692, 0.504],\
                ['Quarrystone (Permeable Base)', 0.775, 0.361],\
                ['Modified Cubes', 0.95, 0.69],\
                ['Tetrapods', 1.01, 0.91],\
                ['Quadrapods', 0.59, 0.35],\
                ['Hexapods', 0.82, 0.63],\
                ['Tribars', 1.81, 1.57],\
                ['Dolosse', 0.988, 0.703]]

            numOptions = len(runupCoeffDataList) + 1
            print("Suggested Empirical Rough Slope Runup Coeff Listing")
            for i in range(len(runupCoeffDataList)):
                print("[%d] %s\t%-6.3f\t%-6.3f" %\
                    (i + 1, runupCoeffDataList[i][0],\
                    runupCoeffDataList[i][1], runupCoeffDataList[i][2]))
            print("[%d] Enter custom values" % (numOptions))

            coeffChoice = USER_INPUT.FINITE_CHOICE("Select option: ",\
                [str(i + 1) for i in range(numOptions)])
            coeffChoice = int(coeffChoice)

            if coeffChoice == numOptions:
                self.a = USER_INPUT.DATA_VALUE("coefficient a", 0.0, 20.0)
                self.b = USER_INPUT.DATA_VALUE("coefficient b", 0.0, 20.0)
            else:
                self.a = runupCoeffDataList[coeffChoice - 1][1]
                self.b = runupCoeffDataList[coeffChoice - 1][2]

    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueH"):
            self.inputList.append(BaseField(\
                "H: incident wave height (Hs for irregular waves) (%s)" % (self.labelUnitDist),\
                0.1, 100.0))
        if not hasattr(self, "defaultValueT"):
            self.inputList.append(BaseField(\
                "T: wave period (Tp for irregular waves) (s)", 1.0, 1000.0))
        if not hasattr(self, "defaultValue_cotphi"):
            self.inputList.append(BaseField(\
                "cotphi: cotan of nearshore slope", 5.0, 10000.0))
        if not hasattr(self, "defaultValue_ds"):
            self.inputList.append(BaseField(\
                "ds: water depth at structure toe (%s)" % (self.labelUnitDist), 0.1, 200.0))

        if self.option != 2 and not hasattr(self, "defaultValue_cottheta"):
            self.inputList.append(BaseField(\
                "cottheta: cotan of structure slope (0.0 for vertical wall)", 0.0, 30.0))

        if not hasattr(self, "defaultValue_hs"):
            self.inputList.append(BaseField(\
                "hs: structure height above toe (%s)" % (self.labelUnitDist), 0.0, 200.0))
        if not hasattr(self, "defaultValueB"):
            self.inputList.append(BaseField(\
                "B: structure crest width (%s)" % (self.labelUnitDist), 0.0, 200.0))

        if self.option == 1 and not hasattr(self, "defaultValueR"):
            self.inputList.append(BaseField(\
                "R: wave runup (if known) (%s)" % (self.labelUnitDist), 0.0, 100.0))

        if self.option == 2 and not hasattr(self, "defaultValue_hB"):
            self.inputList.append(BaseField(\
                "hB: structure berm height above toe (%s)" % (self.labelUnitDist),\
                0.0, 200.0))

    # end defineInputDataList

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueH"):
            H = self.defaultValueH
        else:
            H = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueT"):
            T = self.defaultValueT
        else:
            T = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_cotphi"):
            cotphi = self.defaultValue_cotphi
        else:
            cotphi = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_ds"):
            ds = self.defaultValue_ds
        else:
            ds = caseInputList[currIndex]
            currIndex = currIndex + 1

        if self.option != 2:
            if hasattr(self, "defaultValue_cottheta"):
                cottheta = self.defaultValue_cottheta
            else:
                cottheta = caseInputList[currIndex]
                currIndex = currIndex + 1
        else:
            cottheta = 0

        if hasattr(self, "defaultValue_hs"):
            hs = self.defaultValue_hs
        else:
            hs = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueB"):
            B = self.defaultValueB
        else:
            B = caseInputList[currIndex]
            currIndex = currIndex + 1

        if self.option == 1:
            if hasattr(self, "defaultValueR"):
                R = self.defaultValueR
            else:
                R = caseInputList[currIndex]
                currIndex = currIndex + 1
        else:
            R = None

        if self.option == 2:
            if hasattr(self, "defaultValue_hB"):
                hB = self.defaultValue_hB
            else:
                hB = caseInputList[currIndex]
                currIndex = currIndex + 1
        else:
            hB = None

        return H, T, cotphi, ds, cottheta, hs, B, R, hB

    # end getCalcValues

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename="wavetrans_imperm")

    def performCalculations(self, caseInputList, caseIndex=0):
        H, T, cotphi, ds, cottheta, hs, B, R, hB = self.getCalcValues(
            caseInputList)
        dataDict = {"H": H, "T": T, "cotphi": cotphi, "ds": ds,\
            "cottheta": cottheta, "hs": hs, "B": B, "R": R, "hB": hB}
        m = 1.0 / cotphi

        if self.option != 2 and not (ds < hs):
            self.errorMsg = "Error: Method does not apply to submerged structures."

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        c, c0, cg, cg0, k, L, L0, reldep = LWTGEN(ds, T, self.g)

        Hbs = ERRWAVBRK2(T, m, ds)
        if not (H < Hbs):
            self.errorMsg = "Error: Wave broken at structure (Hbs = %6.2f %s" %\
                (Hbs, self.labelUnitDist)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        steep, maxstp = ERRSTP(H, ds, L)
        if not (steep < maxstp):
            self.errorMsg = "Error: Input wave unstable (Max: %0.4f, [H/L] = %0.4f)" % (
                maxstp, steep)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        if cottheta == 0:
            if self.option != 2:
                self.errorMsg = "Error: A cotangent of zero indicates a vertical wall."

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            reldep = ds / L

            if not (reldep > 0.14 and reldep < 0.5):
                self.errorMsg = "Error: d/L conditions exceeded - 0.14 <= (d/L) <= 0.5"

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return
        else:
            theta = math.atan(1 / cottheta)
            ssp = (1 / cottheta) / math.sqrt(H / L0)

        if self.option == 3:
            R = RUNUPR(H, ssp, self.a, self.b)
            print("Runup\t\t%-6.3f" % R)
        elif self.option == 4:
            R = RUNUPS(H, L, ds, theta, ssp)
            print("Runup\t\t%-6.3f" % R)

        freeb = hs - ds

        if self.option != 2:
            Ht = HTP(B, hs, R, H, freeb)
        else:
            dl = ds - hB
            Ht = VERTKT(H, freeb, B, ds, dl)
        print("Transmitted wave height\t%-6.3f" % Ht)

        dataDict.update({"R": R, "Ht": Ht})
        self.fileOutputWriteMain(dataDict, caseIndex)

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("H\t\t%6.2f %s\n" %
                           (dataDict["H"], self.labelUnitDist))
        self.fileRef.write("T\t\t%6.2f %s\n" %
                           (dataDict["T"], self.labelUnitDist))
        self.fileRef.write("cotphi\t\t%6.2f\n" % (dataDict["cotphi"]))
        self.fileRef.write("ds\t\t%6.2f %s\n" %
                           (dataDict["ds"], self.labelUnitDist))
        self.fileRef.write("cottheta\t%6.2f\n" % (dataDict["cottheta"]))
        self.fileRef.write("hs\t\t%6.2f %s\n" %
                           (dataDict["hs"], self.labelUnitDist))
        self.fileRef.write("B\t\t%6.2f %s\n" %
                           (dataDict["B"], self.labelUnitDist))

        if self.option == 1:
            self.fileRef.write("R\t\t%6.2f %s\n" %
                               (dataDict["R"], self.labelUnitDist))

        if self.option == 2:
            self.fileRef.write("hB\t\t%6.2f %s\n" %
                               (dataDict["hB"], self.labelUnitDist))

        if self.option == 3:
            self.fileRef.write("a\t\t%6.3f\n" % (self.a))
            self.fileRef.write("b\t\t%6.3f\n" % (self.b))

        self.fileRef.write("\n")

        if self.errorMsg != None:
            self.fileRef.write("%s\n" % self.errorMsg)
        else:
            if self.option == 3 or self.option == 4:
                self.fileRef.write("Runup\t\t%6.3f\n" % dataDict["R"])

            self.fileRef.write("Transmitted wave height\t%-6.3f %s\n" %\
                (dataDict["Ht"], self.labelUnitDist))

        exportData = [dataDict["H"], dataDict["T"], dataDict["cotphi"],\
            dataDict["ds"], dataDict["cottheta"], dataDict["hs"],\
            dataDict["B"]]
        if self.option == 1:
            exportData.append(dataDict["R"])
        if self.option == 2:
            exportData.append(dataDict["hB"])
        if self.option == 3:
            exportData.append(self.a)
            exportData.append(self.b)

        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            if self.option == 3 or self.option == 4:
                exportData.append(dataDict["R"])
            exportData.append(dataDict["Ht"])
        self.exporter.writeData(exportData)
Ejemplo n.º 5
0
class WindAdj(BaseDriver):
    def __init__(self, windobs = None, wgtyp = None, useKnots = None,\
        zobs = None, Uobs = None, dtemp = None, duro = None, durf = None,\
        lat = None, F = None, d = None, wdir = None, dang = None,\
        ang1 = None, manualOrFile = None, Nfet = None, angs = None):
        self.exporter = EXPORTER("output/exportWindAdj")

        if windobs != None:
            self.isSingleCase = True
            self.defaultValue_windobs = windobs
        if wgtyp != None:
            self.isSingleCase = True
            self.defaultValue_wgtyp = wgtyp
        if useKnots != None:
            self.isSingleCase = True
            self.defaultValue_useKnots = useKnots
        if zobs != None:
            self.isSingleCase = True
            self.defaultValue_zobs = zobs
        if Uobs != None:
            self.isSingleCase = True
            self.defaultValueUobs = Uobs
        if dtemp != None:
            self.isSingleCase = True
            self.defaultValue_dtemp = dtemp
        if duro != None:
            self.isSingleCase = True
            self.defaultValue_duro = duro
        if durf != None:
            self.isSingleCase = True
            self.defaultValue_durf = durf
        if lat != None:
            self.isSingleCase = True
            self.defaultValue_lat = lat
        if F != None:
            self.isSingleCase = True
            self.defaultValueF = F
        if d != None:
            self.isSingleCase = True
            self.defaultValue_d = d
        if wdir != None:
            self.isSingleCase = True
            self.defaultValue_wdir = wdir
        if dang != None:
            self.isSingleCase = True
            self.defaultValue_dang = dang
        if ang1 != None:
            self.isSingleCase = True
            self.defaultValue_ang1 = ang1
        if manualOrFile != None:
            self.isSingleCase = True
            self.defaultValue_manualOrFile = manualOrFile
        if Nfet != None:
            self.isSingleCase = True
            self.defaultValue_useKnots = useKnots
        if angs != None:
            self.isSingleCase = True
            self.defaultValue_useKnots = useKnots

        super(WindAdj, self).__init__()

        self.exporter.close()

    # end __init__

    def userInput(self):
        self.windObsList = ["Overwater (shipboard)",\
            "Overwater (not shipboard)",\
            "Shore (windward - offshore to onshore)",\
            "Shore (leeward - onshore to offshore)",\
            "Over land",\
            "Geostrophic wind"]

        if not hasattr(self, "defaultValue_windobs"):
            windObsMsg = "Wind observation types:\n"
            for i in range(len(self.windObsList)):
                windObsMsg += "[%d] %s\n" % ((i + 1), self.windObsList[i])
            windObsMsg += "Select option: "

            self.windobs = USER_INPUT.FINITE_CHOICE(\
                windObsMsg, ["1", "2", "3", "4", "5", "6"])
            self.windobs = int(self.windobs)
        else:
            self.windobs = self.defaultValue_windobs

        self.wgtypList = ["Open Water - Deep",\
            "Open Water - Shallow",\
            "Restricted - Deep",\
            "Restricted - Shallow"]

        if not hasattr(self, "defaultValue_wgtyp"):
            wgtypMsg = "Wind fetch and wave growth options:\n"
            for i in range(len(self.wgtypList)):
                wgtypMsg += "[%d] %s\n" % ((i + 1), self.wgtypList[i])
            wgtypMsg += "Select option: "

            self.wgtyp = USER_INPUT.FINITE_CHOICE(\
                wgtypMsg, ["1", "2", "3", "4"])
            self.wgtyp = int(self.wgtyp)
        else:
            self.wgtyp = self.defaultValue_wgtyp

        self.isWaterOpen = self.wgtyp == 1 or self.wgtyp == 2
        self.isWaterShallow = self.wgtyp == 2 or self.wgtyp == 4

        super(WindAdj, self).userInput()

        if not self.isWaterOpen:
            if not hasattr(self, "defaultValue_dang"):
                self.dang = USER_INPUT.DATA_VALUE(\
                    "dang: radial angle increment [deg]", 1.0, 180.0)
            else:
                self.dang = self.defaultValue_dang

            if not hasattr(self, "defaultValue_ang1"):
                self.ang1 = USER_INPUT.DATA_VALUE(\
                    "ang1: direction of first radial fetch [deg]",\
                    0.0, 360.0)
            else:
                self.ang1 = self.defaultValue_ang1

            if not hasattr(self, "defaultValue_manualOrFile"):
                manualOrFile = USER_INPUT.FINITE_CHOICE(\
                    "Would you like to enter fetch length data " +\
                    "manually or load from a file?\n" +\
                    "[M] for manual entry or [F] for file loading: ",
                    ["M", "m", "F", "f"])

                if manualOrFile == "M" or manualOrFile == "m":
                    self.Nfet = USER_INPUT.DATA_VALUE(\
                        "Nfet: number of radial fetches", 2, 360)
                    self.Nfet = int(self.Nfet)

                    self.angs = []
                    for i in range(self.Nfet):
                        self.angs.append(USER_INPUT.DATA_VALUE(\
                            "angs: fetch length [%s] #%d" %\
                            (self.labelUnitDistLrg, (i + 1)), 0.0, 9999.0))
                else:
                    accepted = False
                    while not accepted:
                        filename = USER_INPUT.FILE_NAME()

                        fileRef = open(filename)

                        fileData = fileRef.read()

                        self.angs = []
                        for dataLine in fileData.split("\n"):
                            if len(dataLine) > 0:
                                self.angs.append(float(dataLine))
                        self.Nfet = len(self.angs)

                        fileRef.close()

                        if self.Nfet >= 2 and self.Nfet <= 360:
                            accepted = True
                        else:
                            print(
                                "File must have between 2 and 360 fetch lengths."
                            )
                    # end while

    # end userInput

    def defineInputDataList(self):
        if self.isMetric:
            self.labelSpeed = "m/s"
            self.labelUnitDistLrg = "km"
        else:
            self.labelSpeed = "mph"
            self.labelUnitDistLrg = "mi"

        if not hasattr(self, "defaultValue_useKnots"):
            self.useKnots = USER_INPUT.FINITE_CHOICE(\
                "Speed options:\n[M] %s\n[K] knots\nSelect option: " %\
                self.labelSpeed,\
                ["M", "m", "K", "k"])
        else:
            self.useKnots = self.defaultValue_useKnots
        if self.useKnots == "K" or self.useKnots == "k":
            self.labelSpeedFinal = "knots"
            self.useKnots = True
        else:
            self.labelSpeedFinal = self.labelSpeed
            self.useKnots = False

        self.inputList = []

        if not hasattr(self, "defaultValue_zobs"):
            self.inputList.append(BaseField(\
                "zobs: elevation of observed winds [%s]" % (self.labelUnitDist),\
                1.0, 5000.0))
        if not hasattr(self, "defaultValueUobs"):
            self.inputList.append(BaseField(\
                "uobs: observed wind speed [%s]" % self.labelSpeedFinal,\
                0.1, 200.0))
        if not hasattr(self, "defaultValue_dtemp"):
            self.inputList.append(BaseField(\
                "dtemp: air-sea temperature difference [deg C]",\
                -100.0, 100.0))
        if not hasattr(self, "defaultValue_duro"):
            self.inputList.append(BaseField(\
                "duro: duration of observed wind [hr]", 0.1, 86400.0))
        if not hasattr(self, "defaultValue_durf"):
            self.inputList.append(BaseField(\
                "durf: duration of final wind [hr]", 0.1, 86400.0))
        if not hasattr(self, "defaultValue_lat"):
            self.inputList.append(BaseField(\
                "lat: latitude of wind observation [deg]", 0.0, 180.0))

        if self.isWaterOpen and not hasattr(self, "defaultValueF"):
            self.inputList.append(BaseField(\
                "F: length of wind fetch [%s]" % self.labelUnitDistLrg,
                0.0, 9999.0))

        if self.isWaterShallow and not hasattr(self, "defaultValue_d"):
            self.inputList.append(BaseField(\
                "d: average depth of fetch [%s]" % self.labelUnitDist,
                0.1, 10000.0))

        if not self.isWaterOpen and not hasattr(self, "defaultValue_wdir"):
            self.inputList.append(BaseField(\
                "wdir: wind direction [deg]", 0.0, 360.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename="wind_adj")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValue_zobs"):
            zobs = self.defaultValue_zobs
        else:
            zobs = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueUobs"):
            Uobs = self.defaultValueUobs
        else:
            Uobs = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_dtemp"):
            dtemp = self.defaultValue_dtemp
        else:
            dtemp = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_duro"):
            duro = self.defaultValue_duro
        else:
            duro = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_durf"):
            durf = self.defaultValue_durf
        else:
            durf = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_lat"):
            lat = self.defaultValue_lat
        else:
            lat = caseInputList[currIndex]
            currIndex = currIndex + 1

        if self.isWaterOpen:
            if hasattr(self, "defaultValueF"):
                F = self.defaultValueF
            else:
                F = caseInputList[currIndex]
                currIndex = currIndex + 1
        else:
            F = None

        if self.isWaterShallow:
            if hasattr(self, "defaultValue_d"):
                d = self.defaultValue_d
            else:
                d = caseInputList[currIndex]
                currIndex = currIndex + 1
        else:
            d = 0.0

        if not self.isWaterOpen:
            if hasattr(self, "defaultValue_wdir"):
                wdir = self.defaultValue_wdir
            else:
                wdir = caseInputList[currIndex]
                currIndex = currIndex + 1
        else:
            wdir = None

        if not self.isWaterOpen:
            dang = self.dang
            ang1 = self.ang1
            Nfet = self.Nfet
            angs = self.angs
        else:
            dang = None
            ang1 = None
            Nfet = None
            angs = None

        return zobs, Uobs, dtemp, duro, durf, lat, F, d, wdir,\
            dang, ang1, Nfet, angs

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        zobs, Uobs, dtemp, duro, durf, lat, F, d, wdir,\
            dang, ang1, Nfet, angs = self.getCalcValues(caseInputList)
        dataDict = {"zobs": zobs, "Uobs": Uobs, "dtemp": dtemp,\
            "duro": duro, "durf": durf, "lat": lat, "F": F,\
            "d": d, "wdir": wdir, "dang": dang, "ang1": ang1}

        # Constant for convertions
        ft2m = 0.3048
        mph2mps = 0.44704
        hr2s = 3600.0
        min2s = 60.0
        deg2rad = math.pi / 180.0
        mi2m = 1609.344
        km2m = 0.001
        F2C = 5.0 / 9.0
        knots2mps = 0.5144

        if not self.isMetric:
            conversionDist = ft2m
            conversionDistLrg = mi2m
        else:
            conversionDist = 1.0
            conversionDistLrg = km2m

        if self.useKnots:
            conversionSpeed = knots2mps
        elif not self.isMetric:
            conversionSpeed = mph2mps
        else:
            conversionSpeed = 1.0

        if self.isWaterOpen:
            phi = 0.0
        else:
            F, phi, theta = WGFET(ang1, dang, wdir, angs)

        if np.isclose(lat, 0.0):
            self.errorMsg = "Error: Latitude must be a non-zero value."

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        # Check WDIR vs Fetch data. WDIR must meet this criterion:
        # ang1 -45 degrees <= WDIR <= anglast + 45 degrees
        if not self.isWaterOpen:
            if not (ang1 - 45 <= wdir):
                self.errorMsg = "Error: wdir must be at least 45 degrees less than the first fetch angle."

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return
            if not (wdir <= (ang1 + (Nfet - 1) * dang)):
                self.errorMsg = "Error: wdir must be at most 45 degrees more than the final fetch angle."

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

        ue = WADJ(Uobs*conversionSpeed,\
            zobs*conversionDist,\
            dtemp,\
            F*conversionDistLrg,\
            duro*hr2s,\
            durf*hr2s,\
            lat*deg2rad,\
            self.windobs)

        ua, Hmo, Tp, wgmsg = WGRO(d*conversionDist,\
            F*conversionDistLrg,\
            phi,
            durf*hr2s,\
            ue,\
            self.wgtyp)

        if not self.isWaterOpen:
            print("Wind fetch\t\t\t%-6.2f %s" %\
                (F, self.labelUnitDistLrg))
            print("Wind Direction\t\t\t%-6.2f deg" % wdir)

        print("Equiv. wind speed\t\t%-6.2f %s" %\
            (ue/conversionSpeed, self.labelSpeedFinal))
        print("Adjus. wind speed\t\t%-6.2f %s" %\
            (ua/conversionSpeed, self.labelSpeedFinal))

        if not self.isWaterOpen:
            print("Mean wave direction\t\t%-6.2f deg" % theta)

        print("Wave height\t\t\t%-6.2f %s" %\
            (Hmo/conversionDist, self.labelUnitDist))
        print("Wave period\t\t\t%-6.2f s" % Tp)

        print("Wave growth: %s" % wgmsg)

        dataDict["F"] = F
        dataDict["ue"] = ue
        dataDict["ua"] = ua
        dataDict["Hmo"] = Hmo
        dataDict["Tp"] = Tp
        dataDict["wgmsg"] = wgmsg
        dataDict["conversionDist"] = conversionDist
        dataDict["conversionDistLrg"] = conversionDistLrg
        dataDict["conversionSpeed"] = conversionSpeed
        if not self.isWaterOpen:
            dataDict["theta"] = theta
        self.fileOutputWriteMain(dataDict, caseIndex)

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("zobs\t%6.2f %s\n" %
                           (dataDict["zobs"], self.labelUnitDist))
        self.fileRef.write("uobs\t%6.2f %s\n" %
                           (dataDict["Uobs"], self.labelSpeedFinal))
        self.fileRef.write("dtemp\t%6.2f deg\n" % dataDict["dtemp"])
        self.fileRef.write("duro\t%6.2f hr\n" % dataDict["duro"])
        self.fileRef.write("durf\t%6.2f hr\n" % dataDict["durf"])
        self.fileRef.write("lat\t%6.2f deg\n" % dataDict["lat"])

        if self.isWaterOpen:
            self.fileRef.write("F\t%6.2f %s\n" %
                               (dataDict["F"], self.labelUnitDistLrg))

        if self.isWaterShallow:
            self.fileRef.write("d\t%6.2f %s\n" %
                               (dataDict["d"], self.labelUnitDist))

        if not self.isWaterOpen:
            self.fileRef.write("wdir\t%6.2f deg\n" % dataDict["wdir"])

        if self.errorMsg != None:
            self.fileRef.write("\n%s\n" % self.errorMsg)
        else:
            self.fileRef.write("\nOutput\n")

            if not self.isWaterOpen:
                self.fileRef.write("Wind fetch\t\t\t%-6.2f %s\n" %\
                    (dataDict["F"], self.labelUnitDistLrg))
                self.fileRef.write("Wind Direction\t\t\t%-6.2f deg\n" %\
                    dataDict["wdir"])

            self.fileRef.write("Equiv. wind speed\t\t%-6.2f %s\n" %\
                (dataDict["ue"]/dataDict["conversionSpeed"], self.labelSpeedFinal))
            self.fileRef.write("Adjus. wind speed\t\t%-6.2f %s\n" %\
                (dataDict["ua"]/dataDict["conversionSpeed"], self.labelSpeedFinal))

            if not self.isWaterOpen:
                self.fileRef.write("Mean wave direction\t\t%-6.2f deg\n" %\
                    dataDict["theta"])

            self.fileRef.write("Wave height\t\t\t%-6.2f %s\n" %\
                (dataDict["Hmo"]/dataDict["conversionDist"], self.labelUnitDist))
            self.fileRef.write("Wave period\t\t\t%-6.2f s\n" % dataDict["Tp"])

            self.fileRef.write("Wave growth: %s\n" % dataDict["wgmsg"])

        exportData = [dataDict["zobs"], dataDict["Uobs"], dataDict["dtemp"],\
            dataDict["duro"], dataDict["durf"], dataDict["lat"]]
        if self.isWaterOpen:
            exportData.append(dataDict["F"])
        if self.isWaterShallow:
            exportData.append(dataDict["d"])
        if not self.isWaterOpen:
            exportData.append(dataDict["wdir"])

        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            if not self.isWaterOpen:
                exportData = exportData + [dataDict["F"]]  #, dataDict["wdir"]]
            exportData = exportData + [\
                    dataDict["ue"]/dataDict["conversionSpeed"],\
                    dataDict["ua"]/dataDict["conversionSpeed"]]

            if not self.isWaterOpen:
                exportData.append(dataDict["theta"])

            exportData = exportData + [\
                dataDict["Hmo"]/dataDict["conversionDist"],\
                dataDict["Tp"], dataDict["wgmsg"]]

        self.exporter.writeData(exportData)
Ejemplo n.º 6
0
class BetaRayleigh(BaseDriver):
    def __init__(self, Hmo = None, Tp = None, d = None):
        self.exporter = EXPORTER("output/exportBetaRayleigh")

        if Hmo != None:
            self.isSingleCase = True
            self.defaultValueHmo = Hmo
        if Tp != None:
            self.isSingleCase = True
            self.defaultValueTp = Tp
        if d != None:
            self.isSingleCase = True
            self.defaultValue_d = d

        super(BetaRayleigh, self).__init__()

        self.exporter.close()
    # end __init__

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueHmo"):
            self.inputList.append(BaseField("Hmo: zero-moment wave height [%s]" % (self.labelUnitDist), 0.1, 60.0))
        if not hasattr(self, "defaultValueTp"):
            self.inputList.append(BaseField("Tp: peak wave period [s]", 2.0, 30.0))
        if not hasattr(self, "defaultValue_d"):
            self.inputList.append(BaseField("d: water depth [%s]" % (self.labelUnitDist), 0.1, 3000.0))
    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename = "beta_rayleigh")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueHmo"):
            Hmo = self.defaultValueHmo
        else:
            Hmo = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueTp"):
            Tp = self.defaultValueTp
        else:
            Tp = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_d"):
            d = self.defaultValue_d
        else:
            d = caseInputList[currIndex]

        return Hmo, Tp, d
    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex = 0):
        Hmo, Tp, d = self.getCalcValues(caseInputList)
        dataDict = {"Hmo": Hmo, "Tp": Tp, "d": d}

        Htype = []
        Htype.append(0.50) #Hmed;
        Htype.append(0.66) #H1/3 (1-1/3);
        Htype.append(0.90) #H1/10 (1-1/10);
        Htype.append(0.99) #H1/100 (1-1/100);

        Hb = ERRWAVBRK1(d, 0.9)
        if Hmo >= Hb:
            self.errorMsg =\
                "Error: Input wave broken (Hb = %6.2f %s)" % (Hb, self.labelUnitDist)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        L, k = WAVELEN(d, Tp, 50, self.g)
        steep, maxstp = ERRSTP(Hmo, d, L)
        if ComplexUtil.greaterThanEqual(steep, maxstp):
            self.errorMsg =\
                "Error: Input wave unstable (Max: %0.4f, [H/L] = %0.4f)" %\
                    (maxstp.real, steep.real)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        dterm = d/(self.g*Tp**2)
        k = 0
        sum1 = 0

        if dterm > 0.01:
            print("Input conditions indicate Rayleigh distribution")
            Hb = math.sqrt(5)*Hmo
            Hinc = Hb/10000
            sigma = Hmo/4
            Hrms = 2*math.sqrt(2)*sigma

            H = [0]
            p = [0]
            index = [0, 0, 0, 0]
            for i in range(2, 10002):
                # Rayleigh distribution
                H.append(Hinc * (i - 1))
                term1 = math.exp(-(H[i - 1]/Hrms)**2)
                term2 = (2 * H[i - 1])/Hrms**2
                p.append(term1 * term2)

                sum1 = sum1 + (p[i - 1]*Hinc)
                if k < 4 and sum1 > Htype[k]:
                    index[k] = i
                    k = k + 1

            Hout = []
            for k in range(1, 4):
                sum2 = 0
                Hstart = H[index[k]]
                Hinc = (Hb - Hstart)/10000
                pprv = p[index[k]]
                Hprv = Hstart

                for i in range(2, 10001):
                    Hnxt = Hstart + Hinc*(i - 1)
                    term1 = math.exp(-(Hnxt/Hrms)**2)
                    term2 = (2 * Hnxt)/Hrms**2
                    pnxt = term1 * term2
                    darea = 0.5*(pprv + pnxt)*Hinc # area of a trapezoid
                    sum2 = sum2 + (Hinc/2.0 + Hprv)*darea
                    pprv = pnxt
                    Hprv = Hnxt
                Hout.append(sum2 / (1 - Htype[k])) # computing centroid (areasum = 1-Htype)
        else:
            Hb = d
            Hinc = Hb / 100.0
            print("Input conditions indicate Beta-Rayleigh distribution")
            a1 = 0.00089
            b1 = 0.834
            a2 = 0.000098
            b2 = 1.208

            d1 = a1*dterm**(-b1)
            if d1 > 35.0:
                self.errorMsg = "Error: d/gT^2 approaching infinity"

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            Hrms = (1/math.sqrt(2))*math.exp(d1)*Hmo # root-mean-square wave height

            d2 = a2 * dterm**(-b2)
            if d2 > 35.0:
                self.errorMsg = "Error: d/gT^2 approaching infinity"

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            Hrmsq = (1/math.sqrt(2))*math.exp(d2)*Hmo**2 # root-mean-quad wave height

            # Computing alpha and beta
            K1 = (Hrms / Hb)**2
            K2 = (Hrmsq**2) / (Hb**4)

            alpha = (K1*(K2 - K1))/(K1**2 - K2)
            beta = ((1.0 - K1)*(K2 - K1))/(K1**2 - K2)

            term1 = (2*sp.gamma(alpha + beta))/(sp.gamma(alpha)*sp.gamma(beta))

            H = []
            p = []
            index = [0, 0, 0, 0]
            for i in range(101):
                # Beta-Rayleigh distribution
                H.append(Hinc*i)
                
                # Avoid division by zero
                try:
                    term2 = (H[i]**(2*alpha - 1))/(Hb**(2*alpha))
                except:
                    term2 = float('inf')
                
                # Avoid division by zero
                try:
                    term3 = (1.0 - (H[i]/Hb)**2)**(beta - 1.0)
                except:
                    term3 = float('inf')
                
                p.append(term1 * term2 * term3)

                sum1 = sum1 + (p[i]*Hinc)
                if k < 4 and sum1 > Htype[k]:
                    index[k] = i
                    k = k + 1

            Hout = []
            for k in range(1, 4):
                sum2 = 0
                Hstart = H[index[k]]
                Hinc = (Hb - Hstart)/20
                pprv = p[index[k]]
                Hprv = Hstart

                for i in range(1, 20):
                    Hnxt = Hstart + Hinc*i
                    term2 = (Hnxt**(2*alpha - 1))/(Hb**(2*alpha))
                    
                    # Avoid division by zero
                    try:
                        term3 = (1 - (Hnxt/Hb)**2)**(beta - 1)
                    except:
                        term3 = float('inf')
                        
                    pnxt = term1*term2*term3
                    darea = 0.5*(pprv + pnxt)*Hinc # area of a trapezoid
                    sum2 = sum2 + (Hinc/2.0 + Hprv)*darea
                    pprv = pnxt
                    Hprv = Hnxt

                Hout.append(sum2 / (1 - Htype[k])) # computing centroid (areasum = 1-Htype)

        Hmed = H[index[0]]

        print("Wave heights")
        print("Hrms\t\t%6.2f %s" % (Hrms, self.labelUnitDist))
        print("Hmed\t\t%6.2f %s" % (Hmed, self.labelUnitDist))
        print("H(1/3)\t\t%6.2f %s" % (Hout[0], self.labelUnitDist))
        print("H(1/10)\t\t%6.2f %s" % (Hout[1], self.labelUnitDist))
        print("H(1/100)\t%6.2f %s" % (Hout[2], self.labelUnitDist))

        dataDict["Hrms"] = Hrms
        dataDict["Hmed"] = Hmed
        dataDict["Hout"] = Hout
        self.fileOutputWriteMain(dataDict, caseIndex)

        if self.isSingleCase:
            self.plotDict = {"Hrms": Hrms, "Hmed": Hmed, "Hout": Hout,\
                "H": H, "p": p}
    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("Hmo       %8.2f %s\n" % (dataDict["Hmo"], self.labelUnitDist))
        self.fileRef.write("Tp        %8.2f s\n" % (dataDict["Tp"]))
        self.fileRef.write("d         %8.2f %s\n\n" % (dataDict["d"], self.labelUnitDist))

        if self.errorMsg != None:
            self.fileRef.write("%s\n" % self.errorMsg)
        else:
            self.fileRef.write("Wave heights\n")
            self.fileRef.write("Hrms      %8.2f %s\n" % (dataDict["Hrms"], self.labelUnitDist))
            self.fileRef.write("Hmed      %8.2f %s\n" % (dataDict["Hmed"], self.labelUnitDist))
            self.fileRef.write("H(1/3)    %8.2f %s\n" % (dataDict["Hout"][0], self.labelUnitDist))
            self.fileRef.write("H(1/10)   %8.2f %s\n" % (dataDict["Hout"][1], self.labelUnitDist))
            self.fileRef.write("H(1/100)  %8.2f %s\n" % (dataDict["Hout"][2], self.labelUnitDist))

        exportData = [dataDict["Hmo"], dataDict["Tp"], dataDict["d"]]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["Hrms"], dataDict["Hmed"],\
                dataDict["Hout"][0], dataDict["Hout"][1], dataDict["Hout"][2]]
        self.exporter.writeData(exportData)
    # end fileOutputWrite

    def hasPlot(self):
        return True

    def performPlot(self):
        plt.figure(1, figsize = self.plotConfigDict["figSize"],\
            dpi = self.plotConfigDict["dpi"])
        plt.plot(self.plotDict["Hout"][0], 0, "ks",\
            self.plotDict["Hout"][1], 0, "ro",\
            self.plotDict["Hout"][2], 0, "bd",\
            self.plotDict["Hrms"], 0, "g*",\
            self.plotDict["Hmed"], 0, "m^",\
            self.plotDict["H"], self.plotDict["p"])
        plt.xlabel("H [%s]" % self.labelUnitDist,\
            fontsize = self.plotConfigDict["axisLabelFontSize"])
        plt.ylabel("Probability density p(H)",\
            fontsize = self.plotConfigDict["axisLabelFontSize"])
        plt.legend([r"H$_{1/3}$", r"H$_{1/10}$", r"H$_{1/100}$",\
            r"H$_{rms}$", r"H$_{med}$"])

        plt.show()

        self.fileOutputPlotWriteData()
    # end performPlot

    def fileOutputPlotWriteData(self):
        self.fileRef.write("Counter\tWave height\tProbability density\n")

        for i in range(len(self.plotDict["H"])):
            self.fileRef.write("%d\t%-6.5f\t\t%-6.5f\n" %\
                ((i + 1), self.plotDict["H"][i], self.plotDict["p"][i]))
Ejemplo n.º 7
0
class SnellsLaw(BaseDriver):
    def __init__(self, H1 = None, T = None, d1 = None, alpha1 = None,\
        cotphi = None, d2 = None):
        self.exporter = EXPORTER("output/exportSnellsLaw")
        
        if H1 != None:
            self.isSingleCase = True
            self.defaultValueH1 = H1
        if T != None:
            self.isSingleCase = True
            self.defaultValueT = T
        if d1 != None:
            self.isSingleCase = True
            self.defaultValue_d1 = d1
        if alpha1 != None:
            self.isSingleCase = True
            self.defaultValue_alpha1 = alpha1
        if cotphi != None:
            self.isSingleCase = True
            self.defaultValue_cotphi = cotphi
        if d2 != None:
            self.isSingleCase = True
            self.defaultValue_d2 = d2

        super(SnellsLaw, self).__init__()

        self.exporter.close()
    # end __init__

    def userInput(self):
        super(SnellsLaw, self).userInput()

        self.water, self.rho = USER_INPUT.SALT_FRESH_WATER(self.isMetric)
    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueH1"):
            self.inputList.append(BaseField("H1: wave height at known location (%s)" % (self.labelUnitDist), 0.1, 200.0))
        if not hasattr(self, "defaultValueT"):
            self.inputList.append(BaseField("T: wave period at known location (sec)", 1.0, 1000.0))
        if not hasattr(self, "defaultValue_d1"):
            self.inputList.append(BaseField("d1: water depth at known location (%s)" % (self.labelUnitDist), 0.1, 5000.0))
        if not hasattr(self, "defaultValue_alpha1"):
            self.inputList.append(BaseField("alpha1: wave crest angle (deg)", 0.0, 90.0))
        if not hasattr(self, "defaultValue_cotphi"):
            self.inputList.append(BaseField("cotphi: cotan of nearshore slope", 5.0, 1000.0))
        if not hasattr(self, "defaultValue_d2"):
            self.inputList.append(BaseField("d2: water depth at desired location (%s)" % (self.labelUnitDist), 0.1, 5000.0))
    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename = "snells_law")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueH1"):
            H1 = self.defaultValueH1
        else:
            H1 = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueT"):
            T = self.defaultValueT
        else:
            T = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_d1"):
            d1 = self.defaultValue_d1
        else:
            d1 = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_alpha1"):
            alpha1 = self.defaultValue_alpha1
        else:
            alpha1 = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_cotphi"):
            cotphi = self.defaultValue_cotphi
        else:
            cotphi = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_d2"):
            d2 = self.defaultValue_d2
        else:
            d2 = caseInputList[currIndex]

        return H1, T, d1, alpha1, cotphi, d2
    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex = 0):
        H1, T, d1, alpha1, cotphi, d2 =\
            self.getCalcValues(caseInputList)
        dataDict = {"H1": H1, "T": T, "d1": d1, "alpha1": alpha1,\
            "cotphi": cotphi, "d2": d2}
        
        m = 1.0 / cotphi

        Hb = ERRWAVBRK1(d1, 0.78)
        if not (H1 < Hb):
            self.errorMsg = "Error: Known wave broken (Hb = %6.2f %s)" %\
                (Hb, self.labelUnitDist)
            
            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        #determine known wave properties
        c1, c0, cg1, cg0, k1, L1, L0, reldep1 = LWTGEN(d1, T, self.g)
        E1, P1, Ur1, setdown1 = LWTTWM(cg1, d1, H1, L1, reldep1, self.rho, self.g, k1)

        steep, maxstp = ERRSTP(H1, d1, L1)
        if not ComplexUtil.lessThan(steep, maxstp):
            self.errorMsg = "Error: Known wave unstable (Max: %0.4f, [H/L] = %0.4f)" %\
                (maxstp.real, steep.real)
            
            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        #determine deepwater wave properties
        alpha0, H0, self.errorMsg = LWTDWS(alpha1, c1, cg1, c0, H1)
        if self.errorMsg != None:
            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        E0 = (1.0/8.0)*self.rho*self.g*(H0**2)
        P0 = E0*cg0
        HL = H0/L0

        if not ComplexUtil.lessThan(HL, (1.0/7.0)):
            self.errorMsg = "Error: Deepwater wave unstable, [H0/L0] > (1/7)"
            
            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        #determine subject wave properties
        c2, c0, cg2, cg0, k2, L2, L0, reldep2 = LWTGEN(d2, T, self.g)
        alpha2, H2, kr, ks = LWTTWS(alpha0, c2, cg2, c0, H0)
        E2, P2, Ur2, sedown2 = LWTTWM(cg2, d2, H2, L2, reldep2, self.rho, self.g, k2)

        Hb, db = ERRWAVBRK3(H0, L0, T, m)
        if not ComplexUtil.lessThan(H2, Hb):
            self.errorMsg = "Error: Subject wave broken (Hb = %6.2f %s, hb = %6.2f %s)" %\
                (Hb.real, self.labelUnitDist, db.real, self.labelUnitDist)
            
            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        steep, maxstp = ERRSTP(H2, d2, L2)
        if not ComplexUtil.lessThan(steep, maxstp):
            self.errorMsg = "Error: Subject wave unstable (Max: %0.4f, [H/L] = %0.4f)" %\
                (maxstp.real, steep.real)
            
            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        print("\t\t\tKnown\t\tDeepwater\t\tSubject\t\tUnits")
        print("Wave height\t\t%-5.2f\t\t%-5.2f\t\t\t%-5.2f\t\t%s" %\
            (H1, H0.real, H2.real, self.labelUnitDist))
        print("Wave crest angle\t%-5.2f\t\t%-5.2f\t\t\t%-5.2f\t\tdeg" %\
            (alpha1, alpha0.real, alpha2.real))
        print("Wavelength\t\t%-5.2f\t\t%-5.2f\t\t\t%-5.2f\t\t%s" %\
            (L1.real, L0.real, L2.real, self.labelUnitDist))
        print("Celerity\t\t%-5.2f\t\t%-5.2f\t\t\t%-5.2f\t\t%s/s" %\
            (c1.real, c0.real, c2.real, self.labelUnitDist))
        print("Group speed\t\t%-5.2f\t\t%-5.2f\t\t\t%-5.2f\t\t%s/s" %\
            (cg1.real, cg0.real, cg2.real, self.labelUnitDist))
        print("Energy density\t\t%-8.2f\t%-8.2f\t\t%-8.2f\t%s-%s/%s^2" %\
            (E1.real, E0.real, E2.real, self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))
        print("Energy flux\t\t%-8.2f\t%-8.2f\t\t%-8.2f\t%s-%s/sec-%s" %\
            (P1.real, P0.real, P2.real, self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))
        print("Ursell number\t\t%-5.2f\t\t\t\t\t%-5.2f" % (Ur1.real, Ur2.real))
        print("Wave steepness\t\t\t\t%-5.2f" % HL.real)

        print("\nBreaking Parameters")
        print("Breaking height\t\t%-5.2f %s" % (Hb.real, self.labelUnitDist))
        print("Breaking depth\t\t%-5.2f %s" % (db.real, self.labelUnitDist))

        dataDict.update({"H0": H0, "H2": H2,\
            "alpha0": alpha0, "alpha2": alpha2, "L1": L1,\
            "L0": L0, "L2": L2, "c1": c1, "c0": c0, "c2": c2,\
            "cg1": cg1, "cg0": cg0, "cg2": cg2, "E1": E1, "E0": E0,\
            "E2": E2, "P1": P1, "P0": P0, "P2": P2, "Ur1": Ur1,\
            "Ur2": Ur2, "HL": HL, "Hb": Hb, "db": db})
        self.fileOutputWriteMain(dataDict, caseIndex)
    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("H1\t%6.2f %s\n" % (dataDict["H1"], self.labelUnitDist))
        self.fileRef.write("T\t%6.2f s\n" % dataDict["T"])
        self.fileRef.write("d1\t%6.2f %s\n" % (dataDict["d1"], self.labelUnitDist))
        self.fileRef.write("alpha1\t%6.2f deg\n" % dataDict["alpha1"])
        self.fileRef.write("cotphi\t%6.2f\n" % dataDict["cotphi"])
        self.fileRef.write("d2\t%6.2f %s\n\n" % (dataDict["d2"], self.labelUnitDist))

        if self.errorMsg != None:
            self.fileRef.write("%s\n" % self.errorMsg)
        else:
            self.fileRef.write("\t\t\tKnown\t\tDeepwater\t\tSubject\t\tUnits\n")
            self.fileRef.write("Wave height\t\t%-5.2f\t\t%-5.2f\t\t\t%-5.2f\t\t%s\n" %\
                (dataDict["H1"], dataDict["H0"].real, dataDict["H2"].real, self.labelUnitDist))
            self.fileRef.write("Wave crest angle\t%-5.2f\t\t%-5.2f\t\t\t%-5.2f\t\tdeg\n" %\
                (dataDict["alpha1"], dataDict["alpha0"].real, dataDict["alpha2"].real))
            self.fileRef.write("Wavelength\t\t%-5.2f\t\t%-5.2f\t\t\t%-5.2f\t\t%s\n" %\
                (dataDict["L1"].real, dataDict["L0"].real, dataDict["L2"].real, self.labelUnitDist))
            self.fileRef.write("Celerity\t\t%-5.2f\t\t%-5.2f\t\t\t%-5.2f\t\t%s/s\n" %\
                (dataDict["c1"].real, dataDict["c0"].real, dataDict["c2"].real, self.labelUnitDist))
            self.fileRef.write("Group speed\t\t%-5.2f\t\t%-5.2f\t\t\t%-5.2f\t\t%s/s\n" %\
                (dataDict["cg1"].real, dataDict["cg0"].real, dataDict["cg2"].real, self.labelUnitDist))
            self.fileRef.write("Energy density\t\t%-8.2f\t%-8.2f\t\t%-8.2f\t%s-%s/%s^2\n" %\
                (dataDict["E1"].real, dataDict["E0"].real, dataDict["E2"].real, self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))
            self.fileRef.write("Energy flux\t\t%-8.2f\t%-8.2f\t\t%-8.2f\t%s-%s/sec-%s\n" %\
                (dataDict["P1"].real, dataDict["P0"].real, dataDict["P2"].real, self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))
            self.fileRef.write("Ursell number\t\t%-5.2f\t\t\t\t\t%-5.2f\n" %\
                (dataDict["Ur1"].real, dataDict["Ur2"].real))
            self.fileRef.write("Wave steepness\t\t\t\t%-5.2f\n" % dataDict["HL"].real)
    
            self.fileRef.write("\nBreaking Parameters\n")
            self.fileRef.write("Breaking height\t\t%-5.2f %s\n" %\
                (dataDict["Hb"].real, self.labelUnitDist))
            self.fileRef.write("Breaking depth\t\t%-5.2f %s\n" %\
                (dataDict["db"].real, self.labelUnitDist))
            
        exportData = [dataDict["H1"], dataDict["T"], dataDict["d1"],\
            dataDict["alpha1"], dataDict["cotphi"], dataDict["d2"]]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["H1"], dataDict["H0"],\
                dataDict["H2"], dataDict["alpha1"], dataDict["alpha0"],\
                dataDict["alpha2"], dataDict["L1"], dataDict["L0"],\
                dataDict["L2"], dataDict["c1"], dataDict["c0"],\
                dataDict["c2"], dataDict["cg1"], dataDict["cg0"],\
                dataDict["cg2"], dataDict["E1"], dataDict["E0"],\
                dataDict["E2"], dataDict["P1"], dataDict["P0"],\
                dataDict["P2"], dataDict["Ur1"], dataDict["Ur2"],\
                dataDict["HL"], dataDict["Hb"], dataDict["db"]]
        self.exporter.writeData(exportData)
Ejemplo n.º 8
0
class WavetransPerm(BaseDriver):
    def __init__(self, H = None, T = None, ds = None, d50 = None,\
        por = None, hs = None, cottheta = None, b = None,\
        th = None, hlen = None):
        self.exporter = EXPORTER("output/exportWavetransPerm")

        if H != None:
            self.isSingleCase = True
            self.defaultValueH = H
        if T != None:
            self.isSingleCase = True
            self.defaultValueT = T
        if ds != None:
            self.defaultValue_ds = ds
        if d50 != None:
            self.defaultValue_d50 = d50
        if por != None:
            self.defaultValue_por = por
        if hs != None:
            self.defaultValue_hs = hs
        if cottheta != None:
            self.defaultValue_cottheta = cottheta
        if b != None:
            self.defaultValue_b = b
        if th != None:
            self.defaultValue_th = th
        if hlen != None:
            self.defaultValue_hlen = hlen

        super(WavetransPerm, self).__init__()

        self.exporter.close()

    # end __init__

    def userInput(self):
        super(WavetransPerm, self).userInput()

        if hasattr(self, "defaultValue_ds"):
            self.ds = self.defaultValue_ds
        else:
            self.ds = USER_INPUT.DATA_VALUE(\
                "ds: water depth at structure toe (%s)" %\
                self.labelUnitDist, 0.1, 200.0)

        # define NM and NL if any relevant defaults are used
        if hasattr(self, "defaultValue_d50"):
            self.d50 = self.defaultValue_d50
            self.NM = len(self.d50)

        if hasattr(self, "defaultValue_por"):
            self.por = self.defaultValue_por
            self.NM = len(self.por)

        if hasattr(self, "defaultValue_th"):
            self.th = self.defaultValue_th
            self.NL = len(self.th)

        if hasattr(self, "defaultValue_hlen"):
            self.hlen = self.defaultValue_hlen
            self.NM = len(self.hlen)
            self.NL = len(self.hlen[0])

        if not hasattr(self, "NM"):
            self.NM = USER_INPUT.DATA_VALUE(\
                "NM: number of materials comprising the breakwater", 1, 4)
            self.NM = int(self.NM)

        if not hasattr(self, "d50"):
            self.d50 = []
            for i in range(self.NM):
                self.d50.append(USER_INPUT.DATA_VALUE(\
                    "d50: mean diameter of material #%d (%s)" %\
                    ((i + 1), self.labelUnitDist), 0.05, 99.0))

        if not hasattr(self, "defaultValue_por"):
            self.por = []
            for i in range(self.NM):
                self.por.append(USER_INPUT.DATA_VALUE(\
                    "p: porosity of material #%d (%%)" % (i + 1), 0.0, 100.0))
            self.por = [i / 100.0 for i in self.por]

        if not hasattr(self, "defaultValue_hs"):
            self.hs = USER_INPUT.DATA_VALUE(\
                "hs: structure height above toe (%s)" %\
                self.labelUnitDist, 0.1, 200.0)
        else:
            self.hs = self.defaultValue_hs

        if not hasattr(self, "defaultValue_cottheta"):
            self.cottheta = USER_INPUT.DATA_VALUE(\
                "cottheta: cotangent of structure slope", 1.0, 5.0)
        else:
            self.cottheta = self.defaultValue_cottheta

        if not hasattr(self, "defaultValue_b"):
            self.b = USER_INPUT.DATA_VALUE(\
                "b: structure crest width (%s)" % self.labelUnitDist, 0.1, 200.0)
        else:
            self.b = self.defaultValue_b

        if not hasattr(self, "NL"):
            self.NL = USER_INPUT.DATA_VALUE(\
                "NL: number of horizontal layers in the breakwater", 1, 4)
            self.NL = int(self.NL)

        if not hasattr(self, "th"):
            self.th = []
            for i in range(self.NL):
                self.th.append(USER_INPUT.DATA_VALUE(\
                    "th: thickness of horizontal layer #%d (%s)" %\
                    ((i + 1), self.labelUnitDist), 0.1, 200.0))

        if not hasattr(self, "hlen"):
            self.hlen = []
            for i in range(self.NM):
                self.hlen.append([])

                for j in range(self.NL):
                    self.hlen[i].append(USER_INPUT.DATA_VALUE(\
                        "hlen: horizontal length of material #%d in layer #%d (%s)" %\
                        ((i + 1), (j + 1), self.labelUnitDist), 0.0, 200.0))

        self.water, self.rho = USER_INPUT.SALT_FRESH_WATER(self.isMetric)

    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueH"):
            self.inputList.append(BaseField(\
                "H: incident wave height (%s)" % self.labelUnitDist, 0.1, 100.0))

        if not hasattr(self, "defaultValueT"):
            self.inputList.append(BaseField("T: wave period (s)", 1.0, 1000.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename="wavetrans_perm")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueH"):
            H = self.defaultValueH
        else:
            H = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueT"):
            T = self.defaultValueT
        else:
            T = caseInputList[currIndex]

        return H, T, self.ds, self.d50, self.por, self.hs,\
            self.cottheta, self.b, self.th, self.hlen

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        H, T, ds, d50, por, hs, cottheta, b, th, hlen =\
            self.getCalcValues(caseInputList)
        dataDict = {"H": H, "T": T, "ds": ds, "d50": d50, "por": por,\
            "hs": hs, "cottheta": cottheta, "b": b, "th": th,\
            "hlen": hlen}

        if not self.isMetric:
            if self.water == "S" or self.water == "s":
                nu = 14.643223710**(-6)  #salt water
            else:
                nu = 0.0000141  #ft^2/s KINEMATIC VISCOSITY OF THE WATER AT 50 DEGREES FAHRENHEIT
        else:
            if self.water == "S" or self.water == "s":
                nu = 1.3604 * 10**(-6)  # salt water
            else:
                nu = 1.307 * 10**(-6)  # m^2/s fresh

        Hb = ERRWAVBRK1(ds, 0.78)
        if not (H < Hb):
            self.errorMsg = "Error: Input wave broken (Hb = %6.2f %s)" % (
                Hb, self.labelUnitDist)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        Hbs = ERRWAVBRK2(T, 1.0 / cottheta, ds)
        if not (H < Hbs):
            self.errorMsg = "Error: Input wave breaking at toe of the structure (Hbs = %6.2f %s)" % (
                Hbs, self.labelUnitDist)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        L, k = WAVELEN(ds, T, 50, self.g)

        steep, maxstp = ERRSTP(H, ds, L)
        if not ComplexUtil.lessThan(steep, maxstp):
            self.errorMsg = "Error: Input wave unstable (Max: %0.4f, [H/L] = %0.4f)" %\
                (ComplexUtil.getDisplayVal(maxstp), ComplexUtil.getDisplayVal(steep))

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        if not (ds < hs):
            self.errorMsg = "Error: Method does not apply to submerged structures."

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        if not (np.isclose(sum(th), ds)):
            self.errorMsg = "Error: Water depth must equal sum of all layer thicknesses."

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        KTt, Kto, KT, Kr, Ht, L, self.errorMsg = MADSEELG(\
            H, T, ds, hs, b, self.NL, th, hlen, self.NM, d50, por, cottheta, nu, self.g)
        if self.errorMsg != None:
            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        print("Reflection coefficient, Kr\t\t%-6.3f" % Kr)
        print("Wave transmission coefficient")
        print("Wave Transmission (Through), KTt\t%-6.3f" % KTt)
        print("Wave Transmission (Overtopping), KTo\t%-6.3f" % Kto)
        print("Wave Transmission (Total), KT\t\t%-6.3f" % KT)
        print("Transmitted wave height, Ht\t\t%-6.2f %s" %
              (Ht, self.labelUnitDist))

        dataDict.update({"Kr": Kr, "KTt": KTt, "Kto": Kto, "KT": KT, "Ht": Ht})
        self.fileOutputWriteMain(dataDict)

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("H\t\t%6.2f %s\n" %
                           (dataDict["H"], self.labelUnitDist))
        self.fileRef.write("T\t\t%6.2f s\n" % dataDict["T"])
        self.fileRef.write("ds\t\t%6.2f %s\n" %
                           (dataDict["ds"], self.labelUnitDist))
        for i in range(len(dataDict["d50"])):
            self.fileRef.write("d50 #%i\t\t%6.2f %s\n" %\
                ((i + 1), dataDict["d50"][i], self.labelUnitDist))
        for i in range(len(dataDict["por"])):
            self.fileRef.write("por #%i\t\t%6.2f%%\n" %\
                ((i + 1), dataDict["por"][i]*100))
        self.fileRef.write("hs\t\t%6.2f %s\n" %\
            (dataDict["hs"], self.labelUnitDist))
        self.fileRef.write("cottheta\t%6.2f\n" % dataDict["cottheta"])
        self.fileRef.write("b\t\t%6.2f %s\n" %\
            (dataDict["b"], self.labelUnitDist))
        for i in range(len(dataDict["th"])):
            self.fileRef.write("th #%d\t\t%6.2f %s\n" %\
                ((i + 1), dataDict["th"][i], self.labelUnitDist))
        for i in range(len(dataDict["hlen"])):
            for j in range(len(dataDict["hlen"][i])):
                self.fileRef.write("Len mat %d,\t%6.2f %s\n" %\
                    ((i + 1), dataDict["hlen"][i][j], self.labelUnitDist))
                self.fileRef.write("  layer %d\n" % (j + 1))

        if self.errorMsg != None:
            self.fileRef.write("\n%s\n" % self.errorMsg)
        else:
            self.fileRef.write("\nReflection coefficient, Kr\t\t%-6.3f\n" %\
                dataDict["Kr"])
            self.fileRef.write("Wave transmission coefficient\n")
            self.fileRef.write("Wave Transmission (Through), KTt\t%-6.3f\n" %\
                dataDict["KTt"])
            self.fileRef.write("Wave Transmission (Overtopping), KTo\t%-6.3f\n" %\
                dataDict["Kto"])
            self.fileRef.write("Wave Transmission (Total), KT\t\t%-6.3f\n" %\
                dataDict["KT"])
            self.fileRef.write("Transmitted wave height, Ht\t\t%-6.2f %s\n" %\
                (dataDict["Ht"], self.labelUnitDist))

        exportData = [dataDict["H"], dataDict["T"], dataDict["ds"]] +\
            [i for i in dataDict["d50"]] + [i*100 for i in dataDict["por"]] +\
            [dataDict["hs"], dataDict["cottheta"], dataDict["b"]] +\
            [i for i in dataDict["th"]] +\
            [j for i in dataDict["hlen"] for j in i]
        if self.errorMsg != None:
            exportData.append("Error")
        else:
            exportData = exportData + [dataDict["Kr"], dataDict["KTt"],\
                dataDict["Kto"], dataDict["KT"], dataDict["Ht"]]
        self.exporter.writeData(exportData)
Ejemplo n.º 9
0
class LinearWaveTheory(BaseDriver):
    def __init__(self, H = None, T = None, d = None,\
        z = None, xL = None):
        self.exporter = EXPORTER("output/exportLinearWaveTheory")
        
        if H != None:
            self.isSingleCase = True
            self.defaultValueH = H
        if T != None:
            self.isSingleCase = True
            self.defaultValueT = T
        if d != None:
            self.isSingleCase = True
            self.defaultValue_d = d
        if z != None:
            self.isSingleCase = True
            self.defaultValue_z = z
        if xL != None:
            self.isSingleCase = True
            self.defaultValue_xL = xL

        super(LinearWaveTheory, self).__init__()

        self.exporter.close()
    # end __init__

    def userInput(self):
        super(LinearWaveTheory, self).userInput()

        self.waterType, self.rho =\
            USER_INPUT.SALT_FRESH_WATER(self.isMetric)
    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueH"):
            self.inputList.append(BaseField(\
                "H: wave height (%s)" % self.labelUnitDist, 0.1, 200.0))
        if not hasattr(self, "defaultValueT"):
            self.inputList.append(BaseField(\
                "T: wave period (sec)", 1.0, 1000.0))
        if not hasattr(self, "defaultValue_d"):
            self.inputList.append(BaseField(\
                "d: water depth (%s)" % self.labelUnitDist, 0.1, 5000.0))
        if not hasattr(self, "defaultValue_z"):
            self.inputList.append(BaseField(\
                "z: vertical coordinate (%s)" % self.labelUnitDist,\
                -5100.0, 100.0))
        if not hasattr(self, "defaultValue_xL"):
            self.inputList.append(BaseField(\
                "xL: horizontal coordinate as fraction of wavelength (x/L)",\
                0.0, 1.0))
    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename = "linear_wave_theory")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueH"):
            H = self.defaultValueH
        else:
            H = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueT"):
            T = self.defaultValueT
        else:
            T = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_d"):
            d = self.defaultValue_d
        else:
            d = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_z"):
            z = self.defaultValue_z
        else:
            z = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_xL"):
            xL = self.defaultValue_xL
        else:
            xL = caseInputList[currIndex]
            currIndex = currIndex + 1

        return H, T, d, z, xL
    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex = 0):
        H, T, d, z, xL = self.getCalcValues(caseInputList)
        dataDict = {"H": H, "T": T, "d": d, "z": z, "xL": xL}

        twopi = 2*math.pi
        nIteration = 50

        L, k = WAVELEN(d, T, nIteration, self.g)

        theta = xL*twopi #theta=(kx-wt) where arbitrarily t=0 and k=2*pi/L

        # Check for monochromatic wave breaking (depth limited - no slope)
        Hb = ERRWAVBRK1(d, 0.78)
        if not (H < Hb):
            self.errorMsg = "Error: Input wave broken (Hb = %6.2f %s)" %\
                (Hb, self.labelUnitDist)
            
            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        # Check to make sure vertical coordinate is within waveform
        eta = (H/2)*math.cos(theta)
        if not (z < eta and (z + d) > 0):
            self.errorMsg = "Error: Point outside waveform."
            
            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        # Main Computations
        arg = (2*k*d/(math.sinh(2*k*d)))
        tot = d + z

        C = L/T
        Cg = 0.5*(1 + arg)*C
        E = (1.0/8.0)*self.rho*self.g*(H**2)
        Ef = E*Cg
        Ur = L**2*H/(d**3)
        px = (-H/2)*(math.cosh(k*tot)/math.sinh(k*d))*math.sin(theta)
        py = (H/2)*(math.sinh(k*tot)/math.sinh(k*d))*math.cos(theta)
        u = (H*math.pi/T)*(math.cosh(k*tot)/math.sinh(k*d))*math.cos(theta)
        w = (H*math.pi/T)*(math.sinh(k*tot)/math.sinh(k*d))*math.sin(theta)
        dudt = (H*2*math.pi**2/(T**2))*(math.cosh(k*tot)/math.sinh(k*d))*math.sin(theta)
        dwdt = (-H*2*math.pi**2/(T**2))*(math.sinh(k*tot)/math.sinh(k*d))*math.cos(theta)
        pres = -self.rho*self.g*z + self.rho*self.g*(H/2)*(math.cosh(k*tot)/math.cosh(k*d))*math.cos(theta)

        # plotting waveform
        if self.isSingleCase:
            plotxL = np.arange(-1, 1, 0.001)
            plottheta = plotxL * np.pi * 2
    
            ploteta = (H / 2) * np.cos(plottheta)
            plotu = (H * np.pi / T) * (np.cosh(k * tot) / np.sinh(k * d)) * np.cos(plottheta)
            plotw = (H * np.pi / T) * (np.sinh(k * tot) / np.sinh(k * d)) * np.sin(plottheta)
    
            plt.subplot(3, 1, 1)
            plt.plot(plotxL, ploteta, lw=2)
            plt.ylabel('Elevation [%s]' % self.labelUnitDist)
            plt.ylim(min(ploteta) - 1, max(ploteta) + 1)
            plt.axhline(color = 'r', linestyle = '--')
    
            # subplot
            plt.subplot(3, 1, 2)
            plt.plot(plotxL, plotu, lw=2)
            plt.axhline(color = 'r', linestyle = '--')
            plt.ylabel('Velocity, u [%s/s]' % self.labelUnitDist)
            plt.ylim(min(plotu) - 1, max(plotu) + 1)
    
            # subplot
            plt.subplot(3, 1, 3)
            plt.plot(plotxL, plotw, lw=2)
            plt.axhline(color = 'r', linestyle = '--')
            plt.ylabel('Velocity, w [%s/s]' % self.labelUnitDist)
            plt.ylim(min(plotw) - 1, max(plotw) + 1)
    
            plt.tight_layout(pad=0.4)
    
            plt.show()

        print("\t\t\t\t\tUnits")
        print("Wavelength\t\t\t%-6.2f\t%s" % (L, self.labelUnitDist))
        print("Celerity\t\t\t%-6.2f\t%s/s" % (C, self.labelUnitDist))
        print("Group speed\t\t\t%-6.2f\t%s/s" % (Cg, self.labelUnitDist))
        print("Energy density\t\t\t%-8.2f%s-%s/%s^2" %\
            (E, self.labelUnitWt, self.labelUnitDist, self.labelUnitDist))
        print("Energy flux\t\t\t%-8.2f%s-%s/%s-s" %\
            (Ef, self.labelUnitWt, self.labelUnitDist, self.labelUnitDist))
        print("Ursell number\t\t\t%-6.2f" % Ur)
        print("Water Surface Elevation\t\t%-6.2f\t%s" %\
            (eta, self.labelUnitDist))
        print("Horz. displacement\t\t%-6.2f\t%s" % (px, self.labelUnitDist))
        print("Vert. displacement\t\t%-6.2f\t%s" % (py, self.labelUnitDist))
        print("Horz. velocity\t\t\t%-6.2f\t%s/s" % (u, self.labelUnitDist))
        print("Vert. velocity\t\t\t%-6.2f\t%s/s" % (w, self.labelUnitDist))
        print("Horz. acceleration\t\t%-6.2f\t%s/s^2" %\
            (dudt, self.labelUnitDist))
        print("Vert. acceleration\t\t%-6.2f\t%s/s^2" %\
            (dwdt, self.labelUnitDist))
        print("Pressure\t\t\t%-8.2f%s/%s^2" %\
            (pres, self.labelUnitWt, self.labelUnitDist))

        dataDict["L"] = L
        dataDict["C"] = C
        dataDict["Cg"] = Cg
        dataDict["E"] = E
        dataDict["Ef"] = Ef
        dataDict["Ur"] = Ur
        dataDict["eta"] = eta
        dataDict["px"] = px
        dataDict["py"] = py
        dataDict["u"] = u
        dataDict["w"] = w
        dataDict["dudt"] = dudt
        dataDict["dwdt"] = dwdt
        dataDict["pres"] = pres
        self.fileOutputWriteMain(dataDict, caseIndex)
    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Linear Wave Theory Summary\n\n");

        self.fileRef.write("Input\n")
        self.fileRef.write("Wave heights\t\t\t%8.2f %s\n" %\
            (dataDict["H"], self.labelUnitDist))
        self.fileRef.write("Wave period\t\t\t%8.2f s\n" % dataDict["T"])
        self.fileRef.write("Water depth\t\t\t%8.2f %s\n" %\
            (dataDict["d"], self.labelUnitDist))
        self.fileRef.write("Vertical coordinate\t\t%8.2f %s\n" %\
            (dataDict["z"], self.labelUnitDist))
        self.fileRef.write("Horizontal coordinate as\t%8.2f (x/L)\n" %\
            dataDict["xL"])
        self.fileRef.write("fraction of wavelength\n\n")

        if self.errorMsg != None:
            self.fileRef.write("%s\n" % self.errorMsg)
        else:
            self.fileRef.write("Item\t\t\t\tValue\t\tUnits\n")
            self.fileRef.write("Wavelength\t\t\t%8.2f\t%s\n" % (dataDict["L"], self.labelUnitDist))
            self.fileRef.write("Celerity\t\t\t%8.2f\t%s/s\n" % (dataDict["C"], self.labelUnitDist))
            self.fileRef.write("Group speed\t\t\t%8.2f\t%s/s\n" % (dataDict["Cg"], self.labelUnitDist))
            self.fileRef.write("Energy density\t\t\t%8.2f\t%s-%s/%s^2\n" %\
                (dataDict["E"], self.labelUnitWt, self.labelUnitDist, self.labelUnitDist))
            self.fileRef.write("Energy flux\t\t\t%8.2f\t%s-%s/%s-s\n" %\
                (dataDict["Ef"], self.labelUnitWt, self.labelUnitDist, self.labelUnitDist))
            self.fileRef.write("Ursell number\t\t\t%8.2f\n" % dataDict["Ur"])
            self.fileRef.write("Water Surface Elevation\t\t%8.2f\t%s\n" %\
                (dataDict["eta"], self.labelUnitDist))
            self.fileRef.write("Horz. displacement\t\t%8.2f\t%s\n" % (dataDict["px"], self.labelUnitDist))
            self.fileRef.write("Vert. displacement\t\t%8.2f\t%s\n" % (dataDict["py"], self.labelUnitDist))
            self.fileRef.write("Horz. velocity\t\t\t%8.2f\t%s/s\n" % (dataDict["u"], self.labelUnitDist))
            self.fileRef.write("Vert. velocity\t\t\t%8.2f\t%s/s\n" % (dataDict["w"], self.labelUnitDist))
            self.fileRef.write("Horz. acceleration\t\t%8.2f\t%s/s^2\n" %\
                (dataDict["dudt"], self.labelUnitDist))
            self.fileRef.write("Vert. acceleration\t\t%8.2f\t%s/s^2\n" %\
                (dataDict["dwdt"], self.labelUnitDist))
            self.fileRef.write("Pressure\t\t\t%8.2f\t%s/%s^2\n" %\
                (dataDict["pres"], self.labelUnitWt, self.labelUnitDist))
            
        exportData = [dataDict["H"], dataDict["T"], dataDict["d"], dataDict["z"], dataDict["xL"] ]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["L"], dataDict["C"],\
                dataDict["Cg"], dataDict["E"], dataDict["Ef"],dataDict["Ur"], dataDict["eta"],\
                dataDict["px"], dataDict["py"], dataDict["u"], dataDict["w"], dataDict["dudt"],\
                dataDict["dwdt"], dataDict["pres"]]
        self.exporter.writeData(exportData)
Ejemplo n.º 10
0
class IrrWaveTrans(BaseDriver):
    def __init__(self, Ho = None, d = None, Ts = None,\
        cotnsl = None, direc = None):
        self.exporter = EXPORTER("output/exportIrrWaveTrans")

        if Ho != None:
            self.isSingleCase = True
            self.defaultValueHo = Ho
        if d != None:
            self.isSingleCase = True
            self.defaultValue_d = d
        if Ts != None:
            self.isSingleCase = True
            self.defaultValueTs = Ts
        if cotnsl != None:
            self.isSingleCase = True
            self.defaultValue_cotnsl = cotnsl
        if direc != None:
            self.isSingleCase = True
            self.defaultValue_direc = direc

        super(IrrWaveTrans, self).__init__()

        self.exporter.close()

    # end __init__

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueHo"):
            if self.isMetric:
                self.inputList.append(BaseField(\
                    "Ho: significant deepwater wave height (m)", 0.61, 6.09))
            else:
                self.inputList.append(BaseField(\
                    "Ho: significant deepwater wave height (ft)", 2.0, 20.0))

        if not hasattr(self, "defaultValue_d"):
            self.inputList.append(BaseField(\
                "d: water depth (%s)" % self.labelUnitDist, 10.0, 5000.0))
        if not hasattr(self, "defaultValueTs"):
            self.inputList.append(BaseField(\
                "Ts: significant wave period (s)", 4.0, 16.0))
        if not hasattr(self, "defaultValue_cotnsl"):
            self.inputList.append(BaseField(\
                "cotnsl: cotangent of nearshore slope", 30.0, 100.0))
        if not hasattr(self, "defaultValue_direc"):
            self.inputList.append(BaseField(\
                "direc: principle direction of incident wave spectrum (deg)", -75.0, 75.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename="irr_wave_trans")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueHo"):
            Ho = self.defaultValueHo
        else:
            Ho = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_d"):
            d = self.defaultValue_d
        else:
            d = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueTs"):
            Ts = self.defaultValueTs
        else:
            Ts = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_cotnsl"):
            cotnsl = self.defaultValue_cotnsl
        else:
            cotnsl = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_direc"):
            direc = self.defaultValue_direc
        else:
            direc = caseInputList[currIndex]

        return Ho, d, Ts, cotnsl, direc

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        Ho, d, Ts, cotnsl, direc = self.getCalcValues(caseInputList)
        dataDict = {"Ho": Ho, "d": d, "Ts": Ts,\
            "cotnsl": cotnsl, "direc": direc}
        m2cm = 100.0
        g = self.g * m2cm

        # Convert meter input to centimeters
        Ho = Ho * m2cm
        d = d * m2cm

        Hb = ERRWAVBRK1(d, 0.78)
        if not (Ho < Hb):
            self.errorMsg = "Error: Input wave broken (Hb = %6.2f %s" % (
                Hb, self.labelUnitDist)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        Ks, Kr, Hmax, Hrms, Hbar, Hs, H10, H02, SBrms, HoLo, dLo,\
            dHo, deepd, theta, Sw, Hxo, cdfo, Hx, cdfx =\
            GODA(Ho, d, Ts, cotnsl, direc, g)

        print("\tSubject\tDeep\tUnits")
        print("Hs\t%-6.2f\t%-6.2f\t%s" %\
            (Hs[1]/m2cm, Hs[0]/m2cm, self.labelUnitDist))
        print("Hmean\t%-6.2f\t%-6.2f\t%s" %\
            (Hbar[1]/m2cm, Hbar[0]/m2cm, self.labelUnitDist))
        print("Hrms\t%-6.2f\t%-6.2f\t%s" %\
            (Hrms[1]/m2cm, Hrms[0]/m2cm, self.labelUnitDist))
        print("H10%%\t%-6.2f\t%-6.2f\t%s" %\
            (H10[1]/m2cm, H10[0]/m2cm, self.labelUnitDist))
        print("H02%%\t%-6.2f\t%-6.2f\t%s" %\
            (H02[1]/m2cm, H02[0]/m2cm, self.labelUnitDist))
        print("Hmax%%\t%-6.2f\t%-6.2f\t%s" %\
            (Hmax[1]/m2cm, Hmax[0]/m2cm, self.labelUnitDist))
        print("\nKs\t%-6.4f\t%-6.4f" % (Ks[1], Ks[0]))
        print("SBrms\t%-6.4f\t%-6.4f\t%s" %\
            (SBrms[1]/m2cm, SBrms[0]/m2cm, self.labelUnitDist))
        print("Sw\t%-6.4f\t%-6.4f\t%s" %\
            (Sw[1]/m2cm, Sw[0]/m2cm, self.labelUnitDist))
        print("Ho/Lo\t%-6.4f\t%-6.4f" % (HoLo, HoLo))
        print("Kr\t%-6.4f" % Kr)
        print("d/Ho\t%-6.4f\t%-6.4f" % (dHo[1], dHo[0]))
        print("d/Lo\t%-6.4f\t%-6.4f" % (dLo[1], dLo[0]))

        dataDict.update({"Hs": Hs, "Hbar": Hbar, "Hrms": Hrms,\
            "H10": H10, "H02": H02, "Hmax": Hmax, "Ks": Ks,\
            "SBrms": SBrms, "Sw": Sw, "HoLo": HoLo, "Kr": Kr,\
            "dHo": dHo, "dLo": dLo})
        self.fileOutputWriteMain(dataDict, caseIndex)

        if self.isSingleCase:
            self.plotDict = {"Hxo": Hxo, "cdfo": cdfo,\
                "Hx": Hx, "cdfx": cdfx, "d": d}

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        m2cm = 100.0

        self.fileRef.write("Input\n")
        self.fileRef.write("Ho\t%6.2f %s\n" %
                           (dataDict["Ho"] / m2cm, self.labelUnitDist))
        self.fileRef.write("d\t%6.2f %s\n" %
                           (dataDict["d"] / m2cm, self.labelUnitDist))
        self.fileRef.write("Ts\t%6.2f s\n" % dataDict["Ts"])
        self.fileRef.write("cotnsl\t%6.2f\n" % dataDict["cotnsl"])
        self.fileRef.write("direc\t%6.2f deg\n\n" % dataDict["direc"])

        if self.errorMsg != None:
            self.fileRef.write("%s\n" % self.errorMsg)
        else:
            self.fileRef.write("\tSubject\tDeep\tUnits\n")
            self.fileRef.write("Hs\t%-6.2f\t%-6.2f\t%s\n" %\
                (dataDict["Hs"][1]/m2cm, dataDict["Hs"][0]/m2cm, self.labelUnitDist))
            self.fileRef.write("Hmean\t%-6.2f\t%-6.2f\t%s\n" %\
                (dataDict["Hbar"][1]/m2cm, dataDict["Hbar"][0]/m2cm, self.labelUnitDist))
            self.fileRef.write("Hrms\t%-6.2f\t%-6.2f\t%s\n" %\
                (dataDict["Hrms"][1]/m2cm, dataDict["Hrms"][0]/m2cm, self.labelUnitDist))
            self.fileRef.write("H10%%\t%-6.2f\t%-6.2f\t%s\n" %\
                (dataDict["H10"][1]/m2cm, dataDict["H10"][0]/m2cm, self.labelUnitDist))
            self.fileRef.write("H02%%\t%-6.2f\t%-6.2f\t%s\n" %\
                (dataDict["H02"][1]/m2cm, dataDict["H02"][0]/m2cm, self.labelUnitDist))
            self.fileRef.write("Hmax%%\t%-6.2f\t%-6.2f\t%s\n" %\
                (dataDict["Hmax"][1]/m2cm, dataDict["Hmax"][0]/m2cm, self.labelUnitDist))
            self.fileRef.write("\nKs\t%-6.4f\t%-6.4f\n" %
                               (dataDict["Ks"][1], dataDict["Ks"][0]))
            self.fileRef.write("SBrms\t%-6.4f\t%-6.4f\t%s\n" %\
                (dataDict["SBrms"][1]/m2cm, dataDict["SBrms"][0]/m2cm, self.labelUnitDist))
            self.fileRef.write("Sw\t%-6.4f\t%-6.4f\t%s\n" %\
                (dataDict["Sw"][1]/m2cm, dataDict["Sw"][0]/m2cm, self.labelUnitDist))
            self.fileRef.write("Ho/Lo\t%-6.4f\t%-6.4f\n" %
                               (dataDict["HoLo"], dataDict["HoLo"]))
            self.fileRef.write("Kr\t%-6.4f\n" % dataDict["Kr"])
            self.fileRef.write("d/Ho\t%-6.4f\t%-6.4f\n" %
                               (dataDict["dHo"][1], dataDict["dHo"][0]))
            self.fileRef.write("d/Lo\t%-6.4f\t%-6.4f\n" %
                               (dataDict["dLo"][1], dataDict["dLo"][0]))

        exportData = [dataDict["Ho"], dataDict["d"], dataDict["Ts"],\
            dataDict["cotnsl"], dataDict["direc"]]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["Hs"][1]/m2cm, dataDict["Hs"][0]/m2cm,\
                dataDict["Hbar"][1]/m2cm, dataDict["Hbar"][0]/m2cm,\
                dataDict["Hrms"][1]/m2cm, dataDict["Hrms"][0]/m2cm,\
                dataDict["H10"][1]/m2cm, dataDict["H10"][0]/m2cm,\
                dataDict["H02"][1]/m2cm, dataDict["H02"][0]/m2cm,\
                dataDict["Hmax"][1]/m2cm, dataDict["Hmax"][0]/m2cm,\
                dataDict["Ks"][1], dataDict["Ks"][0],\
                dataDict["SBrms"][1]/m2cm, dataDict["SBrms"][0]/m2cm,\
                dataDict["Sw"][1]/m2cm, dataDict["Sw"][0]/m2cm,\
                dataDict["HoLo"], dataDict["Kr"],\
                dataDict["dHo"][1], dataDict["dHo"][0],
                dataDict["dLo"][1], dataDict["dLo"][0]]
        self.exporter.writeData(exportData)

    # end fileOutputWriteData

    def hasPlot(self):
        return True

    def performPlot(self):
        m2cm = 100.0

        plot1Hxo = [i / m2cm for i in self.plotDict["Hxo"]]
        pyplot.figure(1, figsize = self.plotConfigDict["figSize"],\
            dpi = self.plotConfigDict["dpi"])
        pyplot.plot(plot1Hxo, self.plotDict["cdfo"])
        pyplot.title("Deep Water",
                     fontsize=self.plotConfigDict["titleFontSize"])
        pyplot.xlabel("H [%s]" % self.labelUnitDist,\
            fontsize = self.plotConfigDict["axisLabelFontSize"])
        pyplot.ylabel("CDF",\
            fontsize = self.plotConfigDict["axisLabelFontSize"])

        plot2Hx = [i / m2cm for i in self.plotDict["Hx"]]
        pyplot.figure(2, figsize = self.plotConfigDict["figSize"],\
            dpi = self.plotConfigDict["dpi"])
        pyplot.plot(plot2Hx, self.plotDict["cdfx"])
        pyplot.title("Subject Depth",\
            fontsize = self.plotConfigDict["titleFontSize"])
        pyplot.xlabel("H [%s]" % self.labelUnitDist,\
            fontsize = self.plotConfigDict["axisLabelFontSize"])
        pyplot.ylabel("CDF2",\
            fontsize = self.plotConfigDict["axisLabelFontSize"])

        pyplot.show()

        self.plotDict["plot1Hxo"] = plot1Hxo
        self.plotDict["plot2Hx"] = plot2Hx
        self.fileOutputPlotWriteData()

    # end performPlot

    def fileOutputPlotWriteData(self):
        m2cm = 100.0

        self.fileRef.write(
            "Wave Height versus Cumulative Probability\nDistribution of Exceedance\n\n"
        )

        self.fileRef.write("Deep Water\tWater Depth = %-6.2f %s\n" %\
            (self.plotDict["d"]/m2cm, self.labelUnitDist))
        self.fileRef.write("H (%s)\tCDF\tH(%s)\tCDF2\n" %\
            (self.labelUnitDist, self.labelUnitDist))

        for i in range(len(self.plotDict["plot1Hxo"])):
            self.fileRef.write("%-6.3f\t%-6.3f\t%-6.3f\t%-6.3f\n" %\
                (self.plotDict["plot1Hxo"][i], self.plotDict["cdfo"][i],\
                self.plotDict["plot2Hx"][i], self.plotDict["cdfx"][i]))
Ejemplo n.º 11
0
class WaveForces(BaseDriver):
    def __init__(self, d=None, Hi=None, T=None, chi=None, cotphi=None):
        self.exporter = EXPORTER("output/exportWaveForces")

        if d != None:
            self.isSingleCase = True
            self.defaultValue_d = d
        if Hi != None:
            self.isSingleCase = True
            self.defaultValueHi = Hi
        if T != None:
            self.isSingleCase = True
            self.defaultValueT = T
        if chi != None:
            self.isSingleCase = True
            self.defaultValue_chi = chi
        if cotphi != None:
            self.isSingleCase = True
            self.defaultValue_cotphi = cotphi

        super(WaveForces, self).__init__()

        self.exporter.close()

    # end __init__

    def userInput(self):
        super(WaveForces, self).userInput()

        self.water, self.rho = USER_INPUT.SALT_FRESH_WATER(self.isMetric)

    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValue_d"):
            self.inputList.append(BaseField("d: depth for sea water level (%s)" %\
                self.labelUnitDist, 0.1, 200.0))
        if not hasattr(self, "defaultValueHi"):
            self.inputList.append(BaseField("Hi: incident wave height (%s)" %\
                self.labelUnitDist, 0.1, 100.0))
        if not hasattr(self, "defaultValueT"):
            self.inputList.append(BaseField("T: wave period (s)", 1.0, 100.0))
        if not hasattr(self, "defaultValue_chi"):
            self.inputList.append(BaseField(\
                "chi: wave reflection coefficient", 0.9, 1.0))
        if not hasattr(self, "defaultValue_cotphi"):
            self.inputList.append(BaseField(\
                "cotphi: cotangent of nearshore slope", 5.0, 10000.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename="wave_forces")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValue_d"):
            d = self.defaultValue_d
        else:
            d = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueHi"):
            Hi = self.defaultValueHi
        else:
            Hi = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueT"):
            T = self.defaultValueT
        else:
            T = caseInputList[currIndex]

        if hasattr(self, "defaultValue_chi"):
            chi = self.defaultValue_chi
        else:
            chi = caseInputList[currIndex]

        if hasattr(self, "defaultValue_cotphi"):
            cotphi = self.defaultValue_cotphi
        else:
            cotphi = caseInputList[currIndex]

        return d, Hi, T, chi, cotphi

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        d, Hi, T, chi, cotphi = self.getCalcValues(caseInputList)
        dataDict = {"d": d, "Hi": Hi, "T": T, "chi": chi, "cotphi": cotphi}

        H20weight = self.rho * self.g

        m = 1.0 / cotphi
        if np.isclose(m, 0.0):
            Hbs = ERRWAVBRK1(d, 0.78)
        else:
            Hbs = ERRWAVBRK2(T, m, d)

        if not (Hi < Hbs):
            self.errorMsg = "Error: Wave broken at structure (Hbs = %6.2f %s)" %\
                (Hbs, self.labelUnitDist)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        L, k = WAVELEN(d, T, 50, self.g)

        steep, maxstp = ERRSTP(Hi, d, L)
        #        assert(steep<maxstp,'Error: Input wave unstable (Max: %0.4f, [H/L] = %0.4f)',maxstp,steep')
        if not ComplexUtil.lessThan(steep, maxstp):
            self.errorMsg = "Error: Input wave unstable (Max: %0.4f, [H/L] = %0.4f)" %\
                (maxstp.real, steep.real)

        MR, S, MRintc, MRintt, Sintc, Sintt = WFVW1(d, Hi, chi, L, H20weight)
        print('\n\t\t\t\t %s \t\t %s' % ('Miche-Rundgren', 'Sainflou'))
        print(
            "Wave Position at Wall\t\tCrest\t\tTrough\t\tCrest\t\tTrough\t\tUnits"
        )
        print("Hgt above bottom \t\t %-6.2f \t %6.2f \t %-6.2f \t %6.2f \t %s" %\
            (MR[0].real, MR[3].real, S[0].real, S[3].real, self.labelUnitDist))
        print("Integrated force \t\t %-6.2f \t %6.2f \t %-6.2f \t %6.2f \t %s/%s" %\
            (MR[1].real, MR[4].real, S[1].real, S[4].real, self.labelUnitWt, self.labelUnitDist))
        print("Integrated moment \t\t %-6.2f \t %6.2f \t %-6.2f \t %6.2f \t %s-%s/%s" %\
            (MR[2].real, MR[5].real, S[2].real, S[5].real, self.labelUnitWt, self.labelUnitDist, self.labelUnitDist))

        dataDict.update({"MR": MR, "S": S})
        self.fileOutputWriteMain(dataDict, caseIndex)

        if self.isSingleCase:
            self.plotDict = {"MRintc": MRintc, "MRintt": MRintt,\
                "Sintc": Sintc, "Sintt": Sintt}

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("d\t%6.2f %s\n" %
                           (dataDict["d"], self.labelUnitDist))
        self.fileRef.write("Hi\t%6.2f %s\n" %
                           (dataDict["Hi"], self.labelUnitDist))
        self.fileRef.write("T\t%6.2f s\n" % dataDict["T"])
        self.fileRef.write("chi\t%6.2f\n" % dataDict["chi"])
        self.fileRef.write("cotphi\t%6.2f\n" % dataDict["cotphi"])

        if self.errorMsg != None:
            self.fileRef.write("\n%s\n" % self.errorMsg)
        else:
            self.fileRef.write('\n\t\t\t\t %s \t\t %s \n' %
                               ('Miche-Rundgren', 'Sainflou'))
            self.fileRef.write(
                "Wave Position at Wall\t\tCrest\t\tTrough\t\tCrest\t\tTrough\t\tUnits\n"
            )
            self.fileRef.write("Hgt above bottom \t\t %-6.2f \t %6.2f \t %-6.2f \t %6.2f \t %s \n" %\
                (dataDict["MR"][0].real, dataDict["MR"][3].real,\
                dataDict["S"][0].real, dataDict["S"][3].real, self.labelUnitDist))
            self.fileRef.write("Integrated force \t\t %-6.2f \t %6.2f \t %-6.2f \t %6.2f \t %s/%s \n" %\
                (dataDict["MR"][1].real, dataDict["MR"][4].real,\
                dataDict["S"][1].real, dataDict["S"][4].real,\
                self.labelUnitWt, self.labelUnitDist))
            self.fileRef.write("Integrated moment \t\t %-6.2f \t %6.2f \t %-6.2f \t %6.2f \t %s-%s/%s \n" %\
                (dataDict["MR"][2].real, dataDict["MR"][5].real,\
                dataDict["S"][2].real, dataDict["S"][5].real,\
                self.labelUnitWt, self.labelUnitDist, self.labelUnitDist))

        exportData = [dataDict["d"], dataDict["Hi"], dataDict["T"],\
            dataDict["chi"], dataDict["cotphi"]]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["MR"][0], dataDict["MR"][3],\
                dataDict["S"][0], dataDict["S"][3],\
                dataDict["MR"][1], dataDict["MR"][4],\
                dataDict["S"][1], dataDict["S"][4],\
                dataDict["MR"][2], dataDict["MR"][5],\
                dataDict["S"][2], dataDict["S"][5]]
        self.exporter.writeData(exportData)

    # end fileOutputWriteData

    def hasPlot(self):
        return True

    def performPlot(self):
        plt.figure(1, figsize = self.plotConfigDict["figSize"],\
            dpi = self.plotConfigDict["dpi"])
        plt.subplot(2, 1, 1)
        plt.plot(self.plotDict["MRintc"][1],\
            self.plotDict["MRintc"][0], "g-",\
            self.plotDict["MRintc"][2],\
            self.plotDict["MRintc"][0], "c-.",\
            self.plotDict["MRintc"][3],\
            self.plotDict["MRintc"][0], "r:")
        plt.axhline(y=0.0, color="r", LineStyle="--")
        plt.legend(["Wave Pressure", "Hydrostatic Pressure",\
            "Wave and Hydrostatic Pressure"])
        plt.xlabel("Pressure [%s/%s^2]" %
                   (self.labelUnitWt, self.labelUnitDist))
        plt.ylabel("Elevation [%s]" % self.labelUnitDist)
        plt.title("Miche-Rundgren Pressure Distribution - Crest at Wall")

        ax = plt.subplot(2, 1, 2)
        plt.plot(self.plotDict["MRintt"][1],\
            self.plotDict["MRintt"][0], "g-",\
            self.plotDict["MRintt"][2],\
            self.plotDict["MRintt"][0], "c-.",\
            self.plotDict["MRintt"][3],\
            self.plotDict["MRintt"][0], "r:")
        plt.axhline(y=0.0, color="r", LineStyle="--")
        ax.add_patch(patches.Rectangle(\
            (-50.0, math.floor(min([i.real for i in self.plotDict["Sintt"][0]]))),\
            50.0, abs(math.floor(min([i.real for i in self.plotDict["Sintt"][0]]))) + 5,\
            lineWidth=2, fill=None))
        plt.ylim([math.floor(min([i.real for i in self.plotDict["Sintt"][0]])),\
            abs(math.floor(min([i.real for i in self.plotDict["Sintt"][0]]))) - 5])
        plt.legend(["Wave Pressure", "Hydrostatic Pressure",\
            "Wave and Hydrostatic Pressure"])
        plt.xlabel("Pressure [%s/%s^2]" %
                   (self.labelUnitWt, self.labelUnitDist))
        plt.ylabel("Elevation [%s]" % self.labelUnitDist)
        plt.title("Miche-Rundgren Pressure Distribution - Trough at Wall")
        plt.tight_layout(h_pad=1.0)

        plt.figure(2, figsize = self.plotConfigDict["figSize"],\
            dpi = self.plotConfigDict["dpi"])
        plt.subplot(2, 1, 1)
        plt.plot(self.plotDict["Sintc"][1],\
            self.plotDict["Sintc"][0], "g-",\
            self.plotDict["Sintc"][2],\
            self.plotDict["Sintc"][0], "c-.",
            self.plotDict["Sintc"][3],\
            self.plotDict["Sintc"][0], "r:")
        plt.axhline(y=0.0, color="r", LineStyle="--")
        plt.legend(["Wave Pressure", "Hydrostatic Pressure",\
            "Wave and Hydrostatic Pressure"])
        plt.xlabel("Pressure [%s/%s^2]" %
                   (self.labelUnitWt, self.labelUnitDist))
        plt.ylabel("Elevation [%s]" % self.labelUnitDist)
        plt.title("Sainflou Pressure Distribution - Crest at Wall")

        ax = plt.subplot(2, 1, 2)
        plt.plot(self.plotDict["Sintt"][1],\
            self.plotDict["Sintt"][0], "g-",\
            self.plotDict["Sintt"][2],\
            self.plotDict["Sintt"][0], "c-.",\
            self.plotDict["Sintt"][3],\
            self.plotDict["Sintt"][0], "r:")
        plt.axhline(y=0.0, color="r", LineStyle="--")
        ax.add_patch(patches.Rectangle(\
            (-50.0, math.floor(min([i.real for i in self.plotDict["Sintt"][0]]))),\
            50.0, abs(math.floor(min([i.real for i in self.plotDict["Sintt"][0]]))) + 5,\
            lineWidth=2, fill=None))
        plt.ylim([math.floor(min([i.real for i in self.plotDict["Sintt"][0]])),\
            abs(math.floor(min([i.real for i in self.plotDict["Sintt"][0]]))) - 5])
        plt.legend(["Wave Pressure", "Hydrostatic Pressure",\
            "Wave and Hydrostatic Pressue"])
        plt.xlabel("Pressure [%s/%s^2]" %
                   (self.labelUnitWt, self.labelUnitDist))
        plt.ylabel("Elevation [%s]" % self.labelUnitDist)
        plt.title("Sainflou Pressure Distribution - Trough at Wall")
        plt.tight_layout(h_pad=1.0)

        plt.show()

        self.fileOutputPlotWriteData()

    # end performPlot

    def fileOutputPlotWriteData(self):
        self.fileRef.write('Partial Listing of Plot Output File\n\n')

        self.fileRef.write('Miche-Rundgren Pressure Distribution\n')
        self.fileRef.write('Crest at Wall \n\n')

        self.fileRef.write(
            '          Elevation    Wave Pressure    Hydrostatic Pressure    Wave & Hydrostatic Pressure\n'
        )
        self.fileRef.write('          (%s)         (%s/%s^2)        (%s/%s^2)               (%s/%s^2)\n' %\
            (self.labelUnitDist, self.labelUnitWt, self.labelUnitDist,\
            self.labelUnitWt, self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))

        for i in range(len(self.plotDict["MRintc"][0])):
            self.fileRef.write('%-6d    %-6.2f       %-6.2f           %-6.2f                  %-6.2f\n' %\
                ((i + 1), self.plotDict["MRintc"][0][i].real,\
                self.plotDict["MRintc"][1][i].real,\
                self.plotDict["MRintc"][2][i].real,\
                self.plotDict["MRintc"][3][i].real))

        self.fileRef.write('\n\nMiche-Rundgren Pressure Distribution\n')
        self.fileRef.write('Trough at Wall \n\n')

        self.fileRef.write(
            '          Elevation    Wave Pressure    Hydrostatic Pressure    Wave & Hydrostatic Pressure\n'
        )
        self.fileRef.write('          (%s)         (%s/%s^2)        (%s/%s^2)               (%s/%s^2)\n' %\
            (self.labelUnitDist, self.labelUnitWt, self.labelUnitDist,\
            self.labelUnitWt, self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))

        for i in range(len(self.plotDict["MRintt"][0])):
            self.fileRef.write('%-6d    %-6.2f       %-6.2f           %-6.2f                  %-6.2f\n' %\
                ((i + 1), self.plotDict["MRintt"][0][i].real,\
                self.plotDict["MRintt"][1][i].real,\
                self.plotDict["MRintt"][2][i].real,\
                self.plotDict["MRintt"][3][i].real))

        self.fileRef.write('\n\nSainflou Pressure Distribution\n')
        self.fileRef.write('Crest at Wall \n\n')

        self.fileRef.write(
            '          Elevation    Wave Pressure    Hydrostatic Pressure    Wave & Hydrostatic Pressure\n'
        )
        self.fileRef.write('          (%s)         (%s/%s^2)        (%s/%s^2)               (%s/%s^2)\n' %\
            (self.labelUnitDist, self.labelUnitWt, self.labelUnitDist,\
            self.labelUnitWt, self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))

        for i in range(len(self.plotDict["Sintc"][0])):
            self.fileRef.write('%-6d    %-6.2f       %-6.2f           %-6.2f                  %-6.2f\n' %\
                ((i + 1), self.plotDict["Sintc"][0][i].real,\
                self.plotDict["Sintc"][1][i].real,\
                self.plotDict["Sintc"][2][i].real,\
                self.plotDict["Sintc"][3][i].real))

        self.fileRef.write('\n\nSainflou Pressure Distribution\n')
        self.fileRef.write('Trough at Wall \n\n')

        self.fileRef.write(
            '          Elevation    Wave Pressure    Hydrostatic Pressure    Wave & Hydrostatic Pressure\n'
        )
        self.fileRef.write('          (%s)         (%s/%s^2)        (%s/%s^2)               (%s/%s^2)\n' %\
            (self.labelUnitDist, self.labelUnitWt, self.labelUnitDist,\
            self.labelUnitWt, self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))

        for i in range(len(self.plotDict["Sintt"][0])):
            self.fileRef.write('%-6d    %-6.2f       %-6.2f           %-6.2f                  %-6.2f\n' %\
                ((i + 1), self.plotDict["Sintt"][0][i].real,\
                self.plotDict["Sintt"][1][i].real,\
                self.plotDict["Sintt"][2][i].real,\
                self.plotDict["Sintt"][3][i].real))
Ejemplo n.º 12
0
class RefdiffVertWedge(BaseDriver):
    def __init__(self, Hi = None, T = None, d = None,\
        alpha = None, wedgang = None, mode = None, xcor = None,\
        ycor = None, x0 = None, xend = None, dx = None, y0 = None,\
        yend = None, dy = None):
        self.exporter = EXPORTER("output/exportRefdiffVertWedge")

        if Hi != None:
            self.isSingleCase = True
            self.defaultValueHi = Hi
        if T != None:
            self.isSingleCase = True
            self.defaultValueT = T
        if d != None:
            self.isSingleCase = True
            self.defaultValue_d = d
        if alpha != None:
            self.isSingleCase = True
            self.defaultValue_alpha = alpha
        if wedgang != None:
            self.isSingleCase = True
            self.defaultValue_wedgang = wedgang
        if mode != None:
            self.isSingleCase = True
            self.defaultValue_mode = mode
        if xcor != None:
            self.isSingleCase = True
            self.defaultValue_xcor = xcor
        if ycor != None:
            self.isSingleCase = True
            self.defaultValue_ycor = ycor
        if x0 != None:
            self.isSingleCase = True
            self.defaultValue_x0 = x0
        if xend != None:
            self.isSingleCase = True
            self.defaultValue_xend = xend
        if dx != None:
            self.isSingleCase = True
            self.defaultValue_dx = dx
        if y0 != None:
            self.isSingleCase = True
            self.defaultValue_y0 = y0
        if yend != None:
            self.isSingleCase = True
            self.defaultValue_yend = yend
        if dy != None:
            self.isSingleCase = True
            self.defaultValue_dy = dy

        super(RefdiffVertWedge, self).__init__()

        self.exporter.close()

    # end __init__

    def userInput(self):
        if not hasattr(self, "defaultValue_mode"):
            self.mode = USER_INPUT.FINITE_CHOICE(\
                "Mode 1 Single Case or Mode 2 Grid Case (1 or 2): ",\
                ["1", "2"])
            if self.mode == "1":
                self.mode = 0
            else:
                self.mode = 1
        else:
            self.mode = self.defaultValue_mode

        super(RefdiffVertWedge, self).userInput()

        if self.mode == 1:
            if not hasattr(self, "defaultValue_x0"):
                self.x0 = USER_INPUT.DATA_VALUE(\
                    "x0: x start coordinate (%s)" % self.labelUnitDist,\
                    -5280.0, 5280.0)
            else:
                self.x0 = self.defaultValue_x0

            if not hasattr(self, "defaultValue_xend"):
                self.xend = USER_INPUT.DATA_VALUE(\
                    "xend: x end coordinate (%s)" % self.labelUnitDist,\
                    -5280.0, 5280.0)
            else:
                self.xend = self.defaultValue_xend

            if not hasattr(self, "defaultValue_dx"):
                self.dx = USER_INPUT.DATA_VALUE(\
                    "dx: x spatial increment (%s)" % self.labelUnitDist,\
                    0.1, 5280.0)
            else:
                self.dx = self.defaultValue_dx

            if not hasattr(self, "defaultValue_y0"):
                self.y0 = USER_INPUT.DATA_VALUE(\
                    "y0: y start coordinate (%s)" % self.labelUnitDist,\
                    -5280.0, 5280.0)
            else:
                self.y0 = self.defaultValue_y0

            if not hasattr(self, "defaultValue_yend"):
                self.yend = USER_INPUT.DATA_VALUE(\
                    "yend: y end coordinate (%s)" % self.labelUnitDist,\
                    -5280.0, 5280.0)
            else:
                self.yend = self.defaultValue_yend

            if not hasattr(self, "defaultValue_dy"):
                self.dy = USER_INPUT.DATA_VALUE(\
                    "dy: y spatial increment (%s)" % self.labelUnitDist,\
                    0.1, 5280.0)
            else:
                self.dy = self.defaultValue_dy

    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueHi"):
            self.inputList.append(BaseField(\
                "Hi: incident wave height (%s)" % (self.labelUnitDist), 0.1, 200.0))
        if not hasattr(self, "defaultValueT"):
            self.inputList.append(BaseField(\
                "T: water period (sec)", 1.0, 1000.0))
        if not hasattr(self, "defaultValue_d"):
            self.inputList.append(BaseField(\
                "d: water depth (%s)" % (self.labelUnitDist), 0.01, 5000.0))
        if not hasattr(self, "defaultValue_alpha"):
            self.inputList.append(BaseField(\
                "alpha: wave angle (deg)", 0.0, 180.0))
        if not hasattr(self, "defaultValue_wedgang"):
            self.inputList.append(BaseField(\
                "wedgang: wedge angle (deg)", 0.0, 180.0))

        if self.mode == 0:
            if not hasattr(self, "defaultValue_xcor"):
                self.inputList.append(BaseField(\
                    "xcor: x-coordinate (%s)" %\
                    (self.labelUnitDist), -5280.0, 5280.0))
            if not hasattr(self, "defaultValue_ycor"):
                self.inputList.append(BaseField(\
                    "ycor: y-coordinate (%s)" %\
                    (self.labelUnitDist), -5280.0, 5280.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        if self.mode == 0:
            fileSuffix = "single_point"
        else:
            fileSuffix = "uniform_grid"

        self.fileOutputRequestMain(\
            defaultFilename = "refdiff_vert_wedge_%s" % fileSuffix)

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueHi"):
            Hi = self.defaultValueHi
        else:
            Hi = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueT"):
            T = self.defaultValueT
        else:
            T = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_d"):
            d = self.defaultValue_d
        else:
            d = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_alpha"):
            alpha = self.defaultValue_alpha
        else:
            alpha = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_wedgang"):
            wedgang = self.defaultValue_wedgang
        else:
            wedgang = caseInputList[currIndex]
            currIndex = currIndex + 1

        if self.mode == 0:
            if hasattr(self, "defaultValue_xcor"):
                xcor = self.defaultValue_xcor
            else:
                xcor = caseInputList[currIndex]
                currIndex = currIndex + 1

            if hasattr(self, "defaultValue_ycor"):
                ycor = self.defaultValue_ycor
            else:
                ycor = caseInputList[currIndex]
        else:
            xcor = None
            ycor = None

        return Hi, T, d, alpha, wedgang, xcor, ycor

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        Hi, T, d, alpha, wedgang, xcor, ycor =\
            self.getCalcValues(caseInputList)
        dataDict = {"Hi": Hi, "T": T, "d": d,\
            "alpha": alpha, "wedgang": wedgang}

        if self.mode == 0:
            dataDict["xcor"] = xcor
            dataDict["ycor"] = ycor
        else:
            dataDict["x0"] = self.x0
            dataDict["xend"] = self.xend
            dataDict["dx"] = self.dx
            dataDict["y0"] = self.y0
            dataDict["yend"] = self.yend
            dataDict["dy"] = self.dy

        # Single Point Case
        if self.mode == 0:
            L, k = WAVELEN(d, T, 50, self.g)

            steep, maxstp = ERRSTP(Hi, d, L)
            if not (steep < maxstp):
                self.errorMsg = "Error: Input wave unstable (Max: %0.4f, [H/L] = %0.4f" %\
                    (maxstp, steep)

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            Hb = ERRWAVBRK1(d, 0.78)
            if not (Hi < Hb):
                self.errorMsg = "Error: Input wave broken (Hb = %6.2f %s" %\
                    (Hb, self.labelUnitDist)

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            phi, beta, H, error = DRWEDG(xcor, ycor, Hi, alpha, wedgang, L)
            if error == 1:
                self.errorMsg = "Error: (x,y) location inside structure."

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            print("Wavelength\t\t%6.2f\t%s" % (L, self.labelUnitDist))
            print("Mod factor (phi)\t%6.2f" % phi)
            print("Wave phase\t\t%6.2f\trad" % beta)
            print("Mod wave height\t\t%6.2f\t%s" % (H, self.labelUnitDist))

            dataDict["L"] = L
            dataDict["phi"] = phi
            dataDict["beta"] = beta
            dataDict["H"] = H
        else:
            xcors = []
            nxpt = int((self.xend - self.x0 + self.dx) / self.dx)
            [xcors.append(self.x0 + i * self.dx) for i in range(nxpt)]

            ycors = []
            nypt = int((self.yend - self.y0 + self.dy) / self.dy)
            [ycors.append(self.y0 + (nypt - i - 1)*self.dy) \
                for i in range(nypt)]

            L, k = WAVELEN(d, T, 50, self.g)
            dataDict["L"] = L

            steep, maxstp = ERRSTP(Hi, d, L)
            if not (steep < maxstp):
                self.errorMsg = "Error: Input wave unstable (Max: %0.4f, [H/L] = %0.4f" %\
                    (maxstp, steep)

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            Hb = ERRWAVBRK(T, d, 0.0, 0.78, 0)
            if not (Hi < Hb):
                self.errorMsg = "error: Input wave broken (Hb = %6.2f %s" %\
                    (Hb, self.labelUnitDist)

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            phi = []
            beta = []
            H = []

            for i in range(nypt):
                phi.append([])
                beta.append([])
                H.append([])

                for j in range(nxpt):
                    xx = xcors[j]
                    yy = ycors[i]

                    valPhi, valBeta, valH, error = DRWEDG(
                        xx, yy, Hi, alpha, wedgang, L)

                    phi[i].append(valPhi)
                    beta[i].append(valBeta)
                    H[i].append(valH)

                    if error == 1:
                        self.errorMsg = "Error: (x,y) location inside structure."

                        print(self.errorMsg)
                        self.fileOutputWriteMain(dataDict, caseIndex)
                        return
                # end for loop
            # end for loop

            print("Wavelength\t\t%6.2f %s" % (L, self.labelUnitDist))

            print("Modification factors:")
            printMsg = ""
            for i in range(len(xcors)):
                printMsg += ("\t%6.2f" % xcors[i])
            print(printMsg)

            for i in range(len(phi)):
                printMsg = "%6.2f" % ycors[i]

                for j in range(len(phi[0])):
                    printMsg += ("\t%6.2f" % phi[i][j])
                print(printMsg)

            print("\nModified Wave Heights:")
            printMsg = ""
            for i in range(len(xcors)):
                printMsg += "\t%6.2f" % xcors[i]
            print(printMsg)

            for i in range(len(H)):
                printMsg = "%6.2f" % ycors[i]

                for j in range(len(H[0])):
                    printMsg += "\t%6.2f" % H[i][j]
                print(printMsg)

            print("\nPhase Angles (rad):")
            printMsg = ""
            for i in range(len(xcors)):
                printMsg += "\t%6.2f" % xcors[i]
            print(printMsg)

            for i in range(len(beta)):
                printMsg = "%6.2f" % ycors[i]

                for j in range(len(beta[0])):
                    printMsg += "\t%6.2f" % beta[i][j]
                print(printMsg)

            dataDict["xcors"] = xcors
            dataDict["ycors"] = ycors
            dataDict["phi"] = phi
            dataDict["beta"] = beta
            dataDict["H"] = H
        # end if

        self.fileOutputWriteMain(dataDict, caseIndex)

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        if self.mode == 0:
            self.fileRef.write("Input\n")
            self.fileRef.write("Hi                  %6.2f %s\n" %
                               (dataDict["Hi"], self.labelUnitDist))
            self.fileRef.write("T                   %6.2f s\n" % dataDict["T"])
            self.fileRef.write("d                   %6.2f %s\n" %
                               (dataDict["d"], self.labelUnitDist))
            self.fileRef.write("alpha               %6.2f deg\n" %
                               dataDict["alpha"])
            self.fileRef.write("wedgang             %6.2f deg\n" %
                               dataDict["wedgang"])
            self.fileRef.write("xcor                %6.2f %s\n" %
                               (dataDict["xcor"], self.labelUnitDist))
            self.fileRef.write("ycor                %6.2f %s\n" %
                               (dataDict["ycor"], self.labelUnitDist))

            if self.errorMsg != None:
                self.fileRef.write("\n%s\n" % self.errorMsg)
            else:
                self.fileRef.write("\nWavelength          %6.2f %s\n" %
                                   (dataDict["L"], self.labelUnitDist))
                self.fileRef.write("Mod factor (phi)    %6.2f\n" %
                                   dataDict["phi"])
                self.fileRef.write("Wave phase          %6.2f rad\n" %
                                   dataDict["beta"])
                self.fileRef.write("Mod wave height     %6.2f %s\n" %
                                   (dataDict["H"], self.labelUnitDist))

            exportData = [dataDict["Hi"], dataDict["T"], dataDict["d"],\
                dataDict["alpha"], dataDict["wedgang"], dataDict["xcor"],\
                dataDict["ycor"]]
            if self.errorMsg != None:
                exportData.append("Error")
            else:
                exportData = exportData + [dataDict["L"], dataDict["phi"],\
                    dataDict["beta"], dataDict["H"]]
            self.exporter.writeData(exportData)
        else:
            self.fileRef.write("Incident Wave Height\t=\t%-6.2f\t%s\tWave Period\t=\t%-6.2f\tsec\n" %\
                (dataDict["Hi"], self.labelUnitDist, dataDict["T"]))
            self.fileRef.write("Water Depth\t\t=\t%-6.2f\t%s\tWavelength\t=\t%-6.2f\t%s\n" %\
                (dataDict["d"], self.labelUnitDist, dataDict["L"], self.labelUnitDist))
            self.fileRef.write(
                "Wave Angle\t\t=\t%-6.2f\tdeg\tWedge Angle\t=\t%-6.2f\tdeg\n\n"
                % (dataDict["alpha"], dataDict["wedgang"]))

            if self.errorMsg != None:
                self.fileRef.write("%s\n" % self.errorMsg)
            else:
                # phi table
                self.fileRef.write("**** Modification Factors:\n")
                self.fileRef.write("              x=  ")
                for xcor in dataDict["xcors"]:
                    self.fileRef.write("  %8.2f" % xcor)
                self.fileRef.write(
                    "\n--------------------------------------------------------------------\n"
                )

                for i in range(len(dataDict["phi"])):
                    self.fileRef.write("y=      %8.2f  " %
                                       dataDict["ycors"][i])

                    for j in range(len(dataDict["phi"][0])):
                        self.fileRef.write("  %8.2f" % dataDict["phi"][i][j])

                    self.fileRef.write("\n")
                self.fileRef.write(
                    "--------------------------------------------------------------------\n"
                )

                self.fileRef.write("              x=  ")
                for xcor in dataDict["xcors"]:
                    self.fileRef.write("  %8.2f" % xcor)
                self.fileRef.write(
                    "\n--------------------------------------------------------------------\n"
                )
                # end phi table

                self.fileRef.write("\n\n")

                # H table
                self.fileRef.write("**** Modified Wave Heights (%s):\n" %
                                   self.labelUnitDist)

                self.fileRef.write("              x=  ")
                for xcor in dataDict["xcors"]:
                    self.fileRef.write("  %8.2f" % xcor)
                self.fileRef.write(
                    "\n--------------------------------------------------------------------\n"
                )

                for i in range(len(dataDict["H"])):
                    self.fileRef.write("y=      %8.2f  " %
                                       dataDict["ycors"][i])

                    for j in range(len(dataDict["H"][0])):
                        self.fileRef.write("  %8.2f" % dataDict["H"][i][j])

                    self.fileRef.write("\n")
                self.fileRef.write(
                    "--------------------------------------------------------------------\n"
                )

                self.fileRef.write("              x=  ")
                for xcor in dataDict["xcors"]:
                    self.fileRef.write("  %8.2f" % xcor)
                self.fileRef.write(
                    "\n--------------------------------------------------------------------\n"
                )
                # end H table

                self.fileRef.write("\n\n")

                # beta table
                self.fileRef.write("**** Phase Angles (rad):\n")

                self.fileRef.write("              x=  ")
                for xcor in dataDict["xcors"]:
                    self.fileRef.write("  %8.2f" % xcor)
                self.fileRef.write(
                    "\n--------------------------------------------------------------------\n"
                )

                for i in range(len(dataDict["beta"])):
                    self.fileRef.write("y=      %8.2f  " %
                                       dataDict["ycors"][i])

                    for j in range(len(dataDict["beta"][0])):
                        self.fileRef.write("  %8.2f" % dataDict["beta"][i][j])

                    self.fileRef.write("\n")
                self.fileRef.write(
                    "--------------------------------------------------------------------\n"
                )

                self.fileRef.write("              x=  ")
                for xcor in dataDict["xcors"]:
                    self.fileRef.write("  %8.2f" % xcor)
                self.fileRef.write(
                    "\n--------------------------------------------------------------------\n"
                )
                # end beta table
            # end if

            exportData = [dataDict["Hi"], dataDict["T"], dataDict["d"]]
            exportData = exportData + [dataDict["alpha"], dataDict["wedgang"]]
            if self.errorMsg != None:
                exportData.append(self.errorMsg)
            else:
                exportData = exportData + [dataDict["L"],\
                    dataDict["xcors"][0], dataDict["xcors"][-1],\
                    (dataDict["xcors"][1] - dataDict["xcors"][0]),\
                    dataDict["ycors"][-1], dataDict["ycors"][0],\
                    (dataDict["ycors"][1] - dataDict["ycors"][0])]

                for i in dataDict["phi"]:
                    for j in i:
                        exportData.append(j)

                for i in dataDict["H"]:
                    for j in i:
                        exportData.append(j)

                for i in dataDict["beta"]:
                    for j in i:
                        exportData.append(j)

            self.exporter.writeData(exportData)
Ejemplo n.º 13
0
class RubbleMound(BaseDriver):
    def __init__(self, Hs = None, Ts = None, cotnsl = None,\
        ds = None, cotssl = None, unitwt = None, P = None, S = None):
        self.exporter = EXPORTER("output/exportRubbleMound")

        if Hs != None:
            self.isSingleCase = True
            self.defaultValueHs = Hs
        if Ts != None:
            self.isSingleCase = True
            self.defaultValueTs = Ts
        if cotnsl != None:
            self.isSingleCase = True
            self.defaultValue_cotnsl = cotnsl
        if ds != None:
            self.isSingleCase = True
            self.defaultValue_ds = ds
        if cotssl != None:
            self.isSingleCase = True
            self.defaultValue_cotssl = cotssl
        if unitwt != None:
            self.isSingleCase = True
            self.defaultValue_unitwt = unitwt
        if P != None:
            self.isSingleCase = True
            self.defaultValueP = P
        if S != None:
            self.isSingleCase = True
            self.defaultValueS = S

        super(RubbleMound, self).__init__()

        self.exporter.close()

    # end __init__

    def userInput(self):
        super(RubbleMound, self).userInput()

        self.water, self.rho = USER_INPUT.SALT_FRESH_WATER(self.isMetric)

    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueHs"):
            self.inputList.append(BaseField(\
                "Hs: significant wave height (%s)" %\
                (self.labelUnitDist), 0.1, 100.0))
        if not hasattr(self, "defaultValueTs"):
            self.inputList.append(BaseField(\
                "Ts: signficiant wave period (sec)", 1.0, 1000.0))
        if not hasattr(self, "defaultValue_cotnsl"):
            self.inputList.append(BaseField(\
                "cotnsl: cotangent of nearshore slope", 5.0, 10000.0))
        if not hasattr(self, "defaultValue_ds"):
            self.inputList.append(BaseField(\
                "ds: water depth at toe of revetment (%s)" %\
                self.labelUnitDist, 0.1, 200.0))
        if not hasattr(self, "defaultValue_cotssl"):
            self.inputList.append(BaseField(\
                "cotssl: cotangent of structure slope", 2.0, 6.0))
        if not hasattr(self, "defaultValue_unitwt"):
            self.inputList.append(BaseField(\
                "unitwt: unit weight of rock (%s/%s^3)" %\
                (self.labelUnitWt, self.labelUnitDist), 1.0, 99999.0))
        if not hasattr(self, "defaultValueP"):
            self.inputList.append(BaseField(\
                "P: permeability coefficient", 0.05, 0.6))
        if not hasattr(self, "defaultValueS"):
            self.inputList.append(BaseField("S: damage level", 2.0, 17.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename="rubble_mound")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueHs"):
            Hs = self.defaultValueHs
        else:
            Hs = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueTs"):
            Ts = self.defaultValueTs
        else:
            Ts = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_cotnsl"):
            cotnsl = self.defaultValue_cotnsl
        else:
            cotnsl = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_ds"):
            ds = self.defaultValue_ds
        else:
            ds = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_cotssl"):
            cotssl = self.defaultValue_cotssl
        else:
            cotssl = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_unitwt"):
            unitwt = self.defaultValue_unitwt
        else:
            unitwt = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueP"):
            P = self.defaultValueP
        else:
            P = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueS"):
            S = self.defaultValueS
        else:
            S = caseInputList[currIndex]

        return Hs, Ts, cotnsl, ds, cotssl, unitwt, P, S

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        Hs, Ts, cotnsl, ds, cotssl, unitwt, P, S =\
            self.getCalcValues(caseInputList)
        dataDict = {"Hs": Hs, "Ts": Ts, "cotnsl": cotnsl, "ds": ds,\
            "cotssl": cotssl, "unitwt": unitwt, "P": P, "S": S}

        N = 7000

        H20weight = self.g * self.rho

        m = 1.0 / cotnsl

        Hbs = ERRWAVBRK2(Ts, m, ds)
        if not (Hs < Hbs):
            self.errorMsg = "Error: Wave broken at structure (Hbs = %6.2f %s)" %\
                (Hbs, self.labelUnitDist)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        L, k = WAVELEN(ds, Ts, 50, self.g)

        steep, maxstp = ERRSTP(Hs, ds, L)
        if not (steep < maxstp):
            self.errorMsg = "Error: Wave unstable (Max: %0.4f, [H/L] = %0.4f)" % (
                maxstp, steep)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        tanssl = 1.0 / cotssl
        Tz = Ts * (0.67 / 0.80)
        ssz = tanssl / math.sqrt(2.0 * math.pi * Hs / (self.g * Tz**2))

        arg1 = 1.0 / (P + 0.5)
        ssp = (6.2 * (P**0.31) * math.sqrt(tanssl))**arg1

        CERC_NS = (1.45 / 1.27) * (cotssl**(1.0 / 6.0)
                                   )  #if change to 1.14, same answer as ACES

        arg2 = (S / math.sqrt(N))**0.2
        plunge_NS = 6.2 * (P**0.18) * arg2 * (ssz**-0.5)
        surging_NS = 1.0 * (P**-0.13) * arg2 * math.sqrt(cotssl) * (ssz**P)

        if ssz <= ssp:
            Dutch_NS = plunge_NS
        else:
            Dutch_NS = surging_NS

        Dutch_NS = 1.20 * Dutch_NS

        #Stability number used to calculated the mean weight of
        #armor units is the larger of the CERC vs Dutch stability numb
        NS = max(CERC_NS, Dutch_NS)

        w50 = unitwt * (Hs / (NS * ((unitwt / H20weight) - 1.0)))**3

        #Minimum thickness of armor layer
        rarmor = 2.0 * ((w50 / unitwt)**(1.0 / 3.0))

        #Determine bedding/filter layer thickness where %maximum
        #of either rarmor/4 or 1
        rfilter = max(rarmor / 4.0, 1.0)

        #Calculate the total horizontal layer thickness (l) of the
        #armor layer and first underlayer
        rt = rarmor + rfilter
        l = rt * math.sqrt(1.0 + (cotssl**2))

        #Compare l to 2*Hs. If l<2*Hs then set L=2*Hs and solve for a new RT. Then
        #calculate a new rarmor and a new rbed.
        if l < (2 * Hs):
            l = 2 * Hs
            rt = l / math.sqrt(1.0 + (cotssl**2))
            rarmor = rt - rfilter
            rfilter = max(rarmor / 4.0, 1.0)

        #Armor layer weight
        alw0 = (1.0 / 8.0) * w50
        alw15 = 0.4 * w50
        alw50 = w50
        alw85 = 1.96 * w50
        alw100 = 4.0 * w50

        #Armor layer dimension
        ald0 = (alw0 / unitwt)**(1.0 / 3.0)
        ald15 = (alw15 / unitwt)**(1.0 / 3.0)
        ald50 = (alw50 / unitwt)**(1.0 / 3.0)
        ald85 = (alw85 / unitwt)**(1.0 / 3.0)
        ald100 = (alw100 / unitwt)**(1.0 / 3.0)

        #Bedding/filter layer dimensions
        bld85 = ald15 / 4.0

        temp1 = math.exp(0.01157 * 85.0 - 0.5785)
        bld50 = bld85 / temp1

        temp1 = math.exp(0.01157 * 0.0 - 0.5785)
        bld0 = bld50 * temp1

        temp1 = math.exp(0.01157 * 15.0 - 0.5785)
        bld15 = bld50 * temp1

        temp1 = math.exp(0.01157 * 100.0 - 0.5785)
        bld100 = bld50 * temp1

        #Filter layer weight
        blw0 = unitwt * (bld0**3)
        blw15 = unitwt * (bld15**3)
        blw50 = unitwt * (bld50**3)
        blw85 = unitwt * (bld85**3)
        blw100 = unitwt * (bld100**3)

        Tp = Ts / 0.8

        Lp, k = WAVELEN(ds, Tp, 50, self.g)

        Hm01 = 0.1 * Lp * math.tanh(2.0 * math.pi * ds / Lp)
        Hm02 = Hs / math.exp(0.00089 * ((ds / (self.g * (Tp**2)))**(-0.834)))

        Hm0 = min(Hm01, Hm02)

        esp = tanssl / ((2.0 * math.pi * Hm0 / (self.g * (Tp**2)))**0.5)

        runupr_max = RUNUPR(Hm0, esp, 1.022, 0.247)
        runupr_conserv = RUNUPR(Hm0, esp, 1.286, 0.247)

        print("Armor layer thickness =  %-6.2f %s" %\
            (rarmor, self.labelUnitDist))
        print("Percent less than by weight\tWeight (%s)\tDimension (%s)" %\
            (self.labelUnitWt, self.labelUnitDist))
        print("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f" % (0.0, alw0, ald0))
        print("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f" % (15.0, alw15, ald15))
        print("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f" % (50.0, alw50, ald50))
        print("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f" % (85.0, alw85, ald85))
        print("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n" % (100.0, alw100, ald100))

        print("Filter layer thickness =  %-6.2f %s" %\
            (rfilter, self.labelUnitDist))
        print("Percent less than by weight\tWeight (%s)\tDimension (%s)" %\
            (self.labelUnitWt, self.labelUnitDist))
        print("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f" % (0.0, blw0, bld0))
        print("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f" % (15.0, blw15, bld15))
        print("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f" % (50.0, blw50, bld50))
        print("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f" % (85.0, blw85, bld85))
        print("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n" % (100.0, blw100, bld100))

        print("Irregular runup")
        print("Conservative = %-6.2f %s" %\
            (runupr_conserv, self.labelUnitDist))
        print("Expected Maximum = %-6.2f %s" %\
            (runupr_max, self.labelUnitDist))

        dataDict.update({"rarmor": rarmor, "alw0": alw0, "ald0": ald0,\
            "alw15": alw15, "ald15": ald15, "alw50": alw50, "ald50": ald50,\
            "alw85": alw85, "ald85": ald85, "alw100": alw100,\
            "ald100": ald100, "rfilter": rfilter, "blw0": blw0,\
            "bld0": bld0, "blw15": blw15, "bld15": bld15,\
            "blw50": blw50, "bld50": bld50, "blw85": blw85,\
            "bld85": bld85, "blw100": blw100, "bld100": bld100,\
            "runupr_conserv": runupr_conserv, "runupr_max": runupr_max})
        self.fileOutputWriteMain(dataDict, caseIndex)

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("Hs\t%6.2f %s\n" %\
            (dataDict["Hs"], self.labelUnitDist))
        self.fileRef.write("Ts\t%6.2f s\n" % dataDict["Ts"])
        self.fileRef.write("cotnsl\t%6.2f\n" % dataDict["cotnsl"])
        self.fileRef.write("ds\t%6.2f %s\n" %
                           (dataDict["ds"], self.labelUnitDist))
        self.fileRef.write("cotssl\t%6.2f\n" % dataDict["cotssl"])
        self.fileRef.write("unitwt\t%6.2f %s/%s^3\n" %\
            (dataDict["unitwt"], self.labelUnitWt, self.labelUnitDist))
        self.fileRef.write("P\t%6.2f\n" % dataDict["P"])
        self.fileRef.write("S\t%6.2f\n\n" % dataDict["S"])

        if self.errorMsg != None:
            self.fileRef.write("%s\n\n" % self.errorMsg)
        else:
            self.fileRef.write("Armor layer thickness =  %-6.2f %s\n" %\
                (dataDict["rarmor"], self.labelUnitDist))
            self.fileRef.write("Percent less than by weight\tWeight (%s)\tDimension (%s)\n" %\
                (self.labelUnitWt, self.labelUnitDist))
            self.fileRef.write("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n" %\
                (0.0, dataDict["alw0"], dataDict["ald0"]))
            self.fileRef.write("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n" %\
                (15.0, dataDict["alw15"], dataDict["ald15"]))
            self.fileRef.write("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n" %\
                (50.0, dataDict["alw50"], dataDict["ald50"]))
            self.fileRef.write("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n" %\
                (85.0, dataDict["alw85"], dataDict["ald85"]))
            self.fileRef.write("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n\n" %\
                (100.0, dataDict["alw100"], dataDict["ald100"]))

            self.fileRef.write("Filter layer thickness =  %-6.2f %s\n" %\
                (dataDict["rfilter"], self.labelUnitDist))
            self.fileRef.write("Percent less than by weight\tWeight (%s)\tDimension (%s)\n" %\
                (self.labelUnitWt, self.labelUnitDist))
            self.fileRef.write("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n" %\
                (0.0, dataDict["blw0"], dataDict["bld0"]))
            self.fileRef.write("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n" %\
                (15.0, dataDict["blw15"], dataDict["bld15"]))
            self.fileRef.write("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n" %\
                (50.0, dataDict["blw50"], dataDict["bld50"]))
            self.fileRef.write("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n" %\
                (85.0, dataDict["blw85"], dataDict["bld85"]))
            self.fileRef.write("%-3.1f\t\t\t\t%-6.2f\t\t%-6.2f\n\n" %\
                (100.0, dataDict["blw100"], dataDict["bld100"]))

            self.fileRef.write("Irregular runup\n")
            self.fileRef.write("Conservative = %-6.2f %s\n" %\
                (dataDict["runupr_conserv"], self.labelUnitDist))
            self.fileRef.write("Expected Maximum = %-6.2f %s\n" %\
                (dataDict["runupr_max"], self.labelUnitDist))

        exportData = [dataDict["Hs"], dataDict["Ts"], dataDict["cotnsl"],\
            dataDict["ds"], dataDict["cotssl"], dataDict["unitwt"],\
            dataDict["P"], dataDict["S"]]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["rarmor"], dataDict["alw0"],\
                dataDict["ald0"], dataDict["alw15"], dataDict["ald15"],\
                dataDict["alw50"], dataDict["ald50"], dataDict["alw85"],\
                dataDict["ald85"], dataDict["alw100"], dataDict["ald100"],\
                dataDict["rfilter"], dataDict["blw0"], dataDict["bld0"],\
                dataDict["blw15"], dataDict["bld15"], dataDict["blw50"],\
                dataDict["bld50"], dataDict["blw85"], dataDict["bld85"],\
                dataDict["blw100"], dataDict["bld100"],\
                dataDict["runupr_conserv"], dataDict["runupr_max"]]
        self.exporter.writeData(exportData)
Ejemplo n.º 14
0
class CnoidalWaveTheory(BaseDriver):
    def __init__(self, H = None, T = None, d = None, z = None, xL = None,\
        O = None):
        self.exporter = EXPORTER("output/exportCnoidalWaveTheory.txt")

        if H != None:
            self.isSingleCase = True
            self.defaultValueH = H
        if T != None:
            self.isSingleCase = True
            self.defaultValueT = T
        if d != None:
            self.isSingleCase = True
            self.defaultValue_d = d
        if z != None:
            self.isSingleCase = True
            self.defaultValue_z = z
        if xL != None:
            self.isSingleCase = True
            self.defaultValue_xL = xL
        if O != None:
            self.isSingleCase = True
            self.defaultValue_O = O

        super(CnoidalWaveTheory, self).__init__()

        self.exporter.close()

    # end __init__

    def userInput(self):
        super(CnoidalWaveTheory, self).userInput()

        self.waterType, self.rho =\
            USER_INPUT.SALT_FRESH_WATER(self.isMetric)


#        self.O = USER_INPUT.FINITE_CHOICE(\
#            "Enter O: order approximation (1 or 2): ",\
#            ["1", "2"])
#        self.O = int(self.O)
# end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueH"):
            self.inputList.append(BaseField(\
                "H: wave height (%s)" % self.labelUnitDist, 0.1, 200.0))
        if not hasattr(self, "defaultValueT"):
            self.inputList.append(BaseField(\
                "T: wave period (sec)", 1.0, 1000.0))
        if not hasattr(self, "defaultValue_d"):
            self.inputList.append(BaseField(\
                "d: water depth (%s)" % self.labelUnitDist, 0.1, 5000.0))
        if not hasattr(self, "defaultValue_z"):
            self.inputList.append(BaseField(\
                "z: vertical coordinate (%s)" % self.labelUnitDist,\
                -5100.0, 100.0))
        if not hasattr(self, "defaultValue_xL"):
            self.inputList.append(BaseField(\
                "xL: horizontal coordinate as fraction of wavelength (x/L)",\
                0.0, 1.0))
        if not hasattr(self, "defaultValue_O"):
            self.inputList.append(BaseField(\
                "O: order approximation (1 or 2)",\
                1.0, 2.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(requestDesc=True)

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueH"):
            H = self.defaultValueH
        else:
            H = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueT"):
            T = self.defaultValueT
        else:
            T = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_d"):
            d = self.defaultValue_d
        else:
            d = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_z"):
            z = self.defaultValue_z
        else:
            z = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_xL"):
            xL = self.defaultValue_xL
        else:
            xL = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_O"):
            O = self.defaultValue_O
        else:
            O = caseInputList[currIndex]
            currIndex = currIndex + 1
        O = int(O)

        return H, T, d, z, xL, O

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        H, T, d, z, xL, O = self.getCalcValues(caseInputList)
        dataDict = {"H": H, "T": T, "d": d, "z": z, "xL": xL, "O": O}

        time = 0

        epsi = H / d

        Hb = ERRWAVBRK1(d, 0.78)
        if not (H < Hb):
            self.errorMsg = "Error: Input wave broken (Hb = %6.2f %s)" %\
                (Hb, self.labelUnitDist)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        # First Order Approximation
        if O == 1:  #determining m using bisection method
            a = 1.0 * 10**-12
            b = 1.0 - 10**-12

            loopCount = 0
            while (b - a) / 2.0 >= 0.00001:
                xi = (a + b) / 2.0
                if self.F1(xi, H, T, d) == 0:
                    break
                else:
                    if self.F1(xi, H, T, d) * self.F1(b, H, T, d) < 0.0:
                        a = xi
                    elif self.F1(xi, H, T, d) * self.F1(a, H, T, d) < 0.0:
                        b = xi

                loopCount += 1
                if loopCount >= 20:
                    break
            # end while loop

            m = xi

            K = sp.ellipk(m)
            E = sp.ellipe(m)

            lambdaVal = (1 - m) / m
            mu = E / (m * K)
            theta = 2.0 * K * (xL - (time / T))

            C0 = 1.0
            C1 = (1.0 + 2.0 * lambdaVal - 3.0 * mu) / 2.0
            C = math.sqrt(self.g * d) * (C0 + epsi * C1)  # celerity

            L = C * T  # wave length

            Ur = (H * (L**2)) / (d**3)
            if not (Ur > 26.0):
                self.errorMsg = "Error: Ursell parameter test failed."

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            SN, CN, DN, PH = sp.ellipj(theta, m)
            CSD = CN * SN * DN

            A0 = epsi * (lambdaVal - mu)
            A1 = epsi
            eta = d * (A0 + A1 * CN**2)  # water surface elevation

            if not (z < eta and (z + d) > 0.0):
                self.errorMsg = "Error: Point outside waveform."

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            E0 = (-lambdaVal + 2.0 * mu + 4.0 * lambdaVal * mu - lambdaVal**2 -
                  3.0 * mu**2) / 3.0
            E = self.rho * self.g * H**2 * E0  # average energy density

            F0 = E0
            Ef = self.rho * self.g * H**2 * math.sqrt(
                self.g * d) * F0  # energy flux

            B00 = epsi * (lambdaVal - mu)
            B10 = epsi
            u = math.sqrt(self.g * d) * (B00 + B10 * CN**2
                                         )  # horizontal velocity

            w = math.sqrt(self.g * d) * (4.0 * K * d * CSD / L) * (
                (z + d) / d) * B10  # vertical velocity

            dudt = math.sqrt(self.g * d) * B10 * (
                4.0 * K / T) * CSD  # horizontal acceleration

            term = math.sqrt(self.g * d) * (4 * K * d / L) * (
                (z + d) / d) * B10 * (2.0 * K / T)
            dwdt = term * ((SN * DN)**2 - (CN * DN)**2 +
                           (m * SN * CN)**2)  # vertical acceleration

            P1 = (1.0 + 2.0 * lambdaVal - 3.0 * mu) / 2.0
            P0 = 1.5
            Pb = self.rho * self.g * d * (P0 + epsi * P1)
            pres = Pb - (self.rho / 2.0) * (
                (u - C)**2 + w**2) - self.g * self.rho * (z + d)  # pressure

            print("First Order Approximations")
        # Second Order Approximations
        else:
            a = 1.0 * 10**-12
            b = 1.0 - 10**-12

            loopCount = 0
            while (b - a) / 2.0 >= 0.00001:
                xi = (a + b) / 2.0
                if self.F2(xi, H, T, d, epsi) == 0:
                    break
                else:
                    if self.F2(xi, H, T, d, epsi) * self.F2(b, H, T, d,
                                                            epsi) < 0.0:
                        a = xi
                    elif self.F2(xi, H, T, d, epsi) * self.F2(
                            a, H, T, d, epsi) < 0.0:
                        b = xi

                loopCount += 1
                if loopCount >= 20:
                    break
            # end while loop

            m = xi

            K = sp.ellipk(m)
            E = sp.ellipe(m)

            lambdaVal = (1 - m) / m
            mu = E / (m * K)
            theta = 2.0 * K * (xL - (time / T))

            SN, CN, DN, PH = sp.ellipj(theta, m)
            CSD = CN * SN * DN

            C2 = (-6.0 - 16.0 * lambdaVal + 5.0 * mu - 16.0 * lambdaVal**2 +
                  10.0 * lambdaVal * mu + 15.0 * mu**2) / 40.0
            C1 = (1.0 + 2.0 * lambdaVal - 3.0 * mu) / 2.0
            C0 = 1.0
            C = math.sqrt(self.g * d) * (C0 + epsi * C1 + epsi**2 * C2
                                         )  #celerity

            L = C * T  #wave length

            Ur = (H * (L**2)) / (d**3)
            if not (Ur > 26.0):
                self.errorMsg = "Error: Ursell parameter test failed."

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            A2 = 0.75 * epsi**2
            A1 = epsi - A2
            A0 = epsi*(lambdaVal - mu) +\
                epsi**2*((-2.0*lambdaVal + mu - 2.0*lambdaVal**2 + 2.0*lambdaVal*mu)/4.0)
            eta = d * (A0 + A1 * CN**2 + A2 * CN**4)  #wave surface elevation

            if not (z < eta and (z + d) > 0.0):
                self.errorMsg = "Error: Point outside waveform."

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            E1 = (1.0/30.0)*(lambdaVal - 2.0*mu - 17.0*lambdaVal*mu +\
                3.0*lambdaVal**2 - 17.0*lambdaVal**2*mu +\
                2.0*lambdaVal**3 + 15.0*mu**3)
            E0 = (-lambdaVal + 2.0 * mu + 4.0 * lambdaVal * mu - lambdaVal**2 -
                  3.0 * mu**2) / 3.0
            E = self.rho * self.g * H**2 * (E0 + epsi * E1
                                            )  #average energy density

            F1 = (1.0/30.0)*(-4.0*lambdaVal + 8.0*mu +\
                53.0*lambdaVal*mu - 12*lambdaVal**2 - 60.0*mu**2 +\
                53.0*lambdaVal**2*mu - 120.0*lambdaVal*mu**2 -\
                8.0*lambdaVal**3 + 75.0*mu**3)
            F0 = E0
            Ef = self.rho * self.g * H**2 * math.sqrt(self.g * d) * (
                F0 + epsi * F1)  #energy flux

            term = (z + d) / d

            B21 = -4.5 * epsi**2
            B11 = 3.0 * epsi**2 * (1 - lambdaVal)
            B01 = ((3.0 * lambdaVal) / 2.0) * epsi**2
            B20 = -(epsi**2)
            B10 = epsi + epsi**2 * ((1.0 - 6.0 * lambdaVal + 2.0 * mu) / 4.0)
            B00 = epsi * (lambdaVal - mu) + epsi**2 * (
                (lambdaVal - mu - 2.0 * lambdaVal**2 + 2.0 * mu**2) / 4.0)
            u = math.sqrt(self.g*d)*((B00 + B10*CN**2 + B20*CN**4) -\
                0.5*term**2*(B01 + B11*CN**2 + B21*CN**4)) #horizontal velocity

            w1 = term * (B10 + 2.0 * B20 * CN**2)
            w2 = (1.0 / 6.0) * term**3 * (B11 + 2.0 * B21 * CN**2)
            w = math.sqrt(self.g * d) * (4.0 * K * d * CSD / L) * (
                w1 - w2)  #vertical velocity

            u1 = (B10 - 0.5 * term**2 * B11) * (4.0 * K * CSD / T)
            u2 = (B20 - 0.5 * term**2 * B21) * (8.0 * K * CN**2 * CSD / T)
            dudt = math.sqrt(self.g * d) * (u1 + u2)  #horizontal acceleration

            w1 = (8.0 * K * CSD**2 / T) * (term * B20 -
                                           (1.0 / 6.0) * term**3 * B21)
            w2 = term * (B10 + 2.0 * B20 * CN**2) - (1.0 / 6.0) * term**3 * (
                B11 + 2.0 * B21 * CN**2)
            w3 = (2.0 * K / T) * ((SN * DN)**2 - (CN * DN)**2 +
                                  (m * SN * CN)**2)
            dwdt = math.sqrt(self.g * d) * (4.0 * K * d / L) * (
                w1 + w2 * w3)  #vertical acceleration

            P2 = (-1.0 - 16.0 * lambdaVal + 15.0 * mu - 16.0 * lambdaVal**2 +
                  30 * lambdaVal * mu) / 40.0
            P1 = (1.0 + 2 * lambdaVal - 3.0 * mu) / 2.0
            P0 = 1.5
            Pb = self.rho * self.g * d * (P0 + epsi * P1 + epsi**2 * P2)
            pres = Pb - (self.rho / 2.0) * (
                (u - C)**2 + w**2) - self.g * self.rho * (z + d)

            print("Second Order Approximations")
        # end if

        print("Wavelength\t\t%-6.2f %s" % (L, self.labelUnitDist))
        print("Celerity\t\t%-6.2f %s/sec" % (C, self.labelUnitDist))
        print("Energy density\t\t%-8.2f %s-%s/%s^2" %\
            (E, self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))
        print("Energy flux\t\t%-8.2f %s-%s/sec-%s" %
              (Ef, self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))
        print("Ursell number\t\t%-6.2f" % Ur)
        print("Elevation\t\t%-6.2f %s" % (eta, self.labelUnitDist))
        print("Horz. velocity\t\t%-6.2f %s/sec" % (u, self.labelUnitDist))
        print("Vert. velocity\t\t%-6.2f %s/sec" % (w, self.labelUnitDist))
        print("Horz. acceleration\t%-6.2f %s/sec^2" %
              (dudt, self.labelUnitDist))
        print("Vert. acceleration\t%-6.2f %s/sec^2" %
              (dwdt, self.labelUnitDist))
        print("Pressure\t\t%-8.2f %s/%s^2" %
              (pres, self.labelUnitWt, self.labelUnitDist))

        dataDict["L"] = L
        dataDict["C"] = C
        dataDict["E"] = E
        dataDict["Ef"] = Ef
        dataDict["Ur"] = Ur
        dataDict["eta"] = eta
        dataDict["u"] = u
        dataDict["w"] = w
        dataDict["dudt"] = dudt
        dataDict["dwdt"] = dwdt
        dataDict["pres"] = pres
        self.fileOutputWriteMain(dataDict, caseIndex)

        if self.isSingleCase:
            self.plotDict = {"O": O, "K": K, "time": time, "T": T, "m": m,\
                "d": d, "A0": A0, "A1": A1, "B00": B00,\
                "B10": B10, \
                "z": z, "L": L}

            if O == 2:
                self.plotDict["A2"] = A2
                self.plotDict["B01"] = B01
                self.plotDict["B20"] = B20
                self.plotDict["B11"] = B11
                self.plotDict["B21"] = B21

    # end performCalculations

    def F1(self, m, H, T, d):
        return (16 * m * sp.ellipk(m)**2 / 3) - (self.g * H * T**2 / d**2)

    # end F1

    def F2(self, m, H, T, d, epsi):
        return (16 * m * sp.ellipk(m)**2 /
                3) - (self.g * H * T**2 / d**2) * (1 - epsi *
                                                   ((1.0 + 2.0 *
                                                     ((1.0 - m) / m)) / 4.0))

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("Wave height\t\t\t%8.2f %s\n" %\
            (dataDict["H"], self.labelUnitDist))
        self.fileRef.write("Wave period\t\t\t%8.2f s\n" % dataDict["T"])
        self.fileRef.write("Water depth\t\t\t%8.2f %s\n" %\
            (dataDict["d"], self.labelUnitDist))
        self.fileRef.write("Vertical coordinate\t\t%8.2f %s\n" %\
            (dataDict["z"], self.labelUnitDist))
        self.fileRef.write(
            "Horizontal coordinate\t\t%8.2f\nas fraction of wavelength (x/L)\n"
            % dataDict["xL"])

        if self.errorMsg != None:
            self.fileRef.write("\n%s\n" % self.errorMsg)
        else:
            if dataDict["O"] == 1:
                self.fileRef.write("\nFirst Order Approximations\n")
            else:
                self.fileRef.write("\nSecond Order Approximations\n")

            self.fileRef.write("Wavelength\t\t%-6.2f %s\n" %\
                (dataDict["L"], self.labelUnitDist))
            self.fileRef.write("Celerity\t\t%-6.2f %s/sec\n" %\
                (dataDict["C"], self.labelUnitDist))
            self.fileRef.write("Energy density\t\t%-8.2f %s-%s/%s^2\n" %\
                (dataDict["E"], self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))
            self.fileRef.write("Energy flux\t\t%-8.2f %s-%s/sec-%s\n" %\
                (dataDict["Ef"], self.labelUnitDist, self.labelUnitWt, self.labelUnitDist))
            self.fileRef.write("Ursell number\t\t%-6.2f\n" % dataDict["Ur"])
            self.fileRef.write("Elevation\t\t%-6.2f %s\n" %\
                (dataDict["eta"], self.labelUnitDist))
            self.fileRef.write("Horz. velocity\t\t%-6.2f %s/sec\n" %\
                (dataDict["u"], self.labelUnitDist))
            self.fileRef.write("Vert. velocity\t\t%-6.2f %s/sec\n" %\
                (dataDict["w"], self.labelUnitDist))
            self.fileRef.write("Horz. acceleration\t%-6.2f %s/sec^2\n" %\
                (dataDict["dudt"], self.labelUnitDist))
            self.fileRef.write("Vert. acceleration\t%-6.2f %s/sec^2\n" %\
                (dataDict["dwdt"], self.labelUnitDist))
            self.fileRef.write("Pressure\t\t%-8.2f %s/%s^2\n" %\
                (dataDict["pres"], self.labelUnitWt, self.labelUnitDist))


        exportData = [dataDict["H"], dataDict["T"], dataDict["d"],\
            dataDict["z"], dataDict["xL"], dataDict["O"]]
        if self.errorMsg != None:
            exportData.append("Error")
        else:
            exportData = exportData + [dataDict["L"], dataDict["C"],\
                dataDict["E"], dataDict["Ef"], dataDict["eta"],\
                dataDict["u"], dataDict["w"], dataDict["dudt"], dataDict["dwdt"],\
                dataDict["pres"]]
        self.exporter.writeData(exportData)

    # end fileOutputWriteData

    def hasPlot(self):
        return True

    def performPlot(self):
        #Plotting waveform
        plotxL = list(np.arange(-1, 1.001, 0.001))
        plottheta = [2*self.plotDict["K"]*\
            (i - (self.plotDict["time"]/self.plotDict["T"])) for i in plotxL]
        pSN, pCN, pDN, pPH = sp.ellipj(plottheta, self.plotDict["m"])
        pCSD = pSN * pCN * pDN

        if self.plotDict["O"] == 1:
            ploteta = self.plotDict["d"]*\
                (self.plotDict["A0"] + self.plotDict["A1"]*pCN**2)
            plotu = math.sqrt(self.g*self.plotDict["d"])*\
                (self.plotDict["B00"] + self.plotDict["B10"]*pCN**2)
            plotw = math.sqrt(self.g*self.plotDict["d"])*\
                (4.0*self.plotDict["K"]*self.plotDict["d"]*pCSD/self.plotDict["L"])*\
                ((self.plotDict["z"] + self.plotDict["d"])/self.plotDict["d"])*self.plotDict["B10"]
        else:
            ploteta = self.plotDict["d"]*(self.plotDict["A0"] +\
                self.plotDict["A1"]*pCN**2 + self.plotDict["A2"]*pCN**4)
            plotu = math.sqrt(self.g*self.plotDict["d"])*\
                ((self.plotDict["B00"] + self.plotDict["B10"]*pCN**2 +\
                self.plotDict["B20"]*pCN**4) -\
                0.5*((self.plotDict["z"] + self.plotDict["d"]) / self.plotDict["d"])**2 *\
                (self.plotDict["B01"] + self.plotDict["B11"]*pCN**2 + self.plotDict["B21"]*pCN**4))

            pw1 = ((self.plotDict["z"] + self.plotDict["d"])/self.plotDict["d"])*\
                (self.plotDict["B10"] + 2.0*self.plotDict["B20"]*pCN**2)
            pw2 = (1.0/6.0)*(((self.plotDict["z"] + self.plotDict["d"])/self.plotDict["d"])**3)*\
                (self.plotDict["B11"] + 2.0*self.plotDict["B21"]*pCN**2)
            plotw = math.sqrt(self.g*self.plotDict["d"])*\
                (4.0*self.plotDict["K"]*self.plotDict["d"]*pCSD/self.plotDict["L"])*(pw1 - pw2)
        # end if

        plt.figure(1, figsize=(8, 12), dpi=self.plotConfigDict["dpi"])

        plt.subplot(3, 1, 1)
        plt.plot(plotxL, ploteta)
        plt.axhline(y=0.0, color="r", LineStyle="--")
        plt.ylabel("Elevation [%s]" % self.labelUnitDist)

        plt.subplot(3, 1, 2)
        plt.plot(plotxL, plotu)
        plt.axhline(y=0.0, color="r", LineStyle="--")
        plt.ylabel("Velocity, u [%s/s]" % self.labelUnitDist)

        plt.subplot(3, 1, 3)
        plt.plot(plotxL, plotw)
        plt.axhline(y=0.0, color="r", LineStyle="--")
        plt.ylabel("Velocity, w [%s/s]" % self.labelUnitDist)
        plt.xlabel("x/L")

        plt.show()

        self.plotDict["plotxL"] = plotxL
        self.plotDict["ploteta"] = ploteta
        self.plotDict["plotu"] = plotu
        self.plotDict["plotw"] = plotw
        self.fileOutputPlotWriteData()

    # end performPlot

    def fileOutputPlotWriteData(self):
        self.fileRef.write(\
            "Partial Listing of Plot Output File 1 for %s\n\n" %\
            self.fileOutputData.fileDesc)

        self.fileRef.write(\
            "X/L\tETA (%s)\tU(%s/sec)\tW (%s/sec)\n" %\
            (self.labelUnitDist, self.labelUnitDist, self.labelUnitDist))

        for i in range(len(self.plotDict["plotxL"])):
            self.fileRef.write("%-6.3f\t%-6.3f\t\t%-6.3f\t\t%-6.3f\n" %\
                (self.plotDict["plotxL"][i],\
                self.plotDict["ploteta"][i],\
                self.plotDict["plotu"][i],\
                self.plotDict["plotw"][i]))
Ejemplo n.º 15
0
class ToeDesign(BaseDriver):
    def __init__(self, H = None, T = None, ds = None, cotphi = None,\
        Kp = None, de = None, ht = None, unitwt = None):
        self.exporter = EXPORTER("output/exportToeDesign")

        if H != None:
            self.isSingleCase = True
            self.defaultValueH = H
        if T != None:
            self.isSingleCase = True
            self.defaultValueT = T
        if ds != None:
            self.isSingleCase = True
            self.defaultValue_ds = ds
        if cotphi != None:
            self.isSingleCase = True
            self.defaultValue_cotphi = cotphi
        if Kp != None:
            self.isSingleCase = True
            self.defaultValueKp = Kp
        if de != None:
            self.isSingleCase = True
            self.defaultValue_de = de
        if ht != None:
            self.isSingleCase = True
            self.defaultValue_ht = ht
        if unitwt != None:
            self.isSingleCase = True
            self.defaultValue_unitwt = unitwt

        super(ToeDesign, self).__init__()

        self.exporter.close()

    # end __init__

    def userInput(self):
        super(ToeDesign, self).userInput()

        self.water, self.rho = USER_INPUT.SALT_FRESH_WATER(self.isMetric)

    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueH"):
            self.inputList.append(BaseField(\
                "Hi: wave height (%s)" % (self.labelUnitDist), 0.1, 100.0))
        if not hasattr(self, "defaultValueT"):
            self.inputList.append(BaseField(\
                "T: wave period (sec)", 1.0, 1000.0))
        if not hasattr(self, "defaultValue_ds"):
            self.inputList.append(BaseField(\
                "ds: water depth at structure (%s)" % (self.labelUnitDist), 0.1, 200.0))
        if not hasattr(self, "defaultValue_cotphi"):
            self.inputList.append(BaseField(\
                "cotphi: cotangent of nearshore slope", 5.0, 10000.0))
        if not hasattr(self, "defaultValueKp"):
            self.inputList.append(BaseField(\
                "Kp: passive earth pressure coefficient", 0.0, 50.0))
        if not hasattr(self, "defaultValue_de"):
            self.inputList.append(BaseField(\
                "de: sheet-pile penetration depth (%s)" % (self.labelUnitDist), 0.0, 200.0))
        if not hasattr(self, "defaultValue_ht"):
            self.inputList.append(BaseField(\
                "ht: height of toe protection layer above mudline (%s)" % (self.labelUnitDist), 0.1, 200.0))
        if not hasattr(self, "defaultValue_unitwt"):
            self.inputList.append(BaseField(\
                "unitwt: unit weight of rock (%s/%s^3)" % (self.labelUnitWt, self.labelUnitDist), 1.0, 99999.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename="toe_design")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueH"):
            H = self.defaultValueH
        else:
            H = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueT"):
            T = self.defaultValueT
        else:
            T = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_ds"):
            ds = self.defaultValue_ds
        else:
            ds = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_cotphi"):
            cotphi = self.defaultValue_cotphi
        else:
            cotphi = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueKp"):
            Kp = self.defaultValueKp
        else:
            Kp = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_de"):
            de = self.defaultValue_de
        else:
            de = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_ht"):
            ht = self.defaultValue_ht
        else:
            ht = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_unitwt"):
            unitwt = self.defaultValue_unitwt
        else:
            unitwt = caseInputList[currIndex]

        return H, T, ds, cotphi, Kp, de, ht, unitwt

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        H, T, ds, cotphi, Kp, de, ht, unitwt =\
            self.getCalcValues(caseInputList)
        dataDict = {"H": H, "T": T, "ds": ds, "cotphi": cotphi,\
            "Kp": Kp, "de": de, "ht": ht, "unitwt": unitwt}

        H20weight = self.g * self.rho

        specgrav = unitwt / H20weight

        dl = ds - ht
        m = 1.0 / cotphi

        if not (ds / (T**2) > 0.0037424):
            self.errorMsg = "Error: Limiting value detected...Hbs cannot be solved."

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        Hbs = ERRWAVBRK2(T, m, ds)
        if not (H < Hbs):
            self.errorMsg = "Error: Wave broken at structure (Hbs = %6.2f %s)" %\
                (Hbs, self.labelUnitDist)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        L, k = WAVELEN(dl, T, 50, self.g)

        steep, maxstp = ERRSTP(H, dl, L)
        if not ComplexUtil.lessThan(steep, maxstp):
            self.errorMsg = "Error: Input wave unstable (Max: %0.4f, [H/L] = %0.4f)" %\
                (maxstp.real, steep.real)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        b1 = de * Kp
        b2 = 2.0 * H
        b3 = 0.4 * ds
        b = [1.0, b1, b2, b3]
        b = max(b)

        arg1 = (4.0 * math.pi * dl / L)
        kappa = (arg1 / cmath.sinh(arg1)) * (
            (cmath.sin(2.0 * math.pi * b / L))**2)
        arg2 = ((1.0 - kappa) / (kappa**(1.0 / 3.0))) * (dl / H)
        Ns = 1.3 * arg2 + 1.8 * cmath.exp(-1.5 * (1.0 - kappa) * arg2)

        #        Ns = max(Ns, 1.8)
        if ComplexUtil.getCompVal(Ns) < 1.8:
            Ns = 1.8

        w = (unitwt * (H**3)) / ((Ns**3) * ((specgrav - 1.0)**3))

        print("\nWidth of toe apron\t\t%6.2f %s" %\
            (b, self.labelUnitDist))
        print("Weight of individual armor unit\t%6.2f %s" %\
            (w.real, self.labelUnitWt))
        print("Water depth at top of tow\t%6.2f %s" %\
            (dl, self.labelUnitDist))

        dataDict.update({"b": b, "w": w, "dl": dl})
        self.fileOutputWriteMain(dataDict, caseIndex)

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("H\t\t\t\t%6.2f %s\n" %\
            (dataDict["H"], self.labelUnitDist))
        self.fileRef.write("T\t\t\t\t%6.2f s\n" % dataDict["T"])
        self.fileRef.write("ds\t\t\t\t%6.2f %s\n" %\
            (dataDict["ds"], self.labelUnitDist))
        self.fileRef.write("cotphi\t\t\t\t%6.2f\n" % dataDict["cotphi"])
        self.fileRef.write("Kp\t\t\t\t%6.2f\n" % dataDict["Kp"])
        self.fileRef.write("de\t\t\t\t%6.2f %s\n" %\
            (dataDict["de"], self.labelUnitDist))
        self.fileRef.write("ht\t\t\t\t%6.2f %s\n" %\
            (dataDict["ht"], self.labelUnitDist))
        self.fileRef.write("unitwt\t\t\t\t%6.2f %s/%s^3\n" %\
            (dataDict["unitwt"], self.labelUnitWt, self.labelUnitDist))

        if self.errorMsg != None:
            self.fileRef.write("\n%s\n" % self.errorMsg)
        else:
            self.fileRef.write("\nWidth of toe apron\t\t%6.2f %s\n" %\
                (dataDict["b"], self.labelUnitDist))
            self.fileRef.write("Weight of individual armor unit\t%6.2f %s\n" %\
                (dataDict["w"].real, self.labelUnitWt))
            self.fileRef.write("Water depth at top of tow\t%6.2f %s\n" %\
                (dataDict["dl"], self.labelUnitDist))

        exportData = [dataDict["H"], dataDict["T"], dataDict["ds"],\
            dataDict["cotphi"], dataDict["Kp"], dataDict["de"],\
            dataDict["ht"], dataDict["unitwt"]]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["b"], dataDict["w"],\
                dataDict["dl"]]
        self.exporter.writeData(exportData)
Ejemplo n.º 16
0
class ExtHsAnalysis(BaseDriver):
    def __init__(self, Nt = None, K = None, d = None,\
        Hs = None, option = None):
        self.exporter = EXPORTER("output/exportExtHsAnalysis")

        self.isSingleCase = True

        if Nt != None:
            self.defaultValueNt = Nt
        if K != None:
            self.defaultValueK = K
        if d != None:
            self.defaultValue_d = d
        if Hs != None:
            self.defaultValueHs = Hs
        if option != None:
            self.defaultValue_option = option

        super(ExtHsAnalysis, self).__init__()
        
        self.exporter.close()
    # end __init__

    def userInput(self):
        super(ExtHsAnalysis, self).userInput()

        if not hasattr(self, "defaultValueHs"):
            hsCount = USER_INPUT.DATA_VALUE(\
                "the number of significant wave heights", 1, 200)
            hsCount = int(hsCount)

            self.Hs = []
            for i in range(hsCount):
                self.Hs.append(USER_INPUT.DATA_VALUE(\
                    "significant wave height [%s] #%d" %\
                    (self.labelUnitDist, (i + 1)),\
                    0.0, 100.0))
        else:
            self.Hs = self.defaultValueHs

        if not hasattr(self, "defaultValue_option"):
            self.option = USER_INPUT.FINITE_CHOICE(\
                "Confidence intervals:\n[1] 80%\n[2] 85%\n[3] 90%\n[4] 95%\n[5] 99%\nSelect option: ",\
                ["1", "2", "3", "4", "5"])
            self.option = int(self.option)
        else:
            self.option = self.defaultValue_option
    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueNt"):
            self.inputList.append(BaseField(\
                "Nt: estimated total number of events",  0.0, 10000.0))

        if not hasattr(self, "defaultValueK"):
            self.inputList.append(BaseField(\
                "K: length of the record in years", 0.0, 999.9))

        if not hasattr(self, "defaultValue_d"):
            self.inputList.append(BaseField(\
                "d: water depth [%s]" % (self.labelUnitDist), 0.0, 1000.0))
    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename = "ext_Hs_analysis")

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValueNt"):
            Nt = self.defaultValueNt
        else:
            Nt = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueK"):
            K = self.defaultValueK
        else:
            K = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_d"):
            d = self.defaultValue_d
        else:
            d = caseInputList[currIndex]

        return Nt, K, d
    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex = 0):
        Nt, K, d = self.getCalcValues(caseInputList)

        N = len(self.Hs)
        lambdaVal = Nt / K
        nu = N / Nt

        dataDict = {"Nt": Nt, "K": K, "d": d, "N": N,\
            "nu": nu, "lambdaVal": lambdaVal}
        
        self.Hs = [i / 0.3048 for i in self.Hs]
        d = d / 0.3048

        Hb = ERRWAVBRK1(d, 0.78)
        for j in self.Hs:
            if not (j < Hb):
                self.errorMsg = "Error: Input wave broken (Hb = %6.2f %s)" %\
                    (Hb, self.labelUnitDist)
                    
                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

        ret = [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9,\
            2.0, 5.0, 10.0, 25.0, 50.0, 100.0]

        #Coefficients
        k_W = [0.75, 1.00, 1.40, 2.00]
        a1 = [0.64, 1.65, 1.92, 2.05, 2.24]
        a2 = [9.0, 11.4, 11.4, 11.4, 11.4]
        kappa = [0.93, -0.63, 0.00, 0.69, 1.34]
        c = [0.0, 0.0, 0.3, 0.4, 0.5]
        epsi = [1.33, 1.15, 0.90, 0.72, 0.54]

        pret = [1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0]
        plen = pret

        self.Hs.sort()
        self.Hs.reverse()

        yact = [[0.0 for j in range(5)] for i in range(N)]
        ym = [[0.0 for j in range(5)] for i in range(N)]
        for j in range(N):
            yact[j][0] = 1.0 - ((j + 1) - 0.44)/(Nt + 0.12) #FT-I
            ym[j][0] = -math.log(-math.log(yact[j][0]))

            for m in range(1, 5):
                k = k_W[m - 1] #Weibull
                yact[j][m] = 1.0 - ((j + 1) - 0.2 - 0.27/math.sqrt(k))/\
                    (Nt + 0.2 + 0.23/math.sqrt(k))
                ym[j][m] = (-math.log(1.0 - yact[j][m]))**(1.0/k)
        # end for loop

        Sx = sum(self.Hs)
        Sy = [sum([yact[j][m] for j in range(N)]) for m in range(5)]
        Sxx = sum([i**2 for i in self.Hs])
        Slly = [sum([ym[j][m] for j in range(N)]) for m in range(5)]
        Syy = [sum([ym[j][m]**2 for j in range(N)]) for m in range(5)]

        Sxy = [[0.0 for j in range(5)] for i in range(N)]
        for j in range(N):
            for m in range(5):
                Sxy[j][m] = self.Hs[j]*ym[j][m]
        Sxy = [sum([Sxy[j][m] for j in range(N)]) for m in range(5)]

        alpha = []
        beta = []
        for m in range(5):
            alpha.append((N*Sxy[m] - Sx*Slly[m])/(N*Syy[m] - Slly[m]**2))
            beta.append((1.0/N)*(Sx - alpha[m]*Slly[m]))

        yest = []
        for j in range(N):
            yest.append([])
            yest[j].append(\
                math.exp(-math.exp(-(self.Hs[j] - beta[0])/alpha[0]))) #FT-I

            for m in range(1, 5):
                k = k_W[m - 1] #Weibull
                if (self.Hs[j] - beta[m])/alpha[m] >= 0.0:
                    yest[j].append(\
                        1.0 - math.exp(-((self.Hs[j] - beta[m])/alpha[m])**k))
                else:
                    yest[j].append(0.0)

        st = []
        for j in range(N):
            st.append([])
            for m in range(5):
                st[j].append((yact[j][m] - yest[j][m])**2)

        # sumresid = sum(st)/0.3048
        sumresid = [sum([st[j][m] for j in range(N)]) for m in range(5)]
        sumresid = [i/0.3048 for i in sumresid] #sum square of residuals

        rxy = []
        for m in range(5):
            numer = N*Sxy[m] - Sx*Slly[m]
            term1d = N*Sxx - Sx**2
            term2d = N*Syy[m] - Slly[m]**2
            rxy.append(numer/(math.sqrt(term1d*term2d))) #correlation coefficient

        yr = [[0.0 for m in range(5)] for j in range(len(ret))]
        Hsr = [[0.0 for m in range(5)] for j in range(len(ret))]
        for j in range(len(ret)):
            prob1 = 1.0 - 1.0/(lambdaVal*ret[j])

            if prob1 <= 0.0:
                prob1 = 1.0*10**(-7)

            yr[j][0] = -math.log(-math.log(prob1)) #FT-I
            Hsr[j][0] = alpha[0]*yr[j][0] + beta[0]

            for m in range(1, 5):
                prob2 = lambdaVal*ret[j]
                if prob2 <= 0.0:
                    prob2 = 1.0*10**(-7)

                k = k_W[m - 1] #Weibull
                yr[j][m] = math.log(prob2)**(1.0/k)
                Hsr[j][m] = alpha[m]*yr[j][m] + beta[m]
        # end for loop

        rtp = []
        for j in range(N):
            rtp.append([])
            rtp[j].append(\
                1.0/((1.0 - math.exp(-math.exp(-ym[j][0])))*lambdaVal)) #FT-I

            for m in range(1, 5):
                k = k_W[m - 1] #Weibull
                rtp[j].append(math.exp(ym[j][m]**k)/lambdaVal)
        # end for loop

        standev = np.std(self.Hs, ddof=1) #standard deviation

        #Calculate confidence intervals
        sigr = [[0.0 for m in range(5)] for j in range(len(ret))]
        for m in range(5):
            coeff = a1[m]*math.exp(a2[m]*N**(-1.3) + kappa[m]*math.sqrt(-math.log(nu)))

            for j in range(len(ret)):
                signr = (1.0/math.sqrt(N))*(1.0 + coeff*(yr[j][m] - c[m] + epsi[m]*math.log(nu))**2)**(0.5)
                sigr[j][m] = signr*standev
        # end for loop

        if self.option == 1: #80%
            bounds = [[j*1.28 for j in i] for i in sigr]
            conf = 80
        elif self.option == 2: #85%
            bounds = [[j*1.44 for j in i] for i in sigr]
            conf = 85
        elif self.option == 3: #90%
            bounds = [[j*1.65 for j in i] for i in sigr]
            conf = 90
        elif self.option == 4: #95%
            bounds = [[j*1.96 for j in i] for i in sigr]
            conf = 95
        elif self.option == 5: #99%
            bounds = [[j*2.58 for j in i] for i in sigr]
            conf = 99

        lowbound = []
        highbound = []
        for j in range(len(Hsr)):
            lowbound.append([])
            highbound.append([])

            for m in range(5):
                lowbound[j].append(Hsr[j][m] - bounds[j][m])
                highbound[j].append(Hsr[j][m] + bounds[j][m])

        #Calculated percent chance for significant wave height
        #equaling or exceeding the return period
        pe = [[0.0 for j in range(7)] for i in range(7)]
        for i in range(7):
            for j in range(7):
                pe[j][i] = 100.0*(1.0 - (1.0 - 1.0/pret[j])**plen[i])

        xxr = []
        for i in range(N):
            xxr.append([])

            for m in range(5):
                xxr[i].append(ym[i][m]*alpha[m] + beta[m])

        printpe = [[j for j in i] for i in pe]
        printside = [2, 5, 10, 25, 50, 100]
        printpe[0][0] = 999
        for i in range(1, len(printpe)):
            printpe[i][0] = printside[i - 1]
        for j in range(1, len(printpe[0])):
            printpe[0][j] = printside[j - 1]

        indexList = [ret.index(2.0), ret.index(5.0), ret.index(10.0),\
            ret.index(25.0), ret.index(50.0), ret.index(100.0)]

        print("N = %-i NU = %-3.2f NT = %-i K = %-3.2f lambda = %-3.2f\n" %\
            (N, nu, Nt, K, lambdaVal))
        print("\t\tFT-I\tW (k=0.75)  W (k=1.00)  W (k=1.40)  W (k=2.00)")
        print("Corr. coeff.\t%-12.4f%-12.4f%-12.4f%-12.4f%-12.4f" %\
            (rxy[0], rxy[1], rxy[2], rxy[3], rxy[4]))
        print("Sq. of Resid.\t%-12.4f%-12.4f%-12.4f%-12.4f%-12.4f\n" %\
            (sumresid[0], sumresid[1], sumresid[2], sumresid[3], sumresid[4]))

        print("Return period\tHs [%s]   Hs [%s]   Hs [%s]   Hs [%s]   Hs [%s]" %\
            (self.labelUnitDist, self.labelUnitDist, self.labelUnitDist, self.labelUnitDist, self.labelUnitDist))
        for m in range(6):
            print("%-i\t\t%-10.2f%-10.2f%-10.2f%-10.2f%-10.2f" %\
                (ret[indexList[m]], Hsr[indexList[m]][0], Hsr[indexList[m]][1],\
                Hsr[indexList[m]][2], Hsr[indexList[m]][3], Hsr[indexList[m]][4]))

        val = max(rxy)
        C = rxy.index(val)
        if C == 0:
            print("\nBest fit distribution function: Fisher-Tippett Type I\n")
        elif C == 1:
            print("\nBest fit distribution function: Weibull Distribution (k=0.75)\n")
        elif C == 2:
            print("\nBest fit distribution function: Weibull Distribution (k=1.00)\n")
        elif C == 3:
            print("\nBest fit distribution function: Weibull Distribution (k=1.40)\n")
        elif C == 4:
            print("\nBest fit distribution function: Weibull Distribution (k=2.00)\n")

        print("%i%% Confidence Interval, (Lower Bound - Upper Bound)\nReturn period" % conf)
        print("\tFT-I          W (k=0.75)    W (k=1.00)    W (k=1.40)    W (k=2.00)")

        for m in range(6):
            print("%-i\t%-3.1f - %-3.1f   %-3.1f - %-3.1f   %-3.1f - %-3.1f   %-3.1f - %-3.1f   %-3.1f - %-3.1f" %\
                (ret[indexList[m]], lowbound[indexList[m]][0], highbound[indexList[m]][0],\
                lowbound[indexList[m]][1], highbound[indexList[m]][1],
                lowbound[indexList[m]][2], highbound[indexList[m]][2],
                lowbound[indexList[m]][3], highbound[indexList[m]][3],
                lowbound[indexList[m]][4], highbound[indexList[m]][4]))

        print("\nPercent Chance for Significant Height Equaling or Exceeding Return Period Hs")
        for i in range(len(printpe)):
            printLine = ""

            for j in range(len(printpe[0])):
                if i == 0 and j == 0:
                    printLine += "      "
                elif i == 0:
                    printLine += "%6d" % printpe[i][j]
                else:
                    printLine += "%6d" % round(printpe[i][j])

            print(printLine)
        # end for loop

        dataDict["Sx"] = Sx
        dataDict["standev"] = standev
        dataDict["alpha"] = alpha
        dataDict["beta"] = beta
        dataDict["rxy"] = rxy
        dataDict["sumresid"] = sumresid
        dataDict["yact"] = yact
        dataDict["ym"] = ym
        dataDict["xxr"] = xxr
        dataDict["conf"] = conf
        dataDict["Hsr"] = Hsr
        dataDict["sigr"] = sigr
        dataDict["printside"] = printside
        dataDict["indexList"] = indexList
        
        self.fileOutputWriteMain(dataDict)

        self.plotDict = {"ret": ret, "Hsr": Hsr, "rtp": rtp,\
            "highbound": highbound, "lowbound": lowbound}
    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        distList = ["FISHER-TIPPETT TYPE (FT-I) DISTRIBUTION",\
            "WEIBULL DISTRIBUTION k = 0.75",\
            "WEIBULL DISTRIBUTION k = 1.00",\
            "WEIBULL DISTRIBUTION k = 1.40",\
            "WEIBULL DISTRIBUTION k = 2.00"]

        self.fileRef.write("EXTREMAL SIGNIFICANT WAVE HEIGHT ANALYSIS\n")
        self.fileRef.write("DELFT Data\n\n")

        self.fileRef.write("N = %d STORMS\n" % dataDict["N"])
        self.fileRef.write("NT = %d STORMS\n" % dataDict["Nt"])
        self.fileRef.write("NU = %-6.2f\n" % dataDict["nu"])
        self.fileRef.write("K = %-6.2f YEARS\n" % dataDict["K"])
        self.fileRef.write("LAMBDA = %-6.2f STORMS PER YEAR\n" % dataDict["lambdaVal"])
        
        if self.errorMsg != None:
            self.fileRef.write("\n%s" % self.errorMsg)
        else:
            self.fileRef.write("MEAN OF SAMPLE DATA = %-6.3f FEET\n" % (dataDict["Sx"]/dataDict["N"]))
            self.fileRef.write("STANDARD DEVIATION OF SAMPLE = %-6.3f FEET\n" % dataDict["standev"])
    
            for distIndex in range(len(distList)):
                self.fileRef.write("\n%s\n" % distList[distIndex])
                self.fileRef.write("F(Hs) = EXP(-EXP(-(Hs-B)/A)) - Equation 1\n")
                self.fileRef.write("A = %-6.3f %s\n" % (dataDict["alpha"][distIndex], self.labelUnitDist))
                self.fileRef.write("B = %-6.3f %s\n" % (dataDict["beta"][distIndex], self.labelUnitDist))
                self.fileRef.write("CORRELATION = %-6.4f\n" % dataDict["rxy"][distIndex])
                self.fileRef.write("SUM SQUARE OF RESIDUALS = %-6.4f %s\n" %\
                    (dataDict["sumresid"][distIndex], self.labelUnitDist))
    
                self.fileRef.write("\nRANK\tHsm\tF(Hs<=Hsm)\tYm\tA*Ym+B\t\tHsm-(A*Ym+B)\n")
                self.fileRef.write("\t(Ft)\tEq. 3\t\tEq. 5\tEq. 4 (%s)\t(%s)\n" %\
                    (self.labelUnitDist, self.labelUnitDist))
    
                for loopIndex in range(len(self.Hs)):
                    self.fileRef.write("%d\t%-6.2f\t%-6.4f\t\t%-6.3f\t%-6.4f\t\t%-6.4f\n" %\
                        ((loopIndex + 1),\
                        self.Hs[loopIndex],\
                        dataDict["yact"][loopIndex][distIndex],\
                        dataDict["ym"][loopIndex][distIndex],\
                        dataDict["xxr"][loopIndex][distIndex],\
                        (self.Hs[loopIndex] - dataDict["xxr"][loopIndex][distIndex])))
    
                self.fileRef.write("\nRETURN PERIOD TABLE with %d%% CONFIDENCE INTERVAL\n" % dataDict["conf"])
    
                self.fileRef.write("\nRETURN\tHs\tSIGR\tHs-1.28*SIGR\tHs+1.28*SIGR\n")
                self.fileRef.write("PERIOD\t(%s)\t(%s)\t(%s)\t\t(%s)\n" %\
                    (self.labelUnitDist, self.labelUnitDist, self.labelUnitDist, self.labelUnitDist))
                self.fileRef.write("(Yr)\tEq. 6\tEq. 10\n")
                
                for loopIndex in range(len(dataDict["indexList"])):
                    self.fileRef.write("%-6.2f\t%-6.2f\t%-6.2f\t%-6.2f\t\t%-6.2f\n" %\
                        (dataDict["printside"][loopIndex],\
                        dataDict["Hsr"][dataDict["indexList"][loopIndex]][distIndex],\
                        dataDict["sigr"][dataDict["indexList"][loopIndex]][distIndex],\
                        dataDict["Hsr"][dataDict["indexList"][loopIndex]][distIndex] - 1.28*dataDict["sigr"][dataDict["indexList"][loopIndex]][distIndex],\
                        dataDict["Hsr"][dataDict["indexList"][loopIndex]][distIndex] + 1.28*dataDict["sigr"][dataDict["indexList"][loopIndex]][distIndex]))
        # end if
        
        exportData = [dataDict["N"], dataDict["Nt"], dataDict["nu"],\
            dataDict["K"], dataDict["lambdaVal"]]
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["Sx"]/dataDict["N"],\
                dataDict["standev"]]
            for distIndex in range(len(distList)):
                exportData = exportData + [dataDict["alpha"][distIndex],\
                    dataDict["beta"][distIndex], dataDict["rxy"][distIndex],\
                    dataDict["sumresid"][distIndex]]
                
                for loopIndex in range(len(self.Hs)):
                    exportData = exportData + [self.Hs[loopIndex],\
                        dataDict["yact"][loopIndex][distIndex],\
                        dataDict["ym"][loopIndex][distIndex],\
                        dataDict["xxr"][loopIndex][distIndex],\
                        (self.Hs[loopIndex] - dataDict["xxr"][loopIndex][distIndex])]
                
                for loopIndex in range(len(dataDict["indexList"])):
                    exportData = exportData + [dataDict["printside"][loopIndex],\
                        dataDict["Hsr"][dataDict["indexList"][loopIndex]][distIndex],\
                        dataDict["sigr"][dataDict["indexList"][loopIndex]][distIndex],\
                        dataDict["Hsr"][dataDict["indexList"][loopIndex]][distIndex] -\
                            1.28*dataDict["sigr"][dataDict["indexList"][loopIndex]][distIndex],\
                        dataDict["Hsr"][dataDict["indexList"][loopIndex]][distIndex] +\
                            1.28*dataDict["sigr"][dataDict["indexList"][loopIndex]][distIndex]]
        # end if
        self.exporter.writeData(exportData)
    # end fileOutputWrite

    def hasPlot(self):
        return True

    def performPlot(self):
        for i in range(5):
            plt.figure((i + 1), figsize = self.plotConfigDict["figSize"],\
                dpi = self.plotConfigDict["dpi"])

            plotDataHsr = [j[i] for j in self.plotDict["Hsr"]]
            plotDataRtp = [j[i] for j in self.plotDict["rtp"]]
            plotDataHighbound = [j[i] for j in self.plotDict["highbound"]]
            plotDataLowbound = [j[i] for j in self.plotDict["lowbound"]]
            plt.semilogx(\
                self.plotDict["ret"], plotDataHsr, ":",\
                plotDataRtp, self.Hs,\
                self.plotDict["ret"], plotDataHighbound, "r--",\
                self.plotDict["ret"], plotDataLowbound, "r--")

            if i == 0:
                plotTitle = "FT-I"
                plotLegend = "FT-I Distribution"
            elif i == 1:
                plotTitle = "Weibull (k=0.75)"
                plotLegend = "Weibull (k=0.75)"
            elif i == 2:
                plotTitle = "Weibull (k=1.00)"
                plotLegend = "Weibull (k=1.00)"
            elif i == 3:
                plotTitle = "Weibull (k=1.40)"
                plotLegend = "Weibull (k=1.40)"
            elif i == 4:
                plotTitle = "Weibull (k=2.00)"
                plotLegend = "Weibull (k=2.00)"

            plt.title(plotTitle,\
                fontsize = self.plotConfigDict["titleFontSize"])
            plt.xlabel("Return period [yr]",\
                fontsize = self.plotConfigDict["axisLabelFontSize"])
            plt.ylabel(r"H$_s$",\
                fontsize = self.plotConfigDict["axisLabelFontSize"])
            plt.legend([plotLegend, "Data", "Confidence Bounds",\
                "Location", "SouthEast"])
        # end for loop

        plt.show()
    # end performPlot

    # Override to prevent creating additional output file
    def fileOutputPlotInit(self):
        pass
Ejemplo n.º 17
0
class RunupOvertopping(BaseDriver):
    def __init__(self, H = None, T = None, cotphi = None,\
        ds = None, cottheta = None, hs = None):
        self.exporter = EXPORTER("output/exportRunupOvertopping")

        if H != None:
            self.isSingleCase = True
            self.defaultValueH = H
        if T != None:
            self.isSingleCase = True
            self.defaultValueT = T
        if cotphi != None:
            self.isSingleCase = True
            self.defaultValue_cotphi = cotphi
        if ds != None:
            self.isSingleCase = True
            self.defaultValue_ds = ds
        if cottheta != None:
            self.isSingleCase = True
            self.defaultValue_cottheta = cottheta
        if hs != None:
            self.isSingleCase = True
            self.defaultValue_hs = hs

        self.conversionKnots2mph = 1.15077945  #1 knots = 1.15077945 mph

        super(RunupOvertopping, self).__init__()

        self.exporter.close()

    # end __init__

    def userInput(self):
        print('%s \n\n' % 'Calculation and slope type options: ')
        print('%s \n' % 'Monochromatic Waves')
        print('%s \n' %
              '[1] Rough <------------- Runup -------------> [2] Smooth')
        print('%s \n' %
              '[3] Rough <----------- Overtopping ---------> [4] Smooth')
        print('%s \n\n' %
              '[5] Rough <----- Runup and Overtopping -----> [6] Smooth')
        print('%s \n' % 'Irregular Waves')
        print('%s \n\n' %
              '[7] Rough <----- Runup and Overtopping -----> [8] Smooth')

        self.option = USER_INPUT.FINITE_CHOICE("Select option (1 - 8): ",\
            ["1", "2", "3", "4", "5", "6", "7", "8"])
        self.option = int(self.option)

        self.has_rough_slope = self.option == 1 or\
            self.option == 5 or self.option == 7 or self.option == 8
        self.has_overtopping = self.option > 2
        self.has_runup = self.option != 3 and self.option != 4

        if self.option == 3:
            R_default = 15.0
        elif self.option == 4:
            R_default = 20.0
        else:
            R_default = 0.0

        super(RunupOvertopping, self).userInput()

        if self.option != 2:
            self.roughSlopeCoeffDict = USER_INPUT.ROUGH_SLOPE_COEFFICIENTS(\
                self.has_rough_slope, self.has_overtopping, self.has_runup,\
                {"numCases": len(self.dataOutputList), "R_default": R_default})
        else:
            self.roughSlopeCoeffDict = {}

    # end userInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValueH"):
            self.inputList.append(BaseField("H: incident wave height (Hs for irregular waves) (%s)" %\
                (self.labelUnitDist), 0.1, 100.0))
        if not hasattr(self, "defaultValueT"):
            self.inputList.append(
                BaseField("T: wave period (Tp for irregular waves) (s)", 1.0,
                          1000.0))
        if not hasattr(self, "defaultValue_cotphi"):
            self.inputList.append(
                BaseField("cotphi: cotan of nearshore slope", 5.0, 10000.0))
        if not hasattr(self, "defaultValue_ds"):
            self.inputList.append(BaseField("ds: water depth at structure toe (%s)" %\
                self.labelUnitDist, 0.1, 200.0))
        if not hasattr(self, "defaultValue_cottheta"):
            self.inputList.append(BaseField("cottheta: cotan of structure slope (0.0 for vertical walls)",\
                0.0, 30.0))
        if not hasattr(self, "defaultValue_hs"):
            self.inputList.append(BaseField("hs: structure height above toe (%s)" % self.labelUnitDist,\
                0.0, 200.0))

    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(defaultFilename="runup_overtopping")

    def getCalcValues(self, caseInputList, caseIndex):
        currIndex = 0

        if hasattr(self, "defaultValueH"):
            H = self.defaultValueH
        else:
            H = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValueT"):
            T = self.defaultValueT
        else:
            T = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_cotphi"):
            cotphi = self.defaultValue_cotphi
        else:
            cotphi = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_ds"):
            ds = self.defaultValue_ds
        else:
            ds = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_cottheta"):
            cottheta = self.defaultValue_cottheta
        else:
            cottheta = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_hs"):
            hs = self.defaultValue_hs
        else:
            hs = caseInputList[currIndex]

        coeffDict = {}
        for coeffName in ["a", "b", "alpha", "Qstar0", "U", "R"]:
            if coeffName in self.roughSlopeCoeffDict:
                coeffDict[coeffName] = self.roughSlopeCoeffDict[coeffName]
            elif (coeffName + "List") in self.roughSlopeCoeffDict:
                coeffDict[coeffName] =\
                    self.roughSlopeCoeffDict[coeffName + "List"][caseIndex]
            else:
                coeffDict[coeffName] = None

        return H, T, cotphi, ds, cottheta, hs,\
            coeffDict["a"],\
            coeffDict["b"],\
            coeffDict["alpha"],\
            coeffDict["Qstar0"],\
            coeffDict["U"],\
            coeffDict["R"]

    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex=0):
        H, T, cotphi, ds, cottheta, hs, a, b, alpha, Qstar0, U, R =\
            self.getCalcValues(caseInputList, caseIndex)
        dataDict = {"H": H, "T": T, "cotphi": cotphi, "ds": ds,\
            "cottheta": cottheta, "hs": hs, "a": a, "b": b,\
            "alpha": alpha, "Qstar0": Qstar0, "U": U, "R": R}

        m = 1.0 / cotphi

        if not (ds < hs):
            self.errorMsg = "Error: Method does not apply to submerged structures."

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        Hbs = ERRWAVBRK2(T, m, ds)
        if not (H < Hbs):
            self.errorMsg = "Error: Wave broken at structure (Hbs = %6.2f %s)" %\
                (Hbs, self.labelUnitDist)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        c, c0, cg, cg0, k, L, L0, reldep = LWTGEN(ds, T, self.g)

        steep, maxstp = ERRSTP(H, ds, L)
        if not (steep < maxstp):
            self.errorMsg = "Error: Input wave unstable (Max: %0.4f. [H/L] = %0.4f" %\
                (maxstp, steep)

            print(self.errorMsg)
            self.fileOutputWriteMain(dataDict, caseIndex)
            return

        alpha0, H0 = LWTDWS(0.0, c, cg, c0, H)

        relht0 = ds / H0
        steep0 = H0 / (self.g * T**2)

        if np.isclose(cottheta, 0):
            if not (self.option != 1):
                self.errorMsg = "Error: Vertical wall cannot have rough slope."

                print(self.errorMsg)
                self.fileOutputWriteMain(dataDict, caseIndex)
                return

            theta = 0.5 * math.pi
            ssp = 1000
        else:
            theta = math.atan(1.0 / cottheta)
            ssp = (1.0 / cottheta) / math.sqrt(H / L0)
        # end if

        print("Deepwater")
        print("\tWave height, Hs0\t\t%-6.3f %s" % (H0, self.labelUnitDist))
        print("\tRelative height, ds/H0\t\t%-6.3f" % relht0)
        print("\tWave steepness, Hs0/(gT^2)\t%-6.6f" % steep0)

        freeb = hs - ds

        dataDict.update({"H0": H0, "relht0": relht0, "steep0": steep0})

        if self.option == 1:
            R = RUNUPR(H, ssp, a, b)
        elif self.option == 2:
            R = RUNUPS(H, L, ds, theta, ssp)
        elif self.option == 3:
            Q = QOVERT(H0, freeb, R, Qstar0, alpha, theta, U, self.g)
        elif self.option == 4:
            Q = QOVERT(H0, freeb, R, Qstar0, alpha, theta, U, self.g)
        elif self.option == 5:
            R = RUNUPR(H, ssp, a, b)
            Q = QOVERT(H0, freeb, R, Qstar0, alpha, theta, U, self.g)
        elif self.option == 6:
            R = RUNUPS(H, L, ds, theta, ssp)
            Q = QOVERT(H0, freeb, R, Qstar0, alpha, theta, U, self.g)
        elif self.option == 7:
            R = RUNUPR(H, ssp, a, b)
            Q = QOVERT_IRR(H0, freeb, R, Qstar0, alpha, theta, U, self.g)
        elif self.option == 8:
            R = RUNUPS(H, L, ds, theta, ssp)
            Q = QOVERT_IRR(H0, freeb, R, Qstar0, alpha, theta, U, self.g)

        if self.option == 1 or self.option == 2 or\
            self.option == 5 or self.option == 6 or\
            self.option == 7 or self.option == 8:
            print("Runup\t\t\t\t\t%-6.3f %s" % (R, self.labelUnitDist))
        if self.option == 3 or self.option == 4 or\
            self.option == 5 or self.option == 6 or\
            self.option == 7 or self.option == 8:
            print("Overtopping rate per unit width\t\t%-6.3f %s^3/sec-%s" %\
                (Q, self.labelUnitDist, self.labelUnitDist))
            dataDict["Q"] = Q

        dataDict["R"] = R
        self.fileOutputWriteMain(dataDict, caseIndex)

    # end performCalculations

    def fileOutputWriteData(self, dataDict):
        self.fileRef.write("Input\n")
        self.fileRef.write("H\t\t%6.2f %s\n" %\
            (dataDict["H"], self.labelUnitDist))
        self.fileRef.write("T\t\t%6.2f s\n" % dataDict["T"])
        self.fileRef.write("cotphi\t\t%6.2f\n" % dataDict["cotphi"])
        self.fileRef.write("ds\t\t%6.2f %s\n" %\
            (dataDict["ds"], self.labelUnitDist))
        self.fileRef.write("cottheta\t%6.2f\n" % dataDict["cottheta"])
        self.fileRef.write("hs\t\t%6.2f %s\n" %\
            (dataDict["hs"], self.labelUnitDist))

        if "a" in dataDict and dataDict["a"] != None:
            self.fileRef.write("a\t\t%6.4f\n" % dataDict["a"])
        if "b" in dataDict and dataDict["b"] != None:
            self.fileRef.write("b\t\t%6.4f\n" % dataDict["b"])
        if "alpha" in dataDict and dataDict["alpha"] != None:
            self.fileRef.write("alpha\t\t%6.4f\n" % dataDict["alpha"])
        if "Qstar0" in dataDict and dataDict["Qstar0"] != None:
            self.fileRef.write("Qstar0\t\t%6.4f\n" % dataDict["Qstar0"])
        if "U" in dataDict and dataDict["U"] != None:
            self.fileRef.write("U\t\t%6.4f kn\n" %\
                (dataDict["U"]/self.conversionKnots2mph))
        if "R" in dataDict and dataDict["R"] != None and not self.has_runup:
            self.fileRef.write("R\t\t%6.4f %s\n" %\
                (dataDict["R"], self.labelUnitDist))

        if self.errorMsg != None:
            self.fileRef.write("\n%s\n" % self.errorMsg)
        else:
            self.fileRef.write("\nDeepwater\n")
            self.fileRef.write("\tWave height, Hs0\t\t%-6.3f %s\n" %\
                (dataDict["H0"], self.labelUnitDist))
            self.fileRef.write("\tRelative height, ds/H0\t\t%-6.3f\n" %\
                dataDict["relht0"])
            self.fileRef.write("\tWave steepness, Hs0/(gT^2)\t%-6.6f\n" %\
                dataDict["steep0"])

            if self.option == 1 or self.option == 2 or\
                self.option == 5 or self.option == 6 or\
                self.option == 7 or self.option == 8:
                self.fileRef.write("Runup\t\t\t\t\t%-6.3f %s\n" %\
                    (dataDict["R"], self.labelUnitDist))
            if self.option == 3 or self.option == 4 or\
                self.option == 5 or self.option == 6 or\
                self.option == 7 or self.option == 8:
                self.fileRef.write("Overtopping rate per unit width\t\t%-6.3f %s^3/sec-%s\n" %\
                    (dataDict["Q"], self.labelUnitDist, self.labelUnitDist))

        exportData = [dataDict["H"], dataDict["T"], dataDict["cotphi"],\
            dataDict["ds"], dataDict["cottheta"], dataDict["hs"]]
        if "a" in dataDict and dataDict["a"] != None:
            exportData.append(dataDict["a"])
        if "b" in dataDict and dataDict["b"] != None:
            exportData.append(dataDict["b"])
        if "alpha" in dataDict and dataDict["alpha"] != None:
            exportData.append(dataDict["alpha"])
        if "Qstar0" in dataDict and dataDict["Qstar0"] != None:
            exportData.append(dataDict["Qstar0"])
        if "U" in dataDict and dataDict["U"] != None:
            exportData.append(dataDict["U"] / self.conversionKnots2mph)
        if "R" in dataDict and dataDict["R"] != None and not self.has_runup:
            exportData.append(dataDict["R"])
        if self.errorMsg != None:
            exportData.append(self.errorMsg)
        else:
            exportData = exportData + [dataDict["H0"], dataDict["relht0"],\
                dataDict["steep0"]]
            if self.option == 1 or self.option == 2 or\
                self.option == 5 or self.option == 6 or\
                self.option == 7 or self.option == 8:
                exportData.append(dataDict["R"])
            if self.option == 3 or self.option == 4 or\
                self.option == 5 or self.option == 6 or\
                self.option == 7 or self.option == 8:
                exportData.append(dataDict["Q"])
        self.exporter.writeData(exportData)
Ejemplo n.º 18
0
class TideGeneration(BaseDriver):
    def __init__(self, year = None, mon = None, day = None, hr = None,\
        tlhrs = None, delt = None, gauge0 = None, glong = None):
        self.exporter = EXPORTER("output/exportTideGeneration")
        
        self.isSingleCase = True

        if year != None:
            self.defaultValue_year = year
        if mon != None:
            self.defaultValuemon = mon
        if day != None:
            self.defaultValue_day = day
        if hr != None:
            self.defaultValue_hr = hr
        if tlhrs != None:
            self.defaultValuetlhrs = tlhrs
        if delt != None:
            self.defaultValue_delt = delt
        if gauge0 != None:
            self.defaultValue_gauge0 = gauge0
        if glong != None:
            self.defaultValue_glong = glong

        super(TideGeneration, self).__init__()
        
        self.exporter.close()
    # end __init__

    def userInput(self):
        self.defineInputDataList()

        if len(self.inputList) > 0:
            self.manualOrFile = USER_INPUT.FINITE_CHOICE(\
                "Enter data manually or load from file? (M or F): ",\
                ["M", "m", "F", "f"])

            if self.manualOrFile == "F" or self.manualOrFile == "f":
                accepted = False

                while not accepted:
                    filenameData = USER_INPUT.FILE_NAME()

                    fileRef = open(filenameData)

                    fileDataTemp = fileRef.read().split("\n")
                    fileData = []
                    for i in fileDataTemp:
                        if len(i) > 0:
                            fileData.append(float(i))

                    if len(fileData) >= len(self.inputList):
                        accepted = True

                        for i in range(len(fileData)):
                            if i < len(self.inputList):
                                inputIndex = i
                            else:
                                inputIndex = len(self.inputList) - 1

                            if fileData[i] < self.inputList[inputIndex].min or\
                                fileData[i] > self.inputList[inputIndex].max:
                                accepted = False
                                print("Value #%d out of range. Please check your value and try again." %\
                                    (i + 1))
                        # end for loop

                        if accepted == True:
                            glongList = []
                            if not hasattr(self, "defaultValue_glong"):
                                mainInputListLen = len(self.inputList) - 1
                            else:
                                mainInputListLen = len(self.inputList)

                            self.dataOutputList = []

                            for i in range(len(fileData)):
                                # check if we need to add glong values
                                # and are at that point
                                if not hasattr(self, "defaultValue_glong") and\
                                    i >= len(self.inputList) - 1:
                                    glongList.append(fileData[i])
                                # else, add normally
                                else:
                                    self.dataOutputList.append(fileData[i])
                            # end for loop
                                    
                            self.dataOutputList.append(glongList)
                        # end if
                    else:
                        print("%d values are required. Please check your file and try again." %\
                            len(self.inputList))
                # end while loop
            # end if
        # end if

        super(TideGeneration, self).userInput()

        accepted = False
        while not accepted:
            print("\nConstituent Data Loading from file")
            filenameTideConstituents = USER_INPUT.FILE_NAME()
            fileRef = open(filenameTideConstituents)

            fileData = fileRef.read()
            fileRef.close()

            fileData = fileData.split("\n")

            self.cst = []
            self.amp = []
            self.ep = []
            for i in fileData:
                lineData = i.split("\t")

                if len(lineData) >= 1:
                    self.cst.append(lineData[0])
                if len(lineData) >= 2:
                    self.amp.append(float(lineData[1]))
                if len(lineData) >= 3:
                    self.ep.append(float(lineData[2]))
            # end for loop

            if len(self.amp) == 0 or len(self.ep) == 0:
                print("ERROR: Constituent Data Incomplete.")
                print("Please correct the input file and try again.")
            else:
                accepted = True
        # end while loop
    # end userInput

    def getSingleCaseInput(self):
        if not hasattr(self, "manualOrFile") or\
            (self.manualOrFile == "M" or self.manualOrFile == "m"):
            super(TideGeneration, self).getSingleCaseInput()
    # end getSingleCaseInput

    def defineInputDataList(self):
        self.inputList = []

        if not hasattr(self, "defaultValue_year"):
            self.inputList.append(BaseField(\
                "year: year simulation starts (YYYY)", 1900, 2050))
        if not hasattr(self, "defaultValuemon"):
            self.inputList.append(BaseField(\
                "mon: month simulation starts (MM)", 1, 12))
        if not hasattr(self, "defaultValue_day"):
            self.inputList.append(BaseField(\
                "day: day simulation starts (DD)", 1, 31))
        if not hasattr(self, "defaultValue_hr"):
            self.inputList.append(BaseField(\
                "hr: hour simulation starts (HH.H)", 0, 24))
        if not hasattr(self, "defaultValuetlhrs"):
            self.inputList.append(BaseField(\
                "tlhrs: length of record (HH.H)", 0, 744))
        if not hasattr(self, "defaultValue_delt"):
            self.inputList.append(BaseField(\
                "delt: output time interval (min)" , 1, 60))
        if not hasattr(self, "defaultValue_gauge0"):
            self.inputList.append(BaseField(\
                "gauge0: mean water level height above datum", -100.0, 100.0))
        if not hasattr(self, "defaultValue_glong"):
            self.inputList.append(BaseField(\
                "glong: gauge longitude (deg)", -180, 180))
    # end defineInputDataList

    def fileOutputRequestInit(self):
        self.fileOutputRequestMain(\
            defaultFilename = "tide_generation",\
            requestDesc = True)

    def getCalcValues(self, caseInputList):
        currIndex = 0

        if hasattr(self, "defaultValue_year"):
            year = self.defaultValue_year
        else:
            year = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValuemon"):
            mon = self.defaultValuemon
        else:
            mon = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_day"):
            day = self.defaultValue_day
        else:
            day = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_hr"):
            hr = self.defaultValue_hr
        else:
            hr = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValuetlhrs"):
            tlhrs = self.defaultValuetlhrs
        else:
            tlhrs = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_delt"):
            delt = self.defaultValue_delt
        else:
            delt = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_gauge0"):
            gauge0 = self.defaultValue_gauge0
        else:
            gauge0 = caseInputList[currIndex]
            currIndex = currIndex + 1

        if hasattr(self, "defaultValue_glong"):
            glong = self.defaultValue_glong
        else:
            if isinstance(caseInputList[currIndex], list):
                glong = caseInputList[currIndex]
            else:
                glong = [caseInputList[currIndex]]

        return int(year), int(mon), int(day), hr, tlhrs, delt, gauge0, glong
    # end getCalcValues

    def performCalculations(self, caseInputList, caseIndex = 0):
        year, mon, day, hr, tlhrs, delt, gauge0, glong = self.getCalcValues(caseInputList)

        delthr = delt/60.0

        nogauge = len(glong)

        acst = [28.9841042,30.0,28.4397295,15.0410686,57.9682084,\
            13.9430356,86.9523127,44.0251729,60.0,57.4238337,28.5125831,\
            90.0,27.9682084,27.8953548,16.1391017,29.4556253,15.0,\
            14.4966939,15.5854433,0.5443747,0.0821373,0.0410686,\
            1.0158958,1.0980331,13.4715145,13.3986609,29.9589333,\
            30.0410667,12.8542862,14.9589314,31.0158958,43.4761563,\
            29.5284789,42.9271398,30.0821373,115.9364169,58.9841042]

        pcst = [2,2,2,1,4,1,6,3,4,4,2,6,2,2,1,2,1,1,1,0,0,0,0,0,1,1,2,2,1,1,2,3,2,3,2,8,4]
        pcst = [float(i) for i in pcst]

        ## Intialize gage-specific info relevant to harmonic constituents
        alpha, fndcst = GAGINI(\
            nogauge, year, mon, day, hr, tlhrs, glong, self.ep, acst, pcst)

        ntid = int(tlhrs/delthr) + 1

        tidelv = []
        xtim = []
        for i in range(ntid):
            xtim.append(i*delthr)
            tidelv.append(TIDELV(\
                nogauge, xtim[i], self.amp, alpha, fndcst, acst))

        ytide = [gauge0 + i for i in tidelv]

        self.plotDict = {"xtim": xtim, "ytide": ytide}
    # end performCalculations

    def hasPlot(self):
        return True

    def fileOutputPlotInit(self):
        self.fileRef = open(self.getFilePath() +\
            self.fileOutputData.filename + ".txt", "w")
    # end fileOutputPlotInit

    def performPlot(self):
        plt.figure(1, figsize = self.plotConfigDict["figSize"],\
            dpi = self.plotConfigDict["dpi"])
        plt.plot(self.plotDict["xtim"], self.plotDict["ytide"])
        plt.title("Tide Elevations [from constituents]", fontsize = self.plotConfigDict["titleFontSize"])
        plt.xlabel("Time [hr]",\
            fontsize = self.plotConfigDict["axisLabelFontSize"])
        #output same units as amplitude, datum input
        plt.ylabel("Elevation [%s]" % self.labelUnitDist,\
            fontsize = self.plotConfigDict["axisLabelFontSize"])

        plt.show()

        self.fileOutputPlotWriteData()
    # end performPlot

    def fileOutputPlotWriteData(self):
        self.fileRef.write("CONSTITUENT TIDE ELEVATION RECORD\n")
        self.fileRef.write("%s\n" % self.fileOutputData.fileDesc)
        self.fileRef.write("TIME\tELEVATION\n")

        for i in range(len(self.plotDict["xtim"])):
            self.fileRef.write("%-6.2f\t%-6.2f\n" %\
                (self.plotDict["xtim"][i], self.plotDict["ytide"][i]))
        
        exportData = []
        for i in range(len(self.plotDict["xtim"])):
            exportData = exportData + [self.plotDict["xtim"][i],\
                self.plotDict["ytide"][i]]
        self.exporter.writeData(exportData)