示例#1
0
文件: tmr.c 项目: chleemobile/rossnet
void
tmr_init(tmr_state * s, tw_lp * lp)
{
	int              i;

	if(!lp->rng)
	{
		tw_error(TW_LOC, "No RNG!");
		lp->rng = tw_calloc(TW_LOC, "LP RNG", sizeof(tw_rng_stream), 1);
		tw_rand_initial_seed(lp->pe->rng, lp->rng, lp->gid);
	}

	for (i = 0; i < g_tmr_start_events; i++)
	{
		tw_event_send(
			tw_event_new(lp->gid, 
				     tw_rand_exponential(lp->rng, mean), 
				     lp));
	}

	if((s->timer = tw_timer_init(lp, 100.0)) == NULL)
		tw_error(TW_LOC, "scheduled timer past end time \n");
}
示例#2
0
void
epi_init_hospital()
{
    int	 i;

    g_epi_nhospital = 1;
    g_epi_hospital = tw_calloc(TW_LOC, "", sizeof(unsigned int *), 1);
    g_epi_hospital_ww = tw_calloc(TW_LOC, "", sizeof(unsigned int *), 1);
    g_epi_hospital_wws = tw_calloc(TW_LOC, "", sizeof(unsigned int *), 1);

    if(NULL == (g_epi_hospital_f = fopen(g_epi_hospital_fn, "w")))
        tw_error(TW_LOC, "Unable to open for writing: %s", g_epi_hospital_fn);

    for(i = 0; i < g_epi_nhospital; i++)
    {
        g_epi_hospital[i] = tw_calloc(TW_LOC, "", sizeof(unsigned int), 1);
        g_epi_hospital_ww[i] = tw_calloc(TW_LOC, "", sizeof(unsigned int), 1);
        g_epi_hospital_wws[i] = tw_calloc(TW_LOC, "", sizeof(unsigned int), 1);
    }
}
示例#3
0
/* 
 * This function creates and setups the g_rn_machines global data structure of nodes
 */
