Ejemplo n.º 1
0
def readSelection(select=True,draw=True,multi=True):
    """Read a Formex (or list) from asked file name(s).

    If select is True (default), this becomes the current selection.
    If select and draw are True (default), the selection is drawn.
    """
    types = utils.fileDescription(['pgf','all'])
    fn = askFilename(GD.cfg['workdir'],types,multi=multi)
    if fn:
        if not multi:
            fn = [ fn ]
        chdir(fn[0])
        res = ODict()
        GD.GUI.setBusy()
        for f in fn:
            res.update(readGeomFile(f))
        GD.GUI.setBusy(False)
        export(res)
        if select:
            oknames = [ k for k in res if isinstance(res[k],Formex) ]
            selection.set(oknames)
            GD.message("Set Formex selection to %s" % oknames)
            if draw:
                selection.draw()
    return fn
Ejemplo n.º 2
0
 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 = ODict()
     self.step = None
     self.inc = None
Ejemplo n.º 3
0
 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 = ODict()
     self.step = None
     self.inc = None
Ejemplo n.º 4
0
    def readHeader(self):
        """Read the header of a pyFormex geometry file.

        """
        sep = ' '
        s = self.fil.readline()
        if s.startswith('# Formex'):
            version = '1.1'
        elif s.startswith('# pyFormex Geometry File'):
            pos = s.rfind(')')
            exec(s[pos + 1:].strip())
        else:
            version = None
            raise RuntimeError, "This does not look like a pyFormex geometry file, or it is a very old version."

        self._version_ = version
        self.sep = sep
        self.objname = utils.NameSequence('%s_000' %
                                          utils.projectName(self.fil.name))
        self.results = ODict()
Ejemplo n.º 5
0
    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] = ODict()
            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]
Ejemplo n.º 6
0
    def __init__(self, i, body=False):
        self.data = ODict()

        while True:
            # escape or continue?
            while True:
                nc = i.char()
                if is_whitespace(nc):
                    #print('waspay', nc)
                    continue  # look for non-whitespace
                elif nc == ('}' if not body else '\0'):
                    #print('bai', nc)
                    return
                else:
                    ###print('kay', nc)
                    i.rollback()
                    break
            #print("wat")

            # key
            k = TKey(i).data
            #print(k)
            if k in self.data:
                raise TypeError('{0} already present: keys must be unqiue!')

            # eat the '=' sign
            while True:
                nc = i.char()
                if is_whitespace(nc):
                    continue
                elif nc == KVP_SEPR:
                    break
                else:
                    raise ValueError('expected "=" KVP separator')

            self.data[k] = TValue(i).data
Ejemplo n.º 7
0
    'gts': ('gtsset -h', 'Usage(:) '),
    'imagemagick': ('import -version', 'Version: ImageMagick (\S+)'),
    'postabq': ('pyformex-postabq -V', 'postabq (\S+).*'),
    'python': ('python --version', 'Python (\\S+)'),
    'recordmydesktop': ('recordmydesktop --version', 'recordMyDesktop v(\S+)'),
    'tetgen': ('tetgen -h |fgrep Version', 'Version (\S+)'),
    'units': ('units --version', 'GNU Units version (\S+)'),
    'vmtk': ('vmtk --help', 'Usage: 	vmtk(\S+).*'),
}

# Some regular expressions
digits = re.compile(r'(\d+)')

# versions of detected modules
the_version = ODict({
    'pyformex': pf.__version__,
    'python': sys.version.split()[0],
})
# versions of detected external commands
the_external = ODict({})


