markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Since `chart_parse()` returns the completed table, we now need to extract the derivation trees. The Parse MethodFor determining how far we have managed to parse, we simply look for the last index from `chart_parse()` where the `start_symbol` was found. | class EarleyParser(EarleyParser):
def parse_prefix(self, text):
self.table = self.chart_parse(text, self.start_symbol())
for col in reversed(self.table):
states = [
st for st in col.states if st.name == self.start_symbol()
]
if states:
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Here is the `parse_prefix()` in action. | ep = EarleyParser(SAMPLE_GRAMMAR)
cursor, last_states = ep.parse_prefix('adcd')
print(cursor, [str(s) for s in last_states]) | 4 ['<start>:= <A> <B> |(0,4)']
| MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
The following is adapted from the excellent reference on Earley parsing by [Loup Vaillant](http://loup-vaillant.fr/tutorials/earley-parsing/). Our `parse()` method is as follows. It depends on two methods `parse_forest()` and `extract_trees()` that will be defined next. | class EarleyParser(EarleyParser):
def parse(self, text):
cursor, states = self.parse_prefix(text)
start = next((s for s in states if s.finished()), None)
if cursor < len(text) or not start:
raise SyntaxError("at " + repr(text[cursor:]))
forest = self.parse_forest(self.t... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Parsing PathsThe `parse_paths()` method tries to unify the given expression in `named_expr` with the parsed string. For that, it extracts the last symbol in `named_expr` and checks if it is a terminal symbol. If it is, then it checks the chart at `til` to see if the letter corresponding to the position matches the ter... | class EarleyParser(EarleyParser):
def parse_paths(self, named_expr, chart, frm, til):
def paths(state, start, k, e):
if not e:
return [[(state, k)]] if start == frm else []
else:
return [[(state, k)] + r
for r in self.parse_path... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Here is the `parse_paths()` in action | print(SAMPLE_GRAMMAR['<start>'])
ep = EarleyParser(SAMPLE_GRAMMAR)
completed_start = last_states[0]
paths = ep.parse_paths(completed_start.expr, columns, 0, 4)
for path in paths:
print([list(str(s_) for s_ in s) for s in path]) | ['<A><B>']
[['<B>:= <D> |(3,4)', 'n'], ['<A>:= a <B> c |(0,3)', 'n']]
| MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
That is, the parse path for `` given the input `adcd` included recognizing the expression ``. This was recognized by the two states: `` from input(0) to input(2) which further involved recognizing the rule `ac`, and the next state `` from input(3) which involved recognizing the rule ``. Parsing ForestsThe `parse_fores... | class EarleyParser(EarleyParser):
def forest(self, s, kind, chart):
return self.parse_forest(chart, s) if kind == 'n' else (s, [])
def parse_forest(self, chart, state):
pathexprs = self.parse_paths(state.expr, chart, state.s_col.index,
state.e_col.index) if ... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Extracting Trees What we have from `parse_forest()` is a forest of trees. We need to extract a single tree from that forest. That is accomplished as follows. (For now, we return the first available derivation tree. To do that, we need to extract the parse forest from the state corresponding to `start`.) | class EarleyParser(EarleyParser):
def extract_a_tree(self, forest_node):
name, paths = forest_node
if not paths:
return (name, [])
return (name, [self.extract_a_tree(self.forest(*p)) for p in paths[0]])
def extract_trees(self, forest):
yield self.extract_a_tree(fores... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We now verify that our parser can parse a given expression. | A3_GRAMMAR: Grammar = {
"<start>": ["<bexpr>"],
"<bexpr>": [
"<aexpr><gt><aexpr>", "<aexpr><lt><aexpr>", "<aexpr>=<aexpr>",
"<bexpr>=<bexpr>", "<bexpr>&<bexpr>", "<bexpr>|<bexpr>", "(<bexrp>)"
],
"<aexpr>":
["<aexpr>+<aexpr>", "<aexpr>-<aexpr>", "(<aexpr>)", "<integer>"],
"<integ... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We now have a complete parser that can parse almost arbitrary *CFG*. There remains a small corner to fix -- the case of epsilon rules as we will see later. Ambiguous Parsing Ambiguous grammars are grammars that can produce multiple derivation trees for some given string. For example, the `A3_GRAMMAR` can parse `1+2+3`... | import itertools as I
class EarleyParser(EarleyParser):
def extract_trees(self, forest_node):
name, paths = forest_node
if not paths:
yield (name, [])
for path in paths:
ptrees = [self.extract_trees(self.forest(*p)) for p in path]
for p in I.product(*ptre... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
As before, we verify that everything works. | mystring = '1+2'
parser = EarleyParser(A1_GRAMMAR)
for tree in parser.parse(mystring):
assert mystring == tree_to_string(tree)
display_tree(tree) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
One can also use a `GrammarFuzzer` to verify that everything works. | gf = GrammarFuzzer(A1_GRAMMAR)
for i in range(5):
s = gf.fuzz()
print(i, s)
for tree in parser.parse(s):
assert tree_to_string(tree) == s | 0 045+3+2-9+7-7-5-1-449
1 0+9+5-2+1-8+4-3+7+2
2 76413
3 9339
4 62
| MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
The Aycock Epsilon FixWhile parsing, one often requires to know whether a given nonterminal can derive an empty string. For example, in the following grammar A can derive an empty string, while B can't. The nonterminals that can derive an empty string are called _nullable_ nonterminals. For example, in the below gramm... | E_GRAMMAR_1: Grammar = {
'<start>': ['<A>', '<B>'],
'<A>': ['a', ''],
'<B>': ['b']
} | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
One of the problems with the original Earley implementation is that it does not handle rules that can derive empty strings very well. For example, the given grammar should match `a` | EPSILON = ''
E_GRAMMAR: Grammar = {
'<start>': ['<S>'],
'<S>': ['<A><A><A><A>'],
'<A>': ['a', '<E>'],
'<E>': [EPSILON]
}
syntax_diagram(E_GRAMMAR)
mystring = 'a'
parser = EarleyParser(E_GRAMMAR)
with ExpectError():
trees = parser.parse(mystring) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Aycock et al.\cite{Aycock2002} suggests a simple fix. Their idea is to pre-compute the `nullable` set and use it to advance the `nullable` states. However, before we do that, we need to compute the `nullable` set. The `nullable` set consists of all nonterminals that can derive an empty string. Computing the `nullable` ... | def fixpoint(f):
def helper(arg):
while True:
sarg = str(arg)
arg_ = f(arg)
if str(arg_) == sarg:
return arg
arg = arg_
return helper | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Remember `my_sqrt()` from [the first chapter](Intro_Testing.ipynb)? We can define `my_sqrt()` using fixpoint. | def my_sqrt(x):
@fixpoint
def _my_sqrt(approx):
return (approx + x / approx) / 2
return _my_sqrt(1)
my_sqrt(2) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
NullableSimilarly, we can define `nullable` using `fixpoint`. We essentially provide the definition of a single intermediate step. That is, assuming that `nullables` contain the current `nullable` nonterminals, we iterate over the grammar looking for productions which are `nullable` -- that is, productions where the e... | def rules(grammar):
return [(key, choice)
for key, choices in grammar.items()
for choice in choices] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
The `terminals()` method extracts all terminal symbols from a `canonical` grammar representation. | def terminals(grammar):
return set(token
for key, choice in rules(grammar)
for token in choice if token not in grammar)
def nullable_expr(expr, nullables):
return all(token in nullables for token in expr)
def nullable(grammar):
productions = rules(grammar)
@fixpoint
de... | E_GRAMMAR {'', '<A>', '<S>', '<E>', '<start>'}
E_GRAMMAR_1 {'', '<start>', '<A>'}
| MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
So, once we have the `nullable` set, all that we need to do is, after we have called `predict` on a state corresponding to a nonterminal, check if it is `nullable` and if it is, advance and add the state to the current column. | class EarleyParser(EarleyParser):
def __init__(self, grammar, **kwargs):
super().__init__(grammar, **kwargs)
self.epsilon = nullable(self.cgrammar)
def predict(self, col, sym, state):
for alt in self.cgrammar[sym]:
col.add(State(sym, tuple(alt), 0, col))
if sym in se... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
To ensure that our parser does parse all kinds of grammars, let us try two more test cases. | DIRECTLY_SELF_REFERRING: Grammar = {
'<start>': ['<query>'],
'<query>': ['select <expr> from a'],
"<expr>": ["<expr>", "a"],
}
INDIRECTLY_SELF_REFERRING: Grammar = {
'<start>': ['<query>'],
'<query>': ['select <expr> from a'],
"<expr>": ["<aexpr>", "a"],
"<aexpr>": ["<expr>"],
}
mystring = '... | recognized select a from a
Recursion error maximum recursion depth exceeded
recognized select a from a
Recursion error maximum recursion depth exceeded
| MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Why do we get recursion error here? The reason is that, our implementation of `extract_trees()` is eager. That is, it attempts to extract _all_ inner parse trees before it can construct the outer parse tree. When there is a self reference, this results in recursion. Here is a simple extractor that avoids this problem. ... | class SimpleExtractor:
def __init__(self, parser, text):
self.parser = parser
cursor, states = parser.parse_prefix(text)
start = next((s for s in states if s.finished()), None)
if cursor < len(text) or not start:
raise SyntaxError("at " + repr(cursor))
self.my_for... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Using it is as folows: | de = SimpleExtractor(EarleyParser(DIRECTLY_SELF_REFERRING), mystring)
for i in range(5):
tree = de.extract_a_tree()
print(tree_to_string(tree)) | select a from a
select a from a
select a from a
select a from a
select a from a
| MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
On the indirect reference: | ie = SimpleExtractor(EarleyParser(INDIRECTLY_SELF_REFERRING), mystring)
for i in range(5):
tree = ie.extract_a_tree()
print(tree_to_string(tree)) | select a from a
select a from a
select a from a
select a from a
select a from a
| MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Note that the `SimpleExtractor` gives no guarantee of the uniqueness of the returned trees. This can however be fixed by keeping track of the particular nodes that were expanded from `pos_tree` variable, and hence, avoiding exploration of the same paths.For implementing this, we extract the random stream passing into t... | class ChoiceNode:
def __init__(self, parent, total):
self._p, self._chosen = parent, 0
self._total, self.next = total, None
def chosen(self):
assert not self.finished()
return self._chosen
def __str__(self):
return '%d(%s/%s %s)' % (self._i, str(self._chosen),
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Now we come to the enhanced `EnhancedExtractor()`. | class EnhancedExtractor(SimpleExtractor):
def __init__(self, parser, text):
super().__init__(parser, text)
self.choices = ChoiceNode(None, 1) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
First we define `choose_path()` that given an array and a choice node, returns the element in array corresponding to the next choice node if it exists, or produces a new choice nodes, and returns that element. | class EnhancedExtractor(EnhancedExtractor):
def choose_path(self, arr, choices):
arr_len = len(arr)
if choices.next is not None:
if choices.next.finished():
return None, None, None, choices.next
else:
choices.next = ChoiceNode(choices, arr_len)
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We define `extract_a_node()` here. While extracting, we have a choice. Should we allow infinite forests, or should we have a finite number of trees with no direct recursion? A direct recursion is when there exists a parent node with the same nonterminal that parsed the same span. We choose here not to extract such tree... | class EnhancedExtractor(EnhancedExtractor):
def extract_a_node(self, forest_node, seen, choices):
name, paths = forest_node
if not paths:
return (name, []), choices
cur_path, _i, _l, new_choices = self.choose_path(paths, choices)
if cur_path is None:
return N... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
The `extract_a_tree()` is a depth first extractor of a single tree. It tries to extract a tree, and if the extraction returns `None`, it means that a particular choice was exhausted, or we hit on a recursion. In that case, we increment the choice, and explore a new path. | class EnhancedExtractor(EnhancedExtractor):
def extract_a_tree(self):
while not self.choices.finished():
parse_tree, choices = self.extract_a_node(self.my_forest, set(), self.choices)
choices.increment()
if parse_tree is not None:
return self.parser.prune_... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Note that the `EnhancedExtractor` only extracts nodes that are not directly recursive. That is, if it finds a node with a nonterminal that covers the same span as that of a parent node with the same nonterminal, it skips the node. | ee = EnhancedExtractor(EarleyParser(INDIRECTLY_SELF_REFERRING), mystring)
i = 0
while True:
i += 1
t = ee.extract_a_tree()
if t is None: break
print(i, t)
s = tree_to_string(t)
assert s == mystring
istring = '1+2+3+4'
ee = EnhancedExtractor(EarleyParser(A1_GRAMMAR), istring)
i = 0
while True:
... | 1 ('<start>', [('<expr>', [('<expr>', [('<expr>', [('<expr>', [('<integer>', [('<digit>', [('1', [])])])]), ('+', []), ('<expr>', [('<integer>', [('<digit>', [('2', [])])])])]), ('+', []), ('<expr>', [('<integer>', [('<digit>', [('3', [])])])])]), ('+', []), ('<expr>', [('<integer>', [('<digit>', [('4', [])])])])])])
2... | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
More Earley ParsingA number of other optimizations exist for Earley parsers. A fast industrial strength Earley parser implementation is the [Marpa parser](https://jeffreykegler.github.io/Marpa-web-site/). Further, Earley parsing need not be restricted to character data. One may also parse streams (audio and video stre... | mystring = "1 + (2 * 3)"
earley = EarleyParser(EXPR_GRAMMAR)
for tree in earley.parse(mystring):
assert tree_to_string(tree) == mystring
display(display_tree(tree))
mystring = "1 * (2 + 3.35)"
for tree in earley.parse(mystring):
assert tree_to_string(tree) == mystring
display(display_tree(tree)) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
In contrast to the `PEGParser`, above, the `EarleyParser` can handle arbitrary context-free grammars. Excursion: Testing the ParsersWhile we have defined two parser variants, it would be nice to have some confirmation that our parses work well. While it is possible to formally prove that they work, it is much more sat... | def prod_line_grammar(nonterminals, terminals):
g = {
'<start>': ['<symbols>'],
'<symbols>': ['<symbol><symbols>', '<symbol>'],
'<symbol>': ['<nonterminals>', '<terminals>'],
'<nonterminals>': ['<lt><alpha><gt>'],
'<lt>': ['<'],
'<gt>': ['>'],
'<alpha>': nonte... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Now we verify if our arbitrary grammars can be used by the Earley parser. | for i in range(5):
my_grammar = make_grammar()
print(my_grammar)
parser = EarleyParser(my_grammar)
mygf = GrammarFuzzer(my_grammar)
s = mygf.fuzz()
print(s)
for tree in parser.parse(s):
assert tree_to_string(tree) == s
display_tree(tree) | {'<SCS>': ['ts', 'f', 'ng'], '<BQN>': ['wm<SCS>', '<SCS>wi', '<SCS>hw'], '<UZC>': ['gyk<BQN>br', '<SCS>iqp', '<BQN>vb'], '<start>': ['<UZC>']}
fhwvb
{'<CRN>': ['meze', 'de', 'cpcv'], '<AIS>': ['<CRN>hb', 'dc<CRN>', 'pa<CRN>x'], '<MAO>': ['<CRN>su', '<CRN>hj', '<CRN><AIS>g'], '<start>': ['<MAO>']}
dehj
{'<MFY>': ['y', '... | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
With this, we have completed both implementation and testing of *arbitrary* CFG, which can now be used along with `LangFuzzer` to generate better fuzzing inputs. End of Excursion BackgroundNumerous parsing techniques exist that can parse a given string using agiven grammar, and produce corresponding derivation tree o... | from Grammars import US_PHONE_GRAMMAR
us_phone_parser = EarleyParser(US_PHONE_GRAMMAR) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Then, use the `parse()` method to retrieve a list of possible derivation trees: | trees = us_phone_parser.parse("(555)987-6543")
tree = list(trees)[0]
display_tree(tree) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
These derivation trees can then be used for test generation, notably for mutating and recombining existing inputs. | # ignore
from ClassDiagram import display_class_hierarchy
# ignore
display_class_hierarchy([PEGParser, EarleyParser],
public_methods=[
Parser.parse,
Parser.__init__,
Parser.grammar,
Pa... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Lessons Learned* Grammars can be used to generate derivation trees for a given string.* Parsing Expression Grammars are intuitive, and easy to implement, but require care to write.* Earley Parsers can parse arbitrary Context Free Grammars. Next Steps* Use parsed inputs to [recombine existing inputs](LangFuzzer.ipynb)... | class PackratParser(Parser):
def parse_prefix(self, text):
txt, res = self.unify_key(self.start_symbol(), text)
return len(txt), [res]
def parse(self, text):
remain, res = self.parse_prefix(text)
if remain:
raise SyntaxError("at " + res)
return res
def u... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Exercise 2: More PEG SyntaxThe _PEG_ syntax provides a few notational conveniences reminiscent of regular expressions. For example, it supports the following operators (letters `T` and `A` represents tokens that can be either terminal or nonterminal. `ε` is an empty string, and `/` is the ordered choice operator simil... | mystring = 'aaaaaa' | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
To see the problem, we need to enable logging. Here is the logged version of parsing with the `LR_GRAMMAR` | result = EarleyParser(LR_GRAMMAR, log=True).parse(mystring)
for _ in result: pass # consume the generator so that we can see the logs | None chart[0]
<A>:= |(0,0)
<start>:= <A> |(0,0)
a chart[1]
<A>:= <A> a |(0,1)
<start>:= <A> |(0,1)
a chart[2]
<A>:= <A> a |(0,2)
<start>:= <A> |(0,2)
a chart[3]
<A>:= <A> a |(0,3)
<start>:= <A> |(0,3)
a chart[4]
<A>:= <A> a |(0,4)
<start>:= <A> |(0,4)
a chart[5]
<A>:= <A> a |(0,5)
<start>:= <A> |(0,5)
a cha... | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Compare that to the parsing of `RR_GRAMMAR` as seen below: | result = EarleyParser(RR_GRAMMAR, log=True).parse(mystring)
for _ in result: pass | None chart[0]
<A>:= |(0,0)
<start>:= <A> |(0,0)
a chart[1]
<A>:= |(1,1)
<A>:= a <A> |(0,1)
<start>:= <A> |(0,1)
a chart[2]
<A>:= |(2,2)
<A>:= a <A> |(1,2)
<A>:= a <A> |(0,2)
<start>:= <A> |(0,2)
a chart[3]
<A>:= |(3,3)
<A>:= a <A> |(2,3)
<A>:= a <A> |(1,3)
<A>:= a <A> |(0,3)
<start>:= <A> |(0,3)
a chart[4]
<A>:... | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
As can be seen from the parsing log for each letter, the number of states with representation `: a ● (i, j)` increases at each stage, and these are simply a left over from the previous letter. They do not contribute anything more to the parse other than to simply complete these entries. However, they take up space, an... | class LeoParser(EarleyParser):
def complete(self, col, state):
return self.leo_complete(col, state)
def leo_complete(self, col, state):
detred = self.deterministic_reduction(state)
if detred:
col.add(detred.copy())
else:
self.earley_complete(col, state)
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Can you implement the `deterministic_reduction()` method to obtain the topmost element? **Solution.** Here is a possible solution: First, we update our `Column` class with the ability to add transitive items. Note that, while Leo asks the transitive to be added to the set $ I_k $ there is no actual requirement for the... | class Column(Column):
def __init__(self, index, letter):
self.index, self.letter = index, letter
self.states, self._unique, self.transitives = [], {}, {}
def add_transitive(self, key, state):
assert key not in self.transitives
self.transitives[key] = state
return self.tr... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Remember the picture we drew of the deterministic path?``` : seq_3 ● (s_3, e) | constraints satisfied by : seq_3 ● (s_3, s_2) : seq_2 ● (s_2, e) | constraints satisfied by : seq_2 ● (s_2, s_1) : seq_1 ● (s_1, e)``` We... | class LeoParser(LeoParser):
def uniq_postdot(self, st_A):
col_s1 = st_A.s_col
parent_states = [
s for s in col_s1.states if s.expr and s.at_dot() == st_A.name
]
if len(parent_states) > 1:
return None
matching_st_B = [s for s in parent_states if s.dot =... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We next define the function `get_top()` that is the core of deterministic reduction which gets the topmost state above the current state (`A`). | class LeoParser(LeoParser):
def get_top(self, state_A):
st_B_inc = self.uniq_postdot(state_A)
if not st_B_inc:
return None
t_name = st_B_inc.name
if t_name in st_B_inc.e_col.transitives:
return st_B_inc.e_col.transitives[t_name]
st_B = st_B_i... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Once we have the machinery in place, `deterministic_reduction()` itself is simply a wrapper to call `get_top()` | class LeoParser(LeoParser):
def deterministic_reduction(self, state):
return self.get_top(state)
lp = LeoParser(RR_GRAMMAR)
columns = lp.chart_parse(mystring, lp.start_symbol())
[(str(s), str(lp.get_top(s))) for s in columns[-1].states] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Now, both LR and RR grammars should work within $O(n)$ bounds. | result = LeoParser(RR_GRAMMAR, log=True).parse(mystring)
for _ in result: pass | None chart[0]
<A>:= |(0,0)
<start>:= <A> |(0,0)
a chart[1]
<A>:= |(1,1)
<A>:= a <A> |(0,1)
<start>:= <A> |(0,1)
a chart[2]
<A>:= |(2,2)
<A>:= a <A> |(1,2)
<start>:= <A> |(0,2)
a chart[3]
<A>:= |(3,3)
<A>:= a <A> |(2,3)
<start>:= <A> |(0,3)
a chart[4]
<A>:= |(4,4)
<A>:= a <A> |(3,4)
<start>:= <A> |(0,4)
a char... | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We verify the Leo parser with a few more right recursive grammars. | RR_GRAMMAR2 = {
'<start>': ['<A>'],
'<A>': ['ab<A>', ''],
}
mystring2 = 'ababababab'
result = LeoParser(RR_GRAMMAR2, log=True).parse(mystring2)
for _ in result: pass
RR_GRAMMAR3 = {
'<start>': ['c<A>'],
'<A>': ['ab<A>', ''],
}
mystring3 = 'cababababab'
result = LeoParser(RR_GRAMMAR3, log=True).parse(mys... | None chart[0]
a chart[1]
<A>:= a |(0,1)
<start>:= <A> |(0,1)
a chart[2]
<A>:= a |(1,2)
<start>:= <A> |(0,2)
a chart[3]
<A>:= a |(2,3)
<start>:= <A> |(0,3)
a chart[4]
<A>:= a |(3,4)
<start>:= <A> |(0,4)
a chart[5]
<A>:= a |(4,5)
<start>:= <A> |(0,5)
a chart[6]
<A>:= a |(5,6)
<start>:= <A> |(0,6)
a chart[7... | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We verify that our parser works correctly on `LR_GRAMMAR` too. | result = LeoParser(LR_GRAMMAR, log=True).parse(mystring)
for _ in result: pass | None chart[0]
<A>:= |(0,0)
<start>:= <A> |(0,0)
a chart[1]
<A>:= <A> a |(0,1)
<start>:= <A> |(0,1)
a chart[2]
<A>:= <A> a |(0,2)
<start>:= <A> |(0,2)
a chart[3]
<A>:= <A> a |(0,3)
<start>:= <A> |(0,3)
a chart[4]
<A>:= <A> a |(0,4)
<start>:= <A> |(0,4)
a chart[5]
<A>:= <A> a |(0,5)
<start>:= <A> |(0,5)
a cha... | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
__Advanced:__ We have fixed the complexity bounds. However, because we are saving only the topmost item of a right recursion, we need to fix our parser to be aware of our fix while extracting parse trees. Can you fix it?__Hint:__ Leo suggests simply transforming the Leo item sets to normal Earley sets, with the results... | class Column(Column):
def add_transitive(self, key, state):
assert key not in self.transitives
self.transitives[key] = TState(state.name, state.expr, state.dot,
state.s_col, state.e_col)
return self.transitives[key] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We also need a `back()` method to create the constraints. | class State(State):
def back(self):
return TState(self.name, self.expr, self.dot - 1, self.s_col, self.e_col) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We update `copy()` to make `TState` items instead. | class TState(State):
def copy(self):
return TState(self.name, self.expr, self.dot, self.s_col, self.e_col) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We now modify the `LeoParser` to keep track of the chain of constrains that we mentioned earlier. | class LeoParser(LeoParser):
def __init__(self, grammar, **kwargs):
super().__init__(grammar, **kwargs)
self._postdots = {} | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Next, we update the `uniq_postdot()` so that it tracks the chain of links. | class LeoParser(LeoParser):
def uniq_postdot(self, st_A):
col_s1 = st_A.s_col
parent_states = [
s for s in col_s1.states if s.expr and s.at_dot() == st_A.name
]
if len(parent_states) > 1:
return None
matching_st_B = [s for s in parent_states if s.dot =... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We next define a method `expand_tstate()` that, when given a `TState`, generates all the intermediate links that we threw away earlier for a given end column. | class LeoParser(LeoParser):
def expand_tstate(self, state, e):
if state._t() not in self._postdots:
return
c_C = self._postdots[state._t()]
e.add(c_C.advance())
self.expand_tstate(c_C.back(), e) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We define a `rearrange()` method to generate a reversed table where each column contains states that start at that column. | class LeoParser(LeoParser):
def rearrange(self, table):
f_table = [Column(c.index, c.letter) for c in table]
for col in table:
for s in col.states:
f_table[s.s_col.index].states.append(s)
return f_table | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Here is the rearranged table. (Can you explain why the Column 0 has a large number of `` items?) | ep = LeoParser(RR_GRAMMAR)
columns = ep.chart_parse(mystring, ep.start_symbol())
r_table = ep.rearrange(columns)
for col in r_table:
print(col, "\n") | None chart[0]
<A>:= |(0,0)
<start>:= <A> |(0,0)
<A>:= a <A> |(0,1)
<start>:= <A> |(0,1)
<start>:= <A> |(0,2)
<start>:= <A> |(0,3)
<start>:= <A> |(0,4)
<start>:= <A> |(0,5)
<start>:= <A> |(0,6)
a chart[1]
<A>:= |(1,1)
<A>:= a <A> |(1,2)
a chart[2]
<A>:= |(2,2)
<A>:= a <A> |(2,3)
a chart[3]
<A>:= |(3,3)
<A>:= a <A>... | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
We save the result of rearrange before going into `parse_forest()`. | class LeoParser(LeoParser):
def parse(self, text):
cursor, states = self.parse_prefix(text)
start = next((s for s in states if s.finished()), None)
if cursor < len(text) or not start:
raise SyntaxError("at " + repr(text[cursor:]))
self.r_table = self.rearrange(self.table... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Finally, during `parse_forest()`, we first check to see if it is a transitive state, and if it is, expand it to the original sequence of states using `traverse_constraints()`. | class LeoParser(LeoParser):
def parse_forest(self, chart, state):
if isinstance(state, TState):
self.expand_tstate(state.back(), state.e_col)
return super().parse_forest(chart, state) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
This completes our implementation of `LeoParser`. We check whether the previously defined right recursive grammars parse and return the correct parse trees. | result = LeoParser(RR_GRAMMAR).parse(mystring)
for tree in result:
assert mystring == tree_to_string(tree)
result = LeoParser(RR_GRAMMAR2).parse(mystring2)
for tree in result:
assert mystring2 == tree_to_string(tree)
result = LeoParser(RR_GRAMMAR3).parse(mystring3)
for tree in result:
assert mystring3 == tr... | 'bbbbbbb'
'bbbbbbb'
| MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Exercise 6: Filtered Earley Parser One of the problems with our Earley and Leo Parsers is that it can get stuck in infinite loops when parsing with grammars that contain token repetitions in alternatives. For example, consider the grammar below. | RECURSION_GRAMMAR: Grammar = {
"<start>": ["<A>"],
"<A>": ["<A>", "<A>aa", "AA", "<B>"],
"<B>": ["<C>", "<C>cc", "CC"],
"<C>": ["<B>", "<B>bb", "BB"]
} | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
With this grammar, one can produce an infinite chain of derivations of ``, (direct recursion) or an infinite chain of derivations of ` -> -> ...` (indirect recursion). The problem is that, our implementation can get stuck trying to derive one of these infinite chains. One possibility is to use the `LazyExtractor`. An... | from ExpectError import ExpectTimeout
with ExpectTimeout(1, print_traceback=False):
mystring = 'AA'
parser = LeoParser(RECURSION_GRAMMAR)
tree, *_ = parser.parse(mystring)
assert tree_to_string(tree) == mystring
display_tree(tree) | RecursionError: maximum recursion depth exceeded (expected)
| MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Can you implement a solution such that any tree that contains such a chain is discarded? **Solution.** Here is a possible solution. | class FilteredLeoParser(LeoParser):
def forest(self, s, kind, seen, chart):
return self.parse_forest(chart, s, seen) if kind == 'n' else (s, [])
def parse_forest(self, chart, state, seen=None):
if isinstance(state, TState):
self.expand_tstate(state.back(), state.e_col)
def ... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
With the `FilteredLeoParser`, we should be able to recover minimal parse trees in reasonable time. | mystring = 'AA'
parser = FilteredLeoParser(RECURSION_GRAMMAR)
tree, *_ = parser.parse(mystring)
assert tree_to_string(tree) == mystring
display_tree(tree)
mystring = 'AAaa'
parser = FilteredLeoParser(RECURSION_GRAMMAR)
tree, *_ = parser.parse(mystring)
assert tree_to_string(tree) == mystring
display_tree(tree)
mystring... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
As can be seen, we are able to recover minimal parse trees without hitting on infinite chains. Exercise 7: Iterative Earley ParserRecursive algorithms are quite handy in some cases but sometimes we might want to have iteration instead of recursion due to memory or speed problems. Can you implement an iterative version... | class IterativeEarleyParser(EarleyParser):
def parse_paths(self, named_expr_, chart, frm, til_):
return_paths = []
path_build_stack = [(named_expr_, til_, [])]
def iter_paths(path_prefix, path, start, k, e):
x = path_prefix + [(path, k)]
if not e:
ret... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Next we used these paths to recover the forest data structure using `parse_forest()`. Since `parse_forest()` does not recurse, we reuse the original definition. Next, we define `extract_a_tree()` Now we are ready to extract trees from the forest using `extract_a_tree()` | class IterativeEarleyParser(IterativeEarleyParser):
def choose_a_node_to_explore(self, node_paths, level_count):
first, *rest = node_paths
return first
def extract_a_tree(self, forest_node_):
start_node = (forest_node_[0], [])
tree_build_stack = [(forest_node_, start_node[-1], 0... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
For now, we simply extract the first tree found. | class IterativeEarleyParser(IterativeEarleyParser):
def extract_trees(self, forest):
yield self.extract_a_tree(forest) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Let's see if it works with some of the grammars we have seen so far. | test_cases: List[Tuple[Grammar, str]] = [
(A1_GRAMMAR, '1-2-3+4-5'),
(A2_GRAMMAR, '1+2'),
(A3_GRAMMAR, '1+2+3-6=6-1-2-3'),
(LR_GRAMMAR, 'aaaaa'),
(RR_GRAMMAR, 'aa'),
(DIRECTLY_SELF_REFERRING, 'select a from a'),
(INDIRECTLY_SELF_REFERRING, 'select a from a'),
(RECURSION_GRAMMAR, 'AA'),
... | 0 1-2-3+4-5
1 1+2
2 1+2+3-6=6-1-2-3
3 aaaaa
4 aa
5 select a from a
6 select a from a
7 AA
8 AAaaaa
9 BBccbb
| MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
As can be seen, our `IterativeEarleyParser` is able to handle recursive grammars. However, it can only extract the first tree found. What should one do to get all possible parses? What we can do, is to keep track of options to explore at each `choose_a_node_to_explore()`. Next, capture in the nodes explored in a tree d... | def firstset(grammar, nullable):
first = {i: {i} for i in terminals(grammar)}
for k in grammar:
first[k] = {EPSILON} if k in nullable else set()
return firstset_((rules(grammar), first, nullable))[1] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Finally, we rely on the `fixpoint` to update the first set with the contents of the current first set until the first set stops changing. | def first_expr(expr, first, nullable):
tokens = set()
for token in expr:
tokens |= first[token]
if token not in nullable:
break
return tokens
@fixpoint
def firstset_(arg):
(rules, first, epsilon) = arg
for A, expression in rules:
first[A] |= first_expr(expression,... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Exercise 9: Follow Set of a NonterminalThe follow set definition is similar to the first set. The follow set of a nonterminal is the set of terminals that can occur just after that nonterminal is used in any derivation. The follow set of the start symbol is `EOF`, and the follow set of any nonterminal is the super set... | EOF = '\0'
def followset(grammar, start):
follow = {i: set() for i in grammar}
follow[start] = {EOF}
epsilon = nullable(grammar)
first = firstset(grammar, epsilon)
return followset_((grammar, epsilon, first, follow))[-1] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Given the current follow set, one can update the follow set as follows: | @fixpoint
def followset_(arg):
grammar, epsilon, first, follow = arg
for A, expression in rules(grammar):
f_B = follow[A]
for t in reversed(expression):
if t in grammar:
follow[t] |= f_B
f_B = f_B | first[t] if t in epsilon else (first[t] - {EPSILON})
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Exercise 10: A LL(1) ParserAs we mentioned previously, there exist other kinds of parsers that operate left-to-right with right most derivation (*LR(k)*) or left-to-right with left most derivation (*LL(k)*) with _k_ signifying the amount of lookahead the parser is permitted to use.What should one do with the lookahead... | class LL1Parser(Parser):
def parse_table(self):
self.my_rules = rules(self.cgrammar)
self.table = ... # fill in here to produce
def rules(self):
for i, rule in enumerate(self.my_rules):
print(i, rule)
def show_table(self):
ts = list(sorted(terminals(sel... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
On invocation of `LL1Parser(A2_GRAMMAR).show_table()`It should result in the following table: | for i, r in enumerate(rules(canonical(A2_GRAMMAR))):
print("%d\t %s := %s" % (i, r[0], r[1])) | 0 <start> := ['<expr>']
1 <expr> := ['<integer>', '<expr_>']
2 <expr_> := ['+', '<expr>']
3 <expr_> := ['-', '<expr>']
4 <expr_> := []
5 <integer> := ['<digit>', '<integer_>']
6 <integer_> := ['<integer>']
7 <integer_> := []
8 <digit> := ['0']
9 <digit> := ['1']
10 <digit> := ['2']
11 <digit> := ['3']
12 <... | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
|Rule Name || + | - | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9||-----------||---|---|---|---|---|---|---|---|---|---|---|--||start || | | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0||expr || | | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1||expr_ || 2 | 3 | | | | | | | | | | ||integer || | | 5 ... | class LL1Parser(LL1Parser):
def predict(self, rulepair, first, follow, epsilon):
A, rule = rulepair
rf = first_expr(rule, first, epsilon)
if nullable_expr(rule, epsilon):
rf |= follow[A]
return rf
def parse_table(self):
self.my_rules = rules(self.cgrammar)
... | Rule Name | + | - | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<start> | | | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
<expr> | | | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1
<expr_> | 2 | 3 | | | | | | | | | |
<integer> | | | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5
<integer_> | 7 | 7 | 6 | 6 ... | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
Part 2: The ParserOnce we have the parse table, implementing the parser is as follows: Consider the first item from the sequence of tokens to parse, and seed the stack with the start symbol.While the stack is not empty, extract the first symbol from the stack, and if the symbol is a terminal, verify that the symbol ma... | class LL1Parser(LL1Parser):
def parse_helper(self, stack, inplst):
inp, *inplst = inplst
exprs = []
while stack:
val, *stack = stack
if isinstance(val, tuple):
exprs.append(val)
elif val not in self.cgrammar: # terminal
ass... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | rindPHI/fuzzingbook |
#for loops
value=["value 0","value 1","value 2","value 3","value 4","value 5","value 6", "value 7", "value 8", "value 9", "value 10"]
for x in value:
print(x)
#while loop
i=0
while i<11:
print("Value",i)
i+=1 | Value 0
Value 1
Value 2
Value 3
Value 4
Value 5
Value 6
Value 7
Value 8
Value 9
Value 10
| Apache-2.0 | Week_12_Assessment.ipynb | RYCMDNT/CPEN-21A-CPE-1-2 | |
Using plotting tools associated with the Landlab NetworkSedimentTransporter component For more Landlab tutorials, click here: https://landlab.readthedocs.io/en/latest/user_guide/tutorials.htmlThis tutorial illustrates how to plot the results of the NetworkSedimentTransporter Landlab component using the `plot_network_... | import warnings
warnings.filterwarnings('ignore')
import os
import pathlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
from landlab import ExampleData
from landlab.components import FlowDirectorSteepest, NetworkSedimentTransporter
from landlab.data_record import DataRecord
fr... | _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
1. Create and run the synthetic example of NSTFirst, we need to create an implementation of the Landlab NetworkModelGrid to plot. This example creates a synthetic grid, defining the location of each node and link. | y_of_node = (0, 100, 200, 200, 300, 400, 400, 125)
x_of_node = (0, 0, 100, -50, -100, 50, -150, -100)
nodes_at_link = ((1, 0), (2, 1), (1, 7), (3, 1), (3, 4), (4, 5), (4, 6))
grid1 = NetworkModelGrid((y_of_node, x_of_node), nodes_at_link)
grid1.at_node["bedrock__elevation"] = [0.0, 0.05, 0.2, 0.1, 0.25, 0.4, 0.8, 0.8... | _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
2. Create and run an example of NST using a shapefile to define the networkFirst, we need to create an implementation of the Landlab NetworkModelGrid to plot. This example creates a grid based on a polyline shapefile. | datadir = ExampleData("io/shapefile", case="methow").base
shp_file = datadir / "MethowSubBasin.shp"
points_shapefile = datadir / "MethowSubBasin_Nodes_4.shp"
grid2 = read_shapefile(
shp_file,
points_shapefile=points_shapefile,
node_fields=["usarea_km2", "Elev_m"],
link_fields=["usarea_km2", "Length_m"... | _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
3. Options for link color and link line widthsThe dictionary below (`link_color_options`) outlines 4 examples of link color and line width choices: 1. The default output of `plot_network_and_parcels`2. Some simple modifications: the whole network is red, with a line width of 7, and no parcels.3. Coloring links by an e... | network_norm = Normalize(-1, 6) # see matplotlib.colors.Normalize
link_color_options = [
{# empty dictionary = defaults
},
{
"network_color":'r', # specify some simple modifications.
"network_linewidth":7,
"parcel_alpha":0 # make parcels transparent (not visible)
},
{
... | _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
Below, we implement these 4 plotting options, first for the synthetic network, and then for the shapefile-delineated network: | for grid, parcels in zip([grid1, grid2], [parcels1, parcels2]):
for l_opts in link_color_options:
fig = plot_network_and_parcels(
grid, parcels,
parcel_time_index=0, **l_opts)
plt.show()
| _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
In addition to plotting link coloring using an existing link attribute, we can pass any array of size link. In this example, we color links using an array of random values. | random_link = np.random.randn(grid2.size("link"))
l_opts = {
"link_attribute": random_link, # use an array of size link
"network_cmap": "jet", # change colormap
"network_norm": network_norm, # and normalize
"link_attribute_title": "A random number",
"parcel_alpha":0,
... | _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
4. Options for parcel colorThe dictionary below (`parcel_color_options`) outlines 4 examples of link color and line width choices: 1. The default output of `plot_network_and_parcels`2. Some simple modifications: all parcels are red, with a parcel size of 103. Color parcels by an existing parcel attribute, in this case... | parcel_color_norm = Normalize(0, 1) # Linear normalization
parcel_color_norm2=colors.LogNorm(vmin=0.01, vmax=1)
parcel_color_options = [
{# empty dictionary = defaults
},
{
"parcel_color":'r', # specify some simple modifications.
"parcel_size":10
},
{
"parcel_color_attribu... | _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
5. Options for parcel sizeThe dictionary below (`parcel_size_options`) outlines 4 examples of link color and line width choices: 1. The default output of `plot_network_and_parcels`2. Set a uniform parcel size and color3. Size parcels by an existing parcel attribute, in this case the sediment diameter (`parcels1.datase... | parcel_size_norm = Normalize(0, 1)
parcel_size_norm2=colors.LogNorm(vmin=0.01, vmax=1)
parcel_size_options = [
{# empty dictionary = defaults
},
{
"parcel_color":'b', # specify some simple modifications.
"parcel_size":10
},
{
"parcel_size_attribute": "D", # use a parcel at... | _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
6. Plotting a subset of the parcelsIn some cases, we might want to plot only a subset of the parcels on the network. Below, we plot every 50th parcel in the `DataRecord`. | parcel_filter = np.zeros((parcels2.dataset.dims["item_id"]), dtype=bool)
parcel_filter[::50] = True
pc_opts= {
"parcel_color_attribute": "D", # a more complex normalization and a parcel filter.
"parcel_color_norm": parcel_color_norm2,
"parcel_color_attribute_title":"Diameter [m]",
"parc... | _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
7. Select the parcel timestep to be plottedAs a default, `plot_network_and_parcels` plots parcel positions for the last timestep of the model run. However, `NetworkSedimentTransporter` tracks the motion of parcels for all timesteps. We can plot the location of parcels on the link at any timestep using `parcel_time_ind... | parcel_time_options = [0,4,7]
for grid, parcels in zip([grid1, grid2], [parcels1, parcels2]):
for pt_opts in parcel_time_options:
fig = plot_network_and_parcels(
grid, parcels,
parcel_size = 20,
parcel_alpha = 0.1,
parcel_time_index=pt_opts)
plt.show... | _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
7. Combining network and parcel plotting optionsNothing will stop us from making all of the choices at once. | parcel_color_norm=colors.LogNorm(vmin=0.01, vmax=1)
parcel_filter = np.zeros((parcels2.dataset.dims["item_id"]), dtype=bool)
parcel_filter[::30] = True
fig = plot_network_and_parcels(grid2,
parcels2,
parcel_time_index=0,
... | _____no_output_____ | MIT | notebooks/tutorials/network_sediment_transporter/network_plotting_examples.ipynb | pfeiffea/landlab |
The tanh-sinh (or double exponential) method.We calculate an integral in the following fashion:$$I=\int_{-1}^{1} dx f(x) = \int_{-\infty}^{\infty} dt \; f(g(t)) \;g^{\prime}(t) \approx h \sum_{j=-N}^{N} w_j \; f(x_j)\; ,$$with $x_j= g(h \, t)$ and $w_j = g^{\prime}(h \, t) $. The functio $g(t)$ transorms the interva... | import numpy as np
from numpy import tanh,sinh,cosh,pi,abs
#just for testing
from scipy.integrate import quad
class DoubleExp:
def g(self,t):
return tanh( pi/2. * sinh(t) )
def dgdt(self,t):
return pi/2. *cosh(t)/cosh( pi/2. * sinh(t) )**2.
def F(self,t):
#this will be... | _____no_output_____ | MIT | Integration/Double-Exponential/DoubleExp.ipynb | dkaramit/ASAP |
"Custom" tutorialThis tutorial is intended to showcase how to customize some elements of BTK, namely the sampling function, the surveys or the measure function. We encourage you to follow the intro tutorial first if you have not already done so. Table of contents- [Custom sampling function](custom_sampling_function)- ... | class DefaultSampling(btk.sampling_functions.SamplingFunction):
"""Default sampling function used for producing blend tables."""
def __init__(self, max_number=2, stamp_size=24.0, maxshift=None):
"""
Args:
max_number (int): Defined in parent class
stamp_size (float): Size... | _____no_output_____ | MIT | notebooks/02b-custom-tutorial.ipynb | b-biswas/BlendingToolKit |
As you can see, this sampling function does 3 things: applying a magnitude cut to the catalog, selecting random galaxies uniformly (with a random number of galaxies, the maximum being specified at the initialization), and assigning them random uniform shifts.Here is how we would write a sampling function for generating... | class PairSampling(btk.sampling_functions.SamplingFunction):
def __init__(self, stamp_size=24.0, maxshift=None):
super().__init__(2)
self.stamp_size = stamp_size
self.maxshift = maxshift if maxshift else self.stamp_size / 10.0
@property
def compatible_catalogs(self):
re... | _____no_output_____ | MIT | notebooks/02b-custom-tutorial.ipynb | b-biswas/BlendingToolKit |
You can try to write your own sampling function here if you wish. Here is some code to test our new sampling function (please replace the first line if you wrote your own sampling function). | sampling_function = PairSampling()
catalog_name = "../data/sample_input_catalog.fits"
stamp_size = 24
survey = btk.survey.get_surveys("Rubin")
catalog = btk.catalog.CatsimCatalog.from_file(catalog_name)
draw_blend_generator = btk.draw_blends.CatsimGenerator(
catalog,
sampling_function,
survey,
stamp_siz... | _____no_output_____ | MIT | notebooks/02b-custom-tutorial.ipynb | b-biswas/BlendingToolKit |
Custom surveyThe survey defines the observational parameters relative to the instrument and telescope making the observation; in particular, it serves to define the pixel scale, the number of bands, the noise level, the flux, and the PSF.A number of surveys is provided with BTK, so most users will not need to define ... | from btk.survey import Survey, Filter, get_psf
_central_wavelength = {
"u": 3592.13,
"g": 4789.98,
"r": 6199.52,
"i": 7528.51,
"z": 8689.83,
"y": 9674.05,
}
Rubin = btk.survey.Survey(
"Rubin",
pixel_scale=0.2,
effective_area=32.4,
mirror_diameter=8.36,
airmass=1.2,
zerop... | _____no_output_____ | MIT | notebooks/02b-custom-tutorial.ipynb | b-biswas/BlendingToolKit |
Custom measure functionUsers who wish to test their own algorithm using BTK should consider writing a measure function. Morally, a measure function takes in blends and return measurements, ie detections, segmentation and deblended images. It is then fed to a MeasureGenerator, which will apply the function for every bl... | import sep
def sep_measure(batch, idx, channels_last=False, surveys=None, sigma_noise=1.5, **kwargs):
"""Return detection, segmentation and deblending information with SEP.
NOTE: If this function is used with the multiresolution feature,
measurements will be carried on the first survey, and deblended image... | _____no_output_____ | MIT | notebooks/02b-custom-tutorial.ipynb | b-biswas/BlendingToolKit |
You can see that the function takes `batch` and `idx` as arguments, but also has a `channels_last` argument and some kwargs. You can either specify arguments or catch them with `kwargs.get()`, as is done with `sigma_noise` there. To pass those arguments to the function, you can use the measure_kwargs, as detailed later... | catalog_name = "../data/sample_input_catalog.fits"
stamp_size = 24
survey = btk.survey.get_surveys("Rubin")
catalog = btk.catalog.CatsimCatalog.from_file(catalog_name)
draw_blend_generator = btk.draw_blends.CatsimGenerator(
catalog,
btk.sampling_functions.DefaultSampling(),
survey,
stamp_size=stamp_size... | _____no_output_____ | MIT | notebooks/02b-custom-tutorial.ipynb | b-biswas/BlendingToolKit |
Then we can define a target measure function. This one is builtin with BTK and uses the Galsim implementation of the KSB method to measure the ellipticity of the galaxy. | def meas_ksb_ellipticity(image, additional_params):
"""Utility function to measure ellipticity using the `galsim.hsm` package, with the KSB method.
Args:
image (np.array): Image of a single, isolated galaxy with shape (H, W).
additional_params (dict): Containing keys 'psf', 'pixel_scale' and 'm... | _____no_output_____ | MIT | notebooks/02b-custom-tutorial.ipynb | b-biswas/BlendingToolKit |
We can now see the results : | print("Raw metrics results for deblended images : ",metrics_results["reconstruction"]["sep_measure"]["ellipticity0"][:5])
print("Raw metrics results for true images : ",metrics_results["reconstruction"]["sep_measure"]["ellipticity0_true"][:5])
print(metrics_results["galaxy_summary"]["sep_measure"]["ellipticity0","ellip... | ellipticity0 ellipticity0_true
-------------------- ----------------------
-0.02696719765663147 -0.0013318936107680202
nan nan
-10.0 -0.00601611565798521
0.17775359749794006 0.1264297366142273
-0.1585843712091446 -0.14031007885932922
| MIT | notebooks/02b-custom-tutorial.ipynb | b-biswas/BlendingToolKit |
As usual, we can use the interactive function to plot the results. In the case of target measures, you need to provide two additional arguments to have it work : a list of the names of the measures, and the interval in which they are comprised. | btk.plot_utils.plot_metrics_summary(metrics_results,interactive=True,
target_meas_keys=['ellipticity0','ellipticity1'],
target_meas_limits=[(-1, 1),(-1,1)]) | _____no_output_____ | MIT | notebooks/02b-custom-tutorial.ipynb | b-biswas/BlendingToolKit |
- Scipy의 stats 서브 패키지에 있는 binom 클래스는 이항 분포 클래스이다. n 인수와 p 인수를 사용하여 모수를 설정한다 | N = 10
theta = 0.6
rv = sp.stats.binom(N, theta)
rv | _____no_output_____ | MIT | 2018_06_11_Preview_SciPy_Bern.ipynb | jaykim-asset/datascience_review |
- pmf 메서드를 사용하면, 확률 질량 함수 (pmf: probability mass function)를 계산할 수 있다. | %matplotlib inline
xx = np.arange(N + 1)
plt.bar(xx, rv.pmf(xx), align='center')
plt.ylabel('p(x)')
plt.title('binomial pmf')
plt.show() | C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\font_manager.py:1320: UserWarning: findfont: Font family ['nanumgothic'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))
| MIT | 2018_06_11_Preview_SciPy_Bern.ipynb | jaykim-asset/datascience_review |
- 시뮬레이션을 하려면 rvs 메서드를 사용한다. | np.random.seed(0)
x = rv.rvs(100)
x
sns.countplot(x)
plt.title("Binomial Distribution's Simulation")
plt.xlabel('Sample')
plt.show() | C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\font_manager.py:1320: UserWarning: findfont: Font family ['nanumgothic'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))
| MIT | 2018_06_11_Preview_SciPy_Bern.ipynb | jaykim-asset/datascience_review |
- 이론적인 확률 분포와 샘플의 확률 분포를 동시에 나타내려면 다음과 같은 코드를 사용한다. | y = np.bincount(x, minlength=N+1)/float(len(x))
df = pd.DataFrame({'Theory': rv.pmf(xx), 'simulation': y}).stack()
df = df.reset_index()
df.columns = ['values', 'type', 'ratio']
df.pivot('values', 'type', 'ratio')
df
sns.barplot(x='values', y='ratio', hue='type', data=df)
plt.show() | C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\font_manager.py:1320: UserWarning: findfont: Font family ['nanumgothic'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))
| MIT | 2018_06_11_Preview_SciPy_Bern.ipynb | jaykim-asset/datascience_review |
연습 문제 1- 이항 확률 분포의 모수가 다음과 같을 경우에 각각 샘플을 생성한 후, 기댓값과 분산을 구하고 앞의 예제와 같이 확률 밀도 함수와 비교한 카운트 플롯을 그린다.- 샘풀의 갯수가 10개인 경우와 1000개인 경우에 대해 각각 위의 계산을 한다.- 1. Theta = 0.5, N = 5- 2. Theta = 0.9, N = 20 | # 연습문제 1 - 1
N = 5
theta = 0.5
rv = sp.stats.binom(N, theta)
xx10 = np.arange(N + 1)
plt.bar(xx, rv.pmf(xx10), align='center')
plt.ylabel('P(x)')
plt.title('Binomail Distribution pmdf')
plt.show()
# sample 갯수 10개 일 때
np.random.seed(0)
x10 = rv.rvs(10)
sns.countplot(x10)
plt.title('binomail distribution Simulation 10')... | _____no_output_____ | MIT | 2018_06_11_Preview_SciPy_Bern.ipynb | jaykim-asset/datascience_review |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.