コード例 #1
0
ファイル: fe_post.py プロジェクト: gitGNU/gnu_pyformex
 def Finalize(self):
     self.nid = inverseUniqueIndex(self.nodid)
     for k in self.elems.iterkeys():
         v = asarray(self.elems[k])
         self.elems[k] = asarray(self.nid[v])
     self.modeldone = True
     # we use lists, to keep the cases in order
     self.res = OrderedDict()
     self.step = None
     self.inc = None
コード例 #2
0
ファイル: menu.py プロジェクト: gitGNU/gnu_pyformex
 def __init__(self, title='AMenu', parent=None, before=None, items=None):
     """Create a menu."""
     self._title = title
     pf.debug("Creating menu %s" % title, pf.DEBUG.MENU)
     self.parent = parent
     self.separators = OrderedDict()
     self._actions_ = []
     self._submenus_ = []
     if items:
         self.insertItems(items)
     if parent and isinstance(parent, BaseMenu):
         before = parent.action(before)
         parent.insert_menu(self, before)
コード例 #3
0
def detectedSoftware(all=True):
    """Return a dict with all detected helper software"""
    if all:
        checkAllModules()
        checkAllExternals()

    system, host, release, version, arch = os.uname()
    soft = {
        'System':
        OrderedDict([
            ('pyFormex_version', the_version['pyformex']),
            ('pyFormex_installtype', pf.installtype),
            ('pyFormex_fullversion', pf.fullVersion()),
            ('pyFormex_libraries', ', '.join(Libraries())),
            ('pyFormex_shaders', ', '.join(Shaders())),
            ('Python_version', the_version['python']),
            ('Python_fullversion', sys.version.replace('\n', ' ')),
            ('System', system),
            ('Host', host),
            ('Release', release),
            ('Version', version),
            ('Arch', arch),
        ]),
        'Modules':
        the_version,
        'Externals':
        the_external,
    }
    return soft
コード例 #4
0
ファイル: objects.py プロジェクト: gitGNU/gnu_pyformex
    def odict(self):
        """Return the currently selected items as a dictionary.

        Returns an OrderedDict with the currently selected objects in the order
        of the selection.names.
        """
        return OrderedDict(zip(self.names, self.check(warn=False)))
コード例 #5
0
ファイル: fe_post.py プロジェクト: gitGNU/gnu_pyformex
    def Increment(self, step, inc, **kargs):
        """Add a new step/increment to the database.

        This method can be used to add a new increment to an existing step,
        or to add a new step and set the initial increment, or to just select
        an existing step/inc combination.
        If the step/inc combination is new, a new empty result record is created.
        The result record of the specified step/inc becomes the current result.
        """
        if not self.modeldone:
            self.Finalize()
        if step != self.step:
            if step not in self.res.keys():
                self.res[step] = OrderedDict()
            self.step = step
            self.inc = None
        res = self.res[self.step]
        if inc != self.inc:
            if inc not in res.keys():
                res[inc] = {}
            self.inc = inc
        self.R = self.res[self.step][self.inc]
コード例 #6
0
ファイル: postproc_menu.py プロジェクト: gitGNU/gnu_pyformex
result_types = OrderedDict([
    ('', 'None'),
    ('U0', 'X-Displacement'),
    ('U1', 'Y-Displacement'),
    ('U2', 'Z-Displacement'),
    ('U', '[Displacement]'),
    ('S0', 'X-Normal Stress'),
    ('S1', 'Y-Normal Stress'),
    ('S2', 'Z-Normal Stress'),
    ('S3', 'XY-Shear Stress'),
    ('S4', 'XZ-Shear Stress'),
    ('S5', 'YZ-Shear Stress'),
    ('SP0', '1-Principal Stress'),
    ('SP1', '2-Principal Stress'),
    ('SP2', '3-Principal Stress'),
    ('SF0', 'x-Normal Membrane Force'),
    ('SF1', 'y-Normal Membrane Force'),
    ('SF2', 'xy-Shear Membrane Force'),
    ('SF3', 'x-Bending Moment'),
    ('SF4', 'y-Bending Moment'),
    ('SF5', 'xy-Twisting Moment'),
    ('SINV0', 'Mises Stress'),
    ('SINV1', 'Tresca Stress'),
    ('SINV2', 'Hydrostatic Pressure'),
    ('SINV6', 'Third Invariant'),
    ('COORD0', 'X-Coordinate'),
    ('COORD1', 'Y-Coordinate'),
    ('COORD2', 'Z-Coordinate'),
    ('Computed', 'Distance from a point'),
])
コード例 #7
0
ファイル: elements.py プロジェクト: gitGNU/gnu_pyformex
    def __str__(self):
        return self.__name__

    @classmethod
    def __repr__(self):
        return "elementType(%s)" % self.__name__

    @classmethod
    def report(self):
        return "ElementType %s: ndim=%s, nplex=%s, nedges=%s, nfaces=%s" % (
            self.__name__, self.ndim, self.nplex(), self.nedges(),
            self.nfaces())


