Esempio n. 1
0
def init_agents():
    
    global agents, nAgents, square, circle, avgInput, \
            nAgentsWht, nAgentsBlk, nAgentsOth, avgInput
    
    totInput = 0.
    
    ## for each agent
    for agtId in range(nAgents):
        # 
        writelog.write("agtId = %d\n"%agtId)
        newAgent = init_agent(agtId)
        
        # Append to agents list
        agents.append(newAgent)
        totInput += newAgent['iVal']
        
    
    
    avgInput = totInput/float(nAgents)
    
    # Service provider square and 2 sigma range
    square = plt.Rectangle((axes.provXOrg, axes.provYOrg),
                           axes.provSize, axes.provSize, fc=(0,1,0), ec='k')
    axes.ax.add_patch(square)
    
    # Dist feature sigma radius dashed circle
    circle = plt.Circle((axes.provXOrg, axes.provYOrg), radius=rSigma, ec='r',
                        fc='none', linestyle='dashed', visible=axes.checkDist)
    axes.ax.add_patch(circle)
Esempio n. 2
0
def printSched():
    for indx, entry in enumerate(schedList):
        outStr=StringIO.StringIO()
        outStr.write(' %3d: ['%entry[0])
        
        # outStr.write(' %3d: %s ['%(entry[0], ststr)) # Duplicate line?
        for tr in range(1,standardSched+1):
            if entry[tr] == None:
                outStr.write('  ~  ')
            else:
                outStr.write('%4.2f '%entry[tr])
        outStr.write(']\n')
        writelog.write(outStr.getvalue())
        outStr.close()
Esempio n. 3
0
def printSched(schedList):
    for indx, entry in enumerate(schedList):
        outStr=StringIO.StringIO()
        outStr.write(' %3d: ['%entry[0])
        
        outStr.write(' %3d: ['%entry[0])
        for tr in range(1,agents.standardSched+1):
            if entry[tr] == None:
                outStr.write('  ~  ')
            else:
                outStr.write('%4.2f '%entry[tr])
        outStr.write(']\n')
        writelog.write(outStr.getvalue())
        outStr.close()
Esempio n. 4
0
def init_agents():
    
    global agents, nAgents, square, circle, \
            agencyList, nAgencies, \
            nAgentsWht, nAgentsBlk, nAgentsOth, avgInput
    global dataFileName
            
    print '*****[ In init_agents() ]*****'
    
    
    totInput = 0.
    ## for each agent
    for agtId in range(nAgents):
        # 
        if doingLogging:
            writelog.write("agtId = %d\n"%agtId)
        # start = time.time()
        #print '  init_agent(%d) '%agtId
        newAgent = init_agent(agtId)
#        end = time.time()
#        elapsed = end - start
#        (min_, sec) = divmod(elapsed, 60)
#        (hr, min_)  = divmod(min_, 60)
#        print '  elapsed time = %02d:%02d:%02d'%(hr, min_, sec)
        
        
        
        # Append to agents list
        agents.append(newAgent)
        totInput += newAgent['iVal']
        
    avgInput = totInput/float(nAgents)
    
    if axes.checkStepped:
        dataFileName = 'Sp19Stepped.dat'
    else:
        dataFileName = 'Sp19.dat'
        
    if os.path.exists(dataFileName):
        os.remove(dataFileName)
Esempio n. 5
0
def printSched(agcy):
    schedList = agcy['schedList']
    name   = agcy['name']
    abbrev = agcy['abbrev']
    boro   = agcy['boro']
    writelog.write('========[ '+name+' ('+abbrev+') in '+boro+' ]========\n')
    for indx, entry in enumerate(schedList):
        outStr=StringIO.StringIO()
        if entry[1]:
            stateStr = 'X'
        else:
            stateStr = ' '
        outStr.write(' %3d: %s ['%(entry[0], stateStr))
        
        for tr in range(2,standardSched+2):
            if entry[tr] == None:
                outStr.write('  ~  ')
            else:
                outStr.write('%4.2f '%entry[tr])
        outStr.write(']\n')
        writelog.write(outStr.getvalue())
        outStr.close()
Esempio n. 6
0
def on_pick(event):
    for boro in agencies.agenciesList:
        found = False
        for agcy in agencies.agenciesList[boro]:
            if agcy['square'] is event.artist:
                found = True
                agencies.selected['square'].set_lw(1)
                agencies.selected['square'].set_ec('k')
                agencies.selected = agcy
                agcy['square'].set_lw(4)
                agcy['square'].set_ec('r')
                if agencies.selected['tileArray'] == []:
                    agents.initTileArray(agencies.selected)
                agents.updateTileArray(agencies.selected)
                axes.schedTitle.set_text(boro+': '+agcy['abbrev']+' '+agcy['name'])
                axes.fig.canvas.draw()
                break
        if found == True:
            break
        
    if agents.doingLogging:
        writelog.write('In on_pick(): selected is now %s %s %s\n'%(
        agencies.selected['boro'], agencies.selected['abbrev'], agencies.selected['name']))
lastT = 0.
dt = 1
dArray = deque([0.])
tArray = deque([0.])
plotWidth = 500
isFemale = 0
isYoung = 1
race = 'white'
ethn = 'hispanic'
income = 'lowrange'
hadStressors = 0
nSandyTraumas = 0
PTSD_sx = 0

writelog.init('PTSD_Combo1.log')
writelog.write('sex \t age \t race \t ethn \t\t income \t hadStr  nSandTr exp(P)\n')
writelog.write('=== \t === \t ==== \t ==== \t\t ====== \t ======  ======= ======\n\n')

plt.close('all')
fig = plt.figure(figsize=(12,6))
fig.canvas.set_window_title('PTSD_Distribution.py')

