# fmt: off
import numpy as np
from SpectrumCommon.Const.VW.VWConst import *
from SpectrumCommon.Const.VW.VWTags import *
from SpectrumCommon.Const.CS import *
from SpectrumCommon.Const.CS.CSInterventionIDs import *
from SpectrumCommon.Util.CS.CSUtil import *
from .CSUtil import *
from SpectrumCommon.Const.IV import IVDatabaseKeys as ivdbk
from AvenirCommon.Util import GBRange, GBNormalize

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                                                                                          /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def AddRequiredIntervs(result, RequiredIntervs, SumMstID  = -1):
    if not SumMstID == -1:
        if SumMstID in result:
            result[SumMstID]['SumTotal'] = 1

    for mstID in RequiredIntervs:
        if mstID in result:
            newList = RequiredIntervs.copy()
            newList.remove(mstID)
            result[mstID]['RequiredIntervs'] = newList

def IVInfo_Init(IV_DB, DevMode = False, GSKMode = False):    
    result = {}

    # These interventions should only appear in developer mode.
    DevModeIVSet = [CS_IV_ZincFort_MST_ID,
                    CS_IV_ZincSuppInPreg_MST_ID,
                    CS_IV_TreatOfBacteriuria_MST_ID,
                    CS_IV_StopSmokingEduc_MST_ID,
                    CS_IV_ConditionalCashTransfer_MST_ID,
                    CS_IV_FoodAssistanceToFamilies_MST_ID,
                    CS_IV_DirectSupport_MST_ID,
                    CS_IV_FoodShock_MST_ID,
                    CS_IV_DiarVaccPathB_MST_ID,
                    CS_IV_DiarVaccPathC_MST_ID,
                    CS_IV_VaccineD_MST_ID,
                    CS_IV_iKMCComm_MST_ID,
                    CS_IV_iKMCFac_MST_ID,
                    CS_IV_nCPAP_MST_ID,
                    CS_IV_OralAnti_MST_ID,
                    CS_IV_InjectAntiSecFac_MST_ID,
                    CS_IV_Newborn_MST_ID,
                    CS_IV_AnimalDerived_MST_ID,
                    CS_IV_PophylAntifung_MST_ID,
                    CS_IV_InjectAntiTerFac_MST_ID,
                    CS_IV_AntiStewardAndEdu_MST_ID,
                    CS_IV_TropicEnroll_MST_ID,
                    CS_IV_Probriotics_MST_ID,
                    CS_IV_MagSulfate_MST_ID]

    # These interventions should only appear in GSK mode.
    GSKModeIVSet = [CS_IV_DiarVaccPathB_MST_ID,
                    CS_IV_DiarVaccPathC_MST_ID,
                    CS_IV_VaccineD_MST_ID,
                    CS_IV_VaccineE_MST_ID,
                    CS_IV_VaccineF_MST_ID,
                    CS_IV_Innovative_Mal_Prev_MST_ID,
                    CS_IV_New_Mal_Treat_MST_ID]
    
    # Any interventions appearing in both sets should appear in either developer or GSK mode.

    # ========================================================================
    #                             Normal cases:
    # ========================================================================

    currID = 0
    
    for i in GBRange(0, len(IV_DB)-1):        
        record = IV_DB[i]

        # Generally, only interventions with at least one of these flags set to true should
        # be included.
        IVHasShowParam = False
        for key in [ivdbk.IV_M_CS_KEY_IDB, 
                    ivdbk.IV_SB_CS_KEY_IDB, 
                    ivdbk.IV_NN_CS_KEY_IDB, 
                    ivdbk.IV_PNN_CS_KEY_IDB, 
                    ivdbk.IV_ADOL_EFF_CS_KEY_IDB, 
                    ivdbk.IV_COVERAGE_CS_KEY_IDB, 
                    ivdbk.IV_DISPLAY_CS_KEY_IDB, 
                    ivdbk.IV_MATERNAL_DISPLAY_CS_KEY_IDB, 
                    ivdbk.IV_STILLBIRTH_DISPLAY_CS_KEY_IDB, 
                    ivdbk.IV_ADOLESCENT_DISPLAY_CS_KEY_IDB]:
            IVHasShowParam = IVHasShowParam or record[key]

        # These interventions are exceptions in that they don't have one of the above flags 
        # set to true but should still be included.
        ForceOnSet = [CS_IV_ContraceptiveUse_MST_ID,
                      CS_IV_ANC1_MST_ID, 
                      CS_IV_ANC4_MST_ID, 
                      CS_IV_AnemiaReduction_MST_ID,
                      CS_IV_BirthOutcomes_MST_ID, 
                      CS_IV_HealthFacDelivery_MST_ID, 
                      CS_IV_NonHealthFacDelivery_MST_ID, 
                      CS_IV_FoodInsecBES_MST_ID,
                      CS_IV_ApprCompFeed_MST_ID,
                      CS_IV_FoodInsecCompStunt_MST_ID,
                      CS_IV_FoodInsecCompWaste_MST_ID]

        def isInSet(record, set):
            return str(record[ivdbk.IV_MST_ID_KEY_IDB]) in set
        
        if (isInSet(record, ForceOnSet) or IVHasShowParam):
            
            isDevModeOnlyIV = isInSet(record, DevModeIVSet)
            isGSKModeOnlyIV = isInSet(record, GSKModeIVSet)
            
            # Proceed if: 
            #   1. the intervention is not a developer mode only or GSK mode only intervention,
            #   2. the intervention is a developer mode only intervention and we're in developer mode, or
            #   3. the intervention is a GSK mode only intervention and we're in GSK mode.
            
            proceed = (not isDevModeOnlyIV and not isGSKModeOnlyIV) or (
              isDevModeOnlyIV and DevMode) or (isGSKModeOnlyIV and GSKMode)            
            
            if (proceed):
                key = str(record[ivdbk.IV_MST_ID_KEY_IDB])
                result[key] = {'currID' : currID}
                
                for key2 in record:
                    if key2 not in [ivdbk.IV_ROOT_CONSTANT_KEY_IDB, ivdbk.IV_MST_ID_KEY_IDB]:
                        result[key][key2] = IV_DB[i][key2]
                
                result[key]['RequiredIntervs'] = []
                result[key]['SumTotal'] = 0
                result[key]['directEntry'] = 0
                result[key]['isCustom'] = False
                result[key]['HerdIndex'] = -1
                result[key]['HerdDiseaseSet'] = []
                
                key2 = ivdbk.IV_INTERV_TYPE_CS_KEY_IDB
                if   result[key][key2] == 'Peri'  : result[key][key2] = IV_CS_Periconceptual
                elif result[key][key2] == 'Abort' : result[key][key2] = IV_CS_Abortion
                elif result[key][key2] == 'ANC'   : result[key][key2] = IV_CS_ANC
                elif result[key][key2] == 'Deliv' : result[key][key2] = IV_CS_Delivery
                elif result[key][key2] == 'Vacc'  : result[key][key2] = IV_CS_Vaccine
                elif result[key][key2] == 'Prev'  : result[key][key2] = IV_CS_Preventive
                elif result[key][key2] == 'Cur'   : result[key][key2] = IV_CS_Curative
                else:                               result[key][key2] = IV_CS_NoIntervCalcType               
                                
                currID += 1
    
    # Set herd details
    def setHerdIndex(result, mstID, herdIndex):
        if mstID in result:
            result[mstID]['HerdIndex'] = herdIndex
    
    setHerdIndex(result, CS_IV_RotavirusVacc_MST_ID, CS_Rotavirus_Herd)
    setHerdIndex(result, CS_IV_MeningA_MST_ID, CS_MeningococcalA_Herd)
    setHerdIndex(result, CS_IV_MeasVacc_MST_ID, CS_Measles_Herd)
    setHerdIndex(result, CS_IV_HibVacc_MST_ID, CS_Hib_Herd)
    setHerdIndex(result, CS_IV_PneuVacc_MST_ID, CS_Pneumococcal_Herd)
    setHerdIndex(result, CS_IV_DPT_Vacc_MST_ID, CS_DPT_Herd)
    setHerdIndex(result, CS_IV_ITN_IRS_MST_ID, CS_Bednets_Herd)
    setHerdIndex(result, CS_IV_DiarVaccPathB_MST_ID, CS_DiarVaccPathB_Herd)
    setHerdIndex(result, CS_IV_DiarVaccPathC_MST_ID, CS_DiarVaccPathC_Herd)
    setHerdIndex(result, CS_IV_MalVacc_MST_ID, CS_Malaria_Herd)
    setHerdIndex(result, CS_IV_VaccineD_MST_ID, CS_VaccineD_Herd)
    setHerdIndex(result, CS_IV_VaccineE_MST_ID, CS_VaccineE_Herd)
    setHerdIndex(result, CS_IV_VaccineF_MST_ID, CS_VaccineF_Herd)


    # ========================================================================
    #                     Special cases for input flags:
    # ========================================================================

    for mstID in [CS_IV_ContraceptiveUse_MST_ID, CS_IV_MicronSupp_MST_ID, CS_IV_PMTCT_MST_ID]:
        result[mstID][ivdbk.IV_M_CS_KEY_IDB] = 1
        result[mstID][ivdbk.IV_SB_CS_KEY_IDB] = 1
    
    for mstID in [CS_IV_PMTCT_MST_ID, CS_IV_CaseMgmtPrematBabies_MST_ID, CS_IV_CaseMgmtNeonSepsPneu_MST_ID, CS_IV_Cotrimoxazole_MST_ID]:
        result[mstID][ivdbk.IV_NN_CS_KEY_IDB] = 1
        result[mstID][ivdbk.IV_PNN_CS_KEY_IDB] = 1
    
    for mstID in [CS_IV_PentaVacc_MST_ID, CS_IV_TrMAM_MST_ID, CS_IV_CaseMgmtMalTreat_MST_ID]:
        result[mstID][ivdbk.IV_PNN_CS_KEY_IDB] = 1
    
    # ========================================================================
    #                    Special cases for HIV Grouping:
    # ========================================================================

    for mstID in [CS_IV_PMTCT_MST_ID, CS_IV_Cotrimoxazole_MST_ID]:
        result[mstID][ivdbk.IV_GROUP_CURR_ID_KEY_IDB] = CS_LiSTOnline_FamPlanHIV
        result[mstID][ivdbk.IV_GROUP_MST_ID_KEY_IDB] = CS_MstLiSTOnline_FamPlanHIV
        result[mstID][ivdbk.IV_SUBGROUP_MST_ID_KEY_IDB] = -1    
    
    HIVGroupOrderOffset = CS_LastFPMstID - CS_FirstFPMstID + 2

    result[CS_IV_PMTCT_MST_ID][ivdbk.IV_GROUP_ORDER_KEY_IDB] = HIVGroupOrderOffset + 1    
    result[CS_IV_Cotrimoxazole_MST_ID][ivdbk.IV_GROUP_ORDER_KEY_IDB] = HIVGroupOrderOffset + 2
    
    # ==============================================================================
    #      Interventions which relate to other interventions in special ways:
    # ==============================================================================

    AddRequiredIntervs(result, [CS_IV_MicronSupp_MST_ID, CS_IV_IronSuppPreg_MST_ID, CS_IV_MultiMicronSuppPreg_MST_ID], CS_IV_MicronSupp_MST_ID)
    AddRequiredIntervs(result, [CS_IV_PentaVacc_MST_ID, CS_IV_DPT_Vacc_MST_ID, CS_IV_HibVacc_MST_ID, CS_IV_HepBVacc_MST_ID])
    AddRequiredIntervs(result, [CS_IV_CaseMgmtPrematBabies_MST_ID, CS_IV_KangarooMothCare_MST_ID, CS_IV_FullSuppCarePremat_MST_ID, CS_IV_iKMC_MST_ID], CS_IV_CaseMgmtPrematBabies_MST_ID)
    AddRequiredIntervs(result, [CS_IV_CaseMgmtNeonSepsPneu_MST_ID, CS_IV_OralAntibNeonSeps_MST_ID, CS_IV_InjectAntibNeonSeps_MST_ID, CS_IV_FullSuppCareNeonSepsPneu_MST_ID], 
                       CS_IV_CaseMgmtNeonSepsPneu_MST_ID)
    
    RequiredIntervs = [CS_IV_CaseMgmtMalTreat_MST_ID, CS_IV_ACTsMal_MST_ID]
    if GSKMode:
        RequiredIntervs.append(CS_IV_New_Mal_Treat_MST_ID)
    AddRequiredIntervs(result, RequiredIntervs, CS_IV_CaseMgmtMalTreat_MST_ID)
    
    # ==============================================================================
    #                    Nutrition status pseudo interventions:
    # ==============================================================================

    result[str(CS_MstMaternalAgeOfBirthOrder)] = {}
    IVObj = result[str(CS_MstMaternalAgeOfBirthOrder)]
    IVObj[ivdbk.IV_STRING_CONSTANT_KEY_IDB] = 'GB_stDirectEntryFertilityRisks'
    IVObj[ivdbk.IV_SUBGROUP_MST_ID_KEY_IDB] = -1
    IVObj[ivdbk.IV_GROUP_CURR_ID_KEY_IDB] = CS_LiSTOnline_Nutrition
    IVObj[ivdbk.IV_GROUP_MST_ID_KEY_IDB] = CS_MstLiSTOnline_Nutrition
    IVObj[ivdbk.IV_GROUP_ORDER_KEY_IDB] = 1
    IVObj[ivdbk.IV_M_CS_KEY_IDB] = 1
    IVObj[ivdbk.IV_NN_CS_KEY_IDB] = 1
    IVObj[ivdbk.IV_PNN_CS_KEY_IDB] = 1
    IVObj['RequiredIntervs'] = []
    IVObj['SumTotal'] = 0
    IVObj['directEntry'] = 1

    def getNutritionStringConstant(mstID):
        if mstID == CS_MstDirectEntryOfStunting: return 'GB_stDirectEntryStunting'
        if mstID == CS_MstDirectEntryOfWasting: return 'GB_stDirectEntryWasting'
        if mstID == CS_MstDirectEntryOfBF: return 'GB_stDirectEntryBfPrev'
        if mstID == CS_MstBFPromotion: return 'GB_stBFPromo'
        
    for mstID in GBRange(CS_FirstNutMstID, CS_LastNutMstID):
        result[str(mstID)] = {}
        IVObj = result[str(mstID)]
        IVObj[ivdbk.IV_STRING_CONSTANT_KEY_IDB] = getNutritionStringConstant(mstID)
        IVObj[ivdbk.IV_SUBGROUP_MST_ID_KEY_IDB] = -1
        IVObj[ivdbk.IV_GROUP_CURR_ID_KEY_IDB] = CS_LiSTOnline_Nutrition
        IVObj[ivdbk.IV_GROUP_MST_ID_KEY_IDB] = CS_MstLiSTOnline_Nutrition
        IVObj[ivdbk.IV_GROUP_ORDER_KEY_IDB] = mstID - CS_FirstNutMstID + 2
        IVObj[ivdbk.IV_NN_CS_KEY_IDB] = 1
        IVObj[ivdbk.IV_PNN_CS_KEY_IDB] = 1
        IVObj['RequiredIntervs'] = []
        IVObj['SumTotal'] = 0
        IVObj['directEntry'] = 1

        if mstID == CS_MstBFPromotion:
            IVObj['directEntry'] = 0
            
            for key2 in result[CS_IV_ChangesInBF_MST_ID]:
                if key2 not in [ivdbk.IV_MST_ID_KEY_IDB, 
                                ivdbk.IV_ENGLISH_STRING_KEY_IDB,
                                ivdbk.IV_STRING_CONSTANT_KEY_IDB, 
                                ivdbk.IV_SUBGROUP_MST_ID_KEY_IDB, 
                                ivdbk.IV_GROUP_CURR_ID_KEY_IDB, 
                                ivdbk.IV_GROUP_MST_ID_KEY_IDB, 
                                ivdbk.IV_GROUP_ORDER_KEY_IDB, 
                                ivdbk.IV_NN_CS_KEY_IDB, 
                                ivdbk.IV_PNN_CS_KEY_IDB]:
                    IVObj[key2] = result[CS_IV_ChangesInBF_MST_ID][key2]

            result.pop(str(CS_IV_ChangesInBF_MST_ID))

    # ==============================================================================
    #                        FamPlan pseudo interventions:
    # ==============================================================================

    RequiredIntervs = []

    groupOrder = 1

    def getFPStringConstant(mstID):
        if mstID == CS_MstFamPlanInt: return 'GB_stFamilyPlanning_FamPlan'
        if mstID == CS_MstPercMarried: return 'GB_stPercMarried'
        if mstID == CS_MstPercUsingContra: return 'GB_stPercUseContra'
        if mstID == CS_MstContraMethMix: return 'GB_stContraMethMix'
        if mstID == CS_MstPercUnintendedPregTermByAbor: return 'GB_stPercUnintendedPregTermByAbor'
    
    for mstID in GBRange(CS_FirstFPMstID, CS_LastFPMstID):
        result[str(mstID)] = {}
        IVObj = result[str(mstID)] 
        IVObj[ivdbk.IV_STRING_CONSTANT_KEY_IDB] = getFPStringConstant(mstID)
        IVObj[ivdbk.IV_GROUP_ORDER_KEY_IDB] = groupOrder
        IVObj[ivdbk.IV_SUBGROUP_MST_ID_KEY_IDB] = -1
        IVObj[ivdbk.IV_GROUP_CURR_ID_KEY_IDB] = CS_LiSTOnline_FamPlanHIV
        IVObj[ivdbk.IV_GROUP_MST_ID_KEY_IDB] = CS_MstLiSTOnline_FamPlanHIV
        IVObj[ivdbk.IV_NN_CS_KEY_IDB] = 1
        IVObj[ivdbk.IV_PNN_CS_KEY_IDB] = 1
        IVObj[ivdbk.IV_M_CS_KEY_IDB] = 1
        IVObj[ivdbk.IV_ADOL_EFF_CS_KEY_IDB] = 1
        IVObj['RequiredIntervs'] = []
        IVObj['SumTotal'] = int(mstID == CS_FirstFPMstID)
        RequiredIntervs.append(str(mstID))
        groupOrder += 1

    AddRequiredIntervs(result, RequiredIntervs, str(CS_FirstFPMstID))

    # ==============================================================================
    #                          HIV pseudo interventions:
    # ==============================================================================

    RequiredIntervs = [CS_IV_PMTCT_MST_ID, CS_IV_Cotrimoxazole_MST_ID]

    AIMMstIDSet = [CS_FirstAMMstID, CS_MstPercOnART]

    if DevMode:
        for mstID in GBRange(CS_FirstAMMstID, CS_LastAMMstID):
            AIMMstIDSet.append(mstID)

    def getAMStringConstant(mstID):
        if mstID == CS_MstHIVInt: return 'GB_stHIVAIM'
        if mstID == CS_MstPercUsingCondWNonMarContacts: return 'GB_stPercUsingCondWNonMarContacts'
        if mstID == CS_MstPercUsingPrEP: return 'GB_stPercUsingPrEP'
        if mstID == CS_MstPercOnART: return 'GB_stPercentOnART'
        if mstID == CS_MstPercMalesCircum: return 'GB_stPercMalesCircum'
        if mstID == CS_MstPercReceivCompSexEd: return 'GB_stPercReceivCompSexEd'
        if mstID == CS_MstPercFemalesReceivEconStrength: return 'GB_stPercFemalesReceivEconStrength'
    
    for mstID in AIMMstIDSet:
        result[str(mstID)] = {}
        IVObj = result[str(mstID)]
        IVObj[ivdbk.IV_STRING_CONSTANT_KEY_IDB] = getAMStringConstant(mstID)
        IVObj[ivdbk.IV_GROUP_ORDER_KEY_IDB] = groupOrder
        IVObj[ivdbk.IV_SUBGROUP_MST_ID_KEY_IDB] = -1
        IVObj[ivdbk.IV_GROUP_CURR_ID_KEY_IDB] = CS_LiSTOnline_FamPlanHIV
        IVObj[ivdbk.IV_GROUP_MST_ID_KEY_IDB] = CS_MstLiSTOnline_FamPlanHIV
        IVObj[ivdbk.IV_ADOL_EFF_CS_KEY_IDB] = 1
        IVObj['RequiredIntervs'] = []
        IVObj['SumTotal'] = int(mstID == CS_FirstAMMstID)
        RequiredIntervs.append(str(mstID))

        if mstID == CS_FirstAMMstID:
            IVObj[ivdbk.IV_M_CS_KEY_IDB] = 1
            IVObj[ivdbk.IV_SB_CS_KEY_IDB] = 1
            IVObj[ivdbk.IV_NN_CS_KEY_IDB] = 1
            IVObj[ivdbk.IV_PNN_CS_KEY_IDB] = 1

            # Offset for two non-adolescent HIV interventions added in first/main loop. 
            groupOrder += 2

        if mstID == CS_MstPercOnART:
            IVObj[ivdbk.IV_NN_CS_KEY_IDB] = 1
            IVObj[ivdbk.IV_PNN_CS_KEY_IDB] = 1

        groupOrder += 1

    AddRequiredIntervs(result, RequiredIntervs, str(CS_FirstAMMstID))

    result[CS_IV_PMTCT_MST_ID][ivdbk.IV_STRING_CONSTANT_KEY_IDB] = 'GB_stPMTCT'

    # currID minus 1 because it was incremented one too many times on the last pass through the loop through the normal interventions
    numIntervs = currID - 1

    return result, numIntervs

def IVGroupInfo_Init(IVGroup_DB):    
    result = {}

    for i in GBRange(0, len(IVGroup_DB)-1):
        mstID = IVGroup_DB[i][ivdbk.IV_GROUP_MST_ID_KEY_IDB]
        if not mstID == CS_GroupMstID_Breastfeeding:
            if mstID not in result:
                result[mstID] = {
                    'name' : IVGroup_DB[i][ivdbk.IV_ENGLISH_STRING_KEY_IDB],
                    ivdbk.IV_STRING_CONSTANT_KEY_IDB : IVGroup_DB[i][ivdbk.IV_STRING_CONSTANT_KEY_IDB]
                }
    
    result[CS_MstLiSTOnline_Nutrition] = {
        'name' : 'Nutritional status',
        ivdbk.IV_STRING_CONSTANT_KEY_IDB : 'GB_stNutritionalStatus'
    }
    
    result[CS_MstLiSTOnline_FamPlanHIV] = {
        'name' : 'Family Planning/HIV',
        ivdbk.IV_STRING_CONSTANT_KEY_IDB : 'GB_stFPHIV'
    }

    # Getting the order right
    result[CS_GroupMstID_Periconceptual]['groupOrder'] = 1
    result[CS_GroupMstID_Pregnancy]['groupOrder']      = 2
    result[CS_GroupMstID_Childbirth]['groupOrder']     = 3
    result[CS_MstLiSTOnline_Nutrition]['groupOrder']   = 4
    result[CS_GroupMstID_Preventive]['groupOrder']     = 5
    result[CS_GroupMstID_Vaccines]['groupOrder']       = 6
    result[CS_GroupMstID_Curative]['groupOrder']       = 7
    result[CS_MstLiSTOnline_FamPlanHIV]['groupOrder']  = 8

    return result

