コード例 #1
0
ファイル: test-editor-lib.py プロジェクト: agoose77/seamless
import os
import sys
import time

from seamless import context, cell, transformer, reactor, macro
from seamless.lib.gui.basic_editor import edit
from seamless.lib.gui.basic_display import display
ctx = context()

@macro({"formula": {"type": "str", "default": "return value*2"}})
def operator(ctx, formula ):
    from seamless import cell, transformer
    tparams = ctx.tparams = cell("object").set(
    {
      "value": {
        "pin": "input",
        "dtype": "int"
      },
      "output": {
        "pin": "output",
        "dtype": "int"
      }
    }
    )

    cont = ctx.cont = transformer(tparams)
    c_code = cont.code.cell()
    c_code.set(formula)
    ctx.export(cont)

op = ctx.op = operator()
コード例 #2
0
ファイル: version8.py プロジェクト: sjdv1982/seamless
        "array": {"pin": "input", "dtype": "array"},
        "title": {"pin": "input", "dtype": "str"},
    })
    ctx.registrar.python.connect("AspectLayout", ctx.display_numpy)
    ctx.array.connect(ctx.display_numpy.array)
    ctx.title.connect(ctx.display_numpy.title)

    ctx.display_numpy.code_update.set("update()")
    ctx.display_numpy.code_stop.set("destroy()")
    ctx.code = pythoncell()
    ctx.code.connect(ctx.display_numpy.code_start)
    ctx.code.fromfile("cell-display-numpy.py")
    first = False

ctx_bak = ctx
ctx.display_numpy = context()
ctx = ctx.display_numpy
load_display_numpy()
ctx = ctx_bak

ctx_bak = ctx
ctx.display_numpy2 = context()
ctx = ctx.display_numpy2
load_display_numpy()
ctx = ctx_bak

###


ctx.texture = cell("array")
ctx.texture.set_store("GLTex", 2)
コード例 #3
0
print("In the 3D window, press key 1-4 to change the states")
""" #even the kludge does not work... troubles when updating macro
#ctx.display_numpy = ctx.fromfile("../display-numpy/display_numpy.seamless")
#KLUDGE
ctx = ctx.fromfile("../display-numpy/display_numpy.seamless")
ctx.rc_display_numpy = ctx.display_numpy
ctx.display_numpy = context()
ctx.display_numpy.array = ctx.array
ctx.display_numpy.title = ctx.title
#/KLUDGE
seamless.core.context.set_active_context(ctx) #does not help
"""

