예제 #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_tagPosition"></param>
        /// <param name="_distance">Feet</param>
        /// <returns></returns>
        public List <NearbyHydrant> GetNearbyHydrants(GeoPoint _tagPosition, double _distance)
        {
            GeoDistance distance = new GeoDistance(DistanceUnits.Feet, _distance);
            GeoBox      gb       = new GeoBox(_tagPosition, distance, distance);

            List <Hydrant> hydrants = GetHydrants(gb);

            List <NearbyHydrant> output = new List <NearbyHydrant>();

            foreach (Hydrant hydrant in hydrants)
            {
                NearbyHydrant nbh = new NearbyHydrant
                {
                    Position = hydrant.Position,
                    Location = string.Format("Latitude: {0}<br>Longitude: {1}",
                                             hydrant.Position.Y.ToString("###.######"),
                                             hydrant.Position.X.ToString("###.######")),
                    HydrantGuid    = hydrant.Guid,
                    DistanceInFeet =
                        PositionHelper.GetDistance(_tagPosition, hydrant.Position).ToFeet().ToString("###.#"),
                    Thumbnail   = string.Format("<img src=\"{0}\" class=\"tagimg\" onclick=\"ShowImage('{1}');\">", hydrant.GetUrl(true), hydrant.GetUrl(false)),
                    MatchButton = string.Format("<button type=\"button\" class=\"btn btn-info\" onclick=\"MatchHydrant('{0}')\">Match</button>", hydrant.Guid)
                };

                output.Add(nbh);
            }

            return(output);
        }
예제 #2
0
        public static async Task <decimal> GetDistance(string source, string dest)
        {
            using (WorkDBEntities context = new WorkDBEntities())
            {
                //prevent multi records between source and destination manipulation:
                string[] sortedParams = new string[] { source, dest }.OrderBy(x => x).ToArray();
                source = sortedParams[0]; dest = sortedParams[1];

                var any = context.GeoDistance.Any(x => x.Source == source && x.Destination == dest);
                if (!any)
                {
                    decimal dist = await GetDistAsync(source, dest);

                    if (dist <= 0)
                    {
                        return(dist);
                    }

                    //add it into the DB:
                    var newRecord = new GeoDistance()
                    {
                        Destination = dest, Source = source, KMS = dist
                    };
                    context.GeoDistance.Add(newRecord);
                    context.SaveChanges();
                }
                var result = context.GeoDistance.First(x => x.Source == source && x.Destination == dest);

                //update its hits:
                result.Hits = result.Hits + 1;
                context.SaveChanges();

                return(result.KMS);
            }
        }
예제 #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_center"></param>
        /// <param name="_distance">In feet</param>
        /// <returns></returns>
        public List <Hydrant> GetHydrants(GeoPoint _center, double _distance)
        {
            GeoDistance distance = new GeoDistance(DistanceUnits.Feet, _distance);
            GeoBox      gb       = new GeoBox(_center, distance, distance);

            return(GetHydrants(gb));
        }
예제 #4
0
        public static DataCenter GetValidDataCenter(Models.Tuple tuple, List <DataCenter> datacenterList)
        {
            var rnd = new Random();

            double[] arrLatency = { 40, 50, 60 };
            foreach (var item in datacenterList)
            {
                var dis = GeoDistance.CalcDistance(tuple.GeoLocation.getLongitude(), tuple.GeoLocation.getLatitude(),
                                                   item.DatacenterCharacteristics.GeoLocation.getLongitude(), item.DatacenterCharacteristics.GeoLocation.getLatitude(),
                                                   GeoCodeCalcMeasurement.Kilometers);

                lock (item)
                { item.DatacenterCharacteristics.DistanceFromTuple = dis; }
                var link = new Link()
                {
                    Source          = tuple.Name,
                    Destination     = item.Name,
                    SDDistance      = dis,
                    Propagationtime = LinkUtility.CalculateLatency(dis, cooperSpeed, tuple.Size, transmitionRate, arrLatency[rnd.Next(arrLatency.Length)])
                };
                lock (CloudUtility.linksList)
                    CloudUtility.linksList.Add(link);
            }
            return(datacenterList.OrderBy(x => x.DatacenterCharacteristics.DistanceFromTuple).FirstOrDefault());
        }
예제 #5
0
        public void TestGeoDistanceInvalid()
        {
            var distance = new GeoDistance();

            #region Situation

            var la1 = -22.880743;
            var lo1 = -43.5886937;
            var la2 = -23.0107316;
            var lo2 = -43.3080803;

            #endregion

            #region Action

            var result = distance.GetDistanceKm(la1, lo1, la2, lo2);

            #endregion

            #region Validation

            double valorEsperado = 0;

            Assert.AreNotEqual(valorEsperado, result);

            #endregion
        }
예제 #6
0
        private static List <Friend> GetFriendsNext(string friendName)
        {
            var friendVisit = friends.Where(p => p.Name == friendName).FirstOrDefault();
            var distance    = new GeoDistance();

            return(distance.ListFriendsNext(friends, friendVisit));
        }
 protected override QueryContainer QueryFluent(QueryContainerDescriptor <Project> q) => q
 .GeoHashCell(c => c
              .Name("named_query")
              .Boost(1.1)
              .Field(p => p.Location)
              .Location(new GeoLocation(13.4080, 52.5186))
              .Neighbors()
              .Precision(GeoDistance.Meters(3))
              );
        public void GeoDistance_DistanceMeters()
        {
            GeoPosition a = new GeoPosition(0.0, 0.0);
            GeoPosition b = new GeoPosition(12.34, 56.78);

            var m = GeoDistance.DistanceMeters(a, b);

            Assert.AreEqual(6409572, Math.Round(m, 0));
        }
        public void GeoDistance_BetweenPoints()
        {
            GeoPosition a = new GeoPosition(12.34, 56.78);
            GeoPosition b = new GeoPosition(43.21, 87.65);

            GeoDistance g = GeoDistance.BetweenPoints(a, b);

            Assert.AreEqual(4532161, Math.Round(g.Meters, 0));
        }
        public void GeoDistance_FeetToMeters()
        {
            GeoDistance g = new GeoDistance();

            g.Feet = 3280839895;
            Assert.AreEqual(1000000000, Math.Round(g.Meters, 0));

            g.Meters = 1000000000;
            Assert.AreEqual(3280839895, Math.Round(g.Feet, 0));
        }
        public void GeoDistance_FeetToMiles()
        {
            GeoDistance g = new GeoDistance();

            g.Feet = 5280;
            Assert.AreEqual(1, Math.Round(g.Miles, 0));

            g.Miles = 0.5;
            Assert.AreEqual(2640, Math.Round(g.Feet, 0));
        }
예제 #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_pointFrom"></param>
        /// <param name="_pointTo"></param>
        /// <returns></returns>
        public static GeoDistance GetDistance(GeoPoint _pointFrom, GeoPoint _pointTo)
        {
            Position pFrom = new Position(new Longitude(_pointFrom.X), new Latitude(_pointFrom.Y));
            Position pTo   = new Position(new Longitude(_pointTo.X), new Latitude(_pointTo.Y));

            Distance distance = pFrom.DistanceTo(pTo);

            GeoDistance returnValue = new GeoDistance(DistanceUnits.Meters, distance.ToMeters().Value);

            return(returnValue);
        }
