Example #1
0
		Mesh::Mesh(istream &is, bool calculateEdges) : calculateEdges(calculateEdges) {
			FileId id;												// Read File header
			get(is, id);

			if (!is) {
				console::print(1.0f, 0.0f, 0.0f, "Failed to load mesh!");
				return;
			}

			if (id != string2id("mESH")) {
				console::print(1.0f, 0.0f, 0.0f, "Not a mesh file!");
				return;
			}

			FileVersion ver;
			get(is, ver);

			if (ver.major != 1 || ver.minor != 0) {
				console::print(1.0f, 0.0f, 0.0f, "Unknown mesh version!");
				return;
			}

			MeshHeader header;										// Read mesh file header
			get(is, header);									

			for (dword i = 0; i < header.textures; ++i) {			// Read textures
				char name[256];
				byte length;
				get(is, length);
				is.read(name, (int)length + 1);
				addTexture(name);
			}

			for (dword i = 0; i < header.materials; i++) {			// Read materials
				addMaterial(Material(is));
			}

			for (dword i = 0; i < header.vertices; i++) {			// Read vertices
				Vector3 v;
				get(is, v[0]);
				get(is, v[1]);
				get(is, v[2]);
				addVertex(v);
			}
			
			for (dword i = 0; i < header.vertices; i++) {			// Read normals
				Vector3 n;
				get(is, n[0]);
				get(is, n[1]);
				get(is, n[2]);
				setNormal(i, n);
			}
			
			for (dword i = 0; i < header.vertices; i++) {			// Read texture coordinates
				Vector2 uv;
				get(is, uv[0]);
				get(is, uv[1]);
				addTexCoord(uv);
			}
			
			for (dword i = 0; i < header.triangles; i++) {			// Read triangles
				Triangle tri;
				get(is, tri.v[0]);
				get(is, tri.v[1]);
				get(is, tri.v[2]);
				get(is, tri.texture);
				get(is, tri.material);
				tri.uv[0] = tri.v[0];
				tri.uv[1] = tri.v[1];
				tri.uv[2] = tri.v[2];
				addTriangle(tri);
			}
			
			for (dword i = 0; i < header.edges; i++) {				// Read edges
				Edge e;
				get(is, e.v[0]);
				get(is, e.v[1]);
				get(is, e.plane[0]);
				get(is, e.plane[1]);
				if (!calculateEdges) addEdge(e);
			}
		}
RingGraph::RingGraph (int vNum) : Graph (vNum)
{
    for (int v = 1; v < vNum; v++) { addEdge(v-1,v); }
    addEdge(vNum-1,0);
}
Example #3
0
void MergeHull3D::initialFace()
{
    pointList.sort(compareY);

    Point *p0 = pointList.front();
    Point *p0_1 = new Point3D( p0->getCoord(0) + 1.0, p0->getCoord(1), p0->getCoord(2) );
    Point *p0_2 = new Point3D( p0->getCoord(0), p0->getCoord(1), p0->getCoord(2) - 1.0 );

    Vector3D n1 = Vector3D( p0, p0_1 ).cross( Vector3D(p0, p0_2) );

    n1.normalize();

    double ang = 360.0;

    for (std::list<Point*>::iterator it=pointList.begin(); it!=pointList.end(); it++)
    {
        if( (*it)->getId() == p0->getId() )
            continue;

        Vector3D n2 = Vector3D( (*it) , p0 ).cross( Vector3D((*it), p0_2) );

        n2.normalize();

        double ang_temp = n2.angle(n1);

        if(ang >= ang_temp)
        {
            ang = ang_temp;
            p0_1 = (*it);
        }
    }


    n1 = Vector3D( p0, p0_1 ).cross( Vector3D(p0, p0_2) );

    n1.normalize();

    ang = 360.0;

    for (std::list<Point*>::iterator it=pointList.begin(); it!=pointList.end(); it++)
    {
        if( (*it)->getId() == p0->getId() || (*it)->getId() == p0_1->getId() )
            continue;

        Vector3D n2 = Vector3D( (*it) , p0 ).cross( Vector3D((*it), p0_1) );

        n2.normalize();

        double ang_temp = n2.angle(n1);

        if(ang >= ang_temp)
        {
            ang = ang_temp;
            p0_2 = (*it);
        }

    }


    p0->setColorR(1);
    p0_1->setColorG(1);
    p0_2->setColorB(1);

    Edge *e0 = new Edge3D((Point3D*)p0_1, (Point3D*)p0, edgeList.size()+1);
    Edge *e1 = new Edge3D((Point3D*)p0, (Point3D*)p0_2, edgeList.size()+1);
    Edge *e2 = new Edge3D((Point3D*)p0_2, (Point3D*)p0_1, edgeList.size()+1);

    addEdge( (Edge3D*)e0 );
    addEdge( (Edge3D*)e1 );
    addEdge( (Edge3D*)e2 );

    GeometricShape *face_aux = new Polygon(3);

    face_aux->setPoint(0, p0_1);
    face_aux->setPoint(1, p0);
    face_aux->setPoint(2, p0_2);

    face_aux->setEdge(0, e0);
    face_aux->setEdge(1, e1);
    face_aux->setEdge(2, e2);

    ((Edge3D*)e0)->addAdjFace( ((Polygon*)face_aux) );
    ((Edge3D*)e1)->addAdjFace( ((Polygon*)face_aux) );
    ((Edge3D*)e2)->addAdjFace( ((Polygon*)face_aux) );

    ((Polygon*)face_aux)->setColorR(0.5);
    ((Polygon*)face_aux)->setColorG(0.5);
    ((Polygon*)face_aux)->setColorB(0.5);

    facesList.push_back( (Polygon*)face_aux );
}
Example #4
0
void GPolygon::addPolarEdge(double r, double theta) {
   addEdge(r * cos(theta * PI / 180), -r * sin(theta * PI / 180));
}
Example #5
0
void ClosureBuffer::addEdgeSet(OptimizableGraph::EdgeSet& eset){
  for (OptimizableGraph::EdgeSet::iterator it=eset.begin(); it!=eset.end(); ++it){
    OptimizableGraph::Edge *e=(OptimizableGraph::Edge*)(*it);
    addEdge(e);
  }
}
Example #6
0
int main() {
    freopen("input.txt", "r", stdin);
    int i, j, row_1, column_1, test_case, con_number, con, plus;
    int row_sum, column_sum, max_flow, sums, flag;
    char symbol;
    scanf("%d", &test_case);
    while (test_case--) {
        init();
        flag = 1;
        scanf("%d%d", &row, &column);
        source = 0;
        destination = row + column + 1;
        super_source = row + column + 2;
        super_destination = row + column + 3;
        for (i = 1; i <= row; i++) {
            for (j = 1; j <= column; j++) {
                high[i][j] = INF;
            }
        }
        for (i = 1; i<= row; i++) {
            scanf("%d", &row_sum);
            in[i] += row_sum;
            out[source] += row_sum;
        }
        for (i = 1; i <= column; i++) {
            scanf("%d", &column_sum);
            out[i + row] += column_sum;
            in[destination] += column_sum;
        }
        scanf("%d", &con_number);
        for (i = 1; i <= con_number; i++) {
            scanf("%d %d %c %d", &row_1, &column_1, &symbol, &con);
            if (symbol == '=') {
                build(row_1, column_1, con, con);
            }
            else if (symbol == '>') {
                build(row_1, column_1, con + 1, INF);
            }
            else {
                build(row_1, column_1, 0, con - 1);
            }
        }
        for (i = 1; i <= row; i++) {
            for (j = 1; j <= column ; j++) {
                out[i] += low[i][j];
                in[j + row] += low[i][j];
                if (high[i][j] - low[i][j] < 0) {
                    flag = 0;
                }
                addEdge(i, j + row, high[i][j] - low[i][j], 0);
                number[i][j] = edge_number;
            }
        }
        sums = 0;
        for (i = 0; i <= destination; i++) {
            plus = in[i] - out[i];
            if (plus > 0) {
                sums += plus;
                addEdge(super_source, i, plus, 0);
            }
            else {
                addEdge(i, super_destination, -plus, 0);
            }
        }
        addEdge(destination, source, INF, 0);
        max_flow = dinic();
        if (max_flow != sums) {
            flag = 0;
        }
        if (flag) {
            for (i = 1; i <= row; i++) {
                printf("%d", low[i][1] + edge[number[i][1]].cap);
                for (j = 2; j <= column; j++) {
                    printf(" %d", low[i][j] + edge[number[i][j]].cap);
                }
                printf("\n");
            }
        }
        else {
            printf("IMPOSSIBLE\n");
        }
        printf("\n");
    }
    return 0;
}
Example #7
0
/**
 * Добавляет узел в граф и строит связааные с ним зависимости(дуги)
 * Исходим из предположения, что в акутальных данных содержаться 
 * детерминированныее данные, в том числе и скаляры-массивы.
 */
