Exemple #1
0
def create(modelroot, element,field):
        """Create table to record `field` from element `element`

        Tables are created under `dataRoot`, the names are generally
        created by removing `/model` in the beginning of `elementPath`
        and replacing `/` with `_`. If this conflicts with an existing
        table, the id value of the target element (elementPath) is
        appended to the name.
        """
        dataroot = modelroot+"/" + "data"
        if not _moose.exists(dataroot):
            _moose.Neutral(dataroot)
        '''
        if len(field) == 0 or ((element, field) in self._recordDict):
            return
        '''
        field = lst = [word[0].upper() + word[1:] for word in field.split()]
        field = " ".join(lst)
        
        if len(field) == 0 or len(element.neighbors['get%s'%(field)]) > 0:
            return
        # The table path is not foolproof - conflict is
        # possible: e.g. /model/test_object and
        # /model/test/object will map to same table. So we
        # check for existing table without element field
        # path in recording dict.
        relativePath = element.path.partition(modelroot)[-1]
        if relativePath.startswith('/'):
            relativePath = relativePath[1:]

        #Convert to camelcase
        
        tablePath =  relativePath.replace('/', '_') + '.' + field
        tablePath = re.sub('.', lambda m: {'[':'_', ']':'_'}.get(m.group(), m.group()),tablePath)
        
        if tablePath.startswith("_0__"):
            tablePath = tablePath[4:]
        
        #tablePath = dataroot + '/' +tablePath
        tablePath = dataroot+'/'+element.name+'.'+field[:2]
        if _moose.exists(tablePath):
            tablePath = '%s_%d' % (tablePath, element.getId().value)
        
        if not _moose.exists(tablePath):
            table = _moose.Table(tablePath)
            print 'Created', table.path, 'for plotting', '%s.%s' % (element.path, field)
            target = element
            _moose.connect(table, 'requestOut', target, 'get%s' % (field))
            
            tableEmitter.emit(QtCore.SIGNAL('tableCreated()'))
            #tableCreated.emit()
            return True
            #self.emit(QtCore.SIGNAL('tableCreated(PyQt_PyObject)'))
            #self.created.emit()
            
        return False
Exemple #2
0
def arrayelement(path, className='Neutral'):
    """Return a reference to an existing object as an instance of the
    right class. If path does not exist, className is used for
    creating an instance of that class with the given path"""
    if not _moose.exists(path):
        raise NameError('Object %s not defined' % (path))
    oid = _moose.ObjId(path)
    className = oid.getField('class')
    return eval('%sArray("%s")' % (className, path))
Exemple #3
0
def arrayelement(path, className='Neutral'):
    """Return a reference to an existing object as an instance of the
    right class. If path does not exist, className is used for
    creating an instance of that class with the given path"""
    if not _moose.exists(path):
        raise NameError('Object %s not defined' % (path))
    oid = _moose.ObjId(path)
    className = oid.getField('class')
    return eval('%sArray("%s")' % (className, path))
Exemple #4
0
def syncDataHandler(target):
    """Synchronize data handlers for target.

    Parameter:
    target -- target element or path or Id.
    """
    raise NotImplementedError('The implementation is not working for IntFire - goes to invalid objects. First fix that issue with SynBase or something in that line.')
    if isinstance(target, str):
        if not _moose.exists(target):
            raise ValueError('%s: element does not exist.' % (target))
        target = Id(target)
        _moose.syncDataHandler(target)
Exemple #5
0
def syncDataHandler(target):
    """Synchronize data handlers for target.

    Parameter:
    target -- target element or path or Id.
    """
    raise NotImplementedError(
        'The implementation is not working for IntFire - goes to invalid objects. First fix that issue with SynBase or something in that line.'
    )
    if isinstance(target, str):
        if not _moose.exists(target):
            raise ValueError('%s: element does not exist.' % (target))
        target = Id(target)
        _moose.syncDataHandler(target)
Exemple #6
0
def recordTarget(tablePath, target, field = 'vm', **kwargs):
    """Setup a table to record at given path.

    Make sure that all root paths in tablePath exists.

    Returns a table.
    """

    # If target is not an moose object but a string representing intended path
    # then we need to fetch the object first.

    if type( target) == str:
        if not _moose.exists(target):
            msg = "Given target `{}` does not exists. ".format( target )
            raise RuntimeError( msg )
        else:
            target = _moose.Neutral( target )

    assert target.path, "Target must have a valid moose path."

    table = _moose.Table( tablePath )
    assert table

    # Sanities field. 
    if field == "output":
        pass
    elif 'get' not in field:
        field = 'get'+field[0].upper()+field[1:]
    else:
        field = field[:2]+field[3].upper()+field[4:]
    try:
        print_utils.dump("TABLE"
                , "Connecting table {} to target {} field {}".format(
                    table.path
                    , target.path
                    , field
                    )
                )
        table.connect( 'requestOut', target, field )
    except Exception as e:
        debug.dump("ERROR"
                , [ "Failed to connect table to target"
                    , e
                    ]
                )
        raise e
    assert table, "Moose is not able to create a recording table"
    return table
