Exemplo n.º 1
0
int main()
{
        colossal::job_generator gen1(
		0.002616272, 5.009914, 2.174681, 3.394791,
		2.532164, 4.070759, 6.570099, 0.9067149, 1.843567);
        gen1.seed(time(NULL));
        colossal::job_generator gen2(
		0.004299325, 2.562229, 1.038189, 2.600581,
		1.716938, 4.388895, 5.534811, 1.609197, 1.604422);
        gen2.seed(time(NULL) + 1);

	colossal::job j1 = gen1();
        colossal::job j2 = gen2();

	colossal::job_tracker jt(10000, 6000);

	colossal::pool &mod  = jt.add_pool("modeling", 1000, 1000, 1, 500, 5000, colossal::pool::SCHED_FAIR);
	colossal::pool &prod = jt.add_pool("prod",     1000, 1000, 1, 500, 5000, colossal::pool::SCHED_FAIR);

	mod.add_job(j1);
	prod.add_job(j2);

	jt.scale_minshares();
	jt.process();

	printf("------------ WORKLOAD ------------\n");
	printf("%s\n", mod.to_str().c_str());
	printf("%s\n", prod.to_str().c_str());
	printf("----------------------------------\n");

        return 0;
}
jstring JNICALL ScriptMethodsChatNamespace::chatPackOutOfBandToken(JNIEnv * env, jobject self, jlong source, jstring target, jint position)
{
	UNREF(env);
	UNREF(self);
	UNREF(source);
	UNREF(target);
	UNREF(position);

	JavaString result("JavaLibrary::chatPackOutOfBandToken - FAILED Token archive not implemented");
	return result.getReturnValue();

#if 0
	JavaStringParam jt(target);
	Unicode::String t;
	if(! JavaLibrary::convert(jt, t))
		return 0;

	if(! source)
		return 0;

	Token * token = 0;
	if(!JavaLibrary::getObject(source, token))
		return 0;

	Archive::ByteStream bs;
	Archive::put(bs, std::string(token->getObjectTemplateName()));
	Archive::put(bs, *token);

	OutOfBandPackager::pack(bs, gs_Object, position, t);

	JavaString result(t);
	return result.getReturnValue();
#endif
}
Exemplo n.º 3
0
        void start() {
            jsassert( !started_, "Thread already started" );
            // obtain own scope for execution
            // do it here, not in constructor, otherwise it creates an infinite recursion from ScopedThread
            _scope.reset( dynamic_cast< V8Scope * >( globalScriptEngine->newScope() ) );

            JSThread jt( *this );
            thread_.reset( new boost::thread( jt ) );
            started_ = true;
        }
Exemplo n.º 4
0
	std::string toString<stringmap>(const stringmap &v)
	{
		std::ostringstream oss;
		oss << "std::map( ";
		for (stringmap::const_iterator it = v.begin(); it != v.end(); ++it) {
			oss << it->first << " = " << it->second;

			stringmap::const_iterator jt(it);
			if (++jt != v.end()) oss << ", ";
		}
		oss << " )";
		return oss.str();
	}
Exemplo n.º 5
0
    void ProjectionExec::appendArray(BSONObjBuilder* bob, const BSONObj& array, bool nested) const {
        int skip  = nested ?  0 : _skip;
        int limit = nested ? -1 : _limit;

        if (skip < 0) {
            skip = max(0, skip + array.nFields());
        }

        int index = 0;
        BSONObjIterator it(array);
        while (it.more()) {
            BSONElement elt = it.next();

            if (skip) {
                skip--;
                continue;
            }

            if (limit != -1 && (limit-- == 0)) {
                break;
            }

            switch(elt.type()) {
            case Array: {
                BSONObjBuilder subBob;
                appendArray(&subBob, elt.embeddedObject(), true);
                bob->appendArray(bob->numStr(index++), subBob.obj());
                break;
            }
            case Object: {
                BSONObjBuilder subBob;
                BSONObjIterator jt(elt.embeddedObject());
                while (jt.more()) {
                    append(&subBob, jt.next());
                }
                bob->append(bob->numStr(index++), subBob.obj());
                break;
            }
            default:
                if (_include) {
                    bob->appendAs(elt, bob->numStr(index++));
                }
            }
        }
    }
Exemplo n.º 6
0
        std::vector<af::Points> from(lua_State* L, int index)
        {
            std::vector<af::Points> lists;

            for (luabind::iterator it(luabind::object(luabind::from_stack(L, index))), end;
                 it != end; ++it) {
                lists.push_back(af::Points());

                af::Points& list = lists.back();

                for (luabind::iterator jt(*it), end2; jt != end2; ++jt) {
                    list.push_back(b2Vec2(luabind::object_cast<float>((*jt)["x"]),
                                          luabind::object_cast<float>((*jt)["y"])));
                }
            }

            return lists;
        }
Exemplo n.º 7
0
    //b will be the value part of an array-typed BSONElement
    void Projection::appendArray( BSONObjBuilder& b , const BSONObj& a , bool nested) const {
        int skip  = nested ?  0 : _skip;
        int limit = nested ? -1 : _limit;

        if (skip < 0) {
            skip = max(0, skip + a.nFields());
        }

        int i=0;
        BSONObjIterator it(a);
        while (it.more()) {
            BSONElement e = it.next();

            if (skip) {
                skip--;
                continue;
            }

            if (limit != -1 && (limit-- == 0)) {
                break;
            }

            switch(e.type()) {
            case Array: {
                BSONObjBuilder subb;
                appendArray(subb , e.embeddedObject(), true);
                b.appendArray(b.numStr(i++), subb.obj());
                break;
            }
            case Object: {
                BSONObjBuilder subb;
                BSONObjIterator jt(e.embeddedObject());
                while (jt.more()) {
                    append(subb , jt.next());
                }
                b.append(b.numStr(i++), subb.obj());
                break;
            }
            default:
                if (_include)
                    b.appendAs(e, b.numStr(i++));
            }
        }
    }