def IVSubgroupInfo_Init(IVGroup_DB):    
    result = {}

    for i in GBRange(0, len(IVGroup_DB)-1):
        if not IVGroup_DB[i][ivdbk.IV_SUBGROUP_MST_ID_KEY_IDB] == -1:
            if IVGroup_DB[i][ivdbk.IV_SUBGROUP_MST_ID_KEY_IDB] not in result:
                result[IVGroup_DB[i][ivdbk.IV_SUBGROUP_MST_ID_KEY_IDB]] = {
                    'name' : IVGroup_DB[i][ivdbk.IV_ENGLISH_STRING_KEY_IDB],
                    ivdbk.IV_STRING_CONSTANT_KEY_IDB : IVGroup_DB[i][ivdbk.IV_STRING_CONSTANT_KEY_IDB]
                }

    result[CS_MstLiST] = {
        'name' : 'LiST',
        ivdbk.IV_STRING_CONSTANT_KEY_IDB : 'GB_stLiST'
    } 

    result[CS_MstFamPlan] = {
        'name' : 'FamPlan',
        ivdbk.IV_STRING_CONSTANT_KEY_IDB : 'GB_stFamPlanName'
    } 

    result[CS_MstHIV] = {
        'name' : 'HIV',
        ivdbk.IV_STRING_CONSTANT_KEY_IDB : 'GB_stHIV'
    } 
    
    return result

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                            Meta Data                                                     /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def IDMap_init():
    result = Simple_Value_Init({})
    
    def addMapping(result, key, FirstCurrID, FinalCurrID, fun, param = None):
        if key not in result['value']:
            result['value'][key] = {}
        
        for currID in GBRange(FirstCurrID, FinalCurrID):
            if not param == None:
                mstID = fun(param, currID)
            else:
                mstID = fun(currID)
            result['value'][key][mstID] = currID
    
    result['value']['Description'] = 'This modvar contains a mapping of various master ID\'s to various current ID\'s at the time of this projection\'s creation. ' \
    'The keys in this modvar are all master ID\'s; the values associated with each key are the corresponding current ID\'s.  ' \
    'This is important for backwards compatability in case any of these current ID\'s, which are the indices of several modvars in this projection, change after this projection is created and saved.  ' \
    'The current ID\'s are subject to change over time; the master ID\'s will never change.'
    
    addMapping(result, 'AgeCohort', CS_AgeSummary, CS_48t60months, CSGetAgeCohortMstID)
    addMapping(result, 'Term', CS_FirstTerm, CS_FinalTerm, CSGetBirthTermMstID)
    addMapping(result, 'AnemiaWRA', CS_Preg_Anemia, CS_MaxMaternalAnemia, CSGetAnemiaWRAMstID)
    addMapping(result, 'StdDev', CS_GT1STD, CS_GT3STD, CSGetStdDevMstID)
    addMapping(result, 'Distr', CS_Distr_All, CS_Distr_Fatal, CSGetDistrMstID)
    addMapping(result, 'Mortality Rate', CS_NeonatalMR, CS_U5MR, CSGetMRMstID)
    addMapping(result, 'EndPoint', CS_MinEndPoint, CS_MaxEndPoint, CSGetEndPointMstID)
    addMapping(result, 'DxC', CS_DxC_Default, CS_DxC_NoAIDS, CSGetDxCMstID)
    addMapping(result, 'AdolAge', CS_5yrs_9yrs, CS_15yrs_19yrs, CSGetAdolAgeMstID)
    addMapping(result, 'CostCat', CS_InterventionCosts, CS_OtherHealthSysCosts, CSGetCostCatMstID)
    addMapping(result, 'BenefitCat', CS_SocBenSB, CS_StuntReducAddEarn, CSGetBenefitCatMstID)
    addMapping(result, 'BaselineGDP', CS_PerCapita, CS_PerWorker, CSGetBaselineGDPMstID)
    addMapping(result, 'CostBen', CS_Benefits, CS_Costs, CSGetCostBenMstID)
    addMapping(result, 'Factors', CS_SocialValue, CS_PercStillbirthsIncluded, CSGetFactorsMstID)
    addMapping(result, 'BF', CS_ExclusiveBF, CS_NotBF, CSGetBFMstID)
    addMapping(result, 'DetVaccRetro', CS_DetVacc1YrsRetro, CS_DetVacc4YrsRetro, CSGetDetVaccRetroMstID)
    addMapping(result, 'MaternalAge', CS_AllYrs, CS_35_49Yrs, CSGetMAMstID)
    addMapping(result, 'BirthOrder', CS_FirstBirth, CS_GTThirdBirth, CSGetBOMstID)
    addMapping(result, 'BirthInterval', CS_LT18Mths, CS_GE24Mths, CSGetBIMstID)
    addMapping(result, 'DefConst', CS_Default, CS_Data, CSGetDefConstMstID)
    addMapping(result, 'Efficacy', CS_Efficacy, CS_AdjustedRR, CSGetEffAffMstID)
    addMapping(result, 'VaccSec', CS_0PercCov, CS_100PercCov, CSGetVaccSecMstID)
    addMapping(result, 'IUGR', CS_LowBirthWeight_TermAGA, CS_ImpactsOnStuntingFinal, CSGetIUGRMstID)
    addMapping(result, 'ImpactsOnWaste', CS_ImpactsOnWaste_Therafeed, CS_ImpactsOnWaste_FractionChildrenMovMildWastWithTreat, CSGetImpactsOnWasteMstID)
    addMapping(result, 'ImpactsOnWaste', CS_FoodSecureWPromo, CS_InsecureWOPromoSupp, CSGetIUGRMstID)
    addMapping(result, 'ImpactsOnWaste', CS_ImpactsOnWaste_FractionChildrenMovModWastWithTreat, CS_ImpactsOnWaste_FractionChildrenMovSevWastWithTreat, CSGetImpactsOnWasteMstID)
    addMapping(result, 'Preg', CS_Preg, CS_NonPreg, CSGetPregMstID)
    addMapping(result, 'ImpactsOnMatAnemia', CS_IronFolatePW_MatAnemia, CS_ITN_MatAnemia, CSGetImpactsOnMatAnemiaMstID)
    addMapping(result, 'ImpactPromo', CS_ImpactPromoBF, CS_ImpactPromoEarlyBF, CSGetImpactPromoMstID)
    addMapping(result, 'BFPromo', CS_BFPromoHealthSystem, CS_BFPromoBoth, CSGetBFPromoMstID)
    addMapping(result, 'InitBF', CS_EarlyInitBF, CS_LateInitBF, CSGetInitBFMstID)
    addMapping(result, 'Anemic', CS_Mat_NotAnemic, CS_Mat_Anemic, CSGetAnemicMstID)
    addMapping(result, 'Abortions', CS_TotalAbort, CS_SafeAbort, CSGetAbortionsMstID)
    addMapping(result, 'ReducInMort', CS_CovIncIntervPrgm, CS_PercU5MortRedAttrInterv, CSGetReducInMortMstID)
    addMapping(result, 'DiscRate', CS_3Perc, CS_10Perc, CSGetDiscRateMstID)
    addMapping(result, 'WRAAnemia', CS_WRA_Anemia, CS_WRA_Anemia, CSGetWRAAnemiaMstID)
    addMapping(result, 'WRAAnemia', CS_WRA_IronDeficAnemia, CS_WRA_IronDeficAnemia, CSGetWRAAnemiaMstID)
    addMapping(result, 'bMode', CS_bAuto, CS_bHigh, CSGetBModeMstID)
    addMapping(result, 'years', CS_0t1Yr, CS_5t6Yr, CSGetYearMstID)
    addMapping(result, 'CoDTypes', CS_FirstCoDType, CS_NumCoDTypes, CSGetDeathCauseTypeMstID)
    addMapping(result, 'SBCauses', CS_SB_FirstSBCause, CS_SB_MaxCauses, CSGetSB_MstCauseId)
    addMapping(result, 'AdolCauses', CS_Adol_FirstCause, CS_Adol_MaxCauses, CSGetAdol_MstDeathID)
    addMapping(result, 'ChildCauses', CS_FirstNNDeath, CS_FinalPostNNDeath, CSGetMstDeathId)
    addMapping(result, 'MatCauses', CS_Mat_MinDeathCauses, CS_Mat_MaxDeathCauses, CSGetMat_MstDeathId)
    addMapping(result, 'DiarPath', CS_FirstPathDiar, CS_NumPathsDiar, CSGetPathogenMstID, CS_Diarrhea)
    addMapping(result, 'PneumPath', CS_FirstPathPneum, CS_NumPathsPneum, CSGetPathogenMstID, CS_Pneumonia)
    addMapping(result, 'MeninPath', CS_FirstPathMenin, CS_NumPathsMenin, CSGetPathogenMstID, CS_Meningitis)
    addMapping(result, 'VaccDose', CS_FirstVaccDose, CS_MaxVaccDose, CSGetDoseMstID) 
    addMapping(result, 'Herd', CS_FirstVacc_Herd, CS_LastVacc_Herd, CSGetHerdVaccMstID)  
    addMapping(result, 'DetVacc', CS_FirstVacc_Det, CS_LastVacc_Det, CSGetVaccMstID)
    addMapping(result, 'NutDef', CS_FirstNutDef, CS_FinalNutDef, CSGetNutritionalDeficienciesMstID)
    addMapping(result, 'CCFI', CS_First_CCFI, CS_Max_CCFI, CSGetMstCCFI)
    addMapping(result, 'CSUAInputs', CSUA_FirstInput, CSUA_MaxInput, CSGetUAMstInputId)
    addMapping(result, 'DiarInterv', CS_FirstDiarInterv, CS_NumDiarIntervs, CSGetDiarIntervMstID)
    addMapping(result, 'SevDiarInterv', CS_RotavirusVacc_SevDiarInterv, CS_RotavirusVacc_SevDiarInterv, CSGetSevDiarIntervMstID)
    addMapping(result, 'PneumInterv', CS_HibVacc_PneumInterv, CS_ZincP_PneumInterv, CSGetPneumIntervMstID)
    addMapping(result, 'MeninInterv', CS_HibVacc_MeningInterv, CS_MeningA_MeningInterv, CSGetMeninIntervMstID)
    addMapping(result, 'IntervForBO', CS_FirstIntervForBO, CS_LastBOMax, CSGetIntervForBOMstIdFromCurID)
    addMapping(result, 'IntervForFI', CS_FirstIntervForFI, CS_FinalIntervForFIForCalcs, CSGetIntervForFIMstIdFromCurID)
    
    return result
    
def FinalIndices_init():
    result = Simple_Value_Init({})
    
    result['value'] = {}

    result['value']['NumAgeCohorts'] = CS_NumAgeCohorts
    result['value']['NumExtraAgeCohorts'] = CS_NumExtraAgeCohorts
    result['value']['MaxMaternalAnemia'] = CS_MaxMaternalAnemia
    result['value']['FinalSTD'] = CS_FinalSTD
    result['value']['Distr_Final'] = CS_Distr_Final
    result['value']['MaxBaselineMort'] = CS_MaxBaselineMort
    result['value']['MaxEndPoint'] = CS_MaxEndPoint
    result['value']['DxC_Final'] = CS_DxC_Final
    result['value']['NumAdolAgeCohorts'] = CS_NumAdolAgeCohorts
    result['value']['FinalCostCat'] = CS_FinalCostCat
    result['value']['FinalBenefitCat'] = CS_FinalBenefitCat    
    result['value']['MaxFinalYrAtWork'] = CS_MaxFinalYrAtWork
    result['value']['BaselineGDPFinal'] = CS_BaselineGDPFinal
    result['value']['CostBenFinal'] = CS_CostBenFinal
    result['value']['FactorsFinal'] = CS_FactorsFinal
    result['value']['MaxBFType'] = CS_MaxBFType
    result['value']['LastDetVaccRetroYr'] = CS_LastDetVaccRetroYr
    result['value']['MA_Final'] = CS_MA_Final
    result['value']['BO_Final'] = CS_BO_Final
    result['value']['BI_Final'] = CS_BI_Final
    result['value']['DefConstFinal'] = CS_DefConstFinal
    result['value']['EfficacyFinal'] = CS_EfficacyFinal
    result['value']['MaxPercCov'] = CS_MaxPercCov
    result['value']['ImpactsOnStuntingFinal'] = CS_ImpactsOnStuntingFinal
    result['value']['ImpactsOnWaste_MAX'] = CS_ImpactsOnWaste_MAX
    result['value']['PregFinal'] = CS_PregFinal
    result['value']['MAX_MatAnemia'] = CS_MAX_MatAnemia
    result['value']['ImpactPromoFinal'] = CS_ImpactPromoFinal
    result['value']['BFPromoFinal'] = CS_BFPromoFinal
    result['value']['InitBFFinal'] = CS_InitBFFinal
    result['value']['AnemicFinal'] = CS_AnemicFinal
    result['value']['AbortionFinal'] = CS_AbortionFinal
    result['value']['ReducInMortFinal'] = CS_ReducInMortFinal
    result['value']['DiscRateFinal'] = CS_DiscRateFinal
    result['value']['WRAAnemiaFinal'] = CS_WRAAnemiaFinal
    result['value']['BoundsFinal'] = CS_BoundsFinal
    result['value']['SB_MaxCauses'] = CS_SB_MaxCauses
    result['value']['Adol_MaxCauses'] = CS_Adol_MaxCauses
    result['value']['FinalPostNNDeath'] = CS_FinalPostNNDeath
    result['value']['Mat_MaxDeathCauses'] = CS_Mat_MaxDeathCauses
    result['value']['NumPathsDiar'] = CS_NumPathsDiar
    result['value']['NumPathsPneum'] = CS_NumPathsPneum
    result['value']['NumPathsMenin'] = CS_NumPathsMenin
    result['value']['MaxVaccDose'] = CS_MaxVaccDose
    result['value']['LastVacc_Herd'] = CS_LastVacc_Herd 
    result['value']['LastVacc_Det'] = CS_LastVacc_Det
    result['value']['FinalNutDef'] = CS_FinalNutDef
    result['value']['NumDiarIntervs'] = CS_NumDiarIntervs
    result['value']['NumSevDiarIntervs'] = CS_NumSevDiarIntervs
    result['value']['NumPneumIntervs'] = CS_NumPneumIntervs
    result['value']['NumMeningIntervs'] = CS_NumMeningIntervs
    result['value']['LastBOMax'] = CS_LastBOMax
    result['value']['FinalTerm'] = CS_FinalTerm

    return result
    
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                             Controls                                                     /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def MenARecommended_Init(DataByCountry_DB):
    result = Value_1DSource_Init()
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_MenArecommended]
    
    Fill_Data_DBC2(result, 'value', sourceData['values'], index)
    Fill_Source_DBC(result, sourceData, '0')

    result['value'] = bool(result['value'])

    return result

def IPTpCBChecked_Init(DataByCountry_DB):
    result = Value_1DSource_Init()
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_IPTPRec]
    
    Fill_Data_DBC2(result, 'value', sourceData['IPT recommended countries'], index)
    Fill_Source_DBC(result, sourceData, '0')

    result['value'] = bool(result['value'])

    return result

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                          Health status                                                   /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def NutrDefic_Init(DataByCountry_DB):
    result = {
        'value'       : np.zeros((CS_FinalNutDef+1)).tolist(),
        'exploreLiST' : np.zeros((CS_FinalNutDef+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(CS_FinalNutDef+1)
        }

    index = GetDBCBaseYearIndex(DataByCountry_DB)
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_NutritionalDeficiencies]
    
    for key, record in sourceData.items():
        if 'mstID' in record:
            mstID = record['mstID']
            currID = CSGetNutritionalDeficienciesCurrID(mstID)
            Fill_Data_DBC3(result['value'], record['values'], index, currID)      
            Fill_Data_DBC(YearRec, result['exploreLiST'][currID], record['values'])
            Fill_Sources_DBC(result, sourceData, str(mstID), currID)
    
    return result

def VitADefInPW_Init(DataByCountry_DB):
    result = Value_1DSource_Init()
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_VitADefInPW]
    
    Fill_Data_DBC2(result, 'value', sourceData['VitA deficiency in PW based on low serum retinol'], index)
    Fill_Source_DBC(result, sourceData, '0')

    return result

def StatusAtBirth_Init(DataByCountry_DB):
    result = {
        'value'       : np.zeros((CS_TermAGA+1)).tolist(),
        'exploreLiST' : np.zeros((CS_TermAGA+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(1)
        }
        
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_BaseBirthOutcomes]
    
    Fill_Data_DBC3(result['value'], sourceData['SGA-Preterm'], index, CS_PreTermSGA)
    Fill_Data_DBC3(result['value'], sourceData['AGA-Preterm'], index, CS_PreTermAGA)
    Fill_Data_DBC3(result['value'], sourceData['SGA-Term'], index, CS_TermSGA)
    Fill_Data_DBC3(result['value'], sourceData['AGA-Term'], index, CS_TermAGA)

    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_PreTermSGA], sourceData['SGA-Preterm'])
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_PreTermAGA], sourceData['AGA-Preterm'])
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_TermSGA], sourceData['SGA-Term'])
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_TermAGA], sourceData['AGA-Term'])
    
    Fill_Source_DBC(result, sourceData, '0')
    
    return result

def Incidence_Init(DataByCountry_DB, DBC_Tag):
    result = {
        'value'       : np.zeros(CS_NumAgeCohorts+1).tolist(),
        'endpoints'   : np.zeros(CS_MaxEndPoint+1).tolist(),
        'exploreLiST' : np.zeros((CS_NumAgeCohorts+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(1)
        }
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[DBC_Tag]
        
    key = 'Number of cases per child year'

    Fill_Data_DBC3(result['value'], sourceData[key]['0 to 1'], index, CS_0t1months)
    Fill_Data_DBC3(result['value'], sourceData[key]['1 to 5'], index, CS_1t6months)
    Fill_Data_DBC3(result['value'], sourceData[key]['6 to 11'], index, CS_6t12months)
    Fill_Data_DBC3(result['value'], sourceData[key]['12 to 23'], index, CS_12t24months)
    Fill_Data_DBC3(result['value'], sourceData[key]['24 to 59'], index, CS_24t60months)
    
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_0t1months], sourceData[key]['0 to 1'])
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_1t6months], sourceData[key]['1 to 5'])
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_6t12months], sourceData[key]['6 to 11'])
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_12t24months], sourceData[key]['12 to 23'])
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_24t60months], sourceData[key]['24 to 59'])
    
    Fill_Data_DBC3(result['endpoints'], sourceData[key]['Min'], index, CS_Min)
    Fill_Data_DBC3(result['endpoints'], sourceData[key]['Max'], index, CS_Max)

    Fill_Source_DBC(result, sourceData, '0')

    return result

def MaternalAnemia_Init(DataByCountry_DB):
    result = {
        'value'       : np.zeros(CS_MaxMaternalAnemia+1).tolist(),
        'exploreLiST' : np.zeros((CS_MaxMaternalAnemia+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(1)
        }

    index = GetDBCBaseYearIndex(DataByCountry_DB)
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_MaternalAnemia]
    
    Fill_Data_DBC3(result['value'], sourceData['% PW anemic'], index, CS_Preg_Anemia)
    Fill_Data_DBC3(result['value'], sourceData['% NPW anemic'], index, CS_NonPreg_Anemia)
    Fill_Data_DBC3(result['value'], sourceData['% anemia (PW) due to iron deficiency'], index, CS_Preg_IronDeficAnemia)
    Fill_Data_DBC3(result['value'], sourceData['% anemia (NPW) due to iron deficiency'], index, CS_NonPreg_IronDeficAnemia)
    
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_Preg_Anemia], sourceData['% PW anemic'])
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_NonPreg_Anemia], sourceData['% NPW anemic'])
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_Preg_IronDeficAnemia], sourceData['% anemia (PW) due to iron deficiency'])
    Fill_Data_DBC(YearRec, result['exploreLiST'][CS_NonPreg_IronDeficAnemia], sourceData['% anemia (NPW) due to iron deficiency'])    
    
    for i in GBRange(CS_Preg_Anemia, CS_NonPreg_IronDeficAnemia):
        result['value'][i] /= 100
        for t in GBRange(0, DataByCountry_DB['ProjFinalYearIdx']):
            result['exploreLiST'][i][t] /= 100
        
    Fill_Source_DBC(result, sourceData, '0')    

    return result

