示例#1
0
def test_date_range_index():
    path = get_path('meteo00-01.txt')
    weather = Weather(path)
    index = weather.date_range_index('2000-12-31')
    assert len(index) == 24
    index = weather.date_range_index('2000-12-31', by=3)
    assert len(index) == 3
    index = weather.date_range_index('2000-12-31', '2001-01-02', by=24)
    assert len(index) == 2
    assert len(index[0]) == 24
示例#2
0
from alinea.alep.washing import RapillyWashing
from alinea.alep.growth_control import NoPriorityGrowthControl
from alinea.alep.infection_control import BiotrophDUPositionModel
from alinea.alep.senescence import WheatSeptoriaPositionedSenescence

# Imports for display and saving
from alinea.alep.disease_outputs import plot_severity_by_leaf, save_image

# Initiation of the simulation ##########################################
# Set the seed of the simulation
rd.seed(0)
np.random.seed(0)

# Read weather and adapt it to septoria (add wetness)
meteo_path = shared_data(alinea.septo3d, 'meteo05-06.txt')
weather = Weather(data_file=meteo_path)
weather.check(varnames=['wetness'], models={'wetness': wetness_rapilly})
seq = pandas.date_range(start="2005-10-01 01:00:00",
                        end="2006-07-01 01:00:00",
                        freq='H')

# Initialize a wheat canopy
g, wheat, domain_area, domain = initialize_stand(age=0.,
                                                 length=1,
                                                 width=1,
                                                 sowing_density=250,
                                                 plant_density=250,
                                                 inter_row=0.12,
                                                 seed=3)

# Choose source leaf in canopy
示例#3
0
def run_simulation(start_year, variability=True, **kwds):
    # Set the seed of the simulation
    rd.seed(0)
    np.random.seed(0)

    # Read weather and adapt it to septoria (add wetness)
    weather_file = 'meteo'+ str(start_year)[-2:] + '-' + str(start_year+1)[-2:] + '.txt'
    meteo_path = shared_data(alinea.septo3d, weather_file)
    weather = Weather(data_file=meteo_path)
    weather.check(varnames=['wetness'], models={'wetness':wetness_rapilly})
    seq = pandas.date_range(start = str(start_year)+"-10-01 01:00:00",
                            end = str(start_year+1)+"-07-01 01:00:00", 
                            freq='H')

    # Initialize a wheat canopy
    g, wheat, domain_area, domain = initialize_stand(age=0., length=0.1, 
                                                    width=0.2, sowing_density=150,
                                                    plant_density=150, inter_row=0.12, 
                                                    seed=3)
    
    # Initialize the models for septoria
    if 'alinea.alep.septoria_age_physio' in sys.modules:
        del(sys.modules['alinea.alep.septoria_age_physio'])
    if variability==True:
        septoria = variable_septoria(**kwds)
    else:
        septoria = plugin_septoria(model="septoria_age_physio")
    DU = septoria.dispersal_unit()
    inoculator = RandomInoculation()
    growth_controler = NoPriorityGrowthControl()
    infection_controler = BiotrophDUPositionModel()
    sen_model = WheatSeptoriaPositionedSenescence(g, label='LeafElement')
    emitter = SeptoriaRainEmission(domain_area=domain_area)
    transporter = Septo3DSplash(reference_surface=domain_area)
    washor = RapillyWashing()

    # Define the schedule of calls for each model
    every_h = time_filter(seq, delay=1)
    every_24h = time_filter(seq, delay=24)
    every_rain = rain_filter(seq, weather)
    weather_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    wheat_timing = IterWithDelays(*time_control(seq, every_24h, weather.data))
    septo_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    rain_timing = IterWithDelays(*time_control(seq, every_rain, weather.data))

    # Call leaf inspectors for target blades (top 3)
    inspectors = {}
    first_blade = 80
    ind = 4.
    for blade in range(first_blade,104,8):
        ind -= 1
        inspectors[ind] = LeafInspector(g, blade_id=blade)
    
    # Simulation loop
    for i,controls in enumerate(zip(weather_timing, wheat_timing, 
                                    septo_timing, rain_timing)):
        weather_eval, wheat_eval, septo_eval, rain_eval = controls
        
        # Update date
        date = weather_eval.value.index[0]

        # Get weather for date and add it as properties on leaves
        if weather_eval:
            set_properties(g,label = 'LeafElement',
                           temp = weather_eval.value.temperature_air[0],
                           wetness = weather_eval.value.wetness[0],
                           relative_humidity = weather_eval.value.relative_humidity[0],
                           wind_speed = weather_eval.value.wind_speed[0])
        if rain_eval:
            set_properties(g,label = 'LeafElement',
                           rain_intensity = rain_eval.value.rain.mean(),
                           rain_duration = len(rain_eval.value.rain) if rain_eval.value.rain.sum() > 0 else 0.)

        # Grow wheat canopy
        if wheat_eval:
            print(date)
            g,_ = grow_canopy(g, wheat, wheat_eval.value)
            # Note : The position of senescence goes back to its initial value after
            # a while for undetermined reason
            # --> temporary hack for keeping senescence position low when it is over
            positions = g.property('position_senescence')
            are_green = g.property('is_green')
            leaves = get_leaves(g, label = 'LeafElement')
            positions.update({leaf:(0 if positions[leaf]==1 and not are_green[leaf] else positions[leaf]) 
                              for leaf in leaves})
            
        # Develop disease
        if septo_eval:
            sen_model.find_senescent_lesions(g, label = 'LeafElement')
            update_healthy_area(g, label = 'LeafElement')
            if rain_eval and i <= 500:
                # Refill pool of initial inoculum to simulate differed availability
                if rd.random()<0.4:
                    dispersal_units = [DU(nb_spores=rd.randint(1,100), status='emitted') for i in range(rd.randint(0,3))]
                    initiate(g, dispersal_units, inoculator)
            infect(g, septo_eval.dt, infection_controler, label='LeafElement')
            update(g, septo_eval.dt, growth_controler, sen_model, label='LeafElement')                
        
        les = g.property('lesions')
        lesions = sum([l for l in les.values()], [])
        
        print([l.fungus.degree_days_to_chlorosis for l in lesions])
        
        # if len(lesions)>10:
            # import pdb
            # pdb.set_trace()
        
        
        if rain_eval:
            g, nb = disperse(g, emitter, transporter, "septoria", label='LeafElement')
            wash(g, washor, rain_eval.value.rain.mean(), label='LeafElement')
        
        # Save outputs
        for inspector in inspectors.itervalues():
            inspector.update_variables(g)
            inspector.update_du_variables(g)
        
        if wheat_eval:
            plot_severity_by_leaf(g)
    
    return inspectors
