AXON: Examples


In [1]:
import axon

from datetime import date, time, datetime
from pprint import pprint

try:
    from cdecimal import Decimal  
except:
    from decimal import Decimal

Simple values

Integer values


In [2]:
vs = axon.loads('''
0
1
-1
32768
-9223372036854775807''')
pprint(vs)
axon.display_html(vs)


[0, 1, -1, 32768, -9223372036854775807]
:0: FutureWarning: IPython widgets are experimental and may change in the future.

In [3]:
vs = axon.loads('''
340282366920938463463374607431768211456
-340282366920938463463374607431768211456''') # long int value =/-2**128
pprint(vs)
axon.display_html(vs)


[340282366920938463463374607431768211456,
 -340282366920938463463374607431768211456]

Float values


In [4]:
vs = axon.loads('''
0.
0.0
1.0
-1.0
-0.0
3.141528
1.41e2
-1.41e-2''')
pprint(vs)
axon.display_html(vs)


[0.0, 0.0, 1.0, -1.0, -0.0, 3.141528, 141.0, -0.0141]

In [5]:
try:
    vs = axon.loads('.12')
except axon.AxonError:
    print('invalid float number')


invalid float number

In [6]:
vs = axon.loads('''

-∞
?
''')
pprint(vs)
axon.display_html(vs)


[inf, -inf, nan]

In [7]:
try:
    vs = axon.loads('.')
except axon.AxonError:
    print('invalid float number')


invalid float number

Decimal values


In [8]:
vs = axon.loads('''
0D
1d
-1D
0.d
0.0d
1.0D
-1.0D
-0.0D
3.141528D
1.41e2d
-1.41e-2d''')
pprint(vs)
axon.display_html(vs)


[Decimal('0'),
 Decimal('1'),
 Decimal('-1'),
 Decimal('0'),
 Decimal('0.0'),
 Decimal('1.0'),
 Decimal('-1.0'),
 Decimal('-0.0'),
 Decimal('3.141528'),
 Decimal('141'),
 Decimal('-0.0141')]

In [9]:
vs = axon.loads('''
?D
∞D
-∞D''')
pprint(vs)
axon.display_html(vs)


[Decimal('NaN'), Decimal('Infinity'), Decimal('-Infinity')]

Unicode text


In [10]:
vs = axon.loads('''"any unicode text
with line breaks
and control symbols \t\n"''')
pprint(vs)
axon.display_html(vs)


['any unicode text\nwith line breaks\nand control symbols \t\n']

In [11]:
vs = axon.loads('''"text line \
splited \
into chunks"''')
pprint(vs)
axon.display_html(vs)


['text line splited into chunks']

Date/Time values


In [12]:
vs = axon.loads('''
2012-12-31
12:30
12:30:59
12:30:59.150000
12:30:59+03
2012-12-31T12:30:59.015000-04''')
pprint(vs)
axon.display_html(vs)


[datetime.date(2012, 12, 31),
 datetime.time(12, 30),
 datetime.time(12, 30, 59),
 datetime.time(12, 30, 59, 150000),
 datetime.time(12, 30, 59, tzinfo=datetime.timezone(datetime.timedelta(0, 10800))),
 datetime.datetime(2012, 12, 31, 12, 30, 59, 15000, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))]

Anonymous complex objects

Simply lines of data


In [13]:
text = '''
# No Sym Flag Date Time
[1 "a" true 2007-12-20 9:00]
[2 "b" false 2007-12-20 15:00]
[3 "c" false 2007-12-20 00:00]
'''
vs = axon.loads(text)
pprint(vs)
axon.display_html(vs)


[[1, 'a', True, datetime.date(2007, 12, 20), datetime.time(9, 0)],
 [2, 'b', False, datetime.date(2007, 12, 20), datetime.time(15, 0)],
 [3, 'c', False, datetime.date(2007, 12, 20), datetime.time(0, 0)]]

Simply dicts


