Esempio n. 1
0
HRESULT init_function_constr(script_ctx_t *ctx, jsdisp_t *object_prototype)
{
    FunctionInstance *prot, *constr;
    HRESULT hres;

    static const WCHAR FunctionW[] = {'F','u','n','c','t','i','o','n',0};

    hres = create_function(ctx, &Function_info, PROPF_CONSTR, TRUE, object_prototype, &prot);
    if(FAILED(hres))
        return hres;

    prot->value_proc = FunctionProt_value;
    prot->name = prototypeW;

    hres = create_function(ctx, &FunctionInst_info, PROPF_CONSTR|1, TRUE, &prot->dispex, &constr);
    if(SUCCEEDED(hres)) {
        constr->value_proc = FunctionConstr_value;
        constr->name = FunctionW;
        hres = set_prototype(ctx, &constr->dispex, &prot->dispex);
        if(SUCCEEDED(hres))
            hres = set_constructor_prop(ctx, &constr->dispex, &prot->dispex);
        if(FAILED(hres))
            jsdisp_release(&constr->dispex);
    }
    jsdisp_release(&prot->dispex);
    if(FAILED(hres))
        return hres;

    ctx->function_constr = &constr->dispex;
    return S_OK;
}
Esempio n. 2
0
HRESULT create_source_function(script_ctx_t *ctx, bytecode_t *code, function_code_t *func_code,
        scope_chain_t *scope_chain, jsdisp_t **ret)
{
    FunctionInstance *function;
    jsdisp_t *prototype;
    HRESULT hres;

    hres = create_object(ctx, NULL, &prototype);
    if(FAILED(hres))
        return hres;

    hres = create_function(ctx, NULL, PROPF_CONSTR, FALSE, NULL, &function);
    if(SUCCEEDED(hres)) {
        hres = set_prototype(ctx, &function->dispex, prototype);
        if(FAILED(hres))
            jsdisp_release(&function->dispex);
    }
    jsdisp_release(prototype);
    if(FAILED(hres))
        return hres;

    if(scope_chain) {
        scope_addref(scope_chain);
        function->scope_chain = scope_chain;
    }

    bytecode_addref(code);
    function->code = code;
    function->func_code = func_code;
    function->length = function->func_code->param_cnt;

    *ret = &function->dispex;
    return S_OK;
}
Esempio n. 3
0
void CompilerCore::register_function (VertexPtr root, DataStream &os) {
  if (root.is_null()) {
    return;
  }
  FunctionPtr function;
  if (root->type() == op_function || root->type() == op_func_decl) {
    function = create_function (root);
  } else if (root->type() == op_extern_func) {
    register_function_header (root, os);
    return;
  } else {
    kphp_fail();
  }
  FunctionSetPtr function_set = get_function_set (fs_function, function->name, true);

  bool force_flag = function->type() == FunctionData::func_global;
  if (add_to_function_set (
        function_set,
        function,
        force_flag)) {
    function->is_required = true;
    if (force_flag) {
      function->req_id = stage::get_file()->req_id;
    } else {
      function->req_id = function_set->req_id;
    }
    os << function;
  }
};
Esempio n. 4
0
HRESULT create_builtin_function(script_ctx_t *ctx, builtin_invoke_t value_proc, const WCHAR *name,
        const builtin_info_t *builtin_info, DWORD flags, DispatchEx *prototype, DispatchEx **ret)
{
    FunctionInstance *function;
    HRESULT hres;

    hres = create_function(ctx, builtin_info, flags, FALSE, NULL, &function);
    if(FAILED(hres))
        return hres;

    if(builtin_info) {
        VARIANT var;

        V_VT(&var) = VT_I4;
        V_I4(&var) = function->length;
        hres = jsdisp_propput_const(&function->dispex, lengthW, &var);
    }

    if(SUCCEEDED(hres))
        hres = set_prototype(ctx, &function->dispex, prototype);
    if(FAILED(hres)) {
        jsdisp_release(&function->dispex);
        return hres;
    }

    function->value_proc = value_proc;
    function->name = name;

    *ret = &function->dispex;
    return S_OK;
}
Esempio n. 5
0
int 
main (int argc, char **argv)
{
  pthread_attr_t attr;
  pthread_t threads[NUM_CREATE];
  int args[NUM_CREATE];
  int n, i;

  pthread_attr_init (&attr);
  pthread_attr_setstacksize (&attr, 2*PTHREAD_STACK_MIN);

  for (n = 0; n < 100; ++n)
    {
      for (i = 0; i < NUM_CREATE; i++)
	{
	  args[i] = i;
	  pthread_create (&threads[i], &attr, create_function, &args[i]);
	}

      create_function (&i);
      for (i = 0; i < NUM_CREATE; i++)
	pthread_join (threads[i], NULL);
    }

  pthread_attr_destroy (&attr);

  return 0;
}
Esempio n. 6
0
static void 
c_radial_shading(FM *p, double x0, double y0, double r0, double x1, double y1,
                 double r1, int hival, int lookup_len, unsigned char *lookup,
                 double a, double b, double c, double d, double e, double f,
                 bool extend_start, bool extend_end)
{
   Shading_Info *so = (Shading_Info *)calloc(1, sizeof(Shading_Info));
   so->next = shades_list;
   shades_list = so;
   so->shade_num = next_available_shade_number++;
   so->obj_num = next_available_object_number++;
   so->function = create_function(hival, lookup_len, lookup);
   so->axial = false;
   so->x0 = x0;
   so->y0 = y0;
   so->r0 = r0;
   so->x1 = x1;
   so->y1 = y1;
   so->r1 = r1;
   so->extend_start = extend_start;
   so->extend_end = extend_end;
   if (a != 1.0 || b != 0.0 || c != 0.0 || d != 1.0 || e != 0 || f != 0) {
      fprintf(TF, "q %0.2f %0.2f %0.2f %0.2f %0.2f %0.2f cm /Shade%i sh Q\n",
              a, b, c, d, e, f, so->shade_num);
   }
   else {
      fprintf(TF, "/Shade%i sh\n", so->shade_num);
   }
}
Esempio n. 7
0
HRESULT create_builtin_function(script_ctx_t *ctx, builtin_invoke_t value_proc, const WCHAR *name,
        const builtin_info_t *builtin_info, DWORD flags, jsdisp_t *prototype, jsdisp_t **ret)
{
    FunctionInstance *function;
    HRESULT hres;

    hres = create_function(ctx, builtin_info, flags, FALSE, NULL, &function);
    if(FAILED(hres))
        return hres;

    if(builtin_info)
        hres = jsdisp_propput_const(&function->dispex, lengthW, jsval_number(function->length));
    if(SUCCEEDED(hres))
        hres = set_prototype(ctx, &function->dispex, prototype);
    if(FAILED(hres)) {
        jsdisp_release(&function->dispex);
        return hres;
    }

    function->value_proc = value_proc;
    function->name = name;

    *ret = &function->dispex;
    return S_OK;
}
Esempio n. 8
0
/*create func by func head and analyze func body*/
void 
analyze_function_node(struct tree_node* specifier_node, struct tree_node* fundec_node, struct tree_node* compst_node){
	struct func_descriptor* new_func = create_function(specifier_node, fundec_node);
	
	if(new_func!= NULL){	//create success
		analyze_compst_node(new_func, compst_node);
	}
}
Esempio n. 9
0
HRESULT init_function_constr(script_ctx_t *ctx)
{
    FunctionInstance *prot, *constr;
    HRESULT hres;

    hres = create_function(ctx, PROPF_CONSTR, TRUE, NULL, &prot);
    if(FAILED(hres))
        return hres;

    prot->value_proc = FunctionProt_value;

    hres = create_function(ctx, PROPF_CONSTR, TRUE, &prot->dispex, &constr);
    jsdisp_release(&prot->dispex);
    if(FAILED(hres))
        return hres;

    constr->value_proc = FunctionConstr_value;
    ctx->function_constr = &constr->dispex;
    return hres;
}
Esempio n. 10
0
int
main (void)
{
  gsl_function F_cos, F_func1, F_func2, F_func3, F_func4;
  
  const gsl_min_fminimizer_type * fminimizer[4] ;
  const gsl_min_fminimizer_type ** T;

  gsl_ieee_env_setup ();

  fminimizer[0] = gsl_min_fminimizer_goldensection;
  fminimizer[1] = gsl_min_fminimizer_brent;
  fminimizer[2] = 0;

  F_cos = create_function (f_cos) ;
  F_func1 = create_function (func1) ;
  F_func2 = create_function (func2) ;
  F_func3 = create_function (func3) ;
  F_func4 = create_function (func4) ;

  gsl_set_error_handler (&my_error_handler);

  for (T = fminimizer ; *T != 0 ; T++)
    {
      test_f (*T, "cos(x) [0 (3) 6]", &F_cos, 0.0, 3.0, 6.0, M_PI);
      test_f (*T, "x^4 - 1 [-3 (-1) 17]", &F_func1, -3.0, -1.0, 17.0, 0.0);
      test_f (*T, "sqrt(|x|) [-2 (-1) 1.5]", &F_func2, -2.0, -1.0, 1.5, 0.0);
      test_f (*T, "func3(x) [-2 (3) 4]", &F_func3, -2.0, 3.0, 4.0, 1.0);
      test_f (*T, "func4(x) [0 (0.782) 1]", &F_func4, 0, 0.782, 1.0, 0.8);

      test_f_e (*T, "invalid range check [4, 0]", &F_cos, 4.0, 3.0, 0.0, M_PI);
      test_f_e (*T, "invalid range check [1, 1]", &F_cos, 1.0, 1.0, 1.0, M_PI);
      test_f_e (*T, "invalid range check [-1, 1]", &F_cos, -1.0, 0.0, 1.0, M_PI);
    }
  test_bracket("cos(x) [1,2]",&F_cos,1.0,2.0,15);
  test_bracket("sqrt(|x|) [-1,0]",&F_func2,-1.0,0.0,15);
  test_bracket("sqrt(|x|) [-1,-0.6]",&F_func2,-1.0,-0.6,15);
  test_bracket("sqrt(|x|) [-1,1]",&F_func2,-1.0,1.0,15);

  exit (gsl_test_summary ());
}
Esempio n. 11
0
HRESULT create_builtin_function(script_ctx_t *ctx, builtin_invoke_t value_proc, DWORD flags,
        DispatchEx *prototype, DispatchEx **ret)
{
    FunctionInstance *function;
    HRESULT hres;

    hres = create_function(ctx, flags, FALSE, prototype, &function);
    if(FAILED(hres))
        return hres;

    function->value_proc = value_proc;

    *ret = &function->dispex;
    return S_OK;
}
Esempio n. 12
0
HRESULT create_source_function(parser_ctx_t *ctx, parameter_t *parameters, source_elements_t *source,
        scope_chain_t *scope_chain, const WCHAR *src_str, DWORD src_len, DispatchEx **ret)
{
    FunctionInstance *function;
    DispatchEx *prototype;
    parameter_t *iter;
    DWORD length = 0;
    HRESULT hres;

    hres = create_object(ctx->script, NULL, &prototype);
    if(FAILED(hres))
        return hres;

    hres = create_function(ctx->script, NULL, PROPF_CONSTR, FALSE, NULL, &function);
    if(SUCCEEDED(hres)) {
        hres = set_prototype(ctx->script, &function->dispex, prototype);
        if(FAILED(hres))
            jsdisp_release(&function->dispex);
    }
    jsdisp_release(prototype);
    if(FAILED(hres))
        return hres;

    function->source = source;
    function->parameters = parameters;

    if(scope_chain) {
        scope_addref(scope_chain);
        function->scope_chain = scope_chain;
    }

    parser_addref(ctx);
    function->parser = ctx;

    for(iter = parameters; iter; iter = iter->next)
        length++;
    function->length = length;

    function->src_str = src_str;
    function->src_len = src_len;

    *ret = &function->dispex;
    return S_OK;
}
Esempio n. 13
0
static void
c_axial_shading(FM *p, double x0, double y0, double x1, double y1,
                int hival, int lookup_len, unsigned char *lookup,
                bool extend_start, bool extend_end)
{
   Shading_Info *so = (Shading_Info *)calloc(1, sizeof(Shading_Info));
   so->next = shades_list;
   shades_list = so;
   so->shade_num = next_available_shade_number++;
   so->obj_num = next_available_object_number++;
   so->function = create_function(hival, lookup_len, lookup);
   so->axial = true;
   so->x0 = x0;
   so->y0 = y0;
   so->x1 = x1;
   so->y1 = y1;
   so->extend_start = extend_start;
   so->extend_end = extend_end;
   fprintf(TF, "/Shade%i sh\n", so->shade_num);
}
Esempio n. 14
0
static HRESULT create_class_funcprop(compile_ctx_t *ctx, function_decl_t *func_decl, vbdisp_funcprop_desc_t *desc)
{
    vbdisp_invoke_type_t invoke_type;
    function_decl_t *funcprop_decl;
    HRESULT hres;

    desc->name = compiler_alloc_string(ctx->code, func_decl->name);
    if(!desc->name)
        return E_OUTOFMEMORY;

    for(funcprop_decl = func_decl; funcprop_decl; funcprop_decl = funcprop_decl->next_prop_func) {
        switch(funcprop_decl->type) {
        case FUNC_FUNCTION:
        case FUNC_SUB:
        case FUNC_PROPGET:
        case FUNC_DEFGET:
            invoke_type = VBDISP_CALLGET;
            break;
        case FUNC_PROPLET:
            invoke_type = VBDISP_LET;
            break;
        case FUNC_PROPSET:
            invoke_type = VBDISP_SET;
            break;
        default:
            assert(0);
        }

        assert(!desc->entries[invoke_type]);

        if(funcprop_decl->is_public)
            desc->is_public = TRUE;

        hres = create_function(ctx, funcprop_decl, desc->entries+invoke_type);
        if(FAILED(hres))
            return hres;
    }

    return S_OK;
}
Esempio n. 15
0
LsmDomDocument *
lsm_dom_implementation_create_document (const char *namespace_uri,
					const char *qualified_name)
{
	LsmDomDocumentCreateFunction create_function;

	g_return_val_if_fail (qualified_name != NULL, NULL);

	if (document_types == NULL) {
		lsm_dom_implementation_add_document_create_function ("math", lsm_mathml_document_new);
		lsm_dom_implementation_add_document_create_function ("svg", lsm_svg_document_new);
	}

	create_function = g_hash_table_lookup (document_types, qualified_name);
	if (create_function == NULL) {
		lsm_debug_dom ("[LsmDomImplementation::create_document] Unknow document type (%s)",
			   qualified_name);
		return NULL;
	}

	return create_function ();
}
Esempio n. 16
0
void connection::create_function(const char *name, Callable fun) {
	create_function(name, to_stdfunction(std::forward<Callable>(fun)));
}
Esempio n. 17
0
  void BonminInterface::init(const Dict& opts) {
    // Call the init method of the base class
    Nlpsol::init(opts);

    // Default options
    pass_nonlinear_variables_ = true;
    pass_nonlinear_constraints_ = true;
    Dict hess_lag_options, jac_g_options, grad_f_options;

    std::vector< std::vector<int> > sos1_groups;
    std::vector< std::vector<double> > sos1_weights;
    // Read user options
    for (auto&& op : opts) {
      if (op.first=="bonmin") {
        opts_ = op.second;
      } else if (op.first=="pass_nonlinear_variables") {
        pass_nonlinear_variables_ = op.second;
      } else if (op.first=="pass_nonlinear_constraints") {
        pass_nonlinear_constraints_ = op.second;
      }  else if (op.first=="var_string_md") {
        var_string_md_ = op.second;
      } else if (op.first=="var_integer_md") {
        var_integer_md_ = op.second;
      } else if (op.first=="var_numeric_md") {
        var_numeric_md_ = op.second;
      } else if (op.first=="con_string_md") {
        con_string_md_ = op.second;
      } else if (op.first=="con_integer_md") {
        con_integer_md_ = op.second;
      } else if (op.first=="con_numeric_md") {
        con_numeric_md_ = op.second;
      } else if (op.first=="hess_lag_options") {
        hess_lag_options = op.second;
      } else if (op.first=="jac_g_options") {
        jac_g_options = op.second;
      } else if (op.first=="grad_f_options") {
        grad_f_options = op.second;
      } else if (op.first=="hess_lag") {
        Function f = op.second;
        casadi_assert_dev(f.n_in()==4);
        casadi_assert_dev(f.n_out()==1);
        set_function(f, "nlp_hess_l");
      } else if (op.first=="jac_g") {
        Function f = op.second;
        casadi_assert_dev(f.n_in()==2);
        casadi_assert_dev(f.n_out()==2);
        set_function(f, "nlp_jac_g");
      } else if (op.first=="grad_f") {
        Function f = op.second;
        casadi_assert_dev(f.n_in()==2);
        casadi_assert_dev(f.n_out()==2);
        set_function(f, "nlp_grad_f");
      } else if (op.first=="sos1_groups") {
        sos1_groups = to_int(op.second.to_int_vector_vector());
        for (auto & g : sos1_groups) {
          for (auto & e : g) e-= GlobalOptions::start_index;
        }
      } else if (op.first=="sos1_weights") {
        sos1_weights = op.second.to_double_vector_vector();
      } else if (op.first=="sos1_priorities") {
        sos1_priorities_ = to_int(op.second.to_int_vector());
      }
    }

    // Do we need second order derivatives?
    exact_hessian_ = true;
    auto hessian_approximation = opts_.find("hessian_approximation");
    if (hessian_approximation!=opts_.end()) {
      exact_hessian_ = hessian_approximation->second == "exact";
    }


    // Setup NLP functions
    create_function("nlp_f", {"x", "p"}, {"f"});
    create_function("nlp_g", {"x", "p"}, {"g"});
    if (!has_function("nlp_grad_f")) {
      create_function("nlp_grad_f", {"x", "p"}, {"f", "grad:f:x"});
    }
    if (!has_function("nlp_jac_g")) {
      create_function("nlp_jac_g", {"x", "p"}, {"g", "jac:g:x"});
    }
    jacg_sp_ = get_function("nlp_jac_g").sparsity_out(1);

    // By default, assume all nonlinear
    nl_ex_.resize(nx_, true);
    nl_g_.resize(ng_, true);

    // Allocate temporary work vectors
    if (exact_hessian_) {
      if (!has_function("nlp_hess_l")) {
        create_function("nlp_hess_l", {"x", "p", "lam:f", "lam:g"},
                        {"hess:gamma:x:x"}, {{"gamma", {"f", "g"}}});
      }
      hesslag_sp_ = get_function("nlp_hess_l").sparsity_out(0);

      if (pass_nonlinear_variables_) {
        const casadi_int* col = hesslag_sp_.colind();
        for (casadi_int i=0;i<nx_;++i) nl_ex_[i] = col[i+1]-col[i];
      }
    } else {
      if (pass_nonlinear_variables_)
        nl_ex_ = oracle_.which_depends("x", {"f", "g"}, 2, false);
    }
    if (pass_nonlinear_constraints_)
      nl_g_ = oracle_.which_depends("x", {"g"}, 2, true);

    // Create sos info

    // Declare size
    sos_num_ = sos1_groups.size();
    // sos1 type
    sos1_types_.resize(sos_num_, 1);

    casadi_assert(sos1_weights.empty() || sos1_weights.size()==sos_num_,
      "sos1_weights has incorrect size");
    casadi_assert(sos1_priorities_.empty() || sos1_priorities_.size()==sos_num_,
      "sos1_priorities has incorrect size");
    if (sos1_priorities_.empty()) sos1_priorities_.resize(sos_num_, 1);

    sos_num_nz_ = 0;
    for (casadi_int i=0;i<sos_num_;++i) {
      // get local group
      const std::vector<int>& sos1_group = sos1_groups[i];

      // Get local weights
      std::vector<double> default_weights(sos1_group.size(), 1.0);
      const std::vector<double>& sos1_weight =
        sos1_weights.empty() ? default_weights : sos1_weights[i];
      casadi_assert(sos1_weight.size()==sos1_group.size(),
        "sos1_weights has incorrect size");

      // Populate lookup vector
      sos1_starts_.push_back(sos_num_nz_);
      sos_num_nz_+=sos1_group.size();

      sos1_weights_.insert(sos1_weights_.end(), sos1_weight.begin(), sos1_weight.end());
      sos1_indices_.insert(sos1_indices_.end(), sos1_group.begin(), sos1_group.end());
    }

    sos1_starts_.push_back(sos_num_nz_);

    // Allocate work vectors
    alloc_w(nx_, true); // xk_
    alloc_w(nx_, true); // lam_xk_
    alloc_w(ng_, true); // gk_
    alloc_w(nx_, true); // grad_fk_
    alloc_w(jacg_sp_.nnz(), true); // jac_gk_
    if (exact_hessian_) {
      alloc_w(hesslag_sp_.nnz(), true); // hess_lk_
    }
  }
