Ejemplo n.º 1
0
def update_plot(g):
    # Compute severity by leaf
    severity_by_leaf = compute_severity_by_leaf(g, label='LeafElement')
    set_property_on_each_id(g,
                            'severity',
                            severity_by_leaf,
                            label='LeafElement')

    # Visualization
    g = alep_colormap(g,
                      'severity',
                      cmap=green_yellow_red(levels=100),
                      lognorm=False,
                      zero_to_one=False,
                      vmax=100)

    leaves = get_leaves(g, label='LeafElement')
    pos_sen = g.property('position_senescence')
    for leaf in leaves:
        if pos_sen[leaf] == 0.:
            g.node(leaf).color = (157, 72, 7)

    scene = plot3d(g)
    Viewer.display(scene)
    return scene
Ejemplo n.º 2
0
    def display(self, degree = None, add = False, randomcolor = True):
        from openalea.plantgl.all import Scene, Shape, Material, FaceSet, Polyline, PointSet, Viewer
        from random import randint
        s = Scene()
        m = Material()
        if degree is None: degree = self.degree
        if degree >= 2:
            try:
                ccw = self.orientation()
            except ValueError:
                ccw = set()

            for fid in self.iterate_over_each_i_cell(2):
                if fid in ccw: ofid = self.alpha(0,fid)
                else: ofid = fid
                positions = []
                for dart, deg in self.orderedorbit_iter(ofid,[0,1]):
                    if deg != 1:
                        positions.append(self.get_position(dart))
                s.add(Shape(FaceSet(positions, [range(len(positions))]) , Material((randint(0,255),randint(0,255),randint(0,255))) if randomcolor else m))
        elif degree == 1:
            for eid in self.iterate_over_each_i_cell(1):
                s.add(Shape(Polyline([self.get_position(eid),self.get_position(self.alpha(0,eid))]) ,Material((randint(0,255),randint(0,255),randint(0,255))) ))
        elif degree == 0:
                s.add(Shape(PointSet([self.get_position(pid) for pid in self.iterate_over_each_i_cell(0)]) ,Material((randint(0,255),randint(0,255),randint(0,255))) ))
        
        
        if add : Viewer.add(s)
        else   : Viewer.display(s)
Ejemplo n.º 3
0
def update_plot(g):
    from alinea.alep.architecture import set_property_on_each_id
    from alinea.alep.disease_outputs import compute_severity_by_leaf
    from alinea.adel.mtg_interpreter import plot3d
    from openalea.plantgl.all import Viewer

    # Compute severity by leaf
    severity_by_leaf = compute_severity_by_leaf(g, label='LeafElement')
    set_property_on_each_id(g,
                            'severity',
                            severity_by_leaf,
                            label='LeafElement')

    # Visualization
    g = alep_colormap(g,
                      'severity',
                      cmap=green_yellow_red(levels=100),
                      lognorm=False,
                      zero_to_one=False,
                      vmax=100)

    leaves = get_leaves(g, label='LeafElement')
    pos_sen = g.property('position_senescence')
    for leaf in leaves:
        if pos_sen[leaf] == 0.:
            g.node(leaf).color = (157, 72, 7)

    scene = plot3d(g)
    Viewer.display(scene)
    return scene
Ejemplo n.º 4
0
        def display(self, color=(190, 205, 205), add=False):
            """
		Display the 2-cells of a 2-G-Map using the ordered orbit of its darts in PlantGL.
		For each face element, retrieve the position of its ordered face darts and add a FaceSet PlantGL object to the scene.
		Example : s += pgl.Shape(pgl.FaceSet( [[0,0,0],[1,0,0],[1,1,0],[0,1,0]], [[0,1,2,3]]) , pgl.Material((0,100,0))) # for a green square
		"""
            from openalea.plantgl.all import Scene, Shape, Material, FaceSet, Viewer
            from random import randint
            s = Scene()
            for facedart in self.elements(2):
                lastfart = facedart
                positions = []
                for dart in self.oderedorbit(facedart, [0, 1]):
                    if self.alpha(0, dart) != lastfart:
                        positions.append(self.get_position(dart))
                    lastfart = dart
                if color is None:
                    mat = Material(
                        (randint(0, 255), randint(0, 255), randint(0, 255)))
                else:
                    mat = Material(tuple(color), diffuse=0.25)
                s.add(
                    Shape(FaceSet(positions, [range(len(positions))]), mat,
                          facedart))
            if add:
                Viewer.add(s)
            else:
                Viewer.display(s)
Ejemplo n.º 5
0
def testdyn(nplants=1,start = 100,step = 50, nstep=30,dec=10,az=0):
    from time import sleep
   
    pars, d = adelR(nplants,start)
    
    pos = [(i*dec,0,0) for i in range(nplants)]
    
    g=mtg_factory(d,adel_metamer, leaf_sectors=1,leaf_db=leafdb, stand = [(pos[i],az) for i in range(nplants)])
    g=mtg_interpreter(g)
    
    time = start
    oldcanopy = RunAdel(time,pars)
    
    for i in range(nstep):
        s = plot3d(g)
        Viewer.display(s)
        #sleep(2)
        time = start + (i + 1) * step
        canopy = RunAdel(time,pars)
        mtg_update_from_table(g, canopy, oldcanopy)
        g=mtg_interpreter(g)
        oldcanopy = canopy
    return g,d
    
 # TO DO : senescence leaf shrink
 # tester secteurs > 1
 
#df=DataFrame(d)
    #df.Lv
    #df.ix[1:7,6:9]
    #df[['Gl','Gv','Ll','Lv','Lr','L_shape']]
# import numpy as np
# from alinea.popdrops.Rain import get_area_and_normal
# a1,_=get_area_and_normal(g1.property('geometry'))
# a1 = dict(((k,np.sum(v)) for k,v in a1.iteritems()))
Ejemplo n.º 6
0
def test_transport_rain_two_metamers(interleaf=10.,
                                     density = 350.,
                                     layer_thickness=0.01, 
                                     leaf_sectors = 7,
                                     density_emitted=1e5,
                                     by_sector = False,
                                     display_scene = False):
    g, domain_area, domain, convunit = adel_two_metamers_stand(leaf_sectors=leaf_sectors, 
                                                               density=density,
                                                               interleaf=interleaf,
                                                               leaf_length=20,
                                                               leaf_width=1,
                                                               Einc=0)
    if display_scene:
        scene = plot3d(g)
        Viewer.display(scene)
    weather = sample_weather_with_rain()
    leaves = get_leaf_ids(g)
    DU = emission_source(g, leaves, 
                         domain_area=domain_area,
                         density_emitted=density_emitted)
    transporter = PopDropsTransport(domain=domain, domain_area=domain_area,
                                    dh=layer_thickness, convUnit=convunit,
                                    group_dus=True)
    if sum(DU.values())>0:
        deposits = transporter.disperse(g, DU, weather)
    return count_du_source_target(deposits, leaves, by_sector=False)