def PercWom15t49LowBMI_Init(DataByCountry_DB):
    result = {
        'value'       : 0,
        'exploreLiST' : np.zeros((DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(1)
        }
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_PercWom15t49LowBMI]
    
    Fill_Data_DBC2(result, 'value', sourceData['% of women of reproductive age with BMI <18.5'], index)
    Fill_Data_DBC(YearRec, result['exploreLiST'], sourceData['% of women of reproductive age with BMI <18.5'])
    
    Fill_Source_DBC(result, sourceData, '0')

    result['value'] /= 100
    for t in GBRange(0, DataByCountry_DB['ProjFinalYearIdx']):
        result['exploreLiST'][t] /= 100
        
    return result

def SyphilisAmongWRA_Init(DataByCountry_DB):
    result = {
        'value'       : 0,
        'exploreLiST' : np.zeros((DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(1)
        }
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_SyphilisAmongWRA]
    
    Fill_Data_DBC2(result, 'value', sourceData['values'], index)
    Fill_Data_DBC(YearRec, result['exploreLiST'], sourceData['values'])
    
    Fill_Source_DBC(result, sourceData, '0')

    result['value'] /= 100
    for t in GBRange(0, DataByCountry_DB['ProjFinalYearIdx']):
        result['exploreLiST'][t] /= 100
        
    return result

def PercExposedFalciparum_Init(DataByCountry_DB):
    result = {
        'value'       : 0,
        'exploreLiST' : np.zeros((DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(1)
        }

    index = GetDBCBaseYearIndex(DataByCountry_DB)
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_PercExposedFalciparum]
    
    Fill_Data_DBC2(result, 'value', sourceData['% women exposed to falciparum'], index)
    Fill_Data_DBC(YearRec, result['exploreLiST'], sourceData['% women exposed to falciparum'])
    Fill_Source_DBC(result, sourceData, '0')

    return result

def PercWomenWithPrevPreEclamp_Init(DataByCountry_DB):
    result = {
        'value'       : 0,
        'source'      : Create1DSrcArr(1)
        }

    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_PercWomenWithPrevPreEclamp]
    
    Fill_Data_DBC2(result, 'value', sourceData, index)
    Fill_Source_DBC(result, sourceData, '0')

    return result

def PercWomenWithChronicHypertension_Init(DataByCountry_DB):
    result = {
        'value'       : 0,
        'source'      : Create1DSrcArr(1)
        }

    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_PercWomenWithChronicHypertension]
    
    Fill_Data_DBC2(result, 'value', sourceData, index)
    Fill_Source_DBC(result, sourceData, '0')

    return result

def FolicAcidDeficPrev_Init(DataByCountry_DB):
    result = Value_1DSource_Init()
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_SBAffFractions]
    
    Fill_Data_DBC2(result, 'value', sourceData['Folic Acid Deficiency Prevalence'], index)
    Fill_Source_DBC(result, sourceData, '1')

    return result

def CongenitalDueToNTDsAF_Init(DataByCountry_DB):
    result = Value_1DSource_Init()
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_AffFractions]
    
    Fill_Data_DBC2(result, 'value', sourceData['Congenital due to NTDs AF'], index)
    Fill_Source_DBC(result, sourceData, '4')

    return result

