<commit_before>#!/usr/users/4/stbrown/bin/python 
# Copyright 2012 University of Pittsburgh
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License.  You may obtain a copy of
# the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# License for the specific language governing permissions and limitations under
# the License.
from SimulatorService_services import runRequest
'''
Created on Nov 27, 2012

This is an example GenericEpidemicModelService implementation.

@author: <NAME>
'''

from ZSI.wstools import logging
from SimulatorService_services_server import SimulatorService
from ZSI.ServiceContainer import AsServer
from ApolloFactory import *
from ApolloUtils import *
from SimulatorService_services import *
import os,sys
import shutil
#import fred
import random
import datetime
import paramiko
from fredUtils import FredSSHConn,infectiousPeriod,incubationPeriod

fredConn = FredSSHConn()

class FredWebService(SimulatorService):
        _wsdl = "".join(open("simulatorservice.wsdl").readlines())
        
        factory = ApolloFactory()
        utils = ApolloUtils()       
        
        def soap_getSupportedLocations(self, ps, **kw):
            response = SimulatorService.soap_getSupportedLocations(self, ps, **kw)
            
            spl = self.factory.new_SupportedPopulationLocation()
            
            spl._populationLocation = "42003"
            spl._populationLocationDescription = "Allegheny County"
            
            response._supportedPopluationLocations.append(spl)
            return response
        
        #this method checks on the status of a job, indicated by the jobs runId
        def soap_getRunStatus(self, ps, **kw):
            response = SimulatorService.soap_getRunStatus(self, ps, **kw)
            #get the run id of the job 
            request = ps.Parse(getRunStatusRequest.typecode)
            runId = request._runId
	    	   	    
            status, message = fredConn._getStatus(runId)
            response._runStatus = self.factory.new_RunStatus()
            print "Fred status is:" + status
            response._runStatus._status = status.lower()
            print "Fred message is:" + message
            response._runStatus._message = message
            
            return response
        
        
        #this method runs an epidemic model
        def soap_run(self, ps, **kw):
	    fredConn._setup()
            response = SimulatorService.soap_run(self, ps, **kw)
            request = ps.Parse(runRequest.typecode)
            #extract the epidemic model input object from the request
            print "received run request"
            cfg = request._simulatorConfiguration
            
            #get the number of time steps in the simulation
            run_length = cfg._simulatorTimeSpecification._runLength
        
            #log the EpidemicModelInput request to a log file
            self.utils.log_simulatorConfiguration(cfg)

            ### STB CREATE FRED INPUT FILE
            ### do some error checking for this version of the model
            if cfg._simulatorTimeSpecification._timeStepUnit.lower() != 'days':
                    print ('This verison of FRED only supports time_step_unit of days')
                    print ('Apollo sent %s'%(cfg._simulatorTimeSpecification._timeStepUnit))
                    #### Put in Error Handling, have to ask <NAME>.
                    
            if cfg._simulatorTimeSpecification._timeStepValue != 1:
                    print ('This version of FRED only supports a time_step_value of 1')
                    print ('Apollo sent %d'%(cfg._simulatorTimeSpecification._timeStepValue))

	    #### Put in Error Handling, have to ask <NAME>.
	    
            #print ('WARNING: This service is currently ignoring infectious_period')
            #print ('WARNING: This service is currently ignoring latent_period')

            ### Make a random directory name so that multiple calls can be made
            randID = random.randint(0,100000)
            tempDirName = "fred.tmp.%d"%(randID)
            try:
                    os.mkdir(tempDirName)
            except:
                    raise RuntimeError("Cannot make temporary FRED directory %s"%(tempDirName))

            os.chdir(tempDirName)
            doVacc = False
            with open('fred_input.params','wb') as f:
                    f.write('days = %d\n'%cfg._simulatorTimeSpecification._runLength)
                    f.write('symp[0] = %g\n'%cfg._disease._asymptomaticInfectionFraction)
                    f.write('R0 = %g\n'%cfg._disease._reproductionNumber)
                    f.write('primary_cases_file[0] = fred_initial_population_0.txt\n')
                    f.write('residual_immunity_ages[0] = 2 0 100\n')
		    f.write('days_latent[0] = %s\n'\
			    %(incubationPeriod(float(cfg._disease._latentPeriod))))
		    f.write('days_incubating[0] = %s\n'\
			    %(incubationPeriod(float(cfg._disease._latentPeriod))))
		    f.write('days_infectious[0] = %s\n'\
			    %(infectiousPeriod(float(cfg._disease._infectiousPeriod))))
		    f.write('days_symptomatic[0] = %s\n'\
			    %(infectiousPeriod(float(cfg._disease._infectiousPeriod))))	     	       
                    totPop = self.utils.getTotalPopCount(cfg)
                    numImmune = self.utils.getPopCountGivenLocationAndDiseaseState(cfg, "ignoreed", "recovered")
                    percent_immune = float(numImmune)/float(totPop)
                    f.write('residual_immunity_values[0] = 1 %g\n'%(percent_immune))
		    f.write('track_infection_events = 1\n')
		    if sum(cfg._vaccinationControlMeasure._vaccineSupplySchedule) > 0.0:
                        doVacc = True
                        #print ('WARNING: This sevice is currently ignoring vaccine_cm_compliance due to someone fucking FRED up')
                        f.write("##### VACCINE PARAMETERS\n")
                        f.write("enable_behaviors = 1\n")
                        f.write("enable_vaccination = 1\n")
                        f.write("number_of_vaccines = 1\n")
			f.write("accept_vaccine_enabled = 1\n")
			f.write("accept_vaccine_strategy_distribution = 7 %g %g 0 0 0 0 0\n"\
				%(1.0-cfg._vaccinationControlMeasure._vaccineCmCompliance,\
				  cfg._vaccinationControlMeasure._vaccineCmCompliance))
                        f.write("### VACCINE 1\n")
                        f.write("vaccine_number_of_doses[0] = 1\n")
                        # Setting this to infinity for now
                        # need to implement production as a time map as well
                        f.write("vaccine_total_avail[0] = 300000000\n")
                        f.write("vaccine_additional_per_day[0] = 300000000\n")
                        f.write("vaccine_starting_day[0] = 0\n")
                        f.write("##### Vaccine 1 Dose 0\n")<commit_msg>Added new Fred parameters that now allow us to control seeding of both exposed and infectious people.  Thanks to <NAME> for implementing this is Fred so quickly.<commit_after>#!/usr/users/4/stbrown/bin/python 