Ejemplo n.º 7
0
 def display(self, color=[190, 205, 205], add=False, transparency=0):
     from openalea.plantgl.all import Scene, Shape, Material, FaceSet, Viewer
     from random import randint
     s = Scene()
     for facedart in self.elements(2):
         lastdart = facedart
         positions = []
         for dart in self.orderedorbit(facedart, [0, 1]):
             if self.alpha(0, dart) != lastdart:
                 positions.append(self.get_position(dart))
             lastdart = dart
         if color is None:
             mat = Material(
                 (randint(0, 255), randint(0, 255), randint(0, 255)),
                 transparency=transparency)
         else:
             mat = Material(tuple(color),
                            diffuse=0.25,
                            transparency=transparency)
         s.add(
             Shape(FaceSet(positions, [range(len(positions))]), mat,
                   facedart))
     if add:
         Viewer.add(s)
     else:
         Viewer.display(s)
Ejemplo n.º 8
0
    def run(self, exp_id, batch_dir):
        for date, experiment in self.lpk_files.iteritems():
            ##experiment[str(exp_id)] is the name (including directory) of the
            ##corresponding mtg file
            #mtgp = Mtg_Processing(experiment[str(exp_id)])
            #lstring = mtgp.crt_pseudo_lstring()

            pl = open(experiment[str(exp_id)])
            lstring = cPickle.load(pl)
            pl.close()

            scene = self.bgeom_files[date][str(exp_id)]
            sc = Scene(scene)
            experiment_date = time.strftime(
                "%d/%m/%Y %I:%M:%S",
                time.localtime(
                    os.path.getmtime(self.bgeom_files[date][str(exp_id)])))
            #id_dict = mtgp.crt_envdic()
            print "###########################"

            Viewer.display(sc)
            star = STAR(lstring, sc)
            star.collect(lstring, sc)
            #star.process_shoot(lstring, sc)

            stat = Statistics(lstring=lstring, \
                                attribute_list = [\
                                    "parent_observation",\
                                    "length",\
                                    "radius",\
                                    "leaf_area",\
                                    "leaf_state",\
                                    "ta_pgl",\
                                    "sa_pgl",\
                                    "star_pgl",\
                                    "parent_unit_id",\
                                    "parent_fbr_id",\
                                    "parent_tree_id",\
                                ],\
                                shoot_level = True,\
                                branch_level = True,\
                                tree_level = True,\
                                exp_id = exp_id, \
                                growth_date = date,\
                                exp_date = experiment_date,\
                                dir = batch_dir)

            #Pickle the lstring data structure with information
            lpk = open(batch_dir + str(exp_id) + "_lpk_" + date, "w")
            cPickle.dump(lstring, lpk, 0)
            lpk.close()

            #env = Envelope(id_dict,\
            #                scene,\
            #                output_dir = self.general_directory+date+"_Envelope\\")
            #env.intercept()
            gc.collect()
        gc.collect()
Ejemplo n.º 9
0
    def __call__(self, *inputs):

        scene = inputs[0]
        fname = inputs[1]
        Viewer.display(scene)
        Viewer.camera.lookAt((0, 0, 300), (0, 0, 0))
        Viewer.frameGL.saveImage(fname)

        return fname
Ejemplo n.º 10
0
    def view_distri_layers(self, g, nb_dispersal_units = 1e5, vmax = None,
                           position_source = 3./5, return_df=False):
        from alinea.alep.architecture import set_property_on_each_id
        from alinea.alep.alep_color import alep_colormap, green_yellow_red
        from alinea.alep.disease_outputs import plot3d_transparency
        from openalea.plantgl.all import Viewer
        import matplotlib.pyplot as plt
        import pandas as pd
        # Compute severity by leaf
        self.leaves_in_grid(g)
        layers = self.layers.keys()
        layers.sort()        
        layer = layers[int(position_source*len(layers))]
        if len(self.layers[layer])>0:
            leaf = self.layers[layer][0]
        else:
            non_empty = {k:v for k,v in self.layers.iteritems() if len(v)>0}
            leaf = self.layers[min(non_empty.keys(), key=lambda k:abs(k-layer))][0]
        deposits = {k:sum([du.nb_dispersal_units for du in v]) for k,v in 
                    self.disperse(g, dispersal_units = {leaf : nb_dispersal_units}).iteritems()}  
        set_property_on_each_id(g, 'nb_dispersal_units', deposits)
    
        # Visualization
        if vmax is None:
            vmax = 2*max(deposits.values())/3
        g = alep_colormap(g, 'nb_dispersal_units', cmap=green_yellow_red(), 
                          lognorm=False, zero_to_one=False, 
                          vmax = vmax)
        d = [np.arange(vmax)]
        fig, ax = plt.subplots()
        ax.imshow(d, cmap = green_yellow_red())

        transp = {vid:0. for k,v in self.layers.iteritems() for vid in v}
        set_property_on_each_id(g, 'transparency', transp)   
        for id in g:
            if not id in deposits:
                g.node(id).color = (0,0,0)
                g.node(id).transparency = 0.7
            elif deposits[id]==0.:
                g.node(id).color = (0,0,0)
                g.node(id).transparency = 0.7
            else:
                g.node(id).transparency = 0.                      
        scene = plot3d_transparency(g)
        Viewer.display(scene)
        
        if return_df==True:        
            depo_layer = {k:sum([deposits[vid] for vid in v if vid in deposits])
                            for k,v in self.layers.iteritems()}
            df = pd.DataFrame([[k,v] for k, v in depo_layer.iteritems()])
            df = df.sort(0)
            df[2] = df[1]/df[1].sum()
            fig, ax = plt.subplots()
            ax.plot(df[2], df[0], 'k')
            ax.set_ylabel('Height', fontsize = 16)
            ax.set_xlabel('Proportion of deposits', fontsize = 16)
            return df
Ejemplo n.º 11
0
    def __call__(self, *inputs):
 
        scene = inputs[0]
        fname = inputs[1]
        Viewer.display(scene)
        Viewer.camera.lookAt((0,0,300),(0,0,0))
        Viewer.frameGL.saveImage(fname)
 
        return fname
Ejemplo n.º 12
0
def PlantGL(scene):
    fn = tempfile.mktemp(suffix=".png")
    Viewer.frameGL.setBgColor(255, 255, 255)
    Viewer.animation(True)
    Viewer.display(scene)
    Viewer.saveSnapshot(fn, "png")
    img = Image(fn)
    os.unlink(fn)
    return img
