Example #1
0
Real
ParsedODEKernel::computeQpJacobian()
{
  updateParams();
  return evaluate(_func_dFdu);
}
Example #2
0
void interpretert::evaluate(
  const exprt &expr,
  std::vector<mp_integer> &dest) const
{
  if(expr.id()==ID_constant)
  {
    if(expr.type().id()==ID_struct)
    {
    }
    else if(expr.type().id()==ID_floatbv)
    {
      ieee_floatt f;
      f.from_expr(to_constant_expr(expr));
      dest.push_back(f.pack());
      return;
    }
    else if(expr.type().id()==ID_fixedbv)
    {
      fixedbvt f;
      f.from_expr(to_constant_expr(expr));
      dest.push_back(f.get_value());
      return;
    }
    else if(expr.type().id()==ID_bool)
    {
      dest.push_back(expr.is_true());
      return;
    }
    else
    {
      mp_integer i;
      if(!to_integer(expr, i))
      {
        dest.push_back(i);
        return;
      }
    }
  }
  else if(expr.id()==ID_struct)
  {
    dest.reserve(get_size(expr.type()));
    bool error=false;

    forall_operands(it, expr)
    {
      if(it->type().id()==ID_code)
        continue;

      unsigned sub_size=get_size(it->type());
      if(sub_size==0)
        continue;

      std::vector<mp_integer> tmp;
      evaluate(*it, tmp);

      if(tmp.size()==sub_size)
      {
        for(unsigned i=0; i<sub_size; i++)
          dest.push_back(tmp[i]);
      }
      else
        error=true;
    }

    if(!error)
      return;

    dest.clear();
  }
Example #3
0
File: portal.c Project: Lundex/lima
string get_look_in_desc()
{
    return evaluate(look_in_desc);
}
Example #4
0
void TTTrackDialog::OnOkClick( wxCommandEvent& event )
{
  evaluate();
  EndModal( wxID_OK );
}
int main() {

	char* refId = "rs1048659";
	char* name = "HG00372";

	// CI part

    int i,j;
    read_names();
    read_ids();
    int size_names = size_of_names();
    int size_ids = size_of_ids();

    int refId_id = find_ids_id(refId);
    int name_id = find_name_id(name);


    read_encs();
    char encC = get_char_in_enc((size_names*refId_id)+name_id);

    read_skeys();
    char skeyC = get_char_in_skeys((size_names*refId_id)+name_id);
    // SPU -> GC building part

	GarbledCircuit garbledCircuit;
	GarblingContext garblingContext;

	int inputsNb = 32;
	int wiresNb = 50000;
	int gatesNb = 50000;
	int outputsNb = 32;

	//Create a circuit.
	block labels[2 * inputsNb];
	createInputLabels(labels, inputsNb);
	InputLabels inputLabels = labels;
	createEmptyGarbledCircuit(&garbledCircuit, inputsNb, outputsNb, gatesNb,
			wiresNb, inputLabels);
	startBuilding(&garbledCircuit, &garblingContext);

	// Transform generator's input into fixed wire
	int zero = fixedZeroWire(&garbledCircuit,&garblingContext);
	int one = fixedOneWire(&garbledCircuit,&garblingContext);

	int onewire = getNextWire(&garblingContext);
	NOTGate(&garbledCircuit,&garblingContext,zero,onewire);

	int zerowire = getNextWire(&garblingContext);
	NOTGate(&garbledCircuit,&garblingContext,one,zerowire);

	int outputs[outputsNb];
	int *inp = (int *) malloc(sizeof(int) * inputsNb*2);
	countToN(inp, inputsNb);
	//countToN(outputs, inputsNb);

	int bits[inputsNb];
	int_into_ints(encC,bits);
	for (i = 0; i < inputsNb; i++) {
		if (bits[i]) {
			inp[inputsNb+i] = onewire;
		} else {
			inp[inputsNb+i] = zerowire;
		}
	}
	int tempOutput[2*outputsNb];
	XORCircuit(&garbledCircuit, &garblingContext, inputsNb*2, inp, outputs);

	block *outputbs = (block*) malloc(sizeof(block) * outputsNb);
	OutputMap outputMap = outputbs;
	finishBuilding(&garbledCircuit, &garblingContext, outputMap, outputs);
	garbleCircuit(&garbledCircuit, inputLabels, outputMap);

	// MU -> Evaluation part
	block extractedLabels[inputsNb];

	int extractedInputs[inputsNb];
	int_into_ints(skeyC,extractedInputs);

	extractLabels(extractedLabels, inputLabels, extractedInputs, inputsNb);
	block computedOutputMap[outputsNb];
	evaluate(&garbledCircuit, extractedLabels, computedOutputMap);
	int outputVals[outputsNb];
	mapOutputs(outputMap, computedOutputMap, outputVals, outputsNb);
	//TODO
	int res = ints_into_int(outputVals);
	printf("RESULT IS : %d\n",res);
	return 0;
}
Example #6
0
const SoXipData* SoXipSFData::getDataValue() const
{
	evaluate();
	return value;
}
Example #7
0
int
yyparse (void)
{
    int yystate;
    /* Number of tokens to shift before error messages enabled.  */
    int yyerrstatus;

    /* The stacks and their tools:
       'yyss': related to states.
       'yyvs': related to semantic values.

       Refer to the stacks through separate pointers, to allow yyoverflow
       to reallocate them elsewhere.  */

    /* The state stack.  */
    yytype_int16 yyssa[YYINITDEPTH];
    yytype_int16 *yyss;
    yytype_int16 *yyssp;

    /* The semantic value stack.  */
    YYSTYPE yyvsa[YYINITDEPTH];
    YYSTYPE *yyvs;
    YYSTYPE *yyvsp;

    YYSIZE_T yystacksize;

  int yyn;
  int yyresult;
  /* Lookahead token as an internal (translated) token number.  */
  int yytoken = 0;
  /* The variables used to return semantic value and location from the
     action routines.  */
  YYSTYPE yyval;

#if YYERROR_VERBOSE
  /* Buffer for error messages, and its allocated size.  */
  char yymsgbuf[128];
  char *yymsg = yymsgbuf;
  YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif

#define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N))

  /* The number of symbols on the RHS of the reduced rule.
     Keep to zero when no symbol should be popped.  */
  int yylen = 0;

  yyssp = yyss = yyssa;
  yyvsp = yyvs = yyvsa;
  yystacksize = YYINITDEPTH;

  YYDPRINTF ((stderr, "Starting parse\n"));

  yystate = 0;
  yyerrstatus = 0;
  yynerrs = 0;
  yychar = YYEMPTY; /* Cause a token to be read.  */
  goto yysetstate;

/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate.  |
`------------------------------------------------------------*/
 yynewstate:
  /* In all cases, when you get here, the value and location stacks
     have just been pushed.  So pushing a state here evens the stacks.  */
  yyssp++;

 yysetstate:
  *yyssp = yystate;

  if (yyss + yystacksize - 1 <= yyssp)
    {
      /* Get the current used size of the three stacks, in elements.  */
      YYSIZE_T yysize = yyssp - yyss + 1;

#ifdef yyoverflow
      {
        /* Give user a chance to reallocate the stack.  Use copies of
           these so that the &'s don't force the real ones into
           memory.  */
        YYSTYPE *yyvs1 = yyvs;
        yytype_int16 *yyss1 = yyss;

        /* Each stack pointer address is followed by the size of the
           data in use in that stack, in bytes.  This used to be a
           conditional around just the two extra args, but that might
           be undefined if yyoverflow is a macro.  */
        yyoverflow (YY_("memory exhausted"),
                    &yyss1, yysize * sizeof (*yyssp),
                    &yyvs1, yysize * sizeof (*yyvsp),
                    &yystacksize);

        yyss = yyss1;
        yyvs = yyvs1;
      }
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
      goto yyexhaustedlab;
# else
      /* Extend the stack our own way.  */
      if (YYMAXDEPTH <= yystacksize)
        goto yyexhaustedlab;
      yystacksize *= 2;
      if (YYMAXDEPTH < yystacksize)
        yystacksize = YYMAXDEPTH;

      {
        yytype_int16 *yyss1 = yyss;
        union yyalloc *yyptr =
          (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
        if (! yyptr)
          goto yyexhaustedlab;
        YYSTACK_RELOCATE (yyss_alloc, yyss);
        YYSTACK_RELOCATE (yyvs_alloc, yyvs);
#  undef YYSTACK_RELOCATE
        if (yyss1 != yyssa)
          YYSTACK_FREE (yyss1);
      }
# endif
#endif /* no yyoverflow */

      yyssp = yyss + yysize - 1;
      yyvsp = yyvs + yysize - 1;

      YYDPRINTF ((stderr, "Stack size increased to %lu\n",
                  (unsigned long int) yystacksize));

      if (yyss + yystacksize - 1 <= yyssp)
        YYABORT;
    }

  YYDPRINTF ((stderr, "Entering state %d\n", yystate));

  if (yystate == YYFINAL)
    YYACCEPT;

  goto yybackup;

/*-----------.
| yybackup.  |
`-----------*/
yybackup:

  /* Do appropriate processing given the current state.  Read a
     lookahead token if we need one and don't already have one.  */

  /* First try to decide what to do without reference to lookahead token.  */
  yyn = yypact[yystate];
  if (yypact_value_is_default (yyn))
    goto yydefault;

  /* Not known => get a lookahead token if don't already have one.  */

  /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol.  */
  if (yychar == YYEMPTY)
    {
      YYDPRINTF ((stderr, "Reading a token: "));
      yychar = yylex ();
    }

  if (yychar <= YYEOF)
    {
      yychar = yytoken = YYEOF;
      YYDPRINTF ((stderr, "Now at end of input.\n"));
    }
  else
    {
      yytoken = YYTRANSLATE (yychar);
      YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
    }

  /* If the proper action on seeing token YYTOKEN is to reduce or to
     detect an error, take that action.  */
  yyn += yytoken;
  if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
    goto yydefault;
  yyn = yytable[yyn];
  if (yyn <= 0)
    {
      if (yytable_value_is_error (yyn))
        goto yyerrlab;
      yyn = -yyn;
      goto yyreduce;
    }

  /* Count tokens shifted since error; after three, turn off error
     status.  */
  if (yyerrstatus)
    yyerrstatus--;

  /* Shift the lookahead token.  */
  YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);

  /* Discard the shifted token.  */
  yychar = YYEMPTY;

  yystate = yyn;
  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
  *++yyvsp = yylval;
  YY_IGNORE_MAYBE_UNINITIALIZED_END

  goto yynewstate;


/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state.  |
`-----------------------------------------------------------*/
yydefault:
  yyn = yydefact[yystate];
  if (yyn == 0)
    goto yyerrlab;
  goto yyreduce;


/*-----------------------------.
| yyreduce -- Do a reduction.  |
`-----------------------------*/
yyreduce:
  /* yyn is the number of a rule to reduce with.  */
  yylen = yyr2[yyn];

  /* If YYLEN is nonzero, implement the default value of the action:
     '$$ = $1'.

     Otherwise, the following line sets YYVAL to garbage.
     This behavior is undocumented and Bison
     users should not rely upon it.  Assigning to YYVAL
     unconditionally makes the parser a bit smaller, and it avoids a
     GCC warning that YYVAL may be used uninitialized.  */
  yyval = yyvsp[1-yylen];


  YY_REDUCE_PRINT (yyn);
  switch (yyn)
    {
        case 2:
#line 18 "exptree.y" /* yacc.c:1646  */
    {printf("%d",evaluate((yyval)));exit(1);}
#line 1219 "y.tab.c" /* yacc.c:1646  */
    break;

  case 3:
#line 21 "exptree.y" /* yacc.c:1646  */
    {(yyval) = makeNode((yyvsp[-2]),(yyvsp[0]),'+');}
#line 1225 "y.tab.c" /* yacc.c:1646  */
    break;

  case 4:
#line 22 "exptree.y" /* yacc.c:1646  */
    {(yyval) = makeNode((yyvsp[-2]),(yyvsp[0]),'-');}
#line 1231 "y.tab.c" /* yacc.c:1646  */
    break;

  case 5:
#line 23 "exptree.y" /* yacc.c:1646  */
    {(yyval) = makeNode((yyvsp[-2]),(yyvsp[0]),'*');}
#line 1237 "y.tab.c" /* yacc.c:1646  */
    break;

  case 6:
#line 24 "exptree.y" /* yacc.c:1646  */
    {(yyval) = (yyvsp[-1]);}
#line 1243 "y.tab.c" /* yacc.c:1646  */
    break;

  case 7:
#line 25 "exptree.y" /* yacc.c:1646  */
    {(yyval) = (yyvsp[0]);printf("%d",atoi(ptr_string));}
#line 1249 "y.tab.c" /* yacc.c:1646  */
    break;


#line 1253 "y.tab.c" /* yacc.c:1646  */
      default: break;
    }
  /* User semantic actions sometimes alter yychar, and that requires
     that yytoken be updated with the new translation.  We take the
     approach of translating immediately before every use of yytoken.
     One alternative is translating here after every semantic action,
     but that translation would be missed if the semantic action invokes
     YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
     if it invokes YYBACKUP.  In the case of YYABORT or YYACCEPT, an
     incorrect destructor might then be invoked immediately.  In the
     case of YYERROR or YYBACKUP, subsequent parser actions might lead
     to an incorrect destructor call or verbose syntax error message
     before the lookahead is translated.  */
  YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);

  YYPOPSTACK (yylen);
  yylen = 0;
  YY_STACK_PRINT (yyss, yyssp);

  *++yyvsp = yyval;

  /* Now 'shift' the result of the reduction.  Determine what state
     that goes to, based on the state we popped back to and the rule
     number reduced by.  */

  yyn = yyr1[yyn];

  yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
  if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
    yystate = yytable[yystate];
  else
    yystate = yydefgoto[yyn - YYNTOKENS];

  goto yynewstate;