Esempio n. 18
0
void bootstrap_kernel()
{
    // First, instanciate the types that are used by Type.
    TYPES.dict = create_type_uninitialized();
    TYPES.null = create_type_uninitialized();
    TYPES.string = create_type_uninitialized();
    TYPES.type = create_type_uninitialized();

    initialize_type(TYPES.dict);
    initialize_type(TYPES.null);
    initialize_type(TYPES.string);
    initialize_type(TYPES.type);
    string_setup_type(TYPES.string);

    // Initialize remaining global types.
    TYPES.any = create_type();
    TYPES.block = create_type();
    TYPES.bool_type = create_type();
    TYPES.error = create_type();
    TYPES.eval_context = create_type();
    TYPES.float_type = create_type();
    TYPES.function = create_type();
    TYPES.int_type = create_type();
    TYPES.list = create_type();
    TYPES.map = create_type();
    TYPES.opaque_pointer = create_type();
    TYPES.symbol = create_type();
    TYPES.term = create_type();
    TYPES.void_type = create_type();

    any_t::setup_type(TYPES.any);
    block_setup_type(TYPES.block);
    bool_t::setup_type(TYPES.bool_type);
    dict_t::setup_type(TYPES.dict);
    eval_context_t::setup_type(TYPES.eval_context);
    function_t::setup_type(TYPES.function);
    hashtable_setup_type(TYPES.map);
    int_t::setup_type(TYPES.int_type);
    list_t::setup_type(TYPES.list);
    symbol_setup_type(TYPES.symbol);
    null_t::setup_type(TYPES.null);
    number_t::setup_type(TYPES.float_type);
    opaque_pointer_t::setup_type(TYPES.opaque_pointer);
    term_setup_type(TYPES.term);
    string_setup_type(TYPES.error); // errors are just stored as strings for now
    type_t::setup_type(TYPES.type);
    void_t::setup_type(TYPES.void_type);

    // Start building World
    g_world = alloc_world();
    g_world->bootstrapStatus = sym_Bootstrapping;

    // Create root Block.
    g_world->root = new Block();
    Block* kernel = g_world->root;

    // Create value function
    Term* valueFunc = kernel->appendNew();
    rename(valueFunc, "value");
    FUNCS.value = valueFunc;

    // Create Type type
    Term* typeType = kernel->appendNew();
    typeType->function = FUNCS.value;
    typeType->type = TYPES.type;
    term_value(typeType)->value_type = TYPES.type;
    term_value(typeType)->value_data.ptr = TYPES.type;
    TYPES.type->declaringTerm = typeType;
    rename(typeType, "Type");

    // Create Any type
    Term* anyType = kernel->appendNew();
    anyType->function = valueFunc;
    anyType->type = TYPES.type;
    term_value(anyType)->value_type = TYPES.type;
    term_value(anyType)->value_data.ptr = TYPES.any;
    TYPES.any->declaringTerm = anyType;
    rename(anyType, "any");

    // Create Function type
    Term* functionType = kernel->appendNew();
    functionType->function = valueFunc;
    functionType->type = TYPES.type;
    TYPES.function->declaringTerm = functionType;
    term_value(functionType)->value_type = TYPES.type;
    term_value(functionType)->value_data.ptr = TYPES.function;
    rename(functionType, "Function");

    // Initialize value() func
    valueFunc->type = TYPES.function;
    valueFunc->function = valueFunc;
    make(TYPES.function, term_value(valueFunc));

    function_t::initialize(TYPES.function, term_value(valueFunc));
    initialize_function(valueFunc);
    as_function(valueFunc)->name = "value";
    block_set_evaluation_empty(function_contents(valueFunc), true);

    // Initialize primitive types (this requires value() function)
    create_type_value(kernel, TYPES.bool_type, "bool");
    create_type_value(kernel, TYPES.block, "Block");
    create_type_value(kernel, TYPES.dict, "Dict");
    create_type_value(kernel, TYPES.float_type, "number");
    create_type_value(kernel, TYPES.int_type, "int");
    create_type_value(kernel, TYPES.list, "List");
    create_type_value(kernel, TYPES.opaque_pointer, "opaque_pointer");
    create_type_value(kernel, TYPES.string, "String");
    create_type_value(kernel, TYPES.symbol, "Symbol");
    create_type_value(kernel, TYPES.term, "Term");
    create_type_value(kernel, TYPES.void_type, "void");
    create_type_value(kernel, TYPES.map, "Map");

    // Finish initializing World (this requires List and Hashtable types)
    world_initialize(g_world);

    // Create global symbol table (requires Hashtable type)
    symbol_initialize_global_table();

    // Setup output_placeholder() function, needed to declare functions properly.
    FUNCS.output = create_value(kernel, TYPES.function, "output_placeholder");
    function_t::initialize(TYPES.function, term_value(FUNCS.output));
    initialize_function(FUNCS.output);
    as_function(FUNCS.output)->name = "output_placeholder";
    as_function(FUNCS.output)->evaluate = NULL;
    as_function(FUNCS.output)->specializeType = output_placeholder_specializeType;
    ca_assert(function_get_output_type(FUNCS.output, 0) == TYPES.any);

    // Fix some holes in value() function
    {
        Function* attrs = as_function(valueFunc);
        Term* output = append_output_placeholder(function_contents(attrs), NULL);
        change_declared_type(output, TYPES.any);
        finish_building_function(function_contents(attrs));
    }

    ca_assert(function_get_output_type(valueFunc, 0) == TYPES.any);

    // input_placeholder() is needed before we can declare a function with inputs
    FUNCS.input = import_function(kernel, NULL, "input_placeholder() -> any");
    block_set_evaluation_empty(function_contents(FUNCS.input), true);

    // Now that we have input_placeholder() let's declare one input on output_placeholder()
    apply(function_contents(as_function(FUNCS.output)),
        FUNCS.input, TermList())->setBoolProp("optional", true);

    namespace_function::early_setup(kernel);

    // Setup declare_field() function, needed to represent compound types.
    FUNCS.declare_field = import_function(kernel, NULL, "declare_field() -> any");

    // Initialize a few more types
    Term* set_type = create_value(kernel, TYPES.type, "Set");
    set_t::setup_type(unbox_type(set_type));

    Term* indexableType = create_value(kernel, TYPES.type, "Indexable");
    indexable_t::setup_type(unbox_type(indexableType));

    TYPES.selector = unbox_type(create_value(kernel, TYPES.type, "Selector"));
    list_t::setup_type(TYPES.selector);

    control_flow_setup_funcs(kernel);
    selector_setup_funcs(kernel);
    loop_setup_functions(kernel);

    // Setup all the builtin functions defined in src/functions
    setup_builtin_functions(kernel);

    FUNCS.section_block = import_function(kernel, NULL, "def section_block() -> any");
    as_function(FUNCS.section_block)->formatSource = section_block_formatSource;

    // Create IMPLICIT_TYPES (deprecated)
    type_initialize_kernel(kernel);

    // Now we can build derived functions

    // Create overloaded functions
    FUNCS.add = create_overloaded_function(kernel, "add(any a,any b) -> any");
    append_to_overloaded_function(FUNCS.add, FUNCS.add_i);
    append_to_overloaded_function(FUNCS.add, FUNCS.add_f);

    Term* less_than = create_overloaded_function(kernel, "less_than(any a,any b) -> bool");
    append_to_overloaded_function(less_than, kernel->get("less_than_i"));
    append_to_overloaded_function(less_than, kernel->get("less_than_f"));

    Term* less_than_eq = create_overloaded_function(kernel, "less_than_eq(any a,any b) -> bool");
    append_to_overloaded_function(less_than_eq, kernel->get("less_than_eq_i"));
    append_to_overloaded_function(less_than_eq, kernel->get("less_than_eq_f"));

    Term* greater_than = create_overloaded_function(kernel, "greater_than(any a,any b) -> bool");
    append_to_overloaded_function(greater_than, kernel->get("greater_than_i"));
    append_to_overloaded_function(greater_than, kernel->get("greater_than_f"));

    Term* greater_than_eq = create_overloaded_function(kernel, "greater_than_eq(any a,any b) -> bool");
    append_to_overloaded_function(greater_than_eq, kernel->get("greater_than_eq_i"));
    append_to_overloaded_function(greater_than_eq, kernel->get("greater_than_eq_f"));

    Term* max_func = create_overloaded_function(kernel, "max(any a,any b) -> any");
    append_to_overloaded_function(max_func, kernel->get("max_i"));
    append_to_overloaded_function(max_func, kernel->get("max_f"));

    Term* min_func = create_overloaded_function(kernel, "min(any a,any b) -> any");
    append_to_overloaded_function(min_func, kernel->get("min_i"));
    append_to_overloaded_function(min_func, kernel->get("min_f"));

    Term* remainder_func = create_overloaded_function(kernel, "remainder(any a,any b) -> any");
    append_to_overloaded_function(remainder_func, kernel->get("remainder_i"));
    append_to_overloaded_function(remainder_func, kernel->get("remainder_f"));

    Term* mod_func = create_overloaded_function(kernel, "mod(any a,any b) -> any");
    append_to_overloaded_function(mod_func, kernel->get("mod_i"));
    append_to_overloaded_function(mod_func, kernel->get("mod_f"));

    FUNCS.mult = create_overloaded_function(kernel, "mult(any a,any b) -> any");
    append_to_overloaded_function(FUNCS.mult, kernel->get("mult_i"));
    append_to_overloaded_function(FUNCS.mult, kernel->get("mult_f"));

    FUNCS.neg = create_overloaded_function(kernel, "neg(any n) -> any");
    append_to_overloaded_function(FUNCS.neg, kernel->get("neg_i"));
    append_to_overloaded_function(FUNCS.neg, kernel->get("neg_f"));
    as_function(FUNCS.neg)->formatSource = neg_function::formatSource;

    FUNCS.sub = create_overloaded_function(kernel, "sub(any a,any b) -> any");
    append_to_overloaded_function(FUNCS.sub, kernel->get("sub_i"));
    append_to_overloaded_function(FUNCS.sub, kernel->get("sub_f"));

    // Create vectorized functions
    Term* add_v = create_function(kernel, "add_v");
    create_function_vectorized_vv(function_contents(add_v), FUNCS.add, TYPES.list, TYPES.list);
    Term* add_s = create_function(kernel, "add_s");
    create_function_vectorized_vs(function_contents(add_s), FUNCS.add, TYPES.list, TYPES.any);

    append_to_overloaded_function(FUNCS.add, add_v);
    append_to_overloaded_function(FUNCS.add, add_s);

    Term* sub_v = create_function(kernel, "sub_v");
    create_function_vectorized_vv(function_contents(sub_v), FUNCS.sub, TYPES.list, TYPES.list);
    Term* sub_s = create_function(kernel, "sub_s");
    create_function_vectorized_vs(function_contents(sub_s), FUNCS.sub, TYPES.list, TYPES.any);
    
    append_to_overloaded_function(FUNCS.sub, sub_v);
    append_to_overloaded_function(FUNCS.sub, sub_s);

    // Create vectorized mult() functions
    Term* mult_v = create_function(kernel, "mult_v");
    create_function_vectorized_vv(function_contents(mult_v), FUNCS.mult, TYPES.list, TYPES.list);
    Term* mult_s = create_function(kernel, "mult_s");
    create_function_vectorized_vs(function_contents(mult_s), FUNCS.mult, TYPES.list, TYPES.any);

    append_to_overloaded_function(FUNCS.mult, mult_v);
    append_to_overloaded_function(FUNCS.mult, mult_s);

    Term* div_s = create_function(kernel, "div_s");
    create_function_vectorized_vs(function_contents(div_s), FUNCS.div, TYPES.list, TYPES.any);

    // Need dynamic_method before any hosted functions
    FUNCS.dynamic_method = import_function(kernel, dynamic_method_call,
            "def dynamic_method(any inputs :multiple) -> any");

    // Load the standard library from stdlib.ca
    parser::compile(kernel, parser::statement_list, STDLIB_CA_TEXT);

    // Install C functions
    static const ImportRecord records[] = {
        {"assert", hosted_assert},
        {"cppbuild:build_module", cppbuild_function::build_module},
        {"file:version", file__version},
        {"file:exists", file__exists},
        {"file:read_text", file__read_text},
        {"length", length},
        {"from_string", from_string},
        {"to_string_repr", to_string_repr},
        {"call_actor", call_actor_func},
        {"send", send_func},
        {"test_spy", test_spy},
        {"test_oracle", test_oracle},
        {"refactor:rename", refactor__rename},
        {"refactor:change_function", refactor__change_function},
        {"reflect:this_block", reflect__this_block},
        {"reflect:kernel", reflect__kernel},
        {"sys:module_search_paths", sys__module_search_paths},
        {"sys:perf_stats_reset", sys__perf_stats_reset},
        {"sys:perf_stats_dump", sys__perf_stats_dump},

        {"Dict.count", Dict__count},
        {"Dict.get", Dict__get},
        {"Dict.set", Dict__set},

        {"Function.block", Function__block},

        {"empty_list", empty_list},
        {"List.append", List__append},
        {"List.concat", List__concat},
        {"List.resize", List__resize},
        {"List.count", List__count},
        {"List.insert", List__insert},
        {"List.length", List__length},
        {"List.join", List__join},
        {"List.slice", List__slice},
        {"List.get", List__get},
        {"List.set", List__set},

        {"Map.contains", Map__contains},
        {"Map.remove", Map__remove},
        {"Map.get", Map__get},
        {"Map.set", Map__set},
        {"Map.insertPairs", Map__insertPairs},

        {"Mutable.get", Mutable__get},
        {"Mutable.set", Mutable__set},

        {"String.char_at", String__char_at},
        {"String.ends_with", String__ends_with},
        {"String.length", String__length},
        {"String.substr", String__substr},
        {"String.slice", String__slice},
        {"String.starts_with", String__starts_with},
        {"String.split", String__split},
        {"String.to_camel_case", String__to_camel_case},
        {"String.to_upper", String__to_upper},
        {"String.to_lower", String__to_lower},
        
        {"Type.name", Type__name},
        {"Type.property", Type__property},
        {"Type.declaringTerm", Type__declaringTerm},
        {"type", typeof_func},
        {"static_type", static_type_func},

        {NULL, NULL}
    };

    install_function_list(kernel, records);

    closures_install_functions(kernel);
    modules_install_functions(kernel);
    reflection_install_functions(kernel);
    interpreter_install_functions(kernel);

    // Fetch refereneces to certain builtin funcs.
    FUNCS.block_dynamic_call = kernel->get("Block.call");
    FUNCS.dll_patch = kernel->get("sys:dll_patch");
    FUNCS.dynamic_call = kernel->get("dynamic_call");
    FUNCS.has_effects = kernel->get("has_effects");
    FUNCS.length = kernel->get("length");
    FUNCS.list_append = kernel->get("List.append");
    FUNCS.native_patch = kernel->get("native_patch");
    FUNCS.not_func = kernel->get("not");
    FUNCS.output_explicit = kernel->get("output");
    FUNCS.type = kernel->get("type");

    block_set_has_effects(nested_contents(FUNCS.has_effects), true);

    // Finish setting up some hosted types
    TYPES.actor = as_type(kernel->get("Actor"));
    TYPES.color = as_type(kernel->get("Color"));
    TYPES.closure = as_type(kernel->get("Closure"));
    callable_t::setup_type(as_type(kernel->get("Callable")));
    TYPES.frame = as_type(kernel->get("Frame"));
    TYPES.point = as_type(kernel->get("Point"));
    TYPES.file_signature = as_type(kernel->get("FileSignature"));

    Type* mutableType = as_type(kernel->get("Mutable"));
    circa_setup_object_type(mutableType, sizeof(Value), MutableRelease);
    mutableType->initialize = MutableInitialize;

    color_t::setup_type(TYPES.color);

    as_function(FUNCS.list_append)->specializeType = List__append_specializeType;
}
Esempio n. 19
0
  void WorhpInterface::init(const Dict& opts) {

    // Call the init method of the base class
    Nlpsol::init(opts);

    if (CheckWorhpVersion(WORHP_MAJOR, WORHP_MINOR, WORHP_PATCH)) {
      casadi_warning("Worhp incompatibility. Interface was compiled for Worhp " +
        str(WORHP_MAJOR) + "." + str(WORHP_MINOR) + "." + std::string(WORHP_PATCH));
    }

    // Default options
    Dict worhp_opts;

    // Read user options
    for (auto&& op : opts) {
      if (op.first=="worhp") {
        worhp_opts = op.second;
      }
    }

    // Sort Worhp options
    casadi_int nopts = WorhpGetParamCount();
    for (auto&& op : worhp_opts) {
      if (op.first.compare("qp")==0) {
        qp_opts_ = op.second;
        continue;
      }

      // Get corresponding index using a linear search
      casadi_int ind;
      for (ind=1; ind<=nopts; ++ind) {
        // Get name in WORHP
        const char* name = WorhpGetParamName(ind);
        // Break if matching name
        if (op.first.compare(name)==0) break;
      }
      if (ind>nopts) casadi_error("No such Worhp option: " + op.first);

      // Add to the corresponding list
      switch (WorhpGetParamType(ind)) {
      case WORHP_BOOL_T:
        bool_opts_[op.first] = op.second;
        break;
      case WORHP_DOUBLE_T:
        double_opts_[op.first] = op.second;
        break;
      case WORHP_INT_T:
        int_opts_[op.first] = op.second;
        break;
      default:
        casadi_error("Cannot handle WORHP option \"" + op.first + "\": Unknown type " +
          str(WorhpGetParamType(ind)) + ".");
        break;
      }
    }

    // Setup NLP functions
    f_fcn_ = create_function("nlp_f", {"x", "p"}, {"f"});
    g_fcn_ = create_function("nlp_g", {"x", "p"}, {"g"});
    grad_f_fcn_ = create_function("nlp_grad_f", {"x", "p"}, {"f", "grad:f:x"});
    jac_g_fcn_ = create_function("nlp_jac_g", {"x", "p"}, {"g", "jac:g:x"});
    jacg_sp_ = jac_g_fcn_.sparsity_out(1);
    hess_l_fcn_ = create_function("nlp_hess_l", {"x", "p", "lam:f", "lam:g"},
                                  {"transpose:hess:gamma:x:x"},
                                  {{"gamma", {"f", "g"}}});
    hesslag_sp_ = hess_l_fcn_.sparsity_out(0);

    // Temporary vectors
    alloc_w(nx_); // for fetching diagonal entries form Hessian
  }
