Esempio n. 1
0
def get_func_resource(model_name, model, var_symbol):
    """Get resource associated with this function"""
    parser = reqparse.RequestParser()
    func = model[var_symbol]
    defaults = get_defaults(func)

    for arg in getfullargspec(func).args:
        if arg in defaults:
            parser.add_argument(arg, type=str)
        else:
            parser.add_argument(arg, type=str, required=True)

    class FuncResource(Resource):
        """Resource associated with this function"""

        def get(self):
            """get method for this resource"""
            args_ = parser.parse_args(strict=True)
            args = dict()

            for argname, val_ in args_.items():
                args[argname] = pd.read_json(StringIO(val_), typ='series')

            return func(**args).tolist()
    return FuncResource
Esempio n. 2
0
def get_func_plot_resource(model, var_symbol):
    """Get resource associated with this function's plot"""

    parser = reqparse.RequestParser()
    func = model[var_symbol]
    defaults = get_defaults(func)

    for arg in getfullargspec(func).args:
        if arg in defaults:
            parser.add_argument(arg, type=str)
        else:
            parser.add_argument(arg, type=str, required=True)

    class FuncPlotResource(Resource):
        """Resource associated with evaluate"""
        def get(self):
            """get method for this resource"""
            app.logger.info('function plot resource called')
            args_ = parser.parse_args(strict=True)
            args = dict(indexing='ij')  # needed for gridded data

            for argname, val_ in args_.items():
                if val_ is not None:
                    args[argname] = pd.read_json(StringIO(val_), typ='series')
            figure = model.figure(variable=str(type(var_symbol)), **args)
            return go.Figure(figure).to_json()

    return FuncPlotResource
Esempio n. 3
0
    def kamodo_model_func(user_model_name, user_func=None):
        user_model = user_models[user_model_name]
        print(user_model_name, user_func)
        print(user_model)

        if request.method == 'POST':
            func_key = request.form['signature']
            if 'expression' in request.form:
                func_expr = request.form['expression']
                if func_key in user_model:
                    del user_model[func_key]
                user_model[func_key] = func_expr
            elif 'model' in request.form:
                global_model_name = request.form['model']
                global_model = global_models[global_model_name]
                if 'model_func' in request.form:
                    global_model_func_name = request.form['model_func']
                    global_model_func = global_model[global_model_func_name]
                    user_model[func_key] = global_model_func

        if user_func is not None:
            parser = reqparse.RequestParser()
            if request.method == 'GET':
                func = user_model[user_func]
                defaults = get_defaults(func)
                for arg in getfullargspec(func).args:
                    if arg in defaults:
                        parser.add_argument(arg, type=str)
                    else:
                        parser.add_argument(arg, type=str, required=True)

                args_ = parser.parse_args(strict=True)
                args = dict()

                for argname, val_ in args_.items():
                    args[argname] = json.loads(val_, object_hook=deserialize)
                    if isinstance(args[argname], str):
                        args[argname] = json.loads(val_,
                                                   object_hook=deserialize)
                    if isinstance(args[argname], list):
                        args[argname] = np.array(args[argname])
                print('{} {} passed {}'.format(
                    model_name, user_func, ' '.join([
                        '{}:{}'.format(arg, type(arg_value))
                        for arg, arg_value in args.items()
                    ])))
                try:
                    result = func(**args)
                    print('{} {} function returned {}'.format(
                        model_name, user_func, type(result)))
                    return serialize(result)
                except:
                    return json.dumps(None)
            if request.method == "DELETE":
                if user_func in user_model:
                    del user_model[user_func]

        return get_model_details(user_model)
Esempio n. 4
0
 def get(self):
     """get method for this resource"""
     app.logger.info('getting defaults for {}.{}'.format(
         model_name, var_symbol))
     func = model[var_symbol]
     function_defaults = get_defaults(func)
     try:
         function_defaults_ = json.dumps(function_defaults,
                                         default=serialize)
     except:
         print('problem with {}.{}'.format(model_name, var_symbol))
         raise
     return function_defaults_
Esempio n. 5
0
    def kamodo_model_func_defaults(user_model_name, user_func):
        user_model = user_models[user_model_name]
        user_func = user_model[user_func]
        function_defaults = get_defaults(user_func)

        for arg in getfullargspec(user_func).args:
            if arg in function_defaults:
                pass
            else:
                function_defaults[arg] = None
        try:
            function_defaults_ = json.dumps(function_defaults,
                                            default=serialize)
        except:
            print('problem with {}.{}'.format(model_name, user_func))
            raise
        return jsonify(function_defaults_)