# Create axes boxes in a linspace xorg line
xorg = np.linspace(.05,.9,7)
axSex    = plt.axes([xorg[0],.6,.08,.2]); axSex.set_title('Sex')
axAge    = plt.axes([xorg[1],.6,.08,.2]); axAge.set_title('Age')
axRace   = plt.axes([xorg[2],.6,.08,.2]); axRace.set_title('Race')
axEthn   = plt.axes([xorg[3],.6,.08,.2]); axEthn.set_title('Ethn')
axIncome = plt.axes([xorg[4],.6,.08,.2]); axIncome.set_title('Income')
axStress = plt.axes([xorg[5],.6,.08,.2]); axStress.set_title('Stress')
axTrauma = plt.axes([xorg[6],.6,.08,.2]); axTrauma.set_title('Trauma')
Esempio n. 8
0
def update_agent(agent):

    global nEnrolled, schedList, schedPtr

    # print '  In update_agent agent = %r'%agent
    if doingLogging:
        writelog.write('In update_agent %3d\n'%agent['id'])
        writelog.write(re.sub(r',', '\n', '%r\n'%agent))

    xVal = agent['xVal']
    inputVal = agent['iVal']

    # If service is on, service the agents
    if axes.checkService:
        #square.set_fc('#00ff00')

        ########[ Enrollment Test ]#########
        # If not scheduled for treatment consider enrolling
        if not agent['enrolled']:
  

            # Shuffle agency list every time
            boroName = agent['boroName']
            if doingLogging:
                writelog.write('  Searching through agencies in '+boroName+'\n')
            #shuffledList = sample(agencies.agenciesList[boroName], listLen)

############# Loop through agencies in borough here ######################

            #### For each agency in this borough
            for agcy in agencies.agenciesList[boroName]:
                
                abbrev = agcy['abbrev']
                (agcyXLoc, agcyYLoc) = agcy['loc']
                (xLoc, yLoc) = (agent['xLoc'], agent['yLoc'])


                # Calculate probability of enrollment based on need 
                need = max(( avgInput - xVal),0.) * needFactor
                probEnroll = need * (agcy['maxEnrolled'] - agcy['numEnrolled'])
                if useProbCBTprobEnroll:
                    print 'WARNING: useProbCBTprobEnroll TRUE but not implemented.'
                if doingLogging:
                    writelog.write('  agt %3d need = %4.2f numEnrolled = %4.2f probEnroll["%s"] = %5.2f xVal = %5.2f\n'%(
                                agent['id'], need, agcy['numEnrolled'], abbrev.ljust(8), probEnroll, xVal))
    
                ########[ Need Test ]########
                # If enroll probability exceeds random threshold then enroll
                if probEnroll > random():
                    if doingLogging:
                        writelog.write('  probEnroll > random: Enroll!\n')
                    agent['enrolled'] = True
                    agent['agency'] = agcy
                    agcy['numEnrolled'] += 1                    
                    
                    # Define agent's bezier links to that agency
                    if axes.checkGraphics:
                        verts = ((agcyXLoc, agcyYLoc), # Bezier lnk from prov. to here
                                 ((agcyXLoc + xLoc)/2., agcyYLoc),
                                 (xLoc, (agcyYLoc + yLoc)/2.),
                                 (xLoc, yLoc))
                        bezPath = Path(verts, codes)
                        bezPatch = mpatches.PathPatch(bezPath, facecolor='none',
                                                  lw=1, ec='#afafaf', visible=True)
                        axes.ax.add_patch(bezPatch)
                        agent['bezPatch'] = bezPatch
                        agent['idText'].set_visible(True)
                    inputVal = agent['iVal']
    
                    # Register in schedList[]
                    if doingLogging:
                        writelog.write('About to register in schedList\n')
                        writelog.write('  Enrolling agent %d in agency %s\n'%(agent['id'], agcy['abbrev']))
                    treatList = [None for i in range(standardSched)]
                    treatList[agent['treatNo']] = agent['xVal']
                    treatList.insert(0, agent['isComplex'])
                    treatList.insert(0,agent['id'])
                    agcy['schedList'].append(treatList)
                    #agcy['schedList'] = treatList
                    #schedNo = len(agcy['schedList']) -1
                    
                    # update schedule
                    if axes.checkGraphics and agcy is agencies.selected:                    
                        updateTileArray(agcy)
                    if doingLogging:
                        printSched(agcy)
                        
                    break

 ############# End Loop through agencies in borough ######################

   
        # Otherwise if already enrolled compute input treatment
        else:
            
            # If agent not accepting of CBT then un-enroll
            if agent['acceptCBT'] < random():
                agent['treating'] = False;
                if axes.checkGraphics:
                    agent['bezPatch'].set_lw(1)
                    agent['bezPatch'].set_ec('#afafaf')
                inputVal = agent['iVal']

                if doingLogging: writelog.write('  agent %d acceptCBT < random() treatment %d OFF\n'%
                                    (agent['id'], agent['treatNo']))
                                    
            # Otherwise if accepting
            elif random() > .25: # Randomize every other time to break sync

                # If agent not being treated do next treatment
                if agent['treating'] == False:
                    if doingLogging:
                        writelog.write('  agent %d treatment %d ON\n'%(agent['id'], 
                                                                          agent['treatNo']))
                    agent['treating'] = True
                    (provXCtr, provYCtr) = agent['agency']['loc']
                    if axes.checkGraphics:
                        agent['bezPatch'].set_lw(2)
                        agent['bezPatch'].set_ec('#00ff00')
                    
                    # Turn on input
                    if axes.checkEndBen:
                        agent['iVal'] += doseValue*agent['iFact']/10. # endBen increase iVal
                    else:
                        inputVal = agent['iVal'] + doseValue  * agent['iFact']
                        
                    # Increment treatment number
                    agent['treatNo'] += 1
 
                    if axes.checkStepped and not agent['isComplex']:
                        nTreatLeft = steppedSched + 1
                    else:
                        nTreatLeft = standardSched + 1
                        
                    ########[ COMPLETION TEST ]#######
                    # If treatment done then un-enroll
                    if agent['treatNo'] >= nTreatLeft:
                        
                        if doingLogging:
                            if axes.checkStepped and not agent['isComplex']:
                                writelog.write('  treatNo = %d steppedSched = %d\n'%
                                             (agent['treatNo'], steppedSched))
                            else:
                                writelog.write('  treatNo = %d standardSched = %d\n'%
                                             (agent['treatNo'], standardSched))
                            writelog.write('Un-enroll agent %d treatment done\n'% 
                                                            agent['id'])
                                                            
                        agent['enrolled'] = False
                        agent['treatNo'] = 0
                        agent['agency']['numEnrolled'] -= 1
                        if axes.checkGraphics:
                            agent['bezPatch'].remove()
                            agent['idText'].set_visible(False)
                        for entry in agent['agency']['schedList']:
                            if entry[0] == int(agent['id']):
                                agent['agency']['schedList'].remove(entry)
                                #break

                    # Else if already treating turn treatment off, pipeline gray
                    
                    else:
                        for indx, sched in enumerate(agent['agency']['schedList']):
                            if sched[0] == int(agent['id']):
                                agent['agency']['schedList'][indx][agent['treatNo']+1] = agent['xVal']
                                #break
                        if doingLogging: writelog.write('  agent %d treatment %d ON\n'%
                                           (agent['id'], agent['treatNo']+1))
                    
 
                # Otherwise if patient being treated turn it off
                else:
                    agent['treating'] = False;
                    if axes.checkGraphics:
                        agent['bezPatch'].set_lw(1)
                        agent['bezPatch'].set_ec('#afafaf')
                    inputVal = agent['iVal']

                    if doingLogging: writelog.write('  agent %d treatment %d OFF\n'%
                                        (agent['id'], agent['treatNo']))

            # Update schedule
            #schedNo = len(agcy['schedList']) -1
            #print '#### schedNo = %d'%schedNo
            if agent['agency']: 
                if axes.checkGraphics and agent['agency'] is agencies.selected:
                    updateTileArray(agent['agency'])
                if doingLogging:
                    printSched(agent['agency'])
    
               # schedList = [x for x in schedList if x[0] != agent['id']]
    


    # Else if service is off, shut off treatment
    else:
        if agent['bezPatch']:
            if axes.checkGraphics:
                agent['bezPatch'].set_visible(False)
        inputVal = agent['iVal'] * agent['iFact']


    # Shunting equation
    xVal += -A * xVal + (1 - xVal) * inputVal
    if xVal < 0.:
        xVal = 0.
    elif xVal > 1.:
        xVal = 1.
    agent['xVal'] = xVal
    if axes.checkGraphics:
        if xVal > visThresh:
            agent['circ1'].set_visible(False)
        else:
            agent['circ1'].set_visible(True)
    r = (1. - xVal)
    g = xVal
    if axes.checkGraphics:
        agent['circ1'].set_facecolor((r, g, 0.))

    # Time delay
    if delay > 0.:
        time.sleep(delay)