void create_operator(const iterator_t str, const iterator_t end)
{
	create_function(str,end);
	current_func->set_is_operator(IS_OPERATOR);
}
Esempio n. 21
0
  void BonminInterface::init(const Dict& opts) {
    // Call the init method of the base class
    Nlpsol::init(opts);

    // Default options
    pass_nonlinear_variables_ = false;
    Dict hess_lag_options, jac_g_options, grad_f_options;

    // Read user options
    for (auto&& op : opts) {
      if (op.first=="bonmin") {
        opts_ = op.second;
      } else if (op.first=="pass_nonlinear_variables") {
        pass_nonlinear_variables_ = op.second;
      } else if (op.first=="var_string_md") {
        var_string_md_ = op.second;
      } else if (op.first=="var_integer_md") {
        var_integer_md_ = op.second;
      } else if (op.first=="var_numeric_md") {
        var_numeric_md_ = op.second;
      } else if (op.first=="con_string_md") {
        con_string_md_ = op.second;
      } else if (op.first=="con_integer_md") {
        con_integer_md_ = op.second;
      } else if (op.first=="con_numeric_md") {
        con_numeric_md_ = op.second;
      } else if (op.first=="hess_lag_options") {
        hess_lag_options = op.second;
      } else if (op.first=="jac_g_options") {
        jac_g_options = op.second;
      } else if (op.first=="grad_f_options") {
        grad_f_options = op.second;
      } else if (op.first=="hess_lag") {
        Function f = op.second;
        casadi_assert(f.n_in()==4);
        casadi_assert(f.n_out()==1);
        set_function(f, "nlp_hess_l");
      } else if (op.first=="jac_g") {
        Function f = op.second;
        casadi_assert(f.n_in()==2);
        casadi_assert(f.n_out()==2);
        set_function(f, "nlp_jac_g");
      } else if (op.first=="grad_f") {
        Function f = op.second;
        casadi_assert(f.n_in()==2);
        casadi_assert(f.n_out()==2);
        set_function(f, "nlp_grad_f");
      }
    }

    // Do we need second order derivatives?
    exact_hessian_ = true;
    auto hessian_approximation = opts_.find("hessian_approximation");
    if (hessian_approximation!=opts_.end()) {
      exact_hessian_ = hessian_approximation->second == "exact";
    }

    // Setup NLP functions
    create_function("nlp_f", {"x", "p"}, {"f"});
    create_function("nlp_g", {"x", "p"}, {"g"});
    if (!has_function("nlp_grad_f")) {
      create_function("nlp_grad_f", {"x", "p"}, {"f", "grad:f:x"});
    }
    if (!has_function("nlp_jac_g")) {
      create_function("nlp_jac_g", {"x", "p"}, {"g", "jac:g:x"});
    }
    jacg_sp_ = get_function("nlp_jac_g").sparsity_out(1);

    // Allocate temporary work vectors
    if (exact_hessian_) {
      if (!has_function("nlp_hess_l")) {
        create_function("nlp_hess_l", {"x", "p", "lam:f", "lam:g"},
                        {"hess:gamma:x:x"}, {{"gamma", {"f", "g"}}});
      }
      hesslag_sp_ = get_function("nlp_hess_l").sparsity_out(0);
    } else if (pass_nonlinear_variables_) {
      nl_ex_ = oracle_.which_depends("x", {"f", "g"}, 2, false);
    }

    // Allocate work vectors
    alloc_w(nx_, true); // xk_
    alloc_w(ng_, true); // lam_gk_
    alloc_w(nx_, true); // lam_xk_
    alloc_w(ng_, true); // gk_
    alloc_w(nx_, true); // grad_fk_
    alloc_w(jacg_sp_.nnz(), true); // jac_gk_
    if (exact_hessian_) {
      alloc_w(hesslag_sp_.nnz(), true); // hess_lk_
    }
  }
