예제 #1
0
def test_emission(nlesions=100, nplants=1, nsect=1, age=1500., only_MS=True):
    nplants = 1
    nsect = 1
    age = 1500.
    only_MS = True

    # Create wheat
    g, adel = tremie12_main_stem(nplants=nplants,
                                 nsect=nsect,
                                 age=age,
                                 only_MS=only_MS)

    # Deposit emitting lesion on source leaf
    septoria = plugin_septoria()
    source_leaf = get_source_leaf(g)
    lesion = septoria.lesion()
    lesion.surfaces_spo = numpy.array([0.05, 0., 0.])
    lesion.status = 3
    lesions = [lesion for i in range(nlesions)]
    initiation_model = InoculationLowerLeaves()
    initiation_model.allocate(g, lesions, 'LeafElement')

    emitter = PopDropsEmission(domain=adel.domain)
    DU = emitter.get_dispersal_units(g, "septoria", 'LeafElement',
                                     weather_data)
    return DU
예제 #2
0
def test_emission(nlesions = 100, nplants=1, nsect = 1, age = 1500., only_MS = True):
    nplants = 1
    nsect = 1
    age = 1500.
    only_MS = True
    
    # Create wheat
    g, adel = tremie12_main_stem(nplants = nplants, nsect = nsect, age = age, only_MS = only_MS)    

    # Deposit emitting lesion on source leaf 
    septoria = plugin_septoria()
    source_leaf = get_source_leaf(g)
    lesion = septoria.lesion()
    lesion.surfaces_spo = numpy.array([0.05, 0., 0.])
    lesion.status = 3
    lesions = [lesion for i in range(nlesions)]
    initiation_model = InoculationLowerLeaves()
    initiation_model.allocate(g, lesions, 'LeafElement')

    emitter = PopDropsEmission(domain=adel.domain)
    DU = emitter.get_dispersal_units(g, "septoria", 'LeafElement', weather_data)
    return DU
예제 #3
0
# 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
# (Here the value of the leaf is known but it changes with another initialize_stand)
source_leaf = g.node(21943)

# Initialize the models for septoria
septoria = plugin_septoria()
inoculator = RandomInoculation()
growth_controler = NoPriorityGrowthControl()
infection_controler = BiotrophDUPositionModel()
sen_model = WheatSeptoriaPositionedSenescence(g, label='LeafElement')
emitter = SeptoriaRainEmission(domain_area=domain_area)
transporter = SeptoriaRainDispersal()
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))
예제 #4
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
예제 #5
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
예제 #6
0
plt.ion()

# Imports for wheat
from alinea.alep.wheat import adel_one_leaf, initialize_stand
from alinea.alep.architecture import set_properties, update_healthy_area
from alinea.astk.plant_interface import grow_canopy

# Imports for septoria
from alinea.alep.protocol import *
from alinea.alep.septo3d_v2 import plugin_septoria
from alinea.popdrops.alep_interface import PopDropsEmission, PopDropsTransport
from alinea.alep.growth_control import PriorityGrowthControl
from alinea.alep.infection_control import BiotrophDUPositionModel
from alinea.alep.disease_outputs import SeptoRecorder
from alinea.alep.disease_outputs import plot_severity_by_leaf
septoria = plugin_septoria()

# Septo 3D
from alinea.septo3d.cycle.alep_objects import Septo3DFungus
s3d_fungus = Septo3DFungus()

def example_one_leaf(fungus = septoria,
                     nb_dus=10,
                     group_dus = False,
                     infection_controler = BiotrophDUPositionModel(),
                     growth_controler = PriorityGrowthControl(),
                     nb_steps = 1000, 
                     leaf_area = None,
                     eradicant = 0.,
                     protectant = 0.):
    # Initiate wheat MTG with one leaf and good conditions for disease
