forked from russdill/pybis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpybis.py
2177 lines (1888 loc) · 86.7 KB
/
pybis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# module pybis.py
#
# Copyright (C) 2012 Russ Dill <Russ.Dill@asu.edu>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
import sys
import math
import copy
import re
from string import maketrans
from pyparsing import alphanums, alphas, CaselessKeyword, Dict, Each, Forward, Group, LineStart, LineEnd, Literal, NotAny, oneOf, Optional, ParseException, ParserElement, ParseResults, printables, restOfLine, Token, Suppress, Word
from collections import OrderedDict
from numpy import zeros
__all__ = ["Range", "IBSParser", "PKGParser", "EBDParser", "dump"]
def ParseReal(val):
"""Parse an IBIS formatted number."""
try:
return float(val)
except:
ext = val.lstrip('+-0123456789.eE')
e = 1
if len(ext):
val = val[0:-len(ext)]
e = 'fpnum.kMGT'.find(ext[0])
if e == -1:
e = 5
e = 10**((e - 5) * 3)
# 'e' or 'E' can be a unit
if val[-1] == 'e' or val[-1] == 'E':
val = val[:-1]
return float(val) * e
def in_range(lower, upper):
"""Throw an exception if a number is not in a range."""
def func(n):
if not lower <= n <= upper:
raise Exception("'{}' is not in range '{}'".format(n, (lower, upper)))
return n
return func
positive = in_range(0, float("inf"))
class Real(Token):
"""pyparse a Real."""
def __init__(self, check=lambda f: f):
super(Real, self).__init__()
self.check = check
def parseImpl(self, instring, loc, doActions=True):
tokens = re.split("[^a-zA-Z0-9\.\-\+]+", instring[loc:], 1)
try:
return loc + len(tokens[0]), self.check(ParseReal(tokens[0]))
except:
raise ParseException(tokens[0], loc, "Could not parse float, '{}'".format(tokens[0]))
class Integer(Token):
"""pyparse an Integer."""
def __init__(self, check=lambda f: f):
super(Integer, self).__init__()
self.check = check
def parseImpl(self, instring, loc, doActions=True):
tokens = re.split("[^0-9\-\+]+", instring[loc:], 1)
val = tokens[0]
try:
return loc + len(val), self.check(int(val))
except:
raise ParseException(tokens[0], loc, "Could not parse integer")
class NAReal(Real):
"""pyparse an "optional" number, gives 'None' for 'NA'."""
def parseImpl(self, instring, loc, doActions=True):
if instring[loc:2+loc] == "NA":
return loc + 2, None
return super(NAReal, self).parseImpl(instring, loc, doActions)
class Range(list):
"""A typ, min, max range object.
[0-2] - Return raw values (0 = typ, 1 = min, 2 = max).
(0-2) - Return typ for min or max if they are 'None'.
(0-2, invert=False) - Ensure max > min.
(0-2, invert=True) - Ensure mix > max.
.typ, .min, .max - Easy accessors for (0-2).
.norm - Return version of object where max > min.
.inv - return version of object where min > max.
"""
def __getattr__(self, name):
if name == "typ":
return self[0]
elif name == "min":
return self(1)
elif name == "max":
return self(2)
elif name == "norm":
if self.min > self.max:
return Range([self[0], self[2], self[1]])
else:
return self
elif name == "inv":
if self.min < self.max:
return Range([self[0], self[2], self[1]])
else:
return self
else:
raise AttributeError(name)
def __call__(self, n, invert=None):
if n == 0:
return self[0]
elif n < 3:
if invert is not None and invert == self.min < self.max:
n = 3 - n
return self[n] if self[n] is not None else self[0]
else:
raise Exception
class RealRange(Token):
"""pyparser for a line of 'count' Real tokens.
'check' should raise Exception on invalid value.
"""
def __init__(self, count=3, check=lambda f: f):
self.count = count * 2 - 1
self.check = check
super(RealRange, self).__init__()
def parseImpl(self, instring, loc, doActions=True):
tokens = re.split("([^a-zA-Z0-9\.\-\+]+)", instring[loc:])
ret = Range()
intok = True
for tok in tokens[:self.count]:
if intok:
if len(ret) and tok == "NA":
ret.append(None)
else:
try:
ret.append(self.check(ParseReal(tok)))
except:
raise ParseException(tok, loc, "Count not parse float")
intok = not intok
loc += len(tok)
return loc, [ret]
def RampRange():
"""pyparser for range of IBIS ramp values (See Section 6 - [Ramp])."""
ramp_data = Group(Real(check=positive) + Suppress(Literal("/")) + Real(check=positive))
ret = (ramp_data -
(ramp_data | CaselessKeyword("NA")) -
(ramp_data | CaselessKeyword("NA"))
)
def fin(tokens):
for i, t in enumerate(tokens[1:]):
if t == "NA": tokens[i + 1] = None
return Range(tokens.asList())
ret.setParseAction(fin)
return ret
def oneof(val):
"""pyparser for set of caseless keywords.
All parsed values will be lowercase.
"""
return oneOf(val.lower(), caseless=True)
def orderedDict(tokenlist):
"""pyparse action to create and OrderedDict from a set of tokens."""
ret = OrderedDict()
for i, tok in enumerate(tokenlist):
ret[tok[0]] = tok[1]
return ret
class IBISNode(OrderedDict):
"""IBIS parse results object.
This object typically represents a section with named children.
Because most IBIS keywords are case insensitive and many even don't
distinguish between and '_' and ' ', this class allows loose access to
children. All children are stored by their 'pretty_name', such as
"Number of Sections". When an access is made, it is translated to a
'simple_name' by lower() and translating ' ' and '/' to '_', '+' to 'p',
and '-' to 'n'. The pretty_name is then looked up in an internal dict.
The pretty_name is then used to find the child.
In addition to normal dict() accessors, '__getattribute__' can also be
used. For example, 'obj["Vinl+"] and obj.vinlp both work.
"""
ibis_trans = maketrans('+- /', 'pn__')
def __init__(self, *args, **kwds):
object.__setattr__(self, 'pretty_names', dict())
super(IBISNode, self).__init__(*args, **kwds)
@staticmethod
def simple_name(name):
return name.translate(IBISNode.ibis_trans).lower()
def pretty_name(self, name):
return self.pretty_names[IBISNode.simple_name(name)]
def __getattribute__(self, name):
try:
return OrderedDict.__getattribute__(self, name)
except AttributeError:
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
try:
pretty = self.pretty_name(name)
OrderedDict.__setitem__(self, pretty, value)
except KeyError:
OrderedDict.__setattr__(self, name, value)
def __getitem__(self, name):
return OrderedDict.__getitem__(self, self.pretty_name(name))
def __setitem__(self, name, value):
simple = IBISNode.simple_name(name)
doset = False
if simple not in self.pretty_names:
pretty = name
doset = True
else:
pretty = self.pretty_names[simple]
OrderedDict.__setitem__(self, pretty, value)
if doset:
self.pretty_names[simple] = pretty
def __delitem__(self, name):
simple = IBISNode.simple_name(name)
pretty = self.pretty_names.pop(simple)
OrderedDict.__delitem__(self, pretty)
def __contains__(self, name):
return IBISNode.simple_name(name) in self.pretty_names
class container(object):
def __init__(self):
self.data = None
class Node(container):
"""Intermediate parse results holder."""
def __init__(self):
super(Node, self).__init__()
self.children = IBISNode()
self.parser = None
self.parent = None
self.data = None
def __str__(self):
return str(self.data)
__repr__ = __str__
def add(self, child):
orig = container()
if child.parser.key in self.children:
orig.data = self.children[child.parser.key]
else:
# FIXME: Double assign of initial?
orig.data = copy.deepcopy(child.parser.initvalue)
child.parser.merge(orig, child)
self.children[child.parser.key] = orig.data
def __iadd__(self, child):
self.add(child)
return self
class Parse(object):
"""Base pybis Parse object."""
def __init__(self, key, pyparser=None, default=None, initvalue=None, data_name=None, list_merge=False, asList=False, asDict=False, required=False):
"""key: Name of element.
pyparser: Parser to call with pyparse
default: Default value of object if not found
initvalue: Default value of object on first merge
data_name: Make the data of this node a child with name 'data_name'
list_merge: Merge multiple copies together as list
asList: Interpret pyparse results as a list
asDict: Interpret pyparse results as a dict
required: raise Exception if not found
"""
self.key = key
self.flat_key = key.replace(' ', '_').lower()
self.data_name = data_name
self.default = default
self.initvalue = initvalue
self.pyparser = pyparser
self.list_merge = list_merge
if list_merge and initvalue is None:
self.initvalue = list()
self.asList = asList
self.asDict = asDict
self.children = OrderedDict()
self.parent = None
self.globals = None
self.required = required
def add(self, obj):
obj.parent = self
self.children[obj.key] = obj
def __iadd__(self, obj):
self.add(obj)
return self
def get_globals(self):
"""Get the global parse object, for things that are parseable in all contexts."""
if self.globals is None and self.parent is not None:
self.globals = self.parent.get_globals()
return self.globals
def find_parser(self, text):
"""Find a child parser that can parse 'text'."""
for name, child in self.children.iteritems():
if child.can_parse(text):
return child
if self.get_globals() is not None:
return self.globals.find_parser(text)
return None
def can_parse(self, text):
"""True if we can parse 'text'."""
return False
def initial(self, text, comment):
"""Parse the first line of text and return a Node object."""
node = Node()
node.parser = self
# Fill in defaults
if self.initvalue is not None and self.default is None:
# FIXME: Maybe we can shortcut merge here...
node.data = copy.deepcopy(self.initvalue)
for key, parser in self.children.iteritems():
if parser.default is not None:
node.children[key] = copy.deepcopy(parser.default)
return node
def parse(self, node, text, comment):
"""Parse a subsequent line of text, False means we can't."""
return not text
def pyparse(self, text):
"""Use self.pyparser to parse 'text', returns parse tokens.
Returns 'text' if there is no pyparser object.
"""
if self.pyparser is not None:
try:
return self.pyparser.parseString(text, parseAll=True)
except ParseException as e:
raise Exception("Failed to parse '{}': {}".format(text, e.msg))
else:
return text.strip()
def fin(self, node):
"""Add a node to the parent."""
if node.data is not None:
self.flatten(node)
if self.data_name:
node.children[self.data_name] = node.data
for name, p in self.children.iteritems():
if p.required and not name in node.children:
raise Exception("'{}' is missing required '{}'".format(self.key, name))
if node.children:
node.data = node.children
# Oi, so some vendors think it'd be funny to add sections, such as
# [Series Pin Mapping] without any data
if node.data is not None and node.parent:
node.parent += node
def pop(self, new, name):
"""Remove 'name' from ParseResults 'new'."""
ret = new.data[name]
del new.data[name]
if len(new.data.keys()) == 0:
for i, item in enumerate(new.data.asList()):
if item == ret:
del new.data[i]
break
return ret
def flatten(self, new):
"""Reformat pyparse results as what we'd expect."""
if isinstance(new.data, ParseResults):
if self.asList:
new.data = new.data.asList()
elif self.asDict:
new.data = IBISNode(new.data.asDict())
else:
new.data = new.data[0]
def merge(self, orig, new):
"""Merge two instances of the same parser under one parent."""
if self.list_merge:
# FIXME: Maybe specify this behavior?
if isinstance(new.data, list):
orig.data.extend(new.data)
else:
orig.data.append(new.data)
elif orig.data != self.initvalue and orig.data != self.default:
raise Exception("'{}' already assigned".format(self.key))
else:
orig.data = new.data
class Bracket(Parse):
"""An item that starts with '[<name>] ...'"""
def can_parse(self, text):
# FIXME: can_parse seems like a wasteful linear serach
if text and text[0] == '[':
sectionName, _, sectionText = text[1:].partition(']')
sectionName = sectionName.replace(' ', '_').lower()
if sectionName == self.flat_key:
return True
return False
def initial(self, text, comment):
node = super(Bracket, self).initial(text, comment)
sectionName, _, sectionText = text[1:].partition(']')
node.sectionText = sectionText.lstrip()
return node
class Comment(Bracket):
"""IBIS '[Comment Char]' keyword."""
def __init__(self, comment_holder):
super(Comment, self).__init__("Comment Char")
self.holder = comment_holder
def initial(self, text, comment):
node = super(Comment, self).initial(text, comment)
if len(node.sectionText) == 0:
# sectionText probably got commented out, no comment char change.
pass
elif not node.sectionText[1:].startsWith("_char"):
raise Exception("Invalid format, expected '<char>_char'")
elif not node.sectionText[0] in "!\"#$%&'()*,:;<>?@\\^`{|}~":
raise Exception("Invalid comment char, '{}'".format(node.sectionText[0]))
else:
self.holder[0] = node.sectionText[0]
return node
def fin(self, node):
"""Ignore this node."""
pass
class End(Bracket):
"""IBIS '[End]' keyword."""
def initial(self, text, comment):
"""Return None as node, special meaning to close out parent."""
return None
class Keyword(Bracket):
"""[<keyword>] <data>."""
def initial(self, text, comment):
node = super(Keyword, self).initial(text, comment)
if not node.sectionText:
raise Exception("Expected text after '{}'".format(text))
node.data = self.pyparse(node.sectionText)
return node
class Text(Bracket):
"""IBIS text section, such as '[Copyright]'
Since some IBIS files include important copyright data in comments
below the keyword, we capture all text, including comments.
"""
def __init__(self, key, comments=True, **kwds):
self.comments = comments
super(Text, self).__init__(key, **kwds)
def initial(self, text, comment):
node = super(Text, self).initial(text, comment)
self.parse(node, node.sectionText, comment)
return node
def parse(self, node, text, comment):
if self.comments:
if len(text) and len(comment):
text += ' '
text += comment
if node.data:
if len(node.data) and len(text):
node.data += '\n'
node.data += text
else:
node.data = text
return True
def merge(self, orig, new):
"""Just merge together subsequent entries."""
if orig.data is None:
orig.data = ""
if len(orig.data):
orig.data += '\n'
orig.data += new.data
def flatten(self, node):
node.data = node.data.strip('\n')
class Section(Bracket):
"""Multi-line token, such as '[Model]'"""
def __init__(self, key, pyparser=None, labeled=False, **kwds):
"""If a Section is labeled, the data is an OrderedDict of objects
indexed by sectionText.
"""
self.needs_text = labeled
if labeled:
kwds["initvalue"] = OrderedDict()
self.merge = self.labeled_merge
super(Section, self).__init__(key, pyparser, **kwds)
def initial(self, text, comment):
node = super(Section, self).initial(text, comment)
if self.needs_text and not node.sectionText:
raise Exception("Expected text after '{}'".format(text))
elif not self.needs_text and node.sectionText:
raise Exception("Unexpected text after keyword, '{}'".format(node.sectionText))
node.key = node.sectionText
return node
def labeled_merge(self, orig, new):
if new.key in orig.data:
raise Exception("'{}' already contains '{}'".format(self.key, new.key))
orig.data[new.key] = new.data
class TokenizeSection(Section):
"""Text from entire section is collected and parsed with pyparser."""
def __init__(self, key, pyparser=None, **kwds):
super(TokenizeSection, self).__init__(key, pyparser, **kwds)
def initial(self, text, comment):
node = super(TokenizeSection, self).initial(text, comment)
node.text = ""
return node
def parse(self, node, text, comment):
node.text += text
node.text += '\n'
return True
def fin(self, node):
node.data = self.pyparse(node.text)
super(TokenizeSection, self).fin(node)
class TableSection(Section):
"""[<section name>] <col1 name> <col2 name> <...>
<row name> <col1 data> <col2 data> <...>
"""
def __init__(self, key, pyparser=None, headers=[], optional=[], **kwds):
kwds["initvalue"] = OrderedDict()
super(TableSection, self).__init__(key, pyparser, **kwds)
self.needs_text = True
self.parsers = OrderedDict()
self.headers = [ key.lower() for key in headers ]
self.optional = [ key.lower() for key in optional ]
def initial(self, text, comment):
node = super(TableSection, self).initial(text, comment)
node.keys = node.sectionText.lower().split()
if len(node.keys) != len(set(node.keys)):
raise Exception("'{}' contains duplicates".format(node.sectionText))
for key in self.headers:
if key not in node.keys:
raise Exception("Expected header names to contain '{}'".format(key))
for key in node.keys:
if key not in self.headers and key not in self.optional:
raise Exception("Unexpected header name, '{}'".format(key))
for key in self.optional:
if key not in node.keys:
node.keys.append(key)
return node
def assign_row(self, node, key, row):
"""For Seires_Pin_Mapping to override."""
if key in node.data:
raise Exception("'{}' already contains '{}'".format(self.key, key))
node.data[key] = row
def parse(self, node, text, comment):
if super(TableSection, self).parse(node, text, comment):
return True
tokens = text.split()
if not tokens:
return True
row = IBISNode(zip(node.keys, tokens[1:]))
for name, parser in self.parsers.iteritems():
name = name.lower()
if name in row:
tmp = Node()
try:
tmp.data = parser.parseString(row[name], parseAll=True)
except ParseException as e:
raise Exception("Failed to parse '{}', '{}': {}".format(name, row[name], e.msg))
self.flatten(tmp)
row[name] = tmp.data
for key in self.headers:
if key not in row:
raise Exception("Required column '{}' missing".format(key))
for key in self.optional:
if key not in row:
row[key] = None
self.assign_row(node, tokens[0], row)
return True
def add(self, obj):
if isinstance(obj, ParserElement):
self.parsers[obj.resultsName] = obj
else:
super(Section, self).add(obj)
class ListSection(Section):
"""Each line is an element of a list."""
def __init__(self, key, pyparser=None, **kwds):
kwds["initvalue"] = list()
super(ListSection, self).__init__(key, pyparser, **kwds)
def parse(self, node, text, comment):
if not super(ListSection, self).parse(node, text, comment):
tmp = Node()
tmp.data = self.pyparse(text)
self.flatten(tmp)
node.data.append(tmp.data)
return True
class DictSection(Section):
"""Each line is indexed by the first token."""
def __init__(self, key, pyparser=None, **kwds):
kwds["initvalue"] = OrderedDict()
super(DictSection, self).__init__(key, pyparser, **kwds)
def parse(self, node, text, comment):
if not super(DictSection, self).parse(node, text, comment):
tokens = text.split(None, 1)
tmp = Node()
tmp.data = self.pyparse(tokens[1])
self.flatten(tmp)
if tokens[0] in node.data:
raise Exception("'{}' already contains '{}'".format(self.key, tokens[0]))
node.data[tokens[0]] = tmp.data
return True
class RangeSection(Section):
"""Indexed tabular typ/min/max data, such as '[Pullup]'"""
def __init__(self, key, increasing_idx=False, decreasing_idx=False, **kwds):
self.increasing_idx = increasing_idx
self.decreasing_idx = decreasing_idx
super(RangeSection, self).__init__(key, RealRange(4), **kwds)
def initial(self, text, comment):
node = super(RangeSection, self).initial(text, comment)
node.data = Range([ ( [], [] ), ( [], [] ), ( [], [] ) ])
node.last_idx = None
return node
def parse(self, node, text, comment):
if not super(RangeSection, self).parse(node, text, comment):
tokens = self.pyparse(text)[0]
if not node.last_idx:
pass
elif self.increasing_idx:
if tokens[0] <= node.last_idx:
raise Exception("Index values not monotonic")
elif self.decreasing_idx:
if tokens[0] >= node.last_idx:
raise Exception("Index values not monotonic")
elif tokens[0] > node.last_idx:
self.increasing_idx = True
elif tokens[0] < node.last_idx:
self.decreasing_idx = True
else:
raise Exception("Index values not monotonic")
node.last_idx = tokens[0]
for i in range(3):
if not tokens[i + 1] is None:
node.data[i][0].append(tokens[0])
node.data[i][1].append(tokens[i + 1])
return True
def flatten(self, node):
pass
def fin(self, node):
for i in range(3):
if i > 0 and not len(node.data[i][0]):
node.data[i] = None
elif len(node.data[i][0]) < 2:
raise Exception("Requires at least 2 points")
super(RangeSection, self).fin(node)
# FIXME: Make special object to encapsulate matrix with pin mapping.
class MatrixSection(Section):
"""Such as '[Resistance Matrix]'"""
def __init__(self, key, pyparser=Real(), check=lambda f: f, **kwds):
super(MatrixSection, self).__init__(key, pyparser, **kwds)
self += Keyword("Bandwidth", Integer(check=positive))
self += TokenizeSection("Row", labeled=True, pyparser=Word(printables) * (1,), asList=True)
self.needs_text = True
self.check = check
def fin(self, node):
try:
pn = node.parent.parent.children.pin_numbers.keys()
except:
raise Exception("Could not find associated [Pin Numbers] section")
try:
count = node.parent.parent.children.number_of_pins
except:
raise Exception("Could not find associated [Number Of Pins] section")
if count != len(pn):
assert Exception("[Number Of Pins] does not match length of [Pin Numbers]")
try:
pm = node.parent.parent.children.pin_mapping
except:
# Create a 'Pin Mapping' child that maps pin names to matrix indexes.
pm = dict((pin, i) for i, pin in enumerate(pn))
node.parent.parent.children["Pin Mapping"] = pm
node.data = zeros([len(pm), len(pm)])
node.sectionText = node.sectionText.lower()
for row, data in node.children.row.iteritems():
try:
r = pm[row]
except KeyError:
raise Exception("Unknown pin name '{}' in matrix".format(row))
if node.sectionText == "sparse_matrix":
for col, val in zip(data[::2], data[1::2]):
try:
c = pm[col]
except KeyError:
raise Exception("Unknown pin name '{}' in matrix".format(col))
node.data[r][c] = self.check(ParseReal(val))
elif node.sectionText == "banded_matrix" or node.sectionText == "full_matrix":
c = r
for val in data:
node.data[r][c] = self.check(ParseReal(val))
c = (c + 1) % len(pm)
else:
raise Exception("incomplete/unknown matrix".format(node.sectionText))
node.children = None
super(MatrixSection, self).fin(node)
class Param(Parse):
"""A single line param, such as 'Vinl 5.6', or 'Vinl_dc = 100mV'.
'delim' is required if specified.
"""
def __init__(self, key, pyparser=None, delim=None, **kwds):
super(Param, self).__init__(key, pyparser, **kwds)
self.delim = delim
def can_parse(self, text):
if text and text[0] != '[':
if self.delim != None:
name, d, _ = text.partition(self.delim)
if d and name.strip().lower() == self.flat_key:
return True
else:
tokens = text.split(None, 1)
if tokens[0].lower() == self.flat_key:
return True
return False
def initial(self, text, comment):
node = super(Param, self).initial(text, comment)
if self.delim != None:
_, d, text = text.partition(self.delim)
else:
tokens = text.split(None, 1)
text = tokens[1]
node.data = self.pyparse(text)
return node
class DictParam(Param):
"""Label indexing object as _key, such as 'Port_map'."""
def __init__(self, key, pyparser, **kwds):
kwds["initvalue"] = OrderedDict()
super(DictParam, self).__init__(key, pyparser, **kwds)
def flatten(self, new):
new.key = self.pop(new, "_key")
super(DictParam, self).flatten(new)
def merge(self, orig, new):
if new.key in orig.data:
raise Exception("'{}' already contains '{}'".format(self.key, new.key))
orig.data[new.key] = new.data
class RangeParam(Param):
"""Results are tagged with a _range, output is a typ, min, max,
such as 'Corner'
"""
def __init__(self, key, pyparser, **kwds):
kwds["initvalue"] = Range([None, None, None])
super(RangeParam, self).__init__(key, pyparser, **kwds)
def flatten(self, new):
if "_range" in new.data:
new.range = self.pop(new, "_range").lower()
else:
new.range = "typ"
super(RangeParam, self).flatten(new)
def merge(self, orig, new):
if new.range == "typ":
r = 0
elif new.range == "min":
r = 1
elif new.range == "max":
r = 2
else:
raise Exception("Unknown range key, '{}'".format(new.range))
if orig.data[r] is None:
orig.data[r] = new.data
else:
raise Exception("{} value for '{}' already specified".format(new.range, self.key))
class RangeDictParam(Param):
"""Oi...we need a combination of the above two, as in 'D_to_A'."""
def __init__(self, key, pyparser, **kwds):
kwds["initvalue"] = OrderedDict()
super(RangeDictParam, self).__init__(key, pyparser, **kwds)
def flatten(self, new):
new.key = self.pop(new, "_key")
if "_range" in new.data:
new.range = self.pop(new, "_range").lower()
else:
new.range = "typ"
super(RangeDictParam, self).flatten(new)
def merge(self, orig, new):
if new.key not in orig.data:
orig.data[new.key] = Range([None, None, None])
if new.range == "typ":
r = 0
elif new.range == "min":
r = 1
elif new.range == "max":
r = 2
else:
raise Exception("Unknown range key, '{}'".format(new.range))
if orig.data[new.key][r] is None:
orig.data[new.key][r] = new.data
else:
raise Exception("{} value for '{}' already specified".format(new.range, new.key))
class Header(Parse):
"""Section 4."""
def __init__(self, **kwds):
kwds["required"] = True
super(Header, self).__init__("header", **kwds)
self += Keyword("IBIS Ver", required=True)
self += Keyword("File Name", required=True)
self += Keyword("File Rev", required=True)
self += Keyword("Date")
self += Text("Source")
self += Text("Notes")
self += Text("Disclaimer")
self += Text("Copyright")
class Series_Pin_Mapping(TableSection):
def __init__(self):
super(Series_Pin_Mapping, self).__init__("Series Pin Mapping",
headers=["pin_2", "model_name"], optional=["function_table_group"])
def assign_row(self, node, key, row):
key = (key, row["pin_2"] )
del row["pin_2"]
if key[0] == key[1]:
raise Exception("series pin '{}' maps to itself".format(key[0]))
super(Series_Pin_Mapping, self).assign_row(node, key, row)
class Component(Section):
"""Section 5."""
def __init__(self, **kwds):
kwds["required"] = True
kwds["labeled"] = True
super(Component, self).__init__("Component", **kwds)
package = Section("Package", required=True)
package += Param("R_pkg", RealRange(), required=True)
package += Param("L_pkg", RealRange(), required=True)
package += Param("C_pkg", RealRange(), required=True)
pin = TableSection("Pin", required=True,
headers=["signal_name", "model_name"],
optional=["R_pin", "L_pin", "C_pin"])
pin += NAReal(check=positive)("R_pin")
pin += NAReal(check=positive)("L_pin")
pin += NAReal(check=positive)("C_pin")
alternate_package_models = ListSection("Alternate Package Models")
alternate_package_models += End("End Alternate Package Models")
diff_pin = TableSection("Diff Pin",
headers=["inv_pin", "vdiff", "tdelay_typ"],
optional=["tdelay_min", "tdelay_max"])
diff_pin += NAReal(check=positive)("vdiff")
diff_pin += NAReal()("tdelay_typ")
diff_pin += NAReal()("tdelay_min")
diff_pin += NAReal()("tdelay_max")
switch_group = oneof("On Off") + Word(alphanums) * (0,) + Literal("/").suppress()
series_switch_groups = TokenizeSection("Series Switch Groups",
Group(switch_group) * (0,), asList=True)
self += Param("Si_location", oneof("Pin Die"))
self += Param("Timing_location", oneof("Pin Die"))
self += Keyword("Manufacturer", required=True)
self += package
self += pin
self += Keyword("Package Model")
self += alternate_package_models
self += TableSection("Pin Mapping",
headers=["pulldown_ref", "pullup_ref"],
optional=["gnd_clamp_ref", "power_clamp_ref", "ext_ref"])
self += diff_pin
self += Series_Pin_Mapping()
self += series_switch_groups
self += Node_Declarations()
self += Circuit_Call()
self += EMI_Component()
def fin(self, node):
super(Component, self).fin(node)
# NB: Even though 'POWER', 'GND', and 'NC' are 'reserverd words' and
# therefore case sensitive, the golden parser doesn't care.
for name, pin in node.children.pin.iteritems():
if pin.model_name.upper() in [ "POWER", "GND", "NC", "CIRCUITCALL" ]:
pin.model_name = pin.model_name.upper()
if pin.model_name == "NC":
pin.model_name = None
if "Pin Mapping" in node.children:
# Make sure all pins under both pin and Pin Mapping
if len(node.children.pin) != len(node.children.pin_mapping):
raise Exception("Pin mapping table is incomplete")
# Make sure the bus mappings line up properly
available_bus = set()
used_bus = set()
for pin_name, mapping in node.children.pin_mapping.iteritems():
for ref in [ "pullup_ref", "pulldown_ref", "gnd_clamp_ref", "power_clamp_ref", "ext_ref" ]:
if mapping[ref] and mapping[ref].upper() == "NC":
mapping[ref] = None
if pin_name not in node.children.pin:
raise Exception("Invalid pin, '{}', listed in Pin Mapping".format(pin_name))
pin_info = node.children.pin[pin_name]
if pin_info.model_name == "GND":
if mapping.pullup_ref is not None:
raise Exception("Expected 'NC' for pin mapping of '{}'".format(pin_name))
if mapping.pulldown_ref is None:
raise Exception("Unexpected 'NC' for pin mapping of '{}'".format(pin_name))
available_bus.add(mapping.pulldown_ref)
elif pin_info.model_name == "POWER":
if mapping.pulldown_ref is not None:
raise Exception("Expected 'NC' for pin mapping of '{}'".format(pin_name))
if mapping.pullup_ref is None:
raise Exception("Unexpected 'NC' for pin mapping of '{}'".format(pin_name))
available_bus.add(mapping.pullup_ref)
else:
for bus in mapping.values():
if bus is not None:
used_bus.add(bus)
missing = used_bus.difference(available_bus)
if len(missing):
raise Exception("'{}' listed in pin mapping, but not available".format(missing))
if "Diff Pin" in node.children:
for pin_name, mapping in node.children.diff_pin.iteritems():