Exemplo n.º 8
0
  // riding expandable...
  void
  riding_expandable_group
  ::linearise(uctbx::unit_cell const &unit_cell,
              sparse_matrix_type *jacobian_transpose)
  {
    site_parameter
      *pivot = dynamic_cast<site_parameter *>(this->argument(0));
    scalar_parameter
      *size = dynamic_cast<scalar_parameter *>(argument(1));
    const double size_value = size->value;
    const cart_t center = unit_cell.orthogonalize(pivot->value);
    if (!crd_initialised) {
      const cart_t original_pivot_crd = unit_cell.orthogonalize(pivot->value);
      for (int i=0; i < scatterers_.size(); i++)  {
        co_s[i] = unit_cell.orthogonalize(scatterers_[i]->site) -
          original_pivot_crd;
      }
      crd_initialised = true;
    }
    for (int i=0; i < scatterers_.size(); i++) {
      // update site of i-th atoms
      fx_s[i] = unit_cell.fractionalize(center + co_s[i]*size_value);

      // Derivatives
      if (!jacobian_transpose) continue;
      sparse_matrix_type &jt = *jacobian_transpose;
      std::size_t const j_s = this->index() + 3*i;

      // Riding
      for (int j=0; j<3; j++)
        jt.col(j_s + j) = jt.col(pivot->index() + j);

      // expansion/contraction
      if (size->is_variable())  {
        frac_t grad_f = unit_cell.fractionalize(co_s[i]);
        for (int j=0; j<3; j++)
          jt(size->index(), j_s + j) = grad_f[j];
      }
    }
  }
Exemplo n.º 9
0
SubsetGraph get_minimum_spanning_tree(const CliqueGraph& cg) {
  base::Vector<CliqueGraphEdge> mst;
  boost::kruskal_minimum_spanning_tree(cg, std::back_inserter(mst));
  SubsetGraph jt(boost::num_vertices(cg));
  SubsetGraphVertexName cm= boost::get(boost::vertex_name, jt);
  CliqueGraphConstVertexName cgm= boost::get(boost::vertex_name, cg);
  for (unsigned int i=0; i< boost::num_vertices(cg); ++i) {
    cm[i]= cgm[i];
  }
  for (unsigned int i=0; i< mst.size(); ++i) {
    boost::add_edge(boost::source(mst[i], cg),
                    boost::target(mst[i], cg), jt);
  }
  // find disjoint sets and connect them arbitrarily
  {
    typedef boost::vector_property_map<unsigned int> Index;
    typedef Index Parent;
    typedef boost::disjoint_sets<Index,Parent> UF;
    Index index;
    Parent parent;
    UF uf(index, parent);
    for (unsigned int i=0; i< boost::num_vertices(cg); ++i) {
      uf.make_set(i);
    }
    for (std::pair<SubsetGraphTraits::edge_iterator,
                   SubsetGraphTraits::edge_iterator> be= boost::edges(jt);
         be.first != be.second; ++be.first) {
      uf.union_set(boost::source(*be.first, jt),
                   boost::target(*be.first, jt));
    }
    for (unsigned int i=1; i< boost::num_vertices(cg); ++i) {
      if (uf.find_set(i) != uf.find_set(i-1)) {
        boost::add_edge(i,i-1, jt);
        uf.union_set(i,i-1);
      }
    }
  }
  return jt;
}
Exemplo n.º 10
0
int main()
{
        Tempo::job_generator gen1(0.01, 3, 3, 1, 1, 0.6, 0.6, 0.2, 0.2);
        gen1.seed(time(NULL));

	Tempo::job j1 = gen1();
	Tempo::job j2 = gen1();

	Tempo::job_tracker jt(1, 1);

	Tempo::pool &mod  = jt.add_pool("modeling", 10, 10, 1, 1, 1, Tempo::pool::SCHED_FAIR);

	mod.add_job(j1);
	mod.add_job(j2);

	jt.process();

	printf("------------ WORKLOAD ------------\n");
	printf("%s\n", mod.to_str().c_str());
	printf("----------------------------------\n");

        return 0;
}
Exemplo n.º 11
0
int
main (int argc,
      char **argv)
{
  PruneData pd;

  Data data;
  Types::Keys keys(data.allKeys());
  Types::Keys k;
 
  for (Types::Keys::const_iterator it(keys.begin()), et(keys.end()); it != et; ++it) {
    for (int i(Data::FLOW); i < Data::LASTTYPE; ++i) { // Walk through all data types
      Data::tTimeKeys a(data.timeKeys(*it, (Data::Type) i));
      Data::tTimeKeys::size_type n(pd(a));
      if (n) { // Something to prune
        size_t nDropped(0);
        for (Data::tTimeKeys::const_iterator jt(a.begin()), jet(a.end()); jt != jet; ++jt) {
          if (jt->second) {
            k.insert(jt->second);
            ++nDropped;
          }
        }
        std::cout << "Dropping " << nDropped << " rows of " << a.size() << " from " 
                  << data.source().key2name(*it) << " for type " << i << std::endl;
      } 
    }
    if (!data.nRows(*it)) {
	    std::cout << data.source().key2name(*it) << " is empty" << std::endl; 
    }
  }

  if (!k.empty()) {
    std::cout << "Dropped " << k.size() << " rows" << std::endl;
    data.dropRows(k);
    data.checkPoint();
  }
}
Exemplo n.º 12
0
 ///Randomly rotate sgrid_m
 void NonLocalECPComponent::randomize_grid(ParticleSet::ParticlePos_t& sphere, bool randomize)
 {
   if(randomize) {
     //const RealType twopi(6.28318530718);
     //RealType phi(twopi*Random()),psi(twopi*Random()),cth(Random()-0.5),
     RealType phi(TWOPI*((*myRNG)())), psi(TWOPI*((*myRNG)())), cth(((*myRNG)())-0.5);
     RealType sph(std::sin(phi)),cph(std::cos(phi)),
     sth(std::sqrt(1.0-cth*cth)),sps(std::sin(psi)),
     cps(std::cos(psi));
     TensorType rmat( cph*cth*cps-sph*sps, sph*cth*cps+cph*sps,-sth*cps,
         -cph*cth*sps-sph*cps,-sph*cth*sps+cph*cps, sth*sps,
         cph*sth,             sph*sth,             cth     );
     SpherGridType::iterator it(sgridxyz_m.begin());
     SpherGridType::iterator it_end(sgridxyz_m.end());
     SpherGridType::iterator jt(rrotsgrid_m.begin());
     int ic=0;
     while(it != it_end) {*jt = dot(rmat,*it); ++it; ++jt;}
     //copy the radomized grid to sphere
     std::copy(rrotsgrid_m.begin(), rrotsgrid_m.end(), sphere.begin());
   } else {
     //copy sphere to the radomized grid
     std::copy(sphere.begin(), sphere.end(), rrotsgrid_m.begin());
   }
 }
