pyNastran  0.5.0
pyNastran BDF Reader/Writer, OP2 Parser, and GUI
bdf_cardMethods.py
Go to the documentation of this file.
00001 ## GNU Lesser General Public License
00002 ## 
00003 ## Program pyNastran - a python interface to NASTRAN files
00004 ## Copyright (C) 2011-2012  Steven Doyle, Al Danial
00005 ## 
00006 ## Authors and copyright holders of pyNastran
00007 ## Steven Doyle <mesheb82@gmail.com>
00008 ## Al Danial    <al.danial@gmail.com>
00009 ## 
00010 ## This file is part of pyNastran.
00011 ## 
00012 ## pyNastran is free software: you can redistribute it and/or modify
00013 ## it under the terms of the GNU Lesser General Public License as published by
00014 ## the Free Software Foundation, either version 3 of the License, or
00015 ## (at your option) any later version.
00016 ## 
00017 ## pyNastran is distributed in the hope that it will be useful,
00018 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
00019 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00020 ## GNU General Public License for more details.
00021 ## 
00022 ## You should have received a copy of the GNU Lesser General Public License
00023 ## along with pyNastran.  If not, see <http://www.gnu.org/licenses/>.
00024 ## 
00025 # pylint: disable=E1101,C0103,R0902,R0904,R0914
00026 
00027 from __future__ import division, print_function
00028 #import sys
00029 
00030 class CardMethods(object):
00031     def __init__(self, nCardLinesMax=1000):
00032         self.nCardLinesMax = nCardLinesMax
00033 
00034     def _make_lines_pack(self, debug=False):
00035         emptyLines = 0
00036         if not self.linesPack:
00037             return ['']
00038 
00039         while len(self.linesPack[-1]) < self.nCardLinesMax:
00040             line = self.infilesPack[-1].readline()
00041             line = line.split('$')[0].rstrip('\n\r\t ')
00042             if('$' not in line and len(line) > 0):
00043                 if debug:
00044                     print("line = |%r|" %(line))
00045                 self.linesPack[-1].append(line)
00046             else:
00047                 emptyLines += 1
00048             ###
00049             if emptyLines == 500:
00050                 break
00051         return self.linesPack[-1]
00052 
00053     def update_card_lines(self, lines):
00054         """expands a card with tabs in it"""
00055         lines2 = []
00056         for line in lines:
00057             if '\t' in line:
00058                 #raise SyntaxError('lines are ambiguous when there are tabs...'
00059                 #                  'fix them...line=|%r|' %(line))
00060                 if ',' in line:
00061                     #expandTabCommas(line2)
00062                     raise SyntaxError('tabs and commas in the same line are '
00063                                       'not supported...line=|%r|' %(line))
00064                 line = line.expandtabs()
00065             ###
00066             lines2.append(line)
00067         return lines2
00068 
00069     def _get_card(self, debug=False):
00070         """gets a single unparsed card"""
00071         #debug = True
00072         
00073         linesPack = self._make_lines_pack(debug=debug)
00074         #if debug:
00075             #print '-------------------------------------------------'
00076             #print "pack = \n",'\n'.join(linesPack)
00077         
00078         # fix for unhandled card at end of deck
00079         #if linesPack[0][0] in ['+','*',' ']: 
00080             #self.doneReading = True
00081             #return(None, None, None)
00082 
00083         if linesPack == []:
00084             self.close_file()
00085             linesPack = self._make_lines_pack(debug=debug)
00086         
00087         tempcard = [linesPack[0]]
00088         #if 'CQUAD4' in tempcard[0]:
00089         #    debug = True
00090         i = 1
00091         #if emptyLines<50:
00092         try:
00093             (i, tempcard) = self._get_multi_line_card(i, tempcard, debug=debug)
00094         except IndexError:
00095             #try:
00096             #    tempcard = self._get_multi_line_card(i, tempcard, debug=True)
00097             #except IndexError:
00098             #    print("workscard = %s" %(tempcard))
00099             #    print("")
00100             #    #raise
00101             #    pass
00102             #raise
00103             #print "error..."
00104             #print "line = ",self.lines[i]
00105             self.doneReading = True
00106             #raise
00107         ###
00108         #print "i = ",i
00109         
00110         #try:
00111         linesPack[:] = linesPack[i:]
00112         #except IndexError:
00113         #    self.lines = []
00114         
00115         #print "tempcard = ",''.join(tempcard)
00116         
00117         tempcard = self.update_card_lines(tempcard)
00118         upperCard = [line.upper() for line in tempcard]
00119         cardName = self._get_card_name(upperCard)
00120         #print "|%s|" %(cardName)
00121         #if cardName=='CTRIA3':
00122         if debug:
00123         #if 1:
00124             self.log.debug("cardName  = |%s|" %(cardName))
00125             self.log.debug("upperCard = |%s|" %(upperCard))
00126             self.log.debug("tempcard  = |%s|" %(tempcard))
00127             self.log.debug("-------\n")
00128         self._increaseCardCount(cardName)
00129         return (tempcard, upperCard, cardName)
00130 
00131     def _increaseCardCount(self, cardName):
00132         """
00133         Used for testing to check that the number of cards going in is the
00134         same as each time the model is read verifies proper writing of cards
00135         @warning
00136             this wont guarantee proper reading of cards, but will help
00137         """
00138         if cardName == '': # stupid null case
00139             return
00140 
00141         if cardName in self.cardCount:
00142             self.cardCount[cardName] += 1
00143         else:
00144             self.cardCount[cardName]  = 1
00145 
00146     def _get_multi_line_card(self, i, tempcard, isCSV=False, debug=False):
00147         iline = self.linesPack[-1][i].rstrip()
00148         #while iline=='':
00149         #    i+=1
00150         #    iline = self.lines[i].rstrip()
00151         
00152         sCardName = iline[0:8].strip()  # trying to find if it's blank...
00153         isNotDone = len(iline) > 0 and (iline.strip()[0] in ['*', '+', ','] or sCardName == '')
00154         #debug = True
00155         if debug:
00156             print("_get_multi_line_card...i=%s" %(i))
00157             print("tempcard1 = %s" %(tempcard))
00158 
00159             self.log.debug("CRITERIA A")
00160             self.log.debug("  iline      = |%r|" %(iline))
00161             self.log.debug("  len(iline) = %-10s -> len(iline)>0         = %s" %('|'+str(len(iline))+'|', str(len(iline) > 0)))
00162             self.log.debug("  iline[0]   = %-10s -> line[0] in [*,+,','] = %s" %('|'+iline[0]+'|', iline.strip()[0] in ['*', '+', ',']  ))
00163             self.log.debug("  sCardName  = %-10s -> name=''              = %s" %('|'+sCardName+'|', sCardName == '' ))
00164             self.log.debug("  iline = |%s|" %(iline))
00165             self.log.debug("isNotDone A = %s" %(isNotDone))
00166         
00167         while(isNotDone):
00168             if debug:
00169                 print("not done...i=%s" %(i))
00170             tempcard.append(iline)
00171             i += 1
00172             #if debug:
00173             #    print(card)
00174             if 'ENDDATA' in iline:
00175                 #print "********"
00176                 self.log.debug('found ENDDATA')
00177                 self.doneReading = True
00178                 break
00179             if i+1 == len(self.linesPack[-1]):
00180                 if debug:
00181                     self.log.debug("breaking b/c empty pack???")
00182                 break
00183             if i == len(self.linesPack[-1]): # pre-catching the raise...
00184                 self.doneReading = True
00185                 break
00186             #ilineA = self.linesPack[-1]
00187             #print "iLineA = |%r|" %(ilineA)
00188             iline = self.linesPack[-1][i]
00189             #try:
00190             #    iline = self.linesPack[-1][i]
00191             #except IndexError:
00192             #    iline = ''
00193 
00194             sCardName = iline[0:8].strip()  # trying to find if it's blank...
00195             #slot0 = iline[0:8]
00196             #if '\t' in slot0:
00197             #    slot0 = slot0.expandtabs()
00198             #sCardName = slot0.strip()  # trying to find if it's blank...
00199             isNotDone = len(iline) > 0 and (iline.strip()[0] in ['*', '+', ','] or sCardName == '')
00200             if debug:
00201                 print(tempcard)
00202                 self.log.debug("CRITERIA B")
00203                 self.log.debug("  iline       = |%r|" %(iline))
00204                 self.log.debug("  len(iline) = %-10s -> len(iline)>0         = %s" % ('|'+str(len(iline))+'|', str(len(iline) > 0)))
00205                 self.log.debug("  iline[0]   = %-10s -> line[0] in [*,+,','] = %s" % ('|'+iline[0]+'|', iline.strip()[0] in ['*', '+', ',']  ))
00206                 self.log.debug("  sCardName  = %-10s -> name=''              = %s" % ('|'+sCardName+'|', sCardName == ''))
00207                 self.log.debug("  isNotDone B = %s" %isNotDone)
00208         ###
00209         #if debug:
00210         #self.log.debug("tempcard2 = |%s|" %(tempcard))
00211             #print ""
00212         if debug:
00213             print("done...i=%s" % (i))
00214             print("")
00215         return (i, tempcard)
00216 
00217     def isLargeField(self, card):
00218         """returns True if the card is in 16-character width fields"""
00219         starField = ['*' in field for field in card]
00220         #print "starField = ",starField
00221         
00222         if any(starField):
00223             return True
00224         return False
00225 
00226     def processCard(self, tempcard, debug=False):
00227         """
00228         takes a list of strings and returns a list with the 
00229         proper value in the fields of the list
00230         """
00231         #debug = True
00232         card = []
00233         #isLargeField = self.isLargeField(tempcard)
00234         #print "*** isLargeField = ",isLargeField
00235 
00236         #print "tempcard = ",tempcard
00237         for (i, line) in enumerate(tempcard):
00238             #print "line = ",line
00239             isLargeField = self.isLargeField(line)
00240             #print "i = ",i
00241             if debug:
00242                 self.log.debug("  line  = |%r|" % (line))
00243             sline = line[0:72]
00244             if not(sline):
00245                 break
00246             if debug:
00247                 self.log.debug("  line2 = |%r|" % (sline))
00248 
00249             if ',' in sline:  #CSV - doesnt support large field CSV cards which I'd never used...
00250                 try:
00251                     sline = parse_csv(sline)
00252                 except:
00253                     print("cant parse sline=%s" % (sline))
00254                     raise
00255                 #print "sline  = ",sline
00256                 #self.log.debug("sline = %s" %(sline))
00257             else: # standard
00258                 sline = nastran_split(self.log, sline, isLargeField,
00259                                       debug=debug)
00260             #name = sline[0]
00261             #nFields = len(sline)
00262             #print "sline = ",sline
00263             
00264             for (fieldCounter, valueIn) in enumerate(sline):
00265                 #if fieldCounter==8:
00266                     #print "**type(value) = ",type(value)
00267                     #break
00268                 #if debug:
00269                     #print "type(value) = ",type(value)
00270                     #print ""
00271                 if i > 0 and fieldCounter == 0: # blank leading field
00272                     pass
00273                 else:
00274                     #debug = True
00275                     try:
00276                         value = self.getValue(valueIn, sline, debug=debug)
00277                     except:
00278                         self.log.error("card = |%r|" % (card))
00279                         raise
00280                     card.append(value)
00281                     #print "fieldCounter=%s valueIn=%s value=%s type=%s" %(fieldCounter,valueIn,value,type(value))
00282                 ###
00283             ###
00284             #print "cardEnd temp = ",card
00285         ###
00286         #print "cardOut&& = ",card
00287         #if debug:
00288             #self.log.debug("  sline2 = %s" %(card))
00289             #self.log.debug("  sline2 = %s" %(collapse(card)))
00290         #return make_single_streamed_card(self.log, card)
00291         return card
00292         
00293     def expandTabCommas(self, line):
00294         """
00295         The only valid tab/commas format in nastran is having the 
00296         first field be a tab and the rest of the fields be separated by commas.
00297         @param self the object pointer
00298         @param line a BDF line
00299         """
00300         fields = []
00301         isWord = True
00302         field = ''
00303         i = 0
00304         for (i, letter) in enumerate(line):
00305             if letter not in ['\t', ',', ' ']: # tab or comma
00306                 if isWord:
00307                     field += letter
00308                 else:
00309                     isWord = True
00310                     fields.append(field)
00311                     field = ''
00312                     field += letter
00313                 ###
00314             elif letter == ' ' or letter == ',':
00315                 isWord = False
00316                 break
00317             ###
00318         ###
00319         #fields.append(field)
00320         sline = [field]+line[i:72].split(',')
00321         print("expandTabCommas = |%r|" % (sline))
00322         return fields
00323 
00324     def parseDynamicSyntax(self, key):
00325         """
00326         Applies the dynamic syntax for %varName
00327         @param self the object pointer
00328         @param key the uppercased key
00329         @retval value the dynamic value defined by dictOfVars
00330         @note
00331           %varName is actually %VARNAME b/c of auto-uppercasing the string, 
00332           so the setDynamicSyntax method uppercases the key prior to this step.
00333         @see setDynamicSyntax
00334         """
00335         #print "*** valueRaw.lstrip() = |%r|" %(valueRaw.lstrip())
00336         #key = key.lstrip('%%')
00337         key = key[1:]
00338         self.log.info("dynamic key = |%r|" %(key))
00339         #self.dictOfVars = {'P5':0.5,'ONEK':1000.}
00340         return self.dictOfVars[key]
00341 
00342     def getValue(self, valueRaw, card, debug=False):
00343         """converts a value from nastran format into python format."""
00344         if debug:
00345             print("v1 = |%s|" %(valueRaw))
00346         lvalue = valueRaw.lstrip()
00347         if self.isDynamicSyntax and '%' in lvalue[0:1]:
00348             return self.parseDynamicSyntax(valueRaw)
00349         valueIn = valueRaw.lstrip().rstrip(' *').upper()
00350 
00351         if debug:
00352             pass
00353             #print "v2 = |%s|" %(valueIn)
00354         if len(valueIn) == 0:
00355             if debug:
00356                 print("BLANK!")
00357             return None
00358 
00359         if valueIn[0].isalpha():
00360             if debug:
00361                 print("STRING!")
00362             return valueIn
00363         
00364         #print "valueIn = |%s|" %(valueIn)
00365         if ' ' in valueIn:
00366             msg = ('there are embedded blanks in the field (mixed tabs/commas/spaces).\n'
00367                    'valueRaw=|%s| valueIn=|%s| card=%s' %(valueRaw, valueIn,
00368                                                           card))
00369             raise SyntaxError(msg)
00370 
00371         if '=' in valueIn or '(' in valueIn or '*' in valueRaw:
00372             if debug:
00373                 print("=(! - special formatting")
00374             return valueRaw.strip()
00375         #valueIn = valueIn.upper()
00376         # int, float, string, exponent
00377         valuePositive = valueIn.strip('+-')
00378         if debug:
00379             print("isDigit = %s" %(valuePositive.isdigit()))
00380         if valuePositive.isdigit():
00381             if debug:
00382                 print("INT!")
00383             return int(valueIn)
00384         try:
00385             value = float(valueIn)
00386             if debug:
00387                 print("FLOAT!")
00388             return value
00389         except ValueError:
00390             pass
00391 
00392         #if('=' in valueIn or '(' in valueIn or ')' in valueIn):
00393         #    print("=()!")
00394         #    return valueIn
00395 
00396         # if there are non-floats/scientific notation -> string
00397         noED = list(set(valueIn)-set('ED 1234567890+-'))
00398         word = ''.join(noED)
00399         #print "word=|%s|" %word
00400         if word.isalpha():
00401             if debug:
00402                 print("WORD!")
00403             return valueIn
00404 
00405         v0 = valueIn[0]
00406         if '-' == v0 or '+' == v0:
00407             valueLeft = valueIn[1:] # truncate the sign for now
00408         else:
00409             v0 = '+' # inplied positive value
00410             valueLeft = valueIn
00411 
00412         #print "valueIn = |%s|" %(valueIn)
00413         #print "v0 = |%s|" %v0
00414         if v0 == '-':
00415             vFactor = -1.
00416         elif v0 == '+' or v0.isdigit():
00417             vFactor = 1.
00418         else:
00419             msg = ('the only 2 cases for a float/scientific are +/- for v0...'
00420                    'valueRaw=|%s| v0=|%s| card=%s' % (valueRaw, v0, card))
00421             raise SyntaxError(msg)
00422 
00423         vm = valueIn.find('-', 1) # dont include the 1st character, find the exponent
00424         vp = valueIn.find('+', 1)
00425         if vm > 0:
00426             sline = valueLeft.split('-')
00427             expFactor = -1.
00428         elif vp > 0:
00429             sline = valueLeft.split('+')
00430             expFactor = 1.
00431         else:
00432             msg = ('thought this was in scientific notation, but there is no '
00433                   'exponent sign...valueRaw=|%s| valueLeft=|%s| card=%s\n'
00434                   'You also might have mixed tabs/spaces/commas or embedded '
00435                   'blanks in the field.' % (valueRaw, valueLeft, card))
00436             raise SyntaxError(msg)
00437 
00438         sline0 = sline[0].rstrip('Dd')
00439         sline1 = sline[1]
00440         try:
00441             s0 = vFactor*float(sline0)
00442             s1 = expFactor*int(sline1)
00443         except ValueError:
00444             msg = ("vm=%s vp=%s valueRaw=|%s| sline0=%s sline1=%s\ncard=%s"
00445                 % (vm, vp, valueRaw, sline0, sline1, card))
00446             msg2 = ('cannot parse sline0 into a float and sline1 into an '
00447                     'integer\n%s\nYou might have mixed tabs/spaces/commas!  '
00448                     'Fix it!' % (msg))
00449             raise SyntaxError(msg2)
00450 
00451         value = s0*10**(s1)
00452         #print "valueOut = |%s|" %value
00453 
00454         if debug:
00455             print("SCIENTIFIC!")
00456         return value
00457 
00458 def parse_csv(sline):
00459     slineA = sline.split(',')[:9]
00460     sline2 = [''] * 9
00461     for (i, s) in enumerate(slineA):
00462         #print i,s
00463         sline2[i] = s
00464     #sline = sline2
00465     #print "sline2 = ",sline2
00466     #sline = sline2
00467     #sline = sline.split(',')[0:9]  # doesnt fill all fields on line
00468     return sline2
00469 
00470 def make_single_streamed_card(log, card, debug=False):
00471     """
00472     takes a card that has been split b/c it's a multiline card
00473     and gets rid of the required blanks in it.
00474     """
00475     cardOut = []
00476     n = 0
00477     if debug:
00478         log.debug("card = %s" % (card))
00479     for (i, field) in enumerate(card):
00480         if n-9 == 0:
00481             pass
00482         elif n-10 == 0:
00483             n -= 10
00484         else:
00485             cardOut.append(field)
00486         n+=1
00487     ###
00488     #print "cardOut = ",cardOut
00489     return cardOut
00490     #return collapse(cardOut)
00491 
00492 def nastran_split(log, line, isLargeField, debug=False):
00493     """
00494     Splits a single BDF line into large field or small field format
00495     @param self the object pointer
00496     @param line the BDF line
00497     @param a flag indicating small/large field format (True/False)
00498     @param debug extra developer debug
00499     @retval fields the 9 (small) or 5 (large) fields for the line
00500     @note CSV Format is handled by parse_csv
00501     @note tabs are handled prior to running this
00502     """
00503     if debug:
00504         print("isLargeField = %s" % (isLargeField))
00505     if isLargeField:
00506         fields = [line[0:8], line[8:24], line[24:40], line[40:56], line[56:72]]
00507     else: #small field
00508         fields = [line[0 :8 ], line[8 :16], line[16:24], line[24:32],
00509                   line[32:40], line[40:48], line[48:56], line[56:64],
00510                   line[64:72]]
00511     #if debug:
00512     #    print("  fields = ",collapse(fields))
00513     
00514     fields2 = []
00515     for (i, rawField) in enumerate(fields):
00516         field = rawField.strip()
00517         #if debug:
00518         #if (i==9) and field=='' or field=='*' or field=='+':
00519             #print "skipping * or + or empty field"
00520         #    pass
00521         #else:
00522         if debug:
00523             log.debug("i=%s rawField=|%s| field=|%s|" % (i, rawField, field))
00524         fields2.append(field)
00525     return fields2
00526     
00527 
00528 def interpretValue(valueRaw, card='', debug=False):
00529     """converts a value from nastran format into python format."""
00530     #debug = True
00531     if debug:
00532         print("v1 = |%s|" %(valueRaw))
00533     #lvalue = valueRaw.lstrip()
00534     valueIn = valueRaw.lstrip().rstrip(' *').upper()
00535 
00536     if debug:
00537         pass
00538         #print "v2 = |%s|" %(valueIn)
00539     if len(valueIn) == 0:
00540         if debug:
00541             print("BLANK!")
00542         return None
00543 
00544     if valueIn[0].isalpha():
00545         if debug:
00546             print("STRING!")
00547             print("valueStr = %s" % (valueIn))
00548         return valueIn
00549 
00550     if '=' in valueIn or '(' in valueIn or '*' in valueRaw:
00551         if debug:
00552             print("=(! - special formatting")
00553         return valueRaw.strip()
00554     #valueIn = valueIn.upper()
00555     # int, float, string, exponent
00556     valuePositive = valueIn.strip('+-')
00557     if debug:
00558         print("isDigit = %s" %(valuePositive.isdigit()))
00559     if valuePositive.isdigit():
00560         if debug:
00561             print("INT!")
00562         return int(valueIn)
00563     try:
00564         value = float(valueIn)
00565         if debug:
00566             print("FLOAT!")
00567         return value
00568     except ValueError:
00569         pass
00570 
00571     #if('=' in valueIn or '(' in valueIn or ')' in valueIn):
00572     #    print("=()!")
00573     #    return valueIn
00574 
00575     # if there are non-floats/scientific notation -> string
00576     noED = list(set(valueIn)-set('ED 1234567890+-'))
00577     word = ''.join(noED)
00578     #print "word=|%s|" %word
00579     if word.isalpha():
00580         if debug:
00581             print("WORD!")
00582         return valueIn
00583 
00584     v0 = valueIn[0]
00585     if '-' == v0 or '+' == v0:
00586         valueLeft = valueIn[1:] # truncate the sign for now
00587     else:
00588         v0 = '+' # inplied positive value
00589         valueLeft = valueIn
00590 
00591     #print "valueIn = |%s|" %(valueIn)
00592     #print "v0 = |%s|" %v0
00593     if v0 == '-':
00594         vFactor = -1.
00595     elif v0 == '+' or v0.isdigit():
00596         vFactor = 1.
00597     else:
00598         msg = 'the only 2 cases for a float/scientific are +/- for v0...valueRaw=|%s| v0=|%s| card=%s' % (valueRaw, v0, card)
00599         raise SyntaxError(msg)
00600 
00601     vm = valueIn.find('-', 1) # dont include the 1st character, find the exponent
00602     vp = valueIn.find('+', 1)
00603     if vm > 0:
00604         sline = valueLeft.split('-')
00605         expFactor = -1.
00606     elif vp > 0:
00607         sline = valueLeft.split('+')
00608         expFactor = 1.
00609     else:
00610         msg = 'thought this was in scientific notation, but i cant find the exponent sign...valueRaw=|%s| valueLeft=|%s| card=%s\nYou also might have mixed tabs/spaces/commas.' % (valueRaw, valueLeft, card)
00611         raise SyntaxError(msg)
00612 
00613     try:
00614         s0 = vFactor*float(sline[0])
00615         s1 = expFactor*int(sline[1])
00616     except ValueError:
00617         msg = "vm=%s vp=%s valueRaw=|%s| sline=%s" % (vm, vp, valueRaw, sline)
00618         raise SyntaxError('cannot parse sline[0] into a float and sline[1] into an integer\n%s\nYou HAVE mixed tabs/spaces/commas!  Fix it!' % (msg))
00619 
00620     value = s0*10**(s1)
00621     #print "valueOut = |%s|" %value
00622 
00623     if debug:
00624         print("SCIENTIFIC!")
00625     return value
00626 
00627 def stringParser(stringIn):
00628     """not used"""
00629     typeCheck = ''
00630     n = 0
00631     for (i, s) in enumerate(stringIn):
00632         if s in "+-":
00633             state = '+'
00634         elif s == " ":
00635             state = ' '
00636         elif s == ".":
00637             state = '.'
00638         elif s in "eEdD":
00639             state = 'e'
00640         elif s.isdigit():
00641             state = '1'
00642         elif s.isalpha() or s in "()*/=]['\"":
00643             return 'string' # string character
00644         else:
00645             msg = "s=|%r|" % (s)
00646             raise SyntaxError(msg)
00647         ###
00648         
00649         #print "s=%s stringIn[i-1]=%s" % (state,typeCheck[i-1])
00650         #print "i=%s s=%s typeCheck=%s" % (i,s,typeCheck)
00651         if i == 0:
00652             typeCheck += state
00653             n += 1
00654         elif typeCheck[n-1] != state:
00655             typeCheck += state
00656             n += 1
00657         elif state in 'e .+': # double e, space, dot, plus
00658             return 'string'
00659         ###
00660     ###
00661     if typeCheck == ' ':
00662         return None
00663 
00664     typeCheck = typeCheck.strip()
00665     if typeCheck in ['1', '+1']: # integer
00666         return int(stringIn)
00667 
00668     elif typeCheck in [ '1.',  '1.1',  '.1',  # float
00669                        '+1.', '+1.1', '+.1']:
00670         return float(stringIn)
00671 
00672     elif typeCheck in [ '1.1e1',  '1.1e+1',  '1.e1',  '1.e+1', # python scientific
00673                        '+1.1e1', '+1.1e+1', '+1.e1', '+1.e+1',
00674                          '.1e1',   '.1e+1', '+.1e1', '+.1e+1',]:
00675         return float(stringIn)
00676 
00677     elif typeCheck in ['1+1', '+1+1', '.1+1', '+.1+1']: # nastran scientific
00678         stringReversed = stringIn[::-1]
00679         i = stringReversed.index('+')
00680         lString = list(stringIn)
00681         lString.insert(-i-1, 'e')
00682         #print "lString = ",lString
00683         out = ''.join(lString)
00684         print("out = %s" %(out))
00685         return float(out)
00686     else:
00687         #print "string = ",stringIn
00688         #print "typeCheck = ",typeCheck
00689         #return 'string'
00690         return stringIn
00691     
00692     print("typeCheck = |%s|" % (typeCheck))
00693     raise RuntimeError('error parsing a card...this should never happen...')
00694 
00695 if __name__ == '__main__':
00696     print(stringParser('123'))
00697     print(stringParser('+123'))
00698     print(stringParser('.234'))
00699     print(stringParser('+.234'))
00700     print(stringParser('-.234'))
00701     print(stringParser('1+5'))
00702     print("abc = |%s|" % (stringParser('abc')))
00703     print("eeg = |%s|" % (stringParser('eeg')))
00704     #print("e1 = |%s|" %(stringParser('\T')))
00705     print(stringParser('.e1'))
00706  
 All Classes Namespaces Files Functions Variables