void Graph::addNode(const Node &_arg_)
{
    //cout<<"node added"<<endl;
    stringSet local; // local edge vars
    stringSet other; // other vars to arg
    Node arg = _arg_; // will be changed
    arg.setActual(createActual(arg. getIn()), createActual(arg. getOut()));
    // check for return in statement
    bool containReturn = false;
    /*
    {
     cout<<"Node #"<<arg. getNumber()<<" statement: ";
     arg.getAction().print(cout, "");
     cout<<"Node #"<<arg. getNumber()<<" (in):"<<arg.getActualIn()<<endl;
     cout<<"Node #"<<arg. getNumber()<<" (out):"<<arg.getActualOut()<<endl;
    }   */
    if (checkStatement(arg.getAction(), false, false) == -2)
        containReturn = true;
    /*
     * Если в предложении есть возврат, то это зависимость по управлению
     * и необходимо, что бы все действия были завершены до действия возврата
     * это позволит сохранить семантику исполнения программы.  
     */
    nodes_num++;
    // first phase
    stringSet foreverOut = arg. getActualOut(); // arg's out
    stringSet readOut = arg. getActualOut(); // current read for consistency
    stringSet readIn = arg. getActualIn();  // current read for in

    TNodeSet::iterator beg = nodes. begin();
    TNodeSet::iterator end = nodes. end();
    unsigned long layer = init_layer - 1;
    bool findDep = false;
    while (beg != end)
    {
        Node cur = (*--end);
        // forward dep
        if (isForwardDepend(readIn, cur. getActualOut()))
        {
            findDep = true;
            // form local
            createForwardTransition(cur. getActualOut(), readIn, local, other);
            //cout<<"Forward :"<<cur. getNumber()<<"->"<<arg. getNumber()<<":"<<local<<endl;
            // cur. actual(), readIn() - in
            // local, other, actual - out
            readIn = other;
            other. clear(); // для использования в ЛЮБОЙ следующий раз
        }
        else
        {
            // backward dep
            if (isBackwardDepend(foreverOut, cur. getActualIn()))
            {
                //cout<<"Backward :"<<cur. getNumber()<<"->"<<arg. getNumber()<<endl;
                findDep = true;
            }
        }
        // out dep
        if (isOutwardDepend(foreverOut, cur. getActualOut()))
        {
            findDep = true;
            if (arg.getNumber() == 3)
            {
                //cout<<"Extended info"<<endl;
                //cout<<"Forever out : "<<foreverOut<<endl;
                //cout<<"cur out Node #"<<cur. getNumber()<<": "<<cur.getActualOut()<<endl;
                //cout<<"readOut: "<<readOut<<endl;
                //cout<<"Local: "<<local<<endl;
                //cout<<"Node #"<<arg. getNumber()<<" (in):"<<arg.getActualIn()<<endl;
                //cout<<"Node #"<<arg. getNumber()<<" (out):"<<arg.getActualOut()<<endl;
            }

            createOutwardTransition(cur. getActualOut(), readOut, local, other);
            //cout<<"Outward :"<<cur. getNumber()<<"->"<<arg. getNumber()<<":"<<local<<endl;
            // cur. actual(), arg. getIn() - in
            // local, other, actual - inout
            readOut = other;
            other. clear();
        }
        if (findDep)
        {
            // create edge
            Edge edge(arg. getNumber(), cur. getNumber(), packArrays(local));
            //edge. print(cout); // cout
            if (!local. empty())
                ;
            //cout<<"Transit :"<<local<<endl;
            addEdge(edge);
            local. clear();

            arg.addIn(edge. getNumber());
            (*end). addOut(edge. getNumber());
            if (cur. getLayer() > layer)
                layer = cur. getLayer();
            findDep = false;
        }
        else
        {
            if (containReturn)
            {
                // create empty edge
                Edge edge(arg. getNumber(), cur. getNumber(), stringSet());
                addEdge(edge);
                arg.addIn(edge. getNumber());
                (*end). addOut(edge. getNumber());
                if (cur. getLayer() > layer)
                    layer = cur. getLayer();
            } // else - do nothing
        }
    }
    // insert node
    arg. setLayer(layer + 1);
    nodes. push_back(arg);
}
Example #8
0
static void delaunayHull(const int npts, const float* pts,
                                                 const int nhull, const int* hull,
                                                 rcIntArray& tris, rcIntArray& edges)
{
        int nfaces = 0;
        int nedges = 0;
        const int maxEdges = npts*10;
        edges.resize(maxEdges*4);
        
        for (int i = 0, j = nhull-1; i < nhull; j=i++)
                addEdge(&edges[0], nedges, maxEdges, hull[j],hull[i], HULL, UNDEF);
        
        int currentEdge = 0;
        while (currentEdge < nedges)
        {
                if (edges[currentEdge*4+2] == UNDEF)
                        completeFacet(pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);
                if (edges[currentEdge*4+3] == UNDEF)
                        completeFacet(pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);
                currentEdge++;
        }


        // Create tris
        tris.resize(nfaces*4);
        for (int i = 0; i < nfaces*4; ++i)
                tris[i] = -1;
        
        for (int i = 0; i < nedges; ++i)
        {
                const int* e = &edges[i*4];
                if (e[3] >= 0)
                {
                        // Left face
                        int* t = &tris[e[3]*4];
                        if (t[0] == -1)
                        {
                                t[0] = e[0];
                                t[1] = e[1];
                        }
                        else if (t[0] == e[1])
                                t[2] = e[0];
                        else if (t[1] == e[0])
                                t[2] = e[1];
                }
                if (e[2] >= 0)
                {
                        // Right
                        int* t = &tris[e[2]*4];
                        if (t[0] == -1)
                        {
                                t[0] = e[1];
                                t[1] = e[0];
                        }
                        else if (t[0] == e[0])
                                t[2] = e[1];
                        else if (t[1] == e[1])
                                t[2] = e[0];
                }
        }
        
        for (int i = 0; i < tris.size()/4; ++i)
        {
                int* t = &tris[i*4];
                if (t[0] == -1 || t[1] == -1 || t[2] == -1)
                {
                        if (rcGetLog())
                                rcGetLog()->log(RC_LOG_WARNING, "delaunayHull: Removing dangling face %d [%d,%d,%d].", i, t[0],t[1],t[2]);
                        t[0] = tris[tris.size()-4];
                        t[1] = tris[tris.size()-3];
                        t[2] = tris[tris.size()-2];
                        t[3] = tris[tris.size()-1];
                        tris.resize(tris.size()-4);
                }
        }


}
Example #9
0
void main() {
	struct graph *graph = createGraph();
	addVertex(graph, 1);
	addVertex(graph, 2);
	addVertex(graph, 3);
	addVertex(graph, 4);
	addVertex(graph, 5);

	addEdge(graph, 1, 2);
	addEdge(graph, 1, 3);
	addEdge(graph, 1, 4);
	addEdge(graph, 2, 1);
	addEdge(graph, 2, 3);
	addEdge(graph, 3, 2);
	addEdge(graph, 3, 1);
	addEdge(graph, 4, 1);
	addEdge(graph, 5, 2);
	addEdge(graph, 5, 3);
	addEdge(graph, 3, 5);
	addEdge(graph, 2, 5);

	printGraph(graph);
	bfsTraversal(graph);
	dfsTraversal(graph);
}
Example #10
0
// -------------------------------------------------------------------------
int GraphDefinition::my_dijkstra(edge_t *edges, size_t edge_count,
    long start_edge_id, double start_part, long end_edge_id, double end_part,
    bool directed, bool has_reverse_cost, path_element_tt **path,
    size_t *path_count, char **err_msg, std::vector<PDVI> &ruleList) {
    if (!m_bIsGraphConstructed) {
            init();
            construct_graph(edges, edge_count, has_reverse_cost, directed);
            m_bIsGraphConstructed = true;
        }
        GraphEdgeInfo* start_edge_info =
        m_vecEdgeVector[m_mapEdgeId2Index[start_edge_id]];
        edge_t start_edge;
        long start_vertex, end_vertex;
        m_dStartpart = start_part;
        m_dEndPart = end_part;
        m_lStartEdgeId = start_edge_id;
        m_lEndEdgeId = end_edge_id;

        if (start_part == 0.0) {
            start_vertex = start_edge_info->m_lStartNode;
        } else if (start_part == 1.0) {
            start_vertex = start_edge_info->m_lEndNode;
        } else {
            isStartVirtual = true;
            m_lStartEdgeId = start_edge_id;
            start_vertex = max_node_id + 1;
            max_node_id++;
            start_edge.id = max_edge_id + 1;
            max_edge_id++;
            start_edge.source = start_vertex;
            start_edge.reverse_cost = -1.0;
            if (start_edge_info->m_dCost >= 0.0) {
                start_edge.target = start_edge_info->m_lEndNode;
                start_edge.cost = (1.0 - start_part) * start_edge_info->m_dCost;
                addEdge(start_edge);
                edge_count++;
            }
            if (start_edge_info->m_dReverseCost >= 0.0) {
                start_edge.id = max_edge_id + 1;
                max_edge_id++;
                start_edge.target = start_edge_info->m_lStartNode;
                start_edge.cost = start_part * start_edge_info->m_dReverseCost;
                addEdge(start_edge);
                edge_count++;
            }
        }

    GraphEdgeInfo* end_edge_info =
    m_vecEdgeVector[m_mapEdgeId2Index[end_edge_id]];
    edge_t end_edge;

    if (end_part == 0.0) {
        end_vertex = end_edge_info->m_lStartNode;
    } else if (end_part == 1.0) {
        end_vertex = end_edge_info->m_lEndNode;
    } else {
        isEndVirtual = true;
        m_lEndEdgeId = end_edge_id;
        end_vertex = max_node_id + 1;
        max_node_id++;
        end_edge.id = max_edge_id + 1;
        max_edge_id++;
        end_edge.target = end_vertex;
        end_edge.reverse_cost = -1.0;
        if (end_edge_info->m_dCost >= 0.0) {
            end_edge.source = end_edge_info->m_lStartNode;
            end_edge.cost = end_part * end_edge_info->m_dCost;
            addEdge(end_edge);
            edge_count++;
        }
        if (end_edge_info->m_dReverseCost >= 0.0) {
            end_edge.source = end_edge_info->m_lEndNode;
            end_edge.id = max_edge_id + 1;
            end_edge.cost = (1.0 - end_part) * end_edge_info->m_dReverseCost;
            addEdge(end_edge);
            edge_count++;
        }
    }

    return(my_dijkstra(edges, edge_count, start_vertex, end_vertex, directed,
        has_reverse_cost, path, path_count, err_msg, ruleList));
}
int main(int argc, char *argv[]) {
  long matrixSize= 16384;
  int blockSize = 128;
  bool runSequential = false;
  bool validate = false;

  int numBlasThreads = 40;

  int numGausElimThreads = 2;
  int numFactorLowerThreads = 4;
  int numFactorUpperThreads = 4;
  int numMatrixMulThreads = 30;

  std::string runtimeFileStr("runtimes");

  int numRetry = 1;

  if (argc > 1) {
    for (int arg = 1; arg < argc; arg++) {
      std::string argvs(argv[arg]);

      if (argvs == "--size") {
        arg++;
        matrixSize = atoi(argv[arg]);
      }

      if (argvs == "--num-threads-blas") {
        arg++;
        numBlasThreads = atoi(argv[arg]);
      }


      if (argvs == "num-threads-factor-l") {
        arg++;
        numFactorLowerThreads = atoi(argv[arg]);
      }

      if (argvs == "num-threads-factor-u") {
        arg++;
        numFactorUpperThreads = atoi(argv[arg]);
      }

      if (argvs == "num-threads-gaus") {
        arg++;
        numGausElimThreads = atoi(argv[arg]);
      }

      if (argvs == "num-threads-gemm") {
        arg++;
        numMatrixMulThreads = atoi(argv[arg]);
      }

      if (argvs == "--run-sequential") {
        runSequential = true;
      }

      if (argvs == "--num-retry" && arg + 1 < argc) {
        arg++;
        numRetry = atoi(argv[arg]);
      }

      if (argvs == "--block-size") {
        arg++;
        blockSize = atoi(argv[arg]);
      }


      if (argvs == "--runtime-file" && arg + 1 < argc) {
        runtimeFileStr = argv[arg + 1];
        arg++;
      }

      if (argvs == "--validate-results") {
        validate = true;
      }

      if (argvs == "--help") {
        std::cout << argv[0]
                  << " args: [--size <#>] [--block-size <#>] [--num-retry <#>] [--runtime-file <filename>] [--validate-results] [--run-sequential] [--num-threads-factor-l <#>] [--num-threads-factor-u <#>] [--num-threads-gaus <#>] [--num-threads-gemm <#>] [--num-threads-blas <#>] [--help]"
                  << std::endl;
        exit(0);

      }
    }
  }

  std::ofstream runtimeFile(runtimeFileStr, std::ios::app);
  double *matrix = new double[matrixSize * matrixSize];
  double *matrixTest = nullptr;

  // TODO: Ensure diagonally dominant
  initMatrixDiagDom(matrix, matrixSize, matrixSize, true);

  if (validate) {
    matrixTest = new double[matrixSize * matrixSize];
    for (int i = 0; i < matrixSize * matrixSize; i++)
      matrixTest[i] = matrix[i];
  }

  for (int numTry = 0; numTry < numRetry; numTry++) {
    SimpleClock clk;
    SimpleClock endToEnd;

    if (runSequential) {
      endToEnd.start();
      mkl_domain_set_num_threads(numBlasThreads, MKL_DOMAIN_ALL);
//      mkl_set_num_threads(40);

      clk.start();
      runSequentialLU(matrix, matrixSize);
//      computeSequentialMatMul(matrixA, matrixB, matrixC, matrixAHeight, sharedDim, matrixBWidth);
      clk.stopAndIncrement();
      endToEnd.stopAndIncrement();
    }
    else {
      endToEnd.start();
      mkl_domain_set_num_threads(numBlasThreads, MKL_DOMAIN_ALL);

      int gridHeight = (int) matrixSize / blockSize;
      int gridWidth = (int) matrixSize / blockSize;

      // TODO: Build graph and runtime
      htgs::StateContainer<std::shared_ptr<MatrixBlockData<double *>>> *matrixBlocks = new htgs::StateContainer<std::shared_ptr<MatrixBlockData<double *>>>(gridHeight, gridWidth, nullptr);

      for (int r = 0; r < gridHeight; r++)
      {
        for (int c = 0; c < gridWidth; c++)
        {
          // Store pointer locations for all blocks
          double *ptr = &matrix[IDX2C(r * blockSize, c *blockSize, matrixSize)];

          std::shared_ptr<MatrixRequestData> request(new MatrixRequestData(r, c, MatrixType::MatrixA));
          std::shared_ptr<MatrixBlockData<double *>> data(new MatrixBlockData<double *>(request, ptr, blockSize, blockSize));

          matrixBlocks->set(r, c, data);
        }
      }

      GausElimTask *gausElimTask = new GausElimTask(numGausElimThreads, matrixSize, matrixSize);

      auto gausElimBk = new htgs::Bookkeeper<MatrixBlockData<double *>>();

      GausElimRuleUpper *gausElimRuleUpper = new GausElimRuleUpper(matrixBlocks, gridHeight, gridWidth);
      GausElimRuleLower *gausElimRuleLower = new GausElimRuleLower(matrixBlocks, gridHeight, gridWidth);

      FactorUpperTask *factorUpperTask = new FactorUpperTask(numFactorUpperThreads, matrixSize, matrixSize);
      FactorLowerTask *factorLowerTask = new FactorLowerTask(numFactorLowerThreads, matrixSize, matrixSize);

      auto matrixMulBk = new htgs::Bookkeeper<MatrixBlockData<double *>>();
      MatrixMulRule *matrixMulRule = new MatrixMulRule(matrixBlocks, gridHeight, gridWidth);

      MatrixMulBlkTask *matrixMulTask = new MatrixMulBlkTask(numMatrixMulThreads, matrixSize, matrixSize, matrixSize, matrixSize, blockSize);


      auto matrixMulResultBk = new htgs::Bookkeeper<MatrixBlockData<double *>>();

      int numDiagonals = gridWidth - 1;
      GausElimRule *gausElimRule = new GausElimRule(numDiagonals, gridHeight, gridWidth);

      // Number of updates excluding the diagonal and the top/left row/column
      int numUpdates = (1.0/6.0) * (double)gridWidth * (2.0 * ((double)gridWidth * (double)gridWidth) - 3.0 * (double)gridWidth + 1.0);

      UpdateRule *updateRule = new UpdateRule(numUpdates);
      UpdateRule *updateRule2 = new UpdateRule(numUpdates);

      auto taskGraph = new htgs::TaskGraph<MatrixBlockData<double *>, htgs::VoidData>();
      taskGraph->addGraphInputConsumer(gausElimTask);

      taskGraph->addEdge(gausElimTask, gausElimBk);
      taskGraph->addRule(gausElimBk, factorUpperTask, gausElimRuleUpper);
      taskGraph->addRule(gausElimBk, factorLowerTask, gausElimRuleLower);

      taskGraph->addEdge(factorUpperTask, matrixMulBk);
      taskGraph->addEdge(factorLowerTask, matrixMulBk);

      taskGraph->addRule(matrixMulBk, matrixMulTask, matrixMulRule);
      taskGraph->addEdge(matrixMulTask, matrixMulResultBk);

      if (numDiagonals > 0)
        taskGraph->addRule(matrixMulResultBk, gausElimTask, gausElimRule);

      if (numUpdates > 0)
        taskGraph->addRule(matrixMulResultBk, matrixMulBk, updateRule);

      if (numUpdates > 0)
        taskGraph->addRule(matrixMulResultBk, gausElimBk, updateRule2);

      taskGraph->incrementGraphInputProducer();

      taskGraph->writeDotToFile("lud-graph.dot");

      htgs::Runtime *runtime = new htgs::Runtime(taskGraph);

      clk.start();

      runtime->executeRuntime();

      taskGraph->produceData(matrixBlocks->get(0, 0));
      taskGraph->finishedProducingData();

      runtime->waitForRuntime();

      clk.stopAndIncrement();


      delete runtime;
      endToEnd.stopAndIncrement();
    }

    double operations = (2.0 * (matrixSize * matrixSize * matrixSize)) / 3.0;
    double flops = operations / clk.getAverageTime(TimeVal::SEC);
    double gflops = flops / 1073741824.0;

    std::cout << (runSequential ? "sequential" : "htgs")
              << ", matrix-size: " << matrixSize
              << ", " << "blockSize: " << (runSequential ? 0 : blockSize)
              << ", blasThreads: " << numBlasThreads
              << ", gausThreads: " << numGausElimThreads
              << ", factorUpperThreads: " << numFactorUpperThreads
              << ", factorLowerThreads: " << numFactorLowerThreads
              << ", gemmThreads: " << numMatrixMulThreads
              << ", time:" << clk.getAverageTime(TimeVal::MILLI)
              << ", end-to-end:" << endToEnd.getAverageTime(TimeVal::MILLI)
              << ", gflops: " << gflops
        << std::endl;

    runtimeFile << (runSequential ? "sequential" : "htgs")
                << ", " << matrixSize
                << ", " << blockSize
                << ", " << numBlasThreads
                << ", " << numGausElimThreads
                << ", " << numFactorUpperThreads
                << ", " << numFactorLowerThreads
                << ", " << numMatrixMulThreads
                << ", " << clk.getAverageTime(TimeVal::MILLI)
                << ", " << endToEnd.getAverageTime(TimeVal::MILLI)
                << ", " << gflops
                << std::endl;



    if (validate)
    {
      int res = validateResults(matrix, matrixTest, matrixSize);
      std::cout << (res == 0 ? "PASSED" : "FAILED") << std::endl;
    }


  }

  delete[] matrix;
  delete[] matrixTest;

}
 	forn (i, m) {
 	 	int v, u, c;
 	 	scanf("%d%d%d", &v, &u, &c);
 	 	addEdge(v - 1, u - 1, c);
 	}
