Esempio n. 1
0
    def make_model():
        print ('initializing the model')

        #print (start_date)

        start_time = startday

        model = Model(start_time=start_time, duration=timedelta(days=30), 
                      #weathering_substeps = 6,
                      time_step=24 * 3600,
                      uncertain=False)

        mapfile = get_datafile(os.path.join(base_dir,'gulf.bna'))

        #mapfile='gulf.bna'

        print ('adding the map')
        model.map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

        #
        # Add the outputters -- render to images, and save out as netCDF
        #

        

        

        print ("adding shapefile output")

         # with open("Result {}".format(spill_num), "w") as fp:
         # fp.write("text")
        
        dir_name = os.path.join (base_dir, season, str(position), "Spillnum {}".format(spill_num))
        
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)
        
        #os.makedirs(dir_name, exist_ok =True)

        for i in range(1, 31, 1):
            model.outputters += ShapeOutput(os.path.join(dir_name, 'gnome_result {id}'.format(id=i)),
                                        zip_output=False,
                                        output_timestep=timedelta(days=i)) 
        images_dir = os.path.join(dir_name, 'image')
        # print 'adding renderer'
        # model.outputters += Renderer(mapfile,
        #                         images_dir,
        #                         image_size=(800, 600))
                                 
        # print ('adding renderer')
        # dir_image = os.path.join(dir_name)
        # model.outputters += Renderer(mapfile,
        #                            dir_image,
        #                             size=(800, 600))
                              

        #
        # Set up the movers:
        #

        print ('adding a RandomMover:')
        model.movers += RandomMover(diffusion_coef=10000)

        print ('adding a simple wind mover:')
    

        
        wind_file = get_datafile(os.path.join(base_dir, 'ECMWF.nc'))
        model.movers += GridWindMover(wind_file)

                                                  

        print ('adding a current mover:')

        # # this is NEMO currents

        curr_file = get_datafile(os.path.join(base_dir, Currents))
        model.movers += GridCurrentMover(curr_file,
                                         num_method='Euler');


        
        # # Add some spills (sources of elements)
        

        print ('adding one spill')

        
       
        spill = point_line_release_spill(num_elements=1000,
                                                 amount=  3200000000 * spilldur , units='grams',
                                                 start_position = position,
                                                 release_time = start_time,
                                                 substance = (sub))
        model.spills += spill

        ####### open excel file 
        print ('adding Excel file')
      
        workbook = xlsxwriter.Workbook(os.path.join(dir_name, 'Result {}_{}.xlsx'.format(spill_num, position)))
        worksheet = workbook.add_worksheet () 
        a = ((spilldur*3200)**(-0.3))*0.000069
        worksheet.write ('A1', a)
        workbook.close()

        
        print ('adding weatherers and cleanup options:')

        model.environment += [water,wind,waves]
        model.weatherers += Evaporation()
        model.weatherers += Emulsification()
        model.weatherers += NaturalDispersion()
        print ('model full run:')
        model.full_run()
        return model
Esempio n. 2
0
def main(RootDir, Data_Dir, StartSite, RunSite, NumStarts, RunStarts,
         ReleaseLength, TrajectoryRunLength, StartTimeFiles, TrajectoriesPath,
         NumLEs, MapFileName, refloat, current_files, wind_files,
         diffusion_coef, model_timestep, windage_range, windage_persist,
         OutputTimestep):

    timingRecord = open(os.path.join(RootDir, "timing.txt"), "w")
    count = len(StartTimeFiles) * len(RunStarts)
    timingRecord.write("This file tracks the time to process " + str(count) +
                       " gnome runs")

    # model timing
    release_duration = timedelta(hours=ReleaseLength)
    run_time = timedelta(hours=TrajectoryRunLength)

    # initiate model
    model = Model(duration=run_time, time_step=model_timestep, uncertain=False)

    # determine boundary for model
    print "Adding the map:", MapFileName
    mapfile = get_datafile(os.path.join(Data_Dir, MapFileName))
    # model.map = MapFromBNA(mapfile, refloat_halflife=refloat) no, model map needs to inclde mudflats. later

    # loop through seasons
    for Season in StartTimeFiles:
        timer1 = datetime.now()

        SeasonName = Season[1]
        start_times = open(Season[0], 'r').readlines()[:NumStarts]
        SeasonTrajDir = os.path.join(RootDir, TrajectoriesPath, SeasonName)
        if not os.path.isdir(SeasonTrajDir):
            print "Creating directory: ", SeasonTrajDir
            make_dir(SeasonTrajDir)
        print "  Season:", SeasonName

        # get and parse start times in this season
        start_dt = []
        for start_time in start_times:
            start_time = [int(i) for i in start_time.split(',')]
            start_time = datetime(start_time[0], start_time[1], start_time[2],
                                  start_time[3], start_time[4])
            start_dt.append(start_time)

        ## loop through start times
        for time_idx in RunStarts:
            timer2 = datetime.now()

            gc.collect()
            model.movers.clear()

            ## set the start location
            start_time = start_dt[time_idx]
            end_time = start_time + run_time
            model.start_time = start_time
            print "  ", start_time, "to", end_time

            ## get a list of the only data files needed for the start time (less data used)
            ## note: requires data files in year increments
            #Todo: needs fixing before real run
            years = range(start_time.year, end_time.year + 1)
            years = [str(i) for i in years]
            wind = [s for s in wind_files if any(xs in s for xs in years)]
            current = [
                s for s in current_files if any(xs in s for xs in years)
            ]

            #Todo: add mudflats. Does it work like this?
            topology = {'node_lon': 'x', 'node_lat': 'y'}

            ## add wind movers
            w_mover = PyWindMover(filename=wind)
            model.movers += w_mover

            ## add current movers
            current_mover = gs.GridCurrent.from_netCDF(current,
                                                       grid_topology=topology)
            c_mover = PyCurrentMover(current=current_mover)
            model.movers += c_mover

            tideflat = Matroos_Mudflats(current, grid_topology=topology)
            land_map = gs.MapFromBNA(mapfile)
            model.map = TideflatMap(land_map, tideflat)

            ## add diffusion
            model.movers += RandomMover(diffusion_coef=diffusion_coef)

            ## loop through start locations
            timer3 = datetime.now()

            #Todo: can it deal with the test.location.txt file??
            start_position = [float(i) for i in StartSite.split(',')]

            OutDir = os.path.join(RootDir, TrajectoriesPath, SeasonName,
                                  'pos_%03i' % (RunSite + 1))
            make_dir(OutDir)

            print "    ", RunSite, time_idx
            print "    Running: start time:", start_time,
            print "at start location:", start_position

            ## set the spill to the location
            spill = surface_point_line_spill(
                num_elements=NumLEs,
                start_position=(start_position[0], start_position[1], 0.0),
                release_time=start_time,
                end_release_time=start_time + release_duration,
                windage_range=windage_range,
                windage_persist=windage_persist)

            # print "adding netcdf output"
            netcdf_output_file = os.path.join(
                OutDir,
                'pos_%03i-t%03i_%08i.nc' %
                (RunSite + 1, time_idx, int(start_time.strftime('%y%m%d%H'))),
            )
            model.outputters.clear()
            model.outputters += NetCDFOutput(
                netcdf_output_file,
                output_timestep=timedelta(hours=OutputTimestep))

            model.spills.clear()
            model.spills += spill

            model.full_run(rewind=True)

            timer4 = datetime.now()
            diff = round((timer4 - timer3).total_seconds() / 60, 2)
            timingRecord.write("\t\t" + str(RunSite) + " took " + str(diff) +
                               " minutes to complete")
        diff = round((timer4 - timer1).total_seconds() / 3600, 2)
        count = len(RunStarts)
        timingRecord.write("\t" + str(SeasonName) + " took " + str(diff) +
                           " hours to finish " + str(count) + " Gnome runs")
    #OutDir.close
    timingRecord.close