ctx_bak = ctx
ctx.display_numpy = context()
ctx = ctx.display_numpy
###
ctx.array = cell("array")
ctx.title = cell("str").set("Numpy array")
ctx.aspect_layout = pythoncell().fromfile("AspectLayout.py")
ctx.registrar.python.register(ctx.aspect_layout)
ctx.display_numpy = reactor({
    "array": {
        "pin": "input",
        "dtype": "array"
    },
    "title": {
        "pin": "input",
        "dtype": "str"
    },
コード例 #4
0
import seamless
f = "test-tofromfile.seamless"
f2 = "test-tofromfile-reload.seamless"
ctx = seamless.context()
from seamless.core.macro import _macros
_macros.clear()
ctx = seamless.fromfile(f)

ctx.equilibrate()
c_output = ctx.cont.output.cell()
print(c_output.data)
ctx.cont.value.cell().set(10)
ctx.equilibrate()
print(c_output.data)
ctx.cont.code.cell().set("return value**2")
ctx.equilibrate()
print(c_output.data)

ctx.tofile(f2, backup=False)

ctx = seamless.fromfile(f2)
ctx.equilibrate()
c_output = ctx.cont.output.cell()
print(c_output.data)
ctx.cont.code.cell().set("return value*2")
ctx.equilibrate()
print(c_output.data)
ctx.cont.value.cell().set(4)
ctx.equilibrate()
print(c_output.data)
コード例 #5
0
ファイル: test-destroy.py プロジェクト: agoose77/seamless
#TODO: more complicated graph, run gc, etc.

from seamless import context
ctx = context()
silkmodel = """Type Foo {
  Integer x
  Integer y
}"""

ctx.registrar.silk.register(silkmodel)
ctx.destroy()

ctx2 = context()
ctx2.registrar.silk.register(silkmodel)
コード例 #6
0
ファイル: basic.py プロジェクト: xeTaiz/seamless
#!/usr/bin/env ipython
"""Basic example

Sets up a transformer that computes a result based on two inputs
The input and the transformation code is edited live in a GUI
"""

from seamless import context, cell, pythoncell, transformer
from seamless.lib import edit, display

ctx = context()

# Create 3 int cells: a=2, b=3, and result
ctx.a = cell("int").set(2)
ctx.b = cell("int").set(3)
ctx.result = cell("int")

# Set up a transformer that computes "result" as a function of "a" and "b"
t = ctx.transform = transformer({
    "a": {
        "pin": "input",
        "dtype": "int"
    },
    "b": {
        "pin": "input",
        "dtype": "int"
    },
    "result": {
        "pin": "output",
        "dtype": "int"
    }
コード例 #7
0
import seamless
from seamless import context, cell, transformer
from seamless.lib.filelink import link
ctx = context()
ctx.value = cell("int")
ctx.result = cell("int")
#ctx.result.resource.save_policy = 4 #always save value
ctx.result.resource.save_policy = 2  #always save hash
ctx.tf = transformer({
    "value": {
        "pin": "input",
        "dtype": "int"
    },
    "result": {
        "pin": "output",
        "dtype": "int"
    },
})
ctx.tf.code.cell().set("""print("evaluate!"); return value""")
ctx.value.connect(ctx.tf.value)
ctx.tf.result.connect(ctx.result)
ctx.value.set(42)
ctx.link_value = link(ctx.value, ".", "hashcache-value.txt")
ctx.link_result = link(ctx.result,
                       ".",
                       "hashcache-result.txt",
                       file_dominant=True)
ctx.equilibrate()
ctx.tofile("test-hashcache.seamless", backup=False)
ctx = seamless.fromfile("test-hashcache.seamless")
ctx.equilibrate()
コード例 #8
0
ファイル: test-atom.py プロジェクト: sjdv1982/seamless
from seamless import context, cell, transformer, reactor
from seamless.lib import edit, display, link
from seamless.lib.gui.gl import glprogram, glwindow

import numpy as np

ctx = context()
ctx.params = context()
ctx.links = context()
ctx.code = context()

#for now, gen_sphere must be a reactor, because it has multiple outputs
#TODO: make it a transformer in a future version of seamless
c = ctx.params.gen_sphere = cell(("cson", "seamless", "reactor_params"))
ctx.links.params_gen_sphere = link(c, ".", "params-gen-sphere.cson")
rc = ctx.gen_sphere = reactor(c)
c = ctx.code.gen_sphere = cell(("text", "code", "python"))
ctx.links.code_gen_sphere = link(c, ".", "cell-gen-sphere.py")
rc.code_start.cell().set("")
c.connect(rc.code_update)
rc.code_stop.cell().set("")

ctx.subdivisions = cell("int").set(3)
ctx.minimizations = cell("int").set(20)
ctx.coordinates = cell("array").set_store("GL")
ctx.normals = cell("array").set_store("GL")
ctx.edges = cell("array").set_store("GL")
ctx.triangle_indices = cell("array").set_store("GL")
ctx.triangle_normals = cell("array").set_store("GL")
ctx.triangle_coordinates = cell("array").set_store("GL")
コード例 #9
0
ファイル: fireworks.py プロジェクト: sjdv1982/seamless
from seamless import cell, pythoncell, context, reactor, transformer
from seamless.silk import Silk
import seamless.lib
from seamless.lib.gui.basic_editor import edit
from seamless.lib.gui.basic_display import display
from seamless.lib import link
from seamless.lib.gui.gl import glprogram

ctx = context()
file_dominant = False

# Vertexdata Silk model
ctx.silk_vertexdata = cell(("text", "code", "silk"))
ctx.link_silk_vertexdata = link(
    ctx.silk_vertexdata,
    ".", "vertexdata.silk",
    file_dominant=file_dominant
)
ctx.registrar.silk.register(ctx.silk_vertexdata)

# Shaders
ctx.vert_shader = cell(("text", "code", "vertexshader"))
ctx.frag_shader = cell(("text", "code", "fragmentshader"))
ctx.link_vert_shader = link(ctx.vert_shader, ".", "vert_shader.glsl",
    file_dominant=file_dominant)
ctx.link_frag_shader = link(ctx.frag_shader, ".", "frag_shader.glsl",
    file_dominant=file_dominant)

# Program template
ctx.program_template = cell("cson")
ctx.link_program_template = link(ctx.program_template,
コード例 #10
0
ファイル: plotly.py プロジェクト: xeTaiz/seamless
def plotly(ctx, *, dynamic_html, mode):
    from seamless import context, cell, transformer
    from seamless.lib.templateer import templateer
    from seamless.core.worker import \
      ExportedInputPin, ExportedOutputPin

    assert mode in ("nx", "nxy", "manual"), mode
    data_dtype = "json" if mode == "manual" else "text" #csv

    # Subcontexts
    ctx.values = context()
    ctx.templates = context()
    ctx.params = context()
    ctx.code = context()

    # Static HTML output
    ctx.values.html = cell(("text", "html"))
    ctx.html = ExportedOutputPin(ctx.values.html)

    # Templates
    ctx.templates.html_head_body = cell(("text", "html"))\
      .fromfile("template-html-head-body.jinja")
    ctx.templates.head = cell("text")\
      .fromfile("template-head.jinja")
    ctx.templates.body = cell("text")\
      .fromfile("template-body.jinja")
    ctx.templates.body_dynamic = cell("text")\
      .fromfile("template-body-dynamic.jinja")

    # Values: here is where all authoritative state goes
    ctx.values.title = cell("str").set("Seamless Plotly")
    ctx.values.data = cell(data_dtype)
    ctx.values.attrib = cell("json")
    ctx.values.layout = cell("json")
    ctx.values.config = cell("json").set({})
    ctx.values.width = cell("int").set(500)
    ctx.values.height = cell("int").set(500)
    ctx.values.divname = cell("str").set("plotlydiv")

    # Input pins
    ctx.title = ExportedInputPin(ctx.values.title)
    ctx.data = ExportedInputPin(ctx.values.data)
    ctx.attrib = ExportedInputPin(ctx.values.attrib)
    ctx.layout = ExportedInputPin(ctx.values.layout)
    ctx.config = ExportedInputPin(ctx.values.config)

    # Static HTML: templateer_static
    params_static =  {"environment": {"title": "str",
                               "divname": "str",
                               "width": "int",
                               "height": "int",
                               "plotly_data": "json",
                               "layout": "json",
                               "config": "json",
                              },
                "templates": ["body", "head", "head_body"],
                "result": "head_body"}
    ctx.params.templateer_static = cell("json").set(params_static)
    ctx.templateer_static = templateer(ctx.params.templateer_static)
    ctx.values.height.connect(ctx.templateer_static.height)
    ctx.values.width.connect(ctx.templateer_static.width)
    ctx.values.divname.connect(ctx.templateer_static.divname)
    ctx.values.config.connect(ctx.templateer_static.config)
    ctx.values.layout.connect(ctx.templateer_static.layout)
    ctx.values.title.connect(ctx.templateer_static.title)
    ctx.templates.body.connect(ctx.templateer_static.body)
    ctx.templates.head.connect(ctx.templateer_static.head)
    ctx.templates.html_head_body.connect(ctx.templateer_static.head_body)
    ctx.templateer_static.RESULT.connect(ctx.values.html)

    #plotly_data temporary
    ctx.temp_plotly_data = cell("json")
    ctx.temp_plotly_data.connect(ctx.templateer_static.plotly_data)

    # Data integrator
    ctx.integrate_data = transformer({
        "data": {"pin": "input", "dtype": "json"},
        "attrib": {"pin": "input", "dtype": "json"},
        "plotly_data": {"pin": "output", "dtype": "json"},
    })
    ctx.code.integrate_data = cell(("text", "code","python"))\
      .fromfile("cell-integrate-data.py")
    ctx.code.integrate_data.connect(ctx.integrate_data.code)
    ctx.values.attrib.connect(ctx.integrate_data.attrib)
    ctx.integrate_data.plotly_data.connect(ctx.temp_plotly_data)


    if mode != "manual":
        #loaded_data temporary
        ctx.temp_loaded_data = cell("json")
        ctx.temp_loaded_data.connect(ctx.integrate_data.data)

        # Pandas data loader
        ctx.load_data = transformer({
            "csv": {"pin": "input", "dtype": "text"},
            "data": {"pin": "output", "dtype": "json"},
        })
        c = ctx.code.load_data = cell(("text", "code","python"))
        if mode == "nxy":
            c.fromfile("cell-load-data-nxy.py")
        elif mode == "nx":
            c.fromfile("cell-load-data-nx.py")
        ctx.code.load_data.connect(ctx.load_data.code)
        ctx.values.data.connect(ctx.load_data.csv)
        ctx.load_data.data.connect(ctx.temp_loaded_data)
    else:
        ctx.values.data.connect(ctx.integrate_data.data)

    if not dynamic_html:
        return

    from seamless.lib.dynamic_html import dynamic_html

    # Dynamic HTML output
    ctx.values.dynamic_html = cell(("text", "html"))
    ctx.dynamic_html = ExportedOutputPin(ctx.values.dynamic_html)

    # Dynamic HTML: templateer_dynamic
    ctx.params.templateer_dynamic = cell("json")
    params =  {"environment": {"title": "text",
                           "divname": "text",
                           "width": "int",
                           "height": "int",
                           "dynamic_html": ("text","html")
                          },
            "templates": ["body", "head", "head_body"],
            "result": "head_body"}
    ctx.params.templateer_dynamic.set(params)
    ctx.templateer_dynamic = templateer(ctx.params.templateer_dynamic)

    ctx.values.height.connect(ctx.templateer_dynamic.height)
    ctx.values.width.connect(ctx.templateer_dynamic.width)
    ctx.values.divname.connect(ctx.templateer_dynamic.divname)
    ctx.values.title.connect(ctx.templateer_dynamic.title)
    ctx.templates.body_dynamic.connect(ctx.templateer_dynamic.body)
    ctx.templates.head.connect(ctx.templateer_dynamic.head)
    ctx.templates.html_head_body.connect(ctx.templateer_dynamic.head_body)
    ctx.templateer_dynamic.RESULT.connect(ctx.values.dynamic_html)

    # Dynamic HTML maker
    # TODO: more efficient plot regeneration
    ctx.params.dynamic_html_maker = cell("json")
    dynamic_html_params = {
        "divname": {"type": "var", "dtype": "str"},
        "plotly_data": {"type": "var", "dtype": "json", "evals":["make_plot"]},
        #"data": {"type": "var", "dtype": "json", "evals":["update_data"]},
        #"attrib": {"type": "var", "dtype": "json", "evals":["update_attrib"]},
        #"layout": {"type": "var", "dtype": "json", "evals":["update_layout"]},
        "data": {"type": "var", "dtype": "json"},
        "attrib": {"type": "var", "dtype": "json", "evals":["make_plot"]},
        "layout": {"type": "var", "dtype": "json", "evals":["make_plot"]},

        "config": {"type": "var", "dtype": "json", "evals":["make_plot"]},
        "update_data": {"type": "eval", "on_start": False},
        "update_attrib": {"type": "eval", "on_start": False},
        "update_layout": {"type": "eval", "on_start": False},
        "make_plot": {"type": "eval", "on_start": True},
    }
    ctx.params.dynamic_html_maker.set(dynamic_html_params)
    ctx.dynamic_html_maker = dynamic_html(ctx.params.dynamic_html_maker)
    ctx.dynamic_html_maker.dynamic_html.cell().connect(
        ctx.templateer_dynamic.dynamic_html
    )

    ctx.temp_plotly_data.connect(ctx.dynamic_html_maker.plotly_data)
    if mode == "manual":
        ctx.values.data.connect(ctx.dynamic_html_maker.data)
    else:
        ctx.temp_loaded_data.connect(ctx.dynamic_html_maker.data)
    ctx.values.attrib.connect(ctx.dynamic_html_maker.attrib)
    ctx.values.config.connect(ctx.dynamic_html_maker.config)
    ctx.values.layout.connect(ctx.dynamic_html_maker.layout)

    ctx.dynamic_html_maker.make_plot.cell().set("""
Plotly.newPlot(divname, plotly_data, layout, config);
    """)

    ctx.dynamic_html_maker.update_data.cell().set("""
var i, ii, subdata, update, attribname;
for (i = 0; i < plotly_data.length; i++) {
    subdata = data[i];
    update = {};
    for (var attribname in subdata) {
        update[attribname] = [subdata[attribname]];
    }
    /*if (i==0) {
        x = document.getElementById("echo");
        x.innerHTML = "<pre>" + JSON.stringify(update) + "</pre>";
    }*/
    Plotly.restyle(divname, update, [i]);
}
    """)
    ctx.dynamic_html_maker.update_attrib.cell().set("""
var i;
for (i = 0; i < plotly_data.length; i++) {
    Plotly.restyle(divname, attrib[i], [i]);
}
    """)
    ctx.dynamic_html_maker.update_layout.cell().set("""
Plotly.relayout(divname, layout);
    """)

    ctx.values.divname.connect(ctx.dynamic_html_maker.divname)
コード例 #11
0
ファイル: test-sphere.py プロジェクト: sjdv1982/seamless
from seamless import context, cell, transformer, reactor
from seamless.lib import edit, display, link
from seamless.lib.gui.gl import glprogram, glwindow

import numpy as np
from scipy.spatial.distance import cdist

ctx = context()
ctx.params = context()
ctx.links = context()
ctx.code = context()

file_dominant = True

#for now, gen_sphere must be a reactor, because it has multiple outputs
#TODO: make it a transformer in a future version of seamless
c = ctx.params.gen_sphere = cell(("cson", "seamless", "reactor_params"))
ctx.links.params_gen_sphere = link(c, ".", "params-gen-sphere.cson", file_dominant=file_dominant)
rc = ctx.gen_sphere = reactor(c)
c = ctx.code.gen_sphere = cell(("text", "code", "python"))
ctx.links.code_gen_sphere = link(c, ".", "cell-gen-sphere.py", file_dominant=file_dominant)
rc.code_start.cell().set("")
c.connect(rc.code_update)
rc.code_stop.cell().set("")

do_scale_params = {
    "input":{"pin": "input", "dtype": "array"},
    "scale":{"pin": "input", "dtype": "float"},
    "output":{"pin": "output", "dtype": "array"}
}
ctx.subdivisions = cell("int").set(3)
コード例 #12
0
ファイル: basic.py プロジェクト: sjdv1982/seamless
#!/usr/bin/env ipython

"""Basic example

Sets up a transformer that computes a result based on two inputs
The input and the transformation code is edited live in a GUI
"""

from seamless import context, cell, pythoncell, transformer
from seamless.lib import edit, display

ctx = context()

# Create 3 int cells: a=2, b=3, and result
ctx.a = cell("int").set(2)
ctx.b = cell("int").set(3)
ctx.result = cell("int")

# Set up a transformer that computes "result" as a function of "a" and "b"
t = ctx.transform = transformer({
    "a": {"pin": "input", "dtype": "int"},
    "b": {"pin": "input", "dtype": "int"},
    "result": {"pin": "output", "dtype": "int"}
})

# Connect the cells to the transformer pins
ctx.a.connect(t.a)
ctx.b.connect(t.b)
t.result.connect(ctx.result)

# Every transformer has an implicit extra input pin, called "code"
コード例 #13
0
ファイル: slash0.py プロジェクト: sjdv1982/seamless
def slash0(ctx, code, extern_map={}, **macro_args):
    import os, seamless, hashlib
    from seamless import context, cell, pythoncell, reactor, transformer
    from seamless.core.cell import Cell
    from seamless.core.worker import ExportedInputPin, ExportedOutputPin
    from seamless.lib.filehash import filehash
    from seamless.slash.parse_slash0 import parse_slash0
    from seamless.slash.ast_slash0_validate import ast_slash0_validate
    from seamless.slash.slash0_standard_command import make_cmd_params
    ctx.cell_cmd_std = seamless.pythoncell().fromfile(
        "cell-command-standard.py")
    ast = parse_slash0(code)
    symbols = ast_slash0_validate(ast)
    env = {}
    variables = {}
    docs = {}
    contexts = {}
    filehashes = 0

    def make_cmd_std(cmd_params):
        nonlocal filehashes
        tf_params = {
            "PARAMS": {
                "pin": "input",
                "dtype": "json",
            },
        }
        in_connections = []
        out_connections = []
        for file_ in cmd_params["files"]:
            fh = filehash(file_)
            filehashes += 1
            fhname = "filehash_%d" % filehashes
            tf_params[fhname] = {"pin": "input", "dtype": "str"}
            fhname = "filehash_%d" % filehashes
            setattr(ctx, fhname, fh)
            in_connections.append((fh.filehash.cell(), fhname))
        for inp, typ in cmd_params["inputs"].items():
            if typ == "doc":
                dtype = "text"
                prefix = "doc_"
            elif typ == "variable":
                dtype = "str"
                prefix = "var_"
            else:
                raise TypeError((cmd_params["lineno"], cmd_params["source"],
                                 inp, typ))  #must be a bug
            tf_params[inp] = {
                "pin": "input",
                "dtype": dtype,
            }
            in_connections.append((ctx.CHILDREN[prefix + inp], inp))

        if len(cmd_params["outputs"]) > 1:
            raise NotImplementedError("Multiple outputs not yet implemented")

        for output in cmd_params["outputs"]:
            if hasattr(ctx, "ctx_" + output):
                dtype = "json"
                prefix = "ctx_"
            else:
                dtype = "text"
                prefix = "doc_"
            tf_params[output] = {
                "pin": "output",
                "dtype": dtype,
            }  #TODO: in case of multiple outputs => single JSON cell + subcells (to be implemented)
            out_connections.append((output, ctx.CHILDREN[prefix + output]))

        tf = transformer(tf_params)
        tf.PARAMS.cell().set(cmd_params)
        for con in in_connections:
            pin = getattr(tf, con[1])
            con[0].connect(pin)
        for con in out_connections:
            pin = getattr(tf, con[0])
            pin.connect(con[1])
        ctx.cell_cmd_std.connect(tf.code)
        return tf

    for node in ast["nodes"]["env"]:
        envname = node["name"]
        assert envname in os.environ, envname
        env[envname] = os.environ[envname]
    for node in ast["nodes"]["file"]:
        filename = node["name"]
        assert os.path.exists(filename), filename
    for node in ast["nodes"]["context"]:
        name = "ctx_" + node["name"]
        if node["is_json"]:
            c = cell("json")
            c.resource.save_policy = 2
        else:
            c = context()
        contexts[node["name"]] = c
        setattr(ctx, name, c)
    for node in ast["nodes"]["variable"]:
        name = "var_" + node["name"]
        c = cell("str")
        c.resource.save_policy = 2
        variables[node["name"]] = c
        setattr(ctx, name, c)
        origin = node["origin"]
        if origin == "intern":
            pass  #nothing to do
        elif origin == "extern":
            raise NotImplementedError  #c.set(...) using extern_mapping + macro_args
        elif origin == "input":
            pin = ExportedInputPin(c)
            setattr(ctx, node["name"], pin)
        else:
            raise ValueError(origin)
    for node in ast["nodes"]["doc"]:
        name = "doc_" + node["name"]
        c = cell("text")
        c.resource.save_policy = 2
        docs[node["name"]] = c
        setattr(ctx, name, c)
        origin = node["origin"]
        if origin == "intern":
            pass  #nothing to do
        elif origin == "extern":
            raise NotImplementedError  #c.set(...) using extern_mapping + macro_args
        elif origin == "input":
            pin = ExportedInputPin(c)
            setattr(ctx, node["name"], pin)
        else:
            raise ValueError(origin)

    nodes = ast["nodes"]
    for noderef in ast["exports"]:
        node_type = noderef["type"]
        node = nodes[node_type][noderef["index"]]
        name = node["name"]
        if node_type == "context":
            c = contexts[name]
            assert isinstance(c, Cell)  #TODO: export static subcontexts
        elif node_type == "variable":
            c = variables[name]
        elif node_type == "doc":
            c = docs[name]
        pin = ExportedOutputPin(c)
        setattr(ctx, name, pin)
    for command in ast["commands"]:
        source = command["cmd"]["source"]
        sourcehash = hashlib.md5(source.encode("utf-8")).hexdigest()
        cmd_type = command["cmd"]["command"]
        if cmd_type == "standard":
            cmd_params = make_cmd_params(command, nodes, env, sourcehash)
            command_worker = make_cmd_std(cmd_params)
            name = "cmd-" + sourcehash
            setattr(ctx, name, command_worker)
            setattr(ctx, name + "-PARAMS", command_worker.PARAMS.cell())
        else:
            raise NotImplementedError(cmd_type)
コード例 #14
0
from seamless import cell, pythoncell, context, reactor, transformer
from seamless.silk import Silk
import seamless.lib
from seamless.lib.gui.basic_editor import edit
from seamless.lib.gui.basic_display import display
from seamless.lib import link
from seamless.lib.gui.gl import glprogram

ctx = context()
file_dominant = False

# Vertexdata Silk model
ctx.silk_vertexdata = cell(("text", "code", "silk"))
ctx.link_silk_vertexdata = link(ctx.silk_vertexdata,
                                ".",
                                "vertexdata.silk",
                                file_dominant=file_dominant)
ctx.registrar.silk.register(ctx.silk_vertexdata)

# Shaders
ctx.vert_shader = cell(("text", "code", "vertexshader"))
ctx.frag_shader = cell(("text", "code", "fragmentshader"))
ctx.link_vert_shader = link(ctx.vert_shader,
                            ".",
                            "vert_shader.glsl",
                            file_dominant=file_dominant)
ctx.link_frag_shader = link(ctx.frag_shader,
                            ".",
                            "frag_shader.glsl",
                            file_dominant=file_dominant)
コード例 #15
0
ファイル: slash0.py プロジェクト: agoose77/seamless
def slash0(ctx, code, extern_map = {}, **macro_args):
    import os, seamless, hashlib
    from seamless import context, cell, pythoncell, reactor, transformer
    from seamless.core.cell import Cell
    from seamless.core.worker import ExportedInputPin, ExportedOutputPin
    from seamless.lib.filehash import filehash
    from seamless.slash.parse_slash0 import parse_slash0
    from seamless.slash.ast_slash0_validate import ast_slash0_validate
    from seamless.slash.slash0_standard_command import make_cmd_params
    ctx.cell_cmd_std = seamless.pythoncell().fromfile("cell-command-standard.py")
    ast = parse_slash0(code)
    symbols = ast_slash0_validate(ast)
    env = {}
    variables = {}
    docs = {}
    contexts = {}
    filehashes = 0

    def make_cmd_std(cmd_params):
        nonlocal filehashes
        tf_params = {
            "PARAMS": {
                "pin": "input",
                "dtype": "json",
            },
        }
        in_connections = []
        out_connections = []
        for file_ in cmd_params["files"]:
            fh = filehash(file_)
            filehashes += 1
            fhname = "filehash_%d" % filehashes
            tf_params[fhname] = {
                "pin": "input",
                "dtype": "str"
            }
            fhname = "filehash_%d" % filehashes
            setattr(ctx, fhname, fh)
            in_connections.append((fh.filehash.cell(), fhname))
        for inp,typ in cmd_params["inputs"].items():
            if typ == "doc":
                dtype = "text"
                prefix = "doc_"
            elif typ == "variable":
                dtype = "str"
                prefix = "var_"
            else:
                raise TypeError((cmd_params["lineno"], cmd_params["source"], inp, typ)) #must be a bug
            tf_params[inp] = {
                "pin": "input",
                "dtype": dtype,
            }
            in_connections.append((ctx.CHILDREN[prefix + inp], inp))

        if len(cmd_params["outputs"]) > 1:
            raise NotImplementedError("Multiple outputs not yet implemented")

        for output in cmd_params["outputs"]:
            if hasattr(ctx, "ctx_" + output):
                dtype = "json"
                prefix = "ctx_"
            else:
                dtype = "text"
                prefix = "doc_"
            tf_params[output] = {
                "pin": "output",
                "dtype": dtype,
            } #TODO: in case of multiple outputs => single JSON cell + subcells (to be implemented)
            out_connections.append((output, ctx.CHILDREN[prefix + output]))

        tf = transformer(tf_params)
        tf.PARAMS.cell().set(cmd_params)
        for con in in_connections:
            pin = getattr(tf, con[1])
            con[0].connect(pin)
        for con in out_connections:
            pin = getattr(tf, con[0])
            pin.connect(con[1])
        ctx.cell_cmd_std.connect(tf.code)
        return tf

    for node in ast["nodes"]["env"]:
        envname = node["name"]
        assert envname in os.environ, envname
        env[envname] = os.environ[envname]
    for node in ast["nodes"]["file"]:
        filename = node["name"]
        assert os.path.exists(filename), filename
    for node in ast["nodes"]["context"]:
        name = "ctx_" + node["name"]
        if node["is_json"]:
            c = cell("json")
            c.resource.save_policy = 2
        else:
            c = context()
        contexts[node["name"]] = c
        setattr(ctx, name, c)
    for node in ast["nodes"]["variable"]:
        name = "var_" + node["name"]
        c = cell("str")
        c.resource.save_policy = 2
        variables[node["name"]] = c
        setattr(ctx, name, c)
        origin = node["origin"]
        if origin == "intern":
            pass #nothing to do
        elif origin == "extern":
            raise NotImplementedError #c.set(...) using extern_mapping + macro_args
        elif origin == "input":
            pin = ExportedInputPin(c)
            setattr(ctx, node["name"], pin)
        else:
            raise ValueError(origin)
    for node in ast["nodes"]["doc"]:
        name = "doc_" + node["name"]
        c = cell("text")
        c.resource.save_policy = 2
        docs[node["name"]] = c
        setattr(ctx, name, c)
        origin = node["origin"]
        if origin == "intern":
            pass #nothing to do
        elif origin == "extern":
            raise NotImplementedError #c.set(...) using extern_mapping + macro_args
        elif origin == "input":
            pin = ExportedInputPin(c)
            setattr(ctx, node["name"], pin)
        else:
            raise ValueError(origin)

    nodes = ast["nodes"]
    for noderef in ast["exports"]:
        node_type = noderef["type"]
        node = nodes[node_type][noderef["index"]]
        name = node["name"]
        if node_type == "context":
            c = contexts[name]
            assert isinstance(c, Cell) #TODO: export static subcontexts
        elif node_type == "variable":
            c = variables[name]
        elif node_type == "doc":
            c = docs[name]
        pin = ExportedOutputPin(c)
        setattr(ctx, name, pin)
    for command in ast["commands"]:
        source = command["cmd"]["source"]
        sourcehash = hashlib.md5(source.encode("utf-8")).hexdigest()
        cmd_type = command["cmd"]["command"]
        if cmd_type == "standard":
            cmd_params = make_cmd_params(command, nodes, env, sourcehash)
            command_worker = make_cmd_std(cmd_params)
            name = "cmd-" + sourcehash
            setattr(ctx, name, command_worker)
            setattr(ctx, name +"-PARAMS", command_worker.PARAMS.cell())
        else:
            raise NotImplementedError(cmd_type)
コード例 #16
0
#TODO: more complicated graph, run gc, etc.

from seamless import context

ctx = context()
silkmodel = """Type Foo {
  Integer x
  Integer y
}"""

ctx.registrar.silk.register(silkmodel)
ctx.destroy()

ctx2 = context()
ctx2.registrar.silk.register(silkmodel)