Esempio n. 22
0
  void IdasInterface::init(const Dict& opts) {
    log("IdasInterface::init", "begin");

    // Call the base class init
    SundialsInterface::init(opts);

    // Default options
    cj_scaling_ = true;
    calc_ic_ = true;
    suppress_algebraic_ = false;
    max_step_size_ = 0;

    // Read options
    for (auto&& op : opts) {
      if (op.first=="init_xdot") {
        init_xdot_ = op.second;
      } else if (op.first=="cj_scaling") {
        cj_scaling_ = op.second;
      } else if (op.first=="calc_ic") {
        calc_ic_ = op.second;
      } else if (op.first=="suppress_algebraic") {
        suppress_algebraic_ = op.second;
      } else if (op.first=="max_step_size") {
        max_step_size_ = op.second;
      } else if (op.first=="abstolv") {
        abstolv_ = op.second;
      }
    }

    // Default dependent options
    calc_icB_ = calc_ic_;
    first_time_ = grid_.back();

    // Read dependent options
    for (auto&& op : opts) {
      if (op.first=="calc_icB") {
        calc_icB_ = op.second;
      } else if (op.first=="first_time") {
        first_time_ = op.second;
      }
    }

    create_function("daeF", {"x", "z", "p", "t"}, {"ode", "alg"});
    create_function("quadF", {"x", "z", "p", "t"}, {"quad"});
    create_function("daeB", {"rx", "rz", "rp", "x", "z", "p", "t"}, {"rode", "ralg"});
    create_function("quadB", {"rx", "rz", "rp", "x", "z", "p", "t"}, {"rquad"});

    // Get initial conditions for the state derivatives
    if (init_xdot_.empty()) {
      init_xdot_.resize(nx_, 0);
    } else {
      casadi_assert_message(
        init_xdot_.size()==nx_,
        "Option \"init_xdot\" has incorrect length. Expecting " << nx_
        << ", but got " << init_xdot_.size()
        << ". Note that this message may actually be generated by the augmented"
        " integrator. In that case, make use of the 'augmented_options' options"
        " to correct 'init_xdot' for the augmented integrator.");
    }

    // Attach functions for jacobian information
    if (newton_scheme_!=SD_DIRECT || (ns_>0 && second_order_correction_)) {
      create_function("jtimesF",
        {"t", "x", "z", "p", "fwd:x", "fwd:z"},
        {"fwd:ode", "fwd:alg"});
      if (nrx_>0) {
        create_function("jtimesB",
          {"t", "x", "z", "p", "rx", "rz", "rp", "fwd:rx", "fwd:rz"},
          {"fwd:rode", "fwd:ralg"});
      }
    }

    log("IdasInterface::init", "end");
  }