Example #13
0
Recipe &Recipe::addEdge(const Recipe::Vertex &v1, const Recipe::Vertex &v2) {
    return addEdge(_topology.get().toVertexRef(v1), _topology.get().toVertexRef(v2));
}
Example #14
0
 void merge(CBundle* b) {
     for(unsigned i=0;i<b->edges.size();i++) {
         addEdge(b->edges[i]);
     }
 }
void MotionGraph::genGraph()
{
    int k = numBlendingFrames;
    int restPoseIdx = 0;                                            // rest pose motion idx
    restLabel = 0;

    int numMotions = library->getNumMotions();

    std::vector< std::vector<int> > nodeId;            // nodeId[motionIdx][frameIdx]
    for (int m = 0; m < numMotions; m++)
    {
        nodeId.push_back(std::vector<int>());
        for (int f = 0; f < library->getMotion(m)->GetNumFrames(); f++)
            nodeId[m].push_back(-1);                                        // -1 := not a node
        nodeId[m][0] = 1;                                                   // first frame
        //nodeId[m][nodeId[m].size() - 1] = 1;                                // last frame

        // transition point to the rest pose
        int f = nodeId[m].size() - k;
        if (f >= 0)
            nodeId[m][f] = 1;
    }
    // rest pose
    if ((int)nodeId[restPoseIdx].size() >= k)
        nodeId[restPoseIdx][k - 1] = 1;

    std::vector< std::vector< std::vector<WindowPair> > > candidates;       // [motionIdxA][motionIdxB][pairIdx]
    for (int ma = 0; ma < numMotions; ma++)
    {
        candidates.push_back(std::vector< std::vector<WindowPair> >());
        for (int mb = 0; mb < numMotions; mb++)
        {
            candidates[ma].push_back(std::vector<WindowPair>());
        }
    }

    // load candidates
    printf("Loading transition candidates... ");
    std::ifstream ifs;
    ifs.open("./mocap_data/candidates.txt", std::ios::in);
    char buf[256];
    ifs >> buf;                             // #numMotions
    int nmotions;
    ifs >> nmotions;
    double threshold = 100.0;
    int minCandidateCount = 50;

    for (int ma = 0; ma < nmotions; ma++) for (int mb = 0; mb < nmotions; mb++)
    {
        ifs >> buf;                         // #motionIndex
        int motionIdxA, motionIdxB;
        ifs >> motionIdxA >> motionIdxB;
        //printf("motionIndex: %d, %d\n", motionIdxA, motionIdxB);
        ifs >> buf;                         // #motionName
        ifs >> buf;                         // motionNameA
        ifs >> buf;                         // motionNameB
        ifs >> buf;                         // #numFrames
        int numFramesA, numFramesB;
        ifs >> numFramesA >> numFramesB;
        //printf("numFrames: %d, %d\n", numFramesA, numFramesB);
        ifs >> buf;                         // #minListSize
        int minListSize;
        ifs >> minListSize;
        ifs >> buf;                         // #i
        ifs.getline(buf, sizeof(buf));      // j distance theta x0 z0
        
        int count = 0;
        for (int ii = 0; ii < minListSize; ii++)
        {
            int i, j;
            double dist;
            double theta, x0, z0;
            ifs >> i >> j >> dist >> theta >> x0 >> z0;

            if (j > (int)nodeId[mb].size() - k)     // later than last transition point
                continue;

            // check threshold & conditions
            if (dist > threshold &&
                (count > minCandidateCount ||
                 j > numFramesB / 2))
                //count > minListSize / 20)
                continue;
            count++;

            WindowPair pair;
            pair.i = i;
            pair.j = j;
            pair.dist = dist;
            pair.theta = theta;
            pair.x0 = x0;
            pair.z0 = z0;
            candidates[ma][mb].push_back(pair);

            nodeId[ma][i] = 1;
            nodeId[mb][j] = 1;
        }
    }
    ifs.close();

    printf("done.\n");

    /*for (int aa = 0; aa < numMotions; aa++)
        for (int bb = 0; bb < numMotions; bb++)
        {
            printf("motion(%d, %d): %d\n", aa, bb, candidates[aa][bb].size());
            for (size_t ii = 0; ii < candidates[aa][bb].size(); ii++)
            {
                WindowPair &p = candidates[aa][bb][ii];
                printf("%d %d %lf %lf %lf %lf\n", p.i, p.j, p.dist, p.theta, p.x0, p.z0);
            }
        }
    */

    printf("Construcing graph...\n");

    int numNodes = 0;
    int numEdges = 0;

    // construct nodes and edges within motions
    for (int m = 0; m < numMotions; m++)
    {
        int lastNode = -1;
        int count = 0;
        for (int f = 0; f < (int)nodeId[m].size(); f++)
            if (nodeId[m][f] >= 0)
            {
                // form a new node
                nodeId[m][f] = numNodes++;

                //printf("node(%d): %d, %d\n", nodeId[m][f], m, f);

                Node node;
                node.id = nodeId[m][f];
                node.motionIdx = m;
                node.frameIdx = f;
                node.label = m;                 // use motion idx as label
                nodes.push_back(node);
                
                count++;

                if (lastNode != -1)             // not the first node of the motion
                {
                    // construct an edge fram last node to current node
                    int id = numEdges++;
                    int src = nodeId[m][lastNode];
                    int dst = nodeId[m][f];
                    addEdge(id, src, dst, 0.0, 0.0, 0.0, f - lastNode);
                    nodes[src].link.push_back(id);
                }
                lastNode = f;
            }

        printf("Motion(%d): total nodes: %d\n", m, count);
    }
        
    // construct edges crossing two motions
    for (int ma = 0; ma < numMotions; ma++)
    {
        for (int mb = 0; mb < numMotions; mb++)
        {
            for (size_t ii = 0; ii < candidates[ma][mb].size(); ii++)
            {
                WindowPair &pair = candidates[ma][mb][ii];

                // construct an edge from A(i) to B(j)
                int id = numEdges++;
                int src = nodeId[ma][pair.i];
                int dst = nodeId[mb][pair.j];
                addEdge(id, src, dst, pair.theta, pair.x0, pair.z0, k - 1);
                nodes[src].link.push_back(id);
            }
        }
    }

    // construct edges from the end of motions to the rest pose
    if ((int)nodeId[restPoseIdx].size() >= k)
    {
        for (int m = 0; m < numMotions; m++)
        {
            double theta, x0, z0;
            distance(m, restPoseIdx, nodeId[m].size() - k, k - 1, &theta, &x0, &z0);
            
            int id = numEdges++;
            int src = nodeId[m][nodeId[m].size() - k];
            int dst = nodeId[restPoseIdx][k - 1];

            addEdge(id, src, dst, theta, x0, z0, k - 1, 1);
            nodes[src].link.push_back(id);
        }
    }

    // test: dump
    for (size_t eid = 0; eid < edges.size(); eid++)
    {
        Edge &e = edges[eid];
        int srcMotion = nodes[e.src].motionIdx;
        int dstMotion = nodes[e.dst].motionIdx;
        int srcFrame = nodes[e.src].frameIdx;
        int dstFrame = nodes[e.dst].frameIdx;
        //printf("edge(%d): %d(%d) --> %d(%d)\n", eid, srcMotion, srcFrame, dstMotion, dstFrame);
    }

    printf("Construcing graph... done.\n");

    ////////////////////////////////////////////////////////////////////////////

    printf("Constructing shortest path table... ");

    int numLabels = numMotions;         // can be different

    for (int dstLabel = 0; dstLabel < numLabels; dstLabel++)
    {
        // find shortest path to a certain label
        std::vector<int> dist;
        std::vector<int> next;
        for (size_t i = 0; i < nodes.size(); i++)
        {
            int initDist = 999999999;
            if (nodes[i].label == dstLabel)
                initDist = 0;
            dist.push_back(initDist);
            next.push_back(-1);
        }

        // Bellman-Ford
        for (int i = 0; i < (int)nodes.size() - 1; i++)
        {
            for (int j = 0; j < (int)edges.size(); j++)
            {
                int src = edges[j].src;
                int dst = edges[j].dst;
                if (dist[src] > dist[dst] + edges[j].length)
                {
                    dist[src] = dist[dst] + edges[j].length;
                    next[src] = j;
                }
            }
        }

        for (int i = 0; i < (int)nodes.size(); i++)
        {
            int nextEdge = next[i];

            if (nodes[i].label == dstLabel)
            {
                if (nodes[i].link.size() == 0)
                {
                    printf("Warning: nodes[%d](%d, %d).link.size() == 0\n", i, nodes[i].motionIdx, nodes[i].frameIdx);
                    exit(-1);
                }
                else
                {
                    int ndst0 = edges[nodes[i].link[0]].dst; 
                    if (nodes[ndst0].motionIdx == nodes[i].motionIdx && nodes[ndst0].frameIdx > nodes[i].frameIdx)
                    {
                        // set the next edge to the edge towards the next frame
                        nextEdge = nodes[i].link[0];
                    }
                    else
                    {
                        //printf("%d(%d)\n", nodes[i].motionIdx, nodes[i].frameIdx);
                        nextEdge = nodes[i].link[0];
                        // force to transit to rest pose
                        if (nodes[i].label != 1 &&                                  // walk
                            nodes[i].label != 2)                                    // run
                        //if (false)
                        {
                            for (int j = 0; j < (int)nodes[i].link.size(); j++)
                            {
                                if (edges[nodes[i].link[j]].rest != 0)
                                {
                                    nextEdge = nodes[i].link[j];
                                    break;
                                }
                            }
                        }
                        //printf("%d(%d) --> %d(%d)\n", nodes[edges[nextEdge].src].motionIdx, nodes[edges[nextEdge].src].frameIdx,
                        //                              nodes[edges[nextEdge].dst].motionIdx, nodes[edges[nextEdge].dst].frameIdx);
                    }
                    /*for (int j = 0; j < (int)nodes[i].link.size(); j++)
                    {
                        int dst = edges[nodes[i].link[j]].dst;
                        if (nodes[dst].motionIdx == nodes[i].motionIdx &&
                            nodes[dst].frameIdx == nodes[i].frameIdx + 1)
                        {
                            nextEdge = nodes[i].link[j];
                            break;
                        }
                    }*/
                }
            }

            nodes[i].next.push_back(nextEdge);

            if (nextEdge == -1)
            {
                printf("Warning: node[%d](%d, %d) cannot reach label %d.\n", i, nodes[i].motionIdx, nodes[i].frameIdx, dstLabel);
                //exit(-1);
            }
        }
    }

    printf("done.\n");

    printf("Total edges: %d\n", edges.size());

    ////////////////////////////////////////////////////////////////////////////

    printf("Constructing clips... ");

    // construct edge clips
    for (size_t eid = 0; eid < edges.size(); eid++)
    {
        //printf("edge(%d)  ", eid);

        Motion *clip = NULL;

        Edge &e = edges[eid];
        Node &nsrc = nodes[e.src];
        Node &ndst = nodes[e.dst];

        if (nsrc.motionIdx != ndst.motionIdx || e.length != ndst.frameIdx - nsrc.frameIdx)      // transition between two motions
        {
            //printf("src(%d, %d) dst(%d, %d) %d\n", nsrc.motionIdx, nsrc.frameIdx, ndst.motionIdx, ndst.frameIdx, e.length);
            try
            {
                Transition *tran = new Transition(library->getMotion(nsrc.motionIdx), nsrc.frameIdx, library->getMotion(ndst.motionIdx), ndst.frameIdx, e.theta, e.x0, e.z0);
                clip = tran->getBlendedMotion();
                delete tran;
            }
            catch (std::exception &e)
            {
                printf("%s\n", e.what());
                exit(-1);
            }
        }
        else                                                                                    // forward edge
        {
            //printf("forward src(%d, %d) dst(%d, %d) %d\n", nsrc.motionIdx, nsrc.frameIdx, ndst.motionIdx, ndst.frameIdx, e.length);
            Motion *motion = library->getMotion(nsrc.motionIdx);
            clip = new Motion(e.length + 1, library->getSkeleton());
            if (e.length != ndst.frameIdx - nsrc.frameIdx)
            {
                printf("Error: edges[%d].length != nodes[%d].frameIdx - nodes[%d].frameIdx\n", eid, e.dst, e.src);
            }

            for (int i = 0, j = nsrc.frameIdx; i < e.length + 1; i++, j++)
            {
                clip->SetPosture(i, *motion->GetPosture(j));
            }
        }

        clips.push_back(clip);
    }

    printf("done.\n");
        
    reset();

    printf("Generating motion graph: done.\n");
}
Example #16
0
static void completeFacet(const float* pts, int npts, int* edges, int& nedges, const int maxEdges, int& nfaces, int e)
{
        static const float EPS = 1e-5f;


        int* edge = &edges[e*4];
        
        // Cache s and t.
        int s,t;
        if (edge[2] == UNDEF)
        {
                s = edge[0];
                t = edge[1];
        }
        else if (edge[3] == UNDEF)
        {
                s = edge[1];
                t = edge[0];
        }
        else
        {
            // Edge already completed. 
            return;
        }
    
        // Find best point on left of edge. 
        int pt = npts;
        float c[3] = {0,0,0};
        float r = -1;
        for (int u = 0; u < npts; ++u)
        {
                if (u == s || u == t) continue;
                if (vcross2(&pts[s*3], &pts[t*3], &pts[u*3]) > EPS)
                {
                        if (r < 0)
                        {
                                // The circle is not updated yet, do it now.
                                pt = u;
                                circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
                                continue;
                        }
                        const float d = vdist2(c, &pts[u*3]);
                        const float tol = 0.001f;
                        if (d > r*(1+tol))
                        {
                                // Outside current circumcircle, skip.
                                continue;
                        }
                        else if (d < r*(1-tol))
                        {
                                // Inside safe circumcircle, update circle.
                                pt = u;
                                circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
                        }
                        else
                        {
                                // Inside epsilon circum circle, do extra tests to make sure the edge is valid.
                                // s-u and t-u cannot overlap with s-pt nor t-pt if they exists.
                                if (overlapEdges(pts, edges, nedges, s,u))
                                        continue;
                                if (overlapEdges(pts, edges, nedges, t,u))
                                        continue;
                                // Edge is valid.
                                pt = u;
                                circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
                        }
                }
        }
        
        // Add new triangle or update edge info if s-t is on hull. 
        if (pt < npts)
        {
                // Update face information of edge being completed. 
                updateLeftFace(&edges[e*4], s, t, nfaces);
                
                // Add new edge or update face info of old edge. 
                e = findEdge(edges, nedges, pt, s);
                if (e == UNDEF)
                    addEdge(edges, nedges, maxEdges, pt, s, nfaces, UNDEF);
                else
                    updateLeftFace(&edges[e*4], pt, s, nfaces);
                
                // Add new edge or update face info of old edge. 
                e = findEdge(edges, nedges, t, pt);
                if (e == UNDEF)
                    addEdge(edges, nedges, maxEdges, t, pt, nfaces, UNDEF);
                else
                    updateLeftFace(&edges[e*4], t, pt, nfaces);
                
                nfaces++;
        }
        else
        {
                updateLeftFace(&edges[e*4], s, t, HULL);
        }
}
Example #17
0
JG::JG(GM& gm, int i_bound__, int num_iterations__, vector<int>& order,
		JG_TYPE type) :
	num_iterations_(num_iterations__), i_bound_(i_bound__), copy_of_gm(&gm) {
	//printStacktrace();
	vector<int> mapped_order(order.size());
	for (int i = 0; i < order.size(); i++)
		mapped_order[order[i]] = i;
	assert(order.size()==gm.variables.size());
	//cerr<<"Creating buckets\n";
	// Create buckets
	vector<vector<JGHelperFunction> > buckets(order.size());
	for (int i = 0; i < gm.functions.size(); i++) {
		int min_size = (int) gm.variables.size();
		for (int j = 0; j < gm.functions[i]->variables().size(); j++) {
			if (gm.functions[i]->variables()[j]->id() >= order.size()) {
				gm.functions[i]->print();
				exit(1);
			}
			if (mapped_order[gm.functions[i]->variables()[j]->id()] < min_size) {
				min_size = mapped_order[gm.functions[i]->variables()[j]->id()];
			}
		}
		if (min_size == (int) gm.variables.size()) {
			for (int j = 0; j < gm.functions[i]->variables().size(); j++) {
				cerr << gm.functions[i]->variables()[j]->id() << endl;
			}

		}
		//cout<<min_size<<endl;
		buckets[min_size].push_back(JGHelperFunction(
				gm.functions[i]->variables(), INVALID_VALUE, gm.functions[i]));
		//cout<<"\tAdded\n";
	}
	//cout<<"buckets created\n";

	//Update i_bound
	/*
	 int max_func_size=0;

	 for(int i=0;i<gm.functions.size();i++)
	 {
	 int domain_size=0;
	 domain_size=Variable::getDomainSize(gm.functions[i]->variables());
	 if(max_func_size < domain_size)
	 {
	 max_func_size=domain_size;
	 }
	 }
	 int avg_domain_size=0;
	 for(int i=0;i<gm.variables.size();i++)
	 {
	 avg_domain_size+=gm.variables[i]->domain_size();
	 }
	 avg_domain_size/=(int)gm.variables.size();
	 cerr<<avg_domain_size<<" "<<max_func_size<<" ";
	 int i_bound=1;
	 for(int i=0;i<(i_bound_-1);i++)
	 {
	 i_bound*=avg_domain_size;
	 }
	 i_bound*=(max_func_size);
	 */
	//max_cluster_size=i_bound;
	cerr << "Dom size i-bound = " << i_bound() << endl;
	int old_nodes = 0;
	int id = 0;
	// Run schematic mini-buckets
	for (int i = 0; i < order.size(); i++) {
		//cerr<<i<<endl;
		// Form mini-buckets by using the first fill rule
		for (int j = 0; j < buckets[i].size(); j++) {
			bool found = false;
			int loc = INVALID_VALUE;
			for (int k = old_nodes; k < nodes.size(); k++) {
				vector<Variable*> temp_variables;
				do_set_union(buckets[i][j].variables, nodes[k]->variables(),
						temp_variables, less_than_comparator_variable);
				//int domain_size=Variable::getDomainSize(temp_variables);
				//if((int)domain_size <= i_bound)
				if ((int) temp_variables.size() <= i_bound()) {
					found = true;
					loc = k;
					break;
				}
			}
			// If not found create a mini-bucket
			if (!found) {

				nodes.push_back(addNode(type));
				nodes[nodes.size() - 1]->id() = id;
				id++;
				nodes[nodes.size() - 1]->variables() = buckets[i][j].variables;
				if (buckets[i][j].parent_id != INVALID_VALUE) {
					//cout<<"F1\n";
					//nodes[nodes.size()-1]->neighbors().push_back(nodes[buckets[i][j].parent_id]);
					//nodes[buckets[i][j].parent_id]->neighbors().push_back(nodes[nodes.size()-1]);
					JGEdge* edge = addEdge(nodes[nodes.size() - 1],
							nodes[buckets[i][j].parent_id], type);
					do_set_intersection(nodes[nodes.size() - 1]->variables(),
							nodes[buckets[i][j].parent_id]->variables(),
							edge->variables(), less_than_comparator_variable);
					//edge->setNode1(nodes[nodes.size()-1]);
					//edge->setNode2(nodes[buckets[i][j].parent_id]);
					do_set_intersection(nodes[nodes.size() - 1]->variables(),
							nodes[buckets[i][j].parent_id]->variables(),
							edge->variables(), less_than_comparator_variable);
					nodes[nodes.size() - 1]->edges().push_back(edge);
					nodes[buckets[i][j].parent_id]->edges().push_back(edge);

				} else {
					//cout<<"F2\n";
					nodes[nodes.size() - 1]->addFunction(*buckets[i][j].f);
				}
			} else {

				do_set_union(buckets[i][j].variables, nodes[loc]->variables(),
						nodes[loc]->variables(), less_than_comparator_variable);
				if (buckets[i][j].parent_id != INVALID_VALUE) {
					//cout<<"F3\n";
					/*nodes[loc]->neighbors().push_back(nodes[buckets[i][j].parent_id]);
					 nodes[buckets[i][j].parent_id]->neighbors().push_back(nodes[loc]);*/
					JGEdge* edge = addEdge(nodes[loc],
							nodes[buckets[i][j].parent_id], type);
					do_set_intersection(nodes[loc]->variables(),
							nodes[buckets[i][j].parent_id]->variables(),
							edge->variables(), less_than_comparator_variable);
					//edge->setNode1(nodes[loc]);
					//edge->setNode2(nodes[buckets[i][j].parent_id]);
					do_set_intersection(nodes[loc]->variables(),
							nodes[buckets[i][j].parent_id]->variables(),
							edge->variables(), less_than_comparator_variable);
					nodes[loc]->edges().push_back(edge);
					nodes[buckets[i][j].parent_id]->edges().push_back(edge);

				} else {
					//cout<<"F4\n";
					nodes[loc]->addFunction(*buckets[i][j].f);
				}

			}
		}
		vector<Variable*> curr_variable;
		curr_variable.push_back(gm.variables[order[i]]);

		// Connect the newly created nodes to each other
		for (int j = old_nodes; j < (int) nodes.size() - 1; j++) {
			//nodes[j]->neighbors().push_back(nodes[j+1]);
			//nodes[j+1]->neighbors().push_back(nodes[j]);
			JGEdge* edge = addEdge(nodes[j], nodes[j + 1], type);
			//edge->setNode1(nodes[j]);
			//edge->setNode2(nodes[j+1]);
			edge->variables() = curr_variable;
			nodes[j]->edges().push_back(edge);
			nodes[j + 1]->edges().push_back(edge);
		}

		if (i < (int) order.size() - 1) {
			for (int j = old_nodes; j < nodes.size(); j++) {

				vector<Variable*> temp_variables;
				do_set_difference(nodes[j]->variables(), curr_variable,
						temp_variables, less_than_comparator_variable);
				if (temp_variables.empty())
					continue;
				// Put the node in the appropriate bucket
				int min_size = (int) gm.variables.size();
				for (int k = 0; k < temp_variables.size(); k++) {

					if (min_size > mapped_order[temp_variables[k]->id()]) {
						min_size = mapped_order[temp_variables[k]->id()];
					}
				}
				assert(min_size<(int)gm.variables.size());
				//if(min_size >=(int) gm.variables.size())
				//	continue;
				buckets[min_size].push_back(JGHelperFunction(temp_variables, j));
			}
		}
		old_nodes = (int) nodes.size();
	}

	//print();
	// Minimize edges
	//minimize();
	// update node ids
	/*for(int i=0;i<nodes.size();i++)
	 {
	 nodes[i]->id()=i;
	 }*/
	//print();
	//// Set node and edge sizes
	//for(int i=0;i<nodes.size();i++)
	//{
	//	// Find domain size
	//	int domain_size=Variable::getDomainSize(nodes[i]->variables());
	//	nodes[i]->table()=vector<Double>(domain_size);
	//	for(int j=0;j<domain_size;j++)
	//	{
	//		nodes[i]->table()[j]=Double(1.0);
	//	}
	//	for(int j=0;j<nodes[i]->edges().size();j++)
	//	{
	//		int domain_size=Variable::getDomainSize(nodes[i]->edges()[j]->variables());
	//		nodes[i]->edges()[j]->message1()=vector<Double> (domain_size);
	//		nodes[i]->edges()[j]->message2()=vector<Double> (domain_size);
	//		for(int k=0;k<domain_size;k++)
	//		{
	//			nodes[i]->edges()[j]->message1()[k]=Double(1.0);
	//			nodes[i]->edges()[j]->message2()[k]=Double(1.0);
	//		}
	//	}
	//}
	//cerr<<"Now putting functions\n";
	////reduce();
	cout << "Join graph done\n";

}
Example #18
0
int main(int argc, char* argv[]){
   int i, n=8;
   List S = newList();
   Graph G = newGraph(n);
   Graph T=NULL, C=NULL;

   Graph G_undir = newGraph(35);
   for(i=1; i<35; i++) {
      if( i%7!=0 ) addEdge(G_undir, i, i+1);
      if( i<=28 ) addEdge(G_undir, i, i+7);
   }
   printf("The Order of this undirected graph is: %d\n", getOrder(G_undir));
   printf("The Size of this undirected graph is: %d\n", getSize(G_undir));
   printf("Adjacency list representation of G_undir: \n");
   printGraph(stdout, G_undir);
   printf("\n");

   for(i=1; i<=n; i++) append(S, i);

   addArc(G, 1,2);
   addArc(G, 1,5);
   addArc(G, 2,5);
   addArc(G, 2,6);
   addArc(G, 3,2);
   addArc(G, 3,4);
   addArc(G, 3,6);
   addArc(G, 3,7);
   addArc(G, 3,8);
   addArc(G, 6,5);
   addArc(G, 6,7);
   addArc(G, 8,4);
   addArc(G, 8,7);
   printf("The Order of this graph is: %d\n", getOrder(G));
   printf("The Size of this graph is: %d\n", getSize(G));
   printf("Adjacency list representation of G: \n");
   printGraph(stdout, G);

   DFS(G, S);
   fprintf(stdout, "\n");
   fprintf(stdout, "x:  d  f  p\n");
   for(i=1; i<=n; i++){
      fprintf(stdout, "%d: %2d %2d %2d\n", i, getDiscover(G, i), getFinish(G, i), getParent(G, i));
   }
   fprintf(stdout, "\n");
   printList(stdout, S);
   fprintf(stdout, "\n");

   T = transpose(G);
   C = copyGraph(G);
   fprintf(stdout, "\n");
   printGraph(stdout, C);
   fprintf(stdout, "\n");
   printGraph(stdout, T);
   fprintf(stdout, "\n");

   DFS(T, S);
   fprintf(stdout, "\n");
   fprintf(stdout, "x:  d  f  p\n");
   for(i=1; i<=n; i++){
      fprintf(stdout, "%d: %2d %2d %2d\n", i, getDiscover(T, i), getFinish(T, i), getParent(T, i));
   }
   fprintf(stdout, "\n");
   printList(stdout, S);
   fprintf(stdout, "\n");

   freeList(&S);
   freeGraph(&G);
   freeGraph(&T);
   freeGraph(&C);
   return(0);
}
Example #19
0
cMesh::cMesh(const std::string & Filename, bool doAdjacence)
{
    PlyFile * thePlyFile;
    int nelems;
    char **elist;
    int file_type;
    float version;
    int nprops;
    int num_elems;
    char *elem_name;

    thePlyFile = ply_open_for_reading( const_cast<char *>(Filename.c_str()), &nelems, &elist, &file_type, &version);

    ELISE_ASSERT(thePlyFile != NULL, "cMesh3D.cpp: cMesh::cMesh, cannot open ply file for reading");

    for (int i = 0; i < nelems; i++)
    {
        elem_name = elist[i];
        ply_get_element_description (thePlyFile, elem_name, &num_elems, &nprops);

        //printf ("element %s %d\n", elem_name, num_elems);

        if (equal_strings ("vertex", elem_name))
        {
            ply_get_property (thePlyFile, elem_name, &props[0]);
            ply_get_property (thePlyFile, elem_name, &props[1]);
            ply_get_property (thePlyFile, elem_name, &props[2]);

            for (int j = 0; j < num_elems; j++)
            {
                sVertex *vert = (sVertex *) malloc (sizeof(sVertex));

                ply_get_element (thePlyFile, vert);

                //ajout du point
                addPt(Pt3dr(vert->x, vert->y, vert->z));

                //printf ("vertex: %g %g %g\n", vert->x, vert->y, vert->z);
            }
        }
        else if (equal_strings ("face", elem_name))
        {
            ply_get_property ( thePlyFile, elem_name, &face_props[0]);

            for (int j = 0; j < num_elems; j++)
            {
                sFace *theFace = (sFace *) malloc (sizeof (sFace));
                ply_get_element (thePlyFile, theFace);

                vector <int> vIndx;
                for (int aK =0; aK < theFace->nverts; ++aK)
                    vIndx.push_back(theFace->verts[aK]);

                //ajout du triangle
                addTriangle(cTriangle(this, vIndx, j));
            }
        }
    }

    if (doAdjacence) //remplissage du graphe d'adjacence
    {
        int cpt;

        int id0a, id1a, id2a;
        int id0b, id1b, id2b;
        int idc0, idc1; //index des sommets communs
        id0a = id1a = id2a = idc0 = idc1 = -1;
        id0b = id1b = id2b = -2;

        for (int aK = 0; aK < getFacesNumber(); ++aK)
        {
            mTriangles[aK].getVertexesIndexes(id0a, id1a, id2a);

            for (int bK=aK; bK < getFacesNumber(); ++bK)
            {
                mTriangles[bK].getVertexesIndexes(id0b, id1b, id2b);

                cpt = 0;
                if((id0b == id0a)||(id1b == id0a)||(id2b == id0a)) {cpt++; idc0 = id0a;}
                if((id0b == id1a)||(id1b == id1a)||(id2b == id1a))
                {
                    if (cpt) idc1 = id1a;
                    else	 idc0 = id1a;

                    cpt++;
                }
                if((id0b == id2a)||(id1b == id2a)||(id2b == id2a))
                {
                    if (cpt) idc1 = id2a;
                    else	 idc0 = id2a;

                    cpt++;
                }

                if (cpt == 2)
                {
                    #ifdef _DEBUG
                        printf ("found adjacent triangles : %d %d - vertex : %d %d\n", aK, bK, idc0, idc1);
                    #endif

                    addEdge(cEdge(aK, bK, idc0, idc1));
                    int idx = getEdgesNumber() - 1;
                    //cout << "adding edge " << idx << endl;
                    mTriangles[aK].addEdge(idx);
                    mTriangles[bK].addEdge(idx);
                }
            }
        }
    }

    ply_close (thePlyFile);
}
Example #20
0
//------------------------------------------------------------------------------
void NiceGraph::makeStrangersBanquetGraph(int numVertices, int groups, float density, float mu)
{

	makeEmptyGraph(numVertices); 	// first initialize all the vertices

	makeUndirected(); // the SB is only undirected for now...

	if (groups > numVertices)		// bounds checking on number of groups
		groups = numVertices;
	
	for (int c = 0; c < numVertices; c++)	// now subdivide into groups
	{
		for (int g = 0; g < groups; g++)
		{
			if (c % groups == g)
				setVertexColor(c,g);
		}
	}

	// make declining edge scheme to speed things up
	int total_edges = numVertices * (numVertices - 1) / 2;
	vector<Edge> proposals (total_edges);
	
	int edgeIndex = 0;
	for (int froms = 0; froms < numVertices; froms++)
	{
		for (int tos = 0; tos < numVertices; tos++)
		{
			if ((froms != tos) && (froms < tos))
			{
				proposals[edgeIndex].from = vertexList[froms];
				proposals[edgeIndex].to = vertexList[tos];
				edgeIndex++;
			}
		}
	}
	// propose connections and build graph
	int num_edges = (int) (density * (float) total_edges);
	int edge_counter = 0;

	    while (edge_counter < num_edges)
	    {
		// use declining proposal list to speed things up...
		int randIndex = rand() % proposals.size();
		
	    	// choose two vertices to make the proposal
	    	int vertex1 = proposals[randIndex].from->vID;
	    	int vertex2 = proposals[randIndex].to->vID;
	    	
	    	if ((vertex1 != vertex2) && (!testConnected(vertex1,vertex2))) 			// if isn't itself, and aren't already connected
    		{
				// now check to see if they are accepted
				if (vertexList[vertex1]->vColor == vertexList[vertex2]->vColor) 
				{
					// if same color approve match
					addEdge(vertex1, vertex2);		// add edge
					edge_counter++;
					if (!proposals.empty()) 
						proposals.erase(proposals.begin()+randIndex);	// remove from list

				}
				else		// if different colors check against mu
				{
					float chance1 = rand() / (RAND_MAX+1.0);
					float chance2 = rand() / (RAND_MAX+1.0);
	
					if ((chance1 < mu) || (chance2 < mu))
							continue; // if either one rejects the connection do nothing
					else	
					{	// approve the connection
						addEdge(vertex1, vertex2);		// add edge
						edge_counter++;
						if (!proposals.empty()) 
							proposals.erase(proposals.begin()+randIndex);	// remove from list

					}	
				}		
		}
	}
}
Example #21
0
int main (int argc, char * argv[]) {
	/* check command line for correct number of arguments */
	if( argc != 3 ){
		printf("Usage: %s infile outfile\n", argv[0]);
		exit(1);
	}
	
	/* open files for reading and writing */
	FILE *in, *out;
	in = fopen(argv[1], "r");
	out = fopen(argv[2], "w");
	if( in==NULL ) {
		printf("Unable to open file %s for reading\n", argv[1]);
		exit(1);
	}
	if( out==NULL ) {
		printf("Unable to open file %s for writing\n", argv[2]);
		exit(1);
	}
	
	/* declare and initialize variables */
	char line[MAX_LEN];
	char* token;
	int linenum = 0;
	bool flag = FALSE;
	int  n, x, y, source, dest;
	GraphRef G;
	ListRef path = newList();
	
	/* read and store the graph and print out its adjacency list */
	while( !flag && fgets(line, MAX_LEN, in) != NULL ) {
		++linenum;
		token = strtok(line, " \n");
		if( linenum == 1 ) {
			n = atoi(token);
			G = newGraph(n);
		}else {
			x = atoi(token);
			token = strtok(NULL, " \n");
			y = atoi(token);
			if( x != 0 ) {
				addEdge(G, x, y);
			}
			else { flag = TRUE; }
		}
	}
	printGraph(out, G);
	fprintf(out, "\n");
	
	/* read in pair of vertices, run BFS on source vertex, print the distance
	 * to the destination vertex, then find and print the resulting shortest
	 * path, it if exists, or print a message if no path from source to
	 * destination exists */
	while( fgets(line, MAX_LEN, in) != NULL ) {
		token = strtok(line, " \n");
		source = atoi(token);
		token = strtok(NULL, " \n");
		dest = atoi(token);
		if( source != NIL ){
			BFS(G, source);
			makeEmpty(path);
			getPath(path, G, dest);
			printDestandPath(out, G, path, dest);
		}
	}
	
	/* free memory */
	freeList(&path);
	freeGraph(&G);
	
	/* close files */
	fclose(in);
	fclose(out);

	return(0);
}
Example #22
0
int main()
{
	freopen("t.in", "r", stdin);
	scanf("%d%d", &n, &m);
	nVtx = n * m + 2;
	int sVtx = nVtx - 2, tVtx = nVtx - 1;
	int t;
	for(int i = 1; i <= n; i ++)
		for(int j = 1; j <= m; j ++)
		{
			scanf("%d", &t);
			res += t * 2;
			w1[i][j] += t * 2;
		}
	for(int i = 1; i <= n; i ++)
		for(int j = 1; j <= m; j ++)
		{
			scanf("%d", &t);
			res += t * 2;
			w2[i][j] += t * 2;
		}
	for(int i = 1; i < n; i ++)
		for(int j = 1; j <= m; j ++)
		{
			scanf("%d", &t);
			res += t * 2;
			w3[i][j] = t;
			w1[i][j] += t, w1[i + 1][j] += t;
		}
	for(int i = 1; i < n; i ++)
		for(int j = 1; j <= m; j ++)
		{
			scanf("%d", &t);
			res += t * 2;
			w4[i][j] = t;
			w2[i][j] += t, w2[i + 1][j] += t;
		}
	for(int i = 1; i <= n; i ++)
		for(int j = 1; j < m; j ++)
		{
			scanf("%d", &t);
			res += t * 2;
			w5[i][j] = t;
			w1[i][j] += t, w1[i][j + 1] += t;
		}
	for(int i = 1; i <= n; i ++)
		for(int j = 1; j < m; j ++)
		{
			scanf("%d", &t);
			res += t * 2;
			w6[i][j] = t;
			w2[i][j] += t, w2[i][j + 1] += t;
		}
	for(int i = 1; i <= n; i ++)
		for(int j = 1; j <= m; j ++)
		{
			int u = point2Idx(i,j);
			addEdge(sVtx, u, w1[i][j]);
			addEdge(u, tVtx, w2[i][j]);
		}
	for(int i = 1; i < n; i ++)
		for(int j = 1; j <= m; j ++)
		{
			int u = point2Idx(i, j), v = point2Idx(i + 1, j);
			addEdge(u, v, w3[i][j] + w4[i][j]), addEdge(v, u, w3[i][j] + w4[i][j]);
		}
	for(int i = 1; i <= n; i ++)
		for(int j = 1; j < m; j ++)
		{
			int u = point2Idx(i, j), v = point2Idx(i, j + 1);
			addEdge(u, v, w5[i][j] + w6[i][j]), addEdge(v, u, w5[i][j] + w6[i][j]);
		}
	printf("%d\n", (res - dinic(sVtx, tVtx)) / 2);
}
void Graph::setRandom ()
{
    for (int v1 = 0; v1 < size; v1++)
		for (int v2 = v1+1; v2 < size; v2++)
			if (rand()/RAND_MAX > 0.5) addEdge(v1,v2);
}
Example #24
0
void MergeHull3D::nextFaces()
{
    Edge *edge_aux = free_edgeList.front();

    if( ((Edge3D*)edge_aux)->getAdjFaceList().size() == 1 )
    {
        Polygon* face = ((Edge3D*)edge_aux)->getAdjFaceList().front();

        Vector3D n1 = Vector3D( face->getPoint(0) , face->getPoint(1) ).cross( Vector3D(face->getPoint(0), face->getPoint(2)) );

        n1.normalize();

        double ang = 360.0;

        Point *p = NULL;

        for (std::list<Point*>::iterator it=pointList.begin(); it!=pointList.end(); it++)
        {
/*
            if( ((Edge3D*)edge_aux)->getAdjFaceList().front()->getPoint(0)->getId() == (*it)->getId()
               || ((Edge3D*)edge_aux)->getAdjFaceList().front()->getPoint(1)->getId() == (*it)->getId()
               || ((Edge3D*)edge_aux)->getAdjFaceList().front()->getPoint(2)->getId() == (*it)->getId() )
                continue;

            if( existEdge( Edge3D( (Point3D*)(*it), (Point3D*)edge_aux->getP1()) )
                && existEdge( Edge3D( (Point3D*)(*it), (Point3D*)edge_aux->getP2()) ) )
                continue;
*/
            Vector3D n2 = Vector3D( (*it) , edge_aux->getP2() ).cross( Vector3D((*it), edge_aux->getP1()) );

            n2.normalize();

            double ang_temp = n1.angle(n2);

            if(ang >= ang_temp)
            {
                ang = ang_temp;
                p = (*it);
            }
        }
        if(p == NULL) return;


        Edge *e0 = new Edge3D( (Point3D*)edge_aux->getP2(), (Point3D*)edge_aux->getP1(), edgeList.size()+1);;
        Edge *e1 = new Edge3D( (Point3D*)edge_aux->getP1(), (Point3D*)p, edgeList.size()+1);
        Edge *e2 = new Edge3D( (Point3D*)p, (Point3D*)edge_aux->getP2(), edgeList.size()+1);

        addEdge( (Edge3D*)e0 );
        addEdge( (Edge3D*)e1 );
        addEdge( (Edge3D*)e2 );

        GeometricShape *face_aux = new Polygon(3);

        face_aux->setPoint(0, edge_aux->getP1());
        face_aux->setPoint(1, p);
        face_aux->setPoint(2, edge_aux->getP2());

        face_aux->setEdge(0, e0);
        face_aux->setEdge(1, e1);
        face_aux->setEdge(2, e2);

        ((Edge3D*)e0)->addAdjFace( ((Polygon*)face_aux) );
        ((Edge3D*)e1)->addAdjFace( ((Polygon*)face_aux) );
        ((Edge3D*)e2)->addAdjFace( ((Polygon*)face_aux) );

        ((Polygon*)face_aux)->setColorR(0.5);
        ((Polygon*)face_aux)->setColorG(0.5);
        ((Polygon*)face_aux)->setColorB(0.5);

        facesList.push_back( (Polygon*)face_aux );

        //REMOVE A ARESTA QUE ERA FREE DA LISTA POIS FOI ENCONTRADA SUA NOVA FACE
        ((Edge3D*)edge_aux)->addAdjFace( (Polygon*)face_aux );
        free_edgeList.remove(edge_aux);
    }
}
FiliformGraph::FiliformGraph (int vNum) : Graph (vNum)
{
    for (int v = 1; v < vNum; v++) { addEdge(v-1,v); }
}
Example #26
0
void run ()
{   init();
	lastTurn = Straight;
   // endofList = 0;
    // memory allocation for recieved parameters from graph to drive the bot
    //res_params = (param*) malloc(sizeof(param)); 
    int i = 0;
    while(i<9){
    
        createVertexNode();
        
        i++;
    }
    addEdge(searchNode(0),searchNode(1), 3, Left, Right );
    addEdge(searchNode(1),searchNode(2), 3, Left, Right );
    addEdge(searchNode(2),searchNode(5), 3, Back, Straight );
    addEdge(searchNode(5),searchNode(4), 3, Right, Left );
    addEdge(searchNode(4),searchNode(3), 3, Right, Left );
    addEdge(searchNode(1),searchNode(4), 3, Back, Straight );
    addEdge(searchNode(0),searchNode(3), 3, Back, Straight );
    addEdge(searchNode(3),searchNode(6), 3, Back, Straight );
	addEdge(searchNode(6),searchNode(7), 3, Left, Right );
	addEdge(searchNode(7),searchNode(8), 3, Left, Right );
	addEdge(searchNode(4),searchNode(7), 3, Back, Straight );
	addEdge(searchNode(5),searchNode(8), 3, Back, Straight );    
    
   //print();
  }