예제 #7
0
def run_simulation_septoria():
    # Initialization #####################################################
    # Set the seed of the simulation
    rd.seed(0)
    np.random.seed(0)

    # 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)
    date = None

    # Read weather and adapt it to septoria (add wetness)
    weather = get_septoria_weather(data_file='meteo01.csv')

    # 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)

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

    # Define the schedule of calls for each model
    nb_steps = len(pandas.date_range(start_date, end_date, freq='H'))
    weather_timing = TimeControl(delay=1, steps=nb_steps)
    wheat_timing = TimeControl(delay=24,
                               steps=nb_steps,
                               model=wheat,
                               weather=weather,
                               start_date=start_date)
    septo_timing = TimeControl(delay=1, steps=nb_steps)
    timer = TimeControler(weather=weather_timing,
                          wheat=wheat_timing,
                          disease=septo_timing)

    # 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)
    inspectors[4] = LeafInspector(g, blade_id=72)
    dates = []
    # Simulation #########################################################
    for t in timer:
        # print(timer.numiter)
        # Update date
        date = (weather.next_date(t['weather'].dt, date)
                if date != None else start_date)
        dates.append(date)
        print(date)

        # Get weather for date and add it as properties on leaves
        _, data = weather.get_weather(t['weather'].dt, date)
        set_properties(g,
                       label='LeafElement',
                       wetness=data.wetness.values[0],
                       temp=data.temperature_air.values[0],
                       rain_intensity=data.rain.values[0],
                       rain_duration=data.rain_duration.values[0],
                       relative_humidity=data.relative_humidity.values[0],
                       wind_speed=data.wind_speed.values[0])

        # Grow wheat canopy
        grow_canopy(g, wheat, t['wheat'])
        update_healthy_area(g, label='LeafElement')
        # 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')
        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] else
                  positions[vid])
            for vid in vids
        })

        # Develop disease
        if data.dispersal_event.values[
                0] == True and timer.numiter >= 1000 and timer.numiter <= 2000:
            # Refill pool of initial inoculum to simulate differed availability
            dispersal_units = generate_stock_du(nb_dus=10, disease=septoria)
            initiate(g, dispersal_units, inoculator)

        infect(g, t['disease'].dt, infection_controler, label='LeafElement')
        update(g,
               t['disease'].dt,
               growth_controler,
               sen_model,
               label='LeafElement')
        for inspector in inspectors.itervalues():
            inspector.compute_severity(g)
            inspector.update_disease_area(g)
            inspector.update_green_area(g)
            inspector.update_area(g)
        if data.dispersal_event.values[0] == True:
            disperse(g, emitter, transporter, "septoria", label='LeafElement')
            wash(g, washor, data.rain.values[0], label='LeafElement')

        # if timer.numiter%24 == 0:
        # update_plot(g)

    # Tout stocker dans un dataframe avec les dates en index
    outputs = {}
    for id, inspector in inspectors.iteritems():
        outs = {
            'severity': inspectors[id].severity,
            'disease_area': inspectors[id].leaf_disease_area,
            'green_area': inspectors[id].leaf_green_area,
            'total_area': inspectors[id].leaf_area
        }
        outputs[id] = pandas.DataFrame(data=outs, index=dates)
    return outputs