# all registered element types:
_registered_element_types = OrderedDict()


def createElementType(name,
                      doc,
                      ndim,
                      vertices,
                      edges=('', []),
                      faces=('', []),
                      **kargs):
    name = name.capitalize()
    if name in _registered_element_types:
        raise ValueError("Element type %s already exists" % name)

    #print "\n CREATING ELEMENT TYPE %s\n" % name
コード例 #8
0
ファイル: fe_post.py プロジェクト: gitGNU/gnu_pyformex
class FeResult(object):
    """Finite Element Results Database.

    This class can hold a collection of results from a Finite Element
    simulation. While the class was designed for the post-processing
    of Abaqus (tm) results, it can be used more generally to store
    results from any program performing simulations over a mesh.

    pyFormex comes with an included program `postabq` that scans an
    Abaqus .fil output file and translates it into a pyFormex script.
    Use it as follows::

      postabq job.fil > job.py

    Then execute the created script `job.py` from inside pyFormex. This
    will create an FeResult instance with all the recognized results.

    The structure of the FeResult class very closely follows that
    of the Abaqus results database. There are some attributes
    with general info and with the geometry (mesh) of the domain.
    The simulation results are divided in 'steps' and inside each step
    in 'increments'. Increments are usually connected to incremental time
    and so are often the steps, though it is up to the user to interprete
    the time. Steps could just as well be different unrelated simulations
    performed over the same geometry.

    In each step/increment result block, individual values can be accessed
    by result codes. The naming mostly follows the result codes in Abaqus,
    but components of vector/tensor values are number starting from 0, as
    in Python and pyFormex.

    Result codes:

    - `U`: displacement vector
    - `U0`, `U1`, `U2` : x, y, resp. z-component of displacement
    - `S`: stress tensor
    - `S0` .. `S5`: components of the (symmetric) stress tensor:
       0..2 : x, y, z normal stress
       3..5 : xy, yz, zx shear stress
    """

    _name_ = '__FePost__'
    re_Skey = re.compile("S[0-5]")
    re_Ukey = re.compile("U[0-2]")

    def __init__(self, name=_name_, datasize={'U': 3, 'S': 6, 'COORD': 3}):
        self.name = name
        self.datasize = datasize.copy()
        self.about = {
            'creator': pf.Version(),
            'created': pf.StartTime,
        }
        self.modeldone = False
        self.labels = {}
        self.nelems = 0
        self.nnodes = 0
        self.dofs = None
        self.displ = None
        self.nodid = None
        self.nodes = None
        self.elems = None
        self.nset = None
        self.nsetkey = None
        self.eset = None
        self.res = None
        self.hdr = None
        self.nodnr = 0
        self.elnr = 0

    def dataSize(self, key, data):
        if key in self.datasize:
            return self.datasize[key]
        else:
            return len(data)

    def Abqver(self, version):
        self.about.update({'abqver': version})

    def Date(self, date, time):
        self.about.update({'abqdate': date, 'abqtime': time})

    def Size(self, nelems, nnodes, length):
        self.nelems = nelems
        self.nnodes = nnodes
        self.length = length
        self.nodid = -ones((nnodes, ), dtype=int32)
        self.nodes = zeros((nnodes, 3), dtype=float32)
        self.elems = {}
        self.nset = {}
        self.eset = {}

    def Dofs(self, data):
        self.dofs = array(data)
        self.displ = self.dofs[self.dofs[:6] > 0]
        if self.displ.max() > 3:
            self.datasize['U'] = 6

    def Heading(self, head):
        self.about.update({'heading': head})

    def Node(self, nr, coords, normal=None):
        self.nodid[self.nodnr] = nr
        nn = len(coords)
        self.nodes[self.nodnr][:nn] = coords
        self.nodnr += 1

    def Element(self, nr, typ, conn):
        if typ not in self.elems:
            self.elems[typ] = []
        self.elems[typ].append(conn)

    def Nodeset(self, key, data):
        self.nsetkey = key
        self.nset[key] = asarray(data)

    def NodesetAdd(self, data):
        self.nset[self.nsetkey] = union1d(self.nset[self.nsetkey],
                                          asarray(data))

    def Elemset(self, key, data):
        self.esetkey = key
        self.eset[key] = asarray(data)

    def ElemsetAdd(self, data):
        self.eset[self.esetkey] = union1d(self.eset[self.esetkey],
                                          asarray(data))

    def Finalize(self):
        self.nid = inverseUniqueIndex(self.nodid)
        for k in self.elems.iterkeys():
            v = asarray(self.elems[k])
            self.elems[k] = asarray(self.nid[v])
        self.modeldone = True
        # we use lists, to keep the cases in order
        self.res = OrderedDict()
        self.step = None
        self.inc = None

    def Increment(self, step, inc, **kargs):
        """Add a new step/increment to the database.

        This method can be used to add a new increment to an existing step,
        or to add a new step and set the initial increment, or to just select
        an existing step/inc combination.
        If the step/inc combination is new, a new empty result record is created.
        The result record of the specified step/inc becomes the current result.
        """
        if not self.modeldone:
            self.Finalize()
        if step != self.step:
            if step not in self.res.keys():
                self.res[step] = OrderedDict()
            self.step = step
            self.inc = None
        res = self.res[self.step]
        if inc != self.inc:
            if inc not in res.keys():
                res[inc] = {}
            self.inc = inc
        self.R = self.res[self.step][self.inc]

    def EndIncrement(self):
        if not self.modeldone:
            self.Finalize()
        self.step = self.inc = -1

    def Label(self, tag, value):
        self.labels[tag] = value

    def NodeOutput(self, key, nodid, data):
        if key not in self.R:
            self.R[key] = zeros((self.nnodes, self.dataSize(key, data)),
                                dtype=float32)
        if key == 'U':
            self.R[key][nodid - 1][self.displ - 1] = data
        elif key == 'S':
            n1 = self.hdr['ndi']
            n2 = self.hdr['nshr']
            ind = arange(len(data))
            ind[n1:] += (3 - n1)
            #print(ind)
            self.R[key][nodid - 1][ind] = data
        else:
            self.R[key][nodid - 1][:len(data)] = data

    def ElemHeader(self, **kargs):
        self.hdr = dict(**kargs)

    def ElemOutput(self, key, data):
        if self.hdr['loc'] == 'na':
            self.NodeOutput(key, self.hdr['i'], data)

    def Export(self):
        """Align on the last increment and export results"""
        try:
            self.step = self.res.keys()[-1]
            self.inc = self.res[self.step].keys()[-1]
            self.R = self.res[self.step][self.inc]
        except:
            self.step = None
            self.inc = None
            self.R = None
        export({self.name: self, self._name_: self})
        print("Read %d nodes, %d elements" % (self.nnodes, self.nelems))
        if self.res is None:
            print("No results")
        else:
            print("Steps: %s" % self.res.keys())

    def do_nothing(*arg, **kargs):
        """A do nothing function to stand in for as yet undefined functions."""
        pass

    TotalEnergies = do_nothing
    OutputRequest = do_nothing
    Coordinates = do_nothing
    Displacements = do_nothing
    Unknown = do_nothing

    def setStepInc(self, step, inc=1):
        """Set the database pointer to a given step,inc pair.

        This sets the step and inc attributes to the given values, and puts
        the corresponding results in the R attribute. If the step.inc pair does
        not exist, an empty results dict is set.
        """
        try:
            self.step = step
            self.inc = inc
            self.R = self.res[self.step][self.inc]
        except:
            self.R = {}

    def getSteps(self):
        """Return all the step keys."""
        return self.res.keys()

    def getIncs(self, step):
        """Return all the incs for given step."""
        if step in self.res:
            return self.res[step].keys()

    def nextStep(self):
        """Skips to the start of the next step."""
        if self.step < self.getSteps()[-1]:
            self.setStepInc(self.step + 1)

    def nextInc(self):
        """Skips to the next increment.

        The next increment is either the next increment of the current step,
        or the first increment of the next step.
        """
        if self.inc < self.getIncs(self.step)[-1]:
            self.setStepInc(self.step, self.inc + 1)
        else:
            self.nextStep()

    def prevStep(self):
        """Skips to the start of the previous step."""
        if self.step > 1:
            self.setStepInc(self.step - 1)

    def prevInc(self):
        """Skips to the previous increment.

        The previous increment is either the previous increment of the current
        step, or the last increment of the previous step.
        """
        if self.inc > 1:
            self.setStepInc(self.step, self.inc - 1)
        else:
            if self.step > 1:
                step = self.step - 1
                inc = self.getIncs(step)[-1]
            self.setStepInc(step, inc)

    def getres(self, key, domain='nodes'):
        """Return the results of the current step/inc for given key.

        The key may include a component to return only a single column
        of a multicolumn value.
        """
        components = '012'
        if self.re_Skey.match(key):
            if self.datasize['S'] == 3:
                components = '013'
            else:
                components = '012345'
        elif self.re_Ukey.match(key):
            if self.datasize['U'] == 2:
                components = '01'
            else:
                components = '012'
        comp = components.find(key[-1])
        if comp >= 0:
            key = key[:-1]
        if key in self.R:
            val = self.R[key]
            if comp in range(val.shape[1]):
                return val[:, comp]
            else:
                return val
        else:
            return None

    def printSteps(self):
        """Print the steps/increments/resultcodes for which we have results."""
        if self.res is not None:
            for i, step in self.res.items():
                for j, inc in step.items():
                    for k, v in inc.items():
                        if isinstance(v, ndarray):
                            data = "%s %s" % (v.dtype.kind, str(v.shape))
                        else:
                            data = str(v)
                        print("Step %s, Inc %s, Res %s (%s)" % (i, j, k, data))