Exemplo n.º 13
0
void execALU(){
	switch(controle_alu.op_code){
		case  1: add();      break;
		case  2: addinc();   break;
		case  3: and();      break;
		case  4: andnota();  break;
		case  5: asl();      break;
		case  6: asr();      break;
		case  7: deca();     break;
		case  8: inca();     break;
		case  9: j();        break;
		case 10: jal(); 	 break;
		case 11: jf(); 	  	 break;
		case 12: jr(); 		 break;
		case 13: jt(); 		 break;
		case 14: lch(); 	 break;
		case 15: lcl(); 	 break;
		case 16: load();	 break;
		case 17: loadlit();	 break;
		case 18: lsl();		 break;
		case 19: lsr();		 break;
		case 20: nand();	 break;
		case 21: nor();		 break;
		case 22: ones();	 break;
		case 23: or();		 break;
		case 24: ornotb();	 break;
		case 25: passa();	 break;
		case 26: passnota(); break;
		case 27: store();	 break;
		case 28: sub();		 break;
		case 29: subdec();	 break;
		case 30: xnor();	 break;
		case 31: xor();		 break;
		case 32: zeros();	 break;
	}
}
Exemplo n.º 14
0
 void start() {
     jsassert(!_started, "Thread already started");
     JSThread jt(*this);
     _thread.reset(new boost::thread(jt));
     _started = true;
 }
