Esempio n. 1
0
def moveSemiRandom(animal, animalList, lattice):
    paraList = parameters()
    forestSize = paraList['forestSize']
    r = random.randint(1, 4)
    x = animal[0]
    y = animal[1]
    if ('prey' in lattice[(x + 1) % forestSize][y]):
        lattice[(x + 1) % forestSize][y].append(animal[2])
        lattice[x][y].remove(animal[2])
        animalList.remove(animal)
        animalList.append([(x + 1) % forestSize, y, animal[2]])
        return lattice, animalList
    if ('prey' in lattice[x][(y + 1) % forestSize]):
        lattice[x][(y + 1) % forestSize].append(animal[2])
        lattice[x][y].remove(animal[2])
        animalList.remove(animal)
        animalList.append([x, (y + 1) % forestSize, animal[2]])
        return lattice, animalList
    if ('prey' in lattice[(x - 1) % forestSize][y]):
        lattice[(x - 1) % forestSize][y].append(animal[2])
        lattice[x][y].remove(animal[2])
        animalList.remove(animal)
        animalList.append([(x - 1) % forestSize, y, animal[2]])
        return lattice, animalList
    if ('prey' in lattice[x][(y - 1) % forestSize]):
        lattice[x][(y - 1) % forestSize].append(animal[2])
        lattice[x][y].remove(animal[2])
        animalList.remove(animal)
        animalList.append([x, (y - 1) % forestSize, animal[2]])
        return lattice, animalList
    if (r == 1):
        lattice[(x + 1) % forestSize][y].append(animal[2])
        lattice[x][y].remove(animal[2])
        animalList.remove(animal)
        animalList.append([(x + 1) % forestSize, y, animal[2]])
        return lattice, animalList
    if (r == 2):
        lattice[x][(y + 1) % forestSize].append(animal[2])
        lattice[x][y].remove(animal[2])
        animalList.remove(animal)
        animalList.append([x, (y + 1) % forestSize, animal[2]])
        return lattice, animalList
    if (r == 3):
        lattice[(x - 1) % forestSize][y].append(animal[2])
        lattice[x][y].remove(animal[2])
        animalList.remove(animal)
        animalList.append([(x - 1) % forestSize, y, animal[2]])
        return lattice, animalList
    if (r == 4):
        lattice[x][(y - 1) % forestSize].append(animal[2])
        lattice[x][y].remove(animal[2])
        animalList.remove(animal)
        animalList.append([x, (y - 1) % forestSize, animal[2]])
        return lattice, animalList
    return lattice, animalList
Esempio n. 2
0
def moveRandom(animal, animalList, lattice):
    paraList = parameters()
    forestSize = paraList['forestSize']
    preyPara = preyParameters()
    speed = preyPara['speed']
    r = random.randint(1, 4)
    x = animal[0]
    y = animal[1]

    dx = random.randint(-speed, speed)
    dy = random.randint(-speed, speed)
    lattice[(x + dx) % forestSize][(y + dy) % forestSize].append(animal[2])
    lattice[x][y].remove(animal[2])
    animalList.remove(animal)
    animalList.append([(x + dx) % forestSize, (y + dy) % forestSize,
                       animal[2]])
    return lattice, animalList
Esempio n. 3
0
def Get_median_finSeeing(observations):

    res = []
    params = parameters()
    for obs in observations:
        filtre = obs['filter'][0]
        seeing = obs['rawSeeing']
        airmass = obs['airmass']
        Filter_Wavelength_Correction = np.power(
            500.0 / params.filterWave[filtre], 0.3)
        Airmass_Correction = math.pow(obs['airmass'], 0.6)
        FWHM_Sys = params.FWHM_Sys_Zenith * Airmass_Correction
        FWHM_Atm = seeing * Filter_Wavelength_Correction * Airmass_Correction
        finSeeing = params.scaleToNeff * math.sqrt(
            np.power(FWHM_Sys, 2) +
            params.atmNeffFactor * np.power(FWHM_Atm, 2))
        res.append(finSeeing)
    return np.median(res)