Ejemplo n.º 13
0
    def plot(self,
             a_property=None,
             minval=None,
             maxval=None,
             gamma=None,
             display=True):
        """

        Args:
            a_property: {dict of float or dict of list of float} : a dict of values,
                each key being a scene primitive index.
            minval: (float) minimal value at lower bound of color range
                    if None (default), minimal value of property is used
            maxval: (float) maximal value at upper bound of color range
                    if None (default), maximal value of property is used
            gamma (float): exponent of the normalised values
                    if None (default), na gamma transform is applied
            display: (bool) : should the scene be displayed ? (default True)

        Returns:
            A plantGL scene
        """
        if a_property is None:
            color_property = None
            soil_colors = None
            values = None
        else:
            values = list(a_property.values())
            if isinstance(values[0], list):
                values = list(chain.from_iterable(values))
            values = nan_to_zero(values)
            if minval is None:
                minval = min(values)
            if maxval is None:
                maxval = max(values)
            if gamma is None:
                gamma = 1
            norm = 1
            if minval != maxval:
                norm = maxval - minval
            values = [((x - minval) / float(norm))**gamma for x in values]
            colors = jet_colors(values, 0, 1)
            color_property = {}
            for k, v in a_property.items():
                if isinstance(v, list):
                    color_property[k] = []
                    for i in range(len(v)):
                        color_property[k].append(colors.pop(0))
                else:
                    color_property[k] = [colors.pop(0)
                                         ] * self.scene.getNumberOfTriangles(k)
        scene = self.scene.generate_scene(color_property)
        if display:
            Viewer.display(scene)
        return scene, values
Ejemplo n.º 14
0
def test81(leaf=leaf, scene=None):
    global translation, yt, zt
    if scene is None:
        scene = pgl.Scene()
        Viewer.display(scene)

    mesh = fitting.leaf_shape2(leaf, 10, 7, 7, 1)

    scene += pgl.Translated(translation + (0, yt / 3., 0), mesh)

    Viewer.update()
Ejemplo n.º 15
0
def test7(leaf, scene = None):

    if scene is None:
        scene = pgl.Scene()
        Viewer.display(scene)

    x, y, s, r= leaf
    spline_leaf, leaf_surface = fitting.fit_leaf(x, y, s, r)
    pts, ind = fitting.mesh(spline_leaf,30, 7, 7, 1) 
    fitting.write_smf('leaf_full.smf', pts, ind)
    Viewer.display(fitting.plantgl_shape(pts, ind))
Ejemplo n.º 16
0
def test_positioning():
    d = {'plant':[1,1,1],'axe_id':['MS','T1','T1'],'ms_insertion':[0,1,1],'numphy':[1,1,2],
         'Laz': [0,90,180], 'Ll' :[3,3,3], 'Lv' :[3,3,3] , 'Lsen':[0,0,1], 'L_shape':[3,3,3], 'Lw_shape':[.3,.3,.3], 'Linc':[0,0,0],
         'Einc':[0,45,-45],'El':[1,1,1],'Ev':[1,1,1],'Esen':[0,0,0],'Ed': [0.1,0.1,0.1], 
         'Ginc':[0,0,0],'Gl':[0,0,0],'Gv':[0,0,0],'Gsen':[0,0,0],'Gd': [0.1,0.1,0.1], 
         'Epo':[1,1,1], 'Epos':[1,1,1], 'Gpo':[1,1,1], 'Gpos':[1,1,1], 'Lpo':[1,1,1], 'Lpos':[1,1,1],
         'LsenShrink':[1,1,1], 'LcType':[1,1,1], 'LcIndex':[1,1,1], 'Lr':[0,0,0]}
    chn = getString(d)
    g1,s1 = canMTG(chn)
    g2,s2 = newmtg(d,dec=5)
    Viewer.display(s1+s2)
Ejemplo n.º 17
0
def test7(leaf=leaf, scene=None):

    if scene is None:
        scene = pgl.Scene()
        Viewer.display(scene)

    x, y, s, r = leaf
    spline_leaf, leaf_surface = fitting.fit_leaf(x, y, s, r)
    pts, ind = fitting.mesh(spline_leaf, 30, 7, 7, 1)
    fitting.write_smf('leaf_full.smf', pts, ind)
    Viewer.display(fitting.plantgl_shape(pts, ind))
Ejemplo n.º 18
0
def test81(leaf, scene = None):
    global translation, yt, zt
    if scene is None:
        scene = pgl.Scene()
        Viewer.display(scene)

    mesh = fitting.leaf_shape2(leaf,10, 7, 7, 1)

    scene += pgl.Translated(translation+(0,yt/3.,0), mesh)
    
    Viewer.update()
Ejemplo n.º 19
0
 def plot(self, g, property=None):
     from openalea.plantgl.all import Viewer
     from openalea.mtg.plantframe.color import colormap
     
     colors = None
     if property:
         g = colormap(g, property, cmap='jet', lognorm=True)
         colored = g.property('color')
         colors = {vid:colored.get(vid,colored.get(g.complex(vid),[0,0,0])) for vid in g.vertices(scale=g.max_scale())}
     else:
         colors = None
     s = plot3d(g, colors=colors)  # use the one of openalea.plantframe.color instead ?
     Viewer.display(s)
     return s
Ejemplo n.º 20
0
    def plot(self, a_property=None, minval=None, maxval=None, gamma=None, display=True):
        """

        Args:
            a_property: {dict of float or dict of list of float} : a dict of values,
                each key being a scene primitive index.
            minval: (float) minimal value at lower bound of color range
                    if None (default), minimal value of property is used
            maxval: (float) maximal value at upper bound of color range
                    if None (default), maximal value of property is used
            gamma (float): exponent of the normalised values
                    if None (default), na gamma transform is applied
            display: (bool) : should the scene be displayed ? (default True)

        Returns:
            A plantGL scene
        """
        if a_property is None:
            color_property = None
            soil_colors = None
            values = None
        else:
            values = a_property.values()
            if isinstance(values[0], list):
                values = list(chain.from_iterable(values))
            values = nan_to_zero(values)
            if minval is None:
                minval = min(values)
            if maxval is None:
                maxval = max(values)
            if gamma is None:
                gamma = 1
            norm = 1
            if minval != maxval:
                norm = maxval - minval
            values = map(lambda x: ((x - minval) / float(norm))**gamma, values)
            colors = jet_colors(values, 0, 1)
            color_property = {}
            for k, v in a_property.iteritems():
                if isinstance(v, list):
                    color_property[k] = []
                    for i in range(len(v)):
                        color_property[k].append(colors.pop(0))
                else:
                    color_property[k] = [colors.pop(0)] * len(self.scene[k])
        scene = generate_scene(self.scene, color_property)
        if display:
            Viewer.display(scene)
        return scene, values
Ejemplo n.º 21
0
def test1(leaf=leaf, scene=None):
    """
    Fit the leaf, create a mesh and draw it with plantGL.
    """
    global translation
    if scene is None:
        scene = pgl.Scene()
        Viewer.display(scene)

    x, y, s, r = leaf
    spline_leaf, leaf_surface = fitting.fit_leaf(x, y, s, r)
    mesh = fitting.discretize(spline_leaf, 30, 7, 1)

    scene += pgl.Translated(translation, mesh)
    Viewer.update()
