Exemple #1
0
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, IPersonWrapper person, int sampleSize, IParcelWrapper choice = null, bool choseHome = false)
        {
            var segment                  = Global.Kernel.Get <SamplingWeightsSettingsFactory>().SamplingWeightsSettings.GetTourDestinationSegment(Global.Settings.Purposes.School, Global.Settings.TourPriorities.UsualLocation, Global.Settings.Modes.Sov, person.PersonType);
            var destinationSampler       = new DestinationSampler(choiceProbabilityCalculator, segment, sampleSize, person.Household.ResidenceParcel, choice);
            var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
            var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);
            var schoolLocationUtilities  = new SchoolLocationUtilities(person, sampleSize, destinationArrivalTime, destinationDepartureTime);

            destinationSampler.SampleTourDestinations(schoolLocationUtilities);

            //			var alternative = choiceProbabilityCalculator.GetAlternative(countSampled, true);

            // JLB 20120403 added third call parameter to idenitfy whether this alt is chosen or not
            var alternative = choiceProbabilityCalculator.GetAlternative(sampleSize, true, choseHome);

            alternative.Choice = person.Household.ResidenceParcel;

            alternative.AddUtilityTerm(50, 1);
            alternative.AddUtilityTerm(51, (!person.IsStudentAge).ToFlag());
            alternative.AddUtilityTerm(52, person.Household.Size);
            alternative.AddUtilityTerm(98, 100); //dummy size variable for oddball alt

            //make oddball alt unavailable and remove nesting for estimation of conditional MNL
            //			alternative.Available = false;
            alternative.AddNestedAlternative(sampleSize + 3, 1, 99);
        }
Exemple #2
0
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, IPersonWrapper person, int sampleSize, IParcelWrapper choice = null, bool choseHome = false)
        {
            int segment = Global.ContainerDaySim.GetInstance <SamplingWeightsSettingsFactory>().SamplingWeightsSettings.GetTourDestinationSegment(Global.Settings.Purposes.Work, Global.Settings.TourPriorities.HomeBasedTour, Global.Settings.Modes.Sov, person.PersonType);
            DestinationSampler destinationSampler      = new DestinationSampler(choiceProbabilityCalculator, segment, sampleSize, choice, person.Household.ResidenceParcel);
            int destinationArrivalTime                 = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
            int destinationDepartureTime               = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
            WorkLocationUtilities workLocationUtilites = new WorkLocationUtilities(this, person, sampleSize, destinationArrivalTime, destinationDepartureTime);

            destinationSampler.SampleTourDestinations(workLocationUtilites);

            //var alternative = choiceProbabilityCalculator.GetAlternative(countSampled, true);

            // JLB 20120329 added third call parameter to idenitfy whether this alt is chosen or not
            ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(sampleSize, true, choseHome);

            alternative.Choice = person.Household.ResidenceParcel;

            alternative.AddUtilityTerm(41, 1);
            alternative.AddUtilityTerm(42, person.IsPartTimeWorker.ToFlag());
            alternative.AddUtilityTerm(43, person.IsStudentAge.ToFlag());
            alternative.AddUtilityTerm(44, person.IsFemale.ToFlag());
            alternative.AddUtilityTerm(90, 100);

            //make oddball alt unavailable and remove nesting for estimation of conditional MNL
            //            alternative.Available = false;
            alternative.AddNestedAlternative(sampleSize + 3, 1, 98);
        }
Exemple #3
0
        private void RunAVModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, IHouseholdWrapper household, int choice = Constants.DEFAULT_VALUE)
        {
            int    ageOfHouseholdHead = 0;
            double totalCommuteTime   = 0;

            foreach (var person in household.Persons)
            {
                if (person.Sequence == 1)
                {
                    ageOfHouseholdHead = person.Age;
                }
                if (person.IsWorker && person.UsualWorkParcel != null && person.UsualWorkParcelId != household.ResidenceParcelId)
                {
                    var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                    var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);

                    totalCommuteTime += ImpedanceRoster.GetValue("ivtime", Global.Settings.Modes.Sov, Global.Settings.PathTypes.FullNetwork, Global.Settings.ValueOfTimes.DefaultVot,
                                                                 destinationArrivalTime, household.ResidenceParcel, person.UsualWorkParcel).Variable;
                    totalCommuteTime += ImpedanceRoster.GetValue("ivtime", Global.Settings.Modes.Sov, Global.Settings.PathTypes.FullNetwork, Global.Settings.ValueOfTimes.DefaultVot,
                                                                 destinationDepartureTime, person.UsualWorkParcel, household.ResidenceParcel).Variable;
                }
            }

            // 0 Conventional auotos

            var alternative = choiceProbabilityCalculator.GetAlternative(0, true, choice == 0);

            alternative.Choice = 0;
            //utility is 0

            // 1 AVs

            alternative        = choiceProbabilityCalculator.GetAlternative(1, true, choice == 1);
            alternative.Choice = 1;

            alternative.AddUtilityTerm(200, Global.Configuration.AV_AutoTypeConstant);
            alternative.AddUtilityTerm(200, Global.Configuration.AV_HHIncomeUnder50KCoefficient * household.HasIncomeUnder50K.ToFlag());
            alternative.AddUtilityTerm(200, Global.Configuration.AV_HHIncomeOver100KCoefficient * household.Has100KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(200, Global.Configuration.AV_HHHeadUnder35Coefficient * (ageOfHouseholdHead < 35).ToFlag());
            alternative.AddUtilityTerm(200, Global.Configuration.AV_HHHeadOver65Coefficient * (ageOfHouseholdHead >= 65).ToFlag());
            alternative.AddUtilityTerm(200, Global.Configuration.AV_CoefficientPerHourCommuteTime * (totalCommuteTime / 60.0));

            // 2 not available

            alternative        = choiceProbabilityCalculator.GetAlternative(2, false, choice == 2);
            alternative.Choice = 2;

            // 3 not available

            alternative        = choiceProbabilityCalculator.GetAlternative(3, false, choice == 3);
            alternative.Choice = 3;


            // 4 not available

            alternative        = choiceProbabilityCalculator.GetAlternative(4, false, choice == 4);
            alternative.Choice = 4;
        }
Exemple #4
0
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, IPersonWrapper person, int sampleSize, IParcelWrapper choice = null, bool choseHome = false)
        {
            int segment = Global.ContainerDaySim.GetInstance <SamplingWeightsSettingsFactory>().SamplingWeightsSettings.GetTourDestinationSegment(Global.Settings.Purposes.Work, Global.Settings.TourPriorities.HomeBasedTour, Global.Settings.Modes.Sov, person.PersonType);
            DestinationSampler destinationSampler      = new DestinationSampler(choiceProbabilityCalculator, segment, sampleSize, choice, person.Household.ResidenceParcel);
            int destinationArrivalTime                 = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
            int destinationDepartureTime               = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
            WorkLocationUtilities workLocationUtilites = new WorkLocationUtilities(this, person, sampleSize, destinationArrivalTime, destinationDepartureTime);

            destinationSampler.SampleTourDestinations(workLocationUtilites);

            //var alternative = choiceProbabilityCalculator.GetAlternative(countSampled, true);

            // JLB 20120329 added third call parameter to idenitfy whether this alt is chosen or not
            if (Global.Configuration.IsInEstimationMode && !ESTIMATE_NESTED_MODEL)
            {
                return;
            }
            ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(sampleSize, true, choseHome);

            alternative.Choice = person.Household.ResidenceParcel;

            alternative.AddUtilityTerm(41, 1);
            alternative.AddUtilityTerm(42, person.IsPartTimeWorker.ToFlag());
            alternative.AddUtilityTerm(43, person.IsStudentAge.ToFlag());
            alternative.AddUtilityTerm(44, person.IsFemale.ToFlag());
            alternative.AddUtilityTerm(89, 1);   //new dummy size variable for oddball alt
            alternative.AddUtilityTerm(90, 100); //old dummy size variable for oddball alt

            // OD shadow pricing - add for work at home
            if (Global.Configuration.ShouldUseODShadowPricing && Global.Configuration.UseODShadowPricingForWorkAtHomeAlternative)
            {
                int res = person.Household.ResidenceParcel.District;
                int des = person.Household.ResidenceParcel.District;
                //var first = res <= des? res : des;
                //var second = res <= des? des : res;
                double shadowPriceConfigurationParameter = res == des ? Global.Configuration.WorkLocationOOShadowPriceCoefficient : Global.Configuration.WorkLocationODShadowPriceCoefficient;
                int    odShadowPriceF12Value             = MAX_REGULAR_PARAMETER + Global.Configuration.NumberOfODShadowPricingDistricts * (res - 1) + des;
                alternative.AddUtilityTerm(odShadowPriceF12Value, shadowPriceConfigurationParameter);
            }

            // set shadow price depending on persontype and add it to utility
            // we are using the sampling adjustment factor assuming that it is 1
            if (Global.Configuration.ShouldUseShadowPricing && Global.Configuration.UseWorkShadowPricingForWorkAtHomeAlternative)
            {
                alternative.AddUtilityTerm(1, person.Household.ResidenceParcel.ShadowPriceForEmployment);
            }

            //make oddball alt unavailable and remove nesting for estimation of conditional MNL
            alternative.AddNestedAlternative(sampleSize + 3, 1, THETA_PARAMETER);
        }
Exemple #5
0
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, HouseholdWrapper household, int choice = Constants.DEFAULT_VALUE)
        {
            //			var distanceToTransitCappedUnderQtrMile = household.ResidenceParcel.DistanceToTransitCappedUnderQtrMile();
            //			var distanceToTransitQtrToHalfMile = household.ResidenceParcel.DistanceToTransitQtrToHalfMile();
            var foodRetailServiceMedicalLogBuffer1 = household.ResidenceParcel.FoodRetailServiceMedicalLogBuffer1();

            var workTourLogsumDifference   = 0D;           // (full or part-time workers) full car ownership vs. no car ownership
            var schoolTourLogsumDifference = 0D;           // (school) full car ownership vs. no car ownership
            //			const double workTourOtherLogsumDifference = 0D; // (other workers) full car ownership vs. no car ownership

            // Stefan
            var  netIncome = (household.Income / 1000.0) / 2.0; // in 1000s of DKK
            var  userCost  = 2.441 * 15.0;                      //annual cost to use 1 car in 1000s of DKK
            bool isInCopenhagenMunicipality = true;             //household.ResidenceParcel.Municipality == 101;  Need to change this after Municipality property is added to LD parcel file

            int    numberAdults    = 0;
            int    numberChildren  = 0;
            int    numberWorkers   = 0;
            int    sumAdultAges    = 0;
            double averageAdultAge = 0.0;
            bool   isMale          = false;

            foreach (PersonWrapper person in household.Persons)
            {
                if (person.IsWorker && person.UsualWorkParcel != null && person.UsualWorkParcelId != household.ResidenceParcelId)
                {
                    var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                    var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);

                    var nestedAlternative1 = Global.ChoiceModelSession.Get <WorkTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.HouseholdTotals.DrivingAgeMembers, 0.0);
                    var nestedAlternative2 = Global.ChoiceModelSession.Get <WorkTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, 0, 0.0);

                    workTourLogsumDifference += nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
                    workTourLogsumDifference -= nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
                }

                if (person.IsDrivingAgeStudent && person.UsualSchoolParcel != null && person.UsualSchoolParcelId != household.ResidenceParcelId)
                {
                    var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
                    var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);

                    var nestedAlternative1 = Global.ChoiceModelSession.Get <SchoolTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.HouseholdTotals.DrivingAgeMembers, 0.0);
                    var nestedAlternative2 = Global.ChoiceModelSession.Get <SchoolTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, 0, 0.0);

                    schoolTourLogsumDifference += nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
                    schoolTourLogsumDifference -= nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
                }
                if (person.Age >= 18)
                {
                    numberAdults++;
                    sumAdultAges = sumAdultAges + person.Age;
                    isMale       = person.IsMale;
                    if (person.PersonType == Global.Settings.PersonTypes.FullTimeWorker
                        //|| person.PersonType == Constants.PersonType.PART_TIME_WORKER
                        )
                    {
                        numberWorkers++;
                    }
                }
                else
                {
                    numberChildren++;
                }
            }
            averageAdultAge = sumAdultAges / Math.Max(numberAdults, 1);


            // var votSegment = household.VotALSegment;
            //var taSegment = household.ResidenceParcel.TransitAccessSegment();

            //var aggregateLogsumDifference = // full car ownership vs. no car ownership
            //	Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult][votSegment][taSegment] -
            //	Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votSegment][taSegment];

            // 0 AUTOS

            var alternative = choiceProbabilityCalculator.GetAlternative(0, true, choice == 0);

            alternative.Choice = 0;
            alternative.AddUtilityTerm(14, Math.Log(Math.Max(netIncome, 1)));


            // 1 AUTO

            var beta010 = -6.59;
            var beta011 = 4.25;
            var beta012 = 5.53;
            var beta013 = 6.54;
            var beta014 = 1.17;
            var beta015 = 0.54;
            var beta016 = 0.81;
            var beta017 = 1.20;
            var beta018 = -0.54;
            var beta019 = 0.0;
            var beta020 = 0.45;
            var beta021 = 0.0;
            var beta022 = -0.04;
            var beta023 = 0.57;
            var beta024 = 0.18;
            var beta025 = -0.82;

            var stefanOneCarUtility =
                beta010 * 1.0 +
                beta011 * household.Has1Driver.ToFlag() +
                beta012 * household.Has2Drivers.ToFlag() +
                beta013 * (household.Has3Drivers || household.Has4OrMoreDrivers).ToFlag() +
                beta014 * Math.Log(Math.Max(netIncome - userCost, 1)) +
                beta015 * (numberChildren == 1).ToFlag() +
                beta016 * (numberChildren == 2).ToFlag() +
                beta017 * (numberChildren > 2).ToFlag() +
                beta018 * (numberAdults == 1 && !isMale).ToFlag() +
                beta019 * (numberAdults == 1 && isMale).ToFlag() +
                beta020 * averageAdultAge / 10.0 +
                beta021 * Math.Pow(averageAdultAge / 10.0, 2.0) +
                beta022 * 0 +                 //household.ResidenceParcel.PSearchTime16_17 +  // Add this when new parcel variables with seach time are available
                beta023 * household.ResidenceParcel.DistanceToLocalBus +
                beta024 * household.ResidenceParcel.DistanceToExpressBus +
                beta025 * isInCopenhagenMunicipality.ToFlag() +
                0;

            alternative        = choiceProbabilityCalculator.GetAlternative(1, true, choice == 1);
            alternative.Choice = 1;
            //Stefan
            //alternative.AddUtilityTerm(10, 1.0);
            //alternative.AddUtilityTerm(11, household.Has1Driver.ToFlag());
            //alternative.AddUtilityTerm(12, household.Has2Drivers.ToFlag());
            //alternative.AddUtilityTerm(13, (household.Has3Drivers || household.Has4OrMoreDrivers).ToFlag());
            //alternative.AddUtilityTerm(14, Math.Log(Math.Max(netIncome - userCost, 1)));
            //alternative.AddUtilityTerm(15, (numberChildren == 1).ToFlag());
            //alternative.AddUtilityTerm(16, (numberChildren == 2).ToFlag());
            //alternative.AddUtilityTerm(17, (numberChildren > 2).ToFlag());
            //alternative.AddUtilityTerm(18, (numberAdults == 1 && !isMale).ToFlag());
            //alternative.AddUtilityTerm(19, (numberAdults == 1 && isMale).ToFlag());
            //alternative.AddUtilityTerm(20, averageAdultAge / 10.0);
            //alternative.AddUtilityTerm(21, Math.Pow(averageAdultAge / 10.0, 2.0));
            ////alternative.AddUtilityTerm(22, household.ResidenceParcel.PSearchTime16_17);  // Add this when new parcel variables with seach time are available
            //alternative.AddUtilityTerm(23, household.ResidenceParcel.DistanceToLocalBus);
            //alternative.AddUtilityTerm(24, household.ResidenceParcel.DistanceToExpressBus);
            //alternative.AddUtilityTerm(25, isInCopenhagenMunicipality.ToFlag());
            alternative.AddUtilityTerm(26, stefanOneCarUtility);              //this composite replaces above separate terms 10-25

            alternative.AddUtilityTerm(27, workTourLogsumDifference);         // instead of all Stefan's work-related and logsum variables

            //alternative.AddUtilityTerm(24, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
            //alternative.AddUtilityTerm(25, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            //alternative.AddUtilityTerm(26, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            //alternative.AddUtilityTerm(27, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);

            // 2+ AUTOS

            var beta040 = -9.540;
            var beta041 = 2.79;
            var beta042 = 6.09;
            var beta043 = 7.77;
            var beta044 = 0;
            var beta045 = 0.35;
            var beta046 = 0.81;
            var beta047 = 1.33;
            var beta048 = -1.13;
            var beta049 = 0.60;
            var beta050 = 0.92;
            var beta051 = -0.05;
            var beta052 = -0.09;
            var beta053 = 0.94;
            var beta054 = 0.31;
            var beta055 = -1.54;

            var stefanTwoCarUtility =
                beta040 * 1.0 +
                beta041 * household.Has1Driver.ToFlag() +
                beta042 * household.Has2Drivers.ToFlag() +
                beta043 * (household.Has3Drivers || household.Has4OrMoreDrivers).ToFlag() +
                beta014 * Math.Log(Math.Max(netIncome - userCost * 2.0, 1)) +
                beta045 * (numberChildren == 1).ToFlag() +
                beta046 * (numberChildren == 2).ToFlag() +
                beta047 * (numberChildren > 2).ToFlag() +
                beta048 * (numberAdults == 1 && !isMale).ToFlag() +
                beta049 * (numberAdults == 1 && isMale).ToFlag() +
                beta050 * averageAdultAge / 10.0 +
                beta051 * Math.Pow(averageAdultAge / 10.0, 2.0) +
                beta052 * 0 +                 //household.ResidenceParcel.PSearchTime16_17 +  // Add this when new parcel variables with seach time are available
                beta053 * household.ResidenceParcel.DistanceToLocalBus +
                beta054 * household.ResidenceParcel.DistanceToExpressBus +
                beta055 * isInCopenhagenMunicipality.ToFlag() +
                0;

            alternative        = choiceProbabilityCalculator.GetAlternative(2, true, choice == 2);
            alternative.Choice = 2;
            //Stefan
            //alternative.AddUtilityTerm(40, 1.0);
            //alternative.AddUtilityTerm(41, household.Has1Driver.ToFlag());
            //alternative.AddUtilityTerm(42, household.Has2Drivers.ToFlag());
            //alternative.AddUtilityTerm(43, (household.Has3Drivers || household.Has4OrMoreDrivers).ToFlag());
            //alternative.AddUtilityTerm(14, Math.Log(Math.Max(netIncome - userCost * 2.0, 1)));
            //alternative.AddUtilityTerm(45, (numberChildren == 1).ToFlag());
            //alternative.AddUtilityTerm(46, (numberChildren == 2).ToFlag());
            //alternative.AddUtilityTerm(47, (numberChildren > 2).ToFlag());
            //alternative.AddUtilityTerm(48, (numberAdults == 1 && !isMale).ToFlag());
            //alternative.AddUtilityTerm(49, (numberAdults == 1 && isMale).ToFlag());
            //alternative.AddUtilityTerm(50, averageAdultAge / 10.0);
            //alternative.AddUtilityTerm(51, Math.Pow(averageAdultAge / 10.0, 2.0));
            ////alternative.AddUtilityTerm(52, household.ResidenceParcel.PSearchTime16_17);  // Add this when new parcel variables with seach time are available
            //alternative.AddUtilityTerm(53, household.ResidenceParcel.DistanceToLocalBus);
            //alternative.AddUtilityTerm(54, household.ResidenceParcel.DistanceToExpressBus);
            //alternative.AddUtilityTerm(55, isInCopenhagenMunicipality.ToFlag());
            alternative.AddUtilityTerm(56, stefanTwoCarUtility);              //this composite replaces above separate terms 40-55

            alternative.AddUtilityTerm(57, workTourLogsumDifference);

            //alternative.AddUtilityTerm(44, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
            //alternative.AddUtilityTerm(45, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            //alternative.AddUtilityTerm(46, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            //alternative.AddUtilityTerm(47, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);
        }