Exemplo n.º 15
0
int main()
{
	Tempo::job j1;
        Tempo::job j2;
        Tempo::job j3;

	Tempo::task t1;
	t1.id = 1;
	t1.ctime = 0;
	t1.ptime = 2;
	t1.stime = -1;
	t1.ftime = -1;
	t1.type = Tempo::task::TASK_TYPE_MAP;


	Tempo::task t2;
	t2.id = 2;
	t2.ctime = 0;
	t2.ptime = 1;
	t2.stime = -1;
	t2.ftime = -1;
	t2.type = Tempo::task::TASK_TYPE_MAP;

	Tempo::task t3;
	t3.id = 3;
	t3.ctime = 0;
	t3.ptime = 1;
	t3.stime = -1;
	t3.ftime = -1;
	t3.type = Tempo::task::TASK_TYPE_MAP;

	Tempo::task t4;
	t4.id = 4;
	t4.ctime = 0;
	t4.ptime = 1;
	t4.stime = -1;
	t4.ftime = -1;
	t4.type = Tempo::task::TASK_TYPE_MAP;

	j1.id = 1;
	j1.fs_ctx_map.uid = 1;
	j1.ctime = 0;
	j1.tasks[Tempo::task::TASK_TYPE_MAP].push_back(t1);
	j1.tasks[Tempo::task::TASK_TYPE_MAP].push_back(t3);

	j2.id = 2;
	j2.fs_ctx_map.uid = 2;
	j2.ctime = 0;
	j2.tasks[Tempo::task::TASK_TYPE_MAP].push_back(t2);
	j2.tasks[Tempo::task::TASK_TYPE_MAP].push_back(t4);

	Tempo::job_tracker jt(2, 0);

	Tempo::pool &mod  = jt.add_pool("modeling", -1, -1, 1, 0, 0, Tempo::pool::SCHED_FAIR);

	mod.add_job(j1);
	mod.add_job(j2);

	jt.process();

	printf("------------ WORKLOAD ------------\n");
	printf("%s\n", mod.to_str().c_str());
	printf("----------------------------------\n");

        return 0;
}
jstring JNICALL ScriptMethodsChatNamespace::packOutOfBandProsePackage(JNIEnv * env, jobject self, jstring target, jint position, jobject stringId, jlong objActor, jlong objTarget, jlong objOther, jobject nameIdActor, jobject nameIdTarget, jobject nameIdOther, jstring nameActor, jstring nameTarget, jstring nameOther, jint digitInteger, jfloat digitFloat, jboolean complexGrammar)
{
	UNREF(env);
	UNREF(self);

	if (!stringId)
	{
		DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage attempt to pack prose package with null stringId"));
		return 0;
	}

	Unicode::String t;

	if (target)
	{
		JavaStringParam jt(target);
		if(! JavaLibrary::convert(jt, t))
		{
			DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert target string"));
			return 0;
		}
	}

	ProsePackage pp (complexGrammar);

	if (!ScriptConversion::convert (stringId, pp.stringId))
	{
		DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert StringId"));
		return 0;
	}

	pp.actor.id = NetworkId(objActor);
	if (objActor && pp.actor.id == NetworkId::cms_invalid)
	{
		DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert actor id"));
		return 0;
	}

	pp.target.id = NetworkId(objTarget);
	if (objTarget && pp.target.id == NetworkId::cms_invalid)
	{
		DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert target id"));
		return 0;
	}

	pp.other.id = NetworkId(objOther);
	if (objOther && pp.other.id == NetworkId::cms_invalid)
	{
		DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert other id"));
		return 0;
	}

	if (nameIdActor)
	{
		if (!ScriptConversion::convert(nameIdActor, pp.actor.stringId))
		{
			DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert actor id"));
			return 0;
		}
	}
	else if (nameActor)
	{
		const JavaStringParam jt(nameActor);
		if(! JavaLibrary::convert(jt, pp.actor.str))
		{
			DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert actor name"));
			return 0;
		}
	}

	if (nameIdTarget)
	{
		if (!ScriptConversion::convert(nameIdTarget, pp.target.stringId))
		{
			DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert target id"));
			return 0;
		}
	}
	else if (nameTarget)
	{
		const JavaStringParam jt(nameTarget);
		if(! JavaLibrary::convert(jt, pp.target.str))
		{
			DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert target name"));
			return 0;
		}
	}

	if (nameIdOther)
	{
		if (!ScriptConversion::convert(nameIdOther, pp.other.stringId))
		{
			DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert other id"));
			return 0;
		}
	}
	else if (nameOther)
	{
		const JavaStringParam jt(nameOther);
		if(! JavaLibrary::convert(jt, pp.other.str))
		{
			DEBUG_WARNING (true, ("JavaLibrary::packOutOfBandProsePackage unable to convert other name"));
			return 0;
		}
	}

	pp.digitInteger = digitInteger;
	pp.digitFloat   = digitFloat;

	Archive::ByteStream bs;
	Archive::put(bs, pp);

	OutOfBandPackager::pack(bs, OutOfBandPackager::OT_prosePackage, position, t);

	JavaString result(t);
	return result.getReturnValue();
}
Exemplo n.º 17
0
  // spherical rotatable expandable...
  void
  rotatable_expandable_group
  ::linearise(uctbx::unit_cell const &unit_cell,
              sparse_matrix_type *jacobian_transpose)
  {
    site_parameter
      *pivot = dynamic_cast<site_parameter *>(this->argument(0));
    scalar_parameter
      *size = dynamic_cast<scalar_parameter *>(argument(1));
    const scalar_parameter * angles[] = {
      dynamic_cast<scalar_parameter *>(argument(2)),
      dynamic_cast<scalar_parameter *>(argument(3)),
      dynamic_cast<scalar_parameter *>(argument(4))
    };
    const double
      a_v = angles[0]->value, c_a = cos(a_v), s_a = sin(a_v),
      b_v = angles[1]->value, c_b = cos(b_v), s_b = sin(b_v),
      g_v = angles[2]->value, c_g = cos(g_v), s_g = sin(g_v),
      size_value = size->value;
    // rotation matrix, for ref: http://en.wikipedia.org/wiki/Rotation_matrix
    const scitbx::mat3<double> rm(
      c_b*c_g, -c_b*s_g,  s_b,
      s_a*s_b*c_g + c_a*s_g, -s_a*s_b*s_g+c_a*c_g, -s_a*c_b,
      -c_a*s_b*c_g + s_a*s_g, c_a*s_b*s_g + s_a*c_g, c_a*c_b
    );
    // derivative of the rotation matrix by angle
    const scitbx::mat3<double> rmd[3] = {
      scitbx::mat3<double>(
        0,                      0,                      0,
        c_a*s_b*c_g - s_a*s_g, -c_a*s_b*s_g - s_a*c_g, -c_a*c_b,
        s_a*s_b*c_g + c_a*s_g, -s_a*s_b*s_g + c_a*c_g, -s_a*c_b
      ),
      scitbx::mat3<double>(
        -c_g*s_b,     s_g*s_b,      c_b,
        s_a*c_g*c_b, -s_a*s_g*c_b,  s_a*s_b,
        -c_a*c_g*c_b, c_a*s_g*c_b, -c_a*s_b
      ),
      scitbx::mat3<double>(
        -c_b*s_g,               -c_b*c_g,               0,
        -s_a*s_b*s_g + c_a*c_g, -s_a*s_b*c_g - c_a*s_g, 0,
         c_a*s_b*s_g + s_a*c_g,  c_a*s_b*c_g - s_a*s_g, 0
      )
    };
    if (!crd_initialised) {
      const cart_t original_pivot_crd = unit_cell.orthogonalize(pivot->value);
      cart_t rotation_center = original_pivot_crd;
      for (int i=0; i < scatterers_.size(); i++)  {
        co_s[i] = unit_cell.orthogonalize(scatterers_[i]->site);
        rotation_center += co_s[i];
      }
      rotation_center = rotation_center/(scatterers_.size()+1);
      for (int i=0; i < scatterers_.size(); i++)
        co_s[i] = co_s[i] - rotation_center;
      this->shift_to_pivot = original_pivot_crd-rotation_center;
      crd_initialised = true;
    }
    const cart_t new_pivot_crd = unit_cell.orthogonalize(pivot->value);
    const cart_t shift = new_pivot_crd - size_value*shift_to_pivot*rm;
    // expansion/contraction happens from/to the center
    for (int i=0; i < scatterers_.size(); i++) {
      // update site of i-th atoms
      fx_s[i] = unit_cell.fractionalize(size_value*co_s[i]*rm + shift);

      // Derivatives
      if (!jacobian_transpose) continue;
      sparse_matrix_type &jt = *jacobian_transpose;
      std::size_t const j_s = this->index() + 3*i;

      // Riding
      for (int j=0; j<3; j++)
        jt.col(j_s + j) = jt.col(pivot->index() + j);

      const cart_t grad_vec_ = co_s[i]-shift_to_pivot;
      // Rotating
      for (int j=0; j<3; j++ )  {
        if (!angles[j]->is_variable())  continue;
        frac_t grad_f = unit_cell.fractionalize(size_value*grad_vec_*rmd[j]);
        for (int k=0; k<3; k++)
          jt(angles[j]->index(), j_s + k) = grad_f[k];
      }

      // expansion/contraction
      if (size->is_variable())  {
        frac_t grad_f = unit_cell.fractionalize(grad_vec_*rm);
        for (int j=0; j<3; j++)
          jt(size->index(), j_s + j) = grad_f[j];
      }
    }
  }
