예제 #1
0
WormLogic CountingWorm::solve()
{
	forbidden.clear();
	const SimplePoint head = Position().front();
	forbidden.push_back(head);
	
	const SimplePoint pleft = SimplePoint(head.X - 1, head.Y);
	const SimplePoint pright = SimplePoint(head.X + 1, head.Y);
	const SimplePoint ptop = SimplePoint(head.X, head.Y + 1);
	const SimplePoint pbottom = SimplePoint(head.X, head.Y - 1);

	typedef std::pair<double, WormLogic> dw;
	std::vector<dw> candidates;

	if(FreeToMove(pleft))
	{
		candidates.push_back(dw(CellValue(pleft) + 0.5 * value(pleft, maxMoves - 1), GoLeft));
	}

	if(FreeToMove(pright))
	{
		candidates.push_back(dw(CellValue(pright) + 0.5 * value(pright, maxMoves - 1), GoRight));
	}

	if(FreeToMove(ptop))
	{
		candidates.push_back(dw(CellValue(ptop) + 0.5 * value(ptop, maxMoves - 1), GoUp));
	}

	if(FreeToMove(pbottom))
	{
		candidates.push_back(dw(CellValue(pbottom) + 0.5 * value(pbottom, maxMoves - 1), GoDown));
	}

	forbidden.pop_back();

	if(candidates.empty())
	{
		return Stay;
	}
	else
	{
		std::sort(candidates.begin(), candidates.end(), std::greater<dw>());

		const dw best = candidates[0];
		std::vector<dw> bests;
		for(std::vector<dw>::const_iterator it = candidates.begin(); it != candidates.end(); ++it)
			if(it->first == best.first)
				bests.push_back(*it);

		if(best.first >= 0)
		{
			return bests[Rand(bests.size())].second;
		}
		else
		{
			return Stay;
		}
	}
}
예제 #2
0
CellMatrix::CellMatrix(const MyMatrix& data): Cells(data.rows()), 
	Rows(data.rows()), Columns(data.columns())
{
	for (unsigned long i=0; i < data.rows(); ++i)
		for (unsigned long j=0; j < data.columns(); ++j)
			Cells[i].push_back(CellValue(Element(data,i,j)));
}
예제 #3
0
xlw::CellMatrix::CellMatrix(const MyMatrix& data): Cells(data.size1()),
    Rows(data.size1()), Columns(data.size2())
{
    for (size_t i=0; i < data.size1(); ++i)
        for (size_t j=0; j < data.size2(); ++j)
            Cells[i].push_back(CellValue(Element(data,i,j)));
}
예제 #4
0
void LegacyRule::computeCell()
{

	if (globalError.isError()) {
		value = globalError;
		return;
	}
	size_t size = mem_context->m_recursion_stack.size();
	try {
		double defValue = 0;
		bool notFoundStatus = true;

		// find sources
		size_t precalculatedSourcesCount = sourceStreamsSP.size();
		vector<CellValueStream *> sourceStreamsCopy(precalculatedSourcesCount, 0);
		for (uint32_t source = 0; source < precalculatedSourcesCount; source++) {
			while (sourceStreamsNext[source]) {
				const IdentifiersType &sourceKey = sourceStreams[source]->getKey();
				int keyCmp = CellValueStream::compare(sourceKey, vkey);

				if (keyCmp < 0) {
//					mem_context->m_recursion_stack.push(sourceCubeAreas[source]);
					sourceStreamsNext[source] = sourceStreams[source]->next();
					if (!sourceStreamsNext[source]) {
						sourceStreamsSP[source].reset();
						sourceStreams[source] = 0;
					}
//					mem_context->m_recursion_stack.pop();
				} else if (keyCmp == 0) {
					sourceStreamsCopy[source] = sourceStreams[source];
					break;
				} else {
					break;
				}
			}
		}

		// apply the rule
		virtual_machine machine(mem_context, &value);
		machine.setSourceStreams(&sourceStreamsCopy);
		machine.setCache(&vmCache);

		// Todo: -jj- not optimal - instead of using CellStatus::NotFoundStatus we should define LegacyUbmMarkedRule and define source processor driving the calculation
		EPath vkeyCopy;
		memcpy(vkeyCopy, &vkey[0], vkey.size() * sizeof(IdentifierType));
		machine.compute(engine.get(), &vkeyCopy[0], erule, defValue, notFoundStatus);
		if (value.isEmpty() && node->getDefaultValue()) {	// if value is empty - make sure it has correct type
			value = *node->getDefaultValue();
		}
	} catch (ErrorException& e) {
		if (e.getErrorType() == ErrorException::ERROR_STOPPED_BY_ADMIN) {
			throw e;
		}
		value = CellValue(e.getErrorType());
		value.setRuleId(erule->nr_rule);
		mem_context->m_recursion_stack.clean(size);
		return;
	}
	value.setRuleId(erule->nr_rule);
}
예제 #5
0
double CountingWorm::value(const SimplePoint& position, const int movesLeft)
{
	if(movesLeft == 0)
	{
		return 0.0;
	}
	else
	{
		// варианты
		forbidden.push_back(position);

		const SimplePoint pleft = SimplePoint(position.X - 1, position.Y);
		const SimplePoint pright = SimplePoint(position.X + 1, position.Y);
		const SimplePoint ptop = SimplePoint(position.X, position.Y + 1);
		const SimplePoint pbottom = SimplePoint(position.X, position.Y - 1);

		double ans = -1000000;

		if(FreeToMove(pleft))
		{
			ans = std::max(ans, CellValue(pleft) + 0.5 * value(pleft, movesLeft - 1));
		}

		if(FreeToMove(pright))
		{
			ans = std::max(ans, CellValue(pright) + 0.5 * value(pright, movesLeft - 1));
		}

		if(FreeToMove(ptop))
		{
			ans = std::max(ans, CellValue(ptop) + 0.5 * value(ptop, movesLeft - 1));
		}

		if(FreeToMove(pbottom))
		{
			ans = std::max(ans, CellValue(pbottom) + 0.5 * value(pbottom, movesLeft - 1));
		}

		forbidden.pop_back();

		return ans;
	}
}
예제 #6
0
void runOMPHotspotKernel(dim3 input_size, dim3 stencil_size, DTYPE *input,
                      DTYPE *output, int pyramid_height, DTYPE *ro_data,
                      float step_div_Cap, float Rx, float Ry, float Rz) {
  //fprintf(stderr, "omp_global_ro_data:%p\n", omp_global_ro_data);
  dim3 border;
  border.x = border.y = border.z = 0;
  for (int iter = 0; iter < pyramid_height; ++iter) {
    border.x += stencil_size.x;
    border.y += stencil_size.y;
    int uidx = -1;
    // (x, y, z) is the location in the input of this thread.
  #pragma omp parallel for private(uidx) shared(output)
    for (int y = border.y; y < input_size.y - border.y; ++y) {
      for (int x = border.x; x < input_size.x - border.x; ++x) {
          // Get current cell value or edge value.
          // uidx = ez + input_size.y * (ey * input_size.x + ex);
          uidx = x + input_size.x * y;

          output[uidx] = CellValue(input_size, x, y, input, step_div_Cap,
                                    Rx, Ry, Rz, border);
      }
    }
  }
}
예제 #7
0
파일: XlfOper4.cpp 프로젝트: lemahdi/mglib
int xlw::XlfOper4::ConvertToCellMatrix(CellMatrix& output) const
{

    if (lpxloper_->xltype == xltypeMissing || lpxloper_->xltype == xltypeNil )
    {

        CellMatrix tmp(1,1);
        output = tmp;

        return xlretSuccess;
    }

    if (lpxloper_->xltype == xltypeNum)
    {
        CellMatrix tmp(1,1);

        tmp(0,0) = lpxloper_->val.num;

        output = tmp;



        return xlretSuccess;
    }

    if (lpxloper_->xltype == xltypeBool)
    {
        CellMatrix tmp(1,1);

        tmp(0,0) = (lpxloper_->val.xbool >0);

        output = tmp;


        return xlretSuccess;
    }

    if (lpxloper_->xltype == xltypeErr)
    {
        CellMatrix tmp(1,1);

        tmp(0,0) = CellValue(lpxloper_->val.err,true);

        output = tmp;

        return xlretSuccess;
    }

    if (lpxloper_->xltype == xltypeStr)
    {
        CellMatrix tmpCell(1,1);

        unsigned long len = *((*lpxloper_).val.str);

        std::string tmp;
        tmp.resize(len);


        for(unsigned long k=0; k<len; ++k)
            tmp[k]= ((*lpxloper_).val.str)[k+1];


        tmpCell(0,0) = tmp;

        output = tmpCell;

        return xlretSuccess;
    }


    if (lpxloper_->xltype == xltypeMulti)
    {
        unsigned long rows = lpxloper_->val.array.rows;
        unsigned long columns = lpxloper_->val.array.columns;
        CellMatrix result(rows,columns);

        for (unsigned long i=0; i < rows; i++)
            for (unsigned long j=0; j < columns; j++)
            {
                unsigned long thisType = (*lpxloper_).val.array.lparray[i*columns+j].xltype;
                if (thisType == xltypeNum)
                {
                    double x = (*lpxloper_).val.array.lparray[i*columns+j].val.num;
                    result(i,j) = x;
                }
                else
                {
                    if (thisType==xltypeStr)
                    {
                          unsigned long len = *((*lpxloper_).val.array.lparray[i*columns+j].val.str);

                          std::string tmp;
                          tmp.resize(len);

                          for(unsigned long k=0; k<len; ++k)
                            tmp[k]=
                            ((*lpxloper_).val.array.lparray[i*columns+j].val.str)[k+1];

                          result(i,j) = tmp;
                    }

                    else
                        if (thisType == xltypeBool)
                        {
                            result(i,j) = ((*lpxloper_).val.array.lparray[i*columns+j].val.xbool > 0);
                        }
                        else
                            if (thisType== xltypeErr)
                            {
                                result(i,j) = CellValue(((*lpxloper_).val.array.lparray[i*columns+j].val.err),true);
                            }
                            else
                                if (thisType!=xltypeMissing && thisType != xltypeNil)
                                    throw("cell contains neither number nor string nor boolean nor empty");
                }

            }

        output= result;


        return xlretSuccess;


    }

    XlfRef ref;
    int xlret = ConvertToRef(ref);
    if (xlret != xlretSuccess)
        return xlret;

    unsigned long nbRows = ref.GetNbRows();
    unsigned long nbCols = ref.GetNbCols();

    output = CellMatrix(nbRows,nbCols);
    for (unsigned long i = 0; i < nbRows; ++i)
    {
        for (unsigned long j = 0; j < nbCols; ++j)
        {
            XlfOper4 element = ref.element<XlfOper4>(static_cast<WORD>(i), static_cast<BYTE>(j));
            unsigned long type = element.lpxloper_->xltype;

            if (type == xltypeRef)
            {
                XlfRef xlrefij;

                int xlretij = element.ConvertToRef(xlrefij);

                if (xlretij != xlretSuccess)
                    return xlretij;

                XlfOper4 refElement = xlrefij.element<XlfOper4>(0UL,0UL);
                type = refElement.lpxloper_->xltype;

                if (type == xltypeNum)
                {
                    double tmp;
                    xlret = refElement.ConvertToDouble(tmp);

                    output(i,j) = tmp;

                    if (xlret != xlretSuccess)
                        return xlret;
                }
                else
                    if (type == xltypeErr)
                    {
                        WORD tmp;

                        xlret = refElement.ConvertToErr(tmp);

                        output(i,j) = CellValue(tmp,true);

                        if (xlret != xlretSuccess)
                            return xlret;
                    }
                    else
                    if (type == xltypeBool)
                    {
                        bool tmp;

                        xlret = refElement.ConvertToBool(tmp);

                        output(i,j) = tmp;

                        if (xlret != xlretSuccess)
                            return xlret;
                    }
                    else
                    {
                        if (type == xltypeStr || type == xltypeSRef)
                        {
                            char* tmp;
                            xlret = refElement.ConvertToString(tmp);
                            output(i,j) = std::string(tmp);

                            if (xlret != xlretSuccess)
                                return xlret;
                        }
                        else
                        {

                            if (type != xltypeMissing)
                                return xlretInvXloper;

                        }

                    }

            }
            else
                if (type == xltypeNum)
                {
                    double tmp;
                    xlret = element.ConvertToDouble(tmp);

                    output(i,j) = tmp;

                    if (xlret != xlretSuccess)
                        return xlret;
                }
                else
                {
                    if (type == xltypeStr || type == xltypeSRef)
                    {
                        char* tmp;
                        xlret = element.ConvertToString(tmp);
                        output(i,j) = std::string(tmp);

                        if (xlret != xlretSuccess)
                            return xlret;
                    }
                    else
                    {
                        if (element.lpxloper_->xltype != xltypeMissing)
                            return xlretInvXloper;

                    }

                }
        }

    }
    return xlret;

}
예제 #8
0
xlw::CellMatrix::CellMatrix(int i): Cells(1), Rows(1), Columns(1)
{
    Cells[0].push_back(CellValue(static_cast<double>(i)));
}
예제 #9
0
xlw::CellMatrix::CellMatrix(const MyArray& data) : Cells(data.size()),
    Rows(data.size()), Columns(1)
{
    for (size_t i=0; i < data.size(); ++i)
        Cells[i].push_back(CellValue(data[i]));
}
예제 #10
0
xlw::CellMatrix::CellMatrix(const char* x): Cells(1), Rows(1), Columns(1)
{
    Cells[0].push_back(CellValue(x));
}
예제 #11
0
xlw::CellMatrix::CellMatrix(std::wstring x): Cells(1), Rows(1), Columns(1)
{
    Cells[0].push_back(CellValue(x));
}
예제 #12
0
xlw::CellMatrix::CellMatrix(double x): Cells(1), Rows(1), Columns(1)
{
    Cells[0].push_back(CellValue(x));
}
예제 #13
0
CellMatrix::CellMatrix(unsigned long i)
	: Cells(1), Rows(1), Columns(1)
{
	Cells[0].push_back(CellValue(static_cast<double>(i)));
}
예제 #14
0
void LegacyRule::generateSources()
{
	// if caching enabled
	if (cube->getCacheBarrier() > 0) {
		Context *context = Context::getContext();
		PServer server = context->getServer();
		// precalc markers and store results in cache
		const vector<PRuleMarker>& markers = erule->arule->getMarkers();
		for (vector<PRuleMarker>::const_iterator markerIt = markers.begin(); markerIt != markers.end(); ++markerIt) {
			dbID_cubeID dbCube = (*markerIt)->getFromDbCube();
			if ((*markerIt)->isMultiplicating() || (dbCube.first == db->getId() && dbCube.second == cube->getId())) {
				continue;
			}
			CPDatabase sourceDb = server->lookupDatabase(dbCube.first, false);
			if (sourceDb) {
				CPCube sourceCube = sourceDb->lookupCube(dbCube.second, false);
				if (sourceCube) {
					size_t targetDimmCount = cube->getDimensions()->size();

					PCubeArea sourceCubeArea(new CubeArea(sourceDb, sourceCube, *(*markerIt)->getSourceArea()));	// TODO: -jj- getFromBase->getSourceArea
					Logger::trace << "Prefetching Marker From Base: " << *(*markerIt)->getFromBase() << endl;
					// transform target area into source and calculate source
					const int16_t *permutation = (*markerIt)->getPermutations();
					const RuleMarker::PMappingType *mapping = (*markerIt)->getMapping();

					for (size_t dim = 0; dim < targetDimmCount; dim++) {
						if (permutation[dim] != -1) {
							if (mapping[dim] == 0) {
								sourceCubeArea->insert(permutation[dim], area->getDim(dim));
							} else {
								PSet sourceSet(new Set());
								const Set &targetSet = *area->getDim(dim);
								// remap the set
	//							for (RuleMarker::MappingType::iterator mit = mapping[dim]->begin(); mit != mapping[dim]->end(); ++mit) {
	//								if (targetSet.find(mit->second) != targetSet.end()) {
	//									sourceSet->insert(mit->first);
	//								}
	//							}
								// use the reverse map
								map<uint32_t, uint32_t>& reverseMap = mapping[dim]->getReverseMap();
								for (Set::Iterator sit = targetSet.begin(); sit != targetSet.end(); ++sit) {
									map<uint32_t, uint32_t>::iterator rmit = reverseMap.find(*sit);
									if (rmit != reverseMap.end()) {
										sourceSet->insert(rmit->second);
									}
								}

								if (sourceSet->size()) {
									sourceCubeArea->insert(permutation[dim], sourceSet);
								} else {
									// do not calculate this source
									sourceCubeArea.reset();
									break;
								}
							}
						}
					}
					if (sourceCubeArea) {
						uint64_t barrier = (uint64_t)cube->getCacheBarrier();
						Logger::trace << "Target area: " << *area << endl;
						Logger::trace << "Source area: " << *sourceCubeArea << endl;
						// calculate the area
						PCellStream src = sourceCube->calculateArea(sourceCubeArea, CubeArea::ALL, ALL_RULES, true, barrier);
						if (src) {
							uint64_t srcCount = 0;
							while (src->next() && srcCount < barrier) {
								srcCount++;
							}
							Logger::trace << "Source values: " << srcCount << endl;
						}
					}
				}
			}
		}
	}

	sourceStreamsSP.resize(erule->gc_copy_nr+1);
	sourceStreams.resize(erule->gc_copy_nr+1);
	sourceStreamsNext.resize(erule->gc_copy_nr+1);
	sourceCubeAreas.resize(erule->gc_copy_nr+1);
	for (uint32_t source = 0; source < erule->gc_copy_nr; source++) {
		if (!erule->source_precalc[source]) {
			continue;
		}
		// transform source area
		IdentifiersType transformationMask(erule->cube->nrDimensions, NO_IDENTIFIER);
		SetMultimaps transformationMultiMap;
		sourceCubeAreas[source] = PCubeArea(new CubeArea(*area));
		for (size_t dim = 0; dim < erule->cube->nrDimensions; dim++) {
			if (erule->copy_mask[source][dim] == AreaNode::ABS_RESTRICTION) {
				IdentifierType sourceId = erule->copy_source[source][dim];
				PSet s(new Set);
				s->insert(sourceId);
//				CPSet targetSet = area->getDim(dim);
//				if (targetSet->size() > 1) {
//					// multimap
//					if (transformationMultiMap.empty()) {
//						transformationMultiMap.resize(erule->cube->nrDimensions);
//					}
//					if (!transformationMultiMap[dim]) {
//						transformationMultiMap[dim] = PSetMultimap(new SetMultimap());
//					}
//					for (Set::Iterator targetId = targetSet->begin(); targetId != targetSet->end(); ++targetId) {
//						transformationMultiMap[dim]->insert(SetMultimap::value_type(sourceId, *targetId));
//					}
//				} else {
//					// single element
//					transformationMask[dim] = *(targetSet->begin());
//				}
				sourceCubeAreas[source]->insert(dim, s);
			}
		}
		ErrorException::ErrorType stackeError = mem_context->m_recursion_stack.push(sourceCubeAreas[source], erule->arule);
		if (stackeError) {
			// all cells of the area have error result
			globalError = CellValue(stackeError);
			globalError.setRuleId(erule->nr_rule);
			break;
		}

		PPlanNode sourcePlan = cube->createPlan(sourceCubeAreas[source], CubeArea::ALL, ALL_RULES, true, UNLIMITED_SORTED_PLAN);
		sourcePlan = PPlanNode(new TransformationPlanNode(area, sourcePlan, transformationMask, transformationMultiMap, 1.0));
//		Logger::trace << "Transformed Plan: " << sourcePlan->toXML() << endl;
		PCellStream sourceStream = cube->evaluatePlan(sourcePlan, EngineBase::ANY);
		sourceStreamsSP[source] = sourceStream;
		sourceStreamsNext[source] = sourceStream->next();
		if (!sourceStreamsNext[source]) {
			sourceStreamsSP[source].reset();
		}
		sourceStreams[source] = sourceStream.get();
		mem_context->m_recursion_stack.pop();
	}
	if (erule->precalcStet && !globalError.isError()) {
		uint32_t source = erule->gc_copy_nr;
		PPlanNode sourcePlan = cube->createPlan(area, CubeArea::ALL, RulesType(INDIRECT_RULES | NOCACHE), true, UNLIMITED_SORTED_PLAN);
		PCellStream sourceStream = cube->evaluatePlan(sourcePlan, EngineBase::ANY);
		sourceStreamsSP[source] = sourceStream;
		sourceStreamsNext[source] = sourceStream->next();
		if (!sourceStreamsNext[source]) {
			sourceStreamsSP[source].reset();
		}
		sourceStreams[source] = sourceStream.get();
	}
}
예제 #15
0
const CellValue &SessionInfoProcessor::getValue()
{
	IdentifierType requestedMessagePart = getKey()[1];
	// switch must be identical to SystemDatabase::SESSION_PROPERTIES_ITEMS
//	{"User",	Element::STRING},
//	{"Jobs",	Element::NUMERIC},
//	{"Login Time",	Element::STRING},
//	{"Expiration Time", Element::STRING},
//	{"Time",	Element::NUMERIC},
//	{"Active Jobs", Element::STRING}
//	{"License",	Element::NUMERIC},
//	{"Address",	Element::STRING},
//	{"Command",	Element::STRING},
//	{"Description",	Element::STRING},
//	{"MachineId", Element::STRING}
	switch (requestedMessagePart) {
	case 0:	// 	{"User",     Element::STRING},
	{
		try {
			PUser user = sessionIt->second->getUser();
			if (user) {
				value = user->getName();
			} else if (sessionIt->second->isWorker()) {
				value = "<SupervisionServer>";
			} else {
				value = "<FAKE>";
			}
		} catch (ParameterException&) {
			value = "<UNKNOWN USER>"; // deleted user
		}
		break;
	}
	case 1:	// {"Jobs",	Element::NUMERIC},
		value = double(sessionIt->second->requestCounter);
		break;
	case 2:	// {"Login Time", Element::STRING},
		value = StringUtils::convertTimeToString(sessionIt->second->getLoginTime());
		break;
	case 3:	// {"Expiration Time", Element::STRING},
	{
		time_t ttl = sessionIt->second->getTtl();
		value = StringUtils::convertTimeToString(ttl);
		break;
	}
	case 4:	// {"Time", Element::NUMERIC},
		{
			double totalTime = sessionIt->second->totalTime;
			WriteLocker wl(&sessionIt->second->thisLock);
			for (set<const PaloJob *>::iterator jit = sessionIt->second->activeJobs.begin(); jit != sessionIt->second->activeJobs.end(); ++jit) {
				if (*jit) {
					totalTime += (*jit)->getDuration();
				}
			}
			value = totalTime;
		}
		break;
	case 5:	// {"Active Jobs", Element::STRING}
	{
		WriteLocker wl(&sessionIt->second->thisLock);
		string jobsNames;
		Context *context = Context::getContext();
		for (set<const PaloJob *>::iterator jit = sessionIt->second->activeJobs.begin(); jit != sessionIt->second->activeJobs.end(); ++jit) {
			if (*jit && (*jit)->getContext() != context) {
				if (!jobsNames.empty()) {
					jobsNames += ", ";
				}
				jobsNames += StringUtils::convertToString((*jit)->getId());
			}
		}
		value = jobsNames;
		break;
	}
	case 6:	// {"License",  Element::STRING},
		value = Context::getContext()->getServer()->getSessionLicense(sessionIt->second);
		break;
	case 7:	// {"Address",  Element::STRING},
		value = sessionIt->second->peerName;
		break;
	case 8:	// {"Command",	Element::STRING}
		value = sessionIt->second->command;
		break;
	case 9:	// {"Description",	Element::STRING}
		value = sessionIt->second->description;
		break;
	case 10:	// {"MachineId", Element::STRING}
		value = sessionIt->second->machineId;
		break;
	case 11:	// {"CurrentSession", Element::NUMERIC}
		value = CellValue();
		if (context && context->getSession() == sessionIt->second) {
			value = 1.0;
		}
		break;
	default:
		value = CellValue();
		break;
	}
	return value;
}