示例#1
0
文件: item.cpp 项目: yongwen/columbia
//##ModelId=3B0C087602D2
LOG_PROP * COMP_OP::FindLogProp (	LOG_PROP ** input)
{
    double selectivity;
	
	LOG_ITEM_PROP * LeftProp = (LOG_ITEM_PROP *)input[0];
	LOG_ITEM_PROP * RightProp = (LOG_ITEM_PROP *)input[1];
	
    // Figure out the free variables
    KEYS_SET fv = LeftProp -> FreeVars;
	
    // OP_NOT is the only unary CONJ_OP
    if (op_code != OP_NOT) 
		fv.Merge( RightProp -> FreeVars);
    
	// for COMP_OP
	
    double attr_min, attr_max, attr_cucard, const_value;
	
    // if any of the inputs is ATTR_EXP or both of the them are ATTR_CATs, 
    //  use magic number
    if ( LeftProp->CuCard == -1 || RightProp->CuCard == -1 ||
		( LeftProp->CuCard != 1 && RightProp->CuCard !=1 )	|| 
		op_code == OP_LIKE) 
	{
		// magic numbers
		switch (op_code) 
		{
		case OP_LIKE : 
			// MINIMUM selectivity .05
			if (LeftProp->CuCard==1) 
			{
				ASSERT(LeftProp->Min == LeftProp->Max);
				attr_cucard = RightProp->CuCard;
				ASSERT(attr_cucard >= 1);
				selectivity = MAX(0.05, 1 / attr_cucard); 
			} 
			else 
				if (RightProp->CuCard==1) 
				{
					ASSERT(RightProp->Min == RightProp->Max);
					attr_cucard = LeftProp->CuCard;
					ASSERT(attr_cucard >= 1);
					selectivity = MAX(0.05, 1 / attr_cucard); 
				} 
				else 
				{
					// Neither left or right operand is constant
					selectivity = 0.05; 
				}
				break;
		case OP_EQ : 
			selectivity = 0.1; 
			break;
		case OP_NE :
			selectivity = 0.9; 
			break;
		case OP_LE:
		case OP_LT:
		case OP_GE:
		case OP_GT:
			selectivity = 0.5; 
			break;
		default:
			selectivity = 0.5; 
			break;
		};
    } 
	else 
	{
		if (LeftProp->CuCard==1) 
		{
			ASSERT(LeftProp->Min == LeftProp->Max);
			const_value = LeftProp->Min;
			attr_min = RightProp->Min;
			attr_max = RightProp->Max;
			attr_cucard = RightProp->CuCard;
		} 
		else 
		{
			ASSERT(RightProp->Min == RightProp->Max);
			const_value = RightProp->Min;
			attr_min = LeftProp->Min;
			attr_max = LeftProp->Max;
			attr_cucard = LeftProp->CuCard;
		}
		
		switch (op_code) 
		{
		case OP_IN : 
			// left or right input should be a CONST_SET_OP
			// const_val = cmin is the NUMBER OF ELEMENTS in the SET!
			// Example query 16 predicate:
			//     P_SIZE  IN ([size1], [size2], [size3], [size4], [size5], 
			//     [size6], [size7], [size8])
			// So below 8 is the number of elements in the set
			selectivity = const_value / (attr_cucard); break;
		case OP_EQ : 
			selectivity = 1 / attr_cucard; break;
		case OP_NE :
			selectivity = 1 - 1 / attr_cucard; break;
		case OP_LE:
		case OP_LT:
			selectivity = (MIN(attr_max, const_value) - 
				MIN(attr_min, const_value)) / (attr_max - attr_min);
			break;
		case OP_GE:
		case OP_GT:
			selectivity = (MAX(attr_max, const_value) - 
				MAX(attr_min, const_value)) / (attr_max - attr_min);
			break;
		};
    }
	
    // using independence assumption ... for CONJ_OP
	switch(op_code)
	{
	case OP_AND: 
		selectivity = LeftProp->Selectivity * RightProp->Selectivity; 
		break;
	case OP_OR: 
		selectivity = LeftProp->Selectivity + RightProp->Selectivity -
			LeftProp->Selectivity * RightProp->Selectivity; 
		break;
	case OP_NOT: 
		selectivity = 1 - LeftProp->Selectivity ; 
		break;
	}
	
    // Assert selectivity in range
    if (selectivity < .00001 ) 
	{
		// Warning
		OUTPUT("small selectivity = %.3f\r\n", selectivity);
	}
	
	//"Small selectivity -- shouldn't be a problem -- but is!"
    ASSERT (selectivity > .0000001); 
	
	// "Big selectivity (> 1)"
    ASSERT (selectivity < 1 );
	
    LOG_PROP * result = new LOG_ITEM_PROP (-1,-1,-1, (float)selectivity, fv);
	
    return ( result );
} // CONJ_OP::FindLogProp
int main(int argc, char *argv[]) {

    VERBOSE = 0;
    GRAPHICS = 0;
    validate(argc, argv);
    
    int avatarID = atoi(argv[1]);
    FILE *logFile;
    logFile = fopen(argv[6], "a+");
    char *IP = (char*)calloc(strlen(argv[4]) + 1, sizeof(char));
    MALLOC_CHECK(stderr, IP);
    strncpy(IP, argv[4], strlen(argv[4]));
    
    
    myAvatar *avatar;
    int slobAvatar = 0;     // the one who doesn't move in maze solver

    int mazePort = atoi(argv[5]);
    
    int width = atoi(argv[7]);
    int height = atoi(argv[8]);
    int shmID = atoi(argv[9]);
    char *maze = (char*) shmat(shmID, 0, 0);
    if (maze == (void *)-1 && errno == EACCES) {

        fprintf(stderr, "shmat failed EACCES\n");
        exit(1);
    }
    if (maze == (void *)-1 && errno == EINVAL) {

        fprintf(stderr, "shmat failed EINVAL\n");
        exit(1);
    }
    if (maze == (void *)-1 && errno == ENOMEM) {

        fprintf(stderr, "shmat failed ENOMEM\n");
        exit(1);
    }

    // Server connection stuff
    int sockfd;
    struct sockaddr_in servaddr;
    
    // Create and check status of server
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        free(IP);
        fprintf(stderr, "Could not create socket.\n");
        return 0;   // false
    }
    
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(IP);
    servaddr.sin_port = htons(mazePort);
    
    // Connect to server
    if (connect(sockfd, (struct sockaddr*) &servaddr, \
                sizeof(servaddr)) < 0) {
        fprintf(stderr, "Unable to connect to server. Exiting.\n");
        free(IP);
        return 0;   // false
    }
    
    // Fire off initial AM_AVATAR_READY
    AM_Message *sendmsg = (AM_Message*)calloc(1, sizeof(AM_Message));
    MALLOC_CHECK(stderr, sendmsg);
    
    sendmsg->type = htonl(AM_AVATAR_READY);
    sendmsg->avatar_ready.AvatarId = htonl(avatarID);  // pack information
    
    // Send ready message to server containing avatar ID
    send(sockfd, sendmsg, sizeof(AM_Message), 0);
    
    // Make a message to get back from server
    AM_Message *receivemsg = (AM_Message*)calloc(1, sizeof(AM_Message));
    MALLOC_CHECK(stderr, receivemsg);

    int firstMove = 1;
    int turn = -1;
    // Start while loop that checks all server messages and updates
    // the avatar's position until either error message or AM_SOLVED received
    for ( ;; ) {
        
        // Zero out the message pointers so they can be re-used
        memset(receivemsg, 0, sizeof(AM_Message));
        memset(sendmsg, 0, sizeof(AM_Message));
        
        // Receive the message and make sure it's not empty
        if (recv(sockfd, receivemsg, sizeof(AM_Message), 0) == 0) {
            fprintf(stderr, "Server terminated early.\n");
            OUTPUT(logFile, "Empty message type. Exiting...\n");
            break;
        }
        
        // Check for server error
        if (IS_AM_ERROR(receivemsg->type)) {
            fprintf(stderr, "Error mask detected error.\n");
        }
        
        // Following if statements will check for all possible server errors
        // In all cases, print to stderr, log the error to output file
        // and break to free resources and return
        
        if (ntohl(receivemsg->type) == AM_UNKNOWN_MSG_TYPE) {
            fprintf(stderr, "AM_UNKNOWN_MSG_TYPE\n");
            OUTPUT(logFile, "Unknown message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_NO_SUCH_AVATAR) {
            fprintf(stderr, "AM_NO_SUCH_AVATAR\n");
            OUTPUT(logFile, "No such avatar error. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_UNEXPECTED_MSG_TYPE) {
            fprintf(stderr, "AM_UNEXPECTED_MSG_TYPE\n");
            OUTPUT(logFile, "Unexpected message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_AVATAR_OUT_OF_TURN) {
            fprintf(stderr, "AM_AVATAR_OUT_OF_TURN\n");
            OUTPUT(logFile, "Avatar out of turns message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_TOO_MANY_MOVES) {
            fprintf(stderr, "AM_AVATAR_TOO_MANY_MOVES\n");
            OUTPUT(logFile, "Avatar too many moves message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_SERVER_TIMEOUT) {
            fprintf(stderr, "AM_SERVER_TIMEOUT\n");
            OUTPUT(logFile, "Server timeout message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_SERVER_DISK_QUOTA) {
            fprintf(stderr, "AM_SERVER_DISK_QUOTA\n");
            OUTPUT(logFile, "Server disk quota message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_SERVER_OUT_OF_MEM) {
            fprintf(stderr, "AM_SERVER_OUT_OF_MEM\n");
            OUTPUT(logFile, "Server out of mem message type. Exiting...\n");
            break;
        }
        
        // Huzzah! Output success to log file.
        if (ntohl(receivemsg->type) == AM_MAZE_SOLVED) {
            
            // Only output this stuff once.
            if (avatarID == slobAvatar) {
                fprintf(stdout, "SOLVED!!!\n");
                fprintf(logFile, "Maze solved with %d avatars on %d"
                        " difficulty in %d moves. The Hash key is: %d.\n", ntohl(receivemsg->maze_solved.nAvatars),\
                        ntohl(receivemsg->maze_solved.Difficulty), ntohl(receivemsg->maze_solved.\
                        nMoves), ntohl(receivemsg->maze_solved.Hash));
            }
            
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_AVATAR_TURN) {
            // Only look at messages from the relevant reply messages
            if (ntohl(receivemsg->avatar_turn.TurnId) == avatarID) {
                
                if (firstMove) {
                    // Initialize the avatar.
                    avatar = (myAvatar*)calloc(1, sizeof(myAvatar));
                    MALLOC_CHECK(stderr, avatar);
                    avatar->fd = avatarID;
                    avatar->lastMoveDir = M_NORTH;  // everyone goes north initially
                    
                    // Initially, avatar's previous position and current position
                    // are the same. Retrieve these from server.
                    avatar->pos.x = ntohl(receivemsg->avatar_turn.Pos[avatarID].x);
                    avatar->pos.y = ntohl(receivemsg->avatar_turn.Pos[avatarID].y);
                    
                    // No previous initially.
                    
                    // Send the avatar north.
                    sendmsg->type = htonl(AM_AVATAR_MOVE);
                    sendmsg->avatar_move.AvatarId = htonl(avatarID);
                    sendmsg->avatar_move.Direction = htonl(M_NORTH);
                    
                    if (VERBOSE) {
                        fprintf(stdout, "Avatar %d: Initial pos (%d, %d) moved NORTH\n", avatarID,\
                                avatar->pos.x, avatar->pos.y);
                    }
                    // Send ready message to server containing avatar ID
                    send(sockfd, sendmsg, sizeof(AM_Message), 0);
                    turn = 1;
                    firstMove = 0;

                    if (GRAPHICS) {
                        //initialize graphics
                        AddAvatar(maze,avatar,width);
                        PrintMaze(maze, width, height);
                    }
                    
                    continue;
                    
                }
                
                else {  // not first move
                    
                    // If it's the avatar standing still, arbitrarily picked as
                    // avatar with ID = 0, then always stand still.
                    if (avatarID == slobAvatar) {
                        sendmsg->type = htonl(AM_AVATAR_MOVE);
                        sendmsg->avatar_move.AvatarId = htonl(avatarID); // should be 0
                        sendmsg->avatar_move.Direction = htonl(M_NULL_MOVE);
                        send(sockfd, sendmsg, sizeof(AM_Message), 0);
                        turn++;
                        continue;
                    }
                    
                    // Make the previous the current position
                    avatar->prev.x = avatar->pos.x;
                    avatar->prev.y = avatar->pos.y;
                    turn++;
                    // Make current position the new one from the server
                    int newX = ntohl(receivemsg->avatar_turn.Pos[avatarID].x);
                    int newY = ntohl(receivemsg->avatar_turn.Pos[avatarID].y);
                    avatar->pos.x = newX;
                    avatar->pos.y = newY;
                    
                    // See if the slob and the current avatar are on the same spot.
                    int deltaX = avatar->pos.x - ntohl(receivemsg->avatar_turn.Pos[slobAvatar].x);
                    int deltaY = avatar->pos.y - ntohl(receivemsg->avatar_turn.Pos[slobAvatar].y);
                    int checkSameCell = 0;
                    
                    if ((deltaY == 0) && (deltaX == 0)) {
                        checkSameCell = 1;
                    }
                    // If avatar is on same spot as slob, slob has been found.
                    // Don't move the other avatar.
                    if (checkSameCell) {
                        sendmsg->type = htonl(AM_AVATAR_MOVE);
                        sendmsg->avatar_move.AvatarId = htonl(avatarID);
                        sendmsg->avatar_move.Direction = htonl(M_NULL_MOVE);
                        send(sockfd, sendmsg, sizeof(AM_Message), 0);
                        turn++;
                        continue;
                    }
                    
                    // Avatar is not slob and has not yet met slob.
                    else {
                        
                        // See if the last move was productive
                        int lastMove = checkLastMove(avatar);
                        avatar->lastMoveSuccess = lastMove;

                        //update graphics based on last move

                        if(!lastMove){
                            AddWall(maze,avatar,width);
                        }
                        else{
                            //DelAvatar(maze,avatar,width);//comment out to see history
                            if(!AddMark(maze,avatar,width))//blocks square if test passes
                                AddAvatar(maze,avatar,width);
                        }
                        
                        if (GRAPHICS) {
                            PrintMaze(maze,width,height);
                        }
                        
                        
                        

                        //prep next move
                        int nextMove = getMove(avatar);
                        avatar->lastMoveDir = nextMove;
                        while(isKnown(maze, avatar, width)){
                            avatar->lastMoveSuccess = false;
                            nextMove = getMove(avatar);
                            avatar->lastMoveDir = nextMove;
                        }
                        
                        turn++;
                        sendmsg->type = htonl(AM_AVATAR_MOVE);
                        sendmsg->avatar_move.AvatarId = htonl(avatarID);
                        sendmsg->avatar_move.Direction = htonl(nextMove);
                        
                        if (VERBOSE) {
                            fprintf(stdout, "======== Turn %d ========\n", turn);
                            if (nextMove == M_NORTH) {
                                fprintf(stdout, "Avatar %d: Moved NORTH from (%d, %d).\n", avatarID,\
                                        avatar->pos.x, avatar->pos.y);
                            }
                            if (nextMove == M_SOUTH) {
                                fprintf(stdout, "Avatar %d: Moved SOUTH from (%d, %d).\n", avatarID,\
                                        avatar->pos.x, avatar->pos.y);
                            }
                            
                            if (nextMove == M_WEST) {
                                fprintf(stdout, "Avatar %d: Moved WEST from (%d, %d).\n", avatarID,\
                                        avatar->pos.x, avatar->pos.y);
                            }
                            
                            if (nextMove == M_EAST) {
                                fprintf(stdout, "Avatar %d: Moved EAST from (%d, %d).\n", avatarID,\
                                        avatar->pos.x, avatar->pos.y);
                            }
                            fprintf(stdout, "\n");
                        }
                        
                        send(sockfd, sendmsg, sizeof(AM_Message), 0);
                    }
                    
                }
            }
            
        }
        
    }
    shmctl(shmID, IPC_RMID, NULL);
    free(sendmsg); free(receivemsg); free(IP); free(avatar);
    fclose(logFile);
    close(sockfd);
    return 1;
    
}
示例#3
0
void SubStep3_cpu (real dt) {

//<USER_DEFINED>
  INPUT(Energy);
#ifdef X
  INPUT(Vx_temp);
#endif
#ifdef Y
  INPUT(Vy_temp);
#endif
#ifdef Z
  INPUT(Vz_temp);
#endif
  OUTPUT(Energy);
//<\USER_DEFINED>

//<EXTERNAL>
  real* e   = Energy->field_cpu;
#ifdef X
  real* vx  = Vx_temp->field_cpu;
#endif
#ifdef Y
  real* vy  = Vy_temp->field_cpu;
#endif
#ifdef Z
  real* vz  = Vz_temp->field_cpu;
#endif
  int pitch  = Pitch_cpu;
  int stride = Stride_cpu;
  int size_x = XIP; 
  int size_y = Ny+2*NGHY-1;
  int size_z = Nz+2*NGHZ-1;
//<\EXTERNAL>

//<INTERNAL>
  int i; //Variables reserved
  int j; //for the topology
  int k; //of the kernels
  int ll;
#ifdef X
  int llxp;
#endif
#ifdef Y
  int llyp;
#endif
#ifdef Z
  int llzp;
#endif
  real term;
  real div_v;
//<\INTERNAL>
  
//<CONSTANT>
// real GAMMA(1);
// real Sxj(Ny+2*NGHY);
// real Syj(Ny+2*NGHY);
// real Szj(Ny+2*NGHY);
// real Sxk(Nz+2*NGHZ);
// real Syk(Nz+2*NGHZ);
// real Szk(Nz+2*NGHZ);
// real InvVj(Ny+2*NGHY);
//<\CONSTANT>

//<MAIN_LOOP>
  
  i = j = k = 0;
  
#ifdef Z
  for(k=0; k<size_z; k++) {
#endif
#ifdef Y
    for(j=0; j<size_y; j++) {
#endif
#ifdef X
      for(i=0; i<size_x; i++) {
#endif
//<#>

	ll = l;
#ifdef X
	llxp = lxp;
#endif
#ifdef Y
	llyp = lyp;
#endif
#ifdef Z
	llzp = lzp;
#endif
	div_v = 0.0;
#ifdef X
	div_v += (vx[llxp]-vx[ll])*SurfX(j,k);
#endif
#ifdef Y
	div_v += (vy[llyp]*SurfY(j+1,k)-vy[ll]*SurfY(j,k));
#endif
#ifdef Z
	div_v += (vz[llzp]*SurfZ(j,k+1)-vz[ll]*SurfZ(j,k));
#endif
	term = 0.5 * dt * (GAMMA - 1.) * div_v * InvVol(j,k);
	e[ll] *= (1.0-term)/(1.0+term);
//<\#>
#ifdef X
      }
#endif
#ifdef Y
    }
#endif
#ifdef Z
  }
#endif
//<\MAIN_LOOP>
}
示例#4
0
int notes_merge(struct notes_merge_options *o,
                struct notes_tree *local_tree,
                unsigned char *result_sha1)
{
    unsigned char local_sha1[20], remote_sha1[20];
    struct commit *local, *remote;
    struct commit_list *bases = NULL;
    const unsigned char *base_sha1, *base_tree_sha1;
    int result = 0;

    assert(o->local_ref && o->remote_ref);
    assert(!strcmp(o->local_ref, local_tree->ref));
    hashclr(result_sha1);

    trace_printf("notes_merge(o->local_ref = %s, o->remote_ref = %s)\n",
                 o->local_ref, o->remote_ref);

    /* Dereference o->local_ref into local_sha1 */
    if (!resolve_ref(o->local_ref, local_sha1, 0, NULL))
        die("Failed to resolve local notes ref '%s'", o->local_ref);
    else if (!check_ref_format(o->local_ref) && is_null_sha1(local_sha1))
        local = NULL; /* local_sha1 == null_sha1 indicates unborn ref */
    else if (!(local = lookup_commit_reference(local_sha1)))
        die("Could not parse local commit %s (%s)",
            sha1_to_hex(local_sha1), o->local_ref);
    trace_printf("\tlocal commit: %.7s\n", sha1_to_hex(local_sha1));

    /* Dereference o->remote_ref into remote_sha1 */
    if (get_sha1(o->remote_ref, remote_sha1)) {
        /*
         * Failed to get remote_sha1. If o->remote_ref looks like an
         * unborn ref, perform the merge using an empty notes tree.
         */
        if (!check_ref_format(o->remote_ref)) {
            hashclr(remote_sha1);
            remote = NULL;
        } else {
            die("Failed to resolve remote notes ref '%s'",
                o->remote_ref);
        }
    } else if (!(remote = lookup_commit_reference(remote_sha1))) {
        die("Could not parse remote commit %s (%s)",
            sha1_to_hex(remote_sha1), o->remote_ref);
    }
    trace_printf("\tremote commit: %.7s\n", sha1_to_hex(remote_sha1));

    if (!local && !remote)
        die("Cannot merge empty notes ref (%s) into empty notes ref "
            "(%s)", o->remote_ref, o->local_ref);
    if (!local) {
        /* result == remote commit */
        hashcpy(result_sha1, remote_sha1);
        goto found_result;
    }
    if (!remote) {
        /* result == local commit */
        hashcpy(result_sha1, local_sha1);
        goto found_result;
    }
    assert(local && remote);

    /* Find merge bases */
    bases = get_merge_bases(local, remote, 1);
    if (!bases) {
        base_sha1 = null_sha1;
        base_tree_sha1 = EMPTY_TREE_SHA1_BIN;
        OUTPUT(o, 4, "No merge base found; doing history-less merge");
    } else if (!bases->next) {
        base_sha1 = bases->item->object.sha1;
        base_tree_sha1 = bases->item->tree->object.sha1;
        OUTPUT(o, 4, "One merge base found (%.7s)",
               sha1_to_hex(base_sha1));
    } else {
        /* TODO: How to handle multiple merge-bases? */
        base_sha1 = bases->item->object.sha1;
        base_tree_sha1 = bases->item->tree->object.sha1;
        OUTPUT(o, 3, "Multiple merge bases found. Using the first "
               "(%.7s)", sha1_to_hex(base_sha1));
    }

    OUTPUT(o, 4, "Merging remote commit %.7s into local commit %.7s with "
           "merge-base %.7s", sha1_to_hex(remote->object.sha1),
           sha1_to_hex(local->object.sha1), sha1_to_hex(base_sha1));

    if (!hashcmp(remote->object.sha1, base_sha1)) {
        /* Already merged; result == local commit */
        OUTPUT(o, 2, "Already up-to-date!");
        hashcpy(result_sha1, local->object.sha1);
        goto found_result;
    }
    if (!hashcmp(local->object.sha1, base_sha1)) {
        /* Fast-forward; result == remote commit */
        OUTPUT(o, 2, "Fast-forward");
        hashcpy(result_sha1, remote->object.sha1);
        goto found_result;
    }

    result = merge_from_diffs(o, base_tree_sha1, local->tree->object.sha1,
                              remote->tree->object.sha1, local_tree);

    if (result != 0) { /* non-trivial merge (with or without conflicts) */
        /* Commit (partial) result */
        struct commit_list *parents = NULL;
        commit_list_insert(remote, &parents); /* LIFO order */
        commit_list_insert(local, &parents);
        create_notes_commit(local_tree, parents, o->commit_msg.buf,
                            result_sha1);
    }

found_result:
    free_commit_list(bases);
    strbuf_release(&(o->commit_msg));
    trace_printf("notes_merge(): result = %i, result_sha1 = %.7s\n",
                 result, sha1_to_hex(result_sha1));
    return result;
}
示例#5
0
文件: main.c 项目: ssloy/tutorials
void shift_register_init() {
    OUTPUT(SHIFT_PL_PIN);
    OUTPUT(SHIFT_CP_PIN);
    INPUT(SHIFT_Q7_PIN);
}
示例#6
0
bool ProcessParagraphKeyWords(int iTravelSize)
{
	DISTRIBUTE_KEY.open(distributeKeyFile, ios::out);
	TEST_OUTPUT.open(testKeyFile, ios::out);
	fstream OUTPUT("./processed/key.txt", ios::out);

	string buffer;

	// 构建FP-Tree所需要的数据
	vector<vector<SString>> tmpTransRecords;
	// 开始对每一篇文章进行操作
	for (int i = 0; i < iTravelSize; ++i)
	{
		cout << i << endl;
		sprintf(inputFile, "./context/context%d.txt", i);

		/* ------------------------- 分割线 ----------------------------- */
		// GetKeyWords
		// 对文章的每一段落进行词性分析
		
		fstream INPUT(inputFile, ios::in);
		while (getline(INPUT, buffer))
		{
			if (buffer == "")
				continue;
			vector<SString> tmpSet;
			const char* tmpResult = NLPIR_GetKeyWords(buffer.c_str(), 20, true);
			OUTPUT << tmpResult << endl;
			// 对结果进行分割
			CSplit::split(tmpResult, '#', words, wordNum, 50);
			for (int j = 0; j < wordNum; ++j)
			{
				// 输出TEST、
				TEST_OUTPUT << words[j] << endl;

				// 对每一个词进行分割
				char **subWords = NULL;
				int subWordsNum = 0;
				CSplit::split(words[j], '/', subWords, subWordsNum, 5);
				if (subWords[1][0] != 'n')
					continue;
				tmpSet.push_back(SString(subWords[0]));
				mapKey[subWords[0]]++;

				// 释放空间
				for (int wordIndex = 0; wordIndex < subWordsNum; ++wordIndex)
					delete[] subWords[wordIndex];
				delete[] subWords;
			}
			// 压入临时变量
			tmpTransRecords.push_back(tmpSet);
			
			// 释放空间
			for (int wordIndex = 0; wordIndex < wordNum; ++wordIndex)
				delete[] words[wordIndex];
			delete[] words;
		}
		INPUT.close();
	}

	/* ------------------------- 分割线 ----------------------------- */
	// 过滤tmpTransRecords到transRecordsKey
	for (int i = 0; i < tmpTransRecords.size(); ++i)
	{
		vector<SString> tmpRecords;
		for (int j = 0; j < tmpTransRecords[i].size(); ++j)
		{
			if (mapKey[tmpTransRecords[i][j]] < minSup)
				continue;
			tmpRecords.push_back(tmpTransRecords[i][j]);
		}
		// 对tmpRecords进行排序
		sort(tmpRecords.begin(), tmpRecords.end(), cmp_by_key);
		// 将排好序的vector<SString>压如transRecordsNew
		if (tmpRecords.size() < 2)
			continue;
		transRecordsKey.push_back(tmpRecords);
	}

	/* ------------------------- 分割线 ----------------------------- */
	// map排序输出,效果特别好
	vector<PAIR> vecStr(mapKey.begin(), mapKey.end());
	sort(vecStr.begin(), vecStr.end(), cmp_by_value);
	for (int i = 0; i < vecStr.size(); ++i)
	{
		DISTRIBUTE_KEY << vecStr[i].first.sWord << " -- " << vecStr[i].second << endl;
	}

	/* ------------------------- 分割线 ----------------------------- */
	// 关闭文件输出
	DISTRIBUTE_KEY.close();
	TEST_OUTPUT.close();
	OUTPUT.close();

	return true;
}
示例#7
0
void FeatureExtractor::printTimes() {
#ifdef FEATURE_EXTRACTOR_TIMING
  std::cout << "FeatureExtractor Timings: " << OUTPUT(total) << OUTPUT(pos) << OUTPUT(derived) << OUTPUT(actions) << OUTPUT(history) << std::endl;
  std::cout << "  " << OUTPUT(history) << ":" << OUTPUT(historycalc) << OUTPUT(historyupdate) << OUTPUT(historydiff) << OUTPUT(historyaction) << OUTPUT(historyuncenter) << std::endl;
#endif
}
void CognitionConfigurationDataProvider::update(FieldColors& fieldColors)
{
  update(fieldColors, theFieldColors);
  DEBUG_RESPONSE_ONCE("representation:FieldColors:once")
    OUTPUT(idFieldColors, bin, fieldColors);
}
示例#9
0
void EMF_Upstream_Integrate_cpu (real dt) {

//<USER_DEFINED>
  INPUT (Emfx);
  INPUT (Emfy);
  INPUT (Emfz);
  INPUT (By);
  INPUT (Bz);
  INPUT2D (Vxhyr);
  INPUT2D (Vxhzr);
  INPUT2D (Vxhzr);
  INPUT2DINT (Nxhy);
  INPUT2DINT (Nxhz);
  OUTPUT (Emfx);
  OUTPUT (Emfy);
  OUTPUT (Emfz);
//<\USER_DEFINED>

//<INTERNAL>
  int i;
  int j;
  int k;
  int m;
  int l_plus_m;
  int ll;
  int ll2D;
  int ll2D_int;
//<\INTERNAL>

//<EXTERNAL>
  real* emfx = Emfx->field_cpu;
  real* emfy = Emfy->field_cpu;
  real* emfz = Emfz->field_cpu;
  real* by = By->field_cpu;
  real* bz = Bz->field_cpu;
  real* vxhyr = Vxhyr->field_cpu;
  real* vxhzr = Vxhzr->field_cpu;
  int* nxhy = Nxhy->field_cpu;
  int* nxhz = Nxhz->field_cpu;
  int pitch  = Pitch_cpu;
  int pitch2d_int = Pitch_Int_gpu;
  int pitch2d = Pitch2D;
  int stride = Stride_cpu;
  int size_x = Nx+2*NGHX;
  int size_y = Ny+2*NGHY;
  int size_z = Nz+2*NGHZ;
  real dx = Dx;
  int nx = Nx; 
//<\EXTERNAL>

//<CONSTANT>
// real ymin(Ny+2*NGHY+1);
// real zmin(Nz+2*NGHZ+1);
//<\CONSTANT>

//<MAIN_LOOP>
  for (k = 1; k < size_z; k++) {
    for (j = 1; j < size_y; j++) {
      for (i = 0; i < size_x; i++) {
//<#>
	ll = l;
	ll2D = l2D;
	ll2D_int = l2D_int;
	emfx[ll] = 0.0;
	emfz[ll] *= -vxhyr[ll2D]*dt;
	emfy[ll] *= vxhzr[ll2D]*dt;
	if (nxhy[ll2D_int] > 0) {
	  for (m=0; m < nxhy[ll2D_int]; m++) {
	    l_plus_m = ll+m;
	    if (i+m >= nx+NGHX) l_plus_m -= nx;
	    if (i+m <  NGHX)    l_plus_m += nx;
	    emfz[ll] += -by[l_plus_m]*edge_size_x_middlez_lowy(j,k);
	  }
	} else {
	  for (m=-1; m >= nxhy[ll2D_int]; m--) {
	    l_plus_m = ll+m;
	    if (i+m >= nx+NGHX) l_plus_m -= nx;
	    if (i+m <  NGHX)    l_plus_m += nx;
	    emfz[ll] += by[l_plus_m]*edge_size_x_middlez_lowy(j,k);
	  }
	}
	if (nxhz[ll2D_int] > 0) {
	  for (m=0; m < nxhz[ll2D_int]; m++) {
	    l_plus_m = ll+m;
	    if (i+m >= nx+NGHX) l_plus_m -= nx;
	    if (i+m <  NGHX)    l_plus_m += nx;
	    emfy[ll] += bz[l_plus_m]*edge_size_x_middley_lowz(j,k);
	  }
	} else {
	  for (m=-1; m >= nxhz[ll2D_int]; m--) {
	    l_plus_m = ll+m;
	    if (i+m >= nx+NGHX) l_plus_m -= nx;
	    if (i+m <  NGHX)    l_plus_m += nx;
	    emfy[ll] += -bz[l_plus_m]*edge_size_x_middley_lowz(j,k);
	  }
	}
//<\#>
      }
    }
  }
//<\MAIN_LOOP>
}
示例#10
0
文件: i2clcd.c 项目: ADTL/ARMWork
void i2clcd_backlight(uint8_t fl)
{
	// I2C LCD Backlight controll pin
	OUTPUT(0, 3);
	IOSET( 0, 3, !fl);
}
示例#11
0
/*******************************************************************-o-******
 * test_etime
 *
 * Returns:
 *	Number of failures.
 *
 * Test of LCD Engine ID and Time List.
 */
int
test_etime(void)
{
    int             rval = SNMPERR_SUCCESS, failcount = 0;
    u_int           etime, eboot;

    /*
     * ------------------------------------ -o-
     */
    OUTPUT("Query of empty list, two set actions.");


    rval = ISENGINEKNOWN("A", 1);
    if (rval == TRUE) {
        FAILED(SNMPERR_GENERR, "Query of empty list returned TRUE.")
    }


    rval = set_enginetime("BB", 2, 2, 20, TRUE);
    FAILED(rval, "set_enginetime()");


    rval = set_enginetime("CCC", 3, 31, 90127, TRUE);
    FAILED(rval, "set_enginetime()");


    SUCCESS("Check of empty list, and two additions.");



    /*
     * ------------------------------------ -o-
     */
    OUTPUT("Add entries using macros, test for existence with macros.");


    rval = ENSURE_ENGINE_RECORD("DDDD", 4);
    FAILED(rval, "ENSURE_ENGINE_RECORD()");


    rval = MAKENEW_ENGINE_RECORD("EEEEE", 5);
    if (rval == SNMPERR_SUCCESS) {
        FAILED(rval,
               "MAKENEW_ENGINE_RECORD returned success for "
               "missing record.");
    }


    rval = MAKENEW_ENGINE_RECORD("BB", 2);
    FAILED(rval, "MAKENEW_ENGINE_RECORD().");


    SUCCESS
    ("Added entries with macros, tested for existence with macros.");



    /*
     * ------------------------------------ -o-
     */
    OUTPUT("Dump the list and then sleep.");

#ifdef SNMP_TESTING_CODE
    dump_etimelist();
#endif

    fprintf(stdout, "\nSleeping for %d second%s... ",
            sleeptime, (sleeptime == 1) ? "" : "s");
    fflush(stdout);

    sleep(sleeptime);
    fprintf(stdout, "\n");



    /*
     * ------------------------------------ -o-
     */
    OUTPUT
    ("Retrieve data from real/stubbed records, update real/stubbed.");



    rval = get_enginetime("BB", 2, &eboot, &etime, TRUE);
    FAILED(rval, "get_enginetime().");

    fprintf(stdout, "BB = <%d,%d>\n", eboot, etime);
    if ((etime < 20) || (eboot < 2)) {
        FAILED(SNMPERR_GENERR,
               "get_enginetime() returned bad values.  (1)");
    }

    rval = get_enginetime("DDDD", 4, &eboot, &etime, FALSE);
    FAILED(rval, "get_enginetime().");

    fprintf(stdout, "DDDD = <%d,%d>\n", eboot, etime);
    if ((etime < sleeptime) || (eboot != 0)) {
        FAILED(SNMPERR_GENERR,
               "get_enginetime() returned bad values.  (2)");
    }


    rval = set_enginetime("CCC", 3, 234, 10000, TRUE);
    FAILED(rval, "set_enginetime().");


    rval = set_enginetime("EEEEE", 5, 9876, 55555, TRUE);
    FAILED(rval, "set_enginetime().");


    SUCCESS("Retrieval and updates.");



    /*
     * ------------------------------------ -o-
     */
    OUTPUT("Sleep again, then dump the list one last time.");

    fprintf(stdout, "Sleeping for %d second%s... ",
            sleeptime, (sleeptime == 1) ? "" : "s");
    fflush(stdout);

    sleep(sleeptime);
    fprintf(stdout, "\n");

#ifdef SNMP_TESTING_CODE
    dump_etimelist();
#endif

    return failcount;

}                               /* end test_etime() */
示例#12
0
main()
{
   double A[10][11],S[10],X[10];
   double AMAX,XM,SUM,TEMP;
   int NROW[10];
   int N,M,ICHG,I,NN,IMAX,J,JJ,IP,JP,NCOPY,I1,J1,N1,K,N2,LL,KK,OK;

   INPUT(&OK, A, &N);
   if (OK) {
      M = N + 1;
      /* STEP 1 */
      for (I=1; I<=N; I++) {
         S[I-1] = absval(A[I-1][0]);
         /* initialize row pointer */
         NROW[I-1] = I;
         for (J=1; J<=N; J++) 
            if (absval(A[I-1][J-1] ) > S[I-1])
               S[I-1] = absval(A[I-1][J-1]);
         if (S[I-1] <= ZERO) OK = false;
      }  
      NN = N - 1;
      ICHG = 0;
      I = 1;
      /* STEP 2 */
      /* elimination process */
      while (OK && (I <= NN)) {
         /* STEP 3 */
         IMAX = NROW[I-1];
         AMAX = absval(A[IMAX-1][I-1]) / S[IMAX-1];
         IMAX = I;
         JJ = I + 1;
         for (IP=JJ; IP<=N; IP++) {
            JP = NROW[IP-1];
            TEMP = absval(A[JP-1][I-1]/S[JP-1]);
            if (TEMP > AMAX ) {
               AMAX = TEMP;
               IMAX = IP;
            }  
         }  
         /* STEP 4 */
         /* system has no unique solution */
         if (AMAX <= ZERO) OK = false;
         else {
            /* STEP 5 */
            /* simulate row interchange */
            if (NROW[I-1] != NROW[IMAX-1]) {
               ICHG = ICHG + 1;
               NCOPY = NROW[I-1];
               NROW[I-1] = NROW[IMAX-1];
               NROW[IMAX-1] = NCOPY;
            }
            /* STEP 6 */
            I1 = NROW[I-1];
            for (J=JJ; J<=N; J++) {
               J1 = NROW[J-1];
               /* STEP 7 */
               XM = A[J1-1][I-1] / A[I1-1][I-1];
               /* STEP 8 */
               for (K=JJ; K<=M; K++) 
                   A[J1-1][K-1] = A[J1-1][K-1] - XM * A[I1-1][K-1];
               /* Multiplier XM could be saved in A[J1-1][I-1] */
               A[J1-1][I-1] = 0.0;
            }  
         }  
         I++;
      }
      if (OK) {
         /* STEP 9 */
         N1 = NROW[N-1];
         if (absval(A[N1-1][N-1] ) <= ZERO) OK = false;
         /* system has no unique solution */
         else {
            /* STEP 10 */
            /* start backward substitution */
            X[N-1] = A[N1-1][M-1] / A[N1-1][N-1];
            /* STEP 11 */
            for (K=1; K<=NN; K++) {
               I = NN - K + 1;
               JJ = I + 1;
               N2 = NROW[I-1];
               SUM = 0.0;
               for (KK=JJ; KK<=N; KK++) {
                  SUM = SUM - A[N2-1][KK-1] * X[KK-1];
               }
               X[I-1] = (A[N2-1][N] + SUM) / A[N2-1][I-1];
            }  
            /* STEP 12 */
            /* procedure completed successfully */
            OUTPUT(N, M, ICHG, NROW, X, A);
         }  
      }  
      if (!OK) printf("System has no unique solution\n");
   }
   return 0;
}
示例#13
0
bool WalkingEngineKick::load(const char* filePath, char* buf)
{
  int lineNumber = 0;
  bool error = false;

  for(int i = 0; i < numOfTracks; ++i)
  {
    tracks[i].clear();
    addPhase(Track(i), 0);
  }

  while(*buf)
  {
    ++lineNumber;

    try
    {
      while(*buf == ' ' || *buf == '\t')
        ++buf;

      if(*buf != '#' && *buf != ';' && *buf != '\r' && *buf != '\n')
      {
        String str = readString(buf);
        if(str == "setType")
        {
          // TODO: remove "setType"
          readString(buf);
        }
        else if(str == "setPreStepSize")
        {
          preStepSizeXValue = readValue(buf);
          preStepSizeYValue = readValue(buf);
          preStepSizeZValue = readValue(buf);
          readValue(buf);
          readValue(buf);
          preStepSizeRValue = readValue(buf);
        }
        else if(str == "setStepSize")
        {
          stepSizeXValue = readValue(buf);
          stepSizeYValue = readValue(buf);
          stepSizeZValue = readValue(buf);
          readValue(buf);
          readValue(buf);
          stepSizeRValue = readValue(buf);
        }
        else if(str == "setDuration")
        {
          durationValue = readValue(buf);
        }
        else if(str == "setRefX")
        {
          refXValue = readValue(buf);
        }
        else if(str == "proceed")
        {
          Value* value = readValue(buf);
          for(int i = 0; i < numOfTracks; ++i)
          {
            PhaseInfo& lastPhase = tracks[i].back();
            if(!lastPhase.lengthValue)
              lastPhase.lengthValue = value;
            else
              lastPhase.lengthValue = new PlusExpression(*lastPhase.lengthValue, *value, *this);
          }
        }
        else if(str == "setLeg")
        {
          addPhase(footTranslationX, readValue(buf));
          addPhase(footTranslationY, readValue(buf));
          addPhase(footTranslationZ, readValue(buf));
          addPhase(footRotationX, readValue(buf));
          addPhase(footRotationY, readValue(buf));
          addPhase(footRotationZ, readValue(buf));
        }
        else if(str == "setArms")
        {
          addPhase(lShoulderPitch, readValue(buf));
          addPhase(lShoulderRoll, readValue(buf));
          addPhase(lElbowYaw, readValue(buf));
          addPhase(lElbowRoll, readValue(buf));
          addPhase(rShoulderPitch, readValue(buf));
          addPhase(rShoulderRoll, readValue(buf));
          addPhase(rElbowYaw, readValue(buf));
          addPhase(rElbowRoll, readValue(buf));
        }
        else if(str == "setHead")
        {
          addPhase(headYaw, readValue(buf));
          addPhase(headPitch, readValue(buf));
        }
        else
          throw ParseException("expected keyword");

        while(*buf == ' ' || *buf == '\t')
          ++buf;
      }

      if(*buf == '#' || *buf == ';')
      {
        ++buf;
        while(*buf && *buf != '\r' && *buf != '\n')
          ++buf;
      }

      if(*buf && *buf != '\r' && *buf != '\n')
        throw ParseException("expected end of line");
    }
    catch(ParseException e)
    {
      OUTPUT(idText, text, "AsymmetricWalkingEngine: " << filePath << ":" << lineNumber << ": " << e.message);
      (void)e;
      error = true;
    }

    while(*buf && *buf != '\r' && *buf != '\n')
      ++buf;
    if(*buf == '\r' && buf[1] == '\n')
      buf += 2;
    else if(*buf)
      ++buf;
  }

  if(error)
  {
    for(int i = 0; i < numOfTracks; ++i)
      tracks[i].clear();
    OUTPUT(idText, text, "AsymmetricWalkingEngine: " << filePath << ": failed to load file");
    return false;
  }

  for(int i = 0; i < numOfTracks; ++i)
    addPhase(Track(i), 0);

  return true;
}
示例#14
0
void SubStep1_x_cpu (real dt) {

//<USER_DEFINED>
    INPUT(Pressure);
    INPUT(Density);
    INPUT(Pot);
    INPUT(Vx);
#ifdef MHD
#if defined (CYLINDRICAL) || defined (SPHERICAL)
    INPUT(Bx);
#endif
    INPUT(By);
    INPUT(Bz);
#endif
    OUTPUT(Vx_temp);
//<\USER_DEFINED>

//<EXTERNAL>
    real* p   = Pressure->field_cpu;
    real* pot = Pot->field_cpu;
    real* rho = Density->field_cpu;
#ifdef X
    real* vx      = Vx->field_cpu;
    real* vx_temp = Vx_temp->field_cpu;
#endif
#ifdef MHD
    real* bx = Bx->field_cpu;
    real* by = By->field_cpu;
    real* bz = Bz->field_cpu;
#endif
    int pitch  = Pitch_cpu;
    int stride = Stride_cpu;
    int size_x = XIP;
    int size_y = Ny+2*NGHY-1;
    int size_z = Nz+2*NGHZ-1;
    real dx = Dx;
//<\EXTERNAL>

//<INTERNAL>
    int i; //Variables reserved
    int j; //for the topology
    int k; //of the kernels
    int ll;
    real dtOVERrhom;
#ifdef X
    int llxm;
#endif
#ifdef Y
    int llyp;
#endif
#ifdef Z
    int llzp;
#endif
#ifdef MHD
    real db1;
    real db2;
    real bmeanm;
    real bmean;
#if defined (CYLINDRICAL)|| defined (SPHERICAL)
    real brmean;
#endif
#ifdef SPHERICAL
    real btmean;
#endif
#endif
//<\INTERNAL>

//<CONSTANT>
// real ymin(Ny+2*NGHY+1);
// real zmin(Nz+2*NGHZ+1);
//<\CONSTANT>

//<MAIN_LOOP>

    i = j = k = 0;

#ifdef Z
    for(k=1; k<size_z; k++) {
#endif
#ifdef Y
        for(j=1; j<size_y; j++) {
#endif
#ifdef X
            for(i=XIM; i<size_x; i++) {
#endif
//<#>
#ifdef X
                ll = l;
                llxm = lxm;
#ifdef Y
                llyp = lyp;
#endif
#ifdef Z
                llzp = lzp;
#endif
                dtOVERrhom=2.0*dt/(rho[ll]+rho[llxm]);
                vx_temp[ll] = vx[ll] -
                              dtOVERrhom*(p[ll]-p[llxm])/zone_size_x(j,k);
#ifdef POTENTIAL
                vx_temp[ll] -= (pot[ll]-pot[llxm])*dt/zone_size_x(j,k);
#endif

#ifdef MHD
#ifndef PASSIVEMHD
                bmean  = 0.5*(by[ll] + by[llyp]);
                bmeanm = 0.5*(by[llxm] + by[llxm+pitch]);

                db1 = (bmean*bmean-bmeanm*bmeanm);

#if defined(CYLINDRICAL) || defined(SPHERICAL)
                brmean = .5*(bmean+bmeanm);
                vx_temp[ll] += dtOVERrhom*brmean*bx[ll]/(MU0*ymed(j));
#endif

                bmean  = 0.5*(bz[ll] + bz[llzp]);
                bmeanm = 0.5*(bz[llxm] + bz[llxm+stride]);

                db2 = (bmean*bmean-bmeanm*bmeanm);

                vx_temp[ll] -= .5*dtOVERrhom*(db1 + db2)/(MU0*zone_size_x(j,k));
#ifdef SPHERICAL
                btmean = .5*(bmean+bmeanm);
                vx_temp[ll] += dtOVERrhom*btmean*cos(zmed(k)))*bx[ll]/(MU0*ymed(j)*sin(zmed(k)));
#endif
#endif
#endif
#endif
//<\#>
#ifdef X
            }
#endif
#ifdef Y
        }
#endif
#ifdef Z
    }
#endif
//<\MAIN_LOOP>
}
示例#15
0
main()
{
   double A[10][10], B[9][9], V[10], W[10], VV[10], X[10], Y[10];
   double S,AMAX,YMU,XMU,ERR,TOL;
   int NUM,FLAG,N,I,J,K,M,I1,N1,I2,L1,L2,NN,OK;
   FILE *OUP[1];

   INPUT(&OK, A, X, V, &N, &NN, &M, &TOL, &XMU);
   if (OK) {
      OUTPUT(OUP);
      /* STEP 1 */
      I = 1;
      AMAX = absval(V[0]);
      for (J=2; J<=N; J++) {
         if (absval(V[J-1]) > AMAX) {
            I = J;
            AMAX = absval(V[J-1]);
         }  
      }  
      /* STEP 2 */
      if (I != 1) {
         for (K=1; K<=I-1; K++)
            for (J=1; J<=I-1; J++) 
               B[K-1][J-1] = A[K-1][J-1] - V[K-1] * A[I-1][J-1] / V[I-1];
      }        
      /* STEP 3 */
      if ((I != 1) && (I != N)) {
         for (K=I; K<=N-1; K++)
            for (J=1; J<=I-1; J++) {
               B[K-1][J-1] = A[K][J-1]-V[K]*A[I-1][J-1]/V[I-1];
               B[J-1][K-1] = A[J-1][K]-V[J-1]*A[I-1][K]/V[I-1];
            }  
      }     
      /* STEP 4 */
      if (I != N) {
         for (K=I; K<=N-1; K++)
            for (J=I; J<=N-1; J++)
               B[K-1][J-1] = A[K][J]-V[K]*A[I-1][J]/V[I-1];
      }        
      /* STEP 5 */
      POWER(X, M, &OK, Y, B, &YMU, TOL, NN, OUP);
      if (OK) {
         /* STEP 6 */
         if (I != 1)
            for (K=1; K<=I-1; K++) W[K-1] = Y[K-1];
         /* STEP 7 */
         W[I-1] = 0.0;
         /* STEP 8 */
         if (I != N)
            for (K=I+1; K<=N; K++) W[K-1] = Y[K - 2]; 
         /* STEP 9 */
         S = 0.0;
         for (J=1; J<=N; J++) S = S + A[I-1][J-1] * W[J-1];
         S = S / V[I-1];
         for (K=1; K<=N; K++) 
            /* Compute eigenvector
               VV is used in place of U here */
            VV[K-1] = (YMU - XMU) * W[K-1] + S * V[K-1];
         fprintf(*OUP, "The reduced matrix B:\n");
         for (L1=1; L1<=M; L1++) {
            for (L2=1; L2<=M; L2++) fprintf(*OUP, "%.10e  ", B[L1-1][L2-1]);
            fprintf(*OUP, "\n");
         }  
         fprintf(*OUP, "\nThe Eigenvalue = %12.8f", YMU);
         fprintf(*OUP, " to Tolerance = %.10e\n\n", TOL);
         fprintf(*OUP, "Eigenvector is:\n");
         for (I=1; I<=N; I++) fprintf(*OUP," %11.8f", VV[I-1]);
         fprintf(*OUP, "\n");
      }  
      fclose(*OUP);
   }
   return 0;
}
示例#16
0
文件: drstrace.c 项目: rnk/drmemory
static void
print_arg(drsys_arg_t *arg)
{
    if (arg->ordinal == -1)
        OUTPUT("\tretval: ");
    else
        OUTPUT("\targ %d: ", arg->ordinal);
    /* XXX: add return value to dr_fprintf so we can more easily align
     * after PFX vs PIFX w/o having to print to buffer
     */
    switch (arg->type) {
    case DRSYS_TYPE_VOID:         print_simple_value(arg, true); break;
    case DRSYS_TYPE_POINTER:      print_simple_value(arg, true); break;
    case DRSYS_TYPE_BOOL:         print_simple_value(arg, false); break;
    case DRSYS_TYPE_INT:          print_simple_value(arg, false); break;
    case DRSYS_TYPE_SIGNED_INT:   print_simple_value(arg, false); break;
    case DRSYS_TYPE_UNSIGNED_INT: print_simple_value(arg, false); break;
    case DRSYS_TYPE_HANDLE:       print_simple_value(arg, false); break;
    case DRSYS_TYPE_NTSTATUS:     print_simple_value(arg, false); break;
    case DRSYS_TYPE_ATOM:         print_simple_value(arg, false); break;
    default: {
        if (arg->value == 0) {
            OUTPUT("<null>");
        } else if (arg->pre && !TEST(DRSYS_PARAM_IN, arg->mode)) {
            OUTPUT(PFX, arg->value);
        } else {
            switch (arg->type) {
            case DRSYS_TYPE_UNICODE_STRING: {
                print_unicode_string((UNICODE_STRING *) arg->value);
                break;
            }
            case DRSYS_TYPE_OBJECT_ATTRIBUTES: {
                OBJECT_ATTRIBUTES *oa = (OBJECT_ATTRIBUTES *) arg->value;
                OUTPUT("len="PIFX", root="PIFX", name=",
                       oa->Length, oa->RootDirectory);
                print_unicode_string(oa->ObjectName);
                OUTPUT(", att="PIFX", sd="PFX", sqos="PFX,
                       oa->Attributes, oa->SecurityDescriptor,
                       oa->SecurityQualityOfService);
                break;
            }
            case DRSYS_TYPE_IO_STATUS_BLOCK: {
                IO_STATUS_BLOCK *io = (IO_STATUS_BLOCK *) arg->value;
                OUTPUT("status="PIFX", info="PIFX"", io->StatusPointer.Status,
                       io->Information);
                break;
            }
            case DRSYS_TYPE_LARGE_INTEGER: {
                LARGE_INTEGER *li = (LARGE_INTEGER *) arg->value;
                OUTPUT("0x"HEX64_FORMAT_STRING, li->QuadPart);
                break;
            }
            default: {
                /* FIXME i#1089: add the other types */
                OUTPUT("<NYI>");
            }
            }
            /* XXX: we want KEY_VALUE_PARTIAL_INFORMATION, etc. like in
             * syscall_diagnostics.  Add drsyscall types for those, or hardcode here?
             */
        }
    }
    }
    
    OUTPUT(" (%s%s%stype=%s%s, size="PIFX")\n",
           (arg->arg_name == NULL) ? "" : "name=",
           (arg->arg_name == NULL) ? "" : arg->arg_name,
           (arg->arg_name == NULL) ? "" : ", ",
           (arg->type_name == NULL) ? "\"\"" : arg->type_name,
           (arg->type_name == NULL ||
            TESTANY(DRSYS_PARAM_INLINED|DRSYS_PARAM_RETVAL, arg->mode)) ? "" : "*",
           arg->size);
}
示例#17
0
uint8_t * USBKeyboard::reportDesc() {
    static uint8_t reportDescriptor[] = {
        USAGE_PAGE(1), 0x01,                    // Generic Desktop
        USAGE(1), 0x06,                         // Keyboard
        COLLECTION(1), 0x01,                    // Application
        REPORT_ID(1),       REPORT_ID_KEYBOARD,

        USAGE_PAGE(1), 0x07,                    // Key Codes
        USAGE_MINIMUM(1), 0xE0,
        USAGE_MAXIMUM(1), 0xE7,
        LOGICAL_MINIMUM(1), 0x00,
        LOGICAL_MAXIMUM(1), 0x01,
        REPORT_SIZE(1), 0x01,
        REPORT_COUNT(1), 0x08,
        INPUT(1), 0x02,                         // Data, Variable, Absolute
        REPORT_COUNT(1), 0x01,
        REPORT_SIZE(1), 0x08,
        INPUT(1), 0x01,                         // Constant


        REPORT_COUNT(1), 0x05,
        REPORT_SIZE(1), 0x01,
        USAGE_PAGE(1), 0x08,                    // LEDs
        USAGE_MINIMUM(1), 0x01,
        USAGE_MAXIMUM(1), 0x05,
        OUTPUT(1), 0x02,                        // Data, Variable, Absolute
        REPORT_COUNT(1), 0x01,
        REPORT_SIZE(1), 0x03,
        OUTPUT(1), 0x01,                        // Constant


        REPORT_COUNT(1), 0x06,
        REPORT_SIZE(1), 0x08,
        LOGICAL_MINIMUM(1), 0x00,
        LOGICAL_MAXIMUM(1), 0x65,
        USAGE_PAGE(1), 0x07,                    // Key Codes
        USAGE_MINIMUM(1), 0x00,
        USAGE_MAXIMUM(1), 0x65,
        INPUT(1), 0x00,                         // Data, Array
        END_COLLECTION(0),

        // Media Control
        USAGE_PAGE(1), 0x0C,
        USAGE(1), 0x01,
        COLLECTION(1), 0x01,
        REPORT_ID(1), REPORT_ID_VOLUME,
        USAGE_PAGE(1), 0x0C,
        LOGICAL_MINIMUM(1), 0x00,
        LOGICAL_MAXIMUM(1), 0x01,
        REPORT_SIZE(1), 0x01,
        REPORT_COUNT(1), 0x07,
        USAGE(1), 0xB5,             // Next Track
        USAGE(1), 0xB6,             // Previous Track
        USAGE(1), 0xB7,             // Stop
        USAGE(1), 0xCD,             // Play / Pause
        USAGE(1), 0xE2,             // Mute
        USAGE(1), 0xE9,             // Volume Up
        USAGE(1), 0xEA,             // Volume Down
        INPUT(1), 0x02,             // Input (Data, Variable, Absolute)
        REPORT_COUNT(1), 0x01,
        INPUT(1), 0x01,
        END_COLLECTION(0),
    };
    reportLength = sizeof(reportDescriptor);
    return reportDescriptor;
}
示例#18
0
void _ComputeEmf_cpu(real dt, int idx1, int idy1, int idz1, int idx2, int idy2, int idz2, Field *Bs1, Field *Vs1, Field *Bs2, Field *Vs2, Field* B1, Field*B2, Field* V1, Field* V2, Field* Emf) {

//<USER_DEFINED>

  /*
    Function that computes the EMF. It needs as input the star fields
    (bs1,vs1,bs2,vs2). The integers idx,idy,idz represent the direction
    in which the EMF is computed.
  */

  INPUT(B1);
  INPUT(B2);
  INPUT(V1);
  INPUT(V2);
  INPUT(Bs1);
  INPUT(Bs2);
  INPUT(Vs1);
  INPUT(Vs2);
  INPUT(Slope_v1);
  INPUT(Slope_v2);
  INPUT(Slope_b1);
  INPUT(Slope_b2);
  OUTPUT(Emf);
//<\USER_DEFINED>

//<EXTERNAL>
  real* slope_v1 = Slope_v1->field_cpu;
  real* slope_b1 = Slope_b1->field_cpu;
  real* slope_v2 = Slope_v2->field_cpu;
  real* slope_b2 = Slope_b2->field_cpu;
  real* b1 = B1->field_cpu;
  real* v1 = V1->field_cpu;
  real* b2 = B2->field_cpu;
  real* v2 = V2->field_cpu;
  real* bs1 = Bs1->field_cpu;
  real* bs2 = Bs2->field_cpu;
  real* vs1 = Vs1->field_cpu;
  real* vs2 = Vs2->field_cpu;
  real* emf = Emf->field_cpu;
  int pitch  = Pitch_cpu;
  int stride = Stride_cpu;
  int size_x = Nx+2*NGHX;
  int size_y = Ny+2*NGHY;
  int size_z = Nz+2*NGHZ;
  real dx = Dx;
//<\EXTERNAL>

//<INTERNAL>
  int i;
  int j;
  int k;
  int l1;
  int l2;
  int ll;
  real b1_mean;
  real b2_mean;
  real v1_mean;
  real v2_mean;
  real delta1;
  real delta2;
  real v1_mean_old;
  real v2_mean_old;
//<\INTERNAL>
  
//<CONSTANT>
// real ymin(Ny+2*NGHY+1);
// real zmin(Nz+2*NGHZ+1);
//<\CONSTANT>

//<MAIN_LOOP>

  for (k=1; k<size_z; k++) {
    for (j=1; j<size_y; j++) {
      for (i=XIM; i<size_x; i++) {

//<#>
	ll = l;
	l1 = lxm*idx1+lym*idy1+lzm*idz1;
	l2 = lxm*idx2+lym*idy2+lzm*idz2;
	
	delta1 = (zone_size_x(j,k)*idx1 +
		  zone_size_y(j,k)*idy1 +
		  zone_size_z(j,k)*idz1);
	
	delta2 = (zone_size_x(j,k)*idx2 +
		  zone_size_y(j,k)*idy2 +
		  zone_size_z(j,k)*idz2);
	
	v1_mean_old = 0.5*(v1[ll]+v1[l2]);
	v2_mean_old = 0.5*(v2[ll]+v2[l1]);
	
	if(v2_mean_old<0.0){
	  v1_mean = v1[ll]-.5*slope_v2[ll]*(delta2+v2_mean_old*dt);
	  b1_mean = b1[ll]-.5*slope_b2[ll]*(delta2+v2_mean_old*dt);
	}
	else{
	  v1_mean = v1[l2]+.5*slope_v2[l2]*(delta2-v2_mean_old*dt);
	  b1_mean = b1[l2]+.5*slope_b2[l2]*(delta2-v2_mean_old*dt);
	}
#ifdef STRICTSYM
	if (fabs(v2_mean_old) < SMALLVEL) {
	  v1_mean = .5*(v1[ll]+v1[l2]);
	  b1_mean = .5*(b1[ll]+b1[l2]);
	}
#endif
	if(v1_mean_old<0.0){
	  v2_mean = v2[ll]-.5*slope_v1[ll]*(delta1+v1_mean_old*dt);
	  b2_mean = b2[ll]-.5*slope_b1[ll]*(delta1+v1_mean_old*dt);
	}
	else{
	  v2_mean = v2[l1]+.5*slope_v1[l1]*(delta1-v1_mean_old*dt);
	  b2_mean = b2[l1]+.5*slope_b1[l1]*(delta1-v1_mean_old*dt);
	}
#ifdef STRICTSYM
	if (fabs(v1_mean_old) < SMALLVEL) {
	  v2_mean = .5*(v2[ll]+v2[l1]);
	  b2_mean = .5*(b2[ll]+b2[l1]);
	}
#endif
	emf[ll] = 0.5*(vs1[ll]*b2_mean + bs2[ll]*v1_mean -
		       vs2[ll]*b1_mean - bs1[ll]*v2_mean);
//<\#>
      }
    }
  }
//<\MAIN_LOOP>
}
示例#19
0
/*******************************************************************-o-******
 * test_dokeyedhash
 *
 * Returns:
 *	Number of failures.
 *
 *
 * Test keyed hashes with a variety of MAC length requests.
 *
 *
 * NOTE Both tests intentionally use the same secret
 *
 * FIX	Get input or output from some other package which hashes...
 * XXX	Could cut this in half with a little indirection...
 */
int
test_dokeyedhash(void)
{
    int             rval = SNMPERR_SUCCESS, failcount = 0, bigstring_len = strlen(BIGSTRING), secret_len = strlen(BIGSECRET), properlength, mlcount = 0,        /* MAC Length count.   */
                    hblen;      /* Hash Buffer length. */

    u_int           hashbuf_len[MLCOUNT_MAX] = {
        LOCAL_MAXBUF,
        BYTESIZE(SNMP_TRANS_AUTHLEN_HMACSHA1),
        BYTESIZE(SNMP_TRANS_AUTHLEN_HMACMD5),
        BYTESIZE(SNMP_TRANS_AUTHLEN_HMAC96),
        7,
        0,
    };

    u_char          hashbuf[LOCAL_MAXBUF];
    char           *s;

  test_dokeyedhash_again:

    OUTPUT("Keyed hash test using MD5 --");

    memset(hashbuf, 0, LOCAL_MAXBUF);
    hblen = hashbuf_len[mlcount];
    properlength = BYTESIZE(SNMP_TRANS_AUTHLEN_HMACMD5);

    rval =
        sc_generate_keyed_hash(usmHMACMD5AuthProtocol,
                               USM_LENGTH_OID_TRANSFORM, BIGSECRET,
                               secret_len, BIGSTRING, bigstring_len,
                               hashbuf, &hblen);
    FAILED(rval, "sc_generate_keyed_hash().");

    if (hashbuf_len[mlcount] > properlength) {
        if (hblen != properlength) {
            FAILED(SNMPERR_GENERR, "Wrong MD5 hash length returned.  (1)");
        }

    } else if (hblen != hashbuf_len[mlcount]) {
        FAILED(SNMPERR_GENERR, "Wrong MD5 hash length returned.  (2)");
    }

    rval =
        sc_check_keyed_hash(usmHMACMD5AuthProtocol,
                            USM_LENGTH_OID_TRANSFORM, BIGSECRET,
                            secret_len, BIGSTRING, bigstring_len, hashbuf,
                            hblen);
    FAILED(rval, "sc_check_keyed_hash().");

    binary_to_hex(hashbuf, hblen, &s);
    fprintf(stdout, "hash buffer (len=%d, request=%d):   %s\n",
            hblen, hashbuf_len[mlcount], s);
    SNMP_FREE(s);

    SUCCESS("Keyed hash test using MD5.");



    OUTPUT("Keyed hash test using SHA1 --");

    memset(hashbuf, 0, LOCAL_MAXBUF);
    hblen = hashbuf_len[mlcount];
    properlength = BYTESIZE(SNMP_TRANS_AUTHLEN_HMACSHA1);

    rval =
        sc_generate_keyed_hash(usmHMACSHA1AuthProtocol,
                               USM_LENGTH_OID_TRANSFORM, BIGSECRET,
                               secret_len, BIGSTRING, bigstring_len,
                               hashbuf, &hblen);
    FAILED(rval, "sc_generate_keyed_hash().");

    if (hashbuf_len[mlcount] > properlength) {
        if (hblen != properlength) {
            FAILED(SNMPERR_GENERR,
                   "Wrong SHA1 hash length returned.  (1)");
        }

    } else if (hblen != hashbuf_len[mlcount]) {
        FAILED(SNMPERR_GENERR, "Wrong SHA1 hash length returned.  (2)");
    }

    rval =
        sc_check_keyed_hash(usmHMACSHA1AuthProtocol,
                            USM_LENGTH_OID_TRANSFORM, BIGSECRET,
                            secret_len, BIGSTRING, bigstring_len, hashbuf,
                            hblen);
    FAILED(rval, "sc_check_keyed_hash().");

    binary_to_hex(hashbuf, hblen, &s);
    fprintf(stdout, "hash buffer (len=%d, request=%d):   %s\n",
            hblen, hashbuf_len[mlcount], s);
    SNMP_FREE(s);

    SUCCESS("Keyed hash test using SHA1.");



    /*
     * Run the basic hash tests but vary the size MAC requests.
     */
    if (hashbuf_len[++mlcount] != 0) {
        goto test_dokeyedhash_again;
    }


    return failcount;

}                               /* end test_dokeyedhash() */
示例#20
0
文件: ser_port.c 项目: dorienh/smmu
void InitPort (void)
{
  int mcr;
  int temp;

  if(port_initted)
    return;
  
  //
  // Reset the output queue
  //

  outque.head = outque.tail = 0;

  //
  // find the irq and io address of the port
  //
  GetUart ();

  //
  // init com port settings
  //
  regs.x.ax = 0xf3;               //f3= 9600 n 8 1
  regs.x.dx = comport - 1;
  int86 (0x14, &regs, &regs);
  
  //
  // check for a 16550
  //
  OUTPUT(uart + FIFO_CONTROL_REGISTER, FCR_FIFO_ENABLE + FCR_TRIGGER_04);
  temp = INPUT(uart + INTERRUPT_ID_REGISTER);
  if ((temp & 0xf8) == 0xc0)
    {
      uart_type = UART_16550;
      usermsg ("UART is a 16550");
    }
  else
    {
      uart_type = UART_8250;
      OUTPUT(uart + FIFO_CONTROL_REGISTER, 0);
      usermsg("UART is an 8250");
    }
  
  //
  // prepare for interrupts
  //

  OUTPUT(uart + INTERRUPT_ENABLE_REGISTER, 0);
  mcr = INPUT(uart + MODEM_CONTROL_REGISTER);
  mcr |= MCR_OUT2;
  mcr &= ~MCR_LOOPBACK;
  OUTPUT(uart + MODEM_CONTROL_REGISTER, mcr);
  
  INPUT(uart);  // Clear any pending interrupts
  INPUT(uart + INTERRUPT_ID_REGISTER);
  
  //
  // hook the irq vector
  //
  irqintnum = irq + 8;
  
  asm("cli"); // disable interrupts

  _go32_dpmi_get_protected_mode_interrupt_vector(irqintnum, &oldirqvect);
  newirqvect.pm_offset = (int)isr_8250;
  newirqvect.pm_selector = _go32_my_cs();
  _go32_dpmi_allocate_iret_wrapper(&newirqvect);
  _go32_dpmi_set_protected_mode_interrupt_vector(irqintnum, &newirqvect);

  asm("sti"); // enable interrupts
	
  OUTPUT(0x20 + 1, INPUT(0x20 + 1) & ~(1<<irq));

  asm("cli"); // disable again

  // enable RX and TX interrupts at the uart
  
  OUTPUT(uart + INTERRUPT_ENABLE_REGISTER,
	 IER_RX_DATA_READY + IER_TX_HOLDING_REGISTER_EMPTY);

  // enable interrupts through the interrupt controller
  
  OUTPUT(0x20, 0xc2);

  // set DTR
  OUTPUT(uart + MODEM_CONTROL_REGISTER
	  , INPUT(uart + MODEM_CONTROL_REGISTER) | MCR_DTR);
  
  asm("sti"); // re-enable

  port_initted = true;
}
示例#21
0
文件: bootkbd.c 项目: jvesely/helenos
		LOGICAL_MAXIMUM1(1),
		REPORT_SIZE1(1),
		REPORT_COUNT1(8),
		/* Modifiers */
		INPUT(IOF_DATA | IOF_VARIABLE | IOF_ABSOLUTE),
		REPORT_COUNT1(1),
		REPORT_SIZE1(8),
		/* Reserved */
		INPUT(IOF_CONSTANT),
		REPORT_COUNT1(5),
		REPORT_SIZE1(1),
		STD_USAGE_PAGE(USB_HIDUT_PAGE_LED),
		USAGE_MINIMUM1(1),
		USAGE_MAXIMUM1(5),
		/* LED states */
		OUTPUT(IOF_DATA | IOF_VARIABLE | IOF_ABSOLUTE),
		REPORT_COUNT1(1),
		REPORT_SIZE1(3),
		/* LED states padding */
		OUTPUT(IOF_CONSTANT),
		REPORT_COUNT1(6),
		REPORT_SIZE1(8),
		LOGICAL_MINIMUM1(0),
		LOGICAL_MAXIMUM1(101),
		STD_USAGE_PAGE(USB_HIDUT_PAGE_KEYBOARD),
		USAGE_MINIMUM1(0),
		USAGE_MAXIMUM1(101),
		/* Key array */
		INPUT(IOF_DATA | IOF_ARRAY),
	END_COLLECTION()
};
示例#22
0
文件: ser_port.c 项目: dorienh/smmu
void isr_8250(void)
{
  int c;
  int count;

  while (1)
    {
      switch( INPUT( uart + INTERRUPT_ID_REGISTER ) & 7 )
	{
	  // not enabled
	case IIR_MODEM_STATUS_INTERRUPT :
	  modem_status = INPUT( uart + MODEM_STATUS_REGISTER );
	  break;
	  
	  // not enabled
	case IIR_LINE_STATUS_INTERRUPT :
	  line_status = INPUT( uart + LINE_STATUS_REGISTER );
	  break;
	  
	  //
	  // transmit
	  //
	case IIR_TX_HOLDING_REGISTER_INTERRUPT :
	  //I_ColorBlack (63,0,0);
	  if (outque.tail < outque.head)
	    {
	      if (uart_type == UART_16550)
		count = 16;
	      else
		count = 1;
	      do
		{
		  c = outque.data[outque.tail%QUESIZE];
		  outque.tail++;
		  OUTPUT( uart + TRANSMIT_HOLDING_REGISTER, c );
		} while (--count && outque.tail < outque.head);
	    }
	  break;
	  
	  //
	  // receive
	  //
	case IIR_RX_DATA_READY_INTERRUPT :
	  do
	    {
	      c = INPUT( uart + RECEIVE_BUFFER_REGISTER );
	      inque.data[inque.head%QUESIZE] = c;
	      inque.head++;
	    } while ( uart_type == UART_16550 && INPUT( uart + LINE_STATUS_REGISTER ) & LSR_DATA_READY );
	  
	  break;
	  
	  //
	  // done
	  //
	default:
	  OUTPUT( 0x20, 0x20 );
	  return;
	}
    }
}
示例#23
0
int main(int argc, char *argv[]) {
/*
DRIVER_01 is a FLOW-MOTION LIMITED flow scheme! The flow will end when all vents
          have no more lava to effuse AND when the flow is no longer innundating
          new grid cells.
*/
/*DRIVER for a lava flow code ALGORITHM:
         Read in a Configuration File with INITIALIZE
         Load a DEM Raster with DEM_LOADER and assign parameters to a data grid
         Create Cellular Automata lists and assign source vents with INIT_FLOW
         
         Main Flow Loop:
           If there is more volume to erupt at source vents, call PULSE
           Move lava from cells to neighbors with DISTRIBUTE
           If flow is still moving, keep looping to call DISTRIBUTE
         
         After flow is completely erupted:
           Check for Conservation of Mass
           Write out requested Model Output to user-defined file paths
*/
	
	/*VARIABLES******************************************************************/
	/*Files*/
	char     *configFilename = argv[1]; /*configuration file path               */
	char     **Filenames;               /*A list of file paths for model output */
	char     tempFilename[15];          /*A temporary file path for whatever use*/
	
	/*Main Arrays*/
	DataCell **dataGrid;                /*Global Data Grid                      */
	Automata **CAList;                  /*Cellular Automata Lists (Active Cells)*/
	VentArr  *Vents;                    /*Source Vent List                      */
	unsigned *ActiveCounter;            /*Number of Active Cells in CA List     */
	
	/*Model Parameters*/
	int      i,j, ret;                  /*loop variables, function return value */
	unsigned CAListCount = 0;           /*Number of CA Lists, def in INIT_FLOW  */
	unsigned CAListSize  = 0;           /*Size of each CA List, def in INIT_FLOW*/
	unsigned ventCount   = 0;           /*Number of Src Vents, def in INITIALIZE*/
	int      pulseCount  = 0;           /*Current number of Main PULSE loops    */
	
	/*Physical Parameters*/
	double   residualThickness;         /*Residual Flow Thickness               */
	double   *DEMmetadata;              /*Geographic Coordinates of DEM Raster  */
	double   elevationUncertainty;      /*DEM Raster Elevation Uncertainty      */
	double   volumeToErupt;             /*Total Volume to deliver to vent cells */
	double   volumeErupted = 0;         /*Total Volume in All Active Cells      */
	double   volumeRemaining;           /*Volume Remaining to be Erupted        */
	int      volumeRemainingBool = 0;   /*0 if volume left to erupt, otherwise 1*/
	
	/*Post Flow Motion Detection Variables*/
	double   TotalMotion = 0;           /*Summed thickness change in all cells  */
	double   MinTotalMotion = 1e-11;    /*Threshold: below it flow is "stagnant"*/
	unsigned lastmotionCounter = 0;     /*Number of loops since last motion     */
	unsigned maxLastMotionCount = 10;   /*Max loops allowed since last motion   */
	unsigned lastActiveCounter = 0;     /*Number of active cells in prev. loop  */
	time_t   LastInundationTime;        /*Timestamp of last active cell creation*/
	double   maxLastInundationTime=10.0;/*Max time allowed since last cell cretn*/
	
	
	/*TIME AND RANDOM NUMBER GEN*************************************************/
	startTime = time(NULL); /*Define Start Time*/
	srand(time(NULL));      /*Seed random number generator*/
	
	/*WELCOME USER TO SIMULATION AND CHECK FOR CORRECT USAGE*********************/
	printf("\n\n               MOLASSES is a lava flow simulator.\n\n");
	
	/*User must supply the name of the executable and a configuration file*/
	if(argc<2) {
		printf("Usage: %s config-filename\n",argv[0]);
		return(-1);
	}
	
	printf("Beginning flow simulation...\n");
	
	/*MODULE: INITIALIZE*********************************************************/
	/*        Assigns several empty variables based on a user-defined 
	            configuration file.                                             */
	/*        File Name List output in this order:
	            [0] - DEM
	            [1] - Residual Flow Thickness
	            [2] - Elevation Uncertainty
	            [3] - Output file: ASCII X,Y,Thickness
	            [4] - Output file: Hit Map
	            [5] - Output file: Raster Thickness
	            [6] - Output file: Raster Elevation
	            [7] - Output file: Raster Elevation + Flow Thickness            */
	
	ret = INITIALIZE(configFilename,        /*chr Configuration File Name       */
	                 &Filenames,            /*chr File Name List                */
	                 &residualThickness,    /*dbl Global Residual Flow Thickness*/
	                 &elevationUncertainty, /*dbl Global Elevation Uncertainty  */
	                 &Vents,                /*ventarr Vent Structure Array      */
	                 &ventCount             /*unsignd Number of Vents           */
	                );
	
	/*Check for Error flag (INITIALIZE returns <0 value)*/
	if(ret<0){
		printf("\nERROR [MAIN]: Error flag returned from [INITIALIZE].\n");
		printf("Exiting.\n");
		return(-1);
	}
	
	
	/*MODULE: DEM_LOADER*********************************************************/
	/*        Loads Raster into Global Data Grid based on code:
	            TOPOG - Loads a DEM raster into the data grid's dem_elev value
	            RESID - Loads a raster into the data grid's residual value
	            T_UNC - Loads a raster into the data grid's elev_uncert value
	          Returns a metadata list of geographic coordinates of the raster   */
	/*        DEMmetadata format:
		          [0] lower left x
		          [1] w-e pixel resolution
		          [2] number of cols, assigned manually
		          [3] lower left y
		          [4] number of lines, assigned manually
		          [5] n-s pixel resolution (negative value)                       */
	
	/*Assign Topography to Data Grid Locations*/
	DEMmetadata = DEM_LOADER(Filenames[0], /*char            DEM file name   */
	                         &dataGrid,    /*DataCell        Global Data Grid*/
	                         "TOPOG"       /*DEM_LOADER Code Topography      */
	                        );
	
	/*Check for Error flag (DEM_LOADER returns a null metadata list)*/
	if(DEMmetadata==NULL){
		printf("\nError [MAIN]: Error flag returned from DEM_LOADER[TOPOG].\n");
		printf("Exiting.\n");
		return(-1);
	}
	
	
	/*Assign Residual Thickness to Data Grid Locations*/
	/*If residualThickness is -1, user input a Residual Thickness Map*/
	if(residualThickness==-1) {
		DEMmetadata = DEM_LOADER(Filenames[1], /*char            Residual filename*/
			                       &dataGrid,    /*DataCell        Global Data Grid */
			                       "RESID"       /*DEM_LOADER Code Resid Thickness  */
			                      );
	
		/*Check for Error flag (DEM_LOADER returns a null metadata list)*/
		if(DEMmetadata==NULL){
			printf("\nError [MAIN]: Error flag returned from DEM_LOADER[RESID].\n");
			printf("Exiting.\n");
			return(-1);
		}
	}
	/*If residualThickness is not -1, it is constant globally.*/
	else {
		/*Write residual flow thickness into 2D Global Data Array*/
		for(i=0;i<DEMmetadata[4];i++) {
			for(j=0;j<DEMmetadata[2];j++) {
				dataGrid[i][j].residual = residualThickness;
			}
		}
	}
	
	
	/*Assign Elevation Uncertainty to Data Grid Locations*/
	/*If elevationUncertainty is -1, user input an elevation uncertainty map*/
	if(elevationUncertainty==-1) {
		DEMmetadata = DEM_LOADER(Filenames[2], /*char            uncertny filename*/
			                       &dataGrid,    /*DataCell        Global Data Grid */
			                       "T_UNC"       /*DEM_LOADER Code elev uncertainty */
			                      );
	
		/*Check for Error flag (DEM_LOADER returns a null metadata list)*/
		if(DEMmetadata==NULL){
			printf("\nError [MAIN]: Error flag returned from DEM_LOADER[T_UNC].\n");
			printf("Exiting.\n");
			return(-1);
		}
	}
	/*If elevationUncertainty is not -1, it is constant globally.*/
	else {
		/*Write elevation uncertainty values into 2D Global Data Array*/
		for(i=0;i<DEMmetadata[4];i++) {
			for(j=0;j<DEMmetadata[2];j++) {
				dataGrid[i][j].elev_uncert = elevationUncertainty;
			}
		}
	}
	
	
	/*MODULE: INIT_FLOW**********************************************************/
	/*        Creates Active Cellular Automata lists and activates vents in them.
	          Also creates bookkeeper variables: 
	            total size of CA lists
	            total number of CA lists
	            total number of active automata in the CA list
	            total volume to erupt (combined volumes to erupt at vents)      */
	
	ret = INIT_FLOW(dataGrid,      /*DataCell  Global Data Grid                 */
	               &CAList,        /*Automaton Active Cells List                */
	               Vents,          /*VentArr   Vent Data Array                  */
	               &CAListCount,   /*unsigned  Number of CA Lists created       */
	               &CAListSize,    /*unsigned  Size of each empty CA List       */
	               ventCount,      /*unsigned  Number of Vents                  */
	               &ActiveCounter, /*unsigned  Number of active cells in CA List*/
	               DEMmetadata,    /*double    Geographic Metadata              */
	               &volumeToErupt  /*double    Volume that the model will expel */
	              );
	
	/*Check for Error flag (INIT_FLOW returns <0 value)*/
	if(ret<0) {
		printf("\nError [MAIN]: Error flag returned from [INIT_FLOW].\n");
		printf("Exiting.\n");
		return(-1);
	}
	
	
	
	
	/****************************************************************************/
	/*MAIN FLOW LOOP: PULSE LAVA AND DISTRIBUTE TO CELLS*************************/
	/****************************************************************************/
	volumeRemaining = volumeToErupt; /*set countdown bookkeeper volumeRemaining*/
	
	printf("\n                         Running Flow\n");
	
	
	/*Loop to call PULSE and DISTRIBUTE only if volume remains to be erupted
	  OR if flow has not stopped moving*/
	while((volumeRemaining > 0)||(lastmotionCounter<maxLastMotionCount)) {
		
		if(volumeRemaining > 0) { /*If there is more lava to erupt, call PULSE*/
		/*MODULE: PULSE************************************************************/
		/*        Delivers lava to vents based on information in Vent Data Array.
		          Returns total volume remaining to be erupted.                   */
	
		ret = PULSE(CAList[1],        /*Automaton Active Cells List               */
		            &Vents,           /*VentArr   Vent Data Array                 */
		            ActiveCounter[1], /*unsigned  Number of activ cells in CA List*/
		            &volumeRemaining, /*double    Countdown Lava Volume bookkeeper*/
		            ventCount,        /*unsigned  Number of vents                 */
		            DEMmetadata       /*double    Geographic Metadata             */
		           );
	
		/*Check for Error flags (PULSE returns <0 or 0 value)*/
		if(ret<0) {
			printf("\nERROR [MAIN]: Error flag returned from [PULSE].\n");
			printf("Exiting.\n");
			return(-1);
		}
		else if (ret==0) {
			if (volumeRemaining) {
				/*This return should not be possible, 
				  Pulse should return 0 if no volume remains*/
				printf("\nERROR [MAIN]: Error between [PULSE] return and lava vol.\n");
				printf("Exiting.\n");
				return(-1);
			}
			/*If ret==0, PULSE was called even though there was no lava to distribute.
			  Do not call Pulse or Distribute anymore! Break out of While loop.     */
			break;
		}
		/*if Pulse module successfully updated vents, ret will > 0.
		  Continue, call Distribute module.*/
		
		/*Update status message on screen*/
		printf("\rInundated Cells: %-7d; Volume Remaining: %10.2f",ActiveCounter[1],
		       volumeRemaining);
		}
		else { /*if no more volume to erupt, but flow still moving*/
		/*Update status message on screen to show flow motion*/
			printf("\rInundated Cells: %-7d; total dZ in flow: %10.2e",ActiveCounter[1],
		       TotalMotion);
		}
		
		
		/*MODULE: DISTRIBUTE*******************************************************/
		/*        Distributes lava from cells to neighboring cells depending on
		          module specific algorithm (e.g. slope-proportional sharing).
		          Updates a Cellular Automata List and the active cell counter.*/
		
		ret = DISTRIBUTE(dataGrid,          /*DataCell  Global Data Grid       */
		                 CAList[1],         /*Automaton Active Cells List      */
		                 &ActiveCounter[1], /*unsigned  Number of active cells */
		                 DEMmetadata        /*double    Geographic Metadata    */
		                );
		
		/*Check for Error flag (DISTRIBUTE returns <0 value)*/
		if(ret<0) {
			printf("\nERROR [MAIN]: Error flag returned from [DISTRIBUTE].\n");
			printf("Exiting.\n");
			return(-1);
		}
		
		/*If you want to output the flow at EVERY Pulse, here is a good place to do
		  it. A temporary file name variable is declared using the number of times 
		  this Pulse loop has been completed, then the OUTPUT module is called.
		  Uncomment the lines below if you want this. Commenting out the file name
		  declaration creates warnings since the variables won't later be used, so
		  I've left it uncommented out. (It only runs once per pulse, so it doesn't
		  slow the code down).*/
		
		/*increment pulse count, then rename the temporary file path.*/
		snprintf(tempFilename,15,"pulse_%04d.xyz",(++pulseCount));
		/*MODULE: OUTPUT**************************************/
		/*        writes out a file. Arguments:
		            DataCell  Global Data Grid
		            Automaton Active Cells List
		            unsigned  Number of active cells
		            string    Output Filename
		            OUTPUT Code: 0 = ASCII X,Y,Thickness File
		            double    Geographic Metadata
		            string    Original Raster Projection     */
		/*
		ret = OUTPUT(dataGrid,
		             CAList[1],
		             ActiveCounter[1],
		             tempFilename,
		             0,
		             DEMmetadata,
		             ""
		            );
		*/
		/*Check for Error flag (OUTPUT returns <0 value)*/
		/*
		if(ret<0){
			printf("\nERROR [MAIN]: Error flag returned from [OUTPUT].\n");
			printf("Exiting.\n");
			return(-1);
		}
		*/
		
		
		
		
		
		
		/*TEST TO SEE IF FLOW IS STILL PROGRESSING, IF VOLUME HAS RUN OUT*/
		/*This Driver Module continues to call the DISTRIBUTE Module if there is
		  significant flow within the lava flow, even after all lava has been 
		  delivered to the vents via the PULSE Module.
		  
		  Flow will continue to distribute if:
		    1) There is still volume to deliver to vent
		    2) The summed change in flow thickness across all cells is > than 
		       a pre-defined MinTotalMotion variable.
		    3) The time elapsed in seconds since the last active cell was created
		       is < than a pre-defined maxLastInundationTime.
		  
		  If the summed change in flow thickness (dz) is negligable, 
		    lastmotionCounter is incremented. If lastmotionCounter==pre-defined 
		    maxLastMotionCount, flow will stop.
		  If the time elapsed since the last cell creation is significant,
		    lastmotionCounter will be set at maxLastMotionCount, flow will stop.
		  */
		
		/*Only test for remaining flow IF eruption volume has run out*/
		if(volumeRemaining<=0) {
			/*If this is the first time volume is 0, start new screen output line*/
			if((volumeRemainingBool++)==0) printf("\n");
			
			/*MOTION TEST - If movement has stopped, end the flow*/
			TotalMotion=0.0; /*Reset TotalMotion to 0*/
			for(i=1;i<=ActiveCounter[1];i++) {
				/*Add change in volume of all active cells
				  CA List[2] is a copy of the Active CA List of the last Pulse Loop*/
				TotalMotion += fabs(CAList[1][i].elev - CAList[2][i].elev);
			}
			
			/*If flow has not changed, increment lastmotionCounter*/
			if(TotalMotion <= MinTotalMotion) ++lastmotionCounter;
			/*If flow has changed, reset lastmotionCounter and store flow values
			    in spare CA List.*/
			else{
				lastmotionCounter=0;                     /*reset*/
				for(i=1;i<=ActiveCounter[1];i++) {       /*For all Active Cells*/
					CAList[2][i].elev = CAList[1][i].elev; /*Copy CA List[1] to List[2]*/
				}
			}
			
			/*POPCORN RULE - If a new cell hasn't been created in X secs, end flow*/
			if(lastActiveCounter!=ActiveCounter[1]) { /*If there's a new cell*/
				LastInundationTime = time(NULL);        /*Reset Last inundation time*/
				lastActiveCounter=ActiveCounter[1];     /*Reset lastActiveCounter*/
			}
			/*If there are no new cells, check that X secs have not gone by.*/
			else {
				/*If max time to wait for a new cell HAS been reached, end the flow*/
				if(((unsigned) (time(NULL)-LastInundationTime))>=maxLastInundationTime) {
					printf("\n Ending Flow because last cell to be inundated was ");
					printf(">%u secs ago.", (unsigned) (time(NULL)-LastInundationTime));
					lastmotionCounter=maxLastMotionCount;
				}
			}
		} /*End of Remaining Detectable Flow Check*/
		
		
	} /*End while main flow loop: (while(volumeRemaining>0)and Flow Motion)*/
	
	
	/*POST FLOW WRAP UP**********************************************************/
	
	printf("\n\n                     Single Flow Complete!\n");
	
	/*Print out final number of inundated cells*/
	printf("Final Count: %d cells inundated.\n\n", ActiveCounter[1]);
	
	
	/*POST FLOW WRAP UP: CONSERVATION OF MASS CHECK******************************/
	/*ALL DRIVER MODULES MUST HAVE THIS. In order to do unit testing during
	  code compilation, makefile searches for the string "SUCCESS: MASS CONSERVED"
	  to conclude that the code is Verified (though not validated).*/
	
	volumeErupted = 0;
	/*For each Active Flow Cell, add cell lava volume to volumeErupted*/
	for(i=1;i<=ActiveCounter[1];i++)
		volumeErupted += (CAList[1][i].thickness + 
		               dataGrid[CAList[1][i].row][CAList[1][i].col].residual) *
		               DEMmetadata[1] * DEMmetadata[5];
	
	/*print out volume delivered to vents and total volume now in cells*/
	printf("Conservation of mass check\n");
	printf(" Total (IN) volume pulsed from vents:   %0.3f\n",volumeToErupt);
	printf(" Total (OUT) volume found in cells:     %0.3f\n",volumeErupted);
	/*Double data types are precise to 1e-8, so make sure that volume IN and
	  volume OUT are within this precision.*/
	if(abs(volumeErupted-volumeToErupt)<=1e-8)
		printf(" SUCCESS: MASS CONSERVED\n");
	/*If volumes are significantly different (are more than Double Precision diff.
	  then mass is NOT conserved!!*/
	else 
		/*Print the mass excess*/
		printf(" ERROR: MASS NOT CONSERVED! Excess: %0.2e m^3",
		       volumeErupted-volumeToErupt);
	
	
	/*MODULE: OUTPUT*************************************************************/
	/*        Writes out model output to a file path.
	          File Output types available, and their codes:
	            0: X,Y,Thickness ascii flow list
	            1: Hit Raster (1 = Hit, 0 = Not Hit)
	            2: Thickness Raster
	            3: Elevation Raster
	            4: Elevation + Lava Raster (code 2 + code 3)
	          
	          Filename Index output from INITIALIZE:
	            Filenames[3] - Output file: ASCII X,Y,Thickness
	            Filenames[4] - Output file: Hit Map
	            Filenames[5] - Output file: Raster Thickness
	            Filenames[6] - Output file: Raster Elevation
	            Filenames[7] - Output file: Raster Elevation + Flow Thickness   */
	
	/*Check Filenames Array to see if a filename was given (so model output is
	  requested).*/
	for(i=0;i<4;i++){
		/*Check to see if the File Path is not empty (the following test will !=0)*/
		if(strlen(Filenames[i+3]) > 1) {
		/*If there's a file path given, write model output to it.*/
			ret = OUTPUT(dataGrid,         /*DataCell  Global Data Grid           */
			             CAList[1],        /*Automaton Active Cells List          */
			             ActiveCounter[1], /*unsigned  Number of active cells     */
			             Filenames[i+3],   /*string    Output File Path           */
			             i,                /*OUTPUT Code, see above               */
			             DEMmetadata,""    /*string    Original Raster Projection */
			            );
			
			/*Check for Error flag (OUTPUT returns <0 value)*/
			if(ret<0){
				printf("\nERROR [MAIN]: Error flag returned from [OUTPUT].\n");
				printf("Exiting.\n");
				return(-1);
			}
		}
	}
	
	/*Calculate simulation time elapsed, and print it.*/
	endTime = time(NULL);
	printf("\nElapsed Time of simulation approximately %u seconds.\n\n",
	       (unsigned)(endTime - startTime));
	
	return(0);
}
示例#24
0
main()
{
   double TOL[20], A[20], H[20], FA[20], FC[20], FB[20], S[20], V[7]; 
   int L[20]; 
   double AA,BB,EPS,APP,FD,FE,S1,S2; 
   int CNT,N,I,LEV,OK; 

   double F(double, int *); 
   double absval(double);
   void INPUT(int *, double *, double *, double *, int *); 
   void OUTPUT(double, double, double, double, int);

   INPUT(&OK, &AA, &BB, &EPS, &N); 
   if (OK) {
      CNT = 0;
      OK = true;
      /* STEP 1 */ 
      APP = 0.0; 
      I = 1;
      TOL[I] = 10.0 * EPS;
      A[I] = AA;
      H[I] = 0.5 * (BB - AA);
      FA[I] = F(AA, &CNT);
      FC[I] = F((AA+H[I]), &CNT);
      FB[I] = F(BB, &CNT);
      /* Approximation from Simpsons method for entire interval. */
      S[I] = H[I] * (FA[I] + 4.0 * FC[I] + FB[I]) / 3.0;
      L[I] = 1;
      /* STEP 2 */ 
      while ((I > 0) && OK) {   
	 /* STEP 3 */ 
	 FD = F((A[I] + 0.5 * H[I]), &CNT);     
	 FE = F((A[I] + 1.5 * H[I]), &CNT);
	 /* Approximation from Simpsons method for halves of intervals.*/
	 S1 = H[I] * (FA[I] + 4.0 * FD + FC[I]) / 6.0;
	 S2 = H[I] * (FC[I] + 4.0 * FE + FB[I]) / 6.0;
	 /* Save data at this level */
	 V[0] = A[I];
	 V[1] = FA[I];
	 V[2] = FC[I];
	 V[3] = FB[I];
	 V[4] = H[I];
	 V[5] = TOL[I];
	 V[6] = S[I];
	 LEV = L[I];
	 /* STEP 4 */ 
	 /* Delete the level */
	 I--;   
	 /* STEP 5 */ 
	 if (absval(S1 + S2 - V[6]) < V[5])     
	    APP = APP + (S1 + S2);
	 else {
	    if (LEV >= N) OK = false;   /* procedure fails */
	    else {
	       /* Add one level */
	       /* Data for right half subinterval */
	       I++;
	       A[I] = V[0] + V[4];
	       FA[I] = V[2]; 
	       FC[I] = FE;
	       FB[I] = V[3];
	       H[I] = 0.5 * V[4]; 
	       TOL[I] = 0.5 * V[5];
	       S[I] = S2;
	       L[I] = LEV + 1;
	       /* Data for left half subinterval */  
	       I++;
	       A[I] = V[0];
	       FA[I] = V[1];
	       FC[I] = FD;
	       FB[I] = V[2];
	       H[I] = H[I-1];
	       TOL[I] = TOL[I-1];
	       S[I] = S1;
	       L[I] = L[I-1];
	    }
	 }
      }
      if (!OK) printf("Level exceeded\n");
      else OUTPUT(AA, BB, APP, EPS, CNT); 
   }
   return 0;
}
示例#25
0
文件: pulp.cpp 项目: h3rb/pulp
void LoadConfig() {
 OUTPUT("Loading initial config file `%s`...\n", cmdline.pathsfile.c_str() );
 cfg.Load("paths",cmdline.pathsfile.c_str());
 string mud=cfg.find("paths","mud");
 cfg.Load("mud",mud.c_str());
}
示例#26
0
bool TeamRobot::main()
{
  {
    SYNC;
    OUTPUT(idProcessBegin, bin, 't');

    DECLARE_DEBUG_DRAWING("representation:RobotPose", "drawingOnField"); // The robot pose
    DECLARE_DEBUG_DRAWING("representation:RobotPose:deviation", "drawingOnField"); // The robot pose
    DECLARE_DEBUG_DRAWING("origin:RobotPose", "drawingOnField"); // Set the origin to the robot's current position
    DECLARE_DEBUG_DRAWING("representation:BallModel", "drawingOnField"); // drawing of the ball model
    DECLARE_DEBUG_DRAWING("representation:CombinedWorldModel", "drawingOnField"); // drawing of the combined world model
    DECLARE_DEBUG_DRAWING("representation:GoalPercept:Field", "drawingOnField"); // drawing of the goal percept
    DECLARE_DEBUG_DRAWING("representation:MotionRequest", "drawingOnField"); // drawing of a request walk vector
    DECLARE_DEBUG_DRAWING("representation:ObstacleModel:Center", "drawingOnField"); //drawing center of obstacle model
    DECLARE_DEBUG_DRAWING("representation:LinePercept:Field", "drawingOnField");

    uint8_t teamColor = 0,
            swapSides = 0;
    MODIFY("teamColor", ownTeamInfo.teamColor);
    MODIFY("swapSides", swapSides);

    if(SystemCall::getTimeSince(robotPoseReceived) < 1000)
      robotPose.draw();
    if(SystemCall::getTimeSince(ballModelReceived) < 1000)
      ballModel.draw();
    if(SystemCall::getTimeSince(combinedWorldModelReceived) < 1000)
      combinedWorldModel.draw();
    if(SystemCall::getTimeSince(goalPerceptReceived) < 1000)
      goalPercept.draw();
    if(SystemCall::getTimeSince(motionRequestReceived) < 1000)
      motionRequest.draw();
    if(SystemCall::getTimeSince(obstacleModelReceived) < 1000)
      obstacleModel.draw();
    if(SystemCall::getTimeSince(linePerceptReceived) < 1000)
      linePercept.draw();

    if(swapSides ^ teamColor)
    {
      ORIGIN("field polygons", 0, 0, pi2); // hack: swap sides!
    }
    fieldDimensions.draw();
    fieldDimensions.drawPolygons(teamColor);

    DECLARE_DEBUG_DRAWING("robotState", "drawingOnField"); // text decribing the state of the robot
    int lineY = 3550;
    DRAWTEXT("robotState", -5100, lineY, 150, ColorRGBA::white, "batteryLevel: " << robotHealth.batteryLevel << " %");
    DRAWTEXT("robotState", 3700, lineY, 150, ColorRGBA::white, "role: " << Role::getName(behaviorStatus.role));
    lineY -= 180;
    DRAWTEXT("robotState", -5100, lineY, 150, ColorRGBA::white, "temperatures: joint " << JointData::getName(robotHealth.jointWithMaxTemperature)<< ":" << robotHealth.maxJointTemperature << " C, cpu: " << robotHealth.cpuTemperature << " C");
    lineY -= 180;
    DRAWTEXT("robotState", -5100, lineY, 150, ColorRGBA::white, "rates: cognition: " << (int) std::floor(robotHealth.cognitionFrameRate + 0.5f) << " fps, motion: " << (int) std::floor(robotHealth.motionFrameRate + 0.5f) << " fps");
    if(ballModel.timeWhenLastSeen)
    {
      DRAWTEXT("robotState", 3700, lineY, 150, ColorRGBA::white, "ballLastSeen: " << SystemCall::getRealTimeSince(ballModel.timeWhenLastSeen) << " ms");
    }
    else
    {
      DRAWTEXT("robotState", 3700, lineY, 150, ColorRGBA::white, "ballLastSeen: never");
    }
    //DRAWTEXT("robotState", -5100, lineY, 150, ColorRGBA::white, "ballPercept: " << ballModel.lastPerception.position.x << ", " << ballModel.lastPerception.position.y);
    lineY -= 180;
    DRAWTEXT("robotState", -5100, lineY, 150, ColorRGBA::white, "memory usage: " << robotHealth.memoryUsage << " %");
    if(goalPercept.timeWhenGoalPostLastSeen)
    {
      DRAWTEXT("robotState", 3700, lineY, 150, ColorRGBA::white, "goalLastSeen: " << SystemCall::getRealTimeSince(goalPercept.timeWhenGoalPostLastSeen) << " ms");
    }
    else
    {
      DRAWTEXT("robotState", 3700, lineY, 150, ColorRGBA::white, "goalLastSeen: never");
    }

    lineY -= 180;

    DRAWTEXT("robotState", -5100, lineY, 150, ColorRGBA::white, "load average: " << (float(robotHealth.load[0]) / 10.f) << " " << (float(robotHealth.load[1]) / 10.f) << " " << (float(robotHealth.load[2]) / 10.f));
    DRAWTEXT("robotState", -4100, 0, 150, ColorRGBA(255, 255, 255, 50), robotHealth.robotName);

    DECLARE_DEBUG_DRAWING("robotOffline", "drawingOnField"); // A huge X to display the online/offline state of the robot
    if(SystemCall::getTimeSince(robotPoseReceived) > 500
       || (SystemCall::getTimeSince(isPenalizedReceived) < 1000 && isPenalized)
       || (SystemCall::getTimeSince(hasGroundContactReceived) < 1000 && !hasGroundContact)
       || (SystemCall::getTimeSince(isUprightReceived) < 1000 && !isUpright))
    {
      LINE("robotOffline", -5100, 3600, 5100, -3600, 50, Drawings::ps_solid, ColorRGBA(0xff, 0, 0));
      LINE("robotOffline", 5100, 3600, -5100, -3600, 50, Drawings::ps_solid, ColorRGBA(0xff, 0, 0));
    }
    if(SystemCall::getTimeSince(isPenalizedReceived) < 1000 && isPenalized)
    {
      // Draw a text in red letters to tell that the robot is penalized
      DRAWTEXT("robotState", -2000, 0, 200, ColorRGBA::red, "PENALIZED");
    }
    if(SystemCall::getTimeSince(hasGroundContactReceived) < 1000 && !hasGroundContact)
    {
      // Draw a text in red letters to tell that the robot doesn't have ground contact
      DRAWTEXT("robotState", 300, 0, 200, ColorRGBA::red, "NO GROUND CONTACT");
    }
    if(SystemCall::getTimeSince(isUprightReceived) < 1000 && !isUpright)
    {
      // Draw a text in red letters to tell that the robot is fallen down
      DRAWTEXT("robotState", 300, 0, 200, ColorRGBA::red, "NOT UPRIGHT");
    }

    DEBUG_RESPONSE_ONCE("automated requests:DrawingManager", OUTPUT(idDrawingManager, bin, Global::getDrawingManager()););
    DEBUG_RESPONSE_ONCE("automated requests:DrawingManager3D", OUTPUT(idDrawingManager3D, bin, Global::getDrawingManager3D()););
示例#27
0
void VanLeerX_PPA_steep_cpu(Field *Q){

//<USER_DEFINED>
  INPUT(Q);
  INPUT(Slope);
  INPUT(LapPPA);
  OUTPUT(QL);
  OUTPUT(QR);
//<\USER_DEFINED>

//<EXTERNAL>
  real* slope = Slope->field_cpu;
  real* lapla = LapPPA->field_cpu;
  real* q = Q->field_cpu;
  real* qL = QL->field_cpu;
  real* qR = QR->field_cpu;
  int pitch  = Pitch_cpu;
  int stride = Stride_cpu;
  int size_x = XIP; 
  int size_y = Ny+2*NGHY;
  int size_z = Nz+2*NGHZ;
//<\EXTERNAL>

//<INTERNAL>
  int i;
  int j;
  int k;
  int ll;
  int llxp;
  int llxm;
  real eta;
  real etatilde;
  real aL;
  real aR;
//<\INTERNAL>

//<MAIN_LOOP>

  i = j = k = 0;

#ifdef Z
  for (k=0; k<size_z; k++) {
#endif
#ifdef Y
    for (j=0; j<size_y; j++) {
#endif
      for (i=XIM; i<size_x; i++)	{// Now we compute q_j+1/2
//<#>
	ll = l;
	llxp = lxp;
	llxm = lxm;

	if (lapla[llxp]*lapla[llxm] < 0.0) {
	  if ((fabs(q[llxp]-q[llxm]) > EPS*fabs(q[llxp])) &&		\
	      (fabs(q[llxp]-q[llxm]) > EPS*fabs(q[llxm]))) {  /* Do we have a discontinuity ? */
	    etatilde = - (lapla[llxp]-lapla[llxm])/(q[llxp]-q[llxm]);
	    eta = ETA1*(etatilde-ETA2);
	    if (eta > 1.0) eta=1.0;
	    if (eta < 0.0) eta=0.0;
	    aL = q[llxm]+.5*slope[llxm];
	    aR = q[llxp]-.5*slope[llxp];
	    qL[ll] = qL[ll]*(1.0-eta) + aL*eta;
	    qR[ll] = qR[ll]*(1.0-eta) + aR*eta;
	  }
	}
	  
//<\#>
      }
#ifdef Y
    }
#endif
#ifdef Z
  }
#endif
//<\MAIN_LOOP>
}
示例#28
0
文件: binomial-fc.c 项目: mrry/ciel-c
int 
main(int argc, char **argv)
{

  if(argc < 5) {
    fprintf(stderr, "stream_producer needs at least 4 arguments\n");
    exit(1);
  }
  
  if(strcmp(argv[1], "--write-fifo") != 0) {
    fprintf(stderr, "stream_producer first arg must be --write-fifo\n");
    exit(1);
  }
  if(strcmp(argv[3], "--read-fifo") != 0) {
    fprintf(stderr, "stream producer third arg must be --read-fifo\n");
    exit(1);
  }

  printf("C binopt: start\n");

  ciel_init(argv[2], argv[4]);

  json_t* task_private = ciel_get_task();

  json_error_t error_bucket;
  json_t* kwargs;

  char* s_str;
  char* k_str;
  char* t_str;
  char* v_str;
  char* rf_str;
  char* cp_str;
  char* n_str;
  char* chunk_str;
  char* start_str;

  fprintf(stderr, "doing decode\n");

  if(json_unpack_ex(task_private, &error_bucket, 0, "{s[sssssssss]so}", "proc_pargs", 
		    &s_str, &k_str, &t_str, &v_str, &rf_str, &cp_str, &n_str, 
		    &chunk_str, &start_str, "proc_kwargs", &kwargs)) {
    ciel_json_error("Failed to decode proc_pargs", &error_bucket);
    exit(1);
  }

  fprintf(stderr, "doing conversion\n");

  s = strtod(s_str, NULL);
  k = strtod(k_str, NULL);
  t = strtod(t_str, NULL);
  v = strtod(v_str, NULL);
  rf = strtod(rf_str, NULL);
  cp = strtod(cp_str, NULL);
  n = (int)strtod(n_str, NULL);
  chunk = (int)strtod(chunk_str, NULL);
  start = strcmp(start_str, "false");

  fprintf(stderr, "Got arguments: %g %g %g %g %g %g %d %d %s\n", s, k, t, v, rf, cp, n, chunk, start_str);

  if(!start) {
    
    json_t* in_ref = json_object_get(kwargs, "input_ref");
    binopt_ciel_in = ciel_open_ref_async(in_ref, 1, 1, 0);
    ciel_set_input_unbuffered(binopt_ciel_in);

  }
  else {
    binopt_ciel_in = 0;
  }

  json_decref(task_private);

  binopt_ciel_out = ciel_open_output(0, 1, 0, 0);
  ciel_set_output_unbuffered(binopt_ciel_out);

  init_vals();
  if (start == 1) {
    OUTPUT(n);
    gen_initial_optvals();
  } else {
    int rowstart=0;
    INPUT(rowstart);
    if (rowstart==0) {
      double v;
      INPUT(v);
      char buf[20];
      int chars_written = min(snprintf(buf, 20, "%.9f\n", v), 20);
      ciel_write_output(binopt_ciel_out, buf, chars_written);
    } else {
      int rowto = (rowstart - chunk) > 0 ? (rowstart - chunk) : 0;
      process_rows(rowstart, rowto);
    }
  }


  if(!start) {
    ciel_close_ref(binopt_ciel_in);
  }

  ciel_close_output(binopt_ciel_out);

  ciel_exit();

  return 0;
}
示例#29
0
int main()
{
    int cTotal = 0;
    int cState = STATE_READ;

    char toggleOut = FALSE;

    Signal motor1;
    Signal motor2;
    Signal estop;
    Signal rcMode;

    init_coridium();

	setbaud(0, 17);
	
	
    statusMessage[0] = '#';
	statusMessage[1] = '%';
	statusMessage[2] = 0x82;



    INPUT(RC1); motor1.pin = RC1;
    INPUT(RC2); motor2.pin = RC2;
    INPUT(RC3); estop.pin = RC3;
    INPUT(RC4); rcMode.pin = RC4;


    OUTPUT(TX);
    OUTPUT(ESTOP); LOW(ESTOP);
    OUTPUT(RCMode);
    OUTPUT(FreqPin);
    OUTPUT(LIGHT);

    motor1.state = STATE_WAIT;
    motor1.duty = 0;
    motor1.valid = 0;

    motor2.state = STATE_WAIT;
    motor2.duty = 0;
    motor2.valid = 0;

    estop.state = STATE_WAIT;
    estop.duty = 0;
    estop.valid = 0;

    rcMode.state = STATE_WAIT;
    rcMode.duty = 0;
    rcMode.valid = 0;

    SLEEP(2);

    while (TRUE)
    {
        switch (cState)
        {
        case STATE_READ:
            if (toggleOut)
            {
                toggleOut = FALSE;
                HIGH(FreqPin);
            }
            else
            {
                toggleOut = TRUE;
                LOW(FreqPin);
            }

            cTotal += getDuty(&motor1);
            cTotal += getDuty(&motor2);
            cTotal += getDuty(&estop);
            cTotal += getDuty(&rcMode);

            if (cTotal > 8)
            {
                cState = STATE_SERIAL;
                cTotal = 0;
            }
            break;

        case STATE_SERIAL:
			if (estop.lastVal > 0)
            {
                sendESTOP(0);
                gESTOP = FALSE;
				
                if (rcMode.lastVal > 0)
                {
                    HIGH(LIGHT);
                    HIGH(RCMode);

                    // 11 == Manual (teleop) Mode
                    statusMessage[3] = 0x00;
                    statusMessage[4] = 0xFF;
                    statusMessage[5] = 0xFF;
                    statusMessage[6] = 0xFF;

                    calcSum();
					//statusMessage[7] = 0x84;
                    //SEROUT(TXD0,9600, 1, 3, statusMessage);
					TXD0(statusMessage[0]);
					TXD0(statusMessage[1]);
					TXD0(statusMessage[2]);
					TXD0(statusMessage[3]);
					TXD0(statusMessage[4]);
					TXD0(statusMessage[5]);
					TXD0(statusMessage[6]);
					TXD0(statusMessage[7]);
                }
                else
                {
                    if (flashcount > 0)
                    {
                        HIGH(LIGHT);
                    }
                    else
                    {
                        LOW(LIGHT);
                    }

                    if (flashcount > LIGHTDUTY)
                    {
                        flashcount = -LIGHTDUTY;
                    }

                    LOW(RCMode);

                    // 00 == Autonomous Mode
                    statusMessage[3] = 0x00;
                    statusMessage[4] = 0x00;
                    statusMessage[5] = 0x00;
                    statusMessage[6] = 0x00;

                    calcSum();
					//statusMessage[7] = 0x84;
                    //SEROUT(TXD0,9600, 1, 3, statusMessage);
					
					TXD0(statusMessage[0]);
					TXD0(statusMessage[1]);
					TXD0(statusMessage[2]);
					TXD0(statusMessage[3]);
					TXD0(statusMessage[4]);
					TXD0(statusMessage[5]);
					TXD0(statusMessage[6]);
					TXD0(statusMessage[7]);
                }
            }
            else
            {
                HIGH(LIGHT);
                HIGH(RCMode);
                sendESTOP(1);
                gESTOP = TRUE;
				
				// 11 == Manual (teleop) Mode
				statusMessage[3] = 0x00;
				statusMessage[4] = 0xFF;
				statusMessage[5] = 0xFF;
				statusMessage[6] = 0xFF;

				calcSum();
				//statusMessage[7] = 0x84;
				//SEROUT(TXD0,9600, 1, 3, statusMessage);
				TXD0(statusMessage[0]);
				TXD0(statusMessage[1]);
				TXD0(statusMessage[2]);
				TXD0(statusMessage[3]);
				TXD0(statusMessage[4]);
				TXD0(statusMessage[5]);
				TXD0(statusMessage[6]);
				TXD0(statusMessage[7]);
            }

#ifdef DEBUG
            putchar( binToHexstr((char)((motor1.lastVal >> 4) & 0x0F)) );
            putchar( binToHexstr((char)(motor1.lastVal & 0x0F)) );
            putchar(' ');
                        putchar( binToHexstr((char)((motor2.lastVal >> 4) & 0x0F)) );
            putchar( binToHexstr((char)(motor2.lastVal & 0x0F)) );
            putchar('\n');
            //printf("%d\n", estop.lastVal);
#endif
            // motor1 == forward value
            // motor2 == left/right value

            int left_motor = motor1.lastVal/2 - motor2.lastVal/2;
            int right_motor = motor1.lastVal/2 + motor2.lastVal/2;

            sendSerial(right_motor, 1);
            sendSerial(left_motor, 0);

            cState = STATE_READ;

            break;
        }
        flashcount++;
    }

    return 0;
}
示例#30
0
char* Skmpskip2(char *textt,char *patt,int n, int m) {
	int i, j, k, kmpStart, per, start, wall;
	unsigned char * text,*pat;
	text = (unsigned char *) textt;
	pat = (unsigned char *)patt;
	int kmpNext[m], list[m], mpNext[m],
		z[ASIZE];

	/* Preprocessing */
	preMp((char*)pat, m, mpNext);
	preKmp((char*)pat, m, kmpNext);
	memset(z, -1, ASIZE*sizeof(int));
	memset(list, -1, m*sizeof(int));
	z[pat[0]] = 0;
	for (i = 1; i < m; ++i) {
		list[i] = z[pat[i]];
		z[pat[i]] = i;
	}

	/* Searching */
	wall = 0;
	per = m - kmpNext[m];
	i = j = -1;
	do {
		j += m;
	} while (j < n && z[text[j]] < 0);
	if (j >= n)
		return NULL;
	i = z[text[j]];
	start = j - i;
	while (start <= n - m) {
		if (start > wall)
			wall = start;
		k = attempt((char*)text, (char*)pat, m, start, wall);
		wall = start + k;
		if (k == m) {
			OUTPUT(start);
			i -= per;
		}
		else
			i = list[i];
		if (i < 0) {
			do {
				j += m;
			} while (j < n && z[text[j]] < 0);
			if (j >= n)
				return NULL;
			i = z[text[j]];
		}
		kmpStart = start + k - kmpNext[k];
		k = kmpNext[k];
		start = j - i;
		while (start < kmpStart ||
				(kmpStart < start && start < wall)) {
			if (start < kmpStart) {
				i = list[i];
				if (i < 0) {
					do {
						j += m;
					} while (j < n && z[text[j]] < 0);
					if (j >= n)
						return NULL;
					i = z[text[j]];
				}
				start = j - i;
			}
			else {
				kmpStart += (k - mpNext[k]);
				k = mpNext[k];
			}
		}
	}
	SRET(start);
}