コード例 #9
0
ファイル: menu.py プロジェクト: gitGNU/gnu_pyformex
class BaseMenu(object):
    """A general menu class.

    A hierarchical menu that keeps a list of its item names and actions.
    The item names are normalized by removing all '&' characters and
    converting the result to lower case.
    It thus becomes easy to search for an existing item in a menu.

    This class is not intended for direct use, but through subclasses.
    Subclasses should implement at least the following methods:

    - addSeparator()
    - insertSeperator(before)
    - addAction(text,action)
    - insertAction(before,text,action)
    - addMenu(text,menu)
    - insertMenu(before,text,menu)

    QtGui.Menu and QtGui.MenuBar provide these methods.
    """
    def __init__(self, title='AMenu', parent=None, before=None, items=None):
        """Create a menu."""
        self._title = title
        pf.debug("Creating menu %s" % title, pf.DEBUG.MENU)
        self.parent = parent
        self.separators = OrderedDict()
        self._actions_ = []
        self._submenus_ = []
        if items:
            self.insertItems(items)
        if parent and isinstance(parent, BaseMenu):
            before = parent.action(before)
            parent.insert_menu(self, before)

    def actionList(self):
        """Return a list with the current actions."""
        return [utils.strNorm(str(a.text())) for a in self.actions()]

    def actionsLike(self, clas):
        """Return a list with the current actions of given class."""
        return [a for a in self.actions() if isinstance(a, clas)]

    def subMenus(self):
        """Return a list with the submenus"""
        return self.actionsLike(BaseMenu)

    def index(self, text):
        """Return the index of the specified item in the actionlist.

        If the requested item is not in the actionlist, -1 is returned.
        """
        try:
            return self.actionList().index(utils.strNorm(text))
        except ValueError:
            return -1

    def action(self, text):
        """Return the action with specified text.

        First, a normal action is tried. If none is found,
        a separator is tried.

        See also :meth:`item`.
        """
        if text is None:
            return None
        if text in self.actions():
            return text
        i = self.index(text)
        if i >= 0:
            return self.actions()[i]
        else:
            return self.separators.get(utils.strNorm(text), None)

    def __getitem__(self, text):
        """Return the item with specified text.

        For a normal action or a separator, an action is returned.
        For a menu action, a menu is returned.
        """
        i = self.index(text)
        if i >= 0:
            a = self.actions()[i]
            m = a.menu()
            if m:
                return m
            else:
                return a
        else:
            return self.separators.get(utils.strNorm(text), None)

    # Alias retained for compatibility
    item = __getitem__

    def nextitem(self, text):
        """Returns the name of the next item.

        This can be used to replace the current item with another menu.
        If the item is the last, None is returned.
        """
        itemlist = self.actionList()
        i = itemlist.index(utils.strNorm(text))
        if i >= 0 and i < len(itemlist) - 1:
            return itemlist[i + 1]
        else:
            return None

    def removeItem(self, item):
        """Remove an item from this menu."""
        action = self.action(item)
        if action:
            self.removeAction(action)
            if isinstance(action, QtGui.QMenu):
                action.close()
                del action

    # The need for the following functions demonstrates how much more
    # powerful a dynamically typed language as Python is as compared to
    # the C++ language used by Qt
    def insert_sep(self, before=None):
        """Create and insert a separator"""
        if before:
            return self.insertSeparator(before)
        else:
            return self.addSeparator()

    def insert_menu(self, menu, before=None):
        """Insert an existing menu."""
        self._submenus_.append(menu)
        if before:
            return self.insertMenu(before, menu)
        else:
            return self.addMenu(menu)

    def insert_action(self, action, before=None):
        """Insert an action."""
        if before:
            return self.insertAction(before, action)
        else:
            return self.addAction(action)

    def create_insert_action(self, name, val, before=None):
        """Create and insert an action."""
        if before:
            raise RuntimeError("THIS CAN NOT WORK")
            return self.insertAction(before, name, val)
        else:
            return self.addAction(name, val)

    def insertItems(self, items, before=None, debug=False):
        """Insert a list of items in the menu.

        Parameters:

        - `items`: a list of menuitem tuples. Each item is a tuple of two
          or three elements: (text, action, options):

          - `text`: the text that will be displayed in the menu item.
            It is stored in a normalized way: all lower case and with
            '&' removed.

          - `action`: can be any of the following:

            - a Python function or instance method : it will be called when the
              item is selected,
            - a string with the name of a function/method,
            - a list of Menu Items: a popup Menu will be created that will
              appear when the item is selected,
            - an existing Menu,
            - None : this will create a separator item with no action.

          - `options`: optional dictionary with following honoured fields:

            - `icon`: the name of an icon to be displayed with the item text.
              This name should be that of one of the icons in the pyFormex
              configured icon dirs.
            - `shortcut`: is an optional key combination to select the item.
            - `tooltip`: a text that is displayed as popup help.

        - `before`: if specified, should be the text *or* the action of one
          of the items in the Menu (not the items list!): the new list of
          items will be inserted before the specified item.
        """
        if debug:
            print("Inserting %s items in menu %s" % (len(items), self.title()))
        before = self.action(before)
        for item in items:
            txt, val = item[:2]
            if debug:
                print("INSERTING %s: %s" % (txt, val))
            if len(item) > 2:
                options = item[2]
            else:
                options = {}
            if val is None:
                a = self.insert_sep(before)
                self.separators[txt] = a
            elif isinstance(val, list):
                a = Menu(txt, parent=self, before=before)
                a.insertItems(val)
            elif isinstance(val, BaseMenu):
                #print("INSERTING MENU %s"%txt)
                self.insert_menu(val, before=before)
            else:
                if isinstance(val, str):
                    val = eval(val)
                if 'data' in options:
                    # DActions should be saved to keep them alive !!!
                    if debug:
                        print("INSERTING DAction %s" % txt)
                    a = DAction(txt, data=options['data'])
                    a.signal.connect(val)
                    self.insert_action(a, before)
                    # We need to store the DActions, or else they are
                    # destroyed. QActions are stroed by Qt
                    self._actions_.append(a)
                else:
                    if debug:
                        print("INSERTING QAction %s" % txt)
                    if before is not None:
                        raise RuntimeError(
                            "I can not insert a QAction menu item before an existing one."
                        )
                    a = self.create_insert_action(txt, val, before)
                for k, v in options.items():
                    if k == 'icon':
                        a.setIcon(QtGui.QIcon(QtGui.QPixmap(
                            utils.findIcon(v))))
                    elif k == 'shortcut':
                        a.setShortcut(v)
                    elif k == 'tooltip':
                        a.setToolTip(v)
                    elif k == 'checkable':
                        a.setCheckable(v)
                    elif k == 'checked':
                        a.setCheckable(True)
                        a.setChecked(v)
                    elif k == 'disabled':
                        a.setDisabled(True)

    def print_report(self, recursive=False):
        print("=========== MENU: %s =============" % self.title())
        print("ALL ACTIONS: %s" % self.actionList())
        print("ITEMS: %s" % [self.item(a) for a in self.actionList()])
        print("SUBMENUS: %s" % [a.title() for a in self._submenus_])
        print("SUBMENUS: %s" % [str(a.title()) for a in self.subMenus()])
        if recursive:
            for a in self._submenus_:
                if isinstance(a, BaseMenu):
                    a.print_report()
