Beispiel #1
0
    int maximumGap(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }

        const auto minimum = *min_element(nums.begin(), nums.end());
        const auto maximum = *max_element(nums.begin(), nums.end());
        const auto range = maximum - minimum;
        if (range == 0) {
            return 0;
        }

        const auto minMaxGap = max(range / (static_cast<int>(nums.size()) - 1), 1);

        const auto initialSegment = Segment{false, numeric_limits<int>::max(), numeric_limits<int>::min()};
        vector<Segment> segments((range + minMaxGap) / minMaxGap, initialSegment);

        for (const int x : nums) {
            const auto segment = &segments[(x - minimum) / minMaxGap];
            segment->valid = true;
            segment->low = min(segment->low, x);
            segment->high = max(segment->high, x);
        }

        int maxGap = minMaxGap;
        bool previousHighValid = false;
        int previousHigh = 0;

        for (const auto& segment : segments) {
            if (segment.valid) {
                if (previousHighValid) {
                    maxGap = max(maxGap, segment.low - previousHigh);
                }
                previousHigh = segment.high;
                previousHighValid = true;
            }
        }

        return maxGap;
    }
Beispiel #2
0
/**
 *Validates the optional 'spectra to read' properties, if they have been set
 * @param numberofspectra :: number of spectrum
 */
void LoadNexusProcessed::checkOptionalProperties(const size_t numberofspectra )
{
  //read in the settings passed to the algorithm
  m_spec_list = getProperty("SpectrumList");
  m_spec_max = getProperty("SpectrumMax");
  m_spec_min = getProperty("SpectrumMin");
  //Are we using a list of spectra or all the spectra in a range?
  m_list = !m_spec_list.empty();
  m_interval = (m_spec_max != Mantid::EMPTY_INT()) || (m_spec_min != 1);
  if ( m_spec_max == Mantid::EMPTY_INT() ) m_spec_max = 1;

  // Check validity of spectra list property, if set
  if (m_list)
  {
    m_list = true;
    const int64_t minlist = *min_element(m_spec_list.begin(), m_spec_list.end());
    const int64_t maxlist = *max_element(m_spec_list.begin(), m_spec_list.end());
    if (maxlist > static_cast<int>(numberofspectra) || minlist == 0)
    {
      g_log.error("Invalid list of spectra");
      throw std::invalid_argument("Inconsistent properties defined");
    }
  }

  // Check validity of spectra range, if set
  if (m_interval)
  {
    m_interval = true;
    m_spec_min = getProperty("SpectrumMin");
    if (m_spec_min != 1 && m_spec_max == 1)
    {
      m_spec_max = numberofspectra;
    }
    if (m_spec_max < m_spec_min || m_spec_max > static_cast<int>(numberofspectra))
    {
      g_log.error("Invalid Spectrum min/max properties");
      throw std::invalid_argument("Inconsistent properties defined");
    }
  }
}
Beispiel #3
0
vector<short> Channel::prep_waveform() const{
	//Apply the scale,offset and covert to integer format
	vector<short> prepVec(waveform_.size());
	for(size_t ct=0; ct<prepVec.size(); ct++){
		prepVec[ct] = short(MAX_WF_AMP*(scale_*waveform_[ct]+offset_));
	}

	//Clip to the max and min values allowed
	if (*max_element(prepVec.begin(), prepVec.end()) > MAX_WF_AMP){
		FILE_LOG(logWARNING) << "Waveform element too positive; clipping to max";
		for(short & tmpVal : prepVec){
			if (tmpVal > MAX_WF_AMP) tmpVal = MAX_WF_AMP;
		}
	}
	if (*min_element(prepVec.begin(), prepVec.end()) < -MAX_WF_AMP){
		FILE_LOG(logWARNING) << "Waveform element too negative; clipping to max";
		for(short & tmpVal : prepVec){
			if (tmpVal < -MAX_WF_AMP) tmpVal = -MAX_WF_AMP;
		}
	}
	return prepVec;
}
Beispiel #4
0
/*
 * Calculates speed of given unique car from the list of CarImg
 * Give him a row from the main list<list<CarImg> >
 * Returns a positive double
 * if speed_method isn't recognized, returns -1
 *
 * speed_method is from enum of same name
 */
double CarCV::calcSpeed(list<CarImg> clist, int speed_method, double framerate, double real_measuring_length) {
	if (speed_method == 1) { //SP_FROMSORTEDFILES

		double list_size = clist.size();

		double speed = real_measuring_length * (list_size / framerate) * SPEED_CONVERSION_CONST;

		return speed;
	} else if (speed_method == 2) { //SP_FROMALLFILES

		const int indexesLength = clist.front().getPath()->filename().generic_string().length();

		vector<int> indexes;

		int index = 0;
		for(list<CarImg>::iterator i = clist.begin(); i != clist.end(); i++) {
			indexes.push_back((*i).parseId());
		}

		int maxId = *max_element(indexes.begin(), indexes.end());
		int minId = *min_element(indexes.begin(), indexes.end());

		//cout << "maxId=" << maxId << ";minId=" << minId << endl;

		double diff = abs((double) (maxId - minId));

		double speed = real_measuring_length * (diff / framerate) * SPEED_CONVERSION_CONST;

		//cout << speed << "=" << real_measuring_length << "*(" << diff << "/" << framerate << ")*" << SPEED_CONVERSION_CONST << endl;

		return speed;
	}
	else {
		int n = speed_method;
		cerr << "ERROR: Unimplemented method: " << n << endl;
		return -1;
	}
	return 0;
}
Beispiel #5
0
 int maximumGap(vector<int>& nums) {
     if (nums.size() < 2)
         return 0;
     int min = *min_element(nums.begin(), nums.end());
     int mymax = *max_element(nums.begin(), nums.end());
     int range = mymax - min;
     int nbuckets = nums.size();
     vector<int> mins(nbuckets, INT_MAX), maxs(nbuckets, INT_MIN);
     for(auto x : nums) {
         int index = ((double)(x-min)*(nbuckets-1))/range;
         if (mins[index] > x) mins[index] = x;
         if (maxs[index] < x) maxs[index] = x;
     }
     int prev = maxs[0];
     mymax = 0;
     for (int i = 1; i < nbuckets; i++) {
         if (mins[i] == INT_MAX) continue;
         mymax = max(mymax, mins[i]-prev);
         prev = maxs[i];
     }
     return mymax;
 }
void Planner::updateVertex(list<Uelem> &U, Grid &u, vector<vector<int> > &g, vector<vector<int> > &rhs, Map &map,int km)
{
    // update the vertex value and update the priority queue
    if(u!=map.goal)
    {
        vector<Grid> neighbour = findNeighbour(map, u, 8);
        vector<float> dist;
        
        for_each(neighbour.begin(),neighbour.end(),[&](Grid &it){dist.push_back((float)g[it.y][it.x]+calculateDistance(it,u));});
        
        rhs[u.y][u.x]=*min_element(dist.begin(),dist.end());
    }
    
    auto pt =find_if(U.begin(),U.end(),[u](Uelem &pt){return pt.point==u;});
    if (pt!=U.end()) U.erase(pt);
    if (g[u.y][u.x]!=rhs[u.y][u.x])
    {
        Key knew = calculateKey(u,g,rhs,map.start,0);
        auto pt = find_if(U.begin(),U.end(),[&](Uelem &a){return a.key<knew;});
        U.insert(pt,{u,knew});
    }
}
  inline void assign_pairs2(dataset_t &ds,Titer b,Titer e)
  {
    cellid_t cf[10],*cfe;

    BOOST_AUTO(cmp,bind(&dataset_t::compare_cells<dim+1>,&ds,_1,_2));

    int np = 0;

    for(;b!=e;++b)
      if(!ds.is_paired(*b))
      {
        cfe = cf + ds.get_cets<ASC>(*b,cf);
        cfe = filter_elst2(cf,cfe,cf,*b,ds);

        cellid_t *mcf = min_element(cf,cfe,cmp);

        if( mcf != cfe && ds.is_boundry(*mcf) == ds.is_boundry(*b))
        {
          ds.pair(*b,*mcf); np++;
        }
      }
  }