Esempio n. 4
0
def movePredator(animal, animalList, lattice, densities):
    paraList = parameters()
    forestSize = paraList['forestSize']
    predPara = predatorParameters()
    speed = predPara['speed']
    pounceRange = predPara['pounceRange']
    prob = np.array(densities)
    prob = prob + 1
    prob = prob / sum(prob)
    x = animal[0]
    y = animal[1]

    count = 0
    idx = []
    xmin = (x - pounceRange)
    xmax = (x + pounceRange + 1)
    ymin = (y - pounceRange)
    ymax = (y + pounceRange + 1)
    for i in range(xmin, xmax):
        for j in range(ymin, ymax):
            if 'prey' in lattice[i % forestSize][j % forestSize]:
                count += 1
                idx.append([i % forestSize, j % forestSize])
    if count:
        r = random.randint(0, count - 1)
        lattice[idx[r][0]][idx[r][1]].append(animal[2])
        lattice[x][y].remove(animal[2])
        animalList.remove(animal)
        animalList.append([idx[r][0], idx[r][1], animal[2]])
        return lattice, animalList

    xdir = np.sign(prob[1] - prob[3] + (2 * random.random() - 1))
    dx = int(random.randint(0, speed) * xdir)
    ydir = np.sign(prob[0] - prob[2] + (2 * random.random() - 1))
    dy = int(random.randint(0, speed) * ydir)
    lattice[(x + dx) % forestSize][(y + dy) % forestSize].append(animal[2])
    lattice[x][y].remove(animal[2])
    animalList.remove(animal)
    animalList.append([(x + dx) % forestSize, (y + dy) % forestSize,
                       animal[2]])
    return lattice, animalList
Esempio n. 5
0
    def __init__(self, airmass=1., aerosol=False):

        #self.transmission.Load_Atmosphere(airmass)

        self.filters = ['u', 'g', 'r', 'i', 'z', 'y']

        self.paper = {}
        self.paper['mbsky'] = {
            'u': 22.92,
            'g': 22.27,
            'r': 21.20,
            'i': 20.47,
            'z': 19.59,
            'y': 18.63
        }
        self.paper['Tb'] = {
            'u': 0.0379,
            'g': 0.1493,
            'r': 0.1386,
            'i': 0.1198,
            'z': 0.0838,
            'y': 0.0413
        }
        self.paper['Sigmab'] = {
            'u': 0.0574,
            'g': 0.1735,
            'r': 0.1502,
            'i': 0.1272,
            'z': 0.0872,
            'y': 0.0469
        }
        self.paper['Seeing'] = {
            'u': 0.77,
            'g': 0.73,
            'r': 0.70,
            'i': 0.67,
            'z': 0.65,
            'y': 0.63
        }
        self.paper['FWHMeff'] = {
            'u': 0.92,
            'g': 0.87,
            'r': 0.83,
            'i': 0.80,
            'z': 0.78,
            'y': 0.76
        }
        self.paper['Cb'] = {
            'u': 421.4,
            'g': 691.4,
            'r': 952.9,
            'i': 1152,
            'z': 1373,
            'y': 1511
        }
        self.paper['Skyb'] = {
            'u': 85.07,
            'g': 467.9,
            'r': 1085.2,
            'i': 1800.3,
            'z': 2775.7,
            'y': 3613.4
        }
        self.paper['mb_Z'] = {
            'u': 27.09,
            'g': 28.58,
            'r': 28.50,
            'i': 28.34,
            'z': 27.95,
            'y': 27.18
        }
        self.paper['counts_mb_Z'] = {
            'u': 1.0,
            'g': 1.0,
            'r': 1.0,
            'i': 1.0,
            'z': 1.0,
            'y': 1.0
        }
        self.paper['fiveSigmaDepth'] = {
            'u': 24.22,
            'g': 25.17,
            'r': 24.74,
            'i': 24.38,
            'z': 23.80,
            'y': 22.93
        }
        self.SMTN_paper = {}
        self.SMTN_paper['fiveSigmaDepth'] = {
            'u': 23.60,
            'g': 24.83,
            'r': 24.38,
            'i': 23.92,
            'z': 23.35,
            'y': 22.44
        }

        self.params = parameters()
        transmission_git = Throughputs(aerosol=aerosol)
        transmission_lse40 = Throughputs(through_dir='NEW_THROUGH',
                                         atmos_dir='NEW_THROUGH',
                                         aerosol=aerosol)
        self.airmass = airmass
        transmission_git.Load_Atmosphere(self.airmass)
        transmission_lse40.Load_Atmosphere(self.airmass)

        self.throughput_git = {}
        self.throughput_lse40 = {}
        self.OpSim = {}
        self.OpSim['fiveSigmaDepth'] = {}

        for key in self.paper.keys():
            self.throughput_git[key] = {}
            self.throughput_lse40[key] = {}
            for filtre in self.filters:
                self.throughput_git[key][filtre] = {}
                self.throughput_lse40[key][filtre] = {}

        self.Calc_Inputs(transmission_git, self.throughput_git)
        self.Calc_Inputs(transmission_lse40, self.throughput_lse40)
        self.Calc_Sky(self.paper, self.throughput_lse40, transmission_lse40)
        self.Calc_Sky(self.paper, self.throughput_git, transmission_git)
        self.Calc_m5_OpSim(self.throughput_git)
