void multiscalePartition::partition(partitionLevel & level, int nbParts,
                                    typeOfPartition method)
{
#if defined(HAVE_SOLVER) && (defined(HAVE_METIS) || defined(HAVE_CHACO))

  if (method == LAPLACIAN){
    std::map<MVertex*, SPoint3> coordinates;
    multiscaleLaplace multiLaplace(level.elements, coordinates);
  }
  else if (method == MULTILEVEL){
    setNumberOfPartitions(nbParts);
    PartitionMeshElements(level.elements, options);
  }

  std::vector<std::vector<MElement*> > regions(nbParts);
  partitionRegions(level.elements, regions);
  level.elements.clear();

  for (unsigned i=0;i< regions.size() ; i++){

    partitionLevel *nextLevel = new partitionLevel;
    nextLevel->elements = regions[i];
    nextLevel->recur = level.recur+1;
    nextLevel->region = i;

    levels.push_back(nextLevel);
    int genus, AR, NB;
    getGenusAndRatio(regions[i], genus, AR, NB);

    if (genus < 0) {
      Msg::Error("Genus partition is negative G=%d!", genus);
      return;
    }

    if (genus != 0 ){
      int nbParts = std::max(genus+2,2);
      Msg::Info("Mesh partition: level (%d-%d)  is %d-GENUS (AR=%d) "
                "---> MULTILEVEL partition %d parts",
                nextLevel->recur,nextLevel->region, genus, AR, nbParts);
      partition(*nextLevel, nbParts, MULTILEVEL);
    }
    else if ((genus == 0  &&  AR > AR_MAX) || (genus == 0  &&  NB > 1)){
      int nbParts = 2;
      if(!onlyMultilevel){
	Msg::Info("Mesh partition: level (%d-%d)  is ZERO-GENUS (AR=%d NB=%d) "
                  "---> LAPLACIAN partition %d parts",
		  nextLevel->recur,nextLevel->region, AR, NB, nbParts);
	partition(*nextLevel, nbParts, LAPLACIAN);
      }
      else {
        Msg::Info("Mesh partition: level (%d-%d)  is ZERO-GENUS (AR=%d NB=%d) "
                  "---> MULTILEVEL partition %d parts",
                  nextLevel->recur,nextLevel->region, AR, NB, nbParts);
        partition(*nextLevel, nbParts, MULTILEVEL);
      }
    }
    else {
      Msg::Info("*** Mesh partition: level (%d-%d) is ZERO-GENUS (AR=%d, NB=%d)",
                nextLevel->recur,nextLevel->region, AR, NB);
    }

  }

#endif
}
 vector<vector<string>> partition(string str) {
     len = str.length();
     s = str;
     partition(0);
     return res;
 }
Beispiel #3
0
void Tree::trainTree(const MatrixReal& featMat, const VectorInteger& labels)
{

//	We work with a queue of nodes, initially containing only the root node.
//	We process the queue until it becomes empty. 
	std::queue<int> toTrain;

	int size,numClasses,numVars,dims;

	size = labels.size();
	dims = featMat.cols();
	numClasses = labels.maxCoeff();

	
	classWts = VectorReal::Zero(numClasses+1);

	for(int i = 0; i < labels.size(); ++i)
		classWts(labels(i)) += 1.0;

	classWts /= size;
	for(int i = 0; i < size; ++i)
		nodeix.push_back(i);

	std::cout<<"Training tree, dimensions set\n";

	numVars = (int)((double)sqrt((double)dims)) + 1;
	int cur;

//	The relevant indices for the root node is the entire set of training data
	nodes[0].start = 0;
	nodes[0].end = size-1;

//	Initialise the queue with just the root node
	toTrain.push(0);

//	Stores the relevant features.
	VectorReal relFeat;

//	Resize our boolean array, more on this later. 
	indices.resize(size);
	
	std::cout<<"Starting the queue\n";

	int lpoints,rpoints;
//	While the queue isn't empty, continue processing.
	while(!toTrain.empty())
	{
		int featNum;
		double threshold;
		lpoints = rpoints = 0;

		cur = toTrain.front();
		
//		std::cout<<"In queue, node being processed is d :"<<cur.depth<<"\n";
	
//		There are two ways for a node to get out of the queue trivially,
//		a) it doesn't have enough data to be a non-trivial split, or
//		b) it has hit the maximum permissible depth
		
		if((nodes[cur].end - nodes[cur].start < DATA_MIN) || (nodes[cur].depth == depth))
		{
//			Tell ourselves that this is a leaf node, and remove the node
//			from the queue.
//			std::cout<<"Popping a leaf node\n";

			nodes[cur].setType(true);

//			Initialize the histogram and set it to zero
			
			nodes[cur].hist = VectorReal::Zero(numClasses+1);

//			The below code should give the histogram of all the elements
			for(int i = nodes[cur].start; i <= nodes[cur].end; ++i)
			{
				nodes[cur].hist[labels(nodeix[i])] += 1.0;
			}

			for(int i = 0 ; i < classWts.size(); ++i)
				nodes[cur].hist[i] = nodes[cur].hist[i] / classWts[i];

			toTrain.pop();
			continue;

		}	

		double infoGain(-100.0);
		relFeat.resize(size);

//		In case this isn't a trivial node, we need to process it. 
		for(int i = 0; i < numVars; ++i)
		{
//			std::cout<<"Choosing a random variable\n";
//			Randomly select a feature
			featNum = rand()%dims;
//			std::cout<<"Feat: "<<featNum<<std::endl;
//			Extract the relevant feature set from the training data
			relFeat = featMat.col(featNum);

			double tmax,tmin,curInfo;

			tmax = relFeat.maxCoeff();
			tmin = relFeat.minCoeff();
//			infoGain = -100;
			//std::cout<<"Min "<<tmin<<"Max: "<<tmax<<std::endl;

//			NUM_CHECKS is a macro defined at the start
			for(int j = 0; j  < NUM_CHECKS; ++j)
			{
//				std::cout<<"Choosing a random threshold\n";
//				Generate a random threshold
				threshold = ((rand()%100)/100.0)*(tmax - tmin) + tmin;
				//std::cout<<"Thresh: "<<threshold<<std::endl;
				
				for(int k = nodes[cur].start; k <= nodes[cur].end ; ++k)
					indices[k] = (relFeat(k) < threshold);

//				Check if we have enough information gain
				curInfo = informationGain(nodes[cur].start,nodes[cur].end, labels);
//				std::cout<<"Info gain : "<<curInfo<<"\n";
//				curInfo = (double) ((rand()%10)/10.0);

				if(curInfo > infoGain)
				{
					infoGain = curInfo;
					nodes[cur].x = featNum;
					nodes[cur].threshold = threshold;
				}

			}

		}
//		We have selected a feature and a threshold for it that maximises the information gain.

		relFeat = featMat.col(nodes[cur].x);

//		We just set the indices depending on whether the features are greater or lesser.
//		Conventions followed : greater goes to the right.
		for(int k = nodes[cur].start; k <= nodes[cur].end; ++k)
		{
//			If relfeat is lesser, indices[k] will be true, which will put it in the 
//			left side of the partition.
			indices[k] = relFeat(k) < nodes[cur].threshold;
//			indices[k] = (bool)(rand()%2);
			
			if(indices[k])
				lpoints++;
			else
				rpoints++;
		}


		if( (lpoints < DATA_MIN) || (rpoints < DATA_MIN) )
		{
//			Tell ourselves that this is a leaf node, and remove the node
//			from the queue.
//			std::cout<<"Popping a leaf node\n";

			nodes[cur].setType(true);

//			Initialize the histogram and set it to zero
			
			nodes[cur].hist.resize(numClasses+1);
			nodes[cur].hist = VectorReal::Zero(numClasses+1);

//			The below code should give the histogram of all the elements
			for(int i = nodes[cur].start; i <= nodes[cur].end; ++i)
			{
				nodes[cur].hist[labels(nodeix[i])] += 1.0;
			}
			
			toTrain.pop();
			continue;

		}

		int part;

//		Use the prebuilt function to linearly partition our data
		part = partition(nodes[cur].start,nodes[cur].end);

		Node right, left;
//		Increase the depth of the children
		right.depth = left.depth = nodes[cur].depth + 1;

//		Correctly assign the partitions
		left.start = nodes[cur].start;
		left.end = part -1;
		
//		Push back into the relevant places and also link the parent and the child
		nodes.push_back(left);
		nodes[cur].leftChild = nodes.size()-1;
		toTrain.push(nodes[cur].leftChild);

//		Ditto with the right node. 
		right.start = part;
		right.end = nodes[cur].end;

		nodes.push_back(right);
		nodes[cur].rightChild = nodes.size()-1;
		toTrain.push(nodes[cur].rightChild);

//		Finally remove our node from the queue. 
		toTrain.pop();

	}
}
Beispiel #4
0
static void TestAlgorithms (void)
{
    static const int c_TestNumbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 13, 14, 15, 16, 17, 18 };
    const int* first = c_TestNumbers;
    const int* last = first + VectorSize(c_TestNumbers);
    intvec_t v, buf;
    v.assign (first, last);
    PrintVector (v);

    cout << "swap(1,2)\n";
    swap (v[0], v[1]);
    PrintVector (v);
    v.assign (first, last);

    cout << "copy(0,8,9)\n";
    copy (v.begin(), v.begin() + 8, v.begin() + 9);
    PrintVector (v);
    v.assign (first, last);

    cout << "copy with back_inserter\n";
    v.clear();
    copy (first, last, back_inserter(v));
    PrintVector (v);
    v.assign (first, last);

    cout << "copy with inserter\n";
    v.clear();
    copy (first, first + 5, inserter(v, v.begin()));
    copy (first, first + 5, inserter(v, v.begin() + 3));
    PrintVector (v);
    v.assign (first, last);

    cout << "copy_n(0,8,9)\n";
    copy_n (v.begin(), 8, v.begin() + 9);
    PrintVector (v);
    v.assign (first, last);

    cout << "copy_if(is_even)\n";
    intvec_t v_even;
    copy_if (v, back_inserter(v_even), &is_even);
    PrintVector (v_even);
    v.assign (first, last);

    cout << "for_each(printint)\n{ ";
    for_each (v, &printint);
    cout << "}\n";

    cout << "for_each(reverse_iterator, printint)\n{ ";
    for_each (v.rbegin(), v.rend(), &printint);
    cout << "}\n";

    cout << "find(10)\n";
    cout.format ("10 found at offset %zd\n", abs_distance (v.begin(), find (v, 10)));

    cout << "count(13)\n";
    cout.format ("%zu values of 13, %zu values of 18\n", count(v,13), count(v,18));

    cout << "transform(sqr)\n";
    transform (v, &sqr);
    PrintVector (v);
    v.assign (first, last);

    cout << "replace(13,666)\n";
    replace (v, 13, 666);
    PrintVector (v);
    v.assign (first, last);

    cout << "fill(13)\n";
    fill (v, 13);
    PrintVector (v);
    v.assign (first, last);

    cout << "fill_n(5, 13)\n";
    fill_n (v.begin(), 5, 13);
    PrintVector (v);
    v.assign (first, last);

    cout << "fill 64083 uint8_t(0x41) ";
    TestBigFill<uint8_t> (64083, 0x41);
    cout << "fill 64083 uint16_t(0x4142) ";
    TestBigFill<uint16_t> (64083, 0x4142);
    cout << "fill 64083 uint32_t(0x41424344) ";
    TestBigFill<uint32_t> (64083, 0x41424344);
    cout << "fill 64083 float(0.4242) ";
    TestBigFill<float> (64083, 0x4242f);