Esempio n. 9
0
def init_agent(agtId):

    global nEnrolled, schedList, schedPtr
    global agents, nAgents, square, circle, \
            nAgentsWht, nAgentsBlk, nAgentsOth
    global agencyList, nAgencies
    
    if doingLogging:
        writelog.write('In init_agent(%3d)'%agtId)

    foundSpace = False
    while not foundSpace:
        xLoc = random() * image.aspect + .1*image.aspect
        yLoc = random()
        #writelog.write("agtId: % 3d  xLoc, yLoc = (%4.2f, %4.2f)\n"%(agtId, xLoc, yLoc))
        
        inMask  = image.maskImg[image.imgYSize - yLoc * image.imgYSize,
                                 (xLoc-image.xOff)*image.imgXSize/image.aspect + image.xOff][0]
                            
        boroIndx = int(image.burrIndx[image.imgYSize - yLoc * image.imgYSize,
                                  (xLoc-image.xOff)*image.imgXSize/image.aspect + image.xOff])
        if boroIndx > 0:
            boroIndx -= 1
        #print 'agent %3d loc (%4.2f, %4.2f) boroIndex %3d'%(agtId, xLoc, yLoc, boroIndx)
        #print 'boro[boroindx] = %s'%agencies.boroughsList[boroIndx-1]
        boroName = agencies.boroughsList[boroIndx-1]
        
        
        if doingLogging:
            writelog.write("  agtId: % 3d  xLoc, yLoc = (%4.2f, %4.2f) boro %s boroIndx = %3d\n"%(
                        agtId, xLoc, yLoc, boroName, boroIndx))
        
        # if inMask > .5 and boroIndx in range(1,6):  # If in the masked area check for collision
        if inMask > .9:  # If in the masked area check for collision
            if doingLogging:
                writelog.write('  In boroIndx %3d\n'%boroIndx)
            collision = False
            for agt in range(len(agents)):
                xLoc1 = agents[agt]['xLoc']
                yLoc1 = agents[agt]['yLoc']
                dx = xLoc1 - xLoc
                dy = yLoc1 - yLoc
                dist = np.sqrt(dx**2 + dy**2)
                if dist < minSep:
                    collision = True
                    if doingLogging:
                        writelog.write("  COLLISION !!!\n")
                    break   # Stop going through more agents
            if not collision:
                foundSpace = True
                if doingLogging:
                    writelog.write("  foundSpace!\n")
                    writelog.write("  agtId: % 3d  xLoc, yLoc = (%4.2f, %4.2f) boro %s boroIndx = %3d\n"%(
                                agtId, xLoc, yLoc, boroName, boroIndx))
                # Otherwise keep searching

        
    # Define agent's race and ethnicity
    (income, age, sex, race, ethncy) = probDemographics(boroIndx)
    #print 'boroIndx = %d, income = %s, age = %s, sex = %s, race = %s, ethncy = %s'%(boroIndx, income, age, sex, race, ethncy)
    #(race, ethncy) = probRaceEthncy(boroIndx)
    if race == 'White':
        #raceColor = 'w'
        isWhite = 1.
        isBlack = 0.
        isOther = 0.
        nAgentsWht += 1
    elif race == 'Black':
        #raceColor = 'k'
        isWhite = 0.
        isBlack = 1.
        isOther = 0.
        nAgentsBlk += 1
    elif race == 'Other':
        #raceColor = 'gray'
        isWhite = 0.
        isBlack = 0.
        isOther = 1.
        nAgentsOth += 1
        
    if ethncy == 'Hispanic':
        #ethVis = True
        isHisp = 1.
    else:
        #ethVis = False
        isHisp = 0.
    
    # Define agent's gender
    if sex == 'Female':
        gender = 'Female'
        isFemale = 1.
        isMale = 0.
    else:
        gender = 'Male'
        isMale = 1.
        isFemale = 0.
        
    # Define agent's age
    if age == 'Old':
        isOld = 1.
        isYoung = 0.
    else:
        isOld = 0.
        isYoung = 1.
        
    # Define agent's hadPrior (PTSD)
    if random() > .9:
        hadPrior = 1.
    else:
        hadPrior = 0.

    # Define agent's hadStressors (from Hurricane Sandy)
    if random() > .9:
        hadStressors = 1.
    else:
        hadStressors = 0.

    # Define agent's hadTrauma (from Hurricane Sandy)
    if random() > .9:
        hadTrauma = 1.
    else:
        hadTrauma = 0.

    # Additional coefficients for calculate_nSymptoms()
    isWhiteHisp    = 0.
    isBlackNonHisp = 0.
    isBlackHisp    = 0.
    isOtherNonHisp = 0.
    isOtherHisp    = 0.
    if race == 'White' and ethncy == 'Hispanic':
        isWhiteHisp = 1.
    elif race == 'Black':
        if ethncy == 'NonHisp':
            isBlackNonHisp = 1.
        elif ethncy == 'Hisp':
            isBlackHisp = 1.
    elif race == 'Other':
        if ethncy == 'NonHisp':
            isOtherNonHisp = 1.
        elif ethncy == 'Hisp':
            isOtherHisp = 1.
    if income == 'Low':
        isIncomeLow = 1.
        isIncomeMed = 0.
    elif income == 'Medium':
        isIncomeLow = 0.
        isIncomeMed = 1.
    elif income == 'High':
        isIncomeLow = 0.
        isIncomeMed = 0.
        
    # Define agent's number of PTSD symptoms
    nSymptoms = calculate_nSymptoms(isFemale, isYoung, isOld, isWhiteHisp, 
                        isBlackNonHisp, isBlackHisp, isOtherNonHisp, 
                        isOtherHisp, isIncomeLow, isIncomeMed,
                        hadStressors, hadTrauma)
                        
    # Calculate random value
    randVal = random()
    
    #print '    randVal: %5.2f nSymptoms: %5.2f'%(randVal, nSymptoms)

    # Define agent's "input value" (natural wellness) and input factor
    if useCalcNSymptoms:
        iVal = (1. - nSymptoms) ** boost #<===KLUDGE! 
        if doingLogging:
            writelog.write('  iVal = nSymptoms = %f\n'%iVal)
    else:
        iVal = randVal
        if doingLogging:
            writelog.write('  iVal = random() = %f\n'%iVal)
            
    print '  agent(%3d) iVal: %5.2f nSymptoms: %5.2f'%(agtId, randVal, nSymptoms)

    if iVal > iThresh:
        iFact = 1.
        isComplex = False
        cmplxColor = 'k'
    else:
        if random() > .5:
            iFact = 1.
            isComplex = False
            cmplxColor = 'k'
        else:
            iFact = 0.7
            isComplex = True
            cmplxColor = 'r'
            

    # Define agent's probability of accepting CBT if offered CBT
    acceptCBT = calculate_probAcceptCBT(isMale, isOld, isBlack, isWhite, 
                                        isOther, isHisp, hadPrior)


            

    # Set xVal to equilibrium value
    xVal = iVal/(A+iVal)
    # totInput += iVal
    r = (1. - xVal)
    g = xVal

    # Define agent's triple circle
    circle1 = plt.Circle((xLoc, yLoc), circRad1, fc=(r,g,0),
                         ec=cmplxColor)

    if xVal > visThresh:
        circle1.set_visible(False)
    else:
        circle1.set_visible(True)
    axes.ax.add_patch(circle1)
     
    # Define agent's bezier links
    bezPatch = None
    '''
    for agcy in agencies.agenciesList[agencies.boroughsList[boroIndx-1]]:
        (provXCtr, provYCtr) = agcy['loc']
        
         # Define agent's bezier links to that agency
        verts = ((provXCtr, provYCtr), # Bezier lnk from prov. to here
                 ((provXCtr + xLoc)/2., provYCtr),
                 (xLoc, (provYCtr + yLoc)/2.),
                 (xLoc, yLoc))
        bezPath = Path(verts, codes)
        bezPatch = mpatches.PathPatch(bezPath, facecolor='none',
                                  lw=1, ec='#afafaf', visible=True)
        axes.ax.add_patch(bezPatch)
        bezList.append(bezPatch)
    '''
                          
                              
    # Agent ID number below circle
    idText = axes.ax.text(xLoc-.004, yLoc-.021, '%d'%agtId, visible=False)
    
    newAgent =    {'id':agtId,
                   'circ1':circle1,
                   'boroName':boroName,
                   'boroIndx':boroIndx,
                   'bezPatch':bezPatch,
                   'xLoc':xLoc,
                   'yLoc':yLoc,
                   'xVal':xVal,
                   'iVal':iVal,
                   'iFact':iFact,
                   'isComplex':isComplex,
                   'gender':gender,
                   'race':race,
                   'ethncy':ethncy,
                   'acceptCBT':acceptCBT,
                   'nSymptoms':nSymptoms,
                   'treating':False,
                   'enrolled':False,
                   'agency':None,
                   'treatNo':0,        # current treatment #
                   'idText':idText}
    return newAgent