Exemple #6
0
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, PersonWrapper person, int sampleSize, IParcelWrapper choice = null, bool choseHome = false)
        {
            var segment                  = Global.ContainerDaySim.GetInstance <SamplingWeightsSettingsFactory>().SamplingWeightsSettings.GetTourDestinationSegment(Global.Settings.Purposes.Work, Global.Settings.TourPriorities.HomeBasedTour, Global.Settings.Modes.Sov, person.PersonType);
            var destinationSampler       = new DestinationSampler(choiceProbabilityCalculator, segment, sampleSize, choice, person.Household.ResidenceParcel);
            var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
            var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
            var workLocationUtilites     = new WorkLocationUtilities(person, sampleSize, destinationArrivalTime, destinationDepartureTime);

            var sampleItems = destinationSampler.SampleAndReturnTourDestinations(workLocationUtilites);

            int index = 0;

            foreach (var sampleItem in sampleItems)
            {
                bool   available         = sampleItem.Key.Available;
                bool   isChosen          = sampleItem.Key.IsChosen;
                double adjustmentFactor  = sampleItem.Key.AdjustmentFactor;
                var    destinationParcel = ChoiceModelFactory.Parcels[sampleItem.Key.ParcelId];

                var alternative = choiceProbabilityCalculator.GetAlternative(index++, available, isChosen);

                if (!available)
                {
                    continue;
                }

                alternative.Choice = destinationParcel;

                var workTourLogsum    = 0D;
                var nestedAlternative = Global.ChoiceModelSession.Get <WorkTourModeTimeModel>().RunNested(person, person.Household.ResidenceParcel, destinationParcel, destinationArrivalTime, destinationDepartureTime, person.Household.HouseholdTotals.DrivingAgeMembers, 0.0);
                workTourLogsum = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();

                var votSegment      = person.Household.GetVotALSegment();
                var taSegment       = destinationParcel.TransitAccessSegment();
                var aggregateLogsum = Global.AggregateLogsums[destinationParcel.ZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult][votSegment][taSegment];

                var distanceFromOrigin = person.Household.ResidenceParcel.DistanceFromOrigin(destinationParcel, 1);
                var distance1          = Math.Min(distanceFromOrigin, .35);
                var distance2          = Math.Max(0, Math.Min(distanceFromOrigin - .35, 1 - .35));
                var distance3          = Math.Max(0, distanceFromOrigin - 1);
                var distanceLog        = Math.Log(1 + distanceFromOrigin);
                var distanceFromSchool = person.IsFullOrPartTimeWorker ? 0 : person.UsualSchoolParcel.DistanceFromSchoolLog(destinationParcel, 1);


                // parcel buffers
                var educationBuffer  = Math.Log(destinationParcel.EmploymentEducationBuffer2 + 1);
                var governmentBuffer = Math.Log(destinationParcel.EmploymentGovernmentBuffer2 + 1);
                var officeBuffer     = Math.Log(destinationParcel.EmploymentOfficeBuffer2 + 1);
                var serviceBuffer    = Math.Log(destinationParcel.EmploymentServiceBuffer2 + 1);
                var householdsBuffer = Math.Log(destinationParcel.HouseholdsBuffer2 + 1);

                //                var retailBuffer = Math.Log(destinationParcel.EmploymentRetailBuffer2 + 1);
                var industrialAgricultureConstructionBuffer = Math.Log(destinationParcel.EmploymentIndustrialBuffer2 + destinationParcel.EmploymentAgricultureConstructionBuffer2 + 1);
                var foodBuffer               = Math.Log(destinationParcel.EmploymentFoodBuffer2 + 1);
                var medicalBuffer            = Math.Log(destinationParcel.EmploymentMedicalBuffer2 + 1);
                var employmentTotalBuffer    = Math.Log(destinationParcel.EmploymentTotalBuffer2 + 1);
                var studentsUniversityBuffer = Math.Log(destinationParcel.StudentsUniversityBuffer2 + 1);
                var studentsK12Buffer        = Math.Log(destinationParcel.StudentsK8Buffer2 + destinationParcel.StudentsHighSchoolBuffer2 + 1);

                //                var mixedUse4Index = destinationParcel.MixedUse4Index2();

                //size attributes (derived)
                var employmentIndustrialAgricultureConstruction = destinationParcel.EmploymentIndustrial + destinationParcel.EmploymentAgricultureConstruction;

                // parking attributes
                var parcelParkingDensity = destinationParcel.ParcelParkingPerTotalEmployment();

                // connectivity attributes
                var c34Ratio = destinationParcel.C34RatioBuffer1();


                // Stefan
                bool isInCopenhagenMunicipality  = true; //destinationParcel.Municipality == 101;  Need to change this after Municipality property is added to Actum parcel file
                var  employmentCommercial        = destinationParcel.EmploymentRetail + destinationParcel.EmploymentService;
                var  employmentCommercialBuffer1 = destinationParcel.EmploymentRetailBuffer1 + destinationParcel.EmploymentServiceBuffer1;

                double beta00002 = -2.53;
                double beta00003 = 2.65;
                double beta00004 = 1.57;
                double beta00005 = -0.18;
                double beta00006 = -0.43;
                double beta00007 = -0.19;
                double beta00008 = 0.33;
                double beta00009 = 0.007;
                double beta00010 = 0.55;

                var stefanUtility =
                    beta00002 * destinationParcel.Households / destinationParcel.ThousandsSquareLengthUnits +
                    beta00003 * (person.Household.Income < 300000).ToFlag() * destinationParcel.Households / destinationParcel.ThousandsSquareLengthUnits +
                    beta00004 * person.IsFemale.ToFlag() * destinationParcel.Households / destinationParcel.ThousandsSquareLengthUnits +
                    beta00005 * isInCopenhagenMunicipality.ToFlag() +
                    beta00006 * (person.Household.HasValidIncome && person.Household.Income < 300000).ToFlag() * isInCopenhagenMunicipality.ToFlag() +
                    beta00007 * (person.Household.HasValidIncome && person.Household.Income >= 300000 && person.Household.Income < 600000).ToFlag() * isInCopenhagenMunicipality.ToFlag() +
                    beta00008 * (person.Household.HasValidIncome && person.Household.Income >= 900000).ToFlag() * isInCopenhagenMunicipality.ToFlag() +
                    beta00009 * person.Age * isInCopenhagenMunicipality.ToFlag() +
                    0.0; // beta00010 * (person.Household.ResidenceParcel.Municipality == destination.Municipality).ToFlag();



                //Stefan non-size terms.
                alternative.AddUtilityTerm(1, sampleItem.Key.AdjustmentFactor);
                //alternative.AddUtilityTerm(2, destinationParcel.Households / destinationParcel.ThousandsSquareLengthUnits);
                //alternative.AddUtilityTerm(3, (person.Household.Income < 300000).ToFlag() * destinationParcel.Households / destinationParcel.ThousandsSquareLengthUnits);
                //alternative.AddUtilityTerm(4, person.IsFemale.ToFlag() * destinationParcel.Households / destinationParcel.ThousandsSquareLengthUnits);
                //alternative.AddUtilityTerm(5, isInCopenhagenMunicipality.ToFlag());
                //alternative.AddUtilityTerm(6, (person.Household.HasValidIncome && person.Household.Income < 300000).ToFlag() * isInCopenhagenMunicipality.ToFlag());
                //alternative.AddUtilityTerm(7, (person.Household.HasValidIncome && person.Household.Income >= 300000 && person.Household.Income < 600000).ToFlag() * isInCopenhagenMunicipality.ToFlag());
                //alternative.AddUtilityTerm(8, (person.Household.HasValidIncome && person.Household.Income >= 900000).ToFlag() * isInCopenhagenMunicipality.ToFlag());
                //alternative.AddUtilityTerm(9, person.Age * isInCopenhagenMunicipality.ToFlag());
                ////alternative.AddUtilityTerm(10, (person.Household.ResidenceParcel.Municipality == destination.Municipality).ToFlag());  // Acivate this after Municipality property is added to Actum parcel file
                //following logsums replace Stefan's car and public transport times
                alternative.AddUtilityTerm(11, (person.Household.HasValidIncome && person.Household.Income < 300000).ToFlag() * workTourLogsum);
                alternative.AddUtilityTerm(12, (person.Household.HasValidIncome && person.Household.Income >= 300000 && person.Household.Income < 600000).ToFlag() * workTourLogsum);
                alternative.AddUtilityTerm(13, (person.Household.HasValidIncome && person.Household.Income >= 900000).ToFlag() * workTourLogsum);
                alternative.AddUtilityTerm(14, person.Household.HasMissingIncome.ToFlag() * workTourLogsum);
                alternative.AddUtilityTerm(15, person.IsFemale.ToFlag() * workTourLogsum);
                alternative.AddUtilityTerm(16, person.Age * workTourLogsum);
                alternative.AddUtilityTerm(17, (person.MainOccupation == 50).ToFlag() * workTourLogsum); // self-employed
                                                                                                         //Stefan's composite term 18 replaces terms 2-10 above
                alternative.AddUtilityTerm(18, stefanUtility);                                           // see above for this composite function of StefanMabitt's utility function

                //alternative.AddUtilityTerm(2, person.IsFulltimeWorker.ToFlag() * workTourLogsum);
                //alternative.AddUtilityTerm(3, person.IsPartTimeWorker.ToFlag() * workTourLogsum);
                //alternative.AddUtilityTerm(4, person.IsNotFullOrPartTimeWorker.ToFlag() * workTourLogsum);
                //alternative.AddUtilityTerm(5, distanceLog); // for distance calibration
                //alternative.AddUtilityTerm(6, person.IsFulltimeWorker.ToFlag() * distance1);
                //alternative.AddUtilityTerm(7, person.IsFulltimeWorker.ToFlag() * distance2);
                //alternative.AddUtilityTerm(8, person.IsFulltimeWorker.ToFlag() * distance3);
                //alternative.AddUtilityTerm(9, person.IsPartTimeWorker.ToFlag() * distanceLog);
                //alternative.AddUtilityTerm(10, person.IsNotFullOrPartTimeWorker.ToFlag() * distanceLog);
                //alternative.AddUtilityTerm(11, person.Household.Has0To15KIncome.ToFlag() * distanceLog);
                //alternative.AddUtilityTerm(12, person.Household.Has50To75KIncome.ToFlag() * distanceLog);
                //alternative.AddUtilityTerm(13, person.Household.Has75To100KIncome.ToFlag() * distanceLog);
                //alternative.AddUtilityTerm(14, person.IsFemale.ToFlag() * distanceLog);
                //alternative.AddUtilityTerm(15, person.IsStudentAge.ToFlag() * distanceFromSchool);
                //alternative.AddUtilityTerm(16, person.IsFulltimeWorker.ToFlag() * aggregateLogsum);
                //alternative.AddUtilityTerm(17, person.IsPartTimeWorker.ToFlag() * aggregateLogsum);
                //alternative.AddUtilityTerm(18, person.IsNotFullOrPartTimeWorker.ToFlag() * aggregateLogsum);
                //alternative.AddUtilityTerm(19, parcelParkingDensity);
                //alternative.AddUtilityTerm(20, c34Ratio);

                //Neighborhood
                //alternative.AddUtilityTerm(21, person.Household.HasValidIncome.ToFlag() * serviceBuffer);
                //alternative.AddUtilityTerm(22, person.Household.HasValidIncome.ToFlag() * educationBuffer);
                //alternative.AddUtilityTerm(23, person.Household.HasValidIncome.ToFlag() * foodBuffer);
                //alternative.AddUtilityTerm(24, person.Household.HasValidIncome.ToFlag() * governmentBuffer);
                //alternative.AddUtilityTerm(25, person.Household.HasValidIncome.ToFlag() * officeBuffer);
                //alternative.AddUtilityTerm(26, person.Household.HasValidIncome.ToFlag() * medicalBuffer);
                //alternative.AddUtilityTerm(27, person.Household.HasValidIncome.ToFlag() * householdsBuffer);
                //alternative.AddUtilityTerm(28, person.Household.HasValidIncome.ToFlag() * studentsUniversityBuffer);

                //alternative.AddUtilityTerm(29, person.Household.HasValidIncome.ToFlag() * person.IsFulltimeWorker.ToFlag() * studentsK12Buffer);
                //alternative.AddUtilityTerm(30, person.Household.HasValidIncome.ToFlag() * person.IsFulltimeWorker.ToFlag() * studentsUniversityBuffer);
                //alternative.AddUtilityTerm(31, person.Household.HasValidIncome.ToFlag() * person.IsPartTimeWorker.ToFlag() * industrialAgricultureConstructionBuffer);
                //alternative.AddUtilityTerm(32, person.Household.HasValidIncome.ToFlag() * person.IsNotFullOrPartTimeWorker.ToFlag() * foodBuffer);
                //alternative.AddUtilityTerm(33, person.Household.HasValidIncome.ToFlag() * person.IsNotFullOrPartTimeWorker.ToFlag() * medicalBuffer);

                //alternative.AddUtilityTerm(34, person.IsFulltimeWorker.ToFlag() * person.Household.Has75KPlusIncome.ToFlag() * employmentTotalBuffer);
                //alternative.AddUtilityTerm(35, person.IsNotFullOrPartTimeWorker.ToFlag() * person.Household.HasIncomeUnder50K.ToFlag() * governmentBuffer);
                //alternative.AddUtilityTerm(36, person.IsNotFullOrPartTimeWorker.ToFlag() * person.Household.HasIncomeUnder50K.ToFlag() * employmentTotalBuffer);

                //Size
                // Stefan size terms.
                // Note:  the following assumes: (1) Stefan's size variables enter his utility function as a logsum, a la BAL;
                //                               (2) Jobs--commercial and Jobs--finance apply to hh w unknown incomes in Stefan's spec
                //        If his size variables enter linearly, then if I want to replicate them I should not use alogit size functions.
                //        If Jobs--commercial and Jobs--finance don't apply to missing incomes, then I need to change the size functions below
                alternative.AddUtilityTerm(51, (person.Household.HasValidIncome && person.Household.Income < 300000).ToFlag() * (destinationParcel.EmploymentTotal - employmentCommercial));
                alternative.AddUtilityTerm(52, (person.Household.HasValidIncome && person.Household.Income >= 300000 && person.Household.Income < 600000).ToFlag() * (destinationParcel.EmploymentTotal - employmentCommercial));
                alternative.AddUtilityTerm(53, (person.Household.HasValidIncome && person.Household.Income >= 600000 && person.Household.Income < 900000).ToFlag() * (destinationParcel.EmploymentTotal - employmentCommercial));
                alternative.AddUtilityTerm(54, (person.Household.HasValidIncome && person.Household.Income >= 900000).ToFlag() * (destinationParcel.EmploymentTotal - employmentCommercial));
                alternative.AddUtilityTerm(55, (person.Household.HasValidIncome && person.Household.Income >= 900000).ToFlag() * (destinationParcel.EmploymentTotal - employmentCommercial)); // second term allows first one to have base coef of 0
                alternative.AddUtilityTerm(56, (person.Household.HasMissingIncome.ToFlag() * (destinationParcel.EmploymentTotal - employmentCommercial)));
                alternative.AddUtilityTerm(57, (person.Household.HasValidIncome && person.Household.Income < 300000).ToFlag() * employmentCommercial);
                alternative.AddUtilityTerm(58, (person.Household.HasValidIncome && person.Household.Income >= 300000 && person.Household.Income < 600000).ToFlag() * employmentCommercial);
                alternative.AddUtilityTerm(59, (person.Household.HasValidIncome && person.Household.Income >= 600000 && person.Household.Income < 900000).ToFlag() * employmentCommercial);
                alternative.AddUtilityTerm(60, (person.Household.HasValidIncome && person.Household.Income >= 900000).ToFlag() * employmentCommercial);
                alternative.AddUtilityTerm(61, person.Household.HasMissingIncome.ToFlag() * employmentCommercial);
                alternative.AddUtilityTerm(62, destinationParcel.EmploymentOffice);
                //The following combine with 51-55, 56-60 and 61 to include size of entire buffer region in main size variables
                alternative.AddUtilityTerm(63, (destinationParcel.EmploymentTotalBuffer1 - destinationParcel.EmploymentTotal) - (employmentCommercialBuffer1 - employmentCommercial));
                alternative.AddUtilityTerm(64, employmentCommercialBuffer1 - employmentCommercial);
                alternative.AddUtilityTerm(65, destinationParcel.EmploymentOfficeBuffer1 - destinationParcel.EmploymentOffice);

                //alternative.AddUtilityTerm(51, person.Household.HasValidIncome.ToFlag() * destinationParcel.EmploymentService);
                //alternative.AddUtilityTerm(52, person.Household.HasValidIncome.ToFlag() * destinationParcel.EmploymentEducation);
                //alternative.AddUtilityTerm(53, person.Household.HasValidIncome.ToFlag() * destinationParcel.EmploymentFood);
                //alternative.AddUtilityTerm(54, person.Household.HasValidIncome.ToFlag() * destinationParcel.EmploymentGovernment);
                //alternative.AddUtilityTerm(55, person.Household.HasValidIncome.ToFlag() * destinationParcel.EmploymentOffice);
                //alternative.AddUtilityTerm(56, person.Household.HasValidIncome.ToFlag() * destinationParcel.EmploymentRetail);
                //alternative.AddUtilityTerm(57, person.Household.HasValidIncome.ToFlag() * destinationParcel.EmploymentMedical);
                //alternative.AddUtilityTerm(58, person.Household.HasValidIncome.ToFlag() * employmentIndustrialAgricultureConstruction);
                //alternative.AddUtilityTerm(59, person.Household.HasValidIncome.ToFlag() * destinationParcel.StudentsUniversity);

                //alternative.AddUtilityTerm(60, person.Household.HasValidIncome.ToFlag() * person.IsFulltimeWorker.ToFlag() * destinationParcel.EmploymentGovernment);
                //alternative.AddUtilityTerm(61, person.Household.HasValidIncome.ToFlag() * person.IsFulltimeWorker.ToFlag() * employmentIndustrialAgricultureConstruction);
                //alternative.AddUtilityTerm(62, person.Household.HasValidIncome.ToFlag() * person.IsPartTimeWorker.ToFlag() * employmentIndustrialAgricultureConstruction);
                //alternative.AddUtilityTerm(63, person.Household.HasValidIncome.ToFlag() * person.IsNotFullOrPartTimeWorker.ToFlag() * destinationParcel.EmploymentEducation);
                //alternative.AddUtilityTerm(64, person.Household.HasValidIncome.ToFlag() * person.IsNotFullOrPartTimeWorker.ToFlag() * destinationParcel.EmploymentFood);
                //alternative.AddUtilityTerm(65, person.Household.HasValidIncome.ToFlag() * person.IsNotFullOrPartTimeWorker.ToFlag() * destinationParcel.EmploymentRetail);

                //alternative.AddUtilityTerm(66, person.Household.HasIncomeUnder50K.ToFlag() * destinationParcel.EmploymentRetail);
                //alternative.AddUtilityTerm(67, person.Household.HasIncomeUnder50K.ToFlag() * destinationParcel.EmploymentService);
                //alternative.AddUtilityTerm(68, person.Household.Has50To75KIncome.ToFlag() * destinationParcel.EmploymentMedical);
                //alternative.AddUtilityTerm(69, person.Household.Has50To75KIncome.ToFlag() * destinationParcel.EmploymentOffice);
                //alternative.AddUtilityTerm(70, person.Household.Has75KPlusIncome.ToFlag() * destinationParcel.EmploymentEducation);
                //alternative.AddUtilityTerm(71, person.Household.Has75KPlusIncome.ToFlag() * destinationParcel.EmploymentGovernment);
                //alternative.AddUtilityTerm(72, person.Household.Has75KPlusIncome.ToFlag() * destinationParcel.EmploymentMedical);
                //alternative.AddUtilityTerm(73, person.Household.Has75KPlusIncome.ToFlag() * destinationParcel.EmploymentOffice);

                //alternative.AddUtilityTerm(74, person.IsFulltimeWorker.ToFlag() * person.Household.Has75KPlusIncome.ToFlag() * destinationParcel.EmploymentGovernment);
                //alternative.AddUtilityTerm(75, person.IsFulltimeWorker.ToFlag() * (!person.Household.Has75KPlusIncome).ToFlag() * employmentIndustrialAgricultureConstruction);
                //alternative.AddUtilityTerm(76, person.IsPartTimeWorker.ToFlag() * (!person.Household.HasIncomeUnder50K).ToFlag() * destinationParcel.EmploymentMedical);
                //alternative.AddUtilityTerm(77, (!person.IsFulltimeWorker).ToFlag() * person.Household.Has75KPlusIncome.ToFlag() * destinationParcel.EmploymentOffice);
                //alternative.AddUtilityTerm(78, person.IsNotFullOrPartTimeWorker.ToFlag() * (!person.Household.HasIncomeUnder50K).ToFlag() * destinationParcel.EmploymentRetail);

                //alternative.AddUtilityTerm(79, person.Household.HasMissingIncome.ToFlag() * destinationParcel.EmploymentTotal);
                //alternative.AddUtilityTerm(80, person.Household.HasMissingIncome.ToFlag() * destinationParcel.StudentsUniversity);

                // set shadow price depending on persontype and add it to utility
                // we are using the sampling adjustment factor assuming that it is 1
                alternative.AddUtilityTerm(1, destinationParcel.ShadowPriceForEmployment);

                //remove nesting for estimation of conditional MNL
                alternative.AddNestedAlternative(sampleSize + 2, 0, 98);
            }

            // JLB 20120329 added third call parameter to idenitfy whether this alt is chosen or not
            var homeAlternative = choiceProbabilityCalculator.GetAlternative(sampleSize, true, choseHome);

            homeAlternative.Choice = person.Household.ResidenceParcel;

            homeAlternative.AddUtilityTerm(41, 1);
            homeAlternative.AddUtilityTerm(42, (person.MainOccupation == 50).ToFlag()); // self-employed

            //homeAlternative.AddUtilityTerm(42, person.IsPartTimeWorker.ToFlag());
            //homeAlternative.AddUtilityTerm(43, person.IsStudentAge.ToFlag());
            //homeAlternative.AddUtilityTerm(44, person.IsFemale.ToFlag());
            homeAlternative.AddUtilityTerm(90, 1);

            //make oddball alt unavailable and remove nesting for estimation of conditional MNL
            //            alternative.Available = false;
            homeAlternative.AddNestedAlternative(sampleSize + 3, 1, 98);
        }
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, IHouseholdWrapper household, int choice = Constants.DEFAULT_VALUE)
        {
            //            var distanceToTransitCappedUnderQtrMile = household.ResidenceParcel.DistanceToTransitCappedUnderQtrMile();
            //            var distanceToTransitQtrToHalfMile = household.ResidenceParcel.DistanceToTransitQtrToHalfMile();
            double foodRetailServiceMedicalLogBuffer1 = household.ResidenceParcel.FoodRetailServiceMedicalLogBuffer1();

            double workTourLogsumDifference   = 0D; // (full or part-time workers) full car ownership vs. no car ownership
            double schoolTourLogsumDifference = 0D; // (school) full car ownership vs. no car ownership

            //            const double workTourOtherLogsumDifference = 0D; // (other workers) full car ownership vs. no car ownership

            foreach (IPersonWrapper person in household.Persons)
            {
                if (person.IsWorker && person.UsualWorkParcel != null && person.UsualWorkParcelId != household.ResidenceParcelId)
                {
                    int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                    int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);

                    ChoiceProbabilityCalculator.Alternative nestedAlternative1 = Global.ChoiceModelSession.Get <WorkTourModeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.HouseholdTotals.DrivingAgeMembers);
                    ChoiceProbabilityCalculator.Alternative nestedAlternative2 = Global.ChoiceModelSession.Get <WorkTourModeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, 0);

                    workTourLogsumDifference += nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
                    workTourLogsumDifference -= nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
                }

                if (person.IsDrivingAgeStudent && person.UsualSchoolParcel != null && person.UsualSchoolParcelId != household.ResidenceParcelId)
                {
                    int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
                    int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);

                    ChoiceProbabilityCalculator.Alternative nestedAlternative1 = Global.ChoiceModelSession.Get <SchoolTourModeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.HouseholdTotals.DrivingAgeMembers);
                    ChoiceProbabilityCalculator.Alternative nestedAlternative2 = Global.ChoiceModelSession.Get <SchoolTourModeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, 0);

                    schoolTourLogsumDifference += nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
                    schoolTourLogsumDifference -= nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
                }
            }

            // var votSegment = household.VotALSegment;
            //var taSegment = household.ResidenceParcel.TransitAccessSegment();

            //var aggregateLogsumDifference = // full car ownership vs. no car ownership
            //    Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult][votSegment][taSegment] -
            //    Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votSegment][taSegment];

            double distanceToStop
                = household.ResidenceParcel.GetDistanceToTransit() > 0
                      ? Math.Min(household.ResidenceParcel.GetDistanceToTransit(), 2 * Global.Settings.DistanceUnitsPerMile)  // JLBscale
                      : 2 * Global.Settings.DistanceUnitsPerMile;

            int ruralFlag = household.ResidenceParcel.RuralFlag();

            double zeroVehAVEffect = (Global.Configuration.AV_IncludeAutoTypeChoice && household.OwnsAutomatedVehicles > 0) ? Global.Configuration.AV_Own0VehiclesCoefficientForAVHouseholds : 0;
            double oneVehAVEffect  = (Global.Configuration.AV_IncludeAutoTypeChoice && household.OwnsAutomatedVehicles > 0) ? Global.Configuration.AV_Own1VehicleCoefficientForAVHouseholds : 0;

            double zeroVehSEEffect  = (Global.Configuration.PaidRideShareModeIsAvailable && Global.Configuration.AV_PaidRideShareModeUsesAVs) ? Global.Configuration.AV_SharingEconomy_DensityCoefficientForOwning0Vehicles * Math.Min(household.ResidenceBuffer2Density, 6000) : 0;
            double oneVehSEEffect   = (Global.Configuration.PaidRideShareModeIsAvailable && Global.Configuration.AV_PaidRideShareModeUsesAVs) ? Global.Configuration.AV_SharingEconomy_ConstantForOwning1Vehicle : 0;
            double twoVehSEEffect   = (Global.Configuration.PaidRideShareModeIsAvailable && Global.Configuration.AV_PaidRideShareModeUsesAVs) ? Global.Configuration.AV_SharingEconomy_ConstantForOwning2Vehicles : 0;
            double threeVehSEEffect = (Global.Configuration.PaidRideShareModeIsAvailable && Global.Configuration.AV_PaidRideShareModeUsesAVs) ? Global.Configuration.AV_SharingEconomy_ConstantForOwning3Vehicles : 0;
            double fourVehSEEffect  = (Global.Configuration.PaidRideShareModeIsAvailable && Global.Configuration.AV_PaidRideShareModeUsesAVs) ? Global.Configuration.AV_SharingEconomy_ConstantForOwning4Vehicles : 0;

            // 0 AUTOS

            ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(0, true, choice == 0);

            alternative.Choice = 0;

            alternative.AddUtilityTerm(90, 1); //new calibration constant - can be used in estimation if coefficient 5 is constrained to 0
            alternative.AddUtilityTerm(1, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(5, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(9, household.Has3Drivers.ToFlag());
            alternative.AddUtilityTerm(13, household.Has4OrMoreDrivers.ToFlag());
            //            alternative.AddUtility(17, 0);
            alternative.AddUtilityTerm(18, household.HasNoFullOrPartTimeWorker.ToFlag());
            alternative.AddUtilityTerm(19, household.HouseholdTotals.PartTimeWorkersPerDrivingAgeMembers);
            //            alternative.AddUtility(23, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
            //            alternative.AddUtility(27, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(31, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(35, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);
            //            alternative.AddUtility(39, household.HouseholdTotals.ChildrenUnder5PerDrivingAgeMembers);
            alternative.AddUtilityTerm(43, household.Has0To15KIncome.ToFlag());
            alternative.AddUtilityTerm(47, household.Has50To75KIncome.ToFlag());
            alternative.AddUtilityTerm(51, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(55, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(59, workTourLogsumDifference);
            //            alternative.AddUtility(61, workTourOtherLogsumDifference);
            alternative.AddUtilityTerm(63, schoolTourLogsumDifference);
            //            alternative.AddUtility(67, aggregateLogsumDifference);
            alternative.AddUtilityTerm(69, Math.Log(distanceToStop));
            //            alternative.AddUtility(70, Math.Log(1+household.ResidenceParcel.StopsTransitBuffer1));
            alternative.AddUtilityTerm(73, household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer1);
            alternative.AddUtilityTerm(75, foodRetailServiceMedicalLogBuffer1);
            alternative.AddUtilityTerm(77, workTourLogsumDifference * ruralFlag);
            //            alternative.AddUtility(78, workTourOtherLogsumDifference * ruralFlag);
            //            alternative.AddUtility(79, aggregateLogsumDifference * ruralFlag);
            //            alternative.AddUtility(80, Math.Log(distanceToStop)*ruralFlag);
            //            alternative.AddUtility(81, Math.Log(1+household.ResidenceParcel.StopsTransitBuffer1)*ruralFlag);
            //            alternative.AddUtility(82, foodRetailServiceMedicalQtrMileLog * ruralFlag);
            alternative.AddUtilityTerm(83, ruralFlag);

            alternative.AddUtilityTerm(200, zeroVehAVEffect);
            alternative.AddUtilityTerm(200, zeroVehSEEffect);

            RegionSpecificCustomizations(alternative, household);


            // 1 AUTO

            alternative = choiceProbabilityCalculator.GetAlternative(1, true, choice == 1);

            alternative.Choice = 1;

            alternative.AddUtilityTerm(91, 1); //new calibration constant - can be used in estimation if coefficient 6 is constrained to 0
            alternative.AddUtilityTerm(6, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(10, household.Has3Drivers.ToFlag());
            alternative.AddUtilityTerm(14, household.Has4OrMoreDrivers.ToFlag());
            //            alternative.AddUtility(17, 1D / Math.Max(household.HouseholdTotals.DrivingAgeMembers, 1)); // ratio of 1 car per driving age members
            alternative.AddUtilityTerm(18, household.Has1OrLessFullOrPartTimeWorkers.ToFlag());
            alternative.AddUtilityTerm(20, household.HouseholdTotals.PartTimeWorkersPerDrivingAgeMembers);
            alternative.AddUtilityTerm(24, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(28, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(32, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(36, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);
            //            alternative.AddUtility(40, household.HouseholdTotals.ChildrenUnder5PerDrivingAgeMembers);
            alternative.AddUtilityTerm(44, household.Has0To15KIncome.ToFlag());
            alternative.AddUtilityTerm(48, household.Has50To75KIncome.ToFlag());
            alternative.AddUtilityTerm(52, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(56, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(60, workTourLogsumDifference * household.HasMoreDriversThan1.ToFlag());
            //            alternative.AddUtility(62, workTourOtherLogsumDifference * household.HasMoreDriversThan1.ToFlag());
            //            alternative.AddUtility(64, schoolTourLogsumDifference * household.HasMoreDriversThan1.ToFlag());
            //            alternative.AddUtility(68, aggregateLogsumDifference * household.HasMoreDriversThan1.ToFlag());
            alternative.AddUtilityTerm(72, Math.Log(1 + household.ResidenceParcel.StopsTransitBuffer1) * household.HasMoreDriversThan1.ToFlag());
            //alternative.AddUtility(74, household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer1 * household.HasMoreDriversThan1.ToFlag());
            alternative.AddUtilityTerm(76, foodRetailServiceMedicalLogBuffer1 * household.HasMoreDriversThan1.ToFlag());

            alternative.AddUtilityTerm(200, oneVehAVEffect);
            alternative.AddUtilityTerm(200, oneVehSEEffect);

            RegionSpecificCustomizations(alternative, household);


            // 2 AUTOS

            alternative = choiceProbabilityCalculator.GetAlternative(2, true, choice == 2);

            alternative.Choice = 2;

            alternative.AddUtilityTerm(92, 1); //new calibration constant - must be constrained to 0 in estimation
            alternative.AddUtilityTerm(2, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(11, household.Has3Drivers.ToFlag());
            alternative.AddUtilityTerm(15, household.Has4OrMoreDrivers.ToFlag());
            //            alternative.AddUtility(17, 2D / Math.Max(household.HouseholdTotals.DrivingAgeMembers, 1)); // ratio of 2 cars per driving age members
            alternative.AddUtilityTerm(18, household.Has2OrLessFullOrPartTimeWorkers.ToFlag());
            alternative.AddUtilityTerm(60, workTourLogsumDifference * household.HasMoreDriversThan2.ToFlag());
            //            alternative.AddUtility(62, workTourOtherLogsumDifference * household.HasMoreDriversThan2.ToFlag());
            //            alternative.AddUtility(64, schoolTourLogsumDifference * household.HasMoreDriversThan2.ToFlag());
            //            alternative.AddUtility(68, aggregateLogsumDifference * household.HasMoreDriversThan2.ToFlag());
            alternative.AddUtilityTerm(72, Math.Log(1 + household.ResidenceParcel.StopsTransitBuffer1) * household.HasMoreDriversThan2.ToFlag());
            //            alternative.AddUtility(74, household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer1 * household.HasMoreDriversThan2.ToFlag());
            alternative.AddUtilityTerm(76, foodRetailServiceMedicalLogBuffer1 * household.HasMoreDriversThan2.ToFlag());

            alternative.AddUtilityTerm(200, twoVehSEEffect);

            RegionSpecificCustomizations(alternative, household);

            // 3 AUTOS

            alternative = choiceProbabilityCalculator.GetAlternative(3, true, choice == 3);

            alternative.Choice = 3;

            alternative.AddUtilityTerm(93, 1); //new calibration constant - can be used in estimation if coefficient 7 is constrained to 0
            alternative.AddUtilityTerm(3, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(7, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(16, household.Has4OrMoreDrivers.ToFlag());
            //            alternative.AddUtility(17, 3D / Math.Max(household.HouseholdTotals.DrivingAgeMembers, 1)); // ratio of 3 cars per driving age members
            alternative.AddUtilityTerm(18, household.Has3OrLessFullOrPartTimeWorkers.ToFlag());
            //            alternative.AddUtility(21, household.HouseholdTotals.PartTimeWorkersPerDrivingAgeMembers);
            alternative.AddUtilityTerm(25, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(29, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            //            alternative.AddUtility(33, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(37, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(41, household.HouseholdTotals.ChildrenUnder5PerDrivingAgeMembers);
            alternative.AddUtilityTerm(45, household.Has0To15KIncome.ToFlag());
            alternative.AddUtilityTerm(49, household.Has50To75KIncome.ToFlag());
            alternative.AddUtilityTerm(53, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(57, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(60, workTourLogsumDifference * household.HasMoreDriversThan3.ToFlag());
            //            alternative.AddUtility(62, workTourOtherLogsumDifference * household.HasMoreDriversThan3.ToFlag());
            //            alternative.AddUtility(64, schoolTourLogsumDifference * household.HasMoreDriversThan3.ToFlag());
            //            alternative.AddUtility(68, aggregateLogsumDifference * household.HasMoreDriversThan3.ToFlag());
            alternative.AddUtilityTerm(72, Math.Log(1 + household.ResidenceParcel.StopsTransitBuffer1) * household.HasMoreDriversThan3.ToFlag());
            //            alternative.AddUtility(74, household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer1 * household.HasMoreDriversThan3.ToFlag());
            alternative.AddUtilityTerm(76, foodRetailServiceMedicalLogBuffer1 * household.HasMoreDriversThan3.ToFlag());

            alternative.AddUtilityTerm(200, threeVehSEEffect);

            RegionSpecificCustomizations(alternative, household);

            // 4+ AUTOS

            alternative = choiceProbabilityCalculator.GetAlternative(4, true, choice == 4);

            alternative.Choice = 4;

            alternative.AddUtilityTerm(94, 1); //new calibration constant - can be used in estimation if coefficient 8 is constrained to 0
            alternative.AddUtilityTerm(4, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(8, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(12, household.Has3Drivers.ToFlag());
            //            alternative.AddUtility(17, 4D / Math.Max(household.HouseholdTotals.DrivingAgeMembers, 1)); // ratio of 4 cars per driving age members
            alternative.AddUtilityTerm(18, household.Has4OrLessFullOrPartTimeWorkers.ToFlag());
            alternative.AddUtilityTerm(22, household.HouseholdTotals.PartTimeWorkersPerDrivingAgeMembers);
            alternative.AddUtilityTerm(26, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
            //            alternative.AddUtility(30, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(34, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(38, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(42, household.HouseholdTotals.ChildrenUnder5PerDrivingAgeMembers);
            alternative.AddUtilityTerm(46, household.Has0To15KIncome.ToFlag());
            alternative.AddUtilityTerm(50, household.Has50To75KIncome.ToFlag());
            alternative.AddUtilityTerm(54, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(58, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(60, workTourLogsumDifference * household.HasMoreDriversThan4.ToFlag());
            //            alternative.AddUtility(62, workTourOtherLogsumDifference * household.HasMoreDriversThan4.ToFlag());
            //            alternative.AddUtility(64, schoolTourLogsumDifference * household.HasMoreDriversThan4.ToFlag());
            //            alternative.AddUtility(68, aggregateLogsumDifference * household.HasMoreDriversThan4.ToFlag());
            alternative.AddUtilityTerm(72, Math.Log(1 + household.ResidenceParcel.StopsTransitBuffer1) * household.HasMoreDriversThan4.ToFlag());
            //            alternative.AddUtility(74, household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer1 * household.HasMoreDriversThan4.ToFlag());
            alternative.AddUtilityTerm(76, foodRetailServiceMedicalLogBuffer1 * household.HasMoreDriversThan4.ToFlag());

            alternative.AddUtilityTerm(200, fourVehSEEffect);

            RegionSpecificCustomizations(alternative, household);
        }
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, HouseholdDayWrapper householdDay, int choice = Constants.DEFAULT_VALUE)
        {
            Framework.DomainModels.Wrappers.IHouseholdWrapper household       = householdDay.Household;
            Framework.DomainModels.Wrappers.IParcelWrapper    residenceParcel = household.ResidenceParcel;

            // set household characteristics here that don't depend on person characteristics

            int hasAdultEducLevel12 = 0;
            int youngestAge         = 999;


            double firstWorkLogsum       = 0;
            double secondWorkLogsum      = 0;
            bool   firstWorkLogsumIsSet  = false;
            bool   secondWorkLogsumIsSet = false;
            int    numberWorkers         = 0;
            int    numberAdults          = 0;
            int    numberChildren        = 0;
            int    numberChildrenUnder5  = 0;


            // set characteristics here that depend on person characteristics
            foreach (PersonDayWrapper personDay in householdDay.PersonDays)
            {
                double        workLogsum = 0;
                PersonWrapper person     = (PersonWrapper)personDay.Person;
                if (person.UsualWorkParcel == null || person.UsualWorkParcelId == household.ResidenceParcelId ||
                    (person.PersonType != Global.Settings.PersonTypes.FullTimeWorker &&
                     person.PersonType != Global.Settings.PersonTypes.PartTimeWorker))
                //	|| household.VehiclesAvailable == 0)
                {
                }
                else
                {
                    int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                    int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
                    //JLB 201406
                    //var nestedAlternative = Global.ChoiceModelSession.Get<WorkTourModeModel>().RunNested(personDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);

                    //JLB 201602
                    //var nestedAlternative = Global.ChoiceModelSession.Get<TourModeTimeModel>().RunNested(personDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);
                    ChoiceProbabilityCalculator.Alternative nestedAlternative = Global.ChoiceModelSession.Get <TourModeTimeModel>().RunNested(personDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, Global.Settings.Purposes.Work);
                    workLogsum = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
                }
                //if (person.Age >= 18 && person.EducationLevel >= 12) {
                //  hasAdultEducLevel12 = 1;
                //}

                //if (person.Age >= 18 && person.EducationLevel < 12) {
                //}

                if (person.Age < youngestAge)
                {
                    youngestAge = person.Age;
                }

                if (workLogsum != 0 && !firstWorkLogsumIsSet)
                {
                    firstWorkLogsum      = workLogsum;
                    firstWorkLogsumIsSet = true;
                }
                else if (workLogsum != 0 && !secondWorkLogsumIsSet)
                {
                    secondWorkLogsum      = workLogsum;
                    secondWorkLogsumIsSet = true;
                }
                if (person.Age >= 18)
                {
                    numberAdults++;
                    if (person.PersonType == Global.Settings.PersonTypes.FullTimeWorker
                        //|| person.PersonType == Constants.PersonType.PART_TIME_WORKER
                        )
                    {
                        numberWorkers++;
                    }
                }
                else
                {
                    numberChildren++;
                    if (person.PersonType == Global.Settings.PersonTypes.ChildUnder5)
                    {
                        numberChildrenUnder5++;
                    }
                }
            }
            bool singleWorkerWithChildUnder5 = (numberAdults == numberWorkers && numberAdults == 1 &&
                                                numberChildrenUnder5 > 0) ? true : false;
            bool workingCoupleNoChildren = (numberAdults == numberWorkers && numberAdults == 2 &&
                                            numberChildren == 0) ? true : false;
            bool workingCoupleAllChildrenUnder5 = (numberAdults == numberWorkers && numberAdults == 2 &&
                                                   numberChildren > 0 && numberChildren == numberChildrenUnder5) ? true : false;
            bool otherHouseholdWithPTFTWorkers = false;

            if (!workingCoupleNoChildren && !workingCoupleAllChildrenUnder5 && firstWorkLogsum != 0)
            {
                otherHouseholdWithPTFTWorkers = true;
            }
            if (!workingCoupleNoChildren && !workingCoupleAllChildrenUnder5 && !otherHouseholdWithPTFTWorkers)
            {
            }


            // var votSegment = household.VotALSegment;
            //var taSegment = household.ResidenceParcel.TransitAccessSegment();

            //var aggregateLogsumDifference = // full car ownership vs. no car ownership
            //	Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult][votSegment][taSegment] -
            //	Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votSegment][taSegment];


            //var householdDay = (ActumHouseholdDayWrapper)tour.HouseholdDay;

            int carOwnership =
                household.VehiclesAvailable == 0
                                 ? Global.Settings.CarOwnerships.NoCars
                                 : household.VehiclesAvailable < household.HouseholdTotals.DrivingAgeMembers
                                      ? Global.Settings.CarOwnerships.LtOneCarPerAdult
                                      : Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult;

            int noCarsFlag         = FlagUtility.GetNoCarsFlag(carOwnership);
            int carCompetitionFlag = FlagUtility.GetCarCompetitionFlag(carOwnership);

            int    votALSegment                    = Global.Settings.VotALSegments.Medium; // TODO:  calculate a VOT segment that depends on household income
            int    transitAccessSegment            = household.ResidenceParcel.TransitAccessSegment();
            double personalBusinessAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                                     [Global.Settings.Purposes.PersonalBusiness][carOwnership][votALSegment][transitAccessSegment];
            double shoppingAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                             [Global.Settings.Purposes.Shopping][carOwnership][votALSegment][transitAccessSegment];
            double mealAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                         [Global.Settings.Purposes.Meal][carOwnership][votALSegment][transitAccessSegment];
            double socialAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                           [Global.Settings.Purposes.Social][carOwnership][votALSegment][transitAccessSegment];
            //var compositeLogsum = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][carOwnership][votALSegment][transitAccessSegment];
            double compositeLogsum = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votALSegment][transitAccessSegment];

            int componentIndex = 0;

            for (int pfpt = 0; pfpt < 2; pfpt++)
            {
                if (pfpt == 1)
                {
                    componentIndex = 1;
                    choiceProbabilityCalculator.CreateUtilityComponent(componentIndex);
                    ChoiceProbabilityCalculator.Component pfptComponent = choiceProbabilityCalculator.GetUtilityComponent(componentIndex);
                    pfptComponent.AddUtilityTerm(1, (householdDay.Household.Size == 3).ToFlag());
                    pfptComponent.AddUtilityTerm(2, (householdDay.Household.Size >= 4).ToFlag());
                    pfptComponent.AddUtilityTerm(3, householdDay.Household.HasChildrenUnder5.ToFlag());
                    pfptComponent.AddUtilityTerm(4, (householdDay.AdultsInSharedHomeStay == 1 && householdDay.Household.HasChildrenAge5Through15).ToFlag());
                    pfptComponent.AddUtilityTerm(5, (householdDay.AdultsInSharedHomeStay == 2 && householdDay.Household.HouseholdTotals.FullAndPartTimeWorkers >= 2).ToFlag());
                    pfptComponent.AddUtilityTerm(6, (householdDay.AdultsInSharedHomeStay == 2 && hasAdultEducLevel12 == 1).ToFlag());
                    pfptComponent.AddUtilityTerm(7, (householdDay.Household.VehiclesAvailable == 1 && household.Has2Drivers).ToFlag());
                    pfptComponent.AddUtilityTerm(8, (householdDay.Household.VehiclesAvailable >= 2 && household.Has2Drivers).ToFlag());

                    pfptComponent.AddUtilityTerm(11, (householdDay.Household.Income >= 300000 && householdDay.Household.Income < 600000).ToFlag());
                    pfptComponent.AddUtilityTerm(12, (householdDay.Household.Income >= 600000 && householdDay.Household.Income < 900000).ToFlag());
                    pfptComponent.AddUtilityTerm(13, (householdDay.Household.Income >= 900000).ToFlag());

                    // OBS; 27. aug., work tour mode logsum does not work - see what happens in the old PFPT model
                    // GV, sep. 1st - it is not significant
                    pfptComponent.AddUtilityTerm(15, (firstWorkLogsum + secondWorkLogsum) *
                                                 (workingCoupleNoChildren || workingCoupleAllChildrenUnder5).ToFlag());
                    pfptComponent.AddUtilityTerm(15, (firstWorkLogsum + secondWorkLogsum) * otherHouseholdWithPTFTWorkers.ToFlag());

                    // dette er gamle at-work logsum - it should be plus and significant
                    //alternative.AddUtilityTerm(31, (firstWorkLogsum + secondWorkLogsum) *
                    //(workingCoupleNoChildren || workingCoupleAllChildrenUnder5).ToFlag());
                    //alternative.AddUtilityTerm(31, (firstWorkLogsum + secondWorkLogsum) * otherHouseholdWithPTFTWorkers.ToFlag());

                    // at-home logsum works
                    pfptComponent.AddUtilityTerm(16, compositeLogsum);

                    //pfpt constant
                    pfptComponent.AddUtilityTerm(51, 1);
                }
            }
            for (int jointTourFlag = 0; jointTourFlag < 2; jointTourFlag++)
            {
                if (jointTourFlag == 1)
                {
                    componentIndex = 2;
                    choiceProbabilityCalculator.CreateUtilityComponent(componentIndex);
                    ChoiceProbabilityCalculator.Component jointComponent = choiceProbabilityCalculator.GetUtilityComponent(componentIndex);

                    jointComponent.AddUtilityTerm(21, (householdDay.Household.Size == 3).ToFlag());
                    jointComponent.AddUtilityTerm(22, (householdDay.Household.Size >= 4).ToFlag());

                    // GV: 1st sep.
                    //jointComponent.AddUtilityTerm(23, (householdDay.Household.Size == 2 && householdDay.Household.HasChildren).ToFlag());
                    //jointComponent.AddUtilityTerm(23, (householdDay.Household.Size >= 2 && householdDay.Household.HasChildren).ToFlag());
                    jointComponent.AddUtilityTerm(23, (householdDay.Household.HasChildren).ToFlag());

                    //jointComponent.AddUtilityTerm(21, householdDay.Household.HasChildrenUnder5.ToFlag());
                    //jointComponent.AddUtilityTerm(22, householdDay.Household.HasChildrenAge5Through15.ToFlag());

                    //jointComponent.AddUtilityTerm(23, householdDay.Household.HasChildren.ToFlag());

                    jointComponent.AddUtilityTerm(24, (householdDay.Household.Size == 2 && householdDay.AdultsInSharedHomeStay == 2).ToFlag());
                    //jointComponent.AddUtilityTerm(25, (householdDay.AdultsInSharedHomeStay == 2 && householdDay.Household.HouseholdTotals.FullAndPartTimeWorkers >= 2).ToFlag());
                    jointComponent.AddUtilityTerm(26, (householdDay.AdultsInSharedHomeStay == 2 && hasAdultEducLevel12 == 1).ToFlag());

                    //jointComponent.AddUtilityTerm(27, (householdDay.Household.Size == 2 && householdDay.Household.HasChildrenUnder5).ToFlag());
                    //jointComponent.AddUtilityTerm(28, (householdDay.Household.Size == 2 && householdDay.Household.HasChildrenAge5Through15).ToFlag());
                    //jointComponent.AddUtilityTerm(27, (householdDay.Household.Size == 2 && householdDay.Household.HasChildrenUnder16).ToFlag());

                    jointComponent.AddUtilityTerm(29, (householdDay.AdultsInSharedHomeStay == 1 && householdDay.Household.HasChildrenUnder16).ToFlag());

                    //jointComponent.AddUtilityTerm(37, (householdDay.Household.VehiclesAvailable == 1 && household.Has2Drivers).ToFlag());
                    //jointComponent.AddUtilityTerm(38, (householdDay.Household.VehiclesAvailable >= 2 && household.Has2Drivers).ToFlag());
                    jointComponent.AddUtilityTerm(30, (householdDay.Household.VehiclesAvailable >= 1 && household.Has2Drivers).ToFlag());

                    jointComponent.AddUtilityTerm(31, (householdDay.Household.Income >= 300000 && householdDay.Household.Income < 600000).ToFlag());
                    jointComponent.AddUtilityTerm(32, (householdDay.Household.Income >= 600000 && householdDay.Household.Income < 900000).ToFlag());
                    jointComponent.AddUtilityTerm(33, (householdDay.Household.Income >= 900000).ToFlag());

                    // GV, sep. 1st - it is not significant
                    //jointComponent.AddUtilityTerm(41, compositeLogsum);

                    // joint non-mandatory tour constant
                    jointComponent.AddUtilityTerm(61, 1);
                }
            }

            bool available = true;

            for (int pfpt = 0; pfpt < 2; pfpt++)
            {
                for (int jointTourFlag = 0; jointTourFlag < 2; jointTourFlag++)
                {
                    int altIndex = pfpt + jointTourFlag * 2;
                    if (household.Size < 2 && altIndex > 0)
                    {
                        available = false;
                    }
                    else
                    {
                        available = true;
                    }
                    ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(altIndex, available, choice == altIndex);

                    alternative.Choice = altIndex;

                    //NESTING WAS REJECTED BY TESTS
                    //GV: PFPT on top - cannot be estimated
                    //alternative.AddNestedAlternative(5 + pfpt,          pfpt, THETA_PARAMETER);
                    //alternative.AddNestedAlternative(5 + jointTourFlag, jointTourFlag, THETA_PARAMETER); //jointTourFlag on top

                    if (pfpt == 1)
                    {
                        alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(1));
                        //alternative.AddUtilityTerm(20, 1);
                    }
                    if (jointTourFlag == 1)
                    {
                        alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(2));
                        //alternative.AddUtilityTerm(40, 1);
                    }

                    if (pfpt == 1 && jointTourFlag == 1)
                    {
                        alternative.AddUtilityTerm(71, 1);
                        //alternative.AddUtilityTerm(72, (householdDay.Household.Size == 2 && householdDay.AdultsInSharedHomeStay == 2).ToFlag());

                        // GV: comented out sep. 1st
                        //GV: coeff. 73 is with a wrong sign - 13. june 2016
                        //alternative.AddUtilityTerm(73, householdDay.Household.HasChildren.ToFlag());
                        //alternative.AddUtilityTerm(74, householdDay.Household.HasChildrenUnder16.ToFlag());
                    }
                }
            }
        }
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, TourWrapper tour, int nCallsForTour, HouseholdDayWrapper householdDay, int choice = Constants.DEFAULT_VALUE)
        {
            IEnumerable <PersonDayWrapper> orderedPersonDays = householdDay.PersonDays.OrderBy(p => p.GetJointTourParticipationPriority()).ToList().Cast <PersonDayWrapper>();

            Framework.DomainModels.Wrappers.IPersonWrapper    person    = tour.Person;
            Framework.DomainModels.Wrappers.IPersonDayWrapper personDay = tour.PersonDay;

            int adultFemaleFlag    = person.IsAdultFemale.ToFlag();
            int partTimeWorkerFlag = person.IsPartTimeWorker.ToFlag();

            double foodBuffer2      = tour.DestinationParcel.EmploymentFoodBuffer2;
            double medBuffer2       = tour.DestinationParcel.EmploymentMedicalBuffer2;
            double intDensBuffer2   = tour.DestinationParcel.IntersectionDensity34Buffer2();
            double serviceBuffer2   = tour.DestinationParcel.EmploymentServiceBuffer2;
            double totEmpBuffer2    = tour.DestinationParcel.EmploymentTotalBuffer2;
            double totHHBuffer2     = tour.DestinationParcel.HouseholdsBuffer2;
            double openSpaceBuffer2 = tour.DestinationParcel.OpenSpaceType1Buffer2;
            double mixedUse         = tour.DestinationParcel.MixedUse2Index2();
            //var retailBuffer2 = tour.DestinationParcel.EmploymentRetailBuffer2;
            //var retailBuffer1 = tour.DestinationParcel.EmploymentRetailBuffer1;

            int carOwnership = person.GetCarOwnershipSegment();
            int noCarsFlag   = FlagUtility.GetNoCarsFlag(carOwnership);
            //var carCompetitionFlag = AggregateLogsumsCalculator.GetCarCompetitionFlag(carOwnership);

            int votALSegment = tour.GetVotALSegment();

            int    workTaSegment       = tour.DestinationParcel.TransitAccessSegment();
            double workAggregateLogsum = Global.AggregateLogsums[tour.DestinationParcel.ZoneId]
                                         [Global.Settings.Purposes.WorkBased][carOwnership][votALSegment][workTaSegment];
            double shopAggregateLogsum = Global.AggregateLogsums[tour.DestinationParcel.ZoneId]
                                         [Global.Settings.Purposes.Shopping][carOwnership][votALSegment][workTaSegment];
            //var mealAggregateLogsum = Global.AggregateLogsums[tour.DestinationParcel.ZoneId]
            //[Global.Settings.Purposes.Meal][carOwnership][votALSegment][workTaSegment];
            //var persBusAggregateLogsum = Global.AggregateLogsums[tour.DestinationParcel.ZoneId]
            //[Global.Settings.Purposes.PersonalBusiness][carOwnership][votALSegment][workTaSegment];
            //var socialAggregateLogsum = Global.AggregateLogsums[tour.DestinationParcel.ZoneId]
            //[Global.Settings.Purposes.Social][carOwnership][votALSegment][workTaSegment];

            int numStopPurposes = (personDay.SimulatedEscortStops > 1).ToFlag() + (personDay.SimulatedShoppingStops > 1).ToFlag() + (personDay.SimulatedMealStops > 1).ToFlag() +
                                  (personDay.SimulatedPersonalBusinessStops > 1).ToFlag() + (personDay.SimulatedSocialStops > 1).ToFlag() +
                                  (personDay.SimulatedRecreationStops > 1).ToFlag() + (personDay.SimulatedMedicalStops > 1).ToFlag();

            int    workDestinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
            int    workDestinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
            double workLogsum = 0;

            ChoiceProbabilityCalculator.Alternative nestedAlternative = Global.ChoiceModelSession.Get <WorkTourModeTimeModel>().RunNested(personDay, person.Household.ResidenceParcel, person.UsualWorkParcel, workDestinationArrivalTime, workDestinationDepartureTime, person.Household.VehiclesAvailable);
            workLogsum = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();

            //double logTimeAtWork = Math.Log(1 + (workDestinationDepartureTime - workDestinationArrivalTime) / 60);

            //int countMandatoryKids = (from personDayHH in orderedPersonDays where personDayHH.PatternType == 1 && personDayHH.Person.Age < 12 select personDayHH.PatternType).Count();
            //int countNonMandatory = (from personDayHH in orderedPersonDays where personDayHH.PatternType == 2 select personDayHH.PatternType).Count();
            //int countAtHome = (from personDayHH in orderedPersonDays where personDayHH.PatternType == 3 select personDayHH.PatternType).Count();
            int countNonMandatoryKids = (from personDayHH in orderedPersonDays where personDayHH.PatternType == 2 && personDayHH.Person.Age < 12 select personDayHH.PatternType).Count();

            // NONE_OR_HOME

            ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.NoneOrHome, true, choice == Global.Settings.Purposes.NoneOrHome);

            alternative.Choice = Global.Settings.Purposes.NoneOrHome;

            alternative.AddUtilityTerm(1, (nCallsForTour > 1).ToFlag());
            alternative.AddUtilityTerm(3, personDay.TwoOrMoreWorkToursExist().ToFlag());
            alternative.AddUtilityTerm(4, noCarsFlag);
            //alternative.AddUtilityTerm(5, carCompetitionFlag);
            alternative.AddUtilityTerm(6, partTimeWorkerFlag);
            //alternative.AddUtilityTerm(8, (person.UsualModeToWork != Global.Settings.Modes.Sov).ToFlag());
            alternative.AddUtilityTerm(10, person.TransitPassOwnership);
            //alternative.AddUtilityTerm(15, logTimeAtWork);
            alternative.AddUtilityTerm(17, numStopPurposes);
            alternative.AddUtilityTerm(18, Math.Log(personDay.GetTotalCreatedTours() + 1));

            // WORK

            alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Work, personDay.WorkStops > 0, choice == Global.Settings.Purposes.Work);

            alternative.Choice = Global.Settings.Purposes.Work;

            alternative.AddUtilityTerm(21, 1);
            alternative.AddUtilityTerm(22, Math.Log(1 + totEmpBuffer2));
            //alternative.AddUtilityTerm(23, (person.Household.Income<30000).ToFlag());
            alternative.AddUtilityTerm(24, (person.Household.Has100KPlusIncome).ToFlag());
            alternative.AddUtilityTerm(25, workLogsum);

            // SCHOOL
            //no observations in the PSRC dataset
            alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.School, false, choice == Global.Settings.Purposes.School);

            alternative.Choice = Global.Settings.Purposes.School;

            //alternative.AddUtilityTerm(3, 1);

            // ESCORT

            alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Escort, personDay.EscortStops > 0, choice == Global.Settings.Purposes.Escort);

            alternative.Choice = Global.Settings.Purposes.Escort;

            alternative.AddUtilityTerm(31, 1);
            //alternative.AddUtilityTerm(33, k8HighSchoolQtrMileLog);
            alternative.AddUtilityTerm(36, countNonMandatoryKids);
            alternative.AddUtilityTerm(37, adultFemaleFlag);
            //alternative.AddUtilityTerm(38, person.Household.Size);
            //alternative.AddUtilityTerm(39, householdDay.Household.HouseholdTotals.ChildrenAge5Through15);
            //alternative.AddUtilityTerm(40, partTimeWorkerFlag);
            alternative.AddUtilityTerm(39, workLogsum);

            // PERSONAL_BUSINESS

            alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.PersonalBusiness, personDay.PersonalBusinessStops > 0, choice == Global.Settings.Purposes.PersonalBusiness);

            alternative.Choice = Global.Settings.Purposes.PersonalBusiness;

            alternative.AddUtilityTerm(41, 1);
            //alternative.AddUtilityTerm(43, persBusAggregateLogsum);
            alternative.AddUtilityTerm(45, Math.Log(1 + totEmpBuffer2));
            //alternative.AddUtilityTerm(48, (person.Household.Income>90000).ToFlag());
            alternative.AddUtilityTerm(49, (person.Household.HouseholdTotals.ChildrenUnder16));


            // SHOPPING

            alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Shopping, personDay.ShoppingStops > 0, choice == Global.Settings.Purposes.Shopping);

            alternative.Choice = Global.Settings.Purposes.Shopping;

            alternative.AddUtilityTerm(51, 1);
            //alternative.AddUtilityTerm(53, retailBuffer1);
            //alternative.AddUtilityTerm(54, partTimeWorkerFlag);
            alternative.AddUtilityTerm(55, (person.Household.Has100KPlusIncome).ToFlag());
            alternative.AddUtilityTerm(57, person.Household.HouseholdTotals.ChildrenUnder16);
            alternative.AddUtilityTerm(58, shopAggregateLogsum);
            //alternative.AddUtilityTerm(59, person.Household.Size);
            //alternative.AddUtilityTerm(59, (person.Household.Income<30000).ToFlag());


            // MEAL

            alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Meal, personDay.MealStops > 0, choice == Global.Settings.Purposes.Meal);

            alternative.Choice = Global.Settings.Purposes.Meal;

            alternative.AddUtilityTerm(71, 1);
            alternative.AddUtilityTerm(73, Math.Log(1 + foodBuffer2));
            alternative.AddUtilityTerm(74, mixedUse);
            alternative.AddUtilityTerm(75, intDensBuffer2);
            //alternative.AddUtilityTerm(76, (person.Household.Income<30000).ToFlag());
            //alternative.AddUtilityTerm(77, person.Household.HouseholdTotals.ChildrenUnder16);

            // SOCIAL

            alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Social, personDay.SocialStops > 0, choice == Global.Settings.Purposes.Social);

            alternative.Choice = Global.Settings.Purposes.Social;

            alternative.AddUtilityTerm(91, 1);
            alternative.AddUtilityTerm(93, person.Household.HouseholdTotals.ChildrenUnder16);
            alternative.AddUtilityTerm(94, (person.Age < 35).ToFlag());
            //alternative.AddUtilityTerm(115, workAggregateLogsum);
            alternative.AddUtilityTerm(96, Math.Log(1 + totHHBuffer2 + totEmpBuffer2));
            alternative.AddUtilityTerm(97, (person.Household.Income < 30000).ToFlag());
            //alternative.AddUtilityTerm(118, person.Household.Has100KPlusIncome.ToFlag());

            // RECREATION

            alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Recreation, personDay.RecreationStops > 0, choice == Global.Settings.Purposes.Recreation);

            alternative.Choice = Global.Settings.Purposes.Recreation;

            alternative.AddUtilityTerm(111, 1);
            alternative.AddUtilityTerm(113, person.Household.HouseholdTotals.ChildrenUnder16);
            alternative.AddUtilityTerm(114, (person.Age < 35).ToFlag());
            alternative.AddUtilityTerm(116, Math.Log(1 + totHHBuffer2 + totEmpBuffer2));
            alternative.AddUtilityTerm(117, (person.Household.Income < 30000).ToFlag());
            alternative.AddUtilityTerm(118, (person.Household.Income > 100000).ToFlag());
            alternative.AddUtilityTerm(119, Math.Log(1 + openSpaceBuffer2));

            // MEDICAL

            alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Medical, personDay.MedicalStops > 0, choice == Global.Settings.Purposes.Medical);

            alternative.Choice = Global.Settings.Purposes.Medical;

            alternative.AddUtilityTerm(121, 1);
            alternative.AddUtilityTerm(123, adultFemaleFlag);
            alternative.AddUtilityTerm(124, (person.Age > 65).ToFlag());
            alternative.AddUtilityTerm(125, Math.Log(1 + medBuffer2));
            //alternative.AddUtilityTerm(126, workAggregateLogsum);

            //alternative.AddNestedAlternative(12, 1, 60);
        }
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, HouseholdDayWrapper householdDay, int jHTSimulated, int genChoice, bool[,] jHTAvailable, bool[] fHTAvailable, int[][] altParticipants, int choice = Constants.DEFAULT_VALUE)
        {
            IEnumerable <PersonDayWrapper> orderedPersonDays = householdDay.PersonDays.OrderBy(p => p.GetJointHalfTourParticipationPriority()).ToList().Cast <PersonDayWrapper>();

            PersonDayWrapper pPersonDay = null;

            // set household characteristics here that don't depend on person characteristics

            int hhsize = householdDay.Household.Size;

            int hhinc1 = householdDay.Household.Income <= 300000 ? 1 : 0;
            int hhinc2 = (householdDay.Household.Income > 300000 && householdDay.Household.Income <= 600000) ? 1 : 0;
            int hhinc3 = (householdDay.Household.Income > 600000 && householdDay.Household.Income <= 900000) ? 1 : 0;
            //int hhinc4 = (householdDay.Household.Income > 900000 && householdDay.Household.Income <= 1200000) ? 1 : 0;
            int hhinc4 = (householdDay.Household.Income > 900000) ? 1 : 0;

            IParcelWrapper[] pUsualLocation = new IParcelWrapper[6];
            int[]            pPatternType   = new int[6];
            int[]            pConstant      = new int[6];

            int[] pType9 = new int[6];
            int[] pType8 = new int[6];
            int[] pType7 = new int[6];
            int[] pType6 = new int[6];
            int[] pType5 = new int[6];
            int[] pType4 = new int[6];
            int[] pType3 = new int[6];
            int[] pType2 = new int[6];
            int[] pType1 = new int[6];
            int[] pAdult = new int[6];
            int[] pAdultWithChildrenUnder16 = new int[6];
            int[] pAdultFemale       = new int[6];
            int[] pAdultNonMandatory = new int[6];
            int[] pType7AgeUnder12   = new int[6];
            int[] pType7Age12Plus    = new int[6];
            int[] pAgeUnder12        = new int[6];

            int[] pType8Mandatory    = new int[6];
            int[] pType8NonMandatory = new int[6];

            int[] pType7Mandatory    = new int[6];
            int[] pType7NonMandatory = new int[6];

            int[] pAgeUnder16        = new int[6];
            int[] pYouthMandatory    = new int[6];
            int[] pYouthNonMandatory = new int[6];
            int[] pYouth             = new int[6];
            int[] pAdultMandatory    = new int[6];
            int[] pMandatory         = new int[6];
            int[] pNonMandatory      = new int[6];

            bool[] pHasMandatoryTourToUsualLocation = new bool[6];
            bool[] pIsDrivingAge = new bool[6];

            int count = 0;

            foreach (PersonDayWrapper personDay in orderedPersonDays)
            {
                count++;
                if (count <= 5)
                {
                    if (count == 1)
                    {
                        pPersonDay = personDay;
                    }

                    // set characteristics here that depend on person characteristics
                    if (personDay.Person.IsFullOrPartTimeWorker)
                    {
                        pUsualLocation[count] = personDay.Person.UsualWorkParcel;
                    }
                    else if (personDay.Person.IsStudent)
                    {
                        pUsualLocation[count] = personDay.Person.UsualSchoolParcel;
                    }
                    else if (personDay.Person.IsWorker && personDay.Person.IsNotFullOrPartTimeWorker)
                    {
                        pUsualLocation[count] = personDay.Person.UsualWorkParcel;
                    }
                    else
                    {
                        pUsualLocation[count] = personDay.Household.ResidenceParcel;
                    }

                    pPatternType[count] = personDay.PatternType;
                    pConstant[count]    = 1;

                    pType9[count] = personDay.Person.IsChildUnder16.ToFlag(); // not one og Type 1 to 8

                    pType8[count] = personDay.Person.IsChildUnder5.ToFlag();  // All ACTUM TU persons are one of Type 1 to 8
                    pType7[count] = personDay.Person.IsChildAge5Through15.ToFlag();
                    pType6[count] = personDay.Person.IsDrivingAgeStudent.ToFlag();
                    pType5[count] = personDay.Person.IsUniversityStudent.ToFlag();
                    pType4[count] = personDay.Person.IsNonworkingAdult.ToFlag();
                    pType3[count] = personDay.Person.IsRetiredAdult.ToFlag();
                    pType2[count] = personDay.Person.IsPartTimeWorker.ToFlag();
                    pType1[count] = personDay.Person.IsFulltimeWorker.ToFlag();
                    pAdult[count] = personDay.Person.IsAdult.ToFlag();
                    pAdultWithChildrenUnder16[count] = (personDay.Person.IsAdult && personDay.Household.HasChildrenUnder16).ToFlag(); // THIS person is adult and HH has child. under 16
                    pAdultFemale[count]       = personDay.Person.IsAdultFemale.ToFlag();
                    pAdultNonMandatory[count] = (personDay.Person.IsAdult && personDay.PatternType == Global.Settings.PatternTypes.Optional).ToFlag();
                    pType7AgeUnder12[count]   = (personDay.Person.IsChildAge5Through15 && personDay.Person.Age < 12).ToFlag(); // THIS person is both 5-15 AND below 12
                    pType7Age12Plus[count]    = (personDay.Person.IsChildAge5Through15 && personDay.Person.Age >= 12).ToFlag();
                    pAgeUnder12[count]        = (personDay.Person.Age < 12).ToFlag();
                    pAgeUnder16[count]        = (personDay.Person.Age < 16).ToFlag();

                    pType8Mandatory[count]    = (personDay.Person.IsChildUnder5 && personDay.PatternType == Global.Settings.PatternTypes.Mandatory).ToFlag();
                    pType8NonMandatory[count] = (personDay.Person.IsChildUnder5 && personDay.PatternType == Global.Settings.PatternTypes.Optional).ToFlag();

                    pType7Mandatory[count]    = (personDay.Person.IsChildAge5Through15 && personDay.PatternType == Global.Settings.PatternTypes.Mandatory).ToFlag();
                    pType7NonMandatory[count] = (personDay.Person.IsChildAge5Through15 && personDay.PatternType == Global.Settings.PatternTypes.Optional).ToFlag();

                    pYouthMandatory[count]    = (!personDay.Person.IsChildUnder5 && !personDay.Person.IsAdult && personDay.PatternType == Global.Settings.PatternTypes.Mandatory).ToFlag();
                    pYouthNonMandatory[count] = (!personDay.Person.IsChildUnder5 && !personDay.Person.IsAdult && personDay.PatternType == Global.Settings.PatternTypes.Optional).ToFlag();
                    pYouth[count]             = (!personDay.Person.IsChildUnder5 && !personDay.Person.IsAdult).ToFlag();

                    pAdultMandatory[count] = (personDay.Person.IsAdult && personDay.PatternType == Global.Settings.PatternTypes.Mandatory).ToFlag();

                    pMandatory[count]    = (personDay.PatternType == Global.Settings.PatternTypes.Mandatory).ToFlag();
                    pNonMandatory[count] = (personDay.PatternType == Global.Settings.PatternTypes.Optional).ToFlag();

                    pHasMandatoryTourToUsualLocation[count] = personDay.HasMandatoryTourToUsualLocation;
                    pIsDrivingAge[count] = personDay.Person.IsDrivingAge;
                }
            }

            int componentIndex = 0;

            //Create person utility components
            int[] componentPerson = new int[6];
            for (int p = 1; p <= 5; p++)
            {
                // create component for basic person-purposes
                componentIndex++;
                componentPerson[p] = componentIndex;
                choiceProbabilityCalculator.CreateUtilityComponent(componentPerson[p]);
                // these are dummies compared to base one, i.e. Type 5+6 in one.
                // OBS! - We apply "Adult Mandatory" as the base
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(1, pAdultMandatory[p]); // impact of adult with mandatory travel
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(2, pAdultNonMandatory[p]); // impact of adult with non-mandatory travel

                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(3, pType8Mandatory[p]);    // impact of child under 5 with mandatory travel
                                                                                                                              //GV: not significant, 14. june 2016
                                                                                                                              //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(4, pType8NonMandatory[p]); // impact of child under 5 with non-mandatory travel

                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(04, pYouthMandatory[p]); // impact of youth with mandatory travel
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(05, pYouthNonMandatory[p]); // impact of youth with non-mandatory travel
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(5, pType7Mandatory[p]); // impact of Child5-16 with mandatory travel

                //GV: not significant, 14. june 2016
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(6, pType7NonMandatory[p]); // impact of Child5-16 with non-mandatory travel

                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(7, pAdultFemale[p]); //female
            }

            //create two-way match interaction utility components
            int[,] componentMatch   = new int[6, 6];
            int[,] iMatchAgeUnder12 = new int[6, 6];
            int[,] iMatchAgeUnder16 = new int[6, 6];
            int[,] iMatchAgeUnder5  = new int[6, 6];
            int[,] iMatchAge5to16   = new int[6, 6];

            int[,] iMatchAdult = new int[6, 6];
            int[,] iMatchAdultWithChildrenUnder16 = new int[6, 6];
            int[,] iMatchAdultWithChildrenUnder5  = new int[6, 6];

            int[,] iMatchAdultMandatory    = new int[6, 6];
            int[,] iMatchAdultNonMandatory = new int[6, 6];

            int[,] iMatchMandatory    = new int[6, 6];
            int[,] iMatchNonMandatory = new int[6, 6];

            int[,] iMatchAdultMandatoryAndAdultMandatory       = new int[6, 6];
            int[,] iMatchAdultNonMandatoryAndAdultNonMandatory = new int[6, 6];

            for (int t2 = 1; t2 <= 5; t2++)
            {
                for (int t1 = 1; t1 < t2; t1++)
                {
                    // iMatch joints only persons of the same type
                    // lets the base alt, be adult*adult

                    iMatchAgeUnder12[t1, t2] = pAgeUnder12[t1] * pAgeUnder12[t2];                      // children under 12
                    iMatchAgeUnder16[t1, t2] = pAgeUnder16[t1] * pAgeUnder16[t2];                      // children under 16

                    iMatchAgeUnder5[t1, t2] = pType8[t1] * pType8[t2];                                 // children under 5
                    iMatchAge5to16[t1, t2]  = pType7[t1] * pType7[t2];                                 // children 5 to 16

                    iMatchAdult[t1, t2] = pAdult[t1] * pAdult[t2];                                     // two adults (very important but difficult to understand)

                    iMatchAdultMandatory[t1, t2]    = pAdultMandatory[t1] * pAdultMandatory[t2];       // two adults with mandatory travel
                    iMatchAdultNonMandatory[t1, t2] = pAdultNonMandatory[t1] * pAdultNonMandatory[t2]; // two adults with non-mandatory travel

                    iMatchMandatory[t1, t2]    = pMandatory[t1] * pMandatory[t2];                      //those with mandatory
                    iMatchNonMandatory[t1, t2] = pNonMandatory[t1] * pNonMandatory[t2];                //those tith non-mandatory

                    //iMatchAdultWithChildrenUnder16[t1, t2] = pAdultWithChildrenUnder16[t1] * pAdultWithChildrenUnder16[t2];

                    iMatchAdultWithChildrenUnder16[t1, t2] = pAdult[t1] * pType7[t2];                                      //adult plus child 5-16
                    iMatchAdultWithChildrenUnder5[t1, t2]  = pAdult[t1] * pType8[t2];                                      //adult plus child5

                    iMatchAdultMandatoryAndAdultMandatory[t1, t2]       = pAdultMandatory[t1] * pAdultMandatory[t2];       //2 adults with Mandatory
                    iMatchAdultNonMandatoryAndAdultNonMandatory[t1, t2] = pAdultNonMandatory[t1] * pAdultNonMandatory[t2]; //2 adults with Mandatory


                    //create and populate components
                    // OBS! - We apply "Adult * Adult" as the base
                    componentIndex++;
                    componentMatch[t1, t2] = componentIndex;
                    choiceProbabilityCalculator.CreateUtilityComponent(componentMatch[t1, t2]);
                    choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(21, iMatchAgeUnder5[t1, t2]);

                    //GV: 14. jine 2016, not sign.
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(22, iMatchAge5to16[t1, t2]);

                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(23, iMatchAdultMandatoryAndAdultMandatory[t1, t2]);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(24, iMatchAdultNonMandatoryAndAdultNonMandatory[t1, t2]);

                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(23, iMatchAdult[t1, t2]);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(24, iMatchAdultMandatory[t1, t2]);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(25, iMatchAdultNonMandatory[t1, t2]);

                    // commented out 22nd, but they work well
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(26, iMatchMandatory[t1, t2]);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(27, iMatchNonMandatory[t1, t2]);
                }
            }

            //create two-way cross interaction utility components

            int[,] componentCross = new int[6, 6];
            int[,] iCrossAgeUnderTwelveAndAdult             = new int[6, 6];
            int[,] iCrossAgeUnderTwelveAndAdultNonMandatory = new int[6, 6];
            int[,] iCrossAdultWithChildUnder5 = new int[6, 6];
            int[,] iCrossAdultWithChild5to16  = new int[6, 6];

            int[,] iCrossAdultFemaleWithChildUnder5 = new int[6, 6];
            int[,] iCrossAdultFemaleWithChild5to16  = new int[6, 6];

            int[,] iCrossAdultMandatoryAndAdultNonMandatory    = new int[6, 6];
            int[,] iCrossAdultMandatoryAndAdultMandatory       = new int[6, 6];
            int[,] iCrossAdultNonMandatoryAndAdultNonMandatory = new int[6, 6];

            int[,] iCrossYouthAndChildUnder5      = new int[6, 6];
            int[,] iCrossChild5to16AndChildUnder5 = new int[6, 6];

            for (int t2 = 1; t2 <= 5; t2++)
            {
                for (int t1 = 1; t1 <= 5; t1++)
                {
                    if (!(t1 == t2))
                    {
                        //populate cross variables
                        // again, one is base, all others are dummies

                        iCrossAdultWithChildUnder5[t1, t2] = pAdult[t1] * pType8[t2];             //adult plus child5
                        iCrossAdultWithChild5to16[t1, t2]  = pAdult[t1] * pType7[t2];             //adult plus child 5-16

                        iCrossAdultFemaleWithChildUnder5[t1, t2] = pAdultFemale[t1] * pType8[t2]; //adult mom plus child5
                        iCrossAdultFemaleWithChild5to16[t1, t2]  = pAdult[t1] * pType7[t2];       //adult mom plus child 5-16


                        iCrossAgeUnderTwelveAndAdult[t1, t2]             = pAgeUnder12[t1] * pAdult[t2];
                        iCrossAgeUnderTwelveAndAdultNonMandatory[t1, t2] = pAgeUnder12[t1] * pAdultNonMandatory[t2];

                        iCrossAdultMandatoryAndAdultNonMandatory[t1, t2]    = pAdultMandatory[t1] * pAdultNonMandatory[t2];
                        iCrossAdultMandatoryAndAdultMandatory[t1, t2]       = pAdultMandatory[t1] * pAdultMandatory[t2];
                        iCrossAdultNonMandatoryAndAdultNonMandatory[t1, t2] = pAdultNonMandatory[t1] * pAdultNonMandatory[t2];

                        iCrossYouthAndChildUnder5[t1, t2]      = pYouth[t1] * pType8[t2];
                        iCrossChild5to16AndChildUnder5[t1, t2] = pType7[t1] * pType8[t2];

                        //create and populate cross components
                        // OBS! - We apply "Adult Mandatory * Adult Non-mandatory" as the base
                        componentIndex++;
                        componentCross[t1, t2] = componentIndex;
                        choiceProbabilityCalculator.CreateUtilityComponent(componentCross[t1, t2]);

                        choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(41, iCrossAdultWithChildUnder5[t1, t2]);
                        choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(42, iCrossAdultWithChild5to16[t1, t2]);

                        //choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(43, iCrossAdultMandatoryAndAdultNonMandatory[t1, t2]);

                        //GV: 14. june 2016, not sign.
                        //choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(46, iCrossAdultFemaleWithChildUnder5[t1, t2]);

                        //choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(47, iCrossYouthAndChildUnder5[t1, t2]);
                        choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(47, iCrossChild5to16AndChildUnder5[t1, t2]);

                        //choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(45, iCrossAdultFemaleWithChild5to16[t1, t2]);

                        //choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(41, iCrossAgeUnderTwelveAndAdult[t1, t2]);
                        //choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(42, iCrossAgeUnderTwelveAndAdultNonMandatory[t1, t2]);
                    }
                }
            }

            //Generate utility funtions for the alternatives
            bool[] available = new bool[32];
            bool[] chosen    = new bool[32];

            bool[] threeParticipants    = new bool[32];
            bool[] fourPlusParticipants = new bool[32];

            for (int alt = 0; alt < 32; alt++)
            {
                available[alt] = false;
                chosen[alt]    = false;
                // set availability based on household size
                if (hhsize >= altParticipants[alt][6])
                {
                    available[alt] = true;
                }
                // restrict availability based on person unavailability
                for (int i = 1; i <= 5; i++)
                {
                    if (altParticipants[alt][i] == 1 && (jHTAvailable[genChoice - 1, i] == false || fHTAvailable[i] == false))
                    {
                        available[alt] = false;
                    }
                }
                // restrict availability to cases where all non-adult participants have same usual location
                // first determine first non-adult's usual location
                IParcelWrapper sameUsualLocation = householdDay.Household.ResidenceParcel;
                for (int i = 1; i <= 5; i++)
                {
                    if (altParticipants[alt][i] == 1 && pPatternType[i] == 1 && pUsualLocation[i] != null && pUsualLocation[i].Id > 0 && !(pAdult[i] == 1))
                    {
                        sameUsualLocation = pUsualLocation[i];
                        break;
                    }
                }

                // then make alt unavailable if any M-Usual participant has a different usualLocation
                for (int i = 1; i <= 5; i++)
                {
                    if (altParticipants[alt][i] == 1 && pHasMandatoryTourToUsualLocation[i] && !(pUsualLocation[i] == sameUsualLocation) && !(pAdult[i] == 1))
                    {
                        available[alt] = false;
                        break;
                    }
                }

                // restrict availability of alts that include less than 2 participants
                if (altParticipants[alt][7] < 2)
                {
                    available[alt] = false;
                }

                // restrict availability if 2+ participants lack tour to usual location
                int numberLackMandatoryTourToUsualLocation = 0;
                for (int i = 1; i <= 5; i++)
                {
                    if (altParticipants[alt][i] == 1 && !pHasMandatoryTourToUsualLocation[i])
                    {
                        numberLackMandatoryTourToUsualLocation++;
                    }
                }
                if (numberLackMandatoryTourToUsualLocation > 1)
                {
                    available[alt] = false;
                }

                // require at least one driving age (as chauffeur) //GV:out july 2013
                //int numberDrivingAge = 0;
                //for (int i = 1; i <= 5; i++) {
                //	if (altParticipants[alt][i] == 1 && pIsDrivingAge[i]) {
                //		numberDrivingAge++;
                //	}
                //}
                //if (numberDrivingAge == 0) {
                //	available[alt] = false;
                //}


                double tourLogsum;
                int    destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                int    destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
                //var nestedAlternative = ActumWorkTourModeModel.RunNested(pPersonDay, pPersonDay.Household.ResidenceParcel, sameUsualLocation, destinationArrivalTime, destinationDepartureTime, pPersonDay.Household.VehiclesAvailable);
                //var nestedAlternative = (Global.ChoiceModelDictionary.Get("ActumWorkTourModeModel") as ActumWorkTourModeModel).RunNested(personDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);
                //JLB 201406
                //var nestedAlternative = Global.ChoiceModelSession.Get<WorkTourModeModel>().RunNested(pPersonDay, pPersonDay.Household.ResidenceParcel, sameUsualLocation, destinationArrivalTime, destinationDepartureTime, pPersonDay.Household.VehiclesAvailable);
                //JLB 201602
                //var nestedAlternative = Global.ChoiceModelSession.Get<WorkTourModeTimeModel>().RunNested(pPersonDay, pPersonDay.Household.ResidenceParcel, sameUsualLocation, destinationArrivalTime, destinationDepartureTime, pPersonDay.Household.VehiclesAvailable);
                ChoiceProbabilityCalculator.Alternative nestedAlternative = Global.ChoiceModelSession.Get <TourModeTimeModel>().RunNested(pPersonDay, pPersonDay.Household.ResidenceParcel, sameUsualLocation, destinationArrivalTime, destinationDepartureTime, pPersonDay.Household.VehiclesAvailable, Global.Settings.Purposes.Work);
                tourLogsum = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();


                // determine choice
                if (choice == alt)
                {
                    chosen[alt] = true;
                }

                //Get the alternative
                ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(alt, available[alt], chosen[alt]);

                alternative.Choice = alt;

                //Add utility terms that are not in components
                //alternative.AddUtilityTerm(399, 0);

                // OBS!!! This is new - 21nd January 2013 - it sais that these tris are less expected to be done with 3 or 4+ persons (compared to to people)
                alternative.AddUtilityTerm(59, altParticipants[alt][7] >= 3 ? 1 : 0);
                //alternative.AddUtilityTerm(60, altParticipants[alt][7] >= 4 ? 1 : 0); // OBS! no observations with 4+ HHsize
                alternative.AddUtilityTerm(58, tourLogsum);
                //Add utility components

                for (int p = 1; p <= 5; p++)
                {
                    if (altParticipants[alt][p] == 1)
                    {
                        alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]));
                    }
                }
                for (int t2 = 1; t2 <= 5; t2++)
                {
                    for (int t1 = 1; t1 < t2; t1++)
                    {
                        if (altParticipants[alt][t1] == 1 && altParticipants[alt][t2] == 1)
                        {
                            alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]));
                        }
                    }
                }
                for (int t2 = 1; t2 <= 5; t2++)
                {
                    for (int t1 = 1; t1 <= 5; t1++)
                    {
                        if (!(t1 == t2))
                        {
                            if (altParticipants[alt][t1] == 1 && altParticipants[alt][t2] == 1)
                            {
                                alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]));
                            }
                        }
                    }
                }
            }
        }
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, PersonDayWrapper personDay, HouseholdDayWrapper householdDay, DayPattern[] dayPatterns, DayPattern choice = null)
        {
            var household       = personDay.Household;
            var residenceParcel = household.ResidenceParcel;
            var person          = personDay.Person;

            var carsPerDriver       = household.GetCarsPerDriver();
            var mixedDensity        = residenceParcel.MixedUse3Index2();
            var intersectionDensity = residenceParcel.IntersectionDensity34Minus1Buffer2();

            var purposeLogsums = new double[Global.Settings.Purposes.TotalPurposes + 2];
            var atUsualLogsums = new double[3];
            //var carOwnership = person.CarOwnershipSegment; //GV: sat car ownership not to impact logsums
            var carOwnership  = 0;
            var votSegment    = person.Household.GetVotALSegment();
            var transitAccess = residenceParcel.TransitAccessSegment();

            //GV: input 26. july 2013
            // household inputs
            //var childrenUnder5 = householdTotals.ChildrenUnder5;
            //var childrenAge5Through15 = householdTotals.ChildrenAge5Through15;
            //var nonworkingAdults = householdTotals.NonworkingAdults;
            //var retiredAdults = householdTotals.RetiredAdults;

            var onePersonHouseholdFlag = household.IsOnePersonHousehold.ToFlag();
            var twoPersonHouseholdFlag = household.IsTwoPersonHousehold.ToFlag();

            var householdCars = household.VehiclesAvailable;
            //var noCarsInHouseholdFlag = HouseholdWrapper.GetNoCarsInHouseholdFlag(householdCars);
            //var carsLessThanDriversFlag = household.GetCarsLessThanDriversFlag(householdCars);
            //var carsLessThanWorkersFlag = household.GetCarsLessThanWorkersFlag(householdCars);

            var HHwithChildrenFlag      = household.HasChildren.ToFlag();
            var HHwithSmallChildrenFlag = household.HasChildrenUnder5.ToFlag();
            var HHwithLowIncomeFlag     = (household.Income >= 300000 && household.Income < 600000).ToFlag();
            var HHwithMidleIncomeFlag   = (household.Income >= 600000 && household.Income < 900000).ToFlag();
            var HHwithHighIncomeFlag    = (household.Income >= 900000).ToFlag();

            var primaryFamilyTimeFlag = householdDay.PrimaryPriorityTimeFlag;

            //GV: input 26. july 2013
            // person inputs
            var partTimeWorkerFlag     = person.IsPartTimeWorker.ToFlag();
            var nonworkingAdultFlag    = person.IsNonworkingAdult.ToFlag();
            var universityStudentFlag  = person.IsUniversityStudent.ToFlag();
            var retiredAdultFlag       = person.IsRetiredAdult.ToFlag();
            var fullTimeWorkerFlag     = person.IsFulltimeWorker.ToFlag();
            var childAge5Through15Flag = person.IsChildAge5Through15.ToFlag();
            var childUnder5Flag        = person.IsChildUnder5.ToFlag();
            var adultFlag = person.IsAdult.ToFlag();

            var maleFlag   = person.IsMale.ToFlag();
            var femaleFlag = person.IsFemale.ToFlag();



            if (person.UsualWorkParcel == null || person.UsualWorkParcelId == household.ResidenceParcelId)
            {
                purposeLogsums[Global.Settings.Purposes.Work] = 0;
            }
            else
            {
                var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
                //JLB 201406
                //var nestedAlternative = Global.ChoiceModelSession.Get<WorkTourModeModel>().RunNested(personDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);
                var nestedAlternative = Global.ChoiceModelSession.Get <WorkTourModeTimeModel>().RunNested(personDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);

                purposeLogsums[Global.Settings.Purposes.Work] = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
                atUsualLogsums[Global.Settings.Purposes.Work] = Global.AggregateLogsums[person.UsualWorkParcel.ZoneId][Global.Settings.Purposes.HomeBasedComposite][carOwnership][votSegment][person.UsualWorkParcel.TransitAccessSegment()];
            }

            if (person.UsualSchoolParcel == null || person.UsualSchoolParcelId == household.ResidenceParcelId)
            {
                purposeLogsums[Global.Settings.Purposes.School] = 0;
            }
            else
            {
                var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
                var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);
                //JLB 201406
                //var nestedAlternative = Global.ChoiceModelSession.Get<SchoolTourModeModel>().RunNested(personDay, residenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);
                var nestedAlternative = Global.ChoiceModelSession.Get <SchoolTourModeTimeModel>().RunNested(personDay, residenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);

                purposeLogsums[Global.Settings.Purposes.School] = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
                atUsualLogsums[Global.Settings.Purposes.School] = Global.AggregateLogsums[person.UsualSchoolParcel.ZoneId][Global.Settings.Purposes.HomeBasedComposite][carOwnership][votSegment][person.UsualSchoolParcel.TransitAccessSegment()];
            }

            var compositeLogsum = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][carOwnership][votSegment][transitAccess];

            purposeLogsums[Global.Settings.Purposes.Escort]           = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.Escort][carOwnership][votSegment][transitAccess];
            purposeLogsums[Global.Settings.Purposes.PersonalBusiness] = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.PersonalBusiness][carOwnership][votSegment][transitAccess];
            purposeLogsums[Global.Settings.Purposes.Shopping]         = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.Shopping][carOwnership][votSegment][transitAccess];
            purposeLogsums[Global.Settings.Purposes.Social]           = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.Social][carOwnership][votSegment][transitAccess];

            for (var xPurpose = Global.Settings.Purposes.Escort; xPurpose <= Global.Settings.Purposes.Social + 10; xPurpose++)
            {
                // extra components 1-5 are for 2,3,4,5,6 tour purposes
                // extra components 6-10 are for 2,3,4,5,6 stop puroposes

                // recode purpose to match coefficients
                var purpose = xPurpose <= Global.Settings.Purposes.Social ? xPurpose :
                              xPurpose <= Global.Settings.Purposes.Social + 5 ? Global.Settings.Purposes.Social + 1 :
                              Global.Settings.Purposes.Social + 2;

                // get correct multiplier on coefficients.
                var xMultiplier = xPurpose <= Global.Settings.Purposes.Social ? 1.0 :
                                  xPurpose <= Global.Settings.Purposes.Social + 5 ? Math.Log(xPurpose - Global.Settings.Purposes.Social + 1) :
                                  Math.Log(xPurpose - Global.Settings.Purposes.Social - 5 + 1);

                choiceProbabilityCalculator.CreateUtilityComponent(xPurpose);
                var component = choiceProbabilityCalculator.GetUtilityComponent(xPurpose);

                component.AddUtilityTerm(100 * purpose + 1, xMultiplier * person.IsFulltimeWorker.ToFlag());
                component.AddUtilityTerm(100 * purpose + 2, xMultiplier * person.IsPartTimeWorker.ToFlag());
                component.AddUtilityTerm(100 * purpose + 3, xMultiplier * person.IsRetiredAdult.ToFlag());
                component.AddUtilityTerm(100 * purpose + 4, xMultiplier * person.IsNonworkingAdult.ToFlag());
                component.AddUtilityTerm(100 * purpose + 5, xMultiplier * person.IsUniversityStudent.ToFlag());
                component.AddUtilityTerm(100 * purpose + 6, xMultiplier * person.IsDrivingAgeStudent.ToFlag());
                component.AddUtilityTerm(100 * purpose + 7, xMultiplier * person.IsChildAge5Through15.ToFlag());
                component.AddUtilityTerm(100 * purpose + 8, xMultiplier * person.IsChildUnder5.ToFlag());

                component.AddUtilityTerm(100 * purpose + 9, xMultiplier * HHwithLowIncomeFlag);
                component.AddUtilityTerm(100 * purpose + 10, xMultiplier * HHwithMidleIncomeFlag);
                component.AddUtilityTerm(100 * purpose + 11, xMultiplier * HHwithHighIncomeFlag);

                //component.AddUtilityTerm(100 * purpose + 12, xMultiplier * carsPerDriver);
                component.AddUtilityTerm(100 * purpose + 12, xMultiplier * householdCars);

                component.AddUtilityTerm(100 * purpose + 13, xMultiplier * person.IsOnlyAdult().ToFlag());
                component.AddUtilityTerm(100 * purpose + 14, xMultiplier * person.IsOnlyFullOrPartTimeWorker().ToFlag());
                component.AddUtilityTerm(100 * purpose + 15, xMultiplier * 0);
                component.AddUtilityTerm(100 * purpose + 16, xMultiplier * person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * (!household.HasChildrenUnder16).ToFlag());
                component.AddUtilityTerm(100 * purpose + 17, xMultiplier * person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenUnder5.ToFlag());
                component.AddUtilityTerm(100 * purpose + 18, xMultiplier * person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenAge5Through15.ToFlag());
                component.AddUtilityTerm(100 * purpose + 19, xMultiplier * person.IsMale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenUnder5.ToFlag());
                component.AddUtilityTerm(100 * purpose + 20, xMultiplier * person.IsMale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenAge5Through15.ToFlag());

                //component.AddUtilityTerm(100 * purpose + 21, xMultiplier * primaryFamilyTimeFlag); //GV: wrong sign

                //component.AddUtilityTerm(100 * purpose + 21, xMultiplier * person.AgeIsBetween18And25.ToFlag());
                //component.AddUtilityTerm(100 * purpose + 22, xMultiplier * person.AgeIsBetween26And35.ToFlag());
                //component.AddUtilityTerm(100 * purpose + 23, xMultiplier * person.AgeIsBetween51And65.ToFlag());

                component.AddUtilityTerm(100 * purpose + 24, xMultiplier * person.WorksAtHome.ToFlag());
                component.AddUtilityTerm(100 * purpose + 25, xMultiplier * mixedDensity);
                component.AddUtilityTerm(100 * purpose + 26, xMultiplier * intersectionDensity);
                //component.AddUtilityTerm(100 * purpose + 27, xMultiplier * purposeLogsums[purpose]); //GV: 17.08.2013, the logsums are wrong
                //component.AddUtilityTerm(100 * purpose + 28, xMultiplier * person.TransitPassOwnershipFlag);
            }

            // tour utility
            const int tourComponentIndex = 18;

            choiceProbabilityCalculator.CreateUtilityComponent(tourComponentIndex);
            var tourComponent = choiceProbabilityCalculator.GetUtilityComponent(tourComponentIndex);

            //tourComponent.AddUtilityTerm(1701, carsPerDriver);
            tourComponent.AddUtilityTerm(1701, householdCars);

            tourComponent.AddUtilityTerm(1702, person.WorksAtHome.ToFlag());
            tourComponent.AddUtilityTerm(1703, mixedDensity);
            tourComponent.AddUtilityTerm(1704, mixedDensity * person.IsChildAge5Through15.ToFlag());
            tourComponent.AddUtilityTerm(1705, compositeLogsum);

            //tourComponent.AddUtilityTerm(1706, person.TransitPassOwnershipFlag);
            tourComponent.AddUtilityTerm(1706, primaryFamilyTimeFlag);

            // stop utility
            const int stopComponentIndex = 19;

            choiceProbabilityCalculator.CreateUtilityComponent(stopComponentIndex);
            var stopComponent = choiceProbabilityCalculator.GetUtilityComponent(stopComponentIndex);

            //stopComponent.AddUtilityTerm(1711, carsPerDriver);
            stopComponent.AddUtilityTerm(1711, householdCars);

            stopComponent.AddUtilityTerm(1712, person.WorksAtHome.ToFlag());
            stopComponent.AddUtilityTerm(1713, mixedDensity);
            stopComponent.AddUtilityTerm(1714, mixedDensity * person.IsChildAge5Through15.ToFlag());
            stopComponent.AddUtilityTerm(1715, compositeLogsum);

            //stopComponent.AddUtilityTerm(1716, person.TransitPassOwnershipFlag);
            //stopComponent.AddUtilityTerm(1716, primaryFamilyTimeFlag); //GV: 17.08.2013, the logsums are wrong

            for (var alternativeIndex = 0; alternativeIndex < TOTAL_ALTERNATIVES; alternativeIndex++)
            {
                var dayPattern  = dayPatterns[alternativeIndex];
                var available   = dayPattern.Available;
                var alternative = choiceProbabilityCalculator.GetAlternative(alternativeIndex, available, choice != null && choice.Equals(dayPattern));

                if (!Global.Configuration.IsInEstimationMode && !alternative.Available)
                {
                    continue;
                }

                alternative.Choice = dayPattern;

                // components for the purposes
                for (var purpose = Global.Settings.Purposes.Escort; purpose <= Global.Settings.Purposes.Social; purpose++)
                {
                    if (dayPattern.Tours[purpose] > 0 || dayPattern.Stops[purpose] > 0)
                    {
                        alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(purpose));

                        if (dayPattern.Tours[purpose] > 0)
                        {
                            alternative.AddUtilityTerm(100 * purpose + 50, 1); // tour purpose ASC
                                                                               //alternative.AddUtilityTerm(100 * purpose + 51, purposeLogsums[purpose]); // tour purpose logsum GV: 17.08.2013, the logsums are wrong
                        }

                        if (dayPattern.Stops[purpose] > 0)
                        {
                            alternative.AddUtilityTerm(100 * purpose + 60, 1); // stop purpose ASC
                                                                               //alternative.AddUtilityTerm(100 * purpose + 61, purposeLogsums[purpose]); // stop purpose logsum GV: 17.08.2013, the logsums are wrong
                        }
                        if (Global.Configuration.IsInEstimationMode)
                        {
                            //GV commented out
                            //alternative.AddUtilityTerm(100 * purpose + 70, 1 - person.PaperDiary);
                            //GV commented out
                            //alternative.AddUtilityTerm(100 * purpose + 71, person.ProxyResponse);
                        }
                    }
                }

                // multiple tour purposes component
                if (dayPattern.TotalTourPurposes > 1)
                {
                    alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(Global.Settings.Purposes.Social + (dayPattern.TotalTourPurposes - 1)));
                }

                // multiple stop purposes component
                if (dayPattern.TotalStopPurposes > 1)
                {
                    alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(Global.Settings.Purposes.Social + 5 + (dayPattern.TotalStopPurposes - 1)));
                }

                for (var tourPurpose = Global.Settings.Purposes.Work; tourPurpose <= Global.Settings.Purposes.Social; tourPurpose++)
                {
                    for (var stopPurpose = Global.Settings.Purposes.Work; stopPurpose <= Global.Settings.Purposes.Social - 1; stopPurpose++)
                    {
                        if (tourPurpose > Global.Settings.Purposes.School && stopPurpose <= Global.Settings.Purposes.School)
                        {
                            continue;
                        }

                        if (dayPattern.Tours[tourPurpose] > 0 && dayPattern.Stops[stopPurpose] > 0)
                        {
                            alternative.AddUtilityTerm(1200 + 10 * tourPurpose + stopPurpose, 1); // tour-stop comb. utility
                        }
                    }
                }

                for (var tourPurpose = Global.Settings.Purposes.Work; tourPurpose <= Global.Settings.Purposes.School; tourPurpose++)
                {
                    if (dayPattern.Tours[tourPurpose] == 1 && dayPattern.TotalStopPurposes >= 1)
                    {
                        alternative.AddUtilityTerm(1300 + 10 * tourPurpose, purposeLogsums[tourPurpose]); // usual location logsum x presence of stops in work or school pattern
                        alternative.AddUtilityTerm(1300 + 10 * tourPurpose + 1, compositeLogsum);         // home aggregate logsum x  presence of stops in work or school pattern
                                                                                                          //alternative.AddUtilityTerm(1300 + 10 * tourPurpose + 2, atUsualLogsums[tourPurpose]); // at usual location aggregate logsum x  presence of stops in work or school pattern GV: commented out as the sign is wrong
                    }
                }

                for (var tourPurpose = Global.Settings.Purposes.Work; tourPurpose <= Global.Settings.Purposes.Social - 2; tourPurpose++)
                {
                    for (var tourPurpose2 = tourPurpose + 1; tourPurpose2 <= Global.Settings.Purposes.Social; tourPurpose2++)
                    {
                        if (dayPattern.Tours[tourPurpose] > 0 && dayPattern.Tours[tourPurpose2] > 0)
                        {
                            alternative.AddUtilityTerm(1400 + 10 * tourPurpose + tourPurpose2, 1); // tour-tour comb. utility
                        }
                    }
                }

                for (var tourPurpose = Global.Settings.Purposes.Business; tourPurpose <= Global.Settings.Purposes.Business; tourPurpose++)
                {
                    for (var tourPurpose2 = Global.Settings.Purposes.Escort; tourPurpose2 <= Global.Settings.Purposes.Social; tourPurpose2++)
                    {
                        if (dayPattern.Tours[tourPurpose] > 0 && dayPattern.Tours[tourPurpose2] > 0)
                        {
                            alternative.AddUtilityTerm(1461, 1); // tour-tour comb. utility for business combos
                        }
                    }
                }

                for (var stopPurpose = Global.Settings.Purposes.Work; stopPurpose <= Global.Settings.Purposes.Social - 2; stopPurpose++)
                {
                    for (var stopPurpose2 = stopPurpose + 1; stopPurpose2 <= Global.Settings.Purposes.Social; stopPurpose2++)
                    {
                        if (dayPattern.Stops[stopPurpose] > 0 && dayPattern.Stops[stopPurpose2] > 0)
                        {
                            alternative.AddUtilityTerm(1500 + 10 * stopPurpose + stopPurpose2, 1); // stop-stop comb. utility
                        }
                    }
                }

                if (dayPattern.TotalTourPurposes > 0 && dayPattern.TotalStopPurposes > 0)
                {
                    var totalStopPurposes = dayPattern.TotalStopPurposes;

                    if (totalStopPurposes > 3)
                    {
                        totalStopPurposes = 3;
                    }

                    alternative.AddUtilityTerm(1600 + 10 * dayPattern.TotalTourPurposes + totalStopPurposes, 1); // nttour-ntstop utility
                }
                if (dayPattern.TotalTourPurposes - dayPattern.Tours[Global.Settings.Purposes.Work]
                    - dayPattern.Tours[Global.Settings.Purposes.Business]
                    - dayPattern.Tours[Global.Settings.Purposes.School] > 0)
                {
                    // tour utility
                    alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(tourComponentIndex));
                }
                if (dayPattern.TotalStopPurposes - dayPattern.Stops[Global.Settings.Purposes.Work]
                    - dayPattern.Stops[Global.Settings.Purposes.Business]
                    - dayPattern.Stops[Global.Settings.Purposes.School] > 0)
                {
                    // stop utility
                    alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(stopComponentIndex));
                }
            }
        }