Ejemplo n.º 22
0
def test1(leaf, scene = None):
    """
    Fit the leaf, create a mesh and draw it with plantGL.
    """
    global translation
    if scene is None:
        scene = pgl.Scene()
        Viewer.display(scene)

    x, y, s, r= leaf
    spline_leaf, leaf_surface = fitting.fit_leaf(x, y, s, r)
    mesh = fitting.discretize(spline_leaf,30, 7, 1) 
    
    scene += pgl.Translated(translation, mesh)
    Viewer.update()
Ejemplo n.º 23
0
    def _render(self, name=None, save=False, max_percentile=None):
        """
        Low level method to render a tissue, colored by concentrations.
        
        Concentrations are taken from the table of concentrations of the 
        Simulation. Uses JetMap as ColorMap.
        
        Parameters
        ----------
            name : string
                Name of the species whose concentrations must be
                rendered
            save : bool
                Whether to save a picture or not
        """

        if name == None:
            array = np.zeros(self.sim.n_cells)
            max_cmap = 0
        else:
            array = self.sim.y.get_species(
                name) / self.sim.dilution_volumes.as_1d_array()
            if max_percentile is None:
                max_cmap = np.max(array)
            else:
                max_cmap = np.percentile(array, max_percentile)
                array = np.where(array <= max_cmap, array,
                                 max_cmap * np.ones(array.shape))
        prop = dict(list(zip(self.sim.cids, array)))
        scene = Scene()
        scene += (guillaume.topomesh_display.drawPropertyTopomesh(
            self.sim.mesh,
            self.sim.get_pos(),
            3,
            prop,
            JetMap,
            color_range=[0., max(max_cmap, 1e-6)],
            coef=0.99,
            transparent_min=False))
        Viewer.display(scene)
        if save:
            timestamp = time.strftime('%Y%m%d_%H%M%S') + "_" + str(
                time.time() * 1000 % 1)[2:]
            Viewer.frameGL.saveImage("figures/" + name + "-" + timestamp +
                                     ".png")
        return max_cmap
Ejemplo n.º 24
0
def update_plot(g):
    # Compute severity by leaf
    severity_by_leaf = compute_severity_by_leaf(g, label = 'LeafElement')
    set_property_on_each_id(g, 'severity', severity_by_leaf, label = 'LeafElement')

    # Visualization
    g = alep_colormap(g, 'severity', cmap=green_yellow_red(levels=100),
                      lognorm=False, zero_to_one=False, vmax=100)

    leaves = get_leaves(g, label='LeafElement')
    pos_sen = g.property('position_senescence')
    for leaf in leaves:
        if pos_sen[leaf]==0.:
            g.node(leaf).color = (157, 72, 7)   
    scene = plot3d(g)
    Viewer.display(scene)
    return scene
Ejemplo n.º 25
0
 def display(self, color = [205,205,205], add = False):
   from openalea.plantgl.all import Scene, Shape, Material, FaceSet, Viewer
   from random import randint
   s = Scene()
   for facedart in self.elements(2):
       lastdart = facedart
       positions = []
       for dart in self.orderedorbit(facedart,[0,1]):
           if self.alpha(0, dart) != lastdart:
               positions.append(self.get_position(dart))
           lastdart = dart
       if color is None:
           mat = Material((randint(0,255),randint(0,255),randint(0,255)))
       else:
           mat = Material(tuple(color),diffuse=0.25)
       s.add(Shape(FaceSet(positions, [range(len(positions))]) , mat ))
   if add : Viewer.add(s)
   else : Viewer.display(s)
Ejemplo n.º 26
0
def plot_spline_crv(ctrls, pts):
    """ 
    Parameters
    ==========
      - ctrl: control points
      - pts : evaluated points on the curve
    """
    from openalea.plantgl.all import Scene, Shape, Material, FaceSet, Viewer, Polyline
    from random import randint
    scene = Scene()
    crv = Shape(geometry=Polyline(pts), appearance=Material((12, 12, 125)))
    scene.add(crv)

    ctrl = Shape(geometry=Polyline(ctrls), appearance=Material((12, 125, 12)))
    scene.add(ctrl)
    # To complete: Draw the control points and the line between each ones.

    Viewer.display(scene)
Ejemplo n.º 27
0
 def _render(self, name=None, save=False, max_percentile=None):
     """
     Low level method to render a tissue, colored by concentrations.
     
     Concentrations are taken from the table of concentrations of the 
     Simulation. Uses JetMap as ColorMap.
     
     Parameters
     ----------
         name : string
             Name of the species whose concentrations must be
             rendered
         save : bool
             Whether to save a picture or not
     """
     
     if name == None:
         array = np.zeros(self.sim.n_cells)
         max_cmap = 0
     else:
         array = self.sim.y.get_species(name) / self.sim.dilution_volumes.as_1d_array()
         if max_percentile is None:
             max_cmap = np.max(array)
         else:
             max_cmap = np.percentile(array, max_percentile)
             array = np.where(array <= max_cmap, array, max_cmap * np.ones(array.shape))
     prop = dict(zip(self.sim.cids, array))
     scene = Scene()
     scene += (guillaume
                 .topomesh_display
                 .drawPropertyTopomesh(self.sim.mesh, 
                                       self.sim.get_pos(),
                                       3,
                                       prop,
                                       JetMap,
                                       color_range=[0., max(max_cmap, 1e-6)],
                                       coef=0.99,
                                       transparent_min=False))
     Viewer.display(scene)
     if save:
         timestamp = time.strftime('%Y%m%d_%H%M%S') + "_" + str(time.time() * 1000 % 1)[2:]
         Viewer.frameGL.saveImage("figures/" + name + "-" + timestamp + ".png")
     return max_cmap
Ejemplo n.º 28
0
    def view_distri_layers(self, g, density_dispersal_units=1000., vmax=None):
        from alinea.alep.architecture import set_property_on_each_id
        from alinea.alep.alep_color import alep_colormap, green_yellow_red
        from alinea.alep.disease_outputs import plot3d_transparency
        from openalea.plantgl.all import Viewer
        import matplotlib.pyplot as plt
        # Compute severity by leaf
        nb_dus = density_dispersal_units * self.domain_area
        deposits = {
            k: sum([du.nb_dispersal_units for du in v])
            for k, v in self.contaminate(g, nb_dus).iteritems()
        }
        set_property_on_each_id(g, 'nb_dispersal_units', deposits)

        # Visualization
        if vmax is None:
            vmax = 2 * max(deposits.values()) / 3
        g = alep_colormap(g,
                          'nb_dispersal_units',
                          cmap=green_yellow_red(),
                          lognorm=False,
                          zero_to_one=False)

        d = [np.arange(vmax)]
        fig, ax = plt.subplots()
        ax.imshow(d, cmap=green_yellow_red())

        geometries = g.property('geometry')
        leaves = get_leaves(g, label='LeafElement')
        leaves = [l for l in leaves if l in geometries]
        transp = {vid: 0. for k, v in self.layers.iteritems() for vid in v}
        set_property_on_each_id(g, 'transparency', transp)
        for id in g:
            if not id in deposits:
                g.node(id).color = (1, 1, 1)
                g.node(id).transparency = 0.7
            elif deposits[id] == 0.:
                g.node(id).color = (1, 1, 1)
                g.node(id).transparency = 0.7
            else:
                g.node(id).transparency = 0.
        scene = plot3d_transparency(g)
        Viewer.display(scene)
