Exemplo n.º 1
0
 int peak(const vector<int> &num, const int left, const int right) {
     if (left > right)
         return -1;
     int mid = (left + right) / 2;
     if (isPeak(num, mid))
         return mid;
     else {
         int subleft = peak(num, left, mid - 1);
         if (subleft >= 0)
             return subleft;
         else return peak(num, mid + 1, right);
     }
 }
Exemplo n.º 2
0
int main() {
	int shu_zi_1 = 0, shu_zi_2 = 0, cao_zuo_fu = 0;
	push(5);
	push('+');
	push(3);
	shu_zi_2 = peak();
	pop();
	cao_zuo_fu = peak();
	pop();
	shu_zi_1 = peak();
	pop();
	if ('+' == cao_zuo_fu) {
		printf("计算结果是%d\n", shu_zi_1 + shu_zi_2);
	}
	return 0;
}
Exemplo n.º 3
0
void suspendTask(TCBptr task){
	TCBptr temp = NULL;
	temp = peak(YKRdyList);
	task = dequeue(&YKRdyList);
	task->state = DELAYED;
	if(YKSuspList == NULL){
		YKSuspList = task;//dequeue(&YKRdyList);
	}
	else if(task->delay <= YKSuspList->delay){
		task->next = YKSuspList;
		task->prev = NULL;
		YKSuspList->prev = task;
		YKSuspList->delay -= task->delay;
                YKSuspList = task;
	} else { /* Needs fixin later*/
		temp = YKSuspList;
		while(temp->next != NULL && temp->delay < task->delay){
			//printString("decrement delay\n");
			task->delay -= temp->delay;
			temp = temp->next;
		}
		if(temp->delay < task->delay) {			/* end of the list */
			task->delay -= temp->delay;
			temp->next = task;
			task->prev = temp;
		} else {					/* insert into list */
			temp->prev->next = task;
			task->prev = temp->prev;
			task->next = temp;
			temp->prev = task;
			temp->delay -= task->delay;
		}
	}
}
void accelerometer(){
    if (startuptempswitch == true){
     while (digitalRead(buttonApin) == LOW){}
    }
    test_all_meters();
    startuptempswitch = true;
    int accelx = ( getAccelerometerData (xval) );
    int accely = ( getAccelerometerData (yval) );
 
    pospeakcount++;
    negpeakcount++;
  
    peak(accely);
    Serial.print(0xFE, BYTE);   //command flag
    Serial.print(128, BYTE); 
    delay(60);
    printBarGraph(accely);
   Serial.print(0xFE, BYTE);   
   Serial.print(192, BYTE);  
    delay(60);
    Serial.print("x:");
    printAccelerometerReadout(accelx);
    Serial.print(" y: ");
    printAccelerometerReadout(accely);
}
Exemplo n.º 5
0
function run()
{
	vars Price = series(price());
	vars Trend = series(LowPass(Price,1000));
	
	Stop = 100*PIP;
	TakeProfit = 100*PIP;
	if(valley(Trend)) {
		//plotPriceProfile(50,0);
		enterLong();
	} else if(peak(Trend)) {
		//plotPriceProfile(50,PMINUS);
		enterShort();
	}

	PlotWidth = 1000;
	PlotHeight1 = 320;
	PlotScale = 4;
	
	//plotDay(Equity,PDIFF); 
	//plotWeek(Equity,PDIFF); 
	//plotMonth(Equity,PDIFF); 
	//plotYear(Equity,PDIFF); 
	plotTradeProfile(50);
}
Exemplo n.º 6
0
void test_top_char_element_in_stack(){
	List* list = create();
	char result;
	char num = 'a';
	char num2 = 'b';
	ASSERT(push(list, &num));
	ASSERT( push(list, &num2));
	result = *(char*)peak(list);
	ASSERT('b' == result);
}
Exemplo n.º 7
0
void test_top_element_in_stack(){
	List* list = create();
	int result;
	int num = 7;
	int num2 = 9;
	ASSERT(push(list, &num));
	ASSERT( push(list, &num2));
	result = *(int*)peak(list);
	ASSERT(9 == result);
}
Exemplo n.º 8
0
CMixerWidget::CMixerWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CMixerWidget)
{
    ui->setupUi(this);
    timercounter=0;
    connect(&peakTimer,SIGNAL(timeout()),this,SLOT(peak()));
    mapper=new QSignalMapper(this);
    connect(mapper,SIGNAL(mapped(int)),this,SLOT(setSoloChannel(int)));
    master=new CMasterWidget(this);
    master->hide();
    lo=new QGridLayout(this);
    lo->setSpacing(1);
    lo->setMargin(1);
    setLayout(lo);
}
Exemplo n.º 9
0
//2.5
void YKScheduler(int contextSaved) { /* Determines the highest priority ready task */
	TCBptr next;	
	if(!started)
		return;
	next = peak(YKRdyList);
	if(runningTask != NULL && runningTask->priority != next->priority){
		YKEnterMutex();
		YKCtxSwCount++;
		if(contextSaved ==  0) {
			YKSaveContext();
		}
		YKDispatcher(next);
	} else if (runningTask == NULL){
		YKDispatcher(next);
	}
}
Exemplo n.º 10
0
// Sets list of already centroided mass and intensity values. Converts them to CentroidPeak objects 
// These values must be sorted with respect to increasing mass
void CentroidData::set(
                       vector<double>& pCentroidMasses, // Centroided masses
                       vector<double>& pCentroidIntens  // Centroided intensities
)
{
  vector<double>::iterator mi,hi;
  
  fCentroidPeaks.clear();
  
  for (mi=pCentroidMasses.begin(),hi=pCentroidIntens.begin();mi!=pCentroidMasses.end();++mi,++hi) {
    CentroidPeak peak(*mi,*hi);
    fCentroidPeaks.push_back(peak);		
  }
  
  resetPeakGroupIter();
}
Exemplo n.º 11
0
 Base *StackFrame::pop()
 {
     SCOPED_WRITE_GUARD;
     
     assertMutationPossible();
     
     if(empty()) {
         if(!mParent || mParent->isFrozen())
             gfx_assert(false, str("stack underflow"));
         else
             return mParent->pop();
     }
         
     Base *value = peak();
     mStorage->removeLast();
     return value;
 }
Exemplo n.º 12
0
function tradeTrend()
{
	TimeFrame = 1;
	vars Price = series(price());
	vars Trend = series(LowPass(Price,optimize(500,300,700)));

	Stop = optimize(4,2,10) * ATR(100);
	Trail = 0;

	vars MMI_Raw = series(MMI(Price,300));
	vars MMI_Smooth = series(LowPass(MMI_Raw,500));
	
	if(falling(MMI_Smooth)) {
		if(valley(Trend))
			enterLong();
		else if(peak(Trend))
			enterShort();
	}
}
int main() {
    stack = (int *)calloc(10, sizeof(int));
    int userChoice, element;
    while(1){
        userChoice = readInput();
        switch(userChoice){
            case 1 : scanf("%d",&element);
                push(element);
                break;
            case 2 : pop();
                  break;
            case 3 :  peak();
                  break;
            case 4 : return  0;
                
            default : printf("Enter valid input\n");
        }
    }
    return 0;
}
Exemplo n.º 14
0
void AngleScan_V::FindPeaks()
{
    const unsigned int N = 90;
        /* Detect and save lower and upper edges around peaks in the histogram */
    const double width = fTheta->GetBinWidth(1);      /* Use first bin since fixed bin size */
    for (unsigned int bin = 1; bin <= N; bin++){
        if (fTheta->GetBinContent(bin) > 15 ){        /* Peak is detected */
            int Limitbin = GetLimitBin(fTheta, bin ); /* Find the upper edge of the peak */
            
            const double lower_edge = fTheta->GetBinCenter(bin) - 0.5*width;
            const double upper_edge = fTheta->GetBinCenter(Limitbin) + 0.5*width;
            
            TVector2 peak(lower_edge,upper_edge);

            fPeaks.push_back(peak);
                        
            bin = Limitbin;  /* Finding the next peak starting from this peak's upper edge */
            
        }
    }

    delete fTheta;
}
Exemplo n.º 15
0
Arquivo: main.cpp Projeto: elcos/SLUGS
#include "catch_default_main.hpp" // This brings in a default implementation for main()
#include "circBuffer.h"