예제 #8
0
def run_simulation_septoria():
    # Initialization #####################################################
    # Set the seed of the simulation
    rd.seed(0)
    np.random.seed(0)

    # 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)
    date = None

    # Read weather and adapt it to septoria (add wetness)
    weather = get_septoria_weather(data_file='meteo01.csv')

    # 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)

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

    # Define the schedule of calls for each model
    nb_steps = len(pandas.date_range(start_date, end_date, freq='H'))
    weather_timing = TimeControl(delay=1, steps=nb_steps)
    wheat_timing = TimeControl(delay=24, steps=nb_steps, model=wheat, weather=weather, start_date=start_date)
    septo_timing = TimeControl(delay=1, steps=nb_steps)
    timer = TimeControler(weather=weather_timing, wheat=wheat_timing, disease = septo_timing)

    # 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)
    inspectors[4] = LeafInspector(g, blade_id=72)
    dates = []
    # Simulation #########################################################
    for t in timer:
        # print(timer.numiter)
        # Update date
        date = (weather.next_date(t['weather'].dt, date) if date!=None else start_date)
        dates.append(date)
        print(date)
        
        # Get weather for date and add it as properties on leaves
        _, data = weather.get_weather(t['weather'].dt, date)
        set_properties(g,label = 'LeafElement',
                        wetness = data.wetness.values[0],
                        temp = data.temperature_air.values[0],
                        rain_intensity = data.rain.values[0],
                        rain_duration = data.rain_duration.values[0],
                        relative_humidity = data.relative_humidity.values[0],
                        wind_speed = data.wind_speed.values[0])

        # Grow wheat canopy
        grow_canopy(g,wheat,t['wheat'])
        update_healthy_area(g, label = 'LeafElement')
        # 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')
        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] else positions[vid]) 
                          for vid in vids})
        
        # Develop disease
        if data.dispersal_event.values[0]==True and timer.numiter >= 1000 and timer.numiter <= 2000:
            # Refill pool of initial inoculum to simulate differed availability
            dispersal_units = generate_stock_du(nb_dus=10, disease=septoria)
            initiate(g, dispersal_units, inoculator)
          
        infect(g, t['disease'].dt, infection_controler, label='LeafElement')
        update(g, t['disease'].dt, growth_controler, sen_model, label='LeafElement')
        for inspector in inspectors.itervalues():
            inspector.compute_severity(g)
            inspector.update_disease_area(g)
            inspector.update_green_area(g)
            inspector.update_area(g)
        if data.dispersal_event.values[0]==True:
            disperse(g, emitter, transporter, "septoria", label='LeafElement')
            wash(g, washor, data.rain.values[0], label='LeafElement')

        # if timer.numiter%24 == 0:
            # update_plot(g)
            
    # Tout stocker dans un dataframe avec les dates en index
    outputs = {}
    for id, inspector in inspectors.iteritems():
        outs = {'severity':inspectors[id].severity,
                'disease_area': inspectors[id].leaf_disease_area,
                'green_area': inspectors[id].leaf_green_area,
                'total_area':inspectors[id].leaf_area}
        outputs[id] = pandas.DataFrame(data=outs, index=dates)
    return outputs
예제 #9
0
def example_surface(nb_steps = 4500, density_lesions = 1, with_compet = False,
                    leaf_area = 1., senescence_date = 5000, 
                    return_lesion=False,**kwds):
    weather = read_weather_year(2012)
    df = weather.data
    df = df.reset_index()
    df = df[df['degree_days']>0]
    df['date'] = df['datetime']
    g, leaf = get_g_and_one_leaf()
    leaf.area = leaf_area
    leaf.green_area = leaf_area
#    leaf.green_area = leaf_area-3
    septoria = plugin_septoria()
    lesion = septoria.lesion(mutable = False, group_dus = True, **kwds)
    nb_lesions = density_lesions * leaf_area
    lesion.set_position([[1] for i in range(int(nb_lesions))])
#    lesion.set_position([[1] for i in range(int(nb_lesions/2))]+[[10.] for i in range(int(nb_lesions/2))])
    leaf.lesions = [lesion]
    growth_controler = SeptoRustCompetition()
#    growth_controler = NoPriorityGrowthControl()
    surfs = []
    surfs_inc = []
    surfs_chlo = []
    surfs_nec = []
    surfs_spo = []
    surfs_empty = []
    surfs_sen = []
    tt = []
    cum_tt = 0.
    count = 0.
    for i, row in df.iterrows():
        if count == senescence_date:
#            leaf.green_area = 0.
            leaf.senesced_length = 3.
        if count < nb_steps:
            count += 1
            leaf.temperature_sequence = [row['temperature_air']]
            leaf.relative_humidity_sequence = [row['relative_humidity']]
            lesion.update(leaf = leaf)
            if with_compet == False:
                lesion.control_growth(growth_offer = lesion.growth_demand)
            else:
                growth_controler.control(g)
            surfs.append(lesion.surface)
            surfs_inc.append(lesion.surface_inc)
            surfs_chlo.append(lesion.surface_chlo)
            surfs_nec.append(lesion.surface_nec)
            surfs_spo.append(lesion.surface_spo)
            surfs_empty.append(lesion.surface_empty)
            surfs_sen.append(lesion.surface_senescent)
            cum_tt += lesion.ddday
            tt.append(cum_tt)

    fig, ax = plt.subplots()
    inc = (141/255., 200/255., 2/255.)
    chlo = (1., 220/255., 63/255.)
    nec = (190/255., 128/255., 60/255.)
    spo = (228/255., 108/255., 10/255.)
    ax.plot(tt, surfs, 'b', linewidth=2)
    ax.plot(tt, surfs_inc, color=inc, linewidth=2)
    ax.plot(tt, surfs_chlo, color=chlo, linewidth=2)
    ax.plot(tt, surfs_nec, color=nec, linewidth=2)
    ax.plot(tt, surfs_spo, color=spo, linewidth=2)
    ax.plot(tt, surfs_sen, 'k')
