コード例 #1
0
ファイル: biMVCA.cpp プロジェクト: ardielgr/MLSB_problem
void Graph::RemoveUselessColor(int x) {
   int p;

   sol_cn--;
   for (p=x; p<sol_cn; p++) {
   	L[p]=L[p+1];
   }
   if (Demo==1)	PrintSolution();
   if (Demo==2)	PrintSolution();
}
コード例 #2
0
ファイル: main.cpp プロジェクト: tokar1/mech-math
int main()
{
    int n, TC;
    printf("Input dimension (n): ");
    scanf("%d", &n);
    if (n <= 0) return -1;
    printf("Input number of the threads: ");
    scanf("%d", &TC);
    if (n <= 0) return -2;
    double * a = new double[n*n];
    double * b = new double[n];
    double * x = new double[n];
    int * index = new int[n];
    double * ac = new double[n*n];
    double * bc = new double[n*n];
    FillMatrix(a, b, n);
    for (int i = 0; i < n*n; i++) ac[i] = a[i]; // copy of A
    for (int i = 0; i < n; i++) bc[i] = b[i]; // copy of B

    PrintMatrix(a, b, n);

    timeval tv1;
    gettimeofday(&tv1, 0);
    if (!SolveSystem(n, a, b, x, index, TC))
    {
	printf("Bad matrix!\n");
	return -3;
    }
    timeval tv2;
    gettimeofday(&tv2,0);
    double Time = double(tv2.tv_sec)*1000000.0+double(tv2.tv_usec)-double(tv1.tv_sec)*1000000.0+double(tv1.tv_usec);
	
    printf("Result:\n"); PrintSolution(x, n);
    printf("\n\nThreads: %d,\nError: %1.17lf,\nTime=%1.4lf sec.\n", TC, GetError(ac, bc, x, n), Time/1000000.0);
    delete a; delete b;
    delete x; delete index;    
    delete ac;
    return 0;
}
コード例 #3
0
void Search(int k) {
	/*if(GlobalProgressUpdate < k) {
	printf("== Search(%d)\n", k);
	PrintSolution();
	GlobalProgressUpdate = k;
	}*/
	if ((RootNode->Left == RootNode && RootNode->Right == RootNode) || k == (81 - MaxK)) {
		//Valid solution!
		//printf("----------- SOLUTION FOUND -----------\n");
		PrintSolution();
		Finished = 1;
		return;
	}
	struct str_node *Column = ChooseColumn();
	Cover(Column);

	struct str_node *RowNode;
	struct str_node *RightNode;
	for (RowNode = Column->Down; RowNode != Column && !Finished; RowNode = RowNode->Down) {
		// Try this row node on!
		Result[nResult++] = RowNode->IDNum;

		for (RightNode = RowNode->Right; RightNode != RowNode; RightNode = RightNode->Right)
			Cover(RightNode->Header);

		Search(k + 1);

		// Ok, that node didn't quite work
		for (RightNode = RowNode->Right; RightNode != RowNode; RightNode = RightNode->Right)
			UnCover(RightNode->Header);

		Result[--nResult] = 0;
	}

	UnCover(Column);
}
コード例 #4
0
int Solver::Search2(
	int cornerPermutation,
	int nonMiddleSliceEdgePermutation,
	int middleSliceEdgePermutation,
	int depth)
{
	int cost, totalCost;
	int move;
	int power, powerLimit;
	int	cornerPermutation2;
	int nonMiddleSliceEdgePermutation2;
	int middleSliceEdgePermutation2;
	int result;

	// Compute cost estimate to goal state
	cost = Phase2Cost(
		cornerPermutation,
		nonMiddleSliceEdgePermutation,
		middleSliceEdgePermutation);	// h

	if (cost == 0)	// Solution found...
	{
		solutionLength2 = depth;	// Save phase 2 solution length
		if (solutionLength1 + solutionLength2 < minSolutionLength)
			minSolutionLength = solutionLength1 + solutionLength2;
		PrintSolution();
		return FOUND;
	}

	// See if node should be expanded
	totalCost = depth + cost;	// g + h

	if (totalCost <= threshold2)	// Expand node
	{
		// No point in continuing to search for solutions of equal or greater
		//   length than the current best solution
		if (solutionLength1 + depth >= minSolutionLength-1) return ABORT;

		for (move = Cube::Move::R; move <= Cube::Move::B; move++)
		{
			if (Disallowed(move, solutionMoves2, depth)) continue;

			cornerPermutation2 = cornerPermutation;
			nonMiddleSliceEdgePermutation2 = nonMiddleSliceEdgePermutation;
			middleSliceEdgePermutation2 = middleSliceEdgePermutation;

			solutionMoves2[depth] = move;
			powerLimit = 4;
			if (move != Cube::Move::U && move != Cube::Move::D) powerLimit=2;

			for (power = 1; power < powerLimit; power++)
			{
				cornerPermutation2 =
					cornerPermutationMoveTable[cornerPermutation2][move];
				nonMiddleSliceEdgePermutation2 =
					nonMiddleSliceEdgePermutationMoveTable[nonMiddleSliceEdgePermutation2][move];
				middleSliceEdgePermutation2 =
					middleSliceEdgePermutationMoveTable[middleSliceEdgePermutation2][move];

				solutionPowers2[depth] = power;

				nodes2++;
				// Apply the move
				if (result = Search2(
						cornerPermutation2,
						nonMiddleSliceEdgePermutation2,
						middleSliceEdgePermutation2, depth+1))
						return result;
			}
		}
	}
	else	// Maintain minimum cost exceeding threshold
	{
		if (totalCost < newThreshold2)
			newThreshold2 = totalCost;
	}
	return NOT_FOUND;
}
コード例 #5
0
ファイル: biMVCA.cpp プロジェクト: ardielgr/MLSB_problem
void Graph::PostOptimization(){
	int i,j,p,k;
	int flag;
	int x;
   edge *e;
   int Labeli,Labelj;
   int rem=0;

   if (sol_cn!=0){
      if (Demo==1){
         printf("\n--------------- SOLUTION ");
   		printf("\ncolor(frequency): ");
			for (i=0; i<sol_cn; i++) printf("%d(%d) ",L[i].c,L[i].en);
			printf("\n");
   		getch();
   	}
      x=sol_cn-2;
      //x=0;
      if (Demo==1){
      	printf("\nStart of the Post Optimization Phase\n");
         printf("\nWe start with the last color: %d\n",L[x].c);
      }
   	flag=1;
      while (flag==1) {
			for (i=0; i<vn; i++) {
				label[i]=i;
			}
   		NumComps=vn;
         for (p=0; p<sol_cn; p++) {
           	if (p==x) continue;
            e=L[p].root;
            while (e!=NULL) {
					i=e->u;
         		j=e->v;
            	if (i==j) {
        				e=e->next;
         			continue;
      			}
      			if(label[i]!=label[j]){
            		NumComps=NumComps-1;
         			Labeli=label[i];
         			Labelj=label[j];
         			for (k=0; k<vn; k++){	// := 1 to N
         				if (label[k]==Labelj)	label[k]=Labeli;
         			}
      			}
            	e=e->next;
         	}
         }
         if (Demo==1)	printf("\nNumComps=%d\n",NumComps);
         if (NumComps==1){
           	if (Demo==1){
            	printf("\n *-*-* IT IS POSSIBLE TO DELETE COLOR %d FROM THE SOLUTION!\n",L[x].c);
            	rem++;
            }
            RemoveUselessColor(x);
         }
         else{
           	if (Demo==1)	printf("\nIT IS NOT POSSIBLE TO DELETE COLOR %d FROM THE SOLUTION!\n",L[x].c);
         }
         if (x==0){
         //if (x>=sol_cn-2){
         	flag=0;
            if (Demo==1){
            	if (rem!=0){
            		printf("\n --- Total removed=%d\n",rem);
               	PrintSolution();
               }
            }
         }
         else x=x-1;
         //else x=x+1;
         if (Demo==1){
            if (flag==1) printf("\nnew x=%d; We start again with another color: %d\n",x,L[x].c);
         	getch();
         }
      }
   }
   else{
   	printf("\n!!! DANGER: THE SOLUTION IS EMPTY !!!\n");
		printf("IMPOSSIBLE TO APPLY THE POST OPTIMIZATION PHASE\n");
      printf("\nPress a key to continue ...\n");
		getch();
   }
}
コード例 #6
0
ファイル: search.c プロジェクト: ombt/ombt
int
BestFirst_Astar_Check(const NodeType &start, 
	int &uniquenodes, int &expandednodes)
{
	uniquenodes = expandednodes = 0;

	// copy start state
	NodePtr<NodeType> pstart(start);

	// calculate the heuristic value for this node
	pstart->heuristic(*pstart);

	// create open priority queue
	List<NodePtr<NodeType> > openpq;
	openpq.insertByValue(pstart);
	uniquenodes++;

	// create closed set
	List<NodePtr<NodeType> > closedset;

	// start search loop
	for (NodePtr<NodeType> pnode; ! openpq.isEmpty(); )
	{
		// remove next node from priority open queue
		openpq.removeAtFront(pnode);

		// check if we have a goal node or not
		if (pnode->isGoal())
		{
			// goal node, print solution
			PrintSolution((NodeType *)pnode);
			return(OK);
		}

		// generate the children of the current node
		if (pnode->expand() != OK)
		{
			// unable to expand current node
			return(NOTOK);
		}
		if (((++expandednodes%1000) == 0) && (expandednodes > 0))
		{
			cout << expandednodes << " nodes expanded." << endl;
			cout << "current node is ... " << *pnode << endl;
		}

		// the following two lists are REQUIRED since the
		// list iterator used below does NOT allow nodes
		// to be deleted or inserted into the list while
		// the iterator is traversing the list. the solution
		// is to save the nodes that must be deleted and
		// inserted in two separate lists, and after the
		// iterator is done, then remove and add nodes to
		// pnodes children list.
		//
		// list of nodes to delete from pnode children
		List<NodePtr<NodeType> > nodesToRemove;
		nodesToRemove.clear();

		// list of nodes to add to pnode children
		List<NodePtr<NodeType> > nodesToInsert;
		nodesToInsert.clear();

		// scan children and determine if they already exist.
		ListIterator<NodePtr<NodeType> > 
			childrenIter(*pnode->getChildren());
		for ( ; !childrenIter.done(); childrenIter++)
		{
			// set up link to parent
			childrenIter()->setParent((NodeType *)pnode);

			// calculate the heuristic value
			childrenIter()->heuristic(*pstart);

			// check if node already exists
			NodePtr<NodeType> pchild(childrenIter());
			NodePtr<NodeType> popen(childrenIter());
			NodePtr<NodeType> pclosed(childrenIter());

			// check if node was already generated
			int inopen = NOMATCH;
			int inclosed = NOMATCH;
			if (( ! openpq.isEmpty()) && 
			    (inopen = openpq.retrieveByValue(popen)) == OK)
			{
				// check which path is better, the new
				// path thru pnode, or the old one
				// thru popen.
				//
				int childGvalue = pchild->getGvalue();
				int oldGvalue = popen->getGvalue();
				if (childGvalue < oldGvalue)
				{
					// reset old node parent pointer
					popen->setParent(pchild->getParent());
					popen->heuristic(*pstart);
				}

				// delete copy of node, and insert
				// old node, popen, into children
				// list of pnode.
				//
				nodesToRemove.insertAtFront(pchild);
				nodesToInsert.insertAtFront(popen);
			}
			else if (( ! closedset.isEmpty()) && 
				 (inclosed = closedset.retrieveByValue(pclosed)) == OK)
			{
				// check which path is better, the new
				// path thru pnode, or the old one
				// thru pclosed.
				//
				int childGvalue = pchild->getGvalue();
				int oldGvalue = pclosed->getGvalue();
				if (childGvalue < oldGvalue)
				{
					// reset parent pointer
					pclosed->setParent(pchild->getParent());
					pclosed->heuristic(*pstart);

					// check parent pointers for
					// children of pclosed.
					//
					ListIterator<NodePtr<NodeType> > closedChildrenIter(*pclosed->getChildren());
					for ( ; ! closedChildrenIter.done(); closedChildrenIter++)
					{
						// first we need to check if this child has 
						// the closed node as a parent. if it does,
						// then do nothing. if it does not, then we
						// have to compare g-values. if the existing
						// g-value is smaller, then leave child node
						// alone. if the the existing g-value is greater,
						// then we have to reset the closed child parent
						// pointer to point to the closed node since this
						// path is now better.
						//
						NodePtr<NodeType> pclosedChild(closedChildrenIter());
						NodePtr<NodeType> pclosedChildParent = 
							pclosedChild->getParent();
						if ((NodeType *)pclosedChildParent == (NodeType *)pclosed)
						{
							// parent of closed child is the closed
							// node, so just skip it.
							continue;
						}
TRACE();

						// compare g-values to determine if the new path
						// is better (cheaper) than the old path to 
						// the closed child node.
						//
						int oldClosedChildGvalue = pclosedChild->getGvalue();
						pclosedChild->setParent(pclosed);
						pclosedChild->heuristic(*pstart);
						int newClosedChildGvalue = pclosedChild->getGvalue();
						if (newClosedChildGvalue > oldClosedChildGvalue)
						{
							// set parent to old value
							pclosedChild->setParent(pclosedChildParent);
							pclosedChild->heuristic(*pstart);
						}
					}
				}

				// delete copy of node, and insert
				// old node, pclosed, into children
				// list of pnode.
				//
				nodesToRemove.insertAtFront(pchild);
				nodesToInsert.insertAtFront(pclosed);
			}
			else if (inopen == NOMATCH && inclosed == NOMATCH)
			{
				// new node, place in open queue
				openpq.insertByValue(pchild);
				if (((++uniquenodes%1000) == 0) && (uniquenodes > 0))
				{
					cout << uniquenodes << " unique nodes." << endl;
				}
			}
			else
			{
				// an error of some type
				return(NOTOK);
			}
		}

		// get pointer to nodes children list
		List<NodePtr<NodeType> > 
			*pchildren = pnode->getChildren();

		// remove children nodes
		ListIterator<NodePtr<NodeType> > 
			nodesToRemoveIter(nodesToRemove);
		for ( ; !nodesToRemoveIter.done(); nodesToRemoveIter++)
		{
			pchildren->removeByValue(nodesToRemoveIter());
		}

		// add children nodes
		ListIterator<NodePtr<NodeType> > 
			nodesToInsertIter(nodesToInsert);
		for ( ; !nodesToInsertIter.done(); nodesToInsertIter++)
		{
			pchildren->insertAtFront(nodesToInsertIter());
		}

		// store node in closed set
		closedset.insertAtFront(pnode);
	}

	// finished with error
	return(NOTOK);
}
コード例 #7
0
ファイル: search.c プロジェクト: ombt/ombt
int
BestFirst_Astar_WOCheck(const NodeType &start, const List<NodeType> &goals, 
	int &uniquenodes, int &expandednodes)
{
	uniquenodes = expandednodes = 0;

	// copy start state
	NodePtr<NodeType> pstart(start);

	// calculate the heuristic value for this node
	pstart->heuristic(*pstart, goals);

	// create open priority queue
	List<NodePtr<NodeType> > openpq;
	openpq.insertByValue(pstart);
	uniquenodes++;

	// create closed set
	List<NodePtr<NodeType> > closedset;

	// start search loop
	for (NodePtr<NodeType> pnode; ! openpq.isEmpty(); )
	{
		// remove next node from priority open queue
		openpq.removeAtFront(pnode);

		// check if we have a goal node or not
		if (goals.isInList(*pnode))
		{
			// goal node, print solution
			PrintSolution((NodeType *)pnode);
			return(OK);
		}

		// generate the children of the current node
		if (pnode->expand() != OK)
		{
			// unable to expand current node
			return(NOTOK);
		}
		if (((++expandednodes%1000) == 0) && (expandednodes > 0))
		{
			cout << expandednodes << " nodes expanded." << endl;
			cout << "current node is ... " << *pnode << endl;
		}

		// set up links to parent and calculate the heuristic value
		ListIterator<NodePtr<NodeType> > 
			childrenIter(*pnode->getChildren());
		for ( ; !childrenIter.done(); childrenIter++)
		{
			// set up link to parent
			childrenIter()->setParent((NodeType *)pnode);

			// calculate the heuristic value
			childrenIter()->heuristic(*pstart, goals);

			// insert into open queue
			openpq.insertByValue(childrenIter());
			if (((++uniquenodes%1000) == 0) && (uniquenodes > 0))
			{
				cout << uniquenodes << " unique nodes." << endl;
			}
		}

		// store node in closed set
		closedset.insertAtFront(pnode);
	}

	// finished with error
	return(NOTOK);
}
コード例 #8
0
ファイル: search.cpp プロジェクト: ombt/ombt
int
dfs(Proxy<NodeType> &pnode, int &threshold, int &next_threshold, 
	BinaryTree_AVL<DataType> &startlist, 
	BinaryTree_AVL<DataType> &otherlist)
{
	int status;

	// expand the current node's children
	if ((status = pnode->expand(startlist, otherlist)) != OK)
	{
		// some type of error
		ERRORD("expand() failed.", status, errno);
		return(status);
	}

	// scan children for goal nodes 
	ListIterator<Proxy<NodeType> > childrenIter(*pnode->getChildren());
	for ( ; !childrenIter.done(); childrenIter++)
	{
		// get pointer to child
		Proxy<NodeType> pchild(childrenIter());

		// set up link to parent
		if (reporttype == ReportParent ||
		    reporttype == ReportBoth)
			pchild->setParent(pnode);

		// calculate the heuristic value
		if ((status = pchild->heuristic(startlist, otherlist)) != OK)
		{
			ERRORD("heuristic() failed.", status, errno);
			return(status);
		}

		// check if we have a goal node
		status = pchild->isGoal(startlist, otherlist);
		switch (status)
		{
		case OK:
			break;

		case NOMATCH:
		case MAXDEPTHEXCEEDED:
			continue;

		case MAXCLAUSEEXCEEDED:
			return(status);

		case VALID:
			// goal node, print solution
			PrintSolution(pnode);
			PrintRenameVariables(pnode);
			return(VALID);

		default:
			// some type of error
			ERRORD("isGoal() failed.", status, errno);
			return(status);
		}

		// check if we continue, is threshold exceeded?
		int childcost = pchild->getFvalue();
		if (childcost <= threshold)
		{
			// continue depth-first search
			status = dfs(pchild, threshold, next_threshold,
					startlist, otherlist);
			switch (status)
			{
			case OK:
			case NOMATCH:
			case MAXDEPTHEXCEEDED:
			case NOTPROVEN:
				break;
	
			case MAXCLAUSEEXCEEDED:
				return(MAXCLAUSEEXCEEDED);

			case VALID:
				// goal node, print solution
				return(VALID);

			default:
				// some type of error
				ERRORD("dfs() failed.", status, errno);
				return(status);
			}
		}
		else if (childcost < next_threshold)
		{
			next_threshold = childcost;
		}
	}

	// goal was not not proven
	return(NOTPROVEN);
}
コード例 #9
0
ファイル: search.cpp プロジェクト: ombt/ombt
int
DepthFirstHillClimbSearch(List<NodeType> &startstatelist, 
		BinaryTree_AVL<DataType> &startlist, 
		BinaryTree_AVL<DataType> &otherlist)
{
	int status;

	// track all states created
	BinaryTree_AVL<String> allstates;

	// create open stack for traversal
	List<Proxy<NodeType> > openstack;

	// keep track of current path here instead of 
	// using parent pointers. parent pointers cause
	// cycles and reference-counted pointers cannot
	// deal with cyclic data structures. they cause
	// major memory leaks.
	//
	int nodedepth = 1;
	List<Proxy<NodeType> > currentpath;

	// copy list of start states
	ListIterator<NodeType> startstateIter(startstatelist);
	for ( ; !startstateIter.done(); startstateIter++)
	{
		// copy start state
		Proxy<NodeType> pstart(startstateIter());

		// calculate the heuristic value for this node
		if ((status = pstart->heuristic(startlist, otherlist)) != OK)
		{
			ERRORD("heuristic() failed.", status, errno);
			return(status);
		}

		// set start node depth
		pstart->setDepth(nodedepth);

		// insert start state into open queue
		if ((status = openstack.insertOrdered(pstart)) != OK)
		{
			ERRORD("insertOrdered() failed.", status, errno);
			return(status);
		}
	}

	// children priority queue
	List<Proxy<NodeType> > childpq;
	
	// start search loop
	int olddepth = nodedepth;
	Proxy<NodeType> pchild;
	for (Proxy<NodeType> pnode; ! openstack.isEmpty(); )
	{
		// remove next node from priority open queue
		if ((status = openstack.removeAtFront(pnode)) != OK)
		{
			ERRORD("removeAtFront() failed.", status, errno);
			return(status);
		}

		// check if we have a goal node or not
		status = pnode->isGoal(startlist, otherlist);
		switch (status)
		{
		case OK:
			// update current path
			if ((status = updatepath(nodedepth, 
				olddepth, pnode, currentpath)) != OK)
				return(status);
			break;

		case NOMATCH:
		case MAXDEPTHEXCEEDED:
			// no clauses were generated. skip further
			// processing of this node.
			continue;

		case VALID:
			// update current path
			if ((status = updatepath(nodedepth, 
				olddepth, pnode, currentpath)) != OK)
				return(status);

			// goal node, print solution
			PrintSolution(pnode);
			PrintSolution(currentpath);
			PrintRenameVariables(pnode);

			// check if more than one solutions is required
			solutionsfound += 1;
			statistics[SolutionsFound] += 1;
			totalstatistics[TotalSolutionsFound] += 1;
			if (solutionsfound >= solutionsrequired)
				return(VALID);
			continue;

		case MAXCLAUSEEXCEEDED:
			// check if any solutions were found
			if (solutionsfound > 0)
				return(VALID);
			else
				return(NOTPROVEN);

		default:
			// some type of error
			ERRORD("isGoal() failed.", status, errno);
			return(status);
		}

		// generate the children of the current node
		if ((status = pnode->expand(startlist, otherlist)) != OK)
		{
			ERRORD("expand() failed.", status, errno);
			return(status);
		}

		// clear children priority queue
		childpq.clear();

		// set up links to parent and calculate the heuristic value
		ListIterator<Proxy<NodeType> > 
			childrenIter(*pnode->getChildren());
		for ( ; !childrenIter.done(); childrenIter++)
		{
			// pointer to child
			pchild = childrenIter();

			// set up link to parent
			if (reporttype == ReportParent ||
			    reporttype == ReportBoth)
				pchild->setParent(pnode);

			// calculate the heuristic value
			if ((status = pchild->heuristic(
				startlist, otherlist)) != OK)
			{
				ERRORD("heuristic() failed.", status, errno);
				return(status);
			}

			// insert child into a priority queue to order
			pchild->setDepth(nodedepth+1);
			if ((status = childpq.insertOrdered(pchild)) != OK)
			{
				ERRORD("insertOrdered() failed.", 
					status, errno);
				return(status);
			}
		}

		// insert nodes into stack ordered by heuristic value
		while (!childpq.isEmpty())
		{
			// remove next node from priority open queue
			if ((status = childpq.removeAtEnd(pchild)) != OK)
			{
				ERRORD("removeAtEnd() failed.", 
					status, errno);
				return(status);
			}

			// insert node into a stack
			if (!bfswithchecks)
			{
				if ((status = openstack.insertAtFront(
					pchild)) != OK)
				{
					ERRORD("insertAtFront() failed.", 
						status, errno);
					return(status);
				}
			}
			else
			{
				statistics[RedundantClauseTestsAttempted] += 1;
				totalstatistics[TotalRedundantClauseTestsAttempted] += 1;
				String newnode(pchild->getNormalizedClauses());
				if (allstates.retrieve(newnode) == NOMATCH)
				{
					if ((status = openstack.insertAtFront(
							pchild)) != OK)
					{
						ERRORD("insertAtFront() failed.", 
							status, errno);
						return(status);
					}
				}
				else
				{
					statistics[RedundantClausesRejected] += 1;
					totalstatistics[TotalRedundantClausesRejected] += 1;
				}
			}
		}

		// children are now in the queue. release pointers to
		// children stored in node.
		//
		pnode->getChildren()->clear();
		if (bfswithchecks)
		{
			if (allstates.insert(pnode->getNormalizedClauses()) != OK)
			{
				ERRORD("insert() failed.", status, errno);
				return(status);
			}
		}
	}

	// check if any solutions were found
	if (solutionsfound > 0)
		return(VALID);
	else
		return(NOTPROVEN);
}
コード例 #10
0
ファイル: search.cpp プロジェクト: ombt/ombt
int
BreadthFirstSearch(List<NodeType> &startstatelist, 
		BinaryTree_AVL<DataType> &startlist, 
		BinaryTree_AVL<DataType> &otherlist)
{
	int status;

	// track all states created
	BinaryTree_AVL<String> allstates;

	// create open priority queue
	List<Proxy<NodeType> > openpq;

	// copy list of start states
	int nodedepth = 1;
	ListIterator<NodeType> startstateIter(startstatelist);
	for ( ; !startstateIter.done(); startstateIter++)
	{
		// copy start state
		Proxy<NodeType> pstart(startstateIter());

		// set start node depth
		pstart->setDepth(nodedepth);

		// insert start state into open queue
		if ((status = openpq.insertAtEnd(pstart)) != OK)
		{
			ERRORD("insertAtFront() failed.", status, errno);
			return(status);
		}
	}

	// start search loop
	for (Proxy<NodeType> pnode; ! openpq.isEmpty(); )
	{
		// remove next node from priority open queue
		if ((status = openpq.removeAtFront(pnode)) != OK)
		{
			ERRORD("removeAtFront() failed.", status, errno);
			return(status);
		}

		// set current node depth
		nodedepth = pnode->getDepth();

		// check if we have a goal node or not
		status = pnode->isGoal(startlist, otherlist);
		switch (status)
		{
		case OK:
			break;

		case NOMATCH:
		case MAXDEPTHEXCEEDED:
			// no clauses were generated. skip further
			// processing of this node.
			continue;

		case VALID:
			// goal node, print solution
			PrintSolution(pnode);
			PrintRenameVariables(pnode);

			// check if more than one solutions is required
			solutionsfound += 1;
			statistics[SolutionsFound] += 1;
			totalstatistics[TotalSolutionsFound] += 1;
			if (solutionsfound >= solutionsrequired)
				return(VALID);
			continue;

		case MAXCLAUSEEXCEEDED:
			// check if any solutions were found
			if (solutionsfound > 0)
				return(VALID);
			else
				return(NOTPROVEN);

		default:
			// some type of error
			ERRORD("isGoal() failed.", status, errno);
			return(status);
		}

		// generate the children of the current node
		if ((status = pnode->expand(startlist, otherlist)) != OK)
		{
			ERRORD("expand() failed.", status, errno);
			return(status);
		}

		// set up links to parent and calculate the heuristic value
		ListIterator<Proxy<NodeType> > 
			childrenIter(*pnode->getChildren());
		for ( ; !childrenIter.done(); childrenIter++)
		{
			// pointer to child
			Proxy<NodeType> pchild(childrenIter());

			// set up link to parent
			if (reporttype == ReportParent ||
			    reporttype == ReportBoth)
				pchild->setParent(pnode);

			// insert into queue
			if (!bfswithchecks)
			{
				pchild->setDepth(nodedepth+1);
				if ((status = openpq.insertAtEnd(
					pchild)) != OK)
				{
					ERRORD("insertAtEnd() failed.", 
						status, errno);
					return(status);
				}
			}
			else
			{
				statistics[RedundantClauseTestsAttempted] += 1;
				totalstatistics[TotalRedundantClauseTestsAttempted] += 1;
				String newnode(pchild->getNormalizedClauses());
				if (allstates.retrieve(newnode) == NOMATCH)
				{
					pchild->setDepth(nodedepth+1);
					if ((status = openpq.insertAtEnd(
							pchild)) != OK)
					{
						ERRORD("insertAtEnd() failed.", 
							status, errno);
						return(status);
					}
				}
				else
				{
					statistics[RedundantClausesRejected] += 1;
					totalstatistics[TotalRedundantClausesRejected] += 1;
				}
			}
		}

		if (bfswithchecks)
		{
			if (allstates.insert(pnode->getNormalizedClauses()) != OK)
			{
				ERRORD("insert() failed.", status, errno);
				return(status);
			}
		}
	}

	// check if any solutions were found
	if (solutionsfound > 0)
		return(VALID);
	else
		return(NOTPROVEN);
}
コード例 #11
0
ファイル: search.cpp プロジェクト: ombt/ombt
int
IterativeDeepeningSearch(Proxy<NodeType> &proot, int &threshold, 
	int &next_threshold, BinaryTree_AVL<DataType> &startlist, 
	BinaryTree_AVL<DataType> &otherlist)
{
	int status;

	// check if we have a goal node or not
	status = proot->isGoal(startlist, otherlist);
	switch (status)
	{
	case OK:
		break;

	case NOMATCH:
		return(NOTPROVEN);

	case VALID:
		// goal node, print solution
		PrintSolution(proot);
		PrintRenameVariables(proot);
		return(VALID);

	default:
		// some type of error
		ERRORD("isGoal() failed.", status, errno);
		return(status);
	}

	// calculate the heuristic value for root node
	if ((status = proot->heuristic(startlist, otherlist)) != OK)
	{
		ERRORD("heuristic() failed.", status, errno);
		return(status);
	}

	// set initial threshold values
	threshold = proot->getFvalue();
	next_threshold = INT_MAX;

	// start interative deepening, probe ahead
	while ( 1 )
	{
		status = dfs(proot, threshold, next_threshold,
				startlist, otherlist);
		switch (status)
		{
		case OK:
		case NOMATCH:
		case NOTPROVEN:
		case MAXDEPTHEXCEEDED:
			// reset thresholds
			if (next_threshold == INT_MAX)
			{
				ERROR("next_threshold is STILL INT_MAX.", 
					errno);
				return(NOTOK);
			}
			threshold = next_threshold;
			next_threshold = INT_MAX;
			break;

		case MAXCLAUSEEXCEEDED:
			return(NOTPROVEN);

		case VALID:
			return(status);

		default:
			// some type of error
			ERRORD("interative deepening dfs() failed.", 
				status, errno);
			return(status);
		}
	}
}
コード例 #12
0
ファイル: g.cpp プロジェクト: acmgnyr/acmgnyr.org
int main()
{
   int nprob, curprob, probsz, ret, index, i;

   if(fgets(&(inbuf[0]), 255, stdin) == NULL)
   {
      fprintf(stderr, "Read failed on problem count\n");
      return -1;
   }
   if(sscanf(&(inbuf[0]), "%d", &nprob) != 1)
   {
      fprintf(stderr, "Scan failed on problem count\n");
      return -2;
   }
   for(i = 0 ; i < HASH_SIZE ; i++)
   {
      scanHash[i] = NULL;
   }
   for(curprob = 1; curprob <= nprob ; curprob++)
   {
      if(fgets(&(inbuf[0]), 255, stdin) == NULL)
      {
         fprintf(stderr, "Read failed on problem %d size\n", curprob);
         CleanGlobal();
         return -3;
      }
      if(sscanf(&(inbuf[0]), "%d %d", &index, &probsz) != 2)
      {
         fprintf(stderr, "Scan failed on problem %d size\n", curprob);
         CleanGlobal();
         return -4;
      }
      if((probsz < 3) || (probsz > MAX_POINTS))
      {
         fprintf(stderr, "problem size %d is < 3 or > %d in problem %d\n",
            probsz, MAX_POINTS, curprob);
         CleanGlobal();
         return -5;
      }
      if(index != curprob)
      {
         fprintf(stderr, "problem index %d not = expected problem %d\n", index, curprob);
         CleanGlobal();
         return -7;
      }
      if((ret = ReadInput(probsz, curprob)) != 0)
      {
         CleanGlobal();
         return ret;
      }
      if((ret = BuildScans(probsz, curprob)) != 0)
      {
         CleanGlobal();
         return ret;
      }
      if((ret = BuildHullEdges(curprob)) != 0)
      {
         CleanGlobal();
         return ret;
      }
      if((ret = BuildHullVerts(curprob)) != 0)
      {
         CleanGlobal();
         return ret;
      }
      PrintSolution(curprob);
      CleanLocal();
   }
   CleanGlobal();
   return 0;
}
コード例 #13
0
ファイル: nlinsolve1d.c プロジェクト: mirrorscotty/fe-solver
/**
 * Implicit time integration solver. (Nonlinear version)
 * Works with both backward difference
 * integration (BD) and the trapazoid rule (TR). In either case, the algorithm
 * is supposed to be unconditionally stable. This function only solves the
 * problem at the next time step. In order to solve for the desired variables
 * over the entire time domain, call this function repeatedly.
 *
 * The time deriviative is calculated using the following formula:
 * y'(t1) = a/dt * [y(t1) - y(t0)] + b*y'(t0)
 * Here, t1 is the time at the current time step and t0 is at the previous one.
 * The variables a and b are constants that determine which algorithm is used
 * to approximate the derivative. For a=1, b=0, backward difference is used,
 * and for a=2, b=-1, trapazoid rule is used.
 *
 * @param problem Finite element problem to solve
 * @param guess Initial guess at the solution for the next time step. If this
 *      is not supplied (NULL), then the solution is predicted based on the
 *      previous time steps.
 * @returns Pointer to a matrix of the calculated values. This can be safely
 *      disregarded since the matrix is also stored in the finite element
 *      problem structure.
 */
