Search code examples
anylogiclinkedhashmap

How to use LinkedHashMaps in Anylogic


I want to have a cumulative number of sows that enter the Sink (deadSowsCulledSows and sowDeaths) over the last 52 weeks. I have created variables for weekly sow deaths at these sink locations using cyclic events. I want this cumulative number to be calculated for every week of the simulation. For example, at week 10 – I want to have a cumulative number of deaths for weeks 1 to 10; at week 52 – I want to have a cumulative number for week 1 to 52, and for week 53 – I want to have a cumulative number between weeks 2 and 53, and so on.

It has been suggested that I use a LinkedHashMap, and I agree, but I don't know where to begin with setting this up? I want to use week as the value and weekly deaths as the key. Where do I insert the code to have the values put into the LinkedHashMap?

I feel like I am missing components in order to achieve this.

Death sinks and Collection for LinkedHashMap

Full model view


Solution

  • It sounds like you want a moving window of the last 52 weeks.

    There are a few options here but the easiest one I would suggest for you is to make use of the AnyLogic DataSet object as it already has this "keep up to a maximum number of samples" functionality which is what you need.

    1. Setup a data set where you set the maximum number of samples to keep to 52, do not update automatically and do not use time as x-axis as we will set this up ourselves.

    enter image description here

    1. In the sink block you increase the weekly variable. (Which I assume you are already doing)

    enter image description here

    1. Create a HashMap. I would suggest you use the week as the key and the number of deaths as the value (You had it the other way around in your question)

    enter image description here

    1. Then you have some event that saves the weekly sum of values to the dataset, reset the variable to 0.

    Then gets the sum of the data set and save it to the LinkedHasMap.

    The code for your weekly event can be as below

    weekCounter ++;
    deaths.add(weekCounter, weeklyDeaths);
    weeklyDeaths = 0;
    int tempSum = 0;
    for (int i = 0; i < deaths.size(); i ++) {
        tempSum += deaths.getY(i);
    }
    mapOfDeathsPerWeek.put(weekCounter, tempSum);
    
    

    Where weekCounter is just another variable that I created that I can increase every week to keep track of the weeks.