#if HAVE_INT64_T
    cout << "fill 64083 uint64_t(0x4142434445464748) ";
    TestBigFill<uint64_t> (64083, UINT64_C(0x4142434445464748));
#else
    cout << "No 64bit types available on this platform\n";
#endif

    cout << "copy 64083 uint8_t(0x41) ";
    TestBigCopy<uint8_t> (64083, 0x41);
    cout << "copy 64083 uint16_t(0x4142) ";
    TestBigCopy<uint16_t> (64083, 0x4142);
    cout << "copy 64083 uint32_t(0x41424344) ";
    TestBigCopy<uint32_t> (64083, 0x41424344);
    cout << "copy 64083 float(0.4242) ";
    TestBigCopy<float> (64083, 0.4242f);
#if HAVE_INT64_T
    cout << "copy 64083 uint64_t(0x4142434445464748) ";
    TestBigCopy<uint64_t> (64083, UINT64_C(0x4142434445464748));
#else
    cout << "No 64bit types available on this platform\n";
#endif

    cout << "generate(genint)\n";
    generate (v, &genint);
    PrintVector (v);
    v.assign (first, last);

    cout << "rotate(4)\n";
    rotate (v, 7);
    rotate (v, -3);
    PrintVector (v);
    v.assign (first, last);

    cout << "merge with (3,5,10,11,11,14)\n";
    const int c_MergeWith[] = { 3,5,10,11,11,14 };
    intvec_t vmerged;
    merge (v.begin(), v.end(), VectorRange(c_MergeWith), back_inserter(vmerged));
    PrintVector (vmerged);
    v.assign (first, last);

    cout << "inplace_merge with (3,5,10,11,11,14)\n";
    v.insert (v.end(), VectorRange(c_MergeWith));
    inplace_merge (v.begin(), v.end() - VectorSize(c_MergeWith), v.end());
    PrintVector (v);
    v.assign (first, last);

    cout << "remove(13)\n";
    remove (v, 13);
    PrintVector (v);
    v.assign (first, last);

    cout << "remove (elements 3, 4, 6, 15, and 45)\n";
    vector<uoff_t> toRemove;
    toRemove.push_back (3);
    toRemove.push_back (4);
    toRemove.push_back (6);
    toRemove.push_back (15);
    toRemove.push_back (45);
    typedef index_iterate<intvec_t::iterator, vector<uoff_t>::iterator> riiter_t;
    riiter_t rfirst = index_iterator (v.begin(), toRemove.begin());
    riiter_t rlast = index_iterator (v.begin(), toRemove.end());
    remove (v, rfirst, rlast);
    PrintVector (v);
    v.assign (first, last);

    cout << "unique\n";
    unique (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "reverse\n";
    reverse (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "lower_bound(10)\n";
    PrintVector (v);
    cout.format ("10 begins at position %zd\n", abs_distance (v.begin(), lower_bound (v, 10)));
    v.assign (first, last);

    cout << "upper_bound(10)\n";
    PrintVector (v);
    cout.format ("10 ends at position %zd\n", abs_distance (v.begin(), upper_bound (v, 10)));
    v.assign (first, last);

    cout << "equal_range(10)\n";
    PrintVector (v);
    TestEqualRange (v);
    v.assign (first, last);

    cout << "sort\n";
    reverse (v);
    PrintVector (v);
    random_shuffle (v);
    sort (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "stable_sort\n";
    reverse (v);
    PrintVector (v);
    random_shuffle (v);
    stable_sort (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "is_sorted\n";
    random_shuffle (v);
    const bool bNotSorted = is_sorted (v.begin(), v.end());
    sort (v);
    const bool bSorted = is_sorted (v.begin(), v.end());
    cout << "unsorted=" << bNotSorted << ", sorted=" << bSorted << endl;
    v.assign (first, last);

    cout << "find_first_of\n";
    static const int c_FFO[] = { 10000, -34, 14, 27 };
    cout.format ("found 14 at position %zd\n", abs_distance (v.begin(), find_first_of (v.begin(), v.end(), VectorRange(c_FFO))));
    v.assign (first, last);

    static const int LC1[] = { 3, 1, 4, 1, 5, 9, 3 };
    static const int LC2[] = { 3, 1, 4, 2, 8, 5, 7 };
    static const int LC3[] = { 1, 2, 3, 4 };
    static const int LC4[] = { 1, 2, 3, 4, 5 };
    cout << "lexicographical_compare";
    cout << "\nLC1 < LC2 == " << lexicographical_compare (VectorRange(LC1), VectorRange(LC2));
    cout << "\nLC2 < LC2 == " << lexicographical_compare (VectorRange(LC2), VectorRange(LC2));
    cout << "\nLC3 < LC4 == " << lexicographical_compare (VectorRange(LC3), VectorRange(LC4));
    cout << "\nLC4 < LC1 == " << lexicographical_compare (VectorRange(LC4), VectorRange(LC1));
    cout << "\nLC1 < LC4 == " << lexicographical_compare (VectorRange(LC1), VectorRange(LC4));

    cout << "\nmax_element\n";
    cout.format ("max element is %d\n", *max_element (v.begin(), v.end()));
    v.assign (first, last);

    cout << "min_element\n";
    cout.format ("min element is %d\n", *min_element (v.begin(), v.end()));
    v.assign (first, last);

    cout << "partial_sort\n";
    reverse (v);
    partial_sort (v.begin(), v.iat(v.size() / 2), v.end());
    PrintVector (v);
    v.assign (first, last);

    cout << "partial_sort_copy\n";
    reverse (v);
    buf.resize (v.size());
    partial_sort_copy (v.begin(), v.end(), buf.begin(), buf.end());
    PrintVector (buf);
    v.assign (first, last);

    cout << "partition\n";
    partition (v.begin(), v.end(), &is_even);
    PrintVector (v);
    v.assign (first, last);

    cout << "stable_partition\n";
    stable_partition (v.begin(), v.end(), &is_even);
    PrintVector (v);
    v.assign (first, last);

    cout << "next_permutation\n";
    buf.resize (3);
    iota (buf.begin(), buf.end(), 1);
    PrintVector (buf);
    while (next_permutation (buf.begin(), buf.end()))
	PrintVector (buf);
    cout << "prev_permutation\n";
    reverse (buf);
    PrintVector (buf);
    while (prev_permutation (buf.begin(), buf.end()))
	PrintVector (buf);
    v.assign (first, last);

    cout << "reverse_copy\n";
    buf.resize (v.size());
    reverse_copy (v.begin(), v.end(), buf.begin());
    PrintVector (buf);
    v.assign (first, last);

    cout << "rotate_copy\n";
    buf.resize (v.size());
    rotate_copy (v.begin(), v.iat (v.size() / 3), v.end(), buf.begin());
    PrintVector (buf);
    v.assign (first, last);

    static const int c_Search1[] = { 5, 6, 7, 8, 9 }, c_Search2[] = { 10, 10, 11, 14 };
    cout << "search\n";
    cout.format ("{5,6,7,8,9} at %zd\n", abs_distance (v.begin(), search (v.begin(), v.end(), VectorRange(c_Search1))));
    cout.format ("{10,10,11,14} at %zd\n", abs_distance (v.begin(), search (v.begin(), v.end(), VectorRange(c_Search2))));
    cout << "find_end\n";
    cout.format ("{5,6,7,8,9} at %zd\n", abs_distance (v.begin(), find_end (v.begin(), v.end(), VectorRange(c_Search1))));
    cout.format ("{10,10,11,14} at %zd\n", abs_distance (v.begin(), find_end (v.begin(), v.end(), VectorRange(c_Search2))));
    cout << "search_n\n";
    cout.format ("{14} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 1, 14)));
    cout.format ("{13,13} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 2, 13)));
    cout.format ("{10,10,10} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 3, 10)));
    v.assign (first, last);

    cout << "includes\n";
    static const int c_Includes[] = { 5, 14, 15, 18, 20 };
    cout << "includes=" << includes (v.begin(), v.end(), VectorRange(c_Includes)-1);
    cout << ", not includes=" << includes (v.begin(), v.end(), VectorRange(c_Includes));
    cout << endl;

    static const int c_Set1[] = { 1, 2, 3, 4, 5, 6 }, c_Set2[] = { 4, 4, 6, 7, 8 };
    intvec_t::iterator setEnd;
    cout << "set_difference\n";
    v.resize (4);
    setEnd = set_difference (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    cout << "set_symmetric_difference\n";
    v.resize (7);
    setEnd = set_symmetric_difference (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    cout << "set_intersection\n";
    v.resize (2);
    setEnd = set_intersection (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    cout << "set_union\n";
    v.resize (9);
    setEnd = set_union (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    v.assign (first, last);
}
int Solution::findKthLargestUtil(vector<int>& nums, int begin, int end, int k) {
  int idx = partition(nums, begin, end);
  if (k == end - idx + 1)  return nums[idx];
  if (k < end - idx + 1)  return findKthLargestUtil(nums, idx + 1, end, k);
  return findKthLargestUtil(nums, begin, idx - 1, k - (end - idx + 1));
}
/*
parallelQuicksortHelper
-if the level is still > 0, then partition and make 
parallelQuicksortHelper threads to solve the left and 
right-hand sides, then quit. Otherwise, call sequential.
*/
void *parallelQuicksortHelper(void *threadarg)
{
  int mid, t, rc;
  void *status;

  struct thread_data *my_data;
  my_data = (struct thread_data *) threadarg;

  //fyi:
  //printf("Thread responsible for [%d, %d], level %d.\n",
  //              my_data->low, my_data->high, my_data->level);

  if (my_data->level <= 0 || my_data->low == my_data->high+1) {
    //We have plenty of threads, finish with sequential.
    quicksortHelper(my_data->lyst, my_data->low, my_data->high);
    pthread_exit(NULL);
  }
  //Want joinable threads (usually default).
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  //Now we partition our part of the lyst.
  mid = partition(my_data->lyst, my_data->low, my_data->high);

  //At this point, we will create threads for the 
  //left and right sides.  Must create their data args.
  struct thread_data thread_data_array[2];

  for (t = 0; t < 2; t++) {
    thread_data_array[t].lyst = my_data->lyst;
    thread_data_array[t].level = my_data->level - 1;
  }
  thread_data_array[0].low = my_data->low;
  thread_data_array[0].high = mid - 1;
  thread_data_array[1].low = mid + 1;
  thread_data_array[1].high = my_data->high;

  //Now, instantiate the threads.
  //In quicksort of course, due to the transitive property,
  //no elements in the left and right sides of mid will have
  //to be compared again.
  pthread_t threads[2];
  for (t = 0; t < 2; t++) {
    rc = pthread_create(&threads[t], &attr, parallelQuicksortHelper,
                        (void *) &thread_data_array[t]);
    if (rc) {
      printf("ERROR; return code from pthread_create() is %d\n", rc);
      exit(-1);
    }
  }

  pthread_attr_destroy(&attr);
  //Now, join the left and right sides to finish.
  for (t = 0; t < 2; t++) {
    rc = pthread_join(threads[t], &status);
    if (rc) {
      printf("ERROR; return code from pthread_join() is %d\n", rc);
      exit(-1);
    }
  }

  pthread_exit(NULL);
}
Beispiel #7
0
void NaiveBayes::train(const Matrix &X, const Matrix &y)
{
    // clear last data
    labelDistinct.clear();
    attributeUniqueNumber.clear();
    labelProbability.clear();
    attributeProbability.clear();

    // y distinct
    vector<double> labels;
    for (Matrix::size_type i = 0; i < y.rowSize(); ++i) {
        labels.push_back(y(i, 0));
    }
    sort(labels.begin(), labels.end());
    unique_copy(labels.begin(), labels.end(), back_inserter(labelDistinct));
#ifdef DEBUG
    cout << "all labels" << endl;
    for (auto label : labels)
        cout << label << '\t';
    cout << endl;

    cout << "distinct labels" << endl;
    for (auto label : labelDistinct)
        cout << label << '\t';
    cout << endl << endl;
#endif

    // calculate labelPro
    auto N = y.rowSize();
    double yDistinct = static_cast<double>(y.distinctColumn()[0].size());
    for (auto yEach : labelDistinct) {
        auto range = equal_range(labels.begin(), labels.end(), yEach);
        auto yCount = range.second - range.first;
        labelProbability[yEach] = (yCount + lambda) / (static_cast<double>(N) + yDistinct * lambda);
#ifdef DEBUG
        cout << "y = " << yEach << " ";
        cout << "labelPro = " << labelProbability[yEach] << endl;
#endif
    }

    // calculate distinct number of attribute in each column
    vector<vector<double>> distinctAttribute = X.distinctColumn();
    attributeUniqueNumber.resize(X.columnSize());
    transform(distinctAttribute.begin(), distinctAttribute.end(), attributeUniqueNumber.begin(),
              [](const vector<double> &distinctUnit) {return distinctUnit.size();});
#ifdef DEBUG
    for (auto &distinctNumber : attributeUniqueNumber)
        cout << distinctNumber << '\t';
    cout << endl;
#endif

    // attributeProbability
    vector<Matrix> trainVec = X.merge(y, 1).splictRow();
    for (auto yEach : labelDistinct) {
#ifdef DEBUG
        cout << "y = " << yEach << endl;
#endif
        attributeProbability[yEach].resize(X.columnSize());
        auto partitionIter = partition(trainVec.begin(), trainVec.end(),
                  [=](const Matrix &m) {return m(0, m.columnSize() - 1) == yEach;});
        auto xWithSameY = partitionIter - trainVec.begin();
        vector<vector<double>> attributes(X.columnSize());
        for (vector<Matrix>::iterator it = trainVec.begin(); it != partitionIter; ++it) {
            for (Matrix::size_type col = 0; col < it->columnSize() - 1; ++col) {
                attributes[col].push_back(it->operator()(0, col));
            }
        }
        for (auto i = 0; i < attributes.size(); ++i) {
            vector<double> columnEach = attributes[i];
            sort(columnEach.begin(), columnEach.end());
            vector<double> columnDistinct;
            unique_copy(columnEach.begin(), columnEach.end(), back_inserter(columnDistinct));
            for (double &attributeEach : columnDistinct) {
                auto range = equal_range(columnEach.begin(), columnEach.end(), attributeEach);
                auto xCount = range.second - range.first;
                attributeProbability[yEach][i][attributeEach] =
                        (xCount + lambda) / (static_cast<double>(xWithSameY) + attributeUniqueNumber[i] * lambda);
#ifdef DEBUG
                cout << "y = " << yEach << " " << i << "th column ";
                cout << " attribute = " << attributeEach ;
                cout << " attributePro = " << xCount / static_cast<double>(xWithSameY) << endl;
#endif
            }
        }
    }

}
int main(int argc, char ** argv)
{
    clock_t t0;
    t0 = clock();
    bool print = true;

    if (argc==1)
    {
        help();
        exit(0);
    }

    std::string cmd(argv[1]);

    //primitive programs that do not require help pages and summary statistics by default
    if (argc>1 && cmd=="view")
    {
        print = view(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="index")
    {
        print = index(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="merge")
    {
        print = merge(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="paste")
    {
        print = paste(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="concat")
    {
        print = concat(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="subset")
    {
        subset(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="decompose")
    {
        decompose(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="normalize")
    {
        print = normalize(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="config")
    {
        config(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="mergedups")
    {
        merge_duplicate_variants(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="remove_overlap")
    {
        remove_overlap(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="peek")
    {
        peek(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="partition")
    {
        partition(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="annotate_variants")
    {
        annotate_variants(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="annotate_regions")
    {
        annotate_regions(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="annotate_dbsnp_rsid")
    {
        annotate_dbsnp_rsid(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="discover")
    {
        discover(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="merge_candidate_variants")
    {
        merge_candidate_variants(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="union_variants")
    {
        union_variants(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="genotype")
    {
        genotype2(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="characterize")
    {
        genotype(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="construct_probes")
    {
        construct_probes(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_indels")
    {
        profile_indels(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_snps")
    {
        profile_snps(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_mendelian")
    {
        profile_mendelian(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_na12878")
    {
        profile_na12878(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_chrom")
    {
        profile_chrom(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="align")
    {
        align(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="compute_features")
    {
        compute_features(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_afs")
    {
        profile_afs(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_hwe")
    {
        profile_hwe(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_len")
    {
        profile_len(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="annotate_str")
    {
        annotate_str(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="consolidate_variants")
    {
        consolidate_variants(argc-1, ++argv);
    }
    else
    {
        std::clog << "Command not found: " << argv[1] << "\n\n";
        help();
        exit(1);
    }

    if (print)
    {
        clock_t t1;
        t1 = clock();
        print_time((float)(t1-t0)/CLOCKS_PER_SEC);
    }

    return 0;
}
 * Contains an implementation class for a binary_heap.
 */

PB_DS_CLASS_T_DEC
template<typename Pred>
void
PB_DS_CLASS_C_DEC::
split(Pred pred, PB_DS_CLASS_C_DEC& other)
{
  PB_DS_ASSERT_VALID((*this))

  typedef
    typename entry_pred<value_type, Pred, _Alloc, simple_value>::type
    pred_t;

  const size_type left = partition(pred_t(pred));
  _GLIBCXX_DEBUG_ASSERT(m_size >= left);

  const size_type ersd = m_size - left;
  _GLIBCXX_DEBUG_ASSERT(m_size >= ersd);

  const size_type new_size = resize_policy::get_new_size_for_arbitrary(left);
  const size_type other_actual_size = other.get_new_size_for_arbitrary(ersd);

  entry_pointer a_entries = 0;
  entry_pointer a_other_entries = 0;

  __try
    {
      a_entries = s_entry_allocator.allocate(new_size);
      a_other_entries = s_entry_allocator.allocate(other_actual_size);
Beispiel #10
0
void quicksort(int a[], int l, int r){
    int i;
    i = partition(a, l, r);
    quicksort(a, l, i-1);
    quicksort(a, i+1, r);
}
Beispiel #11
0
	// get the index of the number in the middle
	// s.t. subarray on the left <= A[index] <= subarray on the right
	int randomizedPartition(Distance* A, int p, int r) {
		int i = rand() % (r-p+1) + p;
		Distance tmp = A[i]; A[i] = A[r]; A[r] = tmp;
		return partition(A, p, r);
	}
//----------------------------------------------------------------
void ofSerial::buildDeviceList(){

	deviceType = "serial";
	devices.clear();

	vector <string> prefixMatch;

	#ifdef TARGET_OSX
		prefixMatch.push_back("cu.");
		prefixMatch.push_back("tty.");
	#endif
	#ifdef TARGET_LINUX
		#ifdef TARGET_RASPBERRY_PI
			prefixMatch.push_back("ttyACM");
		#endif

		prefixMatch.push_back("ttyS");
		prefixMatch.push_back("ttyUSB");
		prefixMatch.push_back("rfc");
	#endif


	#if defined( TARGET_OSX ) || defined( TARGET_LINUX )

	DIR *dir;
	struct dirent *entry;
	dir = opendir("/dev");

	string deviceName	= "";
	int deviceCount		= 0;

	if (dir == NULL){
		ofLogError("ofSerial") << "buildDeviceList(): error listing devices in /dev";
	} else {
		//for each device
		while((entry = readdir(dir)) != NULL){
			deviceName = (char *)entry->d_name;

			//we go through the prefixes
			for(int k = 0; k < (int)prefixMatch.size(); k++){
				//if the device name is longer than the prefix
				if( deviceName.size() > prefixMatch[k].size() ){
					//do they match ?
					if( deviceName.substr(0, prefixMatch[k].size()) == prefixMatch[k].c_str() ){
						devices.push_back(ofSerialDeviceInfo("/dev/"+deviceName, deviceName, deviceCount));
						deviceCount++;
						break;
					}
				}
			}
		}
		closedir(dir);
	}

	#endif

	//---------------------------------------------
	#ifdef TARGET_WIN32
	//---------------------------------------------
	enumerateWin32Ports();
	ofLogNotice("ofSerial") << "found " << nPorts << " devices";
	for (int i = 0; i < nPorts; i++){
		//NOTE: we give the short port name for both as that is what the user should pass and the short name is more friendly
		devices.push_back(ofSerialDeviceInfo(string(portNamesShort[i]), string(portNamesShort[i]), i));
	}
	//---------------------------------------------
	#endif
    //---------------------------------------------

	//here we sort the device to have the aruino ones first.
	partition(devices.begin(), devices.end(), isDeviceArduino);
	//we are reordering the device ids. too!
	for(int k = 0; k < (int)devices.size(); k++){
		devices[k].deviceID = k;
	}

	bHaveEnumeratedDevices = true;
}
Beispiel #13
0
// START FUNC DECL
int
vec_f_to_s(
	   char *X,
	   FLD_TYPE fldtype,
	   char *nn_X,
	   long long nR,
	   const char *op,
	   char *rslt_buf,
	   int sz_rslt_buf
	   )
// STOP FUNC DECL
{
  int status = 0;
  long long ll_minval = LLONG_MAX;
  double    dd_minval = DBL_MAX;
  long long ll_maxval = LLONG_MIN;
  double    dd_maxval = DBL_MIN;
  long long ll_sum = 0;
  double    dd_sum = 0.0;
  long long cum_nn_cnt = 0;

  char *part_rslt = NULL;

  long long *nn_cnt = NULL;
  long long *ll_numer = NULL;
  double    *dd_numer = NULL;
  int nT; long long block_size;

  // Break up along nice boundaries
  int max_nT = g_num_cores;
  status = partition(nR, 1024, max_nT, &block_size, &nT);
  cBYE(status);
  nn_cnt = malloc(nT * sizeof(long long)); return_if_malloc_failed(nn_cnt);
  ll_numer = malloc(nT * sizeof(long long)); return_if_malloc_failed(ll_numer);
  dd_numer = malloc(nT * sizeof(double)); return_if_malloc_failed(dd_numer);
  /* 16 is the largest size of a basic type. double = 8 bytes */
  part_rslt = malloc(nT * 16); return_if_malloc_failed(part_rslt);

  char *I1_part_rslt = (char *)part_rslt;
  short *I2_part_rslt = (short *)part_rslt;
  int *I4_part_rslt = (int *)part_rslt;
  long long *I8_part_rslt = (long long *)part_rslt;
  float *F4_part_rslt = (float *)part_rslt;
  double *F8_part_rslt = (double *)part_rslt;

  for ( int i = 0; i < nT; i++ ) { 
    nn_cnt[i]    = 0; 
    ll_numer[i]  = 0; 
    dd_numer[i]  = 0; 
  }
  //----------------------------------------
#pragma omp parallel for
  for ( int tid = 0; tid < nT; tid++ ) { // POTENTIAL CILK LOOP
    if ( status < 0 ) { continue; }
    /* We store results for each iteration of above loop in a "local"
     * variable" and assign it to the partial results at end */
    long long lb = tid * block_size;
    long long ub = lb + block_size;
    if ( tid == (nT-1) ) { ub = nR; }
    long long nX = (ub -lb);
    if ( nX <= 0 ) { status = -1; continue; }
    if ( strcmp(op, "min") == 0 ) {
      char      i1val = SCHAR_MAX, *I1_X = NULL;
      short     i2val = SHRT_MAX,  *I2_X = NULL;
      int       i4val = INT_MAX,   *I4_X = NULL;
      long long i8val = LLONG_MAX, *I8_X = NULL;
      float     f4val = FLT_MAX,   *F4_X = NULL;
      double    f8val = DBL_MAX,   *F8_X = NULL;

      if ( nn_X == NULL ) { 
	nn_cnt[tid] = nX; // all values are defined 
	switch ( fldtype ) {
	case I1 : 
	  I1_X = (char *)X; I1_X += lb;
	  f_to_s_min_I1(I1_X, nX, &i1val);
	  I1_part_rslt[tid] = i1val;
	  break;
	case I2 : 
	  I2_X = (short *)X; I2_X += lb;
	  f_to_s_min_I2(I2_X, nX, &i2val);
	  I2_part_rslt[tid] = i2val;
	  break;
	case I4 : 
	  I4_X = (int *)X; I4_X += lb;
	  f_to_s_min_I4(I4_X, nX, &i4val); 
	  I4_part_rslt[tid] = i4val;
	  break;
	case I8 : 
	  I8_X = (long long *)X; I8_X += lb;
	  f_to_s_min_I8(I8_X, nX, &i8val); 
	  I8_part_rslt[tid] = i8val;
	  break;
	case F4 : 
	  F4_X = (float *)X; F4_X += lb;
	  f_to_s_min_F4(F4_X, nX, &f4val);
	  F4_part_rslt[tid] = f4val;
	  break;
	case F8 : 
	  F8_X = (double *)X; F8_X += lb;
	  f_to_s_min_F8(F8_X, nX, &f8val);
	  F8_part_rslt[tid] = f8val;
	  break;
	default : 
	  status = -1; 
	  break;
	}
      }
      else {
	nn_cnt[tid] = 0; // no idea how many values are defined 
	long long l_nn_cnt = 0;
	switch ( fldtype ) {
	case I1 : 
	  nn_f_to_s_min_I1(((char *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &i1val);
	  I1_part_rslt[tid] = i1val;
	  break;
	case I2 : 
	  nn_f_to_s_min_I2(((short *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &i2val); 
	  I2_part_rslt[tid] = i2val;
	  break;
	case I4 : 
	  nn_f_to_s_min_I4(((int *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &i4val);
	  I4_part_rslt[tid] = i4val;
	  break;
	case I8 : 
	  nn_f_to_s_min_I8(((long long *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &i8val); 
	  I8_part_rslt[tid] = i8val;
	  break;
	case F4 : 
	  nn_f_to_s_min_F4(((float *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &f4val);
	  F4_part_rslt[tid] = f4val;
	  break;
	case F8 : 
	  nn_f_to_s_min_F8(((double *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &f8val);
	  F8_part_rslt[tid] = f8val;
	  break;
	default : 
	  status = -1; 
	  break;
	}
        nn_cnt[tid] = l_nn_cnt;
      }
    }
    else if ( strcmp(op, "max") == 0 ) {
      char      i1val = SCHAR_MIN, *I1_X = NULL;
      short     i2val = SHRT_MIN,  *I2_X = NULL;
      int       i4val = INT_MIN,   *I4_X = NULL;
      long long i8val = LLONG_MIN, *I8_X = NULL;
      float     f4val = FLT_MIN,   *F4_X = NULL;
      double    f8val = DBL_MIN,   *F8_X = NULL;

      if ( nn_X == NULL ) {
	nn_cnt[tid] = nX; // all values are defined 
	switch ( fldtype ) {
	case I1 : 
	  I1_X = (char *)X; I1_X += lb;
	  f_to_s_max_I1(I1_X, nX, &i1val); 
	  I1_part_rslt[tid] = i1val;
	  break;
	case I2 : 
	  I2_X = (short *)X; I2_X += lb;
	  f_to_s_max_I2(I2_X, nX, &i2val);
	  I2_part_rslt[tid] = i2val;
	  break;
	case I4 : 
	  I4_X = (int *)X; I4_X += lb;
	  f_to_s_max_I4(I4_X, nX, &i4val); 
	  I4_part_rslt[tid] = i4val;
	  break;
	case I8 : 
	  I8_X = (long long *)X; I8_X += lb;
	  f_to_s_max_I8(((long long *)X)+lb, nX, &i8val); 
	  I8_part_rslt[tid] = i8val;
	  break;
	case F4 : 
	  F4_X = (float *)X; F4_X += lb;
	  f_to_s_max_F4(F4_X, nX, &f4val); 
	  F4_part_rslt[tid] = f4val;
	  break;
	case F8 : 
	  F8_X = (double *)X; F8_X += lb;
	  f_to_s_max_F8(F8_X, nX, &f8val); 
	  F8_part_rslt[tid] = f8val;
	  break;
	default : 
	  status = -1;
	  break;
	}
      }
      else {
	long long l_nn_cnt = 0;// no idea how many values are defined 
	switch ( fldtype ) {
	case I1 : 
	  nn_f_to_s_max_I1(((char *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &i1val);
	  I1_part_rslt[tid] = i1val;
	  break;
	case I2 : 
	  nn_f_to_s_max_I2(((short *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &i2val);
	  I2_part_rslt[tid] = i2val;
	  break;
	case I4 : 
	  nn_f_to_s_max_I4(((int *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &i4val); 
	  I4_part_rslt[tid] = i4val;
	  break;
	case I8 : 
	  nn_f_to_s_max_I8(((long long *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &i8val);
	  I8_part_rslt[tid] = i8val;
	  break;
	case F4 : 
	  nn_f_to_s_max_F4(((float *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &f4val);
	  F4_part_rslt[tid] = f4val;
	  break;
	case F8 : 
	  nn_f_to_s_max_F8(((double *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &f8val);
	  F8_part_rslt[tid] = f8val;
	  break;
	default : 
	  status = -1;
	  break;
	}
        nn_cnt[tid] = l_nn_cnt;
      }
    }
    else if ( strcmp(op, "sum") == 0 ) {
      long long l_ll_numer = 0;
      double l_dd_numer = 0;
      if ( nn_X == NULL ) {
	nn_cnt[tid] = nX; // all values are defined 
	switch ( fldtype ) {
	case B  : 
	  status = f_to_s_sum_B(X, lb, ub, &l_ll_numer);
	  break;
	case I1 : 
	  f_to_s_sum_I1(((char *)X)+lb, nX, &l_ll_numer);
	  break;
	case I2 : 
	  f_to_s_sum_I2(((short *)X)+lb, nX, &l_ll_numer);
	  break;
	case I4 : 
	  f_to_s_sum_I4(((int *)X)+lb, nX, &l_ll_numer);
	  break;
	case I8 : 
	  f_to_s_sum_I8(((long long *)X)+lb, nX, &l_ll_numer);
	  break;
	case F4 : 
	  f_to_s_sum_F4(((float *)X)+lb, nX, &l_dd_numer);
	  break;
	case F8 : 
	  f_to_s_sum_F8(((double *)X)+lb, nX, &l_dd_numer);
	  break;
	default : 
	  status = -1;
	  break;
	}
	ll_numer[tid] = l_ll_numer;
	dd_numer[tid] = l_dd_numer;
      }
      else {
	long long l_nn_cnt = 0;// no idea how many values are defined 
      long long l_ll_numer = 0;
      double l_dd_numer = 0;
	switch ( fldtype ) {
	case I1 : 
	  nn_f_to_s_sum_I1(((char *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &l_ll_numer);
	  break;
	case I2 : 
	  nn_f_to_s_sum_I2(((short *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &l_ll_numer);
	  break;
	case I4 : 
	  nn_f_to_s_sum_I4(((int *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &l_ll_numer);
	  break;
	case I8 : 
	  nn_f_to_s_sum_I8(((long long *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &l_ll_numer);
	  break;
	case F4 : 
	  nn_f_to_s_sum_F4(((float *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &l_dd_numer);
	  break;
	case F8 : 
	  nn_f_to_s_sum_F8(((double *)X)+lb, nn_X+lb, nX, &l_nn_cnt, &l_dd_numer);
	  break;
	default : 
	  status = -1;
	  break;
	}
	nn_cnt[tid] = l_nn_cnt;
	ll_numer[tid] = l_ll_numer;
	dd_numer[tid] = l_dd_numer;
      }
    }
    else { 
      WHEREAMI; fprintf(stderr, "ERROR Bad operation = [%s] \n", op);
      status = -1; 
    }
  }
  cBYE(status);

  // Now combine results 
  if ( strcmp(op, "min") == 0 ) {
    switch ( fldtype ) { 
      case I1 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( I1_part_rslt[i] < ll_minval ) { 
	    ll_minval = I1_part_rslt[i]; 
	  }
	}
      }
      sprintf(rslt_buf, "%lld:%lld", ll_minval, cum_nn_cnt);
      break;
    case I2 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( I2_part_rslt[i] < ll_minval ) { ll_minval = I2_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lld:%lld", ll_minval, cum_nn_cnt);
      break;
    case I4 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( I4_part_rslt[i] < ll_minval ) { ll_minval = I4_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lld:%lld", ll_minval, cum_nn_cnt);
      break;
    case I8 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( I8_part_rslt[i] < ll_minval ) { ll_minval = I8_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lld:%lld", ll_minval, cum_nn_cnt);
      break;
    case F4 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( F4_part_rslt[i] < dd_minval ) { dd_minval = F4_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lf:%lld", dd_minval, cum_nn_cnt);
      break;
    case F8 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( F8_part_rslt[i] < dd_minval ) { dd_minval = F8_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lf:%lld", dd_minval, cum_nn_cnt);
      break;
    default : 
      go_BYE(-1);
      break;
    }
  }
  else if ( strcmp(op, "max") == 0 ) {
    switch ( fldtype ) { 
    case I1 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( I1_part_rslt[i] > ll_maxval ) { ll_maxval = I1_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lld:%lld", ll_maxval, cum_nn_cnt);
      break;
    case I2 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( I2_part_rslt[i] > ll_maxval ) { ll_maxval = I2_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lld:%lld", ll_maxval, cum_nn_cnt);
      break;
    case I4 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( I4_part_rslt[i] > ll_maxval ) { ll_maxval = I4_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lld:%lld", ll_maxval, cum_nn_cnt);
      break;
    case I8 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( I8_part_rslt[i] > ll_maxval ) { ll_maxval = I8_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lld:%lld", ll_maxval, cum_nn_cnt);
      break;
    case F4 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( F4_part_rslt[i] > dd_maxval ) { dd_maxval = F4_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lf:%lld", dd_maxval, cum_nn_cnt);
      break;
    case F8 : 
      for ( int i = 0; i < nT; i++ ) { 
	if ( nn_cnt[i] > 0 ) { 
	  cum_nn_cnt += nn_cnt[i];
	  if ( F8_part_rslt[i] > dd_maxval ) { dd_maxval = F8_part_rslt[i]; }
	}
      }
      sprintf(rslt_buf, "%lf:%lld", dd_maxval, cum_nn_cnt);
      break;
    default : 
      go_BYE(-1);
      break;
    }
  }
  else if ( strcmp(op, "sum") == 0 ) {
    f_to_s_sum_I8(nn_cnt, nT, &cum_nn_cnt);
    switch ( fldtype ) { 
    case B : 
    case I1 : 
    case I2 : 
    case I4 : 
    case I8 : 
      f_to_s_sum_I8(ll_numer, nT, &ll_sum);
      sprintf(rslt_buf, "%lld:%lld", ll_sum, cum_nn_cnt);
      break;
    case F4 : 
    case F8 : 
      f_to_s_sum_F8(dd_numer, nT, &dd_sum);
      sprintf(rslt_buf, "%lf:%lld", dd_sum, cum_nn_cnt);
      break;
    default : 
      go_BYE(-1);
      break;
    }
  }
  else {
    go_BYE(-1);
  }
 BYE:
  free_if_non_null(nn_cnt);
  free_if_non_null(ll_numer);
  free_if_non_null(dd_numer);
  free_if_non_null(part_rslt);
  return status ;
}
Beispiel #14
0
static void
sort1 (int *array, int count)
{
  omp_lock_t lock;
  struct int_pair_stack global_stack;
  int busy = 1;
  int num_threads;

  omp_init_lock (&lock);
  init_int_pair_stack (&global_stack);
  #pragma omp parallel firstprivate (array, count)
  {
    int lo = 0, hi = 0, mid, next_lo, next_hi;
    bool idle = true;
    struct int_pair_stack local_stack;

    init_int_pair_stack (&local_stack);
    if (omp_get_thread_num () == 0)
      {
	num_threads = omp_get_num_threads ();
	hi = count - 1;
	idle = false;
      }

    for (;;)
      {
	if (hi - lo < THRESHOLD)
	  {
	    insertsort (array, lo, hi);
	    lo = hi;
	  }
	if (lo >= hi)
	  {
	    if (size_int_pair_stack (&local_stack) == 0)
	      {
	      again:
		omp_set_lock (&lock);
		if (size_int_pair_stack (&global_stack) == 0)
		  {
		    if (!idle)
		      busy--;
		    if (busy == 0)
		      {
			omp_unset_lock (&lock);
			break;
		      }
		    omp_unset_lock (&lock);
		    idle = true;
		    while (size_int_pair_stack (&global_stack) == 0
			   && busy)
		      busy_wait ();
		    goto again;
		  }
		if (idle)
		  busy++;
		pop_int_pair_stack (&global_stack, &lo, &hi);
		omp_unset_lock (&lock);
		idle = false;
	      }
	    else
	      pop_int_pair_stack (&local_stack, &lo, &hi);
	  }

	mid = partition (array, lo, hi);
	if (mid - lo < hi - mid)
	  {
	    next_lo = mid;
	    next_hi = hi;
	    hi = mid - 1;
	  }
	else
	  {
	    next_lo = lo;
	    next_hi = mid - 1;
	    lo = mid;
	  }

	if (next_hi - next_lo < THRESHOLD)
	  insertsort (array, next_lo, next_hi);
	else
	  {
	    if (size_int_pair_stack (&global_stack) < num_threads - 1)
	      {
		int size;

		omp_set_lock (&lock);
		size = size_int_pair_stack (&global_stack);
		if (size < num_threads - 1 && size < STACK_SIZE)
		  push_int_pair_stack (&global_stack, next_lo, next_hi);
		else
		  push_int_pair_stack (&local_stack, next_lo, next_hi);
		omp_unset_lock (&lock);
	      }
	    else
	      push_int_pair_stack (&local_stack, next_lo, next_hi);
	  }
      }
    }
  omp_destroy_lock (&lock);
}
int main(int argc, char *argv[])
{
  Pooma::initialize(argc, argv);
  Pooma::Tester tester(argc, argv);

  Interval<2> physicalVertexDomain(10, 10);

  // Note, the layout uses the DistributedTag, since we are using
  // Remote engines in the fields.
  
  Loc<2> blocks(2, 2);
  UniformGridPartition<2> partition(blocks, GuardLayers<2>(1));   
  UniformGridLayout<2> layout(physicalVertexDomain, partition,
			      DistributedTag());
  
  tester.out() << "layout domain: " << layout.domain() << std::endl;
  
  // Now, we can declare a field.

  Centering<2> allFace = canonicalCentering<2>(FaceType, Continuous);

  typedef UniformRectilinearMesh<2> Mesh_t;
  typedef MultiPatch<UniformTag, Remote<Brick> > EngineTag_t;

  typedef Field<Mesh_t, double, EngineTag_t > Field_t;

  typedef Field<Mesh_t, Vector<2>, EngineTag_t > VField_t;

  Vector<2> origin(0.0, 0.0);
  Vector<2> spacings(1.0, 1.0);

  Field_t a(allFace, layout, origin, spacings);
  Field_t b(allFace, layout, origin, spacings);
  Field_t c(allFace, layout, origin, spacings);

  // Should really figure out how to repackage these three lines:

  DomainLayout<2> layoutDom(physicalVertexDomain, GuardLayers<2>(1));
  XField<Mesh_t>::Type_t x(allFace, layoutDom, origin, spacings);
  setXField(x);

  b = 0.0;
  c = 0.0;

  Vector<2> line(1.0, 1.0);

  a = where(dot(x, line) > 8.0, x.comp(0), x.comp(1));

  tester.out() << a << std::endl;

  tester.check("sum a[0]", sum(a[0]), 423.0);
  tester.check("sum a[0]*x[0](0)", sum(a[0] * x[0].comp(0)), 2397.0);
  tester.check("sum a[0]*x[0](1)", sum(a[0] * x[0].comp(1)), 2083.5);
  tester.check("sum a[1]", sum(a[1]), 387.0);
  tester.check("sum a[1]*x[1](0)", sum(a[1] * x[1].comp(0)), 2161.5);
  tester.check("sum a[1]*x[1](1)", sum(a[1] * x[1].comp(1)), 1990.5);

  int ret = tester.results("CrossBox");
  Pooma::finalize();
  return ret;
}
Beispiel #16
0
int isStackSortable(int * array, int len)
{
  int sortable = partition(array, 0, len);
  return sortable;
}
Beispiel #17
0
static void inertial_bisection(unsigned* n, point** o, rcopy** idx)
{
  plane mp = bisection_plane(*n, *o);
  partition(n, o, idx, mp);
}
Beispiel #18
0
int partition(int * array, int start, int end)
{
  if((end-start) < 3)
    {
      return TRUE;
    }

  int indexmax = start; //declaring the indexmax as the first index, since its a recursive function, start is not always zero so we cant use zero
  int i;
  int max = array[start]; //declaring the first element in the array as the maximum then compare them afterwards, again its a recursive function so cant use zero

  for(i = start; i < end; i++) //i<= end because we already use length-1 as an argument (check isStackSortable function)
    {
      if(array[i] > max)
	{
	  max = array[i];
	  indexmax = i;
	}
    }

  int maxleft = array[start]; 
  int indexmaxleft = start;
  if(indexmax == start)
    {
      maxleft = -1;
    }
  else
    {
      for(i = 0;i < indexmax; i++) //i stops before indexmax because it does not take indexmax value into account
	{
      if(array[i] > maxleft)
	{
	  maxleft = array[i];
	  indexmaxleft = i;
	}
	}
    }

  int minright = array[indexmax + 1];
  int indexminright = indexmax + 1;
  if(indexmax == (end-1)) 
    {
      minright = array[indexmax];
    }
  else
    { 
      for(i = indexmax + 1; i < end; i++)
	{
      if(array[i] < minright)
	{
	  minright = array[i];
	  indexminright = i;
	}
    }
    }

  int left = FALSE;
  int right = FALSE;
  if(maxleft == -1)
    {
      left = TRUE;
      right = partition(array, indexmax + 1, end);
    }
  else if(minright == array[indexmax])
    {
      left = partition(array, 0, indexmax);
      right = TRUE;
    }
  else if (maxleft < minright)
    {
      left = partition(array, start, indexmax);
      right = partition(array, indexmax+1, end);
    }

  if((left == TRUE) && (right == TRUE))
    {
      return TRUE;
    }
 
return FALSE;

}
void testList (void){

    // test a list with no nodes in it
    printf ("\nTest 1: an empty list [] = [] \n");
    list sourceList = malloc (sizeof (struct _list));
    assert (sourceList !=NULL);
    sourceList->head = NULL;  

    printf ("before partition..\n");
    printf("sourceList is: ");
    showList (sourceList);
    partition(sourceList);
    printf ("after..\n");
    printf("sourceList is: ");
    showList (sourceList);
    assert (sourceList->head == NULL);
	
    
    // create 10 nodes on the stack 
    node nodes[10];
 
    // test a list with one node in it
    printf ("\nTest 2: one node in list [42] = [42]\n");
    sourceList->head = &nodes[0];
    sourceList->head->value = 42;
    sourceList->head->next = NULL;  
    
    printf ("before partition..\n");
    printf("SourceList is: ");
    showList (sourceList);
    partition (sourceList);
    printf ("after..\n");
    printf("sourceList is: ");
    showList (sourceList);
  

    assert (sourceList->head == &nodes[0]);  
    assert (sourceList->head->value == 42);
    assert (sourceList->head->next == NULL); 
	
    
   
    // test a list with two nodes in it
    printf ("\nTest 3:  A list containing two nodes [73,21] = [21,73]\n");
    sourceList->head = &nodes[0];
    nodes[0].value = 73;
    nodes[1].value = 21;
    nodes[0].next  = &nodes[1];
    nodes[1].next  = NULL;
    
    printf ("before partition..\n");
    showList (sourceList);
    partition (sourceList);
    printf ("after partition..\n");
    printf("sourceList is: ");
    showList (sourceList);
   

    assert (sourceList->head == &nodes[1]);  
    assert (sourceList->head->value == 21);
 
    assert (sourceList->head->next == &nodes[0]);  
    assert (sourceList->head->next->value == 73);
    assert (sourceList->head->next->next == NULL); 
    
   
    // test a list with two nodes in it
    printf ("\nTest 4:  A list containing two nodes [21,73] = [21,73]\n");
    sourceList->head = &nodes[0];
    nodes[0].value = 21;
    nodes[1].value = 73;
    nodes[0].next  = &nodes[1];
    nodes[1].next  = NULL;
    
    printf ("before partition..\n");
    showList (sourceList);
    partition (sourceList);
    printf ("after partition..\n");
    printf("sourceList is: ");
    showList (sourceList);
   

    assert (sourceList->head == &nodes[0]);  
    assert (sourceList->head->value == 21);
 
    assert (sourceList->head->next == &nodes[1]);  
    assert (sourceList->head->next->value == 73);
    assert (sourceList->head->next->next == NULL); 


   
    printf ("\nTest 5:  A list containing three nodes [21,24,22] = [21,24,22]\n");
    sourceList->head = &nodes[0];
    nodes[0].value = 21;
    nodes[1].value = 24;
    nodes[2].value = 22;
    
    nodes[0].next  = &nodes[1];
    nodes[1].next  = &nodes[2];
    nodes[2].next  = NULL;
    
    printf ("before partition..\n");
    showList (sourceList);
    partition (sourceList);
    printf ("after partition..\n");
    printf("sourceList is: ");
    showList (sourceList);
   

    assert (sourceList->head == &nodes[0]);  
    assert (sourceList->head->value == 21);
 
    assert (sourceList->head->next == &nodes[1]);  
    assert (sourceList->head->next->value == 24);
    assert (sourceList->head->next->next == &nodes[2]);
    assert (sourceList->head->next->next->value == 22);
    assert (sourceList->head->next->next->next == NULL);

    printf ("\nTest 6:  A list containing three nodes [21,20,22] = [20,21,22]\n");
    sourceList->head = &nodes[0];
    nodes[0].value = 21;
    nodes[1].value = 20;
    nodes[2].value = 22;
    
    nodes[0].next  = &nodes[1];
    nodes[1].next  = &nodes[2];
    nodes[2].next  = NULL;
    
    printf ("before partition..\n");
    showList (sourceList);
    partition (sourceList);
    printf ("after partition..\n");
    printf("sourceList is: ");
    showList (sourceList);
   

    assert (sourceList->head == &nodes[1]);  
    assert (sourceList->head->value == 20);
 
    assert (sourceList->head->next == &nodes[0]);  
    assert (sourceList->head->next->value == 21);
    assert (sourceList->head->next->next == &nodes[2]);
    assert (sourceList->head->next->next->value == 22);
    assert (sourceList->head->next->next->next == NULL);

    printf ("\nTest 7:  A list containing three nodes [21,22,20] = [20,21,22]\n");
    sourceList->head = &nodes[0];
    nodes[0].value = 21;
    nodes[1].value = 22;
    nodes[2].value = 20;
    
    nodes[0].next  = &nodes[1];
    nodes[1].next  = &nodes[2];
    nodes[2].next  = NULL;
    
    printf ("before partition..\n");
    showList (sourceList);
    partition (sourceList);
    printf ("after partition..\n");
    printf("sourceList is: ");
    showList (sourceList);
   

    assert (sourceList->head == &nodes[2]);  
    assert (sourceList->head->value == 20);
 
    assert (sourceList->head->next == &nodes[0]);  
    assert (sourceList->head->next->value == 21);
    assert (sourceList->head->next->next == &nodes[1]);
    assert (sourceList->head->next->next->value == 22);
    assert (sourceList->head->next->next->next == NULL);


    printf ("\nTest 9:  A list with duplcate values [21,21,21] = [21,21,21]\n");
    sourceList->head = &nodes[0];
    nodes[0].value = 21;
    nodes[1].value = 21;
    nodes[2].value = 21;
    
    nodes[0].next  = &nodes[1];
    nodes[1].next  = &nodes[2];
    nodes[2].next  = NULL;
    
    printf ("before partition..\n");
    showList (sourceList);
    partition (sourceList);
    printf ("after partition..\n");
    printf("sourceList is: ");
    showList (sourceList);
   

    assert (sourceList->head == &nodes[0]);  
    assert (sourceList->head->value == 21);
 
    assert (sourceList->head->next == &nodes[1]);  
    assert (sourceList->head->next->value == 21);
    assert (sourceList->head->next->next == &nodes[2]);
    assert (sourceList->head->next->next->value == 21);
    assert (sourceList->head->next->next->next == NULL);
    




    // test a list with four nodes in it
    printf ("\nTest 10: a list containing four nodes\n");
    sourceList->head = &nodes[0];
    nodes[0].value = 45;
    nodes[1].value = 33;
    nodes[2].value = 12;
    nodes[3].value = 444;
    nodes[0].next  = &nodes[1];
    nodes[1].next  = &nodes[2];
    nodes[2].next  = &nodes[3];
    nodes[3].next  = NULL;
    
    printf ("before partition..\n");
    printf("SourceList is: ");
    showList (sourceList);

    partition (sourceList);
    printf ("after partition..\n");
    printf("SourceList is: ");
    showList (sourceList);

    assert (sourceList->head == &nodes[1]);  
    assert (sourceList->head->value == 33);
    assert (sourceList->head->next == &nodes[2]);
    assert (sourceList->head->next->value == 12);
    assert (sourceList->head->next->next == &nodes[0]);
    assert (sourceList->head->next->next->value == 45);
    assert (sourceList->head->next->next->next == &nodes[3]);
    assert (sourceList->head->next->next->next->value == 444);  
    assert (sourceList->head->next->next->next->next == NULL);  

    
    // test a list with nine nodes in it
    printf ("\nTest 11: a list containing ten nodes\n");
    sourceList->head = &nodes[0];
    nodes[0].value = 33;
    nodes[1].value = 65;
    nodes[2].value = 32;
    nodes[3].value = 90;
    nodes[4].value = 1;
    nodes[5].value = 232;
    nodes[6].value = 21;
    nodes[7].value = 77;
    nodes[8].value = 2;
    nodes[0].next  = &nodes[1];
    nodes[1].next  = &nodes[2];
    nodes[2].next  = &nodes[3];
    nodes[3].next  = &nodes[4]; 
    nodes[4].next  = &nodes[5];
    nodes[5].next  = &nodes[6]; 
    nodes[6].next  = &nodes[7];
    nodes[7].next  = &nodes[8];
    nodes[8].next  = NULL;
    
    printf ("before partition..\n");
    printf("SourceList is: ");
    showList (sourceList);
    partition (sourceList);
    printf ("after partition..\n");
    printf("SourceList is: ");
    showList (sourceList);

    assert (sourceList->head == &nodes[2]);  
    assert (sourceList->head->value == 32);
    assert (sourceList->head->next == &nodes[4]);
    assert (sourceList->head->next->value == 1);
    assert (sourceList->head->next->next == &nodes[6]);
    assert (sourceList->head->next->next->value == 21);
    assert (sourceList->head->next->next->next == &nodes[8]);
    assert (sourceList->head->next->next->next->value == 2);
    assert (sourceList->head->next->next->next->next == &nodes[0]);
    assert (sourceList->head->next->next->next->next->value == 33);
    assert (sourceList->head->next->next->next->next->next == &nodes[1]);
    assert (sourceList->head->next->next->next->next->next->value == 65);
    assert (sourceList->head->next->next->next->next->next->next == &nodes[3]);
    assert (sourceList->head->next->next->next->next->next->next->value == 90);
    assert (sourceList->head->next->next->next->next->next->next->next == &nodes[5]);
    assert (sourceList->head->next->next->next->next->next->next->next->value == 232);
    assert (sourceList->head->next->next->next->next->next->next->next->next == &nodes[7]);
    assert (sourceList->head->next->next->next->next->next->next->next->next->value == 77);
    assert (sourceList->head->next->next->next->next->next->next->next->next->next == NULL);

}
 ListNode* mergeKLists(vector<ListNode*>& lists) 
 {
     return partition(lists, 0, lists.size()-1);
 }
Beispiel #21
0
void merge_sort(int input[], int size)
{
printarray_size=size;
partition(input,0,size-1);
}
Beispiel #22
0
void qsort(int *value, int len) {
    partition(value, len);
}
Beispiel #23
0
//----------------------------------------------------------------
void ofSerial::buildDeviceList(){
	deviceType = "serial";
	devices.clear();
	vector <string> prefixMatch;

	#ifdef TARGET_OSX

		prefixMatch.push_back("cu.");
		prefixMatch.push_back("tty.");

	#endif

	#ifdef TARGET_LINUX

		prefixMatch.push_back("ttyACM");
		prefixMatch.push_back("ttyS");
		prefixMatch.push_back("ttyUSB");
		prefixMatch.push_back("rfc");

	#endif

	#if defined( TARGET_OSX ) || defined( TARGET_LINUX )
		ofDirectory dir("/dev");
		int deviceCount = 0;
		for(auto & entry: dir){
			std::string deviceName = entry.getFileName();

			//we go through the prefixes
			for(auto & prefix: prefixMatch){
				//if the device name is longer than the prefix
				if(deviceName.size() > prefix.size()){
					//do they match ?
					if(deviceName.substr(0, prefix.size()) == prefix.c_str()){
						devices.push_back(ofSerialDeviceInfo("/dev/"+deviceName, deviceName, deviceCount));
						deviceCount++;
						break;
					}
				}
			}
		}

	#endif

	#ifdef TARGET_WIN32

		enumerateWin32Ports();
		ofLogNotice("ofSerial") << "found " << nPorts << " devices";
		for(int i = 0; i < nPorts; i++){
			//NOTE: we give the short port name for both as that is what the user should pass and the short name is more friendly
			devices.push_back(ofSerialDeviceInfo(string(portNamesShort[i]), string(portNamesShort[i]), i));
		}

	#endif

	#if defined( TARGET_OSX )
		//here we sort the device to have the aruino ones first.
		partition(devices.begin(), devices.end(), isDeviceArduino);
		//we are reordering the device ids. too!
		int k = 0;
		for(auto & device: devices){
			device.deviceID = k++;
		}
	#endif

	bHaveEnumeratedDevices = true;
}
Beispiel #24
0
int main (
   int argc ,    // Number of command line arguments (includes prog name)
   char *argv[]  // Arguments (prog name is argv[0])
   )

{
   int i, j, k, nvars, ncases, irep, nreps, nbins, nbins_dep, nbins_indep, *count ;
   int n_indep_vars, idep, icand, *index, *mcpt_max_counts, *mcpt_same_counts, *mcpt_solo_counts ;
   short int *bins_dep, *bins_indep ;
   double *data, *work, dtemp, *save_info, criterion, *crits ;
   double *ab, *bc, *b ;
   char filename[256], **names, depname[256] ;
   FILE *fp ;

/*
   Process command line parameters
*/

#if 1
   if (argc != 6) {
      printf ( "\nUsage: TRANSFER  datafile  n_indep  depname  nreps" ) ;
      printf ( "\n  datafile - name of the text file containing the data" ) ;
      printf ( "\n             The first line is variable names" ) ;
      printf ( "\n             Subsequent lines are the data." ) ;
      printf ( "\n             Delimiters can be space, comma, or tab" ) ;
      printf ( "\n  n_indep - Number of independent vars, starting with the first" ) ;
      printf ( "\n  depname - Name of the 'dependent' variable" ) ;
      printf ( "\n            It must be AFTER the first n_indep variables" ) ;
      printf ( "\n  nbins - Number of bins for all variables" ) ;
      printf ( "\n  nreps - Number of Monte-Carlo permutations, including unpermuted" ) ;
      exit ( 1 ) ;
      }

   strcpy ( filename , argv[1] ) ;
   n_indep_vars = atoi ( argv[2] ) ;
   strcpy ( depname , argv[3] ) ;
   nbins = atoi ( argv[4] ) ;
   nreps = atoi ( argv[5] ) ;
#else
   strcpy ( filename , "..\\SYNTH.TXT" ) ;
   n_indep_vars = 7 ;
   strcpy ( depname , "SUM1234" ) ;
   nbins = 2 ;
   nreps = 1 ;
#endif

   _strupr ( depname ) ;

/*
   These are used by MEM.CPP for runtime memory validation
*/

   _fullpath ( mem_file_name , "MEM.LOG" , 256 ) ;
   fp = fopen ( mem_file_name , "wt" ) ;
   if (fp == NULL) { // Should never happen
      printf ( "\nCannot open MEM.LOG file for writing!" ) ;
      return EXIT_FAILURE ;
      }
   fclose ( fp ) ;
   mem_keep_log = 1 ;  // Change this to 1 to keep a memory use log (slows execution!)
   mem_max_used = 0 ;

/*
   Open the text file to which results will be written
*/

   fp = fopen ( "TRANSFER.LOG" , "wt" ) ;
   if (fp == NULL) { // Should never happen
      printf ( "\nCannot open TRANSFER.LOG file for writing!" ) ;
      return EXIT_FAILURE ;
      }

/*
   Read the file and locate the index of the dependent variable
*/

   if (readfile ( filename , &nvars , &names , &ncases , &data ))
      return EXIT_FAILURE ;

   for (idep=0 ; idep<nvars ; idep++) {
      if (! strcmp ( depname , names[idep] ))
         break ;
      }

   if (idep == nvars) {
      printf ( "\nERROR... Dependent variable %s is not in file", depname ) ;
      return EXIT_FAILURE ;
      }

   if (idep < n_indep_vars) {
      printf ( "\nERROR... Dependent variable %s must be beyond independent vars",
               depname ) ;
      return EXIT_FAILURE ;
      }

/*
   Allocate scratch memory

   crits - Transfer Entropy criterion
   index - Indices that sort the criterion
   save_info - Ditto, this is univariate criteria, to be sorted
*/

   MEMTEXT ( "TRANSFER work allocs" ) ;
   work = (double *) MALLOC ( ncases * sizeof(double) ) ;
   assert ( work != NULL ) ;
   crits = (double *) MALLOC ( n_indep_vars * sizeof(double) ) ;
   assert ( crits != NULL ) ;
   index = (int *) MALLOC ( n_indep_vars * sizeof(int) ) ;
   assert ( index != NULL ) ;
   bins_indep = (short int *) MALLOC ( ncases * sizeof(short int) ) ;
   assert ( bins_indep != NULL ) ;
   bins_dep = (short int *) MALLOC ( ncases * sizeof(short int) ) ;
   assert ( bins_dep != NULL ) ;
   mcpt_max_counts = (int *) MALLOC ( n_indep_vars * sizeof(int) ) ;
   assert ( mcpt_max_counts != NULL ) ;
   mcpt_same_counts = (int *) MALLOC ( n_indep_vars * sizeof(int) ) ;
   assert ( mcpt_same_counts != NULL ) ;
   mcpt_solo_counts = (int *) MALLOC ( n_indep_vars * sizeof(int) ) ;
   assert ( mcpt_solo_counts != NULL ) ;
   save_info = (double *) MALLOC ( n_indep_vars * sizeof(double) ) ;
   assert ( save_info != NULL ) ;
   count = (int *) MALLOC ( nbins * nbins * nbins * sizeof(int) ) ;
   assert ( count != NULL ) ;
   ab = (double *) MALLOC ( nbins * nbins * sizeof(double) ) ;
   assert ( ab != NULL ) ;
   bc = (double *) MALLOC ( nbins * nbins * sizeof(double) ) ;
   assert ( bc != NULL ) ;
   b = (double *) MALLOC ( nbins * sizeof(double) ) ;
   assert ( b != NULL ) ;

/*
   Get the dependent variable and partition it
*/

   for (i=0 ; i<ncases ; i++)            // Get the 'dependent' variable
      work[i] = data[i*nvars+idep] ;

   nbins_dep = nbins ;
   partition ( ncases , work , &nbins_dep , NULL , bins_dep ) ;

/*
   Replication loop is here
*/

   for (irep=0 ; irep<nreps ; irep++) {

/*
   Compute and save the transfer entropy of the dependent variable
   with each individual independent variable candidate.
*/

      for (icand=0 ; icand<n_indep_vars ; icand++) { // Try all candidates
         for (i=0 ; i<ncases ; i++)
            work[i] = data[i*nvars+icand] ;

         //    Shuffle independent variable if in permutation run (irep>0)

         if (irep) {                   // If doing permuted runs, shuffle
            i = ncases ;               // Number remaining to be shuffled
            while (i > 1) {            // While at least 2 left to shuffle
               j = (int) (unifrand () * i) ;
               if (j >= i)
                  j = i - 1 ;
               dtemp = work[--i] ;
               work[i] = work[j] ;
               work[j] = dtemp ;
               }
            }

         nbins_indep = nbins ;
         partition ( ncases , work , &nbins_indep , NULL , bins_indep ) ;

         criterion = trans_ent ( ncases , nbins_indep , nbins_dep ,
                                 bins_indep , bins_dep ,
                                 0 , 1 , 1 , count , ab , bc , b ) ;

         save_info[icand] = criterion ; // We will sort this when all candidates are done
                                        
         if (irep == 0) {               // If doing original (unpermuted), save criterion
            index[icand] = icand ;      // Will need original indices when criteria are sorted
            crits[icand] = criterion ;
            mcpt_max_counts[icand] = mcpt_same_counts[icand] = mcpt_solo_counts[icand] = 1 ;  // This is >= itself so count it now
            }
         else {
            if (criterion >= crits[icand])
               ++mcpt_solo_counts[icand] ;
            }
         } // Initial list of all candidates

      if (irep == 0)  // Find the indices that sort the candidates per criterion
         qsortdsi ( 0 , n_indep_vars-1 , save_info , index ) ;

      else {
         qsortd ( 0 , n_indep_vars-1 , save_info ) ;
         for (icand=0 ; icand<n_indep_vars ; icand++) {
            if (save_info[icand] >= crits[index[icand]])
               ++mcpt_same_counts[index[icand]] ;
            if (save_info[n_indep_vars-1] >= crits[index[icand]]) // Valid only for largest
               ++mcpt_max_counts[index[icand]] ;
            }
         }

      }  // For all reps

   fprintf ( fp , "\nTransfer entropy of %s", depname);

   fprintf ( fp , "\n" ) ;
   fprintf ( fp , "\n" ) ;
   fprintf ( fp , "\nPredictors, in order of decreasing transfer entropy" ) ;
   fprintf ( fp , "\n" ) ;
   fprintf ( fp , "\n                       Variable   Information   Solo pval   Min pval   Max pval" ) ;

   for (icand=0 ; icand<n_indep_vars ; icand++) { // Do all candidates
      k = index[n_indep_vars-1-icand] ;           // Index of sorted candidate
      fprintf ( fp , "\n%31s %11.5lf %12.4lf %10.4lf %10.4lf", names[k], crits[k],
                (double) mcpt_solo_counts[k] / nreps,
                (double) mcpt_same_counts[k] / nreps,
                (double) mcpt_max_counts[k] / nreps ) ;
      }

   MEMTEXT ( "TRANSFER: Finish" ) ;
   fclose ( fp ) ;
   FREE ( work ) ;
   FREE ( crits ) ;
   FREE ( index ) ;
   FREE ( bins_indep ) ;
   FREE ( bins_dep ) ;
   FREE ( mcpt_max_counts ) ;
   FREE ( mcpt_same_counts ) ;
   FREE ( mcpt_solo_counts ) ;
   FREE ( save_info ) ;
   FREE ( count ) ;
   FREE ( ab ) ;
   FREE ( bc ) ;
   FREE ( b ) ;
   free_data ( nvars , names , data ) ;

   MEMCLOSE () ;
   printf ( "\n\nPress any key..." ) ;
   _getch () ;
   return EXIT_SUCCESS ;
}
Beispiel #25
0
void op_partition(const char* lib_name, const char* lib_routine,
  op_set prime_set, op_map prime_map, op_dat coords )
{
  partition(lib_name, lib_routine, prime_set, prime_map, coords );
}
Beispiel #26
0
// last review 9/5/2013
//---------------------------------------------------------------
// START FUNC DECL 
int 
vec_f1opf2(
	   long long nR,
	   FLD_TYPE src_fldtype,
	   char *f1_X,
	   char *nn_f1_X,
	   char *op,
	   char *f2_X,
	   char *nn_f2_X,
	   FLD_TYPE dst_fldtype
	   )
// STOP FUNC DECL 
{
  int status = 0;
#define BUFLEN 32
  unsigned long long seedUI8 = 0;
  int nT; long long block_size;
  /*---------------------------------------------*/
  status = partition(nR, 1024, -1, &block_size, &nT); cBYE(status);
#pragma omp parallel for
  for ( int tid = 0; tid < nT; tid++ ) { // POTENTIAL CILK LOOP
    if ( status < 0 ) { continue; }

    long long lb = 0 + (tid * block_size);
    long long ub = lb + block_size;
    if ( tid == (nT-1) ) { ub = nR; }
    long long nX = (ub -lb);

    char *nn = nn_f1_X; nn +=  lb;
    char      *f1I1 = NULL, *opI1 = NULL;
    short     *f1I2 = NULL, *opI2 = NULL;
    int       *f1I4 = NULL, *opI4 = NULL;
    long long *f1I8 = NULL, *opI8 = NULL;
    float     *f1F4 = NULL, *opF4 = NULL;
    double    *f1F8 = NULL, *opF8 = NULL;
    unsigned long long *opUI8 = NULL;
    unsigned int       *f1UI4 = NULL;
    unsigned long long *f1UI8 = NULL;

    f1I1  = (char               *)f1_X; f1I1  += lb; 
    f1I2  = (short              *)f1_X; f1I2  += lb; 
    f1I4  = (int                *)f1_X; f1I4  += lb; 
    f1I8  = (long long          *)f1_X; f1I8  += lb; 
    f1F4  = (float              *)f1_X; f1F4  += lb; 
    f1F8  = (double             *)f1_X; f1F8  += lb; 
    f1UI8 = (unsigned long long *)f1_X; opUI8 += lb;
    f1UI4 = (unsigned int       *)f1_X; f1UI4 += lb;

    opI1  = (char               *)f2_X; opI1  += lb;
    opI2  = (short              *)f2_X; opI2  += lb;
    opI4  = (int                *)f2_X; opI4  += lb;
    opI8  = (long long          *)f2_X; opI8  += lb;
    opF4  = (float              *)f2_X; opF4  += lb;
    opF8  = (double             *)f2_X; opF8  += lb;
    opUI8 = (unsigned long long *)f2_X; opUI8 += lb;

    /* START: Handle the nn field */
    if ( nn_f1_X != NULL ) {
#ifdef IPP
      ippsCopy_8u(nn_f1_X+lb, nn_f2_X+lb, nX);
#else
      assign_I1(nn_f2_X+lb, nn_f1_X+lb, nX); 
#endif
    }
    /* STOP: Handle the nn field */
    switch ( src_fldtype ) {
      if ( strcmp(op, "conv") == 0 ) {
	status = conv(f1_X, lb, ub, nn_f1_X, src_fldtype, f2_X, dst_fldtype);
      }
      else if ( strcmp(op, "sqrt") == 0 ) {
#ifdef IPP
	ippsSqrt_64f(f1F8, opF8, nX);
#else
	vec_sqrt_F8(f1F8,  nX, opF8);
#endif
      }
      else if ( strcmp(op, "abs") == 0 ) {
#ifdef IPP
	ippsAbs_64f_A53(f1F8, opF8, nX);
#else
	vec_abs_F8(f1F8, nX, opF8);
#endif
      }
      else if ( strcmp(op, "reciprocal") == 0 ) {
	vec_reciprocal_F8(f1F8, nX, opF8);
      }
      else if ( strcmp(op, "normal_cdf_inverse") == 0 ) {
	vec_normal_cdf_inverse(f1F8, nX, nn_f2_X, opF8);
      }
      else if ( strcmp(op, "pval_from_zval") == 0 ) {
	vec_pval_from_zval(f1F8, nX, opF8);
      }
      else {
	if ( status == 0 ) { WHEREAMI; } status = -1; continue;
      }
      break;
    case I4 : 
      if ( strcmp(op, "conv") == 0 ) {
	status = conv(f1_X, lb, ub, nn_f1_X, src_fldtype, f2_X, dst_fldtype);
      }
      else if ( strcmp(op, "hash") == 0 ) {
	hash_I4(f1UI4, nX, seedUI8, opUI8);
      }
      else if ( strcmp(op, "!") == 0 ) {
	not_I4(f1I4, nX, opI4);
      }
      else if ( strcmp(op, "~") == 0 ) {
	ones_complement_I4(f1I4, nX, opI4);
      }
      else if ( strcmp(op, "++") == 0 ) {
	incr_I4(f1I4, nX, opI4);
      }
      else if ( strcmp(op, "--") == 0 ) {
	decr_I4(f1I4, nX, opI4);
      }
      else if ( strcmp(op, "bitcount") == 0 ) {
	bitcount_I4(f1UI4, nX, opI1);
      }
      else { 
	if ( status == 0 ) { WHEREAMI; } status = -1; continue;
      }
      break;
    case I8: 
      if ( strcmp(op, "conv") == 0 ) {
	status = conv(f1_X, lb, ub, nn_f1_X, src_fldtype, f2_X, dst_fldtype);
	if ( status < 0 ) { WHEREAMI; }
      }
      else if ( strcmp(op, "hash") == 0 ) {
	hash_I8(f1UI8, nX, seedUI8, opUI8);
      }
      else if ( strcmp(op, "!") == 0 ) {
	not_I8(f1I8, nX, opI8);
      }
      else if ( strcmp(op, "~") == 0 ) {
	ones_complement_I8(f1I8, nX, opI8);
      }
      else if ( strcmp(op, "++") == 0 ) {
	incr_I8(f1I8, nX, opI8);
      }
      else if ( strcmp(op, "--") == 0 ) {
	decr_I8(f1I8, nX, opI8);
      }
      else if ( strcmp(op, "bitcount") == 0 ) {
	bitcount_I8(f1UI8, nX, opI1);
      }
      else { 
	if ( status == 0 ) { WHEREAMI; } status = -1; continue;
      }
      break;
    case F4 : 
      if ( strcmp(op, "conv") == 0 ) {
	status = conv(f1_X, lb, ub, nn_f1_X, src_fldtype, f2_X, dst_fldtype);
      }
      else if ( strcmp(op, "sqrt") == 0 ) {
#ifdef IPP
	ippsSqrt_32f(f1F4, opF4, nX);
#else
	vec_sqrt_F4(f1F4, nX, opF4);
#endif
      }
      else if ( strcmp(op, "abs") == 0 ) {
#ifdef IPP
	ippsAbs_32f_A24(f1F4, opF4, nX);
#else
	vec_abs_F4(f1F4, nX, opF4);
#endif
      }
      else if ( strcmp(op, "reciprocal") == 0 ) {
	vec_reciprocal_F4(f1F4, nX, opF4);
      }
      else { 
	if ( status == 0 ) { WHEREAMI; } status = -1; continue;
      }
      break;
    case B : 
      if ( strcmp(op, "conv") == 0 ) {
	status = conv(f1_X, lb, ub, nn_f1_X, src_fldtype, f2_X, dst_fldtype);
      }
      else {
	if ( status == 0 ) { 
	  fprintf(stderr, "Invalid op = [%s] \n", op); WHEREAMI; 
	}
	status = -1; continue;
      }
      break;
    case I1 : 
      if ( strcmp(op, "conv") == 0 ) {
	status = conv(f1_X, lb, ub, nn_f1_X, src_fldtype, f2_X, dst_fldtype);
      }
      else if ( strcmp(op, "!") == 0 ) {
	not_I1(f1I1, nX, opI1);
      }
      else if ( strcmp(op, "~") == 0 ) {
	ones_complement_I1(f1I1, nX, opI1);
      }
      else { 
	if ( status == 0 ) { WHEREAMI; } status = -1; continue;
      }
      break;
    default : 
      if ( status == 0 ) { WHEREAMI; } status = -1; continue;
      break;
    }
  }
  cBYE(status);
 BYE:
  return(status);
}
Beispiel #27
0
void quickSort(vector<int> &a){
    partition(a, 0, a.size()-1);
}
Beispiel #28
0
int64_t RandomizedPartition(int64_t* A, int64_t p, int64_t r)
{
    int64_t i = (rand() % (r - p)) + p;
    swap(A, i, r);
    return partition(A, p, r);
}
Beispiel #29
0
QString CreateFileSystemJob::description() const
{
    return xi18nc("@info:progress", "Create file system <filename>%1</filename> on partition <filename>%2</filename>", partition().fileSystem().name(), partition().deviceNode());
}
Beispiel #30
0
bool Nfa::runNfaP(QString string)
{
  /* Create the partition of states */
  QList<QSet<Node*>*>* part = partition();

  /* Allocate threads depending on size partitioning */
  pthread_t* threads = (pthread_t*)malloc(part->size()*sizeof(pthread_t));
  /* Allocate params for each thread */
  NfaParams* params = (NfaParams*)malloc(part->size()*sizeof(NfaParams));
  /* Initial state set will be stored here later in the code */
  QSet<Node*>* initialStateSet = NULL;
  /* Loop counter */
  int i;

  /*
   *  IMPORTANT: An assumption is being made here that the very last set 
   *  in the list contains ONLY the inital state
   *
   */
  for(i = 0; i < part->size(); i++)
  {
    params[i].nfa = this;
    params[i].str = &string;
    /* If the set is the initial state, mark it as such */
    if (i == part->size() - 1) 
    {
      initialStateSet = part->at(i);
      params[i].isInitial = true;
    }
    else
    {
      params[i].isInitial = false;
    }
    /* Assign the params being sent to the thread the list it will be working on */
    params[i].nodes = part->at(i);
    /* Send off the thread! */
    pthread_create(&threads[i], NULL, &traverseP, &params[i]);
  }

  /* Reap the threads */
  for (i = 0; i < part->size(); i++) 
  {
    int* ptr;
    pthread_join(threads[i], (void**)&ptr);
  }

  bool intersects = false;

  /* Again, we're assuming the last list is the inital state so we aren't checking it */
  /* If there's any intersection between the initial set and the final sets then it was a valid string */
  for(i = 0; i < part->size() - 1; i++)
  {
    if(initialStateSet->intersect(*part->at(i)).size() > 0)
      intersects = true;
  }

  free(threads);
  free(params);

  return intersects;
}