Esempio n. 6
0
    def __init__(self,
                 metricName='AnaMetric',
                 mjdCol='expMJD',
                 filterCol='filter',
                 m5Col='fiveSigmaDepth',
                 units='',
                 badval=-666,
                 uniqueBlocks=False,
                 zmin=0.01,
                 zmax=0.5,
                 Nevts=10,
                 model='salt2-extended',
                 version='1.0',
                 fieldname='DD',
                 fieldID=290,
                 opsimrun='minion_1016',
                 snrate='Flat',
                 runtype='Simulation',
                 season=-1,
                 sntype='Ia',
                 nrolling=3,
                 percent_merge=80,
                 **kwargs):
        """
        
        Tmin = the minimum day to consider the SN.
        Tmax = the maximum to consider.
        Nbetween = the number of observations to demand between Tmin and Tmax
        Nfilt = number of unique filters that must observe the SN above the snrCut
        Tless = minimum time to consider 'near peak'
        Tmore = max time to consider 'near peak'
        Nless = number of observations to demand before Tless
        Nmore = number of observations to demand after Tmore
        peakGap = maximum gap alowed between observations in the 'near peak' time
        snrCut = require snr above this limit when counting Nfilt XXX-not yet implemented
        singleDepthLimit = require observations in Nfilt different filters to be this
        deep near the peak.  This is a rough approximation for the Science Book
        requirements for a SNR cut.  Ideally, one would import a time-variable SN SED,
        redshift it, and make filter-keyed dictionary of interpolation objects so the
        magnitude of the SN could be calculated at each observation and then use the m5col
        to compute a SNR.
        resolution = time step (days) to consider when calculating observing windows
        uniqueBlocks = should the code count the number of unique sequences that meet
        the requirements (True), or should all sequences that meet the conditions
        be counted (False).

        The filter centers are shifted to the SN restframe and only observations
        with filters between 300 < lam_rest < 900 nm are included

        In the science book, the metric demands Nfilt observations above a SNR cut.
        Here, we demand Nfilt observations near the peak with a given singleDepthLimt.
        """
        self.mjdCol = mjdCol
        self.m5Col = m5Col
        self.filterCol = filterCol
        self.dateCol = 'expDate'
        self.fieldRA = 'fieldRA'
        self.fieldDec = 'fieldDec'
        self.fieldID = 'fieldID'
        self.ditheredRA = 'ditheredRA'
        self.ditheredDec = 'ditheredDec'
        self.visitTime = 'visitExpTime'
        self.finSeeing = 'finSeeing'
        self.rawSeeing = 'rawSeeing'
        self.moonPhase = 'moonPhase'
        self.airmass = 'airmass'
        self.filtSkyBrightness = 'filtSkyBrightness'

        self.zmin = zmin
        self.zmax = zmax
        self.Nevts = Nevts
        self.snrate = snrate
        self.model = model
        self.version = version
        self.fieldName = fieldname
        self.fieldID_ref = int(fieldID)
        self.outputdir = 'Sim_' + opsimrun
        self.runtype = runtype
        self.season = season
        self.sntype = sntype

        self.nrolling = nrolling
        self.percent_merge = percent_merge

        self.time_begin = time.time()
        if not os.path.exists(self.outputdir):
            os.makedirs(self.outputdir)

        #super(AnaMetric, self).__init__(col=[self.mjdCol, self.m5Col, self.filterCol, self.dateCol,self.fieldRA,self.fieldDec, self.ditheredRA,self.ditheredDec,self.visitTime,self.finSeeing,self.rawSeeing,self.moonPhase,self.airmass,self.filtSkyBrightness,self.fieldID],
        super(AnaMetric, self).__init__(col=[
            self.mjdCol, self.m5Col, self.filterCol, self.dateCol,
            self.fieldRA, self.fieldDec, self.ditheredRA, self.ditheredDec,
            self.visitTime, self.rawSeeing, self.moonPhase, self.airmass,
            self.filtSkyBrightness, self.fieldID
        ],
                                        metricName=metricName,
                                        units=units,
                                        badval=badval,
                                        **kwargs)

        self.uniqueBlocks = uniqueBlocks
        self.filterNames = np.array(['u', 'g', 'r', 'i', 'z', 'y'])
        # Set rough values for the filter effective wavelengths.
        self.singleDepthLimit = -1

        self.params = parameters()
