Esempio n. 1
0
 public void removeOccupant(Occupant occupant, int playerNum)
 {
     if (playerNum == 1)
     {
         player1Occupants.Remove(occupant);
     }
     if (playerNum == 2)
     {
         player2Occupants.Remove(occupant);
     }
 }
Esempio n. 2
0
    public void PlaceEnemy(Occupant occupant)
    {
        RoomManager randomRoom = GetRandomRoom();
        //Instantiate a stair prefab at a random tile in the room
        TileStructure randomTile = randomRoom.GetRandomTile();
        Vector2       position   = new Vector2(randomTile.location.x + .5f, randomTile.location.y + .6f);

        Debug.Log(position);
        GameObject tempPoke = Instantiate(pokemonPrefab, position, transform.rotation);

        tempPoke.GetComponent <Pokemon>().InitializePokemon(occupant.basePokemon, Random.Range(occupant.minLevel, occupant.maxLevel));
    }
        public ActionResult Create([Bind(Include = "OccupantID,HouseholdID,MaleQuantity,FemaleQuantity,ChildQuantity,OccupantNotes,SelfEmployed,EmployedFull,EmployedPart,Home,Retired,Unemployed,School,Further,GovWork,PreSchool,Other,DemographicNotes,BedroomQuantity,UpdateDate")] Occupant occupant, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                db.Occupants.Add(occupant);
                db.SaveChanges();
                return(Redirect(returnUrl));
            }

            ViewBag.HouseholdID = new SelectList(db.Households, "HouseholdID", "WPnumber", occupant.HouseholdID);
            return(View(occupant));
        }
 public void Init()
 {
     possitions[0]   = new Coords(-23, 10);
     possitions[1]   = new Coords(2, 10);
     r1              = new Circle(0, 0);
     r2              = new Circle(0, 60);
     p1              = new Coords(0, 0);
     p2              = new Coords(0, 3);
     trian           = new Triangulation(r1, r2);
     lightToActivate = new DetermineLightsToActivate(200, 60, 400, trian);
     oc              = new Occupant();
     oc.UpdatePositions(100, 100);
 }
        public void Init()
        {
            possitions[0] = new Coords(-23, 10);
            possitions[1] = new Coords(2, 10);

            r1    = new Circle(0, 0);
            r2    = new Circle(0, 60);
            p1    = new Coords(0, 0);
            p2    = new Coords(0, 3);
            trian = new Triangulation(r1, r2);
            oc    = new Occupant();
            oc.UpdatePositions(60, 60);
        }
Esempio n. 6
0
        public async Task <RentleResponse> Delete(IEnumerable <string> ids)
        {
            foreach (string id in ids)
            {
                Occupant occupant = await _occupant.FindOneAndDeleteAsync(o => o.ID == id);
            }

            if (ids.Count() == 1)
            {
                return(new RentleResponse("Le locataire a été supprimer avec succés", true));
            }
            return(new RentleResponse("Les locataires ont bien été supprimé avec succés", true));
        }
        // GET: Occupants/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Occupant occupant = db.Occupants.Find(id);

            if (occupant == null)
            {
                return(HttpNotFound());
            }
            return(View(occupant));
        }
        // GET: Occupants/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Occupant occupant = db.Occupants.Find(id);

            if (occupant == null)
            {
                return(HttpNotFound());
            }
            ViewBag.HouseholdID = new SelectList(db.Households, "HouseholdID", "WPnumber", occupant.HouseholdID);
            return(View(occupant));
        }
Esempio n. 9
0
 public Coords ExcludeImpossiblePositions(Occupant Source, Coords[] PositionsOfSignalSource)
 {
     if (PositionsOfSignalSource[0].x <0 || PositionsOfSignalSource[0].x> GEngine.SimulationWidht)
     {
         return(PositionsOfSignalSource[1]);
     }
     else if (PositionsOfSignalSource[0].y <0 || PositionsOfSignalSource[0].y> GEngine.SimulationHeigt)
     {
         return(PositionsOfSignalSource[1]);
     }
     else
     {
         return(PositionsOfSignalSource[0]);
     }
 }
Esempio n. 10
0
        private static Occupant MakeOccupant([ItemNotNull][NotNull] List <PotentialPerson> eligiablePersons, [NotNull] Random r, [ItemNotNull][NotNull] List <PotentialPerson> potentialPersons,
                                             [NotNull] Household potentialHousehold)
        {
            var pp = eligiablePersons[r.Next(eligiablePersons.Count)];

            potentialPersons.Remove(pp);
            var occ = new Occupant {
                Age           = pp.Age,
                Gender        = pp.Gender,
                HouseholdGuid = potentialHousehold.HouseholdGuid,
                OccupantGuid  = Guid.NewGuid().ToString(),
                HouseGuid     = potentialHousehold.HouseGuid
            };

            return(occ);
        }
Esempio n. 11
0
    public void nextInQueue()
    {
        Occupant occupant = null;

        if (updateQueue.Count != 0)
        {
            occupant = updateQueue.Dequeue();
            if (occupant != null)
            {
                occupant.endOfTurnUpdate(nextInQueue);
            }
        }
        else if (updateQueue.Count == 0)
        {
            queueCompleted();
        }
    }
Esempio n. 12
0
        public void DetermineSignalStrengthFromCoords(Occupant SignalSource, Circle Router1, Circle Router2)
        {
            Coords CoordinatesTouse = new Coords();

            if (SignalSource.IsPosition2Initialized == false)
            {
                CoordinatesTouse = SignalSource.Position1;
            }
            else
            {
                CoordinatesTouse = SignalSource.Position2;
            }

            //Distance between Router and CoordinatesTouse, set this to the radius of Router

            Router1.Radius = CalculateDistanceBetweenPoints(CoordinatesTouse, Router1);
            Router2.Radius = CalculateDistanceBetweenPoints(CoordinatesTouse, Router2);
        }
Esempio n. 13
0
        //Determines what lights need to be activated around the user. Not based on movement.
        //Receives a list of coordinates for every lighting unit in a room (LightingUnitsCoordinates), as well as the last known position of the
        //signal source (UserCoordinates). Calls "ExistsInCircle" to determine whether or not the lights in the room are close
        //enough to activate. If they are (if their coordinates exist in the circle around the user), the coordinates to the lighting
        //unit is stored in the LightingUnitsToActivate list (List<LightingUnits>), which is returned when every lighting unit has been checked.
        //Furthermore, the LightingLevel variable from the LightingUnit class is set by CalculateLightingLevel.

        public List <LightingUnit> LightsToActivateOnUser(Occupant Occupant, List <LightingUnit> LightingUnits)
        {
            List <LightingUnit> LightingUnitsToActivateOnUser = new List <LightingUnit>();

            foreach (LightingUnit LightingUnitToCheck in LightingUnits)
            {
                if (ExistsInCircle(Occupant.LatestPosition(), LightingUnitToCheck))
                {
                    LightingUnitToCheck.wantedLightLevel = Math.Round((CalculateLightingLevel(Occupant.LatestPosition(),
                                                                                              LightingUnitToCheck,
                                                                                              _radius)), 2);

                    LightingUnitsToActivateOnUser.Add(LightingUnitToCheck);
                }
            }

            EnsureCorrectLightingLevels(LightingUnitsToActivateOnUser);
            return(LightingUnitsToActivateOnUser);
        }
Esempio n. 14
0
        public IHttpActionResult Create([FromBody] Occupant item)
        {
            using (var _dbContext = new ApplicationDbContext())
            {
                if (item == null)
                {
                    return(BadRequest());
                }

                item.CreatedOn = DateTime.UtcNow;
                item.UpdatedOn = DateTime.UtcNow;

                _dbContext.Occupants.Add(item);

                _dbContext.SaveChanges();

                return(Ok(item));
            }
        }
Esempio n. 15
0
    public int GridDistanceBetweenOccupants(Occupant a, Occupant b, int maxDistance)
    {
        int distance = 0;

        InternalOccupant occupantA = a as InternalOccupant;
        InternalOccupant occupantB = b as InternalOccupant;

        if (occupantA == null || occupantB == null)
        {
            Debug.LogWarning("One of these occupants is null wtf!");
        }
        if (occupantA.TrackedGameObject == null || occupantB.TrackedGameObject == null)
        {
            Debug.LogWarning("Unable to calculate grid distances between two occupants that do not track GameObjects");
            return(-1);
        }

        distance = GridDistanceBetweenVectors(occupantA.TrackedGameObject.transform.position, occupantB.TrackedGameObject.transform.position, maxDistance);

        return(distance);
    }
Esempio n. 16
0
        public void Start()
        {
            //Initializations
            _occupant = new Occupant(Map, Window, 'W', 'S', 'A', 'D');
            gEngine   = new GEngine(Window, Map, SimulationRoom);
            CreateLightUnit();
            Controller = new DALIController(LightUnitCoordinates);
            Controller.InitGroups();
            InfoScreen   = new InfoScreen(Window, Controller);
            ControlPanel = new ControlPanel(Window, Controller, LightUnitCoordinates, InfoScreen, SimulationRoom);


            //Draw info
            Info = new InfoDrawing(Window);
            Info.initWattInfo();
            Info.InitBrugerPosWiFi();
            Info.InitBrugerPos();

            //Quadtree, initialize the graphics engine and load the visual level
            _tree.CreateQuadTree(LightUnitCoordinates);
            gEngine.init();
            gEngine.LoadLevel(LightUnitCoordinates, Router1, Router2);
        }
Esempio n. 17
0
 /// <summary>
 /// Change the background image of the picture box.
 /// The occupant what image is in the square.
 /// Change his state.
 /// </summary>
 /// <param name="m_Occupant">Define what will be inside the square.</param>
 public void Change_Image(Occupant m_Occupant)
 {
     if (m_Occupant == Occupant.King)
     {
         this.BackgroundImage = Tablut.Properties.Resources.white_Pawn_King;
         this.Occupant        = Occupant.King;
     }
     else if (m_Occupant == Occupant.Defender)
     {
         this.BackgroundImage = Tablut.Properties.Resources.white_Pawn;
         this.Occupant        = Occupant.Defender;
     }
     else if (m_Occupant == Occupant.Attacker)
     {
         this.BackgroundImage = Tablut.Properties.Resources.black_Pawn;
         this.Occupant        = Occupant.Attacker;
     }
     else if (m_Occupant == Occupant.Empty)
     {
         this.BackgroundImage = Tablut.Properties.Resources.square_Highlight;
         this.Occupant        = Occupant.Empty;
     }
 }
Esempio n. 18
0
        private async void onSubmit(object sender, EventArgs e)
        {
            bool isFieldsFilled = FormUtils.isFieldFilled(
                tb_name, tb_surname, tb_email, tb_gsm,
                tb_nationalRegistry, tb_street, tb_zipcode,
                tb_city, tb_country, cb_guarantor);

            if (isFieldsFilled)
            {
                MessageBox.Show("Chargement ...", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                string   gender           = (string)cb_gender.SelectedItem;
                string   name             = tb_name.Text;
                string   surname          = tb_surname.Text;
                string   email            = tb_email.Text;
                string   gsm              = tb_gsm.Text;
                string   nationalRegistry = tb_nationalRegistry.Text;
                DateTime birthDate        = dtp_birthDate.Value;
                string   street           = tb_street.Text;
                string   zipcode          = tb_zipcode.Text;
                string   city             = tb_city.Text;
                string   country          = tb_country.Text;

                Occupant occupant = new Occupant(null, gender, name, surname, email, gsm, nationalRegistry, birthDate, guarantorSelected.ID);
                occupant.Address = new Location(street, zipcode, city, country);

                Dictionary <string, object> occupantDic = Utils.ToDictionnary(occupant);
                string occupantJSON = Utils.ToJson(occupantDic);
                APIRes response     = await Utils.Post(@"http://localhost:5000/api/occupants", occupantJSON);

                if (response.Success)
                {
                    MessageBox.Show(response.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                MessageBox.Show(response.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 19
0
        public List <Occupant> Find(bool withoutLease)
        {
            List <Occupant> occupants          = new List <Occupant>();
            IEnumerable <OccupantJoined> query = Join();

            if (withoutLease)
            {
                query = query.Where(q => {
                    return(q.Lease == null);
                });
            }
            List <OccupantJoined> queryList = query.ToList();

            for (int i = 0; i < queryList.Count; i++)
            {
                Occupant occupant = queryList[i].Occupant;
                occupant.Guarantor      = queryList[i].Guarantor;
                occupant.PropertyLeased = queryList[i].Property;
                occupant.Lease          = queryList[i].Lease;
                occupants.Add(occupant);
            }

            return(occupants);
        }
Esempio n. 20
0
 public Sortie(int position)
 {
     this.position = position;
     this.occupant = null;
 }
Esempio n. 21
0
 public void Init()
 {
     oc = new Occupant();
 }
Esempio n. 22
0
        protected override void RunActualProcess()
        {
            SqlConnection.RecreateTable <OutgoingCommuterEntry>(Stage.Houses, Constants.PresentSlice);
            SqlConnection.RecreateTable <CarDistanceEntry>(Stage.Houses, Constants.PresentSlice);
            var dbHouses  = SqlConnection.GetDatabaseConnection(Stage.Houses, Constants.PresentSlice).Database;
            var dbRaw     = SqlConnection.GetDatabaseConnection(Stage.Raw, Constants.PresentSlice).Database;
            var occupants = dbHouses.Fetch <Occupant>();
            var outGoings = dbRaw.Fetch <OutgoingCommuter>();

            if (occupants.Count == 0)
            {
                throw new Exception("No occupants found");
            }

            var entries = new List <OutgoingCommuterEntry>();

            foreach (var commuter in outGoings)
            {
                for (var i = 0; i < commuter.Erwerbstätige; i++)
                {
                    var oce = new OutgoingCommuterEntry {
                        CommuterGuid = Guid.NewGuid().ToString()
                    };
                    var method = Services.Rnd.NextDouble();

                    if (method < 0.52)
                    {
                        oce.CommuntingMethod = CommuntingMethod.Car;
                    }
                    else
                    {
                        oce.CommuntingMethod = CommuntingMethod.PublicTransport;
                    }

                    oce.DistanceInKm = commuter.Entfernung;
                    oce.WorkCity     = commuter.Arbeitsgemeinde;
                    oce.WorkKanton   = commuter.Arbeitskanton;
                    entries.Add(oce);
                }
            }

            dbHouses.BeginTransaction();
            //HashSet<string> usedHouseholdIDs = new HashSet<string>();
            //oce.CommuniterDistanceInKm = commuter.Entfernung + 27.39; //freizeit km nach mikromobilitätszensus, 12.05 auto-km/tag/person, 0.44 autos pro person = 27.39 km/tag
            var potentialOccupants = occupants.Where(x => x.Age > 18 && x.Age < 65).ToList();
            var cars = dbHouses.Fetch <Car>();
            var householdGuidsWithCar = cars.Select(x => x.HouseholdGuid).ToList();
            var occupantsWithCar      = potentialOccupants.Where(x => householdGuidsWithCar.Contains(x.HouseholdGuid)).ToList();
            var occupantsWithoutCar   = potentialOccupants.Where(x => !occupantsWithCar.Contains(x)).ToList();
            //List<CarDistanceEntry> cdes = new List<CarDistanceEntry>();
            List <Car> availableCars = cars.ToList();

            while (entries.Count > 0)
            {
                OutgoingCommuterEntry ogce = entries[0];
                entries.RemoveAt(0);
                Occupant oc = null;

                if (ogce.CommuntingMethod == CommuntingMethod.Car)
                {
                    Car myCar = null;
                    while (myCar == null)
                    {
                        oc = occupantsWithCar[Services.Rnd.Next(occupantsWithCar.Count)];
                        occupantsWithCar.Remove(oc);
                        myCar = availableCars.FirstOrDefault(x => x.HouseholdGuid == oc.HouseholdGuid);
                    }
                    availableCars.Remove(myCar);
                    CarDistanceEntry cd = new CarDistanceEntry(oc.HouseGuid, oc.HouseholdGuid, myCar.CarGuid, ogce.DistanceInKm, 27.4);
                    //cdes.Add(cd);
                    dbHouses.Save(cd);
                }
                else
                {
                    if (occupantsWithoutCar.Count > 0)
                    {
                        oc = occupantsWithoutCar[Services.Rnd.Next(occupantsWithoutCar.Count)];
                        occupantsWithoutCar.Remove(oc);
                    }
                    else
                    {
                        oc = occupantsWithCar[Services.Rnd.Next(occupantsWithCar.Count)];
                        occupantsWithCar.Remove(oc);
                    }
                }
                ogce.HouseholdGuid = oc.HouseholdGuid;
                ogce.HouseGuid     = oc.HouseGuid;
                ogce.CommuterGuid  = Guid.NewGuid().ToString();
                dbHouses.Save(ogce);
            }

            foreach (Car car in availableCars)
            {
                CarDistanceEntry cd = new CarDistanceEntry(car.HouseGuid, car.HouseholdGuid, car.CarGuid, 0, 27.4);
                dbHouses.Save(cd);
            }
            dbHouses.CompleteTransaction();
        }
        public void FindLightsInPath_ReturnNullTest()
        {
            Occupant temp = new Occupant();

            Assert.IsNull(lightToActivate.LightsToActivateInPath(temp, list));
        }
Esempio n. 24
0
 public Coords GetMovementVector(Occupant occupant)
 {
     return(vector);
 }
Esempio n. 25
0
 // Return the Occupant to the manager
 // occupant - The Occupant that is being returned
 public void ReturnOccupant(ref Occupant occupant)
 {
     ReturnInternalOccupant(occupant as InternalOccupant);
     occupant = null;
 }
Esempio n. 26
0
        protected override void RunActualProcess([NotNull] ScenarioSliceParameters slice)
        {
            Info("running house copying");
            //kill off old people
            //save killed old people
            //delete households and remember now free households
            //put new people into households

            Info("Aging occupants");
            var dbSrcHouses   = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, slice.PreviousSliceNotNull);
            var srcHouseholds = dbSrcHouses.Fetch <Household>();
            var allOccupants  = srcHouseholds.SelectMany(x => x.Occupants).ToList().AsReadOnly();

            foreach (var srcOccupant in allOccupants)
            {
                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                // ReSharper disable once HeuristicUnreachableCode
                if (srcOccupant.HouseholdKey == null)
                {
                    // ReSharper disable once HeuristicUnreachableCode
                    throw new FlaException("Householdkey was null");
                }
            }

            var    dbDstHouses           = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, slice);
            var    dstHouses             = dbDstHouses.Fetch <House>();
            var    hausanschlusses       = dbDstHouses.Fetch <Hausanschluss>();
            double energyReductionFactor = slice.EnergyReductionFactorHouseholds;

            if (Math.Abs(energyReductionFactor) < 0.000001)
            {
                throw new FlaException("Factor 0 for household energy reduction in slice " + slice);
            }

            foreach (var srcHousehold in srcHouseholds)
            {
                srcHousehold.LocalnetEntries.Clear();
                srcHousehold.SetEnergyReduction(slice.DstYear.ToString(), srcHousehold.EffectiveEnergyDemand * (1 - energyReductionFactor));
            }

            var yearsToAge = slice.DstYear - slice.PreviousSlice?.DstYear ?? throw new FlaException("No Previous Scenario Set");

            foreach (var occ in allOccupants)
            {
                occ.Age += yearsToAge;
            }

            ApplyDeathsIncludingPersistence(slice, srcHouseholds, allOccupants);

            srcHouseholds = PutPeopleIntoTheHouseholds(allOccupants, srcHouseholds);

            //create new people
            BirthNewChildren(slice, srcHouseholds);

            //allocate additional households
            foreach (var srcHousehold in srcHouseholds)
            {
                if (srcHousehold.Occupants.Count == 0)
                {
                    throw new FlaException("household with no occupants found ");
                }
            }

            var householdsByHouseGuid = new Dictionary <string, List <Household> >();

            foreach (var household in srcHouseholds)
            {
                if (!householdsByHouseGuid.ContainsKey(household.HouseGuid))
                {
                    householdsByHouseGuid.Add(household.HouseGuid, new List <Household>());
                }

                householdsByHouseGuid[household.HouseGuid].Add(household);
            }

            List <HouseWithHouseholds> allhwhs = new List <HouseWithHouseholds>();

            foreach (var house in dstHouses)
            {
                HouseWithHouseholds hwh;
                if (householdsByHouseGuid.ContainsKey(house.Guid))
                {
                    hwh = new HouseWithHouseholds(house, householdsByHouseGuid[house.Guid]);
                }
                else
                {
                    hwh = new HouseWithHouseholds(house, new List <Household>());
                }

                allhwhs.Add(hwh);
            }

            List <Household> newHouseholds = new List <Household>();

            var persistenceDb = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, slice, DatabaseCode.Persistence);

            persistenceDb.CreateTableIfNotExists <PersistenceMigrationHouseholdEntry>();
            persistenceDb.CreateTableIfNotExists <PersistenceMigratedOccupant>();
            var persistencenewHouseholdEntries = persistenceDb.Fetch <PersistenceMigrationHouseholdEntry>();

            var migrants               = persistenceDb.Fetch <PersistenceMigratedOccupant>();
            int targetPopulation       = (int)slice.TargetPopulationAfterMigration;
            int exisitingPopulation    = srcHouseholds.Sum(x => x.Occupants.Count);
            int numberOfPeopleMovingIn = targetPopulation - exisitingPopulation;

            if (numberOfPeopleMovingIn < 0)
            {
                throw new FlaException("Targetpopulation below natural population count. Add more deaths. Target was " + targetPopulation +
                                       " natural population was : " + exisitingPopulation + " in the slice " + slice + " diff: " +
                                       numberOfPeopleMovingIn);
            }

            if (numberOfPeopleMovingIn < migrants.Count)
            {
                migrants = migrants.Take(numberOfPeopleMovingIn).ToList();
            }

            var persistanceMigrantsHouseKeys = migrants.Select(x => x.HouseholdKey).Distinct().ToList();

            persistenceDb.BeginTransaction();
            var householdsWithNewlyAddedPeople = new List <Household>();

            foreach (var nhhe in persistencenewHouseholdEntries)
            {
                var hwh = allhwhs.FirstOrDefault(x => x.House.ComplexName == nhhe.HouseName);
                if (hwh == null)
                {
                    persistenceDb.Delete(nhhe);
                    continue;
                }

                if (hwh.RemainingOpenHouseholds == 0)
                {
                    double avgEbf = hwh.House.Appartments.Average(x => x.EnergieBezugsFläche);
                    hwh.House.Appartments.Add(new AppartmentEntry(Guid.NewGuid().ToString(), avgEbf, true, slice.DstYear));
                }

                var hausanschluss = hwh.House.GetHausanschlussByIsn(new List <int>(), null, hausanschlusses, MyLogger) ??
                                    throw new FlaException("no hausanschluss");
                var hh = new Household(nhhe.Name,
                                       hwh.House.Guid,
                                       hausanschluss.Guid,
                                       hwh.House.ComplexName,
                                       hausanschluss.Standort,
                                       Guid.NewGuid().ToString());
                if (!persistanceMigrantsHouseKeys.Contains(hh.HouseholdKey))
                {
                    Info("Deleted persistance household because no persistent occupants could be found");
                    persistenceDb.Delete(nhhe);
                    continue;
                }

                if (newHouseholds.Any(x => x.HouseholdKey == hh.HouseholdKey))
                {
                    Info("Deleted persistance household because duplicated key");
                    persistenceDb.Delete(nhhe);
                    continue;
                }

                hwh.Households.Add(hh);

                newHouseholds.Add(hh);
                householdsWithNewlyAddedPeople.Add(hh);
            }

            //haushalte anlegen

            int migratedPeople = 0;

            var emptyHouseholds  = newHouseholds.ToList();
            var newHouseholdKeys = newHouseholds.Select(x => x.HouseholdKey).Distinct().ToHashSet();
            var migrantsToDelete = migrants.Where(x => !newHouseholdKeys.Contains(x.HouseholdKey)).ToList();

            foreach (var persistenceMigratedOccupant in migrantsToDelete)
            {
                persistenceDb.Delete(persistenceMigratedOccupant);
                Info("Deleted persistence migrant due to missing house");
                migrants.Remove(persistenceMigratedOccupant);
            }

            //person migration
            Info("Number of new migratants before persistence: " + numberOfPeopleMovingIn);
            foreach (var migrant in migrants)
            {
                var      newEmptyHousehold = emptyHouseholds.First(x => x.HouseholdKey == migrant.HouseholdKey);
                Occupant occ = new Occupant(newEmptyHousehold.Guid,
                                            Guid.NewGuid().ToString(),
                                            migrant.Age,
                                            migrant.Gender,
                                            newEmptyHousehold.HouseGuid,
                                            newEmptyHousehold.HouseholdKey);
                migratedPeople++;
                newEmptyHousehold.Occupants.Add(occ);
                householdsWithNewlyAddedPeople.Add(newEmptyHousehold);
                numberOfPeopleMovingIn--;
            }

            foreach (var household in newHouseholds)
            {
                if (household.Occupants.Count == 0)
                {
                    throw new FlaException("empty household found");
                }
            }

            if (numberOfPeopleMovingIn < 0)
            {
                throw new FlaException("negative people moving in");
            }

            Info("Number of new migratants after persistence: " + numberOfPeopleMovingIn);
            Info("Number of empty households after persistence: " + emptyHouseholds.Count);

            for (int i = 0; i < numberOfPeopleMovingIn; i++)
            {
                //find a household for the persons
                Household pickedHousehold;
                if (emptyHouseholds.Count > 0)
                {
                    pickedHousehold = emptyHouseholds[0];
                    emptyHouseholds.RemoveAt(0);
                }
                else
                {
                    pickedHousehold = MakeSingleNewHousehold(slice, hausanschlusses, i, persistenceDb, allhwhs, newHouseholds);
                    newHouseholds.Add(pickedHousehold);
                }

                householdsWithNewlyAddedPeople.Add(pickedHousehold);
                Occupant occ = new Occupant(pickedHousehold.Guid,
                                            Guid.NewGuid().ToString(),
                                            Services.Rnd.Next(60),
                                            (Gender)Services.Rnd.Next(2),
                                            pickedHousehold.HouseGuid,
                                            pickedHousehold.HouseholdKey);
                migratedPeople++;
                PersistenceMigratedOccupant moc = new PersistenceMigratedOccupant(occ.HouseholdKey, occ.Age, occ.Gender);
                persistenceDb.Save(moc);
                pickedHousehold.Occupants.Add(occ);
            }


            foreach (var hh in householdsWithNewlyAddedPeople.Distinct())
            {
                if (Math.Abs(hh.LocalnetLowVoltageYearlyTotalElectricityUse) > 0.0001)
                {
                    throw new FlaException("Household with energy consumption already set");
                }

                double energyconsumption = 1000 + hh.Occupants.Count * 500 + Services.Rnd.Next(1000) - 500;
                hh.LocalnetLowVoltageYearlyTotalElectricityUse = energyconsumption;
            }

            Info("Migrators: " + migratedPeople);
            persistenceDb.CompleteTransaction();
            dbDstHouses.RecreateTable <Household>();
            dbDstHouses.BeginTransaction();
            int householdsSaved = 0;

            // save old households
            foreach (var srchh in srcHouseholds)
            {
                srchh.Occupants.Sort((x, y) => x.Age.CompareTo(y.Age));
                if (srchh.Occupants.Count == 0)
                {
                    throw new FlaException("No people left in the hh");
                }

                if (Math.Abs(srchh.LocalnetLowVoltageYearlyTotalElectricityUse) < 0.00001)
                {
                    throw new FlaException("Household without energy consumption found: " + srchh.Name);
                }

                dbDstHouses.Save(srchh);
                householdsSaved++;
            }

            // save new households
            foreach (var newHousehold in newHouseholds)
            {
                newHousehold.Occupants.Sort((x, y) => x.Age.CompareTo(y.Age));
                if (newHousehold.Occupants.Count == 0)
                {
                    throw new FlaException("No people in the new hh");
                }

                dbDstHouses.Save(newHousehold);
                householdsSaved++;
            }

            if (householdsSaved == 0)
            {
                throw new FlaException("Not a single household saved");
            }

            Info("finished writing " + householdsSaved + " households");
            foreach (var house in dstHouses)
            {
                dbDstHouses.Save(house);
            }

            dbDstHouses.CompleteTransaction();
            Info("finished house copying");
        }
Esempio n. 27
0
        private void BirthNewChildren([NotNull] ScenarioSliceParameters slice,
                                      [NotNull][ItemNotNull]
                                      List <Household> srcHouseholds)
        {
            //find households to add children to
            var householdsThatCouldHaveChildren = new List <Household>();

            foreach (var household in srcHouseholds)
            {
                bool hasMom = household.Occupants.Any(x => x.Age > 18 && x.Age < 45 && x.Gender == Gender.Female);
                bool hasDad = household.Occupants.Any(x => x.Age > 18 && x.Age < 60 && x.Gender == Gender.Male);
                if (hasDad && hasMom)
                {
                    householdsThatCouldHaveChildren.Add(household);
                }
            }

            int numberOfChildren = (int)slice.NumberOfChildren;

            Info("Number of children before persistence: " + numberOfChildren);
            int peopleBorn    = 0;
            var persistenceDb = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, slice, DatabaseCode.Persistence);

            persistenceDb.CreateTableIfNotExists <PersistenceBirthEntry>();
            var birthEntries = persistenceDb.Fetch <PersistenceBirthEntry>();

            foreach (var birthEntry in birthEntries)
            {
                var householdToAddChildTo = householdsThatCouldHaveChildren.FirstOrDefault(x => x.HouseholdKey == birthEntry.HouseholdKey);
                if (householdToAddChildTo == null)
                {
                    persistenceDb.Delete(birthEntry);
                    continue;
                }

                Occupant occ = new Occupant(householdToAddChildTo.Guid,
                                            Guid.NewGuid().ToString(),
                                            1,
                                            birthEntry.Gender,
                                            householdToAddChildTo.HouseGuid,
                                            householdToAddChildTo.HouseholdKey);
                householdToAddChildTo.Occupants.Add(occ);
                peopleBorn++;
                numberOfChildren--;
                if (numberOfChildren < 1)
                {
                    break;
                }
            }

            Info("Number of children after persistence: " + numberOfChildren);
            if (householdsThatCouldHaveChildren.Count == 0)
            {
                throw new FlaException("Not a single household available to have children?");
            }

            //give birth to the children
            persistenceDb.BeginTransaction();
            for (int i = 0; i < numberOfChildren; i++)
            {
                var      pickedHousehold = householdsThatCouldHaveChildren[Services.Rnd.Next(householdsThatCouldHaveChildren.Count)];
                var      gender          = (Gender)Services.Rnd.Next(2);
                Occupant occ             = new Occupant(pickedHousehold.Guid,
                                                        Guid.NewGuid().ToString(),
                                                        1,
                                                        gender,
                                                        pickedHousehold.HouseGuid,
                                                        pickedHousehold.HouseholdKey);
                pickedHousehold.Occupants.Add(occ);
                PersistenceBirthEntry be = new PersistenceBirthEntry(occ.HouseholdKey, occ.Gender);
                persistenceDb.Save(be);
                peopleBorn++;
            }

            persistenceDb.CompleteTransaction();
            Info("Children: " + peopleBorn);
        }
Esempio n. 28
0
 public Field(Occupant o, int id, Direction d)
 {
     occupant  = o;
     this.id   = id;
     direction = d;
 }
        protected override void RunActualProcess()
        {
            var dbHouses            = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, Constants.PresentSlice);
            var dbHousesPersistence =
                Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Houses, Constants.PresentSlice, DatabaseCode.Persistence);

            dbHousesPersistence.CreateTableIfNotExists <PersistentOutgoingCommuterEntry>();
            dbHouses.RecreateTable <OutgoingCommuterEntry>();
            dbHouses.RecreateTable <CarDistanceEntry>();
            var dbRaw      = Services.SqlConnectionPreparer.GetDatabaseConnection(Stage.Raw, Constants.PresentSlice);
            var outGoings  = dbRaw.Fetch <OutgoingCommuterSummary>();
            var households = dbHouses.Fetch <Household>();
            var residents  = households.SelectMany(x => x.Occupants).ToList().AsReadOnly();

            if (residents.Count == 0)
            {
                throw new Exception("No occupants found");
            }

            var persistentOutgoingCommuters = dbHousesPersistence.Fetch <PersistentOutgoingCommuterEntry>();
            var cars           = dbHouses.Fetch <Car>();
            var householdGuids = households.Select(x => x.Guid).ToList();

            foreach (var car in cars)
            {
                if (!householdGuids.Contains(car.HouseholdGuid))
                {
                    throw new FlaException("car with invalid household guid");
                }
            }

            if (cars.Count < 1000)
            {
                throw new FlaException("Not a single car was loaded");
            }

            Debug("total planned commuters before persistence: " + outGoings.Sum(x => x.Erwerbstätige));
            int idx         = 0;
            int deletecount = 0;

            dbHouses.BeginTransaction();
            dbHousesPersistence.BeginTransaction();
            foreach (var persistentOutgoingCommuterEntry in persistentOutgoingCommuters)
            {
                var household = households.FirstOrDefault(x => x.HouseholdKey == persistentOutgoingCommuterEntry.HouseholdKey);
                if (household == null)
                {
                    dbHousesPersistence.Delete(persistentOutgoingCommuterEntry);
                    continue;
                }

                Car car = cars.FirstOrDefault(x => x.HouseholdGuid == household.Guid);
                if (car == null && persistentOutgoingCommuterEntry.CommuntingMethod == CommuntingMethod.Car)
                {
                    Debug("deleted inconsistent commuter " + deletecount++);
                    dbHousesPersistence.Delete(persistentOutgoingCommuterEntry);
                    continue;
                }

                OutgoingCommuterEntry ogce = new OutgoingCommuterEntry(Guid.NewGuid().ToString(),
                                                                       household.Guid,
                                                                       persistentOutgoingCommuterEntry.DistanceInKm,
                                                                       persistentOutgoingCommuterEntry.CommuntingMethod,
                                                                       persistentOutgoingCommuterEntry.WorkCity,
                                                                       persistentOutgoingCommuterEntry.WorkKanton,
                                                                       household.HouseGuid);

                dbHouses.Save(ogce);
                var outgoing = outGoings.Single(x =>
                                                x.Arbeitsgemeinde == persistentOutgoingCommuterEntry.WorkCity && x.Arbeitskanton == persistentOutgoingCommuterEntry.WorkKanton);
                outgoing.Erwerbstätige--;
                if (outgoing.Erwerbstätige < 0)
                {
                    throw new FlaException("Negative workers");
                }

                if (car != null)
                {
                    //bus & bahn
                    cars.Remove(car);
                    CarDistanceEntry cde = new CarDistanceEntry(household.HouseGuid,
                                                                household.Guid,
                                                                car.Guid,
                                                                persistentOutgoingCommuterEntry.DistanceInKm,
                                                                27.4,
                                                                household.OriginalISNs,
                                                                household.FinalIsn,
                                                                household.HausAnschlussGuid,
                                                                Guid.NewGuid().ToString(),
                                                                "Car " + (idx++),
                                                                car.CarType);
                    dbHouses.Save(cde);
                }
            }

            dbHouses.CompleteTransaction();
            dbHousesPersistence.CompleteTransaction();
            Debug("total planned commuters after persistence: " + outGoings.Sum(x => x.Erwerbstätige));
            var outgoingCommuters = new List <OutgoingCommuterEntry>();

            foreach (var commuter in outGoings)
            {
                for (var i = 0; i < commuter.Erwerbstätige; i++)
                {
                    var oce = new OutgoingCommuterEntry {
                        CommuterGuid = Guid.NewGuid().ToString()
                    };
                    var method = Services.Rnd.NextDouble();

                    if (method < 0.52)
                    {
                        oce.CommuntingMethod = CommuntingMethod.Car;
                    }
                    else
                    {
                        oce.CommuntingMethod = CommuntingMethod.PublicTransport;
                    }

                    oce.DistanceInKm = commuter.Entfernung;
                    oce.WorkCity     = commuter.Arbeitsgemeinde;
                    oce.WorkKanton   = commuter.Arbeitskanton;
                    outgoingCommuters.Add(oce);
                }
            }

            //freizeit km nach mikromobilitätszensus, 12.05 auto-km/tag/person, 0.44 autos pro person = 27.39 km/tag
            var        potentialResidents           = residents.Where(x => x.Age > 18 && x.Age < 65).ToList();
            var        householdGuidsWithCar        = cars.Select(x => x.HouseholdGuid).ToList();
            var        potentialResidentsWithCar    = potentialResidents.Where(x => householdGuidsWithCar.Contains(x.HouseholdGuid)).ToList();
            var        potentialResidentsWithoutCar = potentialResidents.Where(x => !potentialResidentsWithCar.Contains(x)).ToList();
            List <Car> availableCars = cars.ToList();
            //assign the commuters
            List <OutgoingCommuterEntry> processedOutgoingCommuters = new List <OutgoingCommuterEntry>();

            dbHouses.BeginTransaction();
            while (outgoingCommuters.Count > 0)
            {
                OutgoingCommuterEntry ogce = outgoingCommuters[0];
                processedOutgoingCommuters.Add(ogce);
                outgoingCommuters.RemoveAt(0);
                Occupant occupant = null;

                if (ogce.CommuntingMethod == CommuntingMethod.Car)
                {
                    Car myCar = null;

                    while (myCar == null)
                    {
                        occupant = potentialResidentsWithCar[Services.Rnd.Next(potentialResidentsWithCar.Count)];
                        potentialResidentsWithCar.Remove(occupant);
                        myCar = availableCars.FirstOrDefault(x => x.HouseholdGuid == occupant.HouseholdGuid);
                    }

                    availableCars.Remove(myCar);

                    Household hh = households.FirstOrDefault(x => x.Guid == occupant.HouseholdGuid);
                    if (hh == null)
                    {
                        throw new FlaException("No household for " + ogce.HouseholdGuid);
                    }

                    CarDistanceEntry cd = new CarDistanceEntry(occupant.HouseGuid,
                                                               occupant.HouseholdGuid,
                                                               myCar.Guid,
                                                               ogce.DistanceInKm,
                                                               27.4,
                                                               hh.OriginalISNs,
                                                               hh.FinalIsn,
                                                               hh.HausAnschlussGuid,
                                                               Guid.NewGuid().ToString(),
                                                               (idx++).ToString(),
                                                               myCar.CarType);
                    dbHouses.Save(cd);
                }
                else
                {
                    if (potentialResidentsWithoutCar.Count > 0)
                    {
                        occupant = potentialResidentsWithoutCar[Services.Rnd.Next(potentialResidentsWithoutCar.Count)];
                        potentialResidentsWithoutCar.Remove(occupant);
                    }
                    else
                    {
                        occupant = potentialResidentsWithCar[Services.Rnd.Next(potentialResidentsWithCar.Count)];
                        potentialResidentsWithCar.Remove(occupant);
                    }
                }

                ogce.HouseholdGuid = occupant.HouseholdGuid;
                ogce.HouseGuid     = occupant.HouseGuid;
                ogce.CommuterGuid  = Guid.NewGuid().ToString();
            }

            //the other cars are only used for freizeit / shopping / etc
            foreach (Car car in availableCars)
            {
                Household        hh = households.Single(x => x.Guid == car.HouseholdGuid);
                CarDistanceEntry cd = new CarDistanceEntry(car.HouseGuid,
                                                           car.HouseholdGuid,
                                                           car.Guid,
                                                           0,
                                                           27.4,
                                                           hh.OriginalISNs,
                                                           hh.FinalIsn,
                                                           hh.HausAnschlussGuid,
                                                           Guid.NewGuid().ToString(),
                                                           "Car " + (idx++),
                                                           car.CarType);
                dbHouses.Save(cd);
            }

            foreach (var entry in processedOutgoingCommuters)
            {
                if (string.IsNullOrWhiteSpace(entry.HouseholdGuid))
                {
                    throw new FlaException("Household guid was empty");
                }

                var household = households.Single(x => x.Guid == entry.HouseholdGuid);
                PersistentOutgoingCommuterEntry poce = new PersistentOutgoingCommuterEntry(household.HouseholdKey,
                                                                                           entry.DistanceInKm,
                                                                                           entry.CommuntingMethod,
                                                                                           entry.WorkCity,
                                                                                           entry.WorkKanton);
                dbHousesPersistence.Save(poce);
                dbHouses.Save(entry);
            }

            dbHousesPersistence.CompleteTransaction();
            dbHouses.CompleteTransaction();
        }
 public NewOccupantDomainEvent(Flat flat, Occupant occupant)
 {
     this.flat     = flat;
     this.occupant = occupant;
 }