Ejemplo n.º 1
0
BstClass<ItemType> BstClass<ItemType>::operator+(/* in */BstClass<ItemType> & rtOp)
{
	int index = 0;	//index of array
	int arrSize = (CountNodes(rtOp.root)) + (CountNodes(root));
	vector<int> values(arrSize);//create an array of total values in two trees
	BstClass<ItemType> add;

	//use inorder on both trees to get values into array
	TreeToVec(values, index, root);

	TreeToVec(values, index, rtOp.root);

	//index contains the position of the last number in list 0-index
	int length = index;

	//sort the values
	bool swap = true;	//if there is a swap need to check entire vector again for no swaps
	int temp;			//holds value that is getting swapped
	 for(int i = 1; (i <= length) && swap; i++)
     {
          swap = false;	//no swap yet
         for (int j=0; j < (length -1); j++)
         {
              if (values[j+1] < values[j])    
              { //values out of order... need to swap
                    temp = values[j];
                    values[j] = values[j+1];
                    values[j+1] = temp;
                    swap = true;		// indicates that a swap occurred.
               }//end if
          }//end for
     }//end for

	 for(int i = 0; i < (length -1); i++)
	 {
		 if(values[i] == values[i+1])
		 {//duplicate keys... delete and shuffle
			 for(int j = i; j < length - 1; j++)
				 values[j] = values[j+1];
			 length--;//decrement length for key deleted
		 }//end if
	 }//end for

	 //Insert the values in vector into the new tree
	 //maintaining lowest possible hieght
	 add.root = VecToTree(values, 0, length - 1);
	 return add;
			
}//end operator +
Ejemplo n.º 2
0
int
main(int argc, char **argv)
{
  char *obsFile, *queFile;
  FILE *infile=NULL, *outfile=NULL;
  struct binet *ratings=NULL;
  gsl_rng *rand_gen;
  int seed;
  int q, nquery;
  struct query **querySet;

  /* Command line parameters */
  if (argc < 3) {
    printf("\nUse: multi_recommend_2.out observation_file seed\n\n");
    return;
  }
  obsFile = argv[1];
  seed = atoi(argv[2]);
  rand_gen = gsl_rng_alloc(gsl_rng_mt19937);
  gsl_rng_set(rand_gen, seed);

  /* Build the observation network */
  infile = fopen(obsFile, "r");
  ratings = ReadRecommenderObservations(infile);
  fclose(infile);
  nquery = CountNodes(ratings->net1) * CountNodes(ratings->net2);

  /* Get the scores and print them */
  querySet = AllLinkScore2State(ratings,
				10000, rand_gen, 'v', -1);
  outfile = fopen("link_scores.dat", "w");
  for (q=0; q<nquery; q++) {
    if (strcmp(querySet[q]->n1->label, querySet[q]->n2->label) != 0) {
      fprintf(outfile, "%s %s %lf\n",
	      (querySet[q]->n1)->label,
	      (querySet[q]->n2)->label,
	      querySet[q]->score);
    }
  }
  fclose(outfile);

  /* Finish */
  for (q=0; q<nquery; q++)
    FreeQuery(querySet[q]);
  free(querySet);
  RemoveBipart(ratings);
  gsl_rng_free(rand_gen);
  return 0;
}
Ejemplo n.º 3
0
bool CPCRenderTree::Write(CAbstractIO &file)
{
	// Count the nodes

	file << (uint32)CountNodes();

	// Write out the tree
	std::stack<CPCRenderTreeNode*> cNodeStack;
	cNodeStack.push(m_pRoot);
	while (!cNodeStack.empty())
	{
		// Get the current node off the top
		CPCRenderTreeNode *pCurNode = cNodeStack.top();
		cNodeStack.pop();

		// Write it
		if (!pCurNode->Write(file))
			return false;

		// Push the children on the stack
		for (uint32 nChildLoop = 0; nChildLoop < CPCRenderTreeNode::k_NumChildren; ++nChildLoop)
		{
			CPCRenderTreeNode *pChild = pCurNode->GetChild(nChildLoop);
			if (pChild)
				cNodeStack.push(pChild);
		}
	}

	return true;
}
Ejemplo n.º 4
0
void SkRTree::insert(const SkRect boundsArray[], int N) {
    SkASSERT(0 == fCount);

    SkTDArray<Branch> branches;
    branches.setReserve(N);

    for (int i = 0; i < N; i++) {
        const SkRect& bounds = boundsArray[i];
        if (bounds.isEmpty()) {
            continue;
        }

        Branch* b = branches.push();
        b->fBounds = bounds;
        b->fOpIndex = i;
    }

    fCount = branches.count();
    if (fCount) {
        if (1 == fCount) {
            fNodes.setReserve(1);
            Node* n = this->allocateNodeAtLevel(0);
            n->fNumChildren = 1;
            n->fChildren[0] = branches[0];
            fRoot.fSubtree = n;
            fRoot.fBounds  = branches[0].fBounds;
        } else {
            fNodes.setReserve(CountNodes(fCount, fAspectRatio));
            fRoot = this->bulkLoad(&branches);
        }
    }
}
Ejemplo n.º 5
0
int VocabTree::Read(const char *filename) 
{
    FILE *f = fopen(filename, "rb");
    
    if (f == NULL) {
        printf("[VocabTree::Read] Error opening file %s for reading\n",
               filename);
        return -1;
    }

    /* Read the fields for the tree */
    fread(&m_branch_factor, sizeof(int), 1, f);
    fread(&m_depth, sizeof(int), 1, f);
    fread(&m_dim, sizeof(int), 1, f);    
    
    m_root = new VocabTreeInteriorNode();

    /* Read one byte for the interior field */
    char interior;
    fread(&interior, sizeof(char), 1, f);

    m_root->Read(f, m_branch_factor, m_dim);
    /* unsigned long next_id = */ m_root->ComputeIDs(m_branch_factor, 0);
    /* unsigned long n = */ m_root->CountNodes(m_branch_factor);
    /* printf("  Next id: %lu == %lu + 1\n", next_id, n); */

    m_num_nodes = CountNodes();

    fclose(f);

    return 0;
}
Ejemplo n.º 6
0
// -----------------------------------------------------------------------------------
unsigned int CountNodes(const aiNode* root)
{
	unsigned int i = 0;
	for (unsigned int a = 0; a < root->mNumChildren; ++a ) {
		i += CountNodes(root->mChildren[a]);
	}
	return 1+i;
}
Ejemplo n.º 7
0
int main(int argc, char * argv[])
{
	if (argc>1)
	{
		if (strcmp(argv[1],"-h")==0)
		{
			Help();
			return 0;
		}
		else 
		{
			puts("Error. Improper parameter.");
			return 0;
		}
	}
	tree *root;
	root = NULL;
	while (1)
	{
		puts("Options:\n1 - Create tree\n2 - Show tree\n3 - Count nodes on N level\n0 - Exit");
		int inp = -1;
		if (!GetInt(&inp))
			{
				puts("Input error. Try again");
				continue;
			}
		switch(inp)
		{
			case 1:
			root = CreateTree(root);
			break;
			case 2:
			ShowTree(root);
			break;
			case 3:
			CountNodes(root);
			break;
			case 0:
			TreeDel(root);
			return EXIT_SUCCESS;
			default:
			puts("Input error. Try again");
			break;			
		}
	}
	//TODO
}
int main()
{
	AvlTree TestTree = NULL;
	cout << "This is the test for Avl Tree." << endl;
	cout << "Notice:The print method is preorder traversal " << endl;
	cout << "First,insert some datas..." << endl;
	TestTree = Insert(9, TestTree);
	TestTree = Insert(5, TestTree);
	TestTree = Insert(10, TestTree);
	TestTree = Insert(0, TestTree);
	TestTree = Insert(6, TestTree);
	TestTree = Insert(11, TestTree);
	TestTree = Insert(-1, TestTree);
	TestTree = Insert(1, TestTree);
	TestTree = Insert(2, TestTree);
	PrintTree(TestTree);
	cout << "\nThe Min is " << Retrieve(FindMin(TestTree)) << endl;
	cout << "The Max is " << Retrieve(FindMax(TestTree)) << endl;
	cout << "Count Nodes: " << CountNodes(TestTree) << " Leaves: " 
		<< CountLeaves(TestTree) << " Full: " << CountFull(TestTree) << endl;
	cout << "Now delete 10(with one child node)..." << endl;
	TestTree = Delete(10, TestTree);
	PrintTree(TestTree);
	cout << "\nNow delete 11(with none child node)..." << endl;
	TestTree = Delete(11, TestTree);
	PrintTree(TestTree);
	cout << "\nNow delete 1(with two child node)..." << endl;
	TestTree = Delete(1, TestTree);
	PrintTree(TestTree);
	cout << "\nNow Print element between 5 and 10 in order " << endl;
	PrintKeyBetween(5, 10, TestTree);
	cout << "\nMake empty..." << endl;
	TestTree = MakeEmpty(TestTree);
	int Success = TestTree == NULL;
	cout << "Succeed? " << Success << endl;
	cout << "Now Generate the mininum tree with Height equal to 5" << endl;
	AvlTree MinH10 = MinAvlTree(5);
	PrintTree(MinH10);
	cout << "\nNow Generate the perfect tree with Height equal to 5" << endl;
	AvlTree PrefectH10 = PerfectAvlTree(5);
	PrintTree(PrefectH10);
	cout << "\nMake empty..." << endl;
	MinH10 = MakeEmpty(MinH10);
	PrefectH10 = MakeEmpty(PrefectH10);
	cout << "Good bye!" << endl;
	getchar();
}
int* BSTRighttoLeftRows(struct node* root)
{
	if (root == NULL)
		return NULL;

	int c = 0;
	CountNodes(root, &c);
	int *arr = (int *)malloc(sizeof(int)*c);
	c = 0;

	int height = get_treeHeight(root);
	for (int i = 0; i < height; i++)
	{
		level_order(root, arr, &c, i);
	}
	return arr;
}
Ejemplo n.º 10
0
int VocabTree::WriteDatabaseVectors(const char *filename, 
                                    int start_index, int num_vectors) const
{
    if (m_root == NULL)
        return -1;

    std::vector<sp_list> vectors;
    vectors.resize(num_vectors);
    
    /* Fill the database vectors from the tree */
    m_root->FillDatabaseVectors(vectors, start_index, m_branch_factor, m_dim);

    /* Write the database vectors to disk */
    FILE *f = fopen(filename, "w");
    
    if (f == NULL) {
        printf("[WriteDatabaseVectors] Error opening file %s for writing\n",
               filename);
        return -1;
    }

    // unsigned long num_leaves = CountLeaves();
    unsigned long num_nodes = CountNodes();

    fprintf(f, "%d %lu\n", num_vectors, num_nodes);
    
    for (int i = 0; i < num_vectors; i++) {
        int k = vectors[i].size();
        fprintf(f, "%d", k);
        for (int j = 0; j < k; j++) {
            fprintf(f, " %lu %0.6e", 
                    vectors[i][j].first, vectors[i][j].second);
        }

        fprintf(f, "\n");
    }

    fclose(f);

    return 0;
}
Ejemplo n.º 11
0
int Subgraph::CountNodes(const Node *n) const
{
  if (n->GetType() != TREE) {
    return 0;
  }
  if (IsTrivial()) {
    return 1;
  }
  int count = 1;
  const std::vector<Node*> &children = n->GetChildren();
  for (std::vector<Node *>::const_iterator p = children.begin();
       p != children.end(); ++p) {
    const Node *child = *p;
    if (m_leaves.find(child) == m_leaves.end()) {
      count += CountNodes(child);
    } else if (child->GetType() == TREE) {
      ++count;
    }
  }
  return count;
}
Ejemplo n.º 12
0
// This function parallels bulkLoad, but just counts how many nodes bulkLoad would allocate.
int SkRTree::CountNodes(int branches, SkScalar aspectRatio) {
    if (branches == 1) {
        return 1;
    }
    int numBranches = branches / kMaxChildren;
    int remainder   = branches % kMaxChildren;
    if (remainder > 0) {
        numBranches++;
        if (remainder >= kMinChildren) {
            remainder = 0;
        } else {
            remainder = kMinChildren - remainder;
        }
    }
    int numStrips = SkScalarCeilToInt(SkScalarSqrt(SkIntToScalar(numBranches) / aspectRatio));
    int numTiles  = SkScalarCeilToInt(SkIntToScalar(numBranches) / SkIntToScalar(numStrips));
    int currentBranch = 0;
    int nodes = 0;
    for (int i = 0; i < numStrips; ++i) {
        for (int j = 0; j < numTiles && currentBranch < branches; ++j) {
            int incrementBy = kMaxChildren;
            if (remainder != 0) {
                if (remainder <= kMaxChildren - kMinChildren) {
                    incrementBy -= remainder;
                    remainder = 0;
                } else {
                    incrementBy = kMinChildren;
                    remainder -= kMaxChildren - kMinChildren;
                }
            }
            nodes++;
            currentBranch++;
            for (int k = 1; k < incrementBy && currentBranch < branches; ++k) {
                currentBranch++;
            }
        }
    }
    return nodes + CountNodes(nodes, aspectRatio);
}
Ejemplo n.º 13
0
int VocabTree::WriteASCII(const char *filename) const
{
    if (m_root == NULL)
        return -1;

    FILE *f = fopen(filename, "w");
    
    if (f == NULL) {
        printf("[VocabTree::WriteASCII] Error opening file %s for writing\n",
               filename);
        return -1;
    }
    
    unsigned long num_nodes = CountNodes();
    unsigned long num_leaves = CountLeaves();

    fprintf(f, "%lu %lu %d\n", num_nodes, num_leaves, m_dim);
    m_root->WriteASCII(f, m_branch_factor, m_dim);

    fclose(f);

    return 0;
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
  char *data_filename, *deref_filename;
  double train_pct, prune_pct, test_pct;
  double train_accuracy, test_accuracy;
  DTNODE *tree;
  uchar *test_members, *train_members, *prune_members;
  int multiple_input_files;
  char *train_filename, *prune_filename, *test_filename;
  int num_test, num_train, num_prune, num_features, num_data;
  int depth, count, prev_count;
  int num_negatives, num_false_negatives;
  int num_positives, num_false_positives;
  void **data;
  struct timeval tv;
  unsigned int random_seed;
  SSVINFO ssvinfo;

  ssvinfo.batch = 0;

  progname = (char *) rindex(argv[0], '/');
  argv[0] = progname = (progname != NULL) ? (progname + 1) : argv[0];

  multiple_input_files = 0;
  if (argc>2){
    if (!strcmp(argv[1],"-tpt") && (argc==5)){
      train_filename = argv[2];
      prune_filename = argv[3];
      test_filename = argv[4];
      data = ReadTPT(train_filename, prune_filename, test_filename,
                     &train_members, &prune_members, &test_members,
                     &num_train, &num_prune, &num_test,
                     &num_data, &num_features, &ssvinfo);
      multiple_input_files = 1;
    } else if (!strcmp(argv[1],"-tp") && (argc==4)){
      train_filename = argv[2];
      prune_filename = argv[3];
      data = ReadTwo(train_filename, prune_filename,
		     &train_members, &prune_members,
                     &num_train, &num_prune,
                     &num_data, &num_features, &ssvinfo);
      num_test = 0;
      test_members = CREATE_BITARRAY(num_data);
      ZERO_BITARRAY(test_members,num_data);
      multiple_input_files = 1;
    } else if (!strcmp(argv[1],"-tt")&& (argc==4)){
      train_filename = argv[2];
      test_filename = argv[3];
      data = ReadTwo(train_filename, test_filename,
		     &train_members, &test_members,
                     &num_train, &num_test,
                     &num_data, &num_features, &ssvinfo);
      num_prune = 0;
      prune_members = CREATE_BITARRAY(num_data);
      ZERO_BITARRAY(prune_members,num_data);
      multiple_input_files = 1;
    }
  }

  if (!multiple_input_files){
    if (argc != 5 && argc != 7) {
      fprintf(stderr, USAGE, progname);
      exit(1);
    }
    switch (argc) {
    case 5:
      if (gettimeofday(&tv, NULL) == -1)
	SYS_ERROR1("gettimeofday(%s)", "");
      random_seed = (unsigned int) tv.tv_usec;
      train_pct = atof(argv[1]);
      prune_pct = atof(argv[2]);
      test_pct = atof(argv[3]);
      data_filename = argv[4];
      break;
    case 7:
      if ((argv[1][1] == 's') || (argv[1][1] == 'S')) {
	random_seed = atoi(argv[2]);
      } else if ((argv[1][1] == 'b') || (argv[1][1] == 'B')) {
	if (gettimeofday(&tv, NULL) == -1)
	  SYS_ERROR1("gettimeofday(%s)", "");
	random_seed = (unsigned int) tv.tv_usec;
	ssvinfo.batch = atoi(argv[2]);
      } else {
	fprintf(stderr, USAGE, progname);
	exit(1);
      }
      train_pct = atof(argv[3]);
      prune_pct = atof(argv[4]);
      test_pct = atof(argv[5]);
      data_filename = argv[6];
      break;
    default:
      fprintf(stderr, USAGE, progname);
      exit(1);
    }
    if ((random_seed < 0) ||
	(train_pct <= 0.0) || (train_pct > 1.0) ||
	(prune_pct < 0.0) || (prune_pct > 1.0) ||
	(test_pct < 0.0) || (test_pct > 1.0) ||
	(train_pct + prune_pct + test_pct > 1.00000001)) {
      fprintf(stderr, USAGE, progname);
      exit(1);
    }

    /* Memory-map the examples file. */
    data = ReadSSVFile(data_filename, &num_data, &num_features, &ssvinfo);
    
    /* Initialize random number generator. */
    srandom(random_seed);

    if (ssvinfo.batch>0) {
      BatchMain(data, num_data, num_features, train_pct, prune_pct, test_pct, &ssvinfo);
      exit(0);
    } 

    /* Partition examples in train, test and prune sets. */
    PartitionExamples(data, &num_data, num_features,
		      &train_members, &num_train,
		      &test_members, &num_test,
		      &prune_members, &num_prune,
		      train_pct, prune_pct, test_pct,
		      &ssvinfo);

    /* Print the program arguments */
    PrintSection("Program arguments");

    printf("Random seed:    %u\n", random_seed);
    printf("Training:       %.0f%% (%d examples)\n", train_pct * 100.0, num_train);
    printf("Pruning:        %.0f%% (%d examples)\n", prune_pct * 100.0, num_prune);
    printf("Testing:        %.0f%% (%d examples)\n", test_pct * 100.0, num_test);
    printf("Data filename:  %s\n", data_filename);
  }

  if (num_train == 0) {
    fprintf(stderr, "%s: no examples to train on!\n", progname);
    exit(1);
  }
  
  /* Create a decision tree and print it */
  PrintSection("Growing decision tree");

  tree = CreateDecisionTree(data, num_data, num_features, prune_pct, test_pct,
			    train_members, num_train, &ssvinfo);


  PrintSection("Printing decision tree");
  PrintDecisionTreeStructure(tree, &ssvinfo);

  PrintSection("Computing decision tree statistics");
  PrintStats(tree, data, num_data, train_members, num_train, test_members, num_test, &ssvinfo);

  /* Post-prune the decision tree. */
  if (num_prune > 0) {

    PrintSection("Pruning decision tree");

    prev_count = CountNodes(tree);

    PruneDecisionTree(tree, tree, data, num_data,
			     prune_members, num_prune, &ssvinfo);

    count = CountNodes(tree);
    
    /* If the node count decreased, something must have been pruned */

    if (count < prev_count) {
      
      printf("\nPruning reduced the tree size from %d to %d nodes\n",prev_count,count);

      PrintSection("Printing PRUNED decision tree");
      PrintDecisionTreeStructure(tree, &ssvinfo);

    } else {
      
      printf("\nPruning did not remove any nodes\n");
    
    }

    /* Print the statistics again, for comparison */

    PrintSection("Computing decision tree statistics after pruning");  
    PrintStats(tree, data, num_data, train_members, num_train, test_members, num_test, &ssvinfo);

  }

  free(train_members);
  free(test_members);
  free(prune_members);
  exit(0);
}
Ejemplo n.º 15
0
void BatchMain(void **data, int num_data, int num_features, 
	       double train_pct, double prune_pct, double test_pct, SSVINFO *ssvinfo)
{
  DTNODE *tree;
  uchar *test_members, *train_members, *prune_members;
  int num_test, num_train, num_prune;
  int num_negatives, num_false_negatives;
  int num_positives, num_false_positives;
  int i;
  double train_accuracy = 0, test_accuracy = 0;
  double count_mean, count_stddev;
  double train_mean, train_stddev;
  double test_mean, test_stddev;

  double *train_list, *test_list;
  int count;
  double *count_list;

  count_list = (double *) getmem(ssvinfo->batch * sizeof(double));
  train_list = (double *) getmem(ssvinfo->batch * sizeof(double));
  test_list = (double *) getmem(ssvinfo->batch * sizeof(double));

  for (i=0; i<ssvinfo->batch; i++) {

    /* Partition examples in train, test and prune sets. */
    PartitionExamples(data, &num_data, num_features,
		      &train_members, &num_train,
		      &test_members, &num_test,
		      &prune_members, &num_prune,
		      train_pct, prune_pct, test_pct,
		      ssvinfo);

    if (num_train == 0) {
      fprintf(stderr, "%s: no examples to train on!\n", progname);
      exit(1);
    }
    
    tree = CreateDecisionTree(data, num_data, num_features, prune_pct, test_pct,
			      train_members, num_train, ssvinfo);
    
    
    /* Post-prune the decision tree. */
    if (num_prune > 0) {
      PruneDecisionTree(tree, tree, data, num_data,
			       prune_members, num_prune, ssvinfo);
    }
    
    count = CountNodes(tree);
    count_list[i] = count;
    /* count_sum += count; */

    DecisionTreeAccuracyBinary(tree, data, num_data, train_members, num_train, train_members, 
			       num_train, &num_negatives, &num_false_negatives,
			       &num_positives, &num_false_positives, ssvinfo, 0);
    train_accuracy = (100.0 * (num_train - num_false_positives - num_false_negatives))/num_train;
    train_list[i] = train_accuracy;
    /* train_sum += train_accuracy; */

    if (num_test>0) {
      DecisionTreeAccuracyBinary(tree, data, num_data, train_members, num_train, test_members, 
				 num_test, &num_negatives, &num_false_negatives,
				 &num_positives, &num_false_positives, ssvinfo, 0);
      test_accuracy = (100.0 * (num_test - num_false_positives - num_false_negatives))/num_test;
    }
    test_list[i] = test_accuracy;
    /* test_sum += test_accuracy; */
    
    free(train_members);
    free(test_members);
    free(prune_members);
  }

  CalculateMeanStandardDeviation(count_list,ssvinfo->batch,&count_mean,&count_stddev);
  CalculateMeanStandardDeviation(train_list,ssvinfo->batch,&train_mean,&train_stddev);
  CalculateMeanStandardDeviation(test_list,ssvinfo->batch,&test_mean,&test_stddev);

  printf("----------------------------------------------\n");
  printf("#nodes\t#nodes\ttrain%%\ttrain%%\ttest%%\ttest%%\n");
  printf("mean\tstd\tmean\tstd\tmean\tstd\n");
  printf("----------------------------------------------\n");
  printf("%6.2lf\t%6.2lf\t%6.2lf\t%6.2lf\t%6.2lf\t%6.2lf\n",
	 count_mean, count_stddev, train_mean, train_stddev, test_mean, test_stddev);
  printf("----------------------------------------------\n");

  free(count_list);
  free(train_list);
  free(test_list);
  
}
Ejemplo n.º 16
0
// -----------------------------------------------------------------------------------
// Implementation of the assimp info utility to print basic file info
int Assimp_Info (const char* const* params, unsigned int num)
{
	if (num < 1) {
		printf("assimp info: Invalid number of arguments. "
			"See \'assimp info --help\'\n");
		return 1;
	}

	// --help
	if (!strcmp( params[0],"-h")||!strcmp( params[0],"--help")||!strcmp( params[0],"-?") ) {
		printf("%s",AICMD_MSG_INFO_HELP_E);
		return 0;
	}

	// asssimp info <file> [-r]
	if (num < 1) {
		printf("assimp info: Invalid number of arguments. "
			"See \'assimp info --help\'\n");
		return 1;
	}

	const std::string in  = std::string(params[0]);

	// do maximum post-processing unless -r was specified
	ImportData import;
	import.ppFlags = num>1&&(!strcmp(params[1],"--raw")||!strcmp(params[1],"-r")) ? 0
		: aiProcessPreset_TargetRealtime_MaxQuality;

	// import the main model
    import.log = true;
    import.showLog = true;
	const aiScene* scene = ImportModel(import,in);
	if (!scene) {
		printf("assimp info: Unable to load input file %s\n",
			in.c_str());
		return 5;
	}

	aiMemoryInfo mem;
	globalImporter->GetMemoryRequirements(mem);


	static const char* format_string = 
		"Memory consumption: %i B\n"
		"Nodes:              %i\n"
		"Maximum depth       %i\n"
		"Meshes:             %i\n"
		"Animations:         %i\n"
		"Textures (embed.):  %i\n"
		"Materials:          %i\n"
		"Cameras:            %i\n"
		"Lights:             %i\n"
		"Vertices:           %i\n"
		"Faces:              %i\n"
		"Bones:              %i\n"
		"Animation Channels: %i\n"
		"Primitive Types:    %s\n"
		"Average faces/mesh  %i\n"
		"Average verts/mesh  %i\n"
		"Minimum point      (%f %f %f)\n"
		"Maximum point      (%f %f %f)\n"
		"Center point       (%f %f %f)\n"

		;

	aiVector3D special_points[3];
	FindSpecialPoints(scene,special_points);
	printf(format_string,
		mem.total,
		CountNodes(scene->mRootNode),
		GetMaxDepth(scene->mRootNode),
		scene->mNumMeshes,
		scene->mNumAnimations,
		scene->mNumTextures,
		scene->mNumMaterials,
		scene->mNumCameras,
		scene->mNumLights,
		CountVertices(scene),
		CountFaces(scene),
		CountBones(scene),
		CountAnimChannels(scene),
		FindPTypes(scene).c_str(),
		GetAvgFacePerMesh(scene),
		GetAvgVertsPerMesh(scene),
		special_points[0][0],special_points[0][1],special_points[0][2],
		special_points[1][0],special_points[1][1],special_points[1][2],
		special_points[2][0],special_points[2][1],special_points[2][2]
		)
	;
	unsigned int total=0;
	for(unsigned int i = 0;i < scene->mNumMaterials; ++i) {
		aiString name;
		if (AI_SUCCESS==aiGetMaterialString(scene->mMaterials[i],AI_MATKEY_NAME,&name)) {
			printf("%s\n    \'%s\'",(total++?"":"\nNamed Materials:" ),name.data);
		}
	}
	if(total) {
		printf("\n");
	}

	total=0;
	for(unsigned int i = 0;i < scene->mNumMaterials; ++i) {
		aiString name;
		static const aiTextureType types[] = {
			aiTextureType_NONE,
			aiTextureType_DIFFUSE,
			aiTextureType_SPECULAR,
			aiTextureType_AMBIENT,
			aiTextureType_EMISSIVE,
			aiTextureType_HEIGHT,
			aiTextureType_NORMALS,
			aiTextureType_SHININESS,
			aiTextureType_OPACITY,
			aiTextureType_DISPLACEMENT,
			aiTextureType_LIGHTMAP,
			aiTextureType_REFLECTION,
			aiTextureType_UNKNOWN
		};
		for(unsigned int type = 0; type < sizeof(types)/sizeof(types[0]); ++type) {
			for(unsigned int idx = 0;AI_SUCCESS==aiGetMaterialString(scene->mMaterials[i],
				AI_MATKEY_TEXTURE(types[type],idx),&name); ++idx) {
				printf("%s\n    \'%s\'",(total++?"":"\nTexture Refs:" ),name.data);
			}
		}
	}
	if(total) {
		printf("\n");
	}

	total=0;
	for(unsigned int i = 0;i < scene->mNumAnimations; ++i) {
		if (scene->mAnimations[i]->mName.length) {
			printf("%s\n     \'%s\'",(total++?"":"\nNamed Animations:" ),scene->mAnimations[i]->mName.data);
		}
	}
	if(total) {
		printf("\n");
	}

	printf("\nNode hierarchy:\n");
	unsigned int cline=0;
	PrintHierarchy(scene->mRootNode,20,1000,cline);

	printf("\n");
	return 0;
}
Ejemplo n.º 17
0
struct DragObj * PRIVATE CreateDragObj(struct DragGadget *dg,int x,int y)
{
  struct Screen *scr;
  struct RastPort *rp;
  struct DragObj *gdo;
  ULONG line;
  int wordwidth;
  int width,height,depth;
  int i = 0,xpos,ypos;