Esempio n. 7
0
    #moon_frac:
    #sky:
    #kAtm:
    #airmass:
    #m5sigmadepth_mean:
    #m5sigmadepth_recalc:
    #Nexp:
    legend = '#band #mjd #exptime #seeing #moon_frac #sky #kAtm #airmass #FWHMgeom #FWHMeff #m5sigmadepth #Nexp'

    todisplay = [
        'filter', 'expMJD', 'expTime', 'rawSeeing', 'moonPhase',
        'filtSkyBrightness', 'airmass', 'FWHMgeom', 'FWHMeff'
    ]

    toprocess = thedict[0]['dataSlice']
    params = parameters()
    print legend

    outputfile = open(
        prefix + '_' + opts.fieldname + '_' + str(opts.fieldid) + addit +
        '.txt', 'wb')
    outputfile.write(legend + '\n')
    for band in bands:
        coadd = Get_coadd(toprocess[np.where(toprocess['filter'] == band)])
        #print 'ee',band,len(coadd)
        for key, val in coadd.items():
            filtre = val['filter'][0][0]
            toprint = 'LSST::' + filtre + ' '
            toprint += str(format(np.mean(val['expMJD']), '.7f')) + ' '
            toprint += str(int(np.sum(val['visitExpTime']))) + ' '
            toprint += str(format(np.mean(Get_mean_finSeeing(val)),
Esempio n. 8
0
    def __init__(self,
                 T0,
                 c,
                 x1,
                 z,
                 observations,
                 model='salt2-extended',
                 version='1.0',
                 sn_type='Ia',
                 ra=0.,
                 dec=0.,
                 syste=False):

        self.T0 = T0
        self.c = c
        self.x1 = x1
        self.z = z
        self.obs = observations
        self.model = model
        self.version = version
        self.sn_type = sn_type
        self.mbsim = -1.
        self.ra_field = ra
        self.dec_field = dec
        self.params = parameters()
        self.filterNames = ['u', 'g', 'r', 'i', 'z', 'y']
        self.syste = syste

        #This will be the data for sncosmo fitting
        self.table_for_fit = {}
        self.table_for_fit['error_coadd_opsim'] = Table(
            names=('time', 'flux', 'fluxerr', 'band', 'zp', 'zpsys'),
            dtype=('f8', 'f8', 'f8', 'S7', 'f4', 'S4'))
        self.table_for_fit['error_coadd_through'] = Table(
            names=('time', 'flux', 'fluxerr', 'band', 'zp', 'zpsys'),
            dtype=('f8', 'f8', 'f8', 'S7', 'f4', 'S4'))
        self.table_LC = Table(
            names=('filter', 'expMJD', 'visitExpTime', 'FWHMeff', 'moon_frac',
                   'filtSkyBrightness', 'kAtm', 'airmass', 'fiveSigmaDepth',
                   'Nexp', 'e_per_sec', 'e_per_sec_err'),
            dtype=('S7', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'i8', 'f8', 'f8',
                   'f8', 'f8'))

        if syste:
            vars_a = [
                'filter', 'expMJD', 'visitExpTime', 'FWHMeff', 'moon_frac',
                'filtSkyBrightness', 'kAtm', 'airmass', 'fiveSigmaDepth',
                'Nexp', 'e_per_sec', 'e_per_sec_err', 'mag', 'err_mag',
                'fiveSigmaThrough'
            ]
            dtype_a = [
                'S7', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'i8', 'f8', 'f8',
                'f8', 'f8', 'f8', 'f8', 'f8'
            ]

            for i in range(1, 6, 1):
                vars_a.append('err_mag_plus_' + str(i))
                vars_a.append('err_mag_minus_' + str(i))
                vars_a.append('fiveSigmaThrough_plus_' + str(i))
                vars_a.append('fiveSigmaThrough_minus_' + str(i))
                dtype_a.append('f8')
                dtype_a.append('f8')
                dtype_a.append('f8')
                dtype_a.append('f8')

            vars_a.append('z')
            dtype_a.append('f8')

            self.table_LC_syste = Table(names=tuple(vars_a),
                                        dtype=tuple(dtype_a))

        self.transmission = Throughputs()

        # Register LSST band pass (system) in sncosmo

        for filtre in self.filterNames:
            band = sncosmo.Bandpass(
                self.transmission.lsst_system[filtre].wavelen,
                self.transmission.lsst_system[filtre].sb,
                name='LSST::' + filtre,
                wave_unit=u.nm)
            sncosmo.registry.register(band, force=True)

        print 'hello', self.ra_field, self.dec_field
        self.SN = SN_Object(ra=np.rad2deg(self.ra_field),
                            dec=np.rad2deg(self.dec_field),
                            z=z,
                            t0=T0,
                            c=c,
                            x1=x1,
                            model=self.model,
                            version=self.version,
                            sn_type=self.sn_type)
        if self.SN.sn_type == 'Ia':
            self.mbsim = self.SN.SN._source.peakmag('bessellb', 'vega')

        self.outdict = {}
        self.outdict['t0'] = self.T0
        self.outdict['c'] = self.c
        self.outdict['x1'] = self.x1
        self.outdict['z'] = self.z
        self.outdict['ra'] = self.ra_field
        self.outdict['dec'] = self.dec_field
        self.outdict['status'] = 'unkown'
        self.outdict['fit'] = None
        self.outdict['mbsim'] = -999.
        self.outdict['sn_type'] = self.SN.sn_type
        self.outdict['sn_model'] = self.SN.model
        self.outdict['sn_version'] = self.SN.version
        self.outdict['mbsim'] = self.mbsim

        m_begin_date = self.obs['mjd'].min()
        m_end_date = self.obs['mjd'].max()

        lowrange = -30
        highrange = 50
        timelow = self.T0 + lowrange * (1 + self.z)
        timehigh = self.T0 + highrange * (1 + self.z)

        self.obs.sort('mjd')
        self.obs = self.obs[np.where(
            np.logical_and(self.obs['mjd'] >= timelow,
                           self.obs['mjd'] <= timehigh))]

        self.Simulate_LC()
        """
        for band in self.filterNames:
            sel=self.table_LC[np.where(self.table_LC['filter']==band)]
            print sel
        """
        self.Fit_LCs()
Esempio n. 9
0
def mainSim():
    paraDict = parameters()
    preyPopulationForest = createRandomPrey(paraDict)
    predatorPopulationForest = createRandomPredator(paraDict)
    forest = createLattice(paraDict['forestSize'], preyPopulationForest,
                           predatorPopulationForest)
    preyPop = [paraDict['preyPopulationSize']]
    predPop = [paraDict['predatorPopulationSize']]

    # Plot setup
    '''
    plt.ion()
    fig, ax = plt.subplots()
    x = [prey[0] for prey in preyPopulationForest]
    y = [prey[1] for prey in preyPopulationForest]
    sc1 = ax.scatter(x,y,color = 'blue', s = 1, label = 'plot1')
    x = [predator[0] for predator in predatorPopulationForest]
    y = [predator[1] for predator in predatorPopulationForest]
    sc2 = ax.scatter(x,y,color = 'red', s = 1, label = 'plot2')
    plt.xlim(0,paraDict['forestSize'])
    plt.ylim(0,paraDict['forestSize'])
    plt.title('Forest with predators and prey')
    plt.draw()
    '''
    # Make a random movement for every prey/predator and update plots live
    for t in range(1, paraDict['timeSteps']):
        print(t)
        #if(len(preyPopulationForest) == 0 or len(predatorPopulationForest) == 0):
        #    t = paraDict['timeSteps']
        #    break
        # Change the amount of prey and predators according to the model
        if (np.mod(t, paraDict['timeStepModel']) == 0):
            prob = modelField(len(preyPopulationForest),
                              len(predatorPopulationForest))
            changeInPredatorPop = prob[1] * len(predatorPopulationForest)
            inte = int(np.floor(changeInPredatorPop))
            deci = changeInPredatorPop - inte
            r = random.random()
            if (r < deci):
                inte += 1
            changeInPredatorPop = inte
            changeInPreyPop = prob[0] * len(preyPopulationForest)
            changeInPreyPop = int(np.round(changeInPreyPop, 0))
            forest, predatorPopulationForest = addPredators(
                forest, predatorPopulationForest, changeInPredatorPop)
            forest, preyPopulationForest = addPrey(forest,
                                                   preyPopulationForest,
                                                   changeInPreyPop)
        for prey in preyPopulationForest[:]:
            assert prey[2] in forest[prey[0]][prey[1]]
            forest, preyPopulationForest = moveRandom(prey,
                                                      preyPopulationForest,
                                                      forest)
        for pred in predatorPopulationForest[:]:
            assert pred[2] in forest[pred[0]][pred[1]]
            densities = preyDensity(pred[0], pred[1], forest,
                                    paraDict['visionRange'],
                                    paraDict['forestSize'])
            forest, predatorPopulationForest = movePredator(
                pred, predatorPopulationForest, forest, densities)
        forest, preyPopulationForest = updateLattice(forest,
                                                     preyPopulationForest)

        # Update plot
        '''
        x = [prey[0] for prey in preyPopulationForest]
        y = [prey[1] for prey in preyPopulationForest]
        sc1.set_offsets(np.c_[x,y])
        x = [predator[0] for predator in predatorPopulationForest]
        y = [predator[1] for predator in predatorPopulationForest]
        sc2.set_offsets(np.c_[x,y])
        fig.canvas.draw_idle()
        L = plt.legend(loc = 'upper right')
        L.get_texts()[0].set_text('Prey population size: ' + str(len(preyPopulationForest)))
        L.get_texts()[1].set_text('Predator population size: ' + str(len(predatorPopulationForest)))        
        plt.pause(0.01)
        '''
        preyPop.append(len(preyPopulationForest))
        predPop.append(len(predatorPopulationForest))
    t = [t for t in range(0, len(preyPop))]
    plt.plot(t, preyPop, color='blue', label='Prey population size')
    plt.plot(t, predPop, color='red', label='Predator population size')
    plt.title('Predator/Prey-model, forest simulation')
    plt.legend()
    plt.show()
    print(preyPop[-1])
    print(predPop[-1])