#    ax.plot([tt[0], tt[-1]], [leaf_area, leaf_area], 'k--')
    ax.set_xlabel("Thermal time (Teff)", fontsize = 20)
    ax.set_ylabel("Surface d'une lesion (cm2)", fontsize = 20)
    ax.set_ylim([0,0.31*density_lesions*leaf_area])
    if sum(surfs_empty)>0:
        ax.plot(tt, surfs_empty, 'k--')
        labels = ['Total', 'Incubation', 'Chlorose', 'Necrose', 'Sporulant', 'Vide']
    else:
        labels = ['Total', 'Incubation', 'Chlorose', 'Necrose', 'Sporulant']
    ax.legend(labels, loc = 'best')
    ax.tick_params(axis='both', labelsize=18)
    if return_lesion==True:
        return lesion
예제 #10
0
def scenario_compet(nb_ddays = 1500, leaf_area = 22., 
                    deposits=[50,50,200], **kwds):
    weather = read_weather_year(2012)
    df = weather.data
    df = df.reset_index()
    df = df[df['degree_days']>1200]
    g, leaf = get_g_and_one_leaf()
    leaf.area = leaf_area
    leaf.green_area = leaf_area
    leaf.length = 1.
    leaf.senesced_length = 0.
    septoria = plugin_septoria()
    lesion = septoria.lesion(mutable = False, group_dus = True, **kwds)
    nb_lesions_init = deposits[0]
    lesion.set_position([[np.random.random()] for i in range(int(nb_lesions_init))])
    leaf.lesions = [lesion]
    growth_controler = SeptoRustCompetition()
#    growth_controler = NoPriorityGrowthControl()
    severity = []
    tot_severity = []
    severity_inc = []
    severity_chlo = []
    severity_nec = []
    severity_spo = []
    nb_lesions = []
    green_area = []
    tt = []
    count = 0
    for i, row in df.iterrows():
         if row['degree_days'] < 1060+nb_ddays:
            leaf.temperature_sequence = [row['temperature_air']]
            leaf.relative_humidity_sequence = [row['relative_humidity']]
            leaf.green_area = leaf_area - logistic(row['degree_days'], Kmax=leaf_area)
            green_area.append(leaf.green_area*100./leaf.area)
            leaf.senesced_length = logistic(row['degree_days'], Kmax=leaf.length)
            if row['degree_days'] >= 1160 and count == 0:
                count += 1
                nb_new_les = deposits[1]             
                new_les = septoria.lesion(mutable = False, group_dus = True, **kwds)
                new_les.set_position([[np.random.random()] for i in range(int(nb_new_les))])
                leaf.lesions.append(new_les)
            if row['degree_days'] >= 1400 and count == 1:
                count += 1
                nb_new_les = deposits[2]                
                new_les = septoria.lesion(mutable = False, group_dus = True, **kwds)
                new_les.set_position([[np.random.random()] for i in range(int(nb_new_les))])
                leaf.lesions.append(new_les)
            for lesion in leaf.lesions:
                lesion.update(leaf = leaf)
            growth_controler.control(g)
            surfs = sum([(l.surface_spo + l.surface_empty) for l in leaf.lesions])
            tot_surfs = sum([(l.surface) for l in leaf.lesions])
            inc_surfs = sum([l.surface_inc for l in leaf.lesions])
            chlo_surfs = sum([l.surface_chlo for l in leaf.lesions])
            nec_surfs = sum([l.surface_nec for l in leaf.lesions])
            spo_surfs = sum([l.surface_spo for l in leaf.lesions])
            severity.append(surfs*100./leaf.area)
            tot_severity.append(tot_surfs*100./leaf.area)
            severity_inc.append(inc_surfs*100./leaf.area)
            severity_chlo.append(chlo_surfs*100./leaf.area)
            severity_nec.append(nec_surfs*100./leaf.area)
            severity_spo.append(spo_surfs*100./leaf.area)
            nb_lesions.append(sum([l.nb_lesions for l in leaf.lesions]))
            tt.append(row['degree_days'])

    fig, ax = plt.subplots()
    ax.plot(tt, tot_severity, 'b')
    ax.plot(tt, severity_inc, 'g')
    ax.plot(tt, severity_chlo, 'm')
    ax.plot(tt, severity_nec, 'k')
    ax.plot(tt, severity_spo, 'r')