void
rn_xml_topology()
{
	xmlXPathObjectPtr	obj;

	xmlNodePtr		node;

	unsigned int		i;
	//unsigned int		j;
	unsigned int		id;
	unsigned int		size;

	rn_as			*as;
	rn_area			*ar;
	rn_subnet		*sn;
	rn_machine		*m;

	size = 0;

	/* Environment */
	obj = xpath("//environment", ctxt);
	if(obj->nodesetval->nodeTab)
		g_rn_environment = *obj->nodesetval->nodeTab;
	xmlXPathFreeObject(obj);

	/* ASes */
	obj = xpath("/rossnet/as", ctxt);
	g_rn_nas = xmlXPathNodeSetGetLength(obj->nodesetval);	

	if(g_rn_nas > 0)
	{
		g_rn_as = (rn_as *) tw_calloc(TW_LOC, "", sizeof(rn_as), g_rn_nas);
		size += sizeof(rn_as) * g_rn_nas;
	}

	node = obj->nodesetval->nodeTab[0];
	for(i = 0; i < obj->nodesetval->nodeNr; )
	{
		g_rn_as[i].low = -1;
		g_rn_as[i].id = atoi(xml_getprop(node, "id"));	
		//g_rn_as[i].frequency = atoi(xml_getprop(node, "frequency"));	

#if WASTE_MEM
		if(0 == strcmp(xml_getprop(node, "name"), "name"))
			g_rn_as[i].name = (char *) xmlStrdup((xmlChar *) xml_getprop(node, "name"));
#endif

		node = obj->nodesetval->nodeTab[++i];
	}

	xmlXPathFreeObject(obj);

	/* Areas */
	obj = xpath("/rossnet/as/area", ctxt);
	g_rn_nareas = xmlXPathNodeSetGetLength(obj->nodesetval);	

	if(g_rn_nareas > 0)
	{
		g_rn_areas = (rn_area *) tw_calloc(TW_LOC, "", sizeof(rn_area), g_rn_nareas);
		size += sizeof(rn_area) * g_rn_nareas;
	}

	node = obj->nodesetval->nodeTab[0];
	for(i = 0; i < obj->nodesetval->nodeNr; )
	{
		//g_rn_areas[i].root = INT_MAX;
		//g_rn_areas[i].root_lvl = 0xff;
		g_rn_areas[i].low = INT_MAX;
		g_rn_areas[i].id = atoi(xml_getprop(node, "id"));	
		g_rn_areas[i].as = &g_rn_as[atoi(xml_getprop(node->parent, "id"))];

		if(g_rn_areas[i].as->areas == NULL)
			g_rn_areas[i].as->areas = &g_rn_areas[i];

		if(i > 0 && g_rn_areas[i-1].as->id == g_rn_areas[i].as->id)
			g_rn_areas[i-1].next = &g_rn_areas[i];

		g_rn_areas[i].as->nareas++;

		node = obj->nodesetval->nodeTab[++i];
	}

	xmlXPathFreeObject(obj);

	/* Subnets */
	obj = xpath("/rossnet/as/area/subnet", ctxt);
	g_rn_nsubnets = xmlXPathNodeSetGetLength(obj->nodesetval);	

	if(g_rn_nsubnets > 0)
	{
		g_rn_subnets = (rn_subnet *) tw_calloc(TW_LOC, "", sizeof(rn_subnet), g_rn_nsubnets);
		size += sizeof(rn_subnet) * g_rn_nsubnets;
	}

	node = *obj->nodesetval->nodeTab;
	for(i = 0; i < obj->nodesetval->nodeNr; )
	{
		g_rn_subnets[i].low = INT_MAX;
		g_rn_subnets[i].id = atoi(xml_getprop(node, "id"));	
		g_rn_subnets[i].area = &g_rn_areas[atoi(xml_getprop(node->parent, "id"))];

		if(g_rn_subnets[i].area->subnets == NULL)
			g_rn_subnets[i].area->subnets = &g_rn_subnets[i];

		if(i > 0 && g_rn_subnets[i-1].area->id == g_rn_subnets[i].area->id)
			g_rn_subnets[i-1].next = &g_rn_subnets[i];

		g_rn_subnets[i].area->nsubnets++;

		node = obj->nodesetval->nodeTab[++i];
	}

	xmlXPathFreeObject(obj);

	/* Machines */
	obj = xpath("//node", ctxt);
	g_rn_nmachines = xmlXPathNodeSetGetLength(obj->nodesetval);	

	if(g_rn_nmachines)
	{
		g_rn_machines = tw_calloc(TW_LOC, "machines", 
					  sizeof(rn_machine), 
					  g_rn_nmachines);
		size += sizeof(rn_machine) * g_rn_nmachines;
	} else
		tw_error(TW_LOC, "No machines found in XML!");

	g_tw_nlp = ceil((double) obj->nodesetval->nodeNr / (double) tw_nnodes());

	node = *obj->nodesetval->nodeTab;

	for(i = 0; i < obj->nodesetval->nodeNr; )
	{
		id = atoi(xml_getprop(node, "id"));

		m = rn_getmachine(id);
		m->xml = node;
		m->conn = -1;
		m->id = id;
		m->nlinks = atoi(xml_getprop(node, "links"));	
		//m->level = atoi(xml_getprop(node, "lvl"));
		m->subnet = &g_rn_subnets[atoi(xml_getprop(node->parent, "id"))];

		if(0 != strcmp("", xml_getprop(node, "uid")))
			m->uid = atoi(xml_getprop(node, "uid"));
		else
			m->uid = -1;

		if(strcmp("c_router", xml_getprop(node, "type")) == 0)
		{
			m->type = c_router;
			g_rn_nrouters++;
		} else if(strcmp("c_ct_router", xml_getprop(node, "type")) == 0)
		{
			m->type = c_ct_router;
			g_rn_nrouters++;
		} else if(strcmp("c_og_router", xml_getprop(node, "type")) == 0)
		{
			m->type = c_og_router;
			g_rn_nrouters++;
		} else if(strcmp("c_co_router", xml_getprop(node, "type")) == 0)
		{
			m->type = c_co_router;
			g_rn_nrouters++;
		} else if(strcmp("c_ha_router", xml_getprop(node, "type")) == 0)
		{
			m->type = c_ha_router;
			g_rn_nrouters++;
		} else if(strcmp("c_host", xml_getprop(node, "type")) == 0)
			m->type = c_host;
		else
			tw_error(TW_LOC, "Unknown node type: %s", xml_getprop(node, "type"));

		if(m->subnet->machines == NULL)
			m->subnet->machines = &g_rn_machines[i];

#if 0
		if(id > 0 && 
		   g_rn_machines[id-1].subnet->id == g_rn_machines[id].subnet->id)
			g_rn_machines[id-1].next = &g_rn_machines[id];
#endif

		m->subnet->nmachines++;
		m->subnet->area->nmachines++;
		m->link = (rn_link *) tw_calloc(TW_LOC, "", sizeof(rn_link) * m->nlinks, 1);
		m->hash_link = rn_hash_create(m->nlinks);

		size += sizeof(rn_link) * m->nlinks;

		//printf("Init\'ing Machines id: %d \n", m->id);

		node = obj->nodesetval->nodeTab[++i];
	}

	xmlXPathFreeObject(obj);

	xml_link_topology();

	/*
	 * Set up the global connection library
	 */
	obj = xpath("//connect", ctxt);

	if(obj->nodesetval->nodeNr)
	{
		node = *obj->nodesetval->nodeTab;

		for(i = 0; i < obj->nodesetval->nodeNr; )
		{
			m = rn_getmachine(atoll(xml_getprop(node, "src")));
			m->conn = atoll(xml_getprop(node, "dst"));

			// back link the connection
			//rn_getmachine(m->conn)->conn = m->id;

			node = obj->nodesetval->nodeTab[++i];
		}
	}

	xmlXPathFreeObject(obj);

	for(i = 0; i < g_rn_nmachines; i++)
	{
		m = rn_getmachine(i);

		sn = m->subnet;
		ar = sn->area;
		as = ar->as;

		if(i < sn->low)
		{
			sn->low = i;

			if(i < ar->low)
			{
				ar->low = i;

				if(0 && i < as->low)
					as->low = i;
			}
		}

		if(i > sn->high)
		{
			sn->high = i;

			if(i > ar->high)
			{
				ar->high = i;

				if(0 && i > as->high)
					as->high = i;
			}
		}

		if(m->type == c_host)
			continue;

		ar->g_ospf_nlsa = ar->nmachines + ar->as->nareas + g_rn_nas;

		if(ar->nmachines == 0)
			tw_error(TW_LOC, "No machines in Area %d!\n", ar->id);

#if 0
		m->ft = (int *) tw_calloc(TW_LOC, "", sizeof(int ) * ar->g_ospf_nlsa, 1);
		size += sizeof(int) * ar->g_ospf_nlsa;

		for(j = 0; j < ar->g_ospf_nlsa; j++)
			m->ft[j] = -1;
#endif

/*
		printf("mach %d: alloc FT of size: %d \n", 
			i, ar->nmachines + as->nareas + g_rn_nas);
*/
	}

	ar = NULL;
	as = NULL;
	while(NULL != (as = rn_nextas(as)))
	{
		while(NULL != (ar = rn_nextarea_onas(ar, as)))
		{
			if(as->low == -1)
				as->low = ar->id;
			as->high = ar->id;
		}

		//printf("AS %d: low %ld, high %ld \n", as->id, as->low, as->high);
	}

#if RN_XML_DEBUG || 1
	if(tw_ismaster())
	{
		printf("\n");
		printf("%-32s %11d \n", "ASes: ", g_rn_nas);
		printf("%-32s %11d \n", "Areas: ", g_rn_nareas);
		printf("%-32s %11d \n", "Subnets: ", g_rn_nsubnets);
		printf("%-32s %11d \n", "Machines: ", g_rn_nmachines);
		printf("%-32s %11d \n", "Links: ", g_rn_nlinks);
		printf("%-32s %11d bytes\n", "Total topology size: ", size);
		printf("\n");
	}
#endif

	//verify_topology();
}
示例#4
0
void
epi_init_agent_default(void)
{
    tw_memory	*b;

    epi_agent	*a;

    int		 i;
    int		 j;

    int		 id;
    int		 lid;
    int		 rid;

    if(!g_epi_nagents)
        tw_error(TW_LOC, "No agents specified!");

    if(!g_tw_nlp)
        tw_error(TW_LOC, "No locations specified!");

    if(!g_epi_nregions)
        tw_error(TW_LOC, "No regions specified!");

    g_epi_regions = tw_calloc(TW_LOC, "", sizeof(unsigned int *), g_epi_nregions);

    // create reporting tables for each region, for each disease
    for(i = 0; i < g_epi_nregions; i++)
    {
        g_epi_regions[i] = tw_calloc(TW_LOC, "", sizeof(*g_epi_regions[i]),
                                     g_epi_ndiseases);

        for(j = 0; j < g_epi_ndiseases; j++)
            g_epi_regions[i][j] = tw_calloc(TW_LOC, "",
                                            sizeof(*g_epi_regions[i][j]),
                                            g_epi_diseases[j].nstages);
    }

    // allocate the location priority queues for this node
    g_epi_pq = tw_calloc(TW_LOC, "", sizeof(*g_epi_pq), g_tw_nlp);

    for(i = 0; i < g_tw_nlp; i++)
        g_epi_pq[i] = pq_create();

    // round-robin mapping of agents to locations, and locations to regions
    for(i = 0; i < g_epi_nagents; i++)
    {
        lid = i % g_tw_nlp;
        rid = lid % g_epi_nregions;

        b = tw_memory_alloc(g_tw_lp[lid], g_epi_fd);
        a = tw_memory_data(b);

        a->id = id++;
        a->region = rid;

        a->pathogens = NULL;
        a->curr = 0;
        a->nloc = tw_rand_integer(g_tw_lp[lid]->rng, 0, 10);

        // setup "home" location
        a->loc[0] = lid;
        a->dur[0] = tw_rand_exponential(g_tw_lp[lid]->rng, g_epi_mean);
        a->ts_next = a->ts_remove = a->dur[0];
        pq_enqueue(g_epi_pq[a->loc[0]], b);

        printf("A %d nloc %d: (%d, %lf) ",
               a->id, a->nloc, a->loc[0], a->dur[0]);

        for(j = 1; j < a->nloc; j++)
        {
            a->loc[j] = tw_rand_integer(g_tw_lp[lid]->rng, 0,
                                        (g_tw_nlp * tw_nnodes()) - 2);
            a->dur[j] = tw_rand_exponential(g_tw_lp[lid]->rng,
                                            g_epi_mean);

            printf("(%d %lf) ", a->loc[j], a->dur[j]);
        }

        printf("\n");
        ga = a;
    }
}
示例#5
0
void
epi_init_agent(void)
{
    FILE		*g;
    FILE		*f;
    fpos_t		 pos;

    tw_memory	*b;
    tw_memory	*next;

    epi_agent	*a;

    int		*home_to_ct;
    int		 nagents = 0;
    int		 nlp = -1;
    int		 i;
    int		 j;
    int		 h;
    int		 o;
    int		 t;

    printf("\nEPI Agent Initialization: \n\n");

    home_to_ct = tw_calloc(TW_LOC, "home to ct", sizeof(*home_to_ct), 3363607);
    // create census tract table, hard-coded to 2214 (all CT) for Chicago
    g_epi_nregions = 2215;
    g_epi_regions = tw_calloc(TW_LOC, "", sizeof(unsigned int *), g_epi_nregions);

    // need to read in homes.dat to get CT ids
    if(NULL == (g = fopen("homes.dat", "r")))
        tw_error(TW_LOC, "Unable to open: homes.dat");

    i = 0;
    while(EOF != (fscanf(g, "%d", &home_to_ct[i++])))
        ;

    for(i = 0; i < g_epi_nregions; i++)
    {
        g_epi_regions[i] = tw_calloc(TW_LOC, "", sizeof(unsigned int *), g_epi_ndiseases);

        for(j = 0; j < g_epi_ndiseases; j++)
            g_epi_regions[i][j] = tw_calloc(TW_LOC, "", sizeof(unsigned int),
                                            g_epi_diseases[j].nstages);
    }

    if(NULL == (f = fopen("agents.dat", "r")))
        tw_error(TW_LOC, "Unable to open: agents.dat");

    i = 0;

    if(!g_epi_nagents)
    {
        fgetpos(f, &pos);
        while(EOF != fscanf(f, "%d %d %*d", &h, &o))
            g_epi_nagents++;
        fsetpos(f, &pos);
    }

    if(0 == g_epi_nagents)
        tw_error(TW_LOC, "No agents in agents.dat!");

    g_epi_agents = tw_calloc(TW_LOC, "", sizeof(tw_memoryq), 1);
    g_epi_agents->start_size = g_epi_nagents;
    g_epi_agents->d_size = sizeof(epi_agent);
    g_epi_agents->grow = 1;

    tw_memory_allocate(g_epi_agents);

    b = g_epi_agents->head;
    while(EOF != (fscanf(f, "%d %d %d", &h, &o, &t)))
    {
        // allocate the agent
        a = tw_memory_data(b);
        a->id = nagents++;

        if(h && h > nlp)
            nlp = h;

        if(o != -1 && o > nlp)
            nlp = o;

        // the CT id is stored on the h-th line of the homes.dat file
        a->region = home_to_ct[h];

        if(a->region > 2214)
            tw_error(TW_LOC, "Bad Home to CT Mapping!");

        a->pathogens = NULL;

#if 0
        // default disease stats
        a->stage = EPI_SUSCEPTIBLE;
        a->ts_stage_tran = DBL_MAX;
#endif

        a->curr = 0;
        //a->ts_last_tran = 0.0;

        // go to work at 9am on first day
        a->ts_next = a->ts_remove = (double) 32400.0;
        //a->n_infected = 0;

        if(-1 != o)
            a->nloc = 3;
        else
            a->nloc = 2;

        // only two locs =(
        a->loc[1] = o;
        a->loc[0] = a->loc[a->nloc-1] = h;

        a->dur[0] = 9 * 3600;
        a->dur[1] = 8 * 3600;
        a->dur[a->nloc-1] += 7 * 3600;

        a->behavior_flags = 0;
        a->ts_remove = a->ts_next = a->dur[a->curr];

        for(i = 0; i < g_epi_ndiseases; i++)
            g_epi_regions[a->region][i][0]++;

        if(g_epi_nagents == nagents)
            break;

        b = b->next;
    }

    if(nlp == 0)
        tw_error(TW_LOC, "No locations!");
    else
        printf("\t%-48s %11d\n", "Max Location", ++nlp);

    g_epi_pq = tw_calloc(TW_LOC, "", sizeof(void *), nlp);

    for(i = 0; i < nlp; i++)
        g_epi_pq[i] = pq_create();

    for(b = g_epi_agents->head; b; b = next)
    {
        a = tw_memory_data(b);
        next = b->next;
        pq_enqueue(g_epi_pq[a->loc[0]], b);
    }

    g_tw_nlp = nlp;

}
示例#6
0
void
epi_init_disease_default()
{
    epi_disease	*d;
    epi_ic_stage	*s;

    double		 multiplier;

    double		 stages[1][4][11] =
    {
        {
            {   (double) 'S',
                0.0, 0.0, 1.0, 5.0, 0.0,
                1.0, 0.0, 0.0, 0.0, 0.0,
            },

            {   (double) 'E',
                0.0, 0.0, 1.0, 5.0, 0.0,
                1.0, 0.0, 0.0, 0.0, 0.0,
            },

            {   (double) 'I',
                0.00004, 0.00004, 2.0, 5.0, 0.0,
                1.0, 0.0, 1.0, 1.0, 0.0,
            },

            {   (double) 'R',
                0.0, 0.0, 1000.0, 1000.0, 50.0,
                0.0, 0.0, 0.0, 0.0, 0.0,
            },
        },
    };

    unsigned int	 i;
    unsigned int	 j;
    unsigned int	 k;

    char		 fname[512];

    printf("EPI Disease Stage Initialization: default\n\n");

    g_epi_ndiseases = 1;
    g_epi_diseases = tw_calloc(TW_LOC, "", sizeof(epi_disease), g_epi_ndiseases);
    g_epi_log_f = tw_calloc(TW_LOC, "", sizeof(FILE *), g_epi_ndiseases);

    g_epi_exposed_today = tw_calloc(TW_LOC, "", sizeof(unsigned int), g_epi_ndiseases);
    g_epi_sick_init_pop = tw_calloc(TW_LOC, "", sizeof(unsigned int), g_epi_ndiseases);

    for(i = 0; i < g_epi_ndiseases; i++)
    {
        d = &g_epi_diseases[i];

        d->nstages = 4;
        d->stages = tw_calloc(TW_LOC, "", sizeof(epi_ic_stage), d->nstages);

        strcpy(d->name, "Influenza");
        printf("\tDisease %d: %s\n\n", i+1, d->name);

        sprintf(fname, "%s.log", d->name);
        if(NULL == (g_epi_log_f[i] = fopen(fname, "w")))
            tw_error(TW_LOC, "Unable to open: %s \n", log);

        for(j = 0, k = 0; j < d->nstages; j++, k = 0)
        {
            s = &d->stages[j];

            s->index = j+1;
            s->name[0] = (char) (stages[i][j][k++]);
            s->name[1] = '\0';
            s->start_multiplier = stages[i][j][k++];
            s->stop_multiplier = stages[i][j][k++];
            s->min_duration = stages[i][j][k++];
            s->max_duration = stages[i][j][k++];
            s->mortality_rate = stages[i][j][k++];
            s->eligible_for_inoculation =
                stages[i][j][k++] == 0.0 ? 0.0 : 1.0;
            s->progress_trumps_inoculation =
                stages[i][j][k++] == 0.0 ? 0.0 : 1.0;
            s->hospital_treatment =
                stages[i][j][k++] == 0.0 ? 0.0 : 1.0;
            s->is_symptomatic =
                stages[i][j][k++] == 0.0 ? 0.0 : 1.0;
            s->days_in_hospital = stages[i][j][k++];

            /*
             * Error checking
             */
            if (s->min_duration > s->max_duration)
                tw_error(TW_LOC, "stage min duration > max duration");

            /*
             * Fix-ups & Conversions
             */
            // convert days to seconds
            s->min_duration *= 86400.0;
            s->max_duration *= 86400.0;
            s->days_in_hospital *= 86400.0;

            // Calculate log of multiplier.
            // Right now, using the average of start_multiplier
            // and stop_multriplier.
            multiplier = (s->start_multiplier + s->stop_multiplier) / 2.0;

            if (multiplier > EPSILON)
                s->ln_multiplier = log(1 - multiplier);
            else
                s->ln_multiplier = 0.0;

            // Now print for log
            printf("\t\tStage %d: %s\n", s->index, s->name);
            printf("\t\t\t%-40s %11.2lf\n", "Min Duration",
                   s->min_duration / 86400.0);
            printf("\t\t\t%-40s %11.2lf\n", "Max Duration",
                   s->max_duration / 86400.0);

            if(s->mortality_rate)
                printf("\t\t\t%-40s %11.2lf\n", "Mortality Rate",
                       s->mortality_rate);

            if (s->start_multiplier > EPSILON)
            {
                printf("\t\t\t%-40s %.9lf\n", "Start Multiplier",
                       s->start_multiplier);
                printf("\t\t\t%-40s %.9lf\n", "Stop Multiplier",
                       s->stop_multiplier);
            }

            if(s->ln_multiplier)
                printf("\t\t\t%-45s %.4g\n", "LN Mult",
                       s->ln_multiplier);

            if(s->days_in_hospital)
                printf("\t\t\t%-40s %11.2lf\n", "Days in Hospital",
                       s->days_in_hospital / 86400.0);
            printf("\n");
        }
    }
}
示例#7
0
void
epi_init_disease()
{
    FILE		*f = NULL;

    epi_disease	*d;
    epi_ic_stage	*s;

    unsigned int	 i;
    unsigned int	 j;

    double		 multiplier;

    char		 line[255];
    char		 fname[255];

    printf("EPI Disease Stage Initialization: %s\n\n", g_epi_ic_fn);

    if(NULL == (f = fopen(g_epi_ic_fn, "r")))
        tw_error(TW_LOC, "Unable to open IC Stage file");

    // first line of file is number of diseases
    fscanf(f, "%u", &g_epi_ndiseases);

    // setup vars dependant on number of diseases
    g_epi_diseases = tw_calloc(TW_LOC, "", sizeof(epi_disease), g_epi_ndiseases);
    g_epi_log_f = tw_calloc(TW_LOC, "", sizeof(FILE *), g_epi_ndiseases);

    g_epi_exposed_today = tw_calloc(TW_LOC, "", sizeof(unsigned int), g_epi_ndiseases);
    g_epi_sick_init_pop = tw_calloc(TW_LOC, "", sizeof(unsigned int), g_epi_ndiseases);

    for(i = 0; i < g_epi_ndiseases; i++)
    {
        d = &g_epi_diseases[i];

        // first line of disease is number of stages
        fscanf(f, "%u", &d->nstages);

        if (!d->nstages)
            tw_error(TW_LOC, "No stages in ic file");

        // incr for stage 0
        d->nstages++;
        d->stages = tw_calloc(TW_LOC, "", sizeof(epi_ic_stage), d->nstages);

        /*
         * Stage 0 is Susceptible.  All agents who are not initially infected
         * start in this stage.  This is the default.  Its values are not
         * in the input file, but are set during agent initialization.
         * Agents who are infected at initialization are put into stage 1.
         */
        s = &d->stages[0];
        s->index = 0;
        strcpy(s->name, "Susceptible");
        s->start_multiplier = 0.0;
        s->stop_multiplier = 0.0;
        s->min_duration = DBL_MAX;
        s->max_duration = DBL_MAX;
        s->mortality_rate = 0.0;
        s->eligible_for_inoculation = TW_TRUE;
        s->progress_trumps_inoculation = TW_FALSE;
        s->hospital_treatment = TW_FALSE;
        s->is_symptomatic = TW_FALSE;
        s->days_in_hospital = 0.0;

        j = 1;
        s = &d->stages[j];

#if VERIFY_EPI
        printf("EPSILON: %e\n", EPSILON);
#endif

        fscanf(f, "%s", d->name);
        printf("\tDisease %d: %s\n\n", i+1, d->name);

        sprintf(fname, "%s.log", d->name);
        if(NULL == (g_epi_log_f[i] = fopen(fname, "w")))
            tw_error(TW_LOC, "Unable to open: %s \n", log);

        while(EOF != fscanf(f, "%u", &s->index))
        {
            if(0 == s->index)
                tw_error(TW_LOC, "IC should not have stage 0");

            if(j != s->index)
                tw_error(TW_LOC, "IC stage %d out of order-expected: %d\n",
                         s->index, j);

            fscanf(f, "%s", s->name);

            //printf("\tStage Name: %s\n",s->name);

            if (EOF == fscanf(f, "%lf", &s->start_multiplier))
                tw_error(TW_LOC, "File Error!");

            if (EOF == fscanf(f, "%lf", &s->stop_multiplier))
                tw_error(TW_LOC, "File Error!");

            if (EOF == fscanf(f, "%lf", &s->min_duration))
                tw_error(TW_LOC, "File Error!");

            if (EOF == fscanf(f, "%lf", &s->max_duration))
                tw_error(TW_LOC, "File Error!");

            if (s->min_duration > s->max_duration)
                tw_error(TW_LOC, "stage min duration > max duration");

            // Multiply by secons in a day
            s->min_duration *= 86400.0;
            s->max_duration *= 86400.0;

            if (EOF == fscanf(f, "%lf", &s->mortality_rate))
                tw_error(TW_LOC, "File Error!");

            fscanf(f, "%s", line);
            if (0 == strcmp(line, "true"))
                s->eligible_for_inoculation = TW_TRUE;
            else if (0 == strcmp(line, "false"))
                s->eligible_for_inoculation = TW_FALSE;
            else
                tw_error(TW_LOC, "invalid input for eligible_for_inoculation: %s\n", line);

            //printf("\teligible for inoculation: ");
            //if (s->eligible_for_inoculation == TW_TRUE)
            //	printf(" TRUE\n");
            //else
            //	printf(" FALSE\n");

            fscanf(f, "%s", line);
            if (0 == strcmp(line, "true"))
                s->progress_trumps_inoculation = TW_TRUE;
            else if (0 == strcmp(line, "false"))
                s->progress_trumps_inoculation = TW_FALSE;
            else
                tw_error(TW_LOC, "invalid input for progress_trumps_inoculation: %s\n", line);

            //printf("\tprogress trumps inoculation: ");
            //if (s->progress_trumps_inoculation == TW_TRUE)
            //	printf(" TRUE\n");
            //else
            //	printf(" FALSE\n");

            fscanf(f, "%s", line);
            if (0 == strcmp(line, "true"))
                s->hospital_treatment = TW_TRUE;
            else if (0 == strcmp(line, "false"))
                s->hospital_treatment = TW_FALSE;
            else
                tw_error(TW_LOC, "invalid input for hospital_treatment: %s\n", line);

#if VERIFY_EPI
            printf("\thospital treatment: ");
            if (s->hospital_treatment == TW_TRUE)
                printf(" TRUE\n");
            else
                printf(" FALSE\n");
#endif

            fscanf(f, "%s", line);
            if (0 == strcmp(line, "true"))
                s->is_symptomatic = TW_TRUE;
            else if (0 == strcmp(line, "false"))
                s->is_symptomatic = TW_FALSE;
            else
                tw_error(TW_LOC, "invalid input for s_symptomatic: %s\n", line);

#if VERIFY_EPI
            printf("\tis symptomatic: ");
            if (s->is_symptomatic == TW_TRUE)
                printf(" TRUE\n");
            else
                printf(" FALSE\n");
#endif

            if (EOF == fscanf(f, "%lf", &s->days_in_hospital))
                tw_error(TW_LOC, "File Error!");

            s->days_in_hospital *= 86400.0;

            // Calculate log of multiplier.
            // Right now, using the average of start_multiplier
            // and stop_multriplier.
            multiplier = (s->start_multiplier + s->stop_multiplier) / 2.0;

            if (multiplier > EPSILON)
                s->ln_multiplier = log(1 - multiplier);
            else
                s->ln_multiplier = 0.0;

            // Now print for log
            printf("\tStage %d: %s\n", s->index, s->name);

            printf("\t\t%-40s %11.2lf\n", "Min Duration", s->min_duration / 86400.0);
            printf("\t\t%-40s %11.2lf\n", "Max Duration", s->max_duration / 86400.0);

            if(s->mortality_rate)
                printf("\t\t%-40s %11.2lf\n", "Mortality Rate", s->mortality_rate);

            if (s->start_multiplier > EPSILON)
            {
                printf("\t\t%-40s %.9lf\n", "Start Mult", s->start_multiplier);
                printf("\t\t%-40s %.9lf\n", "Stop Mult", s->stop_multiplier);
            }

            if(s->ln_multiplier)
                printf("\t\t%-45s %.4g\n", "LN Mult", s->ln_multiplier);

            if(s->days_in_hospital)
                printf("\t\t%-40s %11.2lf\n", "Days in Hospital",
                       s->days_in_hospital / 86400.0);
            printf("\n");

            if(j == d->nstages-1)
                break;

            s = &d->stages[++j];
        }
    }

    if(f)
        fclose(f);
}
示例#8
0
/**
 * OSPF model LP init function.
 *
 * This is the OSPF model LP initialization function.  This function is
 * responsible for initializing each OSPF LP.  The main steps are:
 * <ol>
 * <li>Create and init the neighbor array
 * <li>Create and init the LP LSA database
 * <li>Create and init the LP forwarding table
 * <li>Start the aging timer for the oldest LSA
 * </ol>
 *
 * The order of steps 2 and 3 are dependant upon if the model is started in
 * converged state or not.  The determination is based on the fact that 
 * sometimes we build the forwarding table from the LSA database, and sometimes
 * we read it in from file.
 */