def checkVersion(name, version, external=False):
    """Checks a version of a program/module.

    name is either a module or an external program whose availability has
    been registered.
    Default is to treat name as a module. Add external=True for a program.

    Return value is -1, 0 or 1, depending on a version found that is
    <, == or > than the requested values.
    This should normally understand version numbers in the format 2.10.1
Ejemplo n.º 8
0
result_types = ODict([
    ('','None'),
    ('U','[Displacement]'),
    ('U0','X-Displacement'),
    ('U1','Y-Displacement'),
    ('U2','Z-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'),
    ])
Ejemplo n.º 9
0
class FeResult(object):

    data_size = {'U':3,'S':6,'COORD':3}
    re_Skey = re.compile("S[0-5]")

    def __init__(self):
        self.about = {'creator':GD.Version,
                      'created':GD.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 FeResult.data_size.has_key(key):
            return FeResult.data_size[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.data_size['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 not self.elems.has_key(typ):
            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 = connectivity.reverseUniqueIndex(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 = ODict()
        self.step = None
        self.inc = None
 
    def Increment(self,step,inc,**kargs):
        if not self.modeldone:
            self.Finalize()
        if step != self.step:
            if step not in self.res.keys():
                self.res[step] = ODict()
            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 not self.R.has_key(key):
            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({'DB':self})
        GD.message("Read %d nodes, %d elements" % (self.nnodes,self.nelems))
        if self.res is None:
            GD.message("No results")
        else:
            GD.message("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):
        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 self.res.has_key(step):
            return self.res[step].keys()
        

    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.
        """
        #print self.dofs
        if self.re_Skey.match(key) and self.data_size['S']==3:
            components = '013'
        else:
            components = '012345'
        comp = components.find(key[-1])
        if comp >= 0:
            key = key[:-1]
        if self.R.has_key(key):
            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.iteritems():
                for j,inc in step.iteritems():
                    for k,v in inc.iteritems():
                        print "Step %s, Inc %s, Res %s (%s)" % (i,j,k,str(v.shape))
Ejemplo n.º 10
0
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_2d = ODict()
# select the planar patterns from the simple module
for cs in simple.Pattern:
    if re.search('[a-zA-Z]',simple.Pattern[cs]) is None:
        cross_sections_2d[cs] = simple.Pattern[cs]
