void CPLEX_LP_IMSTSolver_v2::generateAddDropVariablesConstraint(
		VertexIdx const sourceVertexIdx, VertexIdx const targetVertexIdx) {
	INFO(logger,
			baseLPMSTSolution.at(sourceVertexIdx).at(targetVertexIdx) ?
					LogBundleKey::CPLPIMST2_BUILD_MODEL_ADD_VAR_CONSTRAINT_1 :
					LogBundleKey::CPLPIMST2_BUILD_MODEL_ADD_VAR_CONSTRAINT_0,
			LogStringUtils::edgeVisualization(
					graph->findEdge(sourceVertexIdx, targetVertexIdx), "\t").c_str(),
			sourceVertexIdx, targetVertexIdx, sourceVertexIdx, targetVertexIdx,
			getVariableName(
					edgeAddVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str());
	model.add(
			edgeAddVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first
					<= 1
							- baseLPMSTSolution.at(sourceVertexIdx).at(
									targetVertexIdx));

	INFO(logger,
			baseLPMSTSolution.at(sourceVertexIdx).at(targetVertexIdx) ?
					LogBundleKey::CPLPIMST2_BUILD_MODEL_DROP_VAR_CONSTRAINT_1 :
					LogBundleKey::CPLPIMST2_BUILD_MODEL_DROP_VAR_CONSTRAINT_0,
			LogStringUtils::edgeVisualization(
					graph->findEdge(sourceVertexIdx, targetVertexIdx), "\t").c_str(),
			sourceVertexIdx, targetVertexIdx, sourceVertexIdx, targetVertexIdx,
			getVariableName(
					edgeDropVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str());

	model.add(
			edgeDropVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first
					<= baseLPMSTSolution.at(sourceVertexIdx).at(
							targetVertexIdx));
}
void CPLEX_LP_IMSTSolver_v2::generateFlowVariables() {
	EdgeIdx edgeIdCount { };
	VertexIdx sourceVertexIdx { };
	VertexIdx targetVertexIdx { };
	EdgeIF* edge { };
	VertexIF* vertex { };

	flowVariables = IloNumVarArray(env, 2 * numberOfEdges, 0, IloInfinity);

	INFO_NOARG(logger, LogBundleKey::CPLPIMST2_FLOW_GEN);

	if (graph->hasAnyVertex(Visibility::VISIBLE)) {
		initialVertexIdx = graph->nextVertex()->getVertexIdx();

		INFO(logger, LogBundleKey::CPLPIMST2_FLOW_GEN_INIT_NODE,
				initialVertexIdx);

		flowVariablesMap.insert(
				std::make_pair(initialVertexIdx,
						IloTargetVertexFlowVarMap { }));

		while (graph->hasNextVertex(Visibility::VISIBLE)) {
			flowVariablesMap.insert(
					std::make_pair(graph->nextVertex()->getVertexIdx(),
							IloTargetVertexFlowVarMap { }));
		}

		edgeIdCount = 0;

		graph->beginEdge();
		while (graph->hasNextEdge(Connectivity::CONNECTED, Visibility::VISIBLE)) {
			edge = graph->nextEdge();
			sourceVertexIdx = edge->getSourceVertex()->getVertexIdx();
			targetVertexIdx = edge->getTargetVertex()->getVertexIdx();

			INFO(logger, LogBundleKey::CPLPIMST2_FLOW_GEN_VAR, sourceVertexIdx,
					targetVertexIdx,
					getVariableName(flowVariables[edgeIdCount]).c_str());

			flowVariablesMap.at(sourceVertexIdx).insert(
					std::make_pair(targetVertexIdx,
							flowVariables[edgeIdCount]));

			edgeIdCount += 1;

			INFO(logger, LogBundleKey::CPLPIMST2_FLOW_GEN_VAR, sourceVertexIdx,
					targetVertexIdx,
					getVariableName(flowVariables[edgeIdCount]).c_str());

			flowVariablesMap.at(targetVertexIdx).insert(
					std::make_pair(sourceVertexIdx,
							flowVariables[edgeIdCount]));

			edgeIdCount += 1;
		}
	}
}
Esempio n. 3
0
String Tableau::toString(int fieldSize, int decimals) const {
  const String  matrixFormatString = format(_T("%%%d.%dlg "), fieldSize, decimals);
  const TCHAR  *matrixFormat       = matrixFormatString.cstr();
  const int     width              = getWidth();
  const int     constraintCount    = getConstraintCount();

#define NEWLINE _T('\n')

  const String separatorLine = format(_T("%s\n"), spaceString(12 + (width+1) * (fieldSize+1) + 3,_T('_')).cstr());

  String result;
  result += format(_T("%-23sB %-*s"), format(_T("size:%dx%d"),getConstraintCount(),getWidth()).cstr(),fieldSize-8,EMPTYSTRING);

  for(int col = 1; col <= width; col++) {
    result += format(_T("%*s "), fieldSize, getVariableName(col).cstr());
  }
  result += NEWLINE;
  result += separatorLine;

  result += format(_T("%-*s"), 17+fieldSize, _T("Orig. cost: "));
  for(int col = 1; col <= getXCount(); col++) {
    result += format(matrixFormat, getDouble(m_costFactor[col]));
  }
  result += NEWLINE;
  result += _T("ObjectValue:");

  result += format(matrixFormat, getDouble(getObjectValue()));
  result += _T("    "); // filler instead of relation
  for(int col = 1; col <= width; col++) {
    result += format(matrixFormat, getDouble(getObjectFactor(col)));
  }
  result += NEWLINE;
  result += separatorLine;

  const bool printOriginalRelation = (m_slackCount == 0);
  for(int r = 1; r <= constraintCount; r++ ) {
    const TableauRow &row = m_table[r];
    result += format(_T("%3d %-6s ="),r, getVariableName(row.m_basisVariable).cstr());
    result += format(matrixFormat,getDouble(getRightSide(r)));
    result += format(_T(" %-2s "), printOriginalRelation ? getRelationString(reverseRelation(row.m_relation)) : _T("="));
    for(int col = 1; col <= width; col++) {
      result += format(matrixFormat,getDouble(row.m_a[col]));
    }
    result += NEWLINE;
  }

  return result;
}
void CPLEX_LP_IMSTSolver_v2::generateFlowBoundsConstraints() {
	EdgeIF* edge { };
	VertexIdx sourceVertexIdx { };
	VertexIdx targetVertexIdx { };
	EdgeCount flowUpperBound { numberOfVertices - 1 };

	INFO_NOARG(logger,
			LogBundleKey::CPLPIMST2_BUILD_MODEL_FLOW_BOUNDS_CONSTRAINTS);

	graph->beginEdge();
	while (graph->hasNextEdge(Connectivity::CONNECTED, Visibility::VISIBLE)) {
		edge = graph->nextEdge();
		sourceVertexIdx = edge->getSourceVertex()->getVertexIdx();
		targetVertexIdx = edge->getTargetVertex()->getVertexIdx();

		INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_FLOW_BOUNDS_CONSTRAINT,
				sourceVertexIdx, targetVertexIdx, flowUpperBound,
				sourceVertexIdx, targetVertexIdx,
				getVariableName(
						flowVariablesMap.at(sourceVertexIdx).at(
								targetVertexIdx)).c_str(), flowUpperBound,
				getVariableName(
						edgeVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str());

		model.add(
				flowVariablesMap.at(sourceVertexIdx).at(targetVertexIdx)
						<= IloNum(flowUpperBound)
								* edgeVariableMap.at(sourceVertexIdx).at(
										targetVertexIdx).first);

		INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_FLOW_BOUNDS_CONSTRAINT,
				targetVertexIdx, sourceVertexIdx, flowUpperBound,
				sourceVertexIdx, targetVertexIdx,
				getVariableName(
						flowVariablesMap.at(targetVertexIdx).at(
								sourceVertexIdx)).c_str(), flowUpperBound,
				getVariableName(
						edgeVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str());

		model.add(
				flowVariablesMap.at(targetVertexIdx).at(sourceVertexIdx)
						<= IloNum(flowUpperBound)
								* edgeVariableMap.at(sourceVertexIdx).at(
										targetVertexIdx).first);

	}
}
void CPLEX_LP_IMSTSolver_v2::generateGoal() {
	IloExpr goalFormula(env);
	IloInt i { };
	IloInt varArraySize { };
	EdgeIF* edge { };

	INFO_NOARG(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_GOAL_CONSTRAINT);

	graph->beginEdge();
	while (graph->hasNextEdge(Connectivity::CONNECTED, Visibility::VISIBLE)) {
		edge = graph->nextEdge();
		INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_GOAL_ADD,
				edge->getSourceVertex()->getVertexIdx(),
				edge->getTargetVertex()->getVertexIdx(),
				edge->getSourceVertex()->getVertexIdx(),
				edge->getTargetVertex()->getVertexIdx(), edge->getEdgeCost(),
				baseLPMSTSolution.at(edge->getSourceVertex()->getVertexIdx()).at(
						edge->getTargetVertex()->getVertexIdx()) ? '1' : '0');

		goalFormula +=
				edge->getEdgeCost()
						* baseLPMSTSolution.at(
								edge->getSourceVertex()->getVertexIdx()).at(
								edge->getTargetVertex()->getVertexIdx());
	}

	INFO_NOARG(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_GOAL_INCR_CONSTRAINT);

	graph->beginEdge();
	while (graph->hasNextEdge(Connectivity::CONNECTED, Visibility::VISIBLE)) {
		edge = graph->nextEdge();
		INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_GOAL_INCR_ADD,
				edge->getSourceVertex()->getVertexIdx(),
				edge->getTargetVertex()->getVertexIdx(),
				edge->getSourceVertex()->getVertexIdx(),
				edge->getTargetVertex()->getVertexIdx(),
				edge->getSourceVertex()->getVertexIdx(),
				edge->getTargetVertex()->getVertexIdx(), edge->getEdgeCost(),
				getVariableName(getAddEdgeVariable(edge)).c_str(),
				getVariableName(getDropEdgeVariable(edge)).c_str());

		goalFormula += edge->getEdgeCost()
				* (getAddEdgeVariable(edge) - getDropEdgeVariable(edge));
	}

	model.add(IloMinimize(env, goalFormula));
}
void CPLEX_LP_IMSTSolver_v2::generateFlowConstraint(VertexIF* const vertex,
		int cost) {
	IloExpr inputFlow(env);
	IloExpr outputFlow(env);
	VertexIdx targetVertexIdx { };
	VertexIdx sourceVertexIdx { vertex->getVertexIdx() };

	INFO(logger,
			(cost == numberOfVertices - 1) ?
					LogBundleKey::CPLPIMST2_BUILD_MODEL_FLOW_SRC_CONSTRAINT :
					LogBundleKey::CPLPIMST2_BUILD_MODEL_FLOW_CONSTRAINT,
			vertex->getVertexIdx());

	vertex->beginOutputEdges();
	while (vertex->hasNextOutputEdge(Visibility::VISIBLE)) {
		targetVertexIdx =
				vertex->nextOutputEdge()->getOtherVertex(vertex)->getVertexIdx();
		INFO(logger,
				LogBundleKey::CPLPIMST2_BUILD_MODEL_FLOW_CONSTRAINT_ADD_OUT,
				sourceVertexIdx, targetVertexIdx,
				getVariableName(
						flowVariablesMap.at(sourceVertexIdx).at(
								targetVertexIdx)).c_str());
		outputFlow += flowVariablesMap.at(sourceVertexIdx).at(targetVertexIdx);
	}

	targetVertexIdx = sourceVertexIdx;

	vertex->beginInputEdges();
	while (vertex->hasNextInputEdge(Visibility::VISIBLE)) {
		sourceVertexIdx =
				vertex->nextInputEdge()->getOtherVertex(vertex)->getVertexIdx();
		INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_FLOW_CONSTRAINT_ADD_IN,
				sourceVertexIdx, targetVertexIdx,
				getVariableName(
						flowVariablesMap.at(sourceVertexIdx).at(
								targetVertexIdx)).c_str());
		inputFlow += flowVariablesMap.at(sourceVertexIdx).at(targetVertexIdx);
	}

	model.add(outputFlow - inputFlow == cost);

	inputFlow.end();
	outputFlow.end();
}
void CPLEX_LP_IMSTSolver_v2::generateIncrementalSolutionConstraint(
		VertexIdx const sourceVertexIdx, VertexIdx const targetVertexIdx) {
	INFO(logger, LogBundleKey::CPLPIMST2_BUILD_MODEL_SOLUTION_VAR_CONSTRAINT,
			sourceVertexIdx, targetVertexIdx, sourceVertexIdx, targetVertexIdx,
			sourceVertexIdx, targetVertexIdx, sourceVertexIdx, targetVertexIdx,
			getVariableName(
					edgeVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str(),
			getVariableName(
					edgeAddVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str(),
			getVariableName(
					edgeDropVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str(),
			baseLPMSTSolution.at(sourceVertexIdx).at(targetVertexIdx) ?
					'1' : '0');
	model.add(
			edgeVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first
					== edgeAddVariableMap.at(sourceVertexIdx).at(
							targetVertexIdx).first
							- edgeDropVariableMap.at(sourceVertexIdx).at(
									targetVertexIdx).first
							+ baseLPMSTSolution.at(sourceVertexIdx).at(
									targetVertexIdx));
}
Esempio n. 8
0
void Tableau::pivot(size_t pivotRow, size_t pivotColumn, bool primalSimplex) {
  TableauRow &row = m_table[pivotRow];
  const int leaveBasis = row.m_basisVariable;
  const int enterBasis = (int)pivotColumn;

  row.m_basisVariable = (int)pivotColumn;

  const Real &factor = row.m_a[pivotColumn];
  const String enteringVarName = getVariableName(enterBasis);
  const String leavingVarName  = getVariableName(leaveBasis);

  if(isTracing(TRACE_PIVOTING)) {
    if(primalSimplex) {
      trace(_T("pivot(%2s,%2s). %s -> %s. Cost[%s]:%-15.10lg   Tab[%2s,%2s]=%-15.10lg   Minimum:%-15.10lg")
            ,FSZ(pivotRow),FSZ(pivotColumn)
            ,enteringVarName.cstr(),leavingVarName.cstr()
            ,enteringVarName.cstr(),getDouble(getObjectFactor(pivotColumn))
            ,FSZ(pivotRow),FSZ(pivotColumn),getDouble(factor)
            ,getDouble(getObjectValue()));
    } else {
      trace(_T("pivot(%2s,%2s). %s -> %s. %s=B[%2s]:%-15.10lg  Tab[%2s,%2s]=%-15.10lg   Minimum:%-15.10lg")
            ,FSZ(pivotRow),FSZ(pivotColumn)
            ,enteringVarName.cstr(),leavingVarName.cstr()
            ,leavingVarName.cstr(),FSZ(pivotRow),getDouble(getRightSide(pivotRow))
            ,FSZ(pivotRow),FSZ(pivotColumn),getDouble(factor)
            ,getDouble(getObjectValue()));
    }
  }

  multiplyRow(pivotRow,1.0/factor);

  for(int dstRow = 0; dstRow <= getConstraintCount(); dstRow++) {
    if(dstRow != (int)pivotRow) {
      addRowsToGetZero(dstRow,pivotRow,pivotColumn);
    }
  }
}
Esempio n. 9
0
/*
** plot
** Plots the data in the buffer
*/
void ofxOscilloscope::plot(){

	// Legend Background
	ofEnableAlphaBlending();
	ofSetColor(_backgroundColor);
	ofPoint legendMax = ofPoint(_min.x + _legendWidth, _max.y);
	ofRect(ofRectangle(_min, legendMax));
	ofDisableAlphaBlending(); 

	for (int i=0; i<_scopePlot.getNumVariables(); i++) {
		// Legend Text
		ofSetColor(_scopePlot.getVariableColor(i));
		_legendFont.drawString(getVariableName(i), 
			_min.x + _legendPadding, _min.y + _legendPadding + _textSpacer*(i+1));
	}	

	// Sets the zero line width when called before plot()
	ofSetLineWidth(_outlineWidth);

	// Plot the Data
	_scopePlot.plot();

	ofSetColor(_outlineColor);
	ofSetLineWidth(_outlineWidth);

	ofEnableAlphaBlending();

	// Legend outline
	ofLine(_min.x,					_min.y,	_min.x,					_max.y);
	ofLine(_min.x,					_max.y,	_min.x + _legendWidth,	_max.y);
	ofLine(_min.x + _legendWidth,	_max.y,	_min.x + _legendWidth,	_min.y);
	ofLine(_min.x + _legendWidth,	_min.y,	_min.x,					_min.y);

	// Scope outline
	//ofLine(_min.x, _min.y, _min.x, _max.y);
	ofLine(_min.x + _legendWidth,	_max.y, _max.x,					_max.y);
	ofLine(_max.x,					_max.y,	_max.x,					_min.y);
	ofLine(_max.x,					_min.y, _min.x + _legendWidth,	_min.y);

	// Timescale
	_legendFont.drawString(ofToString(_scopePlot.getTimeWindow()) + " sec," + " yScale=" + ofToString(getYScale())
		+ ", yOffset=" + ofToString(getYOffset(), 1), 
	_min.x + _legendWidth + _legendPadding, 
	_max.y - _legendPadding);

	ofDisableAlphaBlending(); 
}
void CPLEX_LP_IMSTSolver_v2::createEdgeVariables(GraphIF * const graph,
		IloNumVar::Type edgeVariablesType) {
	EdgeIdx edgeId { };
	VertexIdx sourceVertexIdx { };
	VertexIdx targetVertexIdx { };
	EdgeIF* edge { };
	IteratorId edgeIterator = graph->getEdgeIteratorId();

	INFO(logger, LogBundleKey::CPLPIMST2_EDGE_VAR_GEN,
			graph->getNumberOfEdges(Visibility::VISIBLE),
			EnumUtils::getLPVariableTypeString(
					static_cast<unsigned int>(edgeVariablesType)));
	edgeVariableArray = IloNumVarArray(env,
			graph->getNumberOfEdges(Visibility::VISIBLE), 0, 1,
			edgeVariablesType);
	model.add(edgeVariableArray);

	graph->beginEdge(edgeIterator);

	while (graph->hasNextEdge(edgeIterator, Connectivity::CONNECTED,
			Visibility::VISIBLE)) {
		edge = graph->nextEdge(edgeIterator);
		sourceVertexIdx = edge->getSourceVertex()->getVertexIdx();
		targetVertexIdx = edge->getTargetVertex()->getVertexIdx();

		if (edgeVariableMap.count(sourceVertexIdx) == 0) {
			edgeVariableMap.insert(
					std::make_pair(sourceVertexIdx,
							IloTargetVertexEdgeVarMap()));
		}

		edgeVariableMap.at(sourceVertexIdx).insert(
				std::make_pair(targetVertexIdx,
						std::make_pair(edgeVariableArray[edgeId], edge)));

		INFO(logger, LogBundleKey::CPLPIMST2_EDGE_VAR_ADD,
				LogStringUtils::edgeVisualization(
						edgeVariableMap.at(sourceVertexIdx).at(targetVertexIdx).second,
						"\t").c_str(), sourceVertexIdx, targetVertexIdx,
				getVariableName(
						edgeVariableMap.at(sourceVertexIdx).at(targetVertexIdx).first).c_str());

		edgeId += 1;
	}

	graph->removeEdgeIterator(edgeIterator);
}
FormRestrictions FormFieldRestrictedValues::getRestrictions(QList<FormFieldDescriptorConstPtr> formFields, ArtemisWebPagePtr page)
{
    QSet<SelectRestriction> selects;
    QMap<QString, RadioRestriction > radioGroups;

    // Loop through form fields and add them to selects or radios (or ignore) as appropriate.
    foreach(FormFieldDescriptorConstPtr field, formFields) {
        if (field->getType() == FIXED_INPUT) {
            SelectRestriction result;
            result.variable = getVariableName(field);
            // A small JS injection to make sure the value property is correctly set on all option elements.
            field->getDomElement()->getElement(page).evaluateJavaScript("for(i=0; i<this.length; i++){ this.options[i].value = this.options[i].value; }"); // Surprisingly not necessarily a no-op.
            // Read back the values.
            QWebElementCollection options = field->getDomElement()->getElement(page).findAll("option");
            foreach(QWebElement o, options) {
                result.values.append(o.attribute("value"));
            }
            selects.insert(result);

        } else if (field->getDomElement()->getElement(page).attribute("type") == "radio") {
Esempio n. 12
0
void FileArome::writeCore(std::vector<Variable::Type> iVariables) {
   writeTimes();
   writeReferenceTime();
   writeGlobalAttributes();
   for(int v = 0; v < iVariables.size(); v++) {
      Variable::Type varType = iVariables[v];
      std::string variable = getVariableName(varType);
      NcVar* var;
      if(hasVariableCore(varType)) {
         var = getVar(variable);
      }
      else {
         // Create variable
         if(0) {
            NcDim* dTime    = getDim("time");
            NcDim* dSurface = getDim("height0");
            NcDim* dLon     = getDim("x");
            NcDim* dLat     = getDim("y");
            var = mFile.add_var(variable.c_str(), ncFloat, dTime, dSurface, dLat, dLon);
         }
         else {
            NcDim* dTime    = getDim("time");
            NcDim* dLon     = getDim("x");
            NcDim* dLat     = getDim("y");
            var = mFile.add_var(variable.c_str(), ncFloat, dTime, dLat, dLon);
         }
      }
      float MV = getMissingValue(var); // The output file's missing value indicator
      for(int t = 0; t < mNTime; t++) {
         float offset = getOffset(var);
         float scale = getScale(var);
         FieldPtr field = getField(varType, t);
         if(field != NULL) { // TODO: Can't be null if coming from reference
            float* values = new float[mNLat*mNLon];

            int index = 0;
            for(int lat = 0; lat < mNLat; lat++) {
               for(int lon = 0; lon < mNLon; lon++) {
                  float value = (*field)(lat,lon,0);
                  if(!Util::isValid(value)) {
                     // Field has missing value indicator and the value is missing
                     // Save values using the file's missing indicator value
                     value = MV;
                  }
                  else {
                     value = ((*field)(lat,lon,0) - offset)/scale;
                  }
                  values[index] = value;
                  index++;
               }
            }
            int numDims = var->num_dims();
            if(numDims == 4) {
               var->set_cur(t, 0, 0, 0);
               var->put(values, 1, 1, mNLat, mNLon);
            }
            else if(numDims == 3) {
               var->set_cur(t, 0, 0);
               var->put(values, 1, mNLat, mNLon);
            }
            else {
               std::stringstream ss;
               ss << "Cannot write variable '" << variable << "' from '" << getFilename() << "'";
               Util::error(ss.str());
            }
            setAttribute(var, "coordinates", "longitude latitude");
            setAttribute(var, "units", Variable::getUnits(varType));
            setAttribute(var, "standard_name", Variable::getStandardName(varType));
            delete[] values;
         }
      }
      setMissingValue(var, MV);
   }
}
Esempio n. 13
0
// Parameter phase only for tracing
SimplexResult Tableau::primalSimplex(int phase) {
  const int width           = getWidth();
  const int constraintCount = getConstraintCount();

  for(int r = 1; r <= constraintCount; r++) {
    const TableauRow &row = m_table[r];
    const int bv = row.m_basisVariable;
    const Real &a = row.m_a[bv];
    if(a == 0) {
      continue;
    }
    Real factor = getObjectFactor(bv) / a;
    if(factor == 0) {
      trace(TRACE_WARNINGS,_T("Warning:Cost factor[%s] = 0."), getVariableName(bv).cstr());
      continue;
    }
    for(int col = 0; col <= width; col++) {
      objectFactor(col) -= row.m_a[col] * factor;
    }
    objectFactor(bv) = 0;
  }

  bool looping = false;

  for(int iteration = 1;; iteration++) {
    if(isTracing(TRACE_ITERATIONS)) {
      trace(_T("Phase %d. Iteration %d"), phase, iteration);
      traceTableau();
//      traceBasis(_T("Current basis:"));
    }

    int pivotColumn;
    Real minCost = 1;

    if(looping) {
      for(int col = 1; col <= width; col++) {    // Apply Bland's anti-cycling rule step 1.
        const Real &cc = objectFactor(col);
        if(cc < -EPS) {
          minCost     = cc;
          pivotColumn = col;
          break;
        }
      }
    } else {                                     // else find pivot column the old way
      for(int col = 1; col <= width; col++) {
        const Real &cc = objectFactor(col);
        if(cc < minCost) {
          minCost     = cc;
          pivotColumn = col;
        }
      }
    }

    if(minCost >= -EPS) {
      return SIMPLEX_SOLUTION_OK;                // Optimal value found
    }

    int pivotRow  = -1;
    Real minRatio = 0;
    if(looping) {                                // apply Bland's anti-cycling rule step 2.
      for(int r = 1; r <= constraintCount; r++) {
        const Real &ar = m_table[r].m_a[pivotColumn];
        if(ar > 10*EPS) {
          const Real &br = getRightSide(r);
          const Real ratio = br / ar;
          if((pivotRow == -1) || (ratio < minRatio)) {
            minRatio = ratio;
            pivotRow = r;
          }
        }
      }
      if(pivotRow >= 0) {
        int minIndex = -1;
        for(int r = 1; r <= constraintCount; r++) {
          const Real &ar = m_table[r].m_a[pivotColumn];
          if(ar > 10*EPS) {
            const Real &br = getRightSide(r);
            const Real ratio = br / ar;
            if(ratio == minRatio) {
              const int index = m_table[r].m_basisVariable;
              if(minIndex == -1 || index < minIndex) {
                minIndex = index;
                pivotRow = r;
              }
            }
          }
        }
      }
    } else {                                     // else find pivot row the old way
      for(int r = 1; r <= constraintCount; r++) {
        const Real &ar = m_table[r].m_a[pivotColumn];
        if(ar > EPS) {
          const Real &br = getRightSide(r);
          const Real ratio = br / ar;
          if(pivotRow == -1 || ratio < minRatio) {
            minRatio = ratio;
            pivotRow = r;
          }
        }
      }
    }

    if(pivotRow == -1) {
      return SIMPLEX_SOLUTION_UNLIMITED;
    }

                                                 // Check for degeneracy
    traceDegeneracy(pivotRow, pivotColumn, minRatio);

    DictionaryKey dictKey(this);
    if(m_dictionarySet.contains(dictKey)) {
      looping = true;
      trace(TRACE_WARNINGS, _T("Looping. Applying Blands anti cycling rule."));
    } else {
      m_dictionarySet.add(dictKey);
    }

    pivot(pivotRow,pivotColumn,true);
  }
}
Esempio n. 14
0
void Tableau::addConstraint(size_t xIndex, SimplexRelation relation, const Real &rightSide) {
  if(xIndex < 1 || (int)xIndex >= getXCount()) {
    throwException(_T("addConstraint:Invalid xIndex=%s. Valid interval=[1..%s]"), FSZ(xIndex), FSZ(getXCount()));
  }

  Real currentValue = 0;
  int  bvRow        = -1;

  for(size_t i = 1; i < m_table.size(); i++) {
    if(m_table[i].m_basisVariable == (int)xIndex) {
      currentValue = getRightSide(i);
      bvRow = (int)i;
      break;
    }
  }

  String varName = getVariableName(xIndex);
  switch(relation) {
  case EQUALS     :
    if(currentValue == rightSide) {
      trace(_T("addConstraint:No need to add constraint %s = %-16lg. %s already has the specified value."), varName.cstr(), getDouble(rightSide), varName.cstr());
      return;
    } else if(currentValue < rightSide) {
      relation = GREATERTHAN;
    } else {
      relation = LESSTHAN;
    }
    break;

  case LESSTHAN   :
    if(currentValue <= rightSide) {
      trace(_T("addConstraint:No need to add constraint %s <= %-16lg. %s=%-16lg."), varName.cstr(), getDouble(rightSide), varName.cstr(), getDouble(currentValue));
      return;
    }
    break;

  case GREATERTHAN:
    if(currentValue >= rightSide) {
      trace(_T("addConstraint:No need to add constraint %s >= %-16lg. %s=%-16lg."), varName.cstr(), getDouble(rightSide), varName.cstr(), getDouble(currentValue));
      return;
    }
    break;
  }

  if(isTracing(TRACE_ITERATIONS)) {
    trace(_T("Add constraint %s %s %lg"), varName.cstr(), getRelationString(relation), getDouble(rightSide));
  }

  m_table.add(TableauRow(getMaxColumnCount()));
  const int newRowIndex = getConstraintCount();
  addSlackColumn();
  TableauRow &newRow = m_table[newRowIndex];
  newRow.m_a[xIndex] = 1;
  slackVar(newRowIndex,m_slackCount) = getSlackFactor(relation);
  setRightSide(newRowIndex,rightSide);
  newRow.m_basisVariable = getSlackColumn(m_slackCount);
  objectFactor(newRow.m_basisVariable) = 1;

//  if(isTracing()) trace(_T("addConstraint before normalizing:\n %s"),toString().cstr());

  if(bvRow >= 0) {
    addRowsToGetZero(newRowIndex,bvRow,xIndex);
  }

  if(getRightSide(newRowIndex) > 0)
    multiplyRow(newRowIndex,-1);

//  objectValue() += getRightSide(newRowIndex);
}
Esempio n. 15
0
SimplexResult Tableau::endPhase1() {
  const int constraintCount = getConstraintCount();
  for(int row = 1; row <= constraintCount; row++) {
    const int bv = m_table[row].m_basisVariable;
    if(bv >= getArtificialColumn(1)) {
      trace(TRACE_WARNINGS,_T("endPhase1:Artificial variabel %s not eliminated. Value=%lg"), getVariableName(bv).cstr(),getDouble(getRightSide(row)));
      traceTableau();

      if(getRightSide(row) == 0) {
        return SIMPLEX_NO_SOLUTION_FOUND;
      } else {
        return SIMPLEX_NO_SOLUTION;
      }
    }
  }

  // Delete all artificial variables
  m_artificialCount = 0;

  // Restore original costFactors
  int col;
  for(col = 1; col <= getXCount(); col++) {
    objectFactor(col) = m_costFactor[col];
  }
  for(int index = 1; col <= (int)m_slackCount; index++) {
    objectFactor(getSlackColumn(index)) = 0;
  }

  return SIMPLEX_SOLUTION_OK;
}
Esempio n. 16
0
bool FileNetcdf::hasVariableCore(Variable::Type iVariable) const {
   std::string variable = getVariableName(iVariable);
   return hasVariableCore(variable);
}
Esempio n. 17
0
// #################################################################
// データレコード出力
CDM::E_CDM_ERRORCODE
//cdm_DFI_VTK::write_DataRecord(FILE* fp,
cdm_DFI_VTK::write_DataRecord(cdm_FILE* pFile,
                              cdm_Array* val,
                              const int gc,
                              const int n)
{
  FILE *fp = pFile->m_fp;

  const int* sz = val->getArraySizeInt();
  size_t dLen;
  if( !m_bgrid_interp_flag ) {
    dLen = (size_t)(sz[0]+2*gc)*(size_t)(sz[1]+2*gc)*(size_t)(sz[2]+2*gc);
  } else {
    dLen = (size_t)sz[0]*(size_t)sz[1]*(size_t)sz[2];
  }

  std::string d_type;
  if(      DFI_Finfo.DataType == CDM::E_CDM_UINT8  ) d_type="unsigned_char";
  else if( DFI_Finfo.DataType == CDM::E_CDM_INT8   ) d_type="char";
  else if( DFI_Finfo.DataType == CDM::E_CDM_UINT16 ) d_type="unsigned_short";
  else if( DFI_Finfo.DataType == CDM::E_CDM_INT16  ) d_type="short";
  else if( DFI_Finfo.DataType == CDM::E_CDM_UINT32 ) d_type="unsigned_int";
  else if( DFI_Finfo.DataType == CDM::E_CDM_INT32  ) d_type="int";
  else if( DFI_Finfo.DataType == CDM::E_CDM_UINT64 ) d_type="unsigned_long";
  else if( DFI_Finfo.DataType == CDM::E_CDM_INT64  ) d_type="long";
  else if( DFI_Finfo.DataType == CDM::E_CDM_FLOAT32) d_type="float";
  else if( DFI_Finfo.DataType == CDM::E_CDM_FLOAT64) d_type="double";

  cdm_Array *out = cdm_Array::instanceArray
                   (val->getDataType(),
                    CDM::E_CDM_IJKN,
                    (int *)sz,
                    val->getGc(),
                    1); //変数毎に出力するので、変数の個数は1

  for(int nv=0; nv<DFI_Finfo.NumVariables; nv++) {

    fprintf( fp, "SCALARS %s %s\n", getVariableName(nv).c_str(),d_type.c_str() );
    fprintf( fp, "LOOKUP_TABLE default\n" );

    if( val->copyArrayNvari_to_ijk(out,nv) != 0 ) {
      printf("\tError : copyArrayNvari_to_ijk in class cdm_DFI_VTK\n");
      return CDM::E_CDM_ERROR_WRITE_FIELD_DATA_RECORD;
    }

    //ascii
    if( m_output_type == CDM::E_CDM_FILE_TYPE_ASCII ) {

      if( out->writeAscii(fp) != dLen ) {
        return CDM::E_CDM_ERROR_WRITE_FIELD_DATA_RECORD;
      }
      fprintf( fp, "\n" );

    //binary
    } else {

      //出力実数タイプがuint8のとき
      if( out->getDataType() == CDM::E_CDM_UINT8 ) {
        unsigned char *data = (unsigned char*)out->getData();
        BSWAPVEC(data,dLen);
        fwrite( data, sizeof(unsigned char), dLen, fp );

      //出力実数タイプがint8のとき
      }else if( out->getDataType() == CDM::E_CDM_INT8 ) {
        char *data = (char*)out->getData();
        BSWAPVEC(data,dLen);
        fwrite( data, sizeof(char), dLen, fp );

      //出力実数タイプがuint16のとき
      }else if( out->getDataType() == CDM::E_CDM_UINT16 ) {
        unsigned short *data = (unsigned short*)out->getData();
        BSWAPVEC(data,dLen);
        fwrite( data, sizeof(unsigned short), dLen, fp );

      //出力実数タイプがint16のとき
      }else if( out->getDataType() == CDM::E_CDM_INT16 ) {
        short *data = (short*)out->getData();
        BSWAPVEC(data,dLen);
        fwrite( data, sizeof(short), dLen, fp );

      //出力実数タイプがuint32のとき
      }else if( out->getDataType() == CDM::E_CDM_UINT32 ) {
        unsigned int *data = (unsigned int*)out->getData();
        BSWAPVEC(data,dLen);
        fwrite( data, sizeof(unsigned int), dLen, fp );

      //出力実数タイプがint32のとき
      }else if( out->getDataType() == CDM::E_CDM_INT32 ) {
        int *data = (int*)out->getData();
        BSWAPVEC(data,dLen);
        fwrite( data, sizeof(int), dLen, fp );

      //出力実数タイプがuint64のとき
      }else if( out->getDataType() == CDM::E_CDM_UINT64 ) {
        unsigned long long *data = (unsigned long long*)out->getData();
        BSWAPVEC(data,dLen);
        fwrite( data, sizeof(unsigned long long), dLen, fp );

      //出力実数タイプがint64のとき
      }else if( out->getDataType() == CDM::E_CDM_INT64 ) {
        long long *data = (long long*)out->getData();
        BSWAPVEC(data,dLen);
        fwrite( data, sizeof(long long), dLen, fp );

      //出力実数タイプがfloatのとき
      }else if( out->getDataType() == CDM::E_CDM_FLOAT32 ) {
        float *data = (float*)out->getData();
        BSWAPVEC(data,dLen);
        fwrite( data, sizeof(float), dLen, fp );

      //出力実数タイプがdoubleのとき
      }else if( out->getDataType() == CDM::E_CDM_FLOAT64 ) {
        double *data = (double*)out->getData();
        DBSWAPVEC(data,dLen);
        fwrite( data, sizeof(double), dLen, fp );
      }

      fprintf( fp, "\n" );

    }

  }
  return CDM::E_CDM_SUCCESS;
}
Esempio n. 18
0
File: Grib.cpp Progetto: WFRT/Comps
float InputGrib::getValueCore(const Key::Input& iKey) const {
#ifdef WITH_GRIB
   // Check that date hasn't been checked before
   std::map<int,std::map<float, bool> >::const_iterator it0 = mMissingFiles.find(iKey.date);
   if(it0 != mMissingFiles.end()) {
      // Date has missing files
      std::map<float, bool>::const_iterator it1 = it0->second.find(iKey.offset);
      if(it1 != it0->second.end()) {
         writeMissingToCache(iKey);
         return Global::MV;
      }
   }

   std::string localVariable;
   bool found = getLocalVariableName(iKey.variable, localVariable);
   assert(found);

   int numLocations = Input::getNumLocations();

   std::string filename = getFilename(iKey);
   std::stringstream ss;
   ss << "InputGrib: Loading " << filename << " " << iKey.date << " " << iKey.offset << " " << iKey.location << " " << localVariable;
   Global::logger->write(ss.str(), Logger::message);
   bool foundVariable = false;
   FILE* fid = fopen(filename.c_str(),"r");
   float value = Global::MV;
   if(fid) {
      // GRIB File found
      int err = 0;
      grib_handle* h = NULL;

      // double s = Global::clock();

      // Try to use an index to read file as this is much faster. Fall back on just reading the 
      // GRIB file.
      grib_index* gribIndex = getIndex(iKey, localVariable);
      bool validIndex = (gribIndex != NULL);
      if(!validIndex) {
         std::stringstream ss;
         ss << "InputGrib: No index file available for " << filename;
         Global::logger->write(ss.str(), Logger::message);
      }

      int counter = 1;
      // Loop over available variables (in index or in file)
      while(1) {
         // Read message from file or index
         if(!validIndex) {
            h = grib_handle_new_from_file(0,fid,&err);
         }
         else {
            h = grib_handle_new_from_index(gribIndex,&err);
         }
         if(h == NULL)
            break; // No more messages to process

         std::string currVariable = getVariableName(h);
         std::stringstream ss;
         ss << "InputGrib: Reading message #" << counter << ": " << currVariable;
         Global::logger->write(ss.str(), Logger::message);

         // Check if the current variable is defined in the variable list
         int variableId;
         found = getVariableIdFromLocalVariable(currVariable, variableId);
         if(!found) {
            std::stringstream ss;
            ss << "InputGrib: Found variable " << currVariable << " in " << filename << " but this is not mapped to any variable in namelist" << std::endl;
            Global::logger->write(ss.str(), Logger::message);
         }
         else {
            // Only read the current variable if necessary
            if(mCacheOtherVariables || currVariable == localVariable) {
               std::vector<float> currValues;
               currValues.resize(numLocations, Global::MV);
               int numValid = 0;

               // Check that the message has the right number of locations
               size_t N;
               GRIB_CHECK(grib_get_size(h,"values",&N),0);
               if(N == numLocations) {
                  foundVariable = foundVariable || (currVariable == localVariable);
                  double* arr = new double[N];

                  GRIB_CHECK(grib_get_double_array(h,"values",arr,&N),0);
                  currValues.assign(arr, arr + numLocations);
                  for(int i = 0; i < (int) currValues.size(); i++) {
                     if(currValues[i] == mMV)
                        currValues[i] = Global::MV;
                     else
                        numValid++;
                  }
                  std::stringstream ss;
                  ss << "InputGrib: Number of valid values: " << numValid;
                  Global::logger->write(ss.str(), Logger::message);
                  delete arr;
               }
               else {
                  std::stringstream ss;
                  ss << "GribInput: Discarding variable " << currVariable << " in " << filename
                     << " because it has incorrect number of locations";
                  Global::logger->write(ss.str(), Logger::debug);
               }

               Key::Input key = iKey;
               key.offset = getOffset(h);
               // Cache values
               for(int i = 0; i < numLocations; i++) {
                  key.location = i;
                  key.variable = variableId;
                  if(key.location == iKey.location && currVariable == localVariable) {
                     // Found the value
                     value = currValues[i];
                  }
                  if(mCacheOtherLocations || key.location == iKey.location) {
                     //if(currVariable == localVariable)
                     //   std::cout << currValues[i] << std::endl;
                     Input::addToCache(key, currValues[i]);
                  }
               }
            }
         }
         if(h) {
            grib_handle_delete(h);
         }

         // Quit reading file if we have found the variable we need
         if(!mCacheOtherVariables && (currVariable == localVariable)) {
            break;
         }
         counter++;
      }
      if(!foundVariable) {
         // File was there, but couldn't find variable
         std::stringstream ss;
         ss << "InputGrib: Could not find variable " << localVariable << " in " << filename;
         Global::logger->write(ss.str(), Logger::warning);
         writeMissingToCache(iKey);
      }
      if(validIndex) {
         grib_index_delete(gribIndex);
      }

      // double e = Global::clock();
      //std::cout << "Grib read time: " << e - s << " seconds" << std::endl;

      fclose(fid);
      return value;
   }
   else {
      // GRIB file not found
      std::stringstream ss;
      ss << "GribInput: File not found: " << filename;
      Global::logger->write(ss.str(), Logger::message);

      std::vector<float> currValues;
      currValues.resize(numLocations, Global::MV);
      for(int i = 0; i < numLocations; i++) {
         Key::Input key = iKey;
         key.location = i;
         if(mCacheOtherLocations || key.location == iKey.location)
            Input::addToCache(key, currValues[i]);
      }
      return Global::MV;
   }
#else
   return Global::MV;
#endif
}
Esempio n. 19
0
FieldPtr FileArome::getFieldCore(Variable::Type iVariable, int iTime) const {
   std::string variableName = getVariableName(iVariable);
   return getFieldCore(variableName, iTime);
}