Exemplo n.º 18
0
  // pivoted rotatable...
  void
  pivoted_rotatable_group
  ::linearise(uctbx::unit_cell const &unit_cell,
              sparse_matrix_type *jacobian_transpose)
  {
    site_parameter
      *pivot = dynamic_cast<site_parameter *>(this->argument(0)),
      *pivot_neighbour = dynamic_cast<site_parameter *>(this->argument(1));
    scalar_parameter
      *azimuth = dynamic_cast<scalar_parameter *>(this->argument(2)),
      *size = dynamic_cast<scalar_parameter *>(this->argument(3));

    const cart_t
      x_p = unit_cell.orthogonalize(pivot->value),
      x_pn = unit_cell.orthogonalize(pivot_neighbour->value),
      rv = (x_p - x_pn).normalize();
    const double
      angle = azimuth->value,
      size_value = size->value,
      ca = cos(angle),
      sa = sin(angle),
      t = 1.0-ca;
    // rotation matrix
    const scitbx::mat3<double> rm(
      t*rv[0]*rv[0] + ca,       t*rv[0]*rv[1] + sa*rv[2], t*rv[0]*rv[2] - sa*rv[1],
      t*rv[0]*rv[1] - sa*rv[2], t*rv[1]*rv[1] + ca,       t*rv[1]*rv[2] + sa*rv[0],
      t*rv[0]*rv[2] + sa*rv[1], t*rv[2]*rv[1] - sa*rv[0], t*rv[2]*rv[2] + ca
    );
    // derivative of the rotation matrix by angle
    const scitbx::mat3<double> rmd(
      sa*rv[0]*rv[0] - sa,       sa*rv[0]*rv[1] + ca*rv[2], sa*rv[0]*rv[2] - ca*rv[1],
      sa*rv[0]*rv[1] - ca*rv[2], sa*rv[1]*rv[1] - sa,       sa*rv[1]*rv[2] + ca*rv[0],
      sa*rv[0]*rv[2] + ca*rv[1], sa*rv[1]*rv[2] - ca*rv[0], sa*rv[2]*rv[2] - sa
    );
    if (!crd_initialised) {
      const cart_t rot_center = unit_cell.orthogonalize(pivot->value);
      for (int i=0; i < scatterers_.size(); i++)
        co_s[i] = unit_cell.orthogonalize(scatterers_[i]->site) -
                  rot_center;
      crd_initialised = true;
    }
    // Loop over the scatterers
    for (int i=0; i < scatterers_.size(); i++) {
      // update site of i-th scatterers
      const cart_t p = co_s[i]*rm;
     fx_s[i] = unit_cell.fractionalize(size_value*p + x_p);

      // Derivatives
      if (!jacobian_transpose) continue;
      sparse_matrix_type &jt = *jacobian_transpose;
      std::size_t const j_s = this->index() + 3*i;

      // Riding
      for (int j=0; j<3; j++)
        jt.col(j_s + j) = jt.col(pivot->index() + j);

      // Rotating
      if (azimuth->is_variable()) {
        frac_t grad_f = unit_cell.fractionalize(size_value*co_s[i]*rmd);
        for (int j=0; j<3; j++)
          jt(azimuth->index(), j_s + j) = grad_f[j];
      }
      // stretching
      if (size->is_variable()) {
        frac_t grad_f = unit_cell.fractionalize(p);
        for (int j=0; j<3; j++)
          jt(size->index(), j_s + j) = grad_f[j];
      }
    }
  }
Exemplo n.º 19
0
void
RadialMap::Widget::paintExplodedLabels(QPainter &paint) const
{
    //we are a friend of RadialMap::Map

    LabelList list;
    list.setAutoDelete(true);
    Q3PtrListIterator<Label> it(list);
    unsigned int startLevel = 0;


    //1. Create list of labels  sorted in the order they will be rendered

    if (m_focus && m_focus->file() != m_tree) //separate behavior for selected vs unselected segments
    {
        //don't bother with files
        if (m_focus->file() && !m_focus->file()->isDirectory())
            return;

        //find the range of levels we will be potentially drawing labels for
        //startLevel is the level above whatever m_focus is in
        for (const Directory *p = (const Directory*)m_focus->file(); p != m_tree; ++startLevel)
            p = p->parent();

        //range=2 means 2 levels to draw labels for

        unsigned int a1, a2, minAngle;

        a1 = m_focus->start();
        a2 = m_focus->end();  //boundry angles
        minAngle = int(m_focus->length() * LABEL_MIN_ANGLE_FACTOR);


#define segment (*it)
#define ring (m_map.m_signature + i)

        //**** Levels should be on a scale starting with 0
        //**** range is a useless parameter
        //**** keep a topblock var which is the lowestLevel OR startLevel for identation purposes
        for (unsigned int i = startLevel; i <= m_map.m_visibleDepth; ++i)
            for (Iterator<Segment> it = ring->iterator(); it != ring->end(); ++it)
                if (segment->start() >= a1 && segment->end() <= a2)
                    if (segment->length() > minAngle)
                        list.inSort(new Label(segment, i));

#undef ring
#undef segment

    } else {

#define ring m_map.m_signature

        for (Iterator<Segment> it = ring->iterator(); it != ring->end(); ++it)
            if ((*it)->length() > 288)
                list.inSort(new Label((*it), 0));

#undef ring

    }

    //2. Check to see if any adjacent labels are too close together
    //   if so, remove the least significant labels

    it.toFirst();
    Q3PtrListIterator<Label> jt(it);
    ++jt;

    while (jt) //**** no need to check _it_ as jt will be NULL if _it_ was too
    {
        //this method is fairly efficient

        if ((*it)->tooClose((*jt)->a)) {
            if ((*it)->lvl > (*jt)->lvl) {
                list.remove(*it);
                it = jt;
            }
            else
                list.remove(*jt);
        }
        else
            ++it;

        jt = it;
        ++jt;
    }

    //used in next two steps
    bool varySizes;
    //**** should perhaps use doubles
    int  *sizes = new int [ m_map.m_visibleDepth + 1 ]; //**** make sizes an array of floats I think instead (or doubles)

    do
    {
        //3. Calculate font sizes

        {
            //determine current range of levels to draw for
            uint range = 0;

            for (it.toFirst(); it != 0; ++it)
            {
                uint lvl = (*it)->lvl;
                if (lvl > range)
                    range = lvl;

                //**** better way would just be to assign if nothing is range
            }

            range -= startLevel; //range 0 means 1 level of labels

            varySizes = Config::varyLabelFontSizes && (range != 0);

            if (varySizes)
            {
                //create an array of font sizes for various levels
                //will exceed normal font pitch automatically if necessary, but not minPitch
                //**** this needs to be checked lots

                //**** what if this is negative (min size gtr than default size)
                uint step = (paint.font().pointSize() - Config::minFontPitch) / range;
                if (step == 0)
                    step = 1;

                for (uint x = range + startLevel, y = Config::minFontPitch; x >= startLevel; y += step, --x)
                    sizes[x] = y;
            }
        }

        //4. determine label co-ordinates

        int x1, y1, x2, y2, x3, tx, ty; //coords
        double sinra, cosra, ra;  //angles

        int cx = m_map.width()  / 2 + m_offset.x();  //centre relative to canvas
        int cy = m_map.height() / 2 + m_offset.y();

        int spacer, preSpacer = int(m_map.m_ringBreadth * 0.5) + m_map.m_innerRadius;
        int fullStrutLength = (m_map.width() - m_map.MAP_2MARGIN) / 2 + LABEL_MAP_SPACER; //full length of a strut from map center

        int prevLeftY  = 0;
        int prevRightY = height();

        bool rightSide;

        QFont font;

        for (it.toFirst(); it != 0; ++it)
        {
            //** bear in mind that text is drawn with QPoint param as BOTTOM left corner of text box
            QString qs = (*it)->segment->file()->name();
            if (varySizes)
                font.setPointSize(sizes[(*it)->lvl]);
            QFontMetrics fm(font);
            int fmh  = fm.height(); //used to ensure label texts don't overlap
            int fmhD4 = fmh / 4;

            fmh += LABEL_TEXT_VMARGIN;

            rightSide = ((*it)->a < 1440 || (*it)->a > 4320);

            ra = M_PI/2880 * (*it)->a; //convert to radians
            sincos(ra, &sinra, &cosra);


            spacer = preSpacer + m_map.m_ringBreadth * (*it)->lvl;

            x1 = cx + (int)(cosra * spacer);
            y1 = cy - (int)(sinra * spacer);
            y2 = y1 - (int)(sinra * (fullStrutLength - spacer));

            if (rightSide) { //righthand side, going upwards
                if (y2 > prevRightY /*- fmh*/) //then it is too low, needs to be drawn higher
                    y2 = prevRightY /*- fmh*/;
            }
            else //lefthand side, going downwards
                if (y2 < prevLeftY/* + fmh*/) //then we're too high, need to be drawn lower
                    y2 = prevLeftY /*+ fmh*/;

            x2 = x1 - int(double(y2 - y1) / tan(ra));
            ty = y2 + fmhD4;


            if (rightSide) {
                if (x2 > width() || ty < fmh || x2 < x1) {
                    //skip this strut
                    //**** don't duplicate this code
                    list.remove(*it); //will delete the label and set it to list.current() which _should_ be the next ptr
                    break;
                }

                prevRightY = ty - fmh - fmhD4; //must be after above's "continue"

                qs = fm.elidedText(qs, Qt::ElideMiddle, width() - x2);

                x3 = width() - fm.width(qs)
                     - LABEL_HMARGIN //outer margin
                     - LABEL_TEXT_HMARGIN //margin between strut and text
                     //- ((*it)->lvl - startLevel) * LABEL_HMARGIN; //indentation
                     ;
                if (x3 < x2) x3 = x2;
                tx = x3 + LABEL_TEXT_HMARGIN;

            } else {

                if (x2 < 0 || ty > height() || x2 > x1)
                {
                    //skip this strut
                    list.remove(*it); //will delete the label and set it to list.current() which _should_ be the next ptr
                    break;
                }

                prevLeftY = ty + fmh - fmhD4;

                qs = fm.elidedText(qs, Qt::ElideMiddle, x2);

                //**** needs a little tweaking:

                tx = fm.width(qs) + LABEL_HMARGIN/* + ((*it)->lvl - startLevel) * LABEL_HMARGIN*/;
                if (tx > x2) { //text is too long
                    tx = LABEL_HMARGIN + x2 - tx; //some text will be lost from sight
                    x3 = x2; //no text margin (right side of text here)
                } else {
                    x3 = tx + LABEL_TEXT_HMARGIN;
                    tx = LABEL_HMARGIN /*+ ((*it)->lvl - startLevel) * LABEL_HMARGIN*/;
                }
            }

            (*it)->x1 = x1;
            (*it)->y1 = y1;
            (*it)->x2 = x2;
            (*it)->y2 = y2;
            (*it)->x3 = x3;
            (*it)->tx = tx;
            (*it)->ty = ty;
            (*it)->qs = qs;
        }

        //if an element is deleted at this stage, we need to do this whole
        //iteration again, thus the following loop
        //**** in rare case that deleted label was last label in top level
        //     and last in labelList too, this will not work as expected (not critical)

    } while (it != 0);


    //5. Render labels

    paint.setPen(QPen(Qt::black, 1));

    for (it.toFirst(); it != 0; ++it)
    {
        if (varySizes) {
            //**** how much overhead in making new QFont each time?
            //     (implicate sharing remember)
            QFont font = paint.font();
            font.setPointSize(sizes[(*it)->lvl]);
            paint.setFont(font);
        }

        paint.drawEllipse((*it)->x1 - 3, (*it)->y1 - 3, 7, 7); //**** CPU intensive! better to use a pixmap
        paint.drawLine((*it)->x1,  (*it)->y1, (*it)->x2, (*it)->y2);
        paint.drawLine((*it)->x2, (*it)->y2, (*it)->x3, (*it)->y2);
        paint.drawText((*it)->tx, (*it)->ty, (*it)->qs);
    }

    delete [] sizes;
}
Exemplo n.º 20
0
 void start() {
     jsassert( !started_, "Thread already started" );
     JSThread jt( *this );
     thread_.reset( new boost::thread( jt ) );
     started_ = true;
 }