Beispiel #8
0
    int maximumGap(vector<int>& nums) {
        if (nums.size() < 2) {
            return 0;
        }

        // Init bucket.
        int max_val = *max_element(nums.cbegin(), nums.cend());
        int min_val = *min_element(nums.cbegin(), nums.cend());
        int gap = max(1, static_cast<int>((max_val - min_val) /
                                          (nums.size() - 1)));
        vector<Bucket> buckets((max_val - min_val) / gap + 1);

        // Find the bucket where the n should be put.
        for (const auto& n : nums) {
            // min_val / max_val is in the first / last bucket.
            if (n == max_val || n == min_val) {
                continue;
            }
            int i = (n - min_val) / gap;
            buckets[i].min = min(buckets[i].min, n);
            buckets[i].max = max(buckets[i].max, n);
        }

        // Maximum gap should not be smaller than any gap inside the bucket.
        // i.e. max_gap >= (max_val - min_val) / (count - 1)
        // Thus, only count each bucket gap between the first and the last bucket.
        int max_gap = 0, pre_bucket_max = min_val;
        for (const auto& bucket : buckets) {
            if (bucket.min != numeric_limits<int>::max()) {
                max_gap = max(max_gap, bucket.min - pre_bucket_max);
                pre_bucket_max = bucket.max;
            }
        }
        // Count the last bucket.
        max_gap = max(max_gap, max_val - pre_bucket_max);

        return max_gap;
    }
bool Generalization::SetWeights( const vector<float>& rVecWeights )
{
	AnonyException temp_exception;
	temp_exception.m_bShallContinue = true;
	stringstream temp_sstream;

	try
	{
		if (rVecWeights.size() != m_vecQiAttr.size())
		{
			temp_sstream << "Generalization::SetWeithgt Error: The number of weights differs from the number of QI attributes";
			temp_exception.SetMsg( temp_sstream.str() );
			throw( temp_exception );
		}

		if (*max_element( rVecWeights.begin(), rVecWeights.end() ) > 1 || *min_element( rVecWeights.begin(), rVecWeights.end() ) < 1)
		{
			temp_sstream << "Generalization::SetWeithgt Error: Weights cannot be larger than 100 or smaller than 1";
			temp_exception.SetMsg( temp_sstream.str() );
			throw( temp_exception );
		}

		long i;
		const long temp_size = rVecWeights.size();
		for (i = 0; i < temp_size; ++i)
		{
			m_vecQiAttr[i].m_fWght = rVecWeights[i];
		}
	}
	catch( AnonyException e )
	{
		Clear();
		cout << e.GetMsg() << endl;
		throw( e );
	}

	return true;
}
Beispiel #10
0
 /**
  *@param A: A positive integer which has N digits, A is a string.
  *@param k: Remove k digits.
  *@return: A string
  */
 string DeleteDigits(string A, int k) {
     // wirte your code here
     const int n=A.size();
     if(n <= k)
         return "";
     if(k == 0)
         return A;
     
     string ans="";
     for(int i=0, j=k+1; j<=n;) {
         char c=*min_element(A.begin()+i, A.begin()+j);
         ans.push_back(c);
         i=A.find(c, i)+1;
         ++j;
     }
     
     int start=0;
     while(ans[start]=='0') {
         ++start;
     }
     
     return ans.substr(start, ans.length()-start+1);
 }
/**
 * The training procedure computes and store the graphs for each training
 * sample. Clears any previous training data. Graphs are stored in BFS order
 * starting from the face vertex.
 */
