def getconfig(configfile=None): if configfile is None: configfile = shared_data(alinea.phenomenal) / 'config.cfg' p = PhenomenalConfigParser() p.read(configfile) if p.has_option('General', 'configdir'): confdir = p.get('General', 'configdir') if confdir == 'SharedData': confdir = str(shared_data(alinea.phenomenal)) for s in p._sections: for it in p.items(s, raw=True): if it[0] == 'mask' or it[0] == 'background': p.set(s, it[0], os.path.join(confdir, os.path.basename(it[1]))) if p.has_option('General', 'config_images_dir'): confdir = p.get('General', 'config_images_dir') if confdir == 'SharedData': confdir = str(shared_data(alinea.phenomenal)) s = 'config_images' for it in p.items(s, raw=True): p.set(s, it[0], os.path.join(confdir, os.path.basename(it[1]))) return p
def __init__(self, banner_path=None, content=None): QtGui.QWidget.__init__(self) if banner_path is None: banner_path = shared_data(openalea.oalab, 'icons/logo/banner.png') self._lay = QtGui.QVBoxLayout(self) p = QtGui.QSizePolicy self._banner = QtGui.QLabel() self._banner.setStyleSheet("QLabel { background-color : #ffffff;}") banner = QtGui.QPixmap(banner_path) size = banner.size() self._banner.setPixmap(banner) self._content = QWebView() if hasattr(self._content, "setReadOnly"): self._content.setReadOnly(True) self._content.setHtml(content) self._footer = QtGui.QLabel() self._footer.setStyleSheet("QLabel { background-color : #459454;}") self._lay.addWidget(self._banner) self._lay.addWidget(self._content) self._lay.addWidget(self._footer) self._lay.setContentsMargins(0, 0, 0, 0) self._lay.setSpacing(0)
def createTutorialMenu(self): self.menuTutorials.clear() iconfile = qt.QtGui.QIcon() iconfile.addPixmap(qt.QtGui.QPixmap(":/images/icons/codefile.png"),qt.QtGui.QIcon.Normal,qt.QtGui.QIcon.Off) iconfolder = qt.QtGui.QIcon() iconfolder.addPixmap(qt.QtGui.QPixmap(":/images/icons/fileopen.png"),qt.QtGui.QIcon.Normal,qt.QtGui.QIcon.Off) from openalea.deploy.shared_data import shared_data import openalea.lpy shared_data_path = shared_data(openalea.lpy.__path__, share_path='share/tutorial') if not shared_data_path is None: import os cpath = os.path.abspath(shared_data_path) cmenu = self.menuTutorials toprocess = [(cpath,cmenu)] while len(toprocess) > 0: cpath,cmenu = toprocess.pop(0) for fname in os.listdir(cpath): absfname = os.path.join(cpath,fname) if os.path.isdir(absfname): childmenu = cmenu.addMenu(iconfolder,os.path.basename(str(fname))) toprocess.append( (absfname,childmenu) ) qt.QtCore.QObject.connect(childmenu,qt.QtCore.SIGNAL("triggered(QAction *)"),self.recentMenuAction) elif fname[-4:] == '.lpy': action = qt.QtGui.QAction(os.path.basename(str(fname)),cmenu) action.setData(to_qvariant(absfname)) action.setIcon(iconfile) cmenu.addAction(action)
def updateColormap(self, colormap_index): self.colormap_name = self.combobox.itemText(colormap_index) colormap_path = shared_data(openalea.oalab, 'colormaps/' + self.colormap_name + '.lut') colormap = colormap_from_file(colormap_path, name=self.colormap_name) self.setValue(dict(name=self.colormap_name, color_points=colormap._color_points))
def _repr_html_(self): import openalea.core import base64 from openalea.deploy.shared_data import shared_data from openalea.core.project.formatting.html import html_metainfo_summary, html_item_summary from openalea.core.formatting.util import obj_icon_path from IPython.display import Image stylesheet_path = shared_data(openalea.core, 'stylesheet.css') if stylesheet_path and stylesheet_path.isfile(): with open(stylesheet_path) as f: stylesheet = f.read() html = '<style>%s</style>' % stylesheet else: html = '' icon = obj_icon_path(self, paths=[self.path]) if icon: data = base64.b64encode(Image(filename=icon)._repr_png_()).decode('ascii') image = '<image width="64px" style="vertical-align:middle;" src="data:image/png;base64,%s">' % data else: image = '' args = dict(image=image, title=self.title) html += '<div class="summary"><p class="title">%(image)s%(title)s</p>' % args html += '\n<hr>' html += html_metainfo_summary(self) html += html_item_summary(self) html += '</div>' return html
def loadconfig(config='SideCamera2013_ZoomOut.cfg'): """ load a configuration from shared data directory """ confdir = shared_data(alinea.phenomenal) p = PhenomenalConfigParser() p.read(confdir / config) d = p.as_dict() if p.has_section('config_images'): for it in p.items('config_images', raw=True): flag = cv2.IMREAD_UNCHANGED if it[1].endswith('mask'): flag = cv2.IMREAD_GRAYSCALE d['config_images'][it[0]] = cv2.imread(confdir / it[1], flag) if p.has_section('config_images_elcom'): for it in p.items('config_images_elcom', raw=True): flag = cv2.IMREAD_UNCHANGED if it[1].endswith('mask'): flag = cv2.IMREAD_GRAYSCALE d['config_images_elcom'][it[0]] = cv2.imread(confdir / it[1], flag) for key in d: for sub_key in d[key]: if str(sub_key).startswith('mask'): d[key][sub_key] = cv2.imread(confdir / str(d[key][sub_key]), cv2.IMREAD_GRAYSCALE) if str(sub_key).startswith('background'): d[key][sub_key] = cv2.imread(confdir / str(d[key][sub_key]), cv2.IMREAD_UNCHANGED) return d
def get_filename(name): from os.path import join, exists from openalea.deploy.shared_data import shared_data import openalea.vmango share_dir = shared_data(openalea.vmango, share_path=join("share", 'digitized_mango_mtg')) return join(share_dir, name)
def test_all_lpy_controls(): from openalea.plantlab.lpycontrol import import_lpy_controls from openalea.deploy.shared_data import shared_data import openalea.lpy lpydir = shared_data(openalea.lpy.__path__, share_path='share/tutorial') for lpypath in lpydir.walkfiles('*.lpy'): import_lpy_controls(lpypath)
def icon_path(filepath, default=None, paths=None, packages=None): if filepath is None or isinstance(filepath, basestring) and filepath.startswith(':/'): return None if paths is None: paths = [] if packages is None: packages = [] # Search filename in all paths given by user _paths = [Path(filepath)] + [Path(p) / filepath for p in paths] # Search icons generated by oalab _paths += [Path(p) / '._icon.png' for p in paths] # If a path is found, try to find absolute path # Try to get icon path from object for path in _paths: if path.isfile(): return path # Search in shared icons provided by packages given by user for package in packages: for path in (filepath, 'icons/%s' % filepath): path = shared_data(package, path) if path and path.isfile(): return path
def import_mtgfile(filename): """ parameters: ----------- filename : names of mtg return: ------- a function which import mtg corresponding to the mtg names """ def name(f): "return base name without extension" return f.basename().splitext()[0] filenames = filename files = shared_data(openalea.strawberry).glob('*.mtg') mtg_path = dict((name(f), f) for f in files) mtgfile = dict((k, f) for k, f in mtg_path.items() if k in filenames) if len(filenames) == 1: g = MTG(mtgfile[filenames[0]]) return g else: metaMTG = MTG() for i in mtgfile: metaMTG = algo.union(metaMTG, MTG(mtgfile[i])) return metaMTG
def _repr_html_(self): import openalea.core import base64 from openalea.deploy.shared_data import shared_data from openalea.core.project.formatting.html import html_metainfo_summary, html_item_summary from openalea.core.formatting.util import obj_icon_path from IPython.display import Image stylesheet_path = shared_data(openalea.core, 'stylesheet.css') if stylesheet_path and stylesheet_path.isfile(): with open(stylesheet_path) as f: stylesheet = f.read() html = '<style>%s</style>' % stylesheet else: html = '' icon = obj_icon_path(self, paths=[self.path]) if icon: data = base64.b64encode( Image(filename=icon)._repr_png_()).decode('ascii') image = '<image width="64px" style="vertical-align:middle;" src="data:image/png;base64,%s">' % data else: image = '' args = dict(image=image, title=self.title) html += '<div class="summary"><p class="title">%(image)s%(title)s</p>' % args html += '\n<hr>' html += html_metainfo_summary(self) html += html_item_summary(self) html += '</div>' return html
def test_load_discrete(): import cPickle from openalea.deploy.shared_data import shared_data import rsml filename = shared_data(rsml) / 'discrete.bmtg' with open(filename) as f: g = cPickle.load(f) return g
def updateColormap(self,colormap_index): self.colormap_name = self.combobox.itemText(colormap_index) from tissuelab.gui.vtkviewer.colormap_utils import Colormap, colormap_from_file colormap_path = shared_data(tissuelab,'colormaps/'+self.colormap_name+'.lut') colormap = colormap_from_file(colormap_path,name=self.colormap_name) self.setValue(dict(name=self.colormap_name,color_points=colormap._color_points))
def test_obj_reading(): dirname = shared_data(openalea.cellcomplex) filename = os.path.join(dirname, "icosahedron.obj") topomesh = read_obj_property_topomesh(filename) print topomesh.nb_wisps(0) assert topomesh.nb_wisps(0) == 12 assert topomesh.nb_wisps(2) == 20
def test_length(): data = shared_data(openalea.groalea) f = data / 'length' / 'L_XEG_r.xml' parser = Parser() g, scene = parser.parse(f) mtg = topo.spanning_mtg(g) return mtg, g, scene
def updateColormap(self, colormap_index): self.colormap_name = self.combobox.itemText(colormap_index) from openalea.oalab.colormap.colormap_utils import colormap_from_file colormap_path = shared_data(openalea.oalab, 'colormaps/' + self.colormap_name + '.lut') colormap = colormap_from_file(colormap_path, name=self.colormap_name) self.setValue(dict(name=self.colormap_name, color_points=colormap._color_points))
def test_load_discrete(): import cPickle from openalea.deploy.shared_data import shared_data import rsml filename = shared_data(rsml)/'discrete.bmtg' with open(filename) as f: g = cPickle.load(f) return g
def test_p(): data = shared_data(openalea.groalea) f = data / 'P' / 'P_3Run_Interface_XEG.xml' parser = Parser() g, scene = parser.parse(f) mtg = topo.spanning_mtg(g) return mtg, g, scene
def list_colormaps(): colormap_names = [] colormaps_path = Path(shared_data(openalea.oalab, 'colormaps/grey.lut')).parent for colormap_file in colormaps_path.walkfiles('*.lut'): colormap_name = str(colormap_file.name[:-4]) colormap_names.append(colormap_name) colormap_names.sort() return colormap_names
def test_extraction_at_node_scale(): files = shared_data(openalea.strawberry).glob('*.mtg') mtg_path = dict((name(f), f) for f in files) gariguette = read_mtg_file(mtg_path['Gariguette']) gariguette_extraction_at_node_scale = extract_at_node_scale(gariguette) assert len(gariguette_extraction_at_node_scale) == 784 gariguette_axillary_prod = prob_axillary_production(gariguette, order=0) assert len(gariguette_axillary_prod) == 19
def test_p(): data = shared_data(openalea.groalea) f = data/'P'/'P_3Run_Interface_XEG.xml' parser = Parser() g, scene = parser.parse(f) mtg = topo.spanning_mtg(g) return mtg, g, scene
def __init__(self, parent=None, style=None): AbstractListener.__init__(self) QtGui.QWidget.__init__(self, parent=parent) self.world = None self.name = "" self._controls = [] self._manager = ControlContainer() self.interpreter = get_interpreter() self.interpreter.locals['draco_control'] = self self._layout = QtGui.QVBoxLayout(self) self._title_img = QtGui.QWidget() title_layout = QtGui.QHBoxLayout(self._title_img) p = QtGui.QSizePolicy pixmap_dirname = shared_data(openalea.draco_stem) icon_img = QtGui.QLabel() pixmap_icon = QtGui.QPixmap(os.path.join(pixmap_dirname,"../../src/openalea/draco_stem/draco_oalab/widget/draco_icon.png")) icon_img.setPixmap(pixmap_icon) icon_img.setScaledContents(True) icon_img.setFixedWidth(60) icon_img.setFixedHeight(60) # icon_img.setSizePolicy(p(p.Expanding, p.Maximum)) title_layout.addWidget(icon_img) # title_layout.addSpacing(20) title_img = QtGui.QLabel() pixmap_title = QtGui.QPixmap(os.path.join(pixmap_dirname,"../../src/openalea/draco_stem/draco_oalab/widget/draco_title.png")) title_img.setPixmap(pixmap_title) title_img.setScaledContents(True) # title_img.setSizePolicy(p(p.Expanding, p.Maximum)) title_img.setFixedWidth(140) title_img.setFixedHeight(60) title_layout.addWidget(title_img) # title_layout.addSpacing(20) title_label = QtGui.QLabel(u'Dual Reconstruction\nby Adjacency\nComplex Optimization') title_label.setAlignment(QtCore.Qt.AlignCenter) # title_label.setFixedWidth(150) title_layout.addWidget(title_label) self._title_img.setFixedHeight(75) self._title_img.setSizePolicy(p(p.Expanding, p.Maximum)) self._layout.addWidget(self._title_img,0) self._view = None self._set_manager(self._manager) self.draco = None
def __test_2D(): files = shared_data(openalea.strawberry).glob('*.mtg') mtg_path = dict((name(f), f) for f in files) gariguette = read_mtg_file(mtg_path['Gariguette']) gariguette.properties()['order'] = orders(gariguette) scene = visu2d.plot2d(gariguette, gariguette.vertices(scale=1)[53:54], dist=[3] * 3, display=False) PlantGL(scene)
def tutorials(): from openalea.core.path import path try: from openalea import oalab from openalea.deploy.shared_data import shared_data except ImportError: return [] else: oalab_dir = shared_data(oalab) return [path(oalab_dir)]
def __call__(self): from openalea.core.path import path try: from openalea import oalab from openalea.deploy.shared_data import shared_data except ImportError: return [] else: oalab_dir = shared_data(oalab) return [path(oalab_dir)]
def updateColormap(self, colormap_index): self.colormap_name = self.combobox.itemText(colormap_index) from tissuelab.gui.vtkviewer.colormap_utils import Colormap, colormap_from_file colormap_path = shared_data(tissuelab, 'colormaps/' + self.colormap_name + '.lut') colormap = colormap_from_file(colormap_path, name=self.colormap_name) self.setValue( dict(name=self.colormap_name, color_points=colormap._color_points))
def create_project_shortcut(): """ Create a shortcut/symlink inside project directory to oalab.share directory. Permit to access to oalab examples simpler. """ project_dir = get_project_dir() project_link_name = path(project_dir) / "oalab_examples" if not project_link_name.exists(): oalab_dir = shared_data(oalab) symlink(oalab_dir, project_link_name)
def load_colormaps(): from openalea.oalab.colormap.colormap_utils import Colormap, colormap_from_file colormaps = {} colormaps_path = Path(shared_data(openalea.oalab, 'colormaps/grey.lut')).parent for colormap_file in colormaps_path.walkfiles('*.lut'): colormap_name = str(colormap_file.name[:-4]) colormaps[colormap_name] = colormap_from_file( colormap_file, name=colormap_name) return colormaps
def test_p(): data = shared_data(openalea.groalea) f1 = data / "P" / "P_3Run_Interface_XEG.xml" parser = Parser() g1, scene1 = parser.parse(f1) c3s1 = color3s(g1) for i in [20, 21, 10, 18]: assert c3s1[i] != c3s1[4]
def create_project_shortcut(): """ Create a shortcut/symlink inside project directory to oalab.share directory. Permit to access to oalab examples simpler. """ project_dir = get_project_dir() project_link_name = path(project_dir)/"oalab_examples" if not project_link_name.exists(): oalab_dir = shared_data(oalab) symlink(oalab_dir,project_link_name)
def test_p(): data = shared_data(openalea.groalea) f1 = data / 'L' / 'L.xml' parser = Parser() g1, scene1 = parser.parse(f1) c3s1 = color3s(g1) for i in [20, 21, 10, 18]: assert c3s1[i] != c3s1[4]
def test_LMul_Branch(): data = shared_data(openalea.groalea) f1 = data / 'LMul_Branch' / 'LMul_Branch_3Run_Interface_XEG.xml' parser = Parser() g1, scene1 = parser.parse(f1) sh1 = geometries(g1) assert fabs(volume(sh1[14]) - volume(sh1[21])) < 1e-5, 'Not the same volume %f' % fabs( volume(sh1[25]) - volume(sh1[13]))
def test_LMul_Branch(): data = shared_data(openalea.groalea) f1 = data / "LMul_Branch" / "LMul_Branch_3Run_Interface_XEG.xml" parser = Parser() g1, scene1 = parser.parse(f1) sh1 = geometries(g1) assert fabs(volume(sh1[14]) - volume(sh1[21])) < 1e-5, "Not the same volume %f" % fabs( volume(sh1[25]) - volume(sh1[13]) )
def get_filename(fungus = 'brown_rust', year=2012, variety = 'Tremie12', nplants = 15, inoc=300, suffix=None): inoc = str(inoc) inoc = inoc.replace('.', '_') if suffix is None: suffix='' else: suffix='_'+suffix filename= variety+'_'+str(year)+'_'+str(nplants)+'pl_inoc'+inoc+suffix+'.csv' fungus_path = fungus + '_simulations' return str(shared_data(alinea.alep)/fungus_path/filename)
def load_colormaps(): from openalea.oalab.colormap.colormap_utils import Colormap, colormap_from_file colormaps = {} colormaps_path = Path(shared_data(openalea.oalab, 'colormaps/grey.lut')).parent for colormap_file in colormaps_path.walkfiles('*.lut'): colormap_name = str(colormap_file.name[:-4]) colormaps[colormap_name] = colormap_from_file(colormap_file, name=colormap_name) return colormaps
class PluginFloatWidgetSelector(ControlWidgetSelectorPlugin): controls = ['IFloat'] label = 'Float editor' required = ['IFloat.min', 'IFloat.max', 'IFloat.step'] edit_shape = ['responsive'] icon_path = shared_data(openalea.oalab, 'icons/IntWidgetSelector_hline.png') def __call__(self): from openalea.oalab.control.selector import FloatWidgetSelector return FloatWidgetSelector
def get_weather(start_date="2010-10-15 12:00:00", end_date="2011-08-01 01:00:00"): """ Get weather data for simulation. """ start = datetime.datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S') if start.year >= 2010: filename = 'Boigneville_0109'+str(start.year)+'_3108'+str(start.year+1)+'_h.csv' meteo_path = shared_data(alinea.echap, filename) weather = Weather(meteo_path, reader = arvalis_reader) weather.check(['temperature_air', 'PPFD', 'relative_humidity', 'wind_speed', 'rain', 'global_radiation', 'vapor_pressure']) notation_dates_file = shared_data(alinea.alep, 'notation_dates/notation_dates_'+str(start.year+1)+'.csv') weather.check(varnames=['notation_dates'], models={'notation_dates':add_notation_dates}, notation_dates_file = notation_dates_file) else: start_yr = str(start.year)[2:4] end_yr = str(start.year+1)[2:4] filename = 'meteo'+ start_yr + '-' + end_yr + '.txt' meteo_path = shared_data(alinea.septo3d, filename) weather = Weather(data_file=meteo_path) weather.check(varnames=['wetness'], models={'wetness':wetness_rapilly}) weather.check(varnames=['degree_days'], models={'degree_days':linear_degree_days}, start_date=start_date, base_temp=0., max_temp=30.) weather.check(varnames=['septo_degree_days'], models={'septo_degree_days':linear_degree_days}, start_date=start_date, base_temp=0., max_temp=30.) return weather
def __init__(self): QtGui.QWidget.__init__(self) self.colormap_bar = QColormapBar() self.colormap_bar.setMinimumHeight(20) self.colormap_bar.setMinimumWidth(120) self.colormap_name = "grey" # self.label = QtGui.QLabel(self) # self.label.setText("Colormap") self.combobox = QtGui.QComboBox(self) # self.setMinimumHeight(50) colormap_names = [] # colormaps_path = Path(shared_data(tissuelab, 'colormaps/grey.lut')).parent colormaps_path = shared_data(openalea.oalab) / 'colormaps' for colormap_file in colormaps_path.walkfiles('*.lut'): colormap_name = str(colormap_file.name[:-4]) colormap_names.append(colormap_name) colormap_names.sort() # map between string and combobox index self.map_index = {} for s in colormap_names: self.combobox.addItem(s) self.map_index[s] = self.combobox.count() - 1 self.combobox.setCurrentIndex(self.map_index[self.colormap_name]) # Fill background to avoid to see text or widget behind self.setAutoFillBackground(True) AbstractQtControlWidget.__init__(self) self.combobox.currentIndexChanged.connect(self.updateColormap) self.colormap_bar.valueChanged.connect(self.valueChanged) layout = QtGui.QHBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) # line = QtGui.QHBoxLayout(self) # line.setContentsMargins(0, 0, 0, 0) # line.addWidget(self.label) # line.addWidget(self.combobox) # layout.addLayout(line) layout.addWidget(self.combobox) layout.addWidget(self.colormap_bar) self.value_changed_signal = self.valueChanged
def __init__(self): QtGui.QWidget.__init__(self) self.colormap_bar = QColormapBar() self.colormap_bar.setMinimumHeight(20) self.colormap_bar.setMinimumWidth(120) self.colormap_name = "grey" # self.label = QtGui.QLabel(self) # self.label.setText("Colormap") self.combobox = QtGui.QComboBox(self) # self.setMinimumHeight(50) colormap_names = [] # colormaps_path = Path(shared_data(tissuelab, 'colormaps/grey.lut')).parent colormaps_path = shared_data(tissuelab) / 'colormaps' for colormap_file in colormaps_path.walkfiles('*.lut'): colormap_name = str(colormap_file.name[:-4]) colormap_names.append(colormap_name) colormap_names.sort() # map between string and combobox index self.map_index = {} for s in colormap_names: self.combobox.addItem(s) self.map_index[s] = self.combobox.count() - 1 self.combobox.setCurrentIndex(self.map_index[self.colormap_name]) # Fill background to avoid to see text or widget behind self.setAutoFillBackground(True) AbstractQtControlWidget.__init__(self) self.combobox.currentIndexChanged.connect(self.updateColormap) self.colormap_bar.valueChanged.connect(self.valueChanged) layout = QtGui.QHBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) # line = QtGui.QHBoxLayout(self) # line.setContentsMargins(0, 0, 0, 0) # line.addWidget(self.label) # line.addWidget(self.combobox) # layout.addLayout(line) layout.addWidget(self.combobox) layout.addWidget(self.colormap_bar) self.value_changed_signal = self.valueChanged
def test_3D(): files = shared_data(openalea.strawberry).glob('*.mtg') mtg_path = dict((name(f), f) for f in files) gariguette = read_mtg_file(mtg_path['Gariguette']) gariguette.properties()['order'] = orders(gariguette) scene = visu3d.plot3d(gariguette, by=["Sample_date"], hide_leaves=False, display=False) assert scene.isValid() == True p = PlantGL(scene, group_by_color=True) assert len(p.object_ids) == 103
def test_length(): data = shared_data(openalea.groalea) f1 = data / 'length' / 'L_XEG_r.xml' f2 = data / 'length' / 'L_XEG_w.xml' parser = Parser() g1, scene1 = parser.parse(f1) parser = Parser() g2, scene2 = parser.parse(f2) assert len(g1) == len(g2) assert fabs(volume(scene1) - volume(scene2)) < 1e-5, 'Not the same volume %f' % fabs( volume(scene1) - volume(scene2))
def test_length(): data = shared_data(openalea.groalea) f1 = data / "length" / "L_XEG_r.xml" f2 = data / "length" / "L_XEG_w.xml" parser = Parser() g1, scene1 = parser.parse(f1) parser = Parser() g2, scene2 = parser.parse(f2) assert len(g1) == len(g2) assert fabs(volume(scene1) - volume(scene2)) < 1e-5, "Not the same volume %f" % fabs( volume(scene1) - volume(scene2) )
def sample_weather(periods=24): """ provides a sample weather instance for testing other modules """ from openalea.deploy.shared_data import shared_data import alinea.septo3d meteo_path = shared_data(alinea.septo3d, 'meteo00-01.txt') t_deb = "2000-10-01 01:00:00" seq = pandas.date_range(start="2000-10-02", periods=periods, freq='H') weather = Weather(data_file=meteo_path) weather.check( ['temperature_air', 'PPFD', 'relative_humidity', 'wind_speed', 'rain', 'global_radiation', 'vapor_pressure']) return seq, weather
def test_extract_at_module_scale(): files = shared_data(openalea.strawberry).glob('*.mtg') mtg_path = dict((name(f), f) for f in files) gariguette = read_mtg_file(mtg_path['Gariguette']) gariguette_extraction_at_module_scale = extract_at_module_scale(gariguette) assert len(gariguette_extraction_at_module_scale) == 241 gariguette_frequency = occurence_module_order_along_time(data= gariguette_extraction_at_module_scale,frequency_type= "cdf") assert len(gariguette_frequency) == 6 mean= gariguette_extraction_at_module_scale.groupby(["Genotype", "order"]).mean() sd= gariguette_extraction_at_module_scale.groupby(["Genotype", "order"]).std() assert len(mean) == 6 assert len(sd) == 6
class PluginFloatWidgetSelector(ControlWidgetSelectorPlugin): controls = ['IFloat'] name = 'FloatWidgetSelector' alias = 'Float editor' required = ['IFloat.min', 'IFloat.max', 'IFloat.step'] edit_shape = ['responsive'] icon_path = shared_data(openalea.oalab, 'icons/IntWidgetSelector_hline.png') @classmethod def load(cls): from openalea.oalab.plugins.controls.selectors import FloatWidgetSelector return FloatWidgetSelector
def get_weather(start_date="2010-10-15 12:00:00", end_date="2011-08-01 01:00:00"): """ Get weather data for simulation. """ start = datetime.datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S') if start.year >= 2010: filename = 'Boigneville_0109' + str( start.year) + '_3108' + str(start.year + 1) + '_h.csv' meteo_path = shared_data(alinea.echap, filename) weather = Weather(meteo_path, reader=arvalis_reader) weather.check([ 'temperature_air', 'PPFD', 'relative_humidity', 'wind_speed', 'rain', 'global_radiation', 'vapor_pressure' ]) notation_dates_file = shared_data( alinea.alep, 'notation_dates/notation_dates_' + str(start.year + 1) + '.csv') weather.check(varnames=['notation_dates'], models={'notation_dates': add_notation_dates}, notation_dates_file=notation_dates_file) else: start_yr = str(start.year)[2:4] end_yr = str(start.year + 1)[2:4] filename = 'meteo' + start_yr + '-' + end_yr + '.txt' meteo_path = shared_data(alinea.septo3d, filename) weather = Weather(data_file=meteo_path) weather.check(varnames=['wetness'], models={'wetness': wetness_rapilly}) weather.check(varnames=['degree_days'], models={'degree_days': linear_degree_days}, start_date=start_date, base_temp=0., max_temp=30.) weather.check(varnames=['septo_degree_days'], models={'septo_degree_days': linear_degree_days}, start_date=start_date, base_temp=0., max_temp=30.) return weather
def on_widget_changed(self): widget = None if self.cb_widget.currentIndex() == -1: return widget_name = self.widget_plugins[self.cb_widget.currentIndex()].name iname = self._interfaces[self.cb_interface.currentIndex()] icon_path = None for plugin in qt_widget_plugins(iname): if widget_name == plugin.name: widget = plugin.load() if hasattr(plugin, 'icon_path'): icon_path = plugin.icon_path if icon_path and not icon_path.exists(): icon_path = None else: icon_path = None if icon_path is None: icon_path = shared_data(openalea.oalab, 'icons/preview_%s.png' % iname) if icon_path and not icon_path.exists(): icon_path = None break if icon_path: pixmap = QtGui.QPixmap(icon_path) if pixmap.width() >= 400 or pixmap.height() >= 400: pixmap = pixmap.scaled(400, 400, QtCore.Qt.KeepAspectRatio) self.widget_preview.setPixmap(pixmap) self.l_widget.setToolTip( '<b>%s</b><br /><img src="%s" width="200" />' % (widget_alias(plugin), icon_path)) else: self.widget_preview.setText("No preview") if self._constraints: widget_constraints = self._constraints() self._layout_constraints.removeWidget(widget_constraints) widget_constraints.close() self._constraints = None # self.l_constraints.hide() if widget and hasattr(widget, 'edit_constraints'): widget_constraints = widget.edit_constraints() widget_constraints.setAttribute(QtCore.Qt.WA_DeleteOnClose) self._layout_constraints.addWidget(widget_constraints) # self.l_constraints.show() self._constraints = weakref.ref(widget_constraints)
def get_filename(fungus='brown_rust', year=2012, variety='Tremie12', nplants=15, inoc=300, suffix=None): inoc = str(inoc) inoc = inoc.replace('.', '_') if suffix is None: suffix = '' else: suffix = '_' + suffix filename = variety + '_' + str(year) + '_' + str( nplants) + 'pl_inoc' + inoc + suffix + '.csv' fungus_path = fungus + '_simulations' return str(shared_data(alinea.alep) / fungus_path / filename)
def on_widget_changed(self): widget = None if self.cb_widget.currentIndex() == -1: return widget_name = self.widget_plugins[self.cb_widget.currentIndex()].name iname = self._interfaces[self.cb_interface.currentIndex()] icon_path = None for plugin in qt_widget_plugins(iname): if widget_name == plugin.name: widget = plugin.load() if hasattr(plugin, "icon_path"): icon_path = plugin.icon_path if icon_path and not icon_path.exists(): icon_path = None else: icon_path = None if icon_path is None: icon_path = shared_data(openalea.oalab, "icons/preview_%s.png" % iname) if icon_path and not icon_path.exists(): icon_path = None break if icon_path: pixmap = QtGui.QPixmap(icon_path) if pixmap.width() >= 400 or pixmap.height() >= 400: pixmap = pixmap.scaled(400, 400, QtCore.Qt.KeepAspectRatio) self.widget_preview.setPixmap(pixmap) self.l_widget.setToolTip('<b>%s</b><br /><img src="%s" width="200" />' % (widget_alias(plugin), icon_path)) else: self.widget_preview.setText("No preview") if self._constraints: widget_constraints = self._constraints() self._layout_constraints.removeWidget(widget_constraints) widget_constraints.close() self._constraints = None # self.l_constraints.hide() if widget and hasattr(widget, "edit_constraints"): widget_constraints = widget.edit_constraints() widget_constraints.setAttribute(QtCore.Qt.WA_DeleteOnClose) self._layout_constraints.addWidget(widget_constraints) # self.l_constraints.show() self._constraints = weakref.ref(widget_constraints)
def import_mtgfile(filename): """Import a MTG file from genotype name, in sharedata repo :param filename: genotype = name of the file :type filename: string :return: a MTG loaded from the file :rtype: MTG """ filenames = filename files = shared_data(openalea.strawberry).glob('*.mtg') mtg_path = dict((name(f), f) for f in files) mtgfile = dict((k, f) for k, f in mtg_path.items() if k in filenames) if len(filenames) == 1: g = MTG(mtgfile[filenames[0]]) return g else: metaMTG = MTG() for i in mtgfile: metaMTG = algo.union(metaMTG, MTG(mtgfile[i])) return metaMTG
def test_df2waffle(): files = shared_data(openalea.strawberry).glob('*.mtg') mtg_path = dict((name(f), f) for f in files) mtg = read_mtg_file(mtg_path['Capriss']) df = extract_at_node_scale(mtg) node_scale = df2waffle(df, index='rank', date='2015/03/02', variable='branching_type') assert node_scale.shape == (20, 9) df = extract_at_module_scale(mtg) module_scale = df2waffle(df, index='order', date='2015/03/02', variable='crown_status', aggfunc='median') assert module_scale.shape == (3, 9)
def read_config(config_file): p = PhenomenalConfigParser() p.read(config_file) d = p.as_dict() if d['General']['configdir'] == 'SharedData': shared_directory = shared_data(alinea.phenomenal) else: shared_directory = d['General']['configdir'] for key in d: for sub_key in d[key]: if str(sub_key).startswith('mask'): d[key][sub_key] = cv2.imread( shared_directory / str(d[key][sub_key]), cv2.IMREAD_GRAYSCALE) if str(sub_key).startswith('background'): d[key][sub_key] = cv2.imread( shared_directory / str(d[key][sub_key]), cv2.IMREAD_UNCHANGED) return d
from openalea.deploy.shared_data import shared_data import openalea.mtg from openalea.mtg import * data = shared_data(openalea.mtg) ################################################################################ # 1. Object is directly compatible with viewer. Nothing to do ################################################################################ # Create object (big tree) g2 = MTG(data / 'agraf.mtg') dressing_data2 = dresser.DressingData(DiameterUnit=15) pf2 = PlantFrame(g2, TopDiameter='TopDia', DressingData=dressing_data2) pgl_scene = pf2.plot(gc=True, display=False) # Add it to world world['obj1'] = pgl_scene ################################################################################ # 2. Object is not directly compatible but provides # a method (_repr_geom_) to convert himself to a compatible type # (Currently PlantGL geometry, shape or scene) ################################################################################ # object type (generally defined in a separated module) from openalea.plantgl.all import Box class MyBox(object):
def get_shared_data(filename): return shared_data(openalea.oalab, filename)
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