Exemple #12
0
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, PersonDayWrapper personDay, HouseholdDayWrapper householdDay, int maxPurpose, int choice = Constants.DEFAULT_VALUE)
        {
            IEnumerable <PersonDayWrapper> orderedPersonDays = householdDay.PersonDays.OrderBy(p => p.GetJointTourParticipationPriority()).ToList().Cast <PersonDayWrapper>();

            var household       = householdDay.Household;
            var residenceParcel = household.ResidenceParcel;

            var carOwnership =
                household.VehiclesAvailable == 0
                                                                 ? Global.Settings.CarOwnerships.NoCars
                                                                 : household.VehiclesAvailable < household.HouseholdTotals.DrivingAgeMembers
                                                                          ? Global.Settings.CarOwnerships.LtOneCarPerAdult
                                                                          : Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult;

            var noCarsFlag         = FlagUtility.GetNoCarsFlag(carOwnership);
            var carCompetitionFlag = FlagUtility.GetCarCompetitionFlag(carOwnership);

            var votALSegment                    = household.GetVotALSegment();
            var transitAccessSegment            = household.ResidenceParcel.TransitAccessSegment();
            var personalBusinessAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                                  [Global.Settings.Purposes.PersonalBusiness][carOwnership][votALSegment][transitAccessSegment];
            var shoppingAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                          [Global.Settings.Purposes.Shopping][Global.Settings.CarOwnerships.NoCars][votALSegment][transitAccessSegment];
            //var mealAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
            //	 [Global.Settings.Purposes.Meal][carOwnership][votALSegment][transitAccessSegment];
            var socialAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                        [Global.Settings.Purposes.Social][carOwnership][votALSegment][transitAccessSegment];
            var totalAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                       [Global.Settings.Purposes.HomeBasedComposite][carOwnership][votALSegment][transitAccessSegment];
            // var recreationAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
            // [Global.Settings.Purposes.Recreation][carOwnership][votALSegment][transitAccessSegment];
            //  var medicalAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
            //  [Global.Settings.Purposes.Medical][carOwnership][votALSegment][transitAccessSegment];
            //var compositeLogsum = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][carOwnership][votALSegment][transitAccessSegment];
            var compositeLogsum = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votALSegment][transitAccessSegment];


            int countNonMandatory  = 0;
            int countMandatory     = 0;
            int countWorkingAtHome = 0;


            double totalTimeWork = 0;


            int[] mandPerstype    = new int[8];
            int[] nonMandPerstype = new int[8];

            double[] workLogsum   = new double[8];
            double[] schoolLogsum = new double[8];
            int      count        = 0;

            foreach (PersonDayWrapper pDay in orderedPersonDays)
            {
                var person = pDay.Person;
                count++;
                if (count > 8)
                {
                    break;
                }
                if (pDay.WorksAtHomeFlag == 1)
                {
                    countWorkingAtHome++;
                }
                if (pDay.PatternType == 1)
                {
                    countMandatory++;
                    mandPerstype[pDay.Person.PersonType - 1]++;
                }
                if (pDay.PatternType == 2)
                {
                    countNonMandatory++;
                    nonMandPerstype[pDay.Person.PersonType - 1]++;
                }

                if (person.UsualWorkParcel == null || person.UsualWorkParcelId == household.ResidenceParcelId)
                {
                    workLogsum[count - 1] = 0;
                }
                else
                {
                    var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                    var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
                    //JLB 201406
                    //var nestedAlternative = Global.ChoiceModelSession.Get<WorkTourModeModel>().RunNested(pDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);
                    //JLB 201602
                    //var nestedAlternative = Global.ChoiceModelSession.Get<WorkTourModeTimeModel>().RunNested(pDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);
                    var nestedAlternative = Global.ChoiceModelSession.Get <TourModeTimeModel>().RunNested(pDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, Global.Settings.Purposes.Work);

                    workLogsum[count - 1] = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
                }

                if (person.UsualSchoolParcel == null || person.UsualSchoolParcelId == household.ResidenceParcelId)
                {
                    schoolLogsum[count - 1] = 0;
                }
                else
                {
                    var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
                    var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);
                    //JLB 201406
                    //var nestedAlternative = Global.ChoiceModelSession.Get<SchoolTourModeModel>().RunNested(pDay, residenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);
                    //JLB 201602
                    //var nestedAlternative = Global.ChoiceModelSession.Get<SchoolTourModeTimeModel>().RunNested(pDay, residenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);
                    var nestedAlternative = Global.ChoiceModelSession.Get <TourModeTimeModel>().RunNested(pDay, residenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, Global.Settings.Purposes.School);

                    schoolLogsum[count - 1] = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
                }
            }


            // NONE_OR_HOME

            var alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.NoneOrHome, true, choice == Global.Settings.Purposes.NoneOrHome);

            alternative.Choice = Global.Settings.Purposes.NoneOrHome;

            //alternative.AddUtilityTerm(1, (personDay.TotalCreatedTours == 1).ToFlag());
            alternative.AddUtilityTerm(2, (personDay.GetTotalCreatedTours() == 2).ToFlag());
            alternative.AddUtilityTerm(3, (personDay.GetTotalCreatedTours() >= 3).ToFlag());
            //alternative.AddUtilityTerm(4, (personDay.TotalCreatedTours >= 4).ToFlag());

            //alternative.AddUtilityTerm(5, householdDay.PrimaryPriorityTimeFlag);

            //alternative.AddUtilityTerm(6, householdDay.Household.HasChildren.ToFlag());

            alternative.AddUtilityTerm(4, householdDay.Household.HasChildrenUnder5.ToFlag());
            alternative.AddUtilityTerm(5, householdDay.Household.HasChildrenAge5Through15.ToFlag());
            //alternative.AddUtilityTerm(6, (householdDay.Household.Size == 2 && householdDay.AdultsInSharedHomeStay == 2).ToFlag());
            //alternative.AddUtilityTerm(7, (householdDay.AdultsInSharedHomeStay == 1 && householdDay.Household.HasChildrenUnder16).ToFlag());
            //alternative.AddUtilityTerm(8, (householdDay.AdultsInSharedHomeStay == 2 && householdDay.Household.HouseholdTotals.FullAndPartTimeWorkers >= 2).ToFlag());

            //alternative.AddUtilityTerm(10, (householdDay.Household.Income >= 300000 && householdDay.Household.Income < 600000).ToFlag());
            //alternative.AddUtilityTerm(11, (householdDay.Household.Income >= 600000 && householdDay.Household.Income < 900000).ToFlag());
            //alternative.AddUtilityTerm(12, (householdDay.Household.Income >= 900000).ToFlag());

            alternative.AddUtilityTerm(13, householdDay.PrimaryPriorityTimeFlag);

            alternative.AddUtilityTerm(14, personDay.Person.IsPartTimeWorker.ToFlag());
            alternative.AddUtilityTerm(15, personDay.Person.WorksAtHome.ToFlag());
            //alternative.AddUtilityTerm(16, personDay.Person.IsFulltimeWorker.ToFlag());

            //alternative.AddUtilityTerm(15, (personDay.Person.Gender == 1).ToFlag());

            //alternative.AddUtilityTerm(10, (householdDay.Household.Size == 3).ToFlag());
            //alternative.AddUtilityTerm(11, (householdDay.Household.Size == 4).ToFlag());
            //alternative.AddUtilityTerm(12, (householdDay.Household.Size >= 5).ToFlag());

            //alternative.AddNestedAlternative(11, 0, 200);


            // WORK
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Work, false, choice == Global.Settings.Purposes.Work);
            alternative.Choice = Global.Settings.Purposes.Work;
            alternative.AddUtilityTerm(202, 1);
            //alternative.AddNestedAlternative(12, 1, 200);

            //  SCHOOL
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.School, false, choice == Global.Settings.Purposes.School);
            alternative.Choice = Global.Settings.Purposes.School;
            alternative.AddUtilityTerm(203, 1);
            //alternative.AddNestedAlternative(12, 1, 200);

            // ESCORT
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Escort, maxPurpose <= Global.Settings.Purposes.Escort && personDay.CreatedEscortTours > 0, choice == Global.Settings.Purposes.Escort);
            alternative.Choice = Global.Settings.Purposes.Escort;

            alternative.AddUtilityTerm(151, 1);
            alternative.AddUtilityTerm(152, (personDay.CreatedEscortTours > 1).ToFlag());

            //alternative.AddUtilityTerm(152, householdDay.PrimaryPriorityTimeFlag);

            //alternative.AddUtilityTerm(153, (householdDay.Household.Size == 3).ToFlag());
            //alternative.AddUtilityTerm(154, (householdDay.Household.Size >= 4).ToFlag());

            //alternative.AddUtilityTerm(155, (householdDay.Household.Size > 4).ToFlag());

            alternative.AddUtilityTerm(155, compositeLogsum);

            //alternative.AddUtilityTerm(156, (householdDay.Household.VehiclesAvailable == 0).ToFlag());

            //alternative.AddNestedAlternative(12, 1, 200);


            // PERSONAL_BUSINESS
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.PersonalBusiness, maxPurpose <= Global.Settings.Purposes.PersonalBusiness && personDay.CreatedPersonalBusinessTours > 0, choice == Global.Settings.Purposes.PersonalBusiness);
            alternative.Choice = Global.Settings.Purposes.PersonalBusiness;

            alternative.AddUtilityTerm(21, 1);
            //alternative.AddUtilityTerm(22, (personDay.CreatedPersonalBusinessTours > 1).ToFlag()); //GV: 30. april 2013 - goes to infinity

            alternative.AddUtilityTerm(156, compositeLogsum);

            //alternative.AddNestedAlternative(12, 1, 200);

            // SHOPPING
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Shopping, maxPurpose <= Global.Settings.Purposes.Shopping && personDay.CreatedShoppingTours > 0, choice == Global.Settings.Purposes.Shopping);
            alternative.Choice = Global.Settings.Purposes.Shopping;

            alternative.AddUtilityTerm(41, 1);
            //alternative.AddUtilityTerm(42, (personDay.CreatedShoppingTours > 1).ToFlag()); //GV: cannot be estimated

            //alternative.AddUtilityTerm(42, householdDay.PrimaryPriorityTimeFlag);

            //alternative.AddUtilityTerm(43, (householdDay.Household.Size == 3).ToFlag());
            //alternative.AddUtilityTerm(44, (householdDay.Household.Size == 4).ToFlag());
            //alternative.AddUtilityTerm(45, (householdDay.Household.Size > 4).ToFlag());

            //alternative.AddUtilityTerm(46, (householdDay.Household.VehiclesAvailable == 0).ToFlag());

            //alternative.AddUtilityTerm(157, compositeLogsum); //GV wrong sign
            //alternative.AddUtilityTerm(157, shoppingAggregateLogsum); //GV wrong sign

            //alternative.AddNestedAlternative(12, 1, 200);


            // MEAL

            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Meal, false, choice == Global.Settings.Purposes.Meal);
            alternative.Choice = Global.Settings.Purposes.Meal;

            alternative.AddUtilityTerm(61, 1);
            alternative.AddUtilityTerm(62, (personDay.CreatedMealTours > 1).ToFlag());

            //alternative.AddNestedAlternative(12, 1, 200);

            // SOCIAL

            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Social, maxPurpose <= Global.Settings.Purposes.Social && personDay.CreatedSocialTours > 0, choice == Global.Settings.Purposes.Social);
            alternative.Choice = Global.Settings.Purposes.Social;

            alternative.AddUtilityTerm(81, 1);
            alternative.AddUtilityTerm(82, (personDay.CreatedSocialTours > 1).ToFlag());

            //alternative.AddUtilityTerm(82, householdDay.PrimaryPriorityTimeFlag);

            //alternative.AddUtilityTerm(83, (householdDay.Household.Size == 3).ToFlag());
            //alternative.AddUtilityTerm(84, (householdDay.Household.Size == 4).ToFlag());
            //alternative.AddUtilityTerm(85, (householdDay.Household.Size > 4).ToFlag());

            alternative.AddUtilityTerm(158, compositeLogsum);

            //alternative.AddNestedAlternative(12, 1, 200);

            // RECREATION

            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Recreation, false, choice == Global.Settings.Purposes.Recreation);
            alternative.Choice = Global.Settings.Purposes.Recreation;

            alternative.AddUtilityTerm(101, 1);
            //alternative.AddUtilityTerm(102, (personDay.CreatedRecreationTours > 1).ToFlag());

            //alternative.AddNestedAlternative(12, 1, 60);

            // MEDICAL

            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Medical, false, choice == Global.Settings.Purposes.Medical);
            alternative.Choice = Global.Settings.Purposes.Medical;

            alternative.AddUtilityTerm(121, 1);
            //alternative.AddUtilityTerm(122, (personDay.CreatedMedicalTours > 1).ToFlag());

            //alternative.AddNestedAlternative(11, 1, 60);
        }
