Exemplo n.º 1
0
scalar der_Hr(double x, double y)
{
  double r = sqrt(x*x + y*y);
  double t = atan2(y,x);
  scalar a = cplx(0.0, M_PI/4 - k*r);
  scalar i = cplx(0.0,1.0);
  return 1/sqrt(M_PI) * exp(a) *
        ( (-i*k)*(Fn(sqrt(2*k*r)*sin(t/2 - M_PI/8)) + Fn(sqrt(2*k*r)*sin(t/2 + M_PI/8))) +
        (Fder(sqrt(2*k*r)*sin(t/2 - M_PI/8))*(sqrt(k)/sqrt(2*r)*sin(t/2 - M_PI/8)) +
         Fder(sqrt(2*k*r)*sin(t/2 + M_PI/8))*(sqrt(k)/sqrt(2*r)*sin(t/2 + M_PI/8))));
}
Exemplo n.º 2
0
int main(void)
{
    double x = 0.0;
    double result = 0.0;

    char c = '\0';

    printf(    "This program will calculate the value of: "
            "3x^5 + 2x^4 - 5x^3 - x^2 + 7x - 6\n");

    printf("Please enter the value of x: ");
    
    while (scanf("%Lf", &x) != 1) {
        fprintf(stderr, "Input invalid. Please try again.\n");

        while ((c = getchar()) != '\n' && c != EOF) continue;
    }
    while ((c = getchar()) != '\n' && c != EOF) continue;

    result = Fn(x);

    printf("= %g\n", result);

    getchar();
    return EXIT_SUCCESS;
}
Exemplo n.º 3
0
Arquivo: print.cpp Projeto: csll/llvm
void
print(Printer& p, Type const* t)
{
  struct Fn
  {
    Fn(Printer& p)
      : p(p)
    { }

    void operator()(Void_type const* t) const { print(p, t); }
    void operator()(Half_type const* t) const { print(p, t); }
    void operator()(Float_type const* t) const { print(p, t); }
    void operator()(Double_type const* t) const { print(p, t); }
    void operator()(Integer_type const* t) const { print(p, t); }
    void operator()(Pointer_type const* t) const { print(p, t); }
    void operator()(Function_type const* t) const { print(p, t); }
    void operator()(Vector_type const* t) const { print(p, t); }
    void operator()(Array_type const* t) const { print(p, t); }
    void operator()(Struct_type const* t) const { print(p, t); }
    void operator()(Packed_type const* t) const { print(p, t); }
    void operator()(Opaque_type const* t) const { print(p, t); }
    void operator()(Label_type const* t) const { print(p, t); }
    void operator()(Token_type const* t) const { print(p, t); }

    Printer& p;
  };

  apply(t, Fn(p));
}
Exemplo n.º 4
0
  static void Fn(const InputVecType& x, OutputVecType& y)
  {
    y = x;

    for (size_t i = 0; i < x.n_elem; i++)
      y(i) = Fn(x(i));
  }
Exemplo n.º 5
0
Arquivo: print.cpp Projeto: csll/llvm
void
print(Printer& p, Expr const* e)
{
  struct Fn
  {
    Fn(Printer& p)
      : p(p)
    { }

    void operator()(Identifier_expr const* e) { print(p, e); }
    void operator()(Boolean_expr const* e) { print(p, e); }
    void operator()(Integer_expr const* e) { print(p, e); }
    void operator()(Float_expr const* e) { print(p, e); }
    void operator()(Null_expr const* e) { print(p, e); }
    void operator()(Vector_expr const* e) { print(p, e); }
    void operator()(Array_expr const* e) { print(p, e); }
    void operator()(Struct_expr const* e) { print(p, e); }
    void operator()(Zero_expr const* e) { print(p, e); }
    void operator()(Address_expr const* e) { print(p, e); }
    void operator()(Undefined_expr const* e) { print(p, e); }

    Printer& p;
  };

  apply(e, Fn(p));
}
Exemplo n.º 6
0
        static void
        must_be_derived_class_member(Default const&)
        {
            // https://svn.boost.org/trac/boost/ticket/5803
            //typedef typename assertion<mpl::not_<is_same<Default,Fn> > >::failed test0;
# if !BOOST_WORKAROUND(__MWERKS__, <= 0x2407)
            typedef typename assertion<is_polymorphic<T> >::failed test1;
# endif 
            typedef typename assertion<is_member_function_pointer<Fn> >::failed test2;
            not_a_derived_class_member<Default>(Fn());
        }
Exemplo n.º 7
0
Prop const* 
simplify(Prop const* p)
{
  struct Fn
  {
    Prop const* operator()(Atom const* p) const { return simplify(p); }
    Prop const* operator()(And const* p) const { return simplify(p); }
    Prop const* operator()(Or const* p) const { return simplify(p); }
  };
  
  return apply(p, Fn());
}
Exemplo n.º 8
0
void overFace::getRightState(void)
{
  // Note: fptOffset must be set by Solver during overset setup
  for (int i=0; i<nFptsL; i++) {
    for (int k=0; k<nFields; k++) {
      UR(i,k) = OComm->U_in(fptOffset+i,k);

      if (params->oversetMethod == 1)
        Fn(i,k) = OComm->U_in(fptOffset+i,nFields+k);
    }
  }
}
Exemplo n.º 9
0
void funranx(double(*Fn)(int,double*),double Fnmax,int ndim,double* xmax,double* x){
//returns a random vector x with weight function Fn.  Takes maximal values and number of dimensions as additional inputs

double q,qq;
int flag=0,i;

while(flag==0){
 q=Fnmax*ranx();
 for(i=0;i<ndim;i++){
     x[i]=xmax[i]*ranx();}
 qq=Fn(ndim,x);
 if(q<qq){
    flag=1;}}}
Exemplo n.º 10
0
int precision(Type const* t)
{
  struct Fn
  {
    // should never be called
    // FIXME: throw exceptions
    int operator()(Id_type const* t) { return 0; }
    int operator()(Function_type const* t) { return 0; }
    int operator()(Void_type const* t) { return 0; }
    int operator()(Context_type const* t) { return 0; }
    int operator()(Table_type const* t) { return 0; }
    int operator()(Flow_type const* t) { return 0; }
    int operator()(Key_type const* t) { return 0; }
    int operator()(Opaque_type const* t) { return 0; }
    int operator()(Varargs_type const* t) { return 0; }

    // Port types just end up being integer identifiers.
    int operator()(Port_type const* t) { return 32; }

    // dynamic type
    // FIXME: do this right
    int operator()(Block_type const* t) { return 0; }

    // static type
    int operator()(Boolean_type const* t) { return 8; }
    int operator()(Character_type const* t) { return 8; }
    int operator()(Integer_type const* t) { return t->precision(); }
    int operator()(Array_type const* t) { return t->size(); }
    int operator()(Reference_type const* t) { return precision(t->nonref()); }

    int operator()(Record_type const* t)
    {
      int n = 0;
      for (Decl* d : t->declaration()->fields())
        n += precision(d->type());
      return n;
    }

    // network specific types
    int operator()(Layout_type const* t)
    {
      int n = 0;
      for (Decl* d : t->declaration()->fields())
        n += precision(d->type());
      return n;
    }
  };

  return apply(t, Fn());
}
Exemplo n.º 11
0
void
llvm_stmt(Printer& p, Stmt const* s)
{
    struct Fn
    {
        Fn(Printer& p)
            : p(p)
        { }

        void operator()(Empty_stmt const* s) {
            llvm_stmt(p, s);
        }
        void operator()(Declaration_stmt const* s) {
            llvm_stmt(p, s);
        }
        void operator()(Expression_stmt const* s) {
            llvm_stmt(p, s);
        }
        void operator()(Assignment_stmt const* s) {
            llvm_stmt(p, s);
        }
        void operator()(If_then_stmt const* s) {
            llvm_stmt(p, s);
        }
        void operator()(If_else_stmt const* s) {
            llvm_stmt(p, s);
        }
        void operator()(While_stmt const* s) {
            llvm_stmt(p, s);
        }
        void operator()(Do_stmt const* s) {
            llvm_stmt(p, s);
        }
        void operator()(Exit_stmt const* s) {
            llvm_stmt(p, s);
        }
        void operator()(Return_stmt const* s) {
            llvm_stmt(p, s);
        }
        void operator()(Block_stmt const* s) {
            llvm_stmt(p, s);
        }

        Printer& p;
    };

    return apply(s, Fn(p));
}
Exemplo n.º 12
0
// -------------------------------------------------------------------------- //
//                              Constant length
//
// Determines if an object type has constant length.
bool has_constant_length(Type const* t)
{
  struct Fn
  {
    bool operator()(Id_type const* t) { return false; }
    bool operator()(Boolean_type const* t) { return true; }
    bool operator()(Character_type const* t) { return true; }
    bool operator()(Integer_type const* t) { return true; }
    bool operator()(Function_type const* t) { return false; }
    bool operator()(Block_type const* t) { return false; }
    bool operator()(Array_type const* t) { return true; }
    bool operator()(Reference_type const* t) { return true; }
    bool operator()(Port_type const* t) { return true; }


    bool operator()(Record_type const* t)
    {
      for (Decl* d : t->declaration()->fields())
        if (!has_constant_length(d->type()))
          return false;
      return true;
    }

    bool operator()(Void_type const* t) { return false; }
    bool operator()(Opaque_type const* t) { return false; }

    // network specific types
    bool operator()(Layout_type const* t)
    {
      for (Decl* d : t->declaration()->fields())
        if (!has_constant_length(d->type()))
          return false;
      return true;
    }


    // these should never be called
    bool operator()(Varargs_type const* t) { throw std::runtime_error("non-const length"); }
    bool operator()(Context_type const* t) { throw std::runtime_error("non-const length"); }
    bool operator()(Table_type const* t) { throw std::runtime_error("non-const length"); }
    bool operator()(Flow_type const* t) { throw std::runtime_error("non-const length"); }
    bool operator()(Key_type const* t) { throw std::runtime_error("non-const length"); }
  };

  return apply(t, Fn());
}
Exemplo n.º 13
0
void 
print(std::ostream& os, Prop const* p)
{
  struct Fn
  {
    Fn(std::ostream& os)
      : os(os)
    { }

    void operator()(Atom const* p) const { print(os, p); }
    void operator()(And const* p) const { print(os, p); }
    void operator()(Or const* p) const { print(os, p); }

    std::ostream& os;
  };
  
  apply(p, Fn(os));
}
Exemplo n.º 14
0
Arquivo: print.cpp Projeto: csll/llvm
void
print(Printer& p, Decl const* d)
{
  struct Fn
  {
    Fn(Printer& p)
      : p(p)
    { }

    void operator()(Global_decl const* d) { return print(p, d); }
    void operator()(Constant_decl const* d) { return print(p, d); }
    void operator()(Parameter_decl const* d) { return print(p, d); }
    void operator()(Define_decl const* d) { return print(p, d); }
    void operator()(Declare_decl const* d) { return print(p, d); }
    void operator()(Type_decl const* d) { return print(p, d); }

    Printer& p;
  };

  apply(d, Fn(p));
}
Exemplo n.º 15
0
Arquivo: print.cpp Projeto: csll/llvm
// Print an instruction.
void 
print(Printer& p, Instr const* i)
{
  struct Fn
  {
    Fn(Printer& p)
      : p(p)
    { }

    void operator()(Return_instr const* i) { return print(p, i); }
    void operator()(Branch_instr const* i) { return print(p, i); }
    void operator()(Jump_instr const* i) { return print(p, i); }
    void operator()(Switch_instr const* i) { return print(p, i); }
    void operator()(Invoke_instr const* i) { return print(p, i); }
    void operator()(Unreachable_instr const* i) { return print(p, i); }
    void operator()(Add_instr const* i) { return print(p, i); }
    void operator()(Sub_instr const* i) { return print(p, i); }
    void operator()(Mul_instr const* i) { return print(p, i); }
    void operator()(Udiv_instr const* i) { return print(p, i); }
    void operator()(Sdiv_instr const* i) { return print(p, i); }
    void operator()(Urem_instr const* i) { return print(p, i); }
    void operator()(Srem_instr const* i) { return print(p, i); }
    void operator()(Shl_instr const* i) { return print(p, i); }
    void operator()(Lshr_instr const* i) { return print(p, i); }
    void operator()(Ashr_instr const* i) { return print(p, i); }
    void operator()(And_instr const* i) { return print(p, i); }
    void operator()(Or_instr const* i) { return print(p, i); }
    void operator()(Xor_instr const* i) { return print(p, i); }
    void operator()(Alloca_instr const* i) { return print(p, i); }
    void operator()(Load_instr const* i) { return print(p, i); }
    void operator()(Store_instr const* i) { return print(p, i); }
    void operator()(Icmp_instr const* i) { return print(p, i); }
    void operator()(Call_instr const* i) { return print(p, i); }

    Printer& p;
  };

  apply(i, Fn(p));
}
Exemplo n.º 16
0
template <void (*Fn)()> void WrapFnPtr() { Fn(); }
Exemplo n.º 17
0
                    ranges::begin(r) == ranges::end(r)
                )

            public:
                template<typename R>
                constexpr auto operator()(R &&r) const
                RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
                (
                    fn::impl_(r, detail::priority_tag<2>{})
                )

                template<typename T, typename Fn = fn>
                constexpr auto operator()(std::reference_wrapper<T> ref) const
                RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
                (
                    Fn()(ref.get())
                )

                template<typename T, typename Fn = fn>
                constexpr auto operator()(ranges::reference_wrapper<T> ref) const
                RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
                (
                    Fn()(ref.get())
                )
            };
        }
        /// \endcond

        /// \ingroup group-core
        /// \return true if and only if range contains no elements.
        RANGES_INLINE_VARIABLE(_empty_::fn, empty)
Exemplo n.º 18
0
bool Law2_L6Geom_HertzPhys_DMT::go(const shared_ptr<CGeom>& cg, const shared_ptr<CPhys>& cp, const shared_ptr<Contact>& C){
	const L6Geom& g(cg->cast<L6Geom>()); HertzPhys& ph(cp->cast<HertzPhys>());
	Real& Fn(ph.force[0]); Eigen::Map<Vector2r> Ft(&ph.force[1]);
	ph.torque=Vector3r::Zero();
	const Real& dt(scene->dt);
	const Real& velN(g.vel[0]);
	const Vector2r velT(g.vel[1],g.vel[2]);

	// current normal stiffness
	Real kn0=ph.K*sqrt(ph.R);
	// TODO: this not really valid for Schwarz?
	ph.kn=(3/2.)*kn0*sqrt(-g.uN);
	// normal elastic and adhesion forces
	// those are only split in the DMT model, Fna is zero for Schwarz or Hertz
	Real Fne, Fna=0.;
	if(ph.alpha==0.){
		if(g.uN>0){
			// TODO: track nonzero energy of broken contact with adhesion
			// TODO: take residual shear force in account?
			// if(unlikely(scene->trackEnergy)) scene->energy->add(normalElasticEnergy(ph.kn0,0),"dmtComeGo",dmtIx,EnergyTracker::IsIncrement|EnergyTracker::ZeroDontCreate);
			return false;
		}
		// pure Hertz/DMT
		Fne=-kn0*pow_i_2(-g.uN,3); // elastic force
		// DMT adhesion ("sticking") force
		// See Dejaguin1975 ("Effect of Contact Deformation on the Adhesion of Particles"), eq (44)
		// Derjaguin has Fs=2πRφ(ε), which is derived for sticky sphere (with surface energy)
		// in contact with a rigid plane (without surface energy); therefore the value here is twice that of Derjaguin
		// See also Chiara's thesis, pg 39 eq (3.19).
		Fna=4*M_PI*ph.R*ph.gamma;
	} else {
		// Schwarz model

		// new contacts with adhesion add energy to the system, which is then taken away again
		if(unlikely(scene->trackEnergy) && C->isFresh(scene)){
			// TODO: scene->energy->add(???,"dmtComeGo",dmtIx,EnergyTracker::IsIncrement)
		}

		const Real& gamma(ph.gamma); const Real& R(ph.R); const Real& alpha(ph.alpha); const Real& K(ph.K);
		Real delta=-g.uN; // inverse convention
		Real Pc=-6*M_PI*R*gamma/(pow(alpha,2)+3);
		Real xi=sqrt(((2*M_PI*gamma)/(3*K))*(1-3/(pow(alpha,2)+3)));
		Real deltaMin=-3*cbrt(R*pow(xi,4)); // -3R(-1/3)*ξ^(-4/3)
		// broken contact
		if(delta<deltaMin){
			// TODO: track energy
			return false;
		}

		// solution brackets
		// XXX: a is for sure also greater than delta(a) for Hertz model, with delta>0
		// this should be combined with aMin which gives the function apex
		Real aMin=pow_i_3(xi*R,2); // (ξR)^(2/3)
		Real a0=pow_i_3(4,2)*aMin; // (4ξR)^(2/3)=4^(2/3) (ξR)^(2/3)
		Real aLo=(delta<0?aMin:a0);
		Real aHi=aMin+sqrt(R*(delta-deltaMin));
		auto delta_diff_ddiff=[&](const Real& a){
			Real aInvSqrt=1/sqrt(a);
			return boost::math::make_tuple(
				pow(a,2)/R-4*xi*sqrt(a)-delta, // subtract delta as we need f(x)=0
				2*a/R-2*xi*aInvSqrt,
				2/R+xi*pow(aInvSqrt,3)
			);
		};
		// use a0 (defined as  δ(a0)=0) as intial guess for new contacts, since they are likely close to the equilibrium condition
		// use the previous value for old contacts
		Real aInit=(C->isFresh(scene)?a0:ph.contRad); 
		boost::uintmax_t iter=100;
		Real a=boost::math::tools::halley_iterate(delta_diff_ddiff,aInit,aLo,aHi,digits,iter);
		// increment call and iteration count
		#ifdef WOO_SCHWARZ_COUNTERS
			nCallsIters.add(0,1);
			nCallsIters.add(1,iter);
		#endif

		ph.contRad=a;
		Real Pne=pow(sqrt(pow(a,3)*(K/R))-alpha*sqrt(-Pc),2)+Pc;
		Fne=-Pne; // inverse convention
		if(isnan(Pne)){
			cerr<<"R="<<R<<", K="<<K<<", xi="<<xi<<", alpha="<<alpha<<endl;
			cerr<<"delta="<<delta<<", deltaMin="<<deltaMin<<", aMin="<<aMin<<", aLo="<<aLo<<", aHi="<<aHi<<", a="<<a<<", iter="<<iter<<", Pne="<<Pne<<"; \n\n";
			abort();
		}
	}

	// viscous coefficient, both for normal and tangential force
	// Antypov2012 (10)
	// XXX: max(-g.uN,0.) for adhesive models so that eta is not NaN
	Real eta=(ph.alpha_sqrtMK>0?ph.alpha_sqrtMK*pow_1_4(max(-g.uN,0.)):0.);
	// cerr<<"eta="<<eta<<", -g.uN="<<-g.uN<<"; ";
	Real Fnv=eta*velN; // viscous force
	// DMT ONLY (for now at least):
	if(ph.alpha==0. && noAttraction && Fne+Fnv>0) Fnv=-Fne; // avoid viscosity which would induce attraction with DMT
	// total normal force
	Fn=Fne+Fna+Fnv; 
	// normal viscous dissipation
	if(unlikely(scene->trackEnergy)) scene->energy->add(Fnv*velN*dt,"viscN",viscNIx,EnergyTracker::IsIncrement|EnergyTracker::ZeroDontCreate);

	// shear sense; zero shear stiffness in tension (XXX: should be different with adhesion)
	ph.kt=ph.kt0*sqrt(g.uN<0?-g.uN:0);
	Ft+=dt*ph.kt*velT;
	// sliding: take adhesion in account
	Real maxFt=std::abs(min(0.,Fn)*ph.tanPhi);
	if(Ft.squaredNorm()>pow(maxFt,2)){
		// sliding
		Real FtNorm=Ft.norm();
		Real ratio=maxFt/FtNorm;
		// sliding dissipation
		if(unlikely(scene->trackEnergy)) scene->energy->add((.5*(FtNorm-maxFt)+maxFt)*(FtNorm-maxFt)/ph.kt,"plast",plastIx,EnergyTracker::IsIncrement | EnergyTracker::ZeroDontCreate);
		// cerr<<"uN="<<g.uN<<",Fn="<<Fn<<",|Ft|="<<Ft.norm()<<",maxFt="<<maxFt<<",ratio="<<ratio<<",Ft2="<<(Ft*ratio).transpose()<<endl;
		Ft*=ratio;
	} else {
		// viscous tangent force (only applied in the absence of sliding)
		Ft+=eta*velT;
		if(unlikely(scene->trackEnergy)) scene->energy->add(eta*velT.dot(velT)*dt,"viscT",viscTIx,EnergyTracker::IsIncrement|EnergyTracker::ZeroDontCreate);
	}
	assert(!isnan(Fn)); assert(!isnan(Ft[0]) && !isnan(Ft[1]));
	// elastic potential energy
	if(unlikely(scene->trackEnergy)){
		// XXX: this is incorrect with adhesion
		// skip if in tension, since we would get NaN from delta^(2/5)
		if(g.uN<0) scene->energy->add(normalElasticEnergy(kn0,-g.uN)+0.5*Ft.squaredNorm()/ph.kt,"elast",elastPotIx,EnergyTracker::IsResettable);
	}
	LOG_DEBUG("uN="<<g.uN<<", Fn="<<Fn<<"; duT/dt="<<velT[0]<<","<<velT[1]<<", Ft="<<Ft[0]<<","<<Ft[1]);
	return true;
}
Exemplo n.º 19
0
void Ship::output(){
	ofstream file;
	file.open("Report.txt");
	file << "[table]" << endl;

	cout << fixed << setprecision(2) << "Length: \t\t\t\t" << v.Lpp << " m" << endl;
	file << fixed << setprecision(2) << "[tr][td]Length: \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t[/td][td]" << v.Lpp << " m[/td][/tr]" << endl;
	cout << "Beam: \t\t\t\t\t" << v.B << " m" << endl;
	file << "[tr][td]Beam: [/td][td]" << v.B << " m[/td][/tr]" << endl;
	cout << "Draft: \t\t\t\t\t" << v.D << " m" << endl;
	file << "[tr][td]Draft: [/td][td]" << v.D << " m[/td][/tr]" << endl;
	cout << "Freeboard: \t\t\t\t" << v.fB << " m" << endl;
	file << "[tr][td]Freeboard: [/td][td]" << v.fB << " m[/td][/tr]" << endl;
	cout << setprecision(3) << "Block Coefficient: \t\t\t" << Cb() << endl;
	file << setprecision(3) << "[tr][td]Block Coefficient: [/td][td]" << Cb() << "[/td][/tr]" << endl;
	cout << setprecision(0) << "Displacement: \t\t\t\t" << Vol() << " t" << endl;
	file << setprecision(0) << "[tr][td]Displacement: [/td][td]" << Vol() << " t[/td][/tr]" << endl;
	cout << "Lightship: \t\t\t\t" << Wh() + Wwo() + Wm() + We() + Wspus() + Bunker() << " t" << endl;
	file << "[tr][td]Lightship: [/td][td]" << Lightship() << " t[/td][/tr]" << endl;

	cout << setprecision(1) << "\nMax Speed: \t\t\t\t" << v.Vk << " kn" << endl;
	file << setprecision(1) << "\n[tr][td]Max Speed: [/td][td]" << v.Vk << " kn[/td][/tr]" << endl;
	cout << "Cruise Speed: \t\t\t\t" << v.Vc << " kn / " << v.Range << " nm" << endl;
	file << "[tr][td]Cruise Speed: [/td][td]" << v.Vc << " kn / " << v.Range << " nm[/td][/tr]" << endl;

	cout << "Engine: \t\t\t\t";
	file << "[tr][td]Engine: [/td][td]";
	switch(e.Gear){
		case Direct:
            cout << "Direct ";
            file << "Direct ";
            break;
		case Geared:
		    cout << "Geared ";
		    file << "Geared ";
		    break;
		case Turbo_Electric:
		    cout << "Turbo-Electric ";
		    file << "Turbo-Electric ";
            break;
		default:
            cout << "Unknown";
            file << "Unknown";
	}
	switch(e.Eng){
		case Diesel2stk:
		    cout << "Two Stroke Diesel" << endl;
		    file << "Two Stroke Diesel";
		    break;
		case Diesel4stk:
		    cout << "Four Stroke Diesel" << endl;
		    file << "Four Stroke Diesel" << endl;
		    break;
		case QuadExp:
		    cout << "Quadruple Expansion Reciprocating Engine" << endl;
		    file << "Quadruple Expansion Reciprocating Engine";
		    break;
		case TripExp:
		    cout << "Triple Expansion Reciprocating Engine" << endl;
		    file << "Triple Expansion Reciprocating Engine";
		    break;
		case SimExp:
		    cout << "Simple Reciprocating Engine" << endl;
		    file << "Simple Reciprocating Engine";
		    break;
		case SteamTur:
		    cout << "Steam Turbine" << endl;
		    file << "Steam Turbine";
		    break;
		default:
            cout << endl;
	}
	file << "[/td][/tr]" << endl;

	cout << setprecision(0) << "Power Delivered: \t\t\t" << Pd(v.Vk) << " hp" << endl;
	file << setprecision(0) << "[tr][td]Power Delivered: [/td][td]" << Pd(v.Vk) << " hp[/td][/tr]" << endl;
	cout << setprecision(2) << "Total Efficiency: \t\t\t" << NUt()*100 << "%" << endl;
	file << setprecision(2) << "[tr][td]Total Efficiency: [/td][td]" << NUt()*100 << "%[/td][/tr]" << endl;
	cout << setprecision(3) << "Froude Number: \t\t\t\t" << Fn() << endl;
	file << setprecision(3) << "[tr][td]Froude Number: [/td][td]" << Fn()  << "[/td][/tr]" << endl;
	cout << setprecision(0) << "Bunker Size: \t\t\t\t" << Bunker() << " t" << endl;
	file << setprecision(0) << "[tr][td]Bunker Size: [/td][td]" << Bunker() << " t[/td][/tr]" << endl;
	cout << "Service Allowance: \t\t\t" << e.SA << "%" << endl;
	file << "[tr][td]Service Allowance: [/td][td]" << e.SA << "%[/td][/tr]" << endl;

	cout << setprecision(2);
	file << setprecision(2);
	cout << "Length of Superstructure: \t\t" << v.Lspus << " m" << endl;
	file << "[tr][td]Length of Superstructure: [/td][td]" << v.Lspus << " m[/td][/tr]" << endl;

	cout << "Aftbody Shape: \t\t\t\t";
	file << "[tr][td]Aftbody Shape: [/td][td]";
	switch(e.Faa){
		case V:
		    cout << "V" << endl;
		    file << "V";
		    break;
		case U:
		    cout << "U" << endl;
		    file << "U";
		    break;
		case N:
		    cout << "N" << endl;
		    file << "N";
		    break;
		default:
		    cout << "N" << endl;
		    file << "N";
	}
	file << "[/td][/tr]";

	cout << "\nLongitudinal Center of Buoyancy: \t" << lcb() << "%" << endl;
	file << "\n[tr][td]Longitudinal Center of Buoyancy: [/td][td]" << lcb() << "% / " << lcb()*v.Lpp << " m from midpoint[/td][/tr]" << endl;
	cout << "Longitudinal Center of Gravity: \t" << lcg() << "%" << endl;
	file << "[tr][td]Longitudinal Center of Gravity: [/td][td]" << lcg() << "% / " << lcg()*v.Lpp << " m from midpoint[/td][/tr]" << endl;

	cout << "Vertical Center of Gravity: \t\t" << KGh() << " m" << endl;
	file << "[tr][td]Vertical Center of Gravity: [/td][td]" << KGh() << " m[/td][/tr]" << endl;
	cout << "Metacentric Height: \t\t\t" << GM() << " m" << endl;
	file << "[tr][td]Metacentric Height: [/td][td]" << GM() << " m[/td][/tr]" << endl;
	cout << "Roll Period: \t\t\t\t" << TR() << " s" << endl;
	file << "[tr][td]Roll Period: [/td][td]" << TR() << " s[/td][/tr]" << endl;

	cout << "\nBow Entrance Angle: \t\t\t" << iE() << " deg" << endl;
	file << "\n[tr][td]Bow Entrance Angle: [/td][td]" << iE() << " deg[/td][/tr]" << endl;
	cout << "Length of Engine Room: \t\t\t" << Lcm() << " m" << endl;
	file << "[tr][td]Length of Engine Room: [/td][td]" << Lcm() << " m[/td][/tr]" << endl;

	cout << setprecision(0) << "\nMain Belt: \t\t\t\t" << arm.mb_Ttop << " / " << arm.mb_Tbot << " mm at " << arm.b_deg << " degrees, " << arm.b_L << " m long with " << arm.b_H << " m above and " << arm.b_Db << " m below water" << endl;
	file << setprecision(0) << "\n[tr][td]Main Belt: [/td][td]" << arm.mb_Ttop << " / " << arm.mb_Tbot << " mm, " << arm.b_L << " m long with " << arm.b_H << " m above and " << arm.b_Db << " m below water[/td][/tr]" << endl;

	cout << "End Belt: \t\t\t\t" << arm.eb_Ttop << " / " << arm.eb_Tbot << " mm" << endl;
	file << "[tr][td]End Belt: [/td][td]" << arm.eb_Ttop << " / " << arm.eb_Tbot << " mm[/td][/tr]" << endl;

	cout << "Upper Belt: \t\t\t\t" << arm.ub_Ttop << " / " << arm.ub_Tbot << " mm, " << arm.b_uL << " m long" << endl;
	file << "[tr][td]Upper Belt: [/td][td]" << arm.ub_Ttop << " / " << arm.ub_Tbot << " mm, " << arm.b_uL << " m long[/td][/tr]" << endl;

	cout << "Main Deck: \t\t\t\t" << arm.md_T << " mm covering " << arm.md_P << "% / " << arm.md_P * v.Lpp << " m of deck" << endl;
	file << "[tr][td]Main Deck: [/td][td]" << arm.md_T << " m covering " << arm.md_P << "% / " << arm.md_P * v.Lpp << " m of deck[/td][/tr]" << endl;
	cout << "Weather Deck: \t\t\t\t" << arm.wd_T << " mm covering " << arm.wd_P << "% / " << arm.wd_P * v.Lpp << " m of deck" << endl;
	file << "[tr][td]Weather Deck: [/td][td]" << arm.wd_T << " m covering " << arm.wd_P << "% / " << arm.wd_P * v.Lpp << " m of deck[/td][/tr]" << endl;
	cout << "Splinter Deck: \t\t\t\t" << arm.sd_T << " mm covering " << arm.sd_P << "% / " << arm.sd_P * v.Lpp << " m of deck" << endl;
	file << "[tr][td]Splinter Deck: [/td][td]" << arm.sd_T << " m covering " << arm.sd_P << "% / " << arm.sd_P * v.Lpp << " m of deck[/td][/tr]" << endl;
	cout << "Ends Deck: \t\t\t\t" << arm.ed_T << " mm" << endl;
	file << "[tr][td]Ends Deck: [/td][td]" << arm.ed_T << " mm[/td][/tr]" << endl;

	cout << "Bulkhead: \t\t\t\t" << arm.blk_T << " mm in " << arm.blk_Lct << "x" << arm.blk_D << " m layers, " << arm.blk_L << " m long, " << arm.blk_H << " m tall" << endl;
	file << "[tr][td]Bulkhead: [/td][td]" << arm.blk_T << " mm in " << arm.blk_Lct << "x" << arm.blk_D << " m layers, " << arm.blk_L << " m long, " << arm.blk_H << " m tall[/td][/tr]" << endl;

	file << "[/table]" << endl;

    file.close();
}
Exemplo n.º 20
0
float Ship::lcb(){
	return (8.8 - 38.9 * Fn());
}
Exemplo n.º 21
0
 explicit PaintProperty(T fallbackValue)
     : value(fallbackValue) {
     values.emplace(ClassID::Fallback, Fn(fallbackValue));
 }
Exemplo n.º 22
0
void overFace::rusanovFlux(void)
{
  /* Different flux function to utilize interpolated corrected flux, but still
   * apply upwinding */
  if (params->oversetMethod == 1) {
    for (int fpt=0; fpt<nFptsL; fpt++) {
      // Get primitive variables
      double rhoL = UL(fpt,0);     double rhoR = UR(fpt,0);
      double uL = UL(fpt,1)/rhoL;  double uR = UR(fpt,1)/rhoR;
      double vL = UL(fpt,2)/rhoL;  double vR = UR(fpt,2)/rhoR;

      double wL, pL, vnL=0.;
      double wR, pR, vnR=0.;
      double vgn=0.;

      // Calculate pressure
      if (params->nDims==2) {
        pL = (params->gamma-1.0)*(UL(fpt,3)-0.5*rhoL*(uL*uL+vL*vL));
        pR = (params->gamma-1.0)*(UR(fpt,3)-0.5*rhoR*(uR*uR+vR*vR));
      }
      else {
        wL = UL(fpt,3)/rhoL;   wR = UR(fpt,3)/rhoR;
        pL = (params->gamma-1.0)*(UL(fpt,4)-0.5*rhoL*(uL*uL+vL*vL+wL*wL));
        pR = (params->gamma-1.0)*(UR(fpt,4)-0.5*rhoR*(uR*uR+vR*vR+wR*wR));
      }

      // Get normal fluxes, normal velocities
      for (int dim=0; dim<params->nDims; dim++) {
        vnL += normL(fpt,dim)*UL(fpt,dim+1)/rhoL;
        vnR += normL(fpt,dim)*UR(fpt,dim+1)/rhoR;
        if (params->motion)
          vgn += normL(fpt,dim)*Vg(fpt,dim);
      }

      // Get maximum eigenvalue for diffusion coefficient
      double csqL = max(params->gamma*pL/rhoL,0.0);
      double csqR = max(params->gamma*pR/rhoR,0.0);
      double eigL = std::fabs(vnL) + sqrt(csqL);
      double eigR = std::fabs(vnR) + sqrt(csqR);
      double eig  = max(eigL,eigR);

      /* Calculate Rusanov flux using corrected normal flux from donor grid
       * (copied to Fn) */

      // Outflow - use internal state
      if (vnL - vgn > 0) {
        inviscidFlux(UL[fpt],tempFL,params);
        double tempFnL[5] = {0,0,0,0,0};
        for (int k=0; k<nFields; k++)
          for (int dim=0; dim<nDims; dim++)
            tempFnL[k] += tempFL[dim][k]*normL(fpt,dim);

        for (int k=0; k<params->nFields; k++) {
          Fn(fpt,k) = tempFnL[k] - 0.5*eig*(UR(fpt,k)-UL(fpt,k));
        }
      }

      // Inflow - use external state [previously copied into Fn]
      else {
        for (int k=0; k<params->nFields; k++) {
          Fn(fpt,k) = Fn(fpt,k) - 0.5*eig*(UR(fpt,k)-UL(fpt,k));
        }
      }

      // Store wave speed for calculation of allowable dt
      if (params->motion) {
        eigL = std::fabs(vnL-vgn) + sqrt(csqL);
        eigR = std::fabs(vnR-vgn) + sqrt(csqR);
      }
      *waveSp[fpt] = max(eigL,eigR);
    }
  }

  // For other overset methods, just call normal Rusanov flux
  else {
    face::rusanovFlux();
  }
}
Exemplo n.º 23
0
bool Law2_L6Geom_PelletPhys_Pellet::go(const shared_ptr<CGeom>& cg, const shared_ptr<CPhys>& cp, const shared_ptr<Contact>& C){
	const L6Geom& g(cg->cast<L6Geom>()); PelletPhys& ph(cp->cast<PelletPhys>());
	Real& Fn(ph.force[0]); Eigen::Map<Vector2r> Ft(&ph.force[1]);
	if(C->isFresh(scene)) C->data=make_shared<PelletCData>();
	Real& uNPl(C->data->cast<PelletCData>().uNPl);
	Real& uN0(C->data->cast<PelletCData>().uN0);
	assert(C->data && dynamic_pointer_cast<PelletCData>(C->data));
	if(iniEqlb && C->isFresh(scene)) uN0=g.uN;
	Real uN=g.uN-uN0; // normal displacement, taking iniEqlb in account
	// break contact
	if(uN>0) return false;

	Real d0=g.lens.sum();
	if(ph.normPlastCoeff<=0) uNPl=0.;
	const Vector2r velT(g.vel[1],g.vel[2]);

	ph.torque=Vector3r::Zero();
	
	// normal force
	Fn=ph.kn*(uN-uNPl); // trial force
	if(ph.normPlastCoeff>0){ // normal plasticity activated
		if(Fn>0){
			if(ph.ka<=0) Fn=0;
			else{ Fn=min(Fn,adhesionForce(uN,uNPl,ph.ka)); assert(Fn>0); }
		} else {
			Real Fy=yieldForce(uN,d0,ph.kn,ph.normPlastCoeff);
			// normal plastic slip
			if(Fn<Fy){
				Real uNPl0=uNPl; // needed when tracking energy
				uNPl=uN-Fy/ph.kn;
				if(unlikely(scene->trackEnergy)){
					// backwards trapezoid integration
					Real Fy0=Fy+yieldForceDerivative(uN,d0,ph.kn,ph.normPlastCoeff)*(uNPl0-uNPl);
					Real dissip=.5*abs(Fy0+Fy)*abs(uNPl-uNPl0);
					scene->energy->add(dissip,plastSplit?"normPlast":"plast",plastSplit?normPlastIx:plastIx,EnergyTracker::IsIncrement | EnergyTracker::ZeroDontCreate);
					tryAddDissipState(DISSIP_NORM_PLAST,dissip,C);
				}
				if(thinRate>0 && thinRelRMin<1.){
					const Vector2r bendVel(g.angVel[1],g.angVel[2]);
					Real dRad_0=thinRate*(uNPl0-uNPl)*(scene->dt*bendVel.norm());
					for(const Particle* p:{C->leakPA(),C->leakPB()}){
						if(!dynamic_cast<Sphere*>(p->shape.get())) continue;
						Real dRad=dRad_0; // copy to be modified
						auto& s=p->shape->cast<Sphere>();
						//Real r0=(C->geom->cast<L6Geom>().lens[p.get()==C->pA.get()?0:1]);
						Real r0=cbrt(3*s.nodes[0]->getData<DemData>().mass/(4*M_PI*p->material->density));
						Real rMin=r0*thinRelRMin;
						if(thinRefRad>0.) rMin*=pow(r0/thinRefRad,thinMinExp);
						if(s.radius<=rMin) continue;
						// 0..1 norm between rMin and r0
						Real r01=(s.radius-rMin)/(r0-rMin);
						if(thinExp>0) dRad*=pow(r01,thinExp);
						if(thinRefRad>0.) dRad*=pow(r0/thinRefRad,thinRateExp);
						boost::mutex::scoped_lock lock(s.nodes[0]->getData<DemData>().lock);
						// cerr<<"#"<<p->id<<": radius "<<s.radius<<" -> "<<s.radius-dRad<<endl;
						s.radius=max(rMin,s.radius-dRad*r01);
						s.color=CompUtils::clamped(1-(s.radius-rMin)/(r0-rMin),0,1);
					}
				}
				Fn=Fy;
			}
			// in the elastic regime, Fn is trial force already
		}
	}
	/* add fake confinement */
	if(confSigma!=0) Fn-=g.contA*confSigma*(confRefRad>0.?pow(g.contA/(M_PI*pow(confRefRad,2)),confExp):1.);

	// shear force
	Ft+=scene->dt*ph.kt*velT;
	Real maxFt=abs(Fn)*ph.tanPhi; assert(maxFt>=0);
	// shear plastic slip
	if(Ft.squaredNorm()>pow(maxFt,2)){
		Real FtNorm=Ft.norm();
		Real ratio=maxFt/FtNorm;
		if(unlikely(scene->trackEnergy)){
			Real dissip=(.5*(FtNorm-maxFt)+maxFt)*(FtNorm-maxFt)/ph.kt;
			scene->energy->add(dissip,"plast",plastIx,EnergyTracker::IsIncrement | EnergyTracker::ZeroDontCreate);
			tryAddDissipState(DISSIP_SHEAR_PLAST,dissip,C);
		}
		Ft*=ratio;
	}
	assert(!isnan(Fn)); assert(!isnan(Ft[0]) && !isnan(Ft[1]));
	// elastic potential energy
	if(unlikely(scene->trackEnergy)) scene->energy->add(0.5*(pow(Fn,2)/ph.kn+Ft.squaredNorm()/ph.kt),"elast",elastPotIx,EnergyTracker::IsResettable);
	return true;
}
Exemplo n.º 24
0
void CPrecipitator::EvalLosses(MStream & Prod)
{
  double T = Prod.T;
  double TA = AmbientTemp();
  /// Heat Loss to internal cooling, eg Barriquands
  if (!m_bCoolerOn && iCoolMethod==COOL_Hx) {
    m_dLiquorTout = Prod.T;
    m_dLMTD = 0.0;
    m_dCoolWaterTout = CoolIn.T;
  }
  m_dIntCoolRate=0.0;
  if (m_bCoolerOn && iCoolType==COOL_INTERNAL && bCoolIn && iCoolMethod == COOL_Hx ) {
    MStreamI TubeIn;
    MStreamI TubeOut;
    MStreamI CoolOut;
    if (m_bByVolFlow) 
      m_dCoolFlow = m_dIntCoolVolFlow*Prod.Density();
    else
      m_dIntCoolVolFlow = m_dCoolFlow/Prod.Density();

    TubeIn.SetM(Prod, MP_All, m_dCoolFlow);
    TubeOut.SetF(TubeIn, MP_All, 1.0); 
    CoolOut.SetF(CoolIn, MP_All, 1.0);

    if (TubeIn.MassFlow()>0 && CoolIn.MassFlow()>0) {

	m_dUA=m_dCoolArea*m_dCoolHTC;
	CCoolerFn Fn(m_dUA, TubeIn, CoolIn, TubeOut, CoolOut);

	double TubeOutT;
	double MxTbOutT=TubeIn.T;// No Transfer
	double MnTbOutT=CoolIn.T+0.001;
 	double qShell=-CoolIn.totHz()+CoolOut.totHz(MP_All, TubeIn.T);
 	double qTube= -TubeIn.totHz(MP_All, CoolIn.T)+TubeIn.totHz();
      
	if (qShell<qTube) // Limited By Shell - Tube TOut Limited
	  MnTbOutT=MxTbOutT - (qShell)/GTZ(qTube)*(MxTbOutT-MnTbOutT);

      switch (Fn.FindRoot(0, MnTbOutT, MxTbOutT)) {
      case RF_OK:       TubeOutT = Fn.Result();   break;
      case RF_LoLimit:  TubeOutT = MnTbOutT;      break;
      case RF_HiLimit:  TubeOutT = MxTbOutT;      break;
      default: 
	Log.Message(MMsg_Error, "TubeOutT not found - RootFinder:%s", Fn.ResultString(Fn.Error())); 
	TubeOutT=Fn.Result();
	break;
      }
      TubeOut.T = TubeOutT;
      m_dIntCoolRate = TubeIn.totHz() - TubeOut.totHz();
      m_dCoolWaterTout = CoolOut.T;
      m_dCoolWaterTin = CoolIn.T;
      m_dCoolWaterFlow = CoolIn.Mass();
      m_dCoolWaterFlowVol = CoolIn.Volume();
      m_dLiquorTout = TubeOut.T;
      m_dLMTD=fabs(LMTD(TubeIn.T, TubeOut.T, CoolIn.T, CoolOut.T));
    }



  }
    
  if (iCoolType==COOL_INTERNAL && iCoolMethod == COOL_dQ ) {
    m_dIntCoolRate = m_dCooldQ;
  }
  






  switch (iCoolType) {
  case COOL_NONE:
    m_dCoolRate = 0;
    break;
  case COOL_EXTERNAL:
    m_dCoolRate = m_dExtCoolRate;    // kW
    break;
  case COOL_INTERNAL:
  /// Heat Loss to internal cooling, eg draft tube coolers
    m_dCoolRate = m_dIntCoolRate;
    break;
  }
  

  /// Evaporation Rate
  switch (iEvapMethod) {
  case EVAP_dT:
    m_dEvapRate = m_dEvapRateK*(T-TA);       // kg/s
    x[3] = m_dEvapRate;
    break;
  case EVAP_FIXED:
    x[3] = m_dEvapRate;
    break;
  case EVAP_NONE:
    x[3] = 0;
    m_dEvapRate = 0.0;
    
  }  

  /// Evaporative Heat Loss ... need to fix this up using stream enthalpies
  m_dEvapThermalLoss = 2300*m_dEvapRate;   // kW...


  /// Heat Loss to ambient cooling
  m_dEnvironmentLoss = 0.0;
  switch (iThermalLossMethod) {
  case THL_Ambient:
    m_dEnvironmentLoss = (T-TA)*dThermalLossAmbient;  //kW
    break;
  case THL_FixedHeatFlow:
    m_dEnvironmentLoss = dThermalLossRqd;
    break;
  }
  
  m_dTotThermalLoss = m_dEnvironmentLoss + m_dEvapThermalLoss + m_dCoolRate;
  
}
Exemplo n.º 25
0
BOOL CTokenFileInfo::CheckForInclude()
  {
  if (bUseIncludes && (pParser->sTokenLine[0]==sIncludeChars[0]))
    {
    CString FileName = pParser->sTokenLine;
    if (pParser->sTokenLine.Find((const char*)sIncludeChars)==0)
      {
      FileName = FileName.Mid(sIncludeChars.GetLength(), 1024);
      FileName = FileName.Right(FileName.GetLength() - FileName.SpanIncluding(" \t").GetLength());
      while (FileName.GetLength()>0 && (FileName[FileName.GetLength()-1]==' ' || FileName[FileName.GetLength()-1]=='\t'))
        FileName = FileName.Left(FileName.GetLength()-1);
      BOOL Failed = TRUE;
      DWORD ErrNo = 1;//file not specified
      if (FileName.GetLength()>0)
        {
        if (FileName[0]=='\'' || FileName[0]=='"')
          FileName = FileName.Right(FileName.GetLength() - 1);
        int len = FileName.GetLength();
        if (len>0)
          {
          if (FileName[len-1]=='\'' || FileName[len-1] == '"')
            FileName = FileName.Left(len-1);
          len = FileName.GetLength();
          if (len>0)
            {
            iFileIndex++;
            if (iFileIndex<TP_MaxIncludeFiles)
              {
              Strng Fn, FnFull;
              Fn.FnDrivePath((char*)(const char*)FileName);
              if (Fn()==NULL)
                {// No Path Use Previous
                Fn.FnDrivePath((char*)(const char*)FileNames[iFileIndex-1]);
                Fn+=(char*)(const char*)FileName;
//                FileName=Fn();
                }
              else
                Fn=(char*)(const char*)FileName;

              // CNM
              if ((Fn[0]=='~') || (Fn[0]=='.')) // relative filename ?
                { // yes - prepend current folder (defined by previously openned file - NOT O/S
                Strng T;
                T.FnDrivePath((LPTSTR)(LPCTSTR)AllFileNames[iIncFileCnt-1]);
                T+=Fn;
                Fn=T;
                }

              FnFull.FnSearchExpand(Fn(), bFnPlaces);

              Fn.FnContract();
              FileName=Fn();

              FileNames[iFileIndex] = Fn();
              pParser->wLineNo--;
              FileLineNo[iFileIndex] = 0;

              Failed = !OpenFile(FnFull);
              //File[iFileIndex] = fopen(FnFull(), "rt");

              FnModifyTime(FnFull(), FileTimes[iFileIndex]);
              if (iIncFileCnt<TP_MaxTtlIncludeFiles)
                {
                AllFileNames[iIncFileCnt]=Fn();
                AllFileTimes[iIncFileCnt]=FileTimes[iFileIndex];
                iIncFileCnt++;
                }

              if (Failed)
                ErrNo = 2;//cannot open file
              }
            else
              ErrNo = 3;//too many nested includes
            }
          }
        }
      if (Failed && pParser->pFailFn)
        {
        (*(pParser->pFailFn))((char*)(const char*)FileName, ErrNo, pParser->pFailExtraPtr);
        }
      return TRUE;
      }
    }
  return FALSE;
  }
Exemplo n.º 26
0
template <void (&Fn)()> void WrapFnRef() { Fn(); }
Exemplo n.º 27
0
Expr* length(Type const* t)
{
  struct Fn
  {
    // should never be called
    Expr* operator()(Id_type const* t) { throw std::runtime_error("no length type"); }
    Expr* operator()(Function_type const* t) { throw std::runtime_error("no length type"); }
    Expr* operator()(Void_type const* t) { throw std::runtime_error("no length type"); }
    Expr* operator()(Opaque_type const* t) { throw std::runtime_error("no length type"); }
    Expr* operator()(Context_type const* t) { throw std::runtime_error("no length type"); }
    Expr* operator()(Table_type const* t) { throw std::runtime_error("no length type"); }
    Expr* operator()(Flow_type const* t) { throw std::runtime_error("no length type"); }
    Expr* operator()(Key_type const* t) { throw std::runtime_error("no length type"); }
    Expr* operator()(Varargs_type const* t) { throw std::runtime_error("no length type"); }

    // Ports just end up resolving into integer identifiers.
    Expr* operator()(Port_type const* t) { return make_int(4); }

    // dynamic type
    // FIXME: do this right
    Expr* operator()(Block_type const* t) { return zero(); }

    // static type
    Expr* operator()(Boolean_type const* t) { return one(); }
    Expr* operator()(Character_type const* t) { return one(); }

    Expr* operator()(Integer_type const* t)
    {
      double p = t->precision();
      double w = 8;
      double b = std::ceil(p / w);
      return make_int(b);
    }

    Expr* operator()(Array_type const* t)
    {
      double p = t->size();
      double w = 8;
      double b = std::ceil(p / w);
      return make_int(b);
    }

    Expr* operator()(Reference_type const* t)
    {
      return length(t->ref());
    }

    Expr* operator()(Record_type const* t)
    {
      Evaluator eval;
      Expr* e = zero();
      for (Decl* d : t->declaration()->fields()) {
        Type const* t1 = d->type();

        // If member is constant, just add in the constant value
        if (has_constant_length(t1))
          e = add(e, make_int(precision(t1)));

        // Otherwise, we have to form a call to the function
        // that would compute this type.
        else
          // FIXME: Do this right!
          e = add(e, zero());
      }


      // Compute ceil(e / 8).
      Expr* b = make_int(8); // bits per byte
      Expr* r = div(sub(add(e, b), one()), b);

      // Try folding the result. If it works, good. If not,
      // just return the previously computed expression.
      //
      // TODO: Maximally reduce the expression so that we only
      // add the constant bits to the non-constant bits. Since
      // addition is associative and commutative, we can
      // partition the sequence of terms into constants and
      // non-constants, and then sum the constant parts.
      try {
        Value v = eval.eval(r);
        if (v.is_integer())
          return make_int(v.get_integer().gets());
        else
          throw std::runtime_error("failed to synth length");
      }
      catch(...) {
        return r;
      }
    }

    // network specific types
    Expr* operator()(Layout_type const* t)
    {
      Evaluator eval;
      Expr* e = zero();
      for (Decl* d : t->declaration()->fields()) {
        Type const* t1 = d->type();

        // If member is constant, just add in the constant value
        if (has_constant_length(t1))
          e = add(e, make_int(precision(t1)));

        // Otherwise, we have to form a call to the function
        // that would compute this type.
        else
          // FIXME: Do this right!
          e = add(e, zero());
      }


      // Compute ceil(e / 8).
      Expr* b = make_int(8); // bits per byte
      Expr* r = div(sub(add(e, b), one()), b);

      // Try folding the result. If it works, good. If not,
      // just return the previously computed expression.
      //
      // TODO: Maximally reduce the expression so that we only
      // add the constant bits to the non-constant bits. Since
      // addition is associative and commutative, we can
      // partition the sequence of terms into constants and
      // non-constants, and then sum the constant parts.
      try {
        Value v = eval.eval(r);
        if (v.is_integer())
          return make_int(v.get_integer().gets());
        else
          throw std::runtime_error("failed to synth length");
      }
      catch(...) {
        return r;
      }
    }
  };

  return apply(t, Fn());
}
Exemplo n.º 28
0
 void Fn(const arma::Cube<eT>& x, arma::Cube<eT>& y)
 {
   y = x;
   for (size_t s = 0; s < x.n_slices; s++)
     Fn(x.slice(s), y.slice(s));
 }
Exemplo n.º 29
0
 void operator=(const T& v) { values.emplace(ClassID::Default, Fn(v)); }
Exemplo n.º 30
0
 void Forward(const InputType& input, OutputType& output)
 {
   Fn(input, output);
 }