private async Task <double> ComputeSurvivalRate(List <RubisCell> cellList, int[] ready) { int coreCount = 12; List <Task <double> > tasks = new List <Task <double> >(); int dividedLoad = cellList.Count / coreCount; int remainder = cellList.Count % coreCount; int pos = 0; for (int i = 0; i < coreCount; i++) { int actualLoad = dividedLoad + (i < remainder ? 1 : 0); RubisCell[] workLoad = new RubisCell[actualLoad]; Array.Copy(cellList.ToArray(), pos, workLoad, 0, actualLoad); WorkObject workObject = new WorkObject(workLoad, i, ready); pos += actualLoad; tasks.Add(ComputeSurvivalRateAsync(workObject)); } await Task.WhenAll(tasks); double sum = 0.0; for (int i = 0; i < coreCount; i++) { sum += tasks[i].Result; } return(sum); }
private async Task QuantifyService(int n, int m, List <Station> stationList, Grid grid) { int coreCount = 12; List <Task> tasks = new List <Task>(); int dividedLoad = n / coreCount; int rem = n % coreCount; int row = 0; for (int i = 0; i < coreCount; i++) { int actualLoad = dividedLoad + ((i < rem) ? 1 : 0); GeoCoordinate[] workLoad = new GeoCoordinate[actualLoad]; for (int j = 0; j < actualLoad; j++) { double lat = Utils.ConvertRowToLatFloor(grid.seoulCells[row + j].row); double lon = Utils.ConvertColToLonFloor(grid.seoulCells[row + j].col); workLoad[j] = new GeoCoordinate(lat, lon); } WorkObject workObject = new WorkObject(workLoad, i, row); row += actualLoad; tasks.Add(QuantifyAsync(workObject)); } await Task.WhenAll(tasks); return; }
/// <summary> /// Конвертирует объект в массив данных /// </summary> private object[,] CreateResultData(WorkObject wObj) { object[,] result = null; var count = wObj?.Profile?.Items?.Where(i => i.Column > 0).Count(); if (count != null && count > 0 && wObj?.Addresses != null) { var columns = (int)count + 4; var rows = wObj.Addresses.Count * (int)count; result = new object[rows, columns]; var realRow = 0; for (int i = 0; i < wObj.Addresses.Count; i++) { var adr = wObj.Addresses[i]; var tbl = adr.GetDataTable(); foreach (DictionaryEntry dk in tbl) { result[realRow, 0] = adr.District; result[realRow, 1] = adr.Address; result[realRow, 2] = adr.Uid; result[realRow, 3] = adr.Description; result[realRow, 4] = adr.Regex; result[realRow, 5] = adr.Number; result[realRow, 5] = dk.Key + ""; result[realRow, 6] = dk.Value + ""; realRow++; } } } return(result); }
public dataMonitor() { InitializeComponent(); tool1 = Form1.tool; w1 = Form1.w; toolData = Form1.toolData; wobjData = Form1.wobjData; controller = Form1.controller; }
private static void ReceiveCallback(IAsyncResult ar) { WorkObject client = (WorkObject)ar.AsyncState; int count = client.Socket.EndReceive(ar); string request = Encoding.UTF8.GetString(client.Buffer, 0, count); Console.WriteLine("Got {0}, from {1}", request, client.Socket.RemoteEndPoint); Send(client.Socket, request); }
/// <summary> /// Initializes a new instance of the Movement class. /// </summary> /// <param name="movementType"> The Movement Type. </param> /// <param name="target"> The Target. </param> /// <param name="speedData"> The Speed Data. </param> /// <param name="zoneData"> The Zone Data. </param> /// <param name="robotTool"> The Robot Tool. This will override the set default tool. </param> /// <param name="workObject"> The Work Object. </param> /// <param name="digitalOutput"> The Digital Output. When set this will define a MoveLDO or a MoveJDO instruction. </param> public Movement(MovementType movementType, ITarget target, SpeedData speedData, ZoneData zoneData, RobotTool robotTool, WorkObject workObject, DigitalOutput digitalOutput) { _movementType = movementType; _target = target; _id = -1; _speedData = speedData; _zoneData = zoneData; _robotTool = robotTool; _workObject = workObject; _digitalOutput = digitalOutput; CheckCombination(); }
/// <summary> /// Protected constructor needed for deserialization of the object. /// </summary> /// <param name="info"> The SerializationInfo to extract the data from. </param> /// <param name="context"> The context of this deserialization. </param> protected Movement(SerializationInfo info, StreamingContext context) { // int version = (int)info.GetValue("Version", typeof(int)); // <-- use this if the (de)serialization changes _movementType = (MovementType)info.GetValue("Movement Type", typeof(MovementType)); _target = (ITarget)info.GetValue("Target", typeof(ITarget)); _id = (int)info.GetValue("ID", typeof(int)); _speedData = (SpeedData)info.GetValue("Speed Data", typeof(SpeedData)); _zoneData = (ZoneData)info.GetValue("Zone Data", typeof(ZoneData)); _robotTool = (RobotTool)info.GetValue("Robot Tool", typeof(RobotTool)); _workObject = (WorkObject)info.GetValue("Work Object", typeof(WorkObject)); _digitalOutput = (DigitalOutput)info.GetValue("Digital Output", typeof(DigitalOutput)); }
/// <summary> /// Initializes a new instance of the Movement class. /// This constructor is typically used to cast a Robot Target to a movement. /// </summary> /// <param name="target"> The Target. </param> public Movement(ITarget target) { _movementType = 0; _target = target; _id = -1; _speedData = new SpeedData(5); // Slowest predefined tcp speed _zoneData = new ZoneData(0); _robotTool = new RobotTool(); // Default Robot Tool tool0 _robotTool.Clear(); // Empty Robot Tool _workObject = new WorkObject(); // Default work object wobj0 _digitalOutput = new DigitalOutput(); // InValid / empty DO }
private static void AcceptCallback(IAsyncResult ar) { done.Set();//signal Socket server = (Socket)ar.AsyncState; Socket client = server.EndAccept(ar); WorkObject obj = new WorkObject { Socket = client }; client.BeginReceive(obj.Buffer, 0, WorkObject.SIZE, 0, new AsyncCallback(ReceiveCallback), obj); }
/// <summary> /// Initializes a new instance of the Movement class with a default Work object (wobj0) and an empty Digital Output. /// </summary> /// <param name="movementType"> The Movement Type. </param> /// <param name="target"> The Target. </param> /// <param name="speedData"> The Speed Data. </param> /// <param name="zoneData"> The Zone Data. </param> /// <param name="robotTool"> The Robot Tool. This will override the set default tool. </param> public Movement(MovementType movementType, ITarget target, SpeedData speedData, ZoneData zoneData, RobotTool robotTool) { _movementType = movementType; _target = target; _id = -1; _speedData = speedData; _zoneData = zoneData; _robotTool = robotTool; _workObject = new WorkObject(); // Default work object wobj0 _digitalOutput = new DigitalOutput(); // InValid / empty DO CheckCombination(); }
public void AddItem(WorkObject workObject) { var mtm = _serviceLocator.GetInstance <AddressToAddressViewModel>(); mtm.AddFoundItems(workObject.Addresses, workObject.Profile); TabItems.Add(mtm); if (TabItems.Count == 1) { SelectedItem = mtm; } }
/// <summary> /// Initializes a new instance of the Movement class with an empty Robot Tool (no override) and a default Work Object (wobj0) /// </summary> /// <param name="movementType"> The Movement Type. </param> /// <param name="target"> The Target. </param> /// <param name="speedData"> The Speed Data.</param> /// <param name="zoneData"> The Zone Data. </param> /// <param name="digitalOutput"> The Digital Output. When set this will define a MoveLDO or a MoveJDO instruction. </param> public Movement(MovementType movementType, ITarget target, SpeedData speedData, ZoneData zoneData, DigitalOutput digitalOutput) { _movementType = movementType; _target = target; _id = -1; _speedData = speedData; _zoneData = zoneData; _robotTool = new RobotTool(); // Default Robot Tool tool0 _robotTool.Clear(); // Empty Robot Tool _workObject = new WorkObject(); // Default work object wobj0 _digitalOutput = digitalOutput; CheckCombination(); }
public void button_data_Click(object sender, EventArgs e) { // 获取当前tool 与 wobj try { tool = controller.MotionSystem.ActiveMechanicalUnit.Tool; w = controller.MotionSystem.ActiveMechanicalUnit.WorkObject; // toolData = (ToolData)tool.Data; // wobjData = (WobjData)w.Data; } catch (Exception ex) { MessageBox.Show(ex.Message, "错误"); } activeWindow(new dataMonitor()); }
private async Task WriteEvents() { int[] quotientAndRemainder = new int[2]; int coreCount = 12; Task[] tasks = new Task[coreCount]; DateTime startDate = new DateTime(2019, 1, 1); for (int i = 0; i < coreCount; i++, startDate = startDate.AddYears(20)) { WorkObject workObject = new WorkObject(i, startDate, eventGrid); tasks[i] = Task.Run(() => WriteEventsDoWork(workObject)); } await Task.WhenAll(tasks); }
private static async Task MainAsync() { // Setup example objects Random random = new Random(); List <WorkObject> workObjects = new List <WorkObject>(); int numberOfWorkObjects = random.Next(50, 100); for (int i = 0; i < numberOfWorkObjects; i++) { WorkObject workObject = new WorkObject(random); denominator += workObject.JobCount; workObjects.Add(workObject); } // The CancellationTokenSource is used to immediately abort the progress reporting once the work is complete CancellationTokenSource progressReportCancellationTokenSource = new CancellationTokenSource(); Task workTask = Task.Run(() => { Parallel.ForEach(workObjects, wo => { wo.PerformWork(); lock (syncObj) { numerator += wo.JobCount; } }); progressReportCancellationTokenSource.Cancel(); }); while (!workTask.IsCompleted) { try { ReportProgress(); await Task.Delay(250, progressReportCancellationTokenSource.Token); } catch (TaskCanceledException) { break; } } await workTask; ReportProgress(); }
private double ComputeSurvivalRateDoWork(WorkObject workObject) { double sum = 0.0; foreach (RubisCell cell in workObject.cellList) { double pSum = 0.0; foreach (StationDistancePair pair in cell.stations) { RubisStation s = pair.station; double prob = (1 - pSum) * ProbabilityMassFunction(s.droneList.Count - 1, s.pdfSum); pSum = pSum + prob; cell.survivalRate = cell.survivalRate + (prob * CalculateSurvivalRate(pair.distance)); } sum += cell.survivalRate; } return(sum); }
/// <summary>任务倒计时线程</summary> public void LimitTimeThreading(int time, tg_task worktask) { if (worktask.task_step_type == (int)TaskStepType.RAISE_COIN) { return; } try { time = time * 1000; var obj = new WorkObject { user_id = worktask.user_id, task_id = worktask.id, time = time, }; var token = new CancellationTokenSource(); Task.Factory.StartNew(m => { var wo = m as WorkObject; if (wo == null) { return; } SpinWait.SpinUntil(() => { var g_work = GetWorkInfo(wo.user_id); return(g_work.LimitTime == 0); }, wo.time); }, obj, token.Token).ContinueWith((m, n) => { var wo = n as WorkObject; if (wo == null) { token.Cancel(); return; } TimeEnd(Convert.ToInt64(wo.task_id)); token.Cancel(); }, obj, token.Token); } catch (Exception ex) { XTrace.WriteException(ex); } }
/// <summary> /// Initializes a new instance of the Movement class by duplicating an existing Movement instance. /// </summary> /// <param name="movement"> The Movement instance to duplicate. </param> /// <param name="duplicateMesh"> Specifies whether the meshes should be duplicated. </param> public Movement(Movement movement, bool duplicateMesh = true) { _movementType = movement.MovementType; _target = movement.Target.DuplicateTarget(); _id = movement.SyncID; _speedData = movement.SpeedData.Duplicate(); _zoneData = movement.ZoneData.Duplicate(); _digitalOutput = movement.DigitalOutput.Duplicate(); if (duplicateMesh == true) { _robotTool = movement.RobotTool.Duplicate(); _workObject = movement.WorkObject.Duplicate(); } else { _robotTool = movement.RobotTool.DuplicateWithoutMesh(); _workObject = movement.WorkObject.DuplicateWithoutMesh(); } }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { // Input variables WorkObject workObject = null; // Catch the input data if (!DA.GetData(0, ref workObject)) { return; } // Check if the object is valid if (!workObject.IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The Work Object is not valid"); } // Output DA.SetData(0, workObject.Name); DA.SetData(1, workObject.Plane); DA.SetData(2, workObject.ExternalAxis); }
private double ComputeSurvivalRateDoWork(WorkObject workObject) { double sum = 0.0; foreach (RubisCell cell in workObject.cellList) { double pSum = 0.0; foreach (StationDistancePair pair in cell.stations) { RubisStation s = pair.station; int index = rStationList.IndexOf(s); if (workObject.ready[index] > 0) { double prob = (1 - pSum) * ProbabilityMassFunction(workObject.ready[index] - 1, Utils.DRONE_REST_TIME * 60 * s.pdfSum); pSum += prob; cell.survivalRate = cell.survivalRate + (prob * CalculateSurvivalRate(pair.distance)); } } sum += cell.survivalRate; } return(sum); }
private void WriteEventsDoWork(WorkObject workObject) { DateTime end = workObject.begin.AddYears(20); DateTime current = workObject.begin; Random rand = new Random((int)DateTime.Now.ToBinary() + Utils.SIMULATION_EVENTS * workObject.index); StreamWriter file = new StreamWriter("simulationEvents_" + workObject.index + ".csv"); int eventCount = 0; while (current < end) { for (int i = 0; i < Utils.ROW_NUM; i++) { for (int j = 0; j < Utils.COL_NUM; j++) { if (!workObject.grid.inSeoul[i, j]) { continue; } double randVal = rand.NextDouble(); if (randVal < workObject.grid.lambda[i, j]) { file.Write(Utils.MIN_LATITUDE + (i + 0.5) * Utils.LAT_UNIT); file.Write(","); file.Write(Utils.MIN_LONGITUDE + (j + 0.5) * Utils.LON_UNIT); file.Write(","); file.Write(current.ToString()); file.Write("\n"); eventCount++; } } } current = current.AddMinutes(1); } file.Close(); }
private void QuantifyDoWork(WorkObject workObject) { Overlap overlap = new Overlap(); System.Console.WriteLine(workObject.index); StreamWriter file = new StreamWriter("Pulver_Area_" + workObject.index + ".csv"); for (int i = 0; i < workObject.load.Count(); i++) { int k = i + workObject.row; for (int j = 0; j < this.m; j++) { this.b[k, j] = overlap.Area(workObject.load[i].Latitude, workObject.load[i].Longitude, Utils.LAT_UNIT, Utils.LON_UNIT, stationList[j].lat, stationList[j].lon, Utils.GOLDEN_TIME); this.b[k, j] /= (Utils.UNIT * Utils.UNIT); file.Write(this.b[k, j]); file.Write(","); } file.Write("\n"); //Console.WriteLine("Thread " + workObject.index + " done with line " + i); } file.Close(); Console.WriteLine("thread " + workObject.index + " done."); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA) { // Warning that this component is OBSOLETE AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "This component is OBSOLETE and will be removed " + "in the future. Remove this component from your canvas and replace it by picking the new component " + "from the ribbon."); // Gets the Object Manager of this document _objectManager = DocumentManager.GetDocumentObjectManager(this.OnPingDocument()); // Clears Work Object Name for (int i = 0; i < _woNames.Count; i++) { _objectManager.WorkObjectNames.Remove(_woNames[i]); } _woNames.Clear(); // Removes lastName from WorkObjectNameList if (_objectManager.WorkObjectNames.Contains(_lastName)) { _objectManager.WorkObjectNames.Remove(_lastName); } // Clears Work Objects Local List _workObjects.Clear(); // Input variables List <string> names = new List <string>(); List <Plane> planes = new List <Plane>(); // Catch the input data if (!DA.GetDataList(0, names)) { return; } if (!DA.GetDataList(1, planes)) { return; } // Get longest Input List int[] sizeValues = new int[10]; sizeValues[0] = names.Count; sizeValues[1] = planes.Count; int biggestSize = HelperMethods.GetBiggestValue(sizeValues); // Keeps track of used indicies int nameCounter = -1; int planesCounter = -1; // Creates targets List <WorkObject> workObjects = new List <WorkObject>(); for (int i = 0; i < biggestSize; i++) { string name = ""; Plane plane = new Plane(); // Names counter if (i < names.Count) { name = names[i]; nameCounter++; } else { name = names[nameCounter] + "_" + (i - nameCounter); } // Target planes counter if (i < planes.Count) { plane = planes[i]; planesCounter++; } else { plane = planes[planesCounter]; } WorkObject workObject = new WorkObject(name, plane); workObjects.Add(workObject); } // Checks if the work object name is already in use and counts duplicates #region NameCheck _namesUnique = true; for (int i = 0; i < names.Count; i++) { if (_objectManager.WorkObjectNames.Contains(names[i])) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Work Object Name already in use."); _namesUnique = false; _lastName = ""; break; } else { // Adds Work Object Name to list _woNames.Add(names[i]); _objectManager.WorkObjectNames.Add(names[i]); // Run SolveInstance on other Work Objects with no unique Name to check if their name is now available _objectManager.UpdateWorkObjects(); _lastName = names[i]; } // Checks if variable name exceeds max character limit for RAPID Code if (HelperMethods.VariableExeedsCharacterLimit32(names[i])) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Work Object Name exceeds character limit of 32 characters."); break; } // Checks if variable name starts with a number if (HelperMethods.VariableStartsWithNumber(names[i])) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Work Object Name starts with a number which is not allowed in RAPID Code."); break; } } #endregion // Output _workObjects = workObjects; DA.SetDataList(0, workObjects); // Adds Component to OldWorkObjectsByGuid Dictionary if (!_objectManager.OldWorkObjectsByGuid.ContainsKey(this.InstanceGuid)) { _objectManager.OldWorkObjectsByGuid.Add(this.InstanceGuid, this); } // Recognizes if Component is Deleted and removes it from Object Managers target and name list GH_Document doc = this.OnPingDocument(); if (doc != null) { doc.ObjectsDeleted += DocumentObjectsDeleted; } }
private void DoWork() { WorkObject tWorker = new WorkObject((MyUpdateDelegate) delegate(int count) { this.UpdateCount(count); }, 0); tWorker.StartProcessing(); }
private async Task QuantifyAsync(WorkObject workObject) { await Task.Run(() => QuantifyDoWork(workObject)); }
private async Task <double> ComputeSurvivalRateAsync(WorkObject workObject) { return(await Task.Run(() => ComputeSurvivalRateDoWork(workObject))); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA) { // Clears Work Objects List _workObjects.Clear(); // Input variables List <string> names = new List <string>(); List <Plane> planes = new List <Plane>(); List <ExternalRotationalAxis> externalAxes = new List <ExternalRotationalAxis>(); // Catch the input data if (!DA.GetDataList(0, names)) { return; } if (!DA.GetDataList(1, planes)) { return; } if (!DA.GetDataList(2, externalAxes)) { externalAxes = new List <ExternalRotationalAxis>() { null }; } // Replace spaces names = HelperMethods.ReplaceSpacesAndRemoveNewLines(names); // Get longest Input List int[] sizeValues = new int[3]; sizeValues[0] = names.Count; sizeValues[1] = planes.Count; sizeValues[2] = externalAxes.Count; int biggestSize = HelperMethods.GetBiggestValue(sizeValues); // Keeps track of used indicies int nameCounter = -1; int planesCounter = -1; int axisCounter = -1; // Creates work objects WorkObject workObject; List <WorkObject> workObjects = new List <WorkObject>(); for (int i = 0; i < biggestSize; i++) { string name = ""; Plane plane = new Plane(); ExternalRotationalAxis externalAxis = null; // Names counter if (i < sizeValues[0]) { name = names[i]; nameCounter++; } else { name = names[nameCounter] + "_" + (i - nameCounter); } // Planes counter if (i < sizeValues[1]) { plane = planes[i]; planesCounter++; } else { plane = planes[planesCounter]; } // Axis counter if (i < sizeValues[2]) { externalAxis = externalAxes[i]; axisCounter++; } else { externalAxis = externalAxes[axisCounter]; } // Make work object workObject = new WorkObject(name, plane, externalAxis); workObjects.Add(workObject); } // Output _workObjects = workObjects; DA.SetDataList(0, workObjects); #region Object manager // Gets ObjectManager of this document _objectManager = DocumentManager.GetDocumentObjectManager(this.OnPingDocument()); // Clears Work Object Name for (int i = 0; i < _woNames.Count; i++) { _objectManager.WorkObjectNames.Remove(_woNames[i]); } _woNames.Clear(); // Removes lastName from WorkObjectNameList if (_objectManager.WorkObjectNames.Contains(_lastName)) { _objectManager.WorkObjectNames.Remove(_lastName); } // Adds Component to WorkObjectsByGuid Dictionary if (!_objectManager.OldWorkObjectsByGuid2.ContainsKey(this.InstanceGuid)) { _objectManager.OldWorkObjectsByGuid2.Add(this.InstanceGuid, this); } // Checks if the work object name is already in use and counts duplicates #region Check name in object manager _namesUnique = true; for (int i = 0; i < names.Count; i++) { if (_objectManager.WorkObjectNames.Contains(names[i])) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Work Object Name already in use."); _namesUnique = false; _lastName = ""; break; } else { // Adds Work Object Name to list _woNames.Add(names[i]); _objectManager.WorkObjectNames.Add(names[i]); // Run SolveInstance on other Work Objects with no unique Name to check if their name is now available _objectManager.UpdateWorkObjects(); _lastName = names[i]; } // Checks if variable name exceeds max character limit for RAPID Code if (HelperMethods.VariableExeedsCharacterLimit32(names[i])) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Work Object Name exceeds character limit of 32 characters."); break; } // Checks if variable name starts with a number if (HelperMethods.VariableStartsWithNumber(names[i])) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Work Object Name starts with a number which is not allowed in RAPID Code."); break; } } #endregion // Recognizes if Component is Deleted and removes it from Object Managers target and name list GH_Document doc = this.OnPingDocument(); if (doc != null) { doc.ObjectsDeleted += DocumentObjectsDeleted; } #endregion }