def RunHY(model_dir, control_file):
    """Run hydraulics only"""
    try:
        HSP = ModelControl(model_dir, control_file, 2)
        HSP.Run()
    except:
        msg = "Error: {0}".format(traceback.format_exc())
        logging.error(msg)
        print_console(msg)
예제 #2
0
def RunSH(model_dir, control_file):
    """Run solar routines only"""
    try:
        HSP = ModelControl(model_dir, control_file, 1)
        HSP.Run()
    except:
        msg = "Error: {0}".format(traceback.format_exc())
        logging.error(msg)
        print_console(msg)
def RunSH(model_dir, control_file):
    """Run solar routines only"""
    try:
        HSP = ModelControl(model_dir, control_file, 1)
        HSP.Run()
    except:
        msg = "Error: {0}".format(traceback.format_exc())
        logging.error(msg)
        print_console(msg)
예제 #4
0
def RunHY(model_dir, control_file):
    """Run hydraulics only"""
    try:
        HSP = ModelControl(model_dir, control_file, 2)
        HSP.Run()
    except:
        msg = "Error: {0}".format(traceback.format_exc())
        logging.error(msg)
        print_console(msg)
예제 #5
0
def RunHY(model_dir, control_file):
    """Run hydraulics only"""
    try:
        HSP = ModelControl(model_dir, control_file, 2)
        HSP.Run()
    except Exception, stderr:
        msg = "".join(format_tb(exc_info()[2]))+"\nSynopsis: %s" % stderr, "Heat Source Error"
        logger.error(msg)
        print_console(msg)
def RunHS(model_dir, control_file):
    """Run full temperature model"""
    try:
        HSP = ModelControl(model_dir, control_file, 0)
        HSP.Run()
        del HSP
    except:
        msg = "Error: {0}".format(traceback.format_exc())
        logging.error(msg)
        print_console(msg)
예제 #7
0
def RunHS(model_dir, control_file):
    """Run full temperature model"""
    try:
        HSP = ModelControl(model_dir, control_file, 0)
        HSP.Run()
        del HSP
    except:
        msg = "Error: {0}".format(traceback.format_exc())
        logging.error(msg)
        print_console(msg)
예제 #8
0
def RunHS(model_dir, control_file):
    """Run full temperature model"""
    try:
        HSP = ModelControl(model_dir, control_file, 0)
        HSP.Run()
        del HSP
    except Exception, stderr:
        msg = "".join(format_tb(exc_info()[2]))+"\nSynopsis: %s" % stderr, "Heat Source Error"
        logger.error(msg)
        print_console(msg)