Esempio n. 10
0
def update_agent(agent):

    global nEnrolled, schedList, schedPtr, tileListPtr, avgInput

    # print '  In update_agent agent = %d'%agent['id']
    # writelog.write('In update_agent agent = %d\n'%agent['id'])

    xVal = agent['xVal']
    inputVal = agent['iVal']

    # If service is on, service the agents
    if axes.checkService:
        square.set_fc('#00ff00')

        # If not scheduled for treatment consider enrolling
        if not agent['enrolled']:
            need = max((avgInput - xVal),0.)
            # writelog.write('  not enrolled avgInput= %5.2f xVal= %5.2f need=%5.2f\n'%
            #                     (avgInput, xVal, need))

            # Calculate probability of enrollment based on need (and distance from provider)
            if axes.checkDist:
                distProvX, distProvY = (agent['xLoc'] - axes.provXOrg,
                                        agent['yLoc'] - axes.provYOrg)
                distProv = np.sqrt(distProvX**2 + distProvY**2)
                gauss = (1./rSigma*np.sqrt(2.*np.pi)) * \
                        np.exp(-(distProv**2.)/(2.*rSigma**2))
                probEnroll = need * (maxEnrolled - nEnrolled) * gauss
            else:
                probEnroll = need * (maxEnrolled - nEnrolled)
                
            # writelog.write('  need = %f probEnroll = %5.2f\n'%(need,probEnroll))

            # If enroll probability exceeds random threshold then enroll
            if probEnroll > random():
                # writelog.write('  probEnroll > random\n')
                agent['enrolled'] = True
                nEnrolled += 1
                # agent['nSched'] = standardSched
                agent['bezPatch'].set_visible(True)
                inputVal = agent['iVal']
                agent['idText'].set_visible(True)

                # Register in schedList[]
                # writelog.write('About to enroll\n')
                if doingLogging:
                    writelog.write('Enrolling agent %d\n'% agent['id'])
                treatList = [None for i in range(standardSched)]
                treatList[agent['treatNo']] = agent['xVal']
                treatList.insert(0, agent['isComplex'])
                treatList.insert(0,agent['id'])
                schedList.append(treatList)
                
                # update schedule
                updateSched(schedList)
                if doingLogging:
                    printSched()

        # Otherwise if already enrolled compute input treatment
        else:
            if random() > .25: # Randomize every other time to break sync

                # If agent not being treated do next treatment
                if agent['treating'] == False:
                    if doingLogging:
                        writelog.write('  agent %d treatment %d ON\n'%(agent['id'], 
                                                                          agent['treatNo']))
                    agent['treating'] = True
                    agent['bezPatch'].set_lw(2)
                    agent['bezPatch'].set_ec('#00ff00')

                    # Turn on input
                    if axes.checkEndBen:
                        agent['iVal'] += doseValue*agent['iFact']/10. # endBen increase iVal
                    else:
                        inputVal = agent['iVal'] + doseValue  * agent['iFact']
                        
                    # Increment treatment number
                    agent['treatNo'] += 1
 
                    if axes.checkStepped and agent['isComplex']:
                        nTreatLeft = standardSched + 1
                    else:
                        nTreatLeft = steppedSched+1
                    if agent['treatNo'] >= nTreatLeft:
                        if axes.checkStepped and agent['isComplex']:
                            writelog.write('  treatNo = %d standardSched = %d\n'%
                                         (agent['treatNo'], standardSched))
                        else:
                            writelog.write('  treatNo = %d steppedSched = %d\n'%
                                         (agent['treatNo'], steppedSched))
                        if doingLogging: writelog.write('Un-enroll agent %d treatment done\n'% 
                                                            agent['id'])
                        agent['enrolled'] = False
                        agent['treatNo'] = 0
                        # agent['treating'] = False
                        nEnrolled -= 1
                        agent['bezPatch'].set_lw(1)
                        agent['bezPatch'].set_visible(False)
                        agent['idText'].set_visible(False)
                        for entry in schedList:
                            if entry[0] == int(agent['id']):
                                schedList.remove(entry)
                                break
                    else:
                        for indx, sched in enumerate(schedList):
                            if sched[0] == int(agent['id']):
                                schedList[indx][agent['treatNo']+1] = agent['xVal']
                                break
                        if doingLogging: writelog.write('  agent %d treatment %d ON\n'%
                                           (agent['id'], agent['treatNo']+1))

                    # Update schedule
                    updateSched(schedList)
                    if doingLogging:
                        printSched()

                # Otherwise if patient being treated turn it off
                else:
                    agent['treating'] = False;
                    agent['bezPatch'].set_lw(1)
                    agent['bezPatch'].set_ec('#afafaf')
                    inputVal = agent['iVal']

                    if doingLogging: writelog.write('  agent %d treatment %d OFF\n'%
                                        (agent['id'], agent['treatNo']))

                        # schedList = [x for x in schedList if x[0] != agent['id']]


    # Else if service is off, shut off treatment
    else:
        agent['bezPatch'].set_visible(False)
        square.set_fc('#ffffff')
        inputVal = agent['iVal'] * agent['iFact']


    # Shunting equation
    xVal += -A * xVal + (1 - xVal) * inputVal
    if xVal < 0.:
        xVal = 0.
    elif xVal > 1.:
        xVal = 1.
    agent['xVal'] = xVal
    r = (1. - xVal)
    g = xVal
    agent['circ1'].set_facecolor((r, g, 0.))

    # Time delay
    if delay > 0.:
        time.sleep(delay)
