def step(): global LSystem code = request.form['code'] code = code.encode('ascii', 'ignore') step = 0 if session.get('step') is not None: if code != session['code']: l = lpy.Lsystem() session['code'] = code try: l.set(code) except: return jsonify({'error' : 'Syntax error'}) session['step'] = l.derivationLength session['currentStep'] = 1 lstring = l.derive(session['currentStep']) ilstring = l.interpret(lstring) txtlstring = str(ilstring) LSystem = l return jsonify({'LString' : txtlstring, 'currentStep' : session['currentStep'], 'step' : session['step']}) else: with lock: session['currentStep'] += 1 lstring = LSystem.derive(session['currentStep']) ilstring = LSystem.interpret(lstring) txtlstring = str(ilstring) if session['currentStep'] < session['step']: return jsonify({'LString' : txtlstring, 'currentStep' : session['currentStep'], 'step' : session['step']}) else: step = session['step'] disconnect() return jsonify({'LString' : txtlstring, 'currentStep' : step, 'step' : step}) else: l = lpy.Lsystem() session['code'] = code try: l.set(code) except: return jsonify({'error' : 'Syntax error'}) session['step'] = l.derivationLength session['currentStep'] = 1 lstring = l.derive(session['currentStep']) ilstring = l.interpret(lstring) txtlstring = str(ilstring) LSystem = l return jsonify({'LString' : txtlstring, 'currentStep' : session['currentStep'], 'step' : session['step']})
def run(self): from openalea import lpy from openalea.plantgl import all lpy_globals = json.loads(luigi.DictParameter().serialize(self.lpy_globals)) with tempfile.TemporaryDirectory() as tmpdir: x = self.input().get().get_file(self.lpy_file_id) tmp_filename = os.path.join(tmpdir, "f.lpy") with open(tmp_filename, "wb") as f: f.write(x.read_raw()) lsystem = lpy.Lsystem(tmp_filename, globals=lpy_globals) # lsystem.context().globals()["SEED"] = self.seed for lstring in lsystem: t = all.PglTurtle() lsystem.turtle_interpretation(lstring, t) scene = t.getScene() output_file = self.output_file() fname = os.path.join(tmpdir, "plant.obj") scene.save(fname) classes = luigi.DictParameter().serialize(VirtualPlantConfig().classes).replace(" ", "") subprocess.run(["romi_split_by_material", "--", "--classes", classes, fname, fname], check=True) #subprocess.run(["romi_split_by_material", "--", "--classes", classes, fname, fname], check=True) subprocess.run(["romi_clean_mesh", "--", fname, fname], check=True) output_file.import_file(fname) output_mtl_file = self.output().get().create_file(output_file.id + "_mtl") output_mtl_file.import_file(fname.replace("obj", "mtl")) for m in self.metadata: m_val = lsystem.context().globals()[m] output_file.set_metadata(m, m_val)
def initialize(self): #for name, pnames in self.modules.items(): # for pname in pnames: # setattr(self, name+'_'+pname, np.array([], dtype=float)) parameters = { 'process': self } for n in self.externs: parameters[n]=getattr(self, n) parameters.update(gen_param_structs(self.modules, self)) if not self.graphicalparameters is None: code = open(self.lpyfile,'r').read() self.lsystem = lpy.Lsystem() self.lsystem.set(code+self.graphicalparameters.generate_py_code(), parameters) else: self.lsystem = lpy.Lsystem(self.lpyfile, parameters) self.lstring = self.lsystem.axiom self.scene = self.lsystem.sceneInterpretation(self.lstring)
def run(): out = sys.stdout outlog = open('outlog.txt', 'w') sys.stdout = outlog disconnect() l = lpy.Lsystem() code = request.form['code'] code = code.encode('ascii', 'ignore') try: l.set(code) except: outlog.close() sys.stdout = out outlog = open('outlog.txt', 'r') output = outlog.read() return jsonify({'error': "Syntax Error", 'output': output}) lstring = l.derive() ilstring = l.interpret(lstring) txtlstring = str(ilstring) # txtlstring = lstringtojson(ilstring) outlog.close() sys.stdout = out outlog = open('outlog.txt', 'r') output = outlog.read() return jsonify({'LString' : txtlstring, 'output': output})
def run(options, code, order=0, age=0, rank=0, height=0, vigor=0, d2a=0, leaf=0.15, max_step=210): l = lpy.Lsystem() l.set(code) l.derivationLength = int(max_step) l.context()['options'] = options l.context()['options'].context.order_coeff = order l.context()['options'].context.rank_coeff = rank l.context()['options'].context.height_coeff = height l.context()['options'].context.d2a_coeff = d2a l.context()['options'].context.age_coeff = age l.context()['options'].context.vigor_coeff = vigor l.context()['options'].leaf.resource = leaf res = l.iterate(1) Viewer.animation(False) tree = l.iterate(1, max_step, res) if production == False: l.plot(tree) Viewer.camera.set(Vector3(0, 90, 80), 90, -25) Viewer.frameGL.saveImage( 'pruning_%2.2f_%2.2f_%2.2f_%2.2f_%2.2f_%2.2f_%2.2f.png' % (order, height, rank, age, vigor, d2a, leaf), 'png') return tree
def run(self, exp_id): #Added by han on 16-06-2012 start_time = time.time() #print exp_id conf = ConfigParams(get_shared_data("stocatree.ini")) conf.apex.maximum_size = self.exp_inputs[exp_id][0] conf.leaf.max_area = self.exp_inputs[exp_id][1] conf.internode.max_length = self.exp_inputs[exp_id][2] conf.tree.branching_angle = self.exp_inputs[exp_id][3] conf.stocatree.select_trunk = self.exp_inputs[exp_id][4] print conf.stocatree.select_trunk l = lpy.Lsystem("stocatree.lpy") l.context()["options"] = conf l.context()["current_experiment"] = exp_id if self.data_dir == None: self.data_dir= l.context()["output_directory"] #l.iterate() l.animate() gc.collect() #Added by Han on 16-06-2012 end_time = time.time() running_duration = end_time - start_time #Added by Han on 16-06-2012 for calucating running duration for each experiment durations = open("durations.txt", "a") durations.write(str(exp_id)+","+str(running_duration)) durations.write("\n") durations.close()
def __initialize_parameters(self): self.__lp = LsystemParameters() if not self.is_magic: json_filename = self.__filename.split('.lpy')[0] + '.json' if Path(json_filename).exists(): with io.open(json_filename, 'r') as file: self.__lp.load(file) else: self.__lp.retrieve_from(lpy.Lsystem(self.__filename)) self.__lp.filename = json_filename
def rewind(): disconnect() l = lpy.Lsystem() code = request.form['code'] code = code.encode('ascii', 'ignore') try: l.set(code) except: return jsonify({'error' : 'Syntax error'}) lstring = l.axiom ilstring = l.interpret(lstring) txtlstring = str(ilstring) return jsonify({'LString' : txtlstring})
def __init__(self, shell): """ Parameters ---------- shell : IPython shell """ super(LpyMagics, self).__init__(shell) self._lsys = lpy.Lsystem() self._plot_format = 'png' # Allow publish_display_data to be overridden for # testing purposes. self._publish_display_data = publish_display_data
def launchOptions(savesimu, pix, length, area, angle, diameter, randomseed, optidx): conf = ConfigParams(iniFile) conf.internode.max_length = length # max internode length [m] conf.leaf.max_area = area # max leaf area [m2] conf.tree.branching_angle = angle # branching angle [degree] conf.apex.maximum_size = diameter # radius of apex [m] conf.output.savescene = savesimu # wether to save the scene and simulation conf.output.saveimage = pix # wether to take a picture of the scene conf.general.seed = randomseed # seed for random number generator conf.output.opti_idx = optidx # idx to identify the optimization experiment lsys = lpy.Lsystem(lsystemFile, {"options": conf}) lsys.animate()
def __init__(self, filename=None, code=None, unit=Unit.none, animate=False, dump='', context={}, lp=None, **kwargs): if filename: if filename.endswith('.lpy'): self.__filename = filename else: self.__filename = str(filename) + '.lpy' if not self.__filename and not code: raise ValueError('Neither lpy file nor code provided') self.__lsystem = lpy.Lsystem() self.__extra_context = context self.__lp = lp code_ = '' if self.__filename and Path(self.__filename).is_file(): with io.open(self.__filename, 'r') as file: code_ = file.read() else: self.is_magic = True code_ = code self.__codes = code_.split(lpy.LpyParsing.InitialisationBeginTag) self.__codes.insert(1, f'\n{lpy.LpyParsing.InitialisationBeginTag}\n') self.unit = unit self.animate = animate self.dump = dump self.on_msg(self.__on_custom_msg) if not isinstance(self.__lp, LsystemParameters): self.__initialize_parameters() self.__initialize_lsystem() self.__set_scene(0) super().__init__(**kwargs)
def launchMAppleT(seqid): for i in range(5): conf = ConfigParams( "MAppleT_FSPM.ini" ) # generate a ConfigParam object from the ini file #Adding the experimental parameter to the conf object conf.apex.maximum_size = 0.003 # radius of apex [m] conf.leaf.max_area = 0.003 # max leaf area [m2] conf.internode.max_length = 0.03 # max internode length [m] conf.tree.branching_angle = 45 # branching angle [degree] #conf.general.end_year = '1994-06-30' conf.stocatree.select_trunk = seqid # initial trunk sequence from sequences.seq [0-238] conf.output.opti_idx = str(seqid) + "_" + str(i) #define the lsystem file to use and to define the "options" of the lsystem context lsys = lpy.Lsystem("MAppleT.lpy", {"options": conf}) lsys.animate()
def run(): app = QApplication([]) time1 = time.time() l = lpy.Lsystem('stocatree.lpy') iter_by_dt = 8.05 nb_year = 2 N = int(365 * iter_by_dt * nb_year) #N = 3000 #-> end dec 1994 #N = 4400 #-> end june 1995 #N = 8000 #-> end sept 1996 res = l.iterate(N) l.plot(res) #Viewer.frameGL.setBgColor(170,170,255) Viewer.frameGL.saveImage('output.png', 'png') time2 = time.time() print 'Simulation took %s' % str(time2 - time1) l.plot(res)
def run(options_pruning, code, order=0, age=0, rank=0, height=0, vigor=0, d2a=0, leaf=0.15, pipe_fraction=0.9, growth_threshold=0.9): l = lpy.Lsystem() l.set(code) l.derivationLength = int(max_step) options_pruning.apex.growth_threshold = growth_threshold options_pruning.pipe.fraction = pipe_fraction l.context()['options'] = options_pruning l.context()['options'].context.order_coeff = order l.context()['options'].context.rank_coeff = rank l.context()['options'].context.height_coeff = height l.context()['options'].context.d2a_coeff = d2a l.context()['options'].context.age_coeff = age l.context()['options'].context.vigor_coeff = vigor l.context()['options'].leaf.resource = leaf l.context()['options'].pruning.method = 'trunk' l.context()['options'].pruning.trunk_time = 90 l.context()['options'].pruning.trunk_height = 20 res = l.iterate(1) Viewer.animation(False) tree = l.iterate(1, max_step, res) if production == False: l.plot(tree) Viewer.camera.set(Vector3(0, 90, 80), 90, -25) Viewer.frameGL.saveImage( 'pruning_%2.2f_%2.2f_%2.2f_%2.2f_%2.2f_%2.2f_%2.2f.png' % (order, height, rank, age, vigor, d2a, leaf), 'png') return tree
def runlpy(filename='experiment1.lpy', verbose=False, show=True): """Run a lsystem with **LPy** .. seealso:: vplants.Lpy package :param str filename: a valid filename representing the LPy file :param bool verbose: (default is False) :Example: :: from openalea.plantik.tools.runlpy import runlpy from openalea.plantik import get_shared_data filename = get_shared_data('pruning.lpy') (lsystem, lstring) = runlpy(filename, show=False) scene = lsystem.getLastComputeScene() """ if verbose: print 'starting simulation' time1 = time.time() l = lpy.Lsystem(filename) Viewer.animation(False) #l.animate() context = l.context() scales = {} parameters = {} modules = context.declaredModules() for m in modules: label = m.name parameters[m.name] = m.parameterNames scales[m.name] = m.scale if verbose: print scales print parameters #scales = {'A':4,'I':4,'L':4, 'B':2,'U':3, 'P':1} #assert parameters == {'A': ['Apex'], # 'I': ['Internode'], # 'L': ['Leaf'], # 'P':['Plant'], # 'B':['Branch'], # 'U':['GrowthUnit'], # } max_step = l.derivationLength if verbose: print "max step is ", max_step tree = l.iterate(1) for i in range(0, max_step): tree = l.iterate(i, 1, tree) #scene = l.sceneInterpretation(tree) #mtg1 = axialtree2mtg(tree, scales, scene, parameters) #print mtg1.property('Apex')[0] #[mtg2.order(id) for id in mtg2.property('Apex')] # update the radisu using a pipe model # 2 is the Root's id #for vid in traversal.post_order(mtg2, 2) #all_radius = plantframe.compute_radius(mtg1, 2, mtg1.property('Internode')[2].radius) #print tree #tree1 = mtg2axialtree(mtg1, scales, parameters, None) #print tree1 #del tree1[0] #del tree1[-1] #assert str(tree)==str(tree1[1]) #print 'strahler=', strahler(mtg1) time2 = time.time() if verbose: print 'Simulation took %s' % str(time2-time1) if show: l.plot(tree) Viewer.frameGL.setBgColor(170,170,255) Viewer.frameGL.setSize(1024, 1024) Viewer.frameGL.saveImage('output.png', 'png') lsystem = l lstring = tree return (lsystem, lstring)
import openalea.lpy as lpy from PyQt4.QtCore import * from PyQt4.QtGui import * from openalea.plantik.tools import mtgtools import numpy from openalea.plantik.tools.levenshtein import LevenshteinDistance from openalea.plantik.tools.strahler import * from openalea.stat_tool import * from openalea.sequence_analysis import * from openalea.plantik import get_shared_data app = QApplication([]) Viewer.start() Viewer.animation(False) l = lpy.Lsystem(get_shared_data('pruning.lpy')) options_pruning = l.context()['options'] options_pruning.general.verbose = False options_pruning.geometry.leaf_view = False finput = open(get_shared_data('pruning.lpy'), 'r') code = finput.read() production = False def run(options, code, order=0, age=0, rank=0, height=0, vigor=0, d2a=0, leaf=0.15, max_step=210): l = lpy.Lsystem() l.set(code) l.derivationLength = int(max_step) l.context()['options'] = options l.context()['options'].context.order_coeff = order
def run(): l = lpy.Lsystem('stocatree.lpy') l.animate()
def __init__(): self.l = lpy.Lsystem("stocatree.lpy")
def run(self): l = lpy.Lsystem("stocatree.lpy") l.animate()
from openalea.plantik.tools import mtgtools import numpy from openalea.plantik.tools.levenshtein import LevenshteinDistance from openalea.plantik.tools.strahler import * from openalea.stat_tool import * from openalea.sequence_analysis import * from openalea.plantik import get_shared_data app = QApplication([]) Viewer.start() Viewer.animation(False) #first we read the configuration file for this script, and the pruning model options = ConfigParams('parameter_analysis.ini') l = lpy.Lsystem(get_shared_data(options.general.filename)) options_pruning = l.context()['options'] options_pruning.general.verbose = False options_pruning.geometry.leaf_view = False finput = open(get_shared_data(options.general.filename), 'r') code = finput.read() production = False def run(options, code, order=0, age=0, rank=0,
import openalea.lpy as lpy from openalea.plantik.tools.config import ConfigParams from openalea.stocatree import get_shared_data conf = ConfigParams(get_shared_data('stocatree.ini')) conf.internode.max_length = 0.05 l = lpy.Lsystem("stocatree.lpy") #l = lpy.Lsystem("cnt.lpy") l.context()["options"] = conf l.context()["v"] = 6 l.animate() #l.iterate() #print l.context()["options"].internode.max_length
update_configuration('fruit', 'probability', numpy.random.uniform(0.30, 0.90)) # update_configuration('tree', # 'branching_angle', # numpy.random.randint(35, 55)) # # update_configuration('internode', # 'max_length', # numpy.random.uniform(0.01, 0.05)) # update_configuration('leaf', # 'max_area', # numpy.random.uniform(0.001, 0.01)) # update_configuration('fruit', # 'probability', # numpy.random.uniform(0.1, 0.7)) # update_configuration('stocatree', # 'select_trunk', # numpy.random.randint(1, 239)) # update_configuration('stocatree', 'select_trunk', i) lsys = lpy.Lsystem(confp.general.filename, {"options": confp}) lsys.animate() print("\nend\n")