In [14]:
text = u'''
{"a":1 "b":2.0 "c":3000D}
{"a":100 "b":200.5 "c":30D "d":null}
'''
vs = axon.loads(text)
pprint(vs)
axon.display_html(vs)


[{'a': 1, 'b': 2.0, 'c': Decimal('3000')},
 {'a': 100, 'b': 200.5, 'c': Decimal('30'), 'd': None}]

Simply tuples


In [15]:
text = u'''
(2013-01-01 12:30) 
(2013-01-02 13:00)
(2013-01-03 14:30)
'''
vs = axon.loads(text)
pprint(vs)
axon.display_html(vs)


[(datetime.date(2013, 1, 1), datetime.time(12, 30)),
 (datetime.date(2013, 1, 2), datetime.time(13, 0)),
 (datetime.date(2013, 1, 3), datetime.time(14, 30))]

Simply dicts of lists


In [16]:
text = u'''
{ a: [0 1 2] 
  b: [0. 1.0 2.0] 
  c: [0.D 1.0D] 
  d: [true] }
{ a: [100 200 300] 
  b: [100. 200. 300.] 
  c: [10D 20D] 
  s: [false] }
'''
vs = axon.loads(text)
pprint(vs)
axon.display_html(vs)


[{'a': [0, 1, 2],
  'b': [0.0, 1.0, 2.0],
  'c': [Decimal('0'), Decimal('1.0')],
  'd': [True]},
 {'a': [100, 200, 300],
  'b': [100.0, 200.0, 300.0],
  'c': [Decimal('10'), Decimal('20')],
  's': [False]}]

Named complex objects

Simply named dicts of tuples


In [17]:
text = u'''
rectangle {
    left_top: (-1.0 1.0)
    left_bottom: (-1.0 -1.0)
    right_top: (1.0 1.0)
    right_bottom: (1.0 -1.0)
}
rectangle {
    left_top: (-2.0 2.0)
    left_bottom: (-2.0 -1.0)
    right_top: (1.0 2.0)
    right_bottom: (1.0 -1.0)
}
'''
vs = axon.loads(text)
pprint(vs)
axon.display_html(vs)


[rectangle{left_top: (-1.0, 1.0), left_bottom: (-1.0, -1.0), right_top: (1.0, 1.0), right_bottom: (1.0, -1.0)},
 rectangle{left_top: (-2.0, 2.0), left_bottom: (-2.0, -1.0), right_top: (1.0, 2.0), right_bottom: (1.0, -1.0)}]

In [18]:
v1, v2 = vs
print(v1)
print(v2)
print(v1.__tag__, v1.__attrs__)
print(v1.left_bottom, v1.right_top)


rectangle{left_top: (-1.0, 1.0), left_bottom: (-1.0, -1.0), right_top: (1.0, 1.0), right_bottom: (1.0, -1.0)}
rectangle{left_top: (-2.0, 2.0), left_bottom: (-2.0, -1.0), right_top: (1.0, 2.0), right_bottom: (1.0, -1.0)}
rectangle OrderedDict([('left_top', (-1.0, 1.0)), ('left_bottom', (-1.0, -1.0)), ('right_top', (1.0, 1.0)), ('right_bottom', (1.0, -1.0))])
(-1.0, -1.0) (1.0, 1.0)

Simply named lists of tuples


In [19]:
text = u'''
rectangle {
    (-1.0 1.0) 
    (-1.0 -1.0)
    (1.0 -1.0)
    (1.0 1.0)
}
rectangle {
    (-2.0 2.0)
    (-2.0 -1.0)
    (1.0 -1.0)
    (1.0 2.0)
}
'''
vs = axon.loads(text)
pprint(vs)
axon.display_html(vs)


[rectangle{(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0), (1.0, 1.0)},
 rectangle{(-2.0, 2.0), (-2.0, -1.0), (1.0, -1.0), (1.0, 2.0)}]

In [20]:
print(vs[0])
print(vs[1])
print(vs[0].__tag__, vs[0].__vals__)


