Esempio n. 1
0
void checkArray(int n, int oneZero[], int start[], int *dif, int resultArray1[], int resultArray2[]){
	int difference = 0,
		*interim1 = calloc(n,sizeof(int)),
		*interim2 = calloc(n,sizeof(int));
	int i = 0,
		j = 0,
		k = 0;
	for (i = 0, j = 0, k = 0; i<n; i++){	//splits array in two according to oneZero
		if(oneZero[i] == 1){
			interim1[j] = start[i];
			j++;
		}
		else if (oneZero[i] == 0)
		{
			interim2[k] = start[i];
			k++;	
		}
	}

	//assigns difference of two arrays and makes it absolute value
	difference = sumArray(n,interim1) - sumArray(n,interim2);
	difference = absoluteValue(difference);

	if (difference < *dif){	//checks new difference with old one
		*dif = difference;	//if smaller assigns smaller value
		copyArray(n,resultArray1,interim1);		//and new arrays
		copyArray(n,resultArray2,interim2);
	}
	free(interim1);
	free(interim2);
}//checkArray
Esempio n. 2
0
// Sum all the values in the array arr
// Pre-cond: size >= 0
int sumArray(int arr[], int size) {

	if(size == 0)
		return 0;
	else
		return arr[size-1] + sumArray(arr,size-1);
}
Esempio n. 3
0
double parallelsumArray(double * arr, int num, int id, int numProc){
  int root = 0;
  double sum, totalSum, end, start, scatter, s;
  if(id == 0){ //master reads array and scatters value
    MPI_Bcast(&num, 1, MPI_INT, root, MPI_COMM_WORLD);
    printf("%i\t%g\n", numProc, *arr);
  }
  else{ //workers sum their part of the array
    MPI_Bcast(&num, 1, MPI_INT, root, MPI_COMM_WORLD);
  }
  
  int numElements = num/numProc;
  double* localA = malloc(sizeof(double) * numElements);
  
  start = MPI_Wtime();
  MPI_Scatter(arr, numElements, MPI_DOUBLE, localA, numElements, MPI_DOUBLE, root, MPI_COMM_WORLD);
  end = MPI_Wtime();
  scatter = end - start;
  
  start = MPI_Wtime();
  sum = sumArray(localA, numElements);
  MPI_Reduce(&sum, &totalSum, numProc, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
  end = MPI_Wtime();
  s = end - start; 
  if(id == 0){
    printf("scatter: %f, sum: %f\n", scatter, s);
  }
  //free(localA);
  return totalSum;
}
Esempio n. 4
0
void algorithm(int *arr, int size, int value, int version, FILE *file) {

    clock_t T1, T2;
    double time;
    int *outputArr;
    
    outputArr = createArr(size);
    initArr(outputArr, size);
    
    T1 = clock();//start timer
    
    //Call the appropriate algorithm on the array
    switch (version) {
        case 1 :
            outputArr = algorithm_1(arr, outputArr, size, value);
            break;
        case 2 :
            outputArr = algorithm_2(arr, outputArr, size, value);
            break;
        case 3 :
            outputArr = algorithm_3(arr, outputArr, size, value);
            break;
    }
    
    T2 = clock();//end timer
    time = (double)(T2 - T1) / CLOCKS_PER_SEC;//get total time
    
    value = sumArray(outputArr, size);
    print_results(outputArr, size, value, file);
    
    fprintf(file, "Time to execute: %fs\n", time);
    
    free(outputArr);
}
Esempio n. 5
0
/**
 * LeetCode 120  Triangle  27.3  Medium
 * Given a triangle, find the minimum path sum from top to bottom.
 * Each step you may move to adjacent numbers on the row below.
 *
 *	For example, given the following triangle
 *	[
 *		 [2],
 *		[3,4],
 *	   [6,5,7],
 *	  [4,1,8,3]
 *	]
 *	The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 =
 *11).
 *
 *	Note:
 *	Bonus point if you are able to do this using only O(n) extra space,
 *	where n is the total number of rows in the triangle.
 */
int ArrayQuiz::minimumTotal(vector<vector<int>> &triangle) {

    if (triangle.size() == 1) return triangle[0][0];
    vector<int> sumArray(triangle.size(), 0);
    sumArray[0] = triangle[0][0];
    for (auto i = 1; i < triangle.size(); i++) {
        for (auto j = i; j >= 0; j--) {
            if (j == 0) {
                sumArray[j] = triangle[i][j] + sumArray[j];
            } else if (j == i) {
                sumArray[j] = triangle[i][j] + sumArray[j - 1];
            } else {
                sumArray[j] = std::min(sumArray[j - 1], sumArray[j]) + triangle[i][j];
            }
        }
    }

    // go through sum array to find minimum
    // because triangle may arbitrary large, it is inefficient to compare each
    // time at
    // above loop
    int min = sumArray[0];
    for (auto &i : sumArray) {
        if (min > i) { min = i; }
    }

    return min;
}
Esempio n. 6
0
void QueryPerformanceFrequencyTest(int size) {
	DWORD* a = getFilledArray(size);

	LARGE_INTEGER liCount, liFreq;
	QueryPerformanceFrequency(&liFreq);
	

	ULONGLONG min = 0xFFFFFFFFFFFFFFFFL, start, finish, res;
	DWORD sum;

	for (int i = 0; i < 10; i++) {
		QueryPerformanceCounter(&liCount);
		start = liCount.QuadPart;

		sum = sumArray(a, size);

		QueryPerformanceCounter(&liCount);
		finish = liCount.QuadPart;

		res = finish - start;
		
		if (res < min) {
			min = res;
		}
	} 

	printf("sum  ==> %d\n", sum); 
	printf("freq ==> %d\n", liFreq.QuadPart);
	printf("time ==> %lg\n", (double) min / liFreq.QuadPart);
	printf("takts ==> %I64d", min);
}
int main()
{
	double x [100];
	double y [50];
	int i;
	
	srand(time(NULL));
		
	setToZero(x,100);
	/*fillArray(x, 10);*/
	
	fillRandom(&x[0],100);
	printArray(x,100);
	printf("The largest is %6.2f\n",largest(x,100));
	printf("Total is %6.2f\n",sumArray(x,100));
	printf("Ave is %6.2f\n",aveArray(x,100));
	printf("\n@@@@@@@@@@Sorted@@@@@@@@@@@@@@@@@@\n");
	doSort(x,100);
	
	printArray(x,100);
	/*
	fillRandom(y,50);
	printArray(y,50);
	*/
	
	
	
	
	
	
	return 0;
}
Esempio n. 8
0
int *algorithm_1(int *arr, int *outputArr, int size, int value) {
    
    int i, k, *tempArr1, *tempArr2, *tempArr3;
    k = value;
    
    if (k == 1) {
        outputArr[0]++;
        return outputArr;
    }
    else if ((i = isCoin(arr, size, k))) {
        outputArr[i]++;
        return outputArr;
    }
    else {
        //loop through every integer from 1 to "value"
        for (i = 1; i < k; i++) {
            
            //create and initilize three temprorary arrays of size "size" to all 0's
            tempArr1 = createArr(size);
            tempArr2 = createArr(size);
            tempArr3 = createArr(size);
            initArr(tempArr1, size);
            initArr(tempArr2, size);
            initArr(tempArr3, size);
            
            //recursively call algorithm_1 on array from 1 -> i and i + 1 -> "value"
            tempArr1 = algorithm_1(arr, tempArr1, size, i);
            tempArr2 = algorithm_1(arr, tempArr2, size, k - i);
            
            //add the sum of all elements at each index of tempArr1 and temArr2 together, assign to tempArr3
            addArr(tempArr1, tempArr2, tempArr3, size);
            
            //if this new sum of elements array (tempArr3) is less than the running min (outputArr) or the current output array is not a solution, then replace outputArr with tempArr3
            if ((sumArray(tempArr3, size) < sumArray(outputArr, size)) || !coinCheck(outputArr, arr, size, k)) {
                copyArr(tempArr3, outputArr, size);
            }
            
            free(tempArr1);
            free(tempArr2);
            free(tempArr3);
        }
    }
    
    return outputArr;
    
}
Esempio n. 9
0
int main(void) {
	int list[MAX_SIZE], size;

	size = readArray(list);
	printArray(list, size);

	printf("Sum = %d\n", sumArray(list, size));

	return 0;
}
Esempio n. 10
0
double parallelSumArray(double *masterArray, int howMany, int id, int numProc) {

    // Get the number of elements per process
    int elements_per_proc = howMany / numProc;
    if (debug) { 
        printf("Process %d has elements  %d\n", id, elements_per_proc);
    }
    
    // Allocate our local array in each t hread
    double * localArray = malloc(sizeof(double) * elements_per_proc);
    
    // Scatter the array
    //  This applies to all of the processes.
    MPI_Scatter(masterArray, elements_per_proc, MPI_DOUBLE, localArray, elements_per_proc, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    if (debug) {
        printf("Process %d has completed the scatter\n", id);
    }

    double localSum = sumArray(localArray, elements_per_proc);
    if (debug) {
        printf("The sum of the values in process '%d' is %g\n",    
                id, localSum);
    }

    free(localArray);

    double * local_sums = NULL;
    if (id == 0) {
        local_sums = malloc(sizeof(double) * numProc);
    }

    // Gather the results of the arrays
    MPI_Gather(&localSum, 1, MPI_DOUBLE, local_sums, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    double finalSum = 0;

    if (id == 0) {
        finalSum = sumArray(local_sums, numProc);
    }
    
    return finalSum;
}
int main() {
    std::size_t i;
    std::vector<std::chrono::duration<double>> dts;
    std::chrono::time_point<std::chrono::steady_clock> start, end;
    std::vector<dataType> input(SIZE);
    std::vector<Callable*> callables;
    dataType output;
    std::vector<dataType> repeatOutputs;
    std::uintmax_t r;
    unsigned int nCores, totalTests;

    nCores = std::thread::hardware_concurrency();
    // - 1 serial test
    // - 1 test with nCores + 1 (no improvement expected)
    totalTests = nCores + 2;
    callables.resize(totalTests);
    repeatOutputs.resize(totalTests);
    for (auto& r : repeatOutputs)
        r = 0;
    dts.resize(totalTests);
    for (auto& dt : dts)
        dt = std::chrono::duration<double>::zero();
    std::srand(std::time(NULL));
    for (r = 0; r < REPEAT; ++r) {
        // This data generation dominates the test run time...
        for (i = 0; i < SIZE; ++i)
            input[i] = std::rand();

        // Setup serial test.
        SumArray<dataType> sumArray(input.data(), SIZE, &output);
        callables[0] = &sumArray;

        // Setup parallal tests with different number of threads.
        std::vector<SumArrayParallel<dataType>> sumArrayParallels(totalTests - 1);
        for (std::vector<SumArrayParallel<dataType>>::size_type i = 0; i < sumArrayParallels.size(); ++i) {
            sumArrayParallels[i] = SumArrayParallel<dataType>(input.data(), SIZE, &output, i + 1);
            callables[i + 1] = &sumArrayParallels[i];
        }

        // Run tests.
        for (std::vector<Callable*>::size_type i = 0; i < callables.size(); ++i) {
            start = std::chrono::steady_clock::now();
            (*callables[i])();
            end = std::chrono::steady_clock::now();
            dts[i] += end - start;
            repeatOutputs[i] += output;
        }
    }
    std::cout << "n cores = " << nCores << std::endl;
    std::cout << "result = " << repeatOutputs[0] << std::endl;
    std::cout << "serial / parallel time (s)" << std::endl;
    for (auto& dt : dts)
        std::cout << dt.count() << std::endl;
    assert(std::adjacent_find(repeatOutputs.begin(), repeatOutputs.end(), std::not_equal_to<int>()) == repeatOutputs.end());
}
Esempio n. 12
0
File: 6.c Progetto: faithche/tasks
int main() {
    unsigned size ;
    printf("\n enter size of array:");
    scanf("%u" , &size);
    int arr[size];
    fillArray(size , arr);
    sumArray(size ,arr);
    printArr(size ,arr);
    getchar();
    return 0;
}
 int minSubArrayLen_OLD(int s, vector<int>& nums) {
     auto start = nums.begin();
     
     if(sumArray(nums.begin(),nums.end())<s) return 0;
     
     int min_len = nums.size();
     
     auto stop = ++nums.end();
     for(auto it=start;it!=stop;it++){
         while(sumArray(start,it)>=s) {
             if(distance(start,it)<min_len){
                 min_len=distance(start,it);
             }
             start++;
         }
         
     }
     
     return min_len;
     
 }
Esempio n. 14
0
int main(int argc, char *argv[], char *envp[]) {
  int i=0;  //common incrementor
  int ourArray[arraySize];
  
  for(i=0;i<arraySize;i++) {  //fill in our array
    ourArray[i] = rand() % 50;
  }
  
	printf("Elements:\n");  //print out our array
	for(i=0;i<arraySize-1;i++) {
		printf("%d->",ourArray[i]);
	}
	printf("%d\n",ourArray[arraySize]);
  printf("The sum is: %d\n",sumArray(ourArray,arraySize));

}
Esempio n. 15
0
// Для відносного визначте кількість циклів додавання , які можна виконати за 2 с для кожного розміру. 
DWORD countLoopTimes(int size, DWORD timeToCount) {
	DWORD* a = getFilledArray(size);

	DWORD time = timeToCount, start, finish;

	int times = 0, sum;
	start = GetTickCount();

	do {
		sum = sumArray(a, size);
		finish = GetTickCount();
		times++;
	} while (finish - start <= timeToCount);

	printf("sum = %d\n", sum);

	return times;
}
Esempio n. 16
0
UINT64 rdtscTest(int size) {
	DWORD* a = getFilledArray(size);

	UINT64 min = MAXDWORD64, start, finish, res;
	DWORD sum;

	for (int i = 0; i < 1000; i++) {
		start = __rdtsc();
		sum = sumArray(a, size);
		finish = __rdtsc();

		res = finish - start;

		if (res < min) {
			min = res;
		}
	}

	printf("sum  ==> %d\n", sum);
	return min;
}
Esempio n. 17
0
void test_rec()
{
    printf("\tTesting Recursion Algorithms...\n\n");

    long num = 20;
    printf("factorial of %ld = %ld\n", num, fact(num));

    int len = 10000;
    int i = 0;

    int numbers[len];

    for (i = 0; i < len; ++i)
        numbers[i] = i + 1;

    printf("sum of array = %d\n", sumArray(numbers, len));
    printf("largest in array = %d\n", largest(numbers, len));
    printf("largest in array = %d\n", largest2(numbers, 0, len - 1));

    int big_num = 203041;
    printf("sum of digits of %d = %d\n", big_num, sumOfDigits(big_num));
}
 int minSubArrayLen(int s, vector<int>& nums) {
     auto start = nums.begin();
     
     if(sumArray(nums.begin(),nums.end())<s) return 0;
     
     int min_len = nums.size();
     int sum=0;
     for(auto it=start;it!=nums.end();it++){
         sum+=*it;
         while(sum>=s) {
             if(distance(start,it)<min_len){
                 min_len=distance(start,it);
             }
             sum-=*start;
             start++;
         }
         
     }
     
     return min_len+1;
     
 }
Esempio n. 19
0
void packageAndSendToUart(int fd, const char *buff)//buff -- AT code
{
	unsigned char wbuf[N];

	unsigned char sum = 0;
	unsigned char checksum = 0;
	unsigned int ii = 0;

	size_t length = strlen(buff);
	//printf("len = %d\n",length);

	memset(wbuf, 0, N);
	wbuf[0] = '\0';
	memcpy(wbuf+1,buff,length);

	sum = sumArray(buff, length);
	//printf("sum = %02x\n",sum);
	checksum = 0xff - sum;
	wbuf[length+1] = checksum;
	wbuf[length+2] = '\r';
	wbuf[length+3] = '\n';

	write(fd,wbuf,length+4);

	printf("write:\n");
	for(ii = 0;ii < length+4;ii++)
		printf("%02x ",wbuf[ii]);
   	printf("\n");

	for(ii = 0;ii < length+4;ii++)
	{
		if(wbuf[ii] == '\r')
			continue;
		printf("%c",wbuf[ii]);
	}

}
Esempio n. 20
0
IloNum columnGeneration (IloCplex2 subSolver, IloCplex rmpSolver, 
	IloNumVarArray3 x, IloNumVarArray2 z, IloNumVarArray2 lambda,
	IloObjective2 reducedCost, IloObjective rmpObj,
	IloRangeArray2 maintConEng, IloRangeArray2 removeMod, IloRangeArray2 convex,
	IloNumArray2 addXCol, IloNumArray addZCol,
	IloNumArray2 priceRemoveMod, IloNumArray2 priceMaintConEng, IloNumArray priceConvex, 
	const IloNumArray2 compCosts, const IloNumArray convexityCoef,
	IloBool weightedDW_in, IloBool allowCustomTermination,
	IloInt relChangeSpan, IloNum relChange) {

	// extract optimization enviroment
	IloEnv env = rmpSolver.getEnv();
	
	
	// ANALYSIS: write to file
	const char*	output = "results/colGen_analysis.dat";
	
	// variable declarations..	
	
	// loop counters
	IloInt i, m, t, testCounter;

	testCounter = 0;

	// declare two clock_t objects for start and end time.		
	clock_t start, end;

	// declare an array of size NR_OF_MODULES to temporarily hold the
	// reduced costs from the NR_OF_MODULES different subproblems.
	IloNumArray redCosts(env, NR_OF_MODULES);

	IloBool weightedDW = weightedDW_in;

	// declare an array to hold the RMP objective values: e.g. add
	// one value to array for each iteration.
//	IloNumArray objValues(env);

	// declare an array to hold the lower bounds for the full MP, given
	//  	z(RMP)* + sum_[m in subproblems] redCost(m)^* <= z(full MP)^* <= z(RMP)^*
//	IloNumArray lowerBounds(env);

	// declare two temp IloNum objects for temporarily hold rmp objective value
	// and full MP lower bound. (full: MP with _all_ columns availible).
	IloNum tempRmpObj, tempLowerBound, bestLowerBound;
	bestLowerBound = -IloInfinity;

	// also use a num-array to hold the REL_CHANGE_SPAN most
	// recent RMP objective values. Used to the relative change
	// break criteria (if improvement by col-gen becomes to
	// "slow"/"flat").
	IloNumArray recentObjValues(env, REL_CHANGE_SPAN);

	// declare and initiate col-gen iteration counter
	IloInt itNum = 0;

	// ---- weighted DW decomp - for less trailing in colgen.
	//IloBool weightedDW = IloTrue;

	// declare two IloNum-array to hold all 2x (NR_OF_MODULES x TIME_SPAN)
	// dual vars - or specific, best dual vars (giving highest lower bound)
	IloNumArray2 dualsModBest(env);
	IloNumArray2 dualsEngBest(env);

	// temp..
	//IloBoolArray continueSub(env, NR_OF_MODULES);
	
	// allocate memory for sub-arrays
	for (m = 0; m < NR_OF_MODULES; m++) {

		dualsModBest.add(IloNumArray(env,TIME_SPAN));	
		dualsEngBest.add(IloNumArray(env,TIME_SPAN));

		//continueSub[m] = IloTrue;

		// and maybe: initially set all dual vars to 0?
		for (t = 0; t < TIME_SPAN; t++) {
			dualsModBest[m][t] = 0.0;
			dualsEngBest[m][t] = 0.0;
		}
	}

	// also, a weight for weighted DW:
	IloNum weight = 2.0;

	// counter number of improvements of "best duals"
	IloInt nrOfImprov = 0;

	// const used in weigt
	IloNum weightConst = DW_WEIGHT;

	// initiate numarray for recent objective values
	// UPDATE: this is not really needed now as we check the
	// relative change break criteria only when we know this
	// vector has been filled by REL_CHANGE_SPAN "proper" values...
	recentObjValues[0] = 0.0;
	for (i = 1; i < REL_CHANGE_SPAN; i++) {
		recentObjValues[i] = 0.0;
	}						

	// model before generation start:
	//rmpSolver.exportModel("rmpModel.lp");

	//write results to file
/*	ofstream outFile(output);

	outFile << "Writing out results from initial column generation, T=" << TIME_SPAN << endl
		<< "Form: [(itNum) (dual solution value) (upper bound = tempRmpObj)]" << endl << endl;*/


	//cout << endl << "WE GOT OURSELVES A SEGMENTATION FAULT!" << endl;

	// start timer
	start = clock();

	// also use an alternative time counter..
	time_t start2, end2;
	start2 = time(NULL);

	// loop until break...
	for (;;) {

		// increase iteration counter
		itNum++;

		// solve master
		if ( !rmpSolver.solve() ) {
       			env.error() << "Failed to optimize RMP." << endl;
			throw(-1);
		}
		
		// get the rmp objective value
		tempRmpObj = rmpSolver.getValue(rmpObj);

		// add to objective value array (size: iterations)
	//	objValues.add(tempRmpObj);

		// update recentObjValues:
		recentObjValues.remove(0);
			// remove oldest:
		recentObjValues.add(tempRmpObj);
			// save newest		

		// report something (... report1() )
		// UPDATE: colgen is to quick for anything to see anything reported... so skip this

		// update weight: weight = min{ 2,
		if (itNum>1) { 
			weight = (IloNum(itNum - 1) + IloNum(nrOfImprov))/2;
		}
		if ( weight > weightConst) {
			weight = weightConst;
		}	


		// update duals
		// -> updates obj. functions for subproblems (w.r.t. duals)
		for (m = 0; m < NR_OF_MODULES; m++) {

			//cout << "weight = " << weight << endl;
			//cin.get();

			for (t = 0; t < TIME_SPAN; t++) {

				// if we try weightedWD decomp:
				// for first iteration: just extract duals which will become best duals
				if (itNum > 1 && weightedDW) {

					// price associated with const. removeMod
					priceRemoveMod[m][t] = (rmpSolver.getDual(removeMod[m][t]))/weight + (weight-1)*(dualsModBest[m][t])/weight;

					// price associated with const. maintConEng
					priceMaintConEng[m][t] = (rmpSolver.getDual(maintConEng[m][t]))/weight + (weight-1)*(dualsEngBest[m][t])/weight;	

				}
				// normally:
				else {

					// price associated with const. removeMod
					priceRemoveMod[m][t] = rmpSolver.getDual(removeMod[m][t]);

					// price associated with const. maintConEng
					priceMaintConEng[m][t] = rmpSolver.getDual(maintConEng[m][t]);
				}

				//cout << "priceRemoveMod[m][t] = " << priceRemoveMod[m][t] << endl;

				// update subproblem obj. function coefficients for z[m][t] vars:
				reducedCost[m].setLinearCoef(z[m][t],-(priceRemoveMod[m][t] + priceMaintConEng[m][t]));
			} 

			//cin.get();

			// rmpSolver.getDuals(priceRemoveMod[m], removeMod[m]);
			// rmpSolver.getDuals(priceMaintConEng[m], maintConEng[m]);
			// priceConvex[m] = -rmpSolver.getDual(convex[m][0]);
				
			// if we try weightedWD decomp:
			// for first iteration: just extract duals which will become best duals
	/*		if (itNum > 1 && weightedDW) {

				// price associated with convexity constraint
				priceConvex[m] = -abs(rmpSolver.getDual(convex[m][0]))/weight - (weight-1)*(dualsConvBest[m])/weight;
			} */
		
			// price associated with convexity constraint
			priceConvex[m] = -abs(rmpSolver.getDual(convex[m][0]));

			// update subproblem obj. function's constant term
			reducedCost[m].setConstant(priceConvex[m]);
			
		} // END of updating duals

		// solve subproblems
		for (m = 0; m < NR_OF_MODULES; m++) {

			//if (continueSub[m]) {

				// solve subproblem m
				cout << endl << "Solving subproblem #" << (m+1) << "." << endl;
				if ( !subSolver[m].solve() ) {
       					env.error() << "Failed to optimize subproblem #" << (m+1) << "." << endl;
       					throw(-1);
				}
		
				// extract reduced cost: subSolver[m].getValue(reducedCost[m])
				// into a IloNumArray(env, NR_OF_MODULES) at position m.				
				redCosts[m] = subSolver[m].getValue(reducedCost[m]);

				//env.out() << endl << "Reduced cost for problem #" << (m+1) << ":" << redCosts[m] << endl;

				// if reduced cost is negative, att optimal solution to
				// column pool Q(m)
				if (!(redCosts[m] > -RC_EPS)) {
					
					// add column		
					addColumn(subSolver[m], x[m], z[m], lambda[m], rmpObj, maintConEng[m], removeMod[m],
						convex[m], addXCol, addZCol, compCosts[m], convexityCoef);

					//env.out() << endl << "Added a column to pool Q(" << (m+1) 
					//	<< "). Lambda[" << (m+1) << "].size = " << lambda[m].getSize() << endl; 

					testCounter++;
				}	
				//else {
				//	continueSub[m] = IloFalse;
				//}
			//}
			//else {
			//	redCosts[m] = 0;
			//}	


		} // END of solving subproblems (for this iteration)

		// calculate lower bound on full MP
		tempLowerBound = tempRmpObj + sumArray(redCosts);

		// update best lower bound
		if (tempLowerBound > bestLowerBound) {
			bestLowerBound = tempLowerBound;
		
			// increase counter for number of improved "best duals".
			nrOfImprov++;

			//cout << endl << "WHATEVAAAH" << endl;
			//cin.get();

			// save best duals
			for (m = 0; m < NR_OF_MODULES; m++) {
				for (t = 0; t < TIME_SPAN; t++) {			
					dualsModBest[m][t] = priceRemoveMod[m][t];
					dualsEngBest[m][t] = priceMaintConEng[m][t];
				}
			}
		}						

		// update lower bounds vector
		//lowerBounds.add(bestLowerBound);
		
		// ANALYSIS: print out to file:
		// [(itNum) (dual solution value) (upper bound = tempRmpObj)]
		//outFile << itNum << " " << tempLowerBound << " " << tempRmpObj << endl;

		// if the smallest reduced cost in the updated red-cost vector 
		// with NR_OF_MODULES entries is greater than -RC_EPS: break
		// otherwise, repeat.
		if (minMemberValue(redCosts) > -RC_EPS) {
			env.out() << endl << "All reduced costs non-negative: breaking." << endl;
			bestLowerBound = tempRmpObj;
			break;
		}

		// if relative change in objective value over the last REL_CHANGE_SPAN iterations is
		// less than REL_CHANGE, break.
		//if (allowCustomTermination && (itNum >= REL_CHANGE_SPAN) && (relativeImprovement(recentObjValues) < REL_CHANGE)) {
		if (allowCustomTermination && (itNum >= relChangeSpan) && (relativeImprovement(recentObjValues) < relChange)) {
			env.out() << endl << "Relative change smaller than pre-set acceptance: breaking." << endl;
			break;
		}													

		// if the gap currentUpperBound - currentLowerBound is small enough, break
		if ((tempRmpObj - bestLowerBound) < RC_EPS) {
			env.out() << endl << "Lower<>Upper bound gap less than pre-set acceptance: breaking." << endl;
			cout << endl << "(tempRmpObj - bestLowerBound) = " << (tempRmpObj - bestLowerBound) << endl;
			bestLowerBound = tempRmpObj;
			break;
		}


	} // END of column generation.
		
	// alternative: print the REL_CHANGE_SPAN most recent RMP objective values		
	env.out() << endl;
	/*for (i = 0; i < recentObjValues.getSize(); i++) {
		env.out() << "Recent #" << (i+1) << ": " << recentObjValues[i] << endl;
	}*/

	// solve master using final column setup
      	if ( !rmpSolver.solve() ) {
        	env.error() << "Failed to optimize RMP." << endl;
        	throw(-1);
      	}

	// also add final objective value to objective value array (size: iterations)
//	objValues.add(rmpSolver.getValue(rmpObj));

	// create IloNum object and extract the final RMP objective value.
	IloNum finalObj;
	finalObj = rmpSolver.getValue(rmpObj);

	// end program time counter(s)
	end = clock();
	end2 = time(NULL);

	// print result to file
	//outFile << endl << endl << "Final objective value: " << finalObj << endl
	//	<< "Time required for execution: " << (double)(end-start)/CLOCKS_PER_SEC << " seconds." << endl;

	// outfile.close()	
	//outFile.close(); 
	itNum = 0;
		// re- use iteration counter to count total number of columns generated

	// nr of columns generated from each subproblem		
	for (m = 0; m < NR_OF_MODULES; m++) {
		// ### outFile << "Number of columns generated from subproblem (m = " << m << "): " << (lambda[m].getSize() - 1) << endl;
		cout << "Number of columns generated from subproblem (m = " << m << "): " << (lambda[m].getSize() - 1) << endl;
		//outFile << "Pool (m = " << m << "): " << (lambda[m].getSize() - 1) << endl;
		
		itNum += lambda[m].getSize();
	}
 
	// ###
/*	outFile << endl << "Total number of columns generated: " << itNum << endl;
	outFile << "Time required for column generation: " << (double)(end-start)/CLOCKS_PER_SEC << " seconds." << endl;
	outFile << "ALTERNATIVE: Time required for colgen: " << end2-start2 << " seconds." << endl;
	outFile << "RMP objective function cost: " << finalObj << endl << endl;
	//outFile << "Objective function values for each iteration: " << endl;		
	//outFile << objValues;
	//outFile << endl << endl << "Lower bounds for each iteration: " << endl; 
	//outFile << lowerBounds;
	outFile.close(); */

	//cout << "Initial column generation complete, press enter to continue..." << endl;
	//cin.get();


	// print some results..
	/*env.out() << endl << "RMP objective function cost: " << finalObj << endl;
	env.out() << endl << "Size of objective value vector: " << objValues.getSize() << endl;
	env.out() << endl << "Nr of iterations: " << itNum << endl;	

	cout << endl << "Number of new columns generated: " << testCounter << endl;*/		

	// Note: to explicit output (void function), ass columns are added implicitely via 
	// income argument pointers.		
					
	// clear memory assigned to temporary IloNumArrays:
	redCosts.end();
	//objValues.end();	
	//lowerBounds.end();	
	recentObjValues.end();

	// save best duals
	for (m = 0; m < NR_OF_MODULES; m++) {
		dualsModBest[m].end();
		dualsEngBest[m].end();
	}
	dualsModBest.end();
	dualsEngBest.end();
	//continueSub.end();	

	//cout << endl << "NR OF IMPROVEMENTS: " << nrOfImprov << endl;
	//cin.get();

	// return lower bound
	return bestLowerBound;	

} // END of columnGeneration()
int sumArray(int n, int& sum)
{
	sum += n;
	(n > 0) && sumArray(n-1, sum);
}
Esempio n. 22
0
void engine(double *mesh, hydro_prob *Hyp, hydro_args *Hya){
  int n, i,j;
  int bndL;
  int bndH;
  double dt;
  double cTime, nxttout;

  double volCell;
  double oTM,oTE;
  double TM,TE;
  int M_exp, E_exp;
  double M_prec, E_prec;

  char outfile[30];

  size_t primSize, qSize, flxSize;

  double initT, endT;

  Hp=Hyp;
  Ha=Hya;

  n=0;
  cTime=0;
  nxttout=-1.0;
  
  if(Hp->ny>=Hp->nx){
    primSize=Hp->nvar*(Hp->nx+4)*Hp->ny;
    qSize   =Hp->nvar*(Hp->nx+2)*Hp->ny;
    flxSize =Hp->nvar*(Hp->nx+1)*Hp->ny;
  }else{
    primSize=Hp->nvar*(Hp->ny+4)*Hp->nx;
    qSize   =Hp->nvar*(Hp->ny+2)*Hp->nx;
    flxSize =Hp->nvar*(Hp->ny+1)*Hp->nx;
  }

  if(Ha->nstepmax<0&&Ha->tend<0.0)return;

  q  =(double*)malloc(primSize*sizeof(double));
  qr =(double*)malloc(qSize*sizeof(double));
  ql =(double*)malloc(qSize*sizeof(double));
  flx=(double*)malloc(flxSize*sizeof(double));

  if(Ha->tend>0.0){
    nxttout=Ha->tend;
  }
  if(Ha->dtoutput>0.0&&nxttout>Ha->dtoutput){
    nxttout=Ha->dtoutput;
  }

  volCell=Hp->dx*Hp->dy;
  oTM=sumArray(mesh,VARRHO,Hp->nx,Hp->ny);
  oTE=sumArray(mesh,VARPR ,Hp->nx,Hp->ny);
#ifdef M_PREC_CMP
  frexp(oTM,&M_exp);
  frexp(oTE,&E_exp);

  M_prec=ldexp(DBL_EPSILON,M_exp-1);
  E_prec=ldexp(DBL_EPSILON,E_exp-1);

  printf("TM:%g+-%g TE:%g+-%g\n",volCell*oTM,volCell*M_prec,volCell*oTE,volCell*E_prec);
#endif

  //Print initial condition
  snprintf(outfile,29,"%s%05d",Ha->outPre,n);
  writeVis(outfile,mesh,Hp->dx,Hp->dy,Hp->nvar,Hp->nx,Hp->ny);
  printf("INIT: TM: %g TE: %g\n",volCell*oTM,volCell*oTE);
  
  initT=omp_get_wtime();

  while((n<Ha->nstepmax||Ha->nstepmax<0)&&(cTime<Ha->tend||Ha->tend<0)){
    //Calculate timestep
    dt=Ha->sigma*calcDT(mesh);
    if(nxttout>0.0&&dt>(nxttout-cTime)){
      printf("Adjusting timestep from %g to %g for iter %d\n",dt,nxttout-cTime,n);
      dt=(nxttout-cTime);
    }
    if(n%2==0){
      //X Dir
      runPass(mesh,dt,n,0);
      //Y Dir
      runPass(mesh,dt,n,1);
    }else{
      //Y Dir
      runPass(mesh,dt,n,1);
      //X Dir
      runPass(mesh,dt,n,0);
    }
    n+=1;
    cTime+=dt;
    if(n%Ha->nprtLine==0){
      TM=sumArray(mesh,VARRHO,Hp->nx,Hp->ny);
      TE=sumArray(mesh,VARPR ,Hp->nx,Hp->ny);
      printf("Iter %05d time %f dt %g TM: %g TE: %g\n",n,cTime,dt,volCell*TM,volCell*TE);
      if(0&&(fabs(TM-oTM)>0.0||fabs(TE-oTE)>0.0)){
	printf("ERR(%5s): Mass %g Ene %g\n","RAW",volCell*(TM-oTM),volCell*(TE-oTE));
	printf("ERR(%5s): Mass %g Ene %g\n","%",100.0*(TM-oTM)/oTM,100.0*(TE-oTE)/oTE);
#ifdef M_PREC_CMP
	printf("ERR(%5s): Mass %g Ene %g\n","M PRE",(TM-oTM)/M_prec,(TE-oTE)/E_prec);
#endif
      }
    }
    if((cTime>=nxttout&&nxttout>0)||(Ha->noutput>0&&n%Ha->noutput==0)){
      printf("Vis file @ time %f iter %d\n",cTime,n);
      if(cTime>=nxttout&&nxttout>0.0){
	nxttout+=Ha->dtoutput;
	if(nxttout>Ha->tend&&Ha->tend>0)nxttout=Ha->tend;
	//printf("Next Vis Time: %f\n",nxttout);
      }
      snprintf(outfile,29,"%s%05d",Ha->outPre,n);
      writeVis(outfile,mesh,Hp->dx,Hp->dy,Hp->nvar,Hp->nx,Hp->ny);
    }
  }
  printf("time: %f, %d iters run\n",cTime,n);

  endT=omp_get_wtime();

  printf("TFMT:%s,%s,%s,%s,%s,%s,%s,%s\n","cType","mType","init","nproc","nth","niters","ncells","wRunt");
  printf("TIME:%s,%s,%s,%d,%d,%d,%d,%g\n","\"OMP\"","\"CPU:?\"","\"Init\"",1,omp_get_max_threads(),n,Hp->nx*Hp->ny,(endT-initT));

  //Print final condition
  snprintf(outfile,29,"%s%05d",Ha->outPre,n);
  writeVis(outfile,mesh,Hp->dx,Hp->dy,Hp->nvar,Hp->nx,Hp->ny);

  Hp->t+=cTime;
  free(q  );
  free(qr );
  free(ql );
  free(flx);
}
Esempio n. 23
0
void test1() {
  double s = sumArray(n, a);
  printf("sumArray=%lf\n", s);
}
Esempio n. 24
0
TTree* execute()
{

    // q is simply a prefix for values which are a branch on the TTree
    TTree * dataTree = new TTree("treeData", "treeData");
    float qChargeValues[7];
    float qTotalCharge;
    float qMeasurementTimes[7];
    float qCurrentValues[7];
    float qVoltageValuesPreNoise[7];
    float qVoltageValuesPostNoise[7];
    int qDigitalReadoutValues[7];
    float qFitShiftingTime;
    float qFitScalingFactor;
    int qTotalDigitalReadoutValue;
    int qDifferenceDigitalReadoutValue;
    float qIntegralReadoutValue;

    dataTree->Branch("qChargeValues", qChargeValues, "qChargeValues[7]/F");
    dataTree->Branch("qTotalCharge", &qTotalCharge, "qTotalCharge/F");
    dataTree->Branch("qMeasurementTimes", qMeasurementTimes, "qMeasurementTimes[7]/F"); 
    dataTree->Branch("qCurrentValues", qCurrentValues, "qCurrentValues[7]/F"); 
    dataTree->Branch("qVoltageValuesPreNoise", qVoltageValuesPreNoise, "qVoltageValuesPreNoise[7]/F"); 
    dataTree->Branch("qVoltageValuesPostNoise", qVoltageValuesPostNoise, "qVoltageValuesPostNoise[7]/F"); 
    dataTree->Branch("qDigitalReadoutValues", qDigitalReadoutValues, "qDigitalReadoutValues[7]/I");
    dataTree->Branch("qFitShiftingTime", &qFitShiftingTime, "qFitShiftingTime/F");
    dataTree->Branch("qFitScalingFactor", &qFitScalingFactor, "qFitScalingFactor/F");
    dataTree->Branch("qTotalDigitalReadoutValue", &qTotalDigitalReadoutValue, "qTotalDigitalReadoutValue/I");
    dataTree->Branch("qDifferenceDigitalReadoutValue", &qDifferenceDigitalReadoutValue, "qDifferenceDigitalReadoutValue/I");
    dataTree->Branch("qIntegralReadoutValue", &qIntegralReadoutValue, "qIntegralReadoutValue/F");


    const int numTrials = 10000; // Set number of trials
    const float shapingTime = 40.0;
    const float shapingPower = 1.0;

    ElectronSimulation * eSim = new ElectronSimulation();

    for (int i = 0; i < numTrials; ++i)
    {
        TrialDataSet eSimData;
        eSim->simulate(eSimData, shapingTime, shapingPower);

        qTotalCharge = sumArray(eSimData.chargeValues, 7);
        qTotalDigitalReadoutValue = sumArray(eSimData.digitalReadoutValues, 7);
        qDifferenceDigitalReadoutValue = maxArray(eSimData.digitalReadoutValues, 7) - eSimData.digitalReadoutValues[0];




        TF1 * fittedFunction = eSim->computeFunctionFit(eSimData);
        qFitShiftingTime = fittedFunction->GetParameter(0);
        qFitScalingFactor = fittedFunction->GetParameter(1);
        qIntegralReadoutValue = eSim->integrateFunc(qFitScalingFactor);
        fittedFunction->Draw();

        for (int j = 0; j<7; ++j)
            {
                qChargeValues[j] = eSimData.chargeValues[j];
                qMeasurementTimes[j] = eSimData.measurementTimes[j];
                qCurrentValues[j] = eSimData.currentValues[j];
                qVoltageValuesPreNoise[j] = eSimData.voltageValuesPreNoise[j];
                qVoltageValuesPostNoise[j] = eSimData.voltageValuesPostNoise[j];
                qDigitalReadoutValues[j] = eSimData.digitalReadoutValues[j];
            }
        dataTree->Fill();
    }

    return dataTree;


}