예제 #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_pointFrom"></param>
        /// <param name="_geoDistance"></param>
        /// <returns></returns>
        public static GeoPoint GetPointToNorth(GeoPoint _pointFrom, GeoDistance _geoDistance)
        {
            Position pFrom    = new Position(new Longitude(_pointFrom.X), new Latitude(_pointFrom.Y));
            Distance distance = new Distance(_geoDistance.Meters, DistanceUnit.Meters);

            Position pTo = pFrom.TranslateTo(Azimuth.North, distance);

            GeoPoint returnValue = new GeoPoint(pTo.Longitude.DecimalDegrees, pTo.Latitude.DecimalDegrees);

            return(returnValue);
        }
        public void GeoDistance_BetweenMultiplePoints()
        {
            List <GeoPosition> p = new List <GeoPosition>();

            p.Add(new GeoPosition(0.0, 0.0));
            p.Add(new GeoPosition(12.34, 56.78));
            p.Add(new GeoPosition(43.21, 87.65));

            GeoDistance g = GeoDistance.BetweenPoints(p);

            Assert.AreEqual(6409572 + 4532161, Math.Round(g.Meters, 0));
        }
예제 #15
0
        public static TopoStats FromTracks(IEnumerable <ITopoTrackInfo> tracks)
        {
            var stats = new TopoStats();

            if ((tracks?.Count() ?? 0) == 0)
            {
                return(stats);
            }

            var points   = 0;
            var hours    = 0.0;
            var ascent   = 0.0;
            var descent  = 0.0;
            var distance = 0.0;
            var distanceWithElevation = 0.0;
            var start  = DateTime.MaxValue;
            var finish = DateTime.MinValue;

            foreach (var track in tracks)
            {
                points   += track.TopoPoints.Count();
                hours    += track.FinishUTC.Subtract(track.StartUTC).TotalHours;
                ascent   += GeoDistance.ElevationBetweenPoints(track.TopoPoints, 1).Meters;
                descent  += GeoDistance.ElevationBetweenPoints(track.TopoPoints, -1).Meters;
                distance += GeoDistance.BetweenPoints(track.TopoPoints, true).Meters;
                distanceWithElevation += GeoDistance.BetweenPoints(track.TopoPoints, true).Meters;
                if (track.TopoPoints.First().LocalTime < start)
                {
                    start = track.TopoPoints.First().LocalTime;
                }
                if (track.TopoPoints.Last().LocalTime > finish)
                {
                    finish = track.TopoPoints.Last().LocalTime;
                }
            }

            if (points == 0)
            {
                return(stats);
            }

            stats.ElapsedTime            = TimeSpan.FromHours(hours);
            stats.Distance               = GeoDistance.FromMeters(distance);
            stats.DistanceWithElevation  = GeoDistance.FromMeters(distanceWithElevation);
            stats.EstimatedMetersAscent  = ascent;
            stats.EstimatedMetersDescent = descent;
            stats.SecondsBetweenPoints   = (hours * 60 * 60) / points;
            stats.PointCount             = points;
            stats.DayCount               = (finish.DayOfYear - start.DayOfYear) + 1;

            return(stats);
        }
 protected override QueryContainer QueryFluent(QueryContainerDescriptor <Project> q) => q
 .GeoDistanceRange(g => g
                   .Boost(1.1)
                   .Name("named_query")
                   .Field(p => p.Location)
                   .DistanceType(GeoDistanceType.Arc)
                   .Coerce()
                   .GreaterThanOrEqualTo(200, GeoPrecision.Kilometers)
                   .GreaterThan(200, GeoPrecision.Kilometers)
                   .IgnoreMalformed()
                   .Location(new GeoLocation(40, -70))
                   .Optimize(GeoOptimizeBBox.Indexed)
                   .LessThanOrEqualTo(GeoDistance.Miles(400))
                   .LessThan(GeoDistance.Miles(400))
                   .ValidationMethod(GeoValidationMethod.Strict)
                   );
예제 #17
0
        public void WriteJson_GeoDistance_WritesExpectedOutput()
        {
            var input = new GeoDistance(
                "MyField",
                "123km",
                new GeoPoint(59.8881646, 10.7983952));

            var stringWriter = new StringWriter();
            var jsonWriter   = new JsonTextWriter(stringWriter);
            var converter    = new GeoDistanceConverter();

            converter.WriteJson(jsonWriter, input, new JsonSerializer());
            stringWriter.Flush();

            var result = stringWriter.ToString();

            const string expected = "{\"geo_distance\":{\"distance\":\"123km\",\"MyField\":{\"lat\":59.8881646,\"lon\":10.7983952}}}";

            Assert.Equal(expected, result);
        }
예제 #18
0
        public static CloudDevice CloudComputation(Models.Tuple tuple, CloudDevice cloud)
        {
            var rnd = new Random();

            double[] arrLatency = { 40, 50, 60 };
            var      dis        = GeoDistance.CalcDistance(tuple.GeoLocation.getLongitude(), tuple.GeoLocation.getLatitude(),
                                                           cloud.GeoLocation.getLongitude(), cloud.GeoLocation.getLatitude(), GeoCodeCalcMeasurement.Kilometers);

            lock (Lock)
            { cloud.DistanceFromTuple = dis; }
            lock (Lock)
            {
                link.Source          = tuple.Name;
                link.Destination     = cloud.Name;
                link.SDDistance      = dis;
                link.Propagationtime = LinkUtility.CalculateLatency(dis, cooperSpeed, tuple.Size, transmitionRate, arrLatency[rnd.Next(arrLatency.Length)]);
            }
            CloudRersourceUtility.ResourceConsumption(tuple, cloud);
            return(cloud);
        }
예제 #19
0
        public static TopoStats FromTrack(ITopoTrackInfo track)
        {
            var stats = new TopoStats();

            if (track == null || track.TopoPoints.Count() == 0)
            {
                return(stats);
            }

            stats.ElapsedTime            = track.FinishUTC.Subtract(track.StartUTC);
            stats.Distance               = GeoDistance.BetweenPoints(track.TopoPoints, true);
            stats.DistanceWithElevation  = GeoDistance.BetweenPoints(track.TopoPoints, true);
            stats.EstimatedMetersAscent  = GeoDistance.ElevationBetweenPoints(track.TopoPoints, 1).Meters;
            stats.EstimatedMetersDescent = GeoDistance.ElevationBetweenPoints(track.TopoPoints, -1).Meters;
            stats.SecondsBetweenPoints   = stats.ElapsedTime.TotalSeconds / track.TopoPoints.Count();
            stats.PointCount             = track.TopoPoints.Count();
            stats.DayCount               = track.FinishLocal.DayOfYear - track.StartLocal.DayOfYear;

            return(stats);
        }