Esempio n. 23
0
  void SnoptInterface::init(const Dict& opts) {
    // Call the init method of the base class
    Nlpsol::init(opts);

    // Default: cold start
    Cold_ = 0;

    // Read user options
    for (auto&& op : opts) {
      if (op.first=="snopt") {
        opts_ = op.second;
      } else if (op.first=="start") {
        std::string start = op.second.to_string();
        if (start=="cold") {
          Cold_ = 0;
        } else if (start=="warm") {
          Cold_ = 1;
        } else if (start=="hot") {
          Cold_ = 2;
        } else {
          casadi_error("Unknown start option: " + start);
        }
      }
    }

    // Get/generate required functions
    jac_f_fcn_ = create_function("nlp_jac_f", {"x", "p"}, {"f", "jac:f:x"});
    jac_g_fcn_ = create_function("nlp_jac_g", {"x", "p"}, {"g", "jac:g:x"});
    jacg_sp_ = jac_g_fcn_.sparsity_out(1);

    // prepare the mapping for constraints
    nnJac_ = nx_;
    nnObj_ = nx_;
    nnCon_ = ng_;

    // Here follows the core of the mapping
    //  Two integer matrices are constructed:
    //  one with gradF sparsity, and one with jacG sparsity
    //  the integer values denote the nonzero locations into the original gradF/jacG
    //  but with a special encoding: entries of gradF are encoded "-1-i" and
    //  entries of jacG are encoded "1+i"
    //  "0" is to be interpreted not as an index but as a literal zero

    IM mapping_jacG  = IM(0, nx_);
    IM mapping_gradF = IM(jac_f_fcn_.sparsity_out(1),
                          range(-1, -1-jac_f_fcn_.nnz_out(1), -1));

    if (!jac_g_fcn_.is_null()) {
      mapping_jacG = IM(jacg_sp_, range(1, jacg_sp_.nnz()+1));
    }

    // First, remap jacG
    A_structure_ = mapping_jacG;

    m_ = ng_;

    // Construct the linear objective row
    IM d = mapping_gradF(Slice(0), Slice());

    std::vector<int> ii = mapping_gradF.sparsity().get_col();
    for (int j = 0; j < nnObj_; ++j) {
      if (d.colind(j) != d.colind(j+1)) {
        int k = d.colind(j);
        d.nz(k) = 0;
      }
    }

    // Make it as sparse as you can
    d = sparsify(d);

    jacF_row_ = d.nnz() != 0;
    if (jacF_row_) {  // We need an objective gradient row
      A_structure_ = vertcat(A_structure_, d);
      m_ +=1;
    }
    iObj_ = jacF_row_ ? (m_ - 1) : -1;

    // Is the A matrix completely empty?
    dummyrow_ = A_structure_.nnz() == 0;  // Then we need a dummy row
    if (dummyrow_) {
      IM dummyrow = IM(1, nx_);
      dummyrow(0, 0) = 0;
      A_structure_ = vertcat(A_structure_, dummyrow);
      m_+=1;
    }

    // We don't need a dummy row if a linear objective row is present
    casadi_assert(!(dummyrow_ && jacF_row_));

    // Allocate temporary memory
    alloc_w(nx_, true); // xk2_
    alloc_w(ng_, true); // lam_gk_
    alloc_w(nx_, true); // lam_xk_
    alloc_w(ng_, true); // gk_
    alloc_w(jac_f_fcn_.nnz_out(1), true); // jac_fk_
    if (!jacg_sp_.is_null()) {
      alloc_w(jacg_sp_.nnz(), true); // jac_gk_
    }
  }