#    ax.plot(tt, severity, 'm')
#    ax.plot(tt, nb_lesions, 'b--')
    ax.plot(tt, green_area, 'g')
    ax.set_ylim([0,100])
    ax.set_xlabel("Thermal time (Teff)", fontsize = 18)
    ax.set_ylabel("Severity", fontsize = 18)
    labels = ['total severity', 'severity', 'nb_lesions']
    ax.legend(labels, loc = 'best')
예제 #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 example_surface(nb_steps=4500,
                    density_lesions=1,
                    with_compet=False,
                    leaf_area=1.,
                    senescence_date=5000,
                    return_lesion=False,
                    **kwds):
    weather = read_weather_year(2012)
    df = weather.data
    df = df.reset_index()
    df = df[df['degree_days'] > 0]
    df['date'] = df['datetime']
    g, leaf = get_g_and_one_leaf()
    leaf.area = leaf_area
    leaf.green_area = leaf_area
    #    leaf.green_area = leaf_area-3
    septoria = plugin_septoria()
    lesion = septoria.lesion(mutable=False, group_dus=True, **kwds)
    nb_lesions = density_lesions * leaf_area
    lesion.set_position([[1] for i in range(int(nb_lesions))])
    #    lesion.set_position([[1] for i in range(int(nb_lesions/2))]+[[10.] for i in range(int(nb_lesions/2))])
    leaf.lesions = [lesion]
    growth_controler = SeptoRustCompetition()
    #    growth_controler = NoPriorityGrowthControl()
    surfs = []
    surfs_inc = []
    surfs_chlo = []
    surfs_nec = []
    surfs_spo = []
    surfs_empty = []
    surfs_sen = []
    tt = []
    cum_tt = 0.
    count = 0.
    for i, row in df.iterrows():
        if count == senescence_date:
            #            leaf.green_area = 0.
            leaf.senesced_length = 3.
        if count < nb_steps:
            count += 1
            leaf.temperature_sequence = [row['temperature_air']]
            leaf.relative_humidity_sequence = [row['relative_humidity']]
            lesion.update(leaf=leaf)
            if with_compet == False:
                lesion.control_growth(growth_offer=lesion.growth_demand)
            else:
                growth_controler.control(g)
            surfs.append(lesion.surface)
            surfs_inc.append(lesion.surface_inc)
            surfs_chlo.append(lesion.surface_chlo)
            surfs_nec.append(lesion.surface_nec)
            surfs_spo.append(lesion.surface_spo)
            surfs_empty.append(lesion.surface_empty)
            surfs_sen.append(lesion.surface_senescent)
            cum_tt += lesion.ddday
            tt.append(cum_tt)

    fig, ax = plt.subplots()
    inc = (141 / 255., 200 / 255., 2 / 255.)
    chlo = (1., 220 / 255., 63 / 255.)
    nec = (190 / 255., 128 / 255., 60 / 255.)
    spo = (228 / 255., 108 / 255., 10 / 255.)
    ax.plot(tt, surfs, 'b', linewidth=2)
    ax.plot(tt, surfs_inc, color=inc, linewidth=2)
    ax.plot(tt, surfs_chlo, color=chlo, linewidth=2)
    ax.plot(tt, surfs_nec, color=nec, linewidth=2)
    ax.plot(tt, surfs_spo, color=spo, linewidth=2)
    ax.plot(tt, surfs_sen, 'k')
    #    ax.plot([tt[0], tt[-1]], [leaf_area, leaf_area], 'k--')
    ax.set_xlabel("Thermal time (Teff)", fontsize=20)
    ax.set_ylabel("Surface d'une lesion (cm2)", fontsize=20)
    ax.set_ylim([0, 0.31 * density_lesions * leaf_area])
    if sum(surfs_empty) > 0:
        ax.plot(tt, surfs_empty, 'k--')
        labels = [
            'Total', 'Incubation', 'Chlorose', 'Necrose', 'Sporulant', 'Vide'
        ]
    else:
        labels = ['Total', 'Incubation', 'Chlorose', 'Necrose', 'Sporulant']
    ax.legend(labels, loc='best')
    ax.tick_params(axis='both', labelsize=18)
    if return_lesion == True:
        return lesion