Exemple #13
0
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, HouseholdWrapper household, int choice = Constants.DEFAULT_VALUE)
        {
            //
            double workTourLogsumDifference = 0D; // (full or part-time workers) full car ownership vs. no car ownership

            double countTransitPasses = 0D;

            foreach (Framework.DomainModels.Wrappers.IPersonWrapper person in household.Persons)
            {
                if (person.TransitPassOwnership == 1)
                {
                    countTransitPasses++;
                }
                if (person.IsWorker && person.UsualWorkParcel != null && person.UsualWorkParcelId != household.ResidenceParcelId)
                {
                    int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                    int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);

                    ChoiceProbabilityCalculator.Alternative nestedAlternative1 = Global.ChoiceModelSession.Get <WorkTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.HouseholdTotals.DrivingAgeMembers, 0.0);
                    ChoiceProbabilityCalculator.Alternative nestedAlternative2 = Global.ChoiceModelSession.Get <WorkTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, 0, 0.0);

                    workTourLogsumDifference += nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
                    workTourLogsumDifference -= nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
                }
            }

            int oldestAge   = (from persons in household.Persons select persons.Age).Max();
            int youngestAge = (from persons in household.Persons select persons.Age).Min();

            int noTransitPasses = countTransitPasses == 0 ? 1 : 0;

            int votSegment = household.GetVotALSegment();
            int taSegment  = household.ResidenceParcel.TransitAccessSegment();

            //var aggregateLogsumDifference = // full car ownership vs. no car ownership
            //    Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult][votSegment][taSegment] -
            //    Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votSegment][taSegment];

            double noCarAggLogsum =
                Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votSegment][taSegment];

            double distanceToStop
                = household.ResidenceParcel.GetDistanceToTransit() > 0
                      ? Math.Min(household.ResidenceParcel.GetDistanceToTransit(), 2 * Global.Settings.DistanceUnitsPerMile)  // JLBscale
                      : 2 * Global.Settings.DistanceUnitsPerMile;

            int ruralFlag = household.ResidenceParcel.RuralFlag();

            double discretionaryIncome = (household.Income / 10000 - (1.2 * Math.Log(household.Size) + 2.0));


            //home parcel buffer variables
            double foodRetailServiceMedicalLogBuffer1 = Math.Log(1 + household.ResidenceParcel.FoodRetailServiceMedicalLogBuffer1());
            double intrDens = Math.Log(1 + household.ResidenceParcel.IntersectionDensity34Buffer2());

            // 0 AUTOS

            ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(0, true, choice == 0);

            alternative.Choice = 0;

            alternative.AddUtilityTerm(1, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(2, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(3, household.Has3Drivers.ToFlag());
            alternative.AddUtilityTerm(4, household.Has4OrMoreDrivers.ToFlag());
            alternative.AddUtilityTerm(5, household.HasNoFullOrPartTimeWorker.ToFlag());
            alternative.AddUtilityTerm(8, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(9, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(12, household.Has0To25KIncome.ToFlag());
            alternative.AddUtilityTerm(13, discretionaryIncome);
            alternative.AddUtilityTerm(14, household.HasIncomeOver50K.ToFlag());
            alternative.AddUtilityTerm(16, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(17, workTourLogsumDifference);
            alternative.AddUtilityTerm(21, Math.Log(distanceToStop));
            alternative.AddUtilityTerm(23, Math.Log(1 + household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer2 / 100));
            alternative.AddUtilityTerm(28, noTransitPasses);
            alternative.AddUtilityTerm(29, intrDens);
            alternative.AddUtilityTerm(31, household.HasChildrenUnder16.ToFlag());
            alternative.AddUtilityTerm(33, (household.Has50To75KIncome).ToFlag() * noCarAggLogsum);
            alternative.AddUtilityTerm(34, (household.Has75KPlusIncome).ToFlag() * noCarAggLogsum);
            alternative.AddUtilityTerm(35, (youngestAge > 70).ToFlag());
            alternative.AddUtilityTerm(36, (oldestAge < 35).ToFlag());

            // 1 AUTO

            alternative = choiceProbabilityCalculator.GetAlternative(1, true, choice == 1);

            alternative.Choice = 1;

            alternative.AddUtilityTerm(37, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(38, household.Has3Drivers.ToFlag());
            alternative.AddUtilityTerm(39, household.Has4OrMoreDrivers.ToFlag());
            alternative.AddUtilityTerm(5, household.Has1OrLessFullOrPartTimeWorkers.ToFlag());
            alternative.AddUtilityTerm(8, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(9, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(41, household.Has0To25KIncome.ToFlag());
            alternative.AddUtilityTerm(45, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(19, discretionaryIncome);
            alternative.AddUtilityTerm(17, workTourLogsumDifference * household.HasMoreDriversThan1.ToFlag());
            alternative.AddUtilityTerm(23, Math.Log(1 + household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer2 / 100) * household.HasMoreDriversThan1.ToFlag());
            alternative.AddUtilityTerm(46, intrDens);
            alternative.AddUtilityTerm(35, (youngestAge > 70).ToFlag());
            alternative.AddUtilityTerm(36, (oldestAge < 35).ToFlag());
            alternative.AddUtilityTerm(48, household.HasChildrenUnder16.ToFlag());

            // 2 AUTOS

            alternative = choiceProbabilityCalculator.GetAlternative(2, true, choice == 2);

            alternative.Choice = 2;

            alternative.AddUtilityTerm(50, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(51, household.Has3Drivers.ToFlag());
            alternative.AddUtilityTerm(52, household.Has4OrMoreDrivers.ToFlag());
            alternative.AddUtilityTerm(5, household.Has2OrLessFullOrPartTimeWorkers.ToFlag());
            alternative.AddUtilityTerm(17, workTourLogsumDifference * household.HasMoreDriversThan2.ToFlag());
            alternative.AddUtilityTerm(23, Math.Log(1 + household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer2 / 100) * household.HasMoreDriversThan2.ToFlag());
            alternative.AddUtilityTerm(27, ruralFlag);

            // 3 AUTOS

            alternative = choiceProbabilityCalculator.GetAlternative(3, true, choice == 3);

            alternative.Choice = 3;

            alternative.AddUtilityTerm(70, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(71, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(72, household.Has4OrMoreDrivers.ToFlag());
            alternative.AddUtilityTerm(5, household.Has3OrLessFullOrPartTimeWorkers.ToFlag());
            alternative.AddUtilityTerm(91, household.HouseholdTotals.PartTimeWorkersPerDrivingAgeMembers);
            alternative.AddUtilityTerm(92, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(93, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(94, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(96, household.HouseholdTotals.ChildrenUnder5PerDrivingAgeMembers);
            alternative.AddUtilityTerm(73, household.Has0To25KIncome.ToFlag());
            alternative.AddUtilityTerm(75, household.Has100KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(76, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(17, workTourLogsumDifference * household.HasMoreDriversThan3.ToFlag());
            alternative.AddUtilityTerm(23, Math.Log(1 + household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer2 / 100) * household.HasMoreDriversThan3.ToFlag());
            alternative.AddUtilityTerm(79, ruralFlag);

            // 4+ AUTOS
            alternative = choiceProbabilityCalculator.GetAlternative(4, true, choice == 4);

            alternative.Choice = 4;

            alternative.AddUtilityTerm(100, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(101, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(102, household.Has3Drivers.ToFlag());
            alternative.AddUtilityTerm(5, household.Has4OrLessFullOrPartTimeWorkers.ToFlag());
            alternative.AddUtilityTerm(91, household.HouseholdTotals.PartTimeWorkersPerDrivingAgeMembers);
            alternative.AddUtilityTerm(92, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(93, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(94, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(96, household.HouseholdTotals.ChildrenUnder5PerDrivingAgeMembers);
            alternative.AddUtilityTerm(107, household.Has0To25KIncome.ToFlag());
            alternative.AddUtilityTerm(108, household.Has50To75KIncome.ToFlag());
            alternative.AddUtilityTerm(109, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(110, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(17, workTourLogsumDifference * household.HasMoreDriversThan4.ToFlag());
            alternative.AddUtilityTerm(23, Math.Log(1 + household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer2 / 100) * household.HasMoreDriversThan4.ToFlag());
            alternative.AddUtilityTerm(111, ruralFlag);
        }
Exemple #14
0
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, HouseholdDayWrapper householdDay, int jHTSimulated, int genChoice, bool[,] jHTAvailable, bool[] fHTAvailable, int[][] altParticipants, int choice = Constants.DEFAULT_VALUE)
        {
            IEnumerable <PersonDayWrapper> orderedPersonDays = householdDay.PersonDays.OrderBy(p => p.GetJointHalfTourParticipationPriority()).ToList().Cast <PersonDayWrapper>();

            int pairedHalfTour = genChoice == 1 ? 1 : 0;
            int firstHalfTour  = genChoice == 2 ? 1 : 0;
            int secondHalfTour = genChoice == 3 ? 1 : 0;

            // set household characteristics here that don't depend on person characteristics

            var carOwnership =
                householdDay.Household.VehiclesAvailable == 0
                             ? Global.Settings.CarOwnerships.NoCars
                             : householdDay.Household.VehiclesAvailable < householdDay.Household.HouseholdTotals.DrivingAgeMembers
                                  ? Global.Settings.CarOwnerships.LtOneCarPerAdult
                                  : Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult;
            int hhsize             = householdDay.Household.Size;
            var noCarsFlag         = FlagUtility.GetNoCarsFlag(carOwnership);
            var carCompetitionFlag = FlagUtility.GetCarCompetitionFlag(carOwnership);

            var votALSegment         = householdDay.Household.GetVotALSegment();
            var transitAccessSegment = householdDay.Household.ResidenceParcel.TransitAccessSegment();
            var totalAggregateLogsum = Global.AggregateLogsums[householdDay.Household.ResidenceParcel.ZoneId]
                                       [Global.Settings.Purposes.HomeBasedComposite][carOwnership][votALSegment][transitAccessSegment];

            IPersonDayWrapper pPersonDay = null;

            IParcelWrapper[] pUsualLocation   = new IParcelWrapper[6];
            int[]            pUsualLocationId = new int[6];
            int[]            pPatternType     = new int[6];
            int[]            pConstant        = new int[6];
            int[,] pType = new int[9, 6];
            int[] pAdult = new int[6];
            int[] pChild = new int[6];
            int[] pAge   = new int[6];


            int[] pAdultFemale        = new int[6];
            int[] pAdultMandatory     = new int[6];
            int[] pNonMandatory       = new int[6];
            int[] pFemaleNonMandatory = new int[6];

            int[] pAdultWithChildrenUnder16 = new int[6];

            int[] pType7AgeUnder12 = new int[6];
            int[] pType7Age12Plus  = new int[6];
            int[] pAgeUnder13      = new int[6];
            int[] pAge5To8         = new int[6];
            int[] pAge9To12        = new int[6];
            int[] pAge13To15       = new int[6];

            int[]  pTransitAdult = new int[6];
            int[]  pTransitChild = new int[6];
            int[]  pDrivingAge   = new int[6];
            bool[] pHasMandatoryTourToUsualLocation = new bool[6];
            bool[] pIsDrivingAge = new bool[6];

            int count = 0;

            foreach (PersonDayWrapper personDay in orderedPersonDays)
            {
                count++;
                if (count <= 5)
                {
                    if (count == 1)
                    {
                        pPersonDay = personDay;
                    }
                    // set characteristics here that depend on person characteristics
                    if (personDay.Person.IsFullOrPartTimeWorker && personDay.Person.UsualWorkParcel != null)
                    {
                        pUsualLocation[count] = personDay.Person.UsualWorkParcel;
                    }
                    else if (personDay.Person.IsStudent && personDay.Person.UsualSchoolParcel != null)
                    {
                        pUsualLocation[count] = personDay.Person.UsualSchoolParcel;
                    }
                    else if (personDay.Person.IsWorker && personDay.Person.IsNotFullOrPartTimeWorker && personDay.Person.UsualWorkParcel != null)
                    {
                        pUsualLocation[count] = personDay.Person.UsualWorkParcel;
                    }
                    else
                    {
                        pUsualLocation[count] = personDay.Household.ResidenceParcel;
                    }

                    for (int i = 1; i < 9; i++)
                    {
                        pType[personDay.Person.PersonType, count] = 1;
                    }

                    pPatternType[count] = personDay.PatternType;
                    pConstant[count]    = 1;
                    pAdult[count]       = personDay.Person.IsAdult.ToFlag();
                    pChild[count]       = (!(personDay.Person.IsAdult)).ToFlag();
                    pAdultWithChildrenUnder16[count] = (personDay.Person.IsAdult && personDay.Household.HasChildrenUnder16).ToFlag();
                    pAdultFemale[count]        = personDay.Person.IsAdultFemale.ToFlag();
                    pAdultMandatory[count]     = personDay.Person.IsAdult.ToFlag() * (personDay.PatternType == Global.Settings.PatternTypes.Mandatory).ToFlag();
                    pNonMandatory[count]       = (personDay.PatternType == Global.Settings.PatternTypes.Optional).ToFlag();
                    pFemaleNonMandatory[count] = personDay.Person.IsAdultFemale.ToFlag() * (personDay.PatternType == Global.Settings.PatternTypes.Optional).ToFlag();
                    pType7AgeUnder12[count]    = (personDay.Person.IsChildAge5Through15 && personDay.Person.Age < 12).ToFlag();
                    pType7Age12Plus[count]     = (personDay.Person.IsChildAge5Through15 && personDay.Person.Age >= 12).ToFlag();
                    pAgeUnder13[count]         = (personDay.Person.Age < 13).ToFlag();
                    pAge5To8[count]            = (personDay.Person.Age >= 5 && personDay.Person.Age <= 8).ToFlag();
                    pAge9To12[count]           = (personDay.Person.Age >= 9 && personDay.Person.Age <= 12).ToFlag();
                    pAge13To15[count]          = (personDay.Person.Age >= 13 && personDay.Person.Age <= 15).ToFlag();
                    pTransitAdult[count]       = (personDay.Person.TransitPassOwnership == 1 ? 1 : 0) * (personDay.Person.IsAdult.ToFlag());
                    pTransitChild[count]       = (personDay.Person.TransitPassOwnership == 1 ? 1 : 0) * ((!personDay.Person.IsAdult).ToFlag());
                    pDrivingAge[count]         = personDay.Person.IsDrivingAge.ToFlag();

                    pHasMandatoryTourToUsualLocation[count] = personDay.HasMandatoryTourToUsualLocation;
                    pIsDrivingAge[count] = personDay.Person.IsDrivingAge;
                }
            }
            var componentIndex = 0;

            //Create person utility components
            int[] componentPerson = new int[6];
            for (var p = 1; p <= 5; p++)
            {
                // create component for basic person-purposes
                componentIndex++;
                componentPerson[p] = componentIndex;
                choiceProbabilityCalculator.CreateUtilityComponent(componentPerson[p]);

                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(01, pType[1, p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(02, pType[2, p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(03, pType[3, p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(04, pType[4, p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(05, pType[5, p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(06, pType[6, p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(07, pType[7, p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(08, pType[8, p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(09, pAge5To8[p]);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(10, pAge9To12[p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(11, pAdultFemale[p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(12, pNonMandatory[p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(13, pFemaleNonMandatory[p]);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(14, pTransitAdult[p]);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(15, pTransitChild[p]);

                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(21, pType[1, p] * secondHalfTour);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(22, pType[2, p] * secondHalfTour);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(23, pType[3, p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(24, pType[4, p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(25, pType[5, p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(26, pType[6, p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(27, pType[7, p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(28, pType[8, p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(29, pAge5To8[p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(30, pAge9To12[p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(31, pAdultFemale[p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(32, pNonMandatory[p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(33, pFemaleNonMandatory[p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(34, pTransitAdult[p] * secondHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(35, pTransitChild[p] * secondHalfTour);

                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(41, pType[1, p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(42, pType[2, p] * pairedHalfTour);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(43, pType[3, p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(44, pType[4, p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(45, pType[5, p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(46, pType[6, p] * pairedHalfTour);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(47, pType[7, p] * pairedHalfTour);
                choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(48, pType[8, p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(49, pAge5To8[p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(50, pAge9To12[p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(51, pAdultFemale[p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(52, pNonMandatory[p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(53, pFemaleNonMandatory[p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(54, pTransitAdult[p] * pairedHalfTour);
                //choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]).AddUtilityTerm(55, pTransitChild[p] * pairedHalfTour);
            }

            //create two-way match interaction utility components
            int[,] componentMatch   = new int[6, 6];
            int[,] iMatchAgeUnder13 = new int[6, 6];
            int[,] iMatchAdult      = new int[6, 6];
            int[,] iMatchAdultWithChildrenUnder16 = new int[6, 6];

            int[,] iMatchMandatoryAdults  = new int[6, 6];
            int[,] iMatchChild            = new int[6, 6];
            int[,] iMatchNonMandatory     = new int[6, 6];
            int[,] iMatchAdultsCarDeficit = new int[6, 6];
            int[,] iMatchAdultCountAtHome = new int[6, 6];


            for (var t2 = 1; t2 <= 5; t2++)
            {
                for (var t1 = 1; t1 < t2; t1++)
                {
                    //populate match variables
                    iMatchAgeUnder13[t1, t2] = pAgeUnder13[t1] * pAgeUnder13[t2];
                    iMatchAdult[t1, t2]      = pAdult[t1] * pAdult[t2];
                    iMatchAdultWithChildrenUnder16[t1, t2] = pAdultWithChildrenUnder16[t1] * pAdultWithChildrenUnder16[t2];

                    iMatchMandatoryAdults[t1, t2]  = pAdultMandatory[t1] * pAdultMandatory[t2];
                    iMatchChild[t1, t2]            = (1 - pAdult[t1]) * (1 - pAdult[t2]);
                    iMatchNonMandatory[t1, t2]     = pNonMandatory[t1] * pNonMandatory[t2];
                    iMatchAdultsCarDeficit[t1, t2] = pAdult[t1] * pAdult[t2] * (carCompetitionFlag + noCarsFlag);


                    //create and populate components
                    componentIndex++;
                    componentMatch[t1, t2] = componentIndex;
                    choiceProbabilityCalculator.CreateUtilityComponent(componentMatch[t1, t2]);
                    choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(61, iMatchAgeUnder13[t1, t2]);
                    choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(62, iMatchAdult[t1, t2]);
                    choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(63, iMatchMandatoryAdults[t1, t2]);
                    choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(64, iMatchNonMandatory[t1, t2]);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(65, iMatchAdultWithChildrenUnder16[t1, t2]);
                    choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(66, iMatchChild[t1, t2]);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(67, iMatchAdultsCarDeficit[t1, t2]);

                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(71, iMatchAgeUnder13[t1, t2] * secondHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(72, iMatchAdult[t1, t2] * secondHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(73, iMatchMandatoryAdults[t1, t2] * secondHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(74, iMatchNonMandatory[t1, t2] * secondHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(75, iMatchAdultWithChildrenUnder16[t1, t2] * secondHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(76, iMatchChild[t1, t2] * secondHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(77, iMatchAdultsCarDeficit[t1, t2] * secondHalfTour);

                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(81, iMatchAgeUnder13[t1, t2] * pairedHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(82, iMatchAdult[t1, t2] * pairedHalfTour);
                    choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(83, iMatchMandatoryAdults[t1, t2] * pairedHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(84, iMatchNonMandatory[t1, t2] * pairedHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(85, iMatchAdultWithChildrenUnder16[t1, t2] * pairedHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(86, iMatchChild[t1, t2] * pairedHalfTour);
                    //choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]).AddUtilityTerm(87, iMatchAdultsCarDeficit[t1, t2] * pairedHalfTour);
                }
            }

            //create two-way cross interaction utility components
            int[,] componentCross = new int[6, 6];
            int iCrossAgeUnder5AndNonMandatory;
            int iCrossAge5To12AndNonMandatory;
            int iCrossAge13To15AndNonMandatory;
            int iCrossDrivingAgeChildAndNonMandatory;

            for (var t2 = 1; t2 <= 5; t2++)
            {
                for (var t1 = 1; t1 <= 5; t1++)
                {
                    if (!(t1 == t2))
                    {
                        //populate cross variables
                        iCrossAge5To12AndNonMandatory        = pNonMandatory[t1] * (pAge5To8[t2] + pAge9To12[t2]);
                        iCrossAgeUnder5AndNonMandatory       = pNonMandatory[t1] * pType[8, t2];
                        iCrossAge13To15AndNonMandatory       = pNonMandatory[t1] * pAge13To15[t2];
                        iCrossDrivingAgeChildAndNonMandatory = pNonMandatory[t1] * pType[6, t2];

                        //create and populate cross components
                        componentIndex++;
                        componentCross[t1, t2] = componentIndex;
                        choiceProbabilityCalculator.CreateUtilityComponent(componentCross[t1, t2]);
                        choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(91, iCrossAgeUnder5AndNonMandatory);
                        //choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(92, iCrossAge5To12AndNonMandatory);
                        choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(93, iCrossAge13To15AndNonMandatory);
                        //choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(94, iCrossDrivingAgeChildAndNonMandatory);

                        //choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(95, iCrossAgeUnder5AndNonMandatory * secondHalfTour);
                        //choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]).AddUtilityTerm(96, iCrossAgeUnder5AndNonMandatory * pairedHalfTour);
                    }
                }
            }

            //Generate utility funtions for the alternatives
            bool[] available = new bool[32];
            bool[] chosen    = new bool[32];
            int    numberOfParticipants;
            int    workersParticipating;
            int    numberOfParticipatingChildren;
            int    numberOfParticipatingAdults;
            int    numberOfAvailableChildren;
            int    numberOfAvailablePersons;
            int    numberOfAvailableAdults;

            for (int alt = 0; alt < 32; alt++)
            {
                available[alt] = false;
                chosen[alt]    = false;
                // set availability based on household size
                if (hhsize >= altParticipants[alt][6])
                {
                    available[alt] = true;
                }
                // restrict availability based on person unavailability
                for (int i = 1; i <= 5; i++)
                {
                    if (altParticipants[alt][i] == 1 && (jHTAvailable[genChoice - 1, i] == false || fHTAvailable[i] == false))
                    {
                        available[alt] = false;
                    }
                }
                // restrict availability to cases where all non-driving age participants have same usual location
                // first determine first non-adult's usual location
                IParcelWrapper sameUsualLocation = householdDay.Household.ResidenceParcel;
                for (int i = 1; i <= 5; i++)
                {
                    if (altParticipants[alt][i] == 1 && pPatternType[i] == 1 && pUsualLocation[i].Id > 0 && !(pDrivingAge[i] == 1))
                    {
                        sameUsualLocation = pUsualLocation[i];
                        break;
                    }
                }
                // then make alt unavailable if any M-Usual participant has a different usualLocation
                for (int i = 1; i <= 5; i++)
                {
                    if (altParticipants[alt][i] == 1 && pHasMandatoryTourToUsualLocation[i] && !(pUsualLocation[i].Id == sameUsualLocation.Id) && !(pDrivingAge[i] == 1))
                    {
                        available[alt] = false;
                        break;
                    }
                }
                // restrict availability of alts that include less than 2 participants
                if (altParticipants[alt][7] < 2)
                {
                    available[alt] = false;
                }

                // restrict availability if 2+ participants lack tour to usual location
                int numberLackMandatoryTourToUsualLocation = 0;
                for (int i = 1; i <= 5; i++)
                {
                    if (altParticipants[alt][i] == 1 && !pHasMandatoryTourToUsualLocation[i])
                    {
                        numberLackMandatoryTourToUsualLocation++;
                    }
                }
                if (numberLackMandatoryTourToUsualLocation > 1)
                {
                    available[alt] = false;
                }

                //JLB 20140404 remove the drivign age requirement because children can walk, bik or take bus to/from school without an adult.
                // require at least one driving age (as chauffeur)
                //int numberDrivingAge = 0;
                //for (int i = 1; i <= 5; i++) {
                //    if (altParticipants[alt][i] == 1 && pIsDrivingAge[i]) {
                //        numberDrivingAge++;
                //    }
                //}
                //if (numberDrivingAge == 0) {
                //    available[alt] = false;
                //}


                // Generate alt-specific variables
                numberOfParticipants          = 0;
                workersParticipating          = 0;
                numberOfParticipatingChildren = 0;
                numberOfParticipatingAdults   = 0;
                numberOfAvailableChildren     = 0;
                numberOfAvailablePersons      = 0;
                numberOfAvailableAdults       = 0;
                if (available[alt] == true)
                {
                    for (int i = 1; i <= 5; i++)
                    {
                        if (pChild[i] == 1 && pUsualLocation[i].Id == sameUsualLocation.Id)
                        {
                            numberOfAvailableChildren++;
                            numberOfAvailablePersons++;
                        }
                        if (pAdult[i] == 1 && (pPatternType[i] == Global.Settings.PatternTypes.Optional || pUsualLocation[i].Id == sameUsualLocation.Id))
                        {
                            numberOfAvailableChildren++;
                            numberOfAvailableAdults++;
                        }

                        if (altParticipants[alt][i] == 1)
                        {
                            numberOfParticipants++;
                            if (pType[0, i] == 1 || pType[1, i] == 1)
                            {
                                workersParticipating++;
                            }
                            if (pAdult[i] == 1)
                            {
                                numberOfParticipatingAdults++;
                            }
                            if (pChild[i] == 1)
                            {
                                numberOfParticipatingChildren++;
                            }
                        }
                    }
                }

                double tourLogsum               = 0;
                var    destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                var    destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
                var    nestedAlternative        = Global.ChoiceModelSession.Get <WorkTourModeTimeModel>().RunNested(pPersonDay, pPersonDay.Household.ResidenceParcel, sameUsualLocation, destinationArrivalTime, destinationDepartureTime, pPersonDay.Household.VehiclesAvailable);
                tourLogsum = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();

                // determine choice
                if (choice == alt)
                {
                    chosen[alt] = true;
                }

                //Get the alternative
                var alternative = choiceProbabilityCalculator.GetAlternative(alt, available[alt], chosen[alt]);

                alternative.Choice = alt;

                //Add alt-specific utility terms
                alternative.AddUtilityTerm(101, (numberOfParticipatingAdults > 1 && numberOfParticipatingChildren > 0) ? 1 : 0);
                alternative.AddUtilityTerm(102, (numberOfParticipatingChildren < numberOfAvailableChildren) ? 1 : 0);
                alternative.AddUtilityTerm(103, (numberOfParticipatingAdults == 0) ? 1 : 0);
                //alternative.AddUtilityTerm(104, (numberOfParticipants < numberOfAvailablePersons) ? 1 : 0);
                alternative.AddUtilityTerm(105, tourLogsum);

                //alternative.AddUtilityTerm(105, ((numberOfParticipatingAdults > 1 && numberOfParticipatingChildren > 0) ? 1 : 0) * secondHalfTour);
                //alternative.AddUtilityTerm(106, ((numberOfParticipatingAdults > 1 && numberOfParticipatingChildren > 0) ? 1 : 0) * pairedHalfTour);



                //Add utility components

                for (int p = 1; p <= 5; p++)
                {
                    if (altParticipants[alt][p] == 1)
                    {
                        alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(componentPerson[p]));
                    }
                }
                for (var t2 = 1; t2 <= 5; t2++)
                {
                    for (var t1 = 1; t1 < t2; t1++)
                    {
                        if (altParticipants[alt][t1] == 1 && altParticipants[alt][t2] == 1)
                        {
                            alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(componentMatch[t1, t2]));
                        }
                    }
                }
                for (var t2 = 1; t2 <= 5; t2++)
                {
                    for (var t1 = 1; t1 <= 5; t1++)
                    {
                        if (!(t1 == t2))
                        {
                            if (altParticipants[alt][t1] == 1 && altParticipants[alt][t2] == 1)
                            {
                                alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(componentCross[t1, t2]));
                            }
                        }
                    }
                }
            }
        }
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, HouseholdDayWrapper householdDay, int choice = Constants.DEFAULT_VALUE)
        {
            var household       = householdDay.Household;
            var residenceParcel = household.ResidenceParcel;

            // set household characteristics here that don't depend on person characteristics

            int hasAdultEducLevel12 = 0;
            int allAdultEducLevel12 = 1;
            int youngestAge         = 999;


            double firstWorkLogsum       = 0;
            double secondWorkLogsum      = 0;
            bool   firstWorkLogsumIsSet  = false;
            bool   secondWorkLogsumIsSet = false;
            int    numberWorkers         = 0;
            int    numberAdults          = 0;
            int    numberChildren        = 0;
            int    numberChildrenUnder5  = 0;


            // set characteristics here that depend on person characteristics
            foreach (PersonDayWrapper personDay in householdDay.PersonDays)
            {
                double workLogsum = 0;
                var    person     = (PersonWrapper)personDay.Person;
                if (person.UsualWorkParcel == null || person.UsualWorkParcelId == household.ResidenceParcelId ||
                    (person.PersonType != Global.Settings.PersonTypes.FullTimeWorker &&
                     person.PersonType != Global.Settings.PersonTypes.PartTimeWorker))
                //    || household.VehiclesAvailable == 0)
                {
                }
                else
                {
                    var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                    var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
                    //JLB 201406
                    //var nestedAlternative = Global.ChoiceModelSession.Get<WorkTourModeModel>().RunNested(personDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);
                    var nestedAlternative = Global.ChoiceModelSession.Get <WorkTourModeTimeModel>().RunNested(personDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);
                    workLogsum = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
                }
                if (person.Age >= 18 && person.EducationLevel >= 12)
                {
                    hasAdultEducLevel12 = 1;
                }
                if (person.Age >= 18 && person.EducationLevel < 12)
                {
                    allAdultEducLevel12 = 0;
                }
                if (person.Age < youngestAge)
                {
                    youngestAge = person.Age;
                }
                if (workLogsum != 0 && !firstWorkLogsumIsSet)
                {
                    firstWorkLogsum      = workLogsum;
                    firstWorkLogsumIsSet = true;
                }
                else if (workLogsum != 0 && !secondWorkLogsumIsSet)
                {
                    secondWorkLogsum      = workLogsum;
                    secondWorkLogsumIsSet = true;
                }
                if (person.Age >= 18)
                {
                    numberAdults++;
                    if (person.PersonType == Global.Settings.PersonTypes.FullTimeWorker
                        //|| person.PersonType == Constants.PersonType.PART_TIME_WORKER
                        )
                    {
                        numberWorkers++;
                    }
                }
                else
                {
                    numberChildren++;
                    if (person.PersonType == Global.Settings.PersonTypes.ChildUnder5)
                    {
                        numberChildrenUnder5++;
                    }
                }
            }
            var singleWorkerWithChildUnder5 = (numberAdults == numberWorkers && numberAdults == 1 &&
                                               numberChildrenUnder5 > 0) ? true : false;
            var workingCoupleNoChildren = (numberAdults == numberWorkers && numberAdults == 2 &&
                                           numberChildren == 0) ? true : false;
            var workingCoupleAllChildrenUnder5 = (numberAdults == numberWorkers && numberAdults == 2 &&
                                                  numberChildren > 0 && numberChildren == numberChildrenUnder5) ? true : false;
            var otherHouseholdWithPTFTWorkers = false;

            if (!workingCoupleNoChildren && !workingCoupleAllChildrenUnder5 && firstWorkLogsum != 0)
            {
                otherHouseholdWithPTFTWorkers = true;
            }
            var nonWorkingHousehold = false;

            if (!workingCoupleNoChildren && !workingCoupleAllChildrenUnder5 && !otherHouseholdWithPTFTWorkers)
            {
                nonWorkingHousehold = true;
            }


            // var votSegment = household.VotALSegment;
            //var taSegment = household.ResidenceParcel.TransitAccessSegment();

            //var aggregateLogsumDifference = // full car ownership vs. no car ownership
            //    Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult][votSegment][taSegment] -
            //    Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votSegment][taSegment];


            //var householdDay = (ActumHouseholdDayWrapper)tour.HouseholdDay;

            var carOwnership =
                household.VehiclesAvailable == 0
                                 ? Global.Settings.CarOwnerships.NoCars
                                 : household.VehiclesAvailable < household.HouseholdTotals.DrivingAgeMembers
                                      ? Global.Settings.CarOwnerships.LtOneCarPerAdult
                                      : Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult;

            var noCarsFlag         = FlagUtility.GetNoCarsFlag(carOwnership);
            var carCompetitionFlag = FlagUtility.GetCarCompetitionFlag(carOwnership);

            var votALSegment                    = Global.Settings.VotALSegments.Medium; // TODO:  calculate a VOT segment that depends on household income
            var transitAccessSegment            = household.ResidenceParcel.TransitAccessSegment();
            var personalBusinessAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                                  [Global.Settings.Purposes.PersonalBusiness][carOwnership][votALSegment][transitAccessSegment];
            var shoppingAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                          [Global.Settings.Purposes.Shopping][carOwnership][votALSegment][transitAccessSegment];
            var mealAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                      [Global.Settings.Purposes.Meal][carOwnership][votALSegment][transitAccessSegment];
            var socialAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                        [Global.Settings.Purposes.Social][carOwnership][votALSegment][transitAccessSegment];
            //var compositeLogsum = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][carOwnership][votALSegment][transitAccessSegment];
            var compositeLogsum = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votALSegment][transitAccessSegment];

            var componentIndex = 0;

            for (int pfpt = 0; pfpt < 2; pfpt++)
            {
                if (pfpt == 1)
                {
                    componentIndex = 1;
                    choiceProbabilityCalculator.CreateUtilityComponent(componentIndex);
                    var pfptComponent = choiceProbabilityCalculator.GetUtilityComponent(componentIndex);
                    pfptComponent.AddUtilityTerm(1, (householdDay.Household.Size == 3).ToFlag());
                    pfptComponent.AddUtilityTerm(2, (householdDay.Household.Size >= 4).ToFlag());
                    pfptComponent.AddUtilityTerm(3, householdDay.Household.HasChildrenUnder5.ToFlag());
                    pfptComponent.AddUtilityTerm(4, (householdDay.AdultsInSharedHomeStay == 1 && householdDay.Household.HasChildrenAge5Through15).ToFlag());
                    pfptComponent.AddUtilityTerm(5, (householdDay.AdultsInSharedHomeStay == 2 && householdDay.Household.HouseholdTotals.FullAndPartTimeWorkers >= 2).ToFlag());
                    pfptComponent.AddUtilityTerm(6, (householdDay.AdultsInSharedHomeStay == 2 && hasAdultEducLevel12 == 1).ToFlag());
                    pfptComponent.AddUtilityTerm(7, (householdDay.Household.VehiclesAvailable == 1 && household.Has2Drivers).ToFlag());
                    pfptComponent.AddUtilityTerm(8, (householdDay.Household.VehiclesAvailable >= 2 && household.Has2Drivers).ToFlag());
                    //pfptComponent.AddUtilityTerm(29, (householdDay.Household.Income >= 300000 && householdDay.Household.Income < 600000).ToFlag());
                    //pfptComponent.AddUtilityTerm(30, (householdDay.Household.Income >= 600000 && householdDay.Household.Income < 900000).ToFlag());
                    //pfptComponent.AddUtilityTerm(31, (householdDay.Household.Income >= 900000).ToFlag());
                    pfptComponent.AddUtilityTerm(9, (firstWorkLogsum + secondWorkLogsum) * (workingCoupleNoChildren || workingCoupleAllChildrenUnder5).ToFlag());
                    pfptComponent.AddUtilityTerm(9, (firstWorkLogsum + secondWorkLogsum) * otherHouseholdWithPTFTWorkers.ToFlag());
                    pfptComponent.AddUtilityTerm(10, compositeLogsum);
                }
            }
            for (var jointTourFlag = 0; jointTourFlag < 2; jointTourFlag++)
            {
                if (jointTourFlag == 1)
                {
                    componentIndex = 2;
                    choiceProbabilityCalculator.CreateUtilityComponent(componentIndex);
                    var jointComponent = choiceProbabilityCalculator.GetUtilityComponent(componentIndex);
                    jointComponent.AddUtilityTerm(21, householdDay.Household.HasChildrenUnder5.ToFlag());
                    jointComponent.AddUtilityTerm(22, householdDay.Household.HasChildrenAge5Through15.ToFlag());
                    jointComponent.AddUtilityTerm(23, (youngestAge >= 40).ToFlag());
                    //noJointComponent.AddUtilityTerm(50, (householdDay.Household.Income >= 300000 && householdDay.Household.Income < 600000).ToFlag());
                    //noJointComponent.AddUtilityTerm(51, (householdDay.Household.Income >= 600000 && householdDay.Household.Income < 900000).ToFlag());
                    //noJointComponent.AddUtilityTerm(52, (householdDay.Household.Income >= 900000).ToFlag());
                    jointComponent.AddUtilityTerm(24, compositeLogsum);
                }
            }

            var available = true;

            for (int pfpt = 0; pfpt < 2; pfpt++)
            {
                for (var jointTourFlag = 0; jointTourFlag < 2; jointTourFlag++)
                {
                    var altIndex = pfpt + jointTourFlag * 2;
                    if (household.Size < 2 && altIndex > 0)
                    {
                        available = false;
                    }
                    else
                    {
                        available = true;
                    }
                    var alternative = choiceProbabilityCalculator.GetAlternative(altIndex, available, choice != null && choice == altIndex);

                    alternative.Choice = altIndex;

                    //NESTING WAS REJECTED BY TESTS
                    //alternative.AddNestedAlternative(5 + pfpt,          pfpt, THETA_PARAMETER);  // pfpt on top
                    //alternative.AddNestedAlternative(5 + jointTourFlag, jointTourFlag, THETA_PARAMETER); //jointTourFlag on top

                    if (pfpt == 1)
                    {
                        alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(1));
                        //alternative.AddUtilityTerm(20, 1);
                    }
                    if (jointTourFlag == 0)
                    {
                        alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(2));
                        //alternative.AddUtilityTerm(40, 1);
                    }

                    if (pfpt == 0 && jointTourFlag == 0)
                    {
                    }
                    else if (pfpt == 1 && jointTourFlag == 0)
                    {
                        alternative.AddUtilityTerm(51, 1);
                    }
                    else if (pfpt == 0 && jointTourFlag == 1)
                    {
                        alternative.AddUtilityTerm(61, 1);
                    }
                    else if (pfpt == 1 && jointTourFlag == 1)
                    {
                        alternative.AddUtilityTerm(71, 1);
                        //alternative.AddUtilityTerm(72, (householdDay.Household.Size == 2 && householdDay.AdultsInSharedHomeStay == 2).ToFlag());
                        //alternative.AddUtilityTerm(73, (householdDay.AdultsInSharedHomeStay == 1 && householdDay.Household.HasChildrenUnder16).ToFlag());
                        //alternative.AddUtilityTerm(74, (householdDay.AdultsInSharedHomeStay == 2 && householdDay.Household.HouseholdTotals.FullAndPartTimeWorkers >= 2).ToFlag());
                        //alternative.AddUtilityTerm(75, (householdDay.AdultsInSharedHomeStay == 2 && hasAdultEducLevel12 == 1).ToFlag());
                    }
                }
            }
        }
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, IPersonDayWrapper personDay, DayPattern choice = null)
        {
            IHouseholdWrapper household       = personDay.Household;
            IParcelWrapper    residenceParcel = household.ResidenceParcel;
            IPersonWrapper    person          = personDay.Person;

            int    carsPerDriver       = household.GetCarsPerDriver();
            double mixedDensity        = residenceParcel.MixedUse3Index2();
            double intersectionDensity = residenceParcel.IntersectionDensity34Minus1Buffer2();

            double[] purposeLogsums = new double[Global.Settings.Purposes.TotalPurposes];
            double[] atUsualLogsums = new double[3];
            int      carOwnership   = person.GetCarOwnershipSegment();
            int      votSegment     = person.Household.GetVotALSegment();
            int      transitAccess  = residenceParcel.TransitAccessSegment();

            if (person.UsualWorkParcel == null || person.UsualWorkParcelId == household.ResidenceParcelId)
            {
                purposeLogsums[Global.Settings.Purposes.Work] = 0;
            }
            else
            {
                int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
                ChoiceProbabilityCalculator.Alternative nestedAlternative = Global.ChoiceModelSession.Get <WorkTourModeModel>().RunNested(personDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);

                purposeLogsums[Global.Settings.Purposes.Work] = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
                atUsualLogsums[Global.Settings.Purposes.Work] = Global.AggregateLogsums[person.UsualWorkParcel.ZoneId][Global.Settings.Purposes.HomeBasedComposite][carOwnership][votSegment][person.UsualWorkParcel.TransitAccessSegment()];
            }

            if (person.UsualSchoolParcel == null || person.UsualSchoolParcelId == household.ResidenceParcelId)
            {
                purposeLogsums[Global.Settings.Purposes.School] = 0;
            }
            else
            {
                int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
                int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);
                ChoiceProbabilityCalculator.Alternative nestedAlternative = Global.ChoiceModelSession.Get <SchoolTourModeModel>().RunNested(personDay, residenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);

                purposeLogsums[Global.Settings.Purposes.School] = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
                atUsualLogsums[Global.Settings.Purposes.School] = Global.AggregateLogsums[person.UsualSchoolParcel.ZoneId][Global.Settings.Purposes.HomeBasedComposite][carOwnership][votSegment][person.UsualSchoolParcel.TransitAccessSegment()];
            }

            double compositeLogsum = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][carOwnership][votSegment][transitAccess];

            purposeLogsums[Global.Settings.Purposes.Escort]           = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.Escort][carOwnership][votSegment][transitAccess];
            purposeLogsums[Global.Settings.Purposes.PersonalBusiness] = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.PersonalBusiness][carOwnership][votSegment][transitAccess];
            purposeLogsums[Global.Settings.Purposes.Shopping]         = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.Shopping][carOwnership][votSegment][transitAccess];
            purposeLogsums[Global.Settings.Purposes.Meal]             = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.Meal][carOwnership][votSegment][transitAccess];
            purposeLogsums[Global.Settings.Purposes.Social]           = Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.Social][carOwnership][votSegment][transitAccess];
            purposeLogsums[Global.Settings.Purposes.Recreation]       = compositeLogsum;
            purposeLogsums[Global.Settings.Purposes.Medical]          = compositeLogsum;

            for (int xPurpose = Global.Settings.Purposes.Work; xPurpose <= Global.Settings.Purposes.Social + 10; xPurpose++)
            {
                // extra components 1-5 are for 2,3,4,5,6 tour purposes
                // extra components 6-10 are for 2,3,4,5,6 stop puroposes

                // recode purpose to match coefficients
                int purpose = xPurpose <= Global.Settings.Purposes.Social ? xPurpose :
                              xPurpose <= Global.Settings.Purposes.Social + 5 ?
                              Global.Settings.Purposes.Social + 1 : Global.Settings.Purposes.Social + 2;

                // get correct multiplier on coefficients.
                double xMultiplier = xPurpose <= Global.Settings.Purposes.Social ? 1.0 :
                                     xPurpose <= Global.Settings.Purposes.Social + 5 ?
                                     Math.Log(xPurpose - Global.Settings.Purposes.Social + 1) : Math.Log(xPurpose - Global.Settings.Purposes.Social - 5 + 1);

                choiceProbabilityCalculator.CreateUtilityComponent(xPurpose);
                ChoiceProbabilityCalculator.Component component = choiceProbabilityCalculator.GetUtilityComponent(xPurpose);

                component.AddUtilityTerm(100 * purpose + 51, xMultiplier * person.IsFulltimeWorker.ToFlag());
                component.AddUtilityTerm(100 * purpose + 2, xMultiplier * person.IsPartTimeWorker.ToFlag());
                component.AddUtilityTerm(100 * purpose + 3, xMultiplier * person.IsRetiredAdult.ToFlag());
                component.AddUtilityTerm(100 * purpose + 4, xMultiplier * person.IsNonworkingAdult.ToFlag());
                component.AddUtilityTerm(100 * purpose + 5, xMultiplier * person.IsUniversityStudent.ToFlag());
                component.AddUtilityTerm(100 * purpose + 6, xMultiplier * person.IsDrivingAgeStudent.ToFlag());
                component.AddUtilityTerm(100 * purpose + 7, xMultiplier * person.IsChildAge5Through15.ToFlag());
                component.AddUtilityTerm(100 * purpose + 8, xMultiplier * person.IsChildUnder5.ToFlag());
                component.AddUtilityTerm(100 * purpose + 9, xMultiplier * household.Has0To25KIncome.ToFlag());
                component.AddUtilityTerm(100 * purpose + 10, xMultiplier * household.Has25To45KIncome.ToFlag());
                component.AddUtilityTerm(100 * purpose + 11, xMultiplier * household.Has75KPlusIncome.ToFlag());
                component.AddUtilityTerm(100 * purpose + 12, xMultiplier * carsPerDriver);
                component.AddUtilityTerm(100 * purpose + 13, xMultiplier * person.IsOnlyAdult().ToFlag());
                component.AddUtilityTerm(100 * purpose + 14, xMultiplier * person.IsOnlyFullOrPartTimeWorker().ToFlag());
                component.AddUtilityTerm(100 * purpose + 15, xMultiplier * 0);
                component.AddUtilityTerm(100 * purpose + 16, xMultiplier * person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * (!household.HasChildrenUnder16).ToFlag());
                component.AddUtilityTerm(100 * purpose + 17, xMultiplier * person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenUnder5.ToFlag());
                component.AddUtilityTerm(100 * purpose + 18, xMultiplier * person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenAge5Through15.ToFlag());
                component.AddUtilityTerm(100 * purpose + 19, xMultiplier * person.IsMale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenUnder5.ToFlag());
                component.AddUtilityTerm(100 * purpose + 20, xMultiplier * person.IsMale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenAge5Through15.ToFlag());
                component.AddUtilityTerm(100 * purpose + 21, xMultiplier * person.AgeIsBetween18And25.ToFlag());
                component.AddUtilityTerm(100 * purpose + 22, xMultiplier * person.AgeIsBetween26And35.ToFlag());
                component.AddUtilityTerm(100 * purpose + 23, xMultiplier * person.AgeIsBetween51And65.ToFlag());
                component.AddUtilityTerm(100 * purpose + 24, xMultiplier * person.WorksAtHome().ToFlag());
                component.AddUtilityTerm(100 * purpose + 25, xMultiplier * mixedDensity);
                component.AddUtilityTerm(100 * purpose + 26, xMultiplier * intersectionDensity);
                component.AddUtilityTerm(100 * purpose + 27, xMultiplier * purposeLogsums[purpose]);
                component.AddUtilityTerm(100 * purpose + 28, xMultiplier * person.TransitPassOwnership);
            }

            // tour utility
            int tourComponentIndex = Global.Settings.Purposes.Social + 11;

            choiceProbabilityCalculator.CreateUtilityComponent(tourComponentIndex);
            ChoiceProbabilityCalculator.Component tourComponent = choiceProbabilityCalculator.GetUtilityComponent(tourComponentIndex);
            tourComponent.AddUtilityTerm(1401, carsPerDriver);
            tourComponent.AddUtilityTerm(1402, person.WorksAtHome().ToFlag());
            tourComponent.AddUtilityTerm(1403, mixedDensity);
            tourComponent.AddUtilityTerm(1404, mixedDensity * person.IsChildAge5Through15.ToFlag());
            tourComponent.AddUtilityTerm(1405, compositeLogsum);
            tourComponent.AddUtilityTerm(1406, person.TransitPassOwnership);

            // stop utility
            int stopComponentIndex = Global.Settings.Purposes.Social + 12;

            choiceProbabilityCalculator.CreateUtilityComponent(stopComponentIndex);
            ChoiceProbabilityCalculator.Component stopComponent = choiceProbabilityCalculator.GetUtilityComponent(stopComponentIndex);
            stopComponent.AddUtilityTerm(1411, carsPerDriver);
            stopComponent.AddUtilityTerm(1412, person.WorksAtHome().ToFlag());
            stopComponent.AddUtilityTerm(1413, mixedDensity);
            stopComponent.AddUtilityTerm(1414, mixedDensity * person.IsChildAge5Through15.ToFlag());
            stopComponent.AddUtilityTerm(1415, compositeLogsum);
            stopComponent.AddUtilityTerm(1416, person.TransitPassOwnership);

            for (int alternativeIndex = 0; alternativeIndex < TOTAL_ALTERNATIVES; alternativeIndex++)
            {
                DayPattern dayPattern = _dayPatterns[alternativeIndex];
                bool       available  =
                    // work tours and stops only available for workers
                    (person.IsWorker || (dayPattern.WorkTours <= 0 && dayPattern.WorkStops <= 0)) &&
                    // school tours and stops only available for students with usual school parcel not at home
                    ((person.IsStudent && person.UsualSchoolParcel != null && person.UsualSchoolParcel != person.Household.ResidenceParcel) || (dayPattern.SchoolTours <= 0 && dayPattern.SchoolStops <= 0)) &&
                    // school stops not available if usual school parcel is same as usual work parcel
                    ((person.IsStudent && person.UsualSchoolParcel != null && person.UsualSchoolParcel != person.UsualWorkParcel) || (dayPattern.SchoolStops <= 0));

                ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(alternativeIndex, available, choice != null && choice.Equals(dayPattern));

                if (!Global.Configuration.IsInEstimationMode && !alternative.Available)
                {
                    continue;
                }

                alternative.Choice = dayPattern;

                // components for the purposes
                for (int purpose = Global.Settings.Purposes.Work; purpose <= Global.Settings.Purposes.Social; purpose++)
                {
                    if (dayPattern.Tours[purpose] > 0 || dayPattern.Stops[purpose] > 0)
                    {
                        alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(purpose));

                        if (dayPattern.Tours[purpose] > 0)
                        {
                            alternative.AddUtilityTerm(100 * purpose, 1);                                  // tour purpose ASC
                            alternative.AddUtilityTerm(100 * purpose + 29, purposeLogsums[purpose]);       // tour purpose logsum
                            alternative.AddUtilityTerm(100 * purpose + 30, person.PaidParkingAtWorkplace); // only use for work purpose
                        }

                        if (dayPattern.Stops[purpose] > 0)
                        {
                            alternative.AddUtilityTerm(100 * purpose + 1, 1);                        // stop purpose ASC
                            alternative.AddUtilityTerm(100 * purpose + 31, purposeLogsums[purpose]); // stop purpose logsum
                        }
                        if (Global.Configuration.IsInEstimationMode)
                        {
                            alternative.AddUtilityTerm(100 * purpose + 32, 1 - person.PaperDiary);
                            alternative.AddUtilityTerm(100 * purpose + 33, person.ProxyResponse);
                        }
                    }
                }

                // multiple tour purposes component
                if (dayPattern.TotalTours > 1)
                {
                    alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(Global.Settings.Purposes.Social + (dayPattern.TotalTours - 1)));
                }

                // multiple stop purposes component
                if (dayPattern.TotalStops > 1)
                {
                    alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(Global.Settings.Purposes.Social + 5 + (dayPattern.TotalStops - 1)));
                }

                for (int tourPurpose = Global.Settings.Purposes.Work; tourPurpose <= Global.Settings.Purposes.Social; tourPurpose++)
                {
                    for (int stopPurpose = Global.Settings.Purposes.Work; stopPurpose <= Global.Settings.Purposes.Social - 1; stopPurpose++)
                    {
                        if (tourPurpose > Global.Settings.Purposes.School && stopPurpose <= Global.Settings.Purposes.School)
                        {
                            continue;
                        }

                        if (dayPattern.Tours[tourPurpose] > 0 && dayPattern.Stops[stopPurpose] > 0)
                        {
                            alternative.AddUtilityTerm(1000 + 10 * tourPurpose + stopPurpose, 1); // tour-stop comb. utility
                        }
                    }
                }

                for (int tourPurpose = Global.Settings.Purposes.Work; tourPurpose <= Global.Settings.Purposes.School; tourPurpose++)
                {
                    if (dayPattern.Tours[tourPurpose] == 1 && dayPattern.TotalStops >= 1)
                    {
                        alternative.AddUtilityTerm(1000 + 10 * tourPurpose, purposeLogsums[tourPurpose]);     // usual location logsum x presence of stops in work or school pattern
                        alternative.AddUtilityTerm(1000 + 10 * tourPurpose + 8, compositeLogsum);             // home aggregate logsum x  presence of stops in work or school pattern
                        alternative.AddUtilityTerm(1000 + 10 * tourPurpose + 9, atUsualLogsums[tourPurpose]); // at usual location aggregate logsum x  presence of stops in work or school pattern
                    }
                }

                for (int tourPurpose = Global.Settings.Purposes.Work; tourPurpose <= Global.Settings.Purposes.Social - 2; tourPurpose++)
                {
                    for (int tourPurpose2 = tourPurpose + 1; tourPurpose2 <= Global.Settings.Purposes.Social; tourPurpose2++)
                    {
                        if (dayPattern.Tours[tourPurpose] > 0 && dayPattern.Tours[tourPurpose2] > 0)
                        {
                            alternative.AddUtilityTerm(1100 + 10 * tourPurpose + tourPurpose2, 1); // tour-tour comb. utility
                        }
                    }
                }

                for (int stopPurpose = Global.Settings.Purposes.Work; stopPurpose <= Global.Settings.Purposes.Social - 2; stopPurpose++)
                {
                    for (int stopPurpose2 = stopPurpose + 1; stopPurpose2 <= Global.Settings.Purposes.Social; stopPurpose2++)
                    {
                        if (dayPattern.Stops[stopPurpose] > 0 && dayPattern.Stops[stopPurpose2] > 0)
                        {
                            alternative.AddUtilityTerm(1200 + 10 * stopPurpose + stopPurpose2, 1); // stop-stop comb. utility
                        }
                    }
                }

                if (dayPattern.TotalTours > 0 && dayPattern.TotalStops > 0)
                {
                    int totalStops = dayPattern.TotalStops;

                    if (totalStops > 3)
                    {
                        totalStops = 3;
                    }

                    alternative.AddUtilityTerm(1300 + 10 * dayPattern.TotalTours + totalStops, 1); // nttour-ntstop utility
                }
                if (dayPattern.TotalTours - dayPattern.Tours[Global.Settings.Purposes.Work] - dayPattern.Tours[Global.Settings.Purposes.School] > 0)
                {
                    // tour utility
                    alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(tourComponentIndex));
                }
                if (dayPattern.TotalStops - dayPattern.Stops[Global.Settings.Purposes.Work] - dayPattern.Stops[Global.Settings.Purposes.School] > 0)
                {
                    // stop utility
                    alternative.AddUtilityComponent(choiceProbabilityCalculator.GetUtilityComponent(stopComponentIndex));
                }
            }
        }
Exemple #17
0
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, IPersonDayWrapper personDay, int purpose, int choice = Constants.DEFAULT_VALUE)
        {
            IHouseholdWrapper household       = personDay.Household;
            IParcelWrapper    residenceParcel = household.ResidenceParcel;
            IPersonWrapper    person          = personDay.Person;

            int    carsPerDriver       = household.GetCarsPerDriver();
            double mixedDensity        = residenceParcel.ParcelHouseholdsPerRetailServiceFoodEmploymentBuffer2();
            double intersectionDensity = residenceParcel.IntersectionDensity34Minus1Buffer2();

            double purposeLogsum;

            if (purpose == Global.Settings.Purposes.Work)
            {
                if (person.UsualWorkParcel == null || person.UsualWorkParcelId == household.ResidenceParcelId)
                {
                    purposeLogsum = 0;
                }
                else
                {
                    int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                    int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
                    ChoiceProbabilityCalculator.Alternative nestedAlternative = Global.ChoiceModelSession.Get <WorkTourModeModel>().RunNested(personDay, residenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);

                    purposeLogsum = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
                }
            }
            else if (purpose == Global.Settings.Purposes.School)
            {
                if (person.UsualSchoolParcel == null || person.UsualSchoolParcelId == household.ResidenceParcelId)
                {
                    purposeLogsum = 0;
                }
                else
                {
                    int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
                    int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);
                    ChoiceProbabilityCalculator.Alternative nestedAlternative = Global.ChoiceModelSession.Get <SchoolTourModeModel>().RunNested(personDay, residenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);

                    purposeLogsum = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
                }
            }
            else
            {
                int carOwnership  = person.GetCarOwnershipSegment();
                int votSegment    = person.Household.GetVotALSegment();
                int transitAccess = residenceParcel.TransitAccessSegment();

                purposeLogsum = Global.AggregateLogsums[household.ResidenceZoneId][purpose][carOwnership][votSegment][transitAccess];
            }

            // 1 TOUR

            ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(0, true, choice == 1);

            alternative.Choice = 1;

            alternative.AddUtilityTerm(1, purpose);

            // 2 TOURS

            alternative = choiceProbabilityCalculator.GetAlternative(1, true, choice == 2);

            const int two = 2;

            alternative.Choice = two;

            alternative.AddUtilityTerm(100 * purpose + 1, person.IsFulltimeWorker.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 2, person.IsPartTimeWorker.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 3, person.IsRetiredAdult.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 4, person.IsNonworkingAdult.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 5, person.IsUniversityStudent.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 6, person.IsDrivingAgeStudent.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 7, person.IsChildAge5Through15.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 8, person.IsChildUnder5.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 9, household.Has0To25KIncome.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 10, household.Has25To45KIncome.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 11, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 12, carsPerDriver);
            alternative.AddUtilityTerm(100 * purpose + 13, person.IsOnlyAdult().ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 14, person.IsOnlyFullOrPartTimeWorker().ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 15, 0);
            alternative.AddUtilityTerm(100 * purpose + 16, person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * (!household.HasChildrenUnder16).ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 17, person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenUnder5.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 18, person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenAge5Through15.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 19, person.IsMale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenUnder5.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 20, person.IsMale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenAge5Through15.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 21, person.AgeIsBetween18And25.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 22, person.AgeIsBetween26And35.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 23, person.AgeIsBetween51And65.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 24, person.WorksAtHome().ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 25, mixedDensity);
            alternative.AddUtilityTerm(100 * purpose + 26, intersectionDensity);
            alternative.AddUtilityTerm(100 * purpose + 31, personDay.WorkTours);
            alternative.AddUtilityTerm(100 * purpose + 32, personDay.SchoolTours);
            alternative.AddUtilityTerm(100 * purpose + 33, personDay.EscortTours);
            alternative.AddUtilityTerm(100 * purpose + 34, personDay.PersonalBusinessTours);
            alternative.AddUtilityTerm(100 * purpose + 35, personDay.ShoppingTours);
            alternative.AddUtilityTerm(100 * purpose + 36, personDay.MealTours);
            alternative.AddUtilityTerm(100 * purpose + 37, personDay.SocialTours);
            alternative.AddUtilityTerm(100 * purpose + 41, personDay.WorkStops);

            if (purpose <= Global.Settings.Purposes.Escort)
            {
                alternative.AddUtilityTerm(100 * purpose + 42, personDay.SchoolStops);
            }

            alternative.AddUtilityTerm(100 * purpose + 43, personDay.EscortStops);
            alternative.AddUtilityTerm(100 * purpose + 44, personDay.PersonalBusinessStops);
            alternative.AddUtilityTerm(100 * purpose + 45, personDay.ShoppingStops);
            alternative.AddUtilityTerm(100 * purpose + 46, personDay.MealStops);
            alternative.AddUtilityTerm(100 * purpose + 47, personDay.SocialStops);
            alternative.AddUtilityTerm(100 * purpose + 50 + two, 1);                 // ASC
            alternative.AddUtilityTerm(100 * purpose + 23 + 2 * two, purposeLogsum); // accessibility effect has different coefficient for 2 and 3+

            // 3+ TOURS

            alternative = choiceProbabilityCalculator.GetAlternative(2, true, choice == 3);

            const int three = 3;

            alternative.Choice = three;

            alternative.AddUtilityTerm(100 * purpose + 1, person.IsFulltimeWorker.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 2, person.IsPartTimeWorker.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 3, person.IsRetiredAdult.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 4, person.IsNonworkingAdult.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 5, person.IsUniversityStudent.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 6, person.IsDrivingAgeStudent.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 7, person.IsChildAge5Through15.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 8, person.IsChildUnder5.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 9, household.Has0To25KIncome.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 10, household.Has25To45KIncome.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 11, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 12, carsPerDriver);
            alternative.AddUtilityTerm(100 * purpose + 13, person.IsOnlyAdult().ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 14, person.IsOnlyFullOrPartTimeWorker().ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 15, 0);
            alternative.AddUtilityTerm(100 * purpose + 16, person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * (!household.HasChildrenUnder16).ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 17, person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenUnder5.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 18, person.IsFemale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenAge5Through15.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 19, person.IsMale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenUnder5.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 20, person.IsMale.ToFlag() * person.IsAdult.ToFlag() * household.HasChildrenAge5Through15.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 21, person.AgeIsBetween18And25.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 22, person.AgeIsBetween26And35.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 23, person.AgeIsBetween51And65.ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 24, person.WorksAtHome().ToFlag());
            alternative.AddUtilityTerm(100 * purpose + 25, mixedDensity);
            alternative.AddUtilityTerm(100 * purpose + 26, intersectionDensity);
            alternative.AddUtilityTerm(100 * purpose + 31, personDay.WorkTours);
            alternative.AddUtilityTerm(100 * purpose + 32, personDay.SchoolTours);
            alternative.AddUtilityTerm(100 * purpose + 33, personDay.EscortTours);
            alternative.AddUtilityTerm(100 * purpose + 34, personDay.PersonalBusinessTours);
            alternative.AddUtilityTerm(100 * purpose + 35, personDay.ShoppingTours);
            alternative.AddUtilityTerm(100 * purpose + 36, personDay.MealTours);
            alternative.AddUtilityTerm(100 * purpose + 37, personDay.SocialTours);
            alternative.AddUtilityTerm(100 * purpose + 41, personDay.WorkStops);

            if (purpose <= Global.Settings.Purposes.Escort)
            {
                alternative.AddUtilityTerm(100 * purpose + 42, personDay.SchoolStops);
            }

            alternative.AddUtilityTerm(100 * purpose + 43, personDay.EscortStops);
            alternative.AddUtilityTerm(100 * purpose + 44, personDay.PersonalBusinessStops);
            alternative.AddUtilityTerm(100 * purpose + 45, personDay.ShoppingStops);
            alternative.AddUtilityTerm(100 * purpose + 46, personDay.MealStops);
            alternative.AddUtilityTerm(100 * purpose + 47, personDay.SocialStops);
            alternative.AddUtilityTerm(100 * purpose + 50 + three, 1);                 // ASC
            alternative.AddUtilityTerm(100 * purpose + 23 + 2 * three, purposeLogsum); // accessibility effect has different coefficient for 2 and 3+
        }
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, PersonWrapper person, int choice = Constants.DEFAULT_VALUE)
        {
            Framework.DomainModels.Wrappers.IParcelWrapper homeParcel   = person.Household.ResidenceParcel;
            Framework.DomainModels.Wrappers.IParcelWrapper workParcel   = person.IsUniversityStudent ? person.UsualSchoolParcel : person.UsualWorkParcel;
            Framework.DomainModels.Wrappers.IParcelWrapper schoolParcel = person.IsUniversityStudent ? null : person.UsualSchoolParcel;

            bool workParcelMissing   = workParcel == null;
            bool schoolParcelMissing = schoolParcel == null;

            const double maxTranDist = 1.5;

            double homeTranDist = 99.0;

            if (homeParcel.GetDistanceToTransit() >= 0.0001 && homeParcel.GetDistanceToTransit() <= maxTranDist)
            {
                homeTranDist = homeParcel.GetDistanceToTransit();
            }

            double workTranDist = 99.0;

            if (!workParcelMissing && workParcel.GetDistanceToTransit() >= 0.0001 && workParcel.GetDistanceToTransit() <= maxTranDist)
            {
                workTranDist = workParcel.GetDistanceToTransit();
            }

            double schoolTranDist = 99.0;

            if (!schoolParcelMissing && schoolParcel.GetDistanceToTransit() >= 0.0001 && schoolParcel.GetDistanceToTransit() <= maxTranDist)
            {
                schoolTranDist = schoolParcel.GetDistanceToTransit();
            }

            double workGenTimeNoPass   = -99.0;
            double workGenTimeWithPass = -99.0;

            if (!workParcelMissing && workTranDist < maxTranDist && homeTranDist < maxTranDist)
            {
                IEnumerable <IPathTypeModel> pathTypeModels =
                    PathTypeModelFactory.Singleton.Run(
                        person.Household.RandomUtility,
                        homeParcel,
                        workParcel,
                        Global.Settings.Times.EightAM,
                        Global.Settings.Times.FivePM,
                        Global.Settings.Purposes.Work,
                        Global.Coefficients_BaseCostCoefficientPerMonetaryUnit,
                        Global.Configuration.Coefficients_MeanTimeCoefficient_Work,
                        true,
                        1,
                        0,
                        false,
                        0.0,
                        false,
                        Global.Settings.Modes.Transit);

                IPathTypeModel path = pathTypeModels.First();

                workGenTimeNoPass = path.GeneralizedTimeLogsum;

                // intermediate variable of type IEnumerable<dynamic> is needed to acquire First() method as extension
                pathTypeModels =
                    PathTypeModelFactory.Singleton.Run(
                        person.Household.RandomUtility,
                        homeParcel,
                        workParcel,
                        Global.Settings.Times.EightAM,
                        Global.Settings.Times.FivePM,
                        Global.Settings.Purposes.Work,
                        Global.Coefficients_BaseCostCoefficientPerMonetaryUnit,
                        Global.Configuration.Coefficients_MeanTimeCoefficient_Work,
                        /* isDrivingAge */ true,
                        /* householdCars */ 1,
                        /* transitPassOwnership */ 1,
                        /* carsAreAVs */ false,
                        /* transitDiscountFraction */ 1.0,
                        /* randomChoice */ false,
                        Global.Settings.Modes.Transit);

                path = pathTypeModels.First();

                workGenTimeWithPass = path.GeneralizedTimeLogsum;
            }

            //			double schoolGenTimeNoPass = -99.0;
            double schoolGenTimeWithPass = -99.0;

            if (!schoolParcelMissing && schoolTranDist < maxTranDist && homeTranDist < maxTranDist)
            {
                //				schoolGenTimeNoPass = path.GeneralizedTimeLogsum;

                IEnumerable <IPathTypeModel> pathTypeModels =
                    PathTypeModelFactory.Singleton.Run(
                        person.Household.RandomUtility,
                        homeParcel,
                        schoolParcel,
                        Global.Settings.Times.EightAM,
                        Global.Settings.Times.ThreePM,
                        Global.Settings.Purposes.School,
                        Global.Coefficients_BaseCostCoefficientPerMonetaryUnit,
                        Global.Configuration.Coefficients_MeanTimeCoefficient_Other,
                        true,
                        1,
                        1,
                        false,
                        1.0,
                        false,
                        Global.Settings.Modes.Transit);

                IPathTypeModel path = pathTypeModels.First();
                schoolGenTimeWithPass = path.GeneralizedTimeLogsum;
            }

            const double inflection = 0.50;

            double homeTranDist1 = Math.Pow(Math.Min(inflection, homeTranDist), 2.0);
            double homeTranDist2 = Math.Pow(Math.Max(homeTranDist - inflection, 0), 0.5);

            //			var workTranDist1 = Math.Pow(Math.Min(inflection, workTranDist),2.0);
            //			var workTranDist2 = Math.Pow(Math.Max(workTranDist - inflection, 0),0.5);

            const double minimumAggLogsum = -15.0;
            int          votSegment       = person.Household.GetVotALSegment();

            int    homeTaSegment            = homeParcel.TransitAccessSegment();
            double homeAggregateLogsumNoCar = Math.Max(minimumAggLogsum, Global.AggregateLogsums[homeParcel.ZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votSegment][homeTaSegment]);

            int    workTaSegment            = workParcelMissing ? 0 : workParcel.TransitAccessSegment();
            double workAggregateLogsumNoCar =
                workParcelMissing
                    ? 0
                    : Math.Max(minimumAggLogsum, Global.AggregateLogsums[workParcel.ZoneId][Global.Settings.Purposes.WorkBased][Global.Settings.CarOwnerships.NoCars][votSegment][workTaSegment]);

            int    schoolTaSegment            = schoolParcelMissing ? 0 : schoolParcel.TransitAccessSegment();
            double schoolAggregateLogsumNoCar =
                schoolParcelMissing
                    ? 0
                    : Math.Max(minimumAggLogsum, Global.AggregateLogsums[schoolParcel.ZoneId][Global.Settings.Purposes.WorkBased][Global.Settings.CarOwnerships.NoCars][votSegment][schoolTaSegment]);

            double transitPassCostChange = !Global.Configuration.IsInEstimationMode ? Global.Configuration.PathImpedance_TransitPassCostPercentChangeVersusBase : 0;

            double workTourLogsumDifference   = 0D; // (full or part-time workers) full car ownership vs. no car ownership
            double schoolTourLogsumDifference = 0D; // (school) full car ownership vs. no car ownership

            Framework.DomainModels.Wrappers.IHouseholdWrapper household = person.Household;
            if (person.UsualWorkParcel != null && person.UsualWorkParcelId != household.ResidenceParcelId)
            {
                int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
                //JLB 201602
                //var nestedAlternative1 = Global.ChoiceModelSession.Get<WorkTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, 1.0);
                //var nestedAlternative2 = Global.ChoiceModelSession.Get<WorkTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, 0.0);
                ChoiceProbabilityCalculator.Alternative nestedAlternative1 = Global.ChoiceModelSession.Get <TourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, 1.0, Global.Settings.Purposes.Work);
                ChoiceProbabilityCalculator.Alternative nestedAlternative2 = Global.ChoiceModelSession.Get <TourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, 0.0, Global.Settings.Purposes.Work);

                workTourLogsumDifference = nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
                workTourLogsumDifference = nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
            }

            if (person.UsualSchoolParcel != null && person.UsualSchoolParcelId != household.ResidenceParcelId)
            {
                int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
                int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);

                //JLB 201602
                //var nestedAlternative1 = Global.ChoiceModelSession.Get<SchoolTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, 1.0);
                //var nestedAlternative2 = Global.ChoiceModelSession.Get<SchoolTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, 0.0);
                ChoiceProbabilityCalculator.Alternative nestedAlternative1 = Global.ChoiceModelSession.Get <TourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, 1.0, Global.Settings.Purposes.School);
                ChoiceProbabilityCalculator.Alternative nestedAlternative2 = Global.ChoiceModelSession.Get <TourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable, 0.0, Global.Settings.Purposes.School);

                schoolTourLogsumDifference = nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
                schoolTourLogsumDifference = nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
            }



            //Stefan variables
            double netIncomeNetCarOwnership = Math.Max(0, (person.Household.Income / 1000.0) / 2.0 - 2.441 * 15.0 * person.Household.VehiclesAvailable); //net income minus annual cost to use household's cars in 1000s of DKK
                                                                                                                                                         //set household characteristics here that depend on person characteristics
            int numberAdults   = 0;
            int numberChildren = 0;

            foreach (PersonWrapper p in person.Household.Persons)
            {
                if (p.Age >= 18)
                {
                    numberAdults++;
                }
                else
                {
                    numberChildren++;
                }
            }
            Framework.DomainModels.Wrappers.IParcelWrapper usualParcel = person.IsFullOrPartTimeWorker ? person.UsualWorkParcel : null;
            usualParcel = (usualParcel == null && person.UsualSchoolParcel != null) ? person.UsualSchoolParcel : null;
            int    parkingSearchTime = 0;
            double commuteDistance   = 0.0;
            int    parkingCost       = 0;
            int    model             = 3;

            if (usualParcel != null)
            {
                //parkingSearchTime = usualParcel.PSearchTime07_08; //uncomment when the new parcel attributes have been defined
                commuteDistance = ImpedanceRoster.GetValue("distance", Global.Settings.Modes.Sov, Global.Settings.PathTypes.FullNetwork, 1.0, Global.Settings.Times.EightAM, household.ResidenceParcel, usualParcel).Variable;
                //parkingCost = usualParcel.ParkingCostPerHour8_18;  //uncomment when the new parcel attributes have been defined
                if (person.IsFulltimeWorker && usualParcel == person.UsualWorkParcel)
                {
                    parkingCost = parkingCost * 8;
                    model       = 1;
                }
                else if (person.IsPartTimeWorker && usualParcel == person.UsualWorkParcel)
                {
                    parkingCost = parkingCost * 4;
                    model       = 1;
                }
                else
                {
                    parkingCost = parkingCost * 6; // parking for school
                    model       = 2;
                }
            }


            // 0 No transit pass
            ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(0, true, choice == 0);
            alternative.Choice = 0;

            alternative.AddUtilityTerm(1, 0.0);

            // 1 Transit pass

            double stefanUtility = 0.0;

            alternative        = choiceProbabilityCalculator.GetAlternative(1, true, choice == 1);
            alternative.Choice = 1;

            if (model == 1 && person.Household.VehiclesAvailable == 0)
            {
                double beta001 = -0.33;
                double beta002 = -0.34;
                double beta003 = -1.15;
                double beta004 = -0.34;
                double beta005 = 0.0;
                double beta006 = 0.0;
                double beta007 = 0.0;
                double beta008 = 0.0;
                double beta009 = 0.0;
                double beta010 = 0.0;
                double beta011 = 0.0;
                double beta012 = 0.0;
                stefanUtility =
                    beta001 * 1.0 +
                    beta002 * numberChildren +
                    beta003 * netIncomeNetCarOwnership +
                    beta004 * person.IsMale.ToFlag() +
                    beta005 * (person.IsAdultFemale && numberAdults == 1).ToFlag() +
                    beta006 * (person.IsAdultFemale && numberAdults > 1).ToFlag() +
                    beta007 * person.Age +
                    beta008 * Math.Pow(person.Age, 2.0) +
                    beta009 * (person.Household.VehiclesAvailable >= 2).ToFlag() +
                    beta010 * (person.IsAdultMale && numberAdults == 1).ToFlag() +
                    beta011 * Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0) +
                    beta012 * Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus) +
                    0.0;
                //Stefan utility
                //alternative.AddUtilityTerm(1, 1.0);
                //alternative.AddUtilityTerm(2, numberChildren);
                //alternative.AddUtilityTerm(3, netIncomeNetCarOwnership);
                //alternative.AddUtilityTerm(4, person.IsMale.ToFlag());
                //alternative.AddUtilityTerm(5, (person.IsAdultFemale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(6, (person.IsAdultFemale && numberAdults > 1).ToFlag());
                //alternative.AddUtilityTerm(7, person.Age);
                //alternative.AddUtilityTerm(8, Math.Pow(person.Age, 2.0));
                //non-worker/non-student models only
                //alternative.AddUtilityTerm(9, (person.Household.VehiclesAvailable >= 2).ToFlag());
                //alternative.AddUtilityTerm(10, (person.IsAdultMale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(11, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0));
                //alternative.AddUtilityTerm(12, Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(1, stefanUtility); // this composite replaces terms *1-*12 above

                //Stefan impedance (try replacign these with logsums)
                alternative.AddUtilityTerm(13, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(14, (commuteDistance > 0 && commuteDistance < 3).ToFlag());
                alternative.AddUtilityTerm(15, (commuteDistance >= 7 && commuteDistance < 13).ToFlag());
                alternative.AddUtilityTerm(16, (commuteDistance >= 13).ToFlag());
                alternative.AddUtilityTerm(17, parkingCost);
                alternative.AddUtilityTerm(18, parkingSearchTime);
                //commute logsum difference variable (with and without transit pass)
                alternative.AddUtilityTerm(19, workTourLogsumDifference);
            }
            else if (model == 1 && person.Household.VehiclesAvailable == 1)
            {
                double beta101 = -1.16;
                int    beta102 = 0;
                int    beta103 = 0;
                int    beta104 = 0;
                int    beta105 = 0;
                double beta106 = 0.63;
                double beta107 = -0.76;
                double beta108 = 0.09;
                int    beta109 = 0;
                int    beta110 = 0;
                int    beta111 = 0;
                int    beta112 = 0;
                stefanUtility =
                    beta101 * 1.0 +
                    beta102 * numberChildren +
                    beta103 * netIncomeNetCarOwnership +
                    beta104 * person.IsMale.ToFlag() +
                    beta105 * (person.IsAdultFemale && numberAdults == 1).ToFlag() +
                    beta106 * (person.IsAdultFemale && numberAdults > 1).ToFlag() +
                    beta107 * person.Age +
                    beta108 * Math.Pow(person.Age, 2.0) +
                    beta109 * (person.Household.VehiclesAvailable >= 2).ToFlag() +
                    beta110 * (person.IsAdultMale && numberAdults == 1).ToFlag() +
                    beta111 * Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0) +
                    beta112 * Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus) +
                    0.0;
                //Stefan utility
                //alternative.AddUtilityTerm(101, 1.0);
                //alternative.AddUtilityTerm(102, numberChildren);
                //alternative.AddUtilityTerm(103, netIncomeNetCarOwnership);
                //alternative.AddUtilityTerm(104, person.IsMale.ToFlag());
                //alternative.AddUtilityTerm(105, (person.IsAdultFemale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(106, (person.IsAdultFemale && numberAdults > 1).ToFlag());
                //alternative.AddUtilityTerm(107, person.Age);
                //alternative.AddUtilityTerm(108, Math.Pow(person.Age, 2.0));
                ////non-worker/non-student models only
                //alternative.AddUtilityTerm(109, (person.Household.VehiclesAvailable >= 2).ToFlag());
                //alternative.AddUtilityTerm(110, (person.IsAdultMale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(111, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0));
                //alternative.AddUtilityTerm(112, Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(101, stefanUtility); // this composite replaces terms *1-*12 above
                                                                //Stefan impedance (try replacign these with logsums)
                alternative.AddUtilityTerm(113, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(114, (commuteDistance > 0 && commuteDistance < 3).ToFlag());
                alternative.AddUtilityTerm(115, (commuteDistance >= 7 && commuteDistance < 13).ToFlag());
                alternative.AddUtilityTerm(116, (commuteDistance >= 13).ToFlag());
                alternative.AddUtilityTerm(117, parkingCost);
                alternative.AddUtilityTerm(118, parkingSearchTime);
                //commute logsum difference variable (with and without transit pass)
                alternative.AddUtilityTerm(119, workTourLogsumDifference);
            }
            else if (model == 1 && person.Household.VehiclesAvailable >= 2)
            {
                double beta201 = -0.54;
                int    beta202 = 0;
                int    beta203 = 0;
                int    beta204 = 0;
                double beta205 = 1.35;
                double beta206 = 0.42;
                double beta207 = -1.5;
                double beta208 = 0.17;
                int    beta209 = 0;
                int    beta210 = 0;
                int    beta211 = 0;
                int    beta212 = 0;
                stefanUtility =
                    beta201 * 1.0 +
                    beta202 * numberChildren +
                    beta203 * netIncomeNetCarOwnership +
                    beta204 * person.IsMale.ToFlag() +
                    beta205 * (person.IsAdultFemale && numberAdults == 1).ToFlag() +
                    beta206 * (person.IsAdultFemale && numberAdults > 1).ToFlag() +
                    beta207 * person.Age +
                    beta208 * Math.Pow(person.Age, 2.0) +
                    beta209 * (person.Household.VehiclesAvailable >= 2).ToFlag() +
                    beta210 * (person.IsAdultMale && numberAdults == 1).ToFlag() +
                    beta211 * Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0) +
                    beta212 * Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus) +
                    0.0;
                //Stefan utility
                //alternative.AddUtilityTerm(201, 1.0);
                //alternative.AddUtilityTerm(202, numberChildren);
                //alternative.AddUtilityTerm(203, netIncomeNetCarOwnership);
                //alternative.AddUtilityTerm(204, person.IsMale.ToFlag());
                //alternative.AddUtilityTerm(205, (person.IsAdultFemale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(206, (person.IsAdultFemale && numberAdults > 1).ToFlag());
                //alternative.AddUtilityTerm(207, person.Age);
                //alternative.AddUtilityTerm(208, Math.Pow(person.Age, 2.0));
                //non-worker/non-student models only
                //alternative.AddUtilityTerm(209, (person.Household.VehiclesAvailable >= 2).ToFlag());
                //alternative.AddUtilityTerm(210, (person.IsAdultMale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(211, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0));
                //alternative.AddUtilityTerm(212, Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(201, stefanUtility); // this composite replaces terms *1-*12 above
                                                                //Stefan impedance (try replacign these with logsums)
                alternative.AddUtilityTerm(213, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(214, (commuteDistance > 0 && commuteDistance < 3).ToFlag());
                alternative.AddUtilityTerm(215, (commuteDistance >= 7 && commuteDistance < 13).ToFlag());
                alternative.AddUtilityTerm(216, (commuteDistance >= 13).ToFlag());
                alternative.AddUtilityTerm(217, parkingCost);
                alternative.AddUtilityTerm(218, parkingSearchTime);
                //commute logsum difference variable (with and without transit pass)
                alternative.AddUtilityTerm(219, workTourLogsumDifference);
            }
            else if (model == 2 && person.Household.VehiclesAvailable == 0)
            {
                double beta301 = 4.74;
                double beta302 = 0.39;
                int    beta303 = 0;
                int    beta304 = 0;
                int    beta305 = 0;
                int    beta306 = 0;
                double beta307 = -3.95;
                double beta308 = 0.62;
                int    beta309 = 0;
                int    beta310 = 0;
                int    beta311 = 0;
                int    beta312 = 0;
                stefanUtility =
                    beta301 * 1.0 +
                    beta302 * numberChildren +
                    beta303 * netIncomeNetCarOwnership +
                    beta304 * person.IsMale.ToFlag() +
                    beta305 * (person.IsAdultFemale && numberAdults == 1).ToFlag() +
                    beta306 * (person.IsAdultFemale && numberAdults > 1).ToFlag() +
                    beta307 * person.Age +
                    beta308 * Math.Pow(person.Age, 2.0) +
                    beta309 * (person.Household.VehiclesAvailable >= 2).ToFlag() +
                    beta310 * (person.IsAdultMale && numberAdults == 1).ToFlag() +
                    beta311 * Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0) +
                    beta312 * Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus) +
                    0.0;
                //Stefan utility
                //alternative.AddUtilityTerm(301, 1.0);
                //alternative.AddUtilityTerm(302, numberChildren);
                //alternative.AddUtilityTerm(303, netIncomeNetCarOwnership);
                //alternative.AddUtilityTerm(304, person.IsMale.ToFlag());
                //alternative.AddUtilityTerm(305, (person.IsAdultFemale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(306, (person.IsAdultFemale && numberAdults > 1).ToFlag());
                //alternative.AddUtilityTerm(307, person.Age);
                //alternative.AddUtilityTerm(308, Math.Pow(person.Age, 2.0));
                ////non-worker/non-student models only
                //alternative.AddUtilityTerm(309, (person.Household.VehiclesAvailable >= 2).ToFlag());
                //alternative.AddUtilityTerm(310, (person.IsAdultMale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(311, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0));
                //alternative.AddUtilityTerm(312, Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(301, stefanUtility); // this composite replaces terms *1-*12 above
                                                                //Stefan impedance (try replacign these with logsums)
                alternative.AddUtilityTerm(313, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(314, (commuteDistance > 0 && commuteDistance < 3).ToFlag());
                alternative.AddUtilityTerm(315, (commuteDistance >= 7 && commuteDistance < 13).ToFlag());
                alternative.AddUtilityTerm(316, (commuteDistance >= 13).ToFlag());
                alternative.AddUtilityTerm(317, parkingCost);
                alternative.AddUtilityTerm(318, parkingSearchTime);
                //commute logsum difference variable (with and without transit pass)
                alternative.AddUtilityTerm(319, schoolTourLogsumDifference);
            }
            else if (model == 2 && person.Household.VehiclesAvailable >= 1)
            {
                double beta401 = 3.75;
                int    beta402 = 0;
                int    beta403 = 0;
                int    beta404 = 0;
                int    beta405 = 0;
                int    beta406 = 0;
                double beta407 = 2.81;
                double beta408 = 0.33;
                int    beta409 = 0;
                int    beta410 = 0;
                int    beta411 = 0;
                int    beta412 = 0;
                stefanUtility =
                    beta401 * 1.0 +
                    beta402 * numberChildren +
                    beta403 * netIncomeNetCarOwnership +
                    beta404 * person.IsMale.ToFlag() +
                    beta405 * (person.IsAdultFemale && numberAdults == 1).ToFlag() +
                    beta406 * (person.IsAdultFemale && numberAdults > 1).ToFlag() +
                    beta407 * person.Age +
                    beta408 * Math.Pow(person.Age, 2.0) +
                    beta409 * (person.Household.VehiclesAvailable >= 2).ToFlag() +
                    beta410 * (person.IsAdultMale && numberAdults == 1).ToFlag() +
                    beta411 * Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0) +
                    beta412 * Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus) +
                    0.0;
                //Stefan utility
                //alternative.AddUtilityTerm(401, 1.0);
                //alternative.AddUtilityTerm(402, numberChildren);
                //alternative.AddUtilityTerm(403, netIncomeNetCarOwnership);
                //alternative.AddUtilityTerm(404, person.IsMale.ToFlag());
                //alternative.AddUtilityTerm(405, (person.IsAdultFemale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(406, (person.IsAdultFemale && numberAdults > 1).ToFlag());
                //alternative.AddUtilityTerm(407, person.Age);
                //alternative.AddUtilityTerm(408, Math.Pow(person.Age, 2.0));
                ////non-worker/non-student models only
                //alternative.AddUtilityTerm(409, (person.Household.VehiclesAvailable >= 2).ToFlag());
                //alternative.AddUtilityTerm(410, (person.IsAdultMale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(411, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0));
                //alternative.AddUtilityTerm(412, Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(401, stefanUtility); // this composite replaces terms *1-*12 above
                                                                //Stefan impedance (try replacign these with logsums)
                alternative.AddUtilityTerm(413, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(414, (commuteDistance > 0 && commuteDistance < 3).ToFlag());
                alternative.AddUtilityTerm(415, (commuteDistance >= 7 && commuteDistance < 13).ToFlag());
                alternative.AddUtilityTerm(416, (commuteDistance >= 13).ToFlag());
                alternative.AddUtilityTerm(417, parkingCost);
                alternative.AddUtilityTerm(418, parkingSearchTime);
                //commute logsum difference variable (with and without transit pass)
                alternative.AddUtilityTerm(419, schoolTourLogsumDifference);
            }
            else if (model == 3 && person.Household.VehiclesAvailable == 0)
            {
                double beta501 = 0.05;
                int    beta502 = 0;
                int    beta503 = 0;
                int    beta504 = 0;
                double beta505 = 0.56;
                double beta506 = 0.41;
                int    beta507 = 0;
                int    beta508 = 0;
                int    beta509 = 0;
                int    beta510 = 0;
                double beta511 = -0.45;
                int    beta512 = 0;
                stefanUtility =
                    beta501 * 1.0 +
                    beta502 * numberChildren +
                    beta503 * netIncomeNetCarOwnership +
                    beta504 * person.IsMale.ToFlag() +
                    beta505 * (person.IsAdultFemale && numberAdults == 1).ToFlag() +
                    beta506 * (person.IsAdultFemale && numberAdults > 1).ToFlag() +
                    beta507 * person.Age +
                    beta508 * Math.Pow(person.Age, 2.0) +
                    beta509 * (person.Household.VehiclesAvailable >= 2).ToFlag() +
                    beta510 * (person.IsAdultMale && numberAdults == 1).ToFlag() +
                    beta511 * Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0) +
                    beta512 * Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus) +
                    0.0;
                //Stefan utility
                //alternative.AddUtilityTerm(501, 1.0);
                //alternative.AddUtilityTerm(502, numberChildren);
                //alternative.AddUtilityTerm(503, netIncomeNetCarOwnership);
                //alternative.AddUtilityTerm(504, person.IsMale.ToFlag());
                //alternative.AddUtilityTerm(505, (person.IsAdultFemale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(506, (person.IsAdultFemale && numberAdults > 1).ToFlag());
                //alternative.AddUtilityTerm(507, person.Age);
                //alternative.AddUtilityTerm(508, Math.Pow(person.Age, 2.0));
                ////non-worker/non-student models only
                //alternative.AddUtilityTerm(509, (person.Household.VehiclesAvailable >= 2).ToFlag());
                //alternative.AddUtilityTerm(510, (person.IsAdultMale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(511, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0));
                //alternative.AddUtilityTerm(512, Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(501, stefanUtility); // this composite replaces terms *1-*12 above
            }
            else //(model == 3 && person.Household.VehiclesAvailable >= 1)
            {
                double beta601 = -1.7;
                int    beta602 = 0;
                double beta603 = 0.47;
                int    beta604 = 0;
                double beta605 = 0.63;
                double beta606 = 0.46;
                int    beta607 = 0;
                int    beta608 = 0;
                double beta609 = -0.32;
                double beta610 = 0.35;
                double beta611 = -0.37;
                double beta612 = -0.09;
                stefanUtility =
                    beta601 * 1.0 +
                    beta602 * numberChildren +
                    beta603 * netIncomeNetCarOwnership +
                    beta604 * person.IsMale.ToFlag() +
                    beta605 * (person.IsAdultFemale && numberAdults == 1).ToFlag() +
                    beta606 * (person.IsAdultFemale && numberAdults > 1).ToFlag() +
                    beta607 * person.Age +
                    beta608 * Math.Pow(person.Age, 2.0) +
                    beta609 * (person.Household.VehiclesAvailable >= 2).ToFlag() +
                    beta610 * (person.IsAdultMale && numberAdults == 1).ToFlag() +
                    beta611 * Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0) +
                    beta612 * Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus) +
                    0.0;
                //Stefan utility
                //alternative.AddUtilityTerm(601, 1.0);
                //alternative.AddUtilityTerm(602, numberChildren);
                //alternative.AddUtilityTerm(603, netIncomeNetCarOwnership);
                //alternative.AddUtilityTerm(604, person.IsMale.ToFlag());
                //alternative.AddUtilityTerm(605, (person.IsAdultFemale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(606, (person.IsAdultFemale && numberAdults > 1).ToFlag());
                //alternative.AddUtilityTerm(607, person.Age);
                //alternative.AddUtilityTerm(608, Math.Pow(person.Age, 2.0));
                //non-worker/non-student models only
                //alternative.AddUtilityTerm(609, (person.Household.VehiclesAvailable >= 2).ToFlag());
                //alternative.AddUtilityTerm(610, (person.IsAdultMale && numberAdults == 1).ToFlag());
                //alternative.AddUtilityTerm(611, Math.Min(person.Household.ResidenceParcel.DistanceToLocalBus, 2.0));
                //alternative.AddUtilityTerm(612, Math.Min(5.0, person.Household.ResidenceParcel.DistanceToExpressBus));
                alternative.AddUtilityTerm(601, stefanUtility); // this composite replaces terms *1-*12 above
            }

            //alternative.AddUtilityTerm(2, person.IsPartTimeWorker.ToFlag());
            //alternative.AddUtilityTerm(3, (person.IsWorker && person.IsNotFullOrPartTimeWorker).ToFlag());
            //alternative.AddUtilityTerm(4, person.IsUniversityStudent.ToFlag());
            //alternative.AddUtilityTerm(5, person.IsRetiredAdult.ToFlag());
            //alternative.AddUtilityTerm(6, person.IsNonworkingAdult.ToFlag());
            //alternative.AddUtilityTerm(7, person.IsDrivingAgeStudent.ToFlag());
            //alternative.AddUtilityTerm(8, person.IsChildUnder16.ToFlag());
            //alternative.AddUtilityTerm(9, Math.Log(Math.Max(1, person.Household.Income)));
            //alternative.AddUtilityTerm(10, person.Household.HasMissingIncome.ToFlag());
            //alternative.AddUtilityTerm(11, workParcelMissing.ToFlag());
            //alternative.AddUtilityTerm(12, schoolParcelMissing.ToFlag());
            //alternative.AddUtilityTerm(13, (homeTranDist < 90.0) ? homeTranDist1 : 0);
            //alternative.AddUtilityTerm(14, (homeTranDist < 90.0) ? homeTranDist2 : 0);
            //alternative.AddUtilityTerm(15, (homeTranDist > 90.0) ? 1 : 0);
            //			//alternative.AddUtility(16, (workTranDist < 90.0) ? workTranDist : 0);
            //			//alternative.AddUtility(17, (workTranDist < 90.0) ? workTranDist2 : 0);
            //			//alternative.AddUtility(18, (workTranDist > 90.0) ? 1 : 0);
            //			//alternative.AddUtility(19, (schoolTranDist < 90.0) ? schoolTranDist : 0);
            //			//alternative.AddUtility(20, (schoolTranDist > 90.0) ? 1 : 0);
            //			//alternative.AddUtility(21, (!workParcelMissing && workGenTimeWithPass > -90 ) ? workGenTimeWithPass : 0);
            //alternative.AddUtilityTerm(22, (!workParcelMissing && workGenTimeWithPass <= -90) ? 1 : 0);
            //alternative.AddUtilityTerm(23, (!workParcelMissing && workGenTimeWithPass > -90 && workGenTimeNoPass > -90) ? workGenTimeNoPass - workGenTimeWithPass : 0);
            //			//alternative.AddUtility(24, (!schoolParcelMissing && schoolGenTimeWithPass > -90 ) ? schoolGenTimeWithPass : 0);
            //alternative.AddUtilityTerm(25, (!schoolParcelMissing && schoolGenTimeWithPass <= -90) ? 1 : 0);
            //alternative.AddUtilityTerm(26, homeAggregateLogsumNoCar * (person.IsFullOrPartTimeWorker || person.IsUniversityStudent).ToFlag());
            //alternative.AddUtilityTerm(27, homeAggregateLogsumNoCar * (person.IsDrivingAgeStudent || person.IsChildUnder16).ToFlag());
            //alternative.AddUtilityTerm(28, homeAggregateLogsumNoCar * (person.IsNonworkingAdult).ToFlag());
            //alternative.AddUtilityTerm(29, homeAggregateLogsumNoCar * (person.IsRetiredAdult).ToFlag());
            //alternative.AddUtilityTerm(30, workParcelMissing ? 0 : workAggregateLogsumNoCar);
            //alternative.AddUtilityTerm(31, schoolParcelMissing ? 0 : schoolAggregateLogsumNoCar);
            //alternative.AddUtilityTerm(32, transitPassCostChange);
        }
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, IPersonDayWrapper personDay, IHouseholdDayWrapper householdDay, int maxPurpose, int choice = Constants.DEFAULT_VALUE)
        {
            IEnumerable <PersonDayWrapper> orderedPersonDays = householdDay.PersonDays.OrderBy(p => p.GetJointTourParticipationPriority()).ToList().Cast <PersonDayWrapper>();

            IPersonWrapper    person          = personDay.Person;
            IHouseholdWrapper household       = householdDay.Household;
            IParcelWrapper    residenceParcel = household.ResidenceParcel;

            int carOwnership =
                household.VehiclesAvailable == 0
                                 ? Global.Settings.CarOwnerships.NoCars
                                 : household.VehiclesAvailable < household.HouseholdTotals.DrivingAgeMembers
                                      ? Global.Settings.CarOwnerships.LtOneCarPerAdult
                                      : Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult;

            int noCarsFlag         = FlagUtility.GetNoCarsFlag(carOwnership);
            int carCompetitionFlag = FlagUtility.GetCarCompetitionFlag(carOwnership);

            int    votALSegment                    = household.GetVotALSegment();
            int    transitAccessSegment            = household.ResidenceParcel.TransitAccessSegment();
            double personalBusinessAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                                     [Global.Settings.Purposes.PersonalBusiness][carOwnership][votALSegment][transitAccessSegment];
            double shoppingAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                             [Global.Settings.Purposes.Shopping][carOwnership][votALSegment][transitAccessSegment];
            double mealAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                         [Global.Settings.Purposes.Meal][carOwnership][votALSegment][transitAccessSegment];
            double socialAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                           [Global.Settings.Purposes.Social][carOwnership][votALSegment][transitAccessSegment];
            double totalAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
                                          [Global.Settings.Purposes.HomeBasedComposite][carOwnership][votALSegment][transitAccessSegment];

            // var recreationAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
            // [Global.Settings.Purposes.Recreation][carOwnership][votALSegment][transitAccessSegment];
            //  var medicalAggregateLogsum = Global.AggregateLogsums[household.ResidenceParcel.ZoneId]
            //  [Global.Settings.Purposes.Medical][carOwnership][votALSegment][transitAccessSegment];

            int[] nonMandPerstype = new int[8];
            int[] mandPerstype    = new int[8];

            //int mandatoryAdult=0;
            //int mandatoryChild=0;
            //int nonMandatoryWorker=0;
            //int nonMandatoryNonWorker=0;
            //int nonMandatoryRetired=0;
            //int nonMandatoryChild=0;

            int countNonMandatory = 0;
            int countMandatory    = 0;

            double workLogsum   = 0;
            double schoolLogsum = 0;

            //int worksAtHome=0;
            int countWorkingAtHome = 0;

            int workDestinationArrivalTime   = 0;
            int workDestinationDepartureTime = 0;

            int numStopPurposes = 0;
            int numTourPurposes = 0;

            numTourPurposes = (personDay.CreatedEscortTours > 1).ToFlag() + (personDay.CreatedShoppingTours > 1).ToFlag() + (personDay.CreatedMealTours > 1).ToFlag() +
                              (personDay.CreatedPersonalBusinessTours > 1).ToFlag() + (personDay.CreatedSocialTours > 1).ToFlag() +
                              (personDay.CreatedRecreationTours > 1).ToFlag() + (personDay.CreatedMedicalTours > 1).ToFlag();


            numStopPurposes = (personDay.SimulatedEscortStops > 1).ToFlag() + (personDay.SimulatedShoppingStops > 1).ToFlag() + (personDay.SimulatedMealStops > 1).ToFlag() +
                              (personDay.SimulatedPersonalBusinessStops > 1).ToFlag() + (personDay.SimulatedSocialStops > 1).ToFlag() +
                              (personDay.SimulatedRecreationStops > 1).ToFlag() + (personDay.SimulatedMedicalStops > 1).ToFlag();


            if (person.UsualWorkParcel == null || person.UsualWorkParcelId == household.ResidenceParcelId)
            {
                workLogsum = 0;
            }
            else
            {
                workDestinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                workDestinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
                ChoiceProbabilityCalculator.Alternative nestedAlternative = Global.ChoiceModelSession.Get <WorkTourModeTimeModel>().RunNested(personDay, residenceParcel, person.UsualWorkParcel, workDestinationArrivalTime, workDestinationDepartureTime, household.VehiclesAvailable);

                workLogsum = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
            }

            if (person.UsualSchoolParcel == null || person.UsualSchoolParcelId == household.ResidenceParcelId)
            {
                schoolLogsum = 0;
            }
            else
            {
                int destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
                int destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);
                ChoiceProbabilityCalculator.Alternative nestedAlternative = Global.ChoiceModelSession.Get <SchoolTourModeTimeModel>().RunNested(personDay, residenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.VehiclesAvailable);

                schoolLogsum = nestedAlternative == null ? 0 : nestedAlternative.ComputeLogsum();
            }

            //if (personDay.WorksAtHomeFlag == 1) {
            //    worksAtHome =1;
            //}


            int count = 0;

            foreach (PersonDayWrapper pDay in orderedPersonDays)
            {
                count++;
                if (count > 8)
                {
                    break;
                }
                if (pDay.WorksAtHomeFlag == 1)
                {
                    countWorkingAtHome++;
                }
                if (pDay.PatternType == 1)
                {
                    countMandatory++;
                }
                if (pDay.PatternType == 2)
                {
                    countNonMandatory++;
                }
            }


            // NONE_OR_HOME

            ChoiceProbabilityCalculator.Alternative alternative = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.NoneOrHome, true, choice == Global.Settings.Purposes.NoneOrHome);

            alternative.Choice = Global.Settings.Purposes.NoneOrHome;
            //alternative.AddUtilityTerm(2, (personDay.GetTotalCreatedTours()== 2).ToFlag());
            //alternative.AddUtilityTerm(3,  (personDay.GetTotalCreatedTours()==3).ToFlag());
            alternative.AddUtilityTerm(4, (personDay.GetTotalCreatedTours() >= 4).ToFlag());
            alternative.AddUtilityTerm(5, (numStopPurposes >= 1).ToFlag());
            alternative.AddUtilityTerm(6, (numTourPurposes >= 2).ToFlag());
            alternative.AddUtilityTerm(7, personDay.CreatedWorkTours + personDay.CreatedSchoolTours);
            alternative.AddUtilityTerm(8, (personDay.JointTours));
            alternative.AddUtilityTerm(9, Math.Log(1 + (workDestinationDepartureTime - workDestinationArrivalTime) / 60));
            //alternative.AddUtilityTerm(10,  (household.Size==1).ToFlag());
            //alternative.AddNestedAlternative(11, 0, 200);

            // WORK
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Work, false, choice == Global.Settings.Purposes.Work);
            alternative.Choice = Global.Settings.Purposes.Work;
            alternative.AddUtilityTerm(198, 1);
            //alternative.AddNestedAlternative(12, 1, 200);

            //  SCHOOL
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.School, false, choice == Global.Settings.Purposes.School);
            alternative.Choice = Global.Settings.Purposes.School;
            alternative.AddUtilityTerm(199, 1);
            //alternative.AddNestedAlternative(12, 1, 200);

            // ESCORT
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Escort, maxPurpose <= Global.Settings.Purposes.Escort && personDay.CreatedEscortTours > 0, choice == Global.Settings.Purposes.Escort);
            alternative.Choice = Global.Settings.Purposes.Escort;

            alternative.AddUtilityTerm(11, 1);
            alternative.AddUtilityTerm(12, (personDay.PatternType == 2).ToFlag());
            alternative.AddUtilityTerm(13, personDay.JointTours);
            alternative.AddUtilityTerm(14, (personDay.EscortStops > 0).ToFlag());
            alternative.AddUtilityTerm(15, (personDay.CreatedEscortTours > 1).ToFlag());
            alternative.AddUtilityTerm(17, (household.HouseholdType == Global.Settings.HouseholdTypes.TwoPlusWorkerStudentAdultsWithChildren).ToFlag() + (
                                           household.HouseholdType == Global.Settings.HouseholdTypes.TwoPlusAdultsOnePlusWorkersStudentsWithChildren).ToFlag());
            alternative.AddUtilityTerm(20, (household.HouseholdType == Global.Settings.HouseholdTypes.OneAdultWithChildren).ToFlag());
            alternative.AddUtilityTerm(25, (person.PersonType == Global.Settings.PersonTypes.PartTimeWorker).ToFlag());
            alternative.AddUtilityTerm(28, (person.PersonType == Global.Settings.PersonTypes.ChildUnder5).ToFlag());
            alternative.AddUtilityTerm(29, (person.PersonType == Global.Settings.PersonTypes.ChildAge5Through15).ToFlag());
            alternative.AddUtilityTerm(31, (person.PersonType == Global.Settings.PersonTypes.UniversityStudent).ToFlag());
            alternative.AddUtilityTerm(32, countMandatory);
            // alternative.AddUtilityTerm(33, personDay.CreatedWorkTours);

            //alternative.AddNestedAlternative(12, 1, 200);

            // PERSONAL_BUSINESS
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.PersonalBusiness, maxPurpose <= Global.Settings.Purposes.PersonalBusiness && personDay.CreatedPersonalBusinessTours > 0, choice == Global.Settings.Purposes.PersonalBusiness);
            alternative.Choice = Global.Settings.Purposes.PersonalBusiness;
            alternative.AddUtilityTerm(41, 1);
            alternative.AddUtilityTerm(42, (personDay.PatternType == 2).ToFlag());
            alternative.AddUtilityTerm(43, (personDay.PersonalBusinessStops > 0).ToFlag());
            alternative.AddUtilityTerm(44, personalBusinessAggregateLogsum);
            alternative.AddUtilityTerm(45, (household.HouseholdType == Global.Settings.HouseholdTypes.IndividualWorkerStudent).ToFlag());
            alternative.AddUtilityTerm(46, (household.HouseholdType == Global.Settings.HouseholdTypes.IndividualNonworkerNonstudent).ToFlag());
            alternative.AddUtilityTerm(47, (personDay.CreatedWorkTours + personDay.CreatedSchoolTours));


            // SHOPPING
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Shopping, maxPurpose <= Global.Settings.Purposes.Shopping && personDay.CreatedShoppingTours > 0, choice == Global.Settings.Purposes.Shopping);
            alternative.Choice = Global.Settings.Purposes.Shopping;

            alternative.AddUtilityTerm(61, 1);
            alternative.AddUtilityTerm(52, (personDay.PatternType == 2).ToFlag());
            alternative.AddUtilityTerm(54, (personDay.ShoppingStops > 0).ToFlag());
            //alternative.AddUtilityTerm(55, Math.Log(1+person.Household.ResidenceParcel.EmploymentRetailBuffer2));
            alternative.AddUtilityTerm(56, shoppingAggregateLogsum);
            alternative.AddUtilityTerm(57, (person.PersonType == Global.Settings.PersonTypes.RetiredAdult).ToFlag());
            alternative.AddUtilityTerm(58, (household.HouseholdType == Global.Settings.HouseholdTypes.OnePlusWorkerStudentAdultsAndOnePlusNonworkerNonstudentAdultsWithoutChildren).ToFlag());
            alternative.AddUtilityTerm(60, (household.HouseholdType == Global.Settings.HouseholdTypes.IndividualWorkerStudent).ToFlag());
            alternative.AddUtilityTerm(69, (person.PersonType == Global.Settings.PersonTypes.UniversityStudent).ToFlag());
            alternative.AddUtilityTerm(70, (household.Has100KPlusIncome).ToFlag());

            // MEAL
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Meal, maxPurpose <= Global.Settings.Purposes.Meal && personDay.CreatedMealTours > 0, choice == Global.Settings.Purposes.Meal);
            alternative.Choice = Global.Settings.Purposes.Meal;
            alternative.AddUtilityTerm(71, 1);
            alternative.AddUtilityTerm(72, (personDay.PatternType == 2).ToFlag());
            alternative.AddUtilityTerm(74, mealAggregateLogsum);
            alternative.AddUtilityTerm(80, (household.HouseholdType == Global.Settings.HouseholdTypes.IndividualWorkerStudent).ToFlag());
            alternative.AddUtilityTerm(82, (household.HouseholdType == Global.Settings.HouseholdTypes.TwoPlusNonworkerNonstudentAdultsWithoutChildren).ToFlag());
            alternative.AddUtilityTerm(85, (person.PersonType == Global.Settings.PersonTypes.RetiredAdult).ToFlag());

            // SOCIAL
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Social, maxPurpose <= Global.Settings.Purposes.Social && personDay.CreatedSocialTours > 0, choice == Global.Settings.Purposes.Social);
            alternative.Choice = Global.Settings.Purposes.Social;

            alternative.AddUtilityTerm(111, 1);
            alternative.AddUtilityTerm(112, (personDay.PatternType == 2).ToFlag());
            alternative.AddUtilityTerm(113, household.HouseholdTotals.ChildrenUnder16);
            //alternative.AddUtilityTerm(114, socialAggregateLogsum);
            alternative.AddUtilityTerm(115, Math.Log(1 + person.Household.ResidenceParcel.HouseholdsBuffer2));
            alternative.AddUtilityTerm(122, (household.HouseholdType == Global.Settings.HouseholdTypes.TwoPlusNonworkerNonstudentAdultsWithoutChildren).ToFlag());
            alternative.AddUtilityTerm(123, (person.PersonType == Global.Settings.PersonTypes.PartTimeWorker).ToFlag());
            alternative.AddUtilityTerm(126, (person.PersonType == Global.Settings.PersonTypes.ChildUnder5).ToFlag());
            alternative.AddUtilityTerm(127, (person.PersonType == Global.Settings.PersonTypes.ChildAge5Through15).ToFlag());
            alternative.AddUtilityTerm(130, (person.PersonType == Global.Settings.PersonTypes.RetiredAdult).ToFlag());

            // RECREATION
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Recreation, maxPurpose <= Global.Settings.Purposes.Recreation && personDay.CreatedRecreationTours > 0, choice == Global.Settings.Purposes.Recreation);
            alternative.Choice = Global.Settings.Purposes.Recreation;
            alternative.AddUtilityTerm(111, 1);
            alternative.AddUtilityTerm(112, (personDay.PatternType == 2).ToFlag());
            alternative.AddUtilityTerm(113, household.HouseholdTotals.ChildrenUnder16);
            //alternative.AddUtilityTerm(114, totalAggregateLogsum);
            alternative.AddUtilityTerm(115, Math.Log(1 + person.Household.ResidenceParcel.HouseholdsBuffer2));
            alternative.AddUtilityTerm(122, (household.HouseholdType == Global.Settings.HouseholdTypes.TwoPlusNonworkerNonstudentAdultsWithoutChildren).ToFlag());
            alternative.AddUtilityTerm(123, (person.PersonType == Global.Settings.PersonTypes.PartTimeWorker).ToFlag());
            alternative.AddUtilityTerm(126, (person.PersonType == Global.Settings.PersonTypes.ChildUnder5).ToFlag());
            alternative.AddUtilityTerm(127, (person.PersonType == Global.Settings.PersonTypes.ChildAge5Through15).ToFlag());
            alternative.AddUtilityTerm(128, (household.Has100KPlusIncome).ToFlag());

            // MEDICAL
            alternative        = choiceProbabilityCalculator.GetAlternative(Global.Settings.Purposes.Medical, maxPurpose <= Global.Settings.Purposes.Medical && personDay.CreatedMedicalTours > 0, choice == Global.Settings.Purposes.Medical);
            alternative.Choice = Global.Settings.Purposes.Medical;
            alternative.AddUtilityTerm(131, 1);
            alternative.AddUtilityTerm(132, Math.Log(1 + household.ResidenceParcel.EmploymentMedicalBuffer2));
            alternative.AddUtilityTerm(133, (person.PersonType == Global.Settings.PersonTypes.RetiredAdult).ToFlag());
            //alternative.AddNestedAlternative(11, 1, 60);
        }
        private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, IHouseholdWrapper household, int choice = Constants.DEFAULT_VALUE)
        {
//			var distanceToTransitCappedUnderQtrMile = household.ResidenceParcel.DistanceToTransitCappedUnderQtrMile();
//			var distanceToTransitQtrToHalfMile = household.ResidenceParcel.DistanceToTransitQtrToHalfMile();
            var foodRetailServiceMedicalLogBuffer1 = household.ResidenceParcel.FoodRetailServiceMedicalLogBuffer1();

            var workTourLogsumDifference   = 0D;           // (full or part-time workers) full car ownership vs. no car ownership
            var schoolTourLogsumDifference = 0D;           // (school) full car ownership vs. no car ownership

//			const double workTourOtherLogsumDifference = 0D; // (other workers) full car ownership vs. no car ownership

            foreach (var person in household.Persons)
            {
                if (person.IsWorker && person.UsualWorkParcel != null && person.UsualWorkParcelId != household.ResidenceParcelId)
                {
                    var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
                    var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);

                    var nestedAlternative1 = Global.ChoiceModelSession.Get <WorkTourModeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.HouseholdTotals.DrivingAgeMembers);
                    var nestedAlternative2 = Global.ChoiceModelSession.Get <WorkTourModeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, 0);

                    workTourLogsumDifference += nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
                    workTourLogsumDifference -= nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
                }

                if (person.IsDrivingAgeStudent && person.UsualSchoolParcel != null && person.UsualSchoolParcelId != household.ResidenceParcelId)
                {
                    var destinationArrivalTime   = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
                    var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);

                    var nestedAlternative1 = Global.ChoiceModelSession.Get <SchoolTourModeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.HouseholdTotals.DrivingAgeMembers);
                    var nestedAlternative2 = Global.ChoiceModelSession.Get <SchoolTourModeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, 0);

                    schoolTourLogsumDifference += nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
                    schoolTourLogsumDifference -= nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
                }
            }

            // var votSegment = household.VotALSegment;
            //var taSegment = household.ResidenceParcel.TransitAccessSegment();

            //var aggregateLogsumDifference = // full car ownership vs. no car ownership
            //	Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult][votSegment][taSegment] -
            //	Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votSegment][taSegment];

            var distanceToStop
                = household.ResidenceParcel.GetDistanceToTransit() > 0
                                          ? Math.Min(household.ResidenceParcel.GetDistanceToTransit(), 2 * Global.Settings.DistanceUnitsPerMile)  // JLBscale
                                          : 2 * Global.Settings.DistanceUnitsPerMile;

            var ruralFlag = household.ResidenceParcel.RuralFlag();

            // 0 AUTOS

            var alternative = choiceProbabilityCalculator.GetAlternative(0, true, choice == 0);

            alternative.Choice = 0;

            alternative.AddUtilityTerm(1, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(5, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(9, household.Has3Drivers.ToFlag());
            alternative.AddUtilityTerm(13, household.Has4OrMoreDrivers.ToFlag());
//			alternative.AddUtility(17, 0);
            alternative.AddUtilityTerm(18, household.HasNoFullOrPartTimeWorker.ToFlag());
            alternative.AddUtilityTerm(19, household.HouseholdTotals.PartTimeWorkersPerDrivingAgeMembers);
//			alternative.AddUtility(23, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
//			alternative.AddUtility(27, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(31, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(35, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);
//			alternative.AddUtility(39, household.HouseholdTotals.ChildrenUnder5PerDrivingAgeMembers);
            alternative.AddUtilityTerm(43, household.Has0To15KIncome.ToFlag());
            alternative.AddUtilityTerm(47, household.Has50To75KIncome.ToFlag());
            alternative.AddUtilityTerm(51, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(55, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(59, workTourLogsumDifference);
//			alternative.AddUtility(61, workTourOtherLogsumDifference);
            alternative.AddUtilityTerm(63, schoolTourLogsumDifference);
//			alternative.AddUtility(67, aggregateLogsumDifference);
            alternative.AddUtilityTerm(69, Math.Log(distanceToStop));
//			alternative.AddUtility(70, Math.Log(1+household.ResidenceParcel.StopsTransitBuffer1));
            alternative.AddUtilityTerm(73, household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer1);
            alternative.AddUtilityTerm(75, foodRetailServiceMedicalLogBuffer1);
            alternative.AddUtilityTerm(77, workTourLogsumDifference * ruralFlag);
//			alternative.AddUtility(78, workTourOtherLogsumDifference * ruralFlag);
//			alternative.AddUtility(79, aggregateLogsumDifference * ruralFlag);
//			alternative.AddUtility(80, Math.Log(distanceToStop)*ruralFlag);
//			alternative.AddUtility(81, Math.Log(1+household.ResidenceParcel.StopsTransitBuffer1)*ruralFlag);
//			alternative.AddUtility(82, foodRetailServiceMedicalQtrMileLog * ruralFlag);
            alternative.AddUtilityTerm(83, ruralFlag);

            // 1 AUTO

            alternative = choiceProbabilityCalculator.GetAlternative(1, true, choice == 1);

            alternative.Choice = 1;

            alternative.AddUtilityTerm(6, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(10, household.Has3Drivers.ToFlag());
            alternative.AddUtilityTerm(14, household.Has4OrMoreDrivers.ToFlag());
//			alternative.AddUtility(17, 1D / Math.Max(household.HouseholdTotals.DrivingAgeMembers, 1)); // ratio of 1 car per driving age members
            alternative.AddUtilityTerm(18, household.Has1OrLessFullOrPartTimeWorkers.ToFlag());
            alternative.AddUtilityTerm(20, household.HouseholdTotals.PartTimeWorkersPerDrivingAgeMembers);
            alternative.AddUtilityTerm(24, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(28, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(32, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(36, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);
//			alternative.AddUtility(40, household.HouseholdTotals.ChildrenUnder5PerDrivingAgeMembers);
            alternative.AddUtilityTerm(44, household.Has0To15KIncome.ToFlag());
            alternative.AddUtilityTerm(48, household.Has50To75KIncome.ToFlag());
            alternative.AddUtilityTerm(52, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(56, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(60, workTourLogsumDifference * household.HasMoreDriversThan1.ToFlag());
//			alternative.AddUtility(62, workTourOtherLogsumDifference * household.HasMoreDriversThan1.ToFlag());
//			alternative.AddUtility(64, schoolTourLogsumDifference * household.HasMoreDriversThan1.ToFlag());
//			alternative.AddUtility(68, aggregateLogsumDifference * household.HasMoreDriversThan1.ToFlag());
            alternative.AddUtilityTerm(72, Math.Log(1 + household.ResidenceParcel.StopsTransitBuffer1) * household.HasMoreDriversThan1.ToFlag());
            //alternative.AddUtility(74, household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer1 * household.HasMoreDriversThan1.ToFlag());
            alternative.AddUtilityTerm(76, foodRetailServiceMedicalLogBuffer1 * household.HasMoreDriversThan1.ToFlag());

            // 2 AUTOS

            alternative = choiceProbabilityCalculator.GetAlternative(2, true, choice == 2);

            alternative.Choice = 2;

            alternative.AddUtilityTerm(2, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(11, household.Has3Drivers.ToFlag());
            alternative.AddUtilityTerm(15, household.Has4OrMoreDrivers.ToFlag());
//			alternative.AddUtility(17, 2D / Math.Max(household.HouseholdTotals.DrivingAgeMembers, 1)); // ratio of 2 cars per driving age members
            alternative.AddUtilityTerm(18, household.Has2OrLessFullOrPartTimeWorkers.ToFlag());
            alternative.AddUtilityTerm(60, workTourLogsumDifference * household.HasMoreDriversThan2.ToFlag());
//			alternative.AddUtility(62, workTourOtherLogsumDifference * household.HasMoreDriversThan2.ToFlag());
//			alternative.AddUtility(64, schoolTourLogsumDifference * household.HasMoreDriversThan2.ToFlag());
//			alternative.AddUtility(68, aggregateLogsumDifference * household.HasMoreDriversThan2.ToFlag());
            alternative.AddUtilityTerm(72, Math.Log(1 + household.ResidenceParcel.StopsTransitBuffer1) * household.HasMoreDriversThan2.ToFlag());
//			alternative.AddUtility(74, household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer1 * household.HasMoreDriversThan2.ToFlag());
            alternative.AddUtilityTerm(76, foodRetailServiceMedicalLogBuffer1 * household.HasMoreDriversThan2.ToFlag());

            // 3 AUTOS

            alternative = choiceProbabilityCalculator.GetAlternative(3, true, choice == 3);

            alternative.Choice = 3;

            alternative.AddUtilityTerm(3, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(7, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(16, household.Has4OrMoreDrivers.ToFlag());
//			alternative.AddUtility(17, 3D / Math.Max(household.HouseholdTotals.DrivingAgeMembers, 1)); // ratio of 3 cars per driving age members
            alternative.AddUtilityTerm(18, household.Has3OrLessFullOrPartTimeWorkers.ToFlag());
//			alternative.AddUtility(21, household.HouseholdTotals.PartTimeWorkersPerDrivingAgeMembers);
            alternative.AddUtilityTerm(25, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(29, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
//			alternative.AddUtility(33, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(37, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(41, household.HouseholdTotals.ChildrenUnder5PerDrivingAgeMembers);
            alternative.AddUtilityTerm(45, household.Has0To15KIncome.ToFlag());
            alternative.AddUtilityTerm(49, household.Has50To75KIncome.ToFlag());
            alternative.AddUtilityTerm(53, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(57, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(60, workTourLogsumDifference * household.HasMoreDriversThan3.ToFlag());
//			alternative.AddUtility(62, workTourOtherLogsumDifference * household.HasMoreDriversThan3.ToFlag());
//			alternative.AddUtility(64, schoolTourLogsumDifference * household.HasMoreDriversThan3.ToFlag());
//			alternative.AddUtility(68, aggregateLogsumDifference * household.HasMoreDriversThan3.ToFlag());
            alternative.AddUtilityTerm(72, Math.Log(1 + household.ResidenceParcel.StopsTransitBuffer1) * household.HasMoreDriversThan3.ToFlag());
//			alternative.AddUtility(74, household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer1 * household.HasMoreDriversThan3.ToFlag());
            alternative.AddUtilityTerm(76, foodRetailServiceMedicalLogBuffer1 * household.HasMoreDriversThan3.ToFlag());

            // 4+ AUTOS

            alternative = choiceProbabilityCalculator.GetAlternative(4, true, choice == 4);

            alternative.Choice = 4;

            alternative.AddUtilityTerm(4, household.Has1Driver.ToFlag());
            alternative.AddUtilityTerm(8, household.Has2Drivers.ToFlag());
            alternative.AddUtilityTerm(12, household.Has3Drivers.ToFlag());
//			alternative.AddUtility(17, 4D / Math.Max(household.HouseholdTotals.DrivingAgeMembers, 1)); // ratio of 4 cars per driving age members
            alternative.AddUtilityTerm(18, household.Has4OrLessFullOrPartTimeWorkers.ToFlag());
            alternative.AddUtilityTerm(22, household.HouseholdTotals.PartTimeWorkersPerDrivingAgeMembers);
            alternative.AddUtilityTerm(26, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
//			alternative.AddUtility(30, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(34, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(38, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);
            alternative.AddUtilityTerm(42, household.HouseholdTotals.ChildrenUnder5PerDrivingAgeMembers);
            alternative.AddUtilityTerm(46, household.Has0To15KIncome.ToFlag());
            alternative.AddUtilityTerm(50, household.Has50To75KIncome.ToFlag());
            alternative.AddUtilityTerm(54, household.Has75KPlusIncome.ToFlag());
            alternative.AddUtilityTerm(58, household.HasMissingIncome.ToFlag());
            alternative.AddUtilityTerm(60, workTourLogsumDifference * household.HasMoreDriversThan4.ToFlag());
//			alternative.AddUtility(62, workTourOtherLogsumDifference * household.HasMoreDriversThan4.ToFlag());
//			alternative.AddUtility(64, schoolTourLogsumDifference * household.HasMoreDriversThan4.ToFlag());
//			alternative.AddUtility(68, aggregateLogsumDifference * household.HasMoreDriversThan4.ToFlag());
            alternative.AddUtilityTerm(72, Math.Log(1 + household.ResidenceParcel.StopsTransitBuffer1) * household.HasMoreDriversThan4.ToFlag());
//			alternative.AddUtility(74, household.ResidenceParcel.ParkingOffStreetPaidDailyPriceBuffer1 * household.HasMoreDriversThan4.ToFlag());
            alternative.AddUtilityTerm(76, foodRetailServiceMedicalLogBuffer1 * household.HasMoreDriversThan4.ToFlag());
        }
		private void RunModel(ChoiceProbabilityCalculator choiceProbabilityCalculator, HouseholdWrapper household, int choice = Constants.DEFAULT_VALUE) {
			//			//			var distanceToTransitCappedUnderQtrMile = household.ResidenceParcel.DistanceToTransitCappedUnderQtrMile();
			//			//			var distanceToTransitQtrToHalfMile = household.ResidenceParcel.DistanceToTransitQtrToHalfMile();
			//var foodRetailServiceMedicalLogBuffer1 = household.ResidenceParcel.FoodRetailServiceMedicalLogBuffer1();

			var workTourLogsumDifference = 0D; // (full or part-time workers) full car ownership vs. no car ownership
			var schoolTourLogsumDifference = 0D; // (school) full car ownership vs. no car ownership
															 //															 //			const double workTourOtherLogsumDifference = 0D; // (other workers) full car ownership vs. no car ownership
															 //
															 // Stefan
			var netIncome = (household.Income / 1000.0) / 2.0; // in 1000s of DKK
			var userCost = 2.441 * 15.0;  //annual cost to use 1 car in 1000s of DKK
			bool isInCopenhagenMunicipality = household.MunicipalCode == 101;  

			bool municipality101 = household.MunicipalCode == 101;
			bool municipality147 = household.MunicipalCode == 147;
			bool municipality151 = household.MunicipalCode == 151;
			bool municipality153 = household.MunicipalCode == 153;
			bool municipality155 = household.MunicipalCode == 155;
			bool municipality157 = household.MunicipalCode == 157;
			bool municipality159 = household.MunicipalCode == 159;
			bool municipality161 = household.MunicipalCode == 161;
			bool municipality163 = household.MunicipalCode == 163;
			bool municipality165 = household.MunicipalCode == 165;
			bool municipality167 = household.MunicipalCode == 167;
			bool municipality169 = household.MunicipalCode == 169;
			bool municipality173 = household.MunicipalCode == 173;
			bool municipality175 = household.MunicipalCode == 175;
			bool municipality183 = household.MunicipalCode == 183;
			bool municipality185 = household.MunicipalCode == 185;
			bool municipality187 = household.MunicipalCode == 187;
			bool municipality190 = household.MunicipalCode == 190;
			bool municipality201 = household.MunicipalCode == 201;
			bool municipality210 = household.MunicipalCode == 210;
			bool municipality217 = household.MunicipalCode == 217;
			bool municipality219 = household.MunicipalCode == 219;
			bool municipality223 = household.MunicipalCode == 223;
			bool municipality230 = household.MunicipalCode == 230;
			bool municipality240 = household.MunicipalCode == 240;
			bool municipality250 = household.MunicipalCode == 250;
			bool municipality253 = household.MunicipalCode == 253;
			bool municipality259 = household.MunicipalCode == 259;
			bool municipality260 = household.MunicipalCode == 260;
			bool municipality265 = household.MunicipalCode == 265;
			bool municipality269 = household.MunicipalCode == 269;
			bool municipality270 = household.MunicipalCode == 270;
			bool municipality336 = household.MunicipalCode == 336;
			bool municipality350 = household.MunicipalCode == 350;

			int numberAdults = 0;
			int numberChildren = 0;
			int numberWorkers = 0;
			int sumAdultAges = 0;
			double averageAdultAge = 0.0;
			bool isMale = false;

			foreach (PersonWrapper person in household.Persons) {
				if (person.IsWorker && person.UsualWorkParcel != null && person.UsualWorkParcelId != household.ResidenceParcelId) {
					var destinationArrivalTime = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.WorkTourModeModel);
					var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.WorkTourModeModel);
					//JLB 201602
					//var nestedAlternative1 = Global.ChoiceModelSession.Get<WorkTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.HouseholdTotals.DrivingAgeMembers, 0.0);
					//var nestedAlternative2 = Global.ChoiceModelSession.Get<WorkTourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, 0, 0.0);
					var nestedAlternative1 = Global.ChoiceModelSession.Get<TourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, household.HouseholdTotals.DrivingAgeMembers, 0.0, Global.Settings.Purposes.Work);
					var nestedAlternative2 = Global.ChoiceModelSession.Get<TourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualWorkParcel, destinationArrivalTime, destinationDepartureTime, 0, 0.0, Global.Settings.Purposes.Work);

					workTourLogsumDifference += nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
					workTourLogsumDifference -= nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
				}

				if (person.IsDrivingAgeStudent && person.UsualSchoolParcel != null && person.UsualSchoolParcelId != household.ResidenceParcelId) {
					var destinationArrivalTime = ChoiceModelUtility.GetDestinationArrivalTime(Global.Settings.Models.SchoolTourModeModel);
					var destinationDepartureTime = ChoiceModelUtility.GetDestinationDepartureTime(Global.Settings.Models.SchoolTourModeModel);

					//TODO: change the following school logsum retrievals when estimating this model after schoolTourModeTimeModel is enhanced for COMPAS2 
					var nestedAlternative1 = Global.ChoiceModelSession.Get<TourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, household.HouseholdTotals.DrivingAgeMembers, 0.0, Global.Settings.Purposes.School);
					var nestedAlternative2 = Global.ChoiceModelSession.Get<TourModeTimeModel>().RunNested(person, household.ResidenceParcel, person.UsualSchoolParcel, destinationArrivalTime, destinationDepartureTime, 0, 0.0, Global.Settings.Purposes.School);

					schoolTourLogsumDifference += nestedAlternative1 == null ? 0 : nestedAlternative1.ComputeLogsum();
					schoolTourLogsumDifference -= nestedAlternative2 == null ? 0 : nestedAlternative2.ComputeLogsum();
				}
				if (person.Age >= 18) {
					numberAdults++;
					sumAdultAges = sumAdultAges + person.Age;
					isMale = person.IsMale;
					if (person.PersonType == Global.Settings.PersonTypes.FullTimeWorker
						//|| person.PersonType == Constants.PersonType.PART_TIME_WORKER
						) {
						numberWorkers++;
					}
				}
				else {
					numberChildren++;
				}

			}
			averageAdultAge = sumAdultAges / Math.Max(numberAdults, 1);


			// var votSegment = household.VotALSegment;
			//var taSegment = household.ResidenceParcel.TransitAccessSegment();

			//var aggregateLogsumDifference = // full car ownership vs. no car ownership
			//	Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.OneOrMoreCarsPerAdult][votSegment][taSegment] -
			//	Global.AggregateLogsums[household.ResidenceZoneId][Global.Settings.Purposes.HomeBasedComposite][Global.Settings.CarOwnerships.NoCars][votSegment][taSegment];

			//var distanceToStop
			//	 = household.ResidenceParcel.GetDistanceToTransit() > 0
			//			 ? Math.Min(household.ResidenceParcel.GetDistanceToTransit(), 2 * Global.Settings.DistanceUnitsPerMile)  // JLBscale
			//			 : 2 * Global.Settings.DistanceUnitsPerMile;

			//var ruralFlag = household.ResidenceParcel.RuralFlag();

			var zeroVehAVEffect = (Global.Configuration.AV_IncludeAutoTypeChoice && household.OwnsAutomatedVehicles > 0) ? Global.Configuration.AV_Own0VehiclesCoefficientForAVHouseholds : 0;
			var oneVehAVEffect = (Global.Configuration.AV_IncludeAutoTypeChoice && household.OwnsAutomatedVehicles > 0) ? Global.Configuration.AV_Own1VehicleCoefficientForAVHouseholds : 0;

			var zeroVehSEEffect = (Global.Configuration.PaidRideShareModeIsAvailable && Global.Configuration.AV_PaidRideShareModeUsesAVs) ? Global.Configuration.AV_SharingEconomy_DensityCoefficientForOwning0Vehicles * Math.Min(household.ResidenceBuffer2Density, 6000) : 0;
			var oneVehSEEffect = (Global.Configuration.PaidRideShareModeIsAvailable && Global.Configuration.AV_PaidRideShareModeUsesAVs) ? Global.Configuration.AV_SharingEconomy_ConstantForOwning1Vehicle : 0;
			var twoVehSEEffect = (Global.Configuration.PaidRideShareModeIsAvailable && Global.Configuration.AV_PaidRideShareModeUsesAVs) ? Global.Configuration.AV_SharingEconomy_ConstantForOwning2Vehicles : 0;
			//var threeVehSEEffect = (Global.Configuration.PaidRideShareModeIsAvailable && Global.Configuration.AV_PaidRideShareModeUsesAVs) ? Global.Configuration.AV_SharingEconomy_ConstantForOwning3Vehicles : 0;
			//var fourVehSEEffect = (Global.Configuration.PaidRideShareModeIsAvailable && Global.Configuration.AV_PaidRideShareModeUsesAVs) ? Global.Configuration.AV_SharingEconomy_ConstantForOwning4Vehicles : 0;

			// 0 AUTOS

			var alternative = choiceProbabilityCalculator.GetAlternative(0, true, choice == 0);
			alternative.Choice = 0;
			alternative.AddUtilityTerm(14, Math.Log(Math.Max(netIncome, 1)));
			alternative.AddUtilityTerm(15, workTourLogsumDifference);  // instead of all Stefan's work-related and logsum variables
			alternative.AddUtilityTerm(90, 1); //calibration constant
			alternative.AddUtilityTerm(100, zeroVehAVEffect);
			alternative.AddUtilityTerm(100, zeroVehSEEffect);
			alternative.AddUtilityTerm(101, municipality101.ToFlag());
			alternative.AddUtilityTerm(102, municipality147.ToFlag());
			alternative.AddUtilityTerm(103, municipality151.ToFlag());
			alternative.AddUtilityTerm(104, municipality153.ToFlag());
			alternative.AddUtilityTerm(105, municipality155.ToFlag());
			alternative.AddUtilityTerm(106, municipality157.ToFlag());
			alternative.AddUtilityTerm(107, municipality159.ToFlag());
			alternative.AddUtilityTerm(108, municipality161.ToFlag());
			alternative.AddUtilityTerm(109, municipality163.ToFlag());
			alternative.AddUtilityTerm(110, municipality165.ToFlag());
			alternative.AddUtilityTerm(111, municipality167.ToFlag());
			alternative.AddUtilityTerm(112, municipality169.ToFlag());
			alternative.AddUtilityTerm(113, municipality173.ToFlag());
			alternative.AddUtilityTerm(114, municipality175.ToFlag());
			alternative.AddUtilityTerm(115, municipality183.ToFlag());
			alternative.AddUtilityTerm(116, municipality185.ToFlag());
			alternative.AddUtilityTerm(117, municipality187.ToFlag());
			alternative.AddUtilityTerm(118, municipality190.ToFlag());
			alternative.AddUtilityTerm(119, municipality201.ToFlag());
			alternative.AddUtilityTerm(120, municipality210.ToFlag());
			alternative.AddUtilityTerm(121, municipality217.ToFlag());
			alternative.AddUtilityTerm(122, municipality219.ToFlag());
			alternative.AddUtilityTerm(123, municipality223.ToFlag());
			alternative.AddUtilityTerm(124, municipality230.ToFlag());
			alternative.AddUtilityTerm(125, municipality240.ToFlag());
			alternative.AddUtilityTerm(126, municipality250.ToFlag());
			alternative.AddUtilityTerm(127, municipality253.ToFlag());
			alternative.AddUtilityTerm(128, municipality259.ToFlag());
			alternative.AddUtilityTerm(129, municipality260.ToFlag());
			alternative.AddUtilityTerm(130, municipality265.ToFlag());
			alternative.AddUtilityTerm(131, municipality269.ToFlag());
			alternative.AddUtilityTerm(132, municipality270.ToFlag());
			alternative.AddUtilityTerm(133, municipality336.ToFlag());
			alternative.AddUtilityTerm(134, municipality350.ToFlag());


			// 1 AUTO

			var beta010 = -6.59;
			var beta011 = 4.25;
			var beta012 = 5.53;
			var beta013 = 6.54;
			var beta014 = 1.17;
			var beta015 = 0.54;
			var beta016 = 0.81;
			var beta017 = 1.20;
			var beta018 = -0.54;
			var beta019 = 0.0;
			var beta020 = 0.45;
			var beta021 = 0.0;
			var beta022 = -0.04;
			var beta023 = 0.57;
			var beta024 = 0.18;
			var beta025 = -0.82;

			var stefanOneCarUtility =
				beta010 * 1.0 +
				beta011 * household.Has1Driver.ToFlag() +
				beta012 * household.Has2Drivers.ToFlag() +
				beta013 * (household.Has3Drivers || household.Has4OrMoreDrivers).ToFlag() +
				beta014 * Math.Log(Math.Max(netIncome - userCost, 1)) +
				beta015 * (numberChildren == 1).ToFlag() +
				beta016 * (numberChildren == 2).ToFlag() +
				beta017 * (numberChildren > 2).ToFlag() +
				beta018 * (numberAdults == 1 && !isMale).ToFlag() +
				beta019 * (numberAdults == 1 && isMale).ToFlag() +
				beta020 * averageAdultAge / 10.0 +
				beta021 * Math.Pow(averageAdultAge / 10.0, 2.0) +
				beta022 * 0 + //household.ResidenceParcel.PSearchTime16_17 +  // Add this when new parcel variables with seach time are available
				beta023 * household.ResidenceParcel.DistanceToLocalBus +
				beta024 * household.ResidenceParcel.DistanceToExpressBus +
				beta025 * isInCopenhagenMunicipality.ToFlag() +
				0;

			alternative = choiceProbabilityCalculator.GetAlternative(1, true, choice == 1);
			alternative.Choice = 1;
			//Stefan
			//alternative.AddUtilityTerm(10, 1.0);
			//alternative.AddUtilityTerm(11, household.Has1Driver.ToFlag());
			//alternative.AddUtilityTerm(12, household.Has2Drivers.ToFlag());
			//alternative.AddUtilityTerm(13, (household.Has3Drivers || household.Has4OrMoreDrivers).ToFlag());
			//alternative.AddUtilityTerm(14, Math.Log(Math.Max(netIncome - userCost, 1)));
			//alternative.AddUtilityTerm(15, (numberChildren == 1).ToFlag());
			//alternative.AddUtilityTerm(16, (numberChildren == 2).ToFlag());
			//alternative.AddUtilityTerm(17, (numberChildren > 2).ToFlag());
			//alternative.AddUtilityTerm(18, (numberAdults == 1 && !isMale).ToFlag());
			//alternative.AddUtilityTerm(19, (numberAdults == 1 && isMale).ToFlag());
			//alternative.AddUtilityTerm(20, averageAdultAge / 10.0);
			//alternative.AddUtilityTerm(21, Math.Pow(averageAdultAge / 10.0, 2.0));
			////alternative.AddUtilityTerm(22, household.ResidenceParcel.PSearchTime16_17);  // Add this when new parcel variables with seach time are available
			//alternative.AddUtilityTerm(23, household.ResidenceParcel.DistanceToLocalBus);
			//alternative.AddUtilityTerm(24, household.ResidenceParcel.DistanceToExpressBus);
			//alternative.AddUtilityTerm(25, isInCopenhagenMunicipality.ToFlag());
			alternative.AddUtilityTerm(26, stefanOneCarUtility);  //this composite replaces above separate terms 10-25

			alternative.AddUtilityTerm(27, workTourLogsumDifference * household.HasMoreDriversThan1.ToFlag());  // instead of all Stefan's work-related and logsum variables
			alternative.AddUtilityTerm(91, 1); //calibration constant
			alternative.AddUtilityTerm(100, oneVehAVEffect);
			alternative.AddUtilityTerm(100, oneVehSEEffect);

			//alternative.AddUtilityTerm(24, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
			//alternative.AddUtilityTerm(25, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
			//alternative.AddUtilityTerm(26, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
			//alternative.AddUtilityTerm(27, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);

			// 2+ AUTOS

			var beta040 = -9.540;
			var beta041 = 2.79;
			var beta042 = 6.09;
			var beta043 = 7.77;
			var beta044 = 0;
			var beta045 = 0.35;
			var beta046 = 0.81;
			var beta047 = 1.33;
			var beta048 = -1.13;
			var beta049 = 0.60;
			var beta050 = 0.92;
			var beta051 = -0.05;
			var beta052 = -0.09;
			var beta053 = 0.94;
			var beta054 = 0.31;
			var beta055 = -1.54;

			var stefanTwoCarUtility =
				beta040 * 1.0 +
				beta041 * household.Has1Driver.ToFlag() +
				beta042 * household.Has2Drivers.ToFlag() +
				beta043 * (household.Has3Drivers || household.Has4OrMoreDrivers).ToFlag() +
				beta014 * Math.Log(Math.Max(netIncome - userCost * 2.0, 1)) +
				beta045 * (numberChildren == 1).ToFlag() +
				beta046 * (numberChildren == 2).ToFlag() +
				beta047 * (numberChildren > 2).ToFlag() +
				beta048 * (numberAdults == 1 && !isMale).ToFlag() +
				beta049 * (numberAdults == 1 && isMale).ToFlag() +
				beta050 * averageAdultAge / 10.0 +
				beta051 * Math.Pow(averageAdultAge / 10.0, 2.0) +
				beta052 * 0 + //household.ResidenceParcel.PSearchTime16_17 +  // Add this when new parcel variables with seach time are available
				beta053 * household.ResidenceParcel.DistanceToLocalBus +
				beta054 * household.ResidenceParcel.DistanceToExpressBus +
				beta055 * isInCopenhagenMunicipality.ToFlag() +
				0;

			alternative = choiceProbabilityCalculator.GetAlternative(2, true, choice == 2);
			alternative.Choice = 2;
			//Stefan
			//alternative.AddUtilityTerm(40, 1.0);
			//alternative.AddUtilityTerm(41, household.Has1Driver.ToFlag());
			//alternative.AddUtilityTerm(42, household.Has2Drivers.ToFlag());
			//alternative.AddUtilityTerm(43, (household.Has3Drivers || household.Has4OrMoreDrivers).ToFlag());
			//alternative.AddUtilityTerm(14, Math.Log(Math.Max(netIncome - userCost * 2.0, 1)));
			//alternative.AddUtilityTerm(45, (numberChildren == 1).ToFlag());
			//alternative.AddUtilityTerm(46, (numberChildren == 2).ToFlag());
			//alternative.AddUtilityTerm(47, (numberChildren > 2).ToFlag());
			//alternative.AddUtilityTerm(48, (numberAdults == 1 && !isMale).ToFlag());
			//alternative.AddUtilityTerm(49, (numberAdults == 1 && isMale).ToFlag());
			//alternative.AddUtilityTerm(50, averageAdultAge / 10.0);
			//alternative.AddUtilityTerm(51, Math.Pow(averageAdultAge / 10.0, 2.0));
			////alternative.AddUtilityTerm(52, household.ResidenceParcel.PSearchTime16_17);  // Add this when new parcel variables with seach time are available
			//alternative.AddUtilityTerm(53, household.ResidenceParcel.DistanceToLocalBus);
			//alternative.AddUtilityTerm(54, household.ResidenceParcel.DistanceToExpressBus);
			//alternative.AddUtilityTerm(55, isInCopenhagenMunicipality.ToFlag());
			alternative.AddUtilityTerm(56, stefanTwoCarUtility);  //this composite replaces above separate terms 40-55

			//alternative.AddUtilityTerm(57, workTourLogsumDifference);
			alternative.AddUtilityTerm(92, 1); //new calibration constant - must be constrained to 0 in estimation
			alternative.AddUtilityTerm(100, twoVehSEEffect);
			alternative.AddUtilityTerm(201, municipality101.ToFlag());
			alternative.AddUtilityTerm(202, municipality147.ToFlag());
			alternative.AddUtilityTerm(203, municipality151.ToFlag());
			alternative.AddUtilityTerm(204, municipality153.ToFlag());
			alternative.AddUtilityTerm(205, municipality155.ToFlag());
			alternative.AddUtilityTerm(206, municipality157.ToFlag());
			alternative.AddUtilityTerm(207, municipality159.ToFlag());
			alternative.AddUtilityTerm(208, municipality161.ToFlag());
			alternative.AddUtilityTerm(209, municipality163.ToFlag());
			alternative.AddUtilityTerm(210, municipality165.ToFlag());
			alternative.AddUtilityTerm(211, municipality167.ToFlag());
			alternative.AddUtilityTerm(212, municipality169.ToFlag());
			alternative.AddUtilityTerm(213, municipality173.ToFlag());
			alternative.AddUtilityTerm(214, municipality175.ToFlag());
			alternative.AddUtilityTerm(215, municipality183.ToFlag());
			alternative.AddUtilityTerm(216, municipality185.ToFlag());
			alternative.AddUtilityTerm(217, municipality187.ToFlag());
			alternative.AddUtilityTerm(218, municipality190.ToFlag());
			alternative.AddUtilityTerm(219, municipality201.ToFlag());
			alternative.AddUtilityTerm(220, municipality210.ToFlag());
			alternative.AddUtilityTerm(221, municipality217.ToFlag());
			alternative.AddUtilityTerm(222, municipality219.ToFlag());
			alternative.AddUtilityTerm(223, municipality223.ToFlag());
			alternative.AddUtilityTerm(224, municipality230.ToFlag());
			alternative.AddUtilityTerm(225, municipality240.ToFlag());
			alternative.AddUtilityTerm(226, municipality250.ToFlag());
			alternative.AddUtilityTerm(227, municipality253.ToFlag());
			alternative.AddUtilityTerm(228, municipality259.ToFlag());
			alternative.AddUtilityTerm(229, municipality260.ToFlag());
			alternative.AddUtilityTerm(230, municipality265.ToFlag());
			alternative.AddUtilityTerm(231, municipality269.ToFlag());
			alternative.AddUtilityTerm(232, municipality270.ToFlag());
			alternative.AddUtilityTerm(233, municipality336.ToFlag());
			alternative.AddUtilityTerm(234, municipality350.ToFlag());

			//alternative.AddUtilityTerm(44, household.HouseholdTotals.RetiredAdultsPerDrivingAgeMembers);
			//alternative.AddUtilityTerm(45, household.HouseholdTotals.UniversityStudentsPerDrivingAgeMembers);
			//alternative.AddUtilityTerm(46, household.HouseholdTotals.DrivingAgeStudentsPerDrivingAgeMembers);
			//alternative.AddUtilityTerm(47, household.HouseholdTotals.HomeBasedPersonsPerDrivingAgeMembers);

		}