示例#4
0
def get_weather(start_date="2010-10-15 12:00:00", end_date="2011-08-01 01:00:00"):
    """ Get weather data for simulation. """
    start = datetime.datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')
    if start.year >= 2010:
        filename = 'Boigneville_0109'+str(start.year)+'_3108'+str(start.year+1)+'_h.csv'
        meteo_path = shared_data(alinea.echap, filename)
        weather = Weather(meteo_path, reader = arvalis_reader)
        weather.check(['temperature_air', 'PPFD', 'relative_humidity',
                       'wind_speed', 'rain', 'global_radiation', 'vapor_pressure'])
        notation_dates_file = shared_data(alinea.alep, 'notation_dates/notation_dates_'+str(start.year+1)+'.csv')
        weather.check(varnames=['notation_dates'], models={'notation_dates':add_notation_dates}, notation_dates_file = notation_dates_file)
    else:
        start_yr = str(start.year)[2:4]
        end_yr = str(start.year+1)[2:4]
        filename = 'meteo'+ start_yr + '-' + end_yr + '.txt'
        meteo_path = shared_data(alinea.septo3d, filename)
        weather = Weather(data_file=meteo_path)
    weather.check(varnames=['wetness'], models={'wetness':wetness_rapilly})
    weather.check(varnames=['degree_days'], models={'degree_days':linear_degree_days}, start_date=start_date, base_temp=0., max_temp=30.)
    weather.check(varnames=['septo_degree_days'], models={'septo_degree_days':linear_degree_days}, start_date=start_date, base_temp=0., max_temp=30.)
    return weather
示例#5
0
def get_weather(start_date="2010-10-15 12:00:00",
                end_date="2011-08-01 01:00:00"):
    """ Get weather data for simulation. """
    start = datetime.datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')
    if start.year >= 2010:
        filename = 'Boigneville_0109' + str(
            start.year) + '_3108' + str(start.year + 1) + '_h.csv'
        meteo_path = shared_data(alinea.echap, filename)
        weather = Weather(meteo_path, reader=arvalis_reader)
        weather.check([
            'temperature_air', 'PPFD', 'relative_humidity', 'wind_speed',
            'rain', 'global_radiation', 'vapor_pressure'
        ])
        notation_dates_file = shared_data(
            alinea.alep,
            'notation_dates/notation_dates_' + str(start.year + 1) + '.csv')
        weather.check(varnames=['notation_dates'],
                      models={'notation_dates': add_notation_dates},
                      notation_dates_file=notation_dates_file)
    else:
        start_yr = str(start.year)[2:4]
        end_yr = str(start.year + 1)[2:4]
        filename = 'meteo' + start_yr + '-' + end_yr + '.txt'
        meteo_path = shared_data(alinea.septo3d, filename)
        weather = Weather(data_file=meteo_path)
    weather.check(varnames=['wetness'], models={'wetness': wetness_rapilly})
    weather.check(varnames=['degree_days'],
                  models={'degree_days': linear_degree_days},
                  start_date=start_date,
                  base_temp=0.,
                  max_temp=30.)
    weather.check(varnames=['septo_degree_days'],
                  models={'septo_degree_days': linear_degree_days},
                  start_date=start_date,
                  base_temp=0.,
                  max_temp=30.)
    return weather