TEST_CASE("Peak muestra el proximo elemento a retirar", "Peak debe de mostrar el proximo elemento que readFront nos daria"){

    struct CircBuffer buffer;
    int x;

    CBRef bp = &buffer;
    newCircBuffer(bp);

    writeBack(bp, 5);
    REQUIRE(peak(bp) == 5);

    writeBack(bp, 2);
    REQUIRE(peak(bp) == 5);
    x = readFront(bp);
    REQUIRE_FALSE(peak(bp) == 5);
    REQUIRE(peak(bp) == 2);


    writeBack(bp, 6);
    REQUIRE(peak(bp) == 2);
    x = readFront(bp);
    REQUIRE(peak(bp) == 6);
    x = readFront(bp);
    REQUIRE_FALSE(peak(bp) == 6);
    REQUIRE(peak(bp) == 0);
}
Exemplo n.º 16
0
    void doc_manager::populate(void)
    {
        
        add_class_descriptor(ml::k_base);
        
        add_class_descriptors(ml::k_base, {
            ml::k_classification,
            ml::k_regression
        });
        
        add_class_descriptors(ml::k_regression, {
            ml::k_ann,
            ml::k_linreg,
            ml::k_logreg
        });
        
        add_class_descriptors(ml::k_classification, {
            ml::k_svm,
            ml::k_adaboost,
            ml::k_anbc,
            ml::k_dtw,
            ml::k_hmmc,
            ml::k_softmax,
            ml::k_randforest,
            ml::k_mindist,
            ml::k_knn,
            ml::k_gmm,
            ml::k_dtree
        });
        
        add_class_descriptors(ml::k_feature_extraction, {
            ml::k_peak,
            ml::k_minmax,
            ml::k_zerox
        });
        
        descriptors[ml::k_ann].desc("Artificial Neural Network").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/MLP");
        descriptors[ml::k_linreg].desc("Linear Regression").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/LinearRegression");
        descriptors[ml::k_logreg].desc("Logistic Regression").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/LogisticRegression");
        descriptors[ml::k_peak].desc("Peak Detection").url("").num_outlets(1);
        descriptors[ml::k_minmax].desc("Minimum / Maximum Detection").url("").num_outlets(1);
        descriptors[ml::k_zerox].desc("Zero Crossings Detection").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/ZeroCrossingCounter");
        descriptors[ml::k_svm].desc("Support Vector Machine").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/SVM");
        descriptors[ml::k_adaboost].desc("Adaptive Boosting").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/AdaBoost");
        descriptors[ml::k_anbc].desc("Adaptive Naive Bayes Classifier").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/ANBC");
        descriptors[ml::k_dtw].desc("Dynamic Time Warping").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/DTW");
        descriptors[ml::k_hmmc].desc("Continuous Hidden Markov Model").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/HMM");
        descriptors[ml::k_softmax].desc("Softmax Classifier").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/Softmax");
        descriptors[ml::k_randforest].desc("Random Forests").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/RandomForests");
        descriptors[ml::k_mindist].desc("Minimum Distance").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/MinDist");
        descriptors[ml::k_knn].desc("K Nearest Neighbour").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/KNN");
        descriptors[ml::k_gmm].desc("Gaussian Mixture Model").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/GMMClassifier");
        descriptors[ml::k_dtree].desc("Decision Trees").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/DecisionTree");
        
        for (auto& desc : {&descriptors[ml::k_hmmc], &descriptors[ml::k_dtw]})
        {
            desc->notes(
                        "add and map messages for time series should be delimited with record messages, e.g. record 1, add 1 40 50, add 1 41 50, record 0"
            );
        }
        
        // base descriptor
        message_descriptor add(
                              "add",
                              "list comprising a class id followed by n features, <class> <feature 1> <feature 2> etc",
                               "1 0.2 0.7 0.3 0.1"
                              );

        
        message_descriptor train(
                                "train",
                                "train the model based on vectors added with 'add'"
                                );
        
        message_descriptor map(
                              "map",
                              "generate the output value(s) for the input feature vector",
                               "0.2 0.7 0.3 0.1"
                              );
        
        message_descriptor write(
                                 "write",
                                 "write training data and / or model, first argument gives path to write file",
                                 "/path/to/my_ml-lib_data"
                                 );
        
        message_descriptor read(
                                "read",
                                "read training data and / or model, first argument gives path to the read file",
                                "/path/to/my_ml-lib_data"
                                );
        
        message_descriptor clear(
                                 "clear",
                                 "clear the stored training data and model"
                                 );
        
        message_descriptor help(
                               "help",
                               "post usage statement to the console"
                               );
        
        valued_message_descriptor<int> scaling(
                                               "scaling",
                                               "sets whether values are automatically scaled",
                                               {0, 1},
                                               1
                                               );
        
        valued_message_descriptor<int> record(
                                              "record",
                                              "start or stop time series recording for a single example of a given class",
                                              {0, 1},
                                              0
                                              );
        
        ranged_message_descriptor<float> training_rate(
                                                       "training_rate",
                                                       "set the learning rate, used to update the weights at each step of learning algorithms such as stochastic gradient descent.",
                                                       0.01,
                                                       1.0,
                                                       0.1
                                                       );
        
        ranged_message_descriptor<float> min_change(
                                                    "min_change",
                                                    "set the minimum change that must be achieved between two training epochs for the training to continue",
                                                    0.0,
                                                    1.0,
                                                    1.0e-5
                                                    );
        
        ranged_message_descriptor<int> max_iterations(
                                                      "max_iterations",
                                                      "set the maximum number of training iterations",
                                                      0,
                                                      1000,
                                                      100
                                                      );
        
        record.insert_before = "add";
        descriptors[ml::k_base].add_message_descriptor(add, write, read, train, clear, map, help, scaling, training_rate, min_change, max_iterations);

        // generic classification descriptor
        valued_message_descriptor<bool> null_rejection(
                                                       "null_rejection",
                                                       "toggle NULL rejection off or on, when 'on' classification results below the NULL-rejection threshold will be discarded",
                                                       {false, true},
                                                       true
                                                       );
        
        ranged_message_descriptor<float> null_rejection_coeff(
                                                              "null_rejection_coeff",
                                                              "set a multiplier for the NULL-rejection threshold ",
                                                              0.1,
                                                              1.0,
                                                              0.9
                                                              );
        
        valued_message_descriptor<int> probs(
                                             "probs",
                                             "determines whether probabilities are sent from the right outlet",
                                             {0, 1},
                                             0
                                             );
        
        descriptors[ml::k_classification].add_message_descriptor(null_rejection_coeff, probs, null_rejection);
        
        // generic feature extraction descriptor
//        descriptors[ml::k_feature_extraction].add_message_descriptor(null_rejection_coeff, null_rejection);

        // generic regression descriptor
       
        
//        descriptors[ml::k_regression].add_message_descriptor(training_rate, min_change, max_iterations);
        
        // Object-specific descriptors
        //-- Regressifiers
        //---- ann
        valued_message_descriptor<ml::data_type> mode("mode",
                                                      "set the mode of the ANN, " + std::to_string(ml::LABELLED_CLASSIFICATION) + " for classification, " + std::to_string(ml::LABELLED_REGRESSION) + " for regression",
                                                      {ml::LABELLED_CLASSIFICATION, ml::LABELLED_REGRESSION, ml::LABELLED_TIME_SERIES_CLASSIFICATION},
                                                      ml::defaults::data_type
                                                      );
        
        
        message_descriptor add_ann(
                              "add",
                              "class id followed by n features, <class> <feature 1> <feature 2> etc when in classification mode or N output values followed by M input values when in regression mode (N = num_outputs)",
                                   "1 0.2 0.7 0.3 0.1"

                              );
      
        ranged_message_descriptor<int> num_outputs(
                                                   "num_outputs",
                                                   "set the number of neurons in the output layer",
                                                   1,
                                                   1000,
                                                   ml::defaults::num_output_dimensions
                                                   );
        
        ranged_message_descriptor<int> num_hidden(
                                                  "num_hidden",
                                                  "set the number of neurons in the hidden layer",
                                                  1,
                                                  1000,
                                                  ml::defaults::num_hidden_neurons
                                                  );
        
        ranged_message_descriptor<int> min_epochs(
                                                  "min_epochs",
                                                  "setting the minimum number of training iterations",
                                                  1,
                                                  1000,
                                                  10
                                                  );
        
        // TODO: check if the "epochs" are still needed or if we can use "iterations" as inherited from ml_regression
        ranged_message_descriptor<int> max_epochs(
                                                  "max_epochs",
                                                  "setting the maximum number of training iterations",
                                                  1,
                                                  10000,
                                                  100
                                                  );

        ranged_message_descriptor<float> momentum(
                                                  "momentum",
                                                  "set the momentum",
                                                  0.0,
                                                  1.0,
                                                  0.5
                                                  );
        
        ranged_message_descriptor<float> gamma(
                                                  "gamma",
                                                  "set the gamma",
                                                  0.0,
                                                  10.0,
                                                  2.0
                                                  );
        
        // TODO: have optional value_labels for value labels
        valued_message_descriptor<int> input_activation_function(
                                                                 "input_activation_function",
                                                                 "set the activation function for the input layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID",
                                                                 {0, 1, 2},
                                                                 0
                                                                 );
        
        valued_message_descriptor<int> hidden_activation_function(
                                                                 "hidden_activation_function",
                                                                 "set the activation function for the hidden layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID",
                                                                 {0, 1, 2},
                                                                 0
                                                                 );
        
        valued_message_descriptor<int> output_activation_function(
                                                                 "output_activation_function",
                                                                 "set the activation function for the output layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID",
                                                                 {0, 1, 2},
                                                                 0
                                                                 );

                                                                 
        ranged_message_descriptor<int> rand_training_iterations(
                                                                 "rand_training_iterations",
                                                                 "set the number of random training iterations",
                                                                 0,
                                                                 1000,
                                                                 10
                                                                 );

        valued_message_descriptor<bool> use_validation_set(
                                                           "use_validation_set",
                                                           "set whether to use a validation training set",
                                                           {false, true},
                                                           true
                                                           );
        
        ranged_message_descriptor<int> validation_set_size(
                                                           "validation_set_size",
                                                           "set the size of the validation set",
                                                           1,
                                                           100,
                                                           20
                                                           );
        
        valued_message_descriptor<bool> randomize_training_order(
                                                           "randomize_training_order",
                                                           "sets whether to randomize the training order",
                                                           {false, true},
                                                           false
                                                           );
        
        
        descriptors[ml::k_ann].add_message_descriptor(add_ann, probs, mode, null_rejection, null_rejection_coeff, num_outputs, num_hidden, min_epochs, max_epochs, momentum, gamma, input_activation_function, hidden_activation_function, output_activation_function, rand_training_iterations, use_validation_set, validation_set_size, randomize_training_order);
        
        
        //-- Classifiers
        //---- ml.svm
        ranged_message_descriptor<int> type(
                                            "type",
                                            "set SVM type,"
                                            " 0:C-SVC (multi-class),"
                                            " 1:nu-SVC (multi-class),"
                                            " 2:one-class SVM,"
                                           // " 3:epsilon-SVR (regression),"
                                           // " 4:nu-SVR (regression)"
                                            ,
                                            0,
                                            2,
                                            0
                                            //        "	0 -- C-SVC		(multi-class classification)\n"
                                            //        "	1 -- nu-SVC		(multi-class classification)\n"
                                            //        "	2 -- one-class SVM\n"
                                            //        "	3 -- epsilon-SVR	(regression)\n"
                                            //        "	4 -- nu-SVR		(regression)\n"

                                            );
        
        ranged_message_descriptor<int> kernel(
                                              "kernel",
                                              "set type of kernel function, "
                                              "0:linear, " // (u'*v),"
                                              "1:polynomial, " // (gamma*u'*v + coef0)^degree,"
                                              "2:radial basis function, " //: exp(-gamma*|u-v|^2),"
                                              "3:sigmoid, " //  tanh(gamma*u'*v + coef0),"
                                              "4:precomputed kernel (kernel values in training_set_file)",
                                              0,
                                              4,
                                              0
                                              //        "	0 -- linear: u'*v\n"
                                              //        "	1 -- polynomial: (gamma*u'*v + coef0)^degree\n"
                                              //        "	2 -- radial basis function: exp(-gamma*|u-v|^2)\n"
                                              //        "	3 -- sigmoid: tanh(gamma*u'*v + coef0)\n"
                                              //        "	4 -- precomputed kernel (kernel values in training_set_file)\n"
                                              );
        
        ranged_message_descriptor<float> degree(
                                              "degree",
                                              "set degree in kernel function",
                                              0,
                                              20,
                                              3
                                              );
        
        ranged_message_descriptor<float> svm_gamma(
                                              "gamma",
                                              "set gamma in kernel function",
                                              0.0,
                                              1.0,
                                              0.5
                                              );
        
        ranged_message_descriptor<float> coef0(
                                               "coef0",
                                               "coef0 in kernel function",
                                               INFINITY * -1.f, INFINITY,
                                               0.0
                                               );
        
        ranged_message_descriptor<float> cost(
                                               "cost",
                                               "set the parameter C of C-SVC, epsilon-SVR, and nu-SVR",
                                               INFINITY * -1.f, INFINITY,
                                               1.0
                                               );
        
        ranged_message_descriptor<float> nu(
                                              "nu",
                                              "set the parameter nu of nu-SVC, one-class SVM, and nu-SVR",
                                              INFINITY * -1.f, INFINITY,
                                              0.5
                                              );
        
        message_descriptor cross_validation(
                                            "cross_validation",
                                            "perform cross validation"
                                            );
        
        ranged_message_descriptor<int> num_folds(
                                                 "num_folds",
                                                 "set the number of folds used for cross validation",
                                                 1, 100,
                                                 10
                                                 );
        
        descriptors[ml::k_svm].add_message_descriptor(cross_validation, num_folds, type, kernel, degree, svm_gamma, coef0, cost, nu);
        
        //---- ml.adaboost        
        ranged_message_descriptor<int> num_boosting_iterations(
                                                                "num_boosting_iterations",
                                                               "set the number of boosting iterations that should be used when training the model",
                                                               0,
                                                               200,
                                                               20
                                                               );
        
        valued_message_descriptor<int> prediction_method(
                                                        "prediction_method",
                                                         "set the Adaboost prediction method, 0:MAX_VALUE, 1:MAX_POSITIVE_VALUE",
                                                         {GRT::AdaBoost::MAX_VALUE, GRT::AdaBoost::MAX_POSITIVE_VALUE},
                                                         GRT::AdaBoost::MAX_VALUE
                                                         
        );
        
        valued_message_descriptor<int> set_weak_classifier(
                                                           "set_weak_classifier",
                                                           "sets the weak classifier to be used by Adaboost, 0:DECISION_STUMP, 1:RADIAL_BASIS_FUNCTION",
                                                           {ml::weak_classifiers::DECISION_STUMP, ml::weak_classifiers::RADIAL_BASIS_FUNCTION},
                                                           ml::weak_classifiers::DECISION_STUMP
                                                           );
        
        valued_message_descriptor<int> add_weak_classifier(
                                                           "add_weak_classifier",
                                                           "add a weak classifier to the list of classifiers used by Adaboost",
                                                           {ml::weak_classifiers::DECISION_STUMP, ml::weak_classifiers::RADIAL_BASIS_FUNCTION},
                                                           ml::weak_classifiers::DECISION_STUMP
                                                           );

        descriptors[ml::k_adaboost].add_message_descriptor(num_boosting_iterations, prediction_method, set_weak_classifier, add_weak_classifier);
        
        //---- ml.anbc
        message_descriptor weights("weights",
                                   "vector of 1 integer and N floating point values where the integer is a class label and the floats are the weights for that class. Sending weights with a vector size of zero clears all weights"
                                   );
        
        descriptors[ml::k_anbc].add_message_descriptor(weights);
        
        //---- ml.dtw
        valued_message_descriptor<int> rejection_mode(
                                                      "rejection_mode",
                                                      "sets the method used for null rejection, 0:TEMPLATE_THRESHOLDS, 1:CLASS_LIKELIHOODS, 2:THRESHOLDS_AND_LIKELIHOODS",
                                                      {GRT::DTW::TEMPLATE_THRESHOLDS, GRT::DTW::CLASS_LIKELIHOODS, GRT::DTW::THRESHOLDS_AND_LIKELIHOODS},
                                                      GRT::DTW::TEMPLATE_THRESHOLDS
                                                      );
        
        ranged_message_descriptor<float> warping_radius(
                                                        "warping_radius",
                                                        "sets the radius of the warping path, which is used if the constrain_warping_path is set to 1",
                                                        0.0,
                                                        1.0,
                                                        0.2
                                                        );
        
        valued_message_descriptor<bool> offset_time_series(
                                                           "offset_time_series",
                                                           "set if each timeseries should be offset by the first sample in the time series",
                                                           {false, true},
                                                           false
                                                           );
        
        valued_message_descriptor<bool> constrain_warping_path(
                                                           "constrain_warping_path",
                                                           "sets the warping path should be constrained to within a specific radius from the main diagonal of the cost matrix",
                                                           {false, true},
                                                           true
                                                           );
        
        valued_message_descriptor<bool> enable_z_normalization(
                                                               "enable_z_normalization",
                                                               "turn z-normalization on or off for training and prediction",
                                                               {false, true},
                                                               false
                                                               );
        
        valued_message_descriptor<bool> enable_trim_training_data(
                                                               "enable_trim_training_data",
                                                               "enabling data trimming prior to training",
                                                               {false, true},
                                                               false
                                                               );
  
        descriptors[ml::k_dtw].insert_message_descriptor(record);
        descriptors[ml::k_dtw].add_message_descriptor(rejection_mode, warping_radius, offset_time_series, constrain_warping_path, enable_z_normalization, enable_trim_training_data);
        
        //---- ml.hmmc
        valued_message_descriptor<int> model_type(
                                                  "model_type",
                                                  "set the model type used, 0:ERGODIC, 1:LEFTRIGHT",
                                                  {HMM_ERGODIC, HMM_LEFTRIGHT},
                                                  HMM_LEFTRIGHT
                                                  );
        
        ranged_message_descriptor<int> delta(
                                             "delta",
                                             "control how many states a model can transition to if the LEFTRIGHT model type is used",
                                             1,
                                             100,
                                             11
                                             );
        
        ranged_message_descriptor<int> max_num_iterations(
                                                          "max_num_iterations",
                                                          "set the maximum number of training iterations",
                                                          1,
                                                          1000,
                                                          100
                                                          );
        
        ranged_message_descriptor<int> committee_size(
                                                      "committee_size",
                                                      "set the committee size for the number of votes combined to make a prediction",
                                                      1,
                                                      1000,
                                                      5
                                                      );
        
        ranged_message_descriptor<int> downsample_factor(
                                                      "downsample_factor",
                                                         "set the downsample factor for the resampling of each training time series. A factor of 5 will result in each time series being resized (smaller) by a factor of 5",
                                                      1,
                                                      1000,
                                                      5
                                                      );
        
        descriptors[ml::k_hmmc].insert_message_descriptor(record);
        descriptors[ml::k_hmmc].add_message_descriptor(model_type, delta, max_num_iterations, committee_size, downsample_factor);
        
        //---- ml.softmax
        
        //---- ml.randforest
        ranged_message_descriptor<int> num_random_splits(
                                                         "num_random_splits",
                                                         "set the number of steps that will be used to search for the best spliting value for each node",
                                                         1,
                                                         1000,
                                                         100
                                                         );
        
        ranged_message_descriptor<int> min_samples_per_node2(
                                                            "min_samples_per_node",
                                                            "set the minimum number of samples that are allowed per node",
                                                            1,
                                                            100,
                                                            5
                                                            );
        
        ranged_message_descriptor<int> max_depth(
                                                 "max_depth",
                                                 "sets the maximum depth of the tree, any node that reaches this depth will automatically become a leaf node",
                                                 1,
                                                 100,
                                                 10
                                                 );

        descriptors[ml::k_randforest].add_message_descriptor(num_random_splits, min_samples_per_node2, max_depth);
        
        //----ml.mindist
        ranged_message_descriptor<int> num_clusters(
                                                    "num_clusters",
                                                    "set how many clusters each model will try to find during the training phase",
                                                    1,
                                                    100,
                                                    10
                                                    );

        descriptors[ml::k_mindist].add_message_descriptor(num_clusters);
                
        //---- ml.knn
//        "best_k_value_search:\tbool (0 or 1) set whether k value search is enabled or not (default 0)\n";

        ranged_message_descriptor<int> k(
                                         "k",
                                         "sets the K nearest neighbours that will be searched for by the algorithm during prediction",
                                         1,
                                         500,
                                         10
                                         );
        
        ranged_message_descriptor<int> min_k_search_value(
                                         "min_k_search_value",
                                         "set the minimum K value to use when searching for the best K value",
                                         1,
                                         500,
                                         1
                                         );
        
        ranged_message_descriptor<int> max_k_search_value(
                                                          "max_k_search_value",
                                                          "set the maximum K value to use when searching for the best K value",
                                                          1,
                                                          500,
                                                          10
                                                          );
        
        valued_message_descriptor<bool> best_k_value_search(
                                                            "best_k_value_search",
                                                            "set whether k value search is enabled or not",
                                                            {false, true},
                                                            false
                                                            );
        
        descriptors[ml::k_knn].add_message_descriptor(k, min_k_search_value, max_k_search_value, best_k_value_search);
        
        //---- ml.gmm
        ranged_message_descriptor<int> num_mixture_models(
                                                          "num_mixture_models",
                                                          "sets the number of mixture models used for class",
                                                          1,
                                                          20,
                                                          2
                                                          );

        descriptors[ml::k_gmm].add_message_descriptor(num_mixture_models);

        //---- ml.dtree
        valued_message_descriptor<bool> training_mode(
                                                      "training_mode",
                                                      "set the training mode",
                                                      {GRT::Tree::BEST_ITERATIVE_SPILT, GRT::Tree::BEST_RANDOM_SPLIT},
                                                      GRT::Tree::BEST_ITERATIVE_SPILT
                                                      );
        
        ranged_message_descriptor<int> num_splitting_steps(
                                                          "num_splitting_steps",
                                                          "set the number of steps that will be used to search for the best spliting value for each node",
                                                          1,
                                                          500,
                                                          100
                                                          );
        
        ranged_message_descriptor<int> min_samples_per_node(
                                                          "min_samples_per_node",
                                                          "sets the minimum number of samples that are allowed per node, if the number of samples at a node is below this value then the node will automatically become a leaf node",
                                                          1,
                                                          100,
                                                          5
                                                          );
        
        ranged_message_descriptor<int> dtree_max_depth(
                                                 "max_depth",
                                                 "sets the maximum depth of the tree, any node that reaches this depth will automatically become a leaf node",
                                                 1,
                                                 100,
                                                 10
                                                 );
        
        valued_message_descriptor<bool> remove_features_at_each_split(
                                                               "remove_features_at_each_split",
                                                               "set if a feature is removed at each spilt so it can not be used again",
                                                               {false, true},
                                                               false
                                                               );
        descriptors[ml::k_dtree].add_message_descriptor(training_mode, num_splitting_steps, min_samples_per_node, dtree_max_depth, remove_features_at_each_split);

        //-- Feature extraction
        
        //---- ml.peak
        ranged_message_descriptor<int> search_window_size(
                                                          "search_window_size",
                                                          "set the search window size in values",
                                                          1,
                                                          500,
                                                          5
                                                          );
        
        ranged_message_descriptor<float> peak(
                                              "float",
                                              "set the current value of the peak detector, a bang will be output when a peak is detected",
                                              INFINITY * -1.f, INFINITY,
                                              1
                                              );
        
        message_descriptor reset(
                                "reset",
                                "reset the peak detector"
                                );
        
        message_descriptor peak_help(
                                 "help",
                                 "post usage statement to the console"
                                 );


        descriptors[ml::k_peak].add_message_descriptor(peak, reset, search_window_size, peak_help);
        
        //---- ml.minmax
        
        message_descriptor input(
                                 "list",
                                 "list of float values in which to find minima and maxima",
                                 "0.1 0.5 -0.3 0.1 0.2 -0.1 0.7 0.1 0.3"
                                 );
        
        ranged_message_descriptor<float> minmax_delta(
                                                      "delta",
                                                      "setting the minmax delta. Input values will be considered to be peaks if they are greater than the previous and next value by at least the delta value",
                                                      0,
                                                      1,
                                                      0.1
                                                      );
        
        descriptors[ml::k_minmax].add_message_descriptor(input, minmax_delta);
        
        //---- ml.zerox
        
        valued_message_descriptor<float> zerox_map(
                                                   "map",
                                                   "a stream of input values in which to detect zero crossings",
                                                   0.5
                                                   );
        
        ranged_message_descriptor<float> dead_zone_threshold(
                                                             "dead_zone_threshold",
                                                             "set the dead zone threshold",
                                                             0.f,
                                                             1.f,
                                                             0.01f
                                                             );
        
        ranged_message_descriptor<int> zerox_search_window_size(
                                                          "search_window_size",
                                                          "set the search window size in values",
                                                          1,
                                                          500,
                                                          20
                                                          );
        
        descriptors[ml::k_zerox].add_message_descriptor(zerox_map, dead_zone_threshold, zerox_search_window_size);
    }
