openalea.core package#
Submodules#
openalea.core.actor module#
This module provides an actor interface
- class openalea.core.actor.IActor[source]#
Bases:
objectInterface to emulate a function
The class
IActorimplements an interface to emulate a function. It has functions toinputs()andoutputs().- Examples:
>>> import openalea.core >>> a = openalea.core.actor.IActor()
- output(key)[source]#
Get value computed of the output
- Parameters:
key – a specified key
- Returns:
the corresponding value
openalea.core.alea module#
a script to run alea dataflow and scripts
- openalea.core.alea.function(factory)[source]#
Return a function which is evaluated like a python function.
factory is a NodeFactory.
- openalea.core.alea.get_node(component, inputs, pm=None)[source]#
retrieve a node from its component name and inputs
- Parameters:
component – todo
inputs – todo
pm – package manager
- openalea.core.alea.load_package_manager(*args)[source]#
Return the package manager
- Parameters:
pkg_id – package id
node_id – node id
- Returns:
package manager
- openalea.core.alea.run(component, inputs, pm=None, vtx_id=-1)[source]#
Run component with inputs. can exit by exception.
If node_id is given, eval the dataflow from that node and return the result.
openalea.core.category module#
This module defines category keywords to be used within wralea files
- class openalea.core.category.PackageManagerCategory[source]#
Bases:
objectThe PackageManagerCategory provides a Dictionary of keywords and categories.
This dictionary is used by the
PackageManagerclass so as to extract the category fields that are found in the __wralea__.py files. Those fields are gathered into a list that is shown within Visualea.Here below is the list of keywords to be used within the __wralea__ files – inside the category field. Each of these keywords (left column) corresponds to a label (right column) that will appear in the visualea interface. For instance, if “image” is found in the __wralea__ file, then the corresponding node will appear in “Image Processing/standard category”.
If you provide a keyword that is not in this list, this keyword will not be taken into account. However, a keyword may be appended with a “.” followed by any keywords that will be considered as a subcategory. For instance, a category called scene.myScene will appear in the standard main category “Scene Design” and in a sub-category myScene.
For now there are quite a few keywords that correspond to the same category. The goal in the mid-term in to merge them so that there is only 1 keyword per category.
keywords(__wralea__)
Category names in VisuAlea
image
Image Processing.standard
svg
Image Processing.svg
datatype
Python Functionalities.Datatype
functional
Python Functionalities.functional
math
Python Functionalities.math
python
Python Functionalities.standard
data
Raw Data (txt,geom,png,etc)
tutorial
Tutorial
workflow
Workflow
flow control
Workflow
system
System Interaction
io
Data I/O
file
Data I/O
test
Test
misc
Miscellaneous
spatial
Scene Design.spatial
scene
Scene Design
light
Scene Design.light
sky
Scene Design.sky
PGL Object Generator
Scene Design.PGL
demo
Demo
composite
Composite
descriptive
Data Processing.statistics
stat
Data Processing.statistics
statistics
Data Processing.statistics
regression
Data Processing.regression
fitting
Data Processing.fitting
distribution
Data Processing.distribution
test
Data Processing.statistical tests
string
Data processing.Data Manipulation…
codec
Data processing.Data Manipulation…
fractal analysis
Scene Design.Fractal Analysis
plot
Visualisation
graphics
Visualisation
graphic
Visualisation
visualization
Visualisation
visualisation
Visualisation
web
Web Services
unclassified
to Classify
openalea.core.cli module#
This module defines the command line interface. It is composed by a set of functions useable directly in the interpreter
openalea.core.codegen module#
codegen#
Extension to ast that allow ast -> python code generation.
- copyright:
Copyright 2008 by Armin Ronacher.
- license:
BSD.
- class openalea.core.codegen.SourceGenerator(indent_with, add_line_information=False)[source]#
Bases:
NodeVisitorThis visitor is able to transform a well formed syntax tree into python sourcecode. For more details have a look at the docstring of the node_to_source function.
- visit_GeneratorExp(node)#
- visit_List(node)#
- visit_ListComp(node)#
- visit_Set(node)#
- visit_SetComp(node)#
- openalea.core.codegen.to_source(node, indent_with=' ', add_line_information=False)[source]#
This function can convert a node tree back into python sourcecode. This is useful for debugging purposes, especially if you’re dealing with custom asts not generated by python itself.
It could be that the sourcecode is evaluable when the AST itself is not compilable / evaluable. The reason for this is that the AST contains some more data than regular sourcecode does, which is dropped during conversion.
Each level of indentation is replaced with indent_with. Per default this parameter is equal to four spaces as suggested by PEP 8, but it might be adjusted to match the application’s styleguide.
If add_line_information is set to True comments for the line numbers of the nodes are added to the output. This can be used to spot wrong line number information of statement nodes.
openalea.core.color_palette module#
- openalea.core.color_palette.HTMLColorToRGB(colorstring)[source]#
convert #RRGGBB to an (R, G, B) tuple. Taken from here: http://code.activestate.com/recipes/266466-html-colors-tofrom-rgb-tuples/ Many thanks go to the authors!
openalea.core.compositenode module#
A CompositeNode is a Node that contains other nodes connected in a directed graph. A CompositeNodeFactory instance is a factory that build CompositeNode instances. Different instances of the same factory can coexist and can be modified in a dataflow.
- class openalea.core.compositenode.CompositeNode(inputs=(), outputs=())[source]#
-
The CompositeNode is a container that interconnect different node instances between them in directed graph.
- add_node(node, vid=None, modify=True)[source]#
Add a node in the Graph with a particular id if id is None, autogenrate one
- Parameters:
node – the node instance
vid – element id
- Returns:
the id
- compute_external_io(vertex_selection, new_vid)[source]#
Return the list of input and output edges to connect the composite node.
- compute_io(v_list=None)[source]#
Return (inputs, outputs, connections)
representing the free port of node v_list is a vertex id list
- connect(src_id, port_src, dst_id, port_dst)[source]#
Connect 2 elements
- Parameters:
src_id – source node id
port_src – source output port number
dst_id – destination node id
port_dst – destination input port number
- disconnect(src_id, port_src, dst_id, port_dst)[source]#
Deconnect 2 elements
- Parameters:
src_id – source node id
port_src – source output port number
dst_id – destination node id
port_dst – destination input port number
- eval(*args, **kwds)[source]#
Evaluate the graph
Return True if the node need a reevaluation (like generator)
- eval_as_expression(vtx_id=None, step=False)[source]#
Evaluate a vtx_id
if node_id is None, then all the nodes without sons are evaluated
- mimetype = 'openalea/compositenode'#
- remove_edge(eid)[source]#
remove a specified edge from the graph
- Parameters:
eid (eid) – id of the edge to remove
- set_io(inputs, outputs)[source]#
Define inputs and outputs
Inputs and outputs are list of dict(name=’’, interface=’’, value=’’)
- simulate_destruction_notifications()[source]#
emits messages as if we were adding elements to the composite node
- class openalea.core.compositenode.CompositeNodeFactory(*args, **kargs)[source]#
Bases:
AbstractFactory- copy(**args)[source]#
Copy factory.
- Parameters:
path – new search path
replace_pkg – old and new package names.
When replace package is set, change the package id for all the elt factories.
- instantiate(call_stack=None)[source]#
Create a CompositeNode instance and allocate all elements This function overide default implementation of NodeFactory
- Parameters:
call_stack – the list of NodeFactory id already in recursion stack (in order to avoid infinite loop)
- instantiate_node(vid, call_stack=None)[source]#
Partial instantiation
instantiate only elt_id in CompositeNode
- Parameters:
call_stack – a list of parent id (to avoid infinite recursion)
- instantiate_widget(node=None, parent=None, edit=False, autonomous=False)[source]#
Return the corresponding widget initialised with node
If node is None, the node is allocated else a composite widget composed with the node sub widget is returned.
- mimetype = 'openalea/compositenodefactory'#
The CompositeNodeFactory is able to create CompositeNode instances Each node has an unique id : the element id (elt_id)
- paste(cnode, data_modifiers=[], call_stack=None, meta=False)[source]#
Paste to an existing CompositeNode instance
- Parameters:
cnode – composite node instance
data_modifiers – list of 2-uple (key, function) to apply to internal data (for instance to move the node)
call_stack – the list of NodeFactory id already in recursion stack (in order to avoid infinite loop)
- Returns:
the list of created id
- class openalea.core.compositenode.CompositeNodeInput(inputs)[source]#
Bases:
NodeDummy node to represent the composite node inputs
- class openalea.core.compositenode.CompositeNodeOutput(outputs)[source]#
Bases:
NodeDummy node to represent the composite node outputs
- class openalea.core.compositenode.ContinuousEvalListener(dataflow, vid)[source]#
Bases:
AbstractListenerWhen notified this listener reexecute a dataflow on a particular vid)
- class openalea.core.compositenode.JSONCNFactoryWriter(factory)[source]#
Bases:
PyCNFactoryWriter
- class openalea.core.compositenode.PyCNFactoryWriter(factory)[source]#
Bases:
objectCompositeNodeFactory python Writer
- sgfactory_template = '\n\n$NAME = CompositeNodeFactory(name=$PNAME,\n description=$DESCRIPTION,\n category=$CATEGORY,\n doc=$DOC,\n inputs=$INPUTS,\n outputs=$OUTPUTS,\n elt_factory=$ELT_FACTORY,\n elt_connections=$ELT_CONNECTIONS,\n elt_data=$ELT_DATA,\n elt_value=$ELT_VALUE,\n elt_ad_hoc=$ELT_AD_HOC,\n lazy=$LAZY,\n eval_algo=$EVALALGO,\n )\n\n'#
openalea.core.ctypes_ext module#
This file contains fixes for shared library location under different oses
openalea.core.customexception module#
- exception openalea.core.customexception.CustomException(*args, **kargs)[source]#
Bases:
ExceptionCustomException is an extension of builtin Exception. Goal is to provide an unique structure for all kind of exceptions to allow high-level exception handling.
- For this reason, CustomException always provides :
a title (getTitle)
a message (getMessage)
a detailed description (getDesc)
Typicall use is :
- def print_error(error):
“number of error arguments has no importance” print_in_red(error.getTitle()) print_in_blue(error.getMessage())
- try :
action
- except CustomExceptionNumberOne,error :
print_error(error)
- except CustomExceptionNumberTwo,error :
print_error(error)
- except CustomExceptionNumberThree,error :
fix the problem
# CustomExceptionNumberFour isn’t intercepted here but for example in GUI classes else :
print ‘done’
If CustomException takes one argument, you can reach it using “%(value)s”. If it takes more than one, you must reimplement _kargs method.
Example :
class ErrNotMatchingPuzzlePiece(CustomException): title = u'Error: puzzle pieces do not match' message = u'%(compass_1)s part of piece %(piece_1)%s do not match %(compass_2)s part of piece %(piece_2)%s' desc = "This error is raised because ..." def _kargs(self): return dict( compass_1=unicode(self._args[0].num), piece_1=self._args[1], compass_2=unicode(self._args[2].num), piece_2=self._args[3], ) #two raise this exception: raise ErrNotMatchingPuzzlePiece(p1, u'North', p2, u'South') # with p1 and p2 two "Piece" objects containing a "num" attribute.
- desc = 'No details available'#
- message = 'An unknown error occurs'#
- title = 'Unknown Error'#
- exception openalea.core.customexception.UserException(*args, **kargs)[source]#
Bases:
CustomException
openalea.core.data module#
Data management classes
- class openalea.core.data.Data(**kwargs)[source]#
Bases:
object- property code#
- property content#
- default_file_name = 'filename.ext'#
- default_name = 'Data'#
- extension = 'ext'#
- property filename#
- icon = 'Crystal_Clear_app_kcmdf.png'#
- mimetype = None#
- property name#
- pattern = '*.ext'#
- class openalea.core.data.DataFactory(name, description='', editors=None, includes=None, **kargs)[source]#
Bases:
AbstractFactoryData representation as factory
- instantiate(call_stack=[])[source]#
Return a node instance
- Parameters:
call_stack – the list of NodeFactory id already in call stack (in order to avoid infinite recursion)
- class openalea.core.data.DataNode(packagedata, editors=None, includes=[])[source]#
Bases:
NodeNode representing a Data
- class openalea.core.data.PackageData(pkg_name, filename, package=None)[source]#
Bases:
objectString representing a package data
openalea.core.dataflow module#
This module provide an implementation of a dataflow
- class openalea.core.dataflow.DataFlow[source]#
Bases:
PropertyGraphDirected graph with connections between in_ports of vertices and out_port of vertices ports are typed
- add_actor(actor, vid=None)[source]#
create a vertex and the corresponding ports and associate it with the given actor return: vid
- add_in_port(vid, local_pid, pid=None)[source]#
add a new in port to vertex pid using local_pid use pid as global port id if specified or create a new one if None raise an error if pid is already used
- Returns:
pid used
- Return type:
pid
- add_out_port(vid, local_pid, pid=None)[source]#
add a new out port to vertex pid using local_pid use pid as global port id if specified or create a new one if None raise an error if pid is already used
- Returns:
pid used
- Return type:
pid
- add_vertex(vid=None)[source]#
add a vertex to the graph, if vid is not provided create a new vid
- Parameters:
vid (vid) – the id of the vertex to add, default=None
- Returns:
the id of the created vertex
- Return type:
vid
- connect(source_pid, target_pid, eid=None)[source]#
connect the out port source_pid with the in_port target_pid use eid if not None or create a new one raise an error if eid is already used
- Returns:
eid used
- Return type:
eid
- get_all_parent_nodes(vid)[source]#
Return an iterator of vextex id corresponding to all the parent node of vid
- in_ports(vid=None)[source]#
iter on all in ports of a given vertex iter on all in ports of the dataflow if vid is None
- Return type:
iter of pid
- is_out_port(pid)[source]#
test whether port refered by pid is an out port of its vertex :rtype: bool
- nb_connections(pid)[source]#
Compute number of edges connected to a given port.
- Parameters:
pid (-) – id of port
- Returns:
int
- out_ports(vid=None)[source]#
iter on all out ports of a given vertex iter on all out ports of the dataflow if vid is None
- Parameters:
vid – todo
- Return type:
iter of pid
- ports(vid=None)[source]#
iter on all ports of a given vertex iter on all ports of the dataflow if vid is None
- Return type:
iter of pid
- remove_vertex(vid)[source]#
remove a specified vertex of the graph remove all the edges attached to it
- Parameters:
vid (vid) – the id of the vertex to remove
- source_port(eid)[source]#
out port of the source vertex of the edge
- Parameters:
eid – todo
- Return type:
pid
openalea.core.dataflow_evaluation module#
This module provide algorithms to evaluate a dataflow
- class openalea.core.dataflow_evaluation.AbstractEvaluation(dataflow)[source]#
Bases:
objectAbstract evaluation algorithm
- eval(env, state, vid=None)[source]#
Evaluate associated dataflow.
Produce a valid state from a ready_to_evaluate one.
- Parameters:
env (-) – environment in which to perform the evaluation
state (-) – must be a ready_not_evaluate state
vid (-) – id of vertex to start the evaluation if None starts from the leaves of the dataflow
- class openalea.core.dataflow_evaluation.BruteEvaluation(dataflow)[source]#
Bases:
AbstractEvaluationFor each evaluation reevaluate each node of the dataflow.
- eval(env, state, vid=None)[source]#
Evaluate associated dataflow.
Produce a valid state from a ready_to_evaluate one.
- Parameters:
env (-) – environment in which to perform the evaluation
state (-) – must be a ready_not_evaluate state
vid (-) – id of vertex to start the evaluation if None starts from the leaves of the dataflow
openalea.core.dataflow_state module#
This module provide an implementation of a way to store data exchanged between nodes of a dataflow.
- class openalea.core.dataflow_state.DataflowState(dataflow)[source]#
Bases:
objectStore outputs of node and provide a way to access them
- cmp_port_priority(pid1, pid2)[source]#
Compare port priority.
Compare first x position of actors then use pids
- get_data(pid)[source]#
Retrieve data associated with a port.
If pid is an output port, retrieve single item of data if pid is an input port, retrieve data on all output ports connected to this port and return a list of it or a single item if only one port connected
- Parameters:
pid (-) – id of port either in or out
openalea.core.datapool module#
DataPool is a global dictionnary to share data between node instance
openalea.core.export_app module#
Export application functions
openalea.core.external module#
This module defines all the import used in wralea declarations
- openalea.core.external.add_docstring(obj)[source]#
Decorator that replace a function’s docstring by another from obj
This function should be used to decorate your wralea functions when docstring is equivalent to an already existing function or class.
- Parameters:
obj – a function or class that contains a docstring
- Example:
from math import abs @add_docstring(abs) def int_abs_function(x): if type(x) == int: return abs(x) else: raise TypeError("expect int as parameter")
openalea.core.factory module#
Abstract Factory classes and methods.
A Factory build Functor (Nodes or Pluggings) from its description. Factories instantiates Functors.
- class openalea.core.factory.AbstractFactory[source]#
Bases:
objectAbstract Factory is Factory base class.
- Properties:
name
metainfo
module
distribution (aka egg name)
- instantiate(call_stack=[])[source]#
Return a node instance
- Parameters:
call_stack – the list of NodeFactory id already in call stack (in order to avoir infinite recursion)
- mimetype = 'openalea/factory'#
openalea.core.factory_decorator module#
Decorators to attach signature information to functions
- openalea.core.factory_decorator.factory(f)[source]#
Flag the given function f as an openalea factory.
openalea.core.factory_parser module#
Automatical extraction of openalea factories for python modules and packages
TODO: bad name. The module is not parsed but imported.
- openalea.core.factory_parser.add_factory(pkg, fct, base_dir=None)[source]#
Add a (Node) Factory for function fct into package pkg
If function does not contain suitable meta_info, try to take it from pkg_info
- openalea.core.factory_parser.import_module(module_name, search_path=[])[source]#
load module_name
- Inputs:
- module_name
string with the name of the module as it is given to import (i.e. containing package dependancies separated by ‘.’)
- search_path
Additional search directories, given as a list of string, to look for module_name (and its parent package) if it is in not in sys.path.
- openalea.core.factory_parser.parse_module(module, module_dir=None)[source]#
Create an openalea package from a python module
- Inputs::
- module:
either a python module
or the full name of the module to parse (e.g. ‘pkg.sub_pkg.module’)
- module_dir:
Base directory of module if it is not in the python path.
openalea.core.funcsigs module#
Function signature objects for callables
Back port of Python 3.3’s function signature tools from the inspect module, modified to be compatible with Python 2.7 and 3.2+.
- class openalea.core.funcsigs.BoundArguments(signature, arguments)[source]#
Bases:
objectResult of Signature.bind call. Holds the mapping of arguments to the function’s parameters.
Has the following public attributes:
- argumentsOrderedDict
An ordered mutable mapping of parameters’ names to arguments’ values. Does not contain arguments’ default values.
- signatureSignature
The Signature object that created this instance.
- argstuple
Tuple of positional arguments values.
- kwargsdict
Dict of keyword arguments values.
- property args#
- property kwargs#
- property signature#
- class openalea.core.funcsigs.Parameter(name, kind, default=<class 'openalea.core.funcsigs._empty'>, annotation=<class 'openalea.core.funcsigs._empty'>, _partial_kwarg=False)[source]#
Bases:
objectRepresents a parameter in a function signature.
Has the following public attributes:
- namestr
The name of the parameter as a string.
- defaultobject
The default value for the parameter if specified. If the parameter has no default value, this attribute is not set.
- annotation
The annotation for the parameter if specified. If the parameter has no annotation, this attribute is not set.
- kindstr
Describes how argument values are bound to the parameter. Possible values: Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD, Parameter.VAR_POSITIONAL, Parameter.KEYWORD_ONLY, Parameter.VAR_KEYWORD.
- KEYWORD_ONLY = <_ParameterKind: 'KEYWORD_ONLY'>#
- POSITIONAL_ONLY = <_ParameterKind: 'POSITIONAL_ONLY'>#
- POSITIONAL_OR_KEYWORD = <_ParameterKind: 'POSITIONAL_OR_KEYWORD'>#
- VAR_KEYWORD = <_ParameterKind: 'VAR_KEYWORD'>#
- VAR_POSITIONAL = <_ParameterKind: 'VAR_POSITIONAL'>#
- property annotation#
- property default#
- empty#
alias of
_empty
- property kind#
- property name#
- replace(name=<class 'openalea.core.funcsigs._void'>, kind=<class 'openalea.core.funcsigs._void'>, annotation=<class 'openalea.core.funcsigs._void'>, default=<class 'openalea.core.funcsigs._void'>, _partial_kwarg=<class 'openalea.core.funcsigs._void'>)[source]#
Creates a customized copy of the Parameter.
- class openalea.core.funcsigs.Signature(parameters=None, return_annotation=<class 'openalea.core.funcsigs._empty'>, __validate_parameters__=True)[source]#
Bases:
objectA Signature object represents the overall signature of a function. It stores a Parameter object for each parameter accepted by the function, as well as information specific to the function itself.
A Signature object has the following public attributes and methods:
- parametersOrderedDict
An ordered mapping of parameters’ names to the corresponding Parameter objects (keyword-only arguments are in the same order as listed in code.co_varnames).
- return_annotationobject
The annotation for the return type of the function if specified. If the function has no annotation for its return type, this attribute is not set.
- bind(*args, **kwargs)[source]#
Get a BoundArguments object, that maps the passed args and kwargs to the function’s signature. Raises TypeError if the passed arguments can not be bound.
- bind_partial(*args, **kwargs)[source]#
Get a BoundArguments object, that partially maps the passed args and kwargs to the function’s signature. Raises TypeError if the passed arguments can not be bound.
- empty#
alias of
_empty
- property parameters#
- replace(parameters=<class 'openalea.core.funcsigs._void'>, return_annotation=<class 'openalea.core.funcsigs._void'>)[source]#
Creates a customized copy of the Signature. Pass ‘parameters’ and/or ‘return_annotation’ arguments to override them in the new copy.
- property return_annotation#
openalea.core.interface module#
This module defines Interface classes (I/O types)
- class openalea.core.interface.IBool(**kargs)[source]#
Bases:
IInterfaceBool interface
- class openalea.core.interface.IDateTime(**kargs)[source]#
Bases:
IInterfaceDateTime
- class openalea.core.interface.IDict(**kargs)[source]#
Bases:
IInterfaceDictionary interface
- class openalea.core.interface.IFileStr(filter='All (*)', save=False, **kargs)[source]#
Bases:
IStrFile Path interface
- class openalea.core.interface.IFloat(min=-16777216.0, max=16777216.0, step=1.0, **kargs)[source]#
Bases:
IInterfaceFloat interface
- class openalea.core.interface.IFunction(**kargs)[source]#
Bases:
IInterfaceFunction interface
- class openalea.core.interface.IInt(min=-16777216, max=16777216, step=1, **kargs)[source]#
Bases:
IInterfaceInt interface
- class openalea.core.interface.IInterface(**kargs)[source]#
Bases:
objectAbstract base class for all interfaces
- class openalea.core.interface.IInterfaceMetaClass(name, bases, dict)[source]#
Bases:
typeIInterface Metaclass Allow to register corresponding python type
- all = [IInterface, IStr, ISlice, IFileStr, IDirStr, ITextStr, ICodeStr, IFloat, IInt, IBool, IEnumStr, IRGBColor, IDateTime, ITuple3, ITuple, IFunction, ISequence, IDict, IData]#
- class openalea.core.interface.IInterfaceWidget(node, parent, parameter_str, interface)[source]#
Bases:
AbstractListenerBase class for widget associated to an interface
- class openalea.core.interface.IRGBColor(**kargs)[source]#
Bases:
IInterfaceRGB Color
- class openalea.core.interface.ISequence(**kargs)[source]#
Bases:
IInterfaceSequence interface (list, tuple, …)
- class openalea.core.interface.ISlice(**kargs)[source]#
Bases:
IInterfaceString interface
- class openalea.core.interface.IStr(**kargs)[source]#
Bases:
IInterfaceString interface
- class openalea.core.interface.ITuple(**kargs)[source]#
Bases:
IInterfaceTuple
- class openalea.core.interface.ITuple3(**kargs)[source]#
Bases:
IInterfaceTuple3
- class openalea.core.interface.IWidgetMetaClass(name, bases, dic, **kargs)[source]#
Bases:
typeInterfaceWidget Metaclass
- class openalea.core.interface.InterfaceWidgetMap(*args, **kw)[source]#
Bases:
dictSingleton class to map Interface with InterfaceWidget InterfaceWidgetMap inherits from dict class
- class openalea.core.interface.TypeInterfaceMap(*args, **kw)[source]#
Bases:
dictSingleton class to map Interface with standard python type InterfaceWidgetMap inherits from dict class
openalea.core.logger module#
Central logging module from openalea.
Simple Tutorial#
Just to see how easy it is to log something:
from openalea.core import logger
a = 1234
logger.debug("This is an evil value %d"%a)
This examples uses the defaults of the openalea.core.logger module: There is one base logger name “openalea” that logs to a default stream handler (prints out the logs to stderr).
There are more default loggers available:
logger.default_init(level=logger.DEBUG, handlers=["file"])
This line will make logs go to rotating files in ~/.openalea/.
If you’re running PyQt4:
logger.default_init(level=logger.DEBUG, handlers=["qt"])
Will make your logs go to a QStandardItemModel that you can get this way:
itemModel = logger.get_handler("qt")
You can directly use it in a QListView.
Per-package loggers#
The previous example used the central OpenAlea logger. However, we recommend you use a specific logger for your package, eg. Openalea.MTG:
from openalea.core import logger
mylogger = logger.get_logger("Openalea.MTG")
[...]
mylogger.debug("Execution reached this place...")
This will print nothing as mylogger is attached to no handler. You can attach it to Openalea’s handlers if they are any available:
logger.connect_loggers_to_handlers(mylogger, logger.get_handler_names())
mylogger.debug("Execution reached this other place...")
This will make every handler registered to OpenAlea receive the log.
Or you can connect it to your own handlers (In this case you can completely bypass Openalea.)
import logging
mylogger.addHandler(logging.FileHandler("path_to_file", mode="w"))
Indeed, mylogger is a logger.PatchedPyLogger slightly derived from standard logging.Logger.
- You can disconnect loggers and handlers::
logger.disconnect_loggers_from_handlers(mylogger, logger.get_handler_names())
This will disconnect all handlers know by openalea from mylogger.
Logging levels#
Logging typically happens at different levels, from the less important to the worst case. You have access to 5 default logging levels: DEBUG, INFO, WARNING, ERROR and CRITICAL.
Through the openalea.core.logger module:
logger.debug(str)
logger.info(str)
logger.warning(str)
logger.error(str)
logger.critical(str)
Or a custom logger:
mylogger = logger.get_logger("Openalea.MTG")
mylogger.debug(str)
mylogger.info(str)
mylogger.warning(str)
mylogger.error(str)
mylogger.critical(str)
You can also send logs of arbitrary levels using the log(level (int), msg (str)) module function (or mylogger.log(int, str)).
Logger objects can be set to ignore logs that happen at levels lower than a chosen one. The same goes for handlers.
In openalea.core.logger, you can set all loggers and handlers to have the same level:
logger.set_global_logger_level(logger.INFO) #DEBUG logs will not be sent to handlers
logger.set_global_handler_level(logger.ERROR) #DEBUG and ERROR logs will be ignored by handlers.
Of course you can do this more selectively:
lg = logger.get_logger("Openalea.MTG")
# lg will not send logs below the CRITICAL level:
lg.setLevel(logger.CRITICAL)
hd = logger.get_handler("qt")
# hd will not process logs below INFO level.
hd.setLevel(logger.INFO)
- class openalea.core.logger.LoggerOffice(*args, **kw)[source]#
Bases:
objectThis class behaves as the central registry of loggers and handlers for Openalea. This way, the application can query information about them.
- openalea.core.logger.connect_loggers_to_handlers(loggers, handlers)[source]#
Connects loggers to handlers. Each argument can be a single item or a list of them. Each item can be the name of the logger/handler or an instance of that.
- openalea.core.logger.critical(msg)[source]#
Send a critical level msg to openalea’s default logger. Handlers may or may not be connected yet.
- openalea.core.logger.debug(msg)[source]#
Send a debug level msg to openalea’s default logger. Handlers may or may not be connected yet.
- openalea.core.logger.defaultHandlerNames = ['file', 'stream']#
List of default handler names:
- openalea.core.logger.default_init(level=40, handlers=['file', 'stream'])[source]#
Configure the LoggerOffice with a default openalea logger and handlers named in handlers. The latter is a list of strings from “qt”, “file”, “stream”.
“qt” is only available if PyQt4 or PyQt5 is installed. Logs will go to a QStandardItemModel.
“file” creates a rotating file handler. Logs are stored in “~/.openalea/log.log.X” files X get incremented every day. Beyond 20 days olds files get deleted.
“stream” logs to stderr.
- openalea.core.logger.disconnect_loggers_from_handlers(loggers, handlers)[source]#
Disconnect loggers from handlers. Each argument can be a single item or a list of them. Each item can be the name of the logger/handler or an instance of that.
- openalea.core.logger.error(msg)[source]#
Send a error level msg to openalea’s default logger. Handlers may or may not be connected yet.
- openalea.core.logger.get_handler(name)[source]#
Returns the handler called name. It will always return the same handler for the same name.
- openalea.core.logger.get_handler_names()[source]#
Returns a list of handler names known by OpenAlea’s LoggerOffice
- openalea.core.logger.get_logger(name)[source]#
Returns the logger called name. It will always return the same logger for the same name.
- openalea.core.logger.get_logger_names()[source]#
Returns a list of logger names known by OpenAlea’s LoggerOffice
- openalea.core.logger.info(msg)[source]#
Send a info level msg to openalea’s default logger. Handlers may or may not be connected yet.
- openalea.core.logger.log(level, msg)[source]#
Send an arbitrary level msg to openalea’s default logger. Handlers may or may not be connected yet.
- openalea.core.logger.set_global_handler_level(level)[source]#
Set level of all known handlers to level.
openalea.core.manager module#
- class openalea.core.manager.GenericManager(items=None, item_proxy=None, autoload=['entry_points'])[source]#
Bases:
Observed,AbstractListener
openalea.core.metaclass module#
todo
- openalea.core.metaclass.get_noconflict_metaclass(bases, left_metas, right_metas)[source]#
Not intended to be used outside of this module, unless you know what you are doing.
openalea.core.metadatadict module#
- class openalea.core.metadatadict.HasAdHoc[source]#
Bases:
object
- class openalea.core.metadatadict.MetaDataDict(**kwargs)[source]#
Bases:
ObservedAttach meta data of a graphical representation of a graph component. This metadata can be used to customize the appearance of the node.
- add_metadata(key, valType, notify=True)[source]#
Creates a new entry in the meta data registry. The data to set will be of the given ‘valType’ type.
openalea.core.model module#
A Model is an object that can be run. It is generally used to define algorithms or process.
A model has inputs, outputs and an internal state. Inputs and outputs are used to allow communication between environnement and models and between models. Internal state is used by the model itself but cannot be reached from outside. This internal step is generally used when user want to execute model step by step, each step depending on previous one.
To define model instructions, you need to define at least “step” instructions. To do that, you can use:
To use a Model, you also need to define set_code method that is able to extract inputs, outpus and step, init, … from given source code.
Animate notification are not yet implemented.
To reset internal state, use init() method.
To run one step, use step() method.
Two convenience methods, see run() and “call”
can be used to reset internal state and run a given number of step (one by default)
By default, functions are generated for “init”, “run” and “animate”
- class openalea.core.model.IModel(**kwds)[source]#
Bases:
object- dtype = None#
- mimetype = None#
- set_code(code)[source]#
extract and set inputs, outputs and functions from code. For example, if “code” is:
''' input = a, b:int=5 output = c ''' def step(): c = a+b
you can extract input, output and step function. So, m = Model(“m1”) m.set_code(code)
is equivalent to
m = Model(“m1”) m.set_func_code(“step”, “c=a+b”) m.inputs_info = [InputObj(‘a’), InputObj(‘b:int=5’)] m.outputs_info = [OutputObj(‘c’)]
openalea.core.model_inout module#
Definition of Input and Output objects.
Code to parse the functions.
- class openalea.core.model_inout.InputObj(string='')[source]#
Bases:
object- Inputs object with:
an attribute name: name of the input obj (str) (mandatory)
an attribute interface: interface/type of the input obj (str) (optional)
an attribute default: default value of the input obj (str) (optional)
>>> from openalea.oalab.model.parse import InputObj >>> obj = InputObj('a:float=1') >>> obj.name 'a' >>> obj.default '1' >>> obj.interface IFloat >>> obj InputObj('a:IFloat=1')
- Parameters:
string – string object with format “input_name:input_type=input_default_value” or “input_name=input_default_value” or “input_name:input_type” or “input_name”
- openalea.core.model_inout.extract_functions(codestring, filename='tmp')[source]#
parse the code codestring and detect what are the functions defined inside :return: dict name -> code
- openalea.core.model_inout.parse_doc(docstring)[source]#
Parse a docstring.
- Returns:
model, inputs, outputs
- openalea.core.model_inout.parse_doc_in_code(string)[source]#
Take a lpy string_file, parse it and return only the docstring of the file.
- Parameters:
string – string representation of lpy file
- Returns:
docstring of the file if exists (must be a multiline docstring!). If not found, return None.
- Use:
>>> f = open(lpyfilename, "r") >>> lpystring = f.read() >>> f.close() >>> >>> docstring = parse_lpy(lpystring) >>> >>> from openalea.oalab.model.parse import parse_doc >>> if docstring is not None: ... model, inputs, outputs = parse_doc(docstring) ... print "model : ", model ... print "inputs : ", inputs ... print "outputs : ", outputs
- openalea.core.model_inout.parse_docstring(string)[source]#
parse a string (not a docstring), get the docstring and return information on the model.
- Use:
model, inputs, outputs = parse_docstring(multiline_string_to_parse)
- Parameters:
string – docstring to parse (string)
- Returns:
model, inputs, outputs
- openalea.core.model_inout.parse_function(docstring)[source]#
- Parse a docstring with format:
my_model(a:int=4, b)->r:int
Unused.
- Returns:
model, inputs, outputs
- openalea.core.model_inout.parse_input_and_output(docstring)[source]#
- Parse a docstring with format:
inputs = input_name:input_type=input_default_value, … outputs = output_name:output_type, …
- Use:
>>> from openalea.oalab.model.parse import parse_input_and_output >>> comment = ''' ... input = a:int=4, b ... output = r:float''' >>> inputs, outputs = parse_input_and_output(comment) >>> inputs ['a:int=4', 'b'] >>> outputs ['r:float']
- Returns:
inputs, outputs
openalea.core.node module#
Node and NodeFactory classes.
A Node is generalized functor which is embeded in a dataflow. A Factory build Node from its description. Factories instantiate Nodes on demand for the dataflow.
- class openalea.core.node.AbstractFactory(name, description='', category='', inputs=(), outputs=(), lazy=True, delay=0, view=None, alias=None, authors=None, **kargs)[source]#
Bases:
ObservedAbstract Factory is Factory base class
- get_authors()[source]#
returns node authors
if no authors is found within the node, then it takes the authors field found in its package.
- get_python_name()[source]#
Returns a valid python variable as name. This is used to store the factory into a python list (i.e. __all__).
- get_tip(asRst=False)[source]#
Return the node description
if no authors is found within the node, then it takes the authors field found in its package.
- instantiate(call_stack=[])[source]#
Return a node instance
- Parameters:
call_stack – the list of NodeFactory id already in call stack (in order to avoir infinite recursion)
- instantiate_widget(node=None, parent=None, edit=False, autonomous=False)[source]#
Return the corresponding widget initialised with node
- mimetype = 'openalea/nodefactory'#
- property package#
todo
- class openalea.core.node.AbstractNode[source]#
-
An AbstractNode is the atomic entity in a dataflow.
internal_data contains properties specified by users. They can be extended and the number is not fixed. We use a dict to distinguish these public properties to the others which are used for protected management.
- mimetype = 'openalea/node'#
- property raise_exception#
- class openalea.core.node.AbstractPort(vertex)[source]#
Bases:
dict,Observed,HasAdHocThe class describing the ports. AbstractPort is a dict for historical reason.
- class openalea.core.node.Annotation[source]#
Bases:
AbstractNode
- openalea.core.node.Factory#
alias of
NodeFactory
- class openalea.core.node.FuncNode(inputs, outputs, func)[source]#
Bases:
NodeNode with external function or function
- property process_obj#
Return the process obj
- class openalea.core.node.InputPort(node)[source]#
Bases:
AbstractPortThe class describing the input ports
True if the port should not be displayed.
- class openalea.core.node.Node(inputs=(), outputs=())[source]#
Bases:
AbstractNodeIt is a callable object with typed inputs and outputs. Inputs and Outpus are indexed by their position or by a name (str)
- property block#
todo
- property caption#
Return the node caption
- property delay#
todo
- eval()[source]#
Evaluate the node by calling __call__ Return True if the node needs a reevaluation and a timed delay if the node needs a reevaluation at a later time.
- get_input_port(name=None)[source]#
Gets port by name.
Long description of the function functionality.
- Parameters:
name (string) – the name of the port
- Returns:
Input port characterized by name
- Return type:
Return the hidden state of a port
- property lazy#
todo
- notify_listeners(event)[source]#
Send a notification to all listeners
- Parameters:
event – an object to pass to the notify function
- property process_obj#
Return the process obj
- set_io(inputs, outputs)[source]#
Define the number of inputs and outputs
- Parameters:
inputs – list of dict(name=’X’, interface=IFloat, value=0)
outputs – list of dict(name=’X’, interface=IFloat)
Set the hidden state of a port.
- Parameters:
index_key – the input port index.
state – a boolean value.
- unvalidate_input(index_key, notify=True)[source]#
Unvalidate node and notify listeners.
This method is called when the input value has changed.
- property user_application#
todo
- class openalea.core.node.NodeFactory(name, description='', category='', inputs=None, outputs=None, nodemodule='', nodeclass=None, widgetmodule=None, widgetclass=None, search_path=None, authors=None, **kargs)[source]#
Bases:
AbstractFactoryA Node factory is able to create nodes on demand, and their associated widgets.
- get_node_module()[source]#
Return the python module object (if available) Raise an Import Error if no module is associated
- get_node_src(cache=True)[source]#
Return a string containing the node src Return None if src is not available If cache is False, return the source on the disk
- instantiate(call_stack=[])[source]#
Returns a node instance. :param call_stack: the list of NodeFactory id already in call stack (in order to avoir infinite recursion)
- class openalea.core.node.OutputPort(node)[source]#
Bases:
AbstractPortThe class describing the output ports
- class openalea.core.node.PyNodeFactoryWriter(factory)[source]#
Bases:
objectNodeFactory python Writer
- nodefactory_template = '\n\n$NAME = Factory(name=$PNAME,\n authors=$AUTHORS,\n description=$DESCRIPTION,\n category=$CATEGORY,\n nodemodule=$NODEMODULE,\n nodeclass=$NODECLASS,\n inputs=$LISTIN,\n outputs=$LISTOUT,\n widgetmodule=$WIDGETMODULE,\n widgetclass=$WIDGETCLASS,\n )\n\n'#
openalea.core.observer module#
This module defines all the classes for the Observer design Pattern
- class openalea.core.observer.AbstractListener[source]#
Bases:
objectListener base class
- call_notify(sender, event=None)[source]#
Basic implementation call directly notify function Sub class can override this method to implement different call strategy (like signal slot)
- notify(sender, event=None)[source]#
This function is called by observed objects
- Parameters:
sender – the observed object which send notification
event – the data associated to the notification
- notify_lock = None#
- class openalea.core.observer.Observed[source]#
Bases:
objectObserved Object
- exclusive_command(who, command, *args, **kargs)[source]#
Executes a call “command” and if it triggers any signal from this observed object along the way, “who” will be the only one to be notified
- notify_listeners(event=None)[source]#
Send a notification to all listeners
- Parameters:
event – an object to pass to the notify function
- register_listener(listener)[source]#
Add listener to list of listeners. If the observed is currently notifying, the registration is delayed until it finishes.
openalea.core.package module#
This module defines Package classes.
A Package is a deplyment unit and contains a factories (Node generator) and meta informations (authors, license, doc…)
- class openalea.core.package.AbstractPackageReader(filename)[source]#
Bases:
objectAbstract class to add a package in the package manager.
- class openalea.core.package.DynamicPackage(name, metainfo)[source]#
Bases:
PackageDictPackage for dynamical parsing of python file
- class openalea.core.package.Package(name, metainfo, path=None)[source]#
Bases:
PackageDictA Package is a dictionnary of node factory. Each node factory is able to generate node and their widgets.
Meta informations are associated with a package.
- get_metainfo(key)[source]#
Return a meta information. See the standard key in the __init__ function documentation.
- Parameters:
key – todo
- get_pkg_files()[source]#
Return the list of python filename of the package. The filename are relative to self.path
- is_directory()[source]#
New style package. A package is embeded in a unique directory. This directory can not contain more than one package. Thus, you can move, copy or delete a package by acting on the directory without ambiguity.
Return True if the package is embeded in a directory.
- mimetype = 'openalea/package'#
- class openalea.core.package.PyPackageReader(filename)[source]#
Bases:
AbstractPackageReaderBuild packages from wralea file Use ‘register_package’ function
- class openalea.core.package.PyPackageReaderVlab(filename)[source]#
Bases:
AbstractPackageReaderBuild a package from a vlab specification file.
- class openalea.core.package.PyPackageReaderWralea(filename)[source]#
Bases:
PyPackageReaderBuild a package from a __wralea__.py Use module variable
- class openalea.core.package.PyPackageWriter(package)[source]#
Bases:
objectWrite a wralea python file
- pkg_template = '\n$PKGNAME\n\n$METAINFO\n\n$ALL\n\n$FACTORY_DECLARATION\n'#
- wralea_template = '\n# -*- coding: latin-1 -*-\n# This file has been generated at $TIME\n\nfrom openalea.core import *\n\n$PKG_DECLARATION\n\n'#
- class openalea.core.package.UserPackage(name, metainfo, path=None)[source]#
Bases:
PackagePackage user editable and persistent
- create_user_compositenode(name, category, description, inputs, outputs)[source]#
Add a new user composite node factory to the package and save the package. Returns the cn factory.
openalea.core.path module#
path.py - An object representing a path to a file or directory.
- Original author:
Jason Orendorff <jason.orendorff@gmail.com>
- Contributors:
Mikhail Gusarov <dottedmag@dottedmag.net> Marc Abramowitz <marc@marc-abramowitz.com> Jason R. Coombs <jaraco@jaraco.com> Jason Chu <jchu@xentac.net> Vojislav Stojkovic <vstojkovic@syntertainment.com>
Example:
from path import path d = path(‘/home/guido/bin’) for f in d.files(’*.py’):
f.chmod(0755)
path.py requires Python 2.5 or later.
- class openalea.core.path.path(other)[source]#
Bases:
strRepresents a filesystem path.
For documentation on individual methods, consult their counterparts in os.path.
- access(mode)[source]#
Return true if current user has access to this path.
mode - One of the constants os.F_OK, os.R_OK, os.W_OK, os.X_OK
- property atime#
Last access time of the file.
- copy(dst, *, follow_symlinks=True)#
Copy data and mode bits (“cp src dst”). Return the file’s destination.
The destination may be a directory.
If follow_symlinks is false, symlinks won’t be followed. This resembles GNU’s “cp -P src dst”.
If source and destination are the same file, a SameFileError will be raised.
- copy2(dst, *, follow_symlinks=True)#
Copy data and metadata. Return the file’s destination.
Metadata is copied with copystat(). Please see the copystat function for more information.
The destination may be a directory.
If follow_symlinks is false, symlinks won’t be followed. This resembles GNU’s “cp -P src dst”.
- copyfile(dst, *, follow_symlinks=True)#
Copy data from src to dst in the most efficient way possible.
If follow_symlinks is not set and src is a symbolic link, a new symlink will be created instead of copying the file it points to.
- copymode(dst, *, follow_symlinks=True)#
Copy mode bits from src to dst.
If follow_symlinks is not set, symlinks aren’t followed if and only if both src and dst are symlinks. If lchmod isn’t available (e.g. Linux) this method does nothing.
- copystat(dst, *, follow_symlinks=True)#
Copy file metadata
Copy the permission bits, last access time, last modification time, and flags from src to dst. On Linux, copystat() also copies the “extended attributes” where possible. The file contents, owner, and group are unaffected. src and dst are path-like objects or path names given as strings.
If the optional flag follow_symlinks is not set, symlinks aren’t followed if and only if both src and dst are symlinks.
- copytree(dst, symlinks=False, ignore=None, copy_function=<function copy2>, ignore_dangling_symlinks=False, dirs_exist_ok=False)#
Recursively copy a directory tree and return the destination directory.
If exception(s) occur, an Error is raised with a list of reasons.
If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. If the file pointed to by the symlink doesn’t exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process.
You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this has no effect on platforms that don’t support os.symlink.
The optional ignore argument is a callable. If given, it is called with the src parameter, which is the directory being visited by copytree(), and names which is the list of src contents, as returned by os.listdir():
callable(src, names) -> ignored_names
Since copytree() is called recursively, the callable will be called once for each directory that is copied. It returns a list of names relative to the src directory that should not be copied.
The optional copy_function argument is a callable that will be used to copy each file. It will be called with the source path and the destination path as arguments. By default, copy2() is used, but any function that supports the same signature (like copy()) can be used.
If dirs_exist_ok is false (the default) and dst already exists, a FileExistsError is raised. If dirs_exist_ok is true, the copying operation will continue if it encounters existing directories, and files within the dst tree will be overwritten by corresponding files from the src tree.
- property ctime#
Creation time of the file.
- dirs() List of this directory's subdirectories.[source]#
The elements of the list are path objects. This does not walk recursively into subdirectories (but see path.walkdirs).
With the optional ‘pattern’ argument, this only lists directories whose names match the given pattern. For example, d.dirs(‘build-*’).
- property drive#
‘. This is always empty on systems that don’t use drive specifiers.
- Type:
The drive specifier, for example ‘C
- expand()[source]#
Clean up a filename by calling expandvars(), expanduser(), and normpath() on it.
This is commonly everything needed to clean up a filename read from a configuration file, for example.
- property ext#
The file extension, for example ‘.py’.
- files() List of the files in this directory.[source]#
The elements of the list are path objects. This does not walk into subdirectories (see path.walkfiles).
With the optional ‘pattern’ argument, this only lists files whose names match the given pattern. For example, d.files(’*.pyc’).
- fnmatch(pattern)[source]#
Return True if self.name matches the given pattern.
- pattern - A filename pattern with wildcards,
for example ‘*.py’.
- get_owner()#
Return the name of the owner of this file or directory. Follow symbolic links.
- glob(pattern)[source]#
Return a list of path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example, path(‘/users’).glob(’/bin/’) returns a list of all the files users have in their bin directories.
- joinpath(*others)#
Join first to zero or more path components, adding a separator character (first.module.sep) if needed. Returns a new instance of first._next_class.
- lines(encoding=None, errors='strict', retain=True)[source]#
Open this file, read all lines, return them in a list.
- Optional arguments:
- encoding - The Unicode encoding (or character set) of
the file. The default is None, meaning the content of the file is read as 8-bit characters and returned as a list of (non-Unicode) str objects.
- errors - How to handle Unicode errors; see help(str.decode)
for the options. Default is ‘strict’
- retain - If true, retain newline characters; but all newline
character combinations (’r’, ‘n’, ‘rn’) are translated to ‘n’. If false, newline characters are stripped off. Default is True.
This uses ‘U’ mode.
- listdir() List of items in this directory.[source]#
Use D.files() or D.dirs() instead if you want a listing of just files or just subdirectories.
The elements of the list are path objects.
With the optional ‘pattern’ argument, this only lists items whose names match the given pattern.
- module = <module 'posixpath' (frozen)>#
The path module to use for path operations.
- move(dst, copy_function=<function copy2>)#
Recursively move a file or directory to another location. This is similar to the Unix “mv” command. Return the file or directory’s destination.
If dst is an existing directory or a symlink to a directory, then src is moved inside that directory. The destination path in that directory must not already exist.
If dst already exists but is not a directory, it may be overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. Symlinks are recreated under the new name if os.rename() fails because of cross filesystem renames.
The optional copy_function argument is a callable that will be used to copy the source or it will be delegated to copytree. By default, copy2() is used, but any function that supports the same signature (like copy()) can be used.
A lot more could be done here… A look at a mv.c shows a lot of the issues this implementation glosses over.
- property mtime#
Last-modified time of the file.
- property name#
The name of this file or directory without the full path.
For example, path(‘/usr/local/lib/libpython.so’).name == ‘libpython.so’
- property namebase#
The same as path.name, but with one file extension stripped off.
For example, path(‘/home/guido/python.tar.gz’).name == ‘python.tar.gz’, but path(‘/home/guido/python.tar.gz’).namebase == ‘python.tar’
- property owner#
Name of the owner of this file or directory.
- property parent#
This path’s parent directory, as a new path object.
For example, path(‘/usr/local/lib/libpython.so’).parent == path(‘/usr/local/lib’)
- read_hash(hash_name)[source]#
Calculate given hash for this file.
List of supported hashes can be obtained from hashlib package. This reads the entire file.
- read_hexhash(hash_name)[source]#
Calculate given hash for this file, returning hexdigest.
List of supported hashes can be obtained from hashlib package. This reads the entire file.
- readlink()[source]#
Return the path to which this symbolic link points.
The result may be an absolute or a relative path.
- readlinkabs()[source]#
Return the path to which this symbolic link points.
The result is always an absolute path.
- relpathto(dest)[source]#
Return a relative path from self to dest.
If there is no relative path from self to dest, for example if they reside on different drives in Windows, then this returns dest.abspath().
- rmtree(ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None)#
Recursively delete a directory tree.
If dir_fd is not None, it should be a file descriptor open to a directory; path will then be relative to that directory. dir_fd may not be implemented on your platform. If it is unavailable, using it will raise a NotImplementedError.
If ignore_errors is set, errors are ignored; otherwise, if onexc or onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is platform and implementation dependent; path is the argument to that function that caused it to fail; and the value of exc_info describes the exception. For onexc it is the exception instance, and for onerror it is a tuple as returned by sys.exc_info(). If ignore_errors is false and both onexc and onerror are None, the exception is reraised.
onerror is deprecated and only remains for backwards compatibility. If both onerror and onexc are set, onerror is ignored and onexc is used.
- property size#
Size of the file, in bytes.
- splitall()[source]#
Return a list of the path components in this path.
The first item in the list will be a path. Its value will be either os.curdir, os.pardir, empty, or the root directory of this path (for example, ‘/’ or ‘C:\’). The other items in the list will be strings.
path.path.joinpath(*result) will yield the original path.
- splitdrive() Return (p.drive, <the rest of p>).[source]#
Split the drive specifier from this path. If there is no drive specifier, p.drive is empty, so the return value is simply (path(‘’), p). This is always the case on Unix.
- splitext() Return (p.stripext(), p.ext).[source]#
Split the filename extension from this path and return the two parts. Either part may be empty.
The extension is everything from ‘.’ to the end of the last path segment. This has the property that if (a, b) == p.splitext(), then a + b == p.
- stripext() Remove one file extension from the path.[source]#
For example, path(‘/home/guido/python.tar.gz’).stripext() returns path(‘/home/guido/python.tar’).
- text(encoding=None, errors='strict')[source]#
Open this file, read it in, return the content as a string.
This method uses ‘U’ mode, so ‘rn’ and ‘r’ are automatically translated to ‘n’.
Optional arguments:
- encoding - The Unicode encoding (or character set) of
the file. If present, the content of the file is decoded and returned as a unicode object; otherwise it is returned as an 8-bit str.
- errors - How to handle Unicode errors; see help(str.decode)
for the options. Default is ‘strict’.
- touch()[source]#
Set the access/modified times of this file to the current time. Create the file if it does not exist.
The UNC mount point for this path. This is empty for paths on local drives.
- walk() iterator over files and subdirs, recursively.[source]#
The iterator yields path objects naming each child item of this directory and its descendants. This requires that D.isdir().
This performs a depth-first traversal of the directory tree. Each directory is returned just before all its children.
The errors= keyword argument controls behavior when an error occurs. The default is ‘strict’, which causes an exception. The other allowed values are ‘warn’, which reports the error via warnings.warn(), and ‘ignore’.
- walkdirs() iterator over subdirs, recursively.[source]#
With the optional ‘pattern’ argument, this yields only directories whose names match the given pattern. For example, mydir.walkdirs(’*test’) yields only directories with names ending in ‘test’.
The errors= keyword argument controls behavior when an error occurs. The default is ‘strict’, which causes an exception. The other allowed values are ‘warn’, which reports the error via warnings.warn(), and ‘ignore’.
- walkfiles() iterator over files in D, recursively.[source]#
The optional argument, pattern, limits the results to files with names that match the pattern. For example, mydir.walkfiles(’*.tmp’) yields only files with the .tmp extension.
- write_bytes(bytes, append=False)[source]#
Open this file and write the given bytes to it.
Default behavior is to overwrite any existing file. Call p.write_bytes(bytes, append=True) to append instead.
- write_lines(lines, encoding=None, errors='strict', linesep='\n', append=False)[source]#
Write the given lines of text to this file.
By default this overwrites any existing file at this path.
This puts a platform-specific newline sequence on every line. See ‘linesep’ below.
lines - A list of strings.
- encoding - A Unicode encoding to use. This applies only if
‘lines’ contains any Unicode strings.
- errors - How to handle errors in Unicode encoding. This
also applies only to Unicode strings.
- linesep - The desired line-ending. This line-ending is
applied to every line. If a line already has any standard line ending (’r’, ‘n’, ‘rn’, u’x85’, u’rx85’, u’u2028’), that will be stripped off and this will be used instead. The default is os.linesep, which is platform-dependent (’rn’ on Windows, ‘n’ on Unix, etc.) Specify None to write the lines as-is, like file.writelines().
Use the keyword argument append=True to append lines to the file. The default is to overwrite the file. Warning: When you use this with Unicode data, if the encoding of the existing data in the file is different from the encoding you specify with the encoding= parameter, the result is mixed-encoding data, which can really confuse someone trying to read the file later.
- write_text(text, encoding=None, errors='strict', linesep='\n', append=False)[source]#
Write the given text to this file.
The default behavior is to overwrite any existing file; to append instead, use the ‘append=True’ keyword argument.
There are two differences between path.write_text() and path.write_bytes(): newline handling and Unicode handling. See below.
- Parameters:
written. (- text - str/unicode - The text to be)
used. (- encoding - str - The Unicode encoding that will be) – This is ignored if ‘text’ isn’t a Unicode string.
errors. (- errors - str - How to handle Unicode encoding) – Default is ‘strict’. See help(unicode.encode) for the options. This is ignored if ‘text’ isn’t a Unicode string.
of (- linesep - keyword argument - str/unicode - The sequence) – characters to be used to mark end-of-line. The default is os.linesep. You can also specify None; this means to leave all newlines as they are in ‘text’.
if (- append - keyword argument - bool - Specifies what to do) – the file already exists (True: append to the end of it; False: overwrite it.) The default is False.
— Newline handling.
write_text() converts all standard end-of-line sequences (’n’, ‘r’, and ‘rn’) to your platform’s default end-of-line sequence (see os.linesep; on Windows, for example, the end-of-line marker is ‘rn’).
If you don’t like your platform’s default, you can override it using the ‘linesep=’ keyword argument. If you specifically want write_text() to preserve the newlines as-is, use ‘linesep=None’.
This applies to Unicode text the same as to 8-bit text, except there are three additional standard Unicode end-of-line sequences: u’x85’, u’rx85’, and u’u2028’.
(This is slightly different from when you open a file for writing with fopen(filename, “w”) in C or open(filename, ‘w’) in Python.)
— Unicode
If ‘text’ isn’t Unicode, then apart from newline handling, the bytes are written verbatim to the file. The ‘encoding’ and ‘errors’ arguments are not used and must be omitted.
If ‘text’ is Unicode, it is first converted to bytes using the specified ‘encoding’ (or the default encoding if ‘encoding’ isn’t specified). The ‘errors’ argument applies only to this conversion.
openalea.core.pkgdict module#
Special Dict with case insensitive key and protected field
openalea.core.pkgmanager module#
This module defines the package manager.
It is able to find installed package and their wralea.py It stores the packages and nodes informations
- class openalea.core.pkgmanager.PackageManager(*args, **kw)[source]#
Bases:
ObservedThe PackageManager is a Dictionary of Packages It can locate OpenAlea packages on the system (with wralea).
- add_wralea_path(path, container)[source]#
Add a search path for wralea files
- Parameters:
path – a path string
container – set containing the path
- create_user_package(name, metainfo, path=None)[source]#
Create a new package in the user space and register it Return the created package :param path : the directory where to create the package
- dependencies(package_or_factory=None)[source]#
Return all the dependencies of a package or a factory.
- find_and_register_packages(no_cache=False)[source]#
Find all wralea on the system and register them If no_cache is True, ignore cache file
- find_vlab_dir(directory, recursive=True)[source]#
Find in a directory vlab specification file.
Search recursivly is recursive is True
- Returns:
a list of pkgreader instances
- find_wralea_dir(directory, recursive=True)[source]#
Find in a directory wralea files, Search recursivly is recursive is True
:return : a list of pkgreader instances
- find_wralea_files()[source]#
Find on the system all wralea.py files
:return : a list of pkgreader instances
- get_data(pattern='*.*', pkg_name=None, as_paths=False)[source]#
Return all data that match the pattern.
- get_factory_from_url(url)[source]#
Returns a node instance from the given url.
- Parameters:
url - is either a string or a urlparse.ParseResult instance.
It is encoded this way: oa://domain/packageName?fac=*factoryName*&ft=*factoryType* . “oa” means that it is meant to be used by openalea. “domain” MUST BE “local” for now. “packageName” is the name of the package “factoryName” is the of factory “factoryType” is one of {“CompositeNodeFactory”, “NodeFactory”, “DataFactory”}
- init(dirname=None, verbose=True)[source]#
Initialize package manager
If dirname is None, find wralea files on the system else load directory If verbose is False, don’t print any output
- missing_dependencies(package_or_factory=None)[source]#
Return all the dependencies of a package or a factory.
- reload(pkg=None)[source]#
Reload one or all packages.
If the package pkg is None reloa all the packages. Else reload only pkg.
- search_node(search_str, nb_inputs=-1, nb_outputs=-1)[source]#
Return a list of Factory corresponding to search_str If nb_inputs or nb_outputs is specified, return only node with the same number of (in/out) ports
- The results are sorted in the following way:
- 1 - Highest Prioritypresence of search_str in factory name
and position in the name (closer to the begining = higher score)
- 2 - ThenNumber of occurences of search_str in the factory
description.
3 - Then : Number of occurences of search_str in the category name 4 - Finally : presence of search_str in package name and position
in the name (close to the begining = higher score)
- class openalea.core.pkgmanager.PseudoGroup(name)[source]#
Bases:
PackageDictData structure used to separate dotted naming (packages, category)
- mimetype = 'openalea/package'#
- sep = '.'#
- class openalea.core.pkgmanager.PseudoPackage(name)[source]#
Bases:
PseudoGroupPackage structure used to separate dotted naming (packages, category)
openalea.core.pm_extend module#
openalea.core.script_library module#
This module defines the ScriptLibrary class to register objects with their names
openalea.core.serialization module#
- class openalea.core.serialization.BGEOMLoader[source]#
Bases:
AbstractLoaderSpecific loader that is used to manipulate PlantGL objects
- default_name = 'BGEOMLoader'#
- input_format = '*.BGEOM'#
- class openalea.core.serialization.BGEOMSaver[source]#
Bases:
objectSpecific loader that is used to manipulate PlantGL objects
- default_name = 'BGEOMSaver'#
- output_format = '*.BGEOM'#
- class openalea.core.serialization.BinaryLoader[source]#
Bases:
object- default_name = 'BinaryLoader'#
- input_format = '*'#
- class openalea.core.serialization.BinarySaver[source]#
Bases:
AbstractSaver- default_name = 'BinarySaver'#
- output_format = '*'#
- class openalea.core.serialization.CPickleLoader[source]#
Bases:
AbstractLoaderSpecific loader that use cPickle.loads
- default_name = 'CPickleLoader'#
- input_format = '*'#
- class openalea.core.serialization.CPickleSaver[source]#
Bases:
AbstractSaverSpecific saver that use cPickle.dump
- default_name = 'CPickleSaver'#
- output_format = '*'#
- class openalea.core.serialization.GenericLoader[source]#
Bases:
objectClassical loader that read file
- default_name = 'GenericLoader'#
- input_format = '*.py'#
- class openalea.core.serialization.GenericTextSaver[source]#
Bases:
AbstractSaverClassical saver that write str(obj) into file
- default_name = 'GenericSaver'#
- output_format = '*.py'#
- class openalea.core.serialization.IDeserializer[source]#
Bases:
objectGeneric interface class for savers
- dtype = []#
- options = []#
- protocols = []#
- class openalea.core.serialization.ILoader[source]#
Bases:
object- dtype = []#
- options = []#
- protocols = []#
- update(obj, path, protocol=None, **kwds)[source]#
Like “load” but update, if available, an existing object and return it. If no update is available, method must return new instance.
Ex:
data = MyData() loader = MyLoader() data2 = data.update('test.dat', data) data is data2 # True if update is supported, else False
- class openalea.core.serialization.ISaver[source]#
Bases:
objectGeneric interface class for savers
- dtype = []#
- options = []#
- protocols = []#
- class openalea.core.serialization.ISerializer[source]#
Bases:
objectGeneric interface class for savers
- dtype = []#
- options = []#
- protocols = []#
openalea.core.session module#
Session regroups all the data which can be stored between different executions of the system.
- class openalea.core.session.Session[source]#
Bases:
ObservedA session is composed by different workspaces, and an user package. A workspace is an open node A session can be saved on disk.
- USR_PKG_NAME = '__my_package__'#
- add_workspace(compositenode=None, notify=True)[source]#
Open a new workspace in the session if compositenode = None, create a new empty compositenode
- save(filename=None)[source]#
Save session in filename user_pkg and workspaces data are saved
Be careful, this method do not work very well if data are not persistent.
- property ws#
Return the current workspace object
openalea.core.settings module#
Setting class retrieve and set user configuration
- class openalea.core.settings.Settings(*args, **kw)[source]#
Bases:
objectRetrieve and set user configuration
- openalea.core.settings.get_default_home_dir()[source]#
Return the home directory (valid on linux and windows)
- openalea.core.settings.get_openalea_home_dir(name='.openalea')[source]#
Return the openalea home dirextory If it doesn’t exist, create it
- openalea.core.settings.get_openalea_tmp_dir(name='.openalea')[source]#
Return the openalea temporary project directory If it doesn’t exist, create it
openalea.core.signature module#
Signature class that instropect python functor based on the code
- class openalea.core.signature.Signature(f)[source]#
Bases:
objectObject to represent the signature of a function/method.
- Parameters:
f – a function object containing __name__ variable
- static get_callable_arguments(function)[source]#
Static method that returns 5 values for one entry object which can be any callable. The returned 5-uple is as follows: 0 - list-of-simple-arguments. Can be an empty list. 1 - list-of-(argname,argvalue)-arguments-with-defaults. Can be an empty list. 2 - name-of-vararg-argument. Can be None. 3 - name-of-keyword-argument. Can be None. 5 - boolean : True if function is a method, False otherwise… For Python defined callables, uses the “inspect” module. For builtins, tries some regexp parsing of the docstring.
openalea.core.signature2 module#
Signature class that instropect python functor based on the code
openalea.core.singleton module#
This module defines the singleton metaclass
openalea.core.threadmanager module#
This module defines the thread manager The Thread manager provides thread on demand
openalea.core.traitsui module#
View for organizing the component lookout.
- class openalea.core.traitsui.Group(label, *values, **keys)[source]#
Bases:
objectDescribes the group for View.
<Long description of the class functionality.>
openalea.core.unittest_tools module#
- class openalea.core.unittest_tools.EventTracker(debug=False)[source]#
Bases:
AbstractListener- property events#
openalea.core.util module#
- openalea.core.util.camel_case_to_lower(name)[source]#
- Examples:
>>> camel_case_to_lower('squareRoot') 'square_root'
>>> camel_case_to_lower('SquareRoot') 'square_root'
>>> camel_case_to_lower('ComputeSQRT') 'compute_sqrt'
>>> camel_case_to_lower('SQRTCompute') 'sqrt_compute'
- openalea.core.util.camel_case_to_upper(name)[source]#
- Examples:
>>> camel_case_to_upper('squareRoot') 'SQUARE_ROOT'
>>> camel_case_to_upper('SquareRoot') 'SQUARE_ROOT'
>>> camel_case_to_upper('ComputeSQRT') 'COMPUTE_SQRT'
>>> camel_case_to_upper('SQRTCompute') 'SQRT_COMPUTE'
>>> camel_case_to_upper('Char_U')
- openalea.core.util.to_camel_case(name)[source]#
- Examples:
>>> lower_to_camel_case(camel_case_to_lower('squareRoot')) 'SquareRoot'
>>> lower_to_camel_case(camel_case_to_lower('SquareRoot')) 'SquareRoot'
>>> lower_to_camel_case(camel_case_to_lower('ComputeSQRT')) 'ComputeSqrt'
>>> lower_to_camel_case(camel_case_to_lower('SQRTCompute')) 'SqrtCompute'
openalea.core.version module#
- try:
major, minor, post = numbers[0], numbers[1], numbers[2] patch = ‘.’.join(numbers[3:])
- except IndexError:
major, minor, post = ‘2’, ‘4’, ‘3’ patch = ‘0’ __version__ = ‘.’.join([major, minor, post])
openalea.core.vlab module#
doc todo
- class openalea.core.vlab.VlabObject(directory, pkgmanager)[source]#
Bases:
objectA vlab object is a directory containing a specification file, and a set of data.
- editors = ['MAP', 'loadmap', 'savemap', 'EDIT', 'SURFACE', 'bezieredit', 'PALETTE', 'palette', 'MEDIT', 'medit', 'GALLERY', 'gallery', 'EDIT', 'funcedit', 'panel', 'CHAR']#
- ignore = [';', '#']#
- name2program = {'CHAR': 'edit', 'EDIT': 'edit', 'GALLERY': 'gallery', 'MAP': 'medit', 'MEDIT': 'medit', 'PALETTE': 'palette', 'SURFACE': 'bezieredit', 'loadmap': 'palette'}#
- programs = ['cpfg', 'lpfg']#
- text = ['TEXT', 'HINTS']#
- class openalea.core.vlab.VlabObject2(*args, **kwds)[source]#
Bases:
VlabObject
- openalea.core.vlab.search(file, filenames)[source]#
Returns the filenames that are referenced in a file.
- openalea.core.vlab.vlab_object(directory, pkgmanager)[source]#
Create an openalea package from a vlab object. First, read the specification file and parse it. Create the list of data, the list of editors, and the list of programs. Build the graph of dependencies. Compute the layout of the graph. Create a package with data and a composite node.