  scr = dg->dg_Window->WScreen;
  rp = &scr->RastPort;

  if (dg->dg_Flags & DGF_IMAGES && ((struct ImageNode *)dg->dg_Object.od_Object)->in_Image)
    dg->dg_Image = ((struct ImageNode *)dg->dg_Object.od_Object)->in_Image;

  if (!dg->dg_Width || !dg->dg_Height)
  {
    if ((dg->dg_Type == LISTVIEW_KIND) && !dg->dg_Image)
    {
      dg->dg_Width = dg->dg_Gadget->Width-20;
      dg->dg_Height = dg->dg_ItemHeight;
    }
    else if (!dg->dg_RenderHook && dg->dg_Image)
    {
      dg->dg_Width = dg->dg_Image->Width;
      dg->dg_Height = dg->dg_Image->Height;
    }
    else  /* be sure width & height are not zero */
    {
      dg->dg_Width = dg->dg_Gadget->Width;
      dg->dg_Height = dg->dg_Gadget->Height;
    }
  }
  width = dg->dg_Width;
  height = dg->dg_Height;
  memset(&dm,0,sizeof(struct DropMessage));

  if (dg->dg_Type == LISTVIEW_KIND)
  {
    xpos = dg->dg_Gadget->LeftEdge+2;
    ypos = dg->dg_Gadget->TopEdge+2;
    dg->dg_Object.od_Object = NULL;

    if (y < ypos || y > ypos+dg->dg_Gadget->Height-5)
      return(NULL);
    line = (y-ypos)/dg->dg_ItemHeight;
    ypos += line*dg->dg_ItemHeight;

    GT_GetGadgetAttrs(dg->dg_Gadget,dg->dg_Window,NULL,GTLV_Labels,&dg->dg_List,TAG_END);
    if (dg->dg_List && !IsListEmpty(dg->dg_List))
    {
      GT_GetGadgetAttrs(dg->dg_Gadget,dg->dg_Window,NULL,GTLV_Top,&i,TAG_END);
      i += line;
      if (i < CountNodes(dg->dg_List))
      {
        struct Node *ln;

        dm.dm_SourceEntry = i;
        for(ln = dg->dg_List->lh_Head;i;i--,ln = ln->ln_Succ);

        if (dg->dg_Flags & DGF_TREEVIEW && TREENODE(ln)->tn_Flags & TNF_STATIC)
        {
          mx = ~0L;      // avoid a following drag
          return(NULL);
        }
        dg->dg_Object.od_Object = ln;

        if (dg->dg_ObjectFunc)
          dg->dg_ObjectFunc(dg->dg_Window,dg->dg_Gadget,&dg->dg_Object,dm.dm_SourceEntry);
      }
    }
  }
  else
  {
    if (dg->dg_ObjectFunc)
      dg->dg_ObjectFunc(dg->dg_Window,dg->dg_Gadget,&dg->dg_Object,0L);

    dm.dm_SourceEntry = dg->dg_SourceEntry;
    xpos = x-width/2;
    ypos = y-height/2;
  }
  if (!dg->dg_Object.od_Object)
  {
    mx = ~0L;        // avoid a following drag
    return(NULL);
  }
  wordwidth = (width + 15) >> 4;
  depth = GetBitMapAttr(rp->BitMap,BMA_DEPTH);