예제 #20
0
        public async Task <IActionResult> Create([Bind("FlightId,AirportStart,AirportEnd,FlightDate,FlightTime,NumFCSeats,FCSeatPrice,NumBusSeats,BusSeatPrice")] Flight flight, string AirportStart, string AirportEnd)
        {
            if (ModelState.IsValid)
            {
                var    startAirport = _context.Airports.First(m => m.IATA == AirportStart);
                var    stopAirport  = _context.Airports.First(m => m.IATA == AirportEnd);
                double latStart     = startAirport.Latitude;
                double lonStart     = startAirport.Longitude;
                double latEnd       = stopAirport.Latitude;
                double lonEnd       = stopAirport.Longitude;
                flight.TravelDistance = GeoDistance.Calculate(latStart, lonStart, latEnd, lonEnd, 'M');

                flight.AirportStart = startAirport;
                flight.AirportEnd   = stopAirport;
                _context.Add(flight);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            //ViewBag.Message = "Flight Added!";
            return(View(flight));
        }
		public GeoDistanceFilterDescriptor DistanceType(GeoDistance type)
		{
			((IGeoDistanceFilter)this).DistanceType = type;
			return this;
		}
예제 #22
0
 protected override QueryContainer QueryFluent(QueryContainerDescriptor <Project> q) => q
 .FunctionScore(c => c
                .Name("named_query")
                .Boost(1.1)
                .Query(qq => qq.MatchAll())
                .BoostMode(FunctionBoostMode.Multiply)
                .ScoreMode(FunctionScoreMode.Sum)
                .MaxBoost(20.0)
                .MinScore(1.0)
                .Functions(f => f
                           .Exponential(b => b.Field(p => p.NumberOfCommits).Decay(0.5).Origin(1.0).Scale(0.1).Weight(2.1))
                           .GaussDate(b => b.Field(p => p.LastActivity).Origin(DateMath.Now).Decay(0.5).Scale("1d"))
                           .LinearGeoLocation(b => b.Field(p => p.Location).Origin(new GeoLocation(70, -70)).Scale(GeoDistance.Miles(1)).MultiValueMode(MultiValueMode.Average))
                           .FieldValueFactor(b => b.Field("x").Factor(1.1).Missing(0.1).Modifier(FieldValueFactorModifier.Ln))
                           .RandomScore(1337)
                           .Weight(1.0)
                           .ScriptScore(ss => ss.Script(s => s.File("x")))
                           )
                );
예제 #23
0
 public GeoDistanceFilterBuilder(string name)
 {
     _name = name;
     _geoDistance = Rubber.GeoDistance.ARC;
 }
예제 #24
0
 /// <summary>
 /// The geo distance type used to compute the distance.
 /// </summary>
 /// <param name="geoDistance"></param>
 /// <returns></returns>
 public GeoDistanceFacetBuilder GeoDistance(GeoDistance geoDistance)
 {
     _geoDistance = geoDistance;
     return(this);
 }
예제 #25
0
 /// <summary>
 /// The geo distance type used to compute the distance.
 /// </summary>
 /// <param name="geoDistance"></param>
 /// <returns></returns>
 public GeoDistanceSortBuilder GeoDistance(GeoDistance geoDistance)
 {
     _geoDistance = geoDistance;
     return this;
 }
예제 #26
0
 public GeoDistanceFilterBuilder GeoDistance(GeoDistance geoDistance)
 {
     _geoDistance = geoDistance;
     return this;
 }
		public GeoDistanceRangeFilterDescriptor DistanceType(GeoDistance geoDistance)
		{
			_.DistanceType = geoDistance;
			return this;
		}
예제 #28
0
 public GeoDistanceAggregationDescriptor <T> DistanceType(GeoDistance geoDistance)
 {
     Self.DistanceType = geoDistance;
     return(this);
 }
예제 #29
0
 public GeoDistanceRangeFilterBuilder GeoDistance(GeoDistance geoDistance)
 {
     _geoDistance = geoDistance;
     return(this);
 }
예제 #30
0
        public static string[] FromPoints(IEnumerable <IGpxPoint> points)
        {
            var tags  = new List <string>();
            var count = points.Count();

            // is closed loop
            var loop = GeoDistance.BetweenPoints(points.First(), points.Last());

            if (loop.Meters <= 200)
            {
                tags.Add("Loop");
            }

            // average speed
            var km   = GeoDistance.BetweenPoints(points).KM;
            var time = points.Max(x => x.Timestamp.Value).Subtract(points.Min(x => x.Timestamp.Value));
            var kmh  = km / time.TotalHours;

            if (kmh <= 5)             // km/h
            {
                tags.Add("Walk");
            }
            else if (kmh <= 15)             // km/h
            {
                tags.Add("Bike");
            }

            // max speed (of data)
            var max = points.Max(x => x.Speed ?? 0);

            if (max > 5)
            {
                tags.Add("Fast");                      // m/s
            }
            // number of stops
            var stops = points.Count(x => x.Speed == 0);

            if ((stops / count) >= 0.01)
            {
                tags.Add("Stops");                                      // 1%
            }
            // few options
            if (count < 30)
            {
                tags.Add("Short");
            }

            // bad data points
            var bad = max > 33;             // m/s

            if (!bad)
            {
                bad = points.Average(x => (x.Sats ?? 0)) <= 5;
            }
            if (!bad)
            {
                bad = points.Count(x => !x.HDOP.HasValue) >= 20;                   // TODO: fix this threshold for old files without DOP data
            }
            if (bad)
            {
                tags.Add("Bad");
            }

            return(tags.ToArray());
        }
예제 #31
0
 public GeoDistanceRangeFilterBuilder(string name)
 {
     _geoDistance = Nest.GeoDistance.arc;
     _name        = name;
 }
예제 #32
0
        public IHttpActionResult CreateEdgeDS(FogSimulationPost model)
        {
            try
            {
                /// We are using Same classes in Edge computing
                /// but changing the specifications for Edge..

                Random rnd = new Random();

                FogPost             edge         = model.FogPost;
                Models.TuplePost    tuple        = model.TuplePost;
                bool                F_homo_hetro = true; // true means Homogenious Fogs
                bool                T_homo_hetro = true; // true mean Homogenious  Tuples
                long                EdgeSize     = edge.FogSize;
                List <FogDevice>    edgeList     = new List <FogDevice>();
                List <Models.Tuple> tupleList    = new List <Models.Tuple>();

                #region create Edge dataSet
                if (edge.FogDevice.RAM != 0)
                {
                    #region Edge Homogenious
                    F_homo_hetro = true;
                    for (int i = 0; i < EdgeSize; i++)
                    {
                        bool[] bit = { true, false };
                        var    b   = rnd.Next(bit.Length);

                        Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                        EnumNodeType randomDataType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));

                        edgeList.Add(new FogDevice(
                                         Guid.NewGuid(),
                                         1,
                                         edge.FogDevice.MIPS,
                                         edge.FogDevice.NumberOfPes,
                                         edge.FogDevice.RAM,
                                         edge.FogDevice.UpBW,
                                         edge.FogDevice.DownBW,
                                         edge.FogDevice.Size,
                                         edge.FogDevice.Storage,
                                         edge.FogDevice.Name + "-" + i,
                                         randomDataType.ToString(),
                                         new CloudletScheduler(),
                                         GeoDistance.RandomGeoLocation(rnd),
                                         bit[b],
                                         0,
                                         PowerUtility.SetIdlePower(), 15)
                                     );
                    }

                    #endregion Edge
                }
                else
                {
                    #region Edge Hetrogenious
                    F_homo_hetro = false;
                    for (int i = 0; i < EdgeSize; i++)
                    {
                        bool[] bit = { true };
                        var    b   = rnd.Next(bit.Length);

                        int[] randomRam = { 512, 1024, 2048, 3072, 3584, 4096 };
                        //  var randomRamIndex = rnd.Next(randomRam.Length);
                        var   index           = rnd.Next(randomRam.Length);
                        int[] randomMips      = { 2000, 3500, 7000, 10000, 15000, 18000 };
                        var   randomMipsIndex = rnd.Next(randomMips.Length);

                        int[] randomPe      = { 1, 1, 2, 2, 3, 4 };
                        var   randomPeIndex = rnd.Next(randomPe.Length);

                        int[] randomSize      = { 4000, 5000, 7000, 10000, 12000, 15000 };
                        var   randomSizeIndex = rnd.Next(randomSize.Length);

                        int[] randomDownBW      = { 400, 500, 700, 1000, 1200, 1500 };
                        var   randomDownBWIndex = rnd.Next(randomDownBW.Length);

                        int[] randomUpBW      = { 500, 700, 1000, 1200, 1500, 2000 };
                        var   randomUpBWIndex = rnd.Next(randomUpBW.Length);

                        int[] randomStorage      = { 4000, 5000, 7000, 10000, 12000, 15000 };
                        var   randomStorageIndex = rnd.Next(randomStorage.Length);

                        int[] timeSlice      = { 15, 20, 25, 30 };
                        var   timeSliceIndex = rnd.Next(timeSlice.Length);



                        Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                        EnumNodeType randomDataType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));

                        edgeList.Add(new FogDevice(
                                         Guid.NewGuid(),
                                         1,
                                         randomMips[index],
                                         randomPe[index],
                                         randomRam[index],
                                         randomUpBW[index],
                                         randomDownBW[index],
                                         randomSize[index],
                                         randomStorage[index],
                                         edge.FogDevice.Name + "-" + i,
                                         randomDataType.ToString(),
                                         new CloudletScheduler(),
                                         GeoDistance.RandomGeoLocation(rnd),
                                         bit[b],
                                         0,
                                         PowerUtility.SetIdlePower(), timeSlice[timeSliceIndex])
                                     );
                    }
                    // for writing Json file

                    #endregion Fog
                }
                #endregion

                #region Create Tuple data Set

                if (tuple.TupleData.RAM != 0)
                {
                    T_homo_hetro = true;
                    for (int i = 0; i < tuple.TupleSize; i++)
                    {
                        Array            values         = Enum.GetValues(typeof(EnumDataTypeEdge));
                        EnumDataTypeEdge randomDataType = (EnumDataTypeEdge)values.GetValue(rnd.Next(values.Length));

                        Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                        EnumNodeType randomNodeType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));

                        tupleList.Add(new Models.Tuple(
                                          Guid.NewGuid(),
                                          1,
                                          tuple.TupleData.MIPS,
                                          tuple.TupleData.NumberOfPes,
                                          tuple.TupleData.RAM,
                                          tuple.TupleData.BW,
                                          tuple.TupleData.Size,
                                          "T-" + i,
                                          randomDataType.ToString(),
                                          100,
                                          0.0,
                                          "medium",
                                          new CloudletScheduler(),
                                          GeoDistance.RandomGeoLocation(rnd),
                                          false,
                                          randomNodeType.ToString(), 20, 0)
                                      );
                    }
                }
                else
                {
                    T_homo_hetro = false;
                    for (int i = 0; i < tuple.TupleSize; i++)
                    {
                        Array            values         = Enum.GetValues(typeof(EnumDataTypeEdge));
                        EnumDataTypeEdge randomDataType = (EnumDataTypeEdge)values.GetValue(rnd.Next(values.Length));
                        bool             MedORLB        = randomDataType.ToString() == "Medical" || randomDataType.ToString() == "LocationBased";

                        var        randomMipsIndex = 0;
                        bool       datatypecheck   = false;
                        List <int> randomMips      = new List <int>();
                        switch (randomDataType.ToString())
                        {
                        //case "Bulk":
                        //    randomMips.Add(500);
                        //    randomMips.Add(700);
                        //    randomMips.Add(900);
                        //    randomMips.Add(1000);
                        //    BulkOrLarge = true;
                        //    randomMipsIndex = rnd.Next(randomMips.Count) + 2;
                        //    break;
                        case "Abrupt":
                            randomMips.Add(350);
                            randomMips.Add(375);
                            randomMips.Add(400);
                            randomMips.Add(450);
                            datatypecheck   = true;
                            randomMipsIndex = rnd.Next(randomMips.Count) + 2;
                            break;

                        case "Large":
                            randomMips.Add(400);
                            randomMips.Add(450);
                            randomMips.Add(500);
                            randomMips.Add(700);
                            datatypecheck   = true;
                            randomMipsIndex = rnd.Next(randomMips.Count) + 2;
                            break;

                        case "Medical":
                            randomMips.Add(250);
                            randomMips.Add(270);
                            randomMips.Add(300);
                            randomMips.Add(350);
                            datatypecheck   = true;
                            randomMipsIndex = rnd.Next(randomMips.Count) + 2;
                            break;

                        case "LocationBased":
                            randomMips.Add(300);
                            randomMips.Add(350);
                            randomMips.Add(375);
                            randomMips.Add(400);
                            datatypecheck   = true;
                            randomMipsIndex = rnd.Next(randomMips.Count) + 2;
                            break;

                        //LocationBased
                        case "Multimedia":
                            randomMips.Add(325);
                            randomMips.Add(350);
                            randomMips.Add(375);
                            randomMips.Add(425);
                            datatypecheck   = true;
                            randomMipsIndex = rnd.Next(randomMips.Count) + 2;
                            break;

                        default:
                            randomMips.Add(75);
                            randomMips.Add(100);
                            randomMips.Add(120);
                            randomMips.Add(150);
                            randomMips.Add(150); randomMips.Add(175);
                            randomMipsIndex = rnd.Next(randomMips.Count);
                            break;
                        }
                        //MB
                        int[] randomRam = { 100, 150, 200, 300, 400, 512 };
                        // var randomRamIndex = rnd.Next(randomRam.Length);
                        var   index         = rnd.Next(randomRam.Length);
                        int[] randomPe      = { 1, 1, 1, 1, 1, 1 };
                        var   randomPeIndex = rnd.Next(randomPe.Length);

                        //MB
                        int[] randomSize      = { 80, 120, 170, 220, 270, 300 };
                        var   randomSizeIndex = rnd.Next(randomSize.Length);

                        //bit/sec
                        int[] randomBW      = { 20, 50, 80, 90, 100, 150 };
                        var   randomBWIndex = rnd.Next(randomBW.Length);

                        string[] _priority      = { "medium", "low" };
                        var      _priorityIndex = rnd.Next(_priority.Length);

                        double[] randomTupleBurstTimes = { 20, 40, 60 };
                        var      randomBusrtIndex      = rnd.Next(randomTupleBurstTimes.Length);


                        var    tupleMips         = datatypecheck == true ? randomMips[randomMipsIndex - 2] : randomMips[randomMipsIndex];
                        double burstTimeForTuple = 0.0;
                        if (tupleMips <= 100)
                        {
                            burstTimeForTuple = 10;
                        }

                        else if (tupleMips > 100 && tupleMips <= 300)
                        {
                            burstTimeForTuple = 15;
                        }

                        else if (tupleMips > 300 && tupleMips < 500)
                        {
                            burstTimeForTuple = 20;
                        }

                        else if (tupleMips > 500 && tupleMips < 700)
                        {
                            burstTimeForTuple = 25;
                        }
                        else if (tupleMips > 700 && tupleMips < 900)
                        {
                            burstTimeForTuple = 30;
                        }

                        else if (tupleMips > 900 && tupleMips <= 1200)
                        {
                            burstTimeForTuple = 35;
                        }
                        Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                        EnumNodeType randomNodeType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));
                        //if(BulkOrLarge) randomMipsIndex
                        tupleList.Add(new Models.Tuple(Guid.NewGuid(),
                                                       1,
                                                       datatypecheck == true ? randomMips[randomMipsIndex - 2] : randomMips[randomMipsIndex],
                                                       randomPe[randomMipsIndex],
                                                       randomRam[randomMipsIndex],
                                                       randomBW[randomMipsIndex],
                                                       randomSize[randomMipsIndex],
                                                       "T-" + i,
                                                       randomDataType.ToString(),
                                                       100,
                                                       0.0,
                                                       MedORLB == true ? "high" : _priority[_priorityIndex],
                                                       new CloudletScheduler(),
                                                       GeoDistance.RandomGeoLocation(rnd),
                                                       false,
                                                       randomNodeType.ToString(), burstTimeForTuple, 0)
                                      );
                    }
                }

                #endregion

                if (edgeList != null && tupleList != null)
                {
                    if (F_homo_hetro)
                    {
                        SimJson.WriteJson(edgeList, "EHomo", "JsonEdge.txt");
                    }
                    else
                    {
                        SimJson.WriteJson(edgeList, "EHetro", "JsonEdge.txt");
                    }
                    if (T_homo_hetro)
                    {
                        SimJson.WriteJson(tupleList, "EHomo", "JsonTuple.txt");
                    }
                    else
                    {
                        SimJson.WriteJson(tupleList, "EHetro", "JsonTuple.txt");
                    }
                }
                return(Ok("ok"));
            }
            catch (Exception ex)
            {
                return(Ok(ex.Message.ToString()));
            }
        }