コード例 #10
0
ファイル: colors.py プロジェクト: gitGNU/gnu_pyformex
def setPalette(colors):
    global palette
    palette = OrderedDict([ (k, GLcolor(k)) for k in colors ])
コード例 #11
0
ファイル: colors.py プロジェクト: gitGNU/gnu_pyformex
blue        = (0.0, 0.0, 1.0)
cyan        = (0.0, 1.0, 1.0)
magenta     = (1.0, 0.0, 1.0)
yellow      = (1.0, 1.0, 0.0)
white       = (1.0, 1.0, 1.0)
darkred     = (0.5, 0.0, 0.0)
darkgreen   = (0.0, 0.5, 0.0)
darkblue    = (0.0, 0.0, 0.5)
darkcyan    = (0.0, 0.5, 0.5)
darkmagenta = (0.5, 0.0, 0.5)
darkyellow  = (0.5, 0.5, 0.0)

pyformex_pink = (1.0, 0.2, 0.4)

lightlightgrey = grey(0.9)
lightgrey = grey(0.8)
mediumgrey = grey(0.6)
darkgrey = grey(0.4)


def setPalette(colors):
    global palette
    palette = OrderedDict([ (k, GLcolor(k)) for k in colors ])


# Set default palette
# !! THIS IS CURRENTLY NOT USED YET
palette = OrderedDict([ (k, globals()[k]) for k in ['darkgrey', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'white', 'black', 'darkred', 'darkgreen', 'darkblue', 'darkcyan', 'darkmagenta', 'darkyellow', 'lightgrey'] ])