Esempio n. 11
0
def init_agents():
    
    global agents, nAgents, square, circle, avgInput, \
            nAgentsWht, nAgentsBlk, nAgentsOth
    
    totInput = 0.
    agentId = 0
    
    ## for each agent
    for agtId in range(nAgents):
        writelog.write("agtId = %d\n"%agtId)
        foundSpace = False
        while not foundSpace:
            xLoc = random() * image.aspect + .1*image.aspect
            yLoc = random()
            writelog.write("agtId: % 3d  xLoc, yLoc = (%4.2f, %4.2f)\n"%(agtId, xLoc, yLoc))
            
            inMask  = image.maskImg[image.imgYSize - yLoc * image.imgYSize,
                                     (xLoc-image.xOff)*image.imgXSize/image.aspect + image.xOff][0]
                                
            borough = image.burrIndx[image.imgYSize - yLoc * image.imgYSize,
                                      (xLoc-image.xOff)*image.imgXSize/image.aspect + image.xOff]
            borough -= 1  #<=== KLUDGE! (Don't know why this is necessary)
            writelog.write("agtId: % 3d  xLoc, yLoc = (%4.2f, %4.2f) borough = %3d\n"%(
                            agtId, xLoc, yLoc, borough))
            
            # if inMask > .5 and borough in range(1,6):  # If in the masked area check for collision
            if inMask > .9:  # If in the masked area check for collision
                writelog.write('  In borough %3d\n'%borough)
                collision = False
                for agt in range(len(agents)):
                    xLoc1 = agents[agt]['xLoc']
                    yLoc1 = agents[agt]['yLoc']
                    dx = xLoc1 - xLoc
                    dy = yLoc1 - yLoc
                    dist = np.sqrt(dx**2 + dy**2)
                    if dist < minSep:
                        collision = True
                        writelog.write("  COLLISION !!!\n")
                        break   # Stop going through more agents
                if not collision:
                    foundSpace = True
                    writelog.write("agtId: % 3d  xLoc, yLoc = (%4.2f, %4.2f) borough = %3d\n"%(
                                    agtId, xLoc, yLoc, borough))
                    writelog.write("  foundSpace!\n")
                    # Otherwise keep searching
    
    
        # Define agent's "input value" (natural wellness) and input factor
        iVal = random()
        if iVal > iThresh:
            iFact = 1.
            isComplex = False
            cmplxColor = 'k'
        else:
            if random() > .5:
                iFact = 1.
                isComplex = False
                cmplxColor = 'k'
            else:
                iFact = 0.7
                isComplex = True
                cmplxColor = 'r'
                

        # Set xVal to equilibrium value
        xVal = iVal/(A+iVal)
        totInput += iVal
        r = (1. - xVal)
        g = xVal
        
        # Define agent's race and ethnicity
        (race, ethncy) = probRaceEthncy(borough)
        if race == 'White':
            raceColor = 'w'
            nAgentsWht += 1
        elif race == 'Black':
            raceColor = 'k'
            nAgentsBlk += 1
        elif race == 'Other':
            raceColor = 'gray'
            nAgentsOth += 1
            
        ethVis = ethncy == 'Hispanic'

        # Define agent's triple circle & wedge
        
        circle1 = plt.Circle((xLoc, yLoc), circRad1, fc=(r,g,0),
                             ec=(r,g,0))
        circle2 = plt.Circle((xLoc, yLoc), circRad2, fc=cmplxColor,
                             ec=cmplxColor)
        circle3 = plt.Circle((xLoc, yLoc), circRad3, fc=raceColor,
                             ec=raceColor)
        wedge   = mpatches.Wedge((xLoc, yLoc), circRad3, 180, 0,
                                 fc='brown', ec='brown', visible=ethVis)
        axes.ax.add_patch(circle3)
        axes.ax.add_patch(wedge)
        axes.ax.add_patch(circle2)
        axes.ax.add_patch(circle1)
         
        # Define agent's bezier links
        verts = ((axes.provXCtr, axes.provYCtr), # Bezier lnk from prov. to here
                 ((axes.provXCtr + xLoc)/2., axes.provYCtr),
                 (xLoc, (axes.provYCtr + yLoc)/2.),
                 (xLoc, yLoc))
        bezPath = Path(verts, codes)
        bezPatch = mpatches.PathPatch(bezPath, facecolor='none',
                                  lw=1, ec='#afafaf', visible=False)
    
        # Agent ID number below circle
        idText = axes.ax.text(xLoc-.004, yLoc-.021, '%d'%agtId, visible=False)
        # idText = axes.ax.text(xLoc-.004, yLoc-.021, '%d'%borough, visible=True)
        # idText = axes.ax.text(xLoc-.004, yLoc-.021, '%5.2f'%inMask, visible=True)
    
        # Append to agents list
        agents.append({'id':agtId,
                       'circ1':circle1,
                       'circ2':circle2,
                       'circ3':circle3,
                       'wedge':wedge,
                       'bezPatch':bezPatch,
                       'xLoc':xLoc,
                       'yLoc':yLoc,
                       'xVal':xVal,
                       'iVal':iVal,
                       'iFact':iFact,
                       'isComplex':isComplex,
                       'race':race,
                       'ethncy':ethncy,
                       'treating':False,
                       'enrolled':False,
                       'treatNo':0,        # current treatment #
                       'idText':idText})
        axes.ax.add_patch(bezPatch)
        bezLines.append(bezPatch)
        agentId += 1
    
    
    
    avgInput = totInput/float(nAgents)
    
    # Service provider square and 2 sigma range
    square = plt.Rectangle((axes.provXOrg, axes.provYOrg),
                           axes.provSize, axes.provSize, fc=(0,1,0), ec='k')
    axes.ax.add_patch(square)
    
    # Dist feature sigma radius dashed circle
    circle = plt.Circle((axes.provXOrg, axes.provYOrg), radius=rSigma, ec='r',
                        fc='none', linestyle='dashed', visible=axes.checkDist)
    axes.ax.add_patch(circle)
Esempio n. 12
0
dt = 10
dArray = deque([0.])
tArray = deque([0.])
plotWidth = 500
isMale = 0
isOld = 1
isBlack = 0.
race = 'white'
ethn = 'hispanic'
# income = 'lowrange'
hadPrior = 0
logitCBT = 0
probCBT  = 0

writelog.init('PTSD_Logistic.log')
writelog.write('sex \t age \t race \t ethn \t\t nPrior \t logitCBT \t\t probCBT \n')
writelog.write('=== \t === \t ==== \t ==== \t\t ====== \t ======   \t\t ======= \n\n')

plt.close('all')
fig = plt.figure(figsize=(12,6))
fig.canvas.set_window_title('PTSD_LogisticCombo.py')

# Create axes boxes in a linspace xorg line
xorg = np.linspace(.05,.9,5)
axSex    = plt.axes([xorg[0],.6,.08,.2]); axSex.set_title('Sex')
axAge    = plt.axes([xorg[1],.6,.08,.2]); axAge.set_title('Age')
axRace   = plt.axes([xorg[2],.6,.08,.2]); axRace.set_title('Race')
axEthn   = plt.axes([xorg[3],.6,.08,.2]); axEthn.set_title('Ethn')
# axIncome = plt.axes([xorg[4],.6,.08,.2]); axIncome.set_title('Income')
# axStress = plt.axes([xorg[5],.6,.08,.2]); axStress.set_title('Stress')
# axTrauma = plt.axes([xorg[6],.6,.08,.2]); axTrauma.set_title('Trauma')
Esempio n. 13
0
plotWidth = 500
isMale = 0
isOld = 1
isBlack = 0.
isWhite = 1.
isOther = 0.
race = 'white'
ethn = 'hispanic'
isHisp = 1
# income = 'lowrange'
hadPrior = 0
logitCBT = 0
probCBT = 0

writelog.init('PTSD_Logistic.log')
writelog.write('sex \t age \t race \t ethn \t\t nPrior \t logitCBT \t probCBT \n')
writelog.write('=== \t === \t ==== \t ==== \t\t ====== \t ======   \t ======= \n\n')

plt.close('all')
fig = plt.figure(figsize=(12,6))
fig.canvas.set_window_title('PTSD_LogisticCombo.py')

# Create axes boxes in a linspace xorg line
xorg = np.linspace(.05,.9,5)
axSex    = plt.axes([xorg[0],.6,.08,.2]); axSex.set_title('Sex')
axAge    = plt.axes([xorg[1],.6,.08,.2]); axAge.set_title('Age')
axRace   = plt.axes([xorg[2],.6,.08,.2]); axRace.set_title('Race')
axEthn   = plt.axes([xorg[3],.6,.08,.2]); axEthn.set_title('Ethn')
axPrior  = plt.axes([xorg[4],.6,.08,.2]); axPrior.set_title('Prior CBT')

# Create axes for text output
lastT = 0.
dt = 1
dArray = deque([0.])
tArray = deque([0.])
plotWidth = 500
isFemale = 0
isYoung = 1
race = 'white'
ethn = 'hispanic'
income = 'lowrange'
hadStressors = 0
nSandyTraumas = 0
PTSD_sx = 0

writelog.init('PTSD_Combo.log')
writelog.write('sex \t age \t race \t ethn \t\t income \t hadStr  nSandTr exp(P)\n')
writelog.write('=== \t === \t ==== \t ==== \t\t ====== \t ======  ======= ======\n\n')

plt.close('all')
fig = plt.figure(figsize=(12,6))
fig.canvas.set_window_title('PTSD_Distribution.py')