예제 #33
0
 public GeoDistanceFilterBuilder(string name)
 {
     _name = name;
     _geoDistance = Nest.GeoDistance.arc;
 }
예제 #34
0
        public IHttpActionResult createDS(FogSimulationPost model)
        {
            try
            {
                Random rnd = new Random();

                FogPost             fog          = model.FogPost;
                Models.TuplePost    tuple        = model.TuplePost;
                bool                F_homo_hetro = true; //true means Homogenious Fogs
                bool                T_homo_hetro = true; //true mean Homogenious  Tuples
                long                FogSize      = fog.FogSize;
                List <FogDevice>    fogList      = new List <FogDevice>();
                List <Models.Tuple> tupleList    = new List <Models.Tuple>();

                #region create Fog dataSet
                if (fog.FogDevice.RAM != 0)
                {
                    #region Fog
                    F_homo_hetro = true;
                    for (int i = 0; i < FogSize; i++)
                    {
                        bool[] bit = { true, false };
                        var    b   = rnd.Next(bit.Length);

                        Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                        EnumNodeType randomDataType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));

                        fogList.Add(new FogDevice(
                                        Guid.NewGuid(),
                                        1,
                                        fog.FogDevice.MIPS,
                                        fog.FogDevice.NumberOfPes,
                                        fog.FogDevice.RAM,
                                        fog.FogDevice.UpBW,
                                        fog.FogDevice.DownBW,
                                        fog.FogDevice.Size,
                                        fog.FogDevice.Storage,
                                        fog.FogDevice.Name + "-" + i,
                                        randomDataType.ToString(),
                                        new CloudletScheduler(),
                                        GeoDistance.RandomGeoLocation(rnd),
                                        bit[b],
                                        0,
                                        PowerUtility.SetIdlePower(), 15)
                                    );
                    }

                    #endregion Fog
                }
                else
                {
                    #region Fog
                    F_homo_hetro = false;
                    for (int i = 0; i < FogSize; i++)
                    {
                        bool[] bit = { true };
                        var    b   = rnd.Next(bit.Length);

                        int[] randomRam = { 4096, 6144, 8192, 10240, 12288, 16384 };
                        //  var randomRamIndex = rnd.Next(randomRam.Length);
                        var index = rnd.Next(randomRam.Length);
                        ///commented original values
                        int[] randomMips = { 25000, 50000, 75000, 85000, 95000, 110000 };

                        //these smaller mips were added by ali for testing
                        //int[] randomMips = { 4000, 5000, 10000, 12000, 15000,3000 };


                        var randomMipsIndex = rnd.Next(randomMips.Length);

                        int[] randomPe      = { 1, 1, 2, 2, 3, 4 };
                        var   randomPeIndex = rnd.Next(randomPe.Length);

                        int[] randomSize      = { 7000, 10000, 12000, 15000, 20000, 25000 };
                        var   randomSizeIndex = rnd.Next(randomSize.Length);

                        int[] randomDownBW      = { 500, 700, 1000, 1200, 1500, 1700 };
                        var   randomDownBWIndex = rnd.Next(randomDownBW.Length);

                        int[] randomUpBW      = { 700, 1000, 1200, 1500, 2000, 2500 };
                        var   randomUpBWIndex = rnd.Next(randomUpBW.Length);

                        int[] randomStorage      = { 5000, 10000, 12000, 15000, 20000, 25000 };
                        var   randomStorageIndex = rnd.Next(randomStorage.Length);

                        //processor burst time is random since it is OS defined and processor defined and it is not calculated
                        int[] timeSlice      = { 15, 20, 25, 30 };
                        var   timeSliceIndex = rnd.Next(timeSlice.Length);

                        Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                        EnumNodeType randomDataType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));

                        fogList.Add(new FogDevice(
                                        Guid.NewGuid(),
                                        1,
                                        randomMips[index],
                                        randomPe[index],
                                        randomRam[index],
                                        randomUpBW[index],
                                        randomDownBW[index],
                                        randomSize[index],
                                        randomStorage[index],
                                        fog.FogDevice.Name + "-" + i,
                                        randomDataType.ToString(),
                                        new CloudletScheduler(),
                                        GeoDistance.RandomGeoLocation(rnd),
                                        bit[b],
                                        0,
                                        PowerUtility.SetIdlePower(), timeSlice[timeSliceIndex])
                                    );
                    }
                    // for writing Json file

                    #endregion Fog
                }
                #endregion

                #region Create Tuple data Set

                if (tuple.TupleData.RAM != 0)
                {
                    T_homo_hetro = true;
                    for (int i = 0; i < tuple.TupleSize; i++)
                    {
                        Array        values         = Enum.GetValues(typeof(EnumDataType));
                        EnumDataType randomDataType = (EnumDataType)values.GetValue(rnd.Next(values.Length));

                        Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                        EnumNodeType randomNodeType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));

                        tupleList.Add(new Models.Tuple(
                                          Guid.NewGuid(),
                                          1,
                                          tuple.TupleData.MIPS,
                                          tuple.TupleData.NumberOfPes,
                                          tuple.TupleData.RAM,
                                          tuple.TupleData.BW,
                                          tuple.TupleData.Size,
                                          "T-" + i,
                                          randomDataType.ToString(),
                                          100,
                                          0.0,
                                          "Medium",//its medium temporarly
                                          new CloudletScheduler(),
                                          GeoDistance.RandomGeoLocation(rnd),
                                          false,
                                          randomNodeType.ToString(), 20, 0)
                                      );
                    }
                }
                else
                {
                    T_homo_hetro = false;
                    for (int i = 0; i < tuple.TupleSize; i++)
                    {
                        Array        values          = Enum.GetValues(typeof(EnumDataType));
                        EnumDataType randomDataType  = (EnumDataType)values.GetValue(rnd.Next(values.Length));
                        var          randomMipsIndex = 0;
                        bool         BulkOrLarge     = false;
                        List <int>   randomMips      = new List <int>();
                        bool         MedORLB         = randomDataType.ToString() == "Medical" || randomDataType.ToString() == "LocationBased";
                        switch (randomDataType.ToString())
                        {
                        case "Bulk":
                            randomMips.Add(700);
                            randomMips.Add(900);
                            randomMips.Add(1000);
                            randomMips.Add(1200);
                            BulkOrLarge     = true;
                            randomMipsIndex = rnd.Next(randomMips.Count) + 2;
                            break;

                        case "Large":
                            randomMips.Add(500);
                            randomMips.Add(700);
                            randomMips.Add(900);
                            randomMips.Add(1000);
                            BulkOrLarge     = true;
                            randomMipsIndex = rnd.Next(randomMips.Count) + 2;
                            break;

                        default:
                            randomMips.Add(50);
                            randomMips.Add(75);
                            randomMips.Add(100);
                            randomMips.Add(150);
                            randomMips.Add(200);
                            randomMips.Add(250);

                            randomMipsIndex = rnd.Next(randomMips.Count);
                            break;
                        }
                        //MB
                        int[] randomRam = { 100, 150, 200, 300, 500, 1024 };
                        // var randomRamIndex = rnd.Next(randomRam.Length);
                        var   index         = rnd.Next(randomRam.Length);
                        int[] randomPe      = { 1, 1, 1, 1, 1, 1 };
                        var   randomPeIndex = rnd.Next(randomPe.Length);

                        //MB
                        int[] randomSize      = { 80, 120, 170, 220, 270, 300 };
                        var   randomSizeIndex = rnd.Next(randomSize.Length);

                        //bit/sec
                        int[] randomBW      = { 20, 50, 80, 90, 100, 150 };
                        var   randomBWIndex = rnd.Next(randomBW.Length);

                        string[] _priority      = { "medium", "low" };
                        var      _priorityIndex = rnd.Next(_priority.Length);

                        double[] randomTupleBurstTimes = { 20, 40, 60 };
                        var      randomBusrtIndex      = rnd.Next(randomTupleBurstTimes.Length);

                        Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                        EnumNodeType randomNodeType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));
                        //if(BulkOrLarge) randomMipsIndex

                        var    tupleMips         = BulkOrLarge == true ? randomMips[randomMipsIndex - 2] : randomMips[randomMipsIndex];
                        double burstTimeForTuple = 0.0;
                        if (tupleMips <= 100)
                        {
                            burstTimeForTuple = 10;
                        }

                        else if (tupleMips > 100 && tupleMips <= 300)
                        {
                            burstTimeForTuple = 15;
                        }

                        else if (tupleMips > 300 && tupleMips < 500)
                        {
                            burstTimeForTuple = 20;
                        }

                        else if (tupleMips > 500 && tupleMips < 700)
                        {
                            burstTimeForTuple = 25;
                        }
                        else if (tupleMips > 700 && tupleMips < 900)
                        {
                            burstTimeForTuple = 30;
                        }

                        else if (tupleMips > 900 && tupleMips <= 1200)
                        {
                            burstTimeForTuple = 35;
                        }

                        tupleList.Add(new Models.Tuple(Guid.NewGuid(),
                                                       1,
                                                       BulkOrLarge == true ? randomMips[randomMipsIndex - 2] : randomMips[randomMipsIndex],
                                                       randomPe[randomMipsIndex],
                                                       randomRam[randomMipsIndex],
                                                       randomBW[randomMipsIndex],
                                                       randomSize[randomMipsIndex],
                                                       "T-" + i,
                                                       randomDataType.ToString(),
                                                       100,
                                                       0.0,
                                                       //adding medical, location based and shortest jobs to high priority
                                                       MedORLB == true ? "high" : BulkOrLarge == true?"low":tupleMips <= 100?"high": _priority[_priorityIndex],
                                                       new CloudletScheduler(),
                                                       GeoDistance.RandomGeoLocation(rnd),
                                                       false,
                                                       randomNodeType.ToString(), burstTimeForTuple, 0)
                                      );
                    }
                }

                #endregion

                if (fogList != null && tupleList != null)
                {
                    if (F_homo_hetro)
                    {
                        SimJson.WriteJson(fogList, "H**o", "JsonFog.txt");
                    }
                    else
                    {
                        SimJson.WriteJson(fogList, "Hetro", "JsonFog.txt");
                    }
                    if (T_homo_hetro)
                    {
                        SimJson.WriteJson(tupleList, "H**o", "JsonTuple.txt");
                    }
                    else
                    {
                        SimJson.WriteJson(tupleList, "Hetro", "JsonTuple.txt");
                    }
                }
                return(Ok("ok"));
            }
            catch (Exception ex)
            {
                return(Ok(ex.Message.ToString()));
            }
        }