# End
コード例 #12
0
 def add_field(self, field):
     """_Low level function to add a Field"""
     if not hasattr(self, '_fields'):
         self._fields = OrderedDict()
     self._fields[field.fldname] = field
コード例 #13
0
ファイル: geomfile.py プロジェクト: gitGNU/gnu_pyformex
    def read(self,count=-1,warn_version=True):
        """Read objects from a pyFormex Geometry File.

        This function reads objects from a Geometry File until the file
        ends, or until `count` objects have been read.
        The File should have been opened for reading.

        A count may be specified to limit the number of objects read.

        Returns a dict with the objects read. The keys of the dict are the
        object names found in the file. If the file does not contain
        object names, they will be autogenerated from the file name.

        Note that PGF files of version 1.0 are no longer supported.
        The use of formats 1.1 to 1.5 is deprecated, and users are
        urged to upgrade these files to a newer format. Support for
        these formats may be removed in future.
        """
        if self.writing:
            print("File is opened for writing, not reading.")
            return {}

        self.results = OrderedDict()
        self.geometry = None # used to make sure fields follow geom block

        if Version(self.version) < Version('1.6'):
            if warn_version:
                pf.warning("This is an old PGF format (%s). We recommend you to convert it to a newer format. The geometry import menu contains an item to upgrade a PGF file to the latest format (%s)." % (self.version,GeometryFile._version_))
            return self.readLegacy(count)


        while True:
            s = self.fil.readline()

            if len(s) == 0:   # end of file
                break

            if s.startswith('#'):

                # Remove the leading '#' and space
                s = s[1:].strip()

                if s.startswith('objtype'):
                    if count > 0 and len(self.results) >= count:
                        break
                    self.readGeometry(**self.decode(s))

                elif s.startswith('field'):
                    self.readField(**self.decode(s))

                elif s.startswith('attrib'):
                    self.readAttrib(**self.decode(s))

                elif s.startswith('pyFormex Geometry File'):
                    # we have a new header line
                    self.readHeader(s)

            # Unrecognized lines are silently ignored, whether starting
            # with a '#' or not.
            # We recommend to start all comments lines with a '#' though.

        self.file.close()

        return self.results