Exemplo n.º 21
0
std::uint16_t VirtualCPU::executeInstructionAtAddress(std::uint16_t address) {
  debugger_.pc_  = address; //HACK FOR NOW
    switch (memoryController_.readAtAddress(address)) {
        case 0:
            return address + halt();
        case 1:
            return address + set(memoryController_.readAtAddress(address + 1), memoryController_.readAtAddress(address + 2));
        case 2:
            return address + push(memoryController_.readAtAddress(address + 1));
        case 3:
            return address + pop(memoryController_.readAtAddress(address + 1));
        case 4:
            return address +
                    eq(memoryController_.readAtAddress(address + 1),
                       memoryController_.readAtAddress(address + 2),
                       memoryController_.readAtAddress(address + 3));
        case 5:
            return address + gt(memoryController_.readAtAddress(address + 1),
                                memoryController_.readAtAddress(address +2),
                                memoryController_.readAtAddress(address + 3));
        case 6:
            return jump(memoryController_.readAtAddress(address + 1), address);
        case 7:
            return jt(memoryController_.readAtAddress(address + 1),
                                memoryController_.readAtAddress(address + 2),
                                address);
        case 8:
            return jf(memoryController_.readAtAddress(address + 1),
                                memoryController_.readAtAddress(address + 2),
                                address);
        case 9:
            return address + add(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2),
                                 memoryController_.readAtAddress(address + 3));
        case 10:
            return address + mult(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2),
                                 memoryController_.readAtAddress(address + 3));
        case 11:
            return address + mod(memoryController_.readAtAddress(address + 1),
                                  memoryController_.readAtAddress(address + 2),
                                  memoryController_.readAtAddress(address + 3));
        case 12:
            return address + and_i(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2),
                                 memoryController_.readAtAddress(address + 3));
        case 13:
            return address + or_i(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2),
                                 memoryController_.readAtAddress(address + 3));
        case 14:
            return address + not_i(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2));
        case 15:
            return address + rmem(memoryController_.readAtAddress(address + 1),
                                 memoryController_.readAtAddress(address + 2));
        case 16:
            return address + wmem(memoryController_.readAtAddress(address + 1),
                                  memoryController_.readAtAddress(address + 2));
        case 17:
            return call(memoryController_.readAtAddress(address + 1), address);
        case 18:
            return ret();
        case 19:
            return address + out(memoryController_.readAtAddress(address + 1));
        case 21:
            return address + noop();
        case 20:
            return address + in(memoryController_.readAtAddress(address + 1));
        default:
            std::cout << "CPU ERROR illegal op code: " << memoryController_.readAtAddress(address) << std::endl;
            return address + 1;
    }
}
Exemplo n.º 22
0
bool IfcGeom::Kernel::convert(const IfcSchema::IfcFace* l, TopoDS_Shape& face) {
	IfcSchema::IfcFaceBound::list::ptr bounds = l->Bounds();

	Handle(Geom_Surface) face_surface;
	const bool is_face_surface = l->is(IfcSchema::Type::IfcFaceSurface);

	if (is_face_surface) {
		IfcSchema::IfcFaceSurface* fs = (IfcSchema::IfcFaceSurface*) l;
		fs->FaceSurface();
		// FIXME: Surfaces are interpreted as a TopoDS_Shape
		TopoDS_Shape surface_shape;
		if (!convert_shape(fs->FaceSurface(), surface_shape)) return false;

		// FIXME: Assert this obtaines the only face
		TopExp_Explorer exp(surface_shape, TopAbs_FACE);
		if (!exp.More()) return false;

		TopoDS_Face surface = TopoDS::Face(exp.Current());
		face_surface = BRep_Tool::Surface(surface);
	}
	
	const int num_bounds = bounds->size();
	int num_outer_bounds = 0;

	for (IfcSchema::IfcFaceBound::list::it it = bounds->begin(); it != bounds->end(); ++it) {
		IfcSchema::IfcFaceBound* bound = *it;
		if (bound->is(IfcSchema::Type::IfcFaceOuterBound)) num_outer_bounds ++;
	}

	// The number of outer bounds should be one according to the schema. Also Open Cascade
	// expects this, but it is not strictly checked. Regardless, if the number is greater,
	// the face will still be processed as long as there are no holes. A compound of faces
	// is returned in that case.
	if (num_bounds > 1 && num_outer_bounds > 1 && num_bounds != num_outer_bounds) {
		Logger::Message(Logger::LOG_ERROR, "Invalid configuration of boundaries for:", l->entity);
		return false;
	}

	TopoDS_Compound compound;
	BRep_Builder builder;
	if (num_outer_bounds > 1) {
		builder.MakeCompound(compound);
	}
	
	// The builder is initialized on the heap because of the various different moments
	// of initialization depending on the configuration of surfaces and boundaries.
	BRepBuilderAPI_MakeFace* mf = 0;
	
	bool success = false;
	int processed = 0;

	for (int process_interior = 0; process_interior <= 1; ++process_interior) {
		for (IfcSchema::IfcFaceBound::list::it it = bounds->begin(); it != bounds->end(); ++it) {
			IfcSchema::IfcFaceBound* bound = *it;
			IfcSchema::IfcLoop* loop = bound->Bound();
		
			bool same_sense = bound->Orientation();
			const bool is_interior = 
				!bound->is(IfcSchema::Type::IfcFaceOuterBound) &&
				(num_bounds > 1) &&
				(num_outer_bounds < num_bounds);

			// The exterior face boundary is processed first
			if (is_interior == !process_interior) continue;
		
			TopoDS_Wire wire;
			if (!convert_wire(loop, wire)) {
				Logger::Message(Logger::LOG_ERROR, "Failed to process face boundary loop", loop->entity);
				delete mf;
				return false;
			}

			/*
			The approach below does not result in a significant speed-up
			if (loop->is(IfcSchema::Type::IfcPolyLoop) && processed == 0 && face_surface.IsNull()) {
				IfcSchema::IfcPolyLoop* polyloop = (IfcSchema::IfcPolyLoop*) loop;
				IfcSchema::IfcCartesianPoint::list::ptr points = polyloop->Polygon();

				if (points->size() == 3) {
					// Help Open Cascade by finding the plane more efficiently
					IfcSchema::IfcCartesianPoint::list::it point_iterator = points->begin();
					gp_Pnt a, b, c;
					convert(*point_iterator++, a);
					convert(*point_iterator++, b);
					convert(*point_iterator++, c);
					const gp_XYZ ab = (b.XYZ() - a.XYZ());
					const gp_XYZ ac = (c.XYZ() - a.XYZ());
					const gp_Vec cross = ab.Crossed(ac);
					if (cross.SquareMagnitude() > ALMOST_ZERO) {
						const gp_Dir n = cross;
						face_surface = new Geom_Plane(a, n);
					}
				}
			}
			*/
		
			if (!same_sense) {
				wire.Reverse();
			}

			bool flattened_wire = false;

			if (!mf) {
			process_wire:

				if (face_surface.IsNull()) {
					mf = new BRepBuilderAPI_MakeFace(wire);
				} else {
					/// @todo check necessity of false here
					mf = new BRepBuilderAPI_MakeFace(face_surface, wire, false); 
				}				

				/* BRepBuilderAPI_FaceError er = mf->Error();
				if (er == BRepBuilderAPI_NotPlanar) {
					ShapeFix_ShapeTolerance FTol;
					FTol.SetTolerance(wire, getValue(GV_PRECISION), TopAbs_WIRE);
					delete mf;
					mf = new BRepBuilderAPI_MakeFace(wire);
				} */

				if (mf->IsDone()) {
					TopoDS_Face outer_face_bound = mf->Face();

					// In case of (non-planar) face surface, p-curves need to be computed.
					// For planar faces, Open Cascade generates p-curves on the fly.
					if (!face_surface.IsNull()) {
						TopExp_Explorer exp(outer_face_bound, TopAbs_EDGE);
						for (; exp.More(); exp.Next()) {
							const TopoDS_Edge& edge = TopoDS::Edge(exp.Current());
							ShapeFix_Edge fix_edge;
							fix_edge.FixAddPCurve(edge, outer_face_bound, false, getValue(GV_PRECISION));
						}
					}
					
					if (BRepCheck_Face(outer_face_bound).OrientationOfWires() == BRepCheck_BadOrientationOfSubshape) {
						wire.Reverse();
						same_sense = !same_sense;
						delete mf;
						if (face_surface.IsNull()) {
							mf = new BRepBuilderAPI_MakeFace(wire);
						} else {
							mf = new BRepBuilderAPI_MakeFace(face_surface, wire); 
						}
						ShapeFix_Face fix(mf->Face());
						fix.FixOrientation();
						fix.Perform();
						outer_face_bound = fix.Face();
					}

					// If the wires are reversed the face needs to be reversed as well in order
					// to maintain the counter-clock-wise ordering of the bounding wire's vertices.
					bool all_reversed = true;
					TopoDS_Iterator jt(outer_face_bound, false);
					for (; jt.More(); jt.Next()) {
						const TopoDS_Wire& w = TopoDS::Wire(jt.Value());
						if ((w.Orientation() != TopAbs_REVERSED) == same_sense) {
							all_reversed = false;
						}
					}

					if (all_reversed) {
						outer_face_bound.Reverse();
					}

					if (num_outer_bounds > 1) {
						builder.Add(compound, outer_face_bound);
						delete mf; mf = 0;
					} else if (num_bounds > 1) {
						// Reinitialize the builder to the outer face 
						// bound in order to add holes more robustly.
						delete mf;
						// TODO: What about the face_surface?
						mf = new BRepBuilderAPI_MakeFace(outer_face_bound);
					} else {
						face = outer_face_bound;
						success = true;
					}
				} else {
					const bool non_planar = mf->Error() == BRepBuilderAPI_NotPlanar;
					delete mf;
					if (!non_planar || flattened_wire || !flatten_wire(wire)) {
						Logger::Message(Logger::LOG_ERROR, "Failed to process face boundary", bound->entity);
						return false;
					} else {
						Logger::Message(Logger::LOG_ERROR, "Flattening face boundary", bound->entity);
						flattened_wire = true;
						goto process_wire;
					}
				}

			} else {
				mf->Add(wire);
			}
			processed ++;
		}
	}

	if (!success) {
		success = processed == num_bounds;
		if (success) {
			if (num_outer_bounds > 1) {
				face = compound;
			} else {
				success = success && mf->IsDone();
				if (success) {
					face = mf->Face();
				}
			}
		}
	}

	if (success) {
		ShapeFix_ShapeTolerance FTol;
		FTol.SetTolerance(face, getValue(GV_PRECISION), TopAbs_FACE);
	}

	delete mf;
	return success;
}