예제 #9
0
    def __init__(self, model_dir, control_file, run_type=0):
        """
        model_dir is the path to the directory where the
        control file is located.
        
        control_file is the control file name. It must be a comma
        delimtted text file.
        
        run_type is one of 0, 1, 2, or 3 for Heat Source (Temperature),
        Solar only, hydraulics only respectively.
        """
        
        # Add run type and heat source model version into IniParams
        IniParams["version"] = version_string
        IniParams["run_type"] = run_type
        msg = "Heat Source Version:  {0}".format(IniParams["version"])
        print_console(msg)
        logger.info(msg)
        
        # Create a ModelSetup instance.
        self.HS = ModelSetup(model_dir, control_file, run_type)

        # This is the list of StreamNode instances- we sort it in reverse
        # order because we number stream kilometer from the mouth to the
        # headwater, but we want to run the model from headwater to mouth.
        self.reachlist = sorted(self.HS.Reach.itervalues(), reverse=True)

        # This if statement prevents us from having to test every 
        # timestep. We just call self.run_all(), which is a classmethod 
        # pointing to the correct method.
        if run_type == 0: self.run_all = self.run_hs
        elif run_type == 1: self.run_all = self.run_sh
        elif run_type == 2: self.run_all = self.run_hy
        else:
            logger.error("Bad run_type: {0}. Must be 0, 1, or 2.\
            Something wrong with the executable".format(run_type))
            raise Exception("Bad run_type: {0}. Must be 0, 1, or 2. \
            Something wrong with the executable".format(run_type))
        
        # Create a Chronos iterator that controls all model time.
        Chronos.Start(start = IniParams["modelstart"],
                      stop = IniParams["modelend"],
                      dt = IniParams["dt"],
                      spin = IniParams["flushdays"],
                      offset = IniParams["offset"])
        
        # This is the output class, which is essentially just a list
        # of file objects and an append method which writes to them
        # every so often.
        self.Output = O(self.HS.Reach, IniParams["modelstart"], run_type)
    def __init__(self, model_dir, control_file, run_type=0):
        """
        model_dir is the path to the directory where the
        control file is located.
        
        control_file is the control file name. It must be a comma
        delimited text file.
        
        run_type is one of 0, 1, 2, or 3 for Heat Source (Temperature),
        Solar only, hydraulics only respectively.
        """

        # Add run type and heat source model version into IniParams
        IniParams["version"] = version_string
        IniParams["run_type"] = run_type

        msg = ("\n")

        msg += ("Heat Source, Copyright (C) 2000-2016, "
                "Oregon Department of Environmental Quality\n\n"
                "This program comes with ABSOLUTELY NO WARRANTY. "
                "Appropriate model \n"
                "use and application are the sole responsibility "
                "of the user. \n"
                "This is free software, and you are welcome to "
                "redistribute it under \n"
                "certain conditions described in the License.\n\n")
        msg += "Heat Source Version:  {0}\n".format(IniParams["version"])

        print_console(msg)
        logger.info(msg)

        # Create a ModelSetup instance.
        self.HS = ModelSetup(model_dir, control_file, run_type)

        # This is the list of StreamNode instances- we sort it in reverse
        # order because we number stream kilometer from the mouth to the
        # headwater, but we want to run the model from headwater to mouth.
        self.reachlist = sorted(self.HS.Reach.itervalues(), reverse=True)

        # This if statement prevents us from having to test every
        # timestep. We just call self.run_all(), which is a classmethod
        # pointing to the correct method.
        if run_type == 0: self.run_all = self.run_hs
        elif run_type == 1: self.run_all = self.run_sh
        elif run_type == 2: self.run_all = self.run_hy
        else:
            logger.error("Bad run_type: {0}. Must be 0, 1, or 2.\
            Something wrong with the executable".format(run_type))
            raise Exception("Bad run_type: {0}. Must be 0, 1, or 2. \
            Something wrong with the executable".format(run_type))

        # Create a Chronos iterator that controls all model time.
        Chronos.Start(start=IniParams["modelstart"],
                      stop=IniParams["modelend"],
                      dt=IniParams["dt"],
                      spin=IniParams["flushdays"],
                      offset=IniParams["offset"])

        # This is the output class, which is essentially just a list
        # of file objects and an append method which writes to them
        # every so often.
        self.Output = O(self.HS.Reach, IniParams["modelstart"], run_type)
    def Run(self):
        """Run the model one time

        Use the Chronos instance and list of StreamNodes to cycle
        through each timestep and spacestep, calling the appropriate
        StreamNode functions to calculate heat and hydraulics."""

        msg = "Starting Simulation:  {0}".format(IniParams["name"])
        logger.info(msg)
        print_console(msg)

        # Current time of the Chronos clock (i.e. this timestep)
        time = Chronos.TheTime

        # Stop time for Chronos
        stop = Chronos.stop

        # Start time for Chronos, model start, not flush/spin start.
        start = Chronos.start

        # flush in seconds
        flush = start - (IniParams["flushdays"] * 86400)
        # Number of timesteps is based on the division of the timesteps
        # into the hour. In other words 1 day with a 1 minute dt is
        # 1440 timesteps, while a 3 minute dt is only 480 timesteps.
        # Thus, we define the timesteps by dividing dt (now in seconds)
        # by 3600
        timesteps = (stop - flush) / IniParams["dt"]

        # Counter iterator for counting current timesteps passed
        cnt = count()

        # Volume of water flowing out of mouth (for simple mass balance)
        out = 0

        # Current computer time- for estimating total model runtime
        time1 = Time()

        # Localize run_type for a bit more speed
        ################################################################
        # So, it's simple and stupid. We basically just cycle through the
        # time until we get to the model stop time, and each cycle, we
        # call a method that cycles through the StreamNodes, and
        # calculates them in order. A smarter way would be to thread
        # this so we can start calculating the second timestep (using
        # another CPU or core) while the first one is still unfinished.
        while time <= stop:
            year, month, day, hour, minute, second, JD, offset, JDC = Chronos.TimeTuple(
            )
            # zero hour+minute+second means first timestep of new day
            if not (hour + minute + second):
                # zero out the daily flux sum at this point.
                for nd in self.reachlist:
                    nd.F_DailySum = [0] * 5
                    nd.Solar_Blocked = {}

                    # Number of radial sample directions
                    for i in range(IniParams["trans_count"]):

                        # A spot for each land cover sample
                        nd.Solar_Blocked[i] = [
                            0
                        ] * IniParams["transsample_count"]
                    nd.Solar_Blocked["diffuse"] = 0

            # Back to every timestep level of the loop. Here we wrap the call to
            # run_all() in a try block to catch the exceptions thrown.
            try:
                # Note that all of the run methods have to have
                # the same signature
                #if time == 1056951360.0:
                #   print_console(msg="error timestep")
                self.run_all(time, hour, minute, second, JD, JDC)
            # Shit, there's a problem
            except:
                msg = "Error at model km {0} at {1}, model time {2} {3}".format(
                    nd.km, Chronos.PrettyTime(), Chronos.TheTime,
                    traceback.format_exc())
                logging.error(msg)
                print_console(msg)

                # Then just die
                raise SystemExit

            # If minute and second are both zero, we are at the top of
            # the hour.
            if (minute == 0 and second == 0):
                ts = cnt.next()  # Number of actual timesteps per tick

                # Number of timesteps in one hour
                hr = 60 / (IniParams["dt"] / 60)
                # This writes a line to the status bar.
                msg = "Timesteps:"
                logger.info('{0} {1} {2}'.format(msg, (ts) * hr, timesteps))
                print_console(msg, True, (ts) * hr, timesteps)

                # Call the Output class to update the textfiles. We call
                # this every hour and store the data, then we write to
                # file every day. Limiting disk access saves us
                # considerable time.
                self.Output(time, hour)

            # ----
            # Uncomment to output every timestep and
            # comment section above
            #ts = cnt.next()
            #msg = "Timesteps:"
            #logger.info('{0} {1} {2}'.format(msg, ts, timesteps))
            #print_console("Timesteps:", True, ts, timesteps)
            #self.Output(time, hour, minute, second)
            # ----

            # We've made it through the entire stream without an error,
            # so we update our mass balance
            # by adding the discharge of the mouth...
            out += self.reachlist[-1].Q
            # and tell Chronos that we're moving time forward.
            time = Chronos(tick=True)

        # So, here we are at the end of a model run. First we
        # calculate how long all of this took
        total_time = (Time() - time1) / 60
        # Calculate the mass balance inflow
        balances = [x.Q_mass for x in self.reachlist]
        total_inflow = sum(balances)
        # Calculate how long the model took to run each timestep for
        # each spacestep. This is how long (on average) it took to
        # calculate a single StreamNode's information one time.
        # Ideally, for performance and impatience reasons, we want this
        # to be somewhere around or less than 1 microsecond.
        microseconds = (total_time / timesteps / len(self.reachlist)) * 1e6

        message = "Simulation Complete"

        message += "\n\nFinished in {0:0.1f} minutes ".format(total_time)
        message += "(spent {0:0.3f} microseconds ".format(microseconds)
        message += "in each stream node).\n"
        message += "Water Balance: {0:0.3f}/{1:0.3f}\n".format(
            total_inflow, out)
        message += "Simulation: {0}\n".format(IniParams["name"])
        message += "Outputs: {0}\n\n".format(IniParams["outputdir"])

        logger.info(message)
        print_console(message)
예제 #12
0
    def __init__(self, model_dir, control_file, run_type=0):
        """
        model_dir is the path to the directory where the
        control file is located.
        
        control_file is the control file name. It must be a comma
        delimited text file.
        
        run_type is one of 0, 1, 2, or 3 for Heat Source (Temperature),
        Solar only, hydraulics only respectively.
        """
        
        # Add run type and heat source model version into IniParams
        IniParams["version"] = version_string
        IniParams["run_type"] = run_type
        
        msg = ("\n")
        
        msg += ("Heat Source, Copyright (C) 2000-2016, "
                "Oregon Department of Environmental Quality\n\n"
                "This program comes with ABSOLUTELY NO WARRANTY. "
                "Appropriate model \n"
                "use and application are the sole responsibility "
                "of the user. \n"
                "This is free software, and you are welcome to "
                "redistribute it under \n"
                "certain conditions described in the License.\n\n")
        msg += "Heat Source Version:  {0}\n".format(IniParams["version"])
        
        print_console(msg)
        logger.info(msg)
        
        # Create a ModelSetup instance.
        self.HS = ModelSetup(model_dir, control_file, run_type)

        # This is the list of StreamNode instances- we sort it in reverse
        # order because we number stream kilometer from the mouth to the
        # headwater, but we want to run the model from headwater to mouth.
        self.reachlist = sorted(self.HS.Reach.itervalues(), reverse=True)

        # This if statement prevents us from having to test every 
        # timestep. We just call self.run_all(), which is a classmethod 
        # pointing to the correct method.
        if run_type == 0: self.run_all = self.run_hs
        elif run_type == 1: self.run_all = self.run_sh
        elif run_type == 2: self.run_all = self.run_hy
        else:
            logger.error("Bad run_type: {0}. Must be 0, 1, or 2.\
            Something wrong with the executable".format(run_type))
            raise Exception("Bad run_type: {0}. Must be 0, 1, or 2. \
            Something wrong with the executable".format(run_type))
        
        # Create a Chronos iterator that controls all model time.
        Chronos.Start(start = IniParams["modelstart"],
                      stop = IniParams["modelend"],
                      dt = IniParams["dt"],
                      spin = IniParams["flushdays"],
                      offset = IniParams["offset"])
        
        # This is the output class, which is essentially just a list
        # of file objects and an append method which writes to them
        # every so often.
        self.Output = O(self.HS.Reach, IniParams["modelstart"], run_type)
예제 #13
0
    def Run(self):
        """Run the model one time

        Use the Chronos instance and list of StreamNodes to cycle
        through each timestep and spacestep, calling the appropriate
        StreamNode functions to calculate heat and hydraulics."""
        
        msg = "Starting Simulation:  {0}".format(IniParams["name"])
        logger.info(msg)
        print_console(msg)
        
        # Current time of the Chronos clock (i.e. this timestep)
        time = Chronos.TheTime
        
        # Stop time for Chronos
        stop = Chronos.stop
        
        # Start time for Chronos, model start, not flush/spin start.
        start = Chronos.start
        
        # flush in seconds
        flush = start-(IniParams["flushdays"]*86400) 
        # Number of timesteps is based on the division of the timesteps 
        # into the hour. In other words 1 day with a 1 minute dt is 
        # 1440 timesteps, while a 3 minute dt is only 480 timesteps. 
        # Thus, we define the timesteps by dividing dt (now in seconds) 
        # by 3600
        timesteps = (stop-flush)/IniParams["dt"]
        
        # Counter iterator for counting current timesteps passed
        cnt = count()
        
        # Volume of water flowing out of mouth (for simple mass balance)
        out = 0
        
        # Current computer time- for estimating total model runtime
        time1 = Time()
        
        # Localize run_type for a bit more speed
        ################################################################
        # So, it's simple and stupid. We basically just cycle through the
        # time until we get to the model stop time, and each cycle, we 
        # call a method that cycles through the StreamNodes, and 
        # calculates them in order. A smarter way would be to thread 
        # this so we can start calculating the second timestep (using 
        # another CPU or core) while the first one is still unfinished.
        while time <= stop:
            year, month, day, hour, minute, second, JD, offset, JDC = Chronos.TimeTuple()
            # zero hour+minute+second means first timestep of new day
            if not (hour + minute + second):
                # zero out the daily flux sum at this point.
                for nd in self.reachlist:
                    nd.F_DailySum = [0]*5
                    nd.Solar_Blocked = {}
                    
                    # Number of radial sample directions
                    for i in range(IniParams["trans_count"]):
                        
                        # A spot for each land cover sample
                        nd.Solar_Blocked[i]=[0]*IniParams["transsample_count"]
                    nd.Solar_Blocked["diffuse"]=0

            # Back to every timestep level of the loop. Here we wrap the call to
            # run_all() in a try block to catch the exceptions thrown.
            try:
                # Note that all of the run methods have to have 
                # the same signature
                #if time == 1056951360.0:
                #   print_console(msg="error timestep")                
                self.run_all(time, hour, minute, second, JD, JDC)
            # Shit, there's a problem
            except:
                msg = "Error at model km {0} at {1}, model time {2} {3}".format(nd.km, Chronos.PrettyTime(), Chronos.TheTime, traceback.format_exc())
                logging.error(msg)
                print_console(msg)
                
                # Then just die
                raise SystemExit
                        
            # If minute and second are both zero, we are at the top of 
            # the hour. 
            if (minute == 0 and second == 0):
                ts = cnt.next() # Number of actual timesteps per tick
                
                # Number of timesteps in one hour
                hr = 60/(IniParams["dt"]/60) 
                # This writes a line to the status bar.
                msg = "Timesteps:"
                logger.info('{0} {1} {2}'.format(msg, (ts)*hr, timesteps))
                print_console(msg, True, (ts)*hr, timesteps)
                
                # Call the Output class to update the textfiles. We call
                # this every hour and store the data, then we write to 
                # file every day. Limiting disk access saves us 
                # considerable time.
                self.Output(time, hour)

            # ---- 
            # Uncomment to output every timestep and 
            # comment section above
            #ts = cnt.next()
            #msg = "Timesteps:"
            #logger.info('{0} {1} {2}'.format(msg, ts, timesteps))
            #print_console("Timesteps:", True, ts, timesteps)
            #self.Output(time, hour, minute, second)
            # ---- 

            # We've made it through the entire stream without an error, 
            # so we update our mass balance
            # by adding the discharge of the mouth...
            out += self.reachlist[-1].Q
            # and tell Chronos that we're moving time forward.
            time = Chronos(tick=True)

        # So, here we are at the end of a model run. First we 
        # calculate how long all of this took
        total_time = (Time() - time1) / 60
        # Calculate the mass balance inflow
        balances = [x.Q_mass for x in self.reachlist]
        total_inflow = sum(balances)
        # Calculate how long the model took to run each timestep for 
        # each spacestep. This is how long (on average) it took to 
        # calculate a single StreamNode's information one time. 
        # Ideally, for performance and impatience reasons, we want this
        # to be somewhere around or less than 1 microsecond.
        microseconds = (total_time/timesteps/len(self.reachlist))*1e6
        
        message = "Simulation Complete"
        
        message += "\n\nFinished in {0:0.1f} minutes ".format(total_time)
        message += "(spent {0:0.3f} microseconds ".format(microseconds)
        message += "in each stream node).\n"
        message += "Water Balance: {0:0.3f}/{1:0.3f}\n".format(total_inflow, out)
        message += "Simulation: {0}\n".format(IniParams["name"])
        message += "Outputs: {0}\n\n".format(IniParams["outputdir"])

        logger.info(message)
        print_console(message)