def StuntWasteDistr_Init(DataByCountry_DB, DBC_Tag):
    result = Value_1DSource_Init(np.zeros((CS_GT3STD+1, CS_24t60months+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist())
       
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[DBC_Tag]
    
    def fillAgeData(a, key):   
        Fill_Data_DBC(YearRec, result['value'][CS_GT1STD][a], sourceData[key]['>-1 Z'])  
        Fill_Data_DBC(YearRec, result['value'][CS_1t2STD][a], sourceData[key]['-2 to -1Z'])  
        Fill_Data_DBC(YearRec, result['value'][CS_2t3STD][a], sourceData[key]['-3 to -2 Z'])  
        Fill_Data_DBC(YearRec, result['value'][CS_GT3STD][a], sourceData[key]['<-3 Z'])  

    fillAgeData(CS_0t1months, '0-1  month') 
    fillAgeData(CS_1t6months, '1-5 months')
    fillAgeData(CS_6t12months, '6-11 months')
    fillAgeData(CS_12t24months, '12-23 months')
    fillAgeData(CS_24t60months, '24-59 months')
    
    Fill_Source_DBC(result, sourceData, '0')   
    
    return result

def SingleStuntWasteDistr_Init(final_year_idx):
    return Value_1DSource_Init(np.zeros((final_year_idx+1)).tolist())

def PathFillData(result, index, YearRec, sourceData, distr, path, key):
    for a in GBRange(CS_FirstAgeCohort, CS_NumAgeCohorts):  
        Fill_Data_DBC3(result['value'][distr][path], sourceData[key][getDBCAgeKey(a)], index, a)
        Fill_Data_DBC(YearRec, result['exploreLiST'][distr][path][a], sourceData[key][getDBCAgeKey(a)])
    
def DiarrPath_Init(DataByCountry_DB):
    result = {
        'value'       : np.zeros((CS_Distr_Fatal+1, CS_MaxPathDiar+1, CS_24t60months+1)).tolist(),
        'exploreLiST' : np.zeros((CS_Distr_Fatal+1, CS_MaxPathDiar+1, CS_24t60months+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(1)
        }

    index = GetDBCBaseYearIndex(DataByCountry_DB)
    YearRec = Get_DBC_YearRec(DataByCountry_DB)

    sourceData = DataByCountry_DB[TG_PathSevDiarr]    
    PathFillData(result, index, YearRec, sourceData, CS_Distr_Sevr, CS_RotaPathDiar, 'Rotavirus Incidence')
    # Fill_Source_DBC(result, sourceData, '0')    
    
    sourceData = DataByCountry_DB[TG_PathAllDiarr]
    PathFillData(result, index, YearRec, sourceData, CS_Distr_All, CS_RotaPathDiar, 'Rotavirus Incidence')
    PathFillData(result, index, YearRec, sourceData, CS_Distr_All, CS_PathBDiar, 'Vaccine B incidence')
    PathFillData(result, index, YearRec, sourceData, CS_Distr_All, CS_PathCDiar, 'Vaccine C incidence')
    # Fill_Source_DBC(result, sourceData, '0')    
    
    sourceData = DataByCountry_DB[TG_PathMortDiarr]    
    PathFillData(result, index, YearRec, sourceData, CS_Distr_Fatal, CS_RotaPathDiar, 'Rotavirus mortality')
    PathFillData(result, index, YearRec, sourceData, CS_Distr_Fatal, CS_PathBDiar, 'Vaccine B mortality')
    PathFillData(result, index, YearRec, sourceData, CS_Distr_Fatal, CS_PathCDiar, 'Vaccine C mortality')
    # Fill_Source_DBC(result, sourceData, '0')
    
    return result

def PneumPath_Init(DataByCountry_DB):  
    result = {
        'value'       : np.zeros((CS_Distr_Fatal+1, CS_MaxPathPneum+1, CS_24t60months+1)).tolist(),
        'exploreLiST' : np.zeros((CS_Distr_Fatal+1, CS_MaxPathPneum+1, CS_24t60months+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(1)
        }
   
    index = GetDBCBaseYearIndex(DataByCountry_DB) 
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    
    def fillDistrData(sourceData, distr):
        PathFillData(result, index, YearRec, sourceData, distr, CS_HibPathPneumVT, 'H. influenzae type b') 
        PathFillData(result, index, YearRec, sourceData, distr, CS_PneumocPathPneum, 'S. pneumococcus (non-VT)') 
        PathFillData(result, index, YearRec, sourceData, distr, CS_PneumocPathPneumVT, 'S. pneumococcus (VT)')

    fillDistrData(DataByCountry_DB[TG_PathIncPneum], CS_Distr_Sevr) 
    fillDistrData(DataByCountry_DB[TG_PathMortPneum], CS_Distr_Fatal)        
            
    # Fill_Source_DBC(result, sourceData, '0')    
    
    return result

def MeninPath_Init(DataByCountry_DB):   
    result = {
        'value'       : np.zeros((CS_Distr_Fatal+1, CS_MaxPathMenin+1, CS_24t60months+1)).tolist(),
        'exploreLiST' : np.zeros((CS_Distr_Fatal+1, CS_MaxPathMenin+1, CS_24t60months+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(1)
        }
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    YearRec = Get_DBC_YearRec(DataByCountry_DB) 
    
    def fillDistrData(sourceData, distr):
        PathFillData(result, index, YearRec, sourceData, distr, CS_HibPathMeninVT, 'H. influenzae type b')
        PathFillData(result, index, YearRec, sourceData, distr, CS_PneumocPathMenin, 'S. pneumococcus (non-VT)')
        PathFillData(result, index, YearRec, sourceData, distr, CS_PneumocPathMeninVT, 'S. pneumococcus (VT)')
        PathFillData(result, index, YearRec, sourceData, distr, CS_MeningitPathMenin, 'N. meningitidis (non-NmA)')
        PathFillData(result, index, YearRec, sourceData, distr, CS_MeningitAPathMeninVT, 'N. meningitidis A')

    fillDistrData(DataByCountry_DB[TG_PathIncMening], CS_Distr_Sevr) 
    fillDistrData(DataByCountry_DB[TG_PathMortMening], CS_Distr_Fatal)        
            
    # Fill_Source_DBC(result, sourceData, '0')    
    
    return result

def BaselineMort_Init(DataByCountry_DB, exploreLiST, final_year_idx):
    if not exploreLiST:
        result = {
            'value'          : np.zeros((CS_MaxBaselineMort+1)).tolist(),
            'endpoints'      : np.zeros((CS_MaxEndPoint + 1, CS_MaxBaselineMort+1)).tolist(),
            'LogMean'        : np.zeros((CS_MaxBaselineMort+1)).tolist(),
            'LogSTD'         : np.zeros((CS_MaxBaselineMort+1)).tolist(),
            'CorrNMRandU5MR' : 0,
            'source'         : Create1DSrcArr(CS_MaxBaselineMort+1)
            }
        
        result['endpoints'][CS_MinEndPoint][CS_U5MR] = 0.01
        result['endpoints'][CS_MaxEndPoint][CS_U5MR] = 0.01

        result['endpoints'][CS_MinEndPoint][CS_NeonatalMR] = 0.01
        result['endpoints'][CS_MaxEndPoint][CS_NeonatalMR] = 0.01

        index = GetDBCBaseYearIndex(DataByCountry_DB)  
        sourceData = DataByCountry_DB[TG_MortalityRate]
        
        for key, record in sourceData.items():
            if   key == 'nmr'                         : Fill_Data_DBC3(result['value'], record['Value'], index, CS_NeonatalMR)     
            elif key == 'lognmrmean'                  : Fill_Data_DBC3(result['LogMean'], record, index, CS_NeonatalMR)      
            elif key == 'lognmrsd'                    : Fill_Data_DBC3(result['LogSTD'], record, index, CS_NeonatalMR)       
            elif key == 'imr'                         : Fill_Data_DBC3(result['value'], record, index, CS_InfantMR)      
            elif key == 'u5mr'                        : Fill_Data_DBC3(result['value'], record['Value'], index, CS_U5MR)      
            elif key == 'logU5mean'                   : Fill_Data_DBC3(result['LogMean'], record, index, CS_U5MR)       
            elif key == 'logU5sd'                     : Fill_Data_DBC3(result['LogSTD'], record, index, CS_U5MR)        
            elif key == 'Correlation of NMR and U5MR' : Fill_Data_DBC2(result, 'CorrNMRandU5MR', record, index)
    else:
        result = {
            'value'          : np.zeros((CS_MaxBaselineMort+1, final_year_idx+1)).tolist(),
            'endpoints'      : np.zeros((CS_MaxEndPoint + 1, CS_MaxBaselineMort+1, final_year_idx+1)).tolist(),
            'LogMean'        : np.zeros((CS_MaxBaselineMort+1, final_year_idx+1)).tolist(),
            'LogSTD'         : np.zeros((CS_MaxBaselineMort+1, final_year_idx+1)).tolist(),
            'CorrNMRandU5MR' : np.zeros((final_year_idx+1)).tolist(),
            'source'         : Create1DSrcArr(CS_MaxBaselineMort+1)
            }
        
        for t in GBRange(0, final_year_idx):
            result['endpoints'][CS_MinEndPoint][CS_U5MR][t] = 0.01
            result['endpoints'][CS_MaxEndPoint][CS_U5MR][t] = 0.01

            result['endpoints'][CS_MinEndPoint][CS_NeonatalMR][t] = 0.01
            result['endpoints'][CS_MaxEndPoint][CS_NeonatalMR][t] = 0.01

        YearRec = Get_DBC_YearRec(DataByCountry_DB) 
        sourceData = DataByCountry_DB[TG_MortalityRate]
        
        for key, record in sourceData.items():
            if   key == 'nmr'                         : Fill_Data_DBC(YearRec, result['value'][CS_NeonatalMR], record['Value'])  
            elif key == 'lognmrmean'                  : Fill_Data_DBC(YearRec, result['LogMean'][CS_NeonatalMR], record)      
            elif key == 'lognmrsd'                    : Fill_Data_DBC(YearRec, result['LogSTD'][CS_NeonatalMR], record)       
            elif key == 'imr'                         : Fill_Data_DBC(YearRec, result['value'][CS_InfantMR], record)      
            elif key == 'u5mr'                        : Fill_Data_DBC(YearRec, result['value'][CS_U5MR], record['Value'])      
            elif key == 'logU5mean'                   : Fill_Data_DBC(YearRec, result['LogMean'][CS_U5MR], record)       
            elif key == 'logU5sd'                     : Fill_Data_DBC(YearRec, result['LogSTD'][CS_U5MR], record)        
            elif key == 'Correlation of NMR and U5MR' : Fill_Data_DBC(YearRec, result['CorrNMRandU5MR'], record)

    for i in GBRange(CS_NeonatalMR, CS_U5MR):
        Fill_Sources_DBC(result, sourceData, str(i), i)
    
    return result

def PercDthByCause_Init(DataByCountry_DB, exploreLiST, final_year_idx):
    if not exploreLiST:
        result = {
            'value'     : np.zeros((CS_DxC_NoAIDS+1, CS_MaxDeathCauses+1, CS_24t60months+1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_MaxDeathCauses + 1)).tolist(),
            'alpha'     : np.zeros((CS_MaxDeathCauses+1)).tolist(),
            'beta'      : np.zeros((CS_MaxDeathCauses+1)).tolist(),
            'source'    : Create1DSrcArr(3)
            }
        
        for s in GBRange(1, CS_MaxDeathCauses):
            result['endpoints'][CS_MinEndPoint][s] = 0.05
            result['endpoints'][CS_MaxEndPoint][s] = 0.05

        index = GetDBCBaseYearIndex(DataByCountry_DB)  
        sourceData = DataByCountry_DB[TG_DeathsByCause]
        
        for key, record in sourceData.items():
            if 'mstID' in record:
                currID = CSGetCurDeathID(record['mstID'])

                if currID in CS_NNDeathCauseSet:
                    Fill_Data_DBC3(result['value'][CS_DxC_Default][currID], record['Value'], index, CS_0t1months) 
                    result['value'][CS_DxC_Default][currID][CS_0t1months] /= 100

                if currID in CS_PNNDeathCauseSet:
                    for a in GBRange(CS_1t6months, CS_24t60months):
                        Fill_Data_DBC3(result['value'][CS_DxC_Default][currID], record['Value'], index, a) 
                        result['value'][CS_DxC_Default][currID][a] /= 100
                
                Fill_Data_DBC3(result['endpoints'][CS_Min], record['Min'], index, currID) 
                Fill_Data_DBC3(result['endpoints'][CS_Max], record['Max'], index, currID)      
                result['endpoints'][CS_Min][currID] /= 100    
                result['endpoints'][CS_Max][currID] /= 100
    else:
        result = {
            'value'     : np.zeros((CS_DxC_NoAIDS+1, CS_MaxDeathCauses+1, CS_24t60months+1, final_year_idx+1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_MaxDeathCauses + 1, final_year_idx+1)).tolist(),
            'alpha'     : np.zeros((CS_MaxDeathCauses+1, final_year_idx+1)).tolist(),
            'beta'      : np.zeros((CS_MaxDeathCauses+1, final_year_idx+1)).tolist(),
            'source'    : Create1DSrcArr(3)
            }
        
        for t in GBRange(0, final_year_idx):
            for s in GBRange(1, CS_MaxDeathCauses):
                result['endpoints'][CS_MinEndPoint][s][t] = 0.05
                result['endpoints'][CS_MaxEndPoint][s][t] = 0.05

        YearRec = Get_DBC_YearRec(DataByCountry_DB) 
        sourceData = DataByCountry_DB[TG_DeathsByCause]
        
        for key, record in sourceData.items():
            if 'mstID' in record:
                currID = CSGetCurDeathID(record['mstID'])

                if currID in CS_NNDeathCauseSet:
                    Fill_Data_DBC(YearRec, result['value'][CS_DxC_Default][currID][CS_0t1months], record['Value']) 
                    for t in GBRange(0, final_year_idx):
                        result['value'][CS_DxC_Default][currID][CS_0t1months][t] /= 100

                if currID in CS_PNNDeathCauseSet:
                    for a in GBRange(CS_1t6months, CS_24t60months):
                        Fill_Data_DBC(YearRec, result['value'][CS_DxC_Default][currID][a], record['Value']) 
                        for t in GBRange(0, final_year_idx):
                            result['value'][CS_DxC_Default][currID][a][t] /= 100
                
                Fill_Data_DBC(YearRec, result['endpoints'][CS_Min][currID], record['Min']) 
                Fill_Data_DBC(YearRec, result['endpoints'][CS_Max][currID], record['Max'])      
                for t in GBRange(0, final_year_idx):
                    result['endpoints'][CS_Min][currID][t] /= 100    
                    result['endpoints'][CS_Max][currID][t] /= 100
    
    Fill_Sources_DBC(result, sourceData, '0', 1) 
    Fill_Sources_DBC(result, sourceData, '0', 2) 

    return result

def AdolMortRatio_Init(DataByCountry_DB, exploreLiST, final_year_idx):
    if not exploreLiST:
        result = {
            'value'     : np.zeros((GB_Female + 1, CS_15yrs_19yrs + 1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1)).tolist(),
            'mean'      : 0, 
            'sd'        : 0,
            'source'    : Create1DSrcArr(1)
            }
        
        result['endpoints'][CS_MinEndPoint] = 0.1
        result['endpoints'][CS_MaxEndPoint] = 0.1

        index = GetDBCBaseYearIndex(DataByCountry_DB)  
        sourceData = DataByCountry_DB[TG_BaselineAdolMort]
        
        for key, record in sourceData.items():
            if   key == '5 to 9'   : Fill_Data_DBC3(result['value'][GB_BothSexes], record['Both'], index, CS_5yrs_9yrs)
            elif key == '10 to 14' : Fill_Data_DBC3(result['value'][GB_BothSexes], record['Both'], index, CS_10yrs_14yrs)
            elif key == '15 to 19' : 
                for key2, record2 in record.items():
                    if   key2 == 'Male'   : Fill_Data_DBC3(result['value'][GB_Male], record2, index, CS_15yrs_19yrs)
                    elif key2 == 'Female' : Fill_Data_DBC3(result['value'][GB_Female], record2, index, CS_15yrs_19yrs)
                    elif key2 == 'Both'   : Fill_Data_DBC3(result['value'][GB_BothSexes], record2, index, CS_15yrs_19yrs)
    else:
        result = {
            'value'     : np.zeros((GB_Female + 1, CS_15yrs_19yrs + 1, final_year_idx + 1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, final_year_idx + 1)).tolist(),
            'mean'      : np.zeros((final_year_idx + 1)).tolist(), 
            'sd'        : np.zeros((final_year_idx + 1)).tolist(),
            'source'    : Create1DSrcArr(1)
            }
        
        for t in GBRange(0, final_year_idx):
            result['endpoints'][CS_MinEndPoint][t] = 0.1
            result['endpoints'][CS_MaxEndPoint][t] = 0.1

        YearRec = Get_DBC_YearRec(DataByCountry_DB) 
        sourceData = DataByCountry_DB[TG_BaselineAdolMort]
        
        for key, record in sourceData.items():
            if   key == '5 to 9'   : Fill_Data_DBC(YearRec, result['value'][GB_BothSexes][CS_5yrs_9yrs], record['Both'])
            elif key == '10 to 14' : Fill_Data_DBC(YearRec, result['value'][GB_BothSexes][CS_10yrs_14yrs], record['Both'])
            elif key == '15 to 19' : 
                for key2, record2 in record.items():
                    if   key2 == 'Male'   : Fill_Data_DBC(YearRec, result['value'][GB_Male][CS_15yrs_19yrs], record2)
                    elif key2 == 'Female' : Fill_Data_DBC(YearRec, result['value'][GB_Female][CS_15yrs_19yrs], record2)
                    elif key2 == 'Both'   : Fill_Data_DBC(YearRec, result['value'][GB_BothSexes][CS_15yrs_19yrs], record2)
    
    Fill_Source_DBC(result, sourceData, '0')
    
    return result

def PercAdolDeathsByCause_Init(DataByCountry_DB, exploreLiST, final_year_idx):
    
    def getSexIdx(key):
        if   key == '5 to 9'              : return GB_BothSexes
        elif key == '10 to 14'            : return GB_BothSexes
        elif key == '15 to 19 Male'       : return GB_Male
        elif key == '15 to 19 Female'     : return GB_Female
        elif key == '15 to 19 Both Sexes' : return GB_BothSexes
    
    def getAgeIdx(key):
        if   key == '5 to 9'              : return CS_5yrs_9yrs
        elif key == '10 to 14'            : return CS_10yrs_14yrs
        elif key == '15 to 19 Male'       : return CS_15yrs_19yrs
        elif key == '15 to 19 Female'     : return CS_15yrs_19yrs
        elif key == '15 to 19 Both Sexes' : return CS_15yrs_19yrs
    
    if not exploreLiST:
        result = {
            'value'     : np.zeros((CS_Adol_MaxCauses+1, GB_Female + 1, CS_15yrs_19yrs + 1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_Adol_MaxCauses + 1)).tolist(),
            'alpha'     : np.zeros((CS_Adol_MaxCauses+1)).tolist(),
            'beta'      : np.zeros((CS_Adol_MaxCauses+1)).tolist(),
            'source'    : Create1DSrcArr(1)
            }
        
        for s in GBRange(1, CS_Adol_MaxCauses):
            result['endpoints'][CS_MinEndPoint][s] = 0.05
            result['endpoints'][CS_MaxEndPoint][s] = 0.05

        index = GetDBCBaseYearIndex(DataByCountry_DB)  
        sourceData = DataByCountry_DB[TG_AdolDeathByCause]
        
        for key, record in sourceData.items():
            sex = getSexIdx(key)
            age = getAgeIdx(key)        
            for key2, record2 in record.items():
                if 'mstID' in record2:
                    currID = CSGetAdol_CurDeathID(record2['mstID'])
                    Fill_Data_DBC3(result['value'][currID][sex], record2['values'], index, age) 
    else:
        result = {
            'value'     : np.zeros((CS_Adol_MaxCauses+1, GB_Female + 1, CS_15yrs_19yrs + 1, final_year_idx+1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_Adol_MaxCauses + 1, final_year_idx+1)).tolist(),
            'alpha'     : np.zeros((CS_Adol_MaxCauses+1, final_year_idx+1)).tolist(),
            'beta'      : np.zeros((CS_Adol_MaxCauses+1, final_year_idx+1)).tolist(),
            'source'    : Create1DSrcArr(1)
            }
        
        for t in GBRange(0, final_year_idx):
            for s in GBRange(1, CS_Adol_MaxCauses):
                result['endpoints'][CS_MinEndPoint][s][t] = 0.05
                result['endpoints'][CS_MaxEndPoint][s][t] = 0.05

        YearRec = Get_DBC_YearRec(DataByCountry_DB) 
        sourceData = DataByCountry_DB[TG_AdolDeathByCause]
        
        for key, record in sourceData.items():
            sex = getSexIdx(key)
            age = getAgeIdx(key)                
            for key2, record2 in record.items():
                if 'mstID' in record2:
                    currID = CSGetAdol_CurDeathID(record2['mstID'])
                    Fill_Data_DBC(YearRec, result['value'][currID][sex][age], record2['values']) 
    
    Fill_Source_DBC(result, sourceData, '0') 

    return result

def MatMortRatio_Init(DataByCountry_DB, exploreLiST, final_year_idx):
    if not exploreLiST:
        result = {
            'value'     : 0,
            'endpoints' : np.zeros((CS_MaxEndPoint + 1)).tolist(),
            'mean'      : 0, 
            'sd'        : 0,
            'source'    : Create1DSrcArr(1)
            }
        
        result['endpoints'][CS_MinEndPoint] = 0.1
        result['endpoints'][CS_MaxEndPoint] = 0.1

        index = GetDBCBaseYearIndex(DataByCountry_DB)  
        sourceData = DataByCountry_DB[TG_BaselineMatMort]
        
        for key, record in sourceData.items():
            if   key == 'Maternal mortality ratio' : Fill_Data_DBC2(result, 'value', record, index)     
            elif key == 'Min'                      : Fill_Data_DBC3(result['endpoints'], record, index, CS_Min)      
            elif key == 'Max'                      : Fill_Data_DBC3(result['endpoints'], record, index, CS_Max)       
            elif key == 'Mean'                     : Fill_Data_DBC2(result, 'mean', record, index)      
            elif key == 'SD'                       : Fill_Data_DBC2(result, 'sd', record, index)  
    else:
        result = {
            'value'     : np.zeros((final_year_idx + 1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, final_year_idx + 1)).tolist(),
            'mean'      : np.zeros((final_year_idx + 1)).tolist(), 
            'sd'        : np.zeros((final_year_idx + 1)).tolist(),
            'source'    : Create1DSrcArr(1)
            }
        
        for t in GBRange(0, final_year_idx):
            result['endpoints'][CS_MinEndPoint][t] = 0.1
            result['endpoints'][CS_MaxEndPoint][t] = 0.1

        YearRec = Get_DBC_YearRec(DataByCountry_DB) 
        sourceData = DataByCountry_DB[TG_BaselineMatMort]
        
        for key, record in sourceData.items():
            if   key == 'Maternal mortality ratio' : Fill_Data_DBC(YearRec, result['value'], record)     
            elif key == 'Min'                      : Fill_Data_DBC(YearRec, result['endpoints'][CS_Min], record)      
            elif key == 'Max'                      : Fill_Data_DBC(YearRec, result['endpoints'][CS_Max], record)       
            elif key == 'Mean'                     : Fill_Data_DBC(YearRec, result['mean'], record)      
            elif key == 'SD'                       : Fill_Data_DBC(YearRec, result['sd'], record)  
    
    Fill_Source_DBC(result, sourceData, '0')
    
    return result

def PercMatDthByCause_Init(DataByCountry_DB, exploreLiST, final_year_idx):
    if not exploreLiST:
        result = {
            'value'     : np.zeros((CS_Mat_MaxDeathCauses+1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_Mat_MaxDeathCauses + 1)).tolist(),
            'alpha'     : np.zeros((CS_Mat_MaxDeathCauses+1)).tolist(),
            'beta'      : np.zeros((CS_Mat_MaxDeathCauses+1)).tolist(),
            'source'    : Create1DSrcArr(1)
            }
        
        for s in GBRange(1, CS_Mat_MaxDeathCauses):
            result['endpoints'][CS_MinEndPoint][s] = 0.05
            result['endpoints'][CS_MaxEndPoint][s] = 0.05

        index = GetDBCBaseYearIndex(DataByCountry_DB)  
        sourceData = DataByCountry_DB[TG_MatDeathByCause]
        
        for key, record in sourceData.items():
            if 'mstID' in record:
                currID = CSGetMat_CurDeathID(record['mstID'])

                Fill_Data_DBC3(result['value'], record['Value'], index, currID) 
                result['value'][currID] /= 100

                Fill_Data_DBC3(result['endpoints'][CS_Min], record['Min'], index, currID) 
                Fill_Data_DBC3(result['endpoints'][CS_Max], record['Max'], index, currID)      
                result['endpoints'][CS_Min][currID] /= 100    
                result['endpoints'][CS_Max][currID] /= 100
    else:
        result = {
            'value'     : np.zeros((CS_Mat_MaxDeathCauses+1, final_year_idx+1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_Mat_MaxDeathCauses + 1, final_year_idx+1)).tolist(),
            'alpha'     : np.zeros((CS_Mat_MaxDeathCauses+1, final_year_idx+1)).tolist(),
            'beta'      : np.zeros((CS_Mat_MaxDeathCauses+1, final_year_idx+1)).tolist(),
            'source'    : Create1DSrcArr(1)
            }
        
        for t in GBRange(0, final_year_idx):
            for s in GBRange(1, CS_Mat_MaxDeathCauses):
                result['endpoints'][CS_MinEndPoint][s][t] = 0.05
                result['endpoints'][CS_MaxEndPoint][s][t] = 0.05

        YearRec = Get_DBC_YearRec(DataByCountry_DB) 
        sourceData = DataByCountry_DB[TG_MatDeathByCause]
        
        for key, record in sourceData.items():
            if 'mstID' in record:
                currID = CSGetMat_CurDeathID(record['mstID'])

                Fill_Data_DBC(YearRec, result['value'][currID], record['Value']) 
                for t in GBRange(0, final_year_idx):
                    result['value'][currID][t] /= 100

                Fill_Data_DBC(YearRec, result['endpoints'][CS_Min][currID], record['Min']) 
                Fill_Data_DBC(YearRec, result['endpoints'][CS_Max][currID], record['Max'])      
                for t in GBRange(0, final_year_idx):
                    result['endpoints'][CS_Min][currID][t] /= 100    
                    result['endpoints'][CS_Max][currID][t] /= 100
    
    Fill_Source_DBC(result, sourceData, '0') 

    return result

def PercPregEndAbort_Init(DataByCountry_DB):
    result = {
        'value'       : 0,
        'exploreLiST' : np.zeros((DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create1DSrcArr(1)
        }
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)  
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_PercPregEndInAbort]
    
    Fill_Data_DBC2(result, 'value', sourceData['% pregnancies ending in spontaneous abortion'], index)
    Fill_Data_DBC(YearRec, result['exploreLiST'], sourceData['% pregnancies ending in spontaneous abortion'])
    Fill_Source_DBC(result, sourceData, '0')

    return result

def AbortIncRatio_Init(DataByCountry_DB):
    result = Value_1DSource_Init(np.zeros((DataByCountry_DB['ProjFinalYearIdx']+1)).tolist())
        
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_AbortIncRatio]
    
    Fill_Data_DBC(YearRec, result['value'], sourceData['Abortion incidence ratio'])
    Fill_Source_DBC(result, sourceData, '0')

    return result

def SBRate_Init(DataByCountry_DB, exploreLiST, final_year_idx):
    if not exploreLiST:
        result = {
            'value'     : 0,
            'endpoints' : np.zeros((CS_MaxEndPoint + 1)).tolist(),
            'mean'      : 0, 
            'sd'        : 0,
            'source'    : Create1DSrcArr(1)
            }
        
        result['endpoints'][CS_MinEndPoint] = 0.05
        result['endpoints'][CS_MaxEndPoint] = 0.05

        index = GetDBCBaseYearIndex(DataByCountry_DB)  
        sourceData = DataByCountry_DB[TG_BaselineSBRate]
        
        for key, record in sourceData.items():
            if   key == 'Stillbirth rate' : Fill_Data_DBC2(result, 'value', record, index)     
            elif key == 'Min'             : Fill_Data_DBC3(result['endpoints'], record, index, CS_Min)      
            elif key == 'Max'             : Fill_Data_DBC3(result['endpoints'], record, index, CS_Max)       
            elif key == 'Mean'            : Fill_Data_DBC2(result, 'mean', record, index)      
            elif key == 'sd'              : Fill_Data_DBC2(result, 'sd', record, index)  
    else:
        result = {
            'value'     : np.zeros((final_year_idx + 1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, final_year_idx + 1)).tolist(),
            'mean'      : np.zeros((final_year_idx + 1)).tolist(), 
            'sd'        : np.zeros((final_year_idx + 1)).tolist(),
            'source'    : Create1DSrcArr(1)
            }
        
        for t in GBRange(0, final_year_idx):
            result['endpoints'][CS_MinEndPoint][t] = 0.05
            result['endpoints'][CS_MaxEndPoint][t] = 0.05

        YearRec = Get_DBC_YearRec(DataByCountry_DB) 
        sourceData = DataByCountry_DB[TG_BaselineSBRate]
        
        for key, record in sourceData.items():
            if   key == 'Stillbirth rate' : Fill_Data_DBC(YearRec, result['value'], record)     
            elif key == 'Min'             : Fill_Data_DBC(YearRec, result['endpoints'][CS_Min], record)      
            elif key == 'Max'             : Fill_Data_DBC(YearRec, result['endpoints'][CS_Max], record)       
            elif key == 'Mean'            : Fill_Data_DBC(YearRec, result['mean'], record)      
            elif key == 'sd'              : Fill_Data_DBC(YearRec, result['sd'], record)  
    
    Fill_Source_DBC(result, sourceData, '0')
    
    return result

def SBCauses_Init(DataByCountry_DB, exploreLiST, final_year_idx):
    if not exploreLiST:
        result = {
            'value'     : np.zeros((CS_SB_MaxCauses+1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_SB_MaxCauses + 1)).tolist(),
            'alpha'     : np.zeros((CS_SB_MaxCauses+1)).tolist(),
            'beta'      : np.zeros((CS_SB_MaxCauses+1)).tolist(),
            'source'    : Create1DSrcArr(1)
            }
        
        for s in GBRange(1, CS_SB_MaxCauses):
            result['endpoints'][CS_MinEndPoint][s] = 0.05
            result['endpoints'][CS_MaxEndPoint][s] = 0.05

        index = GetDBCBaseYearIndex(DataByCountry_DB)  
        sourceData = DataByCountry_DB[TG_SBCauses]
        
        for key, record in sourceData.items():
            if 'mstID' in record:
                currID = CSGetSB_CurCauseID(record['mstID'])

                Fill_Data_DBC3(result['value'], record['Value'], index, currID) 
                result['value'][currID] /= 100

                Fill_Data_DBC3(result['endpoints'][CS_Min], record['Min'], index, currID) 
                Fill_Data_DBC3(result['endpoints'][CS_Max], record['Max'], index, currID)      
                result['endpoints'][CS_Min][currID] /= 100    
                result['endpoints'][CS_Max][currID] /= 100
    else:
        result = {
            'value'     : np.zeros((CS_SB_MaxCauses+1, final_year_idx+1)).tolist(),
            'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_SB_MaxCauses + 1, final_year_idx + 1)).tolist(),
            'alpha'     : np.zeros((CS_SB_MaxCauses+1, final_year_idx+1)).tolist(),
            'beta'      : np.zeros((CS_SB_MaxCauses+1, final_year_idx+1)).tolist(),
            'source'    : Create1DSrcArr(1)
            }
        
        for t in GBRange(0, final_year_idx):
            for s in GBRange(1, CS_SB_MaxCauses):
                result['endpoints'][CS_MinEndPoint][s][t] = 0.05
                result['endpoints'][CS_MaxEndPoint][s][t] = 0.05

        YearRec = Get_DBC_YearRec(DataByCountry_DB) 
        sourceData = DataByCountry_DB[TG_SBCauses]
        
        for key, record in sourceData.items():
            if 'mstID' in record:
                currID = CSGetSB_CurCauseID(record['mstID'])

                Fill_Data_DBC(YearRec, result['value'][currID], record['Value']) 
                for t in GBRange(0, final_year_idx):
                    result['value'][currID][t] /= 100

                Fill_Data_DBC(YearRec, result['endpoints'][CS_Min][currID], record['Min']) 
                Fill_Data_DBC(YearRec, result['endpoints'][CS_Max][currID], record['Max'])      
                for t in GBRange(0, final_year_idx):
                    result['endpoints'][CS_Min][currID][t] /= 100    
                    result['endpoints'][CS_Max][currID][t] /= 100
    
    Fill_Source_DBC(result, sourceData, '0') 

    return result

def PerCapitaInc_Init(DataByCountry_DB):
    result = Value_1DSource_Init(np.zeros((DataByCountry_DB['ProjFinalYearIdx']+1)).tolist())
    
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_EconomicStatus]
    
    Fill_Data_DBC(YearRec, result['value'], sourceData['% pop living below $1.90/day'])
    Fill_Source_DBC(result, sourceData, '0')       
    
    return result

def FoodInsecure_Init(DataByCountry_DB):
    result = Value_1DSource_Init(np.full((DataByCountry_DB['ProjFinalYearIdx']+1), -1).tolist())
       
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_AFBalancedEnergySupp]
    
    Fill_Data_DBC(YearRec, result['value'], sourceData, TG_AFBalancedEnergySupp)
    Fill_Source_DBC(result, sourceData, '0')       
       
    return result

def AvgHouseholdSize_Init(DataByCountry_DB):
    result = Value_1DSource_Init(np.zeros((DataByCountry_DB['ProjFinalYearIdx']+1)).tolist())
    
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_AvgHouseHoldSize]
    
    Fill_Data_DBC(YearRec, result['value'], sourceData['Average household size'])
    Fill_Source_DBC(result, sourceData, '0')       
    
    return result

def IncludeCostForBCR_Init():
    result = np.full(CS_FinalCostCat + 1, True)
    return result

def IncludeBenefitForBCR_Init():
    result = np.full(CS_FinalBenefitCat + 1, True)
    return result

def BaselineGDP_Init(DataByCountry_DB):
    result = Value_1DSource_Init(np.zeros((CS_PerWorker+1)).tolist())
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)  

    result['value'][CS_PerCapita] = getVal2(DataByCountry_DB[TG_GDPPerCapita], 'GDP per capita', index)
    result['value'][CS_PerWorker] = getVal2(DataByCountry_DB[TG_GDPPerCapita], 'GDP per worker', index)

    return result

# def AnnualPercGrowthRate_Init(DataByCountry_DB, GNI_Per_Cap_DB):
#     result = Value_1DSource_Init(np.zeros((DataByCountry_DB['ProjFinalYearIdx']+CS_MaxFinalYrAtWork+1)).tolist())
     
#     YearRec = Get_DBC_YearRec(DataByCountry_DB)
#     sourceData = DataByCountry_DB[TG_GNIPerCap]
    
#     YearRec['ProjFinalYearIdx'] += CS_MaxFinalYrAtWork
    
#     Fill_Data_DBC(YearRec, result['value'], sourceData['GNI per capita'], TG_GNIPerCap)
#     Fill_Source_DBC(result, sourceData, '0')   
  
#     #    The currently most recent year with data in general in the database is
#     #    2022, and the currently most recent year with data for GNI Per Capita
#     #    is 2019.  Whenever either of these things changes, an update will be
#     #    needed here to ensure the "value" is the actual most recent value
#     #    for GNI Per Capita.  Currently -3 makes sense because 2022 - 3 = 2019.
#     #    -Jared 3/6/2023
#     finalIndex = len(sourceData['GNI per capita']) - 1
#     value = sourceData['GNI per capita'][finalIndex - 3]

#     for t in GBRange((2020 - DataByCountry_DB['ProjFirstYear']), DataByCountry_DB['ProjFinalYearIdx'] + CS_MaxFinalYrAtWork):
        
#         if t > 0: 
#             value = result['value'][t-1]

#         year = DataByCountry_DB['ProjFirstYear'] + t

#         if t > -1:
#             if   2020 <= year <= 2025 : GrowthRate = GNI_Per_Cap_DB['2020-2025']
#             elif 2026 <= year <= 2030 : GrowthRate = GNI_Per_Cap_DB['2026-2030']
#             elif 2031 <= year <= 2035 : GrowthRate = GNI_Per_Cap_DB['2031-2035']
#             elif 2036 <= year <= 2040 : GrowthRate = GNI_Per_Cap_DB['2036-2040']
#             elif 2041 <= year <= 2045 : GrowthRate = GNI_Per_Cap_DB['2041-2045']
#             elif 2046 <= year <= 2050 : GrowthRate = GNI_Per_Cap_DB['2046-2050']
#             elif 2051 <= year <= 2055 : GrowthRate = GNI_Per_Cap_DB['2051-2055']
#             elif 2056 <= year <= 2060 : GrowthRate = GNI_Per_Cap_DB['2056-2060']
#             elif 2061 <= year <= 2065 : GrowthRate = GNI_Per_Cap_DB['2061-2065']
#             elif 2066 <= year <= 2070 : GrowthRate = GNI_Per_Cap_DB['2066-2070']
#             elif 2071 <= year <= 2075 : GrowthRate = GNI_Per_Cap_DB['2071-2075']
#             elif year >= 2076:          GrowthRate = GNI_Per_Cap_DB['2076-2080']

#             result['value'][t] = value * (1 + (GrowthRate / 100))
    
#     return result

def AnnualPercGrowthRate_Init(DataByCountry_DB, GNI_Per_Cap_DB, final_year_idx):
    result = Value_1DSource_Init(np.zeros((final_year_idx + CS_MaxFinalYrAtWork+1)).tolist())
        
    if not GNI_Per_Cap_DB == None:

        for t in GBRange(0, final_year_idx + CS_MaxFinalYrAtWork):
            year = DataByCountry_DB['ProjFirstYear'] + t
            
            if           year <= 2025 : GrowthRate = GNI_Per_Cap_DB['2020-2025']
            elif 2026 <= year <= 2030 : GrowthRate = GNI_Per_Cap_DB['2026-2030']
            elif 2031 <= year <= 2035 : GrowthRate = GNI_Per_Cap_DB['2031-2035']
            elif 2036 <= year <= 2040 : GrowthRate = GNI_Per_Cap_DB['2036-2040']
            elif 2041 <= year <= 2045 : GrowthRate = GNI_Per_Cap_DB['2041-2045']
            elif 2046 <= year <= 2050 : GrowthRate = GNI_Per_Cap_DB['2046-2050']
            elif 2051 <= year <= 2055 : GrowthRate = GNI_Per_Cap_DB['2051-2055']
            elif 2056 <= year <= 2060 : GrowthRate = GNI_Per_Cap_DB['2056-2060']
            elif 2061 <= year <= 2065 : GrowthRate = GNI_Per_Cap_DB['2061-2065']
            elif 2066 <= year <= 2070 : GrowthRate = GNI_Per_Cap_DB['2066-2070']
            elif 2071 <= year <= 2075 : GrowthRate = GNI_Per_Cap_DB['2071-2075']
            elif 2076 <= year <= 2080 : GrowthRate = GNI_Per_Cap_DB['2076-2080']
            elif 2081 <= year <= 2085 : GrowthRate = GNI_Per_Cap_DB['2081-2085']
            elif 2086 <= year <= 2090 : GrowthRate = GNI_Per_Cap_DB['2086-2090']
            elif 2091 <= year <= 2095 : GrowthRate = GNI_Per_Cap_DB['2091-2095']
            elif year >= 2096:          GrowthRate = GNI_Per_Cap_DB['2096-2100']

            result['value'][t] = GrowthRate  
    
    return result

def LaborForceParRate_Init(DataByCountry_DB, final_year_idx):
    result = Value_1DSource_Init(np.zeros((final_year_idx+CS_MaxFinalYrAtWork+1)).tolist())
    
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_LaborForceParRate]
    
    YearRec['ProjFinalYearIdx'] += CS_MaxFinalYrAtWork
    
    Fill_Data_DBC(YearRec, result['value'], sourceData['Labor force participation rate (%)'])
    Fill_Source_DBC(result, sourceData, '0')   

    return result

def FemaleLaborForceParRate_Init(DataByCountry_DB, final_year_idx):
    result = Value_1DSource_Init(np.zeros((final_year_idx+CS_MaxFinalYrAtWork+1)).tolist())
    
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_FemaleLaborForceParRate]
    
    YearRec['ProjFinalYearIdx'] += CS_MaxFinalYrAtWork
    
    Fill_Data_DBC(YearRec, result['value'], sourceData['Female labor force participation rate (15-64)'])
    Fill_Source_DBC(result, sourceData, '0')   
        
    return result

def PercGDPAllocWage_Init(DataByCountry_DB, final_year_idx):
    result = Value_1DSource_Init(np.zeros((final_year_idx+CS_MaxFinalYrAtWork+1)).tolist())
    
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_LaborShareOfInc]
    
    YearRec['ProjFinalYearIdx'] += CS_MaxFinalYrAtWork
    
    Fill_Data_DBC(YearRec, result['value'], sourceData['Percent of GDP allocated to wages'])
    Fill_Source_DBC(result, sourceData, '0')   
        
    return result

def DiscountRates_Init():
    result = Value_1DSource_Init(np.zeros((CS_Costs+1)).tolist())
    
    result['value'][CS_Benefits] = 3
    result['value'][CS_Costs] = 3

    return result