void MultipleGraphsClassifier::train(vector<std::tuple<DisjointSetForest, Mat_<Vec3b>, Mat_<float>, int > > trainingSet) {
	this->maxTrainingGraphSize = get<0>(*max_element(trainingSet.begin(), trainingSet.end(), compareSampleSize)).getNumberOfComponents();
	this->minTrainingGraphSize = get<0>(*min_element(trainingSet.begin(), trainingSet.end(), compareSampleSize)).getNumberOfComponents();
	this->trainingFeatureGraphs.clear();
	this->trainingFeatureGraphs.reserve(trainingSet.size());

	for (int i = 0; i < (int)trainingSet.size(); i++) {
		DisjointSetForest segmentation;
		Mat_<Vec3b> image;
		Mat_<float> mask;
		int label;
		std::tie (segmentation, image, mask, label) = trainingSet[i];

		vector<WeightedGraph> featureGraphs;
		featureGraphs.reserve(this->features.size());

		for (int j = 0; j < (int)this->features.size(); j++) {
			featureGraphs.push_back(this->computeFeatureGraph(j, segmentation, image, mask));
		}

		this->trainingFeatureGraphs.push_back(std::tuple<vector<WeightedGraph>, int >(featureGraphs, label));
	}
}
Beispiel #12
0
RatedMove	*MinMax::min(GameData const &gd, GameData::team t, int d) const
{
  RatedMove	*ret;
  ChessBoard	board(gd);

  const std::list<Move *>	*successorStateList = NULL;
  successorStateList = board.getSuccessors(t);
  std::list<RatedMove *>	*ratedSuccessorStateList = NULL;
  ratedSuccessorStateList = new std::list<RatedMove *>(); // Alloc 5 (min-func)
  for (std::list<Move *>::const_iterator it = successorStateList->begin() ;
       it != successorStateList->end() ; ++it)
    {
      if (d == 0)
	  ratedSuccessorStateList->push_back(new RatedMove(*it, eval((*it)->getGameData(), t))); // Alloc 4 (min-func)
      else
	{
	  ret = max((*it)->getGameData(), gd.getOtherTeam(t), d - 1);
	  ratedSuccessorStateList->push_back(new RatedMove(*it, ret->getScore())); // Alloc 4 (max-func)
	  delete ret;
	}
    }
  ret = &(*min_element(boost::make_indirect_iterator(ratedSuccessorStateList->begin()), boost::make_indirect_iterator(ratedSuccessorStateList->end())));
  for (std::list<Move *>::const_iterator it = successorStateList->begin() ;
       it != successorStateList->end() ; ++it)
    {
	delete *it; // Un-alloc 8 (min-func)
    }
  for (std::list<RatedMove *>::iterator it = ratedSuccessorStateList->begin() ;
       it != ratedSuccessorStateList->end() ; ++it)
    {
      if (*it != ret)
	delete *it; // Un-alloc 4 (min-func) ! except one
    }
  delete ratedSuccessorStateList; // Un-alloc 5 (min-func)
  delete successorStateList; // Un-alloc 2 (min-func)
  return (ret);
}
int ambientColor::searchArray(vector<int>a, int b) {


	//find nearest element to key            
	//int refElem = b;
	//std::vector<int> v{ 1, 5, 36, 50 };
	auto i = min_element(begin(a), end(a), [=](int x, int y)
	{
		return abs(x - b) < abs(y - b);
	});

	//cout <<"nearestValue"<< distance(begin(a), i)<<endl; 
	return  distance(begin(a), i);
	// Prints 2
	/*
	int min_dist = 0; // keep track of mininum distance seen so far
	int min_index = 0; // keep track of the index of the element 
					   // that has the min index

	for (int i = 0; i < a.size(); i++) { // a.Length is the size of the array

		cout << a[i] << "firstkey" << b << endl;
		if (a[i] == b) { // if we find the exact one, stop
			return i;
		}
		else { // otherwise, keep looking for the closest
			if (abs(a[i] - b) < min_dist) { // if this one is closer, update
				min_dist = abs(a[i] - b);
				min_index = i;

				cout << a[i] << "key" << b << endl;
			}
		}
	}
	return min_index; // when we finish return the index of the closest
	*/
}
void dijkstra(Graph g)//
{
	unordered_map<char, char> shortest;
	unordered_map<char, char> parent;
	unordered_map<char, int> distance;
	for (auto c : g.vertices)
	{
		parent[c] = '\0';
		distance[c] = INT_MAX;
	}
	distance['a'] = 0;//root
	vector<char> q = g.vertices;
	while (!q.empty())//O(V)
	{
		char u = *min_element(q.begin(), q.end(), [&](char x, char y){return distance[x] < distance[y]; });
		vector<char>::iterator i = remove(q.begin(), q.end(), u);
		q.erase(i, q.end());
		if (parent[u] != '\0')
			shortest[u] = parent[u];
		vector<pair<char, Edge>> adj = g.adjacent(u);
		for (auto v : adj)
		{
			if (find(q.begin(), q.end(), v.first) != q.end())
			{
				if (distance[u] + v.second.weight < distance[v.first])
				{
					parent[v.first] = u;
					distance[v.first] = distance[u] + v.second.weight;
				}
			}
		}
	}
	for (auto e : shortest)
		cout << e.first << " to " << e.second << endl;
	for (auto e : distance)
		cout << e.first << " is " << e.second << endl;
}
void prim(Graph g)//time O(V^2)
{
	unordered_map<char, char> mst;
	unordered_map<char, char> parent;
	unordered_map<char, int> key;
	for (auto c : g.vertices)
	{
		parent[c] = '\0';
		key[c] = INT_MAX;
	}
	key['a'] = 0;//root
	vector<char> q = g.vertices;
	while (!q.empty())
	{
		char u = *min_element(q.begin(), q.end(), [&](char x, char y){return key[x] < key[y]; });
		vector<char>::iterator i = remove(q.begin(), q.end(), u);
		q.erase(i, q.end());
		if (parent[u] != '\0')
		{
			mst[u] = parent[u];
		}
		vector<pair<char, Edge>> adj = g.adjacent(u);
		for (pair<char, Edge> v : adj)
		{
			if (find(q.begin(), q.end(), v.first) != q.end())
			{
				if (v.second.weight < key[v.first])
				{
					parent[v.first] = u;
					key[v.first] = v.second.weight;
				}
			}
		}
	}
	for (auto e : mst)
		cout << e.first << " - " << e.second << endl;
}
Beispiel #16
0
    int maximumGap(vector<int>& nums) {
        if (nums.size() < 2) {
            return 0;
        }

        // Init bucket.
        int max_val = *max_element(nums.cbegin(), nums.cend());
        int min_val = *min_element(nums.cbegin(), nums.cend());
        int gap = max(1, static_cast<int>((max_val - min_val) /
                                          (nums.size() - 1)));
        map<int, array<int, 2>> bucket;
        using ValueType = enum {MIN, MAX};

        // Find the bucket where the n should be put.
        for (const auto& n : nums) {
            // min_val / max_val is in the first / last bucket.
            if (n == max_val || n == min_val) {
                continue ;    
            }
            int i = (n - min_val) / gap;
            bucket[i][MIN] = min(!bucket[i][MIN] ? numeric_limits<int>::max() : 
                                                   bucket[i][MIN], n);
            bucket[i][MAX] = max(!bucket[i][MAX] ? numeric_limits<int>::min() :
                                                   bucket[i][MAX], n);
        }

        // Count each bucket gap between the first and the last bucket.
        int max_gap = 0, pre_bucket_max = min_val;
        for (auto& kvp : bucket) {
            max_gap = max(max_gap, kvp.second[MIN] - pre_bucket_max);
            pre_bucket_max = (kvp.second)[MAX];
        }
        // Count the last bucket.
        max_gap = max(max_gap, max_val - pre_bucket_max);

        return max_gap;
    }
Beispiel #17
0
double solve(const Polygon& p) {
  int n = p.size();

  //
  int left = min_element(p.begin(), p.end()) - p.begin();
  int right = max_element(p.begin(), p.end()) - p.begin();

  //
  Vector2 calipers_l(0, 1);
  double r = (p[right] - p[left]).norm();

  // printf("(%lf, %lf) (%lf, %lf) %lf\n",
  //        p[left].x, p[left].y, p[right].x, p[right].y, r);

  //
  std::vector<Vector2> to_next(n);
  for (int i = 0; i < n; ++i) {
    to_next[i] = (p[(i+1) % n] - p[i]).normalize();
  }

  int a = left;
  int b = right;

  while (a != right || b != left) {
    double cos_l = calipers_l.dot(to_next[a]);
    double cos_r = -calipers_l.dot(to_next[b]);
    if (cos_l > cos_r) {
      calipers_l = to_next[a];
      a = (a + 1) % n;
    } else {
      calipers_l = to_next[b] * -1;
      b = (b + 1) % n;
    }
    r = std::max(r, (p[a] - p[b]).norm());
  }
  return r;
}
Beispiel #18
0
int AnalysisDialog::find_epi_threshold() {
    // quick and dirty way to guess the threshold between outbreaks and epidemics
    vector< vector<int> > plotData = resultsHistPlot->getData();
    if (plotData.size() == 0 or plotData[0].size() == 0) return -1;
    vector<int>& data = plotData[0];
    int min = min_element(data);
    int start = 0; // beginning of trough between outbreaks and epis
    int stop  = 0; // end of trough
    int best_range = 0;
    int second_range = 0;

    int curr_start = -1;
    int curr_stop  = -1;

    vector<int> freqs = tabulate_vector(data);

    for (unsigned int s = min; s < freqs.size(); s++) {
        if (freqs[s] == 0 and curr_start == -1) {
            curr_start = s;
        } else if (freqs[s] > 0 and curr_start > -1) {
            curr_stop = s;
            if (curr_stop - curr_start > best_range) {
                start = curr_start;
                stop = curr_stop;
                second_range = best_range;
                best_range = curr_stop - curr_start;
                curr_start = -1;
                curr_stop = -1;
            }
        }
    }
    if (best_range > 1.5 * second_range) {
        return start + (stop-start)/2;
    } else {
        return -1;
    }
}
int NCKinectUser::update(float x_pos) {
    
    if (xpositions.size()>buffer-1) {
        xpositions.erase(xpositions.begin());
        
        std::sort(xpositions.begin(), xpositions.end());
        float av;
        for (int i=0;i<xpositions.size();++i) {
            av +=xpositions[i];
        }
        
        av=av/buffer;
        
        avcounter++;
        
        if (avcounter==91) {
            
            float max =  *max_element(avs.begin(), avs.begin()+90);
            float min = *min_element(avs.begin(), avs.begin()+90);
            //cout<<min<<" : "<<max<<" : "<<max-min<<endl;
            if (max-min<0.3) {
                //cout<<"user "<<id<<" is standing still"<<endl;
                avcounter = 0;
                avs.clear();
                return id;
            }
            avcounter = 0;
            avs.clear();
        } else {
            avs.push_back(av);
        }
        //cout<<(int)av<<" : "<<max<<" : "<<min<<" : "<<abs(max-min)<<endl;
    }
    xpositions.push_back(x_pos);
    
    return -1;
}
Beispiel #20
0
    int minimumTotal(vector<vector<int> > &triangle) {

        vector<int> v1;
        v1.push_back(triangle[0][0]);

        for(int i = 1; i < triangle.size(); i++)
        {
            vector<int> v2;
            for(int j = 0; j < triangle[i].size(); j++)
            {
                if(j == 0)
                {
                    v2.push_back(triangle[i][j]+v1.front());
                } else if(j == triangle[i].size()-1) {
                    v2.push_back(triangle[i][j]+v1.back());
                } else {
                    v2.push_back(triangle[i][j] + min(v1[j-1], v1[j]));
                }
            }
            v1 = v2;
        }

        return *min_element(v1.begin(), v1.end());
    }