Ejemplo n.º 29
0
def plot_spline_surface(ctrl_net, points):
    """
    Parameters
    ==========
      - ctrl_net : the net of control points (list of list)
      - points : a set of evaluated points (list of list)
    """

    scene = Scene()
    n = len(points)
    m = len(points[0])

    # Compute a mesh (i.e. TriangleSet) for the set of points
    pointList = [pt for rank in points for pt in rank]
    indexList = []

    for i in range(n - 1):
        for j in range(m - 1):
            ii = i * m + j
            i1 = (ii, ii + 1, ii + m)
            i2 = (ii + 1, ii + m + 1, ii + m)
            indexList.append(i1)
            indexList.append(i2)

    surf = Shape(TriangleSet(pointList, indexList),
                 appearance=Material((12, 125, 12)))
    scene.add(surf)

    # plot the control net
    n = len(ctrl_net)
    m = len(ctrl_net[0])
    for pts in ctrl_net:
        crv = Shape(geometry=Polyline(pts), appearance=Material((125, 12, 12)))
        scene.add(crv)
        for pt in pts:
            scene.add(Shape(Translated(Vector3(pt), Sphere(radius=0.1))))

    for i in range(m):
        pts = [ctrl_net[j][i] for j in range(n)]
        crv = Shape(geometry=Polyline(pts), appearance=Material((12, 12, 125)))
        scene.add(crv)

    Viewer.display(scene)
Ejemplo n.º 30
0
def test3(leaf=leaf, scene=None):
    """
    Obtain a leaf at different time.
    """
    global zt

    if scene is None:
        scene = pgl.Scene()

    x, y, s, r = leaf
    spline_leaf, leaf_surface = fitting.fit_leaf(x, y, s, r)
    translation = pgl.Vector3()
    n = 7

    for i in range(1, n + 1):
        mesh = fitting.partial_leaf(spline_leaf, 30, n, i, 1)
        scene += pgl.Translated(translation, mesh)
        translation.z += zt

    Viewer.display(scene)
Ejemplo n.º 31
0
def test3(leaf, scene = None):
    """
    Obtain a leaf at different time.
    """
    global zt

    if scene is None:
        scene = pgl.Scene()

    x, y, s, r= leaf
    spline_leaf, leaf_surface = fitting.fit_leaf(x, y, s, r)
    translation = pgl.Vector3()
    n = 7
    
    for i in range (1,n+1):
        mesh = fitting.partial_leaf(spline_leaf, 30, n, i, 1)
        scene += pgl.Translated(translation, mesh)
        translation.z += zt

    Viewer.display(scene)
Ejemplo n.º 32
0
def test2(leaves):
    """
    Visualize all the leaves in the database in the same scene.
    """
    global translation, yt, zt
    translation = pgl.Vector3(0,0,0)
    scene= pgl.Scene()
    Viewer.display(scene)
    for k in leaves:
        print "Rank number: ", k
        index = 0
        for leaf in leaves[k]:
            try:
                test1(leaf,scene)
            except:
                print "problem with leaf %d in rank %s"%(index,k)
            index += 1
            translation.z += zt
            #raw_input('Enter something for next leaf...')
        translation.y = -60 + yt*int(k)
        translation.z = 0
Ejemplo n.º 33
0
def test2(leaves=leaves):
    """
    Visualize all the leaves in the database in the same scene.
    """
    global translation, yt, zt
    translation = pgl.Vector3(0, 0, 0)
    scene = pgl.Scene()
    Viewer.display(scene)
    for k in leaves:
        print "Rank number: ", k
        index = 0
        for leaf in leaves[k]:
            try:
                test1(leaf, scene)
            except:
                print "problem with leaf %d in rank %s" % (index, k)
            index += 1
            translation.z += zt
            #raw_input('Enter something for next leaf...')
        translation.y = -60 + yt * int(k)
        translation.z = 0
Ejemplo n.º 34
0
def testdyn(nplants=1, start=100, step=50, nstep=30, dec=10, az=0):
    from time import sleep

    pars, d = adelR(nplants, start)

    pos = [(i * dec, 0, 0) for i in range(nplants)]

    g = mtg_factory(d,
                    adel_metamer,
                    leaf_sectors=1,
                    leaf_db=leafdb,
                    stand=[(pos[i], az) for i in range(nplants)])
    g = mtg_interpreter(g)

    time = start
    oldcanopy = RunAdel(time, pars)

    for i in range(nstep):
        s = plot3d(g)
        Viewer.display(s)
        #sleep(2)
        time = start + (i + 1) * step
        canopy = RunAdel(time, pars)
        mtg_update_from_table(g, canopy, oldcanopy)
        g = mtg_interpreter(g)
        oldcanopy = canopy
    return g, d

# TO DO : senescence leaf shrink
# tester secteurs > 1


#df=DataFrame(d)
#df.Lv
#df.ix[1:7,6:9]
#df[['Gl','Gv','Ll','Lv','Lr','L_shape']]
# import numpy as np
# from alinea.popdrops.Rain import get_area_and_normal
# a1,_=get_area_and_normal(g1.property('geometry'))
# a1 = dict(((k,np.sum(v)) for k,v in a1.iteritems()))
Ejemplo n.º 35
0
    def plot_layers(self, g):
        from alinea.alep.architecture import set_property_on_each_id
        from alinea.alep.alep_color import alep_colormap
        from alinea.alep.disease_outputs import plot3d_transparency
        from openalea.plantgl.all import Viewer
        # Compute severity by leaf
        self.leaves_in_grid(g)
        layers = self.layers
        layer_by_leaf = {vid:k for k,v in layers.iteritems() for vid in v}
        set_property_on_each_id(g, 'height', layer_by_leaf)
    
        # Visualization
        g = alep_colormap(g, 'height', cmap='prism', 
                          lognorm=False, zero_to_one=False)

        geometries = g.property('geometry') 
        leaves = get_leaves(g, label='LeafElement')
        leaves = [l for l in leaves if l in geometries] 
        transp = {vid:0. for k,v in layers.iteritems() for vid in v}
        set_property_on_each_id(g, 'transparency', transp)                         
        scene = plot3d_transparency(g)
        Viewer.display(scene)