  if (dg->dg_Object.od_Object && (gdo = AllocMem(sizeof(struct DragObj), MEMF_CLEAR | MEMF_PUBLIC)))
  {
#ifdef LOCKLAYERS
    LockLayers(&scr->LayerInfo);
    UnlockLayer(dg->dg_Window->RPort->Layer);
#endif

    gdo->do_Screen = scr;
    gdo->do_ScrRPort = rp;

    gdo->do_BitMap = AllocBitMap(width,height,depth,BMF_CLEAR | BMF_MINPLANES,!(GetBitMapAttr( rp->BitMap, BMA_FLAGS ) & BMF_INTERLEAVED) ? rp->BitMap : NULL);
    gdo->do_SaveBack = AllocBitMap(width,height,depth,BMF_CLEAR | BMF_MINPLANES,rp->BitMap);
    gdo->do_RefreshMap = AllocBitMap(width*2,height*2,depth,BMF_CLEAR | BMF_MINPLANES,rp->BitMap);

    if (GetBitMapAttr(gdo->do_BitMap,BMA_FLAGS) & BMF_STANDARD)
      i = MEMF_CHIP | MEMF_PUBLIC;
    else
      i = 0;

    gdo->do_FullShadow = AllocMem(2*wordwidth*height,i | MEMF_CLEAR);
    gdo->do_HalfShadow = AllocMem(2*wordwidth*height,i);

    if (gdo->do_BitMap && gdo->do_SaveBack && gdo->do_RefreshMap && gdo->do_FullShadow && gdo->do_HalfShadow)
    {
      InitRastPort(&gdo->do_RPort);
      gdo->do_RPort.BitMap = gdo->do_BitMap;
      InitRastPort(&gdo->do_RefreshRPort);
      gdo->do_RefreshRPort.BitMap = gdo->do_RefreshMap;

      gdo->do_DragGadget = dg;
      CopyMem(&dg->dg_Object,&dm.dm_Object,sizeof(struct ObjectDescription));
      dm.dm_Window = dg->dg_Window;
      dm.dm_Gadget = dg->dg_Gadget;

      /*** create the drag&drop image ***/

      if (dg->dg_RenderHook)
      {
        struct LVDrawMsg lvdm;

        SetFont(&gdo->do_RPort,scr->RastPort.Font);
        lvdm.lvdm_MethodID = LV_DRAW;
        lvdm.lvdm_RastPort = &gdo->do_RPort;
        lvdm.lvdm_DrawInfo = GetScreenDrawInfo(scr);
        lvdm.lvdm_Bounds.MinX = 0;
        lvdm.lvdm_Bounds.MinY = 0;
        lvdm.lvdm_Bounds.MaxX = width-1;
        lvdm.lvdm_Bounds.MaxY = height-1;
        lvdm.lvdm_State = LVR_SELECTED;
        CallHookPkt(dg->dg_RenderHook,dm.dm_Object.od_Object,&lvdm);
        FreeScreenDrawInfo(scr,lvdm.lvdm_DrawInfo);
      }
      else if (dg->dg_Image)
        DrawImage(&gdo->do_RPort,dg->dg_Image,0,0);
      else
        ClipBlit(dg->dg_Window->RPort,xpos,ypos,&gdo->do_RPort,0,0,width,height,0xc0);

      /*** initialize drag object structure ***/

      gdo->do_X = -9999;
      gdo->do_Y = ypos+dg->dg_Window->TopEdge;
      gdo->do_PX = -9999;
      gdo->do_Width = width;
      gdo->do_Height = height;
      gdo->do_DeltaX = xpos-x+dg->dg_Window->LeftEdge;
      gdo->do_DeltaY = ypos-y+dg->dg_Window->TopEdge;
      gdo->do_Mask = gdo->do_FullShadow;

      /*** create masks (transparent and full imagery) ***/

      if (CyberGfxBase && (GetBitMapAttr(gdo->do_BitMap,BMA_FLAGS) & BMF_STANDARD) == 0L)
      {
        struct BitMap tbm;
        ULONG  col;

        InitBitMap(&tbm,1,width,height);
        tbm.Planes[0] = (UBYTE *)gdo->do_FullShadow;

        /* if (!GetCyberMapAttr(gdo->do_BitMap, CYBRMATTR_PIXELFMT)) */

        if (GetBitMapAttr(gdo->do_BitMap, BMA_DEPTH) > 8L)
        {
          ULONG triplet[3];

          GetRGB32(scr->ViewPort.ColorMap,0L,1L,triplet);
          col = (triplet[0] & 0xff0000) | (triplet[1] & 0xff00) | (triplet[2] & 0xff);
        }
        else
          col = 0;

        // ExtractColor(rp,&tbm,col,xpos,ypos,width,height);
        ExtractColor(&gdo->do_RPort,&tbm,col,0,0,width,height);

        BltBitMap(&tbm,0,0,&tbm,0,0,width,height,0x50,0xff,NULL);  // invertieren der Maske
      }
      else
      {
        UWORD *p = gdo->do_FullShadow;

        for(ypos = 0;ypos < height;ypos++)
        {
          for(xpos = 0;xpos < wordwidth;xpos++,p++)
          {
            for(i = 0;i < depth;i++)
              *p |= *((UWORD *)gdo->do_BitMap->Planes[i]+ypos*(gdo->do_BitMap->BytesPerRow >> 1)+xpos);
          }
        }
      }

      {
        UWORD *p = gdo->do_HalfShadow;

        CopyMem(gdo->do_FullShadow,p,2*wordwidth*height);
        for(line = 0x5555,ypos = 0;ypos < height;ypos++)
        {
          line = ~line;
          for(xpos = 0;xpos < wordwidth;xpos++,p++)
            *p &= (UWORD)line;
        }
      }

      if (!boopsigad)
        FakeInputEvent();
      UpdateDragObj(gdo,gdo->do_X,gdo->do_Y);    /* show drag object */

      return(gdo);
    }
Ejemplo n.º 18
0
// -----------------------------------------------------------------------------------
// Implementation of the assimp info utility to print basic file info
int Assimp_Info(const aiScene* scene, Assimp::Importer *globalImporter)
{


    aiMemoryInfo mem;
    globalImporter->GetMemoryRequirements(mem);


    static const char* format_string =
        "Memory consumption: %i B\n"
        "Nodes:              %i\n"
        "Maximum depth       %i\n"
        "Meshes:             %i\n"
        "Animations:         %i\n"
        "Textures (embed.):  %i\n"
        "Materials:          %i\n"
        "Cameras:            %i\n"
        "Lights:             %i\n"
        "Vertices:           %i\n"
        "Faces:              %i\n"
        "Bones:              %i\n"
        "Animation Channels: %i\n"
        "Primitive Types:    %s\n"
        "Average faces/mesh  %i\n"
        "Average verts/mesh  %i\n"
        "Minimum point      (%f %f %f)\n"
        "Maximum point      (%f %f %f)\n"
        "Center point       (%f %f %f)\n"

        ;

    aiVector3D special_points[3];
    FindSpecialPoints(scene, special_points);
    fprintf(stderr, format_string,
            mem.total,
            CountNodes(scene->mRootNode),
            GetMaxDepth(scene->mRootNode),
            scene->mNumMeshes,
            scene->mNumAnimations,
            scene->mNumTextures,
            scene->mNumMaterials,
            scene->mNumCameras,
            scene->mNumLights,
            CountVertices(scene),
            CountFaces(scene),
            CountBones(scene),
            CountAnimChannels(scene),
            FindPTypes(scene).c_str(),
            GetAvgFacePerMesh(scene),
            GetAvgVertsPerMesh(scene),
            special_points[0][0], special_points[0][1], special_points[0][2],
            special_points[1][0], special_points[1][1], special_points[1][2],
            special_points[2][0], special_points[2][1], special_points[2][2]
           )
    ;
#define FULLLOG
#ifdef FULLLOG
    unsigned int total = 0;
    for (unsigned int i = 0; i < scene->mNumMaterials; ++i) {
        aiString name;
        if (AI_SUCCESS == aiGetMaterialString(scene->mMaterials[i], AI_MATKEY_NAME, &name)) {
            fprintf(stderr, "%s\n    \'%s\'", (total++ ? "" : "\nNamed Materials:"), name.data);
        }
    }
    if (total) {
        fprintf(stderr, "\n");
    }

    total = 0;
    for (unsigned int i = 0; i < scene->mNumMaterials; ++i) {
        aiString name;
        static const aiTextureType types[] = {
            aiTextureType_NONE,
            aiTextureType_DIFFUSE,
            aiTextureType_SPECULAR,
            aiTextureType_AMBIENT,
            aiTextureType_EMISSIVE,
            aiTextureType_HEIGHT,
            aiTextureType_NORMALS,
            aiTextureType_SHININESS,
            aiTextureType_OPACITY,
            aiTextureType_DISPLACEMENT,
            aiTextureType_LIGHTMAP,
            aiTextureType_REFLECTION,
            aiTextureType_UNKNOWN
        };
        for (unsigned int type = 0; type < sizeof(types) / sizeof(types[0]); ++type) {
            for (unsigned int idx = 0; AI_SUCCESS == aiGetMaterialString(scene->mMaterials[i],
                    AI_MATKEY_TEXTURE(types[type], idx), &name); ++idx) {
                fprintf(stderr, "%s\n    \'%s\'", (total++ ? "" : "\nTexture Refs:"), name.data);
            }
        }
    }
    if (total) {
        fprintf(stderr, "\n");
    }

    total = 0;
    for (unsigned int i = 0; i < scene->mNumAnimations; ++i) {
        if (scene->mAnimations[i]->mName.length) {
            fprintf(stderr, "%s\n     \'%s\'", (total++ ? "" : "\nNamed Animations:"), scene->mAnimations[i]->mName.data);
        }
    }
    if (total) {
        fprintf(stderr, "\n");
    }

 /*
   fprintf(stderr, "\nNode hierarchy:\n");
    unsigned int cline = 0;
    PrintHierarchy(scene->mRootNode, 20, 1000, cline);
    */
#endif
    fprintf(stderr, "\n");
    return 0;
}
Ejemplo n.º 19
0
Archivo: main.c Proyecto: Jasu/HashTWM
// This does the actual tiling
void ArrangeWindows()
{
  int a, i, x, y, width, height;
  unsigned short masterarea_count;
  node *nodes;
  node *temp;

  a = CountNodes();
  if (a == -1) return;
  i = 0;

  nodes = tags[current_tag].nodes;
  masterarea_count = tags[current_tag].masterarea_count;

  for (temp = nodes; temp; temp = temp->next) {
    RestoreWindow(temp->hwnd);

    if (a == 0) { // I think this is universal to all tiling modes
      x = 0;
      y = 0;
      width = screen_width;
      height = screen_height;
    } else {
      switch (tags[current_tag].tilingMode)
      {
        default:
        case MODE_VERTICAL:
          {
            if (i < masterarea_count) {
              x = 0;
              y = (screen_height / masterarea_count) * i;
              width = (screen_width / 2) + margin;
              height = (screen_height / masterarea_count);
            } else {
              x = (screen_width / 2) + margin;
              y = (screen_height / ((a + 1) - masterarea_count)) * (a - i);
              width = (screen_width / 2) - margin;
              height = (screen_height / ((a + 1) - masterarea_count));
            }
          }
          break;
        case MODE_HORIZONTAL:
          {
            if (i < masterarea_count) {
              // Main window
              x = (screen_width / masterarea_count) * i;
              y = 0;
              width = (screen_width / masterarea_count);
              height = (screen_height / 2) + margin;
            } else {
              // Normal windows to be tiled
              x = (screen_width / ((a + 1) - masterarea_count)) * (a - i);
              y = (screen_height / 2) + margin;
              width = (screen_width / ((a + 1) - masterarea_count));
              height = (screen_height / 2) - margin;
            }
          }
          break;
        case MODE_GRID: // See dvtm-license.txt
          {
            int ah, aw, rows, cols;
            for (cols = 0; cols <= (a + 1)/2; cols++) {
              if (cols * cols >= (a + 1)) {
                break;
              }
            }
            rows = (cols && (cols - 1) * cols >= (a + 1)) ? cols - 1 : cols;
            height = screen_height / (rows ? rows : 1);
            width = screen_width / (cols ? cols : 1);
            if (rows > 1 && i == (rows * cols) - cols && ((a + 1) - i) <= ((a + 1) % cols)) {
              width = screen_width / ((a + 1) - i);
            }
            x = (i % cols) * width;
            y = (i / cols) * height;
            ah = (i >= cols * (rows - 1)) ? screen_height - height * rows: 0;
            if (rows > 1 && i == (a + 1) - 1 && ((a + 1) - i) < ((a + 1) % cols)) {
              aw = screen_width - width * ((a + 1) % cols);
            } else {
              aw = ((i + 1) % cols == 0) ? screen_width - width * cols : 0;
            }
            width += aw;
            height += ah;
          }
          break;
        case MODE_FULLSCREEN:
          x = 0;
          y = 0;
          width = screen_width;
          height = screen_height;
          break;
      }
    }

    SetWindowPos(temp->hwnd, HWND_TOP, x + screen_x, y + screen_y, width, height, SWP_SHOWWINDOW);
    i++;
  }

  FocusCurrent();
}
Ejemplo n.º 20
0
int  Compiler::GetNodeCount(One<Exe>& exe)
{
	count_node = 0;
	CountNodes(exe);
	return count_node;
}
Ejemplo n.º 21
0
main(int argc, char **argv)
{
  FILE *outF, *inF;
  int rgm;
  int seed = 1111;
  int to_file = 0;
  int from_file = 0;
  struct binet *binet = NULL;
  struct group *part = NULL;
  struct group *roles_part = NULL;
  struct node_gra *projected = NULL;
  gsl_rng *randGen;
  double degree_based = 0;
  double Ti, Tf;
  double Ts = 0.97;
  double fac = 1.0;
  double modularity = 0;
  char fn_array[256];
  char fno_array[256];
  char *file_name;
  char *file_name_out;
  int invert = 0;
  int weighted = 0;
  int output_type = 0;
  extern char *optarg;
  extern int optind;
  int c; 
  
  /*
    ------------------------------------------------------------
    Arguments parsing
    ------------------------------------------------------------
  */
  
  if (argc == 1) {
	from_file = 1;
	to_file = 1;	
	file_name = fn_array;
	file_name_out = fno_array;
	
	printf("\n# Enter random number seed (POSITIVE integer): ");
	scanf("%d", &seed);
	printf("\n# Enter the name of the network file: ");
	scanf("%s", &fn_array);

	printf("\n# Enter the name of the output file: ");
	scanf("%s", &fno_array);

	printf("\n# Enter iteration factor (recommended 1.0): ");
	scanf("%lf", &fac);
  
	printf("\n# Enter the cooling factor (recommended 0.950-0.995): ");
	scanf("%lf", &Ts);

	printf("\n# Find modules from first column (0) or second column (1): ");
	scanf("%d", &invert);

	printf("\n# Use the weighted (0) or weighted (1) modularity. (Edge weight is extracted from the third column): ");
	scanf("%d", &weighted);

	printf("\n# Use the strength (0) or degree (1) based role metrics: ");
	scanf("%d", &degree_based);


	printf("\n# Choose between tabular output (0), module partition (1) or roles partition (2):");
	scanf("%d", &output_type);}
  
  
  else{
	while ((c = getopt(argc, argv, "hwprmdf:s:i:c:o:")) != -1)
	  switch (c) {
	  case 'h':
		printf("\nUsage: bipartmod_cl [-f file] [-o file] [-s seed] [-i iter] [-c cool] [-pwmrh]\n"
			   "\nIf no arguments are provided, the program will fallback in interactive mode.\n\n"
			   "\t -f file: Name of the input network file (default: standard input)\n"
			   "\t -o file: Name of the output file (default: standard output)\n"
			   "\t -s seed: Random number seed (POSITIVE Integer, default 1111) \n"
			   "\t -i iter: Iteration factor (recommended 1.0, default 1.0)\n"
			   "\t -c cool: Cooling factor (recommended 0.950-0.995, default 0.97)\n "
			   "\t -p : Find modules for the second column (default: first) \n"
			   "\t -w : Read edge weights from the input's third column and uses the weighted modularity.\n"
			   "\t -d : Use degree based role metrics (default: strength based metrics)"
			   "\t -r : Output the roles partition rather than the default tabular output.\n"
			   "\t -m : Output the modules partition rather than the default tabular output. \n"
			   "\t -h : Display this message\n");
		return -1;
		break;
	  case 'f':
		from_file = 1;
		file_name = optarg;
		//printf("input set to %s \n", file_name);
		break;
	  case 's':
		seed = atoi(optarg);
		//printf("seed set to %d \n", seed);
		break;
	  case 'i':
		fac = atof(optarg);
		//printf("iteration factor set to %f \n", fac);
		break;
	  case 'c':
		Ts = atof(optarg);
		//printf("cooling factor set to %f. \n", Ts);
		break;
	  case 'p':
		invert = 1;
		//printf("Looking at second column.\n");
		break;
	  case 'm':
		output_type = 1;
		break;
	  case 'r':
		output_type = 2;
		break;
	  case 'o':
		to_file = 1;
		file_name_out = optarg;
		break;
	  case 'w':
		weighted = 1;
		break;
	  case 'd':
		degree_based = 1;
		break;

	  }
  }

  /*
    ------------------------------------------------------------------
    Initialize the random number generator
    ------------------------------------------------------------------
  */
  randGen = gsl_rng_alloc(gsl_rng_mt19937);
  gsl_rng_set(randGen, seed);

  /*
    ------------------------------------------------------------------
    Build the network
    ------------------------------------------------------------------
  */
  if (from_file == 1) {
	inF = fopen(file_name, "r");
	if (inF == NULL)
	  {
		printf("ERROR: No such file or directory (%s). \n", file_name);
		return(1);
	  }
	binet = FBuildNetworkBipart(inF, weighted, 0);
	fclose(inF);
  }
  else
	binet = FBuildNetworkBipart(stdin, weighted, 0);
  
  if (invert == 1)
    InvertBipart(binet);

  /*
    ------------------------------------------------------------------
    Find the modules using the bipartite network
    ------------------------------------------------------------------
  */
  Ti = 1. / (double)CountNodes(binet->net1);
  Tf = 0.;

  if (weighted == 1){
	part = SACommunityIdentBipartWeighted(binet,
										  Ti, Tf, Ts, fac,
										  0, 'o', 1, 'm',
										  randGen);
  }
  else{
	part = SACommunityIdentBipart(binet,
								  Ti, Tf, Ts, fac,
								  0, 'o', 1, 'm',
								  randGen);
  }

  // Compute the role partition if we have to.
  // Note that the roles are computed (but not as a partition)
  // if the tabular output is selected (output_type==0).
  if (output_type == 2){
	projected = ProjectBipart(binet);
	if (degree_based==1)
	  part = CatalogRoleIdent(projected,part);
	else
	  part = CatalogRoleIdentStrength(projected,part);
  }

  /*
    ------------------------------------------------------------
    Output
    ------------------------------------------------------------
  */

  if (to_file == 1)	{
	outF = fopen(file_name_out, "w");
	if (outF == NULL)
	  {
		printf("ERROR: Cannot write output (%s). \n", file_name_out);
		return(1);
	  }
	if (output_type != 0){
	  // Partition-type output (a la Netcarto).
	  FPrintPartition(outF, part, 0);
	  modularity = Modularity(part);
	  fprintf(outF, "# Modularity = %g\n", modularity);
	}
	else
	  // Tabular output. 
	  FPrintTabNodesBipart(outF, binet, part, degree_based);


	fclose(outF);
  }
  else{
	if (output_type != 0){
	  FPrintPartition(stdout, part, 0);
	  modularity = Modularity(part);
	  fprintf(stdout, "# Modularity = %g\n", modularity);
	}
	else
	  FPrintTabNodesBipart(stdout, binet, part, degree_based);
  }
  
  // Free memory
  RemovePartition(part);
  RemoveBipart(binet);
  if (output_type == 2)
	RemoveGraph(projected);
  gsl_rng_free(randGen);
}
Ejemplo n.º 22
0
int
main(int argc, char **argv)
{
  long seed = 1111;
  FILE *inFile,*outFile;
  struct node_gra *net = NULL;
  struct node_gra *netran = NULL;
  struct node_gra *p = NULL;
  int S;
  int c;
  struct group *part = NULL;
  struct group *roles = NULL;
  int i,t1;
  int rep = 0;
  double realmod;
  double ranmodav, ranmodst;
  double *ranmodlis;
  double Tsched = 0.995, Tf = 0.0;
  double iterfac = 1.0;
  gsl_rng *rand_gen;
  char *netF;
  /*
    ------------------------------------------------------------
    Prompt for user-defined parameters
    ------------------------------------------------------------
  */
  printf ("%d\n",argc);
  if (argc == 1) {

  printf("\n# Enter random number seed (POSITIVE integer): ");
  scanf("%d", &seed);

  printf("\n# Enter the name of the network file: ");
  scanf("%s", &netF);

  printf("\n# Enter iteration factor (recommended 1.0): ");
  scanf("%lf", &iterfac);

  printf("\n# Enter the cooling factor (recommended 0.950-0.995): ");
  scanf("%lf", &Tsched);

  printf("\n# Enter the number of randomizations: ");
  scanf("%d", &rep);
  } else {
while ((c = getopt(argc, argv, "hf:s:i:c:r:")) != -1)
	  switch (c) {
	  case 'h':
		printf(USAGE ARGUMENTS);
		return -1;
		break;
	  case 'f':
		netF = optarg;
		break;
	  case 's':
		seed = atoi(optarg);
		break;
	  case 'r':
		rep = atoi(optarg);
		break;
	  case 'i':
		iterfac = atof(optarg);
		break;
	  case 'c':
		Tsched = atof(optarg);
		break;
	  }
  }
  ranmodlis = allocate_d_vec(rep);

  /*
    ------------------------------------------------------------
    Initialize the random number generator
    ------------------------------------------------------------
  */
  rand_gen = gsl_rng_alloc(gsl_rng_mt19937);
  gsl_rng_set(rand_gen, seed);

  /*
    ------------------------------------------------------------
    Build the network
    ------------------------------------------------------------
  */
  fprintf(stderr, "\n# Creating the network\n");

  inFile=fopen(netF,"r");
  net = FBuildNetwork(inFile, 0, 0, 0, 1);
  fclose(inFile);

  S = CountNodes(net);
  fprintf(stderr, "\n# The network has %d nodes\n", S);

  /*
    ------------------------------------------------------------
    Find and print the modules
    ------------------------------------------------------------
  */
  fprintf(stderr, "\n# Starting the simulated annealing\n");
  fprintf(stderr, "\n# 1/T\tM\tT\n");

  part = SACommunityIdent(net,
			  2.0 / (double)S, Tf, Tsched,
			  iterfac, 0, 'o', 1, 's', rand_gen);

  outFile = fopen("modules.dat", "w");
  FPrintPartition(outFile, part, 0);
  realmod = Modularity(part);
  fprintf(outFile, "# Modularity = %g\n", realmod);
  fclose(outFile);

  FPrintPajekFile("network.net", net, 0, 0, 1);
  FPrintPajekPartitionFile("modules.clu", net);

  /*
    ------------------------------------------------------------
    Calculate and print node properties
    ------------------------------------------------------------
  */
  outFile=fopen("node_prop.dat","w");
  p = net;
  while ((p = p->next) != NULL) {
    fprintf(outFile,"%s %d %lf %lf\n",
	    p->label, NodeDegree(p),
	    ParticipationCoefficient(p),
	    WithinModuleRelativeDegree(p, part));
  }
  fclose(outFile);

  /*
    ------------------------------------------------------------
    Find and print the roles
    ------------------------------------------------------------
  */
  fprintf(stderr, "\n# Finding node roles\n");
  roles = CatalogRoleIdent(net, part);

  outFile = fopen("roles.dat","w");
  FPrintPartition(outFile, roles, 0);
  fclose(outFile);

  MapPartToNet(roles, net);
  FPrintPajekPartitionFile("roles.clu", net);

  /*
    ------------------------------------------------------------
    Calculate properties for the randomized graph
    ------------------------------------------------------------
  */
  ranmodav = 0.0;
  for (i=0; i<rep; i++) {
    fprintf(stderr, "\nRandomization %d\n", i+1);

    RemovePartition(part);
    if ( netran != NULL)
      RemoveGraph(netran);

    netran = RandomizeSymmetricNetwork(CopyNetwork(net), 100, rand_gen);
    part = SACommunityIdent(netran,
			    2.0 / (double)S, Tf, Tsched,
			    iterfac, 0, 'o', 1, 'n', rand_gen);
    ranmodlis[i] = Modularity(part);
    ranmodav += ranmodlis[i];
  }

  /* Average and standard deviation */
  ranmodav /= (double)rep;
  ranmodst = 0.0;
  for (i=0; i<rep; i++) {
    ranmodst += (ranmodlis[i] - ranmodav) * (ranmodlis[i] - ranmodav);
  }
  ranmodst = sqrt(ranmodst / (double)rep);

  outFile = fopen("randomized_mod.dat", "w");
  fprintf(outFile, "# M\tMrand\tsimga_Mrand\n");
  fprintf(outFile, "%lf %lf %lf\n", realmod, ranmodav, ranmodst);
  fclose(outFile);

  /*
    ------------------------------------------------------------
    Free memory
    ------------------------------------------------------------
  */
  gsl_rng_free(rand_gen);
  free_d_vec(ranmodlis);
  RemovePartition(part);
  RemovePartition(roles);
  RemoveGraph(net);
  if (netran != NULL)
    RemoveGraph(netran);
  return 0;
}
Ejemplo n.º 23
0
int main()
{
  FILE *infile=NULL;
  struct node_gra *net = NULL;
  int repeat = 1;
  gsl_rng *randGen;

  /*
    ------------------------------------------------------------
    Build the network
    ------------------------------------------------------------
  */
  infile = fopen("test_graph1.dat", "r");
  net = FBuildNetwork(infile, 0, 0, 0, 1);
  fclose(infile);
  FPrintPajekFile("graph1.net", net, 0, 0, 1);

  /*
    --------------------------------------------------------------
    Initialize the random number generator
    --------------------------------------------------------------
  */
  randGen = gsl_rng_alloc(gsl_rng_mt19937);
  gsl_rng_set(randGen, 3333);

  /*
    ------------------------------------------------------------
    Network properties
    ------------------------------------------------------------
  */
  double dtemp;
  int itemp;
  printf("S = %d\n", CountNodes(net));

  dtemp = ClusteringCoefficient(net);
  if (fabs(dtemp - 0.1875) > EPS)
    return 1;
  else
    printf("C = %g\tOK\n", dtemp);

  printf("A = %g\n", Assortativity(net));

  dtemp = AverageInverseDistance(net);
  if (fabs(dtemp - 19. / 45.) > EPS) {
    printf("P = %g\tWRONG!!\n", dtemp);
    return 1;
  }
  else
    printf("P = %g\tOK\n", dtemp);

  struct node_gra *n1 = net->next;
  struct node_gra *n2 = n1->next;
  struct node_gra *n4 = n2->next->next;
  struct node_gra *n5 = n4->next;
  struct node_gra *n8 = n5->next->next->next;
  dtemp = JaccardIndex(n1, n2);
  if (fabs(dtemp - 0.25) > EPS)
    return 1;
  else
    printf("J[1][2] = %g\tOK\n", dtemp);
  dtemp = JaccardIndex(n2, n4);
  if (fabs(dtemp - 0.50) > EPS)
    return 1;
  else
    printf("J[2][4] = %g\tOK\n", dtemp);
  dtemp = JaccardIndex(n5, n8);
  if (fabs(dtemp - 0.50) > EPS)
    return 1;
  else
    printf("J[5][8] = %g\tOK\n", dtemp);
  
  if ((itemp = CommonNeighbors(n1, n2)) != 1)
    return 1;
  else
    printf("C[1][2] = %d\tOK\n", itemp);
  if ((itemp = CommonNeighbors(n2, n4)) != 1)
    return 1;
  else
    printf("C[2][4] = %d\tOK\n", itemp);
  if ((itemp = CommonNeighbors(n5, n8)) != 2)
    return 1;
  else
    printf("C[5][8] = %d\tOK\n", itemp);
      
  /*
    ------------------------------------------------------------
    Partition
    ------------------------------------------------------------
  */
  struct group *part = NULL;
  part = SACommunityIdent(net, 2. / CountNodes(net), 0.0, 0.995,
			  2.0, 2, 'o', 1, 'n', randGen);
  MapPartToNet(part, net);
  printf("M = %g\n", Modularity(part));
  RemovePartition(part);

  /*
    ------------------------------------------------------------
    Free memory
    ------------------------------------------------------------
  */
  RemoveGraph(net);
  gsl_rng_free(randGen);

  return 0;
}
Ejemplo n.º 24
0
int main()
{
  // ----------------------------------------------------------------
  // Initialize the random number generator
  // ----------------------------------------------------------------
  gsl_rng *rand_gen;
  rand_gen = gsl_rng_alloc(gsl_rng_mt19937);
  gsl_rng_set(rand_gen, seed);

  // ----------------------------------------------------------------
  // Build the network---only use giant component
  // ----------------------------------------------------------------
  struct node_gra *total_net = NULL;
  struct node_gra *net = NULL;
  FILE *infile;

  infile = fopen("test.dat", "r");
  total_net = FBuildNetwork(infile, 0, 0, 0, 1);
  fclose(infile);
  net = GetLargestStronglyConnectedSet(total_net, 100000);

  // ----------------------------------------------------------------
  // Initialize the coclassification matrix
  // ----------------------------------------------------------------
  int i, j;
  int **coclas;
  int S = CountNodes(net);
  coclas = allocate_i_mat(S, S);
  for (i=0; i<S; i++)
    for (j=0; j<S; j++)
      coclas[i][j] = 0;

  // ----------------------------------------------------------------
  // Find the modules rep times and calculate coclassification matrix
  // ----------------------------------------------------------------
  struct group *part = NULL;
  struct node_gra *p1 = NULL;
  struct node_gra *p2 = NULL;
  for (i=0; i<rep; i++) {
    fprintf(stderr, "Repetition %d\n", i+1);
    part = SACommunityIdent(net,
			    0.0, -1.0, 0.0,
			    0.10,
			    S,         // #modules
			    'r',       // r=random initial conf
			    1,         // 0=No collective moves
			    'n',       // n=no output
			    rand_gen);
   
    // Update coclas matrix
    // --------------------------------------------------------------
    p1 = net;
    while ((p1 = p1->next) != NULL) {
      p2 = net;
      while ((p2 = p2->next) != NULL) {
	if (p1->inGroup == p2->inGroup)
	  coclas[p1->num][p2->num] += 1;
      }
    }

    // Remove the partition
    // --------------------------------------------------------------
    RemovePartition(part);
    part = NULL;
  }

  // ----------------------------------------------------------------
  // Output results
  // ----------------------------------------------------------------
  p1 = net;
  while ((p1 = p1->next) != NULL) {
    p2 = net;
    while ((p2 = p2->next) != NULL) {
      fprintf(stdout, "%s %s -1 -1 -1 -1 %lf\n",
	      p1->label, p2->label,
	      (double)coclas[p1->num][p2->num] / (double)rep);
    }
  }

  // ----------------------------------------------------------------
  // Free memory
  // ----------------------------------------------------------------
  RemoveGraph(total_net);
  RemoveGraph(net);
  free_i_mat(coclas,S);
  gsl_rng_free(rand_gen);

  return 0;
}
Ejemplo n.º 25
0
int
main(int argc, char **argv)
{
  long seed;
  char *netF;
  int method;
  FILE *inFile;
  struct node_gra *net = NULL;
  gsl_rng *rand_gen;
  int S, L;
  int nsteps;
  double step, damp;

  /*
    ---------------------------------------------------------------------------
    Command line parameters
    ---------------------------------------------------------------------------
  */
  if (argc < 7) {
    printf("\nUse: netlayout.out net_file_name seed step(-1) nsteps damping(-1) 1(2d)/2(2dp)/3(3d)\n\n");
    return -1;
  }

  netF = argv[1];
  seed = atoi(argv[2]);
  step = atof(argv[3]);
  if (step < 0.0 )
    step = 0.05; // Default step
  nsteps = atoi(argv[4]);
  damp = atof(argv[5]);
  if (damp < 0.0 )
    damp = 0.05; // Default damping
  method = atoi(argv[6]);

  /*
    ---------------------------------------------------------------------------
    Initialize the random number generator
    ---------------------------------------------------------------------------
  */
  rand_gen = gsl_rng_alloc(gsl_rng_mt19937);
  gsl_rng_set(rand_gen, seed);

  /*
    ---------------------------------------------------------------------------
    Build the network
    ---------------------------------------------------------------------------
  */
  inFile=fopen(netF, "r");
  net = FBuildNetwork(inFile, 0, 0, 0, 1);
  fclose(inFile);
  S = CountNodes(net);
  L = TotalNLinks(net, 1);

  /*
    ---------------------------------------------------------------------------
    Layout the graph
    ---------------------------------------------------------------------------
  */
  if (method == 3) {
    MDGraphLayout3D(net, damp, step, nsteps, rand_gen, 0);
  }
  else if (method == 2) {
    MDGraphLayout2Dp(net, damp, step, nsteps, rand_gen, 0);
  }
  else {
    MDGraphLayout(net, damp, step, nsteps, rand_gen, 0);
  }

  /*
    ---------------------------------------------------------------------------
    Output coordinates
    ---------------------------------------------------------------------------
  */
  PrintNodeCoordinates(stdout, net);

  /*
    ---------------------------------------------------------------------------
    Free memory
    ---------------------------------------------------------------------------
  */
  RemoveGraph(net);
  gsl_rng_free(rand_gen);
  return 0;
}