Beispiel #21
0
 int minimumTotal(vector<vector<int> > &triangle) {
     // Start typing your C/C++ solution below
     // DO NOT write int main() function
     if(triangle.size() == 0) return 0;
     int lastLine_prev = 0;
     vector<int> total(triangle.size());
     
     //Initialization
     total[0] = triangle[0][0];
     
     for(int i = 1; i < triangle.size(); ++i) { //Will invoke size() every time?
         lastLine_prev = total[0];
         total[0] += triangle[i][0];
         for(int j = 1; j < i; ++j) {
             int temp = total[j];
             total[j] = min(total[j], lastLine_prev) + triangle[i][j];
             lastLine_prev = temp;
         }
         
         total[i] = lastLine_prev + triangle[i][i];
     }
     
     return *min_element(total.begin(), total.end());
 }
Beispiel #22
0
 int maximumGap(vector<int>& nums) {
     if(nums.size()<2) return 0;
     int maxVal=*max_element(nums.begin(),nums.end());
     int minVal=*min_element(nums.begin(),nums.end());
     if(maxVal==minVal) return 0;
     int agGap=ceil((double)(maxVal-minVal)/nums.size());
     if(agGap==0) agGap++;
     vector<pair<int,int>> buckets(nums.size(),make_pair(INT_MIN,INT_MAX));
     for (auto val : nums){
         int bucketNum = (val - minVal) / agGap;
         if(bucketNum>=buckets.size()) bucketNum--;
         if (val > buckets[bucketNum].first)
             buckets[bucketNum].first = val; // 存储最大值
         if (val < buckets[bucketNum].second) buckets[bucketNum].second = val; // 存储最小值
     }
     int res=0;
     int preMax=buckets[0].first;
     for(int i=1;i<buckets.size();i++){
         if(buckets[i].first==INT_MIN) continue;
         res=max(res,buckets[i].second-preMax);
         preMax=buckets[i].first;
     }
     return res;
 }