Esempio n. 24
0
void evaluate(Node* pNode, Value* pValue) {
  if (return_count != top_of_frame_stack) return;
  print_node(pNode);
  switch(pNode->type) {
    case NTINTEGER:
      // printf("pNode->value.type: %d\n", (int)pNode->value.type);
      // printf("pNode->value.intValue: %d\n", pNode->value.intValue);
      *pValue = pNode->value;
      break;

    case NTDOUBLE:
      *pValue = pNode->value;
      break;

    case NTIDENTIFIER:
      *pValue = get_variable(pNode->name);
      break;

    case NTASSIGNMENT:
      {
        Value rhs;
        evaluate(pNode->child_nodes[1], &rhs);
        set_variable(pNode->child_nodes[0]->name, rhs);
        *pValue = rhs;
      }
      break;

    case NTUNARYOPERATOR :
    {
        Value a;
        evaluate(pNode->child_nodes[0], &a);
        cal_uminus (pValue, a);
    }
    break;

    case NTBINARYOPERATOR:
      {
        Value a, b;
        evaluate(pNode->child_nodes[0], &a);
        evaluate(pNode->child_nodes[1], &b);
        cal_value(pValue, a, b,pNode->op_token);
      }
      break;

    case NTSTATEMENTLIST:
      {
        int i;
        Value temp;
        for(i = 0; i < pNode->n_of_child_nodes; i++) {
          evaluate(pNode->child_nodes[i], &temp);
        }
      }
      break;

    case NTSTATEMENT:
      {
        Value temp;

        if (pNode->n_of_child_nodes > 0) {
          evaluate(pNode->child_nodes[0], &temp);
          *pValue = temp;
        } else {
          pValue->type = STATEMENTVALUE;
          pValue->statementValue = "empty statement";
        }
      }
      break;

    case NTIFSTATEMENT:
      {
        Value test, temp;
        evaluate(pNode->child_nodes[0], &temp);
        test_value(&test, temp);

        if ( (test.type == INTVALUE) && (test.intValue == 1) ) {
          evaluate(pNode->child_nodes[1], &temp);
        } else if (pNode->n_of_child_nodes == 3) {
          evaluate(pNode->child_nodes[2], &temp);
        }

        pValue->type = STATEMENTVALUE;
        pValue->statementValue = "if";
      }
      break;

    case NTWHILESTATEMENT:
      {
        Value test, temp;

        while (1) {
          evaluate(pNode->child_nodes[0], &temp);
          test_value(&test, temp);

          if (!(test.type == INTVALUE && test.intValue)) break;

          // printf("AAAA  - %d\n", test.intValue);
          evaluate(pNode->child_nodes[1], &temp);
        }

        pValue->type = STATEMENTVALUE;
        pValue->statementValue = "while";
      }
      break;

    case  NTFUNCDECLARE:
      {
        Function* pFn;
        Value value;
        create_function(&pFn, pNode->child_nodes[1], pNode->child_nodes[2]);
        value.type = FUNCTIONVALUE;
        value.functionValue = pFn;

        set_variable(pNode->child_nodes[0]->name, value);
        pValue->type = STATEMENTVALUE;
        pValue->statementValue = "a function is defined.";
      }
      break;

    case NTRETURNSTATEMENT:

      {
        evaluate(pNode->child_nodes[0], frame_stack[top_of_frame_stack].pReturnValue);
        return_count --;
      }
      break;

    case NTLOCALSTATEMENT:
      {
        int i;
        Node* parameter_list = pNode->child_nodes[0];

        for(i=0;i<parameter_list->n_of_child_nodes;i++) {
          char* identifier = parameter_list->child_nodes[i]->name;
          register_local_frame(&frame_stack[top_of_frame_stack], identifier);
        }
        pValue->type = STATEMENTVALUE;
        pValue->statementValue = "local variables are defined.";

      }
      break;

    case NTFUNCCALL:
      {
        int i;
        Value value;
        Function* pFn;
        Node* expression_list;
        Node* statement_list;
        value = get_variable(pNode->child_nodes[0]->name);
        expression_list = pNode->child_nodes[1];

        if (value.type != FUNCTIONVALUE) {
          pValue->type = ERRORVALUE;
          pValue->errorValue = "no function name error";
        } else {
          Value temp;
          pFn = value.functionValue;
          statement_list = pFn->statement_list;

          pValue->type = ERRORVALUE;
          pValue->errorValue = "nothing is returned";

          top_of_frame_stack ++;
          return_count ++;
          init_frame(&frame_stack[top_of_frame_stack], pValue, pFn, expression_list);
          if (pValue->type != ERRORVALUE) {
            evaluate(statement_list, &temp);
          }
          top_of_frame_stack --;
          return_count = top_of_frame_stack;
        }
      }
      break;

    default:
      // printf("not evaluated...\n");
      break;
  }
}
Esempio n. 25
0
int
main (void)
{
  gsl_function F_sin, F_cos, F_func1, F_func2, F_func3, F_func4,
    F_func5, F_func6;
  
  gsl_function_fdf FDF_sin, FDF_cos, FDF_func1, FDF_func2, FDF_func3, FDF_func4,
    FDF_func5, FDF_func6;

  const gsl_root_fsolver_type * fsolver[4] ;
  const gsl_root_fdfsolver_type * fdfsolver[4] ;

  const gsl_root_fsolver_type ** T;
  const gsl_root_fdfsolver_type ** S;

  gsl_ieee_env_setup();

  fsolver[0] = gsl_root_fsolver_bisection;
  fsolver[1] = gsl_root_fsolver_brent;
  fsolver[2] = gsl_root_fsolver_falsepos;
  fsolver[3] = 0;

  fdfsolver[0] = gsl_root_fdfsolver_newton;
  fdfsolver[1] = gsl_root_fdfsolver_secant;
  fdfsolver[2] = gsl_root_fdfsolver_steffenson;
  fdfsolver[3] = 0;

  F_sin = create_function (sin_f) ;
  F_cos = create_function (cos_f) ; 
  F_func1 = create_function (func1) ;
  F_func2 = create_function (func2) ;
  F_func3 = create_function (func3) ;
  F_func4 = create_function (func4) ;
  F_func5 = create_function (func5) ;
  F_func6 = create_function (func6) ;

  FDF_sin = create_fdf (sin_f, sin_df, sin_fdf) ;
  FDF_cos = create_fdf (cos_f, cos_df, cos_fdf) ;
  FDF_func1 = create_fdf (func1, func1_df, func1_fdf) ;
  FDF_func2 = create_fdf (func2, func2_df, func2_fdf) ;
  FDF_func3 = create_fdf (func3, func3_df, func3_fdf) ;
  FDF_func4 = create_fdf (func4, func4_df, func4_fdf) ;
  FDF_func5 = create_fdf (func5, func5_df, func5_fdf) ;
  FDF_func6 = create_fdf (func6, func6_df, func6_fdf) ;

  gsl_set_error_handler (&my_error_handler);

  for (T = fsolver ; *T != 0 ; T++)
    {
      test_f (*T, "sin(x) [3, 4]", &F_sin, 3.0, 4.0, M_PI);
      test_f (*T, "sin(x) [-4, -3]", &F_sin, -4.0, -3.0, -M_PI);
      test_f (*T, "sin(x) [-1/3, 1]", &F_sin, -1.0 / 3.0, 1.0, 0.0);
      test_f (*T, "cos(x) [0, 3]", &F_cos, 0.0, 3.0, M_PI / 2.0);
      test_f (*T, "cos(x) [-3, 0]", &F_cos, -3.0, 0.0, -M_PI / 2.0);
      test_f (*T, "x^20 - 1 [0.1, 2]", &F_func1, 0.1, 2.0, 1.0);
      test_f (*T, "sqrt(|x|)*sgn(x)", &F_func2, -1.0 / 3.0, 1.0, 0.0);
      test_f (*T, "x^2 - 1e-8 [0, 1]", &F_func3, 0.0, 1.0, sqrt (1e-8));
      test_f (*T, "x exp(-x) [-1/3, 2]", &F_func4, -1.0 / 3.0, 2.0, 0.0);
      test_f (*T, "(x - 1)^7 [0.9995, 1.0002]", &F_func6, 0.9995, 1.0002, 1.0);
      
      test_f_e (*T, "invalid range check [4, 0]", &F_sin, 4.0, 0.0, M_PI);
      test_f_e (*T, "invalid range check [1, 1]", &F_sin, 1.0, 1.0, M_PI);
      test_f_e (*T, "invalid range check [0.1, 0.2]", &F_sin, 0.1, 0.2, M_PI);
    }

  for (S = fdfsolver ; *S != 0 ; S++)
    {
      test_fdf (*S,"sin(x) {3.4}", &FDF_sin, 3.4, M_PI);
      test_fdf (*S,"sin(x) {-3.3}", &FDF_sin, -3.3, -M_PI);
      test_fdf (*S,"sin(x) {0.5}", &FDF_sin, 0.5, 0.0);
      test_fdf (*S,"cos(x) {0.6}", &FDF_cos, 0.6, M_PI / 2.0);
      test_fdf (*S,"cos(x) {-2.5}", &FDF_cos, -2.5, -M_PI / 2.0);
      test_fdf (*S,"x^{20} - 1 {0.9}", &FDF_func1, 0.9, 1.0);
      test_fdf (*S,"x^{20} - 1 {1.1}", &FDF_func1, 1.1, 1.0);
      test_fdf (*S,"sqrt(|x|)*sgn(x) {1.001}", &FDF_func2, 0.001, 0.0);
      test_fdf (*S,"x^2 - 1e-8 {1}", &FDF_func3, 1.0, sqrt (1e-8));
      test_fdf (*S,"x exp(-x) {-2}", &FDF_func4, -2.0, 0.0);
      test_fdf_e (*S,"max iterations x -> +Inf, x exp(-x) {2}", &FDF_func4, 2.0, 0.0);
      test_fdf_e (*S,"max iterations x -> -Inf, 1/(1 + exp(-x)) {0}", &FDF_func5, 0.0, 0.0);
    }

  test_fdf (gsl_root_fdfsolver_steffenson,
            "(x - 1)^7 {0.9}", &FDF_func6, 0.9, 1.0);    

  /* now summarize the results */

  exit (gsl_test_summary ());
}