# add some more patterns
cross_sections_2d.update({
    'swastika':'l:12+23+34+41',
    'channel' : 'l:1223',
    'H-beam' : 'l:11/322/311',
    'sigma' : 'l:16253',
    'octagon':'l:15263748',
    'Z-beam': 'l:353',
    'solid_square': '4:0123',
    'solid_triangle': '3:012',
    'swastika3': '3:012023034041',
Ejemplo n.º 11
0
Archivo: test.py Proyecto: gbromios/gb
 ODict(
     cool_dude="wat",
     steven="collins",
     hello="kitty,\" ?",
     puppies='\\n\\n cute',
     puppies_2="even more PuPpIeS",
     tony_pepperony="522",
     bloopers=
     "5120\nasdsaf\n\tblah blah. there's quoites, so it doesn't care about \"white\" space???",
     query=
     "avg # of number of head kicks per karate tournament (this isn't a comment btw)",
     things=[
         "1", "2", "watlol", "xen_is_best", "no", "kvm", "me", "too",
         "thanks", "whatever", "dude"
     ],
     umm=[
         "ahem", "excuse me", "thank's", "your welcome",
         "beg your pardon"
     ],
     perfect_system=dict(ayy="lmao",
                         can_hold="0",
                         why="????",
                         temperature="100.04",
                         those_one_guys_ya_know=[
                             dict(name="doge",
                                  mean="sometimes",
                                  rules="venice",
                                  tryhard="0"),
                             dict(name="tony",
                                  mean="very",
                                  kicks="frequently",
                                  tryhard="45"),
                             dict(
                                 name="Unicorn Rodeo",
                                 occupation="JAMES C. UNICORN",
                                 tryhard="999",
                                 mean="never",
                             )
                         ])))
Ejemplo n.º 12
0
result_types = ODict([
    ('', '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'),
])
Ejemplo n.º 13
0
from plugins.curve import *
from odict import ODict

"""Curves

Examples showing the use of the 'curve' plugin

level = 'normal'
topics = ['geometry','curves']
techniques = ['spline','solve']
"""


method = ODict([
    ('Natural Spline', NaturalSpline),
    ('Cardinal Spline', CardinalSpline),
    ('Bezier', BezierCurve),
    ('Polyline', PolyLine),
])

method_color = [ 'red','green','blue','cyan' ] 
point_color = [ 'black','white' ] 
        
open_or_closed = { True:'A closed', False:'An open' }

TA = None

def drawCurve(ctype,dset,closed,tension,curl,interpoints,ndiv,extend):
    global TA
    P = dataset[dset]
    text = "%s %s with %s points" % (open_or_closed[closed],ctype.lower(),len(P))
    if TA is not None:
Ejemplo n.º 14
0
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 = ODict([
        ('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 = image2glcolor(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()
Ejemplo n.º 15
0
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 = ODict()
# 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',
Ejemplo n.º 16
0
limas = ODict([
    ('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() ]),
])
Ejemplo n.º 17
0
    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 = ODict()


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
Ejemplo n.º 18
0
    """
    ns = (X.shape[0]-1) / 3
    ip = 3*arange(ns+1)
    P = X[ip]
    ip = 3*arange(ns)
    ic = column_stack([ip+1,ip+2]).ravel()
    C = X[ic].reshape(-1,2,3)
    # always use False
    return BezierSpline(P,control=C,closed=False)
    

method = ODict([
    ('Bezier Spline', BezierSpline),
    ('Quadratic Bezier Spline', QuadBezierSpline),
    ('Cardinal Spline (app)', CardinalSpline),
    ('Cardinal Spline', CardinalSpline2),
    ('Natural Spline', NaturalSpline),
    ('Polyline', PolyLine),
    ('Bezier Curve', BezierCurve),
])

method_color = [ 'red','green','blue','cyan','magenta','yellow','white' ] 
point_color = [ 'black','white' ] 
        
open_or_closed = { True:'A closed', False:'An open' }

TA = None



def drawCurve(ctype,dset,closed,endcond,tension,curl,ndiv,ntot,extend,spread,drawtype,cutWP=False,scale=None,directions=False):
    ShadesOfGrey,
    RunningInCircles,
    HowManyColors,
    AlignedLines,
    ParallelLinesOverWheel,
    MotionInducedBlindness,
    ## FlickerInducedBlindness,
    SineWave,
    CirclesAndLines,
    Crater,
    Cussion,
    CrazyCircles,
    ]

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

data_items = [
    ['Illusion',None,'select',method.keys()],
    ['Explain',False,{'text':'Show explanation'}],
    ]

globals().update([i[:2] for i in data_items])

for i,it in enumerate(data_items):
    data_items[i][1] = globals()[it[0]]

# Actions

def close():
    """Close the dialog"""
Ejemplo n.º 20
0
class FeResult(object):

    _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 = ODict()
        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] = ODict()
            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})
        pf.message("Read %d nodes, %d elements" % (self.nnodes,self.nelems))
        if self.res is None:
            pf.message("No results")
        else:
            pf.message("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.iteritems():
                for j,inc in step.iteritems():
                    for k,v in inc.iteritems():
                        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))
Ejemplo n.º 21
0
class FeResult(object):

    _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 = ODict()
        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] = ODict()
            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})
        pf.message("Read %d nodes, %d elements" % (self.nnodes, self.nelems))
        if self.res is None:
            pf.message("No results")
        else:
            pf.message("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.iteritems():
                for j, inc in step.iteritems():
                    for k, v in inc.iteritems():
                        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))
Ejemplo n.º 22
0
    ('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'),
    ]

res_dict = ODict(res_types)

dia_full = [
    ['feresult','FE Result DB','','info'],
    ['elgroup','Element Group',None,'select',['--ALL--',]],
    ['resindex','Type of result',None,'select',res_dict.values()],
    ['loadcase','Load case',0],
    ['autoscale','Autocalculate deformation scale',True],
    ['dscale','Deformation scale',100.],
    ['showref','Show undeformed configuration',True],
    ['animate','Animate results',False],
    ['shape','Amplitude shape','linear','radio',['linear','sine']],
    ['cycle','Animation cycle','updown','radio',['up','updown','revert']],
    ['count','Number of cycles',5],
    ['nframes','Number of frames',10],
    ['sleeptime','Animation sleeptime',0.1], 
Ejemplo n.º 23
0
################# Add properties ######################

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

def warn():
   warning("You should first merge the parts!")

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


def setMaterial():
    """Set the material"""
    global section,material
    if model is None:
        warn()