示例#6
0
def test_update(senescence_threshold=330., sen_day=500., model="septoria_exchanging_rings", **kwds):
    """ 
    """
    from alinea.alep.wheat import adel_one_leaf_element
    
    # Read weather and adapt it to septoria (add wetness)
    meteo_path = shared_data(alinea.septo3d, 'meteo00-01.txt')
    weather = Weather(data_file=meteo_path)
    weather.check(varnames=['wetness'], models={'wetness':wetness_rapilly})
    seq = pandas.date_range(start = "2000-10-01 01:00:00",
                            end = "2000-12-31 01:00:00", 
                            freq='H')
    
    # Generate a wheat MTG
    g = adel_one_leaf_element()
    set_properties(g, label = 'LeafElement', 
                   area=5., green_area=5., healthy_area=5., position_senescence=1,
                   wetness=True, temp=22., rain_intensity=0., relative_humidity=90.)
    
    # Generate one lesion of septoria and distribute it on g
    # septoria = new_septoria(senescence_threshold=senescence_threshold)
    septoria = plugin_septoria(model)
    Lesion = septoria.lesion(**kwds)
    leaf = g.node(10)
    leaf.lesions = [Lesion(nb_spores=1, position=[0.5, 0])]
    
    # Call model of growth control
    growth_controler = NoPriorityGrowthControl()
    sen_model = WheatSeptoriaPositionedSenescence(g, label='LeafElement')
    
    #Temp
    emitter = SeptoriaRainEmission(domain_area=0.0004)
    transporter = Septo3DSplash(reference_surface=0.0004)
    
    # Loop of simulation
    every_h = time_filter(seq, delay=1)
    every_rain = rain_filter(seq, weather)
    septo_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    rain_timing = IterWithDelays(*time_control(seq, every_rain, weather.data))
    surface = []
    surface_alive = []
    surface_empty = []
    nb_dus = []
    stock_spores = []
    for i,controls in enumerate(zip(septo_timing, rain_timing)):
        septo_eval, rain_eval = controls
        
        if i==sen_day:
            set_properties(g, label = 'LeafElement', position_senescence=0) 
        if rain_eval:
            set_properties(g,label = 'LeafElement',
                           rain_intensity = rain_eval.value.rain.mean(),
                           rain_duration = len(rain_eval.value.rain) if rain_eval.value.rain.sum() > 0 else 0.)
            
        # Update healthy area
        sen_model.find_senescent_lesions(g, label = 'LeafElement')
        update_healthy_area(g, label = 'LeafElement')
    
        # Update
        update(g, septo_eval.dt, growth_controler, senescence_model=sen_model, label='LeafElement')
        
        if rain_eval:
            g, nb = disperse(g, emitter, transporter, "septoria", label='LeafElement')
        else:
            nb=0.
        nb_dus.append(nb)
        
        # Check that the lesion is in the right status and has the right surface
        lesion = g.property('lesions')
        if lesion:
            assert sum(len(l) for l in lesion.itervalues()) == 1
            l = lesion.values()[0][0]
            surface.append(l.surface)
            surface_alive.append(l.surface_alive)
            surface_empty.append(l.surface_empty)
            stock_spores.append(l.stock_spores)
            # if i==299:
                # import pdb
                # pdb.set_trace()
            l.compute_all_surfaces()
            f = l.fungus
            print('lesion surface: %f' % round(l.surface, 6))
            
    return g, surface, surface_alive, surface_empty, nb_dus, stock_spores
示例#7
0
from alinea.alep.dispersal_emission import PowderyMildewWindEmission
from alinea.alep.dispersal_transport import PowderyMildewWindDispersal
from alinea.alep.growth_control import GrowthControlVineLeaf
from alinea.alep.infection_control import BiotrophDUProbaModel

# Imports for display and saving
from alinea.alep.disease_outputs import plot_severity_vine, save_image

# Initialization ##############################################################
# Set the seed of the simulation
rd.seed(0)
np.random.seed(0)

# Read weather and adapt it to powdery mildew (add wetness)
meteo_path = shared_data(alinea.septo3d, 'meteo05-06.txt')
weather = Weather(data_file=meteo_path)
weather.check(varnames=['wetness'], models={'wetness':wetness_rapilly})
seq = pandas.date_range(start = "2006-03-01 01:00:00", end = "2006-04-10 01:00:00", freq='H')

# Initialize a vine canopy
vine = Vine()
g,_ = new_canopy(vine, age = 6)

# Initialize the models for powdery mildew
diseases=plugin.discover('alep.disease')
powdery_mildew = diseases['powdery_mildew'].load()
infection_controler = BiotrophDUProbaModel()
growth_controler = GrowthControlVineLeaf()
emitter = PowderyMildewWindEmission()
transporter = PowderyMildewWindDispersal()
示例#8
0
def run_sim(year=1999, nb_dus=1, model='septoria_exchanging_rings', **kwds):
    # Set the seed of the simulation
    rd.seed(0)
    np.random.seed(0)

    # Read weather and adapt it to septoria (add wetness)
    weather_file = 'meteo'+ str(year-1)[-2:] + '-' + str(year)[-2:] + '.txt'
    meteo_path = shared_data(alinea.septo3d, weather_file)
    weather = Weather(data_file=meteo_path)
    weather.check(varnames=['wetness'], models={'wetness':wetness_rapilly})
    seq = pandas.date_range(start = str(year)+"-02-01 01:00:00",
                            end = str(year)+"-05-01 01:00:00", 
                            freq='H')

    # Generation of 1 leaf
    g = leaf()
    set_properties(g, label = 'LeafElement', area=20., green_area=20., position_senescence=1)
    source_leaf = g.node(10)
    blade_id = 8
    inspector = LeafInspector(g, blade_id=blade_id)

    # Initialize the models for septoria
    if 'alinea.alep.'+model in sys.modules:
        del(sys.modules['alinea.alep.'+model])
    septoria = plugin_septoria(model)
    DU = septoria.dispersal_unit(**kwds)
    growth_controler = NoPriorityGrowthControl()

    # Define the schedule of calls for each model
    every_h = time_filter(seq, delay=1)
    every_24h = time_filter(seq, delay=24)
    every_rain = rain_filter(seq, weather)
    weather_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    wheat_timing = IterWithDelays(*time_control(seq, every_24h, weather.data))
    septo_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    rain_timing = IterWithDelays(*time_control(seq, every_rain, weather.data))

    # Simulation ############################################################
    for i, controls in enumerate(zip(weather_timing, wheat_timing, septo_timing, rain_timing)):
        weather_eval, wheat_eval, septo_eval, rain_eval = controls
        
        # Get weather for date and add it as properties on leaves
        if weather_eval:
            # set_properties(g,label = 'LeafElement',
                           # temp = weather_eval.value.temperature_air[0],
                           # wetness = weather_eval.value.wetness[0],
                           # relative_humidity = weather_eval.value.relative_humidity[0],
                           # wind_speed = weather_eval.value.wind_speed[0])
            set_properties(g,label = 'LeafElement',
                           temp = 22.,
                           wetness = True,
                           relative_humidity = 90,
                           wind_speed = 0.)
        if rain_eval:
            # set_properties(g,label = 'LeafElement',
                           # rain_intensity = rain_eval.value.rain.mean(),
                           # rain_duration = len(rain_eval.value.rain) if rain_eval.value.rain.sum() > 0 else 0.)
            set_properties(g,label = 'LeafElement',
                           rain_intensity = 0.,
                           rain_duration = 0.) 
             
        # Develop disease
        if septo_eval:
            # Update g for the disease
            update_healthy_area(g, label = 'LeafElement')
            
            # Inoculation
            if i==1:
                # if i<=2.5*24:
                    # nb_dus=i
                # else:
                    # nb_dus= i - (i/2.5*24)
                dus = [DU(nb_spores=1., status='deposited') for i in range(int(nb_dus))]
                try:
                    source_leaf.dispersal_units += dus
                except:
                    source_leaf.dispersal_units = dus
            
            # Update dispersal units and lesions
            infect(g, septo_eval.dt, label='LeafElement')
            
            # if i>=753:
                # import pdb
                # pdb.set_trace()
            update(g, septo_eval.dt, growth_controler, label='LeafElement')
        
            # Save outputs   
            inspector.update_variables(g)
            inspector.update_du_variables(g)
    return inspector
示例#9
0
def run_simulation():
    # Initialization #####################################################
    # Set the seed of the simulation
    rd.seed(0)
    np.random.seed(0)

    # Read weather and adapt it to septoria (add wetness)
    meteo_path = shared_data(alinea.septo3d, 'meteo98-99.txt')
    weather = Weather(data_file=meteo_path)
    weather.check(varnames=['wetness'], models={'wetness': wetness_rapilly})
    seq = pandas.date_range(start="1998-10-01 01:00:00",
                            end="1999-07-01 01:00:00",
                            freq='H')

    # Initialize a wheat canopy
    g, wheat, domain_area, domain = initialize_stand(age=0.,
                                                     length=0.1,
                                                     width=0.2,
                                                     sowing_density=150,
                                                     plant_density=150,
                                                     inter_row=0.12,
                                                     seed=8)

    # Initialize the models for septoria
    # septoria = new_septoria(senescence_treshold=senescence_treshold)
    septoria = plugin_septoria()
    inoculator = RandomInoculation()
    growth_controler = NoPriorityGrowthControl()
    infection_controler = BiotrophDUPositionModel()
    sen_model = WheatSeptoriaPositionedSenescence(g, label='LeafElement')
    emitter = SeptoriaRainEmission(domain_area=domain_area)
    transporter = Septo3DSplash(reference_surface=domain_area)
    washor = RapillyWashing()

    # Define the schedule of calls for each model
    every_h = time_filter(seq, delay=1)
    every_24h = time_filter(seq, delay=24)
    every_rain = rain_filter(seq, weather)
    weather_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    wheat_timing = IterWithDelays(*time_control(seq, every_24h, weather.data))
    septo_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    rain_timing = IterWithDelays(*time_control(seq, every_rain, weather.data))

    # Call leaf inspectors for target blades (top 3)
    inspectors = {}
    # for rank in range(1,3):
    # inspectors[rank] = LeafInspector(g, blade_id=find_blade_id(g, leaf_rank = rank, only_visible=False))
    inspectors[1] = LeafInspector(g, blade_id=96)
    # inspectors[2] = LeafInspector(g, blade_id=88)
    # inspectors[3] = LeafInspector(g, blade_id=80)
    dates = []
    # Simulation #########################################################
    for i, controls in enumerate(
            zip(weather_timing, wheat_timing, septo_timing, rain_timing)):
        weather_eval, wheat_eval, septo_eval, rain_eval = controls

        # Update date
        date = weather_eval.value.index[0]
        dates.append(date)

        # Get weather for date and add it as properties on leaves
        if weather_eval:
            set_properties(
                g,
                label='LeafElement',
                temp=weather_eval.value.temperature_air[0],
                wetness=weather_eval.value.wetness[0],
                relative_humidity=weather_eval.value.relative_humidity[0],
                wind_speed=weather_eval.value.wind_speed[0])
        if rain_eval:
            set_properties(g,
                           label='LeafElement',
                           rain_intensity=rain_eval.value.rain.mean(),
                           rain_duration=len(rain_eval.value.rain)
                           if rain_eval.value.rain.sum() > 0 else 0.)

        # Grow wheat canopy
        if wheat_eval:
            print(date)
            g, _ = grow_canopy(g, wheat, wheat_eval.value)
            # Note : The position of senescence goes back to its initial value after
            # a while for undetermined reason
            # --> temporary hack for keeping senescence position low when it is over
            positions = g.property('position_senescence')
            are_green = g.property('is_green')
            areas = g.property('area')
            senesced_areas = g.property('senesced_area')
            leaves = get_leaves(g, label='LeafElement')
            vids = [leaf for leaf in leaves if leaf in g.property('geometry')]
            positions.update({
                vid: (0 if (positions[vid] == 1 and not are_green[vid]) or
                      (positions[vid] > 0 and round(areas[vid], 5) == round(
                          senesced_areas[vid], 5)) else positions[vid])
                for vid in vids
            })

        # Develop disease
        if septo_eval:
            sen_model.find_senescent_lesions(g, label='LeafElement')
            update_healthy_area(g, label='LeafElement')
            if rain_eval and i <= 500:
                # Refill pool of initial inoculum to simulate differed availability
                dispersal_units = generate_stock_du(nb_dus=rd.randint(0, 5),
                                                    disease=septoria)
                initiate(g, dispersal_units, inoculator)
            infect(g, septo_eval.dt, infection_controler, label='LeafElement')
            update(g,
                   septo_eval.dt,
                   growth_controler,
                   sen_model,
                   label='LeafElement')
        if rain_eval:
            if rain_eval.value.rain.mean() > 0:
                g, nb = disperse(g,
                                 emitter,
                                 transporter,
                                 "septoria",
                                 label='LeafElement')
                for inspector in inspectors.itervalues():
                    inspector.update_du_variables(g)
                wash(g,
                     washor,
                     rain_eval.value.rain.mean(),
                     label='LeafElement')
                # Save outputs after washing
                infection_controler.control_position(g)
                for inspector in inspectors.itervalues():
                    inspector.update_du_variables(g)
                    inspector.update_green_area(g)
                    inspector.update_healthy_area(g)
            else:
                for inspector in inspectors.itervalues():
                    inspector.nb_dus += [0, 0]
                    inspector.nb_dus_on_green += [0, 0]
                    inspector.nb_dus_on_healthy += [0, 0]
                    inspector.update_green_area(g)
                    inspector.update_healthy_area(g)
        else:
            for inspector in inspectors.itervalues():
                inspector.nb_dus += [0, 0]
                inspector.nb_dus_on_green += [0, 0]
                inspector.nb_dus_on_healthy += [0, 0]
                inspector.update_green_area(g)
                inspector.update_healthy_area(g)

        for inspector in inspectors.itervalues():
            inspector.compute_nb_infections(g)

        if wheat_eval:
            update_plot(g)
            # scene = plot3d(g)
            # index = i/24
            # if index < 10 :
            # image_name='./images_septo2/image0000%d.png' % index
            # elif index < 100 :
            # image_name='./images_septo2/image000%d.png' % index
            # elif index < 1000 :
            # image_name='./images_septo2/image00%d.png' % index
            # elif index < 10000 :
            # image_name='./images_septo2/image0%d.png' % index
            # else :
            # image_name='./images_septo/image%d.png' % index
            # save_image(scene, image_name=image_name)

    # Tout stocker dans un dataframe avec les dates en index
    outs = {
        'nb_dus': inspectors[1].nb_dus[::2],
        'nb_unwashed_dus': inspectors[1].nb_dus[1::2],
        'nb_dus_on_healthy': inspectors[1].nb_dus_on_healthy[1::2],
        'nb_infections': inspectors[1].nb_infections,
        'green_area': inspectors[1].leaf_green_area,
        'healthy_area': inspectors[1].leaf_healthy_area
    }
    outputs = pandas.DataFrame(data=outs, index=dates)
    return outputs