# Copyright 2012 University of Pittsburgh
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License.  You may obtain a copy of
# the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# License for the specific language governing permissions and limitations under
# the License.
from SimulatorService_services import runRequest
'''
Created on Nov 27, 2012

This is an example GenericEpidemicModelService implementation.

@author: <NAME>
'''

from ZSI.wstools import logging
from SimulatorService_services_server import SimulatorService
from ZSI.ServiceContainer import AsServer
from ApolloFactory import *
from ApolloUtils import *
from SimulatorService_services import *
import os,sys
import shutil
#import fred
import random
import datetime
import paramiko
from fredUtils import FredSSHConn,infectiousPeriod,incubationPeriod

fredConn = FredSSHConn()

class FredWebService(SimulatorService):
        _wsdl = "".join(open("simulatorservice.wsdl").readlines())
        
        factory = ApolloFactory()
        utils = ApolloUtils()       
        
        def soap_getSupportedLocations(self, ps, **kw):
            response = SimulatorService.soap_getSupportedLocations(self, ps, **kw)
            
            spl = self.factory.new_SupportedPopulationLocation()
            
            spl._populationLocation = "42003"
            spl._populationLocationDescription = "Allegheny County"
            
            response._supportedPopluationLocations.append(spl)
            return response
        
        #this method checks on the status of a job, indicated by the jobs runId
        def soap_getRunStatus(self, ps, **kw):
            response = SimulatorService.soap_getRunStatus(self, ps, **kw)
            #get the run id of the job 
            request = ps.Parse(getRunStatusRequest.typecode)
            runId = request._runId
	    	   	    
            status, message = fredConn._getStatus(runId)
            response._runStatus = self.factory.new_RunStatus()
            print "Fred status is:" + status
            response._runStatus._status = status.lower()
            print "Fred message is:" + message
            response._runStatus._message = message
            
            return response
        
        
        #this method runs an epidemic model
        def soap_run(self, ps, **kw):
	    fredConn._setup()
            response = SimulatorService.soap_run(self, ps, **kw)
            request = ps.Parse(runRequest.typecode)
            #extract the epidemic model input object from the request
            print "received run request"
            cfg = request._simulatorConfiguration
            
            #get the number of time steps in the simulation
            run_length = cfg._simulatorTimeSpecification._runLength
        
            #log the EpidemicModelInput request to a log file
            self.utils.log_simulatorConfiguration(cfg)

            ### STB CREATE FRED INPUT FILE
            ### do some error checking for this version of the model
            if cfg._simulatorTimeSpecification._timeStepUnit.lower() != 'days':
                    print ('This verison of FRED only supports time_step_unit of days')
                    print ('Apollo sent %s'%(cfg._simulatorTimeSpecification._timeStepUnit))
                    #### Put in Error Handling, have to ask <NAME>.
                    
            if cfg._simulatorTimeSpecification._timeStepValue != 1:
                    print ('This version of FRED only supports a time_step_value of 1')
                    print ('Apollo sent %d'%(cfg._simulatorTimeSpecification._timeStepValue))

	    #### Put in Error Handling, have to ask <NAME>.
	    
            #print ('WARNING: This service is currently ignoring infectious_period')
            #print ('WARNING: This service is currently ignoring latent_period')

            ### Make a random directory name so that multiple calls can be made
            randID = random.randint(0,100000)
            tempDirName = "fred.tmp.%d"%(randID)
            try:
                    os.mkdir(tempDirName)
            except:
                    raise RuntimeError("Cannot make temporary FRED directory %s"%(tempDirName))

            os.chdir(tempDirName)
            doVacc = False
            with open('fred_input.params','wb') as f:
                    f.write('days = %d\n'%cfg._simulatorTimeSpecification._runLength)
                    f.write('symp[0] = %g\n'%cfg._disease._asymptomaticInfectionFraction)
                    f.write('R0 = %g\n'%cfg._disease._reproductionNumber)
                    f.write('primary_cases_file[0] = fred_initial_population_0.txt\n')
                    f.write('residual_immunity_ages[0] = 2 0 100\n')
		    f.write('days_latent[0] = %s\n'\
			    %(incubationPeriod(float(cfg._disease._latentPeriod))))
		    f.write('days_incubating[0] = %s\n'\
			    %(incubationPeriod(float(cfg._disease._latentPeriod))))
		    f.write('days_infectious[0] = %s\n'\
			    %(infectiousPeriod(float(cfg._disease._infectiousPeriod))))
		    f.write('days_symptomatic[0] = %s\n'\
			    %(infectiousPeriod(float(cfg._disease._infectiousPeriod))))	     	       
                    totPop = self.utils.getTotalPopCount(cfg)
                    numImmune = self.utils.getPopCountGivenLocationAndDiseaseState(cfg, "ignoreed", "recovered")
                    percent_immune = float(numImmune)/float(totPop)
                    f.write('residual_immunity_values[0] = 1 %g\n'%(percent_immune))
		    numExposed = float(self.utils.getPopCountGivenLocationAndDiseaseState(cfg,"ignoreed","exposed"))
		    numInfectious = float(self.utils.getPopCountGivenLocationAndDiseaseState(cfg,"ignoreed","infectious"))
		    fractionExposed = numExposed/(numExposed+numInfectious)
		    fractionInfectious = 1.0 - fractionExposed
		    f.write('advanced_seeding = exposed:%1.2f;infectious:%1.2f\n'%(fractionExposed,fractionInfectious))
		    f.write('track_infection_events = 1\n')
		    if sum(cfg._vaccinationControlMeasure._vaccineSupplySchedule) > 0.0:
                        doVacc = True
                        f.write("##### VACCINE PARAMETERS\n")
                        f.write("enable_behaviors = 1\n")
                        f.write("enable_vaccination = 1\n")
                        f.write("number_of_vaccines = 1\n")
			f.write("accept_vaccine_enabled = 1\n")
			f.write("accept_vaccine_strategy_distribution = 7 %g %g 0 0 0 0 0\n"\
				%(1.0-cfg._vaccinationControlMeasure._vaccineCmCompliance,\
				  cfg._vaccinationControlMeasure._vaccineCmCompliance))
                        f.write("### VACCINE 1\n")
                        f.write("vaccine_number_of_doses[0] = 1\n")
                        # Setting this to infinity for now
                        # need to implement production as a time map as well
                        f.write("vaccine_total_avail[0] = 300000000\n")
                        f.write("vaccine_additional_per_day[0] = 300000000\n")
                        f.write("vaccine_starting_day[0] = 0\n")
                        f.write("##### Vaccine 1 Dose 0\n")
{'fraction_non_alphanumeric': 0.09110658520027155, 'fraction_numerical': 0.012219959266802444, 'mean_word_length': 2.2955257270693514, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 4, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3140825', 'n_tokens_mistral': 4354, 'n_tokens_neox': 3885, 'n_words': 1016}