Exemple #7
0
def create_table(tablePath, element, field, tableType):
    """Create table to record `field` from element `element`

    Tables are created under `dataRoot`, the names are generally
    created by removing `/model` in the beginning of `elementPath`
    and replacing `/` with `_`. If this conflicts with an existing
    table, the id value of the target element (elementPath) is
    appended to the name.
    """
    if _moose.exists(tablePath):
        table = _moose.element(tablePath)
    else:
        if tableType == "Table2":
            table = _moose.Table2(tablePath)
        elif tableType == "Table":
            table = _moose.Table(tablePath)
        _moose.connect(table, 'requestOut', element, 'get%s' % (field))
    return table
Exemple #8
0
def create_table(tablePath, element, field,tableType):
    """Create table to record `field` from element `element`

    Tables are created under `dataRoot`, the names are generally
    created by removing `/model` in the beginning of `elementPath`
    and replacing `/` with `_`. If this conflicts with an existing
    table, the id value of the target element (elementPath) is
    appended to the name.
    """
    if _moose.exists(tablePath):
        table = _moose.element(tablePath)
    else:
        if tableType == "Table2":
            table = _moose.Table2(tablePath)            
        elif tableType == "Table":
            table = _moose.Table(tablePath)
        _moose.connect(table, 'requestOut', element, 'get%s' % (field))
    return table
Exemple #9
0
def element(path):
    """Return a reference to an existing object as an instance of the
    right class. If path does not exist, raises NameError.

    Id or ObjId can be provided in stead of path"""
    if isinstance(path, Id):
        oid = path[0]
        path = path.getPath()
    elif isinstance(path, ObjId):
        oid = path
        path = oid.getField('path')
    elif isinstance(path, str):
        if not _moose.exists(path):
            raise NameError('Object %s not defined' % (path))
        oid = _moose.ObjId(path)
    else:
        raise TypeError('expected argument: Id/ObjId/str')
    className = oid.getField('class')
    return eval('%s("%s")' % (className, path))
Exemple #10
0
def element(path):
    """Return a reference to an existing object as an instance of the
    right class. If path does not exist, raises NameError.

    Id or ObjId can be provided in stead of path"""
    if isinstance(path, Id):
        oid = path[0]
        path = path.getPath()
    elif isinstance(path, ObjId):
        oid = path
        path = oid.getField('path')
    elif isinstance(path, str):
        if not _moose.exists(path):
            raise NameError('Object %s not defined' % (path))
        oid = _moose.ObjId(path)
    else:
        raise TypeError('expected argument: Id/ObjId/str')
    className = oid.getField('class')
    return eval('%s("%s")' % (className, path))
Exemple #11
0
def showfield(element, field='*', showtype=False):
    """Show the fields of the element, their data types and values in
    human readable format. Convenience function for GENESIS users.

    Parameters:

    element -- Element or path of an existing element or ObjId of an element.

    field -- Field to be displayed. If '*', all fields are displayed.

    showtype -- If True show the data type of each field.

    """
    if isinstance(element, str):
        if not _moose.exists(element):
            raise ValueError('%s -- no such moose object exists.' % (element))
        element = Neutral(element)
    if not isinstance(element, Neutral):
        if not isinstance(element, ObjId):
            raise TypeError(
                'Expected argument of type ObjId or Neutral or a path to an existing object. Found %s'
                % (type(element)))
        element = Neutral(element)
    if field == '*':
        value_field_dict = getFieldDict(element.className, 'valueFinfo')
        max_type_len = max([len(dtype) for dtype in value_field_dict.values()])
        max_field_len = max([len(dtype) for dtype in value_field_dict.keys()])
        print
        print '[', element.path, ']'
        for key, dtype in value_field_dict.items():
            if dtype == 'bad' or key == 'this' or key == 'dummy' or key == 'me' or dtype.startswith(
                    'vector') or 'ObjId' in dtype:
                continue
            value = element.oid_.getField(key)
            if showtype:
                print dtype.ljust(max_type_len + 4),
            print key.ljust(max_field_len + 4), '=', value
    else:
        try:
            print field, '=', element.getField(field)
        except AttributeError:
            pass  # Genesis silently ignores non existent fields