Esempio n. 6
0
def get_func_resource(model_name, model, var_symbol):
    """Get resource associated with this function"""
    parser = reqparse.RequestParser()
    func = model[var_symbol]
    defaults = get_defaults(func)

    for arg in getfullargspec(func).args:
        if arg in defaults:
            parser.add_argument(arg, type=str)
        else:
            parser.add_argument(arg, type=str, required=True)

    class FuncResource(Resource):
        """Resource associated with this function"""
        def get(self):
            """get method for this resource"""
            args_ = parser.parse_args(strict=True)
            args = dict()

            for argname, val_ in args_.items():
                args[argname] = json.loads(val_, object_hook=deserialize)
                if isinstance(args[argname], str):
                    args[argname] = json.loads(val_, object_hook=deserialize)
                if isinstance(args[argname], list):
                    args[argname] = np.array(args[argname])
            print('{} {} passed {}'.format(
                model_name, var_symbol, ' '.join([
                    '{}:{}'.format(arg, type(arg_value))
                    for arg, arg_value in args.items()
                ])))
            result = func(**args)
            print('{} {} function returned {}'.format(model_name, var_symbol,
                                                      type(result)))
            return serialize(result)

            # try:
            #     return result.tolist()
            # except:
            #     return result

    return FuncResource
Esempio n. 7
0
    def kamodo_model_func_plot(user_model_name, user_func):
        user_model = user_models[user_model_name]
        func = user_model[user_func]
        defaults = get_defaults(func)

        parser = reqparse.RequestParser()

        for arg in getfullargspec(func).args:
            if arg in defaults:
                parser.add_argument(arg, type=str)
            else:
                parser.add_argument(arg, type=str, required=True)

        app.logger.info('function plot resource called')
        args_ = parser.parse_args(strict=True)
        args = dict(indexing='ij')  # needed for gridded data

        for argname, val_ in args_.items():
            if val_ is not None:
                args[argname] = pd.read_json(StringIO(val_), typ='series')
        figure = user_model.figure(variable=user_func, **args)
        return go.Figure(figure).to_json()
Esempio n. 8
0
def get_gui(cfg):

    # moved into assets
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
    external_scripts = [
        'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML'
    ]

    app = dash.Dash(
        __name__,
        external_stylesheets=external_stylesheets,
        external_scripts=external_scripts,
    )

    app.layout = html.Div(children=[
        html.H1(children='Kamodo'),
        html.Div(children='''
            Kamodo: A low-coding interface for models and data
        '''),
    ])

    tabs_children = []
    graphs = {}

    for model_name, model_conf in cfg.models.items():
        print(model_name)

        try:
            model = hydra.utils.instantiate(model_conf)
        except Exception as m:
            print('could not instantiate {}'.format(model_name))
            print(m)

        if len(model) == 0:
            continue

        model_params = {}
        if model_conf.plot is None:
            for var_symbol, func in model.items():
                if type(var_symbol) == UndefinedFunction:
                    model_params[str(var_symbol)] = get_defaults(func)
        else:
            for var_name, var_args in model_conf.plot.items():
                if var_args is None:
                    try:
                        model_params[var_name] = get_defaults(model[var_name])
                    except Exception as m:
                        print(model.detail)
                        print(m)
                        sys.exit()
                else:
                    model_params[var_name] = eval_config(var_args)

        tab_children = []

        tab_children.append(get_equation_divs(model, model_name, model_params))

        graph_id = "graph-{}".format(model_name)

        fig_subplots = make_kamodo_subplots(model, model_params.keys(),
                                            model_params)

        tab_children.append(
            dcc.Graph(id=graph_id,
                      figure=fig_subplots,
                      style=dict(height='1000px', width='1200px')))

        # dcc.Store(id = 'store-{}'.format(model_name))

        graphs[graph_id] = model, model_params, model_name

        tab = dcc.Tab(label=model_name, children=tab_children)

        tabs_children.append(tab)

    tabs = dcc.Tabs(children=tabs_children)
    app.layout.children.append(tabs)

    # generate_callbacks(app, graphs)

    for graph_id, (model, model_params, model_name) in graphs.items():
        generate_subplot_callback(app, graph_id, model, model_name,
                                  model_params)

    return app