Esempio n. 1
0
    def test_writeLogToCSV(self):

        envSimu = self.intiSimulation()
        simpleCtl = self.initController()
        algLog = AlgorithmLog()
        while not envSimu.isFinish():
            print("\nDay Count: {}".format(envSimu.currentDayCount))

            envSimu.loadResult()
            # print(envSimu.getCurrentDayWCs())
            WCs = envSimu.getCurrentDayWCs()
            # print(WCs[0])

            predictedIrri = helper.mockControllerBySI(WCs[0], 25)

            if predictedIrri > 0:

                irriDay = envSimu.currentDayCount + 1
                # print("IrriDay: {}".format(irriDay))
                # print("Irri: {}".format(predictedIrri))
                helper.appendDotIRR('Example.Irr', irriDay, predictedIrri)
                envSimu.runOnce()

            sensor0 = 0
            sensor1 = 1
            logDict = {"dayCount": envSimu.currentDayCount,
                       "WCs": envSimu.getCurrentDayWCs(),
                       "refs": simpleCtl.get_ref(),
                       "error": simpleCtl.get_error(WCs),
                       "pidk": simpleCtl.get_k(),
                       "sensor0_depth": sensor0,
                       "sensor1_depth": sensor1,
                       "irri": predictedIrri,
                       "CC": envSimu.getCurrentDayData()[29],
                       "Biomass": envSimu.getCurrentDayData()[36]}

            algLog.log(logDict)
            envSimu.increateTimeStep()

        simulationName = "test_simulation"
        algInfo = {'sensor0': 'sensor0', 'sensor1': 'sensor1',
                   'ref0': 'ref0', 'ref1': 'ref1'}
        summary = {"yield": 0, "water": 0}
        algLog.writeLogToCSV(algInfo, summary, simulationName)
Esempio n. 2
0
    def test_log(self):

        envSimu = self.intiSimulation()
        simpleCtl = self.initController()
        algLog = AlgorithmLog()
        while not envSimu.isFinish():
            print("\nDay Count: {}".format(envSimu.currentDayCount))
            if envSimu.currentDayCount == 2:
                break
            envSimu.loadResult()
            # print(envSimu.getCurrentDayWCs())
            WCs = envSimu.getCurrentDayWCs()
            # print(WCs[0])

            predictedIrri = helper.mockControllerBySI(WCs[0], 25)

            if predictedIrri > 0:

                irriDay = envSimu.currentDayCount + 1
                # print("IrriDay: {}".format(irriDay))
                # print("Irri: {}".format(predictedIrri))
                helper.appendDotIRR('Example.Irr', irriDay, predictedIrri)
                envSimu.runOnce()

            sensor0 = 0
            sensor1 = 1
            logDict = {"dayCount": envSimu.currentDayCount,
                       "WCs": envSimu.getCurrentDayWCs(),
                       "refs": simpleCtl.get_ref(),
                       "error": simpleCtl.get_error(WCs),
                       "pidk": simpleCtl.get_k(),
                       "sensor0_depth": sensor0,
                       "sensor1_depth": sensor1,
                       "irri": predictedIrri,
                       "CC": envSimu.getCurrentDayData()[29],
                       "Biomass": envSimu.getCurrentDayData()[36]}
            algLog.log(logDict)

            envSimu.increateTimeStep()

            self.assertEqual(
                len(algLog.logLines[0].split(",")), len(algLog.getHeader()))
Esempio n. 3
0
    def test_integration(self):

        envSimu = self.intiSimulation()
        print("test_integration")

        while not envSimu.isFinish():
            print("\nDay Count: {}".format(envSimu.currentDayCount))
            envSimu.loadResult()
            print(envSimu.getCurrentDayWCs())
            WCs = envSimu.getCurrentDayWCs()
            print(WCs[0])

            predictedIrri = helper.mockControllerBySI(WCs[0], 25)

            if predictedIrri > 0:

                irriDay = envSimu.currentDayCount + 1
                print("IrriDay: {}".format(irriDay))
                print("Irri: {}".format(predictedIrri))
                helper.appendDotIRR('Example.Irr', irriDay, predictedIrri)
                envSimu.runOnce()

            envSimu.increateTimeStep()
Esempio n. 4
0
def run_simulation(dynamicRef, mp, simulationName):

    project = 'TOMATO2'
    envSimu = EnvSimulator(project)
    envSimu.initRun()

    cfgHolder = ConfigHolder()
    config = cfgHolder.get()

    #
    # Initialize Controller
    #
    simpleCtl = initilzieController(config, dynamicRef)
    refsArray = simpleCtl.get_ref()
    sensor0 = simpleCtl.get_controDepth()
    dynamicRef = refsArray[sensor0]
    #
    # initilize algorithm log
    #
    al = AlgorithmLog()

    #
    # simulation main loop the whole season
    #
    while not envSimu.isFinish():

        print("\nDay Count: {}".format(envSimu.currentDayCount))

        envSimu.loadResult()

        # print("WCs:")
        # print(envSimu.getCurrentDayWCs())
        WCs = envSimu.getCurrentDayWCs()

        ##
        #    Methodology Part:
        #    If moisture condition triggers irrigation event, controller to generate irrigation amount
        ###

        ##
        # Find floating EWC( Efficient Wetting Zone )
        ##
        halfRootDepth = envSimu.getCurrentRootDepth() * mp
        compartment_boundary_list = config['compartment_boundary_list']
        closestCompartment = helper.calEWZbyCompartment(
            compartment_boundary_list, halfRootDepth)
        sensor0 = int(closestCompartment * 10 - 1)

        # print("moving sensor0: {}".format(sensor0))
        simpleCtl.set_controlDepth(sensor0)

        ##
        # *self-adapt with sensor0 and sensor1
        ##
        sensor1 = 0
        #
        # update ref0
        #
        # if WCs[sensor1] > 20 and refsArray[sensor0] > 28:
        #     dynamicRef = dynamicRef - 1
        refsArray[sensor0] = dynamicRef
        simpleCtl.set_ref(refsArray)
        # Display adaptive dynamicRef of sensor0
        print("sensor0 Ref: {}".format(dynamicRef))

        # # notate current sensor0 and sensor1 in soil layer
        # print("WCs:")
        # strWCs = list(map(str, envSimu.getCurrentDayWCs()))
        # strWCs[sensor0] = "*" + strWCs[sensor0]
        # # strWCs[sensor1] = "$" + strWCs[sensor1]
        # print(strWCs)

        # print("Refs:")
        # strRefsArray = list(map(str, simpleCtl.get_ref()))
        # strRefsArray[sensor0] = "*" + strRefsArray[sensor0]
        # # strRefsArray[sensor1] = "$" + strRefsArray[sensor1]
        # print(strRefsArray)

        # print("Error:")
        # strErrors = list(map(str, simpleCtl.get_error(WCs)))
        # strErrors[sensor0] = "*" + strErrors[sensor0]
        # # strErrors[sensor1] = "$" + strErrors[sensor1]
        # print(strErrors)

        ##
        # -- ET-base Irrigation --
        ##
        # ET_k = 1.15
        # predictedIrri = helper.ETbasedIrrigation(ET, ET_k)

        ##
        # -- MI-controller --: shallow point = 0.05m, 0.15m, 0.25m(wc1, wc2, wc3)
        ##
        # print("error:")
        # print(simpleCtl.get_error(WCs))
        predictedIrri = simpleCtl.get_output(WCs)
        controllerStatus = simpleCtl.get_status(WCs)

        logIrri = 0
        if predictedIrri > 0:
            logIrri = predictedIrri
            # irri Day is  currentDatCount add one due to we use
            # today's condition to decide tomorrow's irrigation amount
            irriDay = envSimu.currentDayCount + 1
            # print("IrriDay: {}".format(irriDay))
            # print("To Irrigate: {}".format(predictedIrri))
            helper.appendDotIRR('Example.Irr', irriDay, predictedIrri)
            envSimu.runOnce()

        logDict = {"dayCount": envSimu.currentDayCount + 1,
                   "WCs": envSimu.getCurrentDayWCs(),
                   "refs": simpleCtl.get_ref(),
                   "error": simpleCtl.get_error(WCs),
                   "pidk": simpleCtl.get_k(),
                   "sensor0_depth": sensor0,
                   "sensor1_depth": sensor1,
                   "irri": logIrri,
                   "CC": envSimu.getCurrentDayData()[29],
                   "Biomass": envSimu.getCurrentDayData()[36]}

        al.log(logDict)
        envSimu.increateTimeStep()

    # End the while loop

    # write out the day and season .csv file
    fileName = simulationName
    envSimu.writeOutResult(project, fileName)

    # Write out algorithm log file to csv
    seasonDataPath = r"D:\yk_research\AquaCrop-Irrigation-Design\output\{}_season.csv".format(
        fileName)
    seasonData = helper.loadSeasonCSV(seasonDataPath)

    algInfo = {'sensor0': 'sensor0', 'sensor1': 'sensor1',
               'ref0': 'ref0', 'ref1': 'ref1'}
    summary = {"yield": seasonData['Yield']
               [-1], "water": seasonData['Irri'][-1]}
    al.writeLogToCSV(algInfo, summary, fileName)
def simulateOnce(t, d):

    simpleCtl = SimpleController()
    predictedIrri = 0
    while not envSimu.isFinish():

        print("\nDay Count: {}".format(envSimu.currentDayCount))
        envSimu.loadResult()

        print("WCs:")
        print(envSimu.getCurrentDayWCs())
        WCs = envSimu.getCurrentDayWCs()

        irrHistory = envSimu.getIrrigationHistory()
        # print(WCs[0])
        """
            Methodology Part:
            If moisture condition triggers irrigation event, controller to generate irrigation amount
        """

        ##
        # -- ET-base Irrigation --
        ##
        # ET_k = 1.15
        # predictedIrri = helper.ETbasedIrrigation(ET, ET_k)

        ##
        # -- SI-controller --: shallow point = 0.05m, 0.15m, 0.25m(wc1, wc2, wc3)
        ##
        # predictedIrri = simpleCtl.get_output(WCs)

        # controllerStatus = simpleCtl.get_status(WCs)

        # IrriHistory

        if envSimu.currentDayCount == 0:
            yesterIrrStr = "No yesterday"
        else:
            yesterdayIdx = envSimu.currentDayCount - 1
            yesterIrrStr = str(irrHistory[yesterdayIdx])

        print("Yesterday Irri: {}".format(yesterIrrStr))

        # Reference (Target)
        # ref=" ".join(map(str,controllerStatus['ref']))
        # print("ref: ")
        # print(controllerStatus['ref'])

        # # Error of observation point
        # print("err:")
        # trancatedErrList = ['%.3f'%elem for elem in controllerStatus['e']]
        # print(trancatedErrList)

        # # Coefficient K
        # print("k:")
        # print(controllerStatus['k'])

        # # Initialization miControllerontroller
        # miController = Controller(ref1=25.0, ref2=10.0)
        # miController.setK(1.5, 2.25, 0, 0)

        # ##
        # # Find floating EWC( Efficient Wetting Zone )
        # ##
        # firstQuarter = rDepth * 0.5
        # compartment_boundary_list = config['compartment_boundary_list']
        # closestCompartment = helper.calEWZbyCompartment(
        #     compartment_boundary_list, firstQuarter)

        # EWZGrowIdx = int(closestCompartment * 10 - 1)
        # EWZBottomWaterContent = row[WC1Idx + EWZGrowIdx]
        if predictedIrri > 0:

            irriDay = envSimu.currentDayCount + 1
            print("IrriDay: {}".format(irriDay))
            print("Irri: {}".format(predictedIrri))
            helper.appendDotIRR('Example.Irr', irriDay, predictedIrri)
            envSimu.runOnce()

        envSimu.increateTimeStep()
def simulateOnce(ref, depth, simulationName):

    project = 'TOMATO2'
    envSimu = EnvSimulator(project)
    envSimu.initRun()

    #
    # controller intialization
    #
    soilProperityDict = {"sat": 50, "fc": 30, "pwp": 10}
    soilProfile = {"compartment_num": 7}
    sensorIntepret = {"controlDepth": depth}
    simpleCtl = SimpleController(soilProperityDict, soilProfile,
                                 sensorIntepret)

    # Set refs
    refsArray = np.zeros(soilProfile['compartment_num'])
    refsArray[depth] = ref
    simpleCtl.set_ref(refsArray)

    # Set Kp,Ki,Kd cefficient
    kArray = np.zeros((3, soilProfile['compartment_num']))
    kArrayIndex = simpleCtl.get_kArray_index()

    ku = 4
    tu = 0.7
    kArray[kArrayIndex['p'], depth] = 0.45 * ku
    kArray[kArrayIndex['i'], depth] = 0
    kArray[kArrayIndex['i'], depth] = tu / 2
    kArray[kArrayIndex['d'], depth] = 0
    # kArray[kArrayIndex['d'],depth]=tu/8
    simpleCtl.set_k(kArray)

    # Set windup
    simpleCtl.set_windup(50)

    predictedIrri = 0

    while not envSimu.isFinish():

        # print("\nDay Count: {}".format(envSimu.currentDayCount))
        envSimu.loadResult()

        irrHistory = envSimu.getIrrigationHistory()
        if envSimu.currentDayCount == 0:
            yesterIrrStr = "No yesterday"
        else:
            yesterdayIdx = envSimu.currentDayCount - 1
            yesterIrrStr = str(irrHistory[yesterdayIdx])

        # print("Yesterday Irri: {}".format(yesterIrrStr))

        #
        # LoadData from first execution
        #

        WCs = envSimu.getCurrentDayWCs()
        # print("WCs:")
        # print(WCs)
        WCsnpArray = np.array(WCs)
        """
            Methodology Part:
            If moisture condition triggers irrigation event, controller to generate irrigation amount
        """

        ##
        # -- ET-base Irrigation --
        ##
        # ET_k = 1.15
        # predictedIrri = helper.ETbasedIrrigation(ET, ET_k)

        ##
        # -- SI-controller --: shallow point = 0.05m, 0.15m, 0.25m(wc1, wc2, wc3)
        ##
        err = simpleCtl.get_error(WCsnpArray)
        # print("error")
        # print(err)
        predictedIrri = simpleCtl.get_output(WCsnpArray)
        """
            Find floating EWC( Efficient Wetting Zone )
        """
        # firstQuarter = rDepth * 0.5
        # compartment_boundary_list = config['compartment_boundary_list']
        # closestCompartment = helper.calEWZbyCompartment(
        #     compartment_boundary_list, firstQuarter)

        # EWZGrowIdx = int(closestCompartment * 10 - 1)
        # EWZBottomWaterContent = row[WC1Idx + EWZGrowIdx]

        if predictedIrri > 0:

            irriDay = envSimu.currentDayCount + 1
            # print("IrriDay: {}".format(irriDay))
            # print("Irri: {}".format(predictedIrri))
            helper.appendDotIRR('Example.Irr', irriDay, predictedIrri)
            envSimu.runOnce()

        envSimu.increateTimeStep()

    # Extract Yield and Irrigation Amount from simulation

    # Write result to .csv
    envSimu.writeOutResult(project, simulationName)