/*--------------------------------------.
| yyerrlab -- here on detecting error.  |
`--------------------------------------*/
yyerrlab:
  /* Make sure we have latest lookahead translation.  See comments at
     user semantic actions for why this is necessary.  */
  yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);

  /* If not already recovering from an error, report this error.  */
  if (!yyerrstatus)
    {
      ++yynerrs;
#if ! YYERROR_VERBOSE
      yyerror (YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
                                        yyssp, yytoken)
      {
        char const *yymsgp = YY_("syntax error");
        int yysyntax_error_status;
        yysyntax_error_status = YYSYNTAX_ERROR;
        if (yysyntax_error_status == 0)
          yymsgp = yymsg;
        else if (yysyntax_error_status == 1)
          {
            if (yymsg != yymsgbuf)
              YYSTACK_FREE (yymsg);
            yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
            if (!yymsg)
              {
                yymsg = yymsgbuf;
                yymsg_alloc = sizeof yymsgbuf;
                yysyntax_error_status = 2;
              }
            else
              {
                yysyntax_error_status = YYSYNTAX_ERROR;
                yymsgp = yymsg;
              }
          }
        yyerror (yymsgp);
        if (yysyntax_error_status == 2)
          goto yyexhaustedlab;
      }
# undef YYSYNTAX_ERROR
#endif
    }



  if (yyerrstatus == 3)
    {
      /* If just tried and failed to reuse lookahead token after an
         error, discard it.  */

      if (yychar <= YYEOF)
        {
          /* Return failure if at end of input.  */
          if (yychar == YYEOF)
            YYABORT;
        }
      else
        {
          yydestruct ("Error: discarding",
                      yytoken, &yylval);
          yychar = YYEMPTY;
        }
    }

  /* Else will try to reuse lookahead token after shifting the error
     token.  */
  goto yyerrlab1;