Exemple #12
0
def showfield(element, field='*', showtype=False):
    """Show the fields of the element, their data types and values in
    human readable format. Convenience function for GENESIS users.

    Parameters:

    element -- Element or path of an existing element or ObjId of an element.

    field -- Field to be displayed. If '*', all fields are displayed.

    showtype -- If True show the data type of each field.

    """
    if isinstance(element, str):
        if not _moose.exists(element):
            raise ValueError('%s -- no such moose object exists.' % (element))
        element = Neutral(element)
    if not isinstance(element, Neutral):
        if not isinstance(element, ObjId):
            raise TypeError('Expected argument of type ObjId or Neutral or a path to an existing object. Found %s' % (type(element)))
        element = Neutral(element)
    if field == '*':        
        value_field_dict = getFieldDict(element.className, 'valueFinfo')
        max_type_len = max([len(dtype) for dtype in value_field_dict.values()])
        max_field_len = max([len(dtype) for dtype in value_field_dict.keys()])
        print 
        print '[', element.path, ']'
        for key, dtype in value_field_dict.items():
            if dtype == 'bad' or key == 'this' or key == 'dummy' or key == 'me' or dtype.startswith('vector') or 'ObjId' in dtype:
                continue
            value = element.oid_.getField(key)
            if showtype:
                print dtype.ljust(max_type_len + 4),
            print key.ljust(max_field_len + 4), '=', value
    else:
        try:
            print field, '=', element.getField(field)
        except AttributeError:
            pass # Genesis silently ignores non existent fields
Exemple #13
0
    def __init__(self, *args, **kwargs):
        """
        A NeutralArray object can be constructed in many ways. The
        most basic one being:

        neutral = moose.NeutralArray('my_neutral_object', [3])

        This will create a NeutralArray object with name
        'my_neutral_object' containing 3 elements. The object will be
        created as a child of the current working entity. Any class
        derived from NeutralArray can also be created using the same
        constructor. Actually it takes keyword parameters to do that:

        intfire = moose.NeutralArray(path='/my_neutral_object', dims=[3], type='IntFire')

        will create an IntFire object of size 3 as a child of the root entity.

        If the above code is already executed,

        duplicate = moose.NeutralArray(intfire)

        will create a duplicate reference to the existing intfire
        object. They will share the same Id and any changes made via
        the MOOSE API to one will be effective on the other.
        
        """
        path = None
        dims = None
        self.id_ = None
        try:
            className = kwargs['type']
            self.className = className
        except KeyError:
            # This code is messy and depends on the class name. I
            # could not find a way to pass the element data type to
            # the class definition dynamically
            if not hasattr(self, 'className'):
                self.className = 'Neutral'
        try:
            dims = kwargs['dims']
        except KeyError:
            pass
        try:
            path = kwargs['path']
        except KeyError:
            pass
        if len(args) > 0:
            if isinstance(args[0], str):
                path = args[0]
            elif isinstance(args[0], Id):
                self.id_ = args[0]
            elif isinstance(args[0], int):
                self.id_ = Id(args[0])
        if len(args) > 1:
            dims = args[1]
        if len(args) > 2:
            self.className = args[2]
        # No existing Array element ot Id specified, create new
        # ArrayElement
        if self.id_ is None:
            if path is None:
                raise TypeError(
                    'A string path or an existing Id or an int value for existing Id must be the first argument to __init__'
                )
            if exists(path):
                self.id_ = _moose.Id(path=path)
                # Check if specified dimensions match the existing
                # object's dimensions
                if dims is not None:
                    shape = self.id_.getShape()
                    if isinstance(dims, int):
                        if shape[0] != dims:
                            raise ValueError(
                                'Specified dimensions do not match that of existing array object'
                            )
                    else:
                        if len(shape) != len(dims):
                            raise ValueError(
                                'Specified dimensions do not match that of existing array object'
                            )
                        for ii in range(len(shape)):
                            if shape[ii] != dims[ii]:
                                raise ValueError(
                                    'Specified dimensions do not match that of existing array object'
                                )
                else:
                    dims = (1)
            # Create a new ArrayElement
            _base_class = self.__class__
            _class_name = self.__class__.__name__
            if _class_name.endswith('Array'):
                _class_name = _class_name[:-len('Array')]
            # For classes extended in Python get to the first MOOSE base class
            while _class_name not in _moose_classes:
                _base_class = self.__base__
                if _base_class == object:
                    raise TypeError(
                        'Class %s does not inherit any MOOSE class.' %
                        (self.__class__.__name__))
                _class_name = _base_class.__name__
                if _class_name.endswith('Array'):
                    _class_name = _class_name[:-len('Array')]
            self.id_ = _moose.Id(path=path, dims=dims, type=_class_name)
        # Check for conversion from instance of incompatible MOOSE
        # class.
        orig_classname = self.id_[0].getField('class') + 'Array'
        if self.__class__.__name__ != orig_classname:
            orig_class = eval(orig_classname)
            self_class = self.__class__
            while self_class != object and self_class not in orig_class.mro():
                self_class = self_class.__base__
            if self_class == object:
                self.id_ = None
                raise TypeError('Cannot convert %s to %s' %
                                (orig_class, self.__class__))