コード例 #14
0
ファイル: Sweep.py プロジェクト: gitGNU/gnu_pyformex
from pyformex import simple
import re

linewidth(2)
clear()

rfuncs = [
    'linear (Archimedes)',
    'quadratic',
    'exponential (equi-angular)',
    'constant',
    #    'custom',
]

# Define a dictionary of planar cross sections
cross_sections = OrderedDict()
# select the planar patterns from the simple module
for cs in simple.Pattern:
    if re.search('[a-zA-Z]', simple.Pattern[cs][2:]) is None:
        cross_sections[cs] = simple.Pattern[cs]
# add some more patterns
cross_sections.update({
    'channel': 'l:1223',
    'H-beam': 'l:11/322/311',
    'sigma': 'l:16253',
    'Z-beam': 'l:353',
    'octagon': 'l:15263748',
    'swastika': 'l:12+23+34+41',
    'solid_square': '4:0123',
    'solid_triangle': '3:012',
    'swastika3': '3:012023034041',
コード例 #15
0
    ShadesOfGrey,
    RunningInCircles,
    HowManyColors,
    AlignedLines,
    ParallelLinesOverWheel,
    MotionInducedBlindness,
    ## FlickerInducedBlindness,
    SineWave,
    CirclesAndLines,
    Crater,
    Cussion,
    CrazyCircles,
]

headers = [getattr(f, '__doc__').split('\n')[0] for f in illusions]
method = OrderedDict(zip(headers, illusions))

# Dialog Actions


def close():
    """Close the dialog"""
    global dialog, explanation
    if dialog:
        pf.PF[gdname] = dialog.results
        dialog.close()
        dialog = None
    if explanation:
        explanation.close()
        explanation = None
    # Release script lock
コード例 #16
0
limas = OrderedDict([
    ('Dragon Curve', ["F", {
        "F": "F+G",
        "G": "F-G"
    }, 10, turtlecmds()]),
    ('Koch Line', ["F", {
        "F": "F*F//F*F"
    }, 6, turtlecmds()]),
    ('rule2', ["F+F+F+F", {
        "F": "FF+FF--FF+F"
    }, 4, turtlecmds()]),
    ('rule3', ["F+F+F+F", {
        "F": "FF+F+F-F+FF"
    }, 4, turtlecmds()]),
    ('Koch Snowflake', ["F//F//F", {
        "F": "F*F//F*F"
    }, 5, turtlecmds()]),
    ('rule4', ["F+F+F+F", {
        "F": "FF+F++F+F"
    }, 4, turtlecmds()]),
    ('rule5', ["F+F+F+F", {
        "F": "FF+F+F+F+F+F-F"
    }, 4, turtlecmds()]),
    ('Hilbert Curve',
     ["X", {
         "X": "-YF+XFX+FY-",
         "Y": "+XF-YFY-FX+"
     }, 5, turtlecmds()]),
    ('Greek Cross Curve',
     ["F+XF+F+XF", {
         "X": "XF-F+F-XF+F+XF-F+F-X"
     }, 4, turtlecmds()]),
    ('Peano Curve', [
        "X", {
            "X": "XFYFX+F+YFXFY-F-XFYFX",
            "Y": "YFXFY-F-XFYFX+F+YFXFY"
        }, 4,
        turtlecmds()
    ]),
    ('Gosper Curve', [
        "XF", {
            "X": "X*YF**YF/FX//FXFX/YF*",
            "Y": "/FX*YFYF**YF*FX//FX/Y"
        }, 4,
        turtlecmds()
    ]),
    ('Sierpinski Triangle',
     ["F**F**F", {
         "F": "F*J++F**F",
         "J": "JJ"
     }, 6, turtlecmds()]),
    ('Sierpinski Triangle1',
     ["F", {
         "F": "*G/F/G*",
         "G": "/F*G*F/"
     }, 8, turtlecmds()]),
    ('Sierpinski Carpet',
     ["F+F+F+F", {
         "F": "JF+F+F+F+JF+F+F+F+J",
         "J": "JJJ"
     }, 3,
      turtlecmds()]),
    ('Gosper Island', [
        "F*F*F*F*F*F", {
            "F": "+F/F*F-"
        }, 5,
        turtlecmds({
            '+': 'ro(20);',
            '-': 'ro(-20);'
        })
    ]),
    ('Gosper Island Tiling', [
        "F*F*F*F*F*F/F/F/F/F/F*F*F*F*F*F", {
            "F": "+F/F*F-"
        }, 4,
        turtlecmds({
            '+': 'ro(20);',
            '-': 'ro(-20);'
        })
    ]),
    ('Plant0', [
        "+F", {
            "F": "F[*F]F[/F]F"
        }, 5,
        turtlecmds({
            '*': 'ro(25);',
            '/': 'ro(-25);'
        })
    ]),
    ('Plant1', [
        "+Y", {
            "Y": "YFX[*Y][/Y]",
            "X": "[/F][*F]FX"
        }, 7,
        turtlecmds({
            '*': 'ro(25);',
            '/': 'ro(-25);'
        })
    ]),
    ('Breezy Bush', [
        "+F", {
            "F": "FF[//F*F*F][*F/F/F]"
        }, 4,
        turtlecmds({
            '*': 'ro(22.55);',
            '/': 'ro(-22.5);'
        })
    ]),
    ('Islands and Lakes', [
        "F-F-F-F", {
            "F": "F-J+FF-F-FF-FJ-FF+J-FF+F+FF+FJ+FFF",
            "J": "JJJJJJ"
        }, 2,
        turtlecmds()
    ]),
    ('Hexagones', [
        "F*F*F*F*F*F", {
            "F": "[//J*G*F*G]J",
            "G": "[//K*G*F*G]J"
        }, 5,
        turtlecmds()
    ]),
    ('Lace', ["F+F", {
        "F": "F*FF**F**FF*F"
    }, 4, turtlecmds()]),
    ('rule19', [
        "F++F", {
            "F": "*F//F*"
        }, 10,
        turtlecmds({
            '*': 'ro(30);',
            '/': 'ro(-30);'
        })
    ]),
    ('rule20', [
        "F+F+F+F", {
            "F": "*F//G*",
            "G": "/F**G/"
        }, 8,
        turtlecmds({
            '*': 'ro(30);',
            '/': 'ro(-30);'
        })
    ]),
    ('rule21', [
        "G+G+G+G", {
            "F": "*F//G*",
            "G": "/F**G/"
        }, 8,
        turtlecmds({
            '*': 'ro(30);',
            '/': 'ro(-30);'
        })
    ]),
    ('Grass', [
        "***X", {
            "F": "FF",
            "X": "F*[[X]/X]/F[/FX]*X"
        }, 6,
        turtlecmds({
            '*': 'ro(25);',
            '/': 'ro(-25);'
        })
    ]),
    # (rule22', [ "+F", {"F":"GH", "G":"GG", "H":"G[*F][/F]"}, 12, turtlecmds({'*':'ro(22.5);','/':'ro(-22.5);'}) ]),
    # (rule23', [ "F", {"F":"*F-F*"}, 12, turtlecmds({'*':'ro(45);'}) ]),
    # (rule24', [ "JF", {"F":"*F-FF+F*","J":"/J"}, 8, turtlecmds({'*':'ro(45);','/':'ro(-45);'}) ]),
    # (rule25', [ "F", {"F":"F-F++F-F"}, 4, turtlecmds() ]),
])
コード例 #17
0
ファイル: ColorImage.py プロジェクト: gitGNU/gnu_pyformex
def run():
    global image, scaled_image, viewer
    flat()
    lights(False)
    transparent(False)
    view('front')

    # default image file
    filename = getcfg('datadir') + '/butterfly.png'
    image = None
    scaled_image = None
    w, h = 200, 200

    # image viewer widget
    viewer = ImageView(filename)

    transforms = OrderedDict([
        ('flat', lambda F: F),
        ('cylindrical', lambda F: F.cylindrical(
            [2, 0, 1], [2., 90. / float(nx), 1.]).rollAxes(-1)),
        ('spherical',
         lambda F: F.spherical(scale=[1., 90. / float(nx), 2.]).rollAxes(-1)),
        ('projected_on_cylinder', lambda F: F.projectOnCylinder(2 * R, 1)),
    ])

    res = askItems([
        _I('filename',
           filename,
           text='Image file',
           itemtype='button',
           func=selectImage),
        viewer,  # image previewing widget
        _I('nx', w, text='width'),
        _I('ny', h, text='height'),
        _I('transform', itemtype='vradio', choices=transforms.keys()),
    ])

    if not res:
        return

    globals().update(res)

    if image is None:
        print("Loading image")
        loadImage(filename)

    if image is None:
        return

    # Create the colors
    sz = image.size()
    print("Image size is (%s,%s)" % (sz.width(), sz.height()))
    color, colortable = qimage2glcolor(image.scaled(nx, ny))
    print("Converting image to color array")

    # Create a 2D grid of nx*ny elements
    print("Creating grid")
    R = float(nx) / pi
    L = float(ny)
    F = Formex('4:0123').replic2(nx, ny).centered()
    F = F.translate(2, R)

    # Transform grid and draw
    def drawTransform(transform):
        print("Transforming grid")
        trf = transforms[transform]
        G = trf(F)
        clear()
        print("Drawing Colored grid")
        draw(G, color=color, colormap=colortable)
        drawText('Created with pyFormex', (20, 20), size=24)

    drawTransform(transform)
    zoomAll()
コード例 #18
0
            deleteAll()
    return model is None


################# Add properties ######################

# Plane stress element types for Abaqus
abq_eltype = {
    'quad4': 'CPS4',
    'quad8': 'CPS8',
    'quad9': 'CPS9',
}

material = OrderedDict([
    ('name', 'steel'),
    ('young_modulus', 207000),
    ('poisson_ratio', 0.3),
    ('density', 7.85e-9),
])
section = OrderedDict([
    ('name', 'thin steel plate'),
    ('sectiontype', 'solid'),
    ('thickness', 1.0),
    ('material', 'steel'),
])


def setMaterial():
    """Set the material"""
    global section, material
    if not checkModel():
        return