void
ospf_startup(ospf_state * state, tw_lp * lp)
{
	unsigned int	rv;
	unsigned int	next_timer;

#if OSPF_LOG
	char		 name[255];

	sprintf(name, "%s/ospf-router-%ld.log", g_rn_logs_dir, lp->gid);
	//state->log = fopen(name, "w");
	state->log = stdout;
#endif

	state->from = -1;
	state->from1 = -1;

	state->gstate = g_ospf_state;
	state->m = rn_getmachine(lp->gid);
	state->ar = rn_getarea(state->m);
	state->stats = tw_calloc(TW_LOC, "", sizeof(ospf_statistics), 1);

	if(lp->gid == 0)
	{
		for(rv = 0; rv < 400; rv++)
			g_route[rv] = g_route1[rv] = -1;

		gr1 = gr2 = 0;

		state->sn = .003;
	}

	//printf("Init OSPF router: %ld \n", lp->gid);

	// Create the neighbor data structures
	ospf_neighbor_init(state, lp);

	// Create my router LSA links
	state->lsa_seqnum = OSPF_MIN_LSA_SEQNUM + 1;

	if(!g_rn_converge_ospf)
	{
		ospf_db_read(state, lp);
		ospf_routing_init(state, lp);
	} else if(!g_rn_converge_ospf)
	{
		ospf_routing_init(state, lp);
		ospf_db_read(state, lp);
	} else if(0 == g_ospf_rt_write)
	{
		// Setup the routing table for the first time
		ospf_routing_init(state, lp);

		// Setup the LSA database for the first time
		next_timer = ospf_db_init(state, lp);
	} else
	{
		// Setup the LSA database for the first time
		next_timer = ospf_db_init(state, lp);

		// Setup the routing table for the first time
		ospf_routing_init(state, lp);
	}

	state->lsa = tw_memory_data(state->ar->g_ospf_lsa[lp->gid - state->ar->low]);

	if(!g_rn_converge_ospf && !g_rn_converge_bgp)
		ospf_random_weights(state, lp);

	/*
	 * This timer should only go off when the oldest LSA in my DB
	 * gets to be the REFRESH age, so that I can make sure to request an
	 * update for it
	 */
	state->aging_timer = NULL;

#if 0
	state->aging_timer =
		ospf_timer_start(NULL, state->aging_timer,
				 next_timer, OSPF_AGING_TIMER, lp);
#endif

#if VERIFY_AGING
	printf("%ld: setting aging timer finally: %lf \n", 
		lp->gid, next_timer);
#endif
}
示例#9
0
文件: torus.c 项目: wilseypa/ROSS
/*Initialize the torus model, this initialization part is borrowed from Ning's torus model */
void
torus_init( nodes_state * s, 
	   tw_lp * lp )
{
    int i, j;

    /* contains the real torus dimension coordinates */
    int dim_N[ N_dims + 1 ];
    int dim_N_sim[N_dims_sim + 1];
   
    /* initialize the real torus dimension */ 
    dim_N[ 0 ]=( int )lp->gid;
    
    /* initialize the simulated torus dimension */
    dim_N_sim[0]=(int)lp->gid;

  /* calculate the LP's real torus co-ordinates */
  for ( i=0; i < N_dims; i++ ) 
    {
      s->dim_position[ i ] = dim_N[ i ]%dim_length[ i ];
      dim_N[ i + 1 ] = ( dim_N[ i ] - s->dim_position[ i ] )/dim_length[ i ];

      half_length[ i ] = dim_length[ i ] / 2;
    }

  /* calculate the LP's simulated torus dimensions */
  for ( i=0; i < N_dims_sim; i++ )
    {
      s->dim_position_sim[ i ] = dim_N_sim[ i ]%dim_length_sim[ i ];
      dim_N_sim[ i + 1 ] = ( dim_N_sim[ i ] - s->dim_position_sim[ i ] )/dim_length_sim[ i ];

      half_length_sim[ i ] = dim_length_sim[ i ] / 2;
    }

  factor[ 0 ] = 1;
  factor_sim[0] = 1;

  /* factor helps in calculating the neighbors of the torus */
  for ( i=1; i < N_dims; i++ )
    {
      factor[ i ] = 1;
      for ( j = 0; j < i; j++ )
        factor[ i ] *= dim_length[ j ];
    }

  /* factor helps in calculating neighbors of the simulated torus */
  for ( i=1; i < N_dims_sim; i++ )
    {
      factor_sim[ i ] = 1;
      for ( j = 0; j < i; j++ )
        factor_sim[ i ] *= dim_length_sim[ j ];
    }

  int temp_dim_plus_pos[ N_dims ], temp_dim_plus_pos_sim[ N_dims_sim ];
  int temp_dim_minus_pos[ N_dims ], temp_dim_minus_pos_sim[ N_dims_sim ];

  /* calculate neighbors of the torus dimension */
  for ( i = 0; i < N_dims; i++ )
  {
    temp_dim_plus_pos[ i ] = s->dim_position[ i ];
    temp_dim_minus_pos[ i ] = s->dim_position[ i ];
  }

  /* calculated neighbors of the simulated torus */
  for ( i = 0; i < N_dims_sim; i++ )
  {
    temp_dim_plus_pos_sim[ i ] = s->dim_position_sim[ i ];
    temp_dim_minus_pos_sim[ i ] = s->dim_position_sim[ i ];
  }

  if( lp->gid == TRACK_LP )
  {
    printf("\n LP %d assigned dimensions: ", (int)lp->gid);
    
    for( i = 0; i < N_dims_sim; i++ )
        printf(" %d ", s->dim_position_sim[ i ]);
    
    printf("\t ");

    for( i = 0; i < N_dims; i++ )
        printf(" %d ", s->dim_position[ i ]);
  }

  /* calculate minus and plus neighbour's lpID */
  for ( j = 0; j < N_dims; j++ )
    {
      temp_dim_plus_pos[ j ] = (s->dim_position[ j ] + 1 + dim_length[ j ]) % dim_length[ j ];
      temp_dim_minus_pos[ j ] =  (s->dim_position[ j ] - 1 + dim_length[ j ]) % dim_length[ j ];
      
      s->neighbour_minus_lpID[ j ] = 0;
      s->neighbour_plus_lpID[ j ] = 0;
      
      for ( i = 0; i < N_dims; i++ )
       {
        s->neighbour_minus_lpID[ j ] += factor[ i ] * temp_dim_minus_pos[ i ];
	s->neighbour_plus_lpID[ j ] += factor[ i ] * temp_dim_plus_pos[ i ];
       } 
      
      temp_dim_plus_pos[ j ] = s->dim_position[ j ];
      temp_dim_minus_pos[ j ] = s->dim_position[ j ];
    }

  /* calculate minus and plus neighbour's lpID */
  for ( j = 0; j < N_dims_sim; j++ )
    {
      temp_dim_plus_pos_sim[ j ] = (s->dim_position_sim[ j ] + 1 + dim_length_sim[ j ]) % dim_length_sim[ j ];
      temp_dim_minus_pos_sim[ j ] =  (s->dim_position_sim[ j ] - 1 + dim_length_sim[ j ]) % dim_length_sim[ j ];
      
      s->neighbour_minus_lpID_sim[ j ] = 0;
      s->neighbour_plus_lpID_sim[ j ] = 0;
      
      for ( i = 0; i < N_dims_sim; i++ )
       {
        s->neighbour_minus_lpID_sim[ j ] += factor_sim[ i ] * temp_dim_minus_pos_sim[ i ];
	s->neighbour_plus_lpID_sim[ j ] += factor_sim[ i ] * temp_dim_plus_pos_sim[ i ];
       } 
      
      temp_dim_plus_pos_sim[ j ] = s->dim_position_sim[ j ];
      temp_dim_minus_pos_sim[ j ] = s->dim_position_sim[ j ];
    }

  for( j=0; j < 2 * N_dims; j++ )
   {
    for( i = 0; i < NUM_VC; i++ )
     {
       s->buffer[ j ][ i ] = 0;
       s->next_link_available_time[ j ][ i ] = 0.0;
     }
   }
  // record LP time
    s->packet_counter = 0;
    s->waiting_list = tw_calloc(TW_LOC, "waiting list", sizeof(struct waiting_packet), WAITING_PACK_COUNT);
    
    for (j = 0; j < WAITING_PACK_COUNT - 1; j++) {
    s->waiting_list[j].next = &s->waiting_list[j + 1];
    s->waiting_list[j].dim = -1;
    s->waiting_list[j].dir = -1;
    s->waiting_list[j].packet = NULL; 
    }
    
    s->waiting_list[j].next = NULL;
    s->waiting_list[j].dim = -1;
    s->waiting_list[j].dir = -1;
    s->waiting_list[j].packet = NULL;
 
    s->head = &s->waiting_list[0];
    s->wait_count = 0;

}
示例#10
0
inline
double	*
rm_getlocation(tw_lp * lp)
{
	double	*position;
	double   temp;

	tw_lpid	 id;
	int	 i;

	position = tw_calloc(TW_LOC, "position", sizeof(double) * g_rm_spatial_dim, 1);
	id = lp->gid - (g_rm_spatial_offset * (g_tw_mynode + 1));

#if DEBUG
//if(!g_tw_mynode)
printf("%ld: GETLOCATION: id %d\n", lp->gid, id);
#endif

	for(i = g_rm_spatial_dim-1; id >= 0 && i >= 0; i--)
	{
		if(g_rm_spatial_grid_i[i])
		{
			position[i] = floor(id / g_rm_spatial_grid_i[i]);
		} else
			position[i] = id;

#if DEBUG
	//if(!g_tw_mynode)
		printf("\ti %d, p %lf \n", i, position[i]);
#endif

		if(id && id >= g_rm_spatial_grid_i[i])
			id -= (position[i] * g_rm_spatial_grid_i[i]);

		if(position[i] < 0 || position[i] > g_rm_spatial_grid[i])
			tw_error(TW_LOC, "%ld: Off grid in %dD: 0 <= %d <= %d, LP %ld", 
				 id, i+1, position[i], g_rm_spatial_grid[i], lp->id);

		position[i] *= g_rm_spatial_d[i];

#if DEBUG
	//if(!g_tw_mynode)
		printf("\ti %d, p %lf \n\n", i, position[i]);
#endif
	}

#if DEBUG
//if(!g_tw_mynode)
	printf("\t\tp2 before %lf \n", position[2]);
#endif

	// offset Z-value by base
	position[2] += rm_getelevation(position);

#if DEBUG
//if(!g_tw_mynode)
	printf("\t\tp2 after %lf \n", position[2]);
#endif

	lpid = lp->gid;

	if(rm_getcell(position) != lp->gid)
	{
		printf("%d %lld %lld %lld: (%lf, %lf, %lf (%lf)) gid: %lld != %lld\n", g_tw_mynode, lp->gid, lp->id, id, position[0], position[1], temp, position[2], lp->gid, rm_getcell(position));

		if(_rm_map(rm_getcell(position)) == g_tw_mynode)
		{
			if(tw_getlocal_lp(rm_getcell(position))->type.state_sz != sizeof(rm_state))
				tw_error(TW_LOC, "got user model LP!");
		}

		if(rm_getcell(position) != lp->gid)
			tw_error(TW_LOC, "%d: Did not get correct cell location!", g_tw_mynode);
	}

	return position;
}
示例#11
0
void
tw_pe_create(tw_peid id)
{
	g_tw_npe = id;
	g_tw_pe = (tw_pe **) tw_calloc(TW_LOC, "PE Array", sizeof(*g_tw_pe), id);
}
示例#12
0
void
rn_setup_mobility(rn_lp_state * state, rn_lptype * types, tw_lp * lp)
{
	xmlNodePtr		x_temp;
	xmlNodePtr		x_mobility;
	xmlNodePtr		x_layer;

	rn_machine	*m;
	rn_stream	*mobility;
	rn_layer	*layer;

	int		 cur_mobility;
	int		 cur_layer;

	m = rn_getmachine(lp->gid);
	state->nmobility = 0;

	for(x_mobility = m->xml->children; x_mobility; x_mobility = x_mobility->next)
	{
		if(0 != strcmp((char *) x_mobility->name, "mobility"))
			continue;

		state->nmobility++;
	}

	if(!state->nmobility)
		return;

	state->mobility = tw_calloc(TW_LOC, "Local mobility array", 
				    sizeof(*state->mobility), state->nmobility);

	mobility = state->mobility;
	cur_layer = 0;
	cur_mobility = 0;

	for(x_mobility = m->xml->children; x_mobility; x_mobility = x_mobility->next)
	{
		if(0 != strcmp((char *) x_mobility->name, "mobility"))
			continue;

		/*
		 * Setup the mobility layers
		 */
		for(x_temp = x_mobility->children; x_temp; x_temp = x_temp->next)
		{
			if(0 != strcmp((char *) x_temp->name, "layer"))
				continue;

			mobility->nlayers++;
		}

		mobility->layers = tw_calloc(TW_LOC, "Local layer array",
					     sizeof(*mobility->layers), mobility->nlayers);

		layer = mobility->layers;
		x_layer = x_mobility->children;

		while(0 != strcmp((char *) x_layer->name, "layer"))
			x_layer = x_layer->next;

		rn_setup_layers(state, cur_mobility, layer, types, x_layer, lp);

		mobility = mobility + 1;
		cur_mobility++;
	}
}
示例#13
0
/**
 * This function sets up the star model for the different layers
 */