Esempio n. 3
0
    def make_model(images_dir=os.path.join(base_dir, 'images')):
        print('initializing the model')

        #print (start_date)

        start_time = new_start_date

        model = Model(
            start_time=start_time,
            duration=timedelta(days=30),
            #weathering_substeps = 6,
            time_step=24 * 3600,
            uncertain=True)

        mapfile = get_datafile(os.path.join(base_dir, 'gulf.bna'))

        #mapfile='gulf.bna'

        print('adding the map')
        model.map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

        #
        # Add the outputters -- render to images, and save out as netCDF
        #

        print('adding renderer')
        #model.outputters += Renderer(mapfile,
        # images_dir,
        #size=(800, 600),
        #draw_back_to_fore=True)

        #print ("adding netcdf output")
        #   netcdf_output_file = os.path.join(base_dir,'gulf_output.nc')
        #scripting.remove_netcdf(netcdf_output_file)
        #    model.outputters += NetCDFOutput(netcdf_output_file, which_data='all',
        #                                    output_timestep=timedelta(hours=24))

        print("adding shapefile output")

        # with open("Result {}".format(spill_num), "w") as fp:
        # fp.write("text")

        dir_name = os.path.join(base_dir,
                                "Result{}_{}".format(spill_num, position))
        if not os.path.exists(dir_name):
            os.mkdir(dir_name)

        for i in range(1, 31, 1):
            model.outputters += ShapeOutput(os.path.join(
                dir_name,
                'gnome_result{id}_{spillnum}'.format(id=i,
                                                     spillnum=spill_num)),
                                            zip_output=False,
                                            output_timestep=timedelta(days=i))

        #
        # Set up the movers:
        #

        print('adding a RandomMover:')
        model.movers += RandomMover(diffusion_coef=10000)

        print('adding a simple wind mover:')
        #    model.movers += constant_wind_mover(5, 315, units='m/s')

        wind_file = get_datafile(os.path.join(base_dir, 'nc3ECMWF2016.nc'))
        model.movers += GridWindMover(wind_file)

        #water = Water (temperature=290.367946, salinity=35.0)
        #wind = GridWindMover (wind_file)
        #waves = Waves ()

        print('adding a current mover:')

        # # this is NEMO currents

        curr_file = get_datafile(os.path.join(base_dir, 'current2016nc3.nc'))
        model.movers += GridCurrentMover(curr_file, num_method='Euler')

        # #
        # # Add some spills (sources of elements)
        # #

        print('adding one spill')

        spill = point_line_release_spill(num_elements=1000,
                                         amount=4000 * spilldur,
                                         units='m^3',
                                         start_position=position,
                                         release_time=start_time,
                                         substance=(u'BAHRGANSAR, OIL & GAS'))
        model.spills += spill

        ####### open excel file
        print('adding Excel file')
        #name = 'Result{}_{}'.format(spill_num, position)
        workbook = xlsxwriter.Workbook(
            os.path.join(dir_name,
                         'Result{}_{}.xlsx'.format(spill_num, position)))
        worksheet = workbook.add_worksheet()
        worksheet.write('A1', spilldur * 3200)

        #workbook.close()

        print('adding weatherers and cleanup options:')

        model.environment += [water, wind, waves]
        model.add_weathering()

        #model.weatherers += Evaporation()
        #model.weatherers += Emulsification()
        #model.weatherers += NaturalDispersion()
        model.full_run()
        return model