Ejemplo n.º 36
0
def update_plot(g):
    from alinea.alep.architecture import set_property_on_each_id
    from alinea.alep.disease_outputs import compute_severity_by_leaf
    from alinea.adel.mtg_interpreter import plot3d
    from openalea.plantgl.all import Viewer

    # Compute severity by leaf
    severity_by_leaf = compute_severity_by_leaf(g, label = 'lf')
    set_property_on_each_id(g, 'severity', severity_by_leaf, label = 'lf')
                       
    # Visualization
    g = alep_colormap(g, 'severity', cmap=green_yellow_red(levels=100),
                      lognorm=False, zero_to_one=False, vmax=100)
    brown = (100,70,30)
    trunk_ids = [n for n in g if g.label(n).startswith('tronc')]
    for id in trunk_ids:
        trunk = g.node(id)
        trunk.color = brown
    
    scene = plot3d(g)
    Viewer.display(scene)
    return scene
Ejemplo n.º 37
0
def test8(leaf, scene = None):
    global translation, zt
    if scene is None:
        scene = pgl.Scene()
        Viewer.display(scene)

    x, y, s, r= leaf
    leaf_new, leaf_surface = fitting.fit2(x, y, s, r)

    pts, ind = fitting.mesh2(leaf_new, 7, 7, 1) 
    #pts2, ind2 = fitting.qslim(13, pts, ind)
    #mesh = fitting.plantgl_shape(pts2, ind2)

    #sc=pgl.SurfComputer(pgl.Discretizer())
    #mesh.apply(sc)
    #scale_z = leaf_surface*7 / (sc.surface)
    #mesh_final = mesh.transform(pgl.Scaling((1,1,scale_z)))
    #mesh_final = mesh
    scene += pgl.Translated(translation, fitting.plantgl_shape(pts, ind))
    #scene += pgl.Translated(translation+(0,yt/3.,0), mesh_final)
    
    Viewer.update()
Ejemplo n.º 38
0
def test8(leaf=leaf, scene=None):
    global translation, zt
    if scene is None:
        scene = pgl.Scene()
        Viewer.display(scene)

    x, y, s, r = leaf
    leaf_new, leaf_surface = fitting.fit2(x, y, s, r)

    pts, ind = fitting.mesh2(leaf_new, 7, 7, 1)
    #pts2, ind2 = fitting.qslim(13, pts, ind)
    #mesh = fitting.plantgl_shape(pts2, ind2)

    #sc=pgl.SurfComputer(pgl.Discretizer())
    #mesh.apply(sc)
    #scale_z = leaf_surface*7 / (sc.surface)
    #mesh_final = mesh.transform(pgl.Scaling((1,1,scale_z)))
    #mesh_final = mesh
    scene += pgl.Translated(translation, fitting.plantgl_shape(pts, ind))
    #scene += pgl.Translated(translation+(0,yt/3.,0), mesh_final)

    Viewer.update()
Ejemplo n.º 39
0
def test_positioning():
    d = {
        'plant': [1, 1, 1],
        'axe_id': ['MS', 'T1', 'T1'],
        'ms_insertion': [0, 1, 1],
        'numphy': [1, 1, 2],
        'Laz': [0, 90, 180],
        'Ll': [3, 3, 3],
        'Lv': [3, 3, 3],
        'Lsen': [0, 0, 1],
        'L_shape': [3, 3, 3],
        'Lw_shape': [.3, .3, .3],
        'Linc': [0, 0, 0],
        'Einc': [0, 45, -45],
        'El': [1, 1, 1],
        'Ev': [1, 1, 1],
        'Esen': [0, 0, 0],
        'Ed': [0.1, 0.1, 0.1],
        'Ginc': [0, 0, 0],
        'Gl': [0, 0, 0],
        'Gv': [0, 0, 0],
        'Gsen': [0, 0, 0],
        'Gd': [0.1, 0.1, 0.1],
        'Epo': [1, 1, 1],
        'Epos': [1, 1, 1],
        'Gpo': [1, 1, 1],
        'Gpos': [1, 1, 1],
        'Lpo': [1, 1, 1],
        'Lpos': [1, 1, 1],
        'LsenShrink': [1, 1, 1],
        'LcType': [1, 1, 1],
        'LcIndex': [1, 1, 1],
        'Lr': [0, 0, 0]
    }
    chn = getString(d)
    g1, s1 = canMTG(chn)
    g2, s2 = newmtg(d, dec=5)
    Viewer.display(s1 + s2)
Ejemplo n.º 40
0
def update_plot(g):
    from alinea.alep.architecture import set_property_on_each_id
    from alinea.alep.disease_outputs import compute_severity_by_leaf
    from alinea.adel.mtg_interpreter import plot3d
    from openalea.plantgl.all import Viewer

    # Compute severity by leaf
    severity_by_leaf = compute_severity_by_leaf(g, label = 'LeafElement')
    set_property_on_each_id(g, 'severity', severity_by_leaf, label = 'LeafElement')

    # Visualization
    g = alep_colormap(g, 'severity', cmap=green_yellow_red(levels=100),
                      lognorm=False, zero_to_one=False, vmax=100)

    leaves = get_leaves(g, label='LeafElement')
    pos_sen = g.property('position_senescence')
    for leaf in leaves:
        if pos_sen[leaf]==0.:
            g.node(leaf).color = (157, 72, 7)

    scene = plot3d(g)
    Viewer.display(scene)
    return scene
Ejemplo n.º 41
0
def update_plot(g, leaf_source):
    # Compute severity by leaf
    nb_dus_by_leaf = count_dispersal_units_by_leaf(g, label = 'LeafElement')
    set_property_on_each_id(g, 'nb_dus', nb_dus_by_leaf, label = 'LeafElement')
    
    # Visualization
    g = alep_colormap(g, 'nb_dus', cmap=green_yellow_red(levels=1000),
                      lognorm=False, zero_to_one=False, vmax=25)

    # pos_sen = g.property('position_senescence')
    for id in g:
        if not id in nb_dus_by_leaf:
            # g.node(id).color = (255,255,255)
            # g.node(id).color = (113,113,113)
            # g.node(id).transparency = 0.9
            g.node(id).transparency = 0.
        else:
            g.node(id).transparency = 0.

    g.node(leaf_source).color = (230, 62, 218)
    g.node(leaf_source).transparency = 0.
    scene = plot3d(g)
    Viewer.display(scene)
    return scene
Ejemplo n.º 42
0
 def plot(g, property=None):
     s = Adel.scene(g, property)
     Viewer.display(s)
     return s
Ejemplo n.º 43
0
from openalea.oalab.service.geometry import to_shape3d, register_shape3d

class MyObject(object):
    def __init__(self, n):
        self.points = numpy.random.randn(n, 3) * 100
        self.colors = zip(numpy.random.randint(0, 255, n).tolist(),
                          numpy.random.randint(0, 255, n).tolist(),
                          numpy.random.randint(0, 255, n).tolist())

def myobjectIn3d(obj):
    return PointSet(obj.points, colorList=Color4Array(map(Color4, obj.colors)))

register_shape3d(MyObject, myobjectIn3d)

if __name__ == '__main__':

    from openalea.vpltk.qt import QtGui
    instance = QtGui.QApplication.instance()
    if instance is None :
        app = QtGui.QApplication([])
    else :
        app = instance

    t = MyObject(100)
    Viewer.display(to_shape3d(t))

    if instance is None :
        app.exec_()