void
rn_setup_streams(rn_lp_state * state, rn_lptype * types, tw_lp * lp)
{
	xmlNodePtr		node;
	xmlNodePtr		x_temp;
	xmlNodePtr		x_stream;
	xmlNodePtr		x_layer;

	int			cur_stream;

	rn_layer		*layer;
	rn_stream		*stream;
	rn_machine		*m;

	m = rn_getmachine(lp->gid);
	state->nstreams = 0;

#if RN_VERIFY_SETUP
	printf("SETUP star model for node: %lld \n", lp->gid);
#endif

	for(x_stream = m->xml->children; x_stream; x_stream = x_stream->next)
	{
		if(0 != strcmp((char *) x_stream->name, "stream"))
			continue;

		state->nstreams++;
	}

	if(!state->nstreams)
		return;

	state->streams = tw_calloc(TW_LOC, "Local stream array", 
				   sizeof(*stream), state->nstreams);

	if(!state->streams)
		tw_error(TW_LOC, "Did not get any streams for machine %d!", lp->gid);

	node = m->xml;
	stream = state->streams;
	cur_stream = 0;
	for(x_stream = node->children; x_stream; x_stream = x_stream->next)
	{
		if(0 != strcmp((char *) x_stream->name, "stream"))
			continue;

		stream->port = atoi(xml_getprop(x_stream, "port"));

#if RN_VERIFY_SETUP
		printf("\tport: %d \n", stream->port);
#endif

		/*
		 * Setup the stream layers
		 */
		for(x_temp = x_stream->children; x_temp; x_temp = x_temp->next)
		{
			if(0 != strcmp((char *) x_temp->name, "layer"))
				continue;

			stream->nlayers++;
		}

		stream->layers = tw_calloc(TW_LOC, "Local layer array",
					   sizeof(*stream->layers), stream->nlayers);

		layer = stream->layers;
		x_layer = x_stream->children;

#if RN_VERIFY_SETUP
		printf("\tlayers: %d\n", stream->nlayers);
#endif

		while(0 != strcmp((char *) x_layer->name, "layer"))
			x_layer = x_layer->next;

		rn_setup_layers(state, cur_stream, layer, types, x_layer, lp);

		stream = stream + 1;
		cur_stream++;
	}
}
示例#14
0
文件: epi.c 项目: chleemobile/rossnet
/*
 * epi_init - initialize node LPs state variables
 * 
 * state	- our node LP state space
 * lp		- our node LP
 */
void
epi_init(epi_state * state, tw_lp * lp)
{
	tw_memory	*b;
	tw_memory	*agent = NULL;
	tw_stime	 ts_min_tran = DBL_MAX;

	epi_agent	*a;
	epi_pathogen	*p;
	epi_ic_stage	*s;

	double		 x;

	int		 i;
	int		 j;
	int		 sz;

	// hard-coded, single hospital LP
	if(lp->id == g_tw_nlp-1)
	{
		fprintf(g_epi_hospital_f, "0 0 %u %u %u\n", 
			g_epi_hospital[0][0], g_epi_hospital_ww[0][0], 
			g_epi_hospital_wws[0][0]);

		g_epi_hospital[0][0] = 0;
		g_epi_hospital_ww[0][0] = 0;
		g_epi_hospital_wws[0][0] = 0;

		return;
	}

	// ID of the hospital I go to (or nearest if office/school)
	state->hospital = 0;
	state->stats = tw_calloc(TW_LOC, "", sizeof(epi_statistics), 1);
	state->ncontagious = tw_calloc(TW_LOC, "", sizeof(unsigned int), g_epi_ndiseases);
	state->ts_seir = tw_calloc(TW_LOC, "", sizeof(tw_stime), g_epi_ndiseases);

	for(i = 0; i < g_epi_ndiseases; i++)
		state->ts_seir[i] = DBL_MAX;

	// if no agents initially at this location, then we are done!
	if(0 == (sz = pq_get_size(g_epi_pq[lp->id])))
		return;

	// determine agents initial parameters / configuration
	for(i = 0; i < sz; i++)
	{
		agent = pq_next(g_epi_pq[lp->id], i);
		a = tw_memory_data(agent);

		for(j = 0; j < g_epi_ndiseases; j++)
		{
			if(!a->id && !j)
			{
				// ALLOCATE PATHOGEN AND FILL IT IN
				b = tw_memory_alloc(lp, g_epi_pathogen_fd);
				p = tw_memory_data(b);

				b->next = a->pathogens;
				a->pathogens = b;

				p->index = j;
				p->stage = EPI_SUSCEPTIBLE;
				p->ts_stage_tran = DBL_MAX;

				g_epi_regions[a->region][p->index][p->stage]--;
				p->stage = EPI_EXPOSED;
				g_epi_regions[a->region][p->index][p->stage]++;
				g_epi_exposed_today[j]++;
	
				// determine if agents start out sick.
				if(tw_rand_unif(lp->rng) < g_epi_sick_rate)
				{

				s = &g_epi_diseases[p->index].stages[p->stage];

				x = ((double) tw_rand_integer(lp->rng, 0, INT_MAX) / 
						(double) INT_MAX);

				p->ts_stage_tran = (s->min_duration + 
						(x * (s->max_duration - s->min_duration)));

				if(0.0 >= p->ts_stage_tran)
					tw_error(TW_LOC, "Immediate stage transition?!");

				//state->stats->s_ninfected++;
				state->ncontagious[p->index]++;
				state->ncontagious_tot++;
				//g_epi_hospital[0][0]++;
				g_epi_sick_init_pop[j]++;

				ts_min_tran = min(ts_min_tran, p->ts_stage_tran);

				if(!a->id)
					printf("%ld: agent exposed %d: %s, transition at %lf\n", 
					lp->id, a->id, g_epi_diseases[j].name, 
					p->ts_stage_tran);
				}
			}
		}

		// reflect ts_next change in PQ ordering
		if(ts_min_tran < a->ts_next)
		{
			a->ts_next = ts_min_tran;
			pq_delete_any(g_epi_pq[lp->id], &agent);
			pq_enqueue(g_epi_pq[lp->id], agent);
		}

		// determine if agents are a part of worried well population.
		if(g_epi_ww_rate)
		{
			if(tw_rand_unif(lp->rng) < g_epi_ww_rate)
			{
				a->behavior_flags = 1;
				g_epi_hospital_ww[0][0]++;
				g_epi_ww_init_pop++;
			}
		} else if(g_epi_wws_rate)
		{
			if(tw_rand_unif(lp->rng) < g_epi_wws_rate)
			{
				a->behavior_flags = 2;
				g_epi_hospital_wws[0][0]++;
				g_epi_wws_init_pop++;
			}
		}

		// define agent's at work contact population
		//g_epi_regions[a->region][a->stage]++;
	}

	epi_location_timer(state, lp);
}
示例#15
0
void analysis_init(analysis_state *s, tw_lp *lp)
{
    int i, j, idx = 0, sim_idx = 0;
    tw_lp *cur_lp;

    // set our id relative to all analysis LPs
    s->analysis_id = lp->gid - analysis_start_gid;
    s->num_lps = ceil((double)g_tw_nlp / g_tw_nkp);

    // create list of LPs this is responsible for
    s->lp_list = (tw_lpid*)tw_calloc(TW_LOC, "analysis LPs", sizeof(tw_lpid), s->num_lps);
    s->lp_list_sim = (tw_lpid*)tw_calloc(TW_LOC, "analysis LPs", sizeof(tw_lpid), s->num_lps);
    // size of lp_list is max number of LPs this analysis LP is responsible for
    for (i = 0; i < s->num_lps; i++)
    {
        s->lp_list[i] = ULLONG_MAX;
        s->lp_list_sim[i] = ULLONG_MAX;
    }

    for (i = 0; i < g_tw_nlp; i++)
    {
        cur_lp = g_tw_lp[i];

        if (cur_lp->kp->id == s->analysis_id % g_tw_nkp)
        {
            s->lp_list_sim[sim_idx] = cur_lp->gid;
            sim_idx++;

            // check if this LP even needs sampling performed
            if (cur_lp->model_types == NULL || cur_lp->model_types->sample_struct_sz == 0)
                continue;

            s->lp_list[idx] = cur_lp->gid;
            idx++;
        }
    }

    // update num_lps
    s->num_lps = idx;
    s->num_lps_sim = sim_idx;

    // setup memory to use for model samples
    if ((g_st_model_stats == VT_STATS || g_st_model_stats == ALL_STATS) && s->num_lps > 0)
    {
        s->model_samples_head = (model_sample_data*) tw_calloc(TW_LOC, "analysis LPs", sizeof(model_sample_data), g_st_sample_count); 
        s->model_samples_current = s->model_samples_head;
        model_sample_data *sample = s->model_samples_head;
        for (i = 0; i < g_st_sample_count; i++)
        {
            if (i == 0)
            {
                sample->prev = NULL;
                sample->next = sample + 1;
                sample->next->prev = sample;
            }
            else if (i == g_st_sample_count - 1)
            {
                sample->next = NULL;
                s->model_samples_tail = sample;
            }
            else 
            {
                sample->next = sample + 1;
                sample->next->prev = sample;
            }
            if (s->num_lps <= 0)
                tw_error(TW_LOC, "s->num_lps <= 0!");
            sample->lp_data = (void**) tw_calloc(TW_LOC, "analysis LPs", sizeof(void*), s->num_lps);
            for (j = 0; j < s->num_lps; j++)
            {
                cur_lp = tw_getlocal_lp(s->lp_list[j]);
                sample->lp_data[j] = (void *) tw_calloc(TW_LOC, "analysis LPs", cur_lp->model_types->sample_struct_sz, 1);
            }
            sample = sample->next;
        }
    }

    // schedule 1st sampling event 
    st_create_sample_event(lp);
}
示例#16
0
void
epi_xml(epi_state * state, const xmlNodePtr node, tw_lp * lp)
{
	xmlNodePtr	 agent;
	xmlNodePtr	 move;
	rn_machine	*m = rn_getmachine(lp->id);

	epi_agent	*a;
	epi_ic_stage	*s;

	double		 x;

	int		 ct;
	int		 i;

	char		*sick;

	// create census tract table if it does not exist
	// need 1 more than number of stages to save dead agents
	// dead is not a stage.
	if (!g_epi_ct)
	{
		g_epi_nct = 2200; //rn_getarea(m)->nsubnets;
		g_epi_ct = tw_calloc(TW_LOC, "", sizeof(unsigned int *), g_epi_nct);

		for (i = 0; i < g_epi_nct; i++)
			g_epi_ct[i] = tw_calloc(TW_LOC, "", sizeof(unsigned int), g_epi_nstages);
	}

	state->stats = tw_calloc(TW_LOC, "", sizeof(epi_statistics), 1);
	state->pq = pq_create();

	ct = rn_getsubnet(m)->id - rn_getarea(m)->subnets[0].id;

	// spin through agents 'homed' at this location and allocate + init them
	//
	// NOTE: May not have *any* agents homed at a given location
	for(agent = node->children; agent; agent = agent->next)
	{
		if(0 != strcmp((char *) agent->name, "agent"))
			continue;

		a = tw_calloc(TW_LOC, "", sizeof(epi_agent), 1);

		a->ct = m->uid; //ct;
		a->num = atoi(xml_getprop(agent, "num"));
		//a->a_type = atoi(xml_getprop(agent,"type"));

		sick = xml_getprop(agent, "sick");
		if(g_epi_psick > EPSILON)
		{
			if ( tw_rand_unif(lp->rng) < g_epi_psick )
				sick = "1";
		}

		if(0 != strcmp(sick, "0"))
		{
			//a->ts_infected = atof(sick);
			a->stage = EPI_INCUBATING;

			s = &g_epi_stages[a->stage];

			x = ((double) tw_rand_integer(lp->rng, 0, INT_MAX) / (double) INT_MAX);
		
			a->ts_stage_tran = (s->min_duration + 
						(x * (s->max_duration - s->min_duration)));

#if EPI_XML_VERIFY
			printf("\tstage: %d, time %5f \n",
				s->stage_index, a->ts_stage_tran);
#endif

			g_epi_nsick++;
		} else
		{
			a->stage = EPI_SUSCEPTIBLE;
			a->ts_stage_tran = DBL_MAX;
			//a->ts_infected = DBL_MAX;
		}

		g_epi_ct[a->ct][a->stage]++;

		//a->id = g_epi_nagents++;
		g_epi_nagents++;
		a->curr = 0;
		//a->ts_last_tran = 0.0;
		a->ts_next = a->ts_remove = (double) 86400.0;
		//a->n_infected = 0;

		for(move = agent->children; move; move = move->next)
		{
			if(0 != strcmp((char *) move->name, "move"))
				continue;

			a->nloc++;
		}

		if(!a->nloc)
			tw_error(TW_LOC, "Agent has no locations!");

		a->nloc++; // add a location to return home at end of day

		a->loc = tw_calloc(TW_LOC, "", sizeof(int) * a->nloc, 1);
		a->dur = tw_calloc(TW_LOC, "", sizeof(tw_stime) * a->nloc, 1);

		int seconds_used = 0; // totals duration to check for 24 hours

		for(i = 0, move = agent->children; move; move = move->next)
		{
			if(0 != strcmp((char *) move->name, "move"))
				continue;

			a->loc[i] = atoi(xml_getprop(move, "loc"));
			a->dur[i] = atoi(xml_getprop(move, "dur")) * 3600;
			seconds_used += a->dur[i];
			i++;
		}

		if (seconds_used > 86400)
			tw_error(TW_LOC, "Agent has duration more than 24 hours\n");

		else if (seconds_used == 86400)
			a->nloc--; // do not need last location
		else {
			a->loc[a->nloc-1] = a->loc[0]; // return home
			a->dur[a->nloc-1] = 86400 - seconds_used;
		}

		a->behavior_flags = 0;
		if (g_epi_worried_well_rate > 0)
		{
			if (tw_rand_unif(lp->rng) < g_epi_worried_well_rate)
				a->behavior_flags = 1;
		} else if (g_epi_work_while_sick_p > EPSILON)
			if (tw_rand_unif(lp->rng) < g_epi_work_while_sick_p)
				a->behavior_flags = 2;

		// Set ts_next and enqueue
		a->ts_remove = a->dur[a->curr];
		if(a->ts_remove < a->ts_stage_tran)
			a->ts_next = a->ts_remove;
		else
			a->ts_next = a->ts_stage_tran;

		pq_enqueue(state->pq, a);
	}
}
示例#17
0
void
tlm_md_init(int argc, char ** argv, char ** env)
{
	tw_lpid		 nlp_grid;

	int		 i;

	if(!g_rn_environment)
		return;

	g_tlm_stats = tw_calloc(TW_LOC, "", sizeof(*g_tlm_stats), 1);

	// g_tlm_output_fix up global variables
	g_tw_ts_end += 0.1;

	if(0 != strcmp(g_rn_tools_dir, ""))
		sprintf(g_tlm_spatial_terrain_fn, "tools/%s/terrain.txt", g_rn_tools_dir);
	else
		tw_error(TW_LOC, "No terrain file specified!");

	/*
	 * Open debug plotting files
	 */
#if 0
	g_tlm_waves_plt_f = fopen("waves.plt", "w");
	g_tlm_nodes_plt_f = fopen("user_nodes.plt", "w");
	g_tlm_parts_plt_f = fopen("particles.plt", "w");

	if(!g_tlm_nodes_plt_f || !g_tlm_parts_plt_f)
		tw_error(TW_LOC, "Unable to open plotting files!");
#endif

	g_tlm_stats = tw_calloc(TW_LOC, "tlm stats", sizeof(tlm_statistics), 1);
	memset(g_tlm_stats, 0, sizeof(tlm_statistics));

	// # of cells around me = 2 * # spatial_dim
	g_tlm_spatial_dir = g_tlm_spatial_dim * 2;
	g_tlm_spatial_coeff = 2.0 / g_tlm_spatial_dir;

	g_tlm_spatial_grid_i = tw_calloc(TW_LOC, "spatial grid i", sizeof(int), g_tlm_spatial_dim);
	g_tlm_spatial_offset_ts = tw_calloc(TW_LOC, "spatial offset ts", sizeof(tw_stime), g_tlm_spatial_dir);
	g_tlm_spatial_offset = g_rn_nmachines / (tw_nnodes() * g_tw_npe);

	g_tlm_spatial_ground_coeff = 0.75;

	if(0.0 > g_tlm_wave_loss_coeff)
	{
		g_tlm_wave_loss_coeff = 1.0 / exp(g_tlm_wave_attenuation * g_tlm_spatial_d[0]);

		if(tw_ismaster())
			printf("\n\tSETTING WAVE LOSS COEFF %lf! \n\n", g_tlm_wave_loss_coeff);
	}

	// speed of light in m/s
	g_tlm_wave_velocity = 299792458.0;

	nlp_grid = tlm_grid_init();
	ntlm_lp_per_pe = ceil(nlp_grid / (tw_nnodes() * g_tw_npe));

	if(tw_nnodes() == 1)
		ntlm_lp_per_pe = nlp_grid;

	g_tw_events_per_pe = 1.5 * nlp_grid / (tw_nnodes() * g_tw_npe);
	g_tw_events_per_pe += g_tlm_optmem;

#if 0
	for(i = 0; i < g_tlm_spatial_offset; i++)
		tw_lp_settype(i, types);
#endif

	//tw_error(TW_LOC, "setting types not ported");

	if(!tw_ismaster())
		return;

	printf("\nInitializing Model: Transmission Line Matrix\n");
#if DWB
	printf("\t\t%-42s %11d (%ld)\n", "TLM Membufs", 1000000, g_tlm_fd);
#endif

#if RM_LOG_STATS
	g_tlm_output_f = fopen("tlm.log", "w");

	if(!g_tlm_output_f)
		tw_error(TW_LOC, "Unable to open TLM logfile!");
#else
	g_tlm_output_f = stdout;
#endif

	fprintf(g_tlm_output_f, "\n");
	fprintf(g_tlm_output_f, "\t%-50s\n", "Spatial Parameters:");
	fprintf(g_tlm_output_f, "\n");
	fprintf(g_tlm_output_f, "\t\t%-42s %11.4lf\n", "Spatial Coefficient", g_tlm_spatial_coeff);
	fprintf(g_tlm_output_f, "\n");
	fprintf(g_tlm_output_f, "\t\t%-42s %11dD\n", "Dimensions Computed", g_tlm_spatial_dim);

	for(i = 0; i < g_tlm_spatial_dim; i++)
	{
		fprintf(g_tlm_output_f, "\t\t%-42s %11d %dD\n", "Cells per Dimension", 
						g_tlm_spatial_grid[i], i+1);
		fprintf(g_tlm_output_f, "\t\t%-42s %11d %dD\n", "Cell Spacing ", 
						g_tlm_spatial_d[i], i+1);
	}

	fprintf(g_tlm_output_f, "\n");
	fprintf(g_tlm_output_f, "\t%-50s\n", "Temporal Parameters:");
	fprintf(g_tlm_output_f, "\n");
	fprintf(g_tlm_output_f, "\t\t%-42s %11.11lf\n", "Scatter Offset TS", g_tlm_scatter_ts);
	fprintf(g_tlm_output_f, "\t\t%-42s %11.4lf\n", "Loss Coefficient", g_tlm_wave_loss_coeff);
	fprintf(g_tlm_output_f, "\t\t%-42s %11.4lf\n", "Velocity", g_tlm_wave_velocity);

	for(i = 0; i < g_tlm_spatial_dim; i++)
		fprintf(g_tlm_output_f, "\t\t%-42s %11.11lf %dD\n", "Timestep (d/V)", 
					g_tlm_spatial_offset_ts[i], i+1);
	fprintf(g_tlm_output_f, "\t\t%-42s %11.4lf\n", "Amplitude Threshold", g_tlm_wave_threshold);

	fprintf(g_tlm_output_f, "\t%-50s %11d\n", "Spatial Offset", 
						g_tlm_spatial_offset);
}
示例#18
0
	/*
	 * This function initializes the environment model.. should be called
	 * once by user model.  Allows EM to control how ROSS is init'd.
	 *
	 * This function provides the Reactive Model with a pre-simulation 'main'
	 */
int
rm_initialize(tw_petype * ptypes, tw_lptype * types, tw_peid npe, 
		tw_kpid nkp, tw_lpid nradios, size_t msg_sz)
{
	//FILE		*fp;

	tw_lptype 	*t;
	//tw_pe		*pe;
	//tw_kp		*kp;
	//tw_lp		*lp;

	//size_t		 size;

	//int		 max_name;
	int	   	 ntypes;
	tw_lpid		 nlp_grid;
	//int		 nkp_grid;
	//int		 nnodes;
	int		 i;
	//int		 j;
	//int		 k;
	//int		 m;

	//int		 kp_per_pe;

	/*
	 * Open debug plotting files
	 */
#if 0
	g_rm_waves_plt_f = fopen("waves.plt", "w");
	g_rm_nodes_plt_f = fopen("user_nodes.plt", "w");
	g_rm_parts_plt_f = fopen("particles.plt", "w");

	if(!g_rm_nodes_plt_f || !g_rm_parts_plt_f)
		tw_error(TW_LOC, "Unable to open plotting files!");
#endif

	g_rm_stats = tw_calloc(TW_LOC, "rm stats", sizeof(rm_statistics), 1);
	memset(g_rm_stats, 0, sizeof(rm_statistics));

	// # of cells around me = 2 * # spatial_dim
	g_rm_spatial_dir = g_rm_spatial_dim * 2;
	g_rm_spatial_offset = nradios;
	g_rm_spatial_coeff = 2.0 / g_rm_spatial_dir;

	g_rm_spatial_grid_i = tw_calloc(TW_LOC, "spatial grid i", sizeof(int), g_rm_spatial_dim);
	g_rm_spatial_offset_ts = tw_calloc(TW_LOC, "spatial offset ts", sizeof(tw_stime), g_rm_spatial_dir);

	g_rm_spatial_ground_coeff = 0.75;

	if(0.0 > g_rm_wave_loss_coeff)
	{
		g_rm_wave_loss_coeff = 0.5;
		g_rm_wave_loss_coeff = 1.0 / exp(g_rm_wave_attenuation * g_rm_spatial_d[0]);

		if(tw_node_eq(&g_tw_mynode, &g_tw_masternode))
			printf("\n\tSETTING WAVE LOSS COEFF %lf! \n\n", g_rm_wave_loss_coeff);
	}

	g_rm_wave_velocity = 3.0 * 1000.0 * 1000.0 * 1000.0;

	// Require NULL terminated array, plus LPs for Cells
	for(ntypes = 2, t = types; t->state_sz; t++)
		ntypes++;

	//printf("Creating %d lp types\n", ntypes);
	t = tw_calloc(TW_LOC, "lp types array", sizeof(tw_lptype), ntypes);
	memcpy(t, types, sizeof(tw_lptype) * (ntypes-2));
	memcpy(&t[ntypes-2], rm_lps, sizeof(rm_lps));

	nlp_grid = rm_grid_init();
	nrmlp_per_pe = ceil(nlp_grid / (tw_nnodes() * g_tw_npe));

	if(tw_nnodes() == 1)
		nrmlp_per_pe = nlp_grid;
	nlp_per_pe = nradios + nrmlp_per_pe;

	g_tw_events_per_pe = .1 * nlp_grid / (tw_nnodes() * g_tw_npe);
	g_tw_events_per_pe += optimistic_memory;

	rm_grid_terrain();

	for(i = 0; i < g_tw_npe; i++)
		tw_pe_settype(g_tw_pe[i], rm_pes);
	tw_pe_settype(&g_rm_pe, ptypes);

	g_tw_rng_default = TW_FALSE;
	tw_define_lps(nlp_per_pe, sizeof(rm_message), 0);

	for(i = 0; i < g_rm_spatial_offset; i++)
		tw_lp_settype(i, types);

	for( ; i < g_tw_nlp; i++)
		tw_lp_settype(i, rm_lps);

	return 1;
}