예제 #13
0
def scenario_compet(nb_ddays=1500,
                    leaf_area=22.,
                    deposits=[50, 50, 200],
                    **kwds):
    weather = read_weather_year(2012)
    df = weather.data
    df = df.reset_index()
    df = df[df['degree_days'] > 1200]
    g, leaf = get_g_and_one_leaf()
    leaf.area = leaf_area
    leaf.green_area = leaf_area
    leaf.length = 1.
    leaf.senesced_length = 0.
    septoria = plugin_septoria()
    lesion = septoria.lesion(mutable=False, group_dus=True, **kwds)
    nb_lesions_init = deposits[0]
    lesion.set_position([[np.random.random()]
                         for i in range(int(nb_lesions_init))])
    leaf.lesions = [lesion]
    growth_controler = SeptoRustCompetition()
    #    growth_controler = NoPriorityGrowthControl()
    severity = []
    tot_severity = []
    severity_inc = []
    severity_chlo = []
    severity_nec = []
    severity_spo = []
    nb_lesions = []
    green_area = []
    tt = []
    count = 0
    for i, row in df.iterrows():
        if row['degree_days'] < 1060 + nb_ddays:
            leaf.temperature_sequence = [row['temperature_air']]
            leaf.relative_humidity_sequence = [row['relative_humidity']]
            leaf.green_area = leaf_area - logistic(row['degree_days'],
                                                   Kmax=leaf_area)
            green_area.append(leaf.green_area * 100. / leaf.area)
            leaf.senesced_length = logistic(row['degree_days'],
                                            Kmax=leaf.length)
            if row['degree_days'] >= 1160 and count == 0:
                count += 1
                nb_new_les = deposits[1]
                new_les = septoria.lesion(mutable=False,
                                          group_dus=True,
                                          **kwds)
                new_les.set_position([[np.random.random()]
                                      for i in range(int(nb_new_les))])
                leaf.lesions.append(new_les)
            if row['degree_days'] >= 1400 and count == 1:
                count += 1
                nb_new_les = deposits[2]
                new_les = septoria.lesion(mutable=False,
                                          group_dus=True,
                                          **kwds)
                new_les.set_position([[np.random.random()]
                                      for i in range(int(nb_new_les))])
                leaf.lesions.append(new_les)
            for lesion in leaf.lesions:
                lesion.update(leaf=leaf)
            growth_controler.control(g)
            surfs = sum([(l.surface_spo + l.surface_empty)
                         for l in leaf.lesions])
            tot_surfs = sum([(l.surface) for l in leaf.lesions])
            inc_surfs = sum([l.surface_inc for l in leaf.lesions])
            chlo_surfs = sum([l.surface_chlo for l in leaf.lesions])
            nec_surfs = sum([l.surface_nec for l in leaf.lesions])
            spo_surfs = sum([l.surface_spo for l in leaf.lesions])
            severity.append(surfs * 100. / leaf.area)
            tot_severity.append(tot_surfs * 100. / leaf.area)
            severity_inc.append(inc_surfs * 100. / leaf.area)
            severity_chlo.append(chlo_surfs * 100. / leaf.area)
            severity_nec.append(nec_surfs * 100. / leaf.area)
            severity_spo.append(spo_surfs * 100. / leaf.area)
            nb_lesions.append(sum([l.nb_lesions for l in leaf.lesions]))
            tt.append(row['degree_days'])

    fig, ax = plt.subplots()
    ax.plot(tt, tot_severity, 'b')
    ax.plot(tt, severity_inc, 'g')
    ax.plot(tt, severity_chlo, 'm')
    ax.plot(tt, severity_nec, 'k')
    ax.plot(tt, severity_spo, 'r')
    #    ax.plot(tt, severity, 'm')
    #    ax.plot(tt, nb_lesions, 'b--')
    ax.plot(tt, green_area, 'g')
    ax.set_ylim([0, 100])
    ax.set_xlabel("Thermal time (Teff)", fontsize=18)
    ax.set_ylabel("Severity", fontsize=18)
    labels = ['total severity', 'severity', 'nb_lesions']
    ax.legend(labels, loc='best')