void IOVector3D::Write(MdfStream& fd, Vector3D* vector, Version* version, MgTab& tab) { _ASSERT(NULL != vector); fd << tab.tab() << startStr(sViewDirection) << std::endl; tab.inctab(); // Property: X fd << tab.tab() << startStr(sX); fd << DoubleToStr(vector->GetX()); fd << endStr(sX) << std::endl; // Property: Y fd << tab.tab() << startStr(sY); fd << DoubleToStr(vector->GetY()); fd << endStr(sY) << std::endl; // Property: Z fd << tab.tab() << startStr(sZ); fd << DoubleToStr(vector->GetZ()); fd << endStr(sZ) << std::endl; tab.dectab(); fd << tab.tab() << endStr(sViewDirection) << std::endl; }
void IOPoint3D::Write(MdfStream& fd, Point3D* point, Version* version, const std::string& name, MgTab& tab) { _ASSERT(NULL != point); fd << tab.tab() << startStr(name) << std::endl; tab.inctab(); // Property: X fd << tab.tab() << startStr(sX); fd << DoubleToStr(point->GetX()); fd << endStr(sX) << std::endl; // Property: Y fd << tab.tab() << startStr(sY); fd << DoubleToStr(point->GetY()); fd << endStr(sY) << std::endl; // Property: Z fd << tab.tab() << startStr(sZ); fd << DoubleToStr(point->GetZ()); fd << endStr(sZ) << std::endl; tab.dectab(); fd << tab.tab() << endStr(name) << std::endl; }
void Frame::ToJson(Json::Value &jsonObj, Frame *f, Space *space) { Json::Value frameObj(Json::objectValue); // Create JSON object to contain frame data. frameObj["flags"] = f->m_flags; frameObj["radius"] = DoubleToStr(f->m_radius); frameObj["label"] = f->m_label; VectorToJson(frameObj, f->m_pos, "pos"); frameObj["ang_speed"] = DoubleToStr(f->m_angSpeed); MatrixToJson(frameObj, f->m_initialOrient, "init_orient"); frameObj["index_for_system_body"] = space->GetIndexForSystemBody(f->m_sbody); frameObj["index_for_astro_body"] = space->GetIndexForBody(f->m_astroBody); Json::Value childFrameArray(Json::arrayValue); // Create JSON array to contain child frame data. for (Frame* kid : f->GetChildren()) { Json::Value childFrameArrayEl(Json::objectValue); // Create JSON object to contain child frame. Frame::ToJson(childFrameArrayEl, kid, space); childFrameArray.append(childFrameArrayEl); // Append child frame object to array. } frameObj["child_frames"] = childFrameArray; // Add child frame array to frame object. SfxManager::ToJson(frameObj, f); jsonObj["frame"] = frameObj; // Add frame object to supplied object. }
void calc_unwrap (double& p[], int N) { double dp[MAX_LENGTH]; double dps[MAX_LENGTH]; double dp_corr[MAX_LENGTH]; double cumsum[MAX_LENGTH]; double cutoff = M_PI; /* default value in matlab */ int j; //assert(N <= MAX_LENGTH); // incremental phase variation // MATLAB: dp = diff(p, 1, 1); for (j = 0; j < N-1; j++) dp[j] = p[j+1] - p[j]; // equivalent phase variation in [-pi, pi] // MATLAB: dps = mod(dp+dp,2*pi) - pi; for (j = 0; j < N-1; j++) dps[j] = (dp[j]+M_PI) - MathFloor((dp[j]+M_PI) / (2*M_PI))*(2*M_PI) - M_PI; // preserve variation sign for +pi vs. -pi // MATLAB: dps(dps==pi & dp>0,:) = pi; for (j = 0; j < N-1; j++) if ((dps[j] == -M_PI) && (dp[j] > 0)) dps[j] = M_PI; // incremental phase correction // MATLAB: dp_corr = dps - dp; for (j = 0; j < N-1; j++) dp_corr[j] = dps[j] - dp[j]; // Ignore correction when incremental variation is smaller than cutoff // MATLAB: dp_corr(abs(dp)<cutoff,:) = 0; for (j = 0; j < N-1; j++) if (MathAbs(dp[j]) < cutoff) dp_corr[j] = 0; // Find cumulative sum of deltas // MATLAB: cumsum = cumsum(dp_corr, 1); cumsum[0] = dp_corr[0]; for (j = 1; j < N-1; j++) cumsum[j] = cumsum[j-1] + dp_corr[j]; // Integrate corrections and add to P to produce smoothed phase values // MATLAB: p(2:m,:) = p(2:m,:) + cumsum(dp_corr,1); for (j = 1; j < N; j++) { p[j] += cumsum[j-1]; if (DEBUG == 1) { Print ("phase_unwrapped[", DoubleToStr(j,0), "] ", DoubleToStr(p[j],10)); file_result = FileWrite (file_handle, "phase_unwrapped", j, p[j]); } } }
void Ship::SaveToJson(Json::Value &jsonObj, Space *space) { DynamicBody::SaveToJson(jsonObj, space); Json::Value shipObj(Json::objectValue); // Create JSON object to contain ship data. m_skin.SaveToJson(shipObj); VectorToJson(shipObj, m_angThrusters, "ang_thrusters"); VectorToJson(shipObj, m_thrusters, "thrusters"); shipObj["wheel_transition"] = m_wheelTransition; shipObj["wheel_state"] = FloatToStr(m_wheelState); shipObj["launch_lock_timeout"] = FloatToStr(m_launchLockTimeout); shipObj["test_landed"] = m_testLanded; shipObj["flight_state"] = int(m_flightState); shipObj["alert_state"] = int(m_alertState); shipObj["last_firing_alert"] = DoubleToStr(m_lastFiringAlert); // XXX make sure all hyperspace attrs and the cloud get saved Json::Value hyperspaceDestObj(Json::objectValue); // Create JSON object to contain hyperspace destination data. m_hyperspace.dest.ToJson(hyperspaceDestObj); shipObj["hyperspace_destination"] = hyperspaceDestObj; // Add hyperspace destination object to ship object. shipObj["hyperspace_countdown"] = FloatToStr(m_hyperspace.countdown); Json::Value gunArray(Json::arrayValue); // Create JSON array to contain gun data. for (int i = 0; i<ShipType::GUNMOUNT_MAX; i++) { Json::Value gunArrayEl(Json::objectValue); // Create JSON object to contain gun. gunArrayEl["state"] = m_gun[i].state; gunArrayEl["recharge"] = FloatToStr(m_gun[i].recharge); gunArrayEl["temperature"] = FloatToStr(m_gun[i].temperature); gunArray.append(gunArrayEl); // Append gun object to array. } shipObj["guns"] = gunArray; // Add gun array to ship object. shipObj["ecm_recharge"] = FloatToStr(m_ecmRecharge); shipObj["ship_type_id"] = m_type->id; shipObj["docked_with_port"] = m_dockedWithPort; shipObj["index_for_body_docked_with"] = space->GetIndexForBody(m_dockedWith); shipObj["hull_mass_left"] = FloatToStr(m_stats.hull_mass_left); shipObj["shield_mass_left"] = FloatToStr(m_stats.shield_mass_left); shipObj["shield_cooldown"] = FloatToStr(m_shieldCooldown); if (m_curAICmd) m_curAICmd->SaveToJson(shipObj); shipObj["ai_message"] = int(m_aiMessage); shipObj["thruster_fuel"] = DoubleToStr(m_thrusterFuel); shipObj["reserve_fuel"] = DoubleToStr(m_reserveFuel); shipObj["controller_type"] = static_cast<int>(m_controller->GetType()); m_controller->SaveToJson(shipObj, space); m_navLights->SaveToJson(shipObj); shipObj["name"] = m_shipName; jsonObj["ship"] = shipObj; // Add ship object to supplied object. }
void SpaceStation::SaveToJson(Json::Value &jsonObj, Space *space) { ModelBody::SaveToJson(jsonObj, space); Json::Value spaceStationObj(Json::objectValue); // Create JSON object to contain space station data. Json::Value shipDockingArray(Json::arrayValue); // Create JSON array to contain ship docking data. for (Uint32 i = 0; i<m_shipDocking.size(); i++) { Json::Value shipDockingArrayEl(Json::objectValue); // Create JSON object to contain ship docking. shipDockingArrayEl["index_for_body"] = space->GetIndexForBody(m_shipDocking[i].ship); shipDockingArrayEl["stage"] = m_shipDocking[i].stage; shipDockingArrayEl["stage_pos"] = DoubleToStr(m_shipDocking[i].stagePos); // stagePos is a double but was saved as a float in pre-JSON system for some reason (saved as double here). VectorToJson(shipDockingArrayEl, m_shipDocking[i].fromPos, "from_pos"); QuaternionToJson(shipDockingArrayEl, m_shipDocking[i].fromRot, "from_rot"); shipDockingArray.append(shipDockingArrayEl); // Append ship docking object to array. } spaceStationObj["ship_docking"] = shipDockingArray; // Add ship docking array to space station object. // store each of the port details and bay IDs Json::Value portArray(Json::arrayValue); // Create JSON array to contain port data. for (Uint32 i = 0; i < m_ports.size(); i++) { Json::Value portArrayEl(Json::objectValue); // Create JSON object to contain port. portArrayEl["min_ship_size"] = m_ports[i].minShipSize; portArrayEl["max_ship_size"] = m_ports[i].maxShipSize; portArrayEl["in_use"] = m_ports[i].inUse; Json::Value bayArray(Json::arrayValue); // Create JSON array to contain bay data. for (Uint32 j = 0; j<m_ports[i].bayIDs.size(); j++) { Json::Value bayArrayEl(Json::objectValue); // Create JSON object to contain bay. bayArrayEl["bay_id"] = m_ports[i].bayIDs[j].first; bayArrayEl["name"] = m_ports[i].bayIDs[j].second; bayArray.append(bayArrayEl); // Append bay object to array. } portArrayEl["bays"] = bayArray; // Add bay array to port object. portArray.append(portArrayEl); // Append port object to array. } spaceStationObj["ports"] = portArray; // Add port array to space station object. spaceStationObj["index_for_system_body"] = space->GetIndexForSystemBody(m_sbody); spaceStationObj["door_animation_step"] = DoubleToStr(m_doorAnimationStep); spaceStationObj["door_animation_state"] = DoubleToStr(m_doorAnimationState); m_navLights->SaveToJson(spaceStationObj); jsonObj["space_station"] = spaceStationObj; // Add space station object to supplied object. }
void Game::ToJson(Json::Value &jsonObj) { PROFILE_SCOPED() // preparing the lua serializer Pi::luaSerializer->InitTableRefs(); // signature jsonObj["signature"] = s_saveStart; // version jsonObj["version"] = s_saveVersion; // galaxy generator m_galaxy->ToJson(jsonObj); // game state jsonObj["time"] = DoubleToStr(m_time); jsonObj["state"] = Uint32(m_state); jsonObj["want_hyperspace"] = m_wantHyperspace; jsonObj["hyperspace_progress"] = DoubleToStr(m_hyperspaceProgress); jsonObj["hyperspace_duration"] = DoubleToStr(m_hyperspaceDuration); jsonObj["hyperspace_end_time"] = DoubleToStr(m_hyperspaceEndTime); // space, all the bodies and things m_space->ToJson(jsonObj); jsonObj["player"] = m_space->GetIndexForBody(m_player.get()); // hyperspace clouds being brought over from the previous system Json::Value hyperspaceCloudArray(Json::arrayValue); // Create JSON array to contain hyperspace cloud data. for (std::list<HyperspaceCloud*>::const_iterator i = m_hyperspaceClouds.begin(); i != m_hyperspaceClouds.end(); ++i) { Json::Value hyperspaceCloudArrayEl(Json::objectValue); // Create JSON object to contain hyperspace cloud. (*i)->ToJson(hyperspaceCloudArrayEl, m_space.get()); hyperspaceCloudArray.append(hyperspaceCloudArrayEl); // Append hyperspace cloud object to array. } jsonObj["hyperspace_clouds"] = hyperspaceCloudArray; // Add hyperspace cloud array to supplied object. // views. must be saved in init order m_gameViews->m_cpan->SaveToJson(jsonObj); m_gameViews->m_sectorView->SaveToJson(jsonObj); m_gameViews->m_worldView->SaveToJson(jsonObj); // lua Pi::luaSerializer->ToJson(jsonObj); // trailing signature jsonObj["trailing_signature"] = s_saveEnd; // Don't really need this anymore. Pi::luaSerializer->UninitTableRefs(); }
void Body::SaveToJson(Json::Value &jsonObj, Space *space) { Json::Value bodyObj(Json::objectValue); // Create JSON object to contain body data. Properties().SaveToJson(bodyObj); bodyObj["index_for_frame"] = space->GetIndexForFrame(m_frame); bodyObj["label"] = m_label; bodyObj["dead"] = m_dead; VectorToJson(bodyObj, m_pos, "pos"); MatrixToJson(bodyObj, m_orient, "orient"); bodyObj["phys_radius"] = DoubleToStr(m_physRadius); bodyObj["clip_radius"] = DoubleToStr(m_clipRadius); jsonObj["body"] = bodyObj; // Add body object to supplied object. }
//THE DOUBLETOSTR CONVERSION FUNCTION IS ALL THAT IS LEFT. static void DisplayTimeStats(double time, char* outbuf) { write(STDOUT_FILENO, outbuf, strlen(outbuf)); char mytime[25]; DoubleToStr(time, mytime); write(STDOUT_FILENO, mytime, strlen(mytime)); }
void DynamicBody::SaveToJson(Json::Value &jsonObj, Space *space) { ModelBody::SaveToJson(jsonObj, space); Json::Value dynamicBodyObj(Json::objectValue); // Create JSON object to contain dynamic body data. VectorToJson(dynamicBodyObj, m_force, "force"); VectorToJson(dynamicBodyObj, m_torque, "torque"); VectorToJson(dynamicBodyObj, m_vel, "vel"); VectorToJson(dynamicBodyObj, m_angVel, "ang_vel"); dynamicBodyObj["mass"] = DoubleToStr(m_mass); dynamicBodyObj["mass_radius"] = DoubleToStr(m_massRadius); dynamicBodyObj["ang_inertia"] = DoubleToStr(m_angInertia); dynamicBodyObj["is_moving"] = m_isMoving; jsonObj["dynamic_body"] = dynamicBodyObj; // Add dynamic body object to supplied object. }
int main() { srand(static_cast<unsigned>(time(NULL))); double variables[MaxVarCount]; for (int i = 0; i < MaxVarCount; i++) { variables[i] = GetRandomValue(MaxVarValue); } std::map<std::string, double> expressions; std::ofstream output; output.open("../ADTest/TestFunctions.h"); std::vector<std::string> lines; lines.push_back("#ifndef TESTFUNCTIONS_H"); lines.push_back("#define TESTFUNCTIONS_H"); lines.push_back(""); lines.push_back("const int DataInSize = " + IntToStr(MaxVarCount) + ";"); lines.push_back("const int SimpleTestCases = " + IntToStr(SimpleTestCases) + ";"); lines.push_back("const int ComplexTestCases = " + IntToStr(ComplexTestCases) + ";"); lines.push_back("const int LoopTestCases = " + IntToStr(LoopTestCases) + ";"); lines.push_back("const int TotalTestCases = " + IntToStr(TotalTestCases) + ";"); lines.push_back("const int LoopIterations = " + IntToStr(LoopIterations) + ";"); lines.push_back(""); std::string arguments = ""; for (int i = 0; i < MaxVarCount; i++) { arguments += DoubleToStr(variables[i]) + ", "; } arguments = arguments.substr(0, arguments.size() - 2); lines.push_back("const real realArgs[DataInSize] = {" + arguments + "};"); lines.push_back(""); lines.push_back("template<typename ADType>"); lines.push_back("struct FunctionBase {"); lines.push_back(" virtual ADType TestFunction(const ADType(&x)[DataInSize]) = 0;"); lines.push_back("};"); lines.push_back(""); GenerateSimpleTestCases(0, lines, expressions, variables); GenerateComplexTestCases(SimpleTestCases, lines, expressions, variables); GenerateLoopTestCases(SimpleTestCases + ComplexTestCases, lines, expressions, variables); lines.push_back("template<typename ADType>"); lines.push_back("void Initialize(FunctionBase<ADType>* testArray[TotalTestCases]) {"); for (int i = 0; i < TotalTestCases; i++) { lines.push_back(" testArray[" + IntToStr(i) + "] = new FunctionSpec" + IntToStr(i) + "<ADType>();"); } lines.push_back("};"); lines.push_back(""); lines.push_back("template<typename ADType>"); lines.push_back("void Finalize(FunctionBase<ADType>* testArray[TotalTestCases]) {"); lines.push_back(" for (int i = 0; i < TotalTestCases; i++)"); lines.push_back(" delete testArray[i]; "); lines.push_back("};"); lines.push_back(""); lines.push_back("#endif // TESTFUNCTIONS_H"); for (std::vector<std::string>::iterator line = lines.begin(); line != lines.end(); line++) { output << *line << '\n'; } output.close(); return 0; };
void AddConstants(std::map<std::string, double>& expressions) { for (int i = 0; i < MaxConstCount; i++) { double constant = GetRandomValue(MaxConstValue); std::string key = DoubleToStr(constant); if (constant < 0.0) { key = "(" + key + ")"; } expressions[key] = constant; } };
void TIniFile::WriteDouble(const wxString &Section, const wxString &Ident, double Value) { WriteString(Section, Ident, DoubleToStr(Value)); }
//----------------------------------------------------------------------------------------------- int start() { // E Farrell 2013 // Store these values at the start // because they are dynamic and // get changed during processing later. int store_bars = Bars; int store_indicator_counted = IndicatorCounted(); int store_counted_bars = store_bars - store_indicator_counted - 1; // Three ways of debugging: // Alert(...): display popup MessageBox // Comment(...): display on left corner of MAIN chart // Print(...): write to "experts log" if (DEBUG == 1) { // Print msg to "Experts Log" // i.e. not to debug file bar_info = ""; bar_info = StringConcatenate(bar_info, "Store_bars: ", DoubleToStr(store_bars,0), "; "); bar_info = StringConcatenate(bar_info, "store_indicator_counted: ", DoubleToStr(store_indicator_counted,0), "; "); Print (bar_info); } // Create X-Axis line along zero value ObjectCreate ("X-Axis", OBJ_HLINE, 1, 0, 0); ObjectSet ("X-Axis", OBJPROP_COLOR, Black); ObjectSet ("X-Axis", OBJPROP_WIDTH, 2); // vols[] // Compute stochastic volatility calc_volatility (store_bars, store_counted_bars); // levy_signal[] // Compute Levy Index // of Closing Price (i.e. the signal) calc_alpha_signal (Close, store_counted_bars); // levy_vol[] // Compute Levy Index // of stochastic volatility. calc_alpha_volatility (vols, store_counted_bars); // phase_wrapped[] // Compute WRAPPED phase // of levy_signal[] and levy_vol[]. // i.e. instantaneous phase between -PI and +PI calc_phase (store_counted_bars); // Make a copy of the "phase_wrapped" array. // The new copy "phase_unwrapped" will be // worked on by the "calc_unwrap" function. for (int i = store_counted_bars; i >= 0; i--) { phase_unwrapped[i] = phase_wrapped[i]; } // phase_unwrapped[] // UNWRAP the instantaneous phase calc_unwrap (phase_unwrapped, store_counted_bars); // least_squares_line[] // Compute regression line for unwrapped phase calc_regression (phase_unwrapped, phase_lookback); // phase_adjusted[] // Create a "lower" unwrapped Phase which hugs the x-axis calc_phase_adjusted (phase_lookback); return(0); }
//----------------------------------------------------------------------------------------------- int init() { // E Farrell 2013 IndicatorDigits(10); IndicatorShortName("LEVY PHASE (F. Farrell)"); // Show or Hide a particular line? // // Use "DRAW_NONE" to hide a line // Use "DRAW_LINE" to display a line // Line 0: // Stochastic Volatility Line SetIndexBuffer (0, vols); SetIndexLabel (0, "Volatility"); SetIndexDrawBegin (0, Lookback); SetIndexStyle (0, DRAW_NONE); //SetIndexStyle (0, DRAW_LINE); // Line 1: // Levy Index of closing price (signal) SetIndexBuffer (1, levy_signal); SetIndexLabel (1, "levy_signal"); SetIndexDrawBegin (1, Lookback*2); SetIndexStyle (1, DRAW_NONE); //SetIndexStyle (1, DRAW_LINE); // Line 2: // Levy Index of Volatility SetIndexBuffer (2, levy_vol); SetIndexLabel (2, "levy_vol"); SetIndexDrawBegin (2, Lookback*2); SetIndexStyle (2, DRAW_NONE); //SetIndexStyle (2, DRAW_LINE); // Line 3: // Wrapped Phase Line SetIndexBuffer (3, phase_wrapped); SetIndexLabel (3, "Phase (wrapped)"); SetIndexDrawBegin (3, Lookback*2); //SetIndexStyle (3, DRAW_NONE); SetIndexStyle (3, DRAW_LINE); // Line 4: // Unwrapped Phase Line SetIndexBuffer (4, phase_unwrapped); SetIndexLabel (4, "Phase (Unwrapped)"); SetIndexDrawBegin (4, Lookback*2); //SetIndexStyle (4, DRAW_NONE); SetIndexStyle (4, DRAW_LINE); // Line 5: // Linear approximation of unwrapped phase SetIndexBuffer (5, least_squares_line); SetIndexLabel (5, "Regression Line"); SetIndexDrawBegin (5, Lookback*2); //SetIndexStyle (5, DRAW_NONE); SetIndexStyle (5, DRAW_LINE); // Line 6: // Final Adjusted Phase Line SetIndexBuffer (6, phase_adjusted); SetIndexLabel (6, "Phase (Adjusted)"); SetIndexDrawBegin (6, Lookback*2); SetIndexStyle (6, DRAW_LINE); if (DEBUG == 1) { // Create Debug File to show array values. // It is CSV style, with ";" as field seperators. // // Name: 'Debug File HH-MM.txt' // Location: 'c:\<<alpari directory>>\experts\files\' // file_name = "DebugFile "; file_name = StringConcatenate (file_name, DoubleToStr(Hour()-2,0), "-"); file_name = StringConcatenate (file_name, DoubleToStr(Minute(),0), ".txt"); file_handle = FileOpen (file_name, FILE_CSV|FILE_WRITE, ";"); Print (file_name, " was opened."); if(file_handle == -1) { // File Error occurred Alert ("An error while opening the file. Last Error: ", GetLastError()); } } return(0); }
static void DrawWaypoint(UInt16 listNum) { PFScreenRectType tmpRect; PFScreenRectType bounds; UInt16 iconIndex = 0; Waypoint *proxWp; Coord right; Coord iconDim = IconWindows.iconDim; Coord y; double range; char str[40]; PFScreenRectangleSet(&bounds, proxDisplayArea.x1, (listNum*proxRowHeight)+proxDisplayArea.y1, proxDisplayArea.x2, proxDisplayArea.y1 + (listNum+1)*proxRowHeight); PFDrawStatePush(); PFEraseRectangle(&bounds,0); PFSetTextColour(GUIGetSystemColour(GUIObjectForeground)); PFSetBackColour(GUIGetSystemColour(GUIFormFill)); listNum += topOfList; if (listNum >= proxList.numWaypoints) { PFDrawStatePop(); return; } /* * draw the icon * * the icons are stored in a strip in a single bitmap resource, * we need to copy a small portion of the strip to get the * icon we want * */ proxWp = WDMGetWaypoint(WPDataset, proxList.waypoints[listNum].id); if (WDMGetWaypointType(proxWp) & wpAllAirfields) { iconIndex = proxList.waypoints[listNum].runwayIcon; } else { switch (proxList.waypoints[listNum].type) { case wpVOR: iconIndex = 9; break; case wpVORDME: iconIndex = 10; break; case wpVORTAC: iconIndex = 13; break; case wpDME: iconIndex = 11; break; case wpNDBDME: case wpNDB: iconIndex = 12; break; case wpObstacle: iconIndex = 15; break; case wpLightObstacle: iconIndex = 16; break; case wpObstacles: iconIndex = 17; break; case wpLightObstacles: iconIndex = 18; break; case wpIntersection: iconIndex = 14; break; case wpTown: iconIndex = 20; break; case wpVRP: iconIndex = 22; break; case wpDisused: iconIndex = 21; break; case wpMicrolight: iconIndex = 24; break; case wpGlider: iconIndex = 25; break; case wpParachute: iconIndex = 26; break; default: iconIndex = 23; break; } } PFScreenRectangleSetRel(&tmpRect,(iconIndex & 0x7) * iconDim, ((iconIndex & 0xfff8) >> 3) * iconDim, iconDim, iconDim); PFCopyRectangle(IconWindows.icons, &tmpRect, bounds.x1+iconOffset, bounds.y1+(proxRowHeight-iconDim)/2,winOverlay); /* * draw first line: * */ y = bounds.y1; FntSetFont(stdFont); StrPrintF(str,"%03d",proxList.waypoints[listNum].bearing); right = 4+DrawLargeNumberSmallText(str, UC.heading, bounds.x1+iconDim+3, y, ALIGNLEFT,largeBoldFont); FntSetFont(boldFont); DrawAlignedChars(proxList.waypoints[listNum].ident, ALIGNLEFT, bounds.x1+iconDim+3+right, y); /* * 2nd+3d line: * */ y = bounds.y1+(proxRowHeight/2); range = proxList.waypoints[listNum].range * UC.distanceConv; right = 4 + DrawLargeNumberSmallText( range<100?DoubleToStr(range,1):DoubleToStr(range,0), UC.distanceUnits, bounds.x1+iconDim+2, y, ALIGNLEFT,largeBoldFont); StrPrintF(str,"%03d\260 (%s)",proxList.waypoints[listNum].bearingFrom, CompassText[(((proxList.waypoints[listNum].bearingFrom)*4+45)%1440)/90]); FntSetFont(boldFont); y-=12; right+=bounds.x1+iconDim+2; DrawAlignedChars(str, ALIGNLEFT, right, y); y+=pfScreen.boldHeight; FntSetFont(stdFont); PFDrawCharsTruncated(proxList.waypoints[listNum].name, StrLen(proxList.waypoints[listNum].name), right, y, (bounds.x2)-right); y = bounds.y2 - 1; PFDrawLine(bounds.x1, y, bounds.x2, y); PFDrawStatePop(); PFMemFree(proxWp); }
int start() { int err = 0; int total = 0; int prevticket = 0; int modespread = MarketInfo(Symbol(), MODE_SPREAD); //---- if (IsTradeAllowed()) { RefreshRates(); modespread = MarketInfo(Symbol(), MODE_SPREAD); } else { return (0); } ObjectSetText(WT_INFO_NAME, "Perceptron("+gOrderbar+"): " + "Spread("+modespread+") "+ ""+DoubleToStr(perceptron(), 2)+"", 7, "Arial", White); // check for opened position total = OrdersTotal(); //---- for (int i = 0; i < total; i++) { OrderSelect(i, SELECT_BY_POS, MODE_TRADES); // check for symbol & magic number if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) { prevticket = OrderTicket(); gOrderbar = iBarShift(Symbol(), 0, OrderOpenTime()); // long position is opened if (OrderType() == OP_BUY) { // check profit if (Bid > (OrderStopLoss() + (sl * 2 + modespread) * Point)) { if (perceptron() < 0) { // reverse gOrderTicket = OrderSend(Symbol(), OP_SELL, OrderLots(), Bid, 3, Ask + sl * Point, 0, "AI Rev", MagicNumber, 0, Red); Sleep(10000); //---- if (gOrderTicket >= 0) { OrderCloseBy(gOrderTicket, prevticket, Blue); } else { err=GetLastError(); Print("error[1](",err,"): ",ErrorDescription(err)); if (OrderStopLoss() < OrderOpenPrice()) { if (!OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), 0, 0, Blue)) { Sleep(1000); } } } } else { // trailing stop if (!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - sl * Point, 0, 0, Blue)) { Sleep(1000); } } } // short position is opened } else { // check profit if (Ask < (OrderStopLoss() - (sl * 2 + modespread) * Point)) { if (perceptron() > 0) { // reverse gOrderTicket = OrderSend(Symbol(), OP_BUY, OrderLots(), Ask, 3, Bid - sl * Point, 0, "AI Rev", MagicNumber, 0, Blue); Sleep(10000); //---- if (gOrderTicket >= 0) { OrderCloseBy(gOrderTicket, prevticket, Blue); } else { err=GetLastError(); Print("error[2](",err,"): ",ErrorDescription(err)); if (OrderStopLoss() > OrderOpenPrice()) { if (!OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), 0, 0, Blue)) { Sleep(1000); } } } } else { // trailing stop if (!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + sl * Point, 0, 0, Blue)) { Sleep(1000); } } } } // exit return (0); } } if (gOrderbar == iBarShift(Symbol(), 0, 0)) { return (0); } lots = NormalizeDouble(AccountBalance() * aiGetRisk(Period()) / (sl + modespread), 2); if (lots < 0.01) lots = 0.01; // check for long or short position possibility if (perceptron() > 0) { //long gOrderTicket = OrderSend(Symbol(), OP_BUY, lots, Ask, 3, Bid - sl * Point, 0, "AI", MagicNumber, 0, Blue); //---- if (gOrderTicket < 0) { Sleep(10000); err=GetLastError(); Print("error[3](",err,"): ",ErrorDescription(err)); } } else { // short gOrderTicket = OrderSend(Symbol(), OP_SELL, lots, Bid, 3, Ask + sl * Point, 0, "AI", MagicNumber, 0, Red); if (gOrderTicket < 0) { Sleep(10000); err=GetLastError(); Print("error[4](",err,"): ",ErrorDescription(err)); } } //--- exit return (0); }
double TIniFile::ReadDouble(const wxString &Section, const wxString &Ident, double Default) { return StrToDouble(ReadString(Section, Ident, DoubleToStr(Default))); }
// ================== ExprResult AddExpression::Add // ================== ( ExprResult& left, ExprResult& right ) const { // Create a result, and initialise its status as undefined. ExprResult result( m_strPrecision ); result.SetStatus( ExprResult::UNDEF_STATUS ); // Convert any possible UNSPECIFIED operand. left.ConvertFromUnspecified(); right.ConvertFromUnspecified(); // Both operands must now have arithmetic types; check if either // operand has the type FLOAT. if ( left.IsFloat() || right.IsFloat() ) { // Convert both to FLOAT. left.ConvertToFloat(); right.ConvertToFloat(); } // Get the numerical values of the operands. double* pNumValLeft = left.GetNumValue(); double* pNumValRight = right.GetNumValue(); // Check if the numerical values exist; i.e. check if no // null pointers were returned. if ( pNumValLeft != 0 && pNumValRight != 0 ) { // Calculate the numerical value of the result by adding // the numerical values of the operands. double dlNumVal = (*pNumValLeft) + (*pNumValRight); // Since both operands now have the same type, check the type // of the left operand to check if both have type INT. if ( left.IsInt() ) { // Take as value of the result the conversion of its // numerical value to a string; not using exponential // notation, and with a precision of 0. Then, set the // result type to INT. result.SetValue( DoubleAsIntToStr( dlNumVal ) ); result.SetType( ExprResult::INT ); } else { // Take as value of the result the conversion of its // numerical value to a string, using a precision of // ADDPRECISION. Then, set the result type to FLOAT. result.SetValue( DoubleToStr( dlNumVal, ADDPRECISION ) ); result.SetType( ExprResult::FLOAT ); } // Set the result status to OK. result.SetStatus( ExprResult::OK ); } else { // Although the operands were of arithmetic type, no mumerical // value could be determined; internal error. result.SetStatus( ExprResult::INTERNAL_ERROR ); } return result; }
int exponential_growth( void ){ const double rho=0.2; double tmax=20.; const int r=100; unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // The seed mt19937 generator(seed); // The mersenne_twister generator uniform_real_distribution<double> distribution(0.0,1.0); // Uniform [0,1] distribution const int number_of_pop = 1000; // The number of populations we are computing, influence the range of the confidence interval const int number_of_time_steps = 250; // The number of time steps we are interested in double processus[number_of_time_steps][number_of_pop]; // The array containing all trajectories at each time steps. double output_array[number_of_time_steps][5]; // The array containing all relevants informations for (int index_time=0; index_time<number_of_time_steps; index_time++) // Initialize time steps. { output_array[index_time][0]=index_time*tmax/(number_of_time_steps-1); } for (int pop_index=0 ; pop_index<number_of_pop ; pop_index++ ) // For each independent simulation { int n=r; double t=0.0; double runi; double T; int index_time=0; double time_step=output_array[index_time][0]; while (t<tmax) // Until tmax is not reached { runi = distribution(generator); T = -log(runi)/(rho*n); // T is exponentialy distributed t+=T; while (t>time_step) // Write 1/(population size-1) at each time step { processus[index_time][pop_index]=1.0/(double(n)-1); index_time++; if (index_time==number_of_time_steps) break; time_step=output_array[index_time][0]; } n++; } } string file_name = "r="+IntToStr(r)+"_tmax="+IntToStr(tmax)+"_rho="+DoubleToStr(rho)+"_replicate="+IntToStr(number_of_pop)+".txt"; // The file name cout << file_name << endl; ofstream myfile; myfile.open( file_name.c_str() ); // Open the file myfile << "//time estimation lower_bound upper_bound expectation" << endl; // The first line of the file, the header for (int index_time=0; index_time<number_of_time_steps; index_time++) { double s1=0.; // The sum of 1/(population size-1) size at each time step for (int pop_index=0 ; pop_index<number_of_pop ; pop_index++ ) { s1+=processus[index_time][pop_index]; } output_array[index_time][1]=s1/number_of_pop; double s2=0.; // The sum of square of 1/(population size-1) at each time step for (int pop_index=0 ; pop_index<number_of_pop ; pop_index++ ) { s2+=pow(processus[index_time][pop_index],2.0); } double stdev = 1.96*sqrt( (s2/number_of_pop-pow(output_array[index_time][1],2.0) ) / (number_of_pop-1) ); // The standard deviation of 1/(population size-1) at each time step output_array[index_time][2] = output_array[index_time][1]-stdev; // Upper bound for the 95% confidence interval output_array[index_time][3] = output_array[index_time][1]+stdev; // Lower bound for the 95% confidence interval output_array[index_time][4]=exp(-rho*output_array[index_time][0])/(double (r)-1); // The expected value of 1/(population size-1) myfile << output_array[index_time][0] << " " << output_array[index_time][1] << " " << output_array[index_time][2] << " " << output_array[index_time][3] << " " << output_array[index_time][4] << endl; } myfile.close(); cout << "work finish" <<endl; return 0; }
/** *@param info - "miles \t p_min \t p_sec \t tt_hour \t tt_min \t tt_sec" * one of three sections will be all " "; *@return the missing part of the equation */ string RunLog::PaceCalculator( string& p_Info ) { double numbers[6]; int calcCase; string retval = ""; for( int i = 0; i<6; i++) { size_t found = p_Info.find( "\t" ); if( found != string::npos ) { string num = p_Info.substr( 0, found ); if( num == " " ) calcCase = i; else { numbers[i] = atof( num.c_str() ); } p_Info = p_Info.substr( found +1 ); } else { return ""; } } double pace,tt,temp, zero = 0.0; switch( calcCase ) { case 0: //convert pace and tt to seconds pace = convertToSeconds( zero, numbers[1], numbers[2] ); tt = convertToSeconds( numbers[3], numbers[4], numbers[5] ); temp = tt / pace;//divide retval = DoubleToStr( temp ); break; case 1: case 2: //convert tt to seconds tt = convertToSeconds( numbers[3], numbers[4], numbers[5] ); temp = tt / numbers[0]; //divide by miles convertToMinSec( &numbers[1], temp ); //convert to min and seconds retval = DoubleToStr( numbers[2] ); if( retval.size() == 1 ) retval = "0" + retval; retval = DoubleToStr( numbers[1] ) + " " + retval; break; case 4: case 3: case 5: double tempM; //multiply miles by pace min adn sec temp = numbers[0] * numbers[1]; if( temp > 59 ) { numbers[3] = (int)temp / 60; tempM = (int)temp % 60; } temp = numbers[0] * numbers[2]; if( temp > 60 ) { tempM += (int)temp / 60; if (tempM > 59){ numbers[3]++; tempM -= 60;} numbers[5] = (int)temp %60; } retval = DoubleToStr( numbers[3] ) + " " + DoubleToStr( numbers[4] )+ " " + DoubleToStr( numbers[5] ); break; } return retval; }
std::string AutoToStr(double val) { return DoubleToStr(val); }