from alinea.alep.wheat import initialize_stand, find_blade_id, find_leaf_ids
from alinea.astk.plant_interface import grow_canopy
from alinea.alep.architecture import set_properties, update_healthy_area, get_leaves

# Imports for septoria
from alinea.alep.protocol import *
from alinea.alep.disease_operation import generate_stock_du
#from alinea.alep.epidemics import SeptoriaSepto3D as septo

# imported last to overwrite old weather class
from alinea.astk.Weather import Weather

meteo_path = shared_data(alinea.septo3d, 'meteo00-01.txt')
# Read weather and adapt it to septoria (add wetness)
#weather = get_septoria_weather(data_file=meteo_path, sep='\t')
weather = Weather(data_file=meteo_path)
seq = pandas.date_range(start="2000-10-01 01:00:00",
                        end="2001-07-01 01:00:00",
                        freq='H')
# Choose dates of simulation and initialize the value of date

#start_date = datetime(2000, 10, 1, 1, 00, 00)
#end_date = datetime(2001, 07, 01, 00, 00)

# Initialize a wheat canopy
# g, wheat, domain_area, domain = initialize_stand(age=0., length=0.5,
# width=0.5, sowing_density=250,
# plant_density=250, inter_row=0.12, seed=1)

g, wheat, domain_area, domain = initialize_stand(age=0.,
                                                 length=0.1,
示例#11
0
def run_simulation():
    # Initialization #####################################################
    # Set the seed of the simulation
    rd.seed(0)
    np.random.seed(0)

    # Read weather and adapt it to septoria (add wetness)
    meteo_path = shared_data(alinea.septo3d, 'meteo98-99.txt')
    weather = Weather(data_file=meteo_path)
    weather.check(varnames=['wetness'], models={'wetness':wetness_rapilly})
    seq = pandas.date_range(start = "1998-10-01 01:00:00",
                            end = "1999-07-01 01:00:00", 
                            freq='H')

    # Initialize a wheat canopy
    g, wheat, domain_area, domain = initialize_stand(age=0., length=0.1, 
                                                    width=0.2, sowing_density=150,
                                                    plant_density=150, inter_row=0.12, 
                                                    seed=8)

    # Initialize the models for septoria
    # septoria = new_septoria(senescence_treshold=senescence_treshold)
    septoria = plugin_septoria()
    inoculator = RandomInoculation()
    growth_controler = NoPriorityGrowthControl()
    infection_controler = BiotrophDUPositionModel()
    sen_model = WheatSeptoriaPositionedSenescence(g, label='LeafElement')
    emitter = SeptoriaRainEmission(domain_area=domain_area)
    transporter = Septo3DSplash(reference_surface=domain_area)
    washor = RapillyWashing()

    # Define the schedule of calls for each model
    every_h = time_filter(seq, delay=1)
    every_24h = time_filter(seq, delay=24)
    every_rain = rain_filter(seq, weather)
    weather_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    wheat_timing = IterWithDelays(*time_control(seq, every_24h, weather.data))
    septo_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    rain_timing = IterWithDelays(*time_control(seq, every_rain, weather.data))
    
    # Call leaf inspectors for target blades (top 3)
    inspectors = {}
    # for rank in range(1,3):
        # inspectors[rank] = LeafInspector(g, blade_id=find_blade_id(g, leaf_rank = rank, only_visible=False))
    inspectors[1] = LeafInspector(g, blade_id=96)
    # inspectors[2] = LeafInspector(g, blade_id=88)
    # inspectors[3] = LeafInspector(g, blade_id=80)
    dates = []
    # Simulation #########################################################
    for i,controls in enumerate(zip(weather_timing, wheat_timing, 
                                    septo_timing, rain_timing)):
        weather_eval, wheat_eval, septo_eval, rain_eval = controls
        
        # Update date
        date = weather_eval.value.index[0]
        dates.append(date)
        
        # Get weather for date and add it as properties on leaves
        if weather_eval:
            set_properties(g,label = 'LeafElement',
                           temp = weather_eval.value.temperature_air[0],
                           wetness = weather_eval.value.wetness[0],
                           relative_humidity = weather_eval.value.relative_humidity[0],
                           wind_speed = weather_eval.value.wind_speed[0])
        if rain_eval:
            set_properties(g,label = 'LeafElement',
                           rain_intensity = rain_eval.value.rain.mean(),
                           rain_duration = len(rain_eval.value.rain) if rain_eval.value.rain.sum() > 0 else 0.)

        # Grow wheat canopy
        if wheat_eval:
            print(date)
            g,_ = grow_canopy(g, wheat, wheat_eval.value)
            # Note : The position of senescence goes back to its initial value after
            # a while for undetermined reason
            # --> temporary hack for keeping senescence position low when it is over
            positions = g.property('position_senescence')
            are_green = g.property('is_green')
            areas = g.property('area')
            senesced_areas = g.property('senesced_area')
            leaves = get_leaves(g, label = 'LeafElement')
            vids = [leaf for leaf in leaves if leaf in g.property('geometry')]
            positions.update({vid:(0 if (positions[vid]==1 and not are_green[vid]) or
                                        (positions[vid]>0 and round(areas[vid],5)==round(senesced_areas[vid],5))
                                        else positions[vid]) for vid in vids})
            
        # Develop disease
        if septo_eval:
            sen_model.find_senescent_lesions(g, label = 'LeafElement')
            update_healthy_area(g, label = 'LeafElement')
            if rain_eval and i <= 500:
                # Refill pool of initial inoculum to simulate differed availability
                dispersal_units = generate_stock_du(nb_dus=rd.randint(0,5), disease=septoria)
                initiate(g, dispersal_units, inoculator)
            infect(g, septo_eval.dt, infection_controler, label='LeafElement')
            update(g, septo_eval.dt, growth_controler, sen_model, label='LeafElement')
        if rain_eval:
            if rain_eval.value.rain.mean()>0:
                g, nb = disperse(g, emitter, transporter, "septoria", label='LeafElement')
                for inspector in inspectors.itervalues():
                    inspector.update_du_variables(g)
                wash(g, washor, rain_eval.value.rain.mean(), label='LeafElement')
                # Save outputs after washing
                infection_controler.control_position(g)
                for inspector in inspectors.itervalues():
                    inspector.update_du_variables(g)
                    inspector.update_green_area(g)
                    inspector.update_healthy_area(g)
            else:
                for inspector in inspectors.itervalues():
                    inspector.nb_dus += [0, 0]
                    inspector.nb_dus_on_green += [0, 0]
                    inspector.nb_dus_on_healthy += [0, 0]
                    inspector.update_green_area(g)
                    inspector.update_healthy_area(g)
        else:
            for inspector in inspectors.itervalues():
                inspector.nb_dus += [0, 0]
                inspector.nb_dus_on_green += [0, 0]
                inspector.nb_dus_on_healthy += [0, 0]
                inspector.update_green_area(g)
                inspector.update_healthy_area(g)
        
        for inspector in inspectors.itervalues():
            inspector.compute_nb_infections(g)
        
        if wheat_eval:
            update_plot(g)
            # scene = plot3d(g)
            # index = i/24
            # if index < 10 :
                # image_name='./images_septo2/image0000%d.png' % index
            # elif index < 100 :
                # image_name='./images_septo2/image000%d.png' % index
            # elif index < 1000 :
                # image_name='./images_septo2/image00%d.png' % index
            # elif index < 10000 :
                # image_name='./images_septo2/image0%d.png' % index
            # else :
                # image_name='./images_septo/image%d.png' % index
            # save_image(scene, image_name=image_name)
            
    # Tout stocker dans un dataframe avec les dates en index
    outs = {'nb_dus':inspectors[1].nb_dus[::2],
            'nb_unwashed_dus':inspectors[1].nb_dus[1::2],
            'nb_dus_on_healthy':inspectors[1].nb_dus_on_healthy[1::2],
            'nb_infections':inspectors[1].nb_infections,
            'green_area':inspectors[1].leaf_green_area,
            'healthy_area':inspectors[1].leaf_healthy_area}
    outputs = pandas.DataFrame(data=outs, index=dates)
    return outputs
示例#12
0
def run_simulation(start_year, variability=True, **kwds):
    # Set the seed of the simulation
    rd.seed(0)
    np.random.seed(0)

    # Read weather and adapt it to septoria (add wetness)
    weather_file = 'meteo' + str(start_year)[-2:] + '-' + str(start_year +
                                                              1)[-2:] + '.txt'
    meteo_path = shared_data(alinea.septo3d, weather_file)
    weather = Weather(data_file=meteo_path)
    weather.check(varnames=['wetness'], models={'wetness': wetness_rapilly})
    seq = pandas.date_range(start=str(start_year) + "-10-01 01:00:00",
                            end=str(start_year + 1) + "-07-01 01:00:00",
                            freq='H')

    # Initialize a wheat canopy
    g, wheat, domain_area, domain = initialize_stand(age=0.,
                                                     length=0.1,
                                                     width=0.2,
                                                     sowing_density=150,
                                                     plant_density=150,
                                                     inter_row=0.12,
                                                     seed=3)

    # Initialize the models for septoria
    if 'alinea.alep.septoria_age_physio' in sys.modules:
        del (sys.modules['alinea.alep.septoria_age_physio'])
    if variability == True:
        septoria = variable_septoria(**kwds)
    else:
        septoria = plugin_septoria(model="septoria_age_physio")
    DU = septoria.dispersal_unit()
    inoculator = RandomInoculation()
    growth_controler = NoPriorityGrowthControl()
    infection_controler = BiotrophDUPositionModel()
    sen_model = WheatSeptoriaPositionedSenescence(g, label='LeafElement')
    emitter = SeptoriaRainEmission(domain_area=domain_area)
    transporter = Septo3DSplash(reference_surface=domain_area)
    washor = RapillyWashing()

    # Define the schedule of calls for each model
    every_h = time_filter(seq, delay=1)
    every_24h = time_filter(seq, delay=24)
    every_rain = rain_filter(seq, weather)
    weather_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    wheat_timing = IterWithDelays(*time_control(seq, every_24h, weather.data))
    septo_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    rain_timing = IterWithDelays(*time_control(seq, every_rain, weather.data))

    # Call leaf inspectors for target blades (top 3)
    inspectors = {}
    first_blade = 80
    ind = 4.
    for blade in range(first_blade, 104, 8):
        ind -= 1
        inspectors[ind] = LeafInspector(g, blade_id=blade)

    # Simulation loop
    for i, controls in enumerate(
            zip(weather_timing, wheat_timing, septo_timing, rain_timing)):
        weather_eval, wheat_eval, septo_eval, rain_eval = controls

        # Update date
        date = weather_eval.value.index[0]

        # Get weather for date and add it as properties on leaves
        if weather_eval:
            set_properties(
                g,
                label='LeafElement',
                temp=weather_eval.value.temperature_air[0],
                wetness=weather_eval.value.wetness[0],
                relative_humidity=weather_eval.value.relative_humidity[0],
                wind_speed=weather_eval.value.wind_speed[0])
        if rain_eval:
            set_properties(g,
                           label='LeafElement',
                           rain_intensity=rain_eval.value.rain.mean(),
                           rain_duration=len(rain_eval.value.rain)
                           if rain_eval.value.rain.sum() > 0 else 0.)

        # Grow wheat canopy
        if wheat_eval:
            print(date)
            g, _ = grow_canopy(g, wheat, wheat_eval.value)
            # Note : The position of senescence goes back to its initial value after
            # a while for undetermined reason
            # --> temporary hack for keeping senescence position low when it is over
            positions = g.property('position_senescence')
            are_green = g.property('is_green')
            leaves = get_leaves(g, label='LeafElement')
            positions.update({
                leaf: (0 if positions[leaf] == 1 and not are_green[leaf] else
                       positions[leaf])
                for leaf in leaves
            })

        # Develop disease
        if septo_eval:
            sen_model.find_senescent_lesions(g, label='LeafElement')
            update_healthy_area(g, label='LeafElement')
            if rain_eval and i <= 500:
                # Refill pool of initial inoculum to simulate differed availability
                if rd.random() < 0.4:
                    dispersal_units = [
                        DU(nb_spores=rd.randint(1, 100), status='emitted')
                        for i in range(rd.randint(0, 3))
                    ]
                    initiate(g, dispersal_units, inoculator)
            infect(g, septo_eval.dt, infection_controler, label='LeafElement')
            update(g,
                   septo_eval.dt,
                   growth_controler,
                   sen_model,
                   label='LeafElement')

        les = g.property('lesions')
        lesions = sum([l for l in les.values()], [])

        print([l.fungus.degree_days_to_chlorosis for l in lesions])

        # if len(lesions)>10:
        # import pdb
        # pdb.set_trace()

        if rain_eval:
            g, nb = disperse(g,
                             emitter,
                             transporter,
                             "septoria",
                             label='LeafElement')
            wash(g, washor, rain_eval.value.rain.mean(), label='LeafElement')

        # Save outputs
        for inspector in inspectors.itervalues():
            inspector.update_variables(g)
            inspector.update_du_variables(g)

        if wheat_eval:
            plot_severity_by_leaf(g)

    return inspectors
示例#13
0
def test_instantiate():
    weather = Weather()
    assert weather.data is None
    path = get_path('meteo00-01.txt')
    weather = Weather(path)
    assert len(weather.data) == 7296
示例#14
0
def test_update(senescence_threshold=330.,
                sen_day=500.,
                model="septoria_exchanging_rings",
                **kwds):
    """ 
    """
    from alinea.alep.wheat import adel_one_leaf_element

    # Read weather and adapt it to septoria (add wetness)
    meteo_path = shared_data(alinea.septo3d, 'meteo00-01.txt')
    weather = Weather(data_file=meteo_path)
    weather.check(varnames=['wetness'], models={'wetness': wetness_rapilly})
    seq = pandas.date_range(start="2000-10-01 01:00:00",
                            end="2000-12-31 01:00:00",
                            freq='H')

    # Generate a wheat MTG
    g = adel_one_leaf_element()
    set_properties(g,
                   label='LeafElement',
                   area=5.,
                   green_area=5.,
                   healthy_area=5.,
                   position_senescence=1,
                   wetness=True,
                   temp=22.,
                   rain_intensity=0.,
                   relative_humidity=90.)

    # Generate one lesion of septoria and distribute it on g
    # septoria = new_septoria(senescence_threshold=senescence_threshold)
    septoria = plugin_septoria(model)
    Lesion = septoria.lesion(**kwds)
    leaf = g.node(10)
    leaf.lesions = [Lesion(nb_spores=1, position=[0.5, 0])]

    # Call model of growth control
    growth_controler = NoPriorityGrowthControl()
    sen_model = WheatSeptoriaPositionedSenescence(g, label='LeafElement')

    #Temp
    emitter = SeptoriaRainEmission(domain_area=0.0004)
    transporter = Septo3DSplash(reference_surface=0.0004)

    # Loop of simulation
    every_h = time_filter(seq, delay=1)
    every_rain = rain_filter(seq, weather)
    septo_timing = IterWithDelays(*time_control(seq, every_h, weather.data))
    rain_timing = IterWithDelays(*time_control(seq, every_rain, weather.data))
    surface = []
    surface_alive = []
    surface_empty = []
    nb_dus = []
    stock_spores = []
    for i, controls in enumerate(zip(septo_timing, rain_timing)):
        septo_eval, rain_eval = controls

        if i == sen_day:
            set_properties(g, label='LeafElement', position_senescence=0)
        if rain_eval:
            set_properties(g,
                           label='LeafElement',
                           rain_intensity=rain_eval.value.rain.mean(),
                           rain_duration=len(rain_eval.value.rain)
                           if rain_eval.value.rain.sum() > 0 else 0.)

        # Update healthy area
        sen_model.find_senescent_lesions(g, label='LeafElement')
        update_healthy_area(g, label='LeafElement')

        # Update
        update(g,
               septo_eval.dt,
               growth_controler,
               senescence_model=sen_model,
               label='LeafElement')

        if rain_eval:
            g, nb = disperse(g,
                             emitter,
                             transporter,
                             "septoria",
                             label='LeafElement')
        else:
            nb = 0.
        nb_dus.append(nb)

        # Check that the lesion is in the right status and has the right surface
        lesion = g.property('lesions')
        if lesion:
            assert sum(len(l) for l in lesion.itervalues()) == 1
            l = lesion.values()[0][0]
            surface.append(l.surface)
            surface_alive.append(l.surface_alive)
            surface_empty.append(l.surface_empty)
            stock_spores.append(l.stock_spores)
            # if i==299:
            # import pdb
            # pdb.set_trace()
            l.compute_all_surfaces()
            f = l.fungus
            print('lesion surface: %f' % round(l.surface, 6))

    return g, surface, surface_alive, surface_empty, nb_dus, stock_spores
示例#15
0
文件: mango.py 项目: pradal/astk
    data = pandas.read_csv(data_file, parse_dates=['Date'],
                               delimiter = ';',
                               usecols=['Date','Rayonnement','Temperature_Air','HR'], dayfirst=True)
    data = data.rename(columns={'Date':'date',
                                 'Rayonnement':'global_radiation',
                                 'Temperature_Air':'temperature_air',
                                 'HR':'relative_humidity'})
    # convert J.cm2.h-1 to W.m-2
    data['global_radiation'] *= (10000. / 3600)
    return data
  
# a strange mango tree
mango = pgl.Scene(data('generated_mtg/fruitstructure.bgeom'))  
# meteo
weather = Weather(data('environment/rayostpierre2002.csv'), reader=reader, timezone='Indian/Reunion', localisation={'city':'Saint-Pierre', 'latitude':-21.32, 'longitude':55.5})



# converter for azimuth elevation 
# az,el are expected in degrees, in the North-clocwise convention
# In the scene, positive rotations are counter-clockwise
#north is the angle (degrees, positive counter_clockwise) between X+ and North
def azel2vect(az, el, north=0):
  azimuth = radians(north - az)
  zenith = radians(90 - el)
  v = -pgl.Vector3(pgl.Vector3.Spherical( 1., azimuth, zenith ) )
  v.normalize()
  return v

for one_day in weather.date_range_index('2002-12-02','2002-12-15'):