Basic example

1. Import Seamless in IPython or Jupyter


In [1]:
from seamless.highlevel import Context
ctx = Context()

2. Set up a simple Seamless context


In [2]:
def add(a, b):
    return a + b

ctx.a = 10          # ctx.a => Seamless cell
ctx.b = 20          # ctx.b => Seamless cell
ctx.add = add       # ctx.add => Seamless transformer
ctx.add.a = ctx.a
ctx.add.b = ctx.b
ctx.c = ctx.add     # ctx.c => Seamless cell
await ctx.computation()
ctx.c.value


Seamless buffer cache cleanup is currently disabled.
This prevents data loss from bugs in Seamless's buffer caching.
If you have memory issues, restart Python periodically,
 and/or use Redis to store buffers
Out[2]:
<Silk: 30 >

In [3]:
ctx.a += 5 
await ctx.computation()
ctx.c.value


Out[3]:
<Silk: 35 >

3. Define schemas and validation rules


In [4]:
ctx.add.example.a = 0.0  # declares that add.a must be a number
ctx.add.example.b = 0.0  

def validate(self):
    assert self.a < self.b

ctx.add.add_validator(validate, name="validate")

await ctx.computation()
print(ctx.add.exception)
# Validation passes => exception is None


None

4. Create an API for a Seamless cell


In [5]:
def report(self): 
    value = self.unsilk 
    if value is None: 
        print("Sorry, there is no result") 
    else: 
        print("The result is: {}".format(value))

ctx.c.example.report = report
await ctx.computation()
ctx.c.value.report()


The result is: 35

5. Control cells from Jupyter


In [6]:
from ipywidgets import IntSlider, IntText

a = IntSlider(min=-10,max=30)
b = IntSlider(min=-10,max=30)
c = ctx.c.output()
ctx.a.traitlet().link(a)
ctx.b.traitlet().link(b)
display(a)
display(b)
display(c)


6. Mount cells to the file system


In [7]:
ctx.a.celltype = "plain"
ctx.a.mount("/tmp/a.txt")
ctx.b.celltype = "plain"
ctx.b.mount("/tmp/b.txt")
ctx.c.celltype = "plain"
ctx.c.mount("/tmp/c.txt", mode="w")
ctx.add.code.mount("/tmp/code.py")
await ctx.translation()

7. Share a cell over HTTP


In [8]:
ctx.c.mimetype = "text"
ctx.c.share()
await ctx.translation()

8. Save the entire state of the context


In [9]:
# Graph and checksums, as JSON
ctx.save_graph("basic-example.seamless")
# Checksum-to-buffer cache, as ZIP file
ctx.save_zip("basic-example.zip")

9. In a new notebook / IPython console:


In [11]:
from seamless.highlevel import load_graph
ctx = load_graph(
    "basic-example.seamless", 
    zip="basic-example.zip"
)
await ctx.computation()
ctx.c.value


Out[11]:
35