Ejemplo n.º 44
0
def animate(scenes, delay=0.2):
    from time import sleep
    for s in scenes:
        Viewer.display(s)
        sleep(delay)
Ejemplo n.º 45
0
def display_scene(scene):
    """
    Display a plantgl scene
    """

    Viewer.display(scene)
Ejemplo n.º 46
0
class MyObject(object):
    def __init__(self, n):
        self.points = numpy.random.randn(n, 3) * 100
        self.colors = zip(
            numpy.random.randint(0, 255, n).tolist(),
            numpy.random.randint(0, 255, n).tolist(),
            numpy.random.randint(0, 255, n).tolist())


def myobjectIn3d(obj):
    return PointSet(obj.points, colorList=Color4Array(map(Color4, obj.colors)))


register_shape3d(MyObject, myobjectIn3d)

if __name__ == '__main__':

    from openalea.vpltk.qt import QtGui
    instance = QtGui.QApplication.instance()
    if instance is None:
        app = QtGui.QApplication([])
    else:
        app = instance

    t = MyObject(100)
    Viewer.display(to_shape3d(t))

    if instance is None:
        app.exec_()
Ejemplo n.º 47
0
def test(date=500,dec=10):
    pars, d = adelR(1,date)
    chn = getString(d)
    g1,s1 = canMTG(chn)
    g2,s2 = newmtg(d,dec=dec)
    Viewer.display(s1+s2)
Ejemplo n.º 48
0
def plot_severity_rust_by_leaf(g, senescence=True,
                                transparency=None, 
                                label='LeafElement'):
    """ Display the MTG with colored leaves according to disease severity 
    
    Parameters
    ----------
    g: MTG
        MTG representing the canopy
    senescence: bool
        True if senescence must be displayed, False otherwise
    transparency: float[0:1]
        Transparency of the part of the MTG without lesion
    label: str
        Label of the part of the MTG concerned by the calculation
        
    Returns
    -------
    scene:
        Scene containing the MTG attacked by the disease
    
    """
    from alinea.alep.architecture import set_property_on_each_id, get_leaves
    from alinea.alep.alep_color import alep_colormap, green_yellow_red
    from alinea.adel.mtg_interpreter import plot3d
    from alinea.alep.disease_outputs import plot3d_transparency
    from openalea.plantgl.all import Viewer
    # Visualization
    lesions = g.property('lesions')
    leaves = get_leaves(g, label=label)
    severity_by_leaf = {}
    for lf in leaves:
        if lf in lesions:
            leaf = g.node(lf)
            severity_by_leaf[lf] = sum([l.surface for l in leaf.lesions])*100./leaf.area if leaf.area>0 else 0.
        else:
            severity_by_leaf[lf] = 0.
    set_property_on_each_id(g, 'severity', severity_by_leaf, label=label)
    g = alep_colormap(g, 'severity', cmap=green_yellow_red(levels=100),
                      lognorm=False, zero_to_one=False, vmax=100)

    if senescence==True:
        leaves = get_leaves(g, label=label)
        sen_lengths = g.property('senesced_length')
        green_lengths = g.property('green_length')
        for leaf in leaves:
            if sen_lengths[leaf]>0. and round(green_lengths[leaf],15)==0.:
                g.node(leaf).color = (157, 72, 7)
    
    if transparency!=None:
        for id in g:           
            if not id in severity_by_leaf:
                g.node(id).color = (255,255,255)
                g.node(id).transparency = 0.9
            elif severity_by_leaf[id]==0.:
                g.node(id).color = (255,255,255)
                g.node(id).transparency = transparency
            else:
                g.node(id).transparency = 0.
        scene = plot3d_transparency(g)
    else:
        scene = plot3d_transparency(g)
    Viewer.display(scene)
    return scene
Ejemplo n.º 49
0
    shapes = []
    
    currentid = 0
    while currentid < len(cmds):
        currentid, obj = parse_object(cmds, currentid, objmap)
        if type(obj) == pgl.Shape:
            shapes.append(obj)

    if len(shapes) > 0 : return pgl.Scene(shapes)
    else : return pgl.Scene([pgl.Shape(obj) for obj in objmap if isinstance(obj, pgl.Geometry)])



def parse_file(fname):
    txt = read(fname, {})
    tree = lex(txt)
    print(tree)
    return parse(tree)



if __name__ == '__main__':
    import glob
    testfiles = glob.glob('../../../share/plantgl/database/exemples/*.geom')
    for f in testfiles:
        print(f)
        parse_file(f)

    from openalea.plantgl.all import Viewer
    Viewer.display(parse_file('../../../share/plantgl/database/exemples/gen_cylinder.geom'))
    #parse_file('../../../share/plantgl/database/exemples/colors.app')    
Ejemplo n.º 50
0
from impulse.root import root_mtg
from openalea.plantgl.all import Viewer

g = root_mtg.mtg_root()

s = root_mtg.Simulate(g)

for i in range(100):
    s.step()
    scene = root_mtg.plot(g)
    Viewer.display(scene)


Ejemplo n.º 51
0
    def plot(self, inputmtg=None):
        from openalea.plantgl.all import Viewer

        Viewer.display(self.sceneInterpretation(inputmtg))
Ejemplo n.º 52
0
 def dartdisplay(self, add = False, textsize = None):
       from openalea.plantgl.all import Viewer
       s = self.darts2pglscene(textsize)
       if add : Viewer.add(s)
       else : Viewer.display(s)
Ejemplo n.º 53
0
 def plot(self, inputmtg=None):
     from openalea.plantgl.all import Viewer
     Viewer.display(self.sceneInterpretation(inputmtg))
Ejemplo n.º 54
0
def irradiance_distribution(meteo,
                            geo_location,
                            irradiance_unit,
                            time_zone='Europe/Paris',
                            turtle_sectors='46',
                            turtle_format='uoc',
                            sun2scene=None,
                            rotation_angle=0.,
                            icosphere_level=None):
    """Calculates irradiance distribution over a semi-hemisphere surrounding the plant [umol m-2 s-1].

    Args:
        meteo (DataFrame): meteo data having the following columns:
            time (datetime): UTC time
            Tac (float): [°C] air temperature
            hs (float): (%) air relative humidity
            Rg or PPFD (float): respectively global [W m-2] or photosynthetic photon flux density [umol m-2 s-1]
            u (float): [m s-1] wind speed
            Ca (float): [ppm] CO2 concentration in the air
            Pa (float): [kPa] atmospheric pressure
        geo_location: tuple of (latitude [°], longitude [°], elevation [°])
        irradiance_unit (str): unit of the irradiance flux density,
            one of ('Rg_Watt/m2', 'RgPAR_Watt/m2', 'PPFD_umol/m2/s')
        time_zone (str): a 'pytz.timezone' (e.g. 'Europe/Paris')
        turtle_sectors (str): number of turtle sectors (see :func:`turtle` from `sky_tools` package)
        turtle_format (str): format irradiance distribution, could be 'soc', or 'uoc'
            (see :func:`turtle` from `sky_tools` package for details)
        sun2scene (pgl.scene): if provided, a sun object (sphere) is added to it
        rotation_angle (float): [°] counter clockwise azimuth between the default X-axis direction (South) and real
            direction of X-axis
        icosphere_level (int): the level of refinement of the dual icosphere
            (see :func:`alinea.astk.icosphere.turtle_dome` for details)

    Returns:
        [umol m-2 s-1] tuple of tuples, cumulative irradiance flux densities distributed across the semi-hemisphere
            surrounding the plant
        (float) [-] diffuse-to-total irradiance ratio

    Notes:
        meteo data can consist of only one line (single event) or multiple lines.
            In the latter case, this function returns accumulated irradiance throughtout the entire periode with sun
            positions corresponding to each time step.


    TODO: replace by the icosphere procedure

    """
    diffuse_ratio = []
    nrj_sum = 0
    for idate, date in enumerate(meteo.index):

        if irradiance_unit.split('_')[0] == 'PPFD':
            energy = meteo.loc[date, :].PPFD
        else:
            try:
                energy = meteo.loc[date, :].Rg
            except:
                raise TypeError(
                    "'irradiance_unit' must be one of the following 'Rg_Watt/m2', 'RgPAR_Watt/m2' or'PPFD_umol/m2/s'."
                )

        # First check: convert irradiance to W m-2 (Spitters method always gets energy flux as Rg Watt m-2)
        corr = e_conv_Wm2(irradiance_unit)
        energy = energy * corr

        # Second check: Convert to UTC datetime
        latitude, longitude, elevation = [geo_location[x] for x in range(3)]
        temperature = meteo.Tac.values[0]
        date_utc, lst = local2solar(date, latitude, longitude, time_zone,
                                    temperature)
        doy_utc = date_utc.timetuple().tm_yday
        hour_utc = date_utc.hour + date_utc.minute / 60.
        # R: Attention, ne renvoie pas exactement le même RdRsH que celui du noeud 'spitters_horaire' dans topvine.
        diffuse_ratio_hourly = RdRsH(energy, doy_utc, hour_utc, latitude)
        diffuse_ratio.append(diffuse_ratio_hourly * energy)
        nrj_sum += energy

        # Third and final check: it is always desirable to get energy as PPFD
        energy = energy * (0.48 * 4.6)

        irradiance_diff = diffuse_ratio_hourly * energy
        irradiance_dir = (1 - diffuse_ratio_hourly) * energy

        # diffuse irradiance
        if not icosphere_level:
            energy2, emission, direction, elevation, azimuth = turtle.turtle(
                sectors=turtle_sectors,
                format=turtle_format,
                energy=irradiance_diff)
        else:
            vert, fac = ico.turtle_dome(icosphere_level)
            direction = ico.sample_faces(vert, fac, iter=None,
                                         spheric=False).values()
            direction = [idirect[0] for idirect in direction]
            direction = map(lambda x: tuple(list(x[:2]) + [-x[2]]), direction)

        sky = list(
            zip(
                len(direction) * [irradiance_diff / len(direction)],
                direction))

        # direct irradiance
        sun = Gensun.Gensun()(Rsun=irradiance_dir,
                              DOY=doy_utc,
                              heureTU=hour_utc,
                              lat=latitude)
        sun = GetLightsSun.GetLightsSun(sun)
        sun_data = [(float(sun.split()[0]), (float(sun.split()[1]),
                                             float(sun.split()[2]),
                                             float(sun.split()[3])))]

        # diffuse irradiance (distributed over a dome) + direct irradiance (localized as point source(s))
        source = sky.__add__(sun_data)
        source = [list(isource) for isource in source]

        try:
            for j in range(len(source) - 1):
                source_cum[j][0] += source[j][0]
            source_cum.append(source[-1])
        except NameError:
            source_cum = []
            for isource in source:
                source_cum.append([isource[0], isource[1]])

        if date == meteo.index[-1]:
            source_cum = [tuple(isource) for isource in source_cum]

    # Rotate irradiance sources to cope with plant row orientation
    if rotation_angle != 0.:
        v_energy = [vec[0] for vec in source_cum]
        v_coord = [
            tuple(
                vector_rotation(vec[1], (0., 0., 1.), deg2rad(rotation_angle)))
            for vec in source_cum
        ]
        source_cum = zip(v_energy, v_coord)

    # Add Sun to an existing pgl.scene
    if sun2scene != None:
        xSun, ySun, zSun = -500. * array(
            [source_cum[-1][1][i] for i in range(3)])
        if zSun >= 0:
            ss = Translated(xSun, ySun, zSun, Sphere(20))
            sun = Shape(ss, Material('yellow', Color3(255, 255, 0)))
            sun2scene.add(sun)
        Viewer.display(sun2scene)

    # Diffuse_ratio mean
    if nrj_sum > 0:
        diffuse_ratio = sum(diffuse_ratio) / nrj_sum
    else:
        diffuse_ratio = 1

    # Filter black sources up to the penultimate (hsCaribu expect at least one source)
    source_cum = [v for v in source_cum if v[0] > 0]
    if len(source_cum) == 0:  # night
        source_cum = [(0, (0, 0, -1))]

    return source_cum, diffuse_ratio
Ejemplo n.º 55
0
""" Gather different strategies for modeling dispersal of fungus propagules.
Ejemplo n.º 56
0
    crsSect1 = CrossSection((0., 0.), (0.5, 0.), (1., 0.))
    crsSect2 = CrossSection((0., 2.), (0.5, 1.), (1., 0.))
    crsSect3 = CrossSection((0., 0.), (0.5, 0.), (1., 0.))
    crsSect4 = CrossSection((0., 2.), (0.5, 0.), (1., 0.))
    crsSect5 = CrossSection((0., 2.), (0.5, 0.), (0.6, 0.3), (1., 0.))

    tc = InterpolatedProfile()
    tc.add_cross_sections(0.0, crsSect1,
    #0.5, crsSect2,
                          1.0, crsSect2)

    from openalea.vpltk.qt import QtGui
    app=QtGui.QApplication([])

    scene = Scene()
    Viewer.display(scene)


    scene += tc.interpolating_surface
#X     tc.create_control_point(0.25)
#X     scene += tc.interpolating_surface
#X     tc.create_cross_section(0.75)
#X     scene += tc.interpolating_surface
#X 
    Viewer.update()
    # slice_patch(scene, tc, slices = 11)

    #the following will add a new patch to the view, not update the existing one.
    #################################################################################
    # tc.create_control_point(0.25);scene+=tc.interpolating_surface;Viewer.update() #
    # tc.create_cross_section(0.75);scene+=tc.interpolating_surface;Viewer.update() #
Ejemplo n.º 57
0
def animate(scenes,delay=0.2):
    from time import sleep
    for s in scenes:
        Viewer.display(s)
        sleep(delay)