rectangle{(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0), (1.0, 1.0)}
rectangle{(-2.0, 2.0), (-2.0, -1.0), (1.0, -1.0), (1.0, 2.0)}
rectangle [(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0), (1.0, 1.0)]

Simple file system: attributed tree


In [21]:
text = u'''
folder {
  name: "/"
  folder {
    name: "Library"
    file {name: "book.pdf"}
    file {name: "README"}
    folder {
      name: "Temp"
    }
  }
  folder {
    name: "Desktop"
    file {name: "Notes.txt"}
    file {name: "Recipes.txt"}
  }
}
'''
vs = axon.loads(text)
pprint(vs)
axon.display_html(vs)


[folder{name: '/' folder{name: 'Library' file{name: 'book.pdf'}, file{name: 'README'}, folder{name: 'Temp'}}, folder{name: 'Desktop' file{name: 'Notes.txt'}, file{name: 'Recipes.txt'}}}]

In [22]:
val = vs[0]
print(val.__tag__)
print(val[0].__tag__, val[1].__tag__)
print(val[0][0].__tag__, val[1][0].__tag__)
print(val[1].__tag__, val[1].__attrs__, val[1].__vals__)


folder
folder folder
file file
folder OrderedDict([('name', 'Desktop')]) [file{name: 'Notes.txt'}, file{name: 'Recipes.txt'}]

Network of connected units


In [23]:
text = u'''
network {
    nodes {
        &x1 node {label:"x1"}
        &x2 node {label:"x2"}
        &x3 node {label:"x3"}
        &u1 node {label:"u1"}
        &u2 node {label:"u2"}
        &y node {label:"y"}
    }
    units {
        unit {out:(*u1) inp:(*x1 *x2 *x3) weights:(1.0 0.5 0.5)}
        unit {out:(*u2) inp:(*x1 *x2) weights:(1.0 1.5)}
        unit {out:(*y) inp:(*u1 *u2) weights:(0.5 -1.0)}
    }
}
'''
vs = axon.loads(text)
pprint(vs)
axon.display_html(vs)


[network{nodes{node{label: 'x1'}, node{label: 'x2'}, node{label: 'x3'}, node{label: 'u1'}, node{label: 'u2'}, node{label: 'y'}}, units{unit{out: (node{label: 'u1'},), inp: (node{label: 'x1'}, node{label: 'x2'}, node{label: 'x3'}), weights: (1.0, 0.5, 0.5)}, unit{out: (node{label: 'u2'},), inp: (node{label: 'x1'}, node{label: 'x2'}), weights: (1.0, 1.5)}, unit{out: (node{label: 'y'},), inp: (node{label: 'u1'}, node{label: 'u2'}), weights: (0.5, -1.0)}}}]

In [24]:
val = vs[0]
print('Same objects here:')
print(val[0][0] is val[1][0].inp[0])
print(val[0][-1] is val[1][-1].out[0])


Same objects here:
True
True

XML-style representation with collections of elements with same name


In [25]:
text = u'''
network {
    nodes {
        &x1 node {label:"x1"}
        &x2 node {label:"x2"}
        &x3 node {label:"x3"}
        &u1 node {label:"u1"}
        &u2 node {label:"u2"}
        &y  node {label:"y"}
    }
    units {
        unit {out:(*u1) inp:(*x1 *x2 *x3) weights:(1.0 0.5 0.5)}
        unit {out:(*u2) inp:(*x1 *x2) weights:(1.0 1.5)}
        unit {out:(*y) inp:(*u1 *u2) weights:(0.5 -1.0)}
    }
}
'''
vs = axon.loads(text)
pprint(vs)
axon.display_html(vs)


