示例#1
0
Eigen::RowVectorXd Ur5MessageDecoder::getJointPositionsRT(QByteArray data)
{
    Eigen::RowVectorXd jp(6);
    for(int i=0;i<6;i++)
    {
        jp(i) = pickDouble(data,(31+i)*sizeof(double));
    }
    return jp;
}
示例#2
0
bool LR35902::jpf_n(uint8 flag, uint16 addr) {
    if(!flag) {
        jp(addr); 
        return true; 
    }
    return false; 
}
示例#3
0
文件: calls.c 项目: LuccoJ/z80sim
void _SystemRequest() {
	_asm
	ld ix,£_JumpTable
	push hl
	ld h,#0
	ld l,a
	add hl,ix
	jp (hl)
	_endasm;
}
示例#4
0
void RuleParser::parse() {
	sweet::jsonparser jp(str);

	std::string tokStr("Token");
	if(jp.getRoot()->pathExists(tokStr)) {
		auto tok = jp.getRoot()->access(tokStr);
		auto tokType = tok->getType();
		ASSERT_EQ(tokType, sweet::value::type_array);

		for(auto& it : tok->getArray()) {
			std::string name = it->getObject()->access("Name")->getString();
			std::string regex = it->getObject()->access("Regex")->getString();
			std::string convertFunc;
			if(it->getObject()->pathExists("ConvertFunction")) {
				convertFunc = it->getObject()->access("ConvertFunction")->getString();
			}
			token.insert(std::make_pair(name,
				Token(name, regex, convertFunc)
			));
		}
	}

	std::string ruleStr("Rules");
	if(jp.getRoot()->pathExists(ruleStr)) {
		auto rls = jp.getRoot()->access(ruleStr);
		auto rlsType = rls->getType();
		ASSERT_EQ(rlsType, sweet::value::type_array);
		for(auto& it : rls->getArray()) {

			std::string ruleName = it->getObject()->access("Name")->getString();
			auto& entry = it->getObject()->access("Expression")->getArray();
			for(auto& jt : entry) {
				RuleVector rv;
				auto semiSplit = split(jt->getObject()->access("Rule")->getString(), ';');
				std::string ruleEnd = jt->getObject()->get<std::string>("Id", "");
				for(auto& ht : semiSplit) {
					std::string type = trim(ht.substr(0, ht.find('(')));
					size_t lParen = ht.find('(');
					size_t rParen = ht.find(')');
					std::string saveName;
					if(lParen != std::string::npos && rParen != std::string::npos) {
						saveName = trim(ht.substr(lParen+1, rParen), "\t ()");
					}

					rv.push_back(RulePart(type, saveName, ruleEnd));
				}

				ruleMap.insert(std::make_pair(ruleName, Expr(rv)));
			}

		}
	}
}
示例#5
0
int main(int argc, char * argv[]) {

	if(argc != 3) {
		cout << "Usage: ./JobPrinter <input_file> <output_file>\n";
		exit(1);
	}

	JobPrinter jp(argv[1], argv[2]);
	jp.print();

	return 0;

}
TEST(inverted_index_storage, trivial) {
  inverted_index_storage s;
  // r1: (1, 1, 1, 0, 0)
  s.set("c1", "r1", 1);
  s.set("c2", "r1", 1);
  s.set("c3", "r1", 1);
  // r2: (1, 0, 1, 1, 0)
  s.set("c1", "r2", 1);
  s.set("c3", "r2", 1);
  s.set("c4", "r2", 1);
  // r3: (0, 1, 0, 0, 1)
  s.set("c2", "r3", 1);
  s.set("c5", "r3", 1);

  // v:  (1, 1, 0, 0, 0)
  common::sfv_t v;
  v.push_back(make_pair("c1", 1.0));
  v.push_back(make_pair("c2", 1.0));

  vector<pair<string, double> > scores;
  s.calc_scores(v, scores, 100);

  ASSERT_EQ(3u, scores.size());
  EXPECT_DOUBLE_EQ(2.0 / std::sqrt(3) / std::sqrt(2), scores[0].second);
  EXPECT_EQ("r1", scores[0].first);
  EXPECT_DOUBLE_EQ(1.0 / std::sqrt(2) / std::sqrt(2), scores[1].second);
  EXPECT_EQ("r3", scores[1].first);
  EXPECT_DOUBLE_EQ(1.0 / std::sqrt(2) / std::sqrt(3), scores[2].second);
  EXPECT_EQ("r2", scores[2].first);

  msgpack::sbuffer buf;
  framework::stream_writer<msgpack::sbuffer> st(buf);
  framework::jubatus_packer jp(st);
  framework::packer packer(jp);
  s.pack(packer);
  inverted_index_storage s2;
  msgpack::unpacked unpacked;
  msgpack::unpack(&unpacked, buf.data(), buf.size());
  s2.unpack(unpacked.get());
  vector<pair<string, double> > scores2;
  s.calc_scores(v, scores2, 100);
  // expect to get same result
  ASSERT_EQ(3u, scores2.size());
  EXPECT_DOUBLE_EQ(2.0 / std::sqrt(3) / std::sqrt(2), scores2[0].second);
  EXPECT_EQ("r1", scores2[0].first);
  EXPECT_DOUBLE_EQ(1.0 / std::sqrt(2) / std::sqrt(2), scores2[1].second);
  EXPECT_EQ("r3", scores2[1].first);
  EXPECT_DOUBLE_EQ(1.0 / std::sqrt(2) / std::sqrt(3), scores2[2].second);
  EXPECT_EQ("r2", scores2[2].first);
}
示例#7
0
void FrontSrvMainThread::beforeStart()
{
    MainThread<ChatSession, ChatSession>::beforeStart();
    FrontSrvScheduler::createInstance();
    FrontSrvRpcScheduler::createInstance();

    auto& logicThreadsVec = _logicThreadPool.getThreadPoolVec();
    for (auto& t : logicThreadsVec)
    {
        std::unique_ptr<FrontSrvJobProcesser> jp(new FrontSrvJobProcesser());
        jp->setLogicThread(t.get());
        t->setJobProcesser(std::move(jp));
    }
}
示例#8
0
bool LuRatio(void)
{	bool  ok = true;

	size_t  n = 2; // number rows in A 
	double  ratio;

	// values for independent and dependent variables
	CPPAD_TEST_VECTOR<double>  x(n*n), y(n*n+1);

	// pivot vectors
	CPPAD_TEST_VECTOR<size_t> ip(n), jp(n);

	// set x equal to the identity matrix
	x[0] = 1.; x[1] = 0;
	x[2] = 0.; x[3] = 1.;

	// create a fnction object corresponding to this value of x
	CppAD::ADFun<double> *FunPtr = NewFactor(n, x, ok, ip, jp);

	// use function object to factor matrix
	y     = FunPtr->Forward(0, x);
	ratio = y[n*n];
	ok   &= (ratio == 1.);
	ok   &= CheckLuFactor(n, x, y, ip, jp);

	// set x so that the pivot ratio will be infinite
	x[0] = 0. ; x[1] = 1.;
	x[2] = 1. ; x[3] = 0.;

	// try to use old function pointer to factor matrix
	y     = FunPtr->Forward(0, x);
	ratio = y[n*n];

	// check to see if we need to refactor matrix
	ok &= (ratio > 10.);
	if( ratio > 10. )
	{	delete FunPtr; // to avoid a memory leak	
		FunPtr = NewFactor(n, x, ok, ip, jp);
	}

	//  now we can use the function object to factor matrix
	y     = FunPtr->Forward(0, x);
	ratio = y[n*n];
	ok    &= (ratio == 1.);
	ok    &= CheckLuFactor(n, x, y, ip, jp);

	delete FunPtr;  // avoid memory leak
	return ok;
}
示例#9
0
jobject CRJNIEnv::toJavaProperties( CRPropRef props )
{
    jclass cls = env->FindClass("java/util/Properties");
    jmethodID mid = env->GetMethodID(cls, "<init>", "()V");
    jobject obj = env->NewObject(cls, mid);
    CRObjectAccessor jp(env, obj);
    CRMethodAccessor p_setProperty(jp, "setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;");
    for ( int i=0; i<props->getCount(); i++ ) {
    	jstring key = toJavaString(lString16(props->getName(i)));
    	jstring value = toJavaString(lString16(props->getValue(i)));
    	p_setProperty.callObj(key, value);
		env->DeleteLocalRef(key);
		env->DeleteLocalRef(value);
    }
	return obj;
}
示例#10
0
void save_server(FILE* fp,
    const server_base& server, const std::string& id) {
  init_versions();

  msgpack::sbuffer system_data_buf;
  msgpack::pack(&system_data_buf, system_data_container(server, id));

  msgpack::sbuffer user_data_buf;
  {
    core::framework::stream_writer<msgpack::sbuffer> st(user_data_buf);
    core::framework::jubatus_packer jp(st);
    core::framework::packer packer(jp);
    packer.pack_array(2);

    uint64_t user_data_version = server.user_data_version();
    packer.pack(user_data_version);
    server.get_driver()->pack(packer);
  }

  char header_buf[48];
  std::memcpy(header_buf, magic_number, 8);
  write_big_endian(format_version, &header_buf[8]);
  write_big_endian(jubatus_version_major, &header_buf[16]);
  write_big_endian(jubatus_version_minor, &header_buf[20]);
  write_big_endian(jubatus_version_maintenance, &header_buf[24]);
  // write_big_endian(crc32, &header_buf[28]);  // skipped
  write_big_endian(static_cast<uint64_t>(system_data_buf.size()),
                   &header_buf[32]);
  write_big_endian(static_cast<uint64_t>(user_data_buf.size()),
                   &header_buf[40]);

  uint32_t crc32 = calc_crc32(header_buf,
      system_data_buf.data(), system_data_buf.size(),
      user_data_buf.data(), user_data_buf.size());
  write_big_endian(crc32, &header_buf[28]);

  if (!fwrite_helper(header_buf, sizeof(header_buf), fp)) {
    throw std::ios_base::failure("Failed to write header_buf.");
  }
  if (!fwrite_helper(system_data_buf.data(), system_data_buf.size(), fp)) {
    throw std::ios_base::failure("Failed to write system_data_buf.");
  }
  if (!fwrite_helper(user_data_buf.data(), user_data_buf.size(), fp)) {
    throw std::ios_base::failure("Failed to write user_data_buf.");
  }
}
示例#11
0
CRPropRef CRJNIEnv::fromJavaProperties( jobject jprops )
{
    CRPropRef props = LVCreatePropsContainer();
    CRObjectAccessor jp(env, jprops);
    CRMethodAccessor p_getProperty(jp, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject en = CRMethodAccessor( jp, "propertyNames", "()Ljava/util/Enumeration;").callObj();
    CRObjectAccessor jen(env, en);
    CRMethodAccessor jen_hasMoreElements(jen, "hasMoreElements", "()Z");
    CRMethodAccessor jen_nextElement(jen, "nextElement", "()Ljava/lang/Object;");
    while ( jen_hasMoreElements.callBool() ) {
    	jstring key = (jstring)jen_nextElement.callObj();
    	jstring value = (jstring)p_getProperty.callObj(key);
    	props->setString(LCSTR(fromJavaString(key)),LCSTR(fromJavaString(value))); 
    	env->DeleteLocalRef(key); 
    	env->DeleteLocalRef(value); 
    }
	return props;
}
示例#12
0
    unsigned int
    add_arc_as_single_cubic(int max_recursion, Builder *B, float tol,
                            vec2 from_pt, vec2 to_pt, float angle)
    {
      vec2 vp(to_pt - from_pt);
      vec2 jp(-vp.y(), vp.x());
      float d(t_tan(angle * 0.25f));
      vec2 c0, c1;

      vp *= ((1.0f - d * d) / 3.0f);
      jp *= (2.0f * d / 3.0f);
      c0 = from_pt + vp - jp;
      c1 = to_pt - vp - jp;

      return add_cubic_adaptive(max_recursion, B,
                                vecN<vec2, 4>(from_pt, c0, c1, to_pt),
                                tol);
    }
示例#13
0
void GameConfig::load() {
  JsonParser jp(JsonParser::getBuffer("configs/GameConfig.json"));
  auto &json = jp.getCurrentDocument();
  
  HeroSize = json["heroSize"].GetDouble();
  MoveAcceleration = json["moveAcceleration"].GetDouble();
  JumpAcceleration = json["jumpAcceleration"].GetDouble();
  AccelerationResistance = json["accelerationResistance"].GetDouble();
  SawImage = json["sawImage"].GetString();
  SawImageRotation = json["sawImageRotation"].GetString();
  CurtainMoveTime = json["curtainMoveTime"].GetDouble();

  std::string controlKey = "controlPad" + JsonParser::getLevelSuffix();
  auto &controls = json[controlKey.c_str()];
  ControlPadScale = controls["scale"].GetDouble();
  ControlPadLeftButton = controls["leftButton"].GetVec2();
  ControlPadRightButton = controls["rightButton"].GetVec2();
  ControlPadJumpButton = controls["jumpButton"].GetVec2();
}
示例#14
0
TEST_F(stat_test, small) {
  stat_->push("hoge", 12);
  ASSERT_DOUBLE_EQ(12.0, stat_->sum("hoge"));

  // TODO(kuenishi): add more tests
  ASSERT_DOUBLE_EQ(.0, stat_->stddev("hoge"));
  ASSERT_DOUBLE_EQ(12.0, stat_->max("hoge"));
  ASSERT_DOUBLE_EQ(12.0, stat_->min("hoge"));

  ASSERT_DOUBLE_EQ(0., stat_->entropy());

  msgpack::sbuffer sbuf;
  framework::stream_writer<msgpack::sbuffer> st(sbuf);
  framework::jubatus_packer jp(st);
  framework::packer pk(jp);
  stat_->pack(pk);

  msgpack::unpacked msg;
  msgpack::unpack(&msg, sbuf.data(), sbuf.size());
  stat_->unpack(msg.get());
}
示例#15
0
void delay(unsigned long r)
{
__asm
    pop hl	; return address
    pop de	; low
    pop bc	; high
    
loop:
    dec de
    ld a,d
    or e
    jp nz,loop
    ld a,b
    or c
    dec bc
    jp nz,loop
    push bc
    push de
    jp (hl)
__endasm;
}
示例#16
0
TEST_F(anomaly_test, small) {
  {
    fv_converter::datum datum;
    datum.num_values_.push_back(make_pair("f1", 1.0));

    anomaly_->add("1", datum);  // is it good to be inf?
    std::pair<std::string, float> w = anomaly_->add("2", datum);
    float v = anomaly_->calc_score(datum);
    ASSERT_DOUBLE_EQ(w.second, v);
  }
  {
    std::vector<std::string> rows = anomaly_->get_all_rows();
    ASSERT_EQ(2u, rows.size());
  }


  // save
  msgpack::sbuffer sbuf;
  framework::stream_writer<msgpack::sbuffer> st(sbuf);
  framework::jubatus_packer jp(st);
  framework::packer pk(jp);
  anomaly_->pack(pk);

  // clear
  anomaly_->clear();
  {
    std::vector<std::string> rows = anomaly_->get_all_rows();
    ASSERT_EQ(0u, rows.size());
  }

  { // load
    msgpack::unpacked msg;
    msgpack::unpack(&msg, sbuf.data(), sbuf.size());
    anomaly_->unpack(msg.get());
    std::vector<std::string> rows = anomaly_->get_all_rows();
    ASSERT_EQ(2u, rows.size());
  }
}
示例#17
0
TEST_P(storage_test, pack_unpack) {
  storage_ptr s = storage_factory::create(name, conf);
  ASSERT_TRUE(s != NULL);
  for (size_t i = 0; i < 10; ++i) {
    s->add(get_point(3));
  }

  // pack
  msgpack::sbuffer buf;
  {
    framework::stream_writer<msgpack::sbuffer> st(buf);
    framework::jubatus_packer jp(st);
    framework::packer packer(jp);
    s->pack(packer);
  }

  // unpack
  storage_ptr s2 = storage_factory::create(name, conf);
  ASSERT_TRUE(s2 != NULL);
  {
    msgpack::unpacked unpacked;
    msgpack::unpack(&unpacked, buf.data(), buf.size());
    s2->unpack(unpacked.get());
  }

  EXPECT_EQ(s->get_revision(), s2->get_revision());

  {
    wplist all1 = s->get_all(), all2 = s2->get_all();

    ASSERT_EQ(all1.size(), all2.size());
    for (size_t i = 0; i < all1.size(); ++i) {
      EXPECT_EQ(all1[i].weight, all2[i].weight);
      EXPECT_EQ(all1[i].data, all2[i].data);
      // EXPECT_EQ(all1[i].original, all2[i].original);
    }
  }
}
示例#18
0
inline result_t _jsonDecode(const char *data,
                            v8::Local<v8::Value> &retVal)
{
	class json_parser
	{
	public:
		json_parser(const char* source)
			: isolate(Isolate::current()),
			  source_(source),
			  source_length_((int32_t)qstrlen(source)),
			  position_(-1)
		{}

		inline void Advance()
		{
			position_++;
			if (position_ >= source_length_)
				c0_ = 0;
			else
				c0_ = source_[position_];
		}

		inline void AdvanceSkipWhitespace()
		{
			do {
				Advance();
			} while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r');
		}

		inline void SkipWhitespace()
		{
			while (c0_ == ' ' || c0_ == '\t' || c0_ == '\n' || c0_ == '\r') {
				Advance();
			}
		}

		inline char AdvanceGetChar()
		{
			Advance();
			return c0_;
		}

		inline bool MatchSkipWhiteSpace(char c)
		{
			if (c0_ == c) {
				AdvanceSkipWhitespace();
				return true;
			}
			return false;
		}

		result_t ParseJsonNumber(v8::Local<v8::Value> &retVal)
		{
			bool negative = false;
			int32_t beg_pos = position_;

			if (c0_ == '-') {
				Advance();
				negative = true;
			}

			if (c0_ == '0') {
				Advance();
				if (IsDecimalDigit(c0_))
					return ReportUnexpectedCharacter();
			} else
			{
				int32_t i = 0;
				int32_t digits = 0;
				if (c0_ < '1' || c0_ > '9')
					return ReportUnexpectedCharacter();

				do {
					i = i * 10 + c0_ - '0';
					digits++;
					Advance();
				} while (IsDecimalDigit(c0_));

				if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) {
					SkipWhitespace();
					retVal = v8::Int32::New(isolate->m_isolate, negative ? -i : i);
					return 0;
				}
			}

			if (c0_ == '.') {
				Advance();
				if (!IsDecimalDigit(c0_))
					return ReportUnexpectedCharacter();

				do {
					Advance();
				} while (IsDecimalDigit(c0_));
			}

			if (AsciiAlphaToLower(c0_) == 'e') {
				Advance();
				if (c0_ == '-' || c0_ == '+') Advance();
				if (!IsDecimalDigit(c0_))
					return ReportUnexpectedCharacter();

				do {
					Advance();
				} while (IsDecimalDigit(c0_));
			}

			int32_t length = position_ - beg_pos;
			double number;
			std::string chars(source_ + beg_pos, length);

			number = atof(chars.c_str());
			SkipWhitespace();
			retVal = v8::Number::New(isolate->m_isolate, number);
			return 0;
		}

		result_t ParseJsonString(v8::Local<v8::Value> &retVal)
		{
			wstring str;

			Advance();
			while (c0_ != '"') {
				if (c0_ >= 0 && c0_ < 0x20)
					return ReportUnexpectedCharacter();

				if (c0_ != '\\') {
					int32_t beg_pos = position_;

					while (c0_ != '"' && c0_ != '\\')
					{
						Advance();
						if (c0_ >= 0 && c0_ < 0x20)
							return ReportUnexpectedCharacter();
					}
					str.append(utf8to16String(source_ + beg_pos, position_ - beg_pos));
				} else {
					Advance();
					switch (c0_) {
					case '"':
					case '\\':
					case '/':
						str.append(1, c0_);
						break;
					case 'b':
						str.append(1, '\x08');
						break;
					case 'f':
						str.append(1, '\x0c');
						break;
					case 'n':
						str.append(1, '\x0a');
						break;
					case 'r':
						str.append(1, '\x0d');
						break;
					case 't':
						str.append(1, '\x09');
						break;
					case 'u': {
						uint16_t value = 0;
						for (int32_t i = 0; i < 4; i++) {
							Advance();
							if (!qisxdigit(c0_))
								return ReportUnexpectedCharacter();

							value = value * 16 + qhex(c0_);
						}

						str.append(1, value);
						break;
					}
					default:
						return ReportUnexpectedCharacter();
					}
					Advance();
				}
			}

			AdvanceSkipWhitespace();

			retVal = v8::String::NewFromTwoByte(isolate->m_isolate,
			                                    (const uint16_t*)str.c_str(),
			                                    v8::String::kNormalString,
			                                    (int32_t) str.length());
			return 0;
		}

		result_t ParseJsonArray(v8::Local<v8::Value> &retVal)
		{
			v8::Local<v8::Array> elements = v8::Array::New(isolate->m_isolate);
			int32_t cnt = 0;
			result_t hr;

			AdvanceSkipWhitespace();

			if (c0_ != ']')
			{
				do {
					v8::Local<v8::Value> element;
					hr = ParseJsonValue(element);
					if (hr < 0)
						return hr;
					elements->Set(cnt ++, element);
				} while (MatchSkipWhiteSpace(','));

				if (c0_ != ']')
					return ReportUnexpectedCharacter();
			}

			AdvanceSkipWhitespace();
			retVal = elements;
			return 0;
		}

		result_t ParseJsonObject(v8::Local<v8::Value> &retVal)
		{
			v8::Local<v8::Object> json_object = v8::Object::New(isolate->m_isolate);
			result_t hr;

			AdvanceSkipWhitespace();
			if (c0_ != '}')
			{
				do {
					if (c0_ != '"')
						return ReportUnexpectedCharacter();

					v8::Local<v8::Value> key;
					v8::Local<v8::Value> value;

					hr = ParseJsonString(key);
					if (hr < 0)
						return hr;

					if (c0_ != ':')
						return ReportUnexpectedCharacter();

					AdvanceSkipWhitespace();

					hr = ParseJsonValue(value);
					if (hr < 0)
						return hr;

					json_object->Set(key, value);
				} while (MatchSkipWhiteSpace(','));

				if (c0_ != '}')
					return ReportUnexpectedCharacter();
			}

			AdvanceSkipWhitespace();
			retVal = json_object;
			return 0;
		}

		result_t ParseJsonValue(v8::Local<v8::Value> &retVal)
		{
			if (c0_ == '"')
				return ParseJsonString(retVal);

			if ((c0_ >= '0' && c0_ <= '9') || c0_ == '-')
				return ParseJsonNumber(retVal);

			if (c0_ == '{')
				return ParseJsonObject(retVal);

			if (c0_ == '[')
				return ParseJsonArray(retVal);

			if (c0_ == 'f') {
				if (AdvanceGetChar() == 'a' && AdvanceGetChar() == 'l' &&
				        AdvanceGetChar() == 's' && AdvanceGetChar() == 'e') {
					AdvanceSkipWhitespace();
					retVal = v8::False(isolate->m_isolate);

					return 0;
				}
				return ReportUnexpectedCharacter();
			}

			if (c0_ == 't') {
				if (AdvanceGetChar() == 'r' && AdvanceGetChar() == 'u' &&
				        AdvanceGetChar() == 'e') {
					AdvanceSkipWhitespace();
					retVal = v8::True(isolate->m_isolate);

					return 0;
				}
				return ReportUnexpectedCharacter();
			}

			if (c0_ == 'n') {
				if (AdvanceGetChar() == 'u' && AdvanceGetChar() == 'l' &&
				        AdvanceGetChar() == 'l') {
					AdvanceSkipWhitespace();
					retVal = v8::Null(isolate->m_isolate);

					return 0;
				}
				return ReportUnexpectedCharacter();
			}

			return ReportUnexpectedCharacter();
		}

		result_t ReportUnexpectedCharacter()
		{
			std::string s = "Unexpected token ";
			s.append(1, c0_);
			return CHECK_ERROR(Runtime::setError(s));
		}

		result_t ParseJson(v8::Local<v8::Value> &retVal)
		{
			AdvanceSkipWhitespace();
			return ParseJsonValue(retVal);
		}

	private:
		Isolate* isolate;
		const char* source_;
		int32_t source_length_;
		int32_t position_;
		char c0_;
	};

	json_parser jp(data);
	return jp.ParseJson(retVal);
}
示例#19
0
文件: chacha.c 项目: CRTandKDU/TRS80
void main(){
  unsigned char i;
  /* Zero state */
  for( i=0; i<64; i++ ) x[i]=0;
  /* Fills in constants */
  i=0;
  x[i++]='e';
  x[i++]='x';
  x[i++]='p';
  x[i++]='a';
  x[i++]='n';
  x[i++]='d';
  x[i++]=' ';
  x[i++]='3';
  x[i++]='2';
  x[i++]='-';
  x[i++]='b';
  x[i++]='y';
  x[i++]='t';
  x[i++]='e';
  x[i++]=' ';
  x[i++]='k';
  /* Nonce */
  i=48;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;
  x[i++]=0;

  /* 4 rounds of 8 quarter-rounds */
  for( i=0; i<8; i+=2 ){
#ifdef __OPTSPACE__
    qr( 0, 4, 8,12);
    qr( 1, 5, 9,13);
    qr( 2, 6,10,14);
    qr( 3, 7,11,15);
    qr( 0, 5,10,15);
    qr( 1, 6,11,12);
    qr( 2, 7, 8,13);
    qr( 3, 4, 9,14);
#else
    /* Unroll loop */
    QUARTERROUND( 0, 4, 8,12);
    QUARTERROUND( 1, 5, 9,13);
    QUARTERROUND( 2, 6,10,14);
    QUARTERROUND( 3, 7,11,15);
    QUARTERROUND( 0, 5,10,15);
    QUARTERROUND( 1, 6,11,12);
    QUARTERROUND( 2, 7, 8,13);
    QUARTERROUND( 3, 4, 9,14);
#endif
  }

#ifdef __TRS80__
  /* Display resulting state */
  for( i=0; i<64; i++ ){
    if( 0==i%8 ) print_crlf();
    print_char( x[i] );
  }
  /* Jump back to BASIC */
  __asm
    ld		a,#0x0d		; CR
    call	0x33		; Print it
    ld		hl,#0x6cc	; BASIC command line
    jp		(hl)
  __endasm;
#endif
}
示例#20
0
Vector Rosen34(
	Fun           &F , 
	size_t         M , 
	const Scalar &ti , 
	const Scalar &tf , 
	const Vector &xi ,
	Vector       &e )
{
	CPPAD_ASSERT_FIRST_CALL_NOT_PARALLEL;

	// check numeric type specifications
	CheckNumericType<Scalar>();

	// check simple vector class specifications
	CheckSimpleVector<Scalar, Vector>();

	// Parameters for Shampine's Rosenbrock method
	// are static to avoid recalculation on each call and 
	// do not use Vector to avoid possible memory leak
	static Scalar a[3] = {
		Scalar(0),
		Scalar(1),
		Scalar(3)   / Scalar(5)
	};
	static Scalar b[2 * 2] = {
		Scalar(1),
		Scalar(0),
		Scalar(24)  / Scalar(25),
		Scalar(3)   / Scalar(25)
	};
	static Scalar ct[4] = {
		Scalar(1)   / Scalar(2),
		- Scalar(3) / Scalar(2),
		Scalar(121) / Scalar(50),
		Scalar(29)  / Scalar(250)
	};
	static Scalar cg[3 * 3] = {
		- Scalar(4),
		Scalar(0),
		Scalar(0),
		Scalar(186) / Scalar(25),
		Scalar(6)   / Scalar(5),
		Scalar(0),
		- Scalar(56) / Scalar(125),
		- Scalar(27) / Scalar(125),
		- Scalar(1)  / Scalar(5)
	};
	static Scalar d3[3] = {
		Scalar(97) / Scalar(108),
		Scalar(11) / Scalar(72),
		Scalar(25) / Scalar(216)
	};
	static Scalar d4[4] = {
		Scalar(19)  / Scalar(18),
		Scalar(1)   / Scalar(4),
		Scalar(25)  / Scalar(216),
		Scalar(125) / Scalar(216)
	};
	CPPAD_ASSERT_KNOWN(
		M >= 1,
		"Error in Rosen34: the number of steps is less than one"
	);
	CPPAD_ASSERT_KNOWN(
		e.size() == xi.size(),
		"Error in Rosen34: size of e not equal to size of xi"
	);
	size_t i, j, k, l, m;             // indices

	size_t  n    = xi.size();         // number of components in X(t)
	Scalar  ns   = Scalar(double(M)); // number of steps as Scalar object
	Scalar  h    = (tf - ti) / ns;    // step size 
	Scalar  zero = Scalar(0);         // some constants
	Scalar  one  = Scalar(1);
	Scalar  two  = Scalar(2);

	// permutation vectors needed for LU factorization routine
	CppAD::vector<size_t> ip(n), jp(n);

	// vectors used to store values returned by F
	Vector E(n * n), Eg(n), f_t(n);
	Vector g(n * 3), x3(n), x4(n), xf(n), ftmp(n), xtmp(n), nan_vec(n);

	// initialize e = 0, nan_vec = nan
	for(i = 0; i < n; i++)
	{	e[i]       = zero;
		nan_vec[i] = nan(zero);
	}

	xf = xi;           // initialize solution
	for(m = 0; m < M; m++)
	{	// time at beginning of this interval
		Scalar t = ti * (Scalar(int(M - m)) / ns) 
		         + tf * (Scalar(int(m)) / ns);

		// value of x at beginning of this interval
		x3 = x4 = xf;

		// evaluate partial derivatives at beginning of this interval
		F.Ode_ind(t, xf, f_t);
		F.Ode_dep(t, xf, E);    // E = f_x
		if( hasnan(f_t) || hasnan(E) )
		{	e = nan_vec;
			return nan_vec;
		}

		// E = I - f_x * h / 2
		for(i = 0; i < n; i++)
		{	for(j = 0; j < n; j++)
				E[i * n + j] = - E[i * n + j] * h / two;
			E[i * n + i] += one;
		}

		// LU factor the matrix E
# ifndef NDEBUG
		int sign = LuFactor(ip, jp, E);
# else
		LuFactor(ip, jp, E);
# endif
		CPPAD_ASSERT_KNOWN(
			sign != 0,
			"Error in Rosen34: I - f_x * h / 2 not invertible"
		);

		// loop over integration steps
		for(k = 0; k < 3; k++)
		{	// set location for next function evaluation
			xtmp = xf; 
			for(l = 0; l < k; l++)
			{	// loop over previous function evaluations
				Scalar bkl = b[(k-1)*2 + l];
				for(i = 0; i < n; i++)
				{	// loop over elements of x
					xtmp[i] += bkl * g[i*3 + l] * h;
				}
			}
			// ftmp = F(t + a[k] * h, xtmp)
			F.Ode(t + a[k] * h, xtmp, ftmp); 
			if( hasnan(ftmp) )
			{	e = nan_vec;
				return nan_vec;
			}

			// Form Eg for this integration step
			for(i = 0; i < n; i++)
				Eg[i] = ftmp[i] + ct[k] * f_t[i] * h;
			for(l = 0; l < k; l++)
			{	for(i = 0; i < n; i++)
					Eg[i] += cg[(k-1)*3 + l] * g[i*3 + l];
			}

			// Solve the equation E * g = Eg
			LuInvert(ip, jp, E, Eg);

			// save solution and advance x3, x4
			for(i = 0; i < n; i++)
			{	g[i*3 + k]  = Eg[i];
				x3[i]      += h * d3[k] * Eg[i];
				x4[i]      += h * d4[k] * Eg[i];
			}
		}
		// Form Eg for last update to x4 only
		for(i = 0; i < n; i++)
			Eg[i] = ftmp[i] + ct[3] * f_t[i] * h;
		for(l = 0; l < 3; l++)
		{	for(i = 0; i < n; i++)
				Eg[i] += cg[2*3 + l] * g[i*3 + l];
		}

		// Solve the equation E * g = Eg
		LuInvert(ip, jp, E, Eg);

		// advance x4 and accumulate error bound
		for(i = 0; i < n; i++)
		{	x4[i] += h * d4[3] * Eg[i];

			// cant use abs because cppad.hpp may not be included
			Scalar diff = x4[i] - x3[i];
			if( diff < zero )
				e[i] -= diff;
			else	e[i] += diff;
		}

		// advance xf for this step using x4
		xf = x4;
	}
	return xf;
}
示例#21
0
文件: lu_solve.hpp 项目: kaskr/CppAD
int LuSolve(
	size_t             n      ,
	size_t             m      ,
	const FloatVector &A      ,
	const FloatVector &B      ,
	FloatVector       &X      ,
	Float        &logdet      )
{
	// check numeric type specifications
	CheckNumericType<Float>();

	// check simple vector class specifications
	CheckSimpleVector<Float, FloatVector>();

	size_t        p;       // index of pivot element (diagonal of L)
	int     signdet;       // sign of the determinant
	Float     pivot;       // pivot element

	// the value zero
	const Float zero(0);

	// pivot row and column order in the matrix
	std::vector<size_t> ip(n);
	std::vector<size_t> jp(n);

	// -------------------------------------------------------
	CPPAD_ASSERT_KNOWN(
		size_t(A.size()) == n * n,
		"Error in LuSolve: A must have size equal to n * n"
	);
	CPPAD_ASSERT_KNOWN(
		size_t(B.size()) == n * m,
		"Error in LuSolve: B must have size equal to n * m"
	);
	CPPAD_ASSERT_KNOWN(
		size_t(X.size()) == n * m,
		"Error in LuSolve: X must have size equal to n * m"
	);
	// -------------------------------------------------------

	// copy A so that it does not change
	FloatVector Lu(A);

	// copy B so that it does not change
	X = B;

	// Lu factor the matrix A
	signdet = LuFactor(ip, jp, Lu);

	// compute the log of the determinant
	logdet  = Float(0);
	for(p = 0; p < n; p++)
	{	// pivot using the max absolute element
		pivot   = Lu[ ip[p] * n + jp[p] ];

		// check for determinant equal to zero
		if( pivot == zero )
		{	// abort the mission
			logdet = Float(0);
			return   0;
		}

		// update the determinant
		if( LeqZero ( pivot ) )
		{	logdet += log( - pivot );
			signdet = - signdet;
		}
		else	logdet += log( pivot );

	}

	// solve the linear equations
	LuInvert(ip, jp, Lu, X);

	// return the sign factor for the determinant
	return signdet;
}
示例#22
0
void
Elastic::FAC::pack_strain(double* buffer,
                          const SAMRAI::hier::Patch& patch,
                          const SAMRAI::hier::Box& region,
                          const int &depth) const
{
  boost::shared_ptr<SAMRAI::pdat::SideData<double> > v_ptr=
    boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> >
    (patch.getPatchData(v_id));
  SAMRAI::pdat::SideData<double>& v = *v_ptr;

  boost::shared_ptr<SAMRAI::pdat::CellData<double> > dv_diagonal;
  boost::shared_ptr<SAMRAI::pdat::SideData<double> > dv_mixed;
  if(!faults.empty())
    {
      dv_diagonal=boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> >
        (patch.getPatchData(dv_diagonal_id));
      dv_mixed=boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> >
        (patch.getPatchData(dv_mixed_id));
    }

  const Gamra::Dir dim=d_dim.getValue();
  if(have_embedded_boundary())
    {
      boost::shared_ptr<SAMRAI::pdat::SideData<double> > level_set_ptr;
      if(have_embedded_boundary())
        level_set_ptr=boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> >
          (patch.getPatchData(level_set_id));
    }

  Gamra::Dir ix(Gamra::Dir::from_int(depth/dim)),
    iy(Gamra::Dir::from_int(depth%dim));
  const SAMRAI::hier::Index zero(SAMRAI::hier::Index::getZeroIndex(d_dim));
  SAMRAI::hier::Index ip(zero), jp(zero);
  ip[ix]=1;
  jp[iy]=1;

  const double *dx(boost::dynamic_pointer_cast
                   <SAMRAI::geom::CartesianPatchGeometry>
                   (patch.getPatchGeometry())->getDx());

  SAMRAI::pdat::CellIterator iend(SAMRAI::pdat::CellGeometry::end(region));
  for(SAMRAI::pdat::CellIterator
        icell(SAMRAI::pdat::CellGeometry::begin(region));
      icell!=iend; ++icell)
    {
      const SAMRAI::pdat::SideIndex
        s(*icell,ix,SAMRAI::pdat::SideIndex::Lower);
      if(ix==iy)
        {
          double diff(v(s+ip)-v(s));
          if(!faults.empty())
            diff-=(*dv_diagonal)(*icell,ix);
          *buffer=diff/dx[ix];
        }
      else
        {
          const int ix_iy(index_map(ix,iy,dim));
          double diff(- v(s-jp) - v(s+ip-jp) + v(s+jp)  + v(s+ip+jp));

          if(!faults.empty())
            diff+=(*dv_mixed)(s,ix_iy+1) - (*dv_mixed)(s-jp,ix_iy)
              + (*dv_mixed)(s+ip,ix_iy+1) - (*dv_mixed)(s+ip-jp,ix_iy)
              + (*dv_mixed)(s+jp,ix_iy+1) - (*dv_mixed)(s,ix_iy)
              + (*dv_mixed)(s+ip+jp,ix_iy+1) - (*dv_mixed)(s+ip,ix_iy);
          *buffer=diff/(4*dx[iy]);
        }
      ++buffer;
    }
}
示例#23
0
void OdeGear(
	Fun          &F  , 
	size_t        m  ,
	size_t        n  ,
	const Vector &T  , 
	Vector       &X  ,
	Vector       &e  ) 
{
	// temporary indices
	size_t i, j, k;

	typedef typename Vector::value_type Scalar;

	// check numeric type specifications
	CheckNumericType<Scalar>();

	// check simple vector class specifications
	CheckSimpleVector<Scalar, Vector>();

	CPPAD_ASSERT_KNOWN(
		m >= 1,
		"OdeGear: m is less than one"
	);
	CPPAD_ASSERT_KNOWN(
		n > 0,
		"OdeGear: n is equal to zero"
	);
	CPPAD_ASSERT_KNOWN(
		size_t(T.size()) >= (m+1),
		"OdeGear: size of T is not greater than or equal (m+1)"
	);
	CPPAD_ASSERT_KNOWN(
		size_t(X.size()) >= (m+1) * n,
		"OdeGear: size of X is not greater than or equal (m+1) * n"
	);
	for(j = 0; j < m; j++) CPPAD_ASSERT_KNOWN(
		T[j] < T[j+1],
		"OdeGear: the array T is not monotone increasing"
	);

	// some constants
	Scalar zero(0);
	Scalar one(1);

	// vectors required by method
	Vector alpha(m + 1);
	Vector beta(m + 1);
	Vector f(n);
	Vector f_x(n * n);
	Vector x_m0(n);
	Vector x_m(n);
	Vector b(n);
	Vector A(n * n);

	// compute alpha[m] 
	alpha[m] = zero;
	for(k = 0; k < m; k++)
		alpha[m] += one / (T[m] - T[k]);

	// compute beta[m-1]
	beta[m-1] = one / (T[m-1] - T[m]);
	for(k = 0; k < m-1; k++)
		beta[m-1] += one / (T[m-1] - T[k]);


	// compute other components of alpha 
	for(j = 0; j < m; j++)
	{	// compute alpha[j]
		alpha[j] = one / (T[j] - T[m]);
		for(k = 0; k < m; k++)
		{	if( k != j )
			{	alpha[j] *= (T[m] - T[k]);
				alpha[j] /= (T[j] - T[k]);
			}
		}
	}

	// compute other components of beta 
	for(j = 0; j <= m; j++)
	{	if( j != m-1 )
		{	// compute beta[j]
			beta[j] = one / (T[j] - T[m-1]);
			for(k = 0; k <= m; k++)
			{	if( k != j && k != m-1 )
				{	beta[j] *= (T[m-1] - T[k]);
					beta[j] /= (T[j] - T[k]);
				}
			}
		}
	}

	// evaluate f(T[m-1], x_{m-1} )
	for(i = 0; i < n; i++)
		x_m[i] = X[(m-1) * n + i];
	F.Ode(T[m-1], x_m, f);

	// solve for x_m^0
	for(i = 0; i < n; i++)
	{	x_m[i] =  f[i];
		for(j = 0; j < m; j++)
			x_m[i] -= beta[j] * X[j * n + i];
		x_m[i] /= beta[m];
	}
	x_m0 = x_m;

	// evaluate partial w.r.t x of f(T[m], x_m^0)
	F.Ode_dep(T[m], x_m, f_x);

	// compute the matrix A = ( alpha[m] * I - f_x )
	for(i = 0; i < n; i++)
	{	for(j = 0; j < n; j++)
			A[i * n + j]  = - f_x[i * n + j];
		A[i * n + i] += alpha[m];
	}

	// LU factor (and overwrite) the matrix A
	int sign;
	CppAD::vector<size_t> ip(n) , jp(n);
	sign = LuFactor(ip, jp, A);
	CPPAD_ASSERT_KNOWN(
		sign != 0,
		"OdeGear: step size is to large"
	);

	// Iterations of Newton's method
	for(k = 0; k < 3; k++)
	{
		// only evaluate f( T[m] , x_m ) keep f_x during iteration
		F.Ode(T[m], x_m, f);

		// b = f + f_x x_m - alpha[0] x_0 - ... - alpha[m-1] x_{m-1}
		for(i = 0; i < n; i++)
		{	b[i]         = f[i];
			for(j = 0; j < n; j++)
				b[i]         -= f_x[i * n + j] * x_m[j];
			for(j = 0; j < m; j++)
				b[i] -= alpha[j] * X[ j * n + i ];
		}
		LuInvert(ip, jp, A, b);
		x_m = b;
	}

	// return estimate for x( t[k] ) and the estimated error bound
	for(i = 0; i < n; i++)
	{	X[m * n + i] = x_m[i];
		e[i]         = x_m[i] - x_m0[i];
		if( e[i] < zero )
			e[i] = - e[i];
	}
}
示例#24
0
void main(){
  short i;
  unsigned long  u, v;
  // iota constant
  RC[0]=1;
  RC[1]=0;
  RC[2]=32898;
  RC[3]=0;
  RC[4]=32906;
  RC[5]=2147483648;
  RC[6]=2147516416;
  RC[7]=2147483648;
  RC[8]=32907;
  RC[9]=0;
  RC[10]=2147483649;
  RC[11]=0;
  RC[12]=2147516545;
  RC[13]=2147483648;
  RC[14]=32777;
  RC[15]=2147483648;
  RC[16]=138;
  RC[17]=0;
  RC[18]=136;
  RC[19]=0;
  RC[20]=2147516425;
  RC[21]=0;
  RC[22]=2147483658;
  RC[23]=0;
  RC[24]=2147516555;
  RC[25]=0;
  RC[26]=139;
  RC[27]=2147483648;
  RC[28]=32905;
  RC[29]=2147483648;
  RC[30]=32771;
  RC[31]=2147483648;
  RC[32]=32770;
  RC[33]=2147483648;
  RC[34]=128;
  RC[35]=2147483648;
  RC[36]=32778;
  RC[37]=0;
  RC[38]=2147483658;
  RC[39]=2147483648;
  RC[40]=2147516545;
  RC[41]=2147483648;
  RC[42]=32896;
  RC[43]=2147483648;
  RC[44]=2147483649;
  RC[45]=0;
  RC[46]=2147516424;
  RC[47]=2147483648;
  // rho pi constants
  r[0]=0;
  r[1]=1;
  r[2]=62;
  r[3]=28;
  r[4]=27;
  r[5]=36;
  r[6]=44;
  r[7]=6;
  r[8]=55;
  r[9]=20;
  r[10]=3;
  r[11]=10;
  r[12]=43;
  r[13]=25;
  r[14]=39;
  r[15]=41;
  r[16]=45;
  r[17]=15;
  r[18]=21;
  r[19]=8;
  r[20]=18;
  r[21]=2;
  r[22]=61;
  r[23]=56;
  r[24]=14;

  pB[0]=0;
  pB[1]=10;
  pB[2]=20;
  pB[3]=5;
  pB[4]=15;
  pB[5]=16;
  pB[6]=1;
  pB[7]=11;
  pB[8]=21;
  pB[9]=6;
  pB[10]=7;
  pB[11]=17;
  pB[12]=2;
  pB[13]=12;
  pB[14]=22;
  pB[15]=23;
  pB[16]=8;
  pB[17]=18;
  pB[18]=3;
  pB[19]=13;
  pB[20]=14;
  pB[21]=24;
  pB[22]=9;
  pB[23]=19;
  pB[24]=4;

  // Set up and display state
  for( i=0; i<K_LANES; i++ ) { A[2*i] = 0; A[2*i+1] = 0; }
  A[0]=123456L; A[2]=234567L; A[4]=345678L; A[6]=456789L; A[8]=567890L;
#ifdef __TRS80__
  /* Display resulting state */
  for( i=0; i<K_LANES; i++ ){
    if( 0==i || 5==i || 10==i || 15==i || 20==i ) print_crlf();
    u = A[2*i]; v = A[2*i+1];
    print_short( (unsigned short) (u%65536) ); 
    print_short( (unsigned short) (u>>16) );
    print_short( (unsigned short) (v%65536) ); 
    print_short( (unsigned short) (v>>16) );
  }
  print_crlf();
#else
  printf( "Size of lane: %d\n", 2*sizeof( unsigned long ) );
  for( i=0; i<K_LANES; i++ ){
    if( 0==i || 5==i || 10==i || 15==i || 20==i ) printf("\n");
    u = A[2*i]; v = A[2*i+1];
    printf( "(%5u, %5u, %5u %5u) ", 
	    (unsigned int) (u%65536), (unsigned int) (u>>16),
	    (unsigned int) (v%65536), (unsigned int) (v>>16)
	    );
  }
  printf("\n");
#endif

  KRounds();

#ifdef __TRS80__
  /* Display resulting state */
  /* for( i=0; i<K_LANES; i++ ){ */
  /*   if( 0==i || 5==i || 10==i || 15==i || 20==i ) print_crlf(); */
  /*   print_short( A[i] ); */
  /* } */
  /* Jump back to BASIC */
  __asm
    ld		a,#0x0d		; CR
    call	0x33		; Print it
    ld		hl,#0x6cc	; BASIC command line
    jp		(hl)
  __endasm;
#else
  /* Display resulting state */
  for( i=0; i<K_LANES; i++ ){
    if( 0==i || 5==i || 10==i || 15==i || 20==i ) printf("\n");
    u = A[2*i]; v = A[2*i+1];
    printf( "(%5u, %5u, %5u %5u) ", 
	    (unsigned int) (u%65536), (unsigned int) (u>>16),
	    (unsigned int) (v%65536), (unsigned int) (v>>16)
	    );
  }
#endif
}
示例#25
0
void
Stokes::V_Coarsen_Patch_Strategy::postprocessCoarsen_2D
(SAMRAI::hier::Patch& coarse,
 const SAMRAI::hier::Patch& fine,
 const SAMRAI::hier::Box& ,
 const SAMRAI::hier::IntVector& )
{
  /* Fix up the boundary elements by iterating through the boundary
     boxes */

  /* We only care about edges, not corners, so we only iterate over
     edge boundary boxes. */
  const std::vector<SAMRAI::hier::BoundaryBox>
    &boundaries=coarse_fine[fine.getPatchLevelNumber()]->getEdgeBoundaries(coarse.getGlobalId());
     
  boost::shared_ptr<SAMRAI::pdat::SideData<double> > v_fine =
    boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> >
    (fine.getPatchData(v_id));
  boost::shared_ptr<SAMRAI::pdat::SideData<double> > v =
    boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> >
    (coarse.getPatchData(v_id));

  TBOX_ASSERT(v);
  TBOX_ASSERT(v_fine);
  TBOX_ASSERT(v_fine->getDepth() == v->getDepth());
  TBOX_ASSERT(v->getDepth() == 1);

  SAMRAI::hier::Box gbox(v_fine->getGhostBox());
  SAMRAI::hier::Index ip(1,0), jp(0,1);
  for(size_t mm=0; mm<boundaries.size(); ++mm)
    {
      SAMRAI::hier::Box bbox=boundaries[mm].getBox();
      int location_index=boundaries[mm].getLocationIndex();

      SAMRAI::hier::Index
        lower=SAMRAI::hier::Index::coarsen(bbox.lower(),
                                           SAMRAI::hier::Index(2,2)),
        upper=SAMRAI::hier::Index::coarsen(bbox.upper(),
                                           SAMRAI::hier::Index(2,2));

      for(int j=lower(1); j<=upper(1); ++j)
        for(int i=lower(0); i<=upper(0); ++i)
          {
            /* Fix vx */
            if(location_index==0)
              {
                SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),0,
                                               SAMRAI::pdat::SideIndex::Upper);
                SAMRAI::pdat::SideIndex center(coarse*2);
                if(center[1]>=gbox.lower(1) && center[1]<gbox.upper(1))
                  {
                    (*v)(coarse)=((*v_fine)(center) + (*v_fine)(center+jp))/2;
                  }
              }
            else if(location_index==1)
              {
                SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),0,
                                               SAMRAI::pdat::SideIndex::Lower);
                SAMRAI::pdat::SideIndex center(coarse*2);
                if(center[1]>=gbox.lower(1) && center[1]<gbox.upper(1))
                  {
                    (*v)(coarse)=((*v_fine)(center) + (*v_fine)(center+jp))/2;
                  }
              }
            /* Fix vy */
            else if(location_index==2)
              {
                SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),1,
                                               SAMRAI::pdat::SideIndex::Upper);
                SAMRAI::pdat::SideIndex center(coarse*2);
                if(center[0]>=gbox.lower(0) && center[0]<gbox.upper(0))
                  {
                    (*v)(coarse)=((*v_fine)(center) + (*v_fine)(center+ip))/2;
                  }
              }
            else if(location_index==3)
              {
                SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),1,
                                               SAMRAI::pdat::SideIndex::Lower);
                SAMRAI::pdat::SideIndex center(coarse*2);
                if(center[0]>=gbox.lower(0) && center[0]<gbox.upper(0))
                  {
                    (*v)(coarse)=((*v_fine)(center) + (*v_fine)(center+ip))/2;
                  }
              }
            else
              {
                abort();
              }
          }
    }
}
示例#26
0
    unsigned int
    add_arc_as_cubics(int max_recursion, Builder *B, float tol,
                      vec2 start_pt, vec2 end_pt, vec2 center,
                      float radius, float start_angle, float angle)
    {
      /* One way to approximate an arc with a cubic-bezier is as
       * follows (taken from GLyphy which is likely take its
       * computations from Cairo).
       *
       *   D = tan(angle / 4)
       *   p0 = start of arc
       *   p3 = end of arc
       *   vp = p3 - p1
       *   jp = J(vp)
       *   A = (1 - D^2) / 3
       *   B = (2 * D) / 3
       *   p1 = p0 + A * vp - B * jp
       *   p2 = p1 - A * vp - B * jp
       *
       * and the error between the arc and [p0, p1, p2, p3] is given by
       *
       *   error <= |vp| * |D|^5 / (54(1 + D^2))
       *
       * Now, |angle| < 2 * PI, implies |angle| / 4 < PI / 4 thus |D| < 1, giving
       *
       *   error <= |vp| * |D|^5 / 27
       *
       * thus we need:
       *
       *  |tan(|angle| / 4)|^5 < (27 * tol) / |vp|
       *
       * since, tan() is increasing function,
       *
       *   |angle| < 4 * pow(atan((27 * tol) / |vp|), 0.20f)
       *
       */

      vec2 vp(end_pt - start_pt);
      vec2 jp(-vp.y(), vp.x());
      float mag_vp(vp.magnitude());
      float goal, angle_max;

      if (mag_vp < tol)
        {
          B->line_to(end_pt);
          return 1;
        }

      /* half the tolerance for the cubic to quadratic and half
       * the tolerance for arc to cubic.
       */
      tol *= 0.5f;

      goal = t_min(1.0f, (27.0f * tol) / vp.magnitude());
      angle_max = t_min(FASTUIDRAW_PI, 4.0f * std::pow(fastuidraw::t_atan(goal), 0.20f));

      float angle_remaining(angle);
      float current_angle(start_angle);
      float angle_direction(t_sign(angle));
      float angle_advance(angle_max * angle_direction);
      vec2 last_pt(start_pt);
      unsigned int return_value(0);

      while (t_abs(angle_remaining) > angle_max)
        {
          float next_angle(current_angle + angle_advance);
          float cos_next_angle(t_cos(next_angle));
          float sin_next_angle(t_sin(next_angle));
          vec2 next_delta, next_pt;

          next_pt.x() = center.x() + cos_next_angle * radius;
          next_pt.y() = center.y() + sin_next_angle * radius;
          return_value += add_arc_as_single_cubic(max_recursion, B, tol, last_pt, next_pt, angle_advance);

          current_angle += angle_advance;
          angle_remaining -= angle_advance;
          last_pt = next_pt;
        }

      return_value += add_arc_as_single_cubic(max_recursion, B, tol, last_pt, end_pt, angle_remaining);
      return return_value;
    }
void
Elastic::V_Coarsen_Patch_Strategy::fix_boundary_elements_2D
(SAMRAI::pdat::SideData<double>& v,
 const SAMRAI::pdat::SideData<double>& v_fine,
 const boost::shared_ptr<SAMRAI::pdat::SideData<double> > dv_mixed,
 const std::vector<SAMRAI::hier::BoundaryBox> &boundaries) const
{
  /* FIXME: Why is this required?  Shouldn't the boundary points be
     ok?  They are partially interpolated from the coarse level, but
     that should not be a problem.  Unfortunately, it is a problem,
     because removing this routine generates nan's. */

  /* Fix up the boundary elements by iterating through the boundary
     boxes */

  /* We only care about edges, not corners, so we only iterate over
     edge boundary boxes. */

  SAMRAI::hier::Box gbox(v_fine.getGhostBox());
  SAMRAI::hier::Index ip(1,0), jp(0,1);
  for(size_t mm=0; mm<boundaries.size(); ++mm)
    {
      SAMRAI::hier::Box bbox=boundaries[mm].getBox();
      int location_index=boundaries[mm].getLocationIndex();

      SAMRAI::hier::Index
        lower=SAMRAI::hier::Index::coarsen(bbox.lower(),
                                           SAMRAI::hier::Index(2,2)),
        upper=SAMRAI::hier::Index::coarsen(bbox.upper(),
                                           SAMRAI::hier::Index(2,2));

      for(int j=lower(1); j<=upper(1); ++j)
        for(int i=lower(0); i<=upper(0); ++i)
          {
            /* Fix vx */
            if(location_index==0)
              {
                SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),0,
                                               SAMRAI::pdat::SideIndex::Upper);
                SAMRAI::pdat::SideIndex x(coarse*2);
                if(x[1]>=gbox.lower(1) && x[1]<gbox.upper(1))
                  {
                    v(coarse)=(v_fine(x) + v_fine(x+jp))/2;
                    if(have_faults() && !is_residual)
                      v(coarse)+=((*dv_mixed)(x,0) + (*dv_mixed)(x+jp,1))/2;
                  }
              }
            else if(location_index==1)
              {
                SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),0,
                                               SAMRAI::pdat::SideIndex::Lower);
                SAMRAI::pdat::SideIndex x(coarse*2);
                if(x[1]>=gbox.lower(1) && x[1]<gbox.upper(1))
                  {
                    v(coarse)=(v_fine(x) + v_fine(x+jp))/2;
                    if(have_faults() && !is_residual)
                      v(coarse)+=((*dv_mixed)(x,0) + (*dv_mixed)(x+jp,1))/2;
                  }
              }
            /* Fix vy */
            else if(location_index==2)
              {
                SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),1,
                                               SAMRAI::pdat::SideIndex::Upper);
                SAMRAI::pdat::SideIndex y(coarse*2);
                if(y[0]>=gbox.lower(0) && y[0]<gbox.upper(0))
                  {
                    v(coarse)=(v_fine(y) + v_fine(y+ip))/2;
                    if(have_faults() && !is_residual)
                      v(coarse)+=((*dv_mixed)(y,0) + (*dv_mixed)(y+ip,1))/2;
                  }
              }
            else if(location_index==3)
              {
                SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),1,
                                               SAMRAI::pdat::SideIndex::Lower);
                SAMRAI::pdat::SideIndex y(coarse*2);
                if(y[0]>=gbox.lower(0) && y[0]<gbox.upper(0))
                  {
                    v(coarse)=(v_fine(y) + v_fine(y+ip))/2;
                    if(have_faults() && !is_residual)
                      v(coarse)+=((*dv_mixed)(y,0) + (*dv_mixed)(y+ip,1))/2;
                  }
              }
            else
              {
                abort();
              }
          }
    }
}
示例#28
0
void LR35902::call(uint16 addr, uint16 next_pc) {
    push(next_pc); 
    jp(addr); 
}