# Create axes boxes in a linspace xorg line
xorg = np.linspace(.05,.9,7)
axSex    = plt.axes([xorg[0],.6,.08,.2]); axSex.set_title('Sex')
axAge    = plt.axes([xorg[1],.6,.08,.2]); axAge.set_title('Age')
axRace   = plt.axes([xorg[2],.6,.08,.2]); axRace.set_title('Race')
axEthn   = plt.axes([xorg[3],.6,.08,.2]); axEthn.set_title('Ethn')
axIncome = plt.axes([xorg[4],.6,.08,.2]); axIncome.set_title('Income')
axStress = plt.axes([xorg[5],.6,.08,.2]); axStress.set_title('Stress')
axTrauma = plt.axes([xorg[6],.6,.08,.2]); axTrauma.set_title('Trauma')
Esempio n. 15
0
def init_agent(agtId):

    global nEnrolled, schedList, schedPtr, avgInput
    global agents, nAgents, square, circle, avgInput, \
            nAgentsWht, nAgentsBlk, nAgentsOth


    foundSpace = False
    while not foundSpace:
        xLoc = random() * image.aspect + .1*image.aspect
        yLoc = random()
        writelog.write("agtId: % 3d  xLoc, yLoc = (%4.2f, %4.2f)\n"%(agtId, xLoc, yLoc))
        
        inMask  = image.maskImg[image.imgYSize - yLoc * image.imgYSize,
                                 (xLoc-image.xOff)*image.imgXSize/image.aspect + image.xOff][0]
                            
        borough = image.burrIndx[image.imgYSize - yLoc * image.imgYSize,
                                  (xLoc-image.xOff)*image.imgXSize/image.aspect + image.xOff]
        borough -= 1  #<=== KLUDGE! (Don't know why this is necessary)
        writelog.write("agtId: % 3d  xLoc, yLoc = (%4.2f, %4.2f) borough = %3d\n"%(
                        agtId, xLoc, yLoc, borough))
        
        # if inMask > .5 and borough in range(1,6):  # If in the masked area check for collision
        if inMask > .9:  # If in the masked area check for collision
            writelog.write('  In borough %3d\n'%borough)
            collision = False
            for agt in range(len(agents)):
                xLoc1 = agents[agt]['xLoc']
                yLoc1 = agents[agt]['yLoc']
                dx = xLoc1 - xLoc
                dy = yLoc1 - yLoc
                dist = np.sqrt(dx**2 + dy**2)
                if dist < minSep:
                    collision = True
                    writelog.write("  COLLISION !!!\n")
                    break   # Stop going through more agents
            if not collision:
                foundSpace = True
                writelog.write("agtId: % 3d  xLoc, yLoc = (%4.2f, %4.2f) borough = %3d\n"%(
                                agtId, xLoc, yLoc, borough))
                writelog.write("  foundSpace!\n")
                # Otherwise keep searching

        
    # Define agent's race and ethnicity
    (race, ethncy) = probRaceEthncy(borough)
    if race == 'White':
        raceColor = 'w'
        isWhite = 1.
        isBlack = 0.
        isOther = 0.
        nAgentsWht += 1
    elif race == 'Black':
        raceColor = 'k'
        isWhite = 0.
        isBlack = 1.
        isOther = 0.
        nAgentsBlk += 1
    elif race == 'Other':
        raceColor = 'gray'
        isWhite = 0.
        isBlack = 0.
        isOther = 1.
        nAgentsOth += 1
        
    if ethncy == 'Hispanic':
        ethVis = True
        isHisp = 1.
    else:
        ethVis = False
        isHisp = 0.
    
    # Define agent's gender
    if random() > .5:
        gender = 'Male'
        isMale = 1.
    else:
        gender = 'Female'
        isMale = 0.
        
    # Define agent's age
    if random() > .75:
        isOld = 1.
    else:
        isOld = 0.
        
    # Define agent's hadPrior (PTSD)
    if random() > .9:
        hadPrior = 1.
    else:
        hadPrior = 0.
    
    # Define agent's "input value" (natural wellness) and input factor
    # Using probCBT
    if useProbCBT:
        fstr = '  isMale=%1d isOld=%1d isBlack=%1d isWhite=%1d isOther=%1d '\
               'isHisp=%1d hadPrior=%1d\n'
        writelog.write(fstr%(isMale, isOld, isBlack, isWhite,
                                      isOther, isHisp, hadPrior))
        probCBT = calculate_distribution(isMale, isOld, isBlack, isWhite,
                                      isOther, isHisp, hadPrior)
        iVal = 1. - probCBT
        if iVal > 1:
            iVal = 1.
        elif iVal < 0.:
            iVal = 0.
            
        writelog.write('  calculate_distribution: probCBT = %f iVal = %f\n'%(probCBT,iVal))
    # Or using just random
    else:
        iVal = random()
        writelog.write('  calculate_input: iVal = %f\n'%iVal)
            

    if iVal > iThresh:
        iFact = 1.
        isComplex = False
        cmplxColor = 'k'
    else:
        if random() > .5:
            iFact = 1.
            isComplex = False
            cmplxColor = 'k'
        else:
            iFact = 0.7
            isComplex = True
            cmplxColor = 'r'

    # Set xVal to equilibrium value
    xVal = iVal/(A+iVal)
    # totInput += iVal
    r = (1. - xVal)
    g = xVal

    # Define agent's triple circle & wedge
    circle1 = plt.Circle((xLoc, yLoc), circRad1, fc=(r,g,0),
                         ec=cmplxColor)
    '''
    circle2 = plt.Circle((xLoc, yLoc), circRad2, fc=cmplxColor,
                         ec=cmplxColor)
    circle3 = plt.Circle((xLoc, yLoc), circRad3, fc=raceColor,
                         ec=raceColor)
    wedge   = mpatches.Wedge((xLoc, yLoc), circRad3, 180, 0,
                             fc='brown', ec='brown', visible=ethVis)
    
    axes.ax.add_patch(circle3)
    axes.ax.add_patch(wedge)
    axes.ax.add_patch(circle2)
    '''
    if xVal > visThresh:
        circle1.set_visible(False)
    else:
        circle1.set_visible(True)
    axes.ax.add_patch(circle1)
     
    # Define agent's bezier links
    verts = ((axes.provXCtr, axes.provYCtr), # Bezier lnk from prov. to here
             ((axes.provXCtr + xLoc)/2., axes.provYCtr),
             (xLoc, (axes.provYCtr + yLoc)/2.),
             (xLoc, yLoc))
    bezPath = Path(verts, codes)
    bezPatch = mpatches.PathPatch(bezPath, facecolor='none',
                              lw=1, ec='#afafaf', visible=False)
    axes.ax.add_patch(bezPatch)
                              
    '''
    # Define agent's gender symbol
    if gender == 'Male':
        xData = [xLoc + circRad2, 
                 xLoc + 1.5*circRad2, 
                 xLoc + 1.5*circRad2-circRad2/2,
                 xLoc + 1.5*circRad2, 
                 xLoc + 1.5*circRad2] 
        yData = [yLoc + circRad2, 
                 yLoc + 1.5*circRad2, 
                 yLoc + 1.5*circRad2,
                 yLoc + 1.5*circRad2, 
                 yLoc + 1.5*circRad2-circRad2/2] 
    elif gender == 'Female':
        xData = [xLoc, 
                 xLoc, 
                 xLoc,
                 xLoc - .5*circRad2, 
                 xLoc + .5*circRad2] 
        yData = [yLoc - circRad2, 
                 yLoc - 2*circRad2, 
                 yLoc - 1.5*circRad2,
                 yLoc - 1.5*circRad2, 
                 yLoc - 1.5*circRad2] 
    gendSymb = plt.Line2D(xData, yData, color='k')
    axes.ax.add_line(gendSymb)
    '''

    # Agent ID number below circle
    idText = axes.ax.text(xLoc-.004, yLoc-.021, '%d'%agtId, visible=False)
    
    newAgent =    {'id':agtId,
                   'circ1':circle1,
                   'bezPatch':bezPatch,
                   'xLoc':xLoc,
                   'yLoc':yLoc,
                   'xVal':xVal,
                   'iVal':iVal,
                   'iFact':iFact,
                   'isComplex':isComplex,
                   'gender':gender,
                   'race':race,
                   'ethncy':ethncy,
                   'treating':False,
                   'enrolled':False,
                   'treatNo':0,        # current treatment #
                   'idText':idText}
    return newAgent