예제 #35
0
        public static void EdgeSimulation(FogPost edge, TuplePost tuple, string policy, int CommunicationType, int Service, List <string> DataCenter, string gateway, string cooperation, string edgeType)
        {
            if (cooperation == "0")
            {
                WithCoo = true;
            }
            Random    rnd    = new Random();
            Stopwatch watch  = new Stopwatch();
            var       result = new Results();

            edgeResultList = new List <Results>();
            edgeList       = new List <FogDevice>();
            tupleList      = new List <Models.Tuple>();
            PowerUtility.FillNumRange();
            string JsonReturn, path;

            #region DataSet population
            if (edgeType == "0")
            {
                #region Edge Homogenious

                path       = (new FileInfo(Path.Combine(FileInformation.GetDirectory(), "EHomo\\JsonEdge.txt"))).ToString();
                JsonReturn = SimJson.ReadJsonFile(path);
                edgeList   = JsonConvert.DeserializeObject <List <FogDevice> >(JsonReturn);
                EdgeSize   = edgeList.Count;

                #endregion Edge

                #region Tuple homogenious

                path       = (new FileInfo(Path.Combine(FileInformation.GetDirectory(), "EHomo\\JsonTuple.txt"))).ToString();
                JsonReturn = SimJson.ReadJsonFile(path);
                tupleList  = JsonConvert.DeserializeObject <List <Models.Tuple> >(JsonReturn);

                #endregion Tuple
            }
            else
            {
                #region Edge Hetrogenous

                path       = (new FileInfo(Path.Combine(FileInformation.GetDirectory(), "EHetro\\JsonEdge.txt"))).ToString();
                JsonReturn = SimJson.ReadJsonFile(path);
                edgeList   = JsonConvert.DeserializeObject <List <FogDevice> >(JsonReturn);
                EdgeSize   = edgeList.Count;

                #endregion Edge

                #region Tuple Hetrogenious

                path       = (new FileInfo(Path.Combine(FileInformation.GetDirectory(), "EHetro\\JsonTuple.txt"))).ToString();
                JsonReturn = SimJson.ReadJsonFile(path);
                tupleList  = JsonConvert.DeserializeObject <List <Models.Tuple> >(JsonReturn);
                #endregion Tuple
            }

            #region create fog for Edge-fog cloud
            if (CommunicationType == 1)
            {
                int fCount = Convert.ToInt32(EdgeSize / 2);
                for (int i = 0; i < fCount; i++)
                {
                    bool[] bit = { true };
                    var    b   = rnd.Next(bit.Length);

                    int[] randomRam = { 512, 1024, 2048, 3072, 3584, 4096 };
                    //  var randomRamIndex = rnd.Next(randomRam.Length);
                    var   index           = rnd.Next(randomRam.Length);
                    int[] randomMips      = { 2000, 4000, 8000, 12000, 18000, 20000 };
                    var   randomMipsIndex = rnd.Next(randomMips.Length);

                    int[] randomPe      = { 1, 1, 2, 2, 3, 4 };
                    var   randomPeIndex = rnd.Next(randomPe.Length);

                    int[] randomSize      = { 4000, 5000, 7000, 10000, 12000, 15000 };
                    var   randomSizeIndex = rnd.Next(randomSize.Length);

                    int[] randomDownBW      = { 400, 500, 700, 1000, 1200, 1500 };
                    var   randomDownBWIndex = rnd.Next(randomDownBW.Length);

                    int[] randomUpBW      = { 500, 700, 1000, 1200, 1500, 2000 };
                    var   randomUpBWIndex = rnd.Next(randomUpBW.Length);

                    int[] randomStorage      = { 2500, 4500, 5000, 7000, 10000, 12000 };
                    var   randomStorageIndex = rnd.Next(randomStorage.Length);

                    int[] timeSlice      = { 15, 20, 25, 30 };
                    var   timeSliceIndex = rnd.Next(timeSlice.Length);

                    Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                    EnumNodeType randomDataType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));

                    fogServers.Add(new FogDevice(
                                       Guid.NewGuid(),
                                       1,
                                       randomMips[index],
                                       randomPe[index],
                                       randomRam[index],
                                       randomUpBW[index],
                                       randomDownBW[index],
                                       randomSize[index],
                                       randomStorage[index],
                                       "fog" + "-" + i,
                                       randomDataType.ToString(),
                                       new CloudletScheduler(),
                                       GeoDistance.RandomGeoLocation(rnd),
                                       bit[b],
                                       0,
                                       PowerUtility.SetIdlePower(),
                                       timeSlice[timeSliceIndex])
                                   );
                }
            }

            #endregion

            #endregion
            SmartThreadPool s = new SmartThreadPool();
            s.MaxThreads = 1000;
            s.MinThreads = 1000;

            List <Task> myTaskList = new List <Task>();
            if (policy == "1")
            {
                //FCFS
                #region P1 FCFS

                s = new SmartThreadPool();
                watch.Start();
                foreach (var item in tupleList)
                {
                    // item.QueueDelay = watch.Elapsed.Milliseconds;
                    // FogUtility.EdgeSim(item, edgeList, CommunicationType);
                    s.QueueWorkItem(o => FogUtility.EdgeSim(item, edgeList, CommunicationType), new object());
                }
                watch.Stop();
                try
                {
                    s.WaitForIdle();
                    s.Shutdown();
                }
                catch { };
                #endregion
            }
            else if (policy == "2")
            {
                #region P2 SJF
                var localtupleList = tupleList.OrderBy(x => x.MIPS).ToList();

                s = new SmartThreadPool();
                watch.Start();
                foreach (var item in localtupleList)
                {
                    s.QueueWorkItem(o => FogUtility.EdgeSim(item, edgeList, CommunicationType), new object());
                }
                watch.Stop();
                try
                {
                    s.WaitForIdle();
                    s.Shutdown();
                }
                catch { };
                #endregion
            }
            else if (policy == "3")
            {
                #region P3 LJF
                var localtupleList = tupleList.OrderByDescending(x => x.MIPS).ToList();

                s = new SmartThreadPool();
                watch.Start();
                foreach (var item in localtupleList)
                {
                    s.QueueWorkItem(o => FogUtility.EdgeSim(item, edgeList, CommunicationType), new object());
                }
                watch.Stop();
                try
                {
                    s.WaitForIdle();
                    s.Shutdown();
                }
                catch { };
                #endregion
            }
            //inserted new policy #change
            //LBFC
            else if (policy == "4")
            {
                try
                {
                    IsCreateCache = true;
                    s             = new SmartThreadPool();
                    ///*getting 5% to inital execute*/
                    double initialRandomTuplesCount = Math.Ceiling((double)((tupleList.Count() * 5) / 100));
                    initial_tupleList = tupleList.Take(Convert.ToInt32(initialRandomTuplesCount)).ToList();
                    final_tupleList   = tupleList.Skip(Convert.ToInt32(initialRandomTuplesCount)).ToList();

                    myTaskList = new List <Task>();
                    var split = LinqExtensions.Split(initial_tupleList, 5).ToList();
                    for (int j = 0; j < split.Count(); j++)
                    {
                        foreach (var item in split[j])
                        {
                            int[] ranIndex       = { 0, 1, 0, 1 };
                            var   randCloudIndex = rnd.Next(ranIndex.Length);

                            watch.Start();

                            if (randCloudIndex == 0)
                            {
                                myTaskList.Add(Task.Factory.StartNew(() =>
                                {
                                    var tupleTime = new TupleTimes()
                                    {
                                        TupleArrival = DateTime.Now.ToString("hh:mm:ss.fff tt"), Name = item.Name
                                    };
                                    lock (Lock)
                                        EdgeSimulator.TupleTimings.Add(tupleTime);
                                    FogUtility.EdgeSim(item, edgeList, CommunicationType);
                                }));
                            }
                            else
                            {
                                myTaskList.Add(Task.Factory.StartNew(() =>
                                {
                                    var tupleTime = new TupleTimes()
                                    {
                                        TupleArrival = DateTime.Now.ToString("hh:mm:ss.fff tt"), Name = item.Name
                                    };
                                    lock (Lock)
                                        FogSimulator.TupleTimings.Add(tupleTime);
                                    FogUtility.FogSimulationForEdge(item, fogServers);
                                }));
                            }
                        }
                    }
                    Task.WaitAll(myTaskList.ToArray());
                    #region threadpool base
                    try
                    {
                        FogCache F_cache, C_cache;
                        ///both are same for edge also
                        foreach (var item in final_tupleList)
                        {
                            lock (Lock)
                            {
                                F_cache = FogUtility.fogCahce.Where(x => x.DataType == item.DataType).OrderBy(x => x.InternalProcessingTime).OrderBy(x => x.link.Propagationtime).FirstOrDefault();
                                C_cache = EdgeCahce.Where(x => x.DataType == item.DataType).OrderBy(x => x.InternalProcessingTime).OrderBy(x => x.link.Propagationtime).FirstOrDefault();
                            }
                            watch.Start();
                            if (F_cache == null || C_cache == null)
                            {
                                int[] ranIndex       = { 0, 1, 0, 1 };
                                var   randCloudIndex = rnd.Next(ranIndex.Length);
                                watch.Start();
                                if (randCloudIndex == 0)
                                {
                                    s.QueueWorkItem(o => FogUtility.EdgeSim(item, edgeList, CommunicationType), new object());
                                }
                                else
                                {
                                    s.QueueWorkItem(o => FogUtility.FogSimulationForEdge(item, fogServers), new object());
                                }
                            }
                            else
                            {
                                //for predication base
                                double _CTime = C_cache.InternalProcessingTime + C_cache.link.Propagationtime;
                                double _FTime = F_cache.InternalProcessingTime + F_cache.link.Propagationtime;

                                if (_CTime >= _FTime)
                                {
                                    s.QueueWorkItem(o => FogUtility.EdgeSim(item, edgeList, CommunicationType), new object());
                                }
                                else
                                {
                                    s.QueueWorkItem(o => FogUtility.FogSimulationForEdge(item, fogServers), new object());
                                }
                            }
                        }
                        try
                        {
                            s.WaitForIdle();
                            s.Shutdown();
                        }
                        catch { };
                    }
                    catch (Exception ex)
                    {
                        throw new ArgumentException(ex.Message);
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    throw new ArgumentException(ex.Message);
                }
            }
            else
            {
                #region random
                try
                {
                    var split = LinqExtensions.Split(tupleList, 16).ToList();
                    watch.Start();
                    s = new SmartThreadPool();
                    for (int j = 0; j < split.Count(); j++)
                    {
                        foreach (var item in split[j])
                        {
                            s.QueueWorkItem(o => FogUtility.EdgeSim(item, edgeList, CommunicationType), new object());
                        }
                    }

                    try
                    {
                        s.WaitForIdle();
                        s.Shutdown();
                    }
                    catch { };
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                #endregion
            }
            watch.Stop();
            if (policy == "4")
            {
                if (edgeResultList != null)
                {
                    Excel.CreateExcelSheetEdgeFog(edgeResultList, FogTimings.ToList(), TupleTimings.ToList(), DropedtupleList.ToList());
                }
            }
            else

            {
                Excel.CreateExcelSheetEdgeFog(edgeResultList, FogTimings.ToList(), TupleTimings.ToList(), DropedtupleList.ToList());
                if (CommunicationType == 1)
                {
                    Excel.CreateExcelSheetForFog(FogSimulator.resultList, FogSimulator.FogTimings.ToList(), FogSimulator.TupleTimings.ToList());
                }
            }
        }
예제 #36
0
        public static void CloudSimulation(TuplePost tuple, string policy, int _service, List <string> datacenter)
        {
            resultList = new ConcurrentBag <Results>();
            Random rnd    = new Random();
            var    result = new Results();

            #region Cloud

            bool[] bit = { true };
            var    b   = rnd.Next(bit.Length);

            // create service
            var service = ServicesUtility.GetServices()[_service];

            #endregion Cloud

            if (FogSimulator.tupleList.Count == 0)
            {
                if (tuple.TupleData.RAM != 0)
                {
                    #region Tuple

                    for (int i = 0; i < tuple.TupleSize; i++)
                    {
                        Array        values         = Enum.GetValues(typeof(EnumDataType));
                        EnumDataType randomDataType = (EnumDataType)values.GetValue(rnd.Next(values.Length));

                        Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                        EnumNodeType randomNodeType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));

                        tupleList.Add(new Models.Tuple(
                                          Guid.NewGuid(),
                                          1,
                                          tuple.TupleData.MIPS,
                                          tuple.TupleData.NumberOfPes,
                                          tuple.TupleData.RAM,
                                          tuple.TupleData.BW,
                                          tuple.TupleData.Size,
                                          "T-" + i,
                                          randomDataType.ToString(),
                                          100,
                                          0.0,
                                          "medium",
                                          new CloudletScheduler(),
                                          GeoDistance.RandomGeoLocation(rnd),
                                          false,
                                          randomNodeType.ToString(), 0, 0)
                                      );
                    }

                    #endregion Tuple
                }
                else
                {
                    #region Tuple
                    for (int i = 0; i < tuple.TupleSize; i++)
                    {
                        int[] randomRam      = { 10, 25, 50, 100, 150, 200 };
                        var   randomRamIndex = rnd.Next(randomRam.Length);

                        int[] randomMips      = { 100, 150, 300, 400, 500, 700 };
                        var   randomMipsIndex = rnd.Next(randomMips.Length);

                        int[] randomPe      = { 1 };
                        var   randomPeIndex = rnd.Next(randomPe.Length);

                        int[] randomSize      = { 10, 20, 50, 70, 100 };
                        var   randomSizeIndex = rnd.Next(randomSize.Length);

                        int[] randomBW      = { 10, 30, 50, 80, 100 };
                        var   randomBWIndex = rnd.Next(randomBW.Length);

                        string[] _priority      = { "medium", "low" };
                        var      _priorityIndex = rnd.Next(_priority.Length);

                        Array        values         = Enum.GetValues(typeof(EnumDataType));
                        EnumDataType randomDataType = (EnumDataType)values.GetValue(rnd.Next(values.Length));
                        bool         MedORLB        = randomDataType.ToString() == "Medical" || randomDataType.ToString() == "LocationBased";

                        Array        NodeTypevalues = Enum.GetValues(typeof(EnumNodeType));
                        EnumNodeType randomNodeType = (EnumNodeType)NodeTypevalues.GetValue(rnd.Next(NodeTypevalues.Length));

                        tupleList.Add(new Models.Tuple(
                                          Guid.NewGuid(),
                                          1,
                                          randomMips[randomMipsIndex],
                                          randomPe[randomPeIndex],
                                          randomRam[randomRamIndex],
                                          randomBW[randomBWIndex],
                                          randomSize[randomSizeIndex],
                                          "T-" + i,
                                          randomDataType.ToString(),
                                          100,
                                          0.0,
                                          MedORLB == true ? "high" : _priority[_priorityIndex],
                                          new CloudletScheduler(),
                                          GeoDistance.RandomGeoLocation(rnd),
                                          false,
                                          randomNodeType.ToString(), 0, 0)
                                      );
                    }

                    #endregion Tuple
                }
            }
            else
            {
                tupleList = FogSimulator.tupleList;
            }
            List <Task> myTaskList = new List <Task>();
            if (policy == "1")
            {
                watch.Start();
                foreach (var item in tupleList)
                {
                    item.QueueDelay = watch.Elapsed.Milliseconds;
                    CloudUtility.CloudSim(item, service, datacenter);
                }
                watch.Stop();
            }
            else if (policy == "2")
            {
                var localtupleList = tupleList.OrderBy(x => x.MIPS).ToList();
                watch.Start();
                foreach (var item in localtupleList)
                {
                    item.QueueDelay = watch.Elapsed.Milliseconds;
                    CloudUtility.CloudSim(item, service, datacenter);
                }
                watch.Stop();
            }
            else if (policy == "3")
            {
                var localtupleList = tupleList.OrderByDescending(x => x.MIPS).ToList();
                watch.Start();
                foreach (var item in localtupleList)
                {
                    item.QueueDelay = watch.Elapsed.Milliseconds;
                    CloudUtility.CloudSim(item, service, datacenter);
                }
                watch.Stop();
            }
            else
            {
                var split = LinqExtensions.Split(tupleList, 16).ToList();
                watch.Start();
                for (int j = 0; j < split.Count(); j++)
                {
                    foreach (var item in split[j])
                    {
                        //commented task section by Ali for testing
                        //myTaskList.Add(Task.Factory.StartNew(() =>
                        //{
                        item.QueueDelay = watch.Elapsed.Milliseconds;
                        CloudUtility.CloudSim(item, service, datacenter);
                        //}));
                    }
                }
                watch.Stop();
                Task.WaitAll(myTaskList.ToArray());
            }
            Excel.CreateExcelSheetForCloud(resultList.ToList());

            resultList = new ConcurrentBag <Results>();
            tupleList  = new List <Models.Tuple>();
        }