[network{nodes{node{label: 'x1'}, node{label: 'x2'}, node{label: 'x3'}, node{label: 'u1'}, node{label: 'u2'}, node{label: 'y'}}, units{unit{out: (node{label: 'u1'},), inp: (node{label: 'x1'}, node{label: 'x2'}, node{label: 'x3'}), weights: (1.0, 0.5, 0.5)}, unit{out: (node{label: 'u2'},), inp: (node{label: 'x1'}, node{label: 'x2'}), weights: (1.0, 1.5)}, unit{out: (node{label: 'y'},), inp: (node{label: 'u1'}, node{label: 'u2'}), weights: (0.5, -1.0)}}}]

In [26]:
val = vs[0]
print(val[0][0] is val[1][0].inp[0])
print(val[0][-1] is val[1][-1].out[0])


True
True

Mapping named complex values to types


In [27]:
import numpy as np

@axon.factory('ndarray')
def create_array(mapping, sequence):
    shape = mapping.get('shape', None)
    dtype = mapping['dtype']
    if type(dtype) is list:
        dtype = [(str(n), str(t)) for n, t in dtype]
    a = np.array(sequence, dtype=dtype)
    if shape is not None:
        a.shape = shape
    return a

@axon.reduce(np.ndarray)
def reduce_array(a):
    signes = {'<', '=', '>', '!'}
    if len(a.dtype.descr) > 1:
        dtype = [
            (axon.as_unicode(n), (axon.as_unicode(t[1:]) \
                             if t[0] in signes \
                             else axon.as_unicode(t)))
            for n, t in a.dtype.descr]
        return axon.Node('ndarray', {'dtype':dtype}, a.tolist())
    else:
        dtype_str = a.dtype.str
        dtype_str = axon.as_unicode(dtype_str[1:]) \
                if dtype_str[0] in signes \
                else axon.as_unicode(dtype_str)
        return axon.Node('ndarray', {'shape': a.shape, 'dtype':dtype_str}, a.tolist())

axon.dump_as_str(np.int8)
axon.dump_as_str(np.int16)
axon.dump_as_str(np.int32)
axon.dump_as_str(np.int64)
axon.dump_as_str(np.float16)
axon.dump_as_str(np.float32)
axon.dump_as_str(np.float64)
axon.dump_as_str(np.float128)
axon.dump_as_str(np.int_)
axon.dump_as_str(np.float_)
axon.dump_as_str(np.double)

In [28]:
a = np.array([[1, 2], [3, 4], [5, 6]])
axon.display_html([a])

In [29]:
b = axon.loads(axon.dumps([a]), mode='strict')[0]
print(b == a)
print(a.dtype == b.dtype)


[[ True  True]
 [ True  True]
 [ True  True]]
True

In [30]:
a = np.array(
        [(1, 2, 3.0), (3, 4, 5.0), (4, 5, 6.0)], 
        dtype=[('x', int), ('y', int), ('z', float)])
axon.display_html([a])

In [31]:
b = axon.loads(axon.dumps([a]), mode='strict')[0]
print(b == a)
print(a.dtype == b.dtype)


[ True  True  True]
True

Documents

HTML document as data


In [32]:
html_as_data = '''
html {
  head {
    meta: {charset: "utf-8"}
    title: "Sample html page"
  }
  body {

  form {
    name:"test" method:"post" action:"result.html"
    p {
      b { "Your name:" } br{}
      input { type:"text" size:"40" }
    }
    p { 
      b { "What is your browser:" } 
      input { type:"radio" name:"browser" value:"ie" } "Internet Explorer" br{}
      input { type:"radio" name:"browser" value:"opera" } "Opera" br{}
      input { type:"radio" name:"browser" value:"firefox" } "Firefox" br{}
    }
    p {
      input { type:"submit" value:"Send" }
    }
  }
  }
}
'''
vs = axon.loads(html_as_data)[0]
pprint(vs)
axon.display_html(vs)


html{head{meta: {'charset': 'utf-8'}, title: 'Sample html page'}, body{form{name: 'test', method: 'post', action: 'result.html' p{b{'Your name:'}, br{}, input{type: 'text', size: '40'}}, p{b{'What is your browser:'}, input{type: 'radio', name: 'browser', value: 'ie'}, 'Internet Explorer', br{}, input{type: 'radio', name: 'browser', value: 'opera'}, 'Opera', br{}, input{type: 'radio', name: 'browser', value: 'firefox'}, 'Firefox', br{}}, p{input{type: 'submit', value: 'Send'}}}}}

SVG example


In [33]:
text = '''
svg
  xmlns:"http://www.w3.org/2000/svg" 
  viewBox:(0 0 300 150)
  defs
    radialGradient
        id: "gradient"
        cx: "50%" cy: "50%"
        stop
          offset:"0%" 
          style
            stop_color: rgb{200 200 200} 
            stop_opacity:0
        stop
          offset:"100%"
          style
            stop_color: rgb{0 0 255}
            stop_opacity:1
  ellipse
    cx:100 cy:50 rx:100 ry:50
    style
        fill: url{"#gradient"}
  path
    d: "M150 0 L75 200 L225 200 Z"
  g
    transform: [
        translate{90 30}
        rotate{-30 10}
        scale{0.9}]
  text
    x:0 y:30 font_size:"18px" font_weight:"bold"
    text_anchor:"middle"
    "Button"
'''
vs = axon.loads(text)
pprint(vs)
axon.display_html(vs)


[svg{xmlns: 'http://www.w3.org/2000/svg', viewBox: (0, 0, 300, 150) defs{radialGradient{id: 'gradient', cx: '50%', cy: '50%' stop{offset: '0%' style{stop_color: rgb{200, 200, 200}, stop_opacity: 0}}, stop{offset: '100%' style{stop_color: rgb{0, 0, 255}, stop_opacity: 1}}}}, ellipse{cx: 100, cy: 50, rx: 100, ry: 50 style{fill: url{'#gradient'}}}, path{d: 'M150 0 L75 200 L225 200 Z'}, g{transform: [translate{90, 30}, rotate{-30, 10}, scale{0.9}]}, text{x: 0, y: 30, font_size: '18px', font_weight: 'bold', text_anchor: 'middle' 'Button'}}]

Element tree


In [34]:
from xml.etree import ElementTree, cElementTree

Let's define function for dumping ElementTree structures according to AXON rules.


In [35]:
@axon.reduce(cElementTree.Element)
@axon.reduce(ElementTree.Element)
def element_reduce(elem):
    children = elem.getchildren()
    if elem.attrib:
        if children:
            return axon.Node(elem.tag, elem.attrib, children)
        else:
            return axon.Node(elem.tag, elem.attrib)
    elif children:
            return axon.Node(elem.tag, None, children)
    else:
        return axon.Node(elem.tag)
        
@axon.reduce(cElementTree.ElementTree)
@axon.reduce(ElementTree.ElementTree)
def etree_reduce(element):
    return element_reduce(element.getroot())

In [36]:
root = ElementTree.Element('persons')
ElementTree.SubElement(root, 'person', {'name':'Alice', 'age':"25"})
ElementTree.SubElement(root,'person', {'name':'Bob', 'age':"33"})
etree = ElementTree.ElementTree(root)

ElementTree.dump(etree)
axon.display_html([etree])


<persons><person age="25" name="Alice" /><person age="33" name="Bob" /></persons>

In [37]:
def update_attribs(d):
    for key, val in d.items():
        d[key] = str(val)

class ElementTreeBuilder(axon.Builder):
    def node(self, name, attrs, vals):
        if attrs:
            attrs = dict(attrs)
            update_attribs(attrs)
        else:
            attrs = {}
        e = cElementTree.Element(name, attrs)
        if vals:
            e.extend(vals)
        return e

axon.register_builder('etree', ElementTreeBuilder())

In [38]:
text = axon.dumps([etree])
vals = axon.loads(text, mode='etree')
ElementTree.dump(vals[0])


<persons><person age="25" name="Alice" /><person age="33" name="Bob" /></persons>

In [ ]: