/** \brief Get the floating point output argument of an atomic operation */ double getAtomicInputReal(int k) const{ return algorithm().at(k).arg.d;}
static void trap_dispatch(struct trapframe *tf) { char c; int ret=0; switch (tf->tf_trapno) { case T_PGFLT: //page fault if ((ret = pgfault_handler(tf)) != 0) { print_trapframe(tf); if (current == NULL) { panic("handle pgfault failed. ret=%d\n", ret); } else { if (trap_in_kernel(tf)) { panic("handle pgfault failed in kernel mode. ret=%d\n", ret); } cprintf("killed by kernel.\n"); panic("handle user mode pgfault failed. ret=%d\n", ret); do_exit(-E_KILLED); } } break; case T_SYSCALL: syscall(); break; case IRQ_OFFSET + IRQ_TIMER: #if 0 LAB3 : If some page replacement algorithm(such as CLOCK PRA) need tick to change the priority of pages, then you can add code here. #endif /* LAB1 2013011365 : STEP 3 */ /* handle the timer interrupt */ /* (1) After a timer interrupt, you should record this event using a global variable (increase it), such as ticks in kern/driver/clock.c * (2) Every TICK_NUM cycle, you can print some info using a funciton, such as print_ticks(). * (3) Too Simple? Yes, I think so! */ /* LAB5 YOUR CODE */ /* you should upate you lab1 code (just add ONE or TWO lines of code): * Every TICK_NUM cycle, you should set current process's current->need_resched = 1 */ /* LAB6 YOUR CODE */ /* you should upate you lab5 code * IMPORTANT FUNCTIONS: * sched_class_proc_tick */ /* LAB7 YOUR CODE */ /* you should upate you lab6 code * IMPORTANT FUNCTIONS: * run_timer_list */ ticks++; run_timer_list(); sched_class_proc_tick(current); break; case IRQ_OFFSET + IRQ_COM1: case IRQ_OFFSET + IRQ_KBD: // There are user level shell in LAB8, so we need change COM/KBD interrupt processing. c = cons_getc(); { extern void dev_stdin_write(char c); dev_stdin_write(c); } break; //LAB1 CHALLENGE 1 : YOUR CODE you should modify below codes. case T_SWITCH_TOU: if(tf->tf_cs != USER_CS) { user_stack = *tf; user_stack.tf_cs = USER_CS; user_stack.tf_ds = USER_DS; user_stack.tf_ss = USER_DS; user_stack.tf_es = USER_DS; user_stack.tf_esp = (uint32_t)tf + sizeof(struct trapframe) - 8; user_stack.tf_eflags |= FL_IOPL_MASK; *((uint32_t *)tf - 1) = (uint32_t)&user_stack; } break; case T_SWITCH_TOK: if(tf->tf_cs != KERNEL_CS) { tf->tf_cs = KERNEL_CS; tf->tf_ds = KERNEL_DS; tf->tf_es = KERNEL_DS; tf->tf_eflags &= ~FL_IOPL_MASK; struct trapframe* k = (struct trapframe*)(tf->tf_esp - (sizeof(struct trapframe) - 8)); memmove(k, tf, sizeof(struct trapframe) -8); *((uint32_t *)tf - 1) = (uint32_t)k; } break; case IRQ_OFFSET + IRQ_IDE1: case IRQ_OFFSET + IRQ_IDE2: /* do nothing */ break; default: print_trapframe(tf); if (current != NULL) { cprintf("unhandled trap.\n"); do_exit(-E_KILLED); } // in kernel, it must be a mistake panic("unexpected trap in kernel.\n"); } }
bool EFX::saveXML(QXmlStreamWriter *doc) { Q_ASSERT(doc != NULL); /* Function tag */ doc->writeStartElement(KXMLQLCFunction); /* Common attributes */ saveXMLCommon(doc); /* Fixtures */ QListIterator <EFXFixture*> it(m_fixtures); while (it.hasNext() == true) it.next()->saveXML(doc); /* Propagation mode */ doc->writeTextElement(KXMLQLCEFXPropagationMode, propagationModeToString(m_propagationMode)); /* Speeds */ saveXMLSpeed(doc); /* Direction */ saveXMLDirection(doc); /* Run order */ saveXMLRunOrder(doc); /* Algorithm */ doc->writeTextElement(KXMLQLCEFXAlgorithm, algorithmToString(algorithm())); /* Width */ doc->writeTextElement(KXMLQLCEFXWidth, QString::number(width())); /* Height */ doc->writeTextElement(KXMLQLCEFXHeight, QString::number(height())); /* Rotation */ doc->writeTextElement(KXMLQLCEFXRotation, QString::number(rotation())); /* StartOffset */ doc->writeTextElement(KXMLQLCEFXStartOffset, QString::number(startOffset())); /* IsRelative */ doc->writeTextElement(KXMLQLCEFXIsRelative, QString::number(isRelative() ? 1 : 0)); /******************************************** * X-Axis ********************************************/ doc->writeStartElement(KXMLQLCEFXAxis); doc->writeAttribute(KXMLQLCFunctionName, KXMLQLCEFXX); /* Offset */ doc->writeTextElement(KXMLQLCEFXOffset, QString::number(xOffset())); /* Frequency */ doc->writeTextElement(KXMLQLCEFXFrequency, QString::number(xFrequency())); /* Phase */ doc->writeTextElement(KXMLQLCEFXPhase, QString::number(xPhase())); /* End the (X) <Axis> tag */ doc->writeEndElement(); /******************************************** * Y-Axis ********************************************/ doc->writeStartElement(KXMLQLCEFXAxis); doc->writeAttribute(KXMLQLCFunctionName, KXMLQLCEFXY); /* Offset */ doc->writeTextElement(KXMLQLCEFXOffset, QString::number(yOffset())); /* Frequency */ doc->writeTextElement(KXMLQLCEFXFrequency, QString::number(yFrequency())); /* Phase */ doc->writeTextElement(KXMLQLCEFXPhase, QString::number(yPhase())); /* End the (Y) <Axis> tag */ doc->writeEndElement(); /* End the <Function> tag */ doc->writeEndElement(); return true; }
void traversal_observer::reply(msg const& m) { bdecode_node r = m.message.dict_find_dict("r"); if (!r) { #ifndef TORRENT_DISABLE_LOGGING if (get_observer() != nullptr) { get_observer()->log(dht_logger::traversal , "[%p] missing response dict" , static_cast<void*>(algorithm())); } #endif return; } #ifndef TORRENT_DISABLE_LOGGING dht_observer* logger = get_observer(); if (logger != nullptr && logger->should_log(dht_logger::traversal)) { bdecode_node nid = r.dict_find_string("id"); char hex_id[41]; aux::to_hex({nid.string_ptr(), 20}, hex_id); logger->log(dht_logger::traversal , "[%p] RESPONSE id: %s invoke-count: %d addr: %s type: %s" , static_cast<void*>(algorithm()), hex_id, algorithm()->invoke_count() , print_endpoint(target_ep()).c_str(), algorithm()->name()); } #endif // look for nodes #if TORRENT_USE_IPV6 udp protocol = algorithm()->get_node().protocol(); #endif char const* nodes_key = algorithm()->get_node().protocol_nodes_key(); bdecode_node n = r.dict_find_string(nodes_key); if (n) { char const* nodes = n.string_ptr(); char const* end = nodes + n.string_length(); while (end - nodes >= 20 + detail::address_size(protocol) + 2) { node_id id; std::copy(nodes, nodes + 20, id.begin()); nodes += 20; udp::endpoint ep; #if TORRENT_USE_IPV6 if (protocol == udp::v6()) ep = detail::read_v6_endpoint<udp::endpoint>(nodes); else #endif ep = detail::read_v4_endpoint<udp::endpoint>(nodes); algorithm()->traverse(id, ep); } } bdecode_node id = r.dict_find_string("id"); if (!id || id.string_length() != 20) { #ifndef TORRENT_DISABLE_LOGGING if (get_observer() != nullptr) { get_observer()->log(dht_logger::traversal, "[%p] invalid id in response" , static_cast<void*>(algorithm())); } #endif return; } // in case we didn't know the id of this peer when we sent the message to // it. For instance if it's a bootstrap node. set_id(node_id(id.string_ptr())); }
QString KgpgKey::strength() const { return _describe_key_strength(algorithm(), size(), d->gpgcurve); }
int main( ){ USING_NAMESPACE_ACADO // INTRODUCE THE VARIABLES: // ------------------------- Parameter V ; Parameter km; // READ THE MEASUREMENT FROM A DATA FILE: // -------------------------------------- Matrix m = readFromFile( "michaelis_menten_data.txt" ); // DEFINE A MEASUREMENT FUNCTION: // ------------------------------ Function h; // the measurement function int i; for( i = 0; i < (int) m.getNumRows(); i++ ) h << V*m(i,0)/(km + m(i,0)) - m(i,1); // DEFINE A PARAMETER ESTIMATION PROBLEM: // -------------------------------------- NLP nlp; nlp.minimizeLSQ( h ); nlp.subjectTo( 0.0 <= V <= 2.0 ); nlp.subjectTo( 0.0 <= km <= 2.0 ); // DEFINE AN OPTIMIZATION ALGORITHM AND SOLVE THE ESTIMATION PROBLEM: // ------------------------------------------------------------------ ParameterEstimationAlgorithm algorithm(nlp); algorithm.solve(); VariablesGrid parameters; algorithm.getParameters( parameters ); return 0; // GET THE VARIANCE COVARIANCE IN THE SOLUTION: // --------------------------------------------- Matrix var; algorithm.getParameterVarianceCovariance( var ); double LSSE = 2.0*algorithm.getObjectiveValue(); double MSE = LSSE/( m.getNumRows() - 2.0 ); // m.getNumRows() == number of measurements // 2 == number of parameters var *= MSE; // rescale the variance-covariance with the MSE factor. // PRINT THE RESULT ON THE TERMINAL: // ----------------------------------------------------------------------- printf("\n\nResults for the parameters: \n"); printf("-----------------------------------------------\n"); printf(" V = %.3e +/- %.3e \n", parameters(0,0), sqrt( var(0,0) ) ); printf(" km = %.3e +/- %.3e \n", parameters(0,1), sqrt( var(1,1) ) ); printf("-----------------------------------------------\n\n\n"); return 0; }
/* >>> start tutorial code >>> */ int main( ){ USING_NAMESPACE_ACADO // INTRODUCE THE VARIABLES: // ---------------------------- DifferentialState x1,x2; Control u ; Parameter t1 ; DifferentialEquation f(0.0,t1); // DEFINE A DIFFERENTIAL EQUATION: // ------------------------------- f << dot(x1) == x2; f << dot(x2) == u; // DEFINE AN OPTIMAL CONTROL PROBLEM: // ---------------------------------- OCP ocp(0.0,t1,25); ocp.minimizeMayerTerm( 0, x2 ); ocp.minimizeMayerTerm( 1, 2.0*t1/20.0); ocp.subjectTo( f ); ocp.subjectTo( AT_START, x1 == 0.0 ); ocp.subjectTo( AT_START, x2 == 0.0 ); ocp.subjectTo( AT_END , x1 == 200.0 ); ocp.subjectTo( 0.0 <= x1 <= 200.0001 ); ocp.subjectTo( 0.0 <= x2 <= 40.0 ); ocp.subjectTo( 0.0 <= u <= 5.0 ); ocp.subjectTo( 0.1 <= t1 <= 50.0 ); // DEFINE A MULTI-OBJECTIVE ALGORITHM AND SOLVE THE OCP: // ----------------------------------------------------- MultiObjectiveAlgorithm algorithm(ocp); algorithm.set( PARETO_FRONT_DISCRETIZATION, 11 ); algorithm.set( PARETO_FRONT_GENERATION, PFG_NORMAL_BOUNDARY_INTERSECTION ); algorithm.set( KKT_TOLERANCE, 1e-8 ); // Minimize individual objective function algorithm.solveSingleObjective(0); // Minimize individual objective function algorithm.solveSingleObjective(1); // Generate Pareto set algorithm.solve(); algorithm.getWeights("car_nbi_weights.txt"); algorithm.getAllDifferentialStates("car_nbi_states.txt"); algorithm.getAllControls("car_nbi_controls.txt"); algorithm.getAllParameters("car_nbi_parameters.txt"); // GET THE RESULT FOR THE PARETO FRONT AND PLOT IT: // ------------------------------------------------ VariablesGrid paretoFront; algorithm.getParetoFront( paretoFront ); GnuplotWindow window1; window1.addSubplot( paretoFront, "Pareto Front (time versus energy)", "ENERGY","TIME", PM_POINTS ); window1.plot( ); // PRINT INFORMATION ABOUT THE ALGORITHM: // -------------------------------------- algorithm.printInfo(); // SAVE INFORMATION: // ----------------- FILE *file = fopen("car_nbi_pareto.txt","w"); file << paretoFront; fclose(file); return 0; }
void test(unsigned long items, const char* description) { unsigned long count = getCountWithDefault(items); std::cout << "*** Testing " << description << std::endl; algorithm(count); }
int main( ){ USING_NAMESPACE_ACADO // INTRODUCE FIXED PARAMETERS: // --------------------------- #define v 0.1 #define L 1.0 #define Beta 0.2 #define Delta 0.25 #define E 11250.0 #define k0 1E+06 #define R 1.986 #define K1 250000.0 #define Cin 0.02 #define Tin 340.0 // INTRODUCE THE VARIABLES: // ------------------------- DifferentialState x1,x2; Control u ; DifferentialEquation f( 0.0, L ); // DEFINE A DIFFERENTIAL EQUATION: // ------------------------------- double Alpha, Gamma; Alpha = k0*exp(-E/(R*Tin)); Gamma = E/(R*Tin); f << dot(x1) == Alpha /v * (1.0-x1) * exp((Gamma*x2)/(1.0+x2)); f << dot(x2) == (Alpha*Delta)/v * (1.0-x1) * exp((Gamma*x2)/(1.0+x2)) + Beta/v * (u-x2); // DEFINE AN OPTIMAL CONTROL PROBLEM: // ---------------------------------- OCP ocp( 0.0, L, 50 ); ocp.minimizeMayerTerm( 0, Cin*(1.0-x1) ); // Solve conversion optimal problem ocp.minimizeMayerTerm( 1, (pow((Tin*x2),2.0)/K1) + 0.005*Cin*(1.0-x1) ); // Solve energy optimal problem (perturbed by small conversion cost; // otherwise the problem is ill-defined.) ocp.subjectTo( f ); ocp.subjectTo( AT_START, x1 == 0.0 ); ocp.subjectTo( AT_START, x2 == 0.0 ); ocp.subjectTo( 0.0 <= x1 <= 1.0 ); ocp.subjectTo( (280.0-Tin)/Tin <= x2 <= (400.0-Tin)/Tin ); ocp.subjectTo( (280.0-Tin)/Tin <= u <= (400.0-Tin)/Tin ); // DEFINE A MULTI-OBJECTIVE ALGORITHM AND SOLVE THE OCP: // ----------------------------------------------------- MultiObjectiveAlgorithm algorithm(ocp); algorithm.set( INTEGRATOR_TYPE, INT_BDF ); algorithm.set( KKT_TOLERANCE, 1e-8 ); algorithm.set( PARETO_FRONT_GENERATION , PFG_WEIGHTED_SUM ); algorithm.set( PARETO_FRONT_DISCRETIZATION, 11 ); // Generate Pareto set algorithm.solve(); algorithm.getWeights("plug_flow_reactor_ws_weights.txt"); algorithm.getAllDifferentialStates("plug_flow_reactor_ws_states.txt"); algorithm.getAllControls("plug_flow_reactor_ws_controls.txt"); // VISUALIZE THE RESULTS IN A GNUPLOT WINDOW: // ------------------------------------------ VariablesGrid paretoFront; algorithm.getParetoFront( paretoFront ); GnuplotWindow window1; window1.addSubplot( paretoFront, "Pareto Front (conversion versus energy)", "OUTLET CONCENTRATION", "ENERGY",PM_POINTS ); window1.plot( ); // PRINT INFORMATION ABOUT THE ALGORITHM: // -------------------------------------- algorithm.printInfo(); // SAVE INFORMATION: // ----------------- paretoFront.print(); return 0; }
int main( int argc, char * const argv[] ){ //====================================================================== // PARSE THE INPUT ARGUMENTS: // ---------------------------------- double IC[4]; /* arguments are passed to the main function by string * there are 'int argc' arguments * the first one is the name of the program * the next ones are arguments passed in the call like * program number1 number2 * in this stupid simple parser, we directly read doubles from the arguments */ int i=1; while (i < argc) { // load the i-th string argument passed to the main function char* input = argv[i]; // parse the string to a double value IC[i-1] = atof(input); i++; } cout << "Initial Conditions" << endl; cout << "------------" << endl; for (i = 0; i < argc-1; ++i) { cout << i+1 << ":\t" << IC[i] << endl; } //====================================================================== USING_NAMESPACE_ACADO // DIFFERENTIAL STATES : // ------------------------- Parameter x; // Position Parameter y; // Parameter z; // // ------------------------- // ------------------------------------------- Parameter dx; // Speed Parameter dy; // Parameter dz; // Parameter e11; Parameter e12; Parameter e13; Parameter e21; Parameter e22; Parameter e23; Parameter e31; Parameter e32; Parameter e33; Parameter w1; Parameter w2; Parameter w3; // ------------------------- // ------------------------------------------- Parameter r; // Kite distance Parameter dr; // Kite distance / dt //------------------------- // ------------------------------------------- Parameter delta; // Carousel Parameter ddelta; // Parameter ur; Parameter up; // Ailerons // Collect all the states in a vector const int n_XD = 24; // Number of states IntermediateState XD[n_XD]; // Vector collecting all states XD[0] = x; XD[1] = y; XD[2] = z; XD[3] = dx; XD[4] = dy; XD[5] = dz; XD[6] = e11; XD[7] = e12; XD[8] = e13; XD[9] = e21; XD[10] = e22; XD[11] = e23; XD[12] = e31; XD[13] = e32; XD[14] = e33; XD[15] = w1; XD[16] = w2; XD[17] = w3; XD[18] = r; XD[19] = dr; XD[20] = delta; XD[21] = ddelta; XD[22] = ur; XD[23] = up; // CONTROL : // ------------------------- Parameter dddelta; // Carousel acceleration Parameter ddr; Parameter dur; Parameter dup; // Ailerons // Collect all the controls in a vector const int n_U = 4; // Number of controls IntermediateState U[n_U]; // Vector collecting all states U[0] = dddelta; U[1] = ddr; U[2] = dur; U[3] = dup; // PARAMETERS // ----------------------- // Parameter SlackCLmax; // Parameter SlackLambda; // DEFINITION OF PI : // ------------------------ double PI = 3.1415926535897932; //TAIL LENGTH double LT = 0.45; //ROLL DAMPING double RDfac = 1; double RD0 = 1e-2; double RD = RDfac*RD0; // CONSTANTS : // ------------------------ // PARAMETERS OF THE KITE : // ----------------------------- double mk = 0.463; // mass of the kite // [ kg ] // PHYSICAL CONSTANTS : // ----------------------------- double g = 9.81; // gravitational constant // [ m /s^2] double rho = 1.23; // density of the air // [ kg/m^3] // PARAMETERS OF THE CABLE : // ----------------------------- double rhoc = 1450.00; // density of the cable // [ kg/m^3] double cc = 1.00; // frictional constant // [ ] double dc = 1e-3; // diameter // [ m ] double AQ = PI*dc*dc/4.0; //CAROUSEL ARM LENGTH double rA = 1.085; //(dixit Kurt) //INERTIA MATRIX (Kurt's direct measurements) // Note: low sensitivity to I1,2,3... high sensitivity to I31... double I1 = 0.0163; double I31 = 0.0006; double I2 = 0.0078; double I3 = 0.0229; //WIND-TUNNEL PARAMETERS //Lift (report p. 67) //Sensitivity to CLA error low double CLA = 5.064; //Sensitivity to CLe error low double CLe = 0.318; //Sensitivity to CLr error low double CLr = 0.85; //?!?!?!?!? //HIGH sensitivity to CL0 !! double CL0 = 0.239; //Drag (report p. 70) //Sensitivity to CDA error low double CDA = -0.195; double CDA2 = 4.268; double CDB2 = 0; //Sensitivity to CDe error low double CDe = 0.044; //Sensitivity to CDr error low double CDr = 0.111; //Sensitivity to CD0 error low double CD0 = 0.026; //Roll (report p. 72) //HIGH sensitivity to CRB !! double CRB = -0.062; //HIGH sensitivity to CRAB !! double CRAB = -0.271; //Sensitivity to CRr error low double CRr = -0.244; //Pitch (report p. 74) //HIGH sensitivity to CPA !! double CPA = 0.293; //Sensitivity to CPe error low double CPe = -0.821; //Sensitivity to CPr error low double CPr = -0.647; //?!?!?!?!? //HIGH sensitivity to CP0 !! double CP0 = 0.03; //Yaw (report p. 76) //HIGH sensitivity to CYB !! double CYB = 0.05; //HIGH sensitivity to CYAB !! double CYAB = 0.229; double SPAN = 0.96; double CHORD = 0.1; // OTHER VARIABLES : // ------------------------ IntermediateState mc; // mass of the cable IntermediateState m ; // effective inertial mass IntermediateState mgrav; // gravific mass // IntermediateState dmc; // first derivative of m with respect to t // ORIENTATION AND FORCES : // ------------------------ IntermediateState wind ; // the wind at altitude IntermediateState Cf ; // cable drag IntermediateState CD ; // the aerodynamic drag coefficient IntermediateState CL ; // the aerodynamic lift coefficient IntermediateState CR ; // the aerodynamic roll coefficient IntermediateState CP ; // the aerodynamic pitch coefficient IntermediateState CY ; // the aerodynamic yaw coefficient IntermediateState F [ 3]; // aero forces + gravity IntermediateState FL [ 3]; // the lift force IntermediateState FD [ 3]; // the drag force IntermediateState Ff [ 3]; // the frictional force // IntermediateState Fcable ; // force in the cable IntermediateState er [ 3]; // X normed to 1 IntermediateState eTe [ 3]; //unrotated transversal vector (psi = 0) IntermediateState eLe [ 3]; //unrotated lift vector (psi = 0) IntermediateState we [ 3]; // effective wind vector IntermediateState wE [ 3]; // effective wind vector IntermediateState wp ; IntermediateState wep [ 3]; // effective wind projected in the plane orthogonal to X IntermediateState VKite ; //Kite (relative) speed IntermediateState VKite2 ; //Squared (relative) kite speed IntermediateState Vp; IntermediateState VT [3]; IntermediateState alpha; IntermediateState beta; IntermediateState alphaTail; IntermediateState T [3]; // TERMS ON RIGHT-HAND-SIDE // OF THE DIFFERENTIAL // EQUATIONS : // ------------------------ IntermediateState de11; IntermediateState de12; IntermediateState de13; IntermediateState de21; IntermediateState de22; IntermediateState de23; IntermediateState de31; IntermediateState de32; IntermediateState de33; // MODEL EQUATIONS : // =============================================================== // CROSS AREA OF THE CABLE : // --------------------------------------------------------------- // AQ = PI*dc*dc/4.0 ; // THE EFECTIVE MASS' : // --------------------------------------------------------------- mc = rhoc*AQ*r ; // mass of the cable m = mk + mc/3.0; // effective inertial mass mgrav = mk + mc/2.0; // effective inertial mass // ----------------------------- // ---------------------------- // dm = (rhoc*AQ/ 3.0)*dr; // time derivative of the mass // WIND SHEAR MODEL : // --------------------------------------------------------------- wind = 0.; // EFFECTIVE WIND IN THE KITE`S SYSTEM : // --------------------------------------------------------------- we[0] = -wind + dx; we[1] = dy; we[2] = dz; VKite2 = (we[0]*we[0] + we[1]*we[1] + we[2]*we[2]); VKite = sqrt(VKite2); // CALCULATION OF THE FORCES : // --------------------------------------------------------------- // er er[0] = x/r; er[1] = y/r; er[2] = z/r; //Velocity accross X (cable drag) wp = er[0]*we[0] + er[1]*we[1] + er[2]*we[2]; wep[0] = we[0] - wp*er[0]; wep[1] = we[1] - wp*er[1]; wep[2] = we[2] - wp*er[2]; //Aero coeff. // LIFT DIRECTION VECTOR // ------------------------- //Relative wind speed in Airfoil's referential 'E' wE[0] = e11*we[0] + e21*we[1] + e31*we[2]; wE[1] = e12*we[0] + e22*we[1] + e32*we[2]; wE[2] = e13*we[0] + e23*we[1] + e33*we[2]; //Airfoil's transversal axis in fixed referential 'e' eTe[0] = e12; eTe[1] = e22; eTe[2] = e32; // Lift axis ** Normed to we !! ** eLe[0] = - eTe[1]*we[2] + eTe[2]*we[1]; eLe[1] = - eTe[2]*we[0] + eTe[0]*we[2]; eLe[2] = - eTe[0]*we[1] + eTe[1]*we[0]; // AERODYNAMIC COEEFICIENTS // ---------------------------------- //VT = cross([w1;w2;w3],[-LT;0;0]) + wE; VT[0] = wE[0]; VT[1] = -LT*w3 + wE[1]; VT[2] = LT*w2 + wE[2]; alpha = -wE[2]/wE[0]; //Note: beta & alphaTail are compensated for the tail motion induced by omega beta = VT[1]/sqrt(VT[0]*VT[0] + VT[2]*VT[2]); alphaTail = -VT[2]/VT[0]; CL = CLA*alpha + CLe*up + CLr*ur + CL0; CD = CDA*alpha + CDA2*alpha*alpha + CDB2*beta*beta + CDe*up + CDr*ur + CD0; CR = -RD*w1 + CRB*beta + CRAB*alphaTail*beta + CRr*ur; CP = CPA*alphaTail + CPe*up + CPr*ur + CP0; CY = CYB*beta + CYAB*alphaTail*beta; Cf = rho*dc*r*VKite/8.0; // THE FRICTION OF THE CABLE : // --------------------------------------------------------------- Ff[0] = -rho*dc*r*VKite*cc*wep[0]/8.0; Ff[1] = -rho*dc*r*VKite*cc*wep[1]/8.0; Ff[2] = -rho*dc*r*VKite*cc*wep[2]/8.0; // LIFT : // --------------------------------------------------------------- FL[0] = rho*CL*eLe[0]*VKite/2.0; FL[1] = rho*CL*eLe[1]*VKite/2.0; FL[2] = rho*CL*eLe[2]*VKite/2.0; // DRAG : // --------------------------------------------------------------- FD[0] = -rho*VKite*CD*we[0]/2.0; FD[1] = -rho*VKite*CD*we[1]/2.0; FD[2] = -rho*VKite*CD*we[2]/2.0; // FORCES (AERO) // --------------------------------------------------------------- F[0] = FL[0] + FD[0] + Ff[0]; F[1] = FL[1] + FD[1] + Ff[1]; F[2] = FL[2] + FD[2] + Ff[2]; // TORQUES (AERO) // --------------------------------------------------------------- T[0] = 0.5*rho*VKite2*SPAN*CR; T[1] = 0.5*rho*VKite2*CHORD*CP; T[2] = 0.5*rho*VKite2*SPAN*CY; // ATTITUDE DYNAMICS // ----------------------------------------------------------- de11 = e12*w3 - e13*w2; de12 = e13*w1 - e11*w3; de13 = e11*w2 - e12*w1; de21 = e22*w3 - e23*w2; de22 = e23*w1 - e21*w3; de23 = e21*w2 - e22*w1; de31 = e32*w3 - e33*w2; de32 = e33*w1 - e31*w3; de33 = e31*w2 - e32*w1; //////////////////////////////////////////////////////////////////////// // // // AUTO-GENERATED EQUATIONS (S. Gros, HIGHWIND, OPTEC, KU Leuven) // // // //////////////////////////////////////////////////////////////////////// // Equations read: // IMA = inv(MA) // ddX = IMA*(Bx - CA*lambda) // lambdaNum = CA^T*IMA*Bx - Blambda // lambdaDen = CA^T*IMA*CA // lambda = lambdaNum/lambdaDen // Arm IntermediateState xA; IntermediateState dxA; IntermediateState ddxA; IntermediateState yA; IntermediateState dyA; IntermediateState ddyA; xA = -rA*sin(delta); dxA = -(ddelta*rA*cos(delta)); ddxA = -(dddelta*rA*cos(delta) - ddelta*ddelta*rA*sin(delta)); yA = rA*cos(delta); dyA = -ddelta*rA*sin(delta); ddyA = - rA*cos(delta)*ddelta*ddelta - dddelta*rA*sin(delta); // BUILD DYNAMICS IntermediateState lambdaNum; lambdaNum = ddxA*xA - 2*dy*dyA - ddr*r - ddxA*x - 2*dx*dxA - ddyA*y + ddyA*yA - dr*dr + dx*dx + dxA*dxA + dy*dy + dyA*dyA + dz*dz + (F[0]*(x - xA))/m + (F[1]*(y - yA))/m + (z*(F[2] - g*mgrav))/m; IntermediateState lambdaDen; lambdaDen = x*x/m + xA*xA/m + y*y/m + yA*yA/m + z*z/m - (2*x*xA)/m - (2*y*yA)/m; IntermediateState lambda; lambda = lambdaNum/lambdaDen; // IntermediateState ddX(6,1); IntermediateState ddx = (F[0] - lambda*(x - xA))/m; IntermediateState ddy = (F[1] - lambda*(y - yA))/m; IntermediateState ddz = -(g*mgrav - F[2] + lambda*z)/m; IntermediateState dw1 = (I31*(T[2] + w2*(I1*w1 + I31*w3) - I2*w1*w2))/(I31*I31 - I1*I3) - (I3*(T[0] - w2*(I31*w1 + I3*w3) + I2*w2*w3))/(I31*I31 - I1*I3); IntermediateState dw2 = (T[1] + w1*(I31*w1 + I3*w3) - w3*(I1*w1 + I31*w3))/I2; IntermediateState dw3 = (I31*(T[0] - w2*(I31*w1 + I3*w3) + I2*w2*w3))/(I31*I31 - I1*I3) - (I1*(T[2] + w2*(I1*w1 + I31*w3) - I2*w1*w2))/(I31*I31 - I1*I3); // BUILD CONSTRAINTS IntermediateState Const, dConst; Const = - r*r/2 + x*x/2 - x*xA + xA*xA/2 + y*y/2 - y*yA + yA*yA/2 + z*z/2; dConst = dx*x - dr*r - dxA*x - dx*xA + dxA*xA + dy*y - dyA*y - dy*yA + dyA*yA + dz*z; ///////////////////////////// END OF AUTO-GENERATED CODE ////////////////////////////////////////////////////// // Fcable = lambda*r; // =============================================================== // END OF MODEL EQUATIONS // =============================================================== IntermediateState Cost = 0; for ( i=0; i < n_U; i++ ) { Cost += U[i]*U[i]; } // DEFINE THE NLP: // ---------------------------------- NLP nlp; nlp.minimize( Cost ); nlp.minimize( (CL-0.5)*(CL-0.5) ); // CONSTRAINTS: // --------------------------------- // State bounds nlp.subjectTo( -0.2 <= ur <= 0.2 ); nlp.subjectTo( -0.2 <= up <= 0.2 ); nlp.subjectTo( 0.0 <= x ); nlp.subjectTo( rA <= y ); /* nlp.subjectTo( -1.0 <= e11 <= 1.0 ); nlp.subjectTo( -1.0 <= e12 <= 1.0 ); nlp.subjectTo( -1.0 <= e13 <= 1.0 ); nlp.subjectTo( -1.0 <= e21 <= 1.0 ); nlp.subjectTo( -1.0 <= e22 <= 1.0 ); nlp.subjectTo( -1.0 <= e23 <= 1.0 ); nlp.subjectTo( -1.0 <= e31 <= 1.0 ); nlp.subjectTo( -1.0 <= e32 <= 1.0 ); nlp.subjectTo( -1.0 <= e33 <= 1.0 );*/ nlp.subjectTo( delta == IC[2] ); nlp.subjectTo( ddelta == IC[3] ); // Flight envelope nlp.subjectTo( 0 <= CL <= 1 ); // nlp.subjectTo( CL == 0.5 ); nlp.subjectTo( 1 <= lambda/10 ); nlp.subjectTo( -10*PI/180 <= beta <= 10*PI/180 ); // nlp.subjectTo( -10*PI/180 <= alpha <= 10*PI/180 ); nlp.subjectTo( -15*PI/180 <= alphaTail <= 15*PI/180 ); nlp.subjectTo( 0 <= wE[0] ); // Invariants nlp.subjectTo( Const == 0 ); nlp.subjectTo( dConst == 0 ); nlp.subjectTo( e11*e11 + e12*e12 + e13*e13 - 1 == 0 ); nlp.subjectTo( e11*e21 + e12*e22 + e13*e23 == 0 ); nlp.subjectTo( e11*e31 + e12*e32 + e13*e33 == 0 ); nlp.subjectTo( e21*e21 + e22*e22 + e23*e23 - 1 == 0 ); nlp.subjectTo( e21*e31 + e22*e32 + e23*e33 == 0 ); nlp.subjectTo( e31*e31 + e32*e32 + e33*e33 - 1 == 0 ); // Equilibrium // ROTATE BACK THE SYSTEM DYNAMICS: // --------------------------------------------------------------- nlp.subjectTo( z == IC[0] ); nlp.subjectTo( r == IC[1] ); // Rdot*X R*dX // nlp.subjectTo( (-x)*ddelta + dy == 0 ); nlp.subjectTo( (-y)*ddelta - dx == 0 ); // You never have y=0 nlp.subjectTo( dz == 0 ); nlp.subjectTo( dr == 0 ); // mul(Rdotdot,X) + 2*mul(Rdot,Xdot) + mul(R,Xdotdot) // nlp.subjectTo( ( ( -dddelta )*x + ( -ddelta*ddelta )*y ) + 2*(-dx)*ddelta + ddy == 0 ); nlp.subjectTo( ( ( ddelta*ddelta )*x + ( -dddelta )*y ) + 2*(-dy)*ddelta - ddx == 0 ); nlp.subjectTo( ddz == 0 ); nlp.subjectTo( e11*w1 + e12*w2 + e13*w3 == 0 ); nlp.subjectTo( e21*w1 + e22*w2 + e23*w3 == 0 ); nlp.subjectTo( e31*w1 + e32*w2 + e33*w3 - ddelta == 0 ); nlp.subjectTo( dw1 == 0 ); nlp.subjectTo( dw2 == 0 ); nlp.subjectTo( dw3 == 0 ); nlp.subjectTo( dddelta == 0 ); nlp.subjectTo( ddr == 0 ); nlp.subjectTo( dur == 0 ); nlp.subjectTo( dup == 0 ); // DEFINE AN OPTIMIZATION ALGORITHM AND SOLVE THE OCP: // --------------------------------------------------- OptimizationAlgorithm algorithm(nlp); algorithm.set ( MAX_NUM_ITERATIONS, 100 ); algorithm.set ( KKT_TOLERANCE , 1e-6 ); algorithm.initializeParameters("EQ_init.txt" ); algorithm.set( MIN_LINESEARCH_PARAMETER, 1e-4 ); algorithm.set( HESSIAN_APPROXIMATION, EXACT_HESSIAN ); // algorithm.set( PRINT_SCP_METHOD_PROFILE, YES ); algorithm.solve(); algorithm.getParameters("EQ_params.txt" ); return 0; }
/* >>> start tutorial code >>> */ int main( ){ USING_NAMESPACE_ACADO // INTRODUCE THE VARIABLES: // ------------------------- Parameter y1,y2; // DEFINE AN OPTIMIZATION PROBLEM: // ------------------------------- NLP nlp; nlp.minimize( 0, y1 ); nlp.minimize( 1, y2 ); nlp.subjectTo( 0.0 <= y1 <= 5.0 ); nlp.subjectTo( 0.0 <= y2 <= 5.2 ); nlp.subjectTo( 0.0 <= y2 - 5.0*exp(-y1) - 2.0*exp(-0.5*(y1-3.0)*(y1-3.0)) ); // DEFINE A MULTI-OBJECTIVE ALGORITHM AND SOLVE THE NLP: // ----------------------------------------------------- MultiObjectiveAlgorithm algorithm(nlp); algorithm.set( PARETO_FRONT_GENERATION, PFG_NORMAL_BOUNDARY_INTERSECTION ); algorithm.set( PARETO_FRONT_DISCRETIZATION, 41 ); algorithm.set( KKT_TOLERANCE, 1e-12 ); // Minimize individual objective function algorithm.initializeParameters("initial_scalar2_2.txt"); algorithm.solveSingleObjective(1); // Minimize individual objective function algorithm.solveSingleObjective(0); // Generate Pareto set algorithm.solve(); // GET THE RESULT FOR THE PARETO FRONT AND PLOT IT: // ------------------------------------------------ VariablesGrid paretoFront; algorithm.getParetoFront( paretoFront ); algorithm.getWeights("scalar2_nbi_weights.txt"); GnuplotWindow window1; window1.addSubplot( paretoFront, "Pareto Front y1 vs y2", "y1","y2", PM_POINTS ); window1.plot( ); FILE *file = fopen("scalar2_nbi_pareto.txt","w"); paretoFront.print(); file << paretoFront; fclose(file); // FILTER THE PARETO FRONT AND PLOT IT: // ------------------------------------ algorithm.getParetoFrontWithFilter( paretoFront ); algorithm.getWeightsWithFilter("scalar2_nbi_weights_filtered.txt"); GnuplotWindow window2; window2.addSubplot( paretoFront, "Pareto Front (with filter) y1 vs y2", "y1","y2", PM_POINTS ); window2.plot( ); FILE *file2 = fopen("scalar2_nbi_pareto_filtered.txt","w"); paretoFront.print(); file2 << paretoFront; fclose(file2); // PRINT INFORMATION ABOUT THE ALGORITHM: // -------------------------------------- algorithm.printInfo(); return 0; }
bool SamplingProvider::computation() { if (!this->m_model) { _GT_LOGGER_ERR(this->name(), "Subroutine <computation> failed. Missing model."); return (false); } const openmesh::Mesh &mesh(this->m_model->mesh()); // Verifies settings and prepares geodesic algorithm. _GT_LOGGER_MSG(this->name(), "Verifying settings and preparing geodesic algorithm."); std::vector<real_t> vertices(mesh.n_vertices() * 3); std::vector<size_t> faces(mesh.n_faces() * 3); for (openmesh::Mesh::ConstVertexIter cv_iter = mesh.vertices_begin(); cv_iter != mesh.vertices_end(); ++cv_iter) { size_t offset = cv_iter.handle().idx() * 3; const openmesh::Mesh::Point &point(mesh.point(cv_iter.handle())); vertices[offset + 0] = point[0]; vertices[offset + 1] = point[1]; vertices[offset + 2] = point[2]; } for (openmesh::Mesh::ConstFaceIter cf_iter = mesh.faces_begin(); cf_iter != mesh.faces_end(); ++cf_iter) { size_t offset = cf_iter.handle().idx() * 3; openmesh::Mesh::ConstFaceVertexIter cfv_iter = mesh.cfv_iter(cf_iter.handle()); faces[offset + 0] = ( cfv_iter).handle().idx(); faces[offset + 1] = (++cfv_iter).handle().idx(); faces[offset + 2] = (++cfv_iter).handle().idx(); } geodesic::Mesh geode_mesh; geode_mesh.initialize_mesh_data(vertices, faces); geodesic::GeodesicAlgorithmDijkstra algorithm(&geode_mesh); // Sorts vertices with respect to Gaussian curvatures. _GT_LOGGER_MSG(this->name(), "Sorting vertices with respect to Gaussian curvatures."); std::vector<size_t> vertices_stack = algo::Util::order(this->m_curvatures); // Extracts sample vertices and computes geodesic distances. _GT_LOGGER_MSG(this->name(), "Extracting sample vertices and computing geodesic distances."); _GT_LOGGER_BEG_PROG; _GT_LOGGER_BSY_PROG; real_t sampling_radius = std::sqrt(3.0 * this->m_barycentric_areas.sum() / GT_PI) * this->m_sampling_radius.data(); std::vector<bool> vertices_flags(this->m_curvatures.size(), false); std::vector<std::vector<real_t> > distances; this->m_samples.data().clear(); while (!vertices_stack.empty()) { if (vertices_flags[vertices_stack.back()]) { vertices_stack.pop_back(); continue; } size_t base_vert = vertices_stack.back(); vertices_flags[base_vert] = true; this->m_samples.data().push_back(base_vert); distances.push_back(std::vector<real_t>(geode_mesh.vertices().size(), 0)); std::vector<geodesic::SurfacePoint> sources(1, geodesic::SurfacePoint(&geode_mesh.vertices()[base_vert])); algorithm.propagate(sources); for (size_t j = 0; j < geode_mesh.vertices().size(); ++j) { real_t distance; algorithm.best_source(geodesic::SurfacePoint(&geode_mesh.vertices()[j]), distance); distances.back()[j] = distance; if (distance < sampling_radius) vertices_flags[j] = true; } } _GT_LOGGER_END_PROG; this->m_geodesics.resize(distances.size(), geode_mesh.vertices().size()); for (int i = 0; i < this->m_geodesics.rows(); ++i) for (int j = 0; j < this->m_geodesics.cols(); ++j) { this->m_geodesics(i, j) = distances[i][j]; } return (true); }
bool EFX::saveXML(QDomDocument* doc, QDomElement* wksp_root) { QDomElement root; QDomElement tag; QDomElement subtag; QDomText text; QString str; Q_ASSERT(doc != NULL); Q_ASSERT(wksp_root != NULL); /* Function tag */ root = doc->createElement(KXMLQLCFunction); wksp_root->appendChild(root); root.setAttribute(KXMLQLCFunctionID, id()); root.setAttribute(KXMLQLCFunctionType, Function::typeToString(type())); root.setAttribute(KXMLQLCFunctionName, name()); /* Fixtures */ QListIterator <EFXFixture*> it(m_fixtures); while (it.hasNext() == true) it.next()->saveXML(doc, &root); /* Propagation mode */ tag = doc->createElement(KXMLQLCEFXPropagationMode); root.appendChild(tag); text = doc->createTextNode(propagationModeToString(m_propagationMode)); tag.appendChild(text); /* Speed bus */ tag = doc->createElement(KXMLQLCBus); root.appendChild(tag); tag.setAttribute(KXMLQLCBusRole, KXMLQLCBusFade); str.setNum(busID()); text = doc->createTextNode(str); tag.appendChild(text); /* Direction */ tag = doc->createElement(KXMLQLCFunctionDirection); root.appendChild(tag); text = doc->createTextNode(Function::directionToString(m_direction)); tag.appendChild(text); /* Run order */ tag = doc->createElement(KXMLQLCFunctionRunOrder); root.appendChild(tag); text = doc->createTextNode(Function::runOrderToString(m_runOrder)); tag.appendChild(text); /* Algorithm */ tag = doc->createElement(KXMLQLCEFXAlgorithm); root.appendChild(tag); text = doc->createTextNode(algorithmToString(algorithm())); tag.appendChild(text); /* Width */ tag = doc->createElement(KXMLQLCEFXWidth); root.appendChild(tag); str.setNum(width()); text = doc->createTextNode(str); tag.appendChild(text); /* Height */ tag = doc->createElement(KXMLQLCEFXHeight); root.appendChild(tag); str.setNum(height()); text = doc->createTextNode(str); tag.appendChild(text); /* Rotation */ tag = doc->createElement(KXMLQLCEFXRotation); root.appendChild(tag); str.setNum(rotation()); text = doc->createTextNode(str); tag.appendChild(text); /******************************************** * X-Axis ********************************************/ tag = doc->createElement(KXMLQLCEFXAxis); root.appendChild(tag); tag.setAttribute(KXMLQLCFunctionName, KXMLQLCEFXX); /* Offset */ subtag = doc->createElement(KXMLQLCEFXOffset); tag.appendChild(subtag); str.setNum(xOffset()); text = doc->createTextNode(str); subtag.appendChild(text); /* Frequency */ subtag = doc->createElement(KXMLQLCEFXFrequency); tag.appendChild(subtag); str.setNum(xFrequency()); text = doc->createTextNode(str); subtag.appendChild(text); /* Phase */ subtag = doc->createElement(KXMLQLCEFXPhase); tag.appendChild(subtag); str.setNum(xPhase()); text = doc->createTextNode(str); subtag.appendChild(text); /******************************************** * Y-Axis ********************************************/ tag = doc->createElement(KXMLQLCEFXAxis); root.appendChild(tag); tag.setAttribute(KXMLQLCFunctionName, KXMLQLCEFXY); /* Offset */ subtag = doc->createElement(KXMLQLCEFXOffset); tag.appendChild(subtag); str.setNum(yOffset()); text = doc->createTextNode(str); subtag.appendChild(text); /* Frequency */ subtag = doc->createElement(KXMLQLCEFXFrequency); tag.appendChild(subtag); str.setNum(yFrequency()); text = doc->createTextNode(str); subtag.appendChild(text); /* Phase */ subtag = doc->createElement(KXMLQLCEFXPhase); tag.appendChild(subtag); str.setNum(yPhase()); text = doc->createTextNode(str); subtag.appendChild(text); return true; }
/** \brief Get the (integer) output argument of an atomic operation */ int getAtomicOutput(int k) const{ return algorithm().at(k).res;}
static void trap_dispatch(struct trapframe *tf) { char c; int ret=0; struct trapframe temp = *tf; switch (tf->tf_trapno) { case T_PGFLT: //page fault if ((ret = pgfault_handler(tf)) != 0) { print_trapframe(tf); if (current == NULL) { panic("handle pgfault failed. ret=%d\n", ret); } else { if (trap_in_kernel(tf)) { panic("handle pgfault failed in kernel mode. ret=%d\n", ret); } cprintf("killed by kernel.\n"); panic("handle user mode pgfault failed. ret=%d\n", ret); do_exit(-E_KILLED); } } break; case T_SYSCALL: syscall(); break; case IRQ_OFFSET + IRQ_TIMER: #if 0 LAB3 : If some page replacement algorithm(such as CLOCK PRA) need tick to change the priority of pages, then you can add code here. #endif /* LAB1 2013011326 : STEP 3 */ /* handle the timer interrupt */ /* (1) After a timer interrupt, you should record this event using a global variable (increase it), such as ticks in kern/driver/clock.c * (2) Every TICK_NUM cycle, you can print some info using a funciton, such as print_ticks(). * (3) Too Simple? Yes, I think so! */ /* LAB5 2013011326 */ /* you should upate you lab1 code (just add ONE or TWO lines of code): * Every TICK_NUM cycle, you should set current process's current->need_resched = 1 */ ticks ++; if (ticks % TICK_NUM == 0) { assert(current != NULL); current->need_resched = 1; } break; case IRQ_OFFSET + IRQ_COM1: c = cons_getc(); cprintf("serial [%03d] %c\n", c, c); break; case IRQ_OFFSET + IRQ_KBD: c = cons_getc(); cprintf("kbd [%03d] %c\n", c, c); if(c == '0') { if(tf->tf_cs != USER_CS) { cprintf("user\n"); temp.tf_cs = USER_CS; temp.tf_ds = USER_DS; temp.tf_es = USER_DS; temp.tf_ss = USER_DS; temp.tf_eflags |= FL_IOPL_MASK; temp.tf_esp = (uint32_t)tf + sizeof(struct trapframe) - 8; *((uint32_t *)tf - 1) = (uint32_t)&temp; } } else if(c == '3') { if(tf->tf_cs != KERNEL_CS) { cprintf("kernel\n"); temp.tf_cs = KERNEL_CS; temp.tf_ds = KERNEL_DS; temp.tf_es = KERNEL_DS; temp.tf_eflags &= ~FL_IOPL_MASK; *((uint32_t *)tf - 1) = (uint32_t)&temp; } } else if(c == '4') { cprintf("debug\n"); print_trapframe(tf); } break; //LAB1 CHALLENGE 1 : YOUR CODE you should modify below codes. case T_SWITCH_TOU: temp.tf_cs = USER_CS; temp.tf_ds = USER_DS; temp.tf_es = USER_DS; temp.tf_ss = USER_DS; temp.tf_eflags |= FL_IOPL_MASK; temp.tf_esp = (uint32_t)tf + sizeof(struct trapframe) - 8; *((uint32_t *)tf - 1) = (uint32_t)&temp; break; case T_SWITCH_TOK: // panic("T_SWITCH_** ??\n"); temp.tf_cs = KERNEL_CS; temp.tf_ds = KERNEL_DS; temp.tf_es = KERNEL_DS; temp.tf_eflags &= ~FL_IOPL_MASK; *((uint32_t *)tf - 1) = (uint32_t)&temp; break; case IRQ_OFFSET + IRQ_IDE1: case IRQ_OFFSET + IRQ_IDE2: /* do nothing */ break; default: print_trapframe(tf); if (current != NULL) { cprintf("unhandled trap.\n"); do_exit(-E_KILLED); } // in kernel, it must be a mistake panic("unexpected trap in kernel.\n"); } }
int main(int argc, char** argv) { #if defined(_MSC_VER) compile_msvc compile_policy; #else compile_bjam compile_policy; #endif typedef std::vector<algorithm> v_a_type; v_a_type algorithms; algorithms.push_back(algorithm("area")); algorithms.push_back(algorithm("length")); algorithms.push_back(algorithm("perimeter")); algorithms.push_back(algorithm("correct")); algorithms.push_back(algorithm("distance", 2)); algorithms.push_back(algorithm("centroid", 2)); algorithms.push_back(algorithm("intersects", 2)); algorithms.push_back(algorithm("within", 2)); algorithms.push_back(algorithm("equals", 2)); typedef std::vector<cs> cs_type; cs_type css; css.push_back(cs("cartesian")); // css.push_back(cs("spherical<bg::degree>")); // css.push_back(cs("spherical<bg::radian>")); boost::timer timer; for (v_a_type::const_iterator it = algorithms.begin(); it != algorithms.end(); ++it) { /*([heading Behavior] [table [[Case] [Behavior] ] [[__2dim__][All combinations of: box, ring, polygon, multi_polygon]] [[__other__][__nyiversion__]] [[__sph__][__nyiversion__]] [[Three dimensional][__nyiversion__]] ]*/ std::ostringstream name; name << "../../../../generated/" << it->name << "_status.qbk"; std::ofstream out(name.str().c_str()); out << "[heading Supported geometries]" << std::endl; cs_type::const_iterator cit = css.begin(); { // Construct the table std::vector<std::vector<int> > table; for (int type = point; type < geometry_count; type++) { table.push_back(report(compile_policy, type, *it, true, true, 2, cit->name)); } // Detect red rows/columns std::vector<int> lines_status(table.size(), false); std::vector<int> columns_status(table[0].size(), false); for (unsigned int i = 0; i != table.size(); ++i) { for (unsigned int j = 0; j != table[i].size(); ++j) { lines_status[i] |= table[i][j]; columns_status[j] |= table[i][j]; } } // Display the table out << "[table" << std::endl << "["; if (it->arity > 1) { out << "[ ]"; for (int type = point; type < geometry_count; type++) { if (!columns_status[type]) continue; out << "[" << geometry_string(type) << "]"; } } else { out << "[Geometry][Status]"; } out << "]" << std::endl; for (unsigned int i = 0; i != table.size(); ++i) { if (!lines_status[i]) continue; out << "["; out << "[" << geometry_string(i) << "]"; for (unsigned int j = 0; j != table[i].size(); ++j) { if (!columns_status[j]) continue; out << "[[$img/" << (table[i][j] ? "ok" : "nyi") << ".png]]"; } out << "]" << std::endl; } out << "]" << std::endl; } } std::cout << "TIME: " << timer.elapsed() << std::endl; return 0; }
static void trap_dispatch(struct trapframe *tf) { char c; int ret=0; switch (tf->tf_trapno) { case T_PGFLT: //page fault if ((ret = pgfault_handler(tf)) != 0) { print_trapframe(tf); if (current == NULL) { panic("handle pgfault failed. ret=%d\n", ret); } else { if (trap_in_kernel(tf)) { panic("handle pgfault failed in kernel mode. ret=%d\n", ret); } cprintf("killed by kernel.\n"); panic("handle user mode pgfault failed. ret=%d\n", ret); do_exit(-E_KILLED); } } break; case T_SYSCALL: syscall(); break; case IRQ_OFFSET + IRQ_TIMER: #if 0 LAB3 : If some page replacement algorithm(such as CLOCK PRA) need tick to change the priority of pages, then you can add code here. #endif /* LAB1 YOUR CODE : STEP 3 */ /* handle the timer interrupt */ /* (1) After a timer interrupt, you should record this event using a global variable (increase it), such as ticks in kern/driver/clock.c * (2) Every TICK_NUM cycle, you can print some info using a funciton, such as print_ticks(). * (3) Too Simple? Yes, I think so! */ /* LAB5 YOUR CODE */ /* you should upate you lab1 code (just add ONE or TWO lines of code): * Every TICK_NUM cycle, you should set current process's current->need_resched = 1 */ /* LAB6 YOUR CODE */ /* you should upate you lab5 code * IMPORTANT FUNCTIONS: * sched_class_proc_tick */ ticks++; run_timer_list(current); break; case IRQ_OFFSET + IRQ_COM1: c = cons_getc(); cprintf("serial [%03d] %c\n", c, c); break; case IRQ_OFFSET + IRQ_KBD: c = cons_getc(); cprintf("kbd [%03d] %c\n", c, c); break; //LAB1 CHALLENGE 1 : YOUR CODE you should modify below codes. case T_SWITCH_TOU: if (tf->tf_cs != USER_CS) { switchk2u = *tf; switchk2u.tf_cs = USER_CS; switchk2u.tf_ds = switchk2u.tf_es = switchk2u.tf_ss = USER_DS; switchk2u.tf_esp = (uint32_t)tf + sizeof(struct trapframe) - 8; // set eflags, make sure ucore can use io under user mode. // if CPL > IOPL, then cpu will generate a general protection. switchk2u.tf_eflags |= FL_IOPL_MASK; // set temporary stack // then iret will jump to the right stack *((uint32_t *)tf - 1) = (uint32_t)&switchk2u; } break; case T_SWITCH_TOK: if (tf->tf_cs != KERNEL_CS) { tf->tf_cs = KERNEL_CS; tf->tf_ds = tf->tf_es = KERNEL_DS; tf->tf_eflags &= ~FL_IOPL_MASK; switchu2k = (struct trapframe *)(tf->tf_esp - (sizeof(struct trapframe) - 8)); memmove(switchu2k, tf, sizeof(struct trapframe) - 8); *((uint32_t *)tf - 1) = (uint32_t)switchu2k; } break; case IRQ_OFFSET + IRQ_IDE1: case IRQ_OFFSET + IRQ_IDE2: /* do nothing */ break; default: print_trapframe(tf); if (current != NULL) { cprintf("unhandled trap.\n"); do_exit(-E_KILLED); } // in kernel, it must be a mistake panic("unexpected trap in kernel.\n"); } }
/* >>> start tutorial code >>> */ int main( ){ USING_NAMESPACE_ACADO // INTRODUCE THE VARIABLES: // ------------------------- DifferentialState x , dx ; // the position of the mounting point and its velocity DifferentialState L , dL ; // the length of the cable and its velocity DifferentialState phi, dphi; // the angle phi and its velocity DifferentialState P0,P1,P2 ; // the variance-covariance states Control ddx, ddL ; // the accelarations Parameter T ; // duration of the maneuver Parameter gamma ; // the confidence level double const g = 9.81; // the gravitational constant double const m = 10.0; // the mass at the end of the crane double const b = 0.1 ; // a frictional constant DifferentialEquation f(0.0,T); const double F2 = 50.0; // DEFINE A DIFFERENTIAL EQUATION: // ------------------------------- f << dot(x ) == dx + 0.000001*gamma; // small regularization term f << dot(dx ) == ddx ; f << dot(L ) == dL ; f << dot(dL ) == ddL ; f << dot(phi ) == dphi; f << dot(dphi) == -(g/L)*phi - ( b + 2.0*dL/L )*dphi - ddx/L; f << dot(P0) == 2.0*P1; f << dot(P1) == -(g/L)*P0 - ( b + 2.0*dL/L )*P1 + P2; f << dot(P2) == -2.0*(g/L)*P1 - 2.0*( b + 2.0*dL/L )*P2 + F2/(m*m*L*L); // DEFINE AN OPTIMAL CONTROL PROBLEM: // ---------------------------------- OCP ocp( 0.0, T, 20 ); ocp.minimizeMayerTerm( 0, T ); ocp.minimizeMayerTerm( 1, -gamma ); ocp.subjectTo( f ); ocp.subjectTo( AT_START, x == 0.0 ); ocp.subjectTo( AT_START, dx == 0.0 ); ocp.subjectTo( AT_START, L == 70.0 ); ocp.subjectTo( AT_START, dL == 0.0 ); ocp.subjectTo( AT_START, phi == 0.0 ); ocp.subjectTo( AT_START, dphi == 0.0 ); ocp.subjectTo( AT_START, P0 == 0.0 ); ocp.subjectTo( AT_START, P1 == 0.0 ); ocp.subjectTo( AT_START, P2 == 0.0 ); ocp.subjectTo( AT_END , x == 10.0 ); ocp.subjectTo( AT_END , dx == 0.0 ); ocp.subjectTo( AT_END , L == 70.0 ); ocp.subjectTo( AT_END , dL == 0.0 ); ocp.subjectTo( AT_END , -0.075 <= phi - gamma*sqrt(P0) ); ocp.subjectTo( AT_END , phi + gamma*sqrt(P0) <= 0.075 ); ocp.subjectTo( gamma >= 0.0 ); ocp.subjectTo( 5.0 <= T <= 17.0 ); ocp.subjectTo( -0.3 <= ddx <= 0.3 ); ocp.subjectTo( -1.0 <= ddL <= 1.0 ); ocp.subjectTo( -10.0 <= x <= 50.0 ); ocp.subjectTo( -20.0 <= dx <= 20.0 ); ocp.subjectTo( 30.0 <= L <= 75.0 ); ocp.subjectTo( -20.0 <= dL <= 20.0 ); // DEFINE A MULTI-OBJECTIVE ALGORITHM AND SOLVE THE OCP: // ----------------------------------------------------- MultiObjectiveAlgorithm algorithm(ocp); algorithm.set( PARETO_FRONT_DISCRETIZATION, 31 ); algorithm.set( PARETO_FRONT_GENERATION, PFG_NORMALIZED_NORMAL_CONSTRAINT ); //algorithm.set( DISCRETIZATION_TYPE , SINGLE_SHOOTING ); // Minimize individual objective function algorithm.solveSingleObjective(0); // Minimize individual objective function algorithm.solveSingleObjective(1); // Generate Pareto set //algorithm.set( PARETO_FRONT_HOTSTART , BT_FALSE ); algorithm.solve(); algorithm.getWeights("crane_nnc_weights.txt"); algorithm.getAllDifferentialStates("crane_nnc_states.txt"); algorithm.getAllControls("crane_nnc_controls.txt"); algorithm.getAllParameters("crane_nnc_parameters.txt"); // GET THE RESULT FOR THE PARETO FRONT AND PLOT IT: // ------------------------------------------------ VariablesGrid paretoFront; algorithm.getParetoFront( paretoFront ); GnuplotWindow window1; window1.addSubplot( paretoFront, "Pareto Front (robustness versus time)", "TIME","ROBUSTNESS", PM_POINTS ); window1.plot( ); // PRINT INFORMATION ABOUT THE ALGORITHM: // -------------------------------------- algorithm.printInfo(); // SAVE INFORMATION: // ----------------- paretoFront.print( "crane_nnc_pareto.txt" );
int main( ){ USING_NAMESPACE_ACADO // INTRODUCE THE VARIABLES: // ------------------------ DifferentialState x; Control u; Disturbance w; // DEFINE A DIFFERENTIAL EQUATION: // ------------------------------- DifferentialEquation f, f2; f << dot(x) == -2.0*x + u; f2 << dot(x) == -2.0*x + u + 0.1*w; //- 0.000000000001*x*x // DEFINE LEAST SQUARE FUNCTION: // ----------------------------- Function h; h << x; h << u; Matrix Q(2,2); Q.setIdentity(); Vector r(2); r.setAll( 0.0 ); // DEFINE AN OPTIMAL CONTROL PROBLEM: // ---------------------------------- const double t_start = 0.0; const double t_end = 7.0; OCP ocp ( t_start, t_end, 14 ); ocp.minimizeLSQ( Q, h, r ); ocp.subjectTo ( f ); ocp.subjectTo( -1.0 <= u <= 2.0 ); //ocp.subjectTo( w == 0.0 ); // SETTING UP THE (SIMULATED) PROCESS: // ----------------------------------- OutputFcn identity; DynamicSystem dynamicSystem( f2,identity ); Process process( dynamicSystem,INT_RK45 ); VariablesGrid disturbance = fopen( "my_disturbance.txt", "r" ); // GnuplotWindow window2; // window2.addSubplot( disturbance, "my disturbance" ); // window2.plot(); process.setProcessDisturbance( disturbance ); // SETUP OF THE ALGORITHM AND THE TUNING OPTIONS: // ---------------------------------------------- double samplingTime = 0.5; RealTimeAlgorithm algorithm( ocp,samplingTime ); // // algorithm.set( HESSIAN_APPROXIMATION, BLOCK_BFGS_UPDATE ); algorithm.set( HESSIAN_APPROXIMATION, GAUSS_NEWTON ); // // // algorithm.set( ABSOLUTE_TOLERANCE , 1e-7 ); // // algorithm.set( INTEGRATOR_TOLERANCE, 1e-9 ); // // algorithm.set( KKT_TOLERANCE, 1e-4 ); algorithm.set( MAX_NUM_ITERATIONS,1 ); algorithm.set( USE_REALTIME_SHIFTS, YES ); // algorithm.set( USE_REALTIME_ITERATIONS,NO ); // algorithm.set( TERMINATE_AT_CONVERGENCE,YES ); // algorithm.set( PRINTLEVEL,HIGH ); Vector x0(1); x0(0) = 1.0; // // algorithm.solve( x0 ); // // GnuplotWindow window1; // window1.addSubplot( x, "DIFFERENTIAL STATE: x" ); // window1.addSubplot( u, "CONTROL: u" ); // window1.plot(); // // return 0; // SETTING UP THE NMPC CONTROLLER: // ------------------------------- VariablesGrid myReference = fopen( "my_reference.txt", "r" ); PeriodicReferenceTrajectory reference( myReference ); // GnuplotWindow window3; // window3.addSubplot( myReference(1), "my reference" ); // window3.plot(); Controller controller( algorithm,reference ); // SETTING UP THE SIMULATION ENVIRONMENT, RUN THE EXAMPLE... // ---------------------------------------------------------- double simulationStart = 0.0; double simulationEnd = 15.0; SimulationEnvironment sim( simulationStart, simulationEnd, process, controller ); sim.init( x0 ); sim.run( ); // ...AND PLOT THE RESULTS // ---------------------------------------------------------- VariablesGrid sampledProcessOutput; sim.getSampledProcessOutput( sampledProcessOutput ); VariablesGrid feedbackControl; sim.getFeedbackControl( feedbackControl ); GnuplotWindow window; window.addSubplot( sampledProcessOutput(0), "DIFFERENTIAL STATE: x" ); window.addSubplot( feedbackControl(0), "CONTROL: u" ); window.plot(); return 0; }
/* >>> start tutorial code >>> */ int main( ){ USING_NAMESPACE_ACADO // INTRODUCE THE VARIABLES: // ------------------------------------ DifferentialState v,s,m; Control u ; const double t_start = 0.0; const double t_end = 10.0; const double h = 0.01; DiscretizedDifferentialEquation f(h) ; // DEFINE A DISCRETE-TIME SYTSEM: // ------------------------------- f << next(s) == s + h*v; f << next(v) == v + h*(u-0.02*v*v)/m; f << next(m) == m - h*0.01*u*u; Function eta; eta << u; // DEFINE AN OPTIMAL CONTROL PROBLEM: // ---------------------------------- OCP ocp( t_start, t_end, 50 ); //ocp.minimizeLagrangeTerm( u*u ); ocp.minimizeLSQ( eta ); ocp.subjectTo( f ); ocp.subjectTo( AT_START, s == 0.0 ); ocp.subjectTo( AT_START, v == 0.0 ); ocp.subjectTo( AT_START, m == 1.0 ); ocp.subjectTo( AT_END , s == 10.0 ); ocp.subjectTo( AT_END , v == 0.0 ); ocp.subjectTo( -0.01 <= v <= 1.3 ); // DEFINE A PLOT WINDOW: // --------------------- GnuplotWindow window; window.addSubplot( s,"DifferentialState s" ); window.addSubplot( v,"DifferentialState v" ); window.addSubplot( m,"DifferentialState m" ); window.addSubplot( u,"Control u" ); window.addSubplot( PLOT_KKT_TOLERANCE,"KKT Tolerance" ); window.addSubplot( 0.5 * m * v*v,"Kinetic Energy" ); // DEFINE AN OPTIMIZATION ALGORITHM AND SOLVE THE OCP: // --------------------------------------------------- OptimizationAlgorithm algorithm(ocp); algorithm.set( INTEGRATOR_TYPE, INT_DISCRETE ); algorithm.set( HESSIAN_APPROXIMATION, EXACT_HESSIAN ); algorithm.set( KKT_TOLERANCE, 1e-10 ); algorithm << window; algorithm.solve(); return 0; }
/* >>> start tutorial code >>> */ int main( ){ USING_NAMESPACE_ACADO // INTRODUCE THE VARIABLES: // ---------------------------- DifferentialState x(10); // a differential state vector with dimension 10. (vector) DifferentialState y ; // another differential state y (scalar) Control u(2 ); // a control input with dimension 2. (vector) Parameter p ; // a parameter (here a scalar). (scalar) DifferentialEquation f ; // the differential equation const double t_start = 0.0; const double t_end = 1.0; // READ A MATRIX "A" FROM A FILE: // ------------------------------ Matrix A = readFromFile( "matrix_vector_ocp_A.txt" ); Matrix B = readFromFile( "matrix_vector_ocp_B.txt" ); // READ A VECTOR "x0" FROM A FILE: // ------------------------------- Vector x0 = readFromFile( "matrix_vector_ocp_x0.txt" ); // DEFINE A DIFFERENTIAL EQUATION: // ------------------------------- f << dot(x) == -(A*x) + B*u; // matrix vector notation for a linear equation f << dot(y) == x.transpose()*x + 2.0*u.transpose()*u; // matrix vector notation: x^x = scalar product = ||x||_2^2 // u^u = scalar product = ||u||_2^2 // DEFINE AN OPTIMAL CONTROL PROBLEM: // ---------------------------------- OCP ocp( t_start, t_end, 20 ); ocp.minimizeMayerTerm( y ); ocp.subjectTo( f ); ocp.subjectTo( AT_START, x == x0 ); ocp.subjectTo( AT_START, y == 0.0 ); GnuplotWindow window; window.addSubplot( x(0),"x0" ); window.addSubplot( x(6),"x6" ); window.addSubplot( u(0),"u0" ); window.addSubplot( u(1),"u1" ); // DEFINE AN OPTIMIZATION ALGORITHM AND SOLVE THE OCP: // --------------------------------------------------- OptimizationAlgorithm algorithm(ocp); algorithm.set( MAX_NUM_ITERATIONS, 20 ); algorithm.set( KKT_TOLERANCE, 1e-10 ); algorithm << window; algorithm.solve(); return 0; }
int main( ){ USING_NAMESPACE_ACADO // DEFINE SAMPLE OCP // ----------------- DifferentialState x, y; Control u; DifferentialEquation f; f << dot(x) == y; f << dot(y) == u; OCP ocp( 0.0, 5.0 ); ocp.minimizeLagrangeTerm( x*x + 0.01*u*u ); ocp.subjectTo( f ); ocp.subjectTo( AT_START, x == 1.0 ); ocp.subjectTo( AT_START, y == 0.0 ); ocp.subjectTo( -1.0 <= u <= 1.0 ); // SETUP OPTIMIZATION ALGORITHM AND DEFINE VARIOUS PLOT WINDOWS // ------------------------------------------------------------ OptimizationAlgorithm algorithm( ocp ); GnuplotWindow window1; window1.addSubplot( x, "1st state" ); window1.addSubplot( y, "2nd state","x label","y label",PM_POINTS ); window1.addSubplot( u, "control input","x label","y label",PM_LINES,0,5,-2,2 ); window1.addSubplot( 2.0*sin(x)+y*u, "Why not plotting fancy stuff!?" ); // window1.addSubplot( PLOT_KKT_TOLERANCE, "","iteration","KKT tolerance" ); GnuplotWindow window2( PLOT_AT_EACH_ITERATION ); window2.addSubplot( x, "1st state evolving..." ); algorithm << window1; algorithm << window2; algorithm.solve( ); // For illustration, an alternative way to plot differential states // in form of a VariablesGrid VariablesGrid states; algorithm.getDifferentialStates( states ); GnuplotWindow window3; window3.addSubplot( states(0), "1st state obtained as VariablesGrid" ); window3.addSubplot( states(1), "2nd state obtained as VariablesGrid" ); window3.plot(); VariablesGrid data( 1, 0.0,10.0,11 ); data.setZero(); data( 2,0 ) = 1.0; data( 5,0 ) = -1.0; data( 8,0 ) = 2.0; data( 9,0 ) = 2.0; // data.setType( VT_CONTROL ); GnuplotWindow window4; window4.addSubplot( data, "Any data can be plotted" ); window4.plot(); return 0; }
int main( ){ USING_NAMESPACE_ACADO // INTRODUCE FIXED PARAMETERS: // --------------------------- #define Csin 2.8 // INTRODUCE THE VARIABLES: // ------------------------- DifferentialState x1,x2,x3,x4,x5; IntermediateState mu,sigma,pif; Control u ; Parameter tf ; DifferentialEquation f(0.0,tf) ; // DEFINE A DIFFERENTIAL EQUATION: // ------------------------------- mu = 0.125*x2/x4; sigma = mu/0.135; pif = (-384.0*mu*mu + 134.0*mu); f << dot(x1) == mu*x1; f << dot(x2) == -sigma*x1 + u*Csin; f << dot(x3) == pif*x1; f << dot(x4) == u; f << dot(x5) == 0.001*(u*u + 0.01*tf*tf); // DEFINE AN OPTIMAL CONTROL PROBLEM: // ---------------------------------- OCP ocp( 0.0, tf, 50 ); ocp.minimizeMayerTerm(0, 0.01*x5 -x3/tf ); // Solve productivity optimal problem (Note: - due to maximization, small regularisation term) ocp.minimizeMayerTerm(1, 0.01*x5 -x3/(Csin*x4-x2)); // Solve yield optimal problem (Note: Csin = x2(t=0)/x4(t=0); - due to maximization, small regularisation term) ocp.subjectTo( f ); ocp.subjectTo( AT_START, x1 == 0.1 ); ocp.subjectTo( AT_START, x2 == 14.0 ); ocp.subjectTo( AT_START, x3 == 0.0 ); ocp.subjectTo( AT_START, x4 == 5.0 ); ocp.subjectTo( AT_START, x5 == 0.0 ); ocp.subjectTo( 0.0 <= x1 <= 15.0 ); ocp.subjectTo( 0.0 <= x2 <= 30.0 ); ocp.subjectTo( -0.1 <= x3 <= 1000.0 ); ocp.subjectTo( 5.0 <= x4 <= 20.0 ); ocp.subjectTo( 20.0 <= tf <= 40.0 ); ocp.subjectTo( 0.0 <= u <= 2.0 ); // DEFINE A MULTI-OBJECTIVE ALGORITHM AND SOLVE THE OCP: // ----------------------------------------------------- MultiObjectiveAlgorithm algorithm(ocp); algorithm.set( PARETO_FRONT_DISCRETIZATION, 21 ); algorithm.set( PARETO_FRONT_GENERATION , PFG_NORMAL_BOUNDARY_INTERSECTION ); algorithm.set( HESSIAN_APPROXIMATION, EXACT_HESSIAN ); algorithm.set( KKT_TOLERANCE, 1e-7 ); // Minimize individual objective function algorithm.solveSingleObjective(0); // Minimize individual objective function algorithm.solveSingleObjective(1); // Generate Pareto set algorithm.set( KKT_TOLERANCE, 1e-6 ); algorithm.solve(); algorithm.getWeights("fed_batch_bioreactor_nbi_weights.txt"); algorithm.getAllDifferentialStates("fed_batch_bioreactor_nbi_states.txt"); algorithm.getAllControls("fed_batch_bioreactor_nbi_controls.txt"); algorithm.getAllParameters("fed_batch_bioreactor_nbi_parameters.txt"); // VISUALIZE THE RESULTS IN A GNUPLOT WINDOW: // ------------------------------------------ VariablesGrid paretoFront; algorithm.getParetoFront( paretoFront ); GnuplotWindow window1; window1.addSubplot( paretoFront, "Pareto Front (yield versus productivity)", "-PRODUCTIVTY", "-YIELD", PM_POINTS ); window1.plot( ); // PRINT INFORMATION ABOUT THE ALGORITHM: // -------------------------------------- algorithm.printInfo(); // SAVE INFORMATION: // ----------------- FILE *file = fopen("fed_batch_bioreactor_nbi_pareto.txt","w"); paretoFront.print(); file << paretoFront; fclose(file); return 0; }
USING_NAMESPACE_ACADO int main( ) { // DIFFERENTIAL STATES : // ------------------------- DifferentialState r; // the length r of the cable DifferentialState phi; // the angle phi DifferentialState theta; // the angle theta (grosser wert- naeher am boden/kleiner wert - weiter oben) // ------------------------- // ------------------------------------------- DifferentialState dr; // first derivative of r0 with respect to t DifferentialState dphi; // first derivative of phi with respect to t DifferentialState dtheta; // first derivative of theta with respect to t // ------------------------- // ------------------------------------------- DifferentialState n; // winding number(rauslassen) // ------------------------- // ------------------------------------------- DifferentialState Psi; // the roll angle Psi DifferentialState CL; // the aerodynamic lift coefficient // ------------------------- // ------------------------------------------- DifferentialState W; // integral over the power at the generator // ( = ENERGY )(rauslassen) // MEASUREMENT FUNCTION : // ------------------------- Function model_response ; // the measurement function // CONTROL : // ------------------------- Control ddr0; // second derivative of r0 with respect to t Control dPsi; // first derivative of Psi with respect to t Control dCL; // first derivative of CL with respect to t Disturbance w_extra; // PARAMETERS : // ------------------------ // PARAMETERS OF THE KITE : // ----------------------------- double mk = 2000.00; // mass of the kite // [ kg ](maybe change to 5000kg) double A = 500.00; // effective area // [ m^2 ] double V = 720.00; // volume // [ m^3 ] double cd0 = 0.04; // aerodynamic drag coefficient // [ ] // ( cd0: without downwash ) double K = 0.04; // induced drag constant // [ ] // PHYSICAL CONSTANTS : // ----------------------------- double g = 9.81; // gravitational constant // [ m /s^2] double rho = 1.23; // density of the air // [ kg/m^3] // PARAMETERS OF THE CABLE : // ----------------------------- double rhoc = 1450.00; // density of the cable // [ kg/m^3] double cc = 1.00; // frictional constant // [ ] double dc = 0.05614; // diameter // [ m ] // PARAMETERS OF THE WIND : // ----------------------------- double w0 = 10.00; // wind velocity at altitude h0 // [ m/s ] double h0 = 100.00; // the altitude h0 // [ m ] double hr = 0.10; // roughness length // [ m ] // OTHER VARIABLES : // ------------------------ double AQ ; // cross sectional area IntermediateState mc; // mass of the cable IntermediateState m ; // effective inertial mass IntermediateState m_; // effective gravitational mass IntermediateState Cg; IntermediateState dm; // first derivative of m with respect to t // DEFINITION OF PI : // ------------------------ double PI = 3.1415926535897932; // ORIENTATION AND FORCES : // ------------------------ IntermediateState h ; // altitude of the kite IntermediateState w ; // the wind at altitude h IntermediateState we [ 3]; // effective wind vector IntermediateState nwe ; // norm of the effective wind vector IntermediateState nwep ; // - IntermediateState ewep [ 3]; // projection of ewe IntermediateState eta ; // angle eta: cf. [2] IntermediateState et [ 3]; // unit vector from the left to the right wing tip IntermediateState Caer ; IntermediateState Cf ; // simple constants IntermediateState CD ; // the aerodynamic drag coefficient IntermediateState Fg [ 3]; // the gravitational force IntermediateState Faer [ 3]; // the aerodynamic force IntermediateState Ff [ 3]; // the frictional force IntermediateState F [ 3]; // the total force // TERMS ON RIGHT-HAND-SIDE // OF THE DIFFERENTIAL // EQUATIONS : // ------------------------ IntermediateState a_pseudo [ 3]; // the pseudo accelaration IntermediateState dn ; // the time derivate of the kite's winding number IntermediateState ddr ; // second derivative of s with respect to t IntermediateState ddphi ; // second derivative of phi with respect to t IntermediateState ddtheta ; // second derivative of theta with respect to t IntermediateState power ; // the power at the generator // ------------------------ ------ // ---------------------------------------------- IntermediateState regularisation ; // regularisation of controls // MODEL EQUATIONS : // =============================================================== // SPRING CONSTANT OF THE CABLE : // --------------------------------------------------------------- AQ = PI*dc*dc/4.0 ; // THE EFECTIVE MASS' : // --------------------------------------------------------------- mc = rhoc*AQ*r ; // mass of the cable m = mk + mc / 3.0; // effective inertial mass m_ = mk + mc / 2.0; // effective gravitational mass // ----------------------------- // ---------------------------- dm = (rhoc*AQ/ 3.0)*dr; // time derivative of the mass // WIND SHEAR MODEL : // --------------------------------------------------------------- // for startup +60m h = r*cos(theta)+60.0 ; // h = r*cos(theta) ; w = log(h/hr) / log(h0/hr) *(w0+w_extra) ; // EFFECTIVE WIND IN THE KITE`S SYSTEM : // --------------------------------------------------------------- we[0] = w*sin(theta)*cos(phi) - dr ; we[1] = -w*sin(phi) - r*sin(theta)*dphi ; we[2] = -w*cos(theta)*cos(phi) + r *dtheta; // CALCULATION OF THE KITE`S TRANSVERSAL AXIS : // --------------------------------------------------------------- nwep = pow( we[1]*we[1] + we[2]*we[2], 0.5 ); nwe = pow( we[0]*we[0] + we[1]*we[1] + we[2]*we[2], 0.5 ); eta = asin( we[0]*tan(Psi)/ nwep ) ; // --------------------------------------------------------------- // ewep[0] = 0.0 ; ewep[1] = we[1] / nwep ; ewep[2] = we[2] / nwep ; // --------------------------------------------------------------- et [0] = sin(Psi) ; et [1] = (-cos(Psi)*sin(eta))*ewep[1] - (cos(Psi)*cos(eta))*ewep[2]; et [2] = (-cos(Psi)*sin(eta))*ewep[2] + (cos(Psi)*cos(eta))*ewep[1]; // CONSTANTS FOR SEVERAL FORCES : // --------------------------------------------------------------- Cg = (V*rho-m_)*g ; Caer = (rho*A/2.0 )*nwe ; Cf = (rho*dc/8.0)*r*nwe ; // THE DRAG-COEFFICIENT : // --------------------------------------------------------------- CD = cd0 + K*CL*CL ; // SUM OF GRAVITATIONAL AND LIFTING FORCE : // --------------------------------------------------------------- Fg [0] = Cg * cos(theta) ; // Fg [1] = Cg * 0.0 ; Fg [2] = Cg * sin(theta) ; // SUM OF THE AERODYNAMIC FORCES : // --------------------------------------------------------------- Faer[0] = Caer*( CL*(we[1]*et[2]-we[2]*et[1]) + CD*we[0] ) ; Faer[1] = Caer*( CL*(we[2]*et[0]-we[0]*et[2]) + CD*we[1] ) ; Faer[2] = Caer*( CL*(we[0]*et[1]-we[1]*et[0]) + CD*we[2] ) ; // THE FRICTION OF THE CABLE : // --------------------------------------------------------------- // Ff [0] = Cf * cc* we[0] ; Ff [1] = Cf * cc* we[1] ; Ff [2] = Cf * cc* we[2] ; // THE TOTAL FORCE : // --------------------------------------------------------------- F [0] = Fg[0] + Faer[0] ; F [1] = Faer[1] + Ff[1] ; F [2] = Fg[2] + Faer[2] + Ff[2] ; // THE PSEUDO ACCELERATION: // --------------------------------------------------------------- a_pseudo [0] = - ddr0 + r*( dtheta*dtheta + sin(theta)*sin(theta)*dphi *dphi ) - dm/m*dr ; a_pseudo [1] = - 2.0*cos(theta)/sin(theta)*dphi*dtheta - 2.0*dr/r*dphi - dm/m*dphi ; a_pseudo [2] = cos(theta)*sin(theta)*dphi*dphi - 2.0*dr/r*dtheta - dm/m*dtheta ; // THE EQUATIONS OF MOTION: // --------------------------------------------------------------- ddr = F[0]/m + a_pseudo[0] ; ddphi = F[1]/(m*r*sin(theta)) + a_pseudo[1] ; ddtheta = -F[2]/(m*r ) + a_pseudo[2] ; // THE DERIVATIVE OF THE WINDING NUMBER : // --------------------------------------------------------------- dn = ( dphi*ddtheta - dtheta*ddphi ) / (2.0*PI*(dphi*dphi + dtheta*dtheta) ) ; // THE POWER AT THE GENERATOR : // --------------------------------------------------------------- power = m*ddr*dr ; // REGULARISATION TERMS : // --------------------------------------------------------------- regularisation = 5.0e2 * ddr0 * ddr0 + 1.0e8 * dPsi * dPsi + 1.0e5 * dCL * dCL + 2.5e5 * dn * dn + 2.5e7 * ddphi * ddphi; + 2.5e7 * ddtheta * ddtheta; + 2.5e6 * dtheta * dtheta; // --------------------------- // REFERENCE TRAJECTORY: // --------------------------------------------------------------- VariablesGrid myReference; myReference.read( "ref_w_zeros.txt" );// read the measurements PeriodicReferenceTrajectory reference( myReference ); // THE "RIGHT-HAND-SIDE" OF THE ODE: // --------------------------------------------------------------- DifferentialEquation f; f << dot(r) == dr ; f << dot(phi) == dphi ; f << dot(theta) == dtheta ; f << dot(dr) == ddr0 ; f << dot(dphi) == ddphi ; f << dot(dtheta) == ddtheta ; f << dot(n) == dn ; f << dot(Psi) == dPsi ; f << dot(CL) == dCL ; f << dot(W) == (-power + regularisation)*1.0e-6; model_response << r ; // the state r is measured model_response << phi ; model_response << theta; model_response << dr ; model_response << dphi ; model_response << dtheta; model_response << ddr0; model_response << dPsi; model_response << dCL ; DVector x_scal(9); x_scal(0) = 60.0; x_scal(1) = 1.0e-1; x_scal(2) = 1.0e-1; x_scal(3) = 40.0; x_scal(4) = 1.0e-1; x_scal(5) = 1.0e-1; x_scal(6) = 60.0; x_scal(7) = 1.5e-1; x_scal(8) = 2.5; DMatrix Q(9,9); Q.setIdentity(); DMatrix Q_end(9,9); Q_end.setIdentity(); int i; for( i = 0; i < 6; i++ ){ Q(i,i) = (1.0e-1/x_scal(i))*(1.0e-1/x_scal(i)); Q_end(i,i) = (5.0e-1/x_scal(i))*(5.0e-1/x_scal(i)); } for( i = 6; i < 9; i++ ){ Q(i,i) = (1.0e-1/x_scal(i))*(1.0e-1/x_scal(i)); Q_end(i,i) = (5.0e-1/x_scal(i))*(5.0e-1/x_scal(i)); } DVector measurements(9); measurements.setAll( 0.0 ); // DEFINE AN OPTIMAL CONTROL PROBLEM: // ---------------------------------- const double t_start = 0.0; const double t_end = 10.0; OCP ocp( t_start, t_end, 10 ); ocp.minimizeLSQ( Q,model_response, measurements ) ; // fit h to the data ocp.minimizeLSQEndTerm( Q_end,model_response, measurements ) ; ocp.subjectTo( f ); ocp.subjectTo( -0.34 <= phi <= 0.34 ); ocp.subjectTo( 0.85 <= theta <= 1.45 ); ocp.subjectTo( -40.0 <= dr <= 10.0 ); ocp.subjectTo( -0.29 <= Psi <= 0.29 ); ocp.subjectTo( 0.1 <= CL <= 1.50 ); ocp.subjectTo( -0.7 <= n <= 0.90 ); ocp.subjectTo( -25.0 <= ddr0 <= 25.0 ); ocp.subjectTo( -0.065 <= dPsi <= 0.065 ); ocp.subjectTo( -3.5 <= dCL <= 3.5 ); ocp.subjectTo( -60.0 <= cos(theta)*r ); ocp.subjectTo( w_extra == 0.0 ); // SETTING UP THE (SIMULATED) PROCESS: // ----------------------------------- OutputFcn identity; DynamicSystem dynamicSystem( f,identity ); Process process( dynamicSystem,INT_RK45 ); VariablesGrid disturbance; disturbance.read( "my_wind_disturbance_controlsfree.txt" ); if (process.setProcessDisturbance( disturbance ) != SUCCESSFUL_RETURN) exit( EXIT_FAILURE ); // SETUP OF THE ALGORITHM AND THE TUNING OPTIONS: // ---------------------------------------------- double samplingTime = 1.0; RealTimeAlgorithm algorithm( ocp, samplingTime ); if (algorithm.initializeDifferentialStates("p_s_ref.txt" ) != SUCCESSFUL_RETURN) exit( EXIT_FAILURE ); if (algorithm.initializeControls ("p_c_ref.txt" ) != SUCCESSFUL_RETURN) exit( EXIT_FAILURE ); algorithm.set( MAX_NUM_ITERATIONS, 2 ); algorithm.set( KKT_TOLERANCE , 1e-4 ); algorithm.set( HESSIAN_APPROXIMATION,GAUSS_NEWTON); algorithm.set( INTEGRATOR_TOLERANCE, 1e-6 ); algorithm.set( GLOBALIZATION_STRATEGY,GS_FULLSTEP ); // algorithm.set( USE_IMMEDIATE_FEEDBACK, YES ); algorithm.set( USE_REALTIME_SHIFTS, YES ); algorithm.set(LEVENBERG_MARQUARDT, 1e-5); DVector x0(10); x0(0) = 1.8264164528775887e+03; x0(1) = -5.1770453309520573e-03; x0(2) = 1.2706440287266794e+00; x0(3) = 2.1977888424944396e+00; x0(4) = 3.1840786108641383e-03; x0(5) = -3.8281200674676448e-02; x0(6) = 0.0000000000000000e+00; x0(7) = -1.0372313936413566e-02; x0(8) = 1.4999999999999616e+00; x0(9) = 0.0000000000000000e+00; // SETTING UP THE NMPC CONTROLLER: // ------------------------------- Controller controller( algorithm, reference ); // SETTING UP THE SIMULATION ENVIRONMENT, RUN THE EXAMPLE... // ---------------------------------------------------------- double simulationStart = 0.0; double simulationEnd = 10.0; SimulationEnvironment sim( simulationStart, simulationEnd, process, controller ); if (sim.init( x0 ) != SUCCESSFUL_RETURN) exit( EXIT_FAILURE ); if (sim.run( ) != SUCCESSFUL_RETURN) exit( EXIT_FAILURE ); // ...AND PLOT THE RESULTS // ---------------------------------------------------------- VariablesGrid diffStates; sim.getProcessDifferentialStates( diffStates ); diffStates.print( "diffStates.txt" ); diffStates.print( "diffStates.m","DIFFSTATES",PS_MATLAB ); VariablesGrid interStates; sim.getProcessIntermediateStates( interStates ); interStates.print( "interStates.txt" ); interStates.print( "interStates.m","INTERSTATES",PS_MATLAB ); VariablesGrid sampledProcessOutput; sim.getSampledProcessOutput( sampledProcessOutput ); sampledProcessOutput.print( "sampledOut.txt" ); sampledProcessOutput.print( "sampledOut.m","OUT",PS_MATLAB ); VariablesGrid feedbackControl; sim.getFeedbackControl( feedbackControl ); feedbackControl.print( "controls.txt" ); feedbackControl.print( "controls.m","CONTROL",PS_MATLAB ); GnuplotWindow window; window.addSubplot( sampledProcessOutput(0), "DIFFERENTIAL STATE: r" ); window.addSubplot( sampledProcessOutput(1), "DIFFERENTIAL STATE: phi" ); window.addSubplot( sampledProcessOutput(2), "DIFFERENTIAL STATE: theta" ); window.addSubplot( sampledProcessOutput(3), "DIFFERENTIAL STATE: dr" ); window.addSubplot( sampledProcessOutput(4), "DIFFERENTIAL STATE: dphi" ); window.addSubplot( sampledProcessOutput(5), "DIFFERENTIAL STATE: dtheta" ); window.addSubplot( sampledProcessOutput(7), "DIFFERENTIAL STATE: Psi" ); window.addSubplot( sampledProcessOutput(8), "DIFFERENTIAL STATE: CL" ); window.addSubplot( sampledProcessOutput(9), "DIFFERENTIAL STATE: W" ); window.addSubplot( feedbackControl(0), "CONTROL 1 DDR0" ); window.addSubplot( feedbackControl(1), "CONTROL 1 DPSI" ); window.addSubplot( feedbackControl(2), "CONTROL 1 DCL" ); window.plot( ); GnuplotWindow window2; window2.addSubplot( interStates(1) ); window2.plot(); return 0; }
static void trap_dispatch(struct trapframe *tf) { char c; int ret; static int counter = 0; switch (tf->tf_trapno) { case T_PGFLT: //page fault if ((ret = pgfault_handler(tf)) != 0) { print_trapframe(tf); panic("handle pgfault failed. %e\n", ret); } break; case IRQ_OFFSET + IRQ_TIMER: #if 0 LAB3 : If some page replacement algorithm(such as CLOCK PRA) need tick to change the priority of pages, then you can add code here. #endif /* LAB1 2010011358: STEP 3 */ /* handle the timer interrupt */ /* (1) After a timer interrupt, you should record this event using a global variable (increase it), such as ticks in kern/driver/clock.c * (2) Every TICK_NUM cycle, you can print some info using a funciton, such as print_ticks(). * (3) Too Simple? Yes, I think so! */ if (++counter == TICK_NUM){ counter = 0; print_ticks(); } break; case IRQ_OFFSET + IRQ_COM1: c = cons_getc(); cprintf("serial [%03d] %c\n", c, c); break; case IRQ_OFFSET + IRQ_KBD: c = cons_getc(); cprintf("kbd [%03d] %c\n", c, c); break; //LAB1 CHALLENGE 1 : YOUR CODE you should modify below codes. case T_SWITCH_TOU: asm volatile( "cli;"); tf->tf_ds = 0x23; tf->tf_es = 0x23; tf->tf_fs = 0x23; tf->tf_gs = 0x23; tf->tf_eflags = tf->tf_eflags | 0x200; tf->tf_eflags = tf->tf_eflags | 0x3000; tf->tf_ss = 0x23; tf->tf_cs = 0x1B; tf->tf_esp = tf->tf_regs.reg_eax; break; case T_SWITCH_TOK: asm volatile( "cli;"); tf->tf_ds = 0x10; tf->tf_es = 0x10; tf->tf_fs = 0x10; tf->tf_gs = 0x10; tf->tf_eflags = tf->tf_eflags | 0x200; tf->tf_eflags = tf->tf_eflags & ~0x3000U | 0x1000U; tf->tf_ss = 0x10; tf->tf_cs = 0x8; break; case IRQ_OFFSET + IRQ_IDE1: case IRQ_OFFSET + IRQ_IDE2: /* do nothing */ break; default: // in kernel, it must be a mistake if ((tf->tf_cs & 3) == 0) { print_trapframe(tf); panic("unexpected trap in kernel.\n"); } } }
int main() { algorithm(); return 0; }
// this function should map from 0..M_PI * 2 -> -1..1 void EFX::calculatePoint(float iterator, float* x, float* y) const { switch (algorithm()) { default: case Circle: *x = cos(iterator + M_PI_2); *y = cos(iterator); break; case Eight: *x = cos((iterator * 2) + M_PI_2); *y = cos(iterator); break; case Line: *x = cos(iterator); *y = cos(iterator); break; case Line2: *x = iterator / M_PI - 1; *y = iterator / M_PI - 1; break; case Diamond: *x = pow(cos(iterator - M_PI_2), 3); *y = pow(cos(iterator), 3); break; case Square: if (iterator < M_PI / 2) { *x = (iterator * 2 / M_PI) * 2 - 1; *y = 1; } else if (M_PI / 2 <= iterator && iterator < M_PI) { *x = 1; *y = (1 - (iterator - M_PI / 2) * 2 / M_PI) * 2 - 1; } else if (M_PI <= iterator && iterator < M_PI * 3 / 2) { *x = (1 - (iterator - M_PI) * 2 / M_PI) * 2 - 1; *y = -1; } else // M_PI * 3 / 2 <= iterator { *x = -1; *y = ((iterator - M_PI * 3 / 2) * 2 / M_PI) * 2 - 1; } break; case SquareChoppy: *x = round(cos(iterator)); *y = round(sin(iterator)); break; case Leaf: *x = pow(cos(iterator + M_PI_2), 5); *y = cos(iterator); break; case Lissajous: { if (m_xFrequency > 0) *x = cos((m_xFrequency * iterator) - m_xPhase); else { float iterator0 = ((iterator + m_xPhase) / M_PI); int fff = iterator0; iterator0 -= (fff - fff % 2); float forward = 1 - floor(iterator0); // 1 when forward float backward = 1 - forward; // 1 when backward iterator0 = iterator0 - floor(iterator0); *x = (forward * iterator0 + backward * (1 - iterator0)) * 2 - 1; } if (m_yFrequency > 0) *y = cos((m_yFrequency * iterator) - m_yPhase); else { float iterator0 = ((iterator + m_yPhase) / M_PI); int fff = iterator0; iterator0 -= (fff - fff % 2); float forward = 1 - floor(iterator0); // 1 when forward float backward = 1 - forward; // 1 when backward iterator0 = iterator0 - floor(iterator0); *y = (forward * iterator0 + backward * (1 - iterator0)) * 2 - 1; } } break; } rotateAndScale(x, y); }
virtual void reply(msg const& m) { flags |= flag_done; static_cast<direct_traversal*>(algorithm())->invoke_cb(m); }
static void trap_dispatch(struct trapframe *tf) { char c; int ret = 0; switch (tf->tf_trapno) { case T_PGFLT: //page fault if ((ret = pgfault_handler(tf)) != 0) { print_trapframe(tf); if (current == NULL) { panic("handle pgfault failed. ret=%d\n", ret); } else { if (trap_in_kernel(tf)) { panic("handle pgfault failed in kernel mode. ret=%d\n", ret); } cprintf("killed by kernel.\n"); panic("handle user mode pgfault failed. ret=%d\n", ret); do_exit(-E_KILLED); } } break; case T_SYSCALL: if (tf->tf_regs.reg_eax != SYS_putc) { cprintf("!!!syscall eax:%d\n", tf->tf_regs.reg_eax); // print_trapframe(tf); } syscall(); break; case IRQ_OFFSET + IRQ_TIMER: #if 0 LAB3 : If some page replacement algorithm(such as CLOCK PRA) need tick to change the priority of pages, then you can add code here. #endif /* LAB1 YOUR CODE : STEP 3 */ /* handle the timer interrupt */ /* (1) After a timer interrupt, you should record this event using a global variable (increase it), such as ticks in kern/driver/clock.c * (2) Every TICK_NUM cycle, you can print some info using a funciton, such as print_ticks(). * (3) Too Simple? Yes, I think so! */ /* LAB5 YOUR CODE */ /* you should upate you lab1 code (just add ONE or TWO lines of code): * Every TICK_NUM cycle, you should set current process's current->need_resched = 1 */ ticks ++; if (ticks % TICK_NUM == 0) { assert(current != NULL); current->need_resched = 1; } break; case IRQ_OFFSET + IRQ_COM1: c = cons_getc(); cprintf("serial [%03d] %c\n", c, c); break; case IRQ_OFFSET + IRQ_KBD: c = cons_getc(); cprintf("kbd [%03d] %c\n", c, c); break; //LAB1 CHALLENGE 1 : YOUR CODE you should modify below codes. case T_SWITCH_TOU: case T_SWITCH_TOK: panic("T_SWITCH_** ??\n"); break; case IRQ_OFFSET + IRQ_IDE1: case IRQ_OFFSET + IRQ_IDE2: /* do nothing */ break; default: print_trapframe(tf); if (current != NULL) { cprintf("unhandled trap.\n"); do_exit(-E_KILLED); } // in kernel, it must be a mistake panic("unexpected trap in kernel.\n"); } }
/** \brief Get the (integer) input arguments of an atomic operation */ std::pair<int,int> getAtomicInput(int k) const{ const int* i = algorithm().at(k).arg.i; return std::pair<int,int>(i[0],i[1]);}