Beispiel #23
0
int PeakPicker::findNextLeftValley( int iCurrentLeftValley )
{
	double dCurrentMinimumIntensity;
	double dCurrentValleyIntensity;
	int iOffset =  ( ProRataConfig::getPeakPickerWindowSize() - 1) / 2;

	bool bIsTrueValley = false;
	int iValleyMinusOffset;
	int iValleyPlusOffset;

	vector<double>::iterator itrBegin;
	itrBegin = vdCovarianceChro.begin();

	while ( (iCurrentLeftValley > iOffset ) && ( !bIsTrueValley ) )
	{
		iCurrentLeftValley--;

		dCurrentValleyIntensity = *( itrBegin + iCurrentLeftValley );

		iValleyMinusOffset = max( 0, iCurrentLeftValley - iOffset ); 
		iValleyPlusOffset = min( iChroLength -1,iCurrentLeftValley + iOffset ); 

		// Add one, because
		// min_element finds the smallest element in the range [first, last). 
		// Note the last element is not included.
		dCurrentMinimumIntensity = *( min_element(itrBegin + iValleyMinusOffset, 
					itrBegin + iValleyPlusOffset + 1 ) );

		if ( dCurrentMinimumIntensity >= dCurrentValleyIntensity )
			bIsTrueValley = true;
	}

	return iCurrentLeftValley;


}
void Canvas_Delegate_Tests::create_curve()
{
    std::vector<double> abscissa;
    std::vector<double> ordinates;

    double delta_min = deltas_.front();
    double delta_max = deltas_.back();
    unsigned int N = deltas_.size();

    double a = 2.5/(delta_max - delta_min);
    double b = -1.0 - a*delta_min;

    unsigned int i;
    for(i=0; i<N; i++)
    {
        abscissa.push_back(a*deltas_[i]+b);
    }

    double score_min = *min_element(overall_scores_.begin(), overall_scores_.end());
    double score_max = *max_element(overall_scores_.begin(), overall_scores_.end());

    a = 2.5/(score_max - score_min);
    b = -1.0 - a*score_min;
    for(i=0; i<N; i++)
    {
        ordinates.push_back(a*overall_scores_[i]+b);
    }

    curve_points_.clear();
    for(i=0; i<N; i++)
    {
        curve_points_.push_back(Point(complex_number(abscissa[i], ordinates[i])));
    }

    return;
}
Beispiel #25
0
void doit(const char *basename, const int nbins, const double lofit, const double hifit)
{

  // --- read in the data and create a vector with all the values
  // --- note that this code requires an duplicates to have already been cleaned out
  // --- this is automatically fixed with the new version of the DAQ/stepper code
  // --- but the user would do well do double check all output files anyway
  ifstream fin1(Form("TEMP/%s_Unaveraged_VMin1.txt",basename));
  double content;
  vector<double> voltage1;
  while(fin1>>content)
    {
      voltage1.push_back(content);
    }
  fin1.close();
  cout << voltage1.size() << endl;

  // --- do the same for SiPM2
  ifstream fin2(Form("TEMP/%s_Unaveraged_VMin2.txt",basename));
  vector<double> voltage2;
  while(fin2>>content)
    {
      voltage2.push_back(content);
    }
  fin2.close();
  cout << voltage2.size() << endl;

  // --- get the number of entries and the min and max
  int number = voltage1.size();
  double max = *max_element(voltage1.begin(),voltage1.end());
  double min = *min_element(voltage1.begin(),voltage1.end());
  cout << max << endl;
  cout << min << endl;
  // --- use the min and max to calculate a range for the histogram
  double newmax = min*-0.95;
  double newmin = max*-1.05 - newmax*0.1;
  // --- create the new histogram
  TH1D *h1 = new TH1D("h1","",nbins,newmin,newmax);
  TH1D *h2 = new TH1D("h2","",nbins,newmin,newmax);
  TH1D *hsum = new TH1D("hsum","",nbins,2*newmin,2*newmax);
  TH2D *hh1v2 = new TH2D("hh1v2","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
  TH2D *hhSvA = new TH2D("hhSvA","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
  TH2D *hh1v2_cut1 = new TH2D("hh1v2_cut1","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
  TH2D *hhSvA_cut1 = new TH2D("hhSvA_cut1","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
  TH2D *hh1v2_cut2 = new TH2D("hh1v2_cut2","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
  TH2D *hhSvA_cut2 = new TH2D("hhSvA_cut2","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
  vector<double> sum;
  vector<double> asym;
  // --- loop over the vector to fill the histogram
  for(int i=0; i<number; i++)
    {
      // --- SiPM1
      h1->Fill(-voltage1[i]);
      // --- SiPM2
      h2->Fill(-voltage2[i]);
      // --- SiPM1 vs SiPM2
      hh1v2->Fill(-voltage1[i],-voltage2[i]);
      // --- sum vs asymmetry
      double tempsum = -voltage1[i] + -voltage2[i];
      double tempasym = (voltage1[i] - voltage2[i]) / (-voltage1[i] + -voltage2[i]);
      hsum->Fill(tempsum);
      hhSvA->Fill(tempsum,tempasym);
      sum.push_back(tempsum);
      asym.push_back(tempasym);
      // --- now do some cuts...
      if(fabs(tempasym)<0.4)
	{
	  hh1v2_cut1->Fill(-voltage1[i],-voltage2[i]);
	  hhSvA_cut1->Fill(tempsum,tempasym);
	}
      if((voltage1[i]<(voltage2[i]+20*peconvert))&&(voltage2[i]<(voltage1[i]+20*peconvert)))
	{
	  hh1v2_cut2->Fill(-voltage1[i],-voltage2[i]);
	  hhSvA_cut2->Fill(tempsum,tempasym);
	}
    }

  // --- make a canvas and draw the histogram
  TCanvas *c1 = new TCanvas("c1","",800,800);

  // --- rescale the histograms from volts to photoelectrons
  h1->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  h1->GetXaxis()->SetTitle("Number of photoelectrons");
  h1->GetYaxis()->SetTitle("Counts");

  // --- define Landau function and draw
  // --- don't fit yet because the data have tons of ugly low voltage1 background
  double height = 1049;
  double mu = 23;
  double sigma = 3;
  //TF1 *fun = new TF1("fun","[0]*TMath::Landau(x,[1],[2])",newmin/peconvert,newmax/peconvert);
  TF1 *fun = new TF1("fun","[0]*TMath::Landau(x,[1],[2])",2*newmin/peconvert,2*newmax/peconvert);
  fun->SetParameter(0,height);
  fun->SetParameter(1,mu);
  fun->SetParameter(2,sigma);


  double bgscale = 650; // guess...





  c1->SetLogy(0);
  c1->Clear();
  hh1v2->Draw("colz");
  hh1v2->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2->GetXaxis()->SetTitle("#pe SiPM1");
  hh1v2->GetYaxis()->SetTitle("#pe SiPM2");
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_1v2.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_log.pdf",basename));

  hhSvA->Draw("colz");
  hhSvA->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  hhSvA->GetXaxis()->SetTitle("Sum");
  hhSvA->GetYaxis()->SetTitle("Asymmetry");
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_SvA.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_log.pdf",basename));


  // --- now for some cuts...

  c1->SetLogz(0);
  hh1v2_cut1->Draw("colz");
  hh1v2_cut1->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut1->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut1->GetXaxis()->SetTitle("#pe SiPM1");
  hh1v2_cut1->GetYaxis()->SetTitle("#pe SiPM2");
  TLatex *tex1 = new TLatex(0.2,0.8,"|Asymmetry|<0.4");
  tex1->SetTextSize(0.05);
  tex1->SetNDC(kTRUE);
  tex1->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1_log.pdf",basename));

  hhSvA_cut1->Draw("colz");
  hhSvA_cut1->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  hhSvA_cut1->GetXaxis()->SetTitle("Sum");
  hhSvA_cut1->GetYaxis()->SetTitle("Asymmetry");
  tex1->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1_log.pdf",basename));




  c1->SetLogz(0);
  hh1v2_cut2->Draw("colz");
  hh1v2_cut2->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut2->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut2->GetXaxis()->SetTitle("#pe SiPM1");
  hh1v2_cut2->GetYaxis()->SetTitle("#pe SiPM2");
  TLatex *tex2 = new TLatex(0.2,0.8,"SiPMA < SiPMB + 20");
  tex2->SetTextSize(0.05);
  tex2->SetNDC(kTRUE);
  tex2->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2_log.pdf",basename));

  hhSvA_cut2->Draw("colz");
  hhSvA_cut2->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  hhSvA_cut2->GetXaxis()->SetTitle("Sum");
  hhSvA_cut2->GetYaxis()->SetTitle("Asymmetry");
  tex2->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2_log.pdf",basename));



  hsum->SetLineColor(kBlack);
  hsum->SetLineWidth(2);
  hsum->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  //hsum->GetXaxis()->SetRangeUser(0.0,120.0);
  hsum->GetXaxis()->SetTitle("Number of photoelectrons SiPM1+SiPM2");
  hsum->Draw();
  c1->Print(Form("Cosmics/%s_temp.png",basename));
  c1->Print(Form("Cosmics/%s_temp.pdf",basename));
  hsum->SetMaximum(30);
  c1->Print(Form("Cosmics/%s_templow.png",basename));
  c1->Print(Form("Cosmics/%s_templow.pdf",basename));
  c1->SetLogy();
  hsum->SetMaximum(1.1*h1->GetBinContent(hsum->GetMaximumBin()));
  c1->Print(Form("Cosmics/%s_templog.png",basename));
  c1->Print(Form("Cosmics/%s_templog.pdf",basename));


  // ---------------------------------------------------------
  bgscale = 100;
  h1->Fit(fun,"","",lofit,hifit);
  fun->SetLineColor(kRed);
  fun->SetLineWidth(2);
  fun->Draw("same");

  cout << fun->GetChisquare() << "/" << fun->GetNDF() << endl;

  c1->SetLogy(0);
  c1->Print(Form("Cosmics/%s_tempfit.png",basename));
  c1->Print(Form("Cosmics/%s_tempfit.pdf",basename));
  h1->SetMaximum(175);
  c1->Print(Form("Cosmics/%s_templowfit.png",basename));
  c1->Print(Form("Cosmics/%s_templowfit.pdf",basename));
  h1->SetMaximum(100);
  c1->Print(Form("Cosmics/%s_tempLOWfit.png",basename));
  c1->Print(Form("Cosmics/%s_tempLOWfit.pdf",basename));
  c1->SetLogy(1);
  h1->SetMaximum(1.1*h1->GetBinContent(h1->GetMaximumBin()));
  c1->Print(Form("Cosmics/%s_templogfit.png",basename));
  c1->Print(Form("Cosmics/%s_templogfit.pdf",basename));

  c1->Clear();
  h1->Draw();
  double hax = fun->GetParameter(0);
  double mux = fun->GetParameter(1);
  double six = fun->GetParameter(2);
  fun->SetParameter(0,0.95*hax);
  fun->SetParameter(1,mux);
  fun->SetParameter(2,1.1*six);
  //fun->Draw("same");
  //h1->Fit(simplefun,"","",0,60);

  TF1 *fun2 = new TF1("fun2","([0]/sqrt(6.28))*TMath::Exp(-0.5*((x-[1])/[2] + TMath::Exp(-(x-[1])/[2])))",2*newmin/peconvert,2*newmax/peconvert);
  // fun2->SetParameter(0,hax);
  // fun2->SetParameter(1,mux);
  // fun2->SetParameter(2,six);
  // fun2->SetParameter(0,93);
  // fun2->SetParameter(1,35);
  // fun2->SetParameter(2,5);
  fun2->SetParameter(0,93);
  fun2->SetParameter(1,500);
  fun2->SetParameter(2,100);
  //fun2->SetLineColor(kBlack);

  h1->Fit(fun2,"","",lofit,hifit);
  fun2->Draw("same");

  cout << fun2->GetChisquare() << "/" << fun2->GetNDF() << endl;

  double par1 = fun2->GetParameter(1);
  TLine line(par1,0,par1,0.24*fun2->GetParameter(0));
  line.Draw();

  c1->SetLogy(0);
  c1->Print(Form("Cosmics/%s_tempffit.png",basename));
  c1->Print(Form("Cosmics/%s_tempffit.pdf",basename));
  h1->SetMaximum(25);
  c1->Print(Form("Cosmics/%s_templowffit.png",basename));
  c1->Print(Form("Cosmics/%s_templowffit.pdf",basename));
  h1->SetMaximum(0.3*fun2->GetParameter(0));
  TLatex *tex = new TLatex(0.6,0.8,Form("MPV = %.1f #pm %.1f",fun2->GetParameter(1),fun2->GetParError(1)));
  tex->SetNDC();
  tex->SetTextSize(0.05);
  tex->Draw();
  //h1->GetXaxis()->SetRangeUser(0.0,130.0); // new...
  c1->Print(Form("Cosmics/SmallTileCosmics_%s_tempLOWffit.png",basename));
  c1->Print(Form("Cosmics/SmallTileCosmics_%s_tempLOWffit.pdf",basename));
  c1->SetLogy(1);
  h1->SetMaximum(1.1*h1->GetBinContent(h1->GetMaximumBin()));
  c1->Print(Form("Cosmics/%s_templogffit.png",basename));
  c1->Print(Form("Cosmics/%s_templogffit.pdf",basename));



}
Beispiel #26
0
PAlgebraModDerived<type>::PAlgebraModDerived(const PAlgebra& _zMStar, long _r) 
  : zMStar(_zMStar), r(_r)

{
  long p = zMStar.getP();
  long m = zMStar.getM();

  // For dry-run, use a tiny m value for the PAlgebra tables
  if (isDryRun()) m = (p==3)? 4 : 3;

  assert(r > 0);

  ZZ BigPPowR = power_ZZ(p, r);
  assert(BigPPowR.SinglePrecision());
  pPowR = to_long(BigPPowR);

  long nSlots = zMStar.getNSlots();

  RBak bak; bak.save();
  SetModulus(p);

  // Compute the factors Ft of Phi_m(X) mod p, for all t \in T

  RX phimxmod;

  conv(phimxmod, zMStar.getPhimX()); // Phi_m(X) mod p

  vec_RX localFactors;

  EDF(localFactors, phimxmod, zMStar.getOrdP()); // equal-degree factorization

  

  RX* first = &localFactors[0];
  RX* last = first + localFactors.length();
  RX* smallest = min_element(first, last);
  swap(*first, *smallest);

  // We make the lexicographically smallest factor have index 0.
  // The remaining factors are ordered according to their representives.

  RXModulus F1(localFactors[0]); 
  for (long i=1; i<nSlots; i++) {
    unsigned long t =zMStar.ith_rep(i); // Ft is minimal polynomial of x^{1/t} mod F1
    unsigned long tInv = InvMod(t, m);  // tInv = t^{-1} mod m
    RX X2tInv = PowerXMod(tInv,F1);     // X2tInv = X^{1/t} mod F1
    IrredPolyMod(localFactors[i], X2tInv, F1);
  }
  /* Debugging sanity-check #1: we should have Ft= GCD(F1(X^t),Phi_m(X))
  for (i=1; i<nSlots; i++) {
    unsigned long t = T[i];
    RX X2t = PowerXMod(t,phimxmod);  // X2t = X^t mod Phi_m(X)
    RX Ft = GCD(CompMod(F1,X2t,phimxmod),phimxmod);
    if (Ft != localFactors[i]) {
      cout << "Ft != F1(X^t) mod Phi_m(X), t=" << t << endl;
      exit(0);
    }
  }*******************************************************************/

  if (r == 1) {
    build(PhimXMod, phimxmod);
    factors = localFactors;
    pPowRContext.save();

    // Compute the CRT coefficients for the Ft's
    crtCoeffs.SetLength(nSlots);
    for (long i=0; i<nSlots; i++) {
      RX te = phimxmod / factors[i]; // \prod_{j\ne i} Fj
      te %= factors[i];              // \prod_{j\ne i} Fj mod Fi
      InvMod(crtCoeffs[i], te, factors[i]); // \prod_{j\ne i} Fj^{-1} mod Fi
    }
  }
  else {
    PAlgebraLift(zMStar.getPhimX(), localFactors, factors, crtCoeffs, r);
    RX phimxmod1;
    conv(phimxmod1, zMStar.getPhimX());
    build(PhimXMod, phimxmod1);
    pPowRContext.save();
  }

  // set factorsOverZZ
  factorsOverZZ.resize(nSlots);
  for (long i = 0; i < nSlots; i++)
    conv(factorsOverZZ[i], factors[i]);

  genCrtTable();
  genMaskTable();
}
struct_Histogram histogram(vector<double> data, double binWidth)
{
	/*==============================================================
		This function creates a histogram from the provided
		data.

		The bins are automatically generated using binWidth
		and the minimum and maximum values of the data.
	
	==============================================================*/

	/*==============================================================
		First calculate the number of bins based on the maximum
		and minimum elements in the data, and the specified bin
		width
	==============================================================*/
	int numberOfBins = static_cast<int>( ceil( *max_element(data.begin(), data.end()) - *min_element(data.begin(), data.end()) / binWidth) + 1);

	/*==============================================================
		Pre-allocate the bin edges and bin counts which will be
		returned later.
	==============================================================*/
	struct_Histogram result;

	result.binEdges.assign(numberOfBins, 0.0);
	result.binCounts.assign(numberOfBins, 0.0);

	/*==============================================================
		Create the vector of bin edges.

		This is just the index x binwidth incrementing from the 
		first value in the data.

		The first value in the data specifies the lowest bin, as
		above.
	==============================================================*/
	for (int i = 0; i < result.binEdges.size(); ++i)
	{
		result.binEdges.at(i) = (binWidth * i) + *min_element(data.begin(), data.end());
	}

	/*==============================================================
		Now transfer the data into the histogram.

		This transfer function touches each data item exactly once.
	==============================================================*/
	for (int i = 0; i < data.size(); ++i)
	{
		//Determin the index of the correct bin
		int binIndex = static_cast<int>((data.at(i) - result.binEdges.at(0)) / binWidth);

		//Check we do not exceed the container
		if (binIndex >= result.binEdges.size())
		{
			binIndex = (int)result.binEdges.size() - 1;
		}

		//Increment the counts at this bin
		result.binCounts.at(binIndex)++;
	}

	/*==============================================================
		Return the histogram structure!
	==============================================================*/
	return result;
}
Beispiel #28
0
ttt_t integrator::get_min_dt()
{
	return (ttt_t)*min_element(passed_dt.begin(), passed_dt.end());
}
int internal_degree_and_membership (double mixing_parameter, int overlapping_nodes, int max_mem_num, int num_nodes, deque<deque<int> >  & member_matrix, 
                                    bool excess, bool defect,  deque<int> & degree_seq, deque<int> &num_seq, deque<int> &internal_degree_seq, bool fixed_range, int nmin, int nmax, double tau2) {
	
	
	
	
	
	if(num_nodes< overlapping_nodes) {
		
		cerr<<"\n***********************\nERROR: there are more overlapping nodes than nodes in the whole network! Please, decrease the former ones or increase the latter ones"<<endl;
		return -1;
	}
	
	
	// 
	member_matrix.clear();
	internal_degree_seq.clear();
	
	deque<double> cumulative;
	
	// it assigns the internal degree to each node -------------------------------------------------------------------------
	int max_degree_actual=0;		// maximum internal degree
    
	for (int i=0; i<degree_seq.size(); i++) {
		
		double interno=(1-mixing_parameter)*degree_seq[i];
		int int_interno=int(interno);
		
		
		if (ran4()<(interno-int_interno))
			int_interno++;
		
		if (excess) {
			
			while (   (  double(int_interno)/degree_seq[i] < (1-mixing_parameter) )  &&   (int_interno<degree_seq[i])   )
				int_interno++;
            
            
		}
		
		
		if (defect) {
			
			while (   (  double(int_interno)/degree_seq[i] > (1-mixing_parameter) )  &&   (int_interno>0)   )
				int_interno--;
            
            
		}
        
		
		
		
		internal_degree_seq.push_back(int_interno);
		
		
		if (int_interno>max_degree_actual)
			max_degree_actual=int_interno;
		
        
	}
	
	
	// it assigns the community size sequence -----------------------------------------------------------------------------
	
	powerlaw(nmax, nmin, tau2, cumulative);
	
	
	if (num_seq.empty()) {
		
		int _num_=0;
		if (!fixed_range && (max_degree_actual+1)>nmin) {
            
			_num_=max_degree_actual+1;			// this helps the assignment of the memberships (it assures that at least one module is big enough to host each node)
			num_seq.push_back(max_degree_actual+1);
            
		}
		
		
		while (true) {
			
			
			int nn=lower_bound(cumulative.begin(), cumulative.end(), ran4())-cumulative.begin()+nmin;
			
			if (nn+_num_<=num_nodes + overlapping_nodes * (max_mem_num-1) ) {
				
				num_seq.push_back(nn);				
				_num_+=nn;
                
			}
			else
				break;
			
			
		}
		
		num_seq[min_element(num_seq.begin(), num_seq.end()) - num_seq.begin()]+=num_nodes + overlapping_nodes * (max_mem_num-1) - _num_;
		
	}
	
	
	//cout<<"num_seq"<<endl;
	//prints(num_seq);
	
	int ncom=num_seq.size();
	
	//cout<<"\n----------------------------------------------------------"<<endl;
    
	/*
     cout<<"community sizes"<<endl;
     for (int i=0; i<num_seq.size(); i++)
     cout<<num_seq[i]<<" ";
     cout<<endl<<endl;
     //*/
	
    
	/*
     deque <int> first;
     for (int i=0; i<ncom; i++)
     member_matrix.push_back(first);
     
     
     
     // it puts the overlapping_nodes inside
     cout<<ncom<<endl;
     for (int i=degree_seq.size() - overlapping_nodes; i<degree_seq.size(); i++) {
     
     cout<<i<<endl;
     set<int> members;
     int hh=0;
     
     while(members.size()<max_mem_num) {
     
     int random_module=irand(ncom-1);
     
     if(member_matrix[random_module].size()!=num_seq[random_module])
     members.insert(random_module);
     
     hh++;
     
     if(hh>3*num_nodes) {
     cerr<<"it seems that the overlapping nodes need more communities that those I provided. Please increase the number of communities or decrease the number of overlapping nodes"<<endl;
     return -1;				
     }
     
     }
     
     
     for (set<int>::iterator its=members.begin(); its!=members.end(); its++)
     member_matrix[*its].push_back(i);
     
     }
     
     
     
     // it decides the memberships for the not overlapping nodes		
     
     int moment_module=0;
     for (int i=0; i<num_nodes - overlapping_nodes; i++) {
     
     while(member_matrix[moment_module].size()==num_seq[moment_module])
     moment_module++;
     
     member_matrix[moment_module].push_back(i);
     
     }
     
     
     
     */
	
	// I have to assign the degree to the nodes
	
	
	deque<int> member_numbers;
	for(int i=0; i<overlapping_nodes; i++)
		member_numbers.push_back(max_mem_num);
	for(int i=overlapping_nodes; i<degree_seq.size(); i++)
		member_numbers.push_back(1);
	
	//prints(member_numbers);
	//prints(num_seq);
	
	if(build_bipartite_network(member_matrix, member_numbers, num_seq)==-1) {
		
		cerr<<"it seems that the overlapping nodes need more communities that those I provided. Please increase the number of communities or decrease the number of overlapping nodes"<<endl;
		return -1;			
        
	}
    
	//printm(member_matrix);
	
	//cout<<"degree_seq"<<endl;
	//prints(degree_seq);
	
	//cout<<"internal_degree_seq"<<endl;
	//prints(internal_degree_seq);
    
	deque<int> available;
	for (int i=0; i<num_nodes; i++)
		available.push_back(0);
	
	for (int i=0; i<member_matrix.size(); i++) {
		for (int j=0; j<member_matrix[i].size(); j++)
			available[member_matrix[i][j]]+=member_matrix[i].size()-1;
	}
	
	//cout<<"available"<<endl;
	//prints(available);
	
	
	deque<int> available_nodes;
	for (int i=0; i<num_nodes; i++)
		available_nodes.push_back(i);
	
	
	deque<int> map_nodes;				// in the position i there is the new name of the node i
	for (int i=0; i<num_nodes; i++)
		map_nodes.push_back(0);
    
	
	for (int i=degree_seq.size()-1; i>=0; i--) {
		
		int & degree_here=internal_degree_seq[i];
		int try_this = irand(available_nodes.size()-1);
		
		int kr=0;
		while (internal_degree_seq[i] > available[available_nodes[try_this]]) {
            
			kr++;
			try_this = irand(available_nodes.size()-1);
			if(kr==3*num_nodes) {
                
				if(change_community_size(num_seq)==-1) {
					
					cerr<<"\n***********************\nERROR: this program needs more than one community to work fine"<<endl;
					return -1;
                    
				}
				
				cout<<"it took too long to decide the memberships; I will try to change the community sizes"<<endl;
                
				cout<<"new community sizes"<<endl;
				for (int i=0; i<num_seq.size(); i++)
					cout<<num_seq[i]<<" ";
				cout<<endl<<endl;
				
				return (internal_degree_and_membership(mixing_parameter, overlapping_nodes, max_mem_num, num_nodes, member_matrix, excess, defect, degree_seq, num_seq, internal_degree_seq, fixed_range, nmin, nmax, tau2));
                
                
			}
			
			
		}
		
		
		
		map_nodes[available_nodes[try_this]]=i;
		
		available_nodes[try_this]=available_nodes[available_nodes.size()-1];
		available_nodes.pop_back();
		
        
        
	}
	
	
	for (int i=0; i<member_matrix.size(); i++) {
		for (int j=0; j<member_matrix[i].size(); j++)
			member_matrix[i][j]=map_nodes[member_matrix[i][j]];	
	}
	
	
	
	for (int i=0; i<member_matrix.size(); i++)
		sort(member_matrix[i].begin(), member_matrix[i].end());
    
    
	return 0;
    
}
Beispiel #30
0
void DATA::GetLSCoefficient(const vector<int> &neigh, vector<double> &coeff1, vector<double> &coeff2, vector<double> &coeff3, vector<double> &coeff4){
	int n = neigh.size() - 1;
	double normal[3] = {0};
	double h[150] = {0};
	double k[150] = {0};
	double g[150] = {0};
	for ( int i = 1; i <= n; i++ ){
		h[i] = m_xp[neigh[i]] - m_xp[neigh[0]];
		normal[0] -= h[i];
		k[i] = m_yp[neigh[i]] - m_yp[neigh[0]];
		normal[1] -= k[i];
		g[i] = m_zp[neigh[i]] - m_zp[neigh[0]];
		normal[2] -= g[i];
	}
	m_normal_x[neigh[0]] = normal[0]/n;
	m_normal_y[neigh[0]] = normal[1]/n;
	m_normal_z[neigh[0]] = normal[2]/n;
	double angles[150] = {0};
	double length2 = sqrt(normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]);
	for (int i = 1; i <= n; i++){
		double dot = (h[i] * normal[0] + k[i] * normal[1] + g[i] * normal[2]);
		double length1 = sqrt(h[i] * h[i] + k[i] * k[i] + g[i] * g[i]);
		if (length2 < 0.2 * m_distance)
			angles[i] = 0;
		else{
			double costheta  = dot / (length1 * length2);
			angles[i] = acos(costheta);
		}
	}
	double angle = *(min_element(angles+1, angles+n));
	m_angle.push_back(angle);
	n=26;
	//initialize A
	double A[10][10];
	for (int i = 1; i <= 9; i++)
		for (int j = 1; j <= 9; j++)
			A[i][j] = 0;
	for (int index = 1; index <= n; index++){
		double a[10] = {0,h[index],k[index],g[index],0.5*h[index]*h[index],0.5*k[index]*k[index],0.5*g[index]*g[index],h[index]*k[index],h[index]*g[index],k[index]*g[index]};
		for (int i = 1; i <= 9; i++)
			for (int j = 1; j <= 9; j++)
				A[i][j] += a[i] * a[j];
	}



	//get L and L^T
	LAPACK_CF lapack_cf(9);
	for (int i = 1; i <= 9; i++)
		for (int j = 1; j <= 9; j++)
			lapack_cf.Set_A(i-1,j-1,A[i][j]);
	int status = lapack_cf.Solve();

	//get value of L
	double l[10][10];
	for (int i = 1; i < 10; i++)
		for (int j = 1; j <=i; j++)
			l[i][j] = lapack_cf.Get_L(i-1,j-1);
	//build M
	double M[10][10];
	double c[10] = {0};
	double d[30][10];
	for (int index = 1; index <= n; index++){
		double a[10] = {0,h[index],k[index],g[index],0.5*h[index]*h[index],0.5*k[index]*k[index],0.5*g[index]*g[index],
				h[index]*k[index],h[index]*g[index],k[index]*g[index]};
		for (int i = 1; i <=9; i++){
			d[index][i]=a[i];
			c[i]+=d[index][i];
		}
	}
	for ( int i = 1; i <= 9; i++ )
		for ( int j = 9; j >= 1; j-- ){
			if (j == i)
				M[i][j] = 1 / l[i][i];
			else if (j < i){
				double sum = 0;
				for (int kk = j; kk <= i - 1; kk++){
					sum += l[i][kk] * M[kk][j];
				}
				M[i][j] = -1 * sum / l[i][i];
			}
			else
				M[i][j] = 0;
		}
	double MT[10][10], AI[10][10];
	for (int i = 1; i< 10; i++)
		for (int j = 1; j < 10; j++){
			MT[i][j] = M[j][i];
			AI[i][j] = 0;
		}
	for (int i = 1; i < 10; i++)
		for (int j = 1; j < 10; j++)
			for (int kk = 1; kk < 10; kk++)
				AI[i][j] += MT[i][kk] * M[kk][j];

	//calculate coefficients
	for (int i = 1; i <= 9; i++){
		coeff1[0] += -(AI[4][i] + AI[5][i] + AI[6][i])*c[i];
		coeff2[0] += -AI[1][i]*c[i];
		coeff3[0] += -AI[2][i]*c[i];
		coeff4[0] += -AI[3][i]*c[i];
	}
	for ( int j = 1; j <= n; j++){
		for ( int i = 1; i <= 9; i++ ){
			coeff1[j] += (AI[4][i] + AI[5][i] + AI[6][i])* d[j][i];
			coeff2[j] += AI[1][i] * d[j][i];
			coeff3[j] += AI[2][i] * d[j][i];
			coeff4[j] += AI[3][i] * d[j][i];
		}
	}
	m_coefficient_laplacian[neigh[0]].assign(coeff1.begin(),coeff1.end());
	m_coefficient_dudx[neigh[0]].assign(coeff2.begin(),coeff2.end());
	m_coefficient_dudy[neigh[0]].assign(coeff3.begin(),coeff3.end());
	m_coefficient_dudz[neigh[0]].assign(coeff4.begin(),coeff4.end());

	// Calculating coefficients with ghost particle
	if (angle > PI / 4 - 0.00001){
		coeff1.assign(30,0);
		coeff2.assign(30,0);
		coeff3.assign(30,0);
		coeff4.assign(30,0);
		m_Boundary_Flag[neigh[0]] = 1;
		n++;
		h[n] = m_normal_x[neigh[0]];
		k[n] = m_normal_y[neigh[0]];
		g[n] = m_normal_z[neigh[0]];

		//initialize A
		for (int i = 1; i <= 9; i++)
			for (int j = 1; j <= 9; j++)
				A[i][j] = 0;
		for (int index = 1; index <= n; index++){
			double a[10] = {0,h[index],k[index],g[index],0.5*h[index]*h[index],0.5*k[index]*k[index],0.5*g[index]*g[index],
					h[index]*k[index],h[index]*g[index],k[index]*g[index]};
			for (int i = 1; i <= 9; i++)
				for (int j = 1; j <= 9; j++)
					A[i][j] += a[i] * a[j];
		}

		//get L and L^T
		for (int i = 1; i <= 9; i++)
			for (int j = 1; j <= 9; j++)
				lapack_cf.Set_A(i-1,j-1,A[i][j]);
		int status = lapack_cf.Solve();

		//get value of L
		for (int i = 1; i < 10; i++)
			for (int j = 1; j <=i; j++)
				l[i][j] = lapack_cf.Get_L(i-1,j-1);
		//build M
		for (int i = 1; i < 10; i++)
			c[i] = 0;
		for (int index = 1; index <= n; index++){
			double a[10] = {0,h[index],k[index],g[index],0.5*h[index]*h[index],0.5*k[index]*k[index],0.5*g[index]*g[index],
					h[index]*k[index],h[index]*g[index],k[index]*g[index]};
			for (int i = 1; i <=9; i++){
				d[index][i]=a[i];
				c[i]+=d[index][i];
			}
		}
		for ( int i = 1; i <= 9; i++ )
			for ( int j = 9; j >= 1; j-- ){
				if (j == i)
					M[i][j] = 1 / l[i][i];
				else if (j < i){
					double sum = 0;
					for (int kk = j; kk <= i - 1; kk++){
						sum += l[i][kk] * M[kk][j];
					}
					M[i][j] = -1 * sum / l[i][i];
				}
				else
					M[i][j] = 0;
			}
		double MT[10][10], AI[10][10];
		for (int i = 1; i< 10; i++)
			for (int j = 1; j < 10; j++){
				MT[i][j] = M[j][i];
				AI[i][j] = 0;
			}
		for (int i = 1; i < 10; i++)
			for (int j = 1; j < 10; j++)
				for (int kk = 1; kk < 10; kk++)
					AI[i][j] += MT[i][kk] * M[kk][j];

		//calculate coefficients
		for (int i = 1; i <= 9; i++){
			coeff1[0] += -(AI[4][i] + AI[5][i] + AI[6][i])*c[i];
			coeff2[0] += -AI[1][i]*c[i];
			coeff3[0] += -AI[2][i]*c[i];
			coeff4[0] += -AI[3][i]*c[i];
		}
		for ( int j = 1; j <= n; j++){
			for ( int i = 1; i <= 9; i++ ){
				coeff1[j] += (AI[4][i] + AI[5][i] + AI[6][i])* d[j][i];
				coeff2[j] += AI[1][i] * d[j][i];
				coeff3[j] += AI[2][i] * d[j][i];
				coeff4[j] += AI[3][i] * d[j][i];
			}
		}
		m_coefficient_laplacian_boundary.push_back(coeff1);
		m_coefficient_dudx_boundary.push_back(coeff2);
		m_coefficient_dudy_boundary.push_back(coeff3);
		m_coefficient_dudz_boundary.push_back(coeff4);
		m_num_of_boundary_par++;
	}
}