Exemplo n.º 17
0
void nemo_main()
{
    int    i, dir, nrad, npots=0, ltype, ndim = NDIM, nx, ny, ns, ndat, nret;
    int    cols[4], n, idx, idx_max;
    real   pmax, symsize, rr, omk_max = 0.0, omk_rmax;
    real   rad[MAXPT], *vel, *vel1, *vel2, *vel3, *vel4, *curve;
    real   *ome, *kap, *opk, *omk, r0l[MAXPT+2], omega, *f;
    real   inrad[MAXPT], invel[MAXPT], inrade[MAXPT], invele[MAXPT];
    double pos[3], acc[3], pot, time = 0.0;
/*    char   *fmt, s[20], pfmt[256];    */
    char   headline[256], fmt1[80];
    string axis, mode, infile, plotlabel;
    stream instr;
    bool   Qtab, Qplot, Qome, Qvel, Qlv, Qin, QoILR;

    mode = getparam("mode");
    n = getiparam("n");
    plotlabel = getparam("headline");
    sprintf(fmt1,"%s ",getparam("format"));
    Qome = (*mode == 'o');      /*  options are: velocity|omega|lv */
    Qlv = (*mode == 'l');
    Qvel = (*mode == 'v');
    Qtab = getbparam("tab");
    Qplot = getbparam("plot");
    infile = getparam("in");
    Qin =  (*infile != 0);
    if (Qin) {
        nret = nemoinpi(getparam("cols"),cols,4);
        if (nret<0 || nret > 4) error("cols= requires 4 numbers");
        for (i=nret; i<4; i++)
            cols[i] = 0;
        instr = stropen(infile,"r");
        ndat = read_table(instr,MAXPT,inrad,invel,inrade,invele,cols);
        strclose(instr);
    }
    
    mypot1 = get_potential(getparam("name1"),getparam("pars1"),getparam("file1"));
    omega = get_pattern();
    dprintf(0,"Pattern speed: %f\n",omega);
    mypot2 = get_potential(getparam("name2"),getparam("pars2"),getparam("file2"));
    mypot3 = get_potential(getparam("name3"),getparam("pars3"),getparam("file3"));
    mypot4 = get_potential(getparam("name4"),getparam("pars4"),getparam("file4"));
    headline[0] = '\0';         /* accumulate headline */
    if (mypot1) {
        strcat(headline,getparam("name1"));
        strcat(headline,"(");
        strcat(headline,getparam("pars1"));
        strcat(headline,")");
        npots++;
    } 
    if (mypot2) {
        strcat(headline,getparam("name2"));
        strcat(headline,"(");
        strcat(headline,getparam("pars2"));
        strcat(headline,") ");
        npots++;
    }
    if (mypot3) {
        strcat(headline,getparam("name3"));
        strcat(headline,"(");
        strcat(headline,getparam("pars3"));
        strcat(headline,") ");
        npots++;
    }
    if (mypot4) {
        strcat(headline,getparam("name4"));
        strcat(headline,"(");
        strcat(headline,getparam("pars4"));
        strcat(headline,")");
        npots++;
    }

    nrad = nemoinpr(getparam("radii"),rad,MAXPT);   /* get radii */
    if (nrad <= 0)
        warning("Using %d radii is not very productive",nrad);
    vel  = (real *) allocate(sizeof(real) * nrad);  /* allocate stuff */
    vel1 = (real *) allocate(sizeof(real) * nrad);
    vel2 = (real *) allocate(sizeof(real) * nrad);
    vel3 = (real *) allocate(sizeof(real) * nrad);
    vel4 = (real *) allocate(sizeof(real) * nrad);
    if (Qome) {
        ome = (real *) allocate(4 * sizeof(real) * nrad);  /* plus spline */
        kap = (real *) allocate(sizeof(real) * nrad);
        opk = (real *) allocate(sizeof(real) * nrad);
        omk = (real *) allocate(sizeof(real) * nrad);
    } 

    axis = getparam("axis");
    dir = 0;
    if (*axis == 'x') dir=0;
    if (*axis == 'y') dir=1;
    if (*axis == 'z') dir=2;
    if (dir>NDIM) error("Axis %s not supported in NDIM=%d",axis,NDIM);

    pmax = 0.0;

    for (i=0; i<nrad; i++) {            /* loop to compute */
        CLRV(pos);                      /* clear positions */
        pos[dir] = rad[i];              /* set the right axis */
        vel[i] = 0.0;
        if (mypot1) {
            CLRV(acc);
            (*mypot1) (&ndim,pos,acc,&pot,&time);
            vel1[i] = -rad[i] * acc[dir];
            vel[i] += vel1[i];
            vel1[i] = sqrt(vel1[i]);        
        }
        if (mypot2) {
            CLRV(acc);
            (*mypot2) (&ndim,pos,acc,&pot,&time);
            vel2[i] = -rad[i] * acc[dir];
            vel[i] += vel2[i];
	    vel2[i] = sqrt(vel2[i]);        
        }
        if (mypot3) {
            CLRV(acc);
            (*mypot3) (&ndim,pos,acc,&pot,&time);
            vel3[i] = -rad[i] * acc[dir];
            vel[i] += vel3[i];
	    vel3[i] = sqrt(vel3[i]);        
        }
        if (mypot4) {
            CLRV(acc);
            (*mypot4) (&ndim,pos,acc,&pot,&time);
            vel4[i] = -rad[i] * acc[dir];
            vel[i] += vel4[i];
            vel4[i] = sqrt(vel4[i]);        
        }
        vel[i]  = sqrt(vel[i]);        
    }
    if (Qome) {
	lindblad(nrad,rad,vel,ome,kap,opk,omk,n);
        if (omega> 0.0) {                               /* compute resonances */
            f = opk;
            idx = nrad-1;
            if (omega < f[idx]) {
                warning("Radii not far enough out for OLR: %g",f[idx]);
                f = ome;
                if (omega < f[idx]) {
                    warning("Radii not far enough out for CR: %g",f[idx]);
                    f = omk;
                }
            }
            QoILR = FALSE;
            for(; idx>0; idx--) {
                if (omk[idx] > omk_max) {
                    idx_max = idx;
                    omk_max = omk[idx];
                }
                if (f==omk) {
                    if (QoILR) {
                        if (omega < f[idx]) continue;
                    } else {
                        if (omega > f[idx]) continue;
                    }
                } else {
                    if (omega > f[idx]) continue;
                }
                
                /* found a resonance: */

                rr = rad[idx] + (rad[idx+1]-rad[idx])*
                                (omega-f[idx])/(f[idx+1]-f[idx]);
                if (f == omk) {
#if 0                    
                    if (QoILR) {
                        dprintf(0,"iILR: %g\n",rr);
                        break;
                    } else {
                        dprintf(0,"oILR: %g\n",rr);
                        QoILR = TRUE;
                    }
#endif                    
                } else if (f == ome) {
                    dprintf(0,"CR: %g\n",rr);
                    f = omk;
                } else if (f == opk) {
                    dprintf(0,"OLR: %g\n",rr);
                    f = ome;
                } else
                    error("impossble resonance");
            }
            peak(nrad,rad,omk,idx_max,1, &omk_rmax, &omk_max);
            dprintf(0,"OMK_max: %g\n",omk_max);
            dprintf(0,"OMK_rmax: %g\n",omk_rmax);

            if (omega < omk_max) {			/* search for ILR */
            	for (idx=idx_max; idx<nrad; idx++) {
                    if (omega > omk[idx]) {
                        rr = rad[idx-1] + (rad[idx]-rad[idx-1])*
                                (omega-f[idx-1])/(f[idx]-f[idx-1]);
                        dprintf(0,"oILR: %g\n",rr);
                        break;
                    }
            	}
                for (idx=idx_max; idx>0; idx--) {
                    if (omega > omk[idx]) {
                        rr = rad[idx] + (rad[idx+1]-rad[idx])*
                               (omega-f[idx])/(f[idx+1]-f[idx]);
                        dprintf(0,"iILR: %g\n",rr);
                        break;
                    }
            	}
            }
        }
    }
    for (i=0; i<nrad; i++) {                            /* loop to print */
        if (Qtab) {
	  printf(fmt1,rad[i]);
	  printf(fmt1,vel[i]);
	}
	if (Qtab && npots>1 && !Qome) {
	    if (mypot1) printf(fmt1,vel1[i]);
	    if (mypot2) printf(fmt1,vel2[i]);
	    if (mypot3) printf(fmt1,vel3[i]);
	    if (mypot4) printf(fmt1,vel4[i]);
        }
        if (Qtab && Qome) {
	  printf(fmt1,ome[i]);
	  printf(fmt1,kap[i]);
	  printf(fmt1,opk[i]);
	  printf(fmt1,omk[i]);
	}
	if (Qtab) printf("\n");
        if (Qome)
            pmax = MAX(pmax,opk[i]);
        else
            pmax = MAX(pmax,vel[i]);
    }
    if (Qin && Qvel) 
        goodness(nrad,rad,vel,ndat,inrad,invel,(cols[3]>0?invele:NULL));
    if (Qplot) {
        plinit("***",0.0,20.0,0.0,20.0);                /* open device */
        nx = nemoinpr(getparam("xrange"),xplot,2);      /* get xrange in plot */
        switch(nx) {
         case 0:
            xplot[0] = rad[0];
         case 1:
            xplot[1] = rad[nrad-1];
            break;
         case 2:
            break;
         default:
            warning("xrange= only accepts two values");
            break;
        }
        ny = nemoinpr(getparam("yrange"),yplot,2);      /* get yrange in plot */
        switch(ny) {
         case 0:
            yplot[0] = 0.0;
            yplot[1] = 1.1 * pmax;      /* extra 10% for egde */
            break;
         case 1:
            yplot[1] = 1.1 * pmax;      /* extra 10% for egde */
            break;
         case 2:
            break;
         default:
            warning("yrange= only accepts two values");
            break;
        }
        xaxis ( 2.0, 2.0, 16.0, xplot, -7, xtrans, "R");    /* plot axes */
        xaxis ( 2.0,18.0, 16.0, xplot, -7, xtrans, NULL);
        if (Qome)
            yaxis ( 2.0, 2.0, 16.0, yplot, -7, ytrans, "[V/R]");
        else
            yaxis ( 2.0, 2.0, 16.0, yplot, -7, ytrans, "V");
        yaxis (18.0, 2.0, 16.0, yplot, -7, ytrans, NULL);
        if (*plotlabel)
            pltext(plotlabel,2.0,18.5,0.5,0.0);
        else
            pltext(headline,2.0,18.5,0.35,0.0);
        if (*plotmsg)
            pltext(plotmsg,8.0,2.5,0.25,0.0);

        curve = (Qome ? ome : vel);            /* assign first curve */
        plltype(3,1);                                 /* thick solid line */
        plmove(xtrans(rad[0]),ytrans(curve[0]));
        for (i=1; i<nrad; i++)
            plline(xtrans(rad[i]),ytrans(curve[i]));
        if (Qome) {                   /* if Lindblad - plot omk, opk */
            plltype(1,1);                      /* all regular solid lines */
            plmove(xtrans(rad[0]), ytrans(omk[0]));
            for (i=1; i<nrad; i++)
                plline(xtrans(rad[i]),ytrans(omk[i]));
            plmove(xtrans(rad[0]), ytrans(opk[0]));
            for (i=1; i<nrad; i++)
                plline(xtrans(rad[i]),ytrans(opk[i]));
        } else if (npots>1) {            /* if velocity and > 1 component */
            ltype = 1;
            if (mypot1) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel1[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel1[i]));
            }
            if (mypot2) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel2[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel2[i]));
            }
            if (mypot3) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel2[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel3[i]));
            }
            if (mypot4) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel2[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel4[i]));
            }
        }
	plltype(1,1); 
        symsize = 0.1;
        if (Qin && Qvel) {           /* if input file with velocities */
            for (i=0; i<ndat; i++)
                plbox(xtrans(inrad[i]),ytrans(invel[i]),symsize);
            if (cols[3]>0) {        /* if error bars in radius */
                for (i=0; i<ndat; i++) {
                    plmove(xtrans(inrad[i]-inrade[i]),ytrans(invel[i]));
                    plline(xtrans(inrad[i]+inrade[i]),ytrans(invel[i]));
                }
            }
            if (cols[4]>0) {        /* if error bars in velocity */
                for (i=0; i<ndat; i++) {
                    plmove(xtrans(inrad[i]),ytrans(invel[i]-invele[i]));
                    plline(xtrans(inrad[i]),ytrans(invel[i]+invele[i]));
                }
            }
        } else if (Qin && Qome) {       /* if input file with omega */
            for (i=0; i<ndat; i++)
                plbox(xtrans(inrad[i]),ytrans(invel[i]/inrad[i]),symsize);
        }
        plstop();
    }  /* if plot vel/ome */
    if (Qlv) {
        ns = nemoinpr(getparam("r0l"),r0l,MAXPT+2) - 2;
        if (ns < 0)
            error("r0l= needs at least two values: r0 and l");
        else if (ns==0)
            warning("r0l= no lv-radii array supplied");
        lv(nrad,rad,vel,r0l[0],r0l[1],ns,&r0l[2]);
    }
}
Exemplo n.º 18
0
void 	build_Triangulation( struct Triangulation_T *triang)
{
	int		i=0;							// Loop counter.
	int		len=0;							// Loop length.
	int		finished=0;						// Loop control flag.
#ifdef DEBUG_DELAUNAY
	int		expected_Edges=0;				// Number of edges in triangulation.
	int		expected_Triangles=0;			// Number of triangles in triangulation.
#endif

	int		edgeId=0, faceId=0;				// Edge and face Id counters.
	int		savedEdge=0;
	int		nextConvexEdge=0;				// Next edge to add to convex hull.
	int		originVertex1=0, originVertex2=0;
	int		originVertexIndex1=0, originVertexIndex2=0;
	int		convex_Peak[2];					// Last two points in convex hull.

	struct Dcel_Vertex_T *newVertex=NULL;	// New vertex to add to DCEL.
	struct Convex_T		convex_Edge;		//
	struct Convex_T		peak_Edge;			// Last edge in convex hull.

	// Order in angular order from bottom most point.
	sort( triang->dcel);

	// Insert invalid face. Updated when convex hull added.
	insertFace( triang->dcel, -1);

	// First vertex belongs to convex hull.
	convex_Edge.vertex_Index = 0;
	convex_Edge.edge_ID = 1;
	push( &triang->stack, convex_Edge);

	// Insert first edge.
	triang->dcel->vertex[0].origin_Edge = 1;
	insertEdge( triang->dcel, 1, -1, 3, 2, 1);

	// Second vertex belongs to convex hull.
	convex_Edge.vertex_Index = 1;
	convex_Edge.edge_ID = 2;
	push( &triang->stack, convex_Edge);

	// Insert second edge.
	triang->dcel->vertex[1].origin_Edge = 2;
	insertEdge( triang->dcel, 2, -1, 1, 3, 1);

	// Third element is inserted in convex hull at starting.
	convex_Edge.vertex_Index = 2;
	convex_Edge.edge_ID = 3;
	push( &triang->stack, convex_Edge);

	// Insert third edge.
	triang->dcel->vertex[2].origin_Edge = 3;
	insertEdge( triang->dcel, 3, -1, 2, 1, 1);

	// Insert first face.
	insertFace( triang->dcel, 1);

	// Initianlize variables before loop.
	faceId = 2;
	edgeId = 4;

	// Parse rest of points.
	for (i=3; i<triang->dcel->nVertex ;i++)
	{
		// Get current point.
		newVertex = get_Vertex( triang->dcel, i);

		// Initialize indexes and values.
		originVertexIndex1 = 0;
		originVertex1 = 1;
		originVertexIndex2 = i-1;
		originVertex2 = i;

		finished = 0;
		savedEdge = -1;
		nextConvexEdge = edgeId+2;
		peak_Edge = peak( &triang->stack);
		while (!finished)
		{
			// Get last two vertex from convex hull.
			convex_Edge = peak( &triang->stack);
			convex_Peak[0] = convex_Edge.vertex_Index;
			convex_Edge = peak_Prev( &triang->stack);
			convex_Peak[1] = convex_Edge.vertex_Index;

			// Insert new edge and update its twin.
			triang->dcel->vertex[originVertexIndex1].origin_Edge = edgeId;
			triang->dcel->edges[peak_Edge.edge_ID-1].twin_Edge = edgeId;
			insertEdge( triang->dcel, originVertex1, peak_Edge.edge_ID, edgeId+2, edgeId+1, faceId);
#ifdef DEBUG_DELAUNAY
			printf("A %d LE ASIGNO %d y A %d LE ASIGNO %d\n", edgeId, peak_Edge.edge_ID, peak_Edge.edge_ID, edgeId);
#endif

			// Insert new edge.
			triang->dcel->vertex[originVertexIndex2].origin_Edge = edgeId+1;
			insertEdge( triang->dcel, originVertex2, -1, edgeId, edgeId+2, faceId);
#ifdef DEBUG_DELAUNAY
			printf("A %d LE PONGO -1\n", edgeId+1);
#endif

			// Insert new edge.
			triang->dcel->vertex[i].origin_Edge = edgeId+2;
			insertEdge( triang->dcel, i+1, savedEdge, edgeId+1, edgeId, faceId);
			if (savedEdge != -1)
			{
				triang->dcel->edges[savedEdge-1].twin_Edge = edgeId+2;
#ifdef DEBUG_DELAUNAY
				printf("A %d PONGLE ASIGNO %d y a %d LEASIGNO %d\n", edgeId+2, savedEdge, savedEdge, edgeId+2);
			}
			else
			{
				printf("A %d LE ASIGNO -1\n", edgeId+2);
#endif
			}

			savedEdge = edgeId+1;

			// Check type of turn with new point.
			if ((check_Turn( &triang->dcel->vertex[convex_Peak[1]].vertex,
							&triang->dcel->vertex[convex_Peak[0]].vertex,
							&newVertex->vertex) == LEFT_TURN) ||
				(check_Turn( &triang->dcel->vertex[convex_Peak[1]].vertex,
							&triang->dcel->vertex[convex_Peak[0]].vertex,
							&newVertex->vertex) == COLINEAR))
			{
				// Update peak of convex hull.
				update_Peak( &triang->stack, edgeId+1);
#ifdef DEBUG_DELAUNAY
				printf("Actualizo PEAK con Edge %d\n", edgeId+1);
#endif

				// Add edge to convex hull.
				convex_Edge.vertex_Index = i;
				convex_Edge.edge_ID = nextConvexEdge;
				push( &triang->stack, convex_Edge);
				finished = 1;
#ifdef DEBUG_DELAUNAY
				printf("METO EN PILA PUNTO %d Y EDGE %d\n", convex_Edge.vertex_Index, convex_Edge.edge_ID);
#endif
			}
			else
			{
				// Update source points.
				convex_Edge = peak( &triang->stack);
				originVertexIndex1 = convex_Edge.vertex_Index;
				originVertex1 = convex_Edge.vertex_Index+1;

				// Pop convex hull.
#ifdef DEBUG_DELAUNAY
				printf("SACO DE LA PILA\n");
#endif
				pop( &triang->stack);

				peak_Edge = peak( &triang->stack);
				originVertexIndex2 = peak_Edge.vertex_Index;
				originVertex2 = peak_Edge.vertex_Index+1;
			}

			// Insert face.
			insertFace( triang->dcel, edgeId);

			// Update counters.
			faceId++;
			edgeId = edgeId + 3;
		}
	}

	// Save index of first edge from convex hull.
	convex_Edge = peak( &triang->stack);
	savedEdge = convex_Edge.edge_ID;

	pop( &triang->stack);
	peak_Edge = peak( &triang->stack);

	// Insert first edge from convex hull.
	triang->dcel->edges[peak_Edge.edge_ID-1].twin_Edge = edgeId;
	insertEdge( triang->dcel, convex_Edge.vertex_Index+1, peak_Edge.edge_ID,
								edgeId+get_Stack_nElements(&triang->stack),
								edgeId+1,
								0);

	// Next edge.
	edgeId = edgeId+1;

	// Update convex hull.
	len = get_Stack_nElements( &triang->stack)-1;
	for (i=0; i<len ;i++)
	{
		convex_Edge = peak( &triang->stack);
		pop( &triang->stack);
		peak_Edge = peak( &triang->stack);

		// Insert new edge fom convex hull
		triang->dcel->edges[peak_Edge.edge_ID-1].twin_Edge = edgeId;
		insertEdge( triang->dcel, convex_Edge.vertex_Index+1, peak_Edge.edge_ID, edgeId-1, edgeId+1, 0);

		// Next edge.
		edgeId++;
	}

	// Insert first edge from convx hull.
	triang->dcel->edges[savedEdge-1].twin_Edge = edgeId;
	insertEdge( triang->dcel, 1, savedEdge, edgeId-1, edgeId-len-1, 0);

	// Update convex hull face departing edge.
	triang->dcel->faces[0].edge = edgeId;

#ifdef DEBUG_DELAUNAY
	// Check error in number of triangles.
	expected_Edges = 3*triang->dcel->nVertex - triang->stack.nElements - 3;
	expected_Triangles = 2*triang->dcel->nVertex - triang->stack.nElements - 2;
	printf("Faces %d. Expected %d\nEdges %d. Expected %d\n",
											triang->dcel->nFaces,
											expected_Triangles,
											triang->dcel->nEdges,
											expected_Edges);
#endif
}
Exemplo n.º 19
0
// Calculates centroides of peaks from raw data
void CentroidData::calcCentroids(	RawData &pRawData ) // Profile data object
// Calculates centroide data from profile data
{
  
  int i,hw,j;
  double cm,toti,min_dh;
  vector<double> masses,intens;
  
  pRawData.get(masses,intens);
  fCentroidPeaks.clear();
  
  ////////////////////////////////////////////
  
  if( CENTROID_DATA_MODUS ) { // if data alread centroided in mzXML file
    for (i=0;i<(int)masses.size();i++) { 
      
      double inte = intens[i];
      double mz = masses[i];
      
      if( inte >= pRawData.LOW_INTENSITY_MS_SIGNAL_THRESHOLD ){
        CentroidPeak peak(mz,inte, fScanRetentionTime);
        
        /*
        if( CentroidData::MonoIsoDebugging ){
          if( ( CentroidData::DebugMonoIsoMassMin <= mz) && ( CentroidData::DebugMonoIsoMassMax >= mz) ){
            peak.show_info();
          }
        }
        */
        
        fCentroidPeaks.push_back(peak);
      }
      
    }
  } 
  else {
    
    ////////////////////////////////////////////
    // centroid raw data
    min_dh = pRawData.LOW_INTENSITY_MS_SIGNAL_THRESHOLD; // min height
    hw = fWindowWidth/2;
    
    for (i=2;i<(int)masses.size()-2;i++) { 
      
      // Peak must be concave in the interval [i-2 .. i+2]
      if (intens[i]>min_dh && intens[i]>intens[i-1]+min_dh && intens[i]>=intens[i+1] && intens[i-1]>intens[i-2]+min_dh && intens[i+1]>=intens[i+2]) {
        
        // centroid mass:
        cm = 0.0;
        // total intensity:
        toti = 0.0;
        
        // double Tinte = intens[i];
        double Tmz = masses[i];
        
        /*
        if( MonoIsoDebugging ){
          if( ( DebugMonoIsoMassMin <= Tmz) && ( DebugMonoIsoMassMax >= Tmz) ){
            cout<<endl<<"*Centroid: "<<Tmz<<": "<<Tinte<<endl;
          }
        }
        */
        
        for (j= -hw;j<=hw;j++) {
          double inte = intens[i-j];
          double mz = masses[i-j];

          /*
          if( MonoIsoDebugging ){
            if( ( DebugMonoIsoMassMin <= Tmz) && ( DebugMonoIsoMassMax >= Tmz) ){
              cout<<"** add: "<<mz<<": "<<inte<<endl;
            }
          }
           */
          
          cm += inte*mz;
          toti += (double) intens[i-j];
        }
        cm = cm/toti;  // Centre of gravity = centroid
        
        // take the intensity at the apex of the profile peak:
        CentroidPeak peak(cm,intens[i],fScanRetentionTime);
       
        // Lukas: take summed intensity over all peaks:
        // CentroidPeak peak( cm, toti);
        
        if( MonoIsoDebugging ){
          if( ( DebugMonoIsoMassMin <= Tmz) && ( DebugMonoIsoMassMax >= Tmz) ){
            cout<<"*final: ";
            peak.show_info();
          }
        }
        
        
        fCentroidPeaks.push_back(peak);
      }
    }
  }
}
int main(int argc, const char * argv[]) {

    int userChoice;
    scanf("%d",&size);
    queue = (int *)malloc(size * sizeof(int));
    while(1){
        printf("1 - Enque\n2 -  Dequeue\n3 - peak\nAny other input - Exit\n");
        scanf("%d",&userChoice);
        userChoice == 1 ? enqueue() : (userChoice == 2 ? printf("%d\n",dequeue()) : (userChoice == 3 ? printf("%d\n",peak()) : exit(0)));
    }
    return 0;
}
Exemplo n.º 21
0
void midgSplit (unsigned char * data) {
	
	// Static Variables: CAREFUL
	static unsigned char prevBuffer [2*MAXLOGLEN];
	static unsigned char previousComplete =1;
	static unsigned char indexLast = 0;
	static unsigned char incompleteLen = 0;
	
	// local variables
	unsigned char i;
	unsigned char headerFound=0, noMoreBytes = 1;
	
    // FIXME: this requires MIDG_CHUNKSIZE < 257.  
    // if data[0] is 255, then i overflows from 255 to 0 and this is infinite
	// Add the received bytes to the protocol parsing circular buffer
    for(i = 1; i <= data[0]; i += 1 )
	{
		writeBack(midgBuffer, data[i]);
	}
	
	// update the noMoreBytes flag accordingly
    noMoreBytes = (data[0]>0)?0:1;

	while (!noMoreBytes){
		// if the previous message was complete then read from the circular buffer
		// and make sure that you are into the begining of a message
		if(previousComplete){
			while (!headerFound && !noMoreBytes) {
				// move along until you find a 0x81 or run out of bytes
				while (getLength(midgBuffer)>3 && peak(midgBuffer)!=0x81){
					readFront(midgBuffer);
				}
				// if you found a dollar then make sure the next one is an A1
				// You always make sure to have 4 bytes remaining (including
				// BOF so you can read the ID and the length)
				if(getLength(midgBuffer)>3 && peak(midgBuffer) == 0x81){
					// read it
					prevBuffer[indexLast++] = readFront(midgBuffer);
                    // if next is a 0xA1
					if (peak(midgBuffer) == 0xA1){
						// read the sync
						prevBuffer[indexLast++] = readFront(midgBuffer);
						// read the ID
						prevBuffer[indexLast++] = readFront(midgBuffer);
						// read the count
						prevBuffer[indexLast++] = readFront(midgBuffer);
						// start monitoring the pending count
						incompleteLen = prevBuffer[indexLast -1]; 
						// and signal you found a header
						headerFound = 1;
                         // and set as  incomplete the sentece
                         previousComplete = 0;
					}
				} else {
					noMoreBytes = 1;
				} // else no dollar
			} // while we found header && no more bytes
		} // if previous complete
		
		// At this point either you found a header from a previous complete
		// or you are reading from a message that was incomplete the last time
		// in any of those two cases, keep reading until you run out of bytes
		// or incompleteLen == 0		
		
		while ((incompleteLen > 0) && !noMoreBytes){
			while (incompleteLen >0 && getLength(midgBuffer)>2){
				prevBuffer[indexLast++] = readFront(midgBuffer);
				incompleteLen --;
			}
			// if you completed the Length of the payload and you have 
			// at least two bytes to read to get the checksum
			if (incompleteLen == 0 && getLength(midgBuffer)>=2){
				// read the checksum 0
				prevBuffer[indexLast++] = readFront(midgBuffer);
				// read the checksum 1
				prevBuffer[indexLast++] = readFront(midgBuffer);
				// Parse the message. 
				// Note that parse does the checksumming
				midgParse(prevBuffer);
				
				// Reset the variables
				previousComplete =1;
				indexLast = 0;
            	headerFound = 0;
            	memset(prevBuffer, 0, sizeof(prevBuffer));

			} else {
				noMoreBytes =1;
			}
		}
	} // big outer loop
}
Exemplo n.º 22
0
std::size_t byte_buffer::read(void* dst, const std::size_t sz) {
	std::size_t cpysize = peak( dst , sz );
	rd_ptr(static_cast<int>(cpysize));
	return cpysize;
}
Exemplo n.º 23
0
// TODO: Include a messaging Mechanism for immediate or once in time messages
// TODO: Include a File option for Archiving checksum fails for debuging
float protParseDecode (unsigned char* fromSPI,  FILE* outFile, unsigned char prevException){
#else
void protParseDecode (unsigned char* fromSPI){
#endif
	// Static variables CAREFUL
	static unsigned char prevBuffer[2*MAXLOGLEN];
	static unsigned char previousComplete =1;
	static unsigned char indexLast = 0;
    #ifdef _IN_PC_
         static long long checkSumFail = 0;
         static long long totalPackets = 0;
         static float test = 0.0;
         float alpha = 0.3;
    #endif


	// local variables
	unsigned char i;
	unsigned char tmpChksum = 0, headerFound=0, noMoreBytes = 1;
	unsigned char trailerFound = 0;

	//unsigned char logSize = 0;

	// Add the received bytes to the protocol parsing circular buffer
    for(i = 1; i <= fromSPI[0]; i += 1 )
    //for(i = 0; i <= 95; i += 1 )
	{
		writeBack(ppBuffer, fromSPI[i]);
	}

	// update the noMoreBytes flag accordingly
   noMoreBytes = (fromSPI[0]>0)?0:1;
   // noMoreBytes = 0;

	while (!noMoreBytes){
		// if the previous message was complete then read from the circular buffer
		// and make sure that you are into the begining of a message
		if(previousComplete){
			while (!headerFound && !noMoreBytes) {
				// move along until you find a dollar sign or run out of bytes
				while (getLength(ppBuffer)>1 && peak(ppBuffer)!=DOLLAR){
					readFront(ppBuffer);
				}
				// if you found a dollar then make sure the next one is an AT
				if(getLength(ppBuffer)>1 && peak(ppBuffer) == DOLLAR){
					// read it
					prevBuffer[indexLast++] = readFront(ppBuffer);
                    // if next is a at sign
					if (peak(ppBuffer) == AT){
						// read it
						prevBuffer[indexLast++] = readFront(ppBuffer);
						// and signal you found a header
						headerFound = 1;
                         // and set as  incomplete the sentece
                         previousComplete = 0;
					}
				} else {
					noMoreBytes = 1;
				} // else no dollar
			} // while we found header && no more bytes
		}// if previous complete

		// At this point either you found a header from a previous complete
		// or you are reading from a message that was incomplete the last time
		// in any of those two cases, keep reading until you run out of bytes
		// or find a STAR and an AT
		while (!trailerFound && !noMoreBytes){
			while (getLength(ppBuffer)>2 && peak(ppBuffer)!=STAR){
				prevBuffer[indexLast++] = readFront(ppBuffer);
			}
			// if you found a STAR (42) and stil have bytes
			if (getLength(ppBuffer)>2 && peak(ppBuffer)==STAR){
				// read it
				prevBuffer[indexLast++] = readFront(ppBuffer);
				// if you still have 2 bytes
				if (getLength(ppBuffer)>1){
					// and the next byte is an AT sign
					if (peak(ppBuffer)==AT){
						// then you found a trailer
						trailerFound =1;
					}
				} else {
					noMoreBytes =1;
				}
			} else {
				// no more bytes
				noMoreBytes =1;
			}
		}

		// if you found a trailer, then the message is done
		if(trailerFound){
			// read the AT and the checksum
			prevBuffer[indexLast++] = readFront(ppBuffer);
			prevBuffer[indexLast] = readFront(ppBuffer);

			// Compute the checksum
			tmpChksum= getChecksum(prevBuffer, indexLast-1);
            #ifdef _IN_PC_
               totalPackets++;
            #endif

			// if the checksum is valid
			if (tmpChksum ==prevBuffer[indexLast]){
				// update the states depending on the message
				updateStates(&prevBuffer[0]);
				// increment the log size
				//logSize += (indexLast+1);
                #ifdef _IN_PC_
					// if in PC and loggin is enabled
                    if ((outFile != NULL)){
                       printState(outFile, prevException);
                    }
                    //test = alpha*test;
                #endif
			}
            else{
                 #ifdef _IN_PC_
                    checkSumFail++;
                    //test = (1.0-alpha) + alpha*test;
                 #endif
            }
            // get everything ready to start all-over
			previousComplete =1;
			indexLast = 0;
            headerFound = 0;
            trailerFound = 0;
            memset(prevBuffer, 0, sizeof(prevBuffer));

		}else { // you ran out of bytes
			// No More Bytes
			noMoreBytes = 1;
		}// else no star
	} // big outer while (no more bytes)
    #ifdef _IN_PC_
       if (totalPackets>0){
          //test =  ((float)checkSumFail/(float)totalPackets);
          test = (float)checkSumFail;

       } else {
          test = 0.0;
       }
       return test;
    #endif
}

unsigned char getFilterOnOff (void){
	return filterControlData;
}

// ================================
//  hardware in the loop methods
// ================================

void hil_getRawRead(short * rawData){
	rawData[0] =  	rawControlData.gyroX.shData;
	rawData[1] =  	rawControlData.gyroY.shData;
	rawData[2] =  	rawControlData.gyroZ.shData;
	rawData[3] = 	rawControlData.accelX.shData;
	rawData[4] = 	rawControlData.accelY.shData;
	rawData[5] = 	rawControlData.accelZ.shData;
	rawData[6] = 	rawControlData.magX.shData;
	rawData[7] = 	rawControlData.magY.shData;
	rawData[8] = 	rawControlData.magZ.shData;
	rawData[9] = 	rawControlData.baro.shData;
	rawData[10] = 	rawControlData.pito.shData;
	rawData[11] = 	rawControlData.powr.shData;
	rawData[12] = 	rawControlData.ther.shData;
}
Exemplo n.º 24
0
/* ----------------------------------------------------------------------- */
void get_fast_cands(float *fdata, float *fdsdata, int ind, int step, int size,
                    int dec, int start, int nlags, float *engref, int *maxloc,
                    float *maxval, Cross *cp, float *peaks, int *locs,
                    int *ncand, F0_params *par)
{
  int decind, decstart, decnlags, decsize, i, j, *lp;
  float *corp, xp, yp, lag_wt;
  register float *pe;

  lag_wt = par->lag_weight/nlags;
  decnlags = 1 + (nlags/dec);
  if((decstart = start/dec) < 1) decstart = 1;
  decind = (ind * step)/dec;
  decsize = 1 + (size/dec);
  corp = cp->correl;

  crossf(fdsdata + decind, decsize, decstart, decnlags, engref, maxloc,
	maxval, corp);
  cp->maxloc = *maxloc;	/* location of maximum in correlation */
  cp->maxval = *maxval;	/* max. correlation value (found at maxloc) */
  cp->rms = (float) sqrt(*engref/size); /* rms in reference window */
  cp->firstlag = decstart;

  get_cand(cp,peaks,locs,decnlags,ncand,par->cand_thresh); /* return high peaks in xcorr */

  /* Interpolate to estimate peak locations and values at high sample rate. */
  for(i = *ncand, lp = locs, pe = peaks; i--; pe++, lp++) {
    j = *lp - decstart - 1;
    peak(&corp[j],&xp,&yp);
    *lp = (*lp * dec) + (int)(0.5+(xp*dec)); /* refined lag */
    *pe = yp*(1.0f - (lag_wt* *lp)); /* refined amplitude */
  }

  if(*ncand >= par->n_cands) {	/* need to prune candidates? */
    register int *loc, *locm, lt;
    register float smaxval, *pem;
    register int outer, inner, lim;
    for(outer=0, lim = par->n_cands-1; outer < lim; outer++)
      for(inner = *ncand - 1 - outer,
	  pe = peaks + (*ncand) -1, pem = pe-1,
	  loc = locs + (*ncand) - 1, locm = loc-1;
	  inner--;
	  pe--,pem--,loc--,locm--)
	if((smaxval = *pe) > *pem) {
	  *pe = *pem;
	  *pem = smaxval;
	  lt = *loc;
	  *loc = *locm;
	  *locm = lt;
	}
    *ncand = par->n_cands-1;  /* leave room for the unvoiced hypothesis */
  }
  crossfi(fdata + (ind * step), size, start, nlags, 7, engref, maxloc,
	  maxval, corp, locs, *ncand);

  cp->maxloc = *maxloc;	/* location of maximum in correlation */
  cp->maxval = *maxval;	/* max. correlation value (found at maxloc) */
  cp->rms = (float) sqrt(*engref/size); /* rms in reference window */
  cp->firstlag = start;
  get_cand(cp,peaks,locs,nlags,ncand,par->cand_thresh); /* return high peaks in xcorr */
    if(*ncand >= par->n_cands) {	/* need to prune candidates again? */
    register int *loc, *locm, lt;
    register float smaxval, *pe, *pem;
    register int outer, inner, lim;
    for(outer=0, lim = par->n_cands-1; outer < lim; outer++)
      for(inner = *ncand - 1 - outer,
	  pe = peaks + (*ncand) -1, pem = pe-1,
	  loc = locs + (*ncand) - 1, locm = loc-1;
	  inner--;
	  pe--,pem--,loc--,locm--)
	if((smaxval = *pe) > *pem) {
	  *pe = *pem;
	  *pem = smaxval;
	  lt = *loc;
	  *loc = *locm;
	  *locm = lt;
	}
    *ncand = par->n_cands - 1;  /* leave room for the unvoiced hypothesis */
  }
}
Exemplo n.º 25
0
    /// Run the algorithm
    void PredictFractionalPeaks::exec()
    {
       PeaksWorkspace_sptr Peaks=getProperty("Peaks");

       vector<double> hOffsets = getProperty("HOffset");
       vector<double> kOffsets = getProperty("KOffset");
       vector<double> lOffsets = getProperty("LOffset");
       if ( hOffsets.empty())hOffsets.push_back(0.0);
       if ( kOffsets.empty())kOffsets.push_back(0.0);
       if ( lOffsets.empty())lOffsets.push_back(0.0);

;
       bool includePeaksInRange= getProperty("IncludeAllPeaksInRange");

       if(  Peaks->getNumberPeaks()<=0)
       {
         g_log.error()<<"There are No peaks in the input PeaksWorkspace\n";
         return;
       }

       API::Sample samp= Peaks->sample();

       Geometry::OrientedLattice &ol = samp.getOrientedLattice();

       Geometry::Instrument_const_sptr Instr = Peaks->getInstrument();

       boost::shared_ptr<IPeaksWorkspace> OutPeaks=WorkspaceFactory::Instance().createPeaks();
       OutPeaks->setInstrument(Instr);
      // AnalysisDataService::Instance().addOrReplace(getPropertyValue("FracPeaks"),OutPeaks);

       V3D hkl;
       int peakNum =0;
       int NPeaks = Peaks->getNumberPeaks();
       Kernel::Matrix<double> Gon;
       Gon.identityMatrix();

       double Hmin= getProperty("Hmin");
       double Hmax= getProperty("Hmax");
       double Kmin= getProperty("Kmin");
       double Kmax= getProperty("Kmax");
       double Lmin= getProperty("Lmin");
       double Lmax= getProperty("Lmax");

       int N=NPeaks;
       if( includePeaksInRange)
       {
         N=(int)((Hmax-Hmin+1)*(Kmax-Kmin+1)*(Lmax-Lmin+1)+.5);
         N=max<int>(100,N);
       }
       IPeak& peak0 =Peaks->getPeak(0);
       int RunNumber = peak0.getRunNumber();
       Gon=peak0.getGoniometerMatrix();
       Progress prog(this, 0,  1,N);
       if( includePeaksInRange)
       {


         hkl[0]=Hmin;
         hkl[1]=Kmin;
         hkl[2]=Lmin;
       }else
       {
         hkl[0]=peak0.getH();
         hkl[1]=peak0.getK();
         hkl[2] =peak0.getL();


       }

       Kernel::DblMatrix UB= ol.getUB();
       vector< vector<int> > AlreadyDonePeaks;
       bool done = false;
       int ErrPos = 1;//Used to determine position in code of a throw
       while( !done)
       {
         for( size_t hoffset=0;hoffset<hOffsets.size();hoffset++)
           for(size_t  koffset=0;koffset<kOffsets.size();koffset++)
             for( size_t loffset=0;loffset<lOffsets.size();loffset++)
                try
                {
                  V3D hkl1( hkl );
                  ErrPos = 0;

                  hkl1[0] += hOffsets[hoffset] ;
                  hkl1[1] += kOffsets[koffset] ;
                  hkl1[2] += lOffsets[loffset] ;

                  Kernel::V3D Qs = UB * hkl1 ;
                  Qs*= 2.0;
                  Qs*=M_PI;
                  Qs=Gon*Qs;
                  if( Qs[2] <= 0 )
                    continue;

                  ErrPos=1;
                  boost::shared_ptr<IPeak> peak( Peaks->createPeak( Qs, 1 ));

                  peak->setGoniometerMatrix(Gon);

                  if (Qs[2]>0 && peak->findDetector())
                  {
                    ErrPos=2;
                    vector<int> SavPk;
                    SavPk.push_back(RunNumber);
                    SavPk.push_back((int)floor(1000*hkl1[0]+.5));
                    SavPk.push_back((int)floor(1000*hkl1[1]+.5));
                    SavPk.push_back((int)floor(1000*hkl1[2]+.5));

                  //TODO keep list sorted so searching is faster?
                    vector<vector<int> >::iterator it = find(AlreadyDonePeaks.begin(),AlreadyDonePeaks.end(),SavPk);

                    ErrPos=3;
                    if( it == AlreadyDonePeaks.end())
                      AlreadyDonePeaks.push_back(SavPk);
                    else
                      continue;


                    ErrPos=4;
                    peak->setHKL(hkl1);
                    peak->setRunNumber(RunNumber);
                    OutPeaks->addPeak(*peak);
                  }
                }catch(...)
                {

                  if( ErrPos != 1)// setQLabFrame in createPeak throws exception
                    throw new std::invalid_argument( "Invalid data at this point");
                }
         if( includePeaksInRange)
         {
           hkl[0]++;
           if( hkl[0]>Hmax)
           {
             hkl[0]=Hmin;
             hkl[1]++;
             if( hkl[1]> Kmax)
             {

               hkl[1]=Kmin;
               hkl[2]++;
               if( hkl[2]> Lmax)
                 done = true;
             }
           }
         }else
         {
           peakNum++;
           if( peakNum >= NPeaks)
             done = true;
           else
           {// peak0= Peaks->getPeak(peakNum);
             IPeak& peak1= Peaks->getPeak(peakNum);
           //??? could not assign to peak0 above. Did not work
            // the peak that peak0 was associated with did NOT change
             hkl[0]=peak1.getH();
             hkl[1]=peak1.getK();
             hkl[2] =peak1.getL();
             Gon=peak1.getGoniometerMatrix();
             RunNumber = peak1.getRunNumber();

           }
         }
         prog.report();
       }


     setProperty("FracPeaks",OutPeaks);



    }
Exemplo n.º 26
0
 int findPeakElement(const vector<int> &num) {
     return peak(num, 0, num.size() - 1);
 }