Example #27
0
int main (void) {
	printf ("This program tests the graph client\n");
   Graph test_one = newGraph (6);
   Graph test_two = newGraph (10);
   /************************************************
    * Graph test_one has a representation as follows 
    *   1--------------2
    *   |             /|\
    *   |            / | \
    *   |           /  |  \
    *   3----------4---5---6
    * In this case, all the edges are undirected
    * and we will initialize our adjacency lists to
    * represent this graph
    * We will perform BFS on vertex 3 and test other
    * appropriate functions in the ADT as well
    ***********************************************/
   addArc (test_one, 1, 2); addArc (test_one, 1, 3);
   addArc (test_one, 2, 1); addArc (test_one, 2, 4); addArc (test_one, 2, 5);
                                                     addArc (test_one, 2, 6);
   addArc (test_one, 3, 1); addArc (test_one, 3, 4);
   addArc (test_one, 4, 2); addArc (test_one, 4, 3); addArc (test_one, 4, 5);
   addArc (test_one, 5, 2); addArc (test_one, 5, 4); addArc (test_one, 5, 6);
   addArc (test_one, 6, 2); addArc (test_one, 6, 5);
   BFS (test_one, 3);
   List threesix = newList();
   List threefiv = newList();
   getPath (threesix, test_one, 6);
   getPath (threefiv, test_one, 5);
   printf ("Path from three to five, Expected output: 3 1 2 6, Test output: ");
   printList (stdout, threesix);
   printf ("\n");
   printf ("Path from three to six: Expected output: 3 4 5, Test output: ");
   printList (stdout, threefiv);
   printf ("\n");
   freeList (&threesix);
   freeList (&threefiv);
   printf ("Order: Expected = 6, Output = %d\n", getOrder (test_one));
   printf ("Parent (6) = Expected = 2, Output = %d\n", getParent (test_one, 6));
   printf ("Distance (6) = Expected = 3, Output = %d\n", getDist (test_one, 6));
   printf ("___Adjacency List of test_one, Expected___\n");
   printf ("1: 2 3\n2: 1 4 5 6\n3: 1 4\n4: 2 3 5\n5: 2 4 6\n6: 2 5\n");
   printf ("___Adjacency List of test_two, Output___\n");
   printGraph (stdout, test_one); printf ("\n");
   printf ("The source of this graph is: Expected = 3, Output = %d\n",
           getSource (test_one));

   //Finish test of graph one, tests graph two now
   addEdge (test_two, 1, 2);
   addEdge (test_two, 1, 4);
   addEdge (test_two, 2, 3);
   addEdge (test_two, 2, 5);
   addEdge (test_two, 3, 6);
   addEdge (test_two, 4, 7);
   addEdge (test_two, 5, 6);
   addEdge (test_two, 5, 8);
   addEdge (test_two, 6, 8);
   addEdge (test_two, 7, 8);
   addEdge (test_two, 8, 9);
   addEdge (test_two, 9, 10);

   /**************************************************
   * visual representation of this graph
   *  1----------2----3
   *  |          |    |
   *  |          |    |
   *  4          5----6
   *  |          |    /
   *  |          |   /
   *  |          |  /
   *  |          | /   
   *  7-----------8---9----10
   ***************************************************/
   BFS (test_two, 3);
   printf ("Parent list of each vertex after BFS (test_two, 3) (Expected)\n");
   printf ("parent 1 = 2\n");
   printf ("parent 2 = 3\n");
   printf ("parent 3 = NIL\n");
   printf ("parent 4 = 1\n");
   printf ("parent 5 = 2\n");
   printf ("parent 6 = 3\n");
   printf ("parent 7 = 8\n");
   printf ("parent 8 = 6\n");
   printf ("parent 9 = 8\n");
   printf ("parent 10 = 9\n");
   printf ("The parent vertex of each vertex after BFS (test_two, 3)\n");
   for (int i = 1; i <= getOrder (test_two); ++i) {
      printf ("parent %d = ", i);
      getParent (test_two, i) == -1 ? printf ("NIL\n") 
                                    : printf ("%d\n", getParent (test_two, i));
   }
   printf ("The size of test_two is: Expected = 24, Output = %d\n", 
           getSize (test_two));
   makeNull (test_two);
   printf ("The size of test_two after makeNull (test_two) is ");
   printf ("Expected = 0, Output =%d\n", getSize (test_two));
   freeGraph (&test_one);
   freeGraph (&test_two);
}