matrix* NLinSolve1DTransImp(struct fe1d *problem, matrix *guess)
{
    int iter = 0; /* Current iteration number */
    int maxiter = 5000; /* Maximum allowed iterations before terminating */

    /* Constants that determine the integration algorithm. If a=1 and b=0, then
     * the backward difference method is being used. For the trapazoid rule,
     * a=2, and b=-1. */
    int a, b;
    solution *prev; /* Solution at the previous time step */
    matrix *J, *F, *R; /* Jacobian matrix and the residuals matrix */
    matrix *tmp1, *tmp2; /* Temporary matricies */
    matrix *u, *du, *dx;
    matrix *dguess; /* Time derivative of the guess */

    /* Use BD */
    a = 1; b = 0;
    /* Note: This solver doesn't work at all with anything but backward
     * difference for time integration. The linear one doesn't either, but it
     * at least contains some code for it. */

    /* Get the previous solution */
    prev = FetchSolution(problem, problem->t-1);
    du = prev->dval;
    u = prev->val;

    /* Predict the next solution if an initial guess isn't supplied. */
    if(!guess)
        guess = PredictSolnO0(problem);

    dx = NULL;
    //exit(0);

    do {
        iter++;

        /* Quit if we've reached the maximum number of iterations */
        if(iter == maxiter)
            break;

        problem->guess = guess;

        /* Delete the matricies from the previous iteration */
        DestroyMatrix(problem->J);
        DestroyMatrix(problem->dJ);
        DestroyMatrix(problem->F);
        /* Delete the dx matrix from the previous iteration. */
        if(dx)
            DestroyMatrix(dx);
        /* Initialize the matricies */
        AssembleJ1D(problem, guess);
        AssembledJ1D(problem, guess);
        AssembleF1D(problem, guess);

        //problem->guess = NULL;

        /* Calculate the Jacobian matrix */
        tmp1 = mtxmulconst(problem->dJ, a/problem->dt);
        J = mtxadd(tmp1, problem->J);
        DestroyMatrix(tmp1);

        /* Calculate the load vector */
        tmp1 = mtxmulconst(problem->dJ, a/problem->dt);
        tmp2 = mtxmul(tmp1, u);
        F = mtxadd(problem->F, tmp2);
        DestroyMatrix(tmp1);
        DestroyMatrix(tmp2);

        /* Apply boundary conditions. */
        DestroyMatrix(problem->J);
        DestroyMatrix(problem->F);
        problem->J = J;
        problem->F = F;
        problem->applybcs(problem);

        /* Calculate the residual vector */
        tmp1 = mtxmul(problem->J, guess);
        mtxneg(tmp1);
        R = mtxadd(problem->F, tmp1);
        DestroyMatrix(tmp1);

        //mtxprnt(problem->J);
        //puts("");
        //mtxprnt(problem->dJ);
        //puts("");
        //mtxprnt(problem->F);

        /* Solve for dx */
        dx = SolveMatrixEquation(J, R);

        /* Delete the residual matrix and the Jacobian matrix*/
        DestroyMatrix(R);

        /* Add the change in the unknowns to the guess from the previous
         * iteration */
        tmp1 = mtxadd(guess, dx);
        DestroyMatrix(guess);
        guess = tmp1;

#ifdef VERBOSE_OUTPUT
        /* Print the current iteration number to the console. */
        printf("\rIteration %d", iter);
        fflush(stdout); // Flush the output buffer.
#endif
    } while(!CheckConverg1D(problem, dx));
    /* Delete the final dx matrix */
    DestroyMatrix(dx);

    if(iter==maxiter) {
        printf("Nonlinear solver failed to converge. "
               "Maximum number of iterations reached.\n"
               "Failed to calculate solution at time step %d of %d\n"
               "Exiting.\n",
                problem->t, problem->maxsteps);
        printf("Current step size: %g\n", problem->dt);
        PrintSolution(problem, problem->t-1);
        printf("Current guess:\n");
        PrintGuess(problem, guess);
        exit(0);
    }

#ifdef VERBOSE_OUTPUT
    if(iter == -1)
        /* If we've determined the matrix to be singular by calculating the
         * determinant, then output the appropriate error message. */
        printf("\rSingular matrix.\n");
    else if(iter == maxiter)
        /* If the solver didn't find a solution in the specified number of
         * iterations, then say so. */
        printf("\rNonlinear solver failed to converge. "
               "Maximum number of iterations reached.\n");
    else
        /* Print out the number of iterations it took to converge
         * successfully. */
        printf("\rNonlinear solver converged after %d iterations.\n", iter);
#endif

    /* Solve for the time derivative of the result. */
    dguess = CalcTimeDerivative(problem, guess);

    StoreSolution(problem, guess, dguess);
    /* Delete the time derivative of the pervious solution to save memory. */
    //DeleteTimeDeriv(prev);

    return guess;
}
コード例 #14
0
ファイル: solver.cpp プロジェクト: amine2734/cube
int Solver::Search2(
	int cornerPermutation,
	int nonMiddleSliceEdgePermutation,
	int middleSliceEdgePermutation,
	int depth)
{
	int cost, totalCost;
	int move;
	int power, powerLimit;
	int cornerPermutation2;
	int nonMiddleSliceEdgePermutation2;
	int middleSliceEdgePermutation2;
	int result;

	cost = Phase2Cost(
		cornerPermutation,
		nonMiddleSliceEdgePermutation,
		middleSliceEdgePermutation);

	if (cost == 0)
	{
		solutionLength2 = depth;
		if (solutionLength1 + solutionLength2 < minSolutionLength)
			minSolutionLength = solutionLength1 + solutionLength2;
		PrintSolution();
		return FOUND;
	}

	if (cost < 2)
		Window->ProgressStep(1);

	
	totalCost = depth + cost;

	if (totalCost <= threshold2)
	{
		if (solutionLength1 + depth >= minSolutionLength-1) return ABORT;

		for (move = Cube::R; move <= Cube::B; move++)
		{
		  if (Disallowed(move, solutionMoves2, depth)) continue;

		  cornerPermutation2 = cornerPermutation;
		  nonMiddleSliceEdgePermutation2 = nonMiddleSliceEdgePermutation;
		  middleSliceEdgePermutation2 = middleSliceEdgePermutation;

		  solutionMoves2[depth] = move;
		  powerLimit = 4;
		  if (move != Cube::U && move != Cube::D) powerLimit=2;

		  for (power = 1; power < powerLimit; power++)
		  {
		    cornerPermutation2 =
		        cornerPermutationMoveTable
				    [cornerPermutation2][move];
		    
		    nonMiddleSliceEdgePermutation2 =
		        nonMiddleSliceEdgePermutationMoveTable
				    [nonMiddleSliceEdgePermutation2][move];
		    
		    middleSliceEdgePermutation2 =
		        middleSliceEdgePermutationMoveTable
				    [middleSliceEdgePermutation2][move];

		    solutionPowers2[depth] = power;

		    nodes2++;

		    if ((result = Search2(
				cornerPermutation2,
				nonMiddleSliceEdgePermutation2,
				middleSliceEdgePermutation2, depth+1)))
				return result;
		  }
		}
	}
	else
	{
		if (totalCost < newThreshold2)
			newThreshold2 = totalCost;
	}
	return NOT_FOUND;
}
コード例 #15
0
ファイル: ex42.c プロジェクト: wgapl/petsc
int main(int argc, char **argv)
{
  TS             ts;       /* time-stepping context */
  Vec            x;       /* State vector */
  Mat            J; /* Jacobian matrix */
  AppCtx         user; /* user-defined context */
  PetscErrorCode ierr;
  PetscReal      ftime;
  PetscInt       its;
  PetscMPIInt    size;

  PetscInitialize(&argc, &argv, NULL, help);
  ierr = MPI_Comm_size(PETSC_COMM_WORLD, &size);
  if(size != 1) SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "This is a uniprocessor example only");

  /*
   * Allow user to set the grid dimensions and the equations parameters
   */

  user.nb_cells = 50;
  user.alpha = 10.;
  user.beta = 1.;
  user.rho_a = 1.;
  user.rho_h = 2.;
  user.mu_a = 2.;
  user.mu_h = 3.;
  user.D_a = 0.;
  user.D_h = 30.;

  ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "", "Problem settings", "PROBLEM");
  ierr = PetscOptionsInt("-nb_cells", "Number of cells", "ex42.c",user.nb_cells, &user.nb_cells,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsReal("-alpha", "Autocatalysis factor", "ex42.c",user.alpha, &user.alpha,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsReal("-beta", "Inhibition factor", "ex42.c",user.beta, &user.beta,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsReal("-rho_a", "Default production of the activator", "ex42.c",user.rho_a, &user.rho_a,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsReal("-mu_a", "Degradation rate of the activator", "ex42.c",user.mu_a, &user.mu_a,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsReal("-D_a", "Diffusion rate of the activator", "ex42.c",user.D_a, &user.D_a,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsReal("-rho_h", "Default production of the inhibitor", "ex42.c",user.rho_h, &user.rho_h,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsReal("-mu_h", "Degradation rate of the inhibitor", "ex42.c",user.mu_h, &user.mu_h,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsReal("-D_h", "Diffusion rate of the inhibitor", "ex42.c",user.D_h, &user.D_h,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsEnd();

  ierr = PetscPrintf(PETSC_COMM_WORLD, "nb_cells: %D\n", user.nb_cells);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "alpha: %5.5g\n", user.alpha);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "beta:  %5.5g\n", user.beta);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "rho_a: %5.5g\n", user.rho_a);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "mu_a:  %5.5g\n", user.mu_a);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "D_a:   %5.5g\n", user.D_a);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "rho_h: %5.5g\n", user.rho_h);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "mu_h:  %5.5g\n", user.mu_h);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "D_h:   %5.5g\n", user.D_h);CHKERRQ(ierr);

  /*
   * Create vector to hold the solution
   */
  ierr = VecCreateSeq(PETSC_COMM_WORLD, 2*user.nb_cells, &x);CHKERRQ(ierr);

  /*
   * Create time-stepper context
   */
  ierr = TSCreate(PETSC_COMM_WORLD, &ts);CHKERRQ(ierr);
  ierr = TSSetProblemType(ts, TS_NONLINEAR);CHKERRQ(ierr);

  /*
   * Tell the time-stepper context where to compute the solution
   */
  ierr = TSSetSolution(ts, x);CHKERRQ(ierr);

  /*
   * Allocate the jacobian matrix
   */
  ierr = MatCreateSeqAIJ(PETSC_COMM_WORLD, 2*user.nb_cells, 2*user.nb_cells, 4, 0, &J);CHKERRQ(ierr);

  /*
   * Provide the call-back for the non-linear function we are evaluating.
   */
  ierr = TSSetRHSFunction(ts, NULL, RHSFunction, &user);CHKERRQ(ierr);

  /*
   * Set the Jacobian matrix and the function user to compute Jacobians
   */
  ierr = TSSetRHSJacobian(ts, J, J, RHSJacobian, &user);CHKERRQ(ierr);

  /*
   * Set the function checking the domain
   */
  ierr = TSSetFunctionDomainError(ts, &DomainErrorFunction);CHKERRQ(ierr);

  /*
   * Initialize the problem with random values
   */
  ierr = FormInitialState(x, &user);CHKERRQ(ierr);

  /*
   * Read the solver type from options
   */
  ierr = TSSetType(ts, TSPSEUDO);CHKERRQ(ierr);

  /*
   * Set a large number of timesteps and final duration time to insure
   * convergenge to steady state
   */
  ierr = TSSetDuration(ts, 5000, 1e12);

  /*
   * Set a larger number of potential errors
   */
  ierr = TSSetMaxStepRejections(ts, 50);CHKERRQ(ierr);

  /*
   * Also start with a very small dt
   */
  ierr = TSSetTimeStep(ts, 0.05);CHKERRQ(ierr);

  /*
   * Set a larger time step increment
   */
  ierr = TSPseudoSetTimeStepIncrement(ts, 1.5);CHKERRQ(ierr);

  /*
   * Let the user personalise TS
   */
  ierr = TSSetFromOptions(ts);CHKERRQ(ierr);

  /*
   * Set the context for the time stepper
   */
  ierr = TSSetApplicationContext(ts, &user);CHKERRQ(ierr);

  /*
   * Setup the time stepper, ready for evaluation
   */
  ierr = TSSetUp(ts);CHKERRQ(ierr);

  /*
   * Perform the solve.
   */
  ierr = TSSolve(ts, x);CHKERRQ(ierr);
  ierr = TSGetSolveTime(ts, &ftime);CHKERRQ(ierr);
  ierr = TSGetTimeStepNumber(ts,&its);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "Number of time steps = %D, final time: %4.2e\nResult:\n\n", its, (double)ftime);CHKERRQ(ierr);
  ierr = PrintSolution(x, &user);CHKERRQ(ierr);

  /*
   * Free the data structures
   */
  ierr = VecDestroy(&x);CHKERRQ(ierr);
  ierr = MatDestroy(&J);CHKERRQ(ierr);
  ierr = TSDestroy(&ts);CHKERRQ(ierr);
  ierr = PetscFinalize();
    return 0;
}