/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR.  |
`---------------------------------------------------*/
yyerrorlab:

  /* Pacify compilers like GCC when the user code never invokes
     YYERROR and the label yyerrorlab therefore never appears in user
     code.  */
  if (/*CONSTCOND*/ 0)
     goto yyerrorlab;

  /* Do not reclaim the symbols of the rule whose action triggered
     this YYERROR.  */
  YYPOPSTACK (yylen);
  yylen = 0;
  YY_STACK_PRINT (yyss, yyssp);
  yystate = *yyssp;
  goto yyerrlab1;


/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR.  |
`-------------------------------------------------------------*/
yyerrlab1:
  yyerrstatus = 3;      /* Each real token shifted decrements this.  */

  for (;;)
    {
      yyn = yypact[yystate];
      if (!yypact_value_is_default (yyn))
        {
          yyn += YYTERROR;
          if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
            {
              yyn = yytable[yyn];
              if (0 < yyn)
                break;
            }
        }

      /* Pop the current state because it cannot handle the error token.  */
      if (yyssp == yyss)
        YYABORT;


      yydestruct ("Error: popping",
                  yystos[yystate], yyvsp);
      YYPOPSTACK (1);
      yystate = *yyssp;
      YY_STACK_PRINT (yyss, yyssp);
    }

  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
  *++yyvsp = yylval;
  YY_IGNORE_MAYBE_UNINITIALIZED_END


  /* Shift the error token.  */
  YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);

  yystate = yyn;
  goto yynewstate;


/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here.  |
`-------------------------------------*/
yyacceptlab:
  yyresult = 0;
  goto yyreturn;

/*-----------------------------------.
| yyabortlab -- YYABORT comes here.  |
`-----------------------------------*/
yyabortlab:
  yyresult = 1;
  goto yyreturn;

