def test_infection_impossible_on_senescence(): g = get_small_g() set_properties(g, label='LeafElement', senesced_length=1.) leaves = get_leaves(g) # Individual dispersal unit leaf1 = leaves[0] leaf = g.node(leaf1) brown_rust = BrownRustFungus() du1 = brown_rust.dispersal_unit(mutable=True, group_dus=False) du1.set_position([np.random.random(), np.random.random()]) leaf.dispersal_units = [du1] assert du1.is_active du1.disable() assert du1.is_active == False # Cohort leaf2 = leaves[1] leaf = g.node(leaf2) du2 = brown_rust.dispersal_unit(mutable=True, group_dus=True) du2.set_position([[np.random.random(), np.random.random()] for i in range(20)]) g.node(leaf2).dispersal_units = [du2] assert du2.is_active du2.disable() assert du2.is_active == False
def test_initiate(model="septoria_exchanging_rings"): """ Check if 'initiate' from 'protocol.py' deposits dispersal units on the MTG. Generate a wheat MTG and distribute dispersal units randomly on leaf elements. Check that all the stock of DU is distributed in properties of leaf elements. Parameters ---------- model: model One version of the model of septoria lesion among: 'septoria_exchanging_rings', 'septoria_with_rings', 'septoria_continuous' """ # Generate a wheat MTG g = adel_one_leaf_element() set_properties(g, label='LeafElement', area=5., green_area=5., position_senescence=None) # Generate a stock of septoria dispersal units and distribute it on g nb_initial_dus = 100 distribute_dispersal_units(g, nb_dus=nb_initial_dus, disease_model=model, initiation_model=RandomInoculation(), label='LeafElement') # Check that all the DUs that were in the stock are now instantiated # on leaf elements : dispersal_units = g.property('dispersal_units') nb_dus_on_leaves = sum(len(dus) for dus in dispersal_units.itervalues()) assert nb_dus_on_leaves == nb_initial_dus
def test_update(): """ Check if 'update' from 'protocol.py' provokes the growth of a lesion instantiated on the MTG. """ g = adel_mtg2() set_properties(g, area=20., green_area=20.) septoria = plugin_septoria() SeptoriaDU = septoria.dispersal_unit() stock = [SeptoriaDU(nb_spores=random.randint(1,100), status='emitted') for i in range(100)] inoculator = RandomInoculation() initiate(g, stock, inoculator) controler = NoPriorityGrowthControl() dt = 1 nb_steps = 750 nb_les_inc = numpy.zeros(nb_steps) # nb_les_chlo = numpy.array([0. for i in range(nb_steps)]) # nb_les_nec = numpy.array([0. for i in range(nb_steps)]) nb_les_spo = numpy.zeros(nb_steps) # nb_les_empty = numpy.array([0. for i in range(nb_steps)]) nb_les = 0. for i in range(nb_steps): ts = time.clock() #print('time step %d' % i) update_climate_all(g) #grow(g) update_healthy_area(g, label = 'LeafElement') infect(g, dt) update(g,dt, growth_control_model=controler) # control_growth(g, controler) # Count of lesions : nb_les_inc[i] = count_lesions_in_state(g, state = 0) # nb_les_chlo[i] = count_lesions_in_state(g, state = 1) # nb_les_nec[i] = count_lesions_in_state(g, state = 2) nb_les_spo[i] = count_lesions_in_state(g, state = 3) # nb_les_empty[i] = count_lesions_in_state(g, state = 4) te = time.clock() #print "time ", i, " : ", te-ts # Display results plot(nb_les_inc) plot(nb_les_spo) ylabel('Nombre de lesions dans cet etat sur le MTG') xlabel('Pas de temps de simulation') ylim([0, 120]) # displayer = DisplayLesions() # displayer.print_all_lesions(g) # plot_lesions(g) return g
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 g = adel_one_leaf() set_properties(g, label='LeafElement', wetness=True, temperature_sequence=np.array([22.]), rain_intensity=0., global_efficacy={'eradicant':eradicant, 'protectant':protectant}) if leaf_area is not None: set_properties(g, label='LeafElement', area=leaf_area, green_area=leaf_area) # Initiate disease leaf = g.node(10) dispersal_units = [fungus.dispersal_unit() for i in range(nb_dus)] for du in dispersal_units: du.set_position([random.random() * leaf.length, 0]) if group_dus: pos = [du.position[0] for du in dispersal_units] dispersal_units[0].fungus.group_dus = True dispersal_units[0].set_position(pos) dispersal_units = [dispersal_units[0]] leaf.dispersal_units = dispersal_units # Initiate output recorder recorder = SeptoRecorder(vids=[10], group_dus=group_dus) recorder.record(g,0) # Simulation loop for i in range(nb_steps): # Update wheat healthy area update_healthy_area(g, label = 'LeafElement') # Update dispersal units and lesions infect(g, 1, infection_controler, label='LeafElement') update(g, 1, growth_controler, senescence_model=None, label='LeafElement') # Get outputs recorder.record(g, date=i+1) recorder.get_complete_dataframe() # return g, inspector return g, recorder
def test_infect(model="septoria_exchanging_rings"): """ Check if 'infect' from 'protocol.py' leads to infection by dispersal units on the MTG. Generate a wheat MTG and distribute dispersal units randomly on leaf elements. Run a short loop to compute infection. Check that all the stock of DU caused appearance of a lesion on leaf elements. Parameters ---------- model: model One version of the model of septoria lesion among: 'septoria_exchanging_rings', 'septoria_with_rings', 'septoria_continuous' """ # Generate a wheat MTG g = adel_one_leaf_element() set_properties(g, label='LeafElement', area=5., green_area=5., healthy_area=5., position_senescence=None) # Generate a stock of septoria dispersal units and distribute it on g nb_dus = 100 distribute_dispersal_units(g, nb_dus=nb_dus, disease_model=model, initiation_model=RandomInoculation(), label='LeafElement') # Loop of simulation septo_timing = TimeControl(delay=1, steps=10) timer = TimeControler(disease=septo_timing) for t in timer: # Offer good conditions for at least 10h set_properties(g, label='LeafElement', wetness=True, temp=20.) # Infect infect(g, t['disease'].dt, label='LeafElement') # Check that all the DUs that were in the stock are now lesions on leaf elements lesions = g.property('lesions') nb_lesions_on_leaves = sum(len(l) for l in lesions.itervalues()) assert nb_lesions_on_leaves == nb_dus
def run_dispersal(model=3, position_in_canopy='center', relative_height=2./3, position_on_leaf=0.5, age=1500., seed=3): # Initialize a wheat canopy reconst = EchapReconstructions() adel = reconst.get_reconstruction(name='Tremie13', nplants = 500, nsect = 1) g = adel.setup_canopy(age=age) domain_area = adel.domain_area domain = adel.domain # g, wheat, domain_area, domain = initialize_stand(age=age, length=1, # width=1, sowing_density=250, # plant_density=250, inter_row=0.12, # seed=seed) lai = get_lai(g.property('geometry'), domain_area)/float(1e4) # Define the wind direction wind_direction = (-1, -0.5, 0) set_properties(g,label = 'LeafElement', wind_direction=wind_direction) # Get source leaf and make it emit DUs leaf_id, zmax = get_source_leaf_and_max_height(g, position=position_in_canopy, relative_height=relative_height) leaf = g.node(leaf_id) Fg = DummyFungus(parameters = {'position':[position_on_leaf,0]}) leaf.lesions = [Fg.lesion()] emitter = DummyEmission(domain) if model==1: transporter = Septo3DSplash(reference_surface=domain_area) elif model==2: transporter = PowderyMildewWindDispersal(cid=0.04, a0=45., k_beer=0.65, label='LeafElement') elif model>=3: transporter = SeptoriaRainDispersal() disperse(g, emitter, transporter, "dummy", label='LeafElement') update_plot(g, leaf_source=leaf_id) # Check proportion intercepted : must be low dus = g.property('dispersal_units') nb_deposited = count_dispersal_units(g) max_dus = max([len(du) for du in dus.itervalues()]) min_dus = min([len(du) for du in dus.itervalues()]) return g, lai, zmax, nb_deposited, max_dus, min_dus
def test_infection_impossible_on_senescence(): g = get_small_g() set_properties(g, label = 'LeafElement', senesced_length = 1.) leaves = get_leaves(g) # Individual dispersal unit leaf1 = leaves[0] leaf = g.node(leaf1) brown_rust = BrownRustFungus() du1 = brown_rust.dispersal_unit(mutable = True, group_dus = False) du1.set_position([np.random.random(), np.random.random()]) leaf.dispersal_units = [du1] assert du1.is_active du1.disable_if_senescent(leaf) assert du1.is_active == False # Cohort leaf2 = leaves[1] leaf = g.node(leaf2) du2 = brown_rust.dispersal_unit(mutable = True, group_dus = True) du2.set_position([[np.random.random(), np.random.random()] for i in range(20)]) g.node(leaf2).dispersal_units = [du2] assert du2.is_active du2.disable_if_senescent(leaf) assert du2.is_active == False
def set_properties_node(g, label='LeafElement', dict=None): """ Adapt the function set_properties to receive variable inputs. Parameters ---------- g: MTG MTG representing the canopy label: str Label of the part of the MTG where new properties will be added dict: dict Dictionnary with variable inputs Returns ------- g: MTG Updated MTG with given properties """ return set_properties(g, label=label, **dict)
def set_properties_node(g, label='LeafElement', dict=None): """ Adapt the function set_properties to receive variable inputs. Parameters ---------- g: MTG MTG representing the canopy label: str Label of the part of the MTG where new properties will be added dict: dict Dictionnary with variable inputs Returns ------- g: MTG Updated MTG with given properties """ return set_properties(g, label=label, **dict)
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
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
def annual_loop_septo_rust(year=2013, variety='Tremie13', sowing_date='10-29', nplants=15, nsect=7, sporulating_fraction=5e-3, density_dispersal_units=150, layer_thickness_septo=0.01, layer_thickness_rust=1., record=True, output_file=None, reset_reconst=True, rep_wheat=None, leaf_duration=2., date_inoc_rust=1000., length_inoc_rust=300., force_inoc_leaf=None, **kwds): """ Simulate epidemics with canopy saved before simulation """ if 'temp_min' in kwds: Tmin = kwds['temp_min'] else: Tmin = 0. (g, adel, brown_rust, septoria, canopy_timing, septo_dispersal_timing, rust_dispersal_timing, septo_rust_timing, recorder_timing, recorder, growth_controler, infection_controler, septo_inoculum, septo_contaminator, rust_contaminator, septo_emitter, septo_transporter, rust_dispersor, it_wheat, wheat_dir, wheat_is_loaded) = setup_simu( sowing_date=str(year - 1) + "-" + sowing_date + " 12:00:00", end_date=str(year) + "-07-30 00:00:00", variety=variety, nplants=nplants, nsect=nsect, sporulating_fraction=sporulating_fraction, Tmin=Tmin, rep_wheat=rep_wheat, record=record, layer_thickness_septo=layer_thickness_septo, layer_thickness_rust=layer_thickness_rust, leaf_duration=leaf_duration, **kwds) if force_inoc_leaf is not None: phenT = adel.phenT() phenT = phenT[phenT['n'] == phenT['n'].max() - force_inoc_leaf + 1] date_inoc_rust = phenT['col'].max() for i, controls in enumerate( zip(canopy_timing, septo_dispersal_timing, rust_dispersal_timing, septo_rust_timing, recorder_timing)): (canopy_iter, septo_dispersal_iter, rust_dispersal_iter, septo_rust_iter, record_iter) = controls # Grow wheat canopy if canopy_iter: it_wheat += 1 g = grow_canopy(g, adel, canopy_iter, it_wheat, wheat_dir, wheat_is_loaded, rain_and_light=True) # Get weather for date and add it as properties on leaves if septo_rust_iter: set_properties( g, label='LeafElement', temperature_sequence=septo_rust_iter.value.temperature_air. tolist(), wetness_sequence=septo_rust_iter.value.wetness.tolist(), relative_humidity_sequence=septo_rust_iter.value. relative_humidity.tolist(), dd_sequence=septo_rust_iter.value.degree_days.tolist()) if septo_dispersal_iter: set_properties( g, label='LeafElement', rain_intensity=septo_dispersal_iter.value.rain.mean(), rain_duration=len(septo_dispersal_iter.value.rain) if septo_dispersal_iter.value.rain.sum() > 0 else 0.) # External contamination geom = g.property('geometry') if septo_dispersal_iter and len( geom) > 0 and septo_dispersal_iter.value.rain.mean() > 0.2: g = external_contamination(g, septo_inoculum, septo_contaminator, septo_dispersal_iter.value, domain=adel.domain, domain_area=adel.domain_area) # if (rust_dispersal_iter and len(geom)>0 and # rust_dispersal_iter.value.index[0] > pd.to_datetime(str(year)+'-03-01') and # rust_dispersal_iter.value.index[-1] < pd.to_datetime(str(year)+'-03-15')): # if (rust_dispersal_iter and len(geom)>0 and # rust_dispersal_iter.value.degree_days.tolist()[-1] > date_inoc_rust and # rust_dispersal_iter.value.degree_days.tolist()[-1] < date_inoc_rust+length_inoc_rust): # print 'RUST INOC' if (rust_dispersal_iter and len(geom) > 0): if force_inoc_leaf is not None: if (rust_dispersal_iter.value.degree_days.tolist()[-1] > date_inoc_rust and rust_dispersal_iter.value.degree_days.tolist()[-1] < date_inoc_rust + length_inoc_rust): g = external_contamination( g, rust_contaminator, rust_contaminator, density_dispersal_units=density_dispersal_units, domain_area=adel.domain_area) else: g = external_contamination( g, rust_contaminator, rust_contaminator, density_dispersal_units=density_dispersal_units, domain_area=adel.domain_area) # Develop disease (infect for dispersal units and update for lesions) if septo_rust_iter: infect(g, septo_rust_iter.dt, infection_controler, label='LeafElement') # group_duplicates_in_cohort(g) # Additional optimisation (group identical cohorts) update(g, septo_rust_iter.dt, growth_controler, label='LeafElement') # Disperse and wash if septo_dispersal_iter and len( geom) > 0 and septo_dispersal_iter.value.rain.mean() > 0.2: g = disperse(g, septo_emitter, septo_transporter, "septoria", label='LeafElement', weather_data=septo_dispersal_iter.value, domain=adel.domain, domain_area=adel.domain_area) if rust_dispersal_iter and len(geom) > 0: g = disperse(g, rust_dispersor, rust_dispersor, fungus_name="brown_rust", label='LeafElement', weather_data=rust_dispersal_iter.value, domain_area=adel.domain_area) # Save outputs if record_iter and record == True: date = record_iter.value.index[-1] print date recorder.record(g, date, degree_days=record_iter.value.degree_days[-1]) if record == True: recorder.post_treatment(variety=variety) if output_file is not None: recorder.save(output_file) else: return g, recorder else: return g
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
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
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
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]) 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: 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') greens = g.property('is_green')
def annual_loop_septo_rust(year = 2013, variety = 'Tremie13', sowing_date = '10-29', nplants = 15, nsect = 7, sporulating_fraction = 5e-3, density_dispersal_units = 150, layer_thickness_septo = 0.01, layer_thickness_rust = 1., record = True, output_file = None, reset_reconst = True, rep_wheat = None, leaf_duration = 2., date_inoc_rust=1000., length_inoc_rust=300., force_inoc_leaf=None, **kwds): """ Simulate epidemics with canopy saved before simulation """ if 'temp_min' in kwds: Tmin = kwds['temp_min'] else: Tmin = 0. (g, adel, brown_rust, septoria, canopy_timing, septo_dispersal_timing, rust_dispersal_timing, septo_rust_timing, recorder_timing, recorder, growth_controler, infection_controler, septo_inoculum, septo_contaminator, rust_contaminator, septo_emitter, septo_transporter, rust_dispersor, it_wheat, wheat_dir, wheat_is_loaded) = setup_simu(sowing_date=str(year-1)+"-"+sowing_date+" 12:00:00", end_date=str(year)+"-07-30 00:00:00", variety = variety, nplants = nplants, nsect=nsect, sporulating_fraction=sporulating_fraction, Tmin=Tmin, rep_wheat=rep_wheat, record=record, layer_thickness_septo=layer_thickness_septo, layer_thickness_rust=layer_thickness_rust, leaf_duration=leaf_duration, **kwds) if force_inoc_leaf is not None: phenT = adel.phenT() phenT = phenT[phenT['n']==phenT['n'].max()-force_inoc_leaf+1] date_inoc_rust = phenT['col'].max() for i, controls in enumerate(zip(canopy_timing, septo_dispersal_timing, rust_dispersal_timing, septo_rust_timing, recorder_timing)): (canopy_iter, septo_dispersal_iter, rust_dispersal_iter, septo_rust_iter, record_iter) = controls # Grow wheat canopy if canopy_iter: it_wheat += 1 g = grow_canopy(g, adel, canopy_iter, it_wheat, wheat_dir, wheat_is_loaded,rain_and_light=True) # Get weather for date and add it as properties on leaves if septo_rust_iter: set_properties(g,label = 'LeafElement', temperature_sequence = septo_rust_iter.value.temperature_air.tolist(), wetness_sequence = septo_rust_iter.value.wetness.tolist(), relative_humidity_sequence = septo_rust_iter.value.relative_humidity.tolist(), dd_sequence = septo_rust_iter.value.degree_days.tolist()) if septo_dispersal_iter: set_properties(g,label = 'LeafElement', rain_intensity = septo_dispersal_iter.value.rain.mean(), rain_duration = len(septo_dispersal_iter.value.rain) if septo_dispersal_iter.value.rain.sum() > 0 else 0.) # External contamination geom = g.property('geometry') if septo_dispersal_iter and len(geom)>0 and septo_dispersal_iter.value.rain.mean()>0.2: g = external_contamination(g, septo_inoculum, septo_contaminator, septo_dispersal_iter.value, domain=adel.domain, domain_area=adel.domain_area) # if (rust_dispersal_iter and len(geom)>0 and # rust_dispersal_iter.value.index[0] > pd.to_datetime(str(year)+'-03-01') and # rust_dispersal_iter.value.index[-1] < pd.to_datetime(str(year)+'-03-15')): # if (rust_dispersal_iter and len(geom)>0 and # rust_dispersal_iter.value.degree_days.tolist()[-1] > date_inoc_rust and # rust_dispersal_iter.value.degree_days.tolist()[-1] < date_inoc_rust+length_inoc_rust): # print 'RUST INOC' if (rust_dispersal_iter and len(geom)>0): if force_inoc_leaf is not None: if (rust_dispersal_iter.value.degree_days.tolist()[-1] > date_inoc_rust and rust_dispersal_iter.value.degree_days.tolist()[-1] < date_inoc_rust+length_inoc_rust): g = external_contamination(g, rust_contaminator, rust_contaminator, density_dispersal_units=density_dispersal_units, domain_area=adel.domain_area) else: g = external_contamination(g, rust_contaminator, rust_contaminator, density_dispersal_units=density_dispersal_units, domain_area=adel.domain_area) # Develop disease (infect for dispersal units and update for lesions) if septo_rust_iter: infect(g, septo_rust_iter.dt, infection_controler, label='LeafElement') # group_duplicates_in_cohort(g) # Additional optimisation (group identical cohorts) update(g, septo_rust_iter.dt, growth_controler, label='LeafElement') # Disperse and wash if septo_dispersal_iter and len(geom)>0 and septo_dispersal_iter.value.rain.mean()>0.2: g = disperse(g, septo_emitter, septo_transporter, "septoria", label='LeafElement', weather_data=septo_dispersal_iter.value, domain=adel.domain, domain_area=adel.domain_area) if rust_dispersal_iter and len(geom)>0: g = disperse(g, rust_dispersor, rust_dispersor, fungus_name = "brown_rust", label='LeafElement', weather_data=rust_dispersal_iter.value, domain_area=adel.domain_area) # Save outputs if record_iter and record == True: date = record_iter.value.index[-1] print date recorder.record(g, date, degree_days = record_iter.value.degree_days[-1]) if record == True: recorder.post_treatment(variety = variety) if output_file is not None: recorder.save(output_file) else: return g, recorder else: return g
def annual_loop_rust(year=2013, variety='Tremie13', nplants=15, nsect=7, sowing_date='10-29', density_dispersal_units=150, TT_delay=20, record=True, output_file=None, layer_thickness=1., save_images=False, keep_leaves=False, rep_wheat=True, leaf_duration=2., **kwds): """ Simulate an epidemics over the campaign. """ # Setup simu (g, adel, fungus, canopy_timing, dispersal_timing, rust_timing, recorder, growth_controler, infection_controler, contaminator, dispersor, it_wheat, wheat_dir, wheat_is_loaded) = setup_simu( sowing_date=str(year - 1) + "-" + sowing_date + " 12:00:00", end_date=str(year) + "-07-30 00:00:00", variety=variety, nplants=nplants, nsect=nsect, TT_delay=TT_delay, dispersal_delay=24, record=record, layer_thickness=layer_thickness, save_images=save_images, keep_leaves=keep_leaves, leaf_duration=leaf_duration, **kwds) # Simulation loop for i, controls in enumerate( zip(canopy_timing, dispersal_timing, rust_timing)): canopy_iter, dispersal_iter, rust_iter = controls # Grow wheat canopy if canopy_iter: it_wheat += 1 g = grow_canopy(g, adel, canopy_iter, it_wheat, wheat_dir, wheat_is_loaded) # Get weather for date and add it as properties on leaves if rust_iter: set_properties( g, label='LeafElement', temperature_sequence=rust_iter.value.temperature_air.tolist(), wetness_sequence=rust_iter.value.wetness.tolist(), dd_sequence=rust_iter.value.degree_days.tolist()) # Simulate airborne contamination geom = g.property('geometry') if dispersal_iter and len(geom) > 0: external_contamination( g, contaminator, contaminator, density_dispersal_units=density_dispersal_units, domain_area=adel.domain_area) # Develop disease (infect for dispersal units and update for lesions) if rust_iter: infect(g, rust_iter.dt, infection_controler, label='LeafElement') group_duplicates_in_cohort( g) # Additional optimisation (group identical cohorts) update(g, rust_iter.dt, growth_controler, label='LeafElement') # Disperse disease if dispersal_iter and len(geom) > 0: g = disperse(g, dispersor, dispersor, fungus_name="brown_rust", label='LeafElement', weather_data=dispersal_iter.value, domain_area=adel.domain_area) # Save images if save_images == True: if canopy_iter: scene = plot_severity_rust_by_leaf(g, senescence=False) if it_wheat < 10: image_name = variety + '_image0000%d.png' % it_wheat elif it_wheat < 100: image_name = variety + '_image000%d.png' % it_wheat elif it_wheat < 1000: image_name = variety + '_image00%d.png' % it_wheat elif it_wheat < 10000: image_name = variety + '_image0%d.png' % it_wheat else: image_name = 'image%d.png' % it_wheat image_name = str( shared_data(alinea.alep) / 'images_rust' / image_name) save_image(scene, image_name=image_name) # Save outputs if rust_iter and record == True: date = rust_iter.value.index[-1] print date recorder.record(g, date, degree_days=rust_iter.value.degree_days[-1]) if record == True: recorder.post_treatment(variety=variety) if output_file is not None: recorder.save(output_file) else: return g, recorder else: return g
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
def test_growth_control(model="septoria_exchanging_rings"): """ Check if 'control_growth' from 'protocol.py' limits the lesion growth up to available surface on the leaf. Generate a wheat MTG and deposit sumultaneously 1000 lesions on a leaf element. Run a loop to compute update and growth. Check that the healthy surface of the leaf decreases up to 0. Check that lesion growth is stopped after this point. Parameters ---------- model: model One version of the model of septoria lesion among: 'septoria_exchanging_rings', 'septoria_with_rings', 'septoria_continuous' """ # Generate a wheat MTG g = adel_one_leaf() initial_leaf_area = 5. set_properties(g, label='LeafElement', area=initial_leaf_area, green_area=initial_leaf_area, healthy_area=initial_leaf_area, position_senescence=None) labels = g.property('label') total_initial_area = sum( g.node(vid).area for vid in labels.iterkeys() if labels[vid].startswith('LeafElement')) # Generate a stock of septoria dispersal units and distribute it on g distribute_lesions(g, nb_lesions=1000, disease_model=model, initiation_model=RandomInoculation(), label='LeafElement') # Call model of growth control controler = NoPriorityGrowthControl() # Initiation of healthy area the day before healthy_area_before = [] # Loop of simulation septo_timing = TimeControl(delay=1, steps=100) timer = TimeControler(disease=septo_timing) for t in timer: # print(timer.numiter) # After infection, the lesion 'age_dday' will be added 1 DD by time step # Note : base temperature for septoria = -2 degrees celsius set_properties(g, label='LeafElement', wetness=True, temp=22., rain_intensity=0.) # Update update(g, t['disease'].dt, controler, senescence_model=None, label='LeafElement') update_healthy_area(g, label='LeafElement') # Find the value of interest on the MTG (total healthy area of the leaf) lesions = g.property('lesions') healthy_areas = g.property('healthy_area') bids = (v for v, l in labels.iteritems() if l.startswith('blade')) for blade in bids: leaf = [ vid for vid in g.components(blade) if labels[vid].startswith('LeafElement') ] leaf_healthy_area = sum(healthy_areas[lf] for lf in leaf) print(leaf_healthy_area) # Check that healthy area + lesion surface = initial healthy surface if lesions: leaf_lesion_area = sum(l.surface for les in lesions.itervalues() for l in les) assert round(leaf_healthy_area, 6) + round( leaf_lesion_area, 6) == round(total_initial_area, 6) # Check that healthy area decreases after emergence of the first lesion if lesions and not healthy_area_before: # Emergence of the first lesion healthy_area_before.append(leaf_healthy_area) elif lesions and healthy_area_before[0] > 0.: # Check that healthy area decreases assert leaf_healthy_area < healthy_area_before # Update of 'healthy_area_before' for next step healthy_area_before[0] = leaf_healthy_area elif lesions and healthy_area_before[0] == 0.: # Check that healthy area stays null assert leaf_healthy_area == 0. # Update of 'healthy_surface_before' for next step healthy_area_before[0] = leaf_healthy_area
def test_update(model="septoria_exchanging_rings"): """ Check if 'update' from 'protocol.py' provokes the growth of a lesion instantiated on the MTG. Generate a wheat MTG and deposit 1 lesion on a leaf element. Run a loop to compute update and growth. Check that all the stages of a lesion of septoria have been reached eventually. Check that the lesion size does not exceed Smax. Parameters ---------- model: model One version of the model of septoria lesion among: 'septoria_exchanging_rings', 'septoria_with_rings', 'septoria_continuous' """ # Generate a wheat MTG g = adel_one_leaf_element() set_properties(g, label='LeafElement', area=5., green_area=5., healthy_area=5., position_senescence=None) # Generate a stock of septoria dispersal units and distribute it on g distribute_lesions(g, nb_lesions=1, disease_model=model, initiation_model=RandomInoculation(), label='LeafElement') # Call model of growth control controler = NoPriorityGrowthControl() # Loop of simulation septo_timing = TimeControl(delay=1, steps=1000) timer = TimeControler(disease=septo_timing) for t in timer: # print(timer.numiter) # After infection, the lesion 'age_dday' will be added 1 DD by time step # Note : base temperature for septoria = -2 degrees celsius set_properties(g, label='LeafElement', wetness=True, temp=22., rain_intensity=0.) # Update update(g, t['disease'].dt, controler, senescence_model=None, label='LeafElement') # 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] assert l.age_dday == timer.numiter f = l.fungus print('lesion surface: %f' % round(l.surface, 6)) if l.age_dday < 220.: assert l.status == 0 assert round(l.surface, 6) < round(f.Smin, 6) if 220. <= l.age_dday < 330.: assert l.status == 1 assert round(f.Smin, 6) <= round(l.surface, 6) assert round(l.surface, 6) < round( f.Smin + f.growth_rate * f.degree_days_to_necrosis, 6) elif 330. <= l.age_dday < 350.: assert l.status == 2 assert round( f.Smin + f.growth_rate * f.degree_days_to_necrosis, 6) <= round(l.surface, 6) assert round(l.surface, 6) < round( f.Smin + f.growth_rate * (f.degree_days_to_necrosis + f.degree_days_to_sporulation), 6) elif l.age_dday >= 350.: assert l.status == 3 assert round( f.Smin + f.growth_rate * f.degree_days_to_sporulation, 6) <= round(l.surface, 6) assert round(l.surface, 6) <= round(l.fungus.Smax, 6)
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
every_h = time_filter(seq, delay=1) every_24h = time_filter(seq, delay=24) weather_timing = IterWithDelays(*time_control(seq, every_h, weather.data)) vine_timing = IterWithDelays(*time_control(seq, every_24h, weather.data)) mildew_timing = IterWithDelays(*time_control(seq, every_h, weather.data)) # Simulation ######################################################### for ind, controls in enumerate(zip(weather_timing, vine_timing, mildew_timing)): weather_eval, vine_eval, mildew_eval = controls # Get weather for date and add it as properties on leaves if weather_eval: set_properties(g,label = 'lf', temp = weather_eval.value.temperature_air[0], rain_intensity = weather_eval.value.rain.mean(), wetness = weather_eval.value.wetness[0], relative_humidity = weather_eval.value.relative_humidity[0], wind_speed = weather_eval.value.wind_speed[0], wind_direction = (1,0,0)) # Grow vine canopy if vine_eval: print(vine_eval.value.datetime[0]) g,_ = grow_canopy(g, vine, vine_eval.value) add_area_topvine(g) # Develop disease if mildew_eval: # Update g for the disease update_healthy_area(g, label = 'lf')
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
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
def annual_loop_rust(year = 2013, variety = 'Tremie13', nplants = 15, nsect = 7, sowing_date = '10-29', density_dispersal_units = 150, TT_delay=20, record = True, output_file = None, layer_thickness=1., save_images = False, keep_leaves=False, rep_wheat = True, leaf_duration=2., **kwds): """ Simulate an epidemics over the campaign. """ # Setup simu (g, adel, fungus, canopy_timing, dispersal_timing, rust_timing, recorder, growth_controler, infection_controler, contaminator, dispersor, it_wheat, wheat_dir, wheat_is_loaded) = setup_simu(sowing_date=str(year-1)+"-"+sowing_date+" 12:00:00", end_date=str(year)+"-07-30 00:00:00", variety = variety, nplants = nplants, nsect = nsect, TT_delay = TT_delay, dispersal_delay = 24, record=record, layer_thickness=layer_thickness, save_images=save_images, keep_leaves=keep_leaves, leaf_duration=leaf_duration, **kwds) # Simulation loop for i, controls in enumerate(zip(canopy_timing, dispersal_timing, rust_timing)): canopy_iter, dispersal_iter, rust_iter = controls # Grow wheat canopy if canopy_iter: it_wheat += 1 g = grow_canopy(g, adel, canopy_iter, it_wheat, wheat_dir, wheat_is_loaded) # Get weather for date and add it as properties on leaves if rust_iter: set_properties(g,label = 'LeafElement', temperature_sequence = rust_iter.value.temperature_air.tolist(), wetness_sequence = rust_iter.value.wetness.tolist(), dd_sequence = rust_iter.value.degree_days.tolist()) # Simulate airborne contamination geom = g.property('geometry') if dispersal_iter and len(geom)>0: external_contamination(g, contaminator, contaminator, density_dispersal_units=density_dispersal_units, domain_area=adel.domain_area) # Develop disease (infect for dispersal units and update for lesions) if rust_iter: infect(g, rust_iter.dt, infection_controler, label='LeafElement') group_duplicates_in_cohort(g) # Additional optimisation (group identical cohorts) update(g, rust_iter.dt, growth_controler, label='LeafElement') # Disperse disease if dispersal_iter and len(geom)>0: g = disperse(g, dispersor, dispersor, fungus_name = "brown_rust", label='LeafElement', weather_data=dispersal_iter.value, domain_area=adel.domain_area) # Save images if save_images == True: if canopy_iter: scene = plot_severity_rust_by_leaf(g, senescence=False) if it_wheat < 10 : image_name=variety+'_image0000%d.png' % it_wheat elif it_wheat < 100 : image_name=variety+'_image000%d.png' % it_wheat elif it_wheat < 1000 : image_name=variety+'_image00%d.png' % it_wheat elif it_wheat < 10000 : image_name=variety+'_image0%d.png' % it_wheat else : image_name='image%d.png' % it_wheat image_name = str(shared_data(alinea.alep)/'images_rust'/image_name) save_image(scene, image_name=image_name) # Save outputs if rust_iter and record == True: date = rust_iter.value.index[-1] print date recorder.record(g, date, degree_days = rust_iter.value.degree_days[-1]) if record == True: recorder.post_treatment(variety=variety) if output_file is not None: recorder.save(output_file) else: return g, recorder else: return g
def test_disperse(model="septoria_exchanging_rings"): """ Check if 'disperse' from 'protocol.py' disperse new dispersal units on the MTG. Generate a wheat MTG and distribute lesions randomly on leaf elements. Run a loop to compute infection and update. Create artificial rains in the loop on a regular basis. Check that the number of lesions on the MTG increases. Parameters ---------- model: model One version of the model of septoria lesion among: 'septoria_exchanging_rings', 'septoria_with_rings', 'septoria_continuous' """ # Generate a wheat MTG g = adel_one_leaf() set_properties(g, label='LeafElement', area=5., green_area=5., healthy_area=5., position_senescence=None) # Generate a stock of septoria dispersal units and distribute it on g distribute_lesions(g, nb_lesions=1, disease_model=model, initiation_model=RandomInoculation(), label='LeafElement') # Call models of growth control and dispersal controler = NoPriorityGrowthControl() emitter = SeptoriaRainEmission() transporter = Septo3DSplash() # Loop of simulation septo_timing = TimeControl(delay=1, steps=1000) timer = TimeControler(disease=septo_timing) for t in timer: # Update climate and force rain occurences if timer.numiter > 400 and timer.numiter % 100 == 0: rain_intensity = 3. else: rain_intensity = 0. set_properties(g, label='LeafElement', wetness=True, temp=22., relative_humidity=85., rain_intensity=rain_intensity) # Update update(g, t['disease'].dt, controler, senescence_model=None, label='LeafElement') # Force rain occurences if rain_intensity != 0: # Count objects on the MTG before dispersal event lesions = g.property('lesions') dispersal_units = g.property('dispersal_units') total_stock_spores_before = sum(l.stock_spores for les in lesions.values() for l in les) total_DUs_before = sum( len(du) for du in dispersal_units.itervalues()) # Dispersal event disperse(g, dispersor, "septoria", label='LeafElement') # Check that stocks of spores on lesions decrease if total_stock_spores_before != 0.: total_stock_spores_after = sum(l.stock_spores for les in lesions.values() for l in les) # print(total_stock_spores_after) assert total_stock_spores_after < total_stock_spores_before # Check that new DUs are deposited on the MTG total_DUs_after = sum( len(du) for du in dispersal_units.itervalues()) if total_DUs_after != 0: assert total_DUs_after >= total_DUs_before
def test_senescence(status='CHLOROTIC', model="septoria_exchanging_rings"): """ Check if 'senescence' from 'protocol.py' compute the effects of senescence on the lesions of the MTG Generate a wheat MTG and distribute 2 DUs with know position on leaf elements. Make them grow into lesions until chosen status, then stop updating them. Set senescence on first lesion. Check that the activity of this lesion is reduced by senescence comparatively to the other lesion, but not the stock of spores. Parameters ---------- status: str: 'CHLOROTIC' or 'SPORULATING' Status of the lesion when touched by senescence. model: model One version of the model of septoria lesion among: 'septoria_exchanging_rings', 'septoria_with_rings', 'septoria_continuous' """ # Generate a wheat MTG g = adel_one_leaf_element() set_properties(g, label='LeafElement', area=5., green_area=5., healthy_area=5., position_senescence=None) # Generate a stock of septoria dispersal units and distribute it on g distribute_lesions(g, nb_lesions=2, disease_model=model, initiation_model=RandomInoculation(), label='LeafElement') # create a flat list of lesions and fix their position lesions = g.property('lesions') les = sum(lesions.values(), []) les[0].position = [0.3, 0] les[1].position = [0.7, 0] # Call a models growth control and senescence controler = NoPriorityGrowthControl() senescence_model = WheatSeptoriaPositionedSenescence(g) # Test if lesion is CHLOROTIC when senescence occur if status == "CHLOROTIC": if model != "septoria_exchanging_rings": dt = 300 set_properties(g, label='LeafElement', wetness=True, temp=22., rain_intensity=0.) # Simulation to obtain a lesion in chosen status update(g, dt=dt, growth_control_model=controler, senescence_model=senescence_model) else: dt = 1 nb_steps = 300 for i in range(0, nb_steps, dt): # Simulation to obtain a lesion in chosen status set_properties(g, label='LeafElement', wetness=True, temp=22., rain_intensity=0.) update(g, dt=dt, growth_control_model=controler, senescence_model=senescence_model) # 1. Compare lesions before senescence # Compute variables of interest l = g.property('lesions') l = sum(l.values(), []) lesion1 = l[0] lesion1.compute_all_surfaces() lesion2 = l[1] lesion2.compute_all_surfaces() # Compare the two lesions assert lesion1.status == lesion2.status == 1 assert lesion1.surface_alive == lesion2.surface_alive assert lesion1.surface_dead == lesion2.surface_dead == 0. # 2. Set senescence, update lesion so they know they # are on a senescent tissue and compare lesions set_properties(g, label='LeafElement', position_senescence=0.6) update(g, dt=0., growth_control_model=controler, senescence_model=senescence_model) # Compute variables of interest l = g.property('lesions') l = sum(l.values(), []) lesion1 = l[0] lesion1.compute_all_surfaces() lesion2 = l[1] lesion2.compute_all_surfaces() # Compare the two lesions assert lesion2.growth_is_active == False assert lesion2.is_active == False assert lesion1.surface_alive > lesion2.surface_alive assert lesion2.surface_alive == 0. assert lesion1.surface_dead == 0. assert lesion2.surface_dead > 0. assert lesion2.surface == lesion2.surface_dead # Test if lesion is SPORULATING when senescence occur elif status == "SPORULATING": if model != "septoria_exchanging_rings": dt = 400 set_properties(g, label='LeafElement', wetness=True, temp=22., rain_intensity=0.) # Simulation to obtain a lesion in chosen status update(g, dt=dt, growth_control_model=controler, senescence_model=senescence_model) else: dt = 1 nb_steps = 400 for i in range(0, nb_steps, dt): # Simulation to obtain a lesion in chosen status set_properties(g, label='LeafElement', wetness=True, temp=22., rain_intensity=0.) update(g, dt=dt, growth_control_model=controler, senescence_model=senescence_model) # 1. Compare lesions before senescence # Compute variables of interest l = g.property('lesions') l = sum(l.values(), []) lesion1 = l[0] lesion1.compute_all_surfaces() lesion2 = l[1] lesion2.compute_all_surfaces() # Compare the two lesions assert lesion1.status == lesion2.status == 3 assert lesion1.surface_alive == lesion2.surface_alive assert lesion1.surface_dead == lesion2.surface_dead == 0. assert lesion1.stock_spores == lesion2.stock_spores > 0. # 2. Set senescence, update lesion so they know they # are on a senescent tissue and compare lesions set_properties(g, label='LeafElement', position_senescence=0.6) update(g, dt=0., growth_control_model=controler, senescence_model=senescence_model) # Compute variables of interest l = g.property('lesions') l = sum(l.values(), []) lesion1 = l[0] lesion1.compute_all_surfaces() lesion2 = l[1] lesion2.compute_all_surfaces() # Compare the two lesions assert lesion2.growth_is_active == False assert lesion2.is_active == True assert lesion1.surface_alive > lesion2.surface_alive assert lesion2.surface_alive > 0. assert lesion1.surface_dead == 0. assert lesion2.surface_dead > 0. assert lesion2.surface > lesion2.surface_dead assert lesion1.stock_spores == lesion2.stock_spores > 0. # if __name__ == '__main__': # g=test_growth_control()
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]) 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: 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
def run_simulation(): # 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(2001, 03, 1, 1, 00, 00) end_date = datetime(2001, 05, 1, 00, 00, 00) # end_date = datetime(2001, 07, 01, 00, 00) date = None # Read weather and adapt it to powdery mildew (add wetness) weather = Weather(data_file='meteo02.csv') weather = add_wetness(weather) # Initialize a vine canopy vine = Vine() g,_ = new_canopy(vine, age = 1) # Initialize the models for septoria diseases=plugin.discover('alep.disease') powdery_mildew = diseases['powdery_mildew'].load() inoculator = InoculationYoungLeaves(age_max=5.) growth_controler = GrowthControlVineLeaf() infection_controler = BiotrophDUProbaModel() emitter = PowderyMildewWindEmission() # transporter = PowderyMildewWindDispersal() transporter = NoDeposit() # 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) vine_timing = TimeControl(delay=24, steps=nb_steps) mildew_timing = TimeControl(delay=1, steps=nb_steps) timer = TimeControler(weather=weather_timing, vine=vine_timing, disease = mildew_timing) # Call leaf inspectors for target blades (top 3) target_leaf = 6 inspector = VineLeafInspector(leaf_id=target_leaf) 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 = 'lf', wetness = data.wetness.values[0], temp = data.temperature_air.values[0], rain_intensity = data.rain.values[0], relative_humidity = data.relative_humidity.values[0], wind_speed = data.wind_speed.values[0], wind_direction = (1,0,0)) # Grow vine canopy g,_ = grow_canopy(g, vine, t['vine']) add_area_topvine(g) update_healthy_area(g, label = 'lf') # Develop disease labels = g.property('label') # if timer.numiter < 1500 and labels[target_leaf]=='lf' and timer.numiter%50==0: if timer.numiter > 100 and timer.numiter < 170 and labels[target_leaf]=='lf' and timer.numiter%rd.randint(2,5)==0: # if timer.numiter < 1500 and timer.numiter%50==0: # Refill pool of initial inoculum to simulate differed availability dispersal_units = generate_stock_du(nb_dus=rd.randint(1,5), disease=powdery_mildew) try: g.node(target_leaf).dispersal_units += dispersal_units except: g.node(target_leaf).dispersal_units = dispersal_units # dispersal_units = generate_stock_du(nb_dus=1000, disease=powdery_mildew) # initiate(g, dispersal_units, inoculator, label='lf') infect(g, t['disease'].dt, infection_controler, label='lf') update(g, t['disease'].dt, growth_controler, label='lf') disperse(g, emitter, transporter, "powdery_mildew", label='lf') inspector.update_data(g) if timer.numiter%24 == 0: update_plot(g) outs = {'ratio_latent':inspector.ratio_latent, 'ratio_spo':inspector.ratio_spo, 'ratio_empty':inspector.ratio_empty} outputs = pandas.DataFrame(data=outs, index=dates) return outputs