Exemple #14
0
    def __init__(self, *args, **kwargs):
        """
        A NeutralArray object can be constructed in many ways. The
        most basic one being:

        neutral = moose.NeutralArray('my_neutral_object', [3])

        This will create a NeutralArray object with name
        'my_neutral_object' containing 3 elements. The object will be
        created as a child of the current working entity. Any class
        derived from NeutralArray can also be created using the same
        constructor. Actually it takes keyword parameters to do that:

        intfire = moose.NeutralArray(path='/my_neutral_object', dims=[3], type='IntFire')

        will create an IntFire object of size 3 as a child of the root entity.

        If the above code is already executed,

        duplicate = moose.NeutralArray(intfire)

        will create a duplicate reference to the existing intfire
        object. They will share the same Id and any changes made via
        the MOOSE API to one will be effective on the other.
        
        """
        path = None
        dims = None
        self.id_ = None
        try:
            className = kwargs['type']
            self.className = className
        except KeyError:
            # This code is messy and depends on the class name. I
            # could not find a way to pass the element data type to
            # the class definition dynamically
            if not hasattr(self, 'className'):
                self.className = 'Neutral'
        try:
            dims = kwargs['dims']
        except KeyError:
            pass
        try:
            path = kwargs['path']
        except KeyError:
            pass
        if len(args) > 0:
            if isinstance(args[0], str):
                path = args[0]
            elif isinstance(args[0], Id):
                self.id_ = args[0]
            elif isinstance(args[0], int):
                self.id_ = Id(args[0])
        if len(args) > 1:
            dims = args[1]
        if len(args) > 2:
            self.className = args[2]
        # No existing Array element ot Id specified, create new
        # ArrayElement
        if self.id_ is None:
            if path is None:
                raise TypeError('A string path or an existing Id or an int value for existing Id must be the first argument to __init__')
            if exists(path):
                self.id_ = _moose.Id(path=path)
                # Check if specified dimensions match the existing
                # object's dimensions
                if dims is not None:
                    shape = self.id_.getShape()
                    if isinstance(dims, int):
                        if shape[0] != dims:
                            raise ValueError('Specified dimensions do not match that of existing array object')
                    else:
                        if len(shape) != len(dims):
                            raise ValueError('Specified dimensions do not match that of existing array object')
                        for ii in range(len(shape)):
                            if shape[ii] != dims[ii]:
                                raise ValueError('Specified dimensions do not match that of existing array object')
                else:
                    dims = (1)
            # Create a new ArrayElement
            _base_class = self.__class__
            _class_name = self.__class__.__name__
            if _class_name.endswith('Array'):
                _class_name = _class_name[:-len('Array')]
            # For classes extended in Python get to the first MOOSE base class
            while _class_name not in _moose_classes:
                _base_class = self.__base__
                if _base_class == object:
                    raise TypeError('Class %s does not inherit any MOOSE class.' % (self.__class__.__name__))                    
                _class_name = _base_class.__name__
                if _class_name.endswith('Array'):
                    _class_name = _class_name[:-len('Array')]
            self.id_ = _moose.Id(path=path, dims=dims, type=_class_name)
        # Check for conversion from instance of incompatible MOOSE
        # class.
        orig_classname = self.id_[0].getField('class') + 'Array'
        if self.__class__.__name__ != orig_classname:
            orig_class = eval(orig_classname)
            self_class = self.__class__
            while self_class != object and self_class not in orig_class.mro():
                self_class = self_class.__base__
            if self_class == object:
                self.id_ = None
                raise TypeError('Cannot convert %s to %s' % (orig_class, self.__class__))