#if !defined yyoverflow || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here.  |
`-------------------------------------------------*/
yyexhaustedlab:
  yyerror (YY_("memory exhausted"));
  yyresult = 2;
  /* Fall through.  */
#endif

yyreturn:
  if (yychar != YYEMPTY)
    {
      /* Make sure we have latest lookahead translation.  See comments at
         user semantic actions for why this is necessary.  */
      yytoken = YYTRANSLATE (yychar);
      yydestruct ("Cleanup: discarding lookahead",
                  yytoken, &yylval);
    }
  /* Do not reclaim the symbols of the rule whose action triggered
     this YYABORT or YYACCEPT.  */
  YYPOPSTACK (yylen);
  YY_STACK_PRINT (yyss, yyssp);
  while (yyssp != yyss)
    {
      yydestruct ("Cleanup: popping",
                  yystos[*yyssp], yyvsp);
      YYPOPSTACK (1);
    }
#ifndef yyoverflow
  if (yyss != yyssa)
    YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
  if (yymsg != yymsgbuf)
    YYSTACK_FREE (yymsg);
#endif
  return yyresult;
}
Example #8
0
tree
rewrite_impl (tree t) {
    switch (L(t)) {
    case EXTERN:
    {
        int i, n= N(t);
        tree r (TUPLE, n);
        for (i=0; i<n; i++)
            r[i]= evaluate (t[i]);
        object expr= null_object ();
        for (i=n-1; i>0; i--)
            expr= cons (object (r[i]), expr);
        string fun= evaluate_string (t[0]);
        expr= cons (string_to_object (fun), expr);
        bool secure= as_bool (std_env ["secure"]);
        if (!secure && script_status < 2) {
            if (!as_bool (call ("secure?", expr)))
                return tree (ERROR, "insecure script");
        }
        environment old_env= reenter_rewrite_env;
        reenter_rewrite_env= std_env;
        object o= eval (expr);
        reenter_rewrite_env= old_env;
        return content_to_tree (o);
    }
#ifdef CLASSICAL_MACRO_EXPANSION
    case MAP_ARGS:
    {
        if (!(is_atomic (t[0]) && is_atomic (t[1]) && is_atomic (t[2])))
            return evaluate_error ("invalid map-args");
        if (macro_top_level (std_env))
            return evaluate_error ("undefined", t[2]);
        basic_environment local= macro_arguments (std_env);
        int key= make_tree_label (t[2]->label);
        if (!local->contains (key))
            return evaluate_error ("undefined", t[2]);
        tree v= local [key];
        if (is_atomic (v))
            return evaluate_error ("invalid-map-args");
        macro_up (std_env);

        int start= 0, end= N(v);
        if (N(t)>=4) start= as_int (evaluate (t[3]));
        if (N(t)>=5) end  = as_int (evaluate (t[4]));
        int i, n= max (0, end-start);
        tree r (make_tree_label (t[1]->label), n);
        for (i=0; i<n; i++)
            r[i]= tree (make_tree_label (t[0]->label),
                        tree (ARG, copy (t[2]), as_string (start+i)),
                        as_string (start+i));

        macro_redown (std_env, local);
        return r;
    }
#endif // CLASSICAL_MACRO_EXPANSION
    case VAR_INCLUDE:
    {
        url base_file_name (as_string (std_env ["base-file-name"]));
        url file_name= url_system (evaluate_string (t[0]));
        return load_inclusion (relative (base_file_name, file_name));
    }
    case REWRITE_INACTIVE:
    {
#ifdef CLASSICAL_MACRO_EXPANSION
        if ((!is_func (t[0], ARG)) || is_compound (t[0][0]))
            return evaluate_error ("invalid rewrite-inactive");
        if (macro_top_level (std_env))
            return evaluate_error ("undefined", t[0][0]);
        basic_environment local= macro_arguments (std_env);
        int key= make_tree_label (t[0][0]->label);
        if (!local->contains (key))
            return evaluate_error ("undefined", t[0][0]);
        tree val= local [key];
        int i, n= N(t[0]);
        for (i=1; i<n; i++) {
            int j= as_int (t[0][i]);
            if ((j>=0) && (j<N(val))) val= val[j];
            else return evaluate_error ("invalid rewrite-inactive");
        }
#else
        tree val= t[0];
#endif
        int inactive_mode= INACTIVE_INLINE_RECURSE;
        if (t[1] == "recurse") inactive_mode= INACTIVE_INLINE_RECURSE;
        else if (t[1] == "recurse*") inactive_mode= INACTIVE_BLOCK_RECURSE;
        else if (t[1] == "once") inactive_mode= INACTIVE_INLINE_ONCE;
        else if (t[1] == "once*") inactive_mode= INACTIVE_BLOCK_ONCE;
        else if (t[1] == "error") inactive_mode= INACTIVE_INLINE_ERROR;
        else if (t[1] == "error*") inactive_mode= INACTIVE_BLOCK_ERROR;
        return rewrite_inactive (val, inactive_mode);
    }
    default:
        return t;
    }
}
Example #9
0
 double doubleValue() const override
 {
     return evaluate(m_leftSide->doubleValue(), m_rightSide->doubleValue());
 }
Example #10
0
/*---IT USES LIST FOR KEEPING TOKENS---*/
int add_var(char exp[],int ret)		
{
	int i=0;
	float eval_ans;		//to store answer of evaluation expression
	char eval[20];
	char var_name[MAXNAME];		//VARIABLE NAME SHOULD NOT EXCEED MAXNAME.
	List infix_list;		//INFIX TOKENS
	List postfix_list;		//POSTFIX TOKENS
	
	// HEADER ASSUMED FOR LIST MANIPULATION
	infix_list = malloc(sizeof(struct node));	
	postfix_list = malloc(sizeof(struct node));

	if(infix_list == NULL || postfix_list == NULL)	//ERROR CHECK FOR MALLOC
	{
		printf("\nmemory not enough\n");
		exit(1000);
	}

	infix_list->Next = NULL;
	postfix_list->Next = NULL;

	if(check_assign(exp)==1)	//if '=' is there
	{
		/*store variable name*/
		i=0;
		int sp_val=0;	//to account for end of var_name and only spaces left
		char *tmp;	//to account for the knowledge of var_name end except for leftover spaces
		while(*exp==' ' || *exp=='\t')
			exp++;
		while(*exp!='=')
		{
			/*to remove all the spaces once the variable name ends i do this*/
			{
				tmp = exp;
				while(*tmp!='=')
				{
					if(*tmp!=' ')
						break;
					tmp++;
				}
				if(*tmp == '=')
				{
					sp_val=1;
					while(*exp!='=')
						exp++;
				}
			}

			if(sp_val != 1)
			{
			if(i==29)	/*the var_nmae is exceeding limit,TRUNCATE*/
			{
			 	while(*exp!='=')
					exp++;
				break;
			}
			
			else
			{

			var_name[i] = *exp;
			exp++;
			i++;
			}//else
			
			}//if(sp_val)
		}//while

		exp++;
		var_name[i]='\0';
	
		
		if(check_evaluate(exp)==1)
		{
			/*carry out evaluation*/
			Createlist(exp,infix_list);

			infix_to_postfix(infix_list,postfix_list);

			eval_ans = evaluate(postfix_list);
			
			add_lexicon(var_name,0,eval_ans,NULL);
		
		}//check_evaluate

		else
		{
			/*string value,just add it.*/
			add_lexicon(var_name,0,1,exp);
		}

	}//check_assign

	else
	{
		/*no variable to assign*/
		if(check_evaluate(exp)==1)
		{
			Createlist(exp,infix_list);
			infix_to_postfix(infix_list,postfix_list);
			eval_ans = evaluate(postfix_list);	
		
			/*ret = 0,implies that return ans on terminal,
			else it implies return the answer to program*/

			if(ret == 0)
			{
				printf("%f\n",eval_ans);
			}
			else
			{
				return eval_ans;
			}
		}
	}//else
	return ret;
}
Example #11
0
tree
evaluate_rewrite (tree t) {
    return evaluate (rewrite (t));
}
Example #12
0
bool
BlobValue::evaluate(const BlobValue &other, CSSM_DB_OPERATOR op) const
{
	return evaluate(*this, other, op, Comparator());
}
Example #13
0
JSValue profiledEvaluate(ExecState* exec, ProfilingReason reason, const SourceCode& source, JSValue thisValue, NakedPtr<Exception>& returnedException)
{
    ScriptProfilingScope profilingScope(exec->vmEntryGlobalObject(), reason);
    return evaluate(exec, source, thisValue, returnedException);
}
Example #14
0
FEScalar State::evaluate(const expression * e,const Environment & bs) const
{
	if(dynamic_cast<const div_expression *>(e))
	{
		return evaluate(dynamic_cast<const div_expression*>(e)->getLHS(),bs) /
				evaluate(dynamic_cast<const div_expression*>(e)->getRHS(),bs);
	};

	if(dynamic_cast<const minus_expression *>(e))
	{
		return evaluate(dynamic_cast<const minus_expression*>(e)->getLHS(),bs) -
				evaluate(dynamic_cast<const minus_expression*>(e)->getRHS(),bs);
	};



	if(dynamic_cast<const mul_expression *>(e))
	{
		return evaluate(dynamic_cast<const mul_expression*>(e)->getLHS(),bs) *
				evaluate(dynamic_cast<const mul_expression*>(e)->getRHS(),bs);
	};

	if(dynamic_cast<const plus_expression *>(e))
	{
		return evaluate(dynamic_cast<const plus_expression*>(e)->getLHS(),bs) +
				evaluate(dynamic_cast<const plus_expression*>(e)->getRHS(),bs);
	};

	if(dynamic_cast<const num_expression*>(e))
	{
		return dynamic_cast<const num_expression*>(e)->double_value();
	};
	
	if(dynamic_cast<const uminus_expression*>(e))
	{
		return -(evaluate(dynamic_cast<const uminus_expression*>(e)->getExpr(),bs));
	};

	if(dynamic_cast<const func_term*>(e))
	{
		const FuncExp * fexp = vld->fef.buildFuncExp(dynamic_cast<const func_term*>(e),bs);
    return fexp->evaluate(this);
		//if(feValue.find(fexp) != feValue.end())
			//return feValue.find(fexp)->second;
   /*
		if(LaTeX)
		{
			*report << "\\error{Attempt to access undefined expression: " << *fexp << "}\n";
		}
		else if(Verbose) cout << "Attempt to inspect undefined value: " << *fexp << "\n";
		 */
		//BadAccessError bae;
		//throw bae;
	};

	if(const special_val_expr * sp = dynamic_cast<const special_val_expr *>(e))
	{
		if(sp->getKind() == E_TOTAL_TIME)
		{
				if(vld->durativePlan()) return time;
				return vld->simpleLength();
		};

		if(sp->getKind() == E_DURATION_VAR)
		{
			return bs.duration;
		};

		if(sp->getKind() == E_HASHT)

		{
			if(LaTeX)
				*report << "The use of \\#t is not valid in this context!\n";
			else if(Verbose)
				cout << "The use of #t is not valid in this context!\n";
			SyntaxTooComplex stc;
			throw stc;
		}

	};

	if(const violation_term * vt = dynamic_cast<const violation_term *>(e))
	{
		return vld->violationsFor(vt->getName());
	};

	UnrecognisedCondition uc;
	throw uc;
};
Example #15
0
		value_container binary_op::get_value(evaluation_context errors, value_type type) const {
			return evaluate(errors)->get_value(errors, type);
		}
Example #16
0
 double computeLengthPx(const CSSToLengthConversionData& conversionData) const override
 {
     const double leftValue = m_leftSide->computeLengthPx(conversionData);
     const double rightValue = m_rightSide->computeLengthPx(conversionData);
     return evaluate(leftValue, rightValue);
 }
Example #17
0
bool COptMethodPraxis::optimise()
{
  if (!initialize()) return false;

  C_INT i;
  C_INT prin = 0;
  C_FLOAT64 tmp = 0.0;
  C_FLOAT64 machep, stepmx, d1, d2;

  // initial point is the first guess but we have to make sure that
  // we are within the parameter domain

  for (i = 0; i < mVariableSize; i++)
    {
      const COptItem & OptItem = *(*mpOptItem)[i];
      mCurrent[i] = OptItem.getStartValue();

      //force it to be within the bounds
      switch (OptItem.checkConstraint(mCurrent[i]))
        {
          case - 1:
            mCurrent[i] = *OptItem.getLowerBoundValue();
            break;

          case 1:
            mCurrent[i] = *OptItem.getUpperBoundValue();
            break;
        }

      //set the value
      *mContainerVariables[i] = (mCurrent[i]);
    }

  // Report the first value as the current best
  mBestValue = evaluate();
  mBest = mCurrent;
  mContinue = mpOptProblem->setSolution(mBestValue, mBest);

  // We found a new best value lets report it.
  mpParentTask->output(COutputInterface::DURING);

  //estimate the machine epsilon
  d1 = 1.0;

  do
    {
      d1 /= 2.0;
      d2 = d1 + 1.;
    }
  while (d2 != 1.0);

  machep = d1 * 2.0;

  //estimate the maximum step size
  stepmx = 0.6;

  //carry out the minimisation
  try
    {
      mpCPraxis->praxis_(&mTolerance, &machep, &stepmx, &mVariableSize, &prin, mCurrent.array(), mpPraxis, &tmp);
    }
  catch (bool)
    {}

  return true;
}
Example #18
0
int main(int argc,char * argv[])
{
	int rank,size,i;
	MPI_Init(&argc,&argv);
	MPI_Comm_rank(MPI_COMM_WORLD,&rank);
	MPI_Comm_size(MPI_COMM_WORLD,&size);
	if(rank==0)
	{
		if(!readFromFile())
			exit(-1);
		if(size>2*variableNum)
		{
			printf("Too many Processors,reduce your -np value \n");
			MPI_Abort(MPI_COMM_WORLD,1);
		}
		beginTime=MPI_Wtime();
		for(int i=1;i<size;i++)
		{
		MPI_Send(&variableNum,1,MPI_INT,i,V_TAG,MPI_COMM_WORLD);
		MPI_Send(p,variableNum*2,MPI_DOUBLE,i,P_TAG,MPI_COMM_WORLD);
		}
		
		addTransTime(MPI_Wtime()-beginTime);
	}
	else
	{
	    MPI_Recv(&variableNum,1,MPI_INT,0,V_TAG,MPI_COMM_WORLD,&status);
	    MPI_Recv(p,variableNum*2,MPI_DOUBLE,0,P_TAG,MPI_COMM_WORLD,&status);
	}
	int wLength=2*variableNum;
	for(i=0;i<wLength;i++)
	{
		w[i].real=cos(i*2*PI/wLength);
		w[i].imag=sin(i*2*PI/wLength);
	}
	int everageLength=wLength/size;
	int moreLength=wLength%size;
	int startPos=moreLength+rank*everageLength;
	int stopPos=startPos+everageLength-1;
	if(rank==0)
	{
		startPos=0;
		stopPos=moreLength+everageLength-1;
	}
	evaluate(p,0,variableNum-1,w,s,startPos,stopPos,wLength);
       
	if(rank>0)
	{
		MPI_Send(s+startPos,everageLength*2,MPI_DOUBLE,0,S_TAG,MPI_COMM_WORLD);
		MPI_Recv(s,wLength*2,MPI_DOUBLE,0,S_TAG2,MPI_COMM_WORLD,&status);
	}
	else
	{
		double tempTime=MPI_Wtime();
		for(i=1;i<size;i++)
		{
			MPI_Recv(s+moreLength+i*everageLength,everageLength*2,MPI_DOUBLE,i,S_TAG,MPI_COMM_WORLD,&status);
		}
		for(i=1;i<size;i++)
		{
			MPI_Send(s,wLength*2,MPI_DOUBLE,i,S_TAG2,MPI_COMM_WORLD);
		}
	      printf("The final results :\n");
	      printres(s,wLength);
		addTransTime(MPI_Wtime()-tempTime);
	}	
	if(rank==0)
	{
	        totalTime=MPI_Wtime();
	        totalTime-=beginTime;
		printf("\nUse prossor size=%d\n",size);
		printf("Total running time=%f(s)\n",totalTime);
		printf("Distribute data time = %f(s)\n",transTime);
		printf("Parallel compute time = %f(s)\n ",totalTime-transTime);
	}
	MPI_Finalize();
	return 0;
}
Example #19
0
void Kludget::messageReceived(QString message, QString id, QString instance)
{
	if (instance != "") {
		if (info.instance != instance)
			return;
	}

    if (message == "ping") {
        ipcClient.sendMessage("pong", info.id, info.instance);
        return;
    }

    KLog::log(QString("kludget messageReceived: %1").arg(message));
    
    int messageId = message.toUInt();
    switch (messageId)
    {
    case KIPC::ShowHUD:
    {
        window->moveToTop();
        //window->updateMouseIgnore(false);
        break;
    }
    case KIPC::HideHUD:
    {
		//window->applySettings();
        window->moveToBottom();
        break;
    }
    case KIPC::ShowWindow:
    {
        show();
		window->moveToTop();
		window->applySettings();
        break;
    }
    case KIPC::HideWindow:
    {
        hide();
        break;
    }
    case KIPC::LowerWindow:
    {
        window->lower();
        break;
    }
    case KIPC::SettingsChanged:
    {
        onSettingsChanged();
        break;
    }
	case KIPC::ShowOptions:
	{
		onContextMenu();
		break;
	}
	case KIPC::Configure:
    {
        configure();
        break;
    }
    default:

        evaluate(message);
        break;
    }
}
Example #20
0
int qsearch(s_search_info *info, s_stack *stack, s_board *board, int alpha, int beta)
{
    assert(info != NULL);
    assert(stack != NULL);
    assert(board != NULL);
    assert(alpha < beta);

    int stand_pat = evaluate(board);

    if(stack->ply > info->seldepth)
    {
        info->seldepth = stack->ply-1;
    }

    if(stand_pat >= beta)
    {
        return beta;
    }

#ifdef DELTA_PRUNING
    const int safety = 900; // The value of a queen

    if(stand_pat < alpha - safety && !is_endgame(board))
    {
        return alpha;
    }
#endif

    if(stand_pat > alpha)
    {
        alpha = stand_pat;
    }

    if(stack->ply >= MAX_DEPTH)
    {
        return stand_pat;
    }

    // Set old permissions
    s_irreversible permissions;
    store_irreversible(&permissions, board);

    s_move moves[MAX_MOVES];
    int num_moves = find_moves_captures(board, moves, board->turn);
#ifdef SORT_MOVES
    moves_sort_see(board, moves, num_moves);
#endif

    for(int m = 0; m < num_moves; ++m)
    {
        int val = see_capture(board, moves[m]);
        if(val < -50)
        {
            break;
        }

        move_make(board, &moves[m]);

        if(square_attacked(board, board->pieces[KINGS]&board->colour[!board->turn], board->turn))
        {
            // Restore old permissions
            restore_irreversible(&permissions, board);

            move_undo(board, &moves[m]);
            continue;
        }

        info->nodes++;

        int score = -qsearch(info, stack+1, board, -beta, -alpha);

        // Restore old permissions
        restore_irreversible(&permissions, board);

        move_undo(board, &moves[m]);

        if(score >= beta)
        {
#ifndef NDEBUG
            info->num_cutoffs[m]++;
#endif
            return beta;
        }

        if(score > alpha)
        {
            alpha = score;
        }
    }

    return alpha;
}
Example #21
0
int main()
{
   evaluate( cout_ << "hello" << ", " << "world\n");
   return 0;
}
Example #22
0
int main(int argc, char** argv){//[number of Distinct Inputs][file size][random seed] [num of superOptruns] [num of EvalRuns]
//	char input[] = {'\x00','\x01','\x02','\x03','\x04'};
//	char input[] = {'A','C','G','T','N'};
	int i,j,k;
	int maxNumDistInputs = 200;//input size exceeding 200 causes our naive unique number generator to be extremely slow, exceeding 256
				//breaks the number generator

	int superOptRuns = atoi(argv[4]);
	int evalRuns = atoi(argv[5]);
	int numDataForms = 2; //runTime, evalTime
	
	unsigned char * input;
	unsigned char * output;
	int numDistInputs;
	double runTimes[superOptRuns];
	double evalTimes[evalRuns];
	int maxNumOps = 6;
	long fileSize = atoi(argv[2]);
	
	if(argc != 6){
		printf("Bad arguments");
		return -1;
	}
	if(atoi(argv[1]) >= maxNumDistInputs){
		printf("numDistInputs too large for unique random number generator");
		return -1;
	}
	 
	numDistInputs = atoi(argv[1]);
	input = calloc(sizeof(char),numDistInputs);
	output = calloc(sizeof(char),numDistInputs);

// Random Input Generator // // // // // // // // //	
	srand(atoi(argv[3]));
	for(i=0;i<numDistInputs;++i){
		input[i] = rand()%255;
		for(j=0;j<i;++j){
			if(input[i] == input[j]){
				--i;
				break;
			}
		}
	}
// // // // // // // // // // // // // // // // // 
	char opsSeq [maxNumOps];
	char opRep [maxNumOps];
	int numSeq [maxNumOps] ;
	for(i = 0; i < maxNumOps; ++i){
		opsSeq[i] = add;
		numSeq[i] = 0;
	}
	char * testBuf = malloc(fileSize*sizeof(char));
	srand(time(0));
	for(i=0;i<fileSize;++i){
		testBuf[i] = input[rand()%numDistInputs];
	}
	int success = -1;
	struct timeval time0,time1;
	for(i=0;i<superOptRuns;i++){
		gettimeofday(&time0,NULL);
		success = superOptimizer(input, input, numDistInputs, maxNumOps, maxNumOps, opsSeq, numSeq);
		gettimeofday(&time1,NULL);
		double runTime = (time1.tv_sec-time0.tv_sec)*1000000LL + time1.tv_usec - time0.tv_usec;
		runTimes[i] = runTime;
	}
	int numOps = 0;
	for(i=0;i<maxNumOps;++i){
		if(numSeq[i] != 0){
			opRep[i] = operations[opsSeq[i]];
			++numOps;
		}else{
			opRep[i] = ' ';
		}
	}
	
	for(i=0;i<evalRuns;i++){
		gettimeofday(&time0,NULL);
		for(j = 0; j < fileSize; ++j){
			evaluate(testBuf[j], opsSeq, numSeq, maxNumOps, numOps);
		}
		gettimeofday(&time1,NULL);
		double evalTime = (time1.tv_sec-time0.tv_sec)*1000000LL + time1.tv_usec - time0.tv_usec;
		evalTimes[i] = evalTime;
	}
	free(testBuf);	

	for(i=0; i < numDistInputs; ++i){
		output[i] = evaluate(input[i], opsSeq, numSeq,maxNumOps, numOps);
	}

	
	double *timeArray[numDataForms];
	char *labelArray[numDataForms];	
	timeArray[0] = runTimes;
	timeArray[1] = evalTimes;
	
	labelArray[0] = "RunTimes";
	labelArray[1] = "EvalTimes";
	
	int numLabels= sizeof(labelArray)/sizeof(char*); 
	
	int runsArray[numDataForms];
	runsArray[0] = superOptRuns; 
	runsArray[1] = evalRuns; 
	
	if(write_super_file(timeArray, labelArray, numLabels, runsArray, opRep, numSeq, maxNumOps, input, output, numDistInputs) < 0)
		printf("error writing data file\n"); 
		
	free(input);
	free(output);


//	int numOps = 0;
//	for(i = 0; i<maxNumOps; ++i){
//		if(numSeq[i] != 0) ++numOps;
//	}


/***************************************************************************
* Uncomment the following code to display the discovered operation sequence
****************************************************************************/

//	if(success == 0){
//		printf("Sequence Found: \n");
//		int i, j;
//		printf("%s%d\n", "Number of Operations: ", numOps);
//		for(i=0;i < numOps; ++i){
//			printf("%d%c ",i,':');
//			int opit = maxNumOps - numOps + i;
//			if(opsSeq[opit] == '1') numSeq[opit] = ~numSeq[opit];
//			printf("%c %d",operations[opsSeq[opit]], numSeq[opit]);
//			printf("\n");
//		}
//	} else printf("no sequence found");
//	return success;
	return 0;
}
Example #23
0
void GA::run() {

  fits = new double[num_pop];

  // set up grid
  // centers must be > 8*R apart
  double interval = 8.001 * wfle.scenario.R;

  int nx = (int) wfle.scenario.width / interval;
  int ny = (int) wfle.scenario.height / interval;

  // get number of valid grid spots
  nt=0;
  for (int x=0; x<nx; x++) {
    for (int y=0; y<ny; y++) {
      double xpos = x*interval;
      double ypos = y*interval;
      bool valid = true;

      for (unsigned int o=0; o<wfle.scenario.obstacles.rows; o++) {
        double xmin = wfle.scenario.obstacles.get(o, 0);
        double ymin = wfle.scenario.obstacles.get(o, 1);
        double xmax = wfle.scenario.obstacles.get(o, 2);
        double ymax = wfle.scenario.obstacles.get(o, 3);
        if (xpos>xmin && ypos>ymin && xpos<xmax && ypos<ymax) {
          valid = false;
	  }
      }
      if (valid) {
        nt++;
      }
    }
  }

  grid = new Matrix<double>(nt, 2);
  int t = 0;
  for (int x=0; x<nx; x++) {
    for (int y=0; y<ny; y++) {
      double xpos = x*interval;
      double ypos = y*interval;
      bool valid = true;

      for (unsigned int o=0; o<wfle.scenario.obstacles.rows; o++) {
        double xmin = wfle.scenario.obstacles.get(o, 0);
        double ymin = wfle.scenario.obstacles.get(o, 1);
        double xmax = wfle.scenario.obstacles.get(o, 2);
        double ymax = wfle.scenario.obstacles.get(o, 3);
        if (xpos>xmin && ypos>ymin && xpos<xmax && ypos<ymax) {
          valid = false;
        }
      }
      if (valid) {
        grid->set(t, 0, x*interval);
        grid->set(t, 1, y*interval);
        t++;
      }
    }
  }

  // initialize populations
  pops = new Matrix<int>(nt, num_pop);

  for (int p=0; p<num_pop; p++) {
    for (int i=0; i<nt; i++) {
      int turb = 0;
      double randbit = (double) rand()/RAND_MAX;
      if (randbit > 0.5) {
        turb = 1;
      }
      pops->set(i, p, turb);
    }
  }

  // evaluate initial populations (uses num_pop evals)
  evaluate();

  // GA
  for (int i=0; i<(1000/num_pop); i++) {

    // rank populations (tournament)
    int num_winners = num_pop/tour_size;
    int winners [num_winners];
    int competitors [num_pop];
    for (int c=0; c<num_pop; c++) {
      competitors[c] = c;
    }

    for (int c=0; c<num_pop; c++) {
      int index = rand() % (c+1);
      int temp = competitors[index];
      competitors[index] = competitors[c];
      competitors[c] = temp;
    }


    for (int t=0; t<num_winners; t++) {
      int winner = -1;
      double winner_fit = std::numeric_limits<double>::max();
      for (int c=0; c<tour_size; c++) {
        int competitor = competitors[tour_size*t + c];
        if (fits[competitor] < winner_fit) {
          winner = competitor;
          winner_fit = fits[winner];
        }
      }
      winners[t] = winner;
    }

    // crossover
    // check row,col
    Matrix<int>* children = new Matrix<int>(nt, num_pop);

    for (int c=0; c<(num_pop-num_winners); c++) {
      int s1 = rand() % num_winners;
      int s2 = rand() % (num_winners-1);
      if (s2 >= s1) {
        s2++;
      }
      int p1 = winners[s1];
      int p2 = winners[s2];

      for (int j=0; j<nt; j++) {
        if ((double)rand()/RAND_MAX < cross_rate) {
          children->set(j,c,pops->get(j,p1));
        } else {
          children->set(j,c,pops->get(j,p2));
        }
      }
    }

    // mutate
    for (int c=0; c<(num_pop-num_winners); c++) {
      for (int j=0; j<nt; j++) {
        if ((double)rand()/RAND_MAX < mut_rate) {
          children->set(j,c,1-children->get(j,c));
        }
      }
    }

    // elitism
    for (int c=0; c<num_winners; c++) {
      for (int j=0; j<nt; j++) {
        children->set(j, num_pop-num_winners+c, pops->get(j,winners[c]));
      }
    }

    for (int c=0; c<num_pop; c++) {
      for (int j=0; j<nt; j++) {
        pops->set(j, c, children->get(j, c));
      }
    }

    // evaluate
    evaluate();
    delete children;
  }
}
Example #24
0
int main(int argc, char **argv)
{
  char* attributeFile = 0;
  bool verbose = false;
  int seqGroup = 0;
  int seqElement = 0;

  int group = 0;
  int element = 0;
  char* language = "";		// Language of messages for evaluation
  int level = 1;		// Level 1 is errors only

  while (--argc > 0 && (*++argv)[0] == '-') {
    switch (*(argv[0] + 1)) {
    case 'l':
      argc--; argv++;
      if (argc < 1)
	usage();
      level = atoi(*argv);
      if (level > 2)
	verbose = true;
      break;
    case 'L':
      argc--;
      argv++;
      if (argc < 1)
	usage();
      language = *argv;
      break;
    case 's':
      argc--;
      argv++;
      if (argc < 2)
	usage();
      if (::sscanf(*argv, "%x", &seqGroup) != 1) {
	cerr << "Unable to scan group: " << *argv << endl;
	usage();
      }
      argc--; argv++;
      if (::sscanf(*argv, "%x", &seqElement) != 1) {
	cerr << "Unable to scan element: " << *argv << endl;
	usage();
      }
      break;
    case 'v':
      verbose = true;
      level = 3;
      break;
    default:
      break;
    }
  }

  if (argc < 5)
    usage();

  if (::sscanf(argv[0], "%x", &group) != 1) {
    cerr << "Unable to scan group: " << argv[0] << endl;
    usage();
  }

  if (::sscanf(argv[1], "%x", &element) != 1) {
    cerr << "Unable to scan group: " << argv[1] << endl;
    usage();
  }
  DCM_TAG tag = DCM_MAKETAG(group, element);
  DCM_TAG seqTag = DCM_MAKETAG(seqGroup, seqElement);

  MString maskName(argv[2]);
  
  MStringVector testFiles;
  fillFileVector(testFiles, argv[3]);
  MStringVector stdFiles;
  fillFileVector(stdFiles, argv[4]);

  if (stdFiles.size() != testFiles.size()) {
    cout << "ERR: The number of responses in the test directory (" << argv[3] << ")" << endl
	 << "ERR:  does not match responses in the std directory (" << argv[4] << ")" << endl;
    cout << "ERR:  The counts are: " << testFiles.size() << " and "
	  << stdFiles.size() << endl;

    return 1;
  }

  int rtnStatus = 0;
  int evaluationCount = stdFiles.size();
  int failureCount = 0;

  MStringMap testMap;
  MStringMap stdMap;
  fillMap(testMap, testFiles, seqTag, tag);
  fillMap(stdMap, stdFiles, seqTag, tag);

  MStringMap::iterator it = stdMap.begin();
  for (it; it != stdMap.end(); it++) {
    MString key = (*it).first;

    MString stdFile = (*it).second;
    MString tstFile = testMap[key];

    if (verbose)
      cout << key << " " << tstFile << " " << stdFile << endl;

    int testStatus = evaluate(tstFile, stdFile, maskName, verbose, level, language);
    if (testStatus != 0) {
      cout << "ERR: C-Find resp evaluate failed for: " << tstFile << endl;
      rtnStatus = 1;
      failureCount++;
    }
  }

  return rtnStatus;
}
Example #25
0
union tree *
evaluate(union tree *tr, const struct rt_tess_tol *ttol, const struct bn_tol *tol)
{
    RT_CK_TREE(tr);

    switch (tr->tr_op) {
	case OP_NOP:
	    return tr;
	case OP_NMG_TESS:
	    /* ugh, keep it as nmg_tess and just shove the rt_bot_internal ptr
	     * in as nmgregion. :/ Also, only doing the first shell of the first
	     * model. Primitives should only provide a single shell, right? */
	    {
		struct rt_db_internal ip;
		struct nmgregion *nmgr = BU_LIST_FIRST(nmgregion, &tr->tr_d.td_r->m_p->r_hd);
		/* the bot temporary format may be unnecessary if we can walk
		 * the nmg shells and generate soup from them directly. */
		struct rt_bot_internal *bot = nmg_bot(BU_LIST_FIRST(shell, &nmgr->s_hd), tol);

		/* causes a crash.
		   nmg_kr(nmgr);
		   free(nmgr);
		*/

		tr->tr_d.td_r->m_p = (struct model *)bot2soup(bot, tol);
		SOUP_CKMAG((struct soup_s *)tr->tr_d.td_r->m_p);

		/* fill in a db_internal with our new bot so we can free it */
		RT_DB_INTERNAL_INIT(&ip);
		ip.idb_major_type = DB5_MAJORTYPE_BRLCAD;
		ip.idb_minor_type = ID_BOT;
		ip.idb_meth = &OBJ[ID_BOT];
		ip.idb_ptr = bot;
		ip.idb_meth->ft_ifree(&ip);
	    }
	    return tr;
	case OP_UNION:
	case OP_INTERSECT:
	case OP_SUBTRACT:
	    RT_CK_TREE(tr->tr_b.tb_left);
	    RT_CK_TREE(tr->tr_b.tb_right);
	    tr->tr_b.tb_left = evaluate(tr->tr_b.tb_left, ttol, tol);
	    tr->tr_b.tb_right = evaluate(tr->tr_b.tb_right, ttol, tol);
	    RT_CK_TREE(tr->tr_b.tb_left);
	    RT_CK_TREE(tr->tr_b.tb_right);
	    SOUP_CKMAG(tr->tr_b.tb_left->tr_d.td_r->m_p);
	    SOUP_CKMAG(tr->tr_b.tb_right->tr_d.td_r->m_p);
	    split_faces(tr->tr_b.tb_left, tr->tr_b.tb_right, tol);
	    RT_CK_TREE(tr->tr_b.tb_left);
	    RT_CK_TREE(tr->tr_b.tb_right);
	    SOUP_CKMAG(tr->tr_b.tb_left->tr_d.td_r->m_p);
	    SOUP_CKMAG(tr->tr_b.tb_right->tr_d.td_r->m_p);
	    break;
	default:
	    bu_bomb("bottess evaluate(): bad op (first pass)\n");
    }

    switch (tr->tr_op) {
	case OP_UNION:
	    return compose(tr->tr_b.tb_left, tr->tr_b.tb_right, OUTSIDE, SAME, OUTSIDE);
	case OP_INTERSECT:
	    return compose(tr->tr_b.tb_left, tr->tr_b.tb_right, INSIDE, SAME, INSIDE);
	case OP_SUBTRACT:
	    return invert(compose(tr->tr_b.tb_left, invert(tr->tr_b.tb_right), OUTSIDE, OPPOSITE, INSIDE));
	default:
	    bu_bomb("bottess evaluate(): bad op (second pass, CSG)\n");
    }
    bu_bomb("Got somewhere I shouldn't have\n");
    return NULL;
}
/*
 * Alpha/Beta search
 *
 * - first, start with principal variation
 * - depending on depth, we only do depth search for some move types
 */
int ABIDStrategy::alphabeta(int depth, int alpha, int beta)
{
	int currentValue = -14999+depth, value;
	Move m;
	Move bestMove;
	MoveList list;
	bool depthPhase, doDepthSearch;
	int i=0;
	int movecounter =-1;
	int flag=0;

	/* We make a depth search for the following move types... */
	int maxType = (depth < _currentMaxDepth-1)  ? Move::maxMoveType :
		(depth < _currentMaxDepth)    ? Move::maxPushType :
		Move::maxOutType;

	_board->generateMoves(list);

	if (_sc && _sc->verbose()) {
		char tmp[100];
		sprintf(tmp, "Alpha/Beta [%d;%d], %d moves (%d depth)", alpha, beta,
				list.count(Move::none), list.count(maxType));
		_sc->startedNode(depth, tmp);
	}

	/* check for an old best move in principal variation */
	if (_inPV) {
		m = _pv[depth];

		if ((m.type != Move::none) &&
				(!list.isElement(m, 0, true)))
			m.type = Move::none;

		if (m.type == Move::none) _inPV = false;
	}

	// first, play all moves with depth search
	depthPhase = true;

	while (1) {

		movecounter++;
		// get next move
		if (m.type == Move::none) {
			if (depthPhase)
				depthPhase = list.getNext(m, maxType);
			if (!depthPhase)
				if (!list.getNext(m, Move::none)) break;
		}
		if((thread_rank == movecounter% num_threads) || (depth>0))// we could start with a non-depth move from principal variation
		{
			doDepthSearch = depthPhase && (m.type <= maxType);

			_board->playMove(m);

			/* check for a win position first */
			if (!_board->isValid()) {

				/* Shorter path to win position is better */
				value = 14999-depth;
			}
			else {

				if (doDepthSearch) {
					/* opponent searches for its maximum; but we want the
					 * minimum: so change sign (for alpha/beta window too!)
					 */
					value = -alphabeta(depth+1, -beta, -alpha);
				}
				else {
					value = evaluate();
				}
			}

			_board->takeBack();

			/* best move so far? */
			if (value > currentValue) {
				currentValue = value;
				_pv.update(depth, m);

				if (_sc) _sc->foundBestMove(depth, m, currentValue);
				if (depth == 0)
					_currentBestMove = m;

				/* alpha/beta cut off or win position ... */
				if (currentValue>14900 || currentValue >= beta) {
					if (_sc) _sc->finishedNode(depth, _pv.chain(depth));
					flag = 1;
					break;
					//return currentValue;
				}

				/* maximize alpha */
				if (currentValue > alpha) alpha = currentValue;
			}
		}
		if (_stopSearch) break; // depthPhase=false;
		m.type = Move::none;
	}



	if(depth == 0){
		//all threads send value to thread 0
		if(thread_rank == 0)
		{
			Move *moves=NULL;
			Variation *PVs=NULL;
			int *eval_results;
			PVs=(Variation*)malloc((num_threads -1)*sizeof(Variation));
			moves=(Move*)malloc((num_threads -1)*sizeof(Move));
			eval_results=(int*)malloc((num_threads - 1)*sizeof(int));




			for(i=0;i<num_threads-1;i++)
			{		
				MPI_Status status;	
				MPI_Recv (&moves[i], sizeof(Move), MPI_BYTE, i+1 ,10, MPI_COMM_WORLD, &status);
				MPI_Recv (&PVs[i], sizeof(Variation), MPI_BYTE, i+1 ,10, MPI_COMM_WORLD, &status);
				MPI_Recv (&eval_results[i], 1, MPI_INT, i+1 ,10, MPI_COMM_WORLD, &status);
			}

			for(i=0;i<num_threads-1;i++)
			{
				if(eval_results[i] > currentValue)
				{
					currentValue = eval_results[i];
					_pv=PVs[i];
					_currentBestMove = moves [i];
				}

			}
			for(i=0;i<num_threads-1;i++)
			{
				MPI_Send(&_currentBestMove, sizeof(Move), MPI_BYTE, i+1 ,10, MPI_COMM_WORLD);
				MPI_Send(&_pv, sizeof(Variation), MPI_BYTE, i+1 ,10, MPI_COMM_WORLD);
				MPI_Send(&currentValue, 1, MPI_INT, i+1 ,10, MPI_COMM_WORLD);
			}
		}
		else
		{
			MPI_Status status;
			MPI_Send(&_currentBestMove, sizeof(Move), MPI_BYTE, 0 ,10, MPI_COMM_WORLD);
			MPI_Send(&_pv, sizeof(Variation), MPI_BYTE, 0 ,10, MPI_COMM_WORLD);
			MPI_Send(&currentValue, 1, MPI_INT, 0 ,10, MPI_COMM_WORLD);
			MPI_Recv(&_currentBestMove, sizeof(Move), MPI_BYTE, 0 ,10, MPI_COMM_WORLD, &status);
			pretty_print("thread_rank", thread_rank);
			printf("currentBestMove = %s\n",_currentBestMove.name());
			MPI_Recv(&_pv, sizeof(Variation), MPI_BYTE, 0 ,10, MPI_COMM_WORLD, &status);
			MPI_Recv(&currentValue, 1, MPI_INT, 0 ,10, MPI_COMM_WORLD, &status);

		}	
	
		foundBestMove(0,_currentBestMove,currentValue);
	}

	if(!flag)
	if (_sc) _sc->finishedNode(depth, _pv.chain(depth));

	return currentValue;
}
Example #27
0
void Maxscoreqi::operator() (lptrArray& lps, const int topK, QpResult* res, const float& threshold) {
    unsigned int num_essential_lists = 0;
    unsigned int num_of_non_essential_lists = lps.size();
    float total_maxscore_sum = 0.0f;
    float current_threshold = threshold;
    float current_prefix_sum_max_score = 0.0f;
    float parameter = 1.0f;
    const int threshold_unknown = (Fcompare(threshold, 0.0f) == 0) ? 1 : 0; // treat as bool variable
    const int comparison = -1;
    bool check_for_new_essential_list = false;
    bool essential_list_added = false;
    std::vector <float> lists_maxscore;
    std::vector <float> prefix_sum_max_score;
    lists_maxscore.reserve(lps.size());
    prefix_sum_max_score.reserve(lps.size()-1);

    // initialize results heap
    for (int i = 0; i < topK; ++i)  {
        res[i].did = CONSTS::MAXD + 1;
        res[i].score = -1.0;
    }

    // initial sorting of lists by max score
    lps.sortbyscore();
    int smallest_did = lps[0]->did;
    int next_smallest_did = CONSTS::MAXD + 1;

    // initialize maxscore array
    for (int i=0; i<lps.size(); i++) {
        lists_maxscore.push_back(lps.getListMaxScore(i));
        total_maxscore_sum += lps.getListMaxScore(i); // useless to check!
    }

    // initialize prefix sum max score array that is used in find_essential_lists
    prefix_sum_max_score.push_back(lps.getListMaxScore(0));
    for (int i=1; i<lps.size()-1; i++)
        prefix_sum_max_score.push_back(prefix_sum_max_score.at(i-1) + lps.getListMaxScore(i));

    // if threshold is known find essential lists
    if (threshold_unknown==0) {
        find_new_essential_lists(num_essential_lists, num_of_non_essential_lists, prefix_sum_max_score, lps, current_threshold, essential_list_added, parameter);
        essential_list_added = false;
    }

    // find first smallest did
    find_smallest_did_in_essential_set(lps, num_essential_lists, smallest_did);

    // set it for the first time only
    if (threshold_unknown==1)
        next_smallest_did = smallest_did;

    while(true) {
        // if threshold is not known and heapify occured, update the current_threshold, find if a new list can be added to the essential set
        if ((threshold_unknown == 1) && (check_for_new_essential_list)) {
            // update threshold
            current_threshold = res[topK-1].score;
            // find essential lists
            find_new_essential_lists(num_essential_lists, num_of_non_essential_lists, prefix_sum_max_score, lps, current_threshold, essential_list_added, parameter);
            check_for_new_essential_list = false;

            // if essential list added, check for new smallest did if needed
            if (!essential_list_added)
                smallest_did = next_smallest_did; // we have already found the smallest did from the previous round
            else {
                essential_list_added = false;
                // if new smallest did out of range break, otherwise return smallest_did in this round
                if (! find_smallest_did_in_essential_set(lps, num_essential_lists, smallest_did))
                    break;
            }
        } else
            smallest_did = next_smallest_did; // we have already found the smallest did from the previous round

        // set correct current prefix sum max score
        current_prefix_sum_max_score = num_essential_lists > 0 ? prefix_sum_max_score.at(num_essential_lists-1) : 0.0f;

        // evaluate
        evaluate(lps, res, current_threshold, topK, num_essential_lists, smallest_did, lists_maxscore, current_prefix_sum_max_score, check_for_new_essential_list, threshold_unknown, comparison, next_smallest_did);

        // check if next smallest did is out of docid range
        if (next_smallest_did >= CONSTS::MAXD)
            break;
    }
}
 value_t get() const
 {
     evaluate();
     return ret.result();
 }
Example #29
0
File: portal.c Project: Lundex/lima
string look_in(string prep)
{
    return evaluate(look_in_desc);
}
Example #30
0
Real
ParsedODEKernel::computeQpResidual()
{
  updateParams();
  return evaluate(_func_F);
}