def Factors_Init():
    result = Value_1DSource_Init(np.zeros((CS_PercStillbirthsIncluded+1)).tolist())
    
    result['value'][CS_SocialValue] = 0.5
    result['value'][CS_PercStillbirthsIncluded] = 0.5

    return result

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                            Coverage                                                      /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def Coverage_Init(IVInfo, numIntervs, DataByCountry_DB, Readiness_DB, CSection_Cov_DB):    
    result = {
        'value'     : np.zeros((numIntervs+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'quality'   : np.zeros((numIntervs+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint+1, numIntervs+1)).tolist(),
        'source'    : Create1DSrcArr(numIntervs+1)
        }
    
    for i in GBRange(1, numIntervs):
        result['endpoints'][CS_MinEndPoint][i] = 0.05
        result['endpoints'][CS_MaxEndPoint][i] = 0.05

    index = GetDBCBaseYearIndex(DataByCountry_DB)  
    
    YearRec = Get_DBC_YearRec(DataByCountry_DB)   
    sourceData = DataByCountry_DB[TG_Coverage]
    
    IPTPValues = np.zeros((YearRec['DBC_FinalYr'] - YearRec['DBC_FirstYr'] + 1)).tolist()

    def SetCoverage(record, result, YearRec, index, currID):
        for key in ['Value', 'Sepsis case management']:
            if key in record: Fill_Data_DBC(YearRec, result['value'][currID], record[key])        
        if 'Quality' in record: Fill_Data_DBC(YearRec, result['quality'][currID], record['Quality'])    
        Fill_Data_DBC3(result['endpoints'][CS_Min], record['Min'], index, currID) 
        Fill_Data_DBC3(result['endpoints'][CS_Max], record['Max'], index, currID) 

    def handleIPTP(record, IPTPValues):
        if str(record['mstID']) == CS_IV_IPT_Mal_MST_ID:
            if not record['Value'] == CS_TG_Zeros:
                for t in GBRange(0, len(IPTPValues)-1):
                    IPTPValues[t] = max(record['Value'][t], IPTPValues[t])
                    record['Value'][t] = IPTPValues[t]
        return record, IPTPValues
    
    for key, record in sourceData.items():
        if 'mstID' in record and str(record['mstID']) in IVInfo :
            if (not CSIsVaccine(record['mstID'])):
                currID = IVInfo[str(record['mstID'])]['currID']
                record, IPTPValues = handleIPTP(record, IPTPValues)                
                SetCoverage(record, result, YearRec, index, currID)
                if record['mstID'] == CS_IV_ZincFort_MST_ID:
                    if IV_ZincSuppInPreg in IVInfo:
                        currID = IVInfo[IV_ZincSuppInPreg]['currID']
                        SetCoverage(record, result, YearRec, index, currID)

    if 'sources' in sourceData:
        for key, record in sourceData['sources'].items():
            mstID = str(key)
            if mstID in IVInfo :
                currID = IVInfo[mstID]['currID']
                Fill_Sources_DBC(result, sourceData, key, currID)

    return CalculateQuality(IVInfo, Readiness_DB, CSection_Cov_DB, YearRec, result)

def BFPrev_Init(DataByCountry_DB):
    result = Value_1DSource_Init(np.zeros((CS_NotBF+1, CS_24t60months+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist())
       
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_BreastFeeding]
    
    def fillAgeData(bf, a, key, key2):
        if key2 in sourceData[key]:
            Fill_Data_DBC(YearRec, result['value'][bf][a], sourceData[key][key2])  
    
    def fillBFData(bf, keySet):   
        for key in keySet:
            fillAgeData(bf, CS_0t1months, key, 'less than 1')    
            fillAgeData(bf, CS_1t6months, key, '1 to 5')   
            fillAgeData(bf, CS_6t12months, key, '6 to 11') 
            fillAgeData(bf, CS_12t24months, key, '12 to 23') 

    fillBFData(CS_ExclusiveBF, ['Exclusive breastfeeding']) 
    fillBFData(CS_PredominantBF, ['Predominant breastfeeding'])
    fillBFData(CS_PartialBF, ['Partial breastfeeding', 'Any breastfeeding'])
    fillBFData(CS_NotBF, ['Not breastfeeding'])

    Fill_Source_DBC(result, sourceData, '0')        
    
    return result

def EarlyInitBFPrev_Init(DataByCountry_DB):
    result = Value_1DSource_Init(np.zeros((CS_24t60months+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist())
    
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_EarlyInitBFPrev]
    
    for a in GBRange(CS_AgeSummary, CS_24t60months):     
        Fill_Data_DBC(YearRec, result['value'][a], sourceData['Early initiation'])
    
    Fill_Source_DBC(result, sourceData, '0')       
        
    return result

def RoutDetVaccCov_Init(IVInfo, DataByCountry_DB):
    result = {
        'value' : np.zeros((CS_LastVacc_Det+1, CS_MaxVaccDose+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'retro' : np.zeros((CS_LastVacc_Det+1, CS_MaxVaccDose+1, CS_DetVaccRetroOffset+1)).tolist()
        }
    
    YearRec = Get_DBC_YearRec(DataByCountry_DB)   
    sourceData = DataByCountry_DB[TG_Coverage]

    for key, record in sourceData.items():
        if 'mstID' in record and str(record['mstID']) in IVInfo :
            vt = CSGetVaccCurrID(record['mstID'])
            if (vt != 0):
                dose = CSGetDetVaccEquivDose(vt)
                for key2 in ['Value', '1 dose']:
                    if key2 in record:
                        Fill_Data_DBC(YearRec, result['value'][vt][dose], record[key2]) 

                        # For the vaccines, we have to save the data that is four years before the
                        # first year of the projection.  

                        for t in GBRange(CS_DetVacc1YrsRetro, CS_DetVacc4YrsRetro):     
                            
                            #NOTE: (Jared 4.29.23) this may be a new approach for the indices and we may need to 
                            # update the client appropriately.  Moving forward, index one will correspond to the 
                            # fourth year before the projection, index 2 will correspond to the third year before 
                            # the projection, and so on. So for example, if the first year of the projection was 2020:
                            #
                            #
                            #                          when t = 1, YearToRead = 2016
                            #                          when t = 2, YearToRead = 2017
                            #                          when t = 3, YearToRead = 2018
                            #                          when t = 4, YearToRead = 2019
                            #
                            #
                            
                            retroYear = (DataByCountry_DB['ProjFirstYear'] - (CS_DetVaccRetroOffset + 1) + t)

                            # 1. If the retro year is BEFORE the first database year,
                            #    the value will be zero.
                            
                            # 2. If the retro year is AFTER the final database year,
                            #    then grab the value corresponding to the last database year.
                            
                            # 3. If the retro year is within the range of database years, 
                            #    then grab the value corresponding to that year from database.                        

                            value = 0.0                 

                            finalIndex = len(record[key2]) - 1                         

                            if retroYear < DataByCountry_DB['firstYear']:
                                value = 0.0
                            
                            elif retroYear > DataByCountry_DB['finalYear']:
                                if not record[key2] == CS_TG_Zeros:
                                    value = record[key2][finalIndex]
                            
                            else:
                                for index in GBRange(0, finalIndex):
                                    if (retroYear == DataByCountry_DB['firstYear'] + index):
                                        if not record[key2] == CS_TG_Zeros:
                                            value = record[key2][index]

                            result['retro'][vt][dose][t] = value

    return result

def PentaDetVaccCov_Init(final_year_idx):
    return {
        'value' : np.zeros((final_year_idx+1)).tolist(),
        'retro' : np.zeros((CS_DetVaccRetroOffset+1)).tolist(),
        'source' : Create1DSrcArr(1)
        }

def VaccineSuppPerc_Init(final_year_idx):
    return {
        'value' : np.zeros((CS_LastVacc_Det+1, CS_48t60months+1, final_year_idx+1)).tolist(),
        'retro' : np.zeros((CS_LastVacc_Det+1, CS_48t60months+1, CS_DetVaccRetroOffset+1)).tolist()
        }

def AgeAndBirthOrderMatrix_Init(final_year_idx, easyFPData):
    result = Value_1DSource_Init(np.zeros((CS_35_49Yrs+1, CS_GTThirdBirth+1, final_year_idx+1)).tolist(), CS_35_49Yrs+1) 

    normValues = [0] * 9
    
    normValues[0] = easyFPData['MA_L18FirstBirth']
    normValues[1] = easyFPData['MA_L18_BO2_3']
    normValues[2] = easyFPData['MA_L18_BO_G3']    

    normValues[7] = easyFPData['MA18_34FirstBirth']
    normValues[3] = easyFPData['MA18_34BO2_3']
    normValues[4] = easyFPData['MA18_34BO_G3']

    normValues[8] = easyFPData['MA_G35FirstBirth']
    normValues[5] = easyFPData['MA_G35BO2_3']
    normValues[6] = easyFPData['MA_G35BO_G3']

    GBNormalize(normValues)

    for t in GBRange(0, final_year_idx):
        result['value'][CS_LT18Yrs][CS_FirstBirth][t] = normValues[0]
        result['value'][CS_18_34Yrs][CS_FirstBirth][t] = normValues[7]
        result['value'][CS_35_49Yrs][CS_FirstBirth][t] = normValues[8]

        result['value'][CS_LT18Yrs][CS_SecAndThirdBirths][t] = normValues[1]
        result['value'][CS_18_34Yrs][CS_SecAndThirdBirths][t] = normValues[3]
        result['value'][CS_35_49Yrs][CS_SecAndThirdBirths][t] = normValues[5]

        result['value'][CS_LT18Yrs][CS_GTThirdBirth][t] = normValues[2]
        result['value'][CS_18_34Yrs][CS_GTThirdBirth][t] = normValues[4]
        result['value'][CS_35_49Yrs][CS_GTThirdBirth][t] = normValues[6]
    
    return result

def BirthIntervalsMatrix_Init(final_year_idx, easyFPData):
    result = Value_1DSource_Init(np.zeros((CS_GE24Mths+1, final_year_idx+1)).tolist(), CS_GE24Mths+1)

    birthInterval = [0] * (CS_GE24Mths + 1)

    birthInterval[CS_FirstBirth] = easyFPData['firstBirthInterval']
    birthInterval[CS_LT18Mths]   = easyFPData['L18Months']
    birthInterval[CS_18to23Mths] = easyFPData['BO18_24Months']
    birthInterval[CS_GE24Mths]   = easyFPData['BO_24MonthsOrGreater']

    GBNormalize(birthInterval)

    for t in GBRange(0, final_year_idx):
        for i in GBRange(CS_FirstBirth, CS_GE24Mths):
            result['value'][i][t] = birthInterval[i]

    return result

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                            Maternal, Stillbirth, and Child Efficacy                                      /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def SetAffFromDBC(result, IVInfo, index, sourceData, mstID, d, key = '', divBy100 = False):        
    if type(sourceData) == dict and key in sourceData: sourceData = sourceData[key]    
    if sourceData == CS_TG_Zeros: return    
    if mstID in IVInfo:       
        currID = IVInfo[mstID]['currID']
        for dataType in GBRange(CS_Default, CS_Data):
            value = sourceData[index]                                
            if divBy100: value /= 100                
            result['value'][dataType][CS_AffecFract][currID][d] = value

def MatEff_Init(IVInfo, numIntervs, IVDefaultData_DB, DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AffecFract+1, numIntervs+1, CS_Mat_MaxDeathCauses+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, numIntervs+1, CS_Mat_MaxDeathCauses+1)).tolist(),
        'alpha'     : np.zeros((numIntervs+1, CS_Mat_MaxDeathCauses+1)).tolist(),
        'beta'      : np.zeros((numIntervs+1, CS_Mat_MaxDeathCauses+1)).tolist(),
        'source'    : Create2DSrcArr(CS_Mat_MaxDeathCauses+1, numIntervs+1)
        }    
    
    for dataType in GBRange(CS_Default, CS_Data):
        for currID in GBRange(1, numIntervs):
            for matD in GBRange(1, CS_Mat_MaxDeathCauses):
                result['value'][dataType][CS_AffecFract][currID][matD] = 1    
     
    for key, record in IVDefaultData_DB.items():
        if 'matDeathCauses' in record: 
            for key2, record2 in record['matDeathCauses'].items():
                if 'mstID' in record and str(record['mstID']) in IVInfo:
                    currID = IVInfo[str(record['mstID'])]['currID']
                    if 'mstID' in record2:
                        matD = CSGetMat_CurDeathID(record2['mstID'])            
                        if matD > 0:
                            for dataType in GBRange(CS_Default, CS_Data):
                                Fill_Data(result['value'][dataType][CS_Efficacy][currID], matD, record2, 'Eff')
                                Fill_Data(result['value'][dataType][CS_AffecFract][currID], matD, record2, 'Aff')
                            Fill_Data(result['endpoints'][CS_Min][currID], matD, record2, 'Min')
                            Fill_Data(result['endpoints'][CS_Max][currID], matD, record2, 'Max')
                            Fill_Data(result['alpha'][currID], matD, record2, 'alpha')
                            Fill_Data(result['beta'][currID], matD, record2, 'beta')
                            Fill_2D_Sources(result, matD, currID, record, 'MatSource')
 
    index = GetDBCBaseYearIndex(DataByCountry_DB)  
    
    sourceData = DataByCountry_DB[TG_EconomicStatus]    
    for matD in GBRange(1, CS_Mat_MaxDeathCauses):
        SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_BalEnergySupp_MST_ID, matD, '% pop living below $1.90/day', True)    

    sourceData = DataByCountry_DB[TG_MaternalAF]
    SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_SafeAbortServ_MST_ID, CS_Mat_Abortion, 'Safe abortions acting')
    SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_PostAbortCaseMgmt_MST_ID, CS_Mat_Abortion, 'Post abortion case management acting')
    SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_EctopicPregCaseMgmt_MST_ID, CS_Mat_Abortion, 'Ectopic pregnancy case management acting')
    SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_SurgeryChildbirth_MST_ID, CS_Mat_OtherDirectCauses, 'Cesarean delivery')
    SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_MalCaseMgmt_MST_ID, CS_Mat_IndirectCauses, 'Malaria case management acting')
    SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_TetToxVacc_MST_ID, CS_Mat_IndirectCauses, 'TT vaccination acting')
    SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_IPT_Mal_MST_ID, CS_Mat_IndirectCauses, 'IPTp (if recommended) acting on Indirect causes')
    #  Jared 3-20-17- See Adrienne's comment on ticket #357 on 3/16/17.  It seems like the value of affected fraction for ITN/IRS should be the
    #  same as the value of the affected fraction of IPTp. 
    SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_ITN_IRS_MST_ID, CS_Mat_IndirectCauses, 'IPTp (if recommended) acting on Indirect causes')

    sourceData = DataByCountry_DB[TG_AFStopSmokingEdu]
    for matD in GBRange(1, CS_Mat_MaxDeathCauses):
        SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_StopSmokingEduc_MST_ID, matD)    

    return result

def SBEff_Init(IVInfo, numIntervs, IVDefaultData_DB, DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AdjustedRR+1, numIntervs+1, CS_SB_MaxCauses+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, numIntervs+1, CS_SB_MaxCauses+1)).tolist(),
        'alpha'     : np.zeros((numIntervs+1, CS_SB_MaxCauses+1)).tolist(),
        'beta'      : np.zeros((numIntervs+1, CS_SB_MaxCauses+1)).tolist(),
        'source'    : Create2DSrcArr(CS_SB_MaxCauses+1, numIntervs+1)
        }    
    
    for dataType in GBRange(CS_Default, CS_Data):
        for currID in GBRange(1, numIntervs):
            for d in GBRange(1, CS_SB_MaxCauses):
                result['value'][dataType][CS_AffecFract][currID][d] = 1
                result['value'][dataType][CS_AdjustedRR][currID][d] = 1

    for key, record in IVDefaultData_DB.items():
        if 'SB_DeathCauses' in record: 
            for key2, record2 in record['SB_DeathCauses'].items():
                if 'mstID' in record and str(record['mstID']) in IVInfo:
                    currID = IVInfo[str(record['mstID'])]['currID']
                    if 'mstID' in record2:
                        d = CSGetSB_CurCauseID(record2['mstID'])            
                        if d > 0:
                            for dataType in GBRange(CS_Default, CS_Data):
                                Fill_Data(result['value'][dataType][CS_Efficacy][currID], d, record2, 'Eff')
                                Fill_Data(result['value'][dataType][CS_AffecFract][currID], d, record2, 'Aff')
                                Fill_Data(result['value'][dataType][CS_AdjustedRR][currID], d, record2, 'aRR')
                            Fill_Data(result['endpoints'][CS_Min][currID], d, record2, 'Min')
                            Fill_Data(result['endpoints'][CS_Max][currID], d, record2, 'Max')
                            Fill_Data(result['alpha'][currID], d, record2, 'alpha')
                            Fill_Data(result['beta'][currID], d, record2, 'beta')
                            Fill_2D_Sources(result, d, currID, record, 'SB_Source')

    index = GetDBCBaseYearIndex(DataByCountry_DB)  
    
    for d in GBRange(1, CS_SB_MaxCauses):
        sourceData = DataByCountry_DB[TG_EconomicStatus]    
        SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_BalEnergySupp_MST_ID, d, '% pop living below $1.90/day', True)    

        sourceData = DataByCountry_DB[TG_SBAffFractions]
        SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_SyphDetectTr_MST_ID, d, 'Syphilis Prevalence')
        SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_DiabCaseMgmt_MST_ID, d, 'Diabetes Prevalence')
        SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_HyperDisCaseMgmt_MST_ID, d, 'Hypertensive Disease Prevalence')
        
        sourceData = DataByCountry_DB[TG_AffFractions]
        SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_IPT_Mal_MST_ID, d, 'Malaria Affected Fraction')
        SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_FGRDetMgmt_MST_ID, d, 'FGR Affected Fraction')
    
        sourceData = DataByCountry_DB[TG_AFStopSmokingEdu]
        SetAffFromDBC(result, IVInfo, index, sourceData, CS_IV_StopSmokingEduc_MST_ID, d)    

    return result

def ChildEff_Init(IVInfo, numIntervs, DefaultData_DB, DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AffecFract+1, numIntervs+1, CS_MaxDeathCauses+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, numIntervs+1, CS_MaxDeathCauses+1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((numIntervs+1, CS_MaxDeathCauses+1, CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((numIntervs+1, CS_MaxDeathCauses+1, CS_24t60months+1)).tolist(),
        'source'    : Create2DSrcArr(CS_MaxDeathCauses+1, numIntervs+1)
        }    
    
    for dataType in GBRange(CS_Default, CS_Data):
        for currID in GBRange(1, numIntervs):
            for d in GBRange(1, CS_SB_MaxCauses):
                for a in GBRange(CS_AgeSummary, CS_24t60months):
                    result['value'][dataType][CS_AffecFract][currID][d][a] = 1

    def SetFromDefaultData(currID, d, a, record, key):
        for dataType in GBRange(CS_Default, CS_Data):
            Fill_Data(result['value'][dataType][CS_Efficacy][currID][d], a, record[key], 'Eff')
            Fill_Data(result['value'][dataType][CS_AffecFract][currID][d], a, record[key], 'Aff')
        Fill_Data(result['endpoints'][CS_Min][currID][d], a, record[key], 'Min')
        Fill_Data(result['endpoints'][CS_Max][currID][d], a, record[key], 'Max')
        Fill_Data(result['alpha'][currID][d], a, record[key], 'alpha')
        Fill_Data(result['beta'][currID][d], a, record[key], 'beta')
        Fill_2D_Sources(result, d, currID, record, 'source')

    sourceData = DefaultData_DB[TG_Efficacy]
    
    for key, record in sourceData.items():
        for key2, record2 in record.items():
            if 'mstID' in record:
                d = CSGetCurDeathID(record['mstID'])
                if d > 0:
                    if type(record2) == dict and 'mstID' in record2 and str(record2['mstID']) in IVInfo:
                        currID = IVInfo[str(record2['mstID'])]['currID']                                
                        for a in GBRange(CS_0t1months, CS_24t60months):     
                            key3 = getDefaultDataAgeKey(a)
                            if key3 in record2:                      
                                SetFromDefaultData(currID, d, a, record2, key3)

    index = GetDBCBaseYearIndex(DataByCountry_DB)  
    
    def SetFromDBC(sourceData, EffAff, mstID, d, a, key, key2 = ''):        
        if mstID in IVInfo:       
            currID = IVInfo[mstID]['currID']
            sourceData = sourceData[key]
            if type(sourceData) == dict and key2 in sourceData: sourceData = sourceData[key2]   
            if not sourceData == CS_TG_Zeros:
                for dataType in GBRange(CS_Default, CS_Data):
                    value = sourceData[index]
                    result['value'][dataType][EffAff][currID][d][a] = value

    key = 'Syphillis Affected Fraction for NN-Sepsis'
    SetFromDBC(DataByCountry_DB[TG_AffFractions], CS_AffecFract, CS_IV_SyphDetectTr_MST_ID, CS_NNSepsis, CS_0t1months, key)
    
    for a in GBRange(CS_AgeSummary, CS_24t60months):    
        if a != CS_0t1months:  
            SetFromDBC(DataByCountry_DB[TG_RotavirusEff], CS_Efficacy, CS_IV_RotavirusVacc_MST_ID, CS_Diarrhea, a, '2 dose', 'Value')
        SetFromDBC(DataByCountry_DB[TG_AffFrac], CS_AffecFract, CS_IV_SAM_MST_ID, CS_OtherInfecDis, a, 'Other due to malnutrition')
    
    for a in GBRange(CS_1t6months, CS_24t60months):    
        SetFromDBC(DataByCountry_DB[TG_PneumoEffMortPneum],  CS_Efficacy, CS_IV_PneuVacc_MST_ID, CS_Pneumonia, a, '3 doses', 'Value')
        SetFromDBC(DataByCountry_DB[TG_PneumoEffMortMening], CS_Efficacy, CS_IV_PneuVacc_MST_ID, CS_Meningitis, a, '3 doses', 'Value')
        SetFromDBC(DataByCountry_DB[TG_PathogenMortOther],   CS_AffecFract, CS_IV_PneuVacc_MST_ID, CS_OtherInfecDis, a, 'Pneumococcus', getDBCAgeKey(a))
        SetFromDBC(DataByCountry_DB[TG_PneumoEffMortOther],  CS_Efficacy, CS_IV_PneuVacc_MST_ID, CS_OtherInfecDis, a, '3 doses', 'Value')
    
    return result

def DetVaccEff_Init(IVInfo, DefaultData_DB, DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AffecFract+1, CS_LastVacc_Det+1, CS_FinalPostNNDeath+1, CS_MaxVaccDose+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_LastVacc_Det+1, CS_FinalPostNNDeath+1, CS_MaxVaccDose+1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((CS_LastVacc_Det+1, CS_FinalPostNNDeath+1, CS_MaxVaccDose+1, CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((CS_LastVacc_Det+1, CS_FinalPostNNDeath+1, CS_MaxVaccDose+1, CS_24t60months+1)).tolist(),
        'source'    : Create2DSrcArr(CS_FinalPostNNDeath+1, CS_LastVacc_Det+1)
        }    
    
    for dataType in GBRange(CS_Default, CS_Data):
        for vt in GBRange(CS_FirstVacc_Det, CS_LastVacc_Det):
            for dose in GBRange(1, CS_MaxVaccDose):
                for d in GBRange(CS_FirstPNNDeath, CS_FinalPostNNDeath):
                    for a in GBRange(CS_AgeSummary, CS_24t60months):
                        result['value'][dataType][CS_AffecFract][vt][d][dose][a] = 1

    def getDoseKey(dose):
        if   dose == CS_VaccDoseOne   : return 'Single'
        elif dose == CS_VaccDoseTwo   : return 'Double'
        elif dose == CS_VaccDoseThree : return 'Triple'
        elif dose == CS_VaccBooster   : return 'Booster'
        return ''

    def SetFromDefaultData(vt, d, dose, a, sourceRecord, dataRecord):
        for dataType in GBRange(CS_Default, CS_Data):
            Fill_Data(result['value'][dataType][CS_Efficacy][vt][d][dose], a, dataRecord, 'Eff')
            Fill_Data(result['value'][dataType][CS_AffecFract][vt][d][dose], a, dataRecord, 'Aff')
        Fill_Data(result['endpoints'][CS_Min][vt][d][dose], a, dataRecord, 'Min')
        Fill_Data(result['endpoints'][CS_Max][vt][d][dose], a, dataRecord, 'Max')
        Fill_Data(result['alpha'][vt][d][dose], a, dataRecord, 'alpha')
        Fill_Data(result['beta'][vt][d][dose], a, dataRecord, 'beta')
        Fill_2D_Sources(result, d, vt, sourceRecord, 'source')

    sourceData = DefaultData_DB[TG_DetVaccEff]
    
    for key, record in sourceData.items():
        for key2, record2 in record.items():
           if type(record2) == dict and 'mstID' in record2:
                for dose in GBRange(CS_VaccDoseOne, CS_VaccBooster):     
                    key3 = getDoseKey(dose)
                    if key3 in record2:               
                        record3 = record2[key3]
                        if str(record['mstID']) in IVInfo:
                            vt = CSGetVaccCurrID(record['mstID']) 
                            d = CSGetCurDeathID(record2['mstID'])                          
                            for a in GBRange(CS_0t1months, CS_24t60months):     
                                key4 = getDefaultDataAgeKey(a)
                                if key4 in record3:            
                                    if vt > 0 and d > 0:
                                        SetFromDefaultData(vt, d, dose, a, record3, record3[key4])

    index = GetDBCBaseYearIndex(DataByCountry_DB)  
    
    def SetEffFromDBC(sourceData, vt, d, dose, a, key):            
        for dataType in GBRange(CS_Default, CS_Data):
            Fill_Data_DBC3(result['value'][dataType][CS_Efficacy][vt][d][dose], sourceData[key]['Value'], index, a)      
        Fill_Data_DBC3(result['endpoints'][CS_Min][vt][d][dose], sourceData[key]['Min'], index, a)     
        Fill_Data_DBC3(result['endpoints'][CS_Max][vt][d][dose], sourceData[key]['Max'], index, a)    

    def SetAlphaBetaFromDBC(sourceData, vt, d, dose, a):            
        Fill_Data_DBC3(result['alpha'][vt][d][dose], sourceData['Alpha'], index, a)   
        Fill_Data_DBC3(result['beta'][vt][d][dose], sourceData['Beta'], index, a)   

    def setPneumoEffMort(tag, d, a):          
        SetEffFromDBC(DataByCountry_DB[tag], CS_PCV_Det, d, CS_VaccDoseOne, a, '1 dose')
        SetEffFromDBC(DataByCountry_DB[tag], CS_PCV_Det, d, CS_VaccDoseTwo, a, '2 doses')
        SetEffFromDBC(DataByCountry_DB[tag], CS_PCV_Det, d, CS_VaccDoseThree, a, '3 doses')        
        
        if not tag == TG_PneumoEffMortOther:   
            SetAlphaBetaFromDBC(DataByCountry_DB[tag], CS_PCV_Det, d, CS_VaccDoseThree, a)
    
    sourceData = DataByCountry_DB[TG_RotavirusEff]
    for a in GBRange(CS_AgeSummary, CS_24t60months):    
        if a != CS_0t1months:              
            SetEffFromDBC(sourceData, CS_Rota_Det, CS_Diarrhea, CS_VaccDoseOne, a, '1 dose')
            SetEffFromDBC(sourceData, CS_Rota_Det, CS_Diarrhea, CS_VaccDoseTwo, a, '2 dose')
            SetEffFromDBC(sourceData, CS_Rota_Det, CS_Diarrhea, CS_VaccDoseThree, a, '2 dose')            
            SetAlphaBetaFromDBC(sourceData, CS_Rota_Det, CS_Diarrhea, CS_VaccDoseTwo, a)
            SetAlphaBetaFromDBC(sourceData, CS_Rota_Det, CS_Diarrhea, CS_VaccDoseThree, a)
        
    for a in GBRange(CS_1t6months, CS_24t60months):    
        setPneumoEffMort(TG_PneumoEffMortOther, CS_OtherInfecDis, a)
        setPneumoEffMort(TG_PneumoEffMortPneum, CS_Pneumonia, a)
        setPneumoEffMort(TG_PneumoEffMortMening, CS_Meningitis, a)
        
        sourceData = DataByCountry_DB[TG_PathogenMortOther]['Pneumococcus'][getDBCAgeKey(a)]

        for dose in GBRange(CS_VaccDoseOne, CS_MaxVaccDose):
            for dataType in GBRange(CS_Default, CS_Data):
                Fill_Data_DBC3(result['value'][dataType][CS_AffecFract][CS_PCV_Det][CS_OtherInfecDis][dose], sourceData, index, a)   
    
    return result

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                           Effectiveness of interventions on incidence                                    /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def SetIncReduction_DefaultData(i, key, sourceData, result):
    if key in sourceData:                      
        for a in GBRange(CS_0t1months, CS_24t60months):     
            key2 = getDefaultDataAgeKey(a)
            if key2 in sourceData[key]:                      
                for dataType in GBRange(CS_Default, CS_Data):
                    Fill_Data(result['value'][dataType][i][CS_Efficacy], a, sourceData[key][key2], 'Eff')
                    Fill_Data(result['value'][dataType][i][CS_AffecFract], a, sourceData[key][key2], 'Aff')
                Fill_Data(result['endpoints'][CS_Min][i], a, sourceData[key][key2], 'Min')
                Fill_Data(result['endpoints'][CS_Max][i], a, sourceData[key][key2], 'Max')
                Fill_Data(result['alpha'][i], a, sourceData[key][key2], 'alpha')
                Fill_Data(result['beta'][i], a, sourceData[key][key2], 'beta')
                Fill_1D_Sources(result, i, sourceData[key], 'source')

def SetIncReduction_DBC(result, sourceData, index, key, i):    
    for a in GBRange(CS_AgeSummary, CS_24t60months):    
        if a != CS_0t1months:      
            for dataType in GBRange(CS_Default, CS_Data):
                Fill_Data_DBC3(result['value'][dataType][i][CS_Efficacy], sourceData[key], index, a)
            Fill_Data_DBC3(result['endpoints'][CS_Min][i], sourceData['Min'], index, a)
            Fill_Data_DBC3(result['endpoints'][CS_Max][i], sourceData['Max'], index, a)
            Fill_Data_DBC3(result['alpha'][i], sourceData['Alpha'], index, a)
            Fill_Data_DBC3(result['beta'][i], sourceData['Beta'], index, a)    

def DiarrIncReduction_Init(DefaultData_DB, DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_NumDiarIntervs+1, CS_AffecFract+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_NumDiarIntervs+1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((CS_NumDiarIntervs+1, CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((CS_NumDiarIntervs+1, CS_24t60months+1)).tolist(),
        'source'    : Create1DSrcArr(CS_NumDiarIntervs+1)
        }   
    
    for dataType in GBRange(CS_Default, CS_Data):
        for id in GBRange(CS_FirstDiarInterv, CS_NumDiarIntervs):
            for a in GBRange(CS_AgeSummary, CS_24t60months):
                result['value'][dataType][id][CS_AffecFract][a] = 1
    
    sourceData = DefaultData_DB[TG_ImpactDiarrInc]    
    
    for i in GBRange(CS_FirstDiarInterv, CS_NumDiarIntervs): 
        key = ''
        if   i == CS_BasicSanitation_DiarInterv         : key = 'Basic sanitation'
        elif i == CS_PointOfUseFilteredWater_DiarInterv : key = 'Point-of use filtered water'
        elif i == CS_PipedWater_DiarInterv              : key = 'Piped water'
        elif i == CS_HandWashWSoap_DiarInterv           : key = 'Hand washing with soap'
        elif i == CS_HygDisposalStools_DiarInterv       : key = 'Hygienic disposal of stools'
        elif i == CS_ZincP_DiarInterv                   : key = 'Zinc for prevention'
        elif i == CS_VitAPTwoDoses_DiarInterv           : key = 'Vitamin A for prevention'
        elif i == CS_DiarVaccPathB_DiarInterv           : key = 'Vaccine B'
        elif i == CS_DiarVaccPathC_DiarInterv           : key = 'Vaccine C'
        SetIncReduction_DefaultData(i, key, sourceData, result)
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)  
    SetIncReduction_DBC(result, DataByCountry_DB[TG_RotavirusEffAllDiar], index, '2 dose', CS_RotavirusVacc_DiarInterv)
    
    return result

def SevDiarrIncReduction_Init(DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_NumSevDiarIntervs+1, CS_AffecFract+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_NumSevDiarIntervs+1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((CS_NumSevDiarIntervs+1, CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((CS_NumSevDiarIntervs+1, CS_24t60months+1)).tolist(),
        'source'    : Create1DSrcArr(CS_NumSevDiarIntervs+1)
        }   
    
    for dataType in GBRange(CS_Default, CS_Data):
        for id in GBRange(CS_FirstSevDiarInterv, CS_NumSevDiarIntervs):
            for a in GBRange(CS_AgeSummary, CS_24t60months):
                result['value'][dataType][id][CS_AffecFract][a] = 1  

    index = GetDBCBaseYearIndex(DataByCountry_DB)  
    sourceData = DataByCountry_DB[TG_RotavirusEffSevDiar]
    
    i = CS_FirstSevDiarInterv
    
    for a in GBRange(CS_AgeSummary, CS_24t60months):
        if a != CS_0t1months:
            for key, record in sourceData.items():    
                if key == '2 dose' : 
                    for dataType in GBRange(CS_Default, CS_Data):
                        Fill_Data_DBC2(result['value'][dataType][i][CS_Efficacy], a, record, index)     
                elif key == 'Min'    : Fill_Data_DBC3(result['endpoints'][CS_Min][i], record, index, a)      
                elif key == 'Max'    : Fill_Data_DBC3(result['endpoints'][CS_Max][i], record, index, CS_Max)       
                elif key == 'Alpha'  : Fill_Data_DBC2(result['alpha'][i], a, record, index)      
                elif key == 'Beta'   : Fill_Data_DBC2(result['beta'][i], a, record, index)  
    
    Fill_Source_DBC(result, sourceData, '0')
    
    return result

def PneumIncReduction_Init(DefaultData_DB, DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_NumPneumIntervs+1, CS_AffecFract+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_NumPneumIntervs+1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((CS_NumPneumIntervs+1, CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((CS_NumPneumIntervs+1, CS_24t60months+1)).tolist(),
        'source'    : Create1DSrcArr(CS_NumPneumIntervs+1)
        }   
    
    for dataType in GBRange(CS_Default, CS_Data):
        for i in GBRange(CS_FirstPneumInterv, CS_NumPneumIntervs):
            for a in GBRange(CS_AgeSummary, CS_24t60months):
                result['value'][dataType][i][CS_AffecFract][a] = 1
    
    sourceData = DefaultData_DB[TG_ImpactPneumInc]    
    
    for i in GBRange(CS_FirstPneumInterv, CS_NumPneumIntervs): 
        key = ''
        if   i == CS_HibVacc_PneumInterv   : key = 'Hib vaccine'
        elif i == CS_PneumVacc_PneumInterv : key = 'Pneumococcal vaccine'
        elif i == CS_ZincP_PneumInterv     : key = 'Zinc for prevention'
        SetIncReduction_DefaultData(i, key, sourceData, result)

    index = GetDBCBaseYearIndex(DataByCountry_DB)   
    SetIncReduction_DBC(result, DataByCountry_DB[TG_PneumoEffIncPneum]['Incidence-Pneumonia'], index, 'Value', CS_PneumVacc_PneumInterv)
    
    return result

def MeninIncReduction_Init(DefaultData_DB, DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_NumMeningIntervs+1, CS_AffecFract+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_NumMeningIntervs+1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((CS_NumMeningIntervs+1, CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((CS_NumMeningIntervs+1, CS_24t60months+1)).tolist(),
        'source'    : Create1DSrcArr(CS_NumMeningIntervs+1)
        }   
    
    for dataType in GBRange(CS_Default, CS_Data):
        for i in GBRange(CS_FirstMeningInterv, CS_NumMeningIntervs):
            for a in GBRange(CS_AgeSummary, CS_24t60months):
                result['value'][dataType][i][CS_AffecFract][a] = 1
    
    sourceData = DefaultData_DB[TG_ImpactMeninInc]    
    
    for i in GBRange(CS_FirstMeningInterv, CS_NumMeningIntervs): 
        key = ''
        if   i == CS_HibVacc_MeningInterv   : key = 'Hib vaccine'
        elif i == CS_PneumVacc_MeningInterv : key = 'Pneumococcal vaccine'
        elif i == CS_MeningA_MeningInterv   : key = 'Meningococcal A'
        SetIncReduction_DefaultData(i, key, sourceData, result)

    index = GetDBCBaseYearIndex(DataByCountry_DB)  
    SetIncReduction_DBC(result, DataByCountry_DB[TG_PneumoEffIncMening]['Incidence-Meningitis'], index, 'Value', CS_PneumVacc_MeningInterv)
    
    return result

def RelRisks_Init(DefaultData_DB, tag):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AffecFract+1, CS_NotBF+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_NotBF+1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((CS_NotBF+1, CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((CS_NotBF+1, CS_24t60months+1)).tolist(),
        'source'    : Create1DSrcArr(CS_NotBF+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for i in GBRange(CS_ExclusiveBF, CS_NotBF):
            for a in GBRange(CS_AgeSummary, CS_24t60months):
                result['value'][dataType][CS_AffecFract][i][a] = 1
    
    sourceData = DefaultData_DB[tag]   
    
    for bf in GBRange(CS_ExclusiveBF, CS_NotBF): 
        key = ''
        if   bf == CS_ExclusiveBF   : key = 'Exclusive breastfeeding'
        elif bf == CS_PredominantBF : key = 'Predominant breastfeeding'
        elif bf == CS_PartialBF     : key = 'Partial breastfeeding'
        elif bf == CS_NotBF         : key = 'Not breastfeeding'
        if key in sourceData:                      
            for a in GBRange(CS_0t1months, CS_24t60months):     
                key2 = getDefaultDataAgeKey(a)
                if key2 in sourceData[key]:                      
                    for dataType in GBRange(CS_Default, CS_Data):
                        Fill_Data(result['value'][dataType][CS_Efficacy][bf], a, sourceData[key][key2], 'RR')
                        Fill_Data(result['value'][dataType][CS_AffecFract][bf], a, sourceData[key][key2], 'Aff')
                    Fill_Data(result['endpoints'][CS_Min][bf], a, sourceData[key][key2], 'Min')
                    Fill_Data(result['endpoints'][CS_Max][bf], a, sourceData[key][key2], 'Max')
                    Fill_Data(result['alpha'][bf], a, sourceData[key][key2], 'Mean')
                    Fill_Data(result['beta'][bf], a, sourceData[key][key2], 'sd')
                    Fill_1D_Sources(result, i, sourceData[key], 'source')

    return result

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                 Herd effectiveness of vaccines                                           /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def HerdVaccEff_Init(DataByCountry_DB):
    result = {
        'value'       : np.zeros((CS_Data+1, CS_LastVacc_Herd+1, CS_MaxDeathCauses+1, CS_MaxPercCov+1, CS_24t60months+1)).tolist(),
        'exploreLiST' : np.zeros((CS_Data+1, CS_LastVacc_Herd+1, CS_MaxDeathCauses+1, CS_MaxPercCov+1, CS_24t60months+1, DataByCountry_DB['ProjFinalYearIdx']+1)).tolist(),
        'source'      : Create2DSrcArr(CS_MaxDeathCauses+1, CS_LastVacc_Herd+1)
        }    

    index = GetDBCBaseYearIndex(DataByCountry_DB)
    YearRec = Get_DBC_YearRec(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_HerdEff]   

    for key, record in sourceData.items():
        vt = CSGetHerdVaccCurrID(record['mstID'])
        if vt > 0:
            for key2, record2 in record.items():
                if key2 != 'mstID':
                    for i in GBRange(CS_MinPercCov, CS_MaxPercCov): 
                        if (float(CSGetPercCovName(i)) / 100) == float(key2):
                            for d in CSGetHerdVaccDiseaseSet(vt):     
                                for a in GBRange(CS_0t1months, CS_24t60months): 
                                    for dataType in GBRange(CS_Default, CS_Data):                                
                                        Fill_Data_DBC2(result['value'][dataType][vt][d][i], a, record2, index)   
                                        Fill_Data_DBC(YearRec, result['exploreLiST'][dataType][vt][d][i][a], record2) 

                                        # Note from Bill on 2025-10-28
                                        # The default herd effect for the impact of Vacc C on Diarrhea
                                        # needs to be the same as it is for the impact of Rotavirus on Diarrhea
                                        if vt == CS_Rotavirus_Herd:
                                            if d == CS_Diarrhea:
                                                Fill_Data_DBC2(result['value'][dataType][CS_DiarVaccPathC_Herd][d][i], a, record2, index)   
                                                Fill_Data_DBC(YearRec, result['exploreLiST'][dataType][CS_DiarVaccPathC_Herd][d][i][a], record2) 
                                             
                            break

    return result

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                     Impact on food security                                              /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def ImpOnFoodSecurity_Init():
    return Simple_Value_Init(np.zeros((CS_Data + 1, CS_AffecFract + 1, CS_FinalIntervForFIForCalcs + 1)).tolist())

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                            Effectiveness of nutrition interventions                                      /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def AgeAndBirthOrder_Init(DefaultData_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AffecFract+1, CS_35_49Yrs+1, CS_GTThirdBirth+1, CS_TermAGA+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_35_49Yrs+1, CS_GTThirdBirth+1, CS_TermAGA+1)).tolist(),
        'source'    : Create2DSrcArr(CS_35_49Yrs+1, CS_GTThirdBirth+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for a in GBRange(CS_AllYrs, CS_35_49Yrs):
            for birthOrder in GBRange(CS_FirstBirth, CS_GTThirdBirth):
                for term in GBRange(CS_PreTermSGA, CS_TermAGA):
                    result['value'][dataType][CS_AffecFract][a][birthOrder][term] = 1
    
    sourceData = DefaultData_DB[TG_AgeAndBirthOrder] 
      
    for a in GBRange(CS_LT18Yrs, CS_35_49Yrs): 
        for birthOrder in GBRange(CS_FirstBirth, CS_GTThirdBirth): 
            key = ''
            if   a == CS_LT18Yrs  : key = '<18 years - '
            elif a == CS_18_34Yrs : key = '18-34 years- '
            elif a == CS_35_49Yrs : key = '35-49 years- '

            if   birthOrder == CS_FirstBirth        : key += 'first birth'
            elif birthOrder == CS_SecAndThirdBirths : key += 'second and third births'
            elif birthOrder == CS_GTThirdBirth      : key += 'greater than third birth'

            if key in sourceData:
                for term in GBRange(CS_PreTermSGA, CS_TermSGA): 
                    key2 = ''
                    if   term == CS_PreTermSGA : key2 = 'Pre-term SGA'
                    elif term == CS_PreTermAGA : key2 = 'Pre-term AGA'
                    elif term == CS_TermSGA    : key2 = 'Term SGA'
                    
                    if key2 in sourceData[key]:
                        for dataType in GBRange(CS_Default, CS_Data):
                            Fill_Data(result['value'][dataType][CS_Efficacy][a][birthOrder], term, sourceData[key][key2], 'RR')
                            Fill_Data(result['value'][dataType][CS_AffecFract][a][birthOrder], term, sourceData[key][key2], 'Aff')
                        Fill_Data(result['endpoints'][CS_Min][a][birthOrder], term, sourceData[key][key2], 'Min')
                        Fill_Data(result['endpoints'][CS_Max][a][birthOrder], term, sourceData[key][key2], 'Max')      
                
                Fill_2D_Sources(result, a, birthOrder, sourceData[key], 'source')
            
    return result

def BirthIntervals_Init(DefaultData_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AffecFract+1, CS_GE24Mths+1, CS_TermAGA+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_GE24Mths+1, CS_TermAGA+1)).tolist(),
        'alpha'     : np.zeros((CS_GE24Mths+1, CS_TermAGA+1)).tolist(),
        'beta'      : np.zeros((CS_GE24Mths+1, CS_TermAGA+1)).tolist(),
        'source'    : Create1DSrcArr(CS_GE24Mths+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for birthOrder in GBRange(CS_FirstBirth, CS_GE24Mths):
            for term in GBRange(CS_PreTermSGA, CS_TermAGA):
                result['value'][dataType][CS_AffecFract][birthOrder][term] = 1
    
    sourceData = DefaultData_DB[TG_BirthSpacing] 
      
    for birthOrder in GBRange(CS_FirstBirth, CS_GE24Mths): 
        key = ''
        if   birthOrder == CS_FirstBirth : key = 'First Birth'
        elif birthOrder == CS_LT18Mths   : key = '<18 months'
        elif birthOrder == CS_18to23Mths : key = '18 - 23 months'
        elif birthOrder == CS_GE24Mths   : key = '24 months or greater'

        if key in sourceData:
            for term in GBRange(CS_PreTermSGA, CS_TermSGA): 
                key2 = ''
                if   term == CS_PreTermSGA : key2 = 'Pre-term SGA'
                elif term == CS_PreTermAGA : key2 = 'Pre-term AGA'
                elif term == CS_TermSGA    : key2 = 'Term SGA'
                
                if key2 in sourceData[key]:
                    for dataType in GBRange(CS_Default, CS_Data):
                        Fill_Data(result['value'][dataType][CS_Efficacy][birthOrder], term, sourceData[key][key2], 'Eff')
                        Fill_Data(result['value'][dataType][CS_AffecFract][birthOrder], term, sourceData[key][key2], 'Aff')
                    Fill_Data(result['endpoints'][CS_Min][birthOrder], term, sourceData[key][key2], 'Min')
                    Fill_Data(result['endpoints'][CS_Max][birthOrder], term, sourceData[key][key2], 'Max')   
                    Fill_Data(result['alpha'][birthOrder], term, sourceData[key][key2], 'mean')
                    Fill_Data(result['beta'][birthOrder], term, sourceData[key][key2], 'sd')      
            
            Fill_1D_Sources(result, birthOrder, sourceData[key], 'source')

    return result

def IntervForBO_Init(DefaultData_DB, DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AdjustedRR+1, CS_LastBOMax+1, CS_TermAGA+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_LastBOMax+1, CS_TermAGA+1)).tolist(),
        'alpha'     : np.zeros((CS_LastBOMax+1, CS_TermAGA+1)).tolist(),
        'beta'      : np.zeros((CS_LastBOMax+1, CS_TermAGA+1)).tolist(),
        'source'    : Create1DSrcArr(CS_LastBOMax+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for i in GBRange(CS_FirstIntervForBO, CS_LastBOMax):
            for term in GBRange(CS_PreTermSGA, CS_TermAGA):
                result['value'][dataType][CS_AffecFract][i][term] = 1
                result['value'][dataType][CS_AdjustedRR][i][term] = 1
    
    sourceData = DefaultData_DB[TG_IntervForBO]       

    def setEff(i, currID, term, record, key):
        for dataType in GBRange(CS_Default, CS_Data):
            Fill_Data(result['value'][dataType][i][currID], term, record, key)
    
    for key, record in sourceData.items():
        def GetCurrIDSet(currID): 
            result = [currID]
            if currID == CS_MultMicroLowBMI : result = [CS_MultMicroLowBMI, CS_MultMicroNormBMI]
            if currID == CS_ZincFort        : result = [CS_ZincFort, CS_ZincSuppInPreg]
            return result        
        
        currID = CSGetIntervForBOCurIdFromMstID(record['mstID'])
        currIDSet = GetCurrIDSet(currID)
        
        for currID in currIDSet:                   
            for term in GBRange(CS_PreTermSGA, CS_TermSGA): 
                key2 = ''
                if   term == CS_PreTermSGA : key2 = 'Pre-term SGA'
                elif term == CS_PreTermAGA : key2 = 'Pre-term AGA'
                elif term == CS_TermSGA    : key2 = 'Term SGA'
                
                if key2 in record:
                    setEff(CS_Efficacy, currID, term, record[key2], 'Eff')
                    setEff(CS_AffecFract, currID, term, record[key2], 'Aff')
                    setEff(CS_AdjustedRR, currID, term, record[key2], 'Arr')
                    Fill_Data(result['endpoints'][CS_Min][currID], term, record[key2], 'Min')
                    Fill_Data(result['endpoints'][CS_Max][currID], term, record[key2], 'Max')       
                    Fill_Data(result['alpha'][currID], term, record[key2], 'alpha')
                    Fill_Data(result['beta'][currID], term, record[key2], 'beta')  
                
                Fill_1D_Sources(result, currID, record, 'source')

    index = GetDBCBaseYearIndex(DataByCountry_DB)
    
    sourceData = DataByCountry_DB[TG_EconomicStatus]    
    for term in GBRange(CS_PreTermSGA, CS_TermAGA): 
        for dataType in GBRange(CS_Default, CS_Data):          
            Fill_Data_DBC3(result['value'][dataType][CS_AffecFract][CS_BalEnergy], sourceData['% pop living below $1.90/day'], index, term)
   
    sourceData = DataByCountry_DB[TG_SBAffFractions]
    for term in GBRange(CS_PreTermSGA, CS_TermAGA): 
        for dataType in GBRange(CS_Default, CS_Data):
            Fill_Data_DBC3(result['value'][dataType][CS_AffecFract][CS_SyphilisTreat], sourceData['Syphilis Prevalence'], index, term)

    sourceData = DataByCountry_DB[TG_AFStopSmokingEdu]
    for term in GBRange(CS_PreTermSGA, CS_TermAGA): 
        for dataType in GBRange(CS_Default, CS_Data):
            Fill_Data_DBC3(result['value'][dataType][CS_AffecFract][CS_StopSmokingEduc], sourceData, index, term)

    return result

def ImpactOnStunt_Init(DefaultData_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_ImpactsOnStuntingFinal+1, CS_AffecFract+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_ImpactsOnStuntingFinal+1, CS_24t60months+1)).tolist(),
        'source'    : Create1DSrcArr(CS_ImpactsOnStuntingFinal+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for imp in GBRange(CS_ImpactsOnStuntingFirst, CS_ImpactsOnStuntingFinal):
            for a in GBRange(CS_AgeSummary, CS_24t60months):
                result['value'][dataType][imp][CS_AffecFract][a] = 1
    
    sourceData = DefaultData_DB[TG_ImpactsStunting] 
      
    def setData(imp, key, key2):
        if key in sourceData:
            if key2 in sourceData[key]:
                for a in GBRange(CS_0t1months, CS_24t60months):    
                    key3 = getDefaultDataAgeKey(a)
                    if key3 in sourceData[key][key2]:
                        for dataType in GBRange(CS_Default, CS_Data):
                            Fill_Data(result['value'][dataType][imp][CS_Efficacy], a, sourceData[key][key2][key3], 'OR')
                            Fill_Data(result['value'][dataType][imp][CS_AffecFract], a, sourceData[key][key2][key3], 'Aff')
                        Fill_Data(result['endpoints'][CS_Min][imp], a, sourceData[key][key2][key3], 'Min')
                        Fill_Data(result['endpoints'][CS_Max][imp], a, sourceData[key][key2][key3], 'Max')
                Fill_1D_Sources(result, imp, sourceData[key][key2], 'source')
   
    key = 'Impact of IUGR/Low birth weight on stunting'
    setData(CS_LowBirthWeight_TermAGA, key, 'Term AGA')
    setData(CS_LowBirthWeight_TermSGA, key, 'Term SGA')
    setData(CS_LowBirthWeight_PreTermAGA, key, 'Preterm AGA')
    setData(CS_LowBirthWeight_PreTermSGA, key, 'Preterm SGA')
    
    key = 'Impact of previous stunting on stunting'
    setData(CS_NotStuntedPrevAge, key, 'Not stunted at previous age cohort')
    setData(CS_StuntedPrevAge, key, 'Stunted at previous age cohort')
    
    key = 'Impact of complementary feeding on stunting'
    setData(CS_FoodSecureWPromo, key, 'Food secure with promotion and supplementation')
    setData(CS_FoodSecureWOPromo, key, 'Food secure with neither promotion nor supplementation')
    setData(CS_InsecureWPromoSupp, key, 'Food insecure with promotion and supplementation')
    setData(CS_InsecureWOPromoSupp, key, 'Food insecure with neither promotion nor supplementation')
    
    setData(CS_ImpDiarrPerEpisode, 'Impact of diarrhea on stunting', 'Impact of diarrhea per episode')
    
    key = 'Impact of Zinc supplementation on stunting'
    setData(CS_ZincSupp, key, 'Zinc supplemented')
    setData(CS_NotZincSupp, key, 'Not zinc supplemented')

    return result

def ImpactOnWaste_Init(DefaultData_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_ImpactsOnWaste_MAX+1, CS_AffecFract+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_ImpactsOnWaste_MAX+1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((CS_ImpactsOnWaste_MAX+1, CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((CS_ImpactsOnWaste_MAX+1, CS_24t60months+1)).tolist(),
        'source'    : Create1DSrcArr(CS_ImpactsOnWaste_MAX+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for imp in GBRange(CS_ImpactsOnWaste_Therafeed, CS_ImpactsOnWaste_MAX):
            for a in GBRange(CS_AgeSummary, CS_24t60months):
                result['value'][dataType][imp][CS_AffecFract][a] = 1
    
    for dataType in GBRange(CS_Default, CS_Data):
        for a in GBRange(CS_AgeSummary, CS_24t60months):
            result['value'][dataType][CS_ImpactsOnWaste_FractionChildrenMovModWastWithTreat][CS_Efficacy][a] = 0.06
            result['value'][dataType][CS_ImpactsOnWaste_FractionChildrenMovSevWastWithTreat][CS_Efficacy][a] = 0.10
    
    sourceData = DefaultData_DB[TG_ImpactWastingOnMort] 
      
    def setData(sourceData, imp, key, key2 = ''):
        if key in sourceData:       
            sourceData = sourceData[key]
            if key2 == '' or key2 in sourceData: 
                if key2 in sourceData: sourceData = sourceData[key2]
                for a in GBRange(CS_0t1months, CS_24t60months):    
                    key3 = getDefaultDataAgeKey(a)
                    if key3 in sourceData:
                        for dataType in GBRange(CS_Default, CS_Data):
                            Fill_Data(result['value'][dataType][imp][CS_Efficacy], a, sourceData[key3], 'Eff')
                            Fill_Data(result['value'][dataType][imp][CS_AffecFract], a, sourceData[key3], 'Aff')
                        Fill_Data(result['endpoints'][CS_Min][imp], a, sourceData[key3], 'Min')
                        Fill_Data(result['endpoints'][CS_Max][imp], a, sourceData[key3], 'Max')
                        Fill_Data(result['alpha'][imp], a, sourceData[key3], 'alpha')
                        Fill_Data(result['beta'][imp], a, sourceData[key3], 'beta')
                Fill_1D_Sources(result, imp, sourceData, 'source')
   
    key = 'Therapeutic feeding -- severe acute malnutrition recovery rate'
    setData(sourceData, CS_ImpactsOnWaste_Therafeed, key)
    
    key = 'Treatment of moderate acute malnutrition-- Moderate acute malnutrition recovery rate'
    setData(sourceData, CS_ImpactsOnWaste_FractionChildrenMovMildWastWithTreat, key)
    
    key = 'Impact of complementary feeding on wasting'
    setData(sourceData, CS_FoodSecureWPromo, key, 'Food secure with promotion and supplementation')
    setData(sourceData, CS_FoodSecureWOPromo, key, 'Food secure with neither promotion nor supplementation')
    setData(sourceData, CS_InsecureWPromoSupp, key, 'Food insecure with promotion and supplementation')
    setData(sourceData, CS_InsecureWOPromoSupp, key, 'Food insecure with neither promotion nor supplementation')

    return result

def ImpactOnMatAnemia_Init(DefaultData_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_NonPreg+1, CS_MAX_MatAnemia+1, CS_AffecFract+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_NonPreg+1, CS_MAX_MatAnemia+1)).tolist(),
        'alpha'     : np.zeros((CS_NonPreg+1, CS_MAX_MatAnemia+1)).tolist(),
        'beta'      : np.zeros((CS_NonPreg+1, CS_MAX_MatAnemia+1)).tolist(),
        'source'    : Create2DSrcArr(CS_NonPreg+1, CS_MAX_MatAnemia+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for n in GBRange(CS_Preg, CS_NonPreg):
            for i in GBRange(CS_IronFolatePW_MatAnemia, CS_MAX_MatAnemia):
                result['value'][dataType][n][i][CS_AffecFract] = 1
    
    sourceData = DefaultData_DB[TG_ImpactOnAnemia] 
      
    for i in GBRange(CS_IronFolatePW_MatAnemia, CS_MAX_MatAnemia): 
        key = ''
        if   i == CS_IronFolatePW_MatAnemia : key = 'Iron supplementation in pregnancy'
        elif i == CS_MMicroSuppPW_MatAnemia : key = 'Multiple micronutrient supplementation'
        elif i == CS_IronFortNPW_MatAnemia  : key = 'Iron fortification'
        elif i == CS_IPTP_MatAnemia         : key = 'Pregnant women protected via IPTP'
        elif i == CS_ITN_MatAnemia          : key = 'ITN ownership'

        if key in sourceData:
            for n in GBRange(CS_Preg, CS_NonPreg): 
                key2 = ''
                if   n == CS_Preg    : key2 = 'EFFECT ON PREGNANT WOMEN'
                elif n == CS_NonPreg : key2 = 'EFFECT ON NON-PREGNANT WOMEN'
                
                if key2 in sourceData[key]:
                    for dataType in GBRange(CS_Default, CS_Data):
                        Fill_Data(result['value'][dataType][n][i], CS_Efficacy, sourceData[key][key2], 'Eff')
                        Fill_Data(result['value'][dataType][n][i], CS_AffecFract, sourceData[key][key2], 'Aff')
                    Fill_Data(result['endpoints'][CS_Min][n], i, sourceData[key][key2], 'Min')
                    Fill_Data(result['endpoints'][CS_Max][n], i, sourceData[key][key2], 'Max')   
                    Fill_Data(result['alpha'][n], i, sourceData[key][key2], 'alpha')
                    Fill_Data(result['beta'][n], i, sourceData[key][key2], 'beta')      
            
                Fill_2D_Sources(result, n, i, sourceData[key], 'source')

    return result

def ImpactBFPromo_Init(DefaultData_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_ImpactPromoEarlyBF+1, CS_BFPromoBoth+1, CS_AffecFract+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_ImpactPromoEarlyBF+1, CS_BFPromoBoth+1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((CS_ImpactPromoEarlyBF+1, CS_BFPromoBoth+1, CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((CS_ImpactPromoEarlyBF+1, CS_BFPromoBoth+1, CS_24t60months+1)).tolist(),
        'source'    : Create2DSrcArr(CS_ImpactPromoEarlyBF+1, CS_BFPromoBoth+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for i in GBRange(CS_ImpactPromoBF, CS_ImpactPromoEarlyBF):
            for opt in GBRange(CS_BFPromoHealthSystem, CS_BFPromoBoth):
                for a in GBRange(CS_AgeSummary, CS_24t60months):
                    result['value'][dataType][i][opt][CS_AffecFract][a] = 1
    
    sourceData = DefaultData_DB[TG_BFImprovement] 
    
    def setData(i, opt, key):
        if key in sourceData:       
            for a in GBRange(CS_0t1months, CS_24t60months):    
                key2 = getDefaultDataAgeKey(a)
                if key2 in sourceData[key]:
                    for dataType in GBRange(CS_Default, CS_Data):
                        Fill_Data(result['value'][dataType][i][opt][CS_Efficacy], a, sourceData[key][key2], 'OR')
                        Fill_Data(result['value'][dataType][i][opt][CS_AffecFract], a, sourceData[key][key2], 'Aff')
                    Fill_Data(result['endpoints'][CS_Min][i][opt], a, sourceData[key][key2], 'Min')
                    Fill_Data(result['endpoints'][CS_Max][i][opt], a, sourceData[key][key2], 'Max')
                    Fill_Data(result['alpha'][i][opt], a, sourceData[key][key2], 'mean')
                    Fill_Data(result['beta'][i][opt], a, sourceData[key][key2], 'sd')
            Fill_2D_Sources(result, i, opt, sourceData[key], 'source')
   
    setData(CS_ImpactPromoBF, CS_BFPromoHealthSystem, 'impact of promotion on breastfeeding - Health system')
    setData(CS_ImpactPromoBF, CS_BFPromoHomeComm, 'impact of promotion on breastfeeding - Home/community')
    setData(CS_ImpactPromoBF, CS_BFPromoBoth, 'impact of promotion on breastfeeding - Health system + home/community')
    setData(CS_ImpactPromoEarlyBF, CS_BFPromoHealthSystem, 'impact of promotion on early initiation of breastfeeding - Health system')
    setData(CS_ImpactPromoEarlyBF, CS_BFPromoHomeComm, 'impact of promotion on early initiation of breastfeeding - Home/community')
    setData(CS_ImpactPromoEarlyBF, CS_BFPromoBoth, 'impact of promotion on early initiation of breastfeeding - Health system + home/community')
  
    return result

def KMConBF_Init(DefaultData_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AffecFract+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((CS_24t60months+1)).tolist(),
        'source'    : Create1DSrcArr(1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for a in GBRange(CS_AgeSummary, CS_24t60months):
            result['value'][dataType][CS_AffecFract][a] = 1
    
    sourceData = DefaultData_DB[TG_BFImprovement] 
    
    key = 'Kangaroo mother care on breastfeeding'
    if key in sourceData:       
        for a in GBRange(CS_0t1months, CS_24t60months):    
            key2 = getDefaultDataAgeKey(a)
            if key2 in sourceData[key]:
                for dataType in GBRange(CS_Default, CS_Data):
                    Fill_Data(result['value'][dataType][CS_Efficacy], a, sourceData[key][key2], 'OR')
                    Fill_Data(result['value'][dataType][CS_AffecFract], a, sourceData[key][key2], 'Aff')
                Fill_Data(result['endpoints'][CS_Min], a, sourceData[key][key2], 'Min')
                Fill_Data(result['endpoints'][CS_Max], a, sourceData[key][key2], 'Max')
                Fill_Data(result['alpha'], a, sourceData[key][key2], 'mean')
                Fill_Data(result['beta'], a, sourceData[key][key2], 'sd')
                
        Fill_Source(result, sourceData[key], 'source')

    return result

def LBWF_Init(DataByCountry_DB):
    result = Value_1DSource_Init(np.zeros((CS_Data+1, CS_TermAGA+1)).tolist(), CS_TermAGA+1)
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_LBWConversionAlgorithm]
    
    for dataType in GBRange(CS_Default, CS_Data):
        Fill_Data_DBC3(result['value'][dataType], sourceData['Term-AGA'], index, CS_TermAGA)
        Fill_Data_DBC3(result['value'][dataType], sourceData['Term-SGA'], index, CS_TermSGA)
        Fill_Data_DBC3(result['value'][dataType], sourceData['Preterm-AGA'], index, CS_PreTermAGA)
        Fill_Data_DBC3(result['value'][dataType], sourceData['Preterm-SGA'], index, CS_PreTermSGA)
    
    Fill_Source_DBC(result, sourceData, '0')
    
    return result

def ReducStunt_Init(DefaultData_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AffecFract+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1)).tolist(), 
        'source'    : Create1DSrcArr(1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        result['value'][dataType][CS_AffecFract] = 1
    
    sourceData = DefaultData_DB[TG_ReducInStunt]

    for dataType in GBRange(CS_Default, CS_Data):
        Fill_Data(result['value'][dataType], CS_Efficacy, sourceData, 'Eff')
        Fill_Data(result['value'][dataType], CS_AffecFract, sourceData, 'Aff')
    Fill_Data(result['endpoints'], CS_Min, sourceData, 'Min')
    Fill_Data(result['endpoints'], CS_Max, sourceData, 'Max')
            
    Fill_Source(result, sourceData, 'source')
    
    return result

def EducAttain_Init(DefaultData_DB, DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_AffecFract+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1)).tolist(), 
        'source'    : Create1DSrcArr(1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        result['value'][dataType][CS_AffecFract] = 1
    
    sourceData = DefaultData_DB[TG_EducAttain]

    for dataType in GBRange(CS_Default, CS_Data):
        Fill_Data(result['value'][dataType], CS_Efficacy, sourceData, 'Eff')
        Fill_Data(result['value'][dataType], CS_AffecFract, sourceData, 'Aff')
    Fill_Data(result['endpoints'], CS_Min, sourceData, 'Min')
    Fill_Data(result['endpoints'], CS_Max, sourceData, 'Max')
            
    Fill_Source(result, sourceData, 'source')
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_EconReturnsToSchool]
    for dataType in GBRange(CS_Default, CS_Data):
        Fill_Data_DBC3(result['value'][dataType], sourceData['Economic Returns to Schooling (%)'], index, CS_Efficacy)
        result['value'][dataType][CS_Efficacy] /= 100
    
    return result

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                             Impact of under-nutrition on mortality                                       /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def RelRisksStuntWast_Init(DefaultData_DB, DataByCountry_DB, tag):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_MaxDeathCauses+1, CS_AffecFract+1, CS_GT3STD+1, CS_24t60months+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_MaxDeathCauses+1, CS_GT3STD+1, CS_24t60months+1)).tolist(),
        'alpha'     : np.zeros((CS_MaxDeathCauses+1, CS_GT3STD+1, CS_24t60months+1)).tolist(),
        'beta'      : np.zeros((CS_MaxDeathCauses+1, CS_GT3STD+1, CS_24t60months+1)).tolist(),
        'source'    : Create2DSrcArr(CS_MaxDeathCauses+1, CS_GT3STD+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for d in GBRange(1, CS_MaxDeathCauses):
            for std in GBRange(CS_GT1STD, CS_GT3STD):
                for a in GBRange(CS_AgeSummary, CS_24t60months):
                    result['value'][dataType][d][CS_AffecFract][std][a] = 1
    
    sourceData = DefaultData_DB[tag]

    def setData(record, d, sd, key):
        if key in record:
            for a in GBRange(CS_0t1months, CS_24t60months):            
                key2 = getDefaultDataAgeKey(a)                            
                if key2 in record[key]:
                    for dataType in GBRange(CS_Default, CS_Data):
                        Fill_Data(result['value'][dataType][d][CS_Efficacy][sd], a, record[key][key2], 'RR')
                        Fill_Data(result['value'][dataType][d][CS_AffecFract][sd], a, record[key][key2], 'Aff')
                    Fill_Data(result['endpoints'][CS_Min][d][sd], a, record[key][key2], 'Min')
                    Fill_Data(result['endpoints'][CS_Max][d][sd], a, record[key][key2], 'Max')
                    Fill_Data(result['alpha'][d][sd], a, record[key][key2], 'mean')
                    Fill_Data(result['beta'][d][sd], a, record[key][key2], 'sd')
            Fill_2D_Sources(result, d, sd, record[key], 'source')

    for key, record in sourceData.items():
        d = CSGetCurDeathID(record['mstID'])
        if d > 0:
            setData(record, d, CS_GT1STD, 'is greater than 1 standard deviation less than the median norm')
            setData(record, d, CS_1t2STD, 'between 1 and 2 standard deviations less than the median norm')
            setData(record, d, CS_2t3STD, 'between 2 and 3 standard deviations less than the median norm')
            setData(record, d, CS_GT3STD, 'more than 3 standard deviations less than median norm')
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_AFRiskStuntWasteInfDis]  
    for dataType in GBRange(CS_Default, CS_Data):        
        for sd in GBRange(CS_GT1STD, CS_GT3STD):            
            for a in GBRange(CS_AgeSummary, CS_24t60months):            
                Fill_Data_DBC3(result['value'][dataType][CS_OtherInfecDis][CS_AffecFract][sd], sourceData['Other due to infectious diseases'], index, a)
                    
    return result

def RelRisksIUGR_LBW_Init(DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_MaxDeathCauses+1, CS_TermAGA+1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_MaxDeathCauses+1, CS_TermAGA+1)).tolist(), 
        'source'    : Create1DSrcArr(1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for d in GBRange(CS_FirstNNDeath, CS_FinalNNDeath):
            for term in GBRange(CS_PreTermSGA, CS_TermAGA):
                result['value'][dataType][d][term] = 1
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_ImpactBirthOutcomesOnMort]  

    def setData(term, key):
        if key in sourceData:
            for key2, record in sourceData[key].items():
                d = CSGetCurDeathID(record['mstID'])
                if d > 0:        
                    for dataType in GBRange(CS_Default, CS_Data):
                        Fill_Data_DBC3(result['value'][dataType][d], record["values"], index, term)
                        
    setData(CS_PreTermSGA, 'SGA Preterm')
    setData(CS_PreTermAGA, 'AGA Preterm')
    setData(CS_TermSGA, 'SGA term')
    setData(CS_TermAGA, 'AGA term')

    Fill_Source_DBC(result, sourceData, '0')
    
    return result

def ImpactBFOnMortNeoNat_Init(DefaultData_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_MaxDeathCauses+1, CS_AffecFract+1, CS_LateInitBF + 1, CS_NotBF + 1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_MaxDeathCauses+1, CS_LateInitBF + 1, CS_NotBF + 1)).tolist(),
        'alpha'     : np.zeros((CS_MaxDeathCauses+1, CS_LateInitBF + 1, CS_NotBF + 1)).tolist(),
        'beta'      : np.zeros((CS_MaxDeathCauses+1, CS_LateInitBF + 1, CS_NotBF + 1)).tolist(),
        'source'    : Create2DSrcArr(CS_MaxDeathCauses+1, CS_NotBF+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for d in GBRange(1, CS_MaxDeathCauses):
            for bf in GBRange(CS_EarlyInitBF, CS_LateInitBF):
                for bft in GBRange(CS_ExclusiveBF, CS_NotBF):
                    result['value'][dataType][d][CS_RelRisk][bf][bft] = 1
                    result['value'][dataType][d][CS_AffecFract][bf][bft] = 1
    
    sourceData = DefaultData_DB[TG_RelRiskMortBF]

    def setDataP2(record, d, bft, bf, key, key2):
        if key2 in record[key]:
            for dataType in GBRange(CS_Default, CS_Data):
                Fill_Data(result['value'][dataType][d][CS_RelRisk][bf], bft, record[key][key2], 'RR')
                Fill_Data(result['value'][dataType][d][CS_AffecFract][bf], bft, record[key][key2], 'Aff')
            Fill_Data(result['endpoints'][CS_Min][d][bf], bft, record[key][key2], 'Min')
            Fill_Data(result['endpoints'][CS_Max][d][bf], bft, record[key][key2], 'Max')

    def setDataP1(record, d, bft, key):
        if key in record:                           
            setDataP2(record, d, bft, CS_EarlyInitBF, key, '0-1 months EARLY INITIATORS')
            setDataP2(record, d, bft, CS_LateInitBF, key, '0-1 months LATE INITIATORS')
            Fill_2D_Sources(result, d, bft, record[key], 'source')

    for key, record in sourceData.items():
        d = CSGetCurDeathID(record['mstID'])
        if (d >= CS_FirstNNDeath) and (d <= CS_FinalStdNNDeath):
            setDataP1(record, d, CS_ExclusiveBF, 'Exclusive breastfeeding')
            setDataP1(record, d, CS_PredominantBF, 'Predominant breastfeeding')
            setDataP1(record, d, CS_PartialBF, 'Partial breastfeeding')
            setDataP1(record, d, CS_NotBF, 'Not breastfeeding')
    
    return result

def ImpactBFOnMortPostNat_Init(DefaultData_DB):
    result = {
        'value'     : np.zeros((CS_Data+1, CS_MaxDeathCauses+1, CS_AffecFract+1, CS_NotBF + 1, CS_24t60months + 1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_MaxDeathCauses+1, CS_NotBF + 1, CS_24t60months + 1)).tolist(),
        'alpha'     : np.zeros((CS_MaxDeathCauses+1, CS_NotBF + 1, CS_24t60months + 1)).tolist(),
        'beta'      : np.zeros((CS_MaxDeathCauses+1, CS_NotBF + 1, CS_24t60months + 1)).tolist(),
        'source'    : Create2DSrcArr(CS_MaxDeathCauses+1, CS_NotBF+1)
        }    

    for dataType in GBRange(CS_Default, CS_Data):
        for d in GBRange(1, CS_MaxDeathCauses):
            for bf in GBRange(CS_ExclusiveBF, CS_NotBF):
                for a in GBRange(CS_1t6months, CS_24t60months):
                    result['value'][dataType][d][CS_RelRisk][bf][a] = 1
                    result['value'][dataType][d][CS_AffecFract][bf][a] = 1
    
    sourceData = DefaultData_DB[TG_RelRiskMortBF]

    def setData(record, d, bf, key):
        if key in record:                           
            for a in GBRange(CS_0t1months, CS_24t60months):            
                key2 = getDefaultDataAgeKey(a)                            
                if key2 in record[key]:
                    for dataType in GBRange(CS_Default, CS_Data):
                        Fill_Data(result['value'][dataType][d][CS_RelRisk][bf], a, record[key][key2], 'RR')
                        Fill_Data(result['value'][dataType][d][CS_AffecFract][bf], a, record[key][key2], 'Aff')
                    Fill_Data(result['endpoints'][CS_Min][d][bf], a, record[key][key2], 'Min')
                    Fill_Data(result['endpoints'][CS_Max][d][bf], a, record[key][key2], 'Max')   
                    Fill_Data(result['alpha'][d][bf], a, record[key][key2], 'mean')
                    Fill_Data(result['beta'][d][bf], a, record[key][key2], 'sd')            
            Fill_2D_Sources(result, d, bf, record[key], 'source')

    for key, record in sourceData.items():
        d = CSGetCurDeathID(record['mstID'])
        if d >= CS_FirstPNNDeath:
            setData(record, d, CS_ExclusiveBF, 'Exclusive breastfeeding')
            setData(record, d, CS_PredominantBF, 'Predominant breastfeeding')
            setData(record, d, CS_PartialBF, 'Partial breastfeeding')
            setData(record, d, CS_NotBF, 'Not breastfeeding')
    
    return result

def RelRisksAnemia_Init(DefaultData_DB, DataByCountry_DB):
    result = {
        'value'     : np.zeros((CS_Data + 1, CS_Mat_MaxDeathCauses + 1, CS_Mat_Anemic + 1, CS_AffecFract + 1)).tolist(),
        'endpoints' : np.zeros((CS_MaxEndPoint + 1, CS_Mat_MaxDeathCauses + 1, CS_Mat_Anemic + 1)).tolist(),
        'mean'      : np.zeros((CS_Mat_MaxDeathCauses + 1, CS_Mat_Anemic + 1)).tolist(),
        'sd'        : np.zeros((CS_Mat_MaxDeathCauses + 1, CS_Mat_Anemic + 1)).tolist(),
        'source'    : Create2DSrcArr(CS_Mat_MaxDeathCauses+1, CS_Mat_Anemic+1)
        }
    
    for dataType in GBRange(CS_Default, CS_Data):
        for d in GBRange(CS_Mat_MinDeathCauses, CS_Mat_MaxDeathCauses):
            for an in GBRange(CS_Mat_NotAnemic, CS_Mat_Anemic):
                result['value'][dataType][d][an][CS_RelRisk] = 1
                result['value'][dataType][d][an][CS_AffecFract] = 1
       
    sourceData = DefaultData_DB[TG_RelRiskAnemia]
    
    def setData(record, d, an, key):
        if key in record:                           
            for dataType in GBRange(CS_Default, CS_Data):
                Fill_Data(result['value'][dataType][d][an], CS_RelRisk, record[key], 'OR')
                Fill_Data(result['value'][dataType][d][an], CS_AffecFract, record[key], 'Aff')
            Fill_Data(result['endpoints'][CS_Min][d], an, record[key], 'Min')
            Fill_Data(result['endpoints'][CS_Max][d], an, record[key], 'Max')   
            Fill_Data(result['mean'][d], an, record[key], 'mean')
            Fill_Data(result['sd'][d], an, record[key], 'sd')            
            Fill_2D_Sources(result, d, an, record[key], 'source')

    for key, record in sourceData.items():
        d = CSGetMat_CurDeathID(record['mstID'])
        if d > 0:
            setData(record, d, CS_Mat_NotAnemic, 'Not anemic')
            setData(record, d, CS_Mat_Anemic, 'Anemic')
    
    index = GetDBCBaseYearIndex(DataByCountry_DB)
    sourceData = DataByCountry_DB[TG_PercWomenSevereAnemia]  

    for dataType in GBRange(CS_Default, CS_Data):
        for d in GBRange(CS_Mat_MinDeathCauses, CS_Mat_PostpartHemorr):
            for an in GBRange(CS_Mat_NotAnemic, CS_Mat_Anemic):
                Fill_Data_DBC3(result['value'][dataType][d][an], sourceData['% of anemic PW with severe anemia'], index, CS_AffecFract)      

    return result

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                                                                                          /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def SetDiarrShigellaDistr(CSModvars, DiarrShigella_DB):  
    
    def getAgeKey(a):
        if a == CS_0t1months : return '< 1 month'
        if a == CS_1t6months : return '1-5 months'
        if a == CS_6t12months : return '6-11 months'
        if a == CS_12t24months : return '12-23 months'
        if a == CS_24t60months : return '24-59 months'
    
    for a in GBRange(CS_0t1months, CS_24t60months):
        Fill_Data_DBC4(CSModvars[CS_DiarrPathTag]['value'][CS_Distr_All][CS_PathBDiar], DiarrShigella_DB, '<Distribution among all cases>', getAgeKey(a), a, True)
        Fill_Data_DBC4(CSModvars[CS_DiarrPathTag]['value'][CS_Distr_Sevr][CS_PathBDiar], DiarrShigella_DB, '<Distribution among severe cases>', getAgeKey(a), a, True)
        Fill_Data_DBC4(CSModvars[CS_DiarrPathTag]['value'][CS_Distr_Fatal][CS_PathBDiar], DiarrShigella_DB, '<Distribution among fatal cases>', getAgeKey(a), a, True)
    
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                   For Multiple Result Sectors                                            /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def Year_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, final_year_idx+1)).tolist())

def Intervs_Init(numIntervs):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, numIntervs+1)).tolist())

def AgeByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_24t60months+1, final_year_idx+1)).tolist())

def IntervsByYear_Init(numIntervs, final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, numIntervs+1, final_year_idx+1)).tolist())

def IntervsByAgeByYear_Init(numIntervs, final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, numIntervs+1, CS_24t60months+1, final_year_idx+1)).tolist())

def CauseByAgeByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_MaxDeathCauses+1, CS_24t60months+1, final_year_idx+1)).tolist())

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                              Other                                                       /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def MortalityRates_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_U5MR+1, final_year_idx+1)).tolist())

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                     Neonatal, child results                                              /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def ChDeathsByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_4t5Yr+1, final_year_idx+1)).tolist())

def DeathsByCauseByBirthCohort_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_MaxDeathCauses+1, final_year_idx+1)).tolist())

def ChDeathsPrevByInterByCause_Init(numIntervs, final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, numIntervs+1, CS_MaxDeathCauses+1, CS_24t60months+1, final_year_idx+1)).tolist())

def DetVaccCovResults_Init(final_year_idx):
    result = {
        'value' : np.zeros((CS_bHigh+1, CS_LastVacc_Det+1, CS_MaxVaccDose+1, CS_48t60months+1, final_year_idx+1)).tolist(),
        'retro' : np.zeros((CS_bHigh+1, CS_LastVacc_Det+1, CS_MaxVaccDose+1, CS_48t60months+1, CS_DetVaccRetroOffset+1)).tolist()
        }
    return result

def DAvtdByVaccByCohort_Init(final_year_idx):
    result = {
        'value' : np.zeros((CS_bHigh+1, CS_LastVacc_Det+1, CS_24t60months+1, final_year_idx+1)).tolist(),
        'retro' : np.zeros((CS_bHigh+1, CS_LastVacc_Det+1, CS_24t60months+1, CS_DetVaccRetroOffset+1)).tolist()
        }
    return result

def DAvtdByVaccByCohortByCause_Init(final_year_idx):
    result = {
        'value' : np.zeros((CS_bHigh+1, CS_LastVacc_Det+1, CS_FinalPostNNDeath+1, CS_24t60months+1, final_year_idx+1)).tolist(),
        'retro' : np.zeros((CS_bHigh+1, CS_LastVacc_Det+1, CS_FinalPostNNDeath+1, CS_24t60months+1, CS_DetVaccRetroOffset+1)).tolist()
        }
    return result

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                        Maternal results                                                  /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def MatDeathCausesByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_Mat_MaxDeathCauses+1, final_year_idx+1)).tolist())

def MatDeathsPrevByInterByCause_Init(numIntervs, final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, numIntervs+1, CS_Mat_MaxDeathCauses+1,final_year_idx+1)).tolist())

def NumAbortions_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_SafeAbort+1, final_year_idx+1)).tolist())

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                       Stillbirth results                                                 /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def SBCausesByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_SB_MaxCauses+1, final_year_idx+1)).tolist())

def SBPrevByInterByCause_Init(numIntervs, final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, numIntervs+1, CS_SB_MaxCauses+1, final_year_idx+1)).tolist())

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                    Mortality rates results                                               /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def MortalityRateResult_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_U5MR+1, final_year_idx+1)).tolist())

def RedMortIntervResult_Init(numIntervs):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_PercU5MortRedAttrInterv+1, numIntervs+1)).tolist())

def RedMortIntervSortedIDs_Init(numIntervs):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, numIntervs+1)).tolist())

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                       Nutrition results                                                  /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def SubOpBOAvertByInter_Init(numIntervs, final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, numIntervs+1, CS_GT3STD+1, final_year_idx+1)).tolist())

def MAM_PIN_Init():
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_24t60months+1)).tolist())

def StdDevByAgeByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_GT3STD+1, CS_24t60months+1, final_year_idx+1)).tolist())

def DiscountRate_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_10Perc+1, final_year_idx+1)).tolist())

def BFPrevResult_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_MaxBFType+1, CS_24t60months+1, final_year_idx+1)).tolist())

def BirthTermResult_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_TermAGA+1, final_year_idx+1)).tolist())

def AnemiaByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_WRA_IronDeficAnemia+1, final_year_idx+1)).tolist())

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                 Incidence and etiology results                                           /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def DiarrPathsByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumPathsDiar+1, final_year_idx+1)).tolist())

def PneumPathsByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumPathsPneum+1, final_year_idx+1)).tolist())

def MeninPathsByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumPathsMenin+1, final_year_idx+1)).tolist())

def DiarrIntervsByAgeByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumDiarIntervs+1, CS_24t60months+1, final_year_idx+1)).tolist())

def DiarrPathsByAgeByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumPathsDiar+1, CS_24t60months+1, final_year_idx+1)).tolist())

def PneumPathsByAgeByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumPathsPneum+1, CS_24t60months+1, final_year_idx+1)).tolist())

def MeninPathsByAgeByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumPathsMenin+1, CS_24t60months+1, final_year_idx+1)).tolist())

def DiarrPathsBy1YrAgeGrpsByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumPathsDiar+1, CS_4t5Yr+1, final_year_idx+1)).tolist())

def PneumPathsBy1YrAgeGrpsByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumPathsPneum+1, CS_4t5Yr+1, final_year_idx+1)).tolist())

def MeninPathsBy1YrAgeGrpsByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumPathsMenin+1, CS_4t5Yr+1, final_year_idx+1)).tolist())

def DetVaccByAgeByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_LastVacc_Det+1, CS_24t60months+1, final_year_idx+1)).tolist())

def DetVaccByDoseBy1YrAgeGrpsByYear_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_LastVacc_Det+1, CS_MaxVaccDose+1, CS_4t5Yr+1, final_year_idx+1)).tolist())

def DiarrCasesAvertByInter_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_BFPromotion_DiarInterv+1, CS_24t60months+1, final_year_idx+1)).tolist())

def PneumCasesAvertByInter_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumPneumIntervs+1, CS_24t60months+1, final_year_idx+1)).tolist())

def MeninCasesAvertByInter_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_NumMeningIntervs+1, CS_24t60months+1, final_year_idx+1)).tolist())

def PersonsVaccByInterv_Init(final_year_idx):
    return Simple_Value_Init(np.zeros((CS_bHigh+1, CS_LastVacc_Det+1, CS_MaxVaccDose+1, final_year_idx+1)).tolist())

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                       Set Subnational Data                                               /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def SubnatCov_Init(CSModvars, SubnatData_DB, final_year_idx):
    IVInfo = CSModvars[CS_IVInfoTag]
    
    FlatlineCoverage(CSModvars, final_year_idx)

    for key, record in SubnatData_DB.items():
        if 'value' in record:
            val = float(record['value'])
                
            mstIDSet = [x.strip() for x in key.split(',')]
            for i in GBRange(0, len(mstIDSet) - 1):
                mstID = mstIDSet[i]

                if 'flag' in record:
                    CSModvars[CS_SubnatDataSourceArrayTag]['value'][mstID] = record['flag']
                
                if mstID in VW_FacDelivSet:
                    utilMstID = CS_IV_HealthFacDelivery_MST_ID

                    if int(utilMstID) in CSModvars[CS_SubnatDefDataMstIDsetTag]['value']:
                        if utilMstID in CSModvars[CS_SubnatDataSourceArrayTag]['value']:
                            CSModvars[CS_SubnatDataSourceArrayTag]['value'][mstID] = CSModvars[CS_SubnatDataSourceArrayTag]['value'][utilMstID]
                
                # Set coverages for normal LiST interventions.                
                if mstID in IVInfo:
                    if 'currID' in IVInfo[mstID]:
                        currID = IVInfo[mstID]['currID']
                            
                        # Set coverages for interventions related to health facility delivery.                
                        if mstID == CS_IV_HealthFacDelivery_MST_ID:          
                            
                            # First set the facility delivery coverage itself.
                            for t in GBRange(1, final_year_idx):
                                SetStandardCoverage(CSModvars, mstID, t, val * 100)                            
                            
                            CSModvars[CS_SubnatDefDataMstIDsetTag]['value'].append(int(mstID))

                            NatFacDeliv = CSModvars[CS_CoverageTag]['value'][currID][0]
                            SubnatFacDeliv = val * 100

                            ratio = SubnatFacDeliv / NatFacDeliv

                            for mstID2 in VW_FacDelivSet:
                                if mstID2 in IVInfo:
                                    if 'currID' in IVInfo[mstID2]:
                                        currID2 = IVInfo[mstID2]['currID']
                                        NatCov = CSModvars[CS_CoverageTag]['value'][currID2][0]

                                        # Flatline subnational coverage so it is flatlined in the resulting
                                        # projection even if the user never visits the Wizard's
                                        # coverage editor once.
                                        for t in GBRange(1, final_year_idx):
                                            CSModvars[CS_CoverageTag]['value'][currID2][t] = NatCov * ratio
                                        
                                        CSModvars[CS_SubnatDefDataMstIDsetTag]['value'].append(int(mstID2))
                            
                        # Set coverages for LiST interventions unrelated to health facility delivery.                
                        else:
                            NatCov = GetStandardCoverage(CSModvars, mstID, 0)

                            # Flatline subnational coverage so it is flatlined in the resulting
                            # projection even if the user never visits the Wizard's
                            # coverage editor once.
                            for t in GBRange(1, final_year_idx):
                                if mstID in VW_RatioSet:
                                    SetStandardCoverage(CSModvars, mstID, t, min(val * NatCov, 100))
                                else:
                                    SetStandardCoverage(CSModvars, mstID, t, val * 100)
                            
                            CSModvars[CS_SubnatDefDataMstIDsetTag]['value'].append(int(mstID))
                            
                            if mstID == CS_IV_HealthFacDelivery_MST_ID: 
                                CSModvars[CS_SubnatDefDataMstIDsetTag]['value'].append(IV_InjectAntibNeonSeps)
                            
                            if mstID == CS_IV_VitASupp_MST_ID: 
                                CSModvars[CS_SubnatDefDataMstIDsetTag]['value'].append(IV_VitATrMeas)
                                                                           
                # For Breastfeeding, Stunting and Wasting.
                else:
                    if (int(mstID) in BF_Set | Stunt_Set | Waste_Set) or (int(mstID) == CS_MstEarlyInitBF):
                        for t in GBRange(1, final_year_idx):
                            SetNonStandardCoverage(CSModvars, mstID, t, val * 100)
                        CSModvars[CS_SubnatDefDataMstIDsetTag]['value'].append(int(mstID))

    # Recalculate coverage based on quality in case any subnational utilization values have been supplied.
    UpdateCoverageFromQuality(CSModvars, final_year_idx)

# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
# /////                                                                                                          /////
# /////                                        Create Meta Modvars                                               /////
# /////                                                                                                          /////
# ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def Meta_MV_Init(CSModvars):
    CSModvars[CS_SourcesTag] = {}
    
    metaMVs = {}
    pass
    for key, record in CSModvars.items():
        if 'source' in record:
            CSModvars[CS_SourcesTag][key] = record.pop('source')
        
        if 'value' in record:
            newRecord = {}
            for key2, record2 in record.items():
                if not key2 == 'value':
                    newRecord[key2] = record2            
            
            CSModvars[key] = record['value']
            
            if not newRecord == {}:
                metaMVs[key.replace('V1', 'Meta_V1')] = newRecord
    pass
    
    for key, record in metaMVs.items():
        CSModvars[key] = record
    pass
