Beispiel #1
0
def complex_eval(expression):
    print expression
    expression = expression.replace(" ", "")
    expression = expression.replace("^", "**")

    for bincomplex in re.findall(constants.get("REGEX_BINOM"), expression):
        print bincomplex
        bincomplex = bincomplex[0]
        bincomplex_list = bincomplex.strip("(").strip(")").split(",")

        expression = expression.replace(
            bincomplex, "({}+{}j)".format(bincomplex_list[0],
                                          bincomplex_list[1]))

    for polcomplex in re.findall(constants.get("REGEX_POLAR"), expression):
        print polcomplex
        polcomplex = polcomplex[0]
        polcomplex_list = polcomplex.strip("[").strip("]").split(";")
        real = math.cos(float(polcomplex_list[1])) * float(polcomplex_list[0])
        imag = math.sin(float(polcomplex_list[1])) * float(polcomplex_list[0])
        expression = expression.replace(polcomplex,
                                        "({}+{}j)".format(real, imag))

    print expression
    return eval(expression)
    def getRIR(self, mic, Fs, t0=0.0, t_max=None):
        """
        Compute the room impulse response between the source
        and the microphone whose position is given as an
        argument.
        """

        # compute the distance
        dist = self.distance(mic)
        time = dist / constants.get("c") + t0
        alpha = self.damping / (4.0 * np.pi * dist)

        # the number of samples needed
        if t_max is None:
            # we give a little bit of time to the sinc to decay anyway
            N = np.ceil((1.05 * time.max() - t0) * Fs)
        else:
            N = np.ceil((t_max - t0) * Fs)

        t = np.arange(N) / float(Fs)
        ir = np.zeros(t.shape)

        # from utilities import lowPassDirac
        import utilities as u

        return u.lowPassDirac(time[:, np.newaxis], alpha[:, np.newaxis], Fs, N).sum(axis=0)
    def getRIR(self, mic, Fs, t0=0., t_max=None):
        '''
        Compute the room impulse response between the source
        and the microphone whose position is given as an
        argument.
        '''

        # compute the distance
        dist = self.distance(mic)
        time = dist / constants.get('c') + t0
        alpha = self.damping / (4. * np.pi * dist)

        # the number of samples needed
        if t_max is None:
            # we give a little bit of time to the sinc to decay anyway
            N = np.ceil((1.05 * time.max() - t0) * Fs)
        else:
            N = np.ceil((t_max - t0) * Fs)

        t = np.arange(N) / float(Fs)
        ir = np.zeros(t.shape)

        #from utilities import lowPassDirac
        import utilities as u

        return u.lowPassDirac(time[:, np.newaxis], alpha[:, np.newaxis], Fs,
                              N).sum(axis=0)
def test_background(elID):
    const = constants.get()
    planck = const["planck"]
    elvolt = const["elvolt"]
    nurev, Jnurev = np.loadtxt("test_continuum3.dat", unpack=True)
    #Jnurev /= (2.0)
    print "Using test background radiation field (table power law -1)"
    ediff = 1.0E-10
    ekeys = elID.keys()
    Jnuadd = np.zeros(
        2 * len(ekeys) +
        2 * 7)  # 7 additional points for secondary heat/ionizations
    nuadd = np.zeros(
        2 * len(ekeys) +
        2 * 7)  # 7 additional points for secondary heat/ionizations
    for i in range(len(ekeys)):
        nup = (elID[ekeys[i]].ip + ediff) * elvolt / planck
        num = (elID[ekeys[i]].ip - ediff) * elvolt / planck
        Jnuvp = np.interp(nup, nurev, Jnurev)
        Jnuvm = np.interp(nup, nurev, Jnurev)
        nuadd[2 * i] = nup
        nuadd[2 * i + 1] = num
        Jnuadd[2 * i] = Jnuvp
        Jnuadd[2 * i + 1] = Jnuvm
    # Now include the additional points for secondary heat/ionizations
    ekeysA = ["H I", "D I", "He I", "He II"]
    #	ekeysA = ["H I", "He I", "He II"]
    extra = 28.0
    cntr = 2 * len(ekeys)
    for i in range(len(ekeysA)):
        nup = (elID[ekeysA[i]].ip + extra + ediff) * elvolt / planck
        num = (elID[ekeysA[i]].ip + extra - ediff) * elvolt / planck
        Jnuvp = np.interp(nup, nurev, Jnurev)
        Jnuvm = np.interp(nup, nurev, Jnurev)
        nuadd[2 * i + cntr] = nup
        nuadd[2 * i + cntr + 1] = num
        Jnuadd[2 * i + cntr] = Jnuvp
        Jnuadd[2 * i + cntr + 1] = Jnuvm
    ekeysB = ["H I", "D I", "He I"]
    #	ekeysB = ["H I", "He I"]
    extra = 11.0
    cntr = 2 * len(ekeys) + 2 * 4
    for i in range(len(ekeysB)):
        nup = (elID[ekeysB[i]].ip + extra + ediff) * elvolt / planck
        num = (elID[ekeysB[i]].ip + extra - ediff) * elvolt / planck
        Jnuvp = np.interp(nup, nurev, Jnurev)
        Jnuvm = np.interp(nup, nurev, Jnurev)
        nuadd[2 * i + cntr] = nup
        nuadd[2 * i + cntr + 1] = num
        Jnuadd[2 * i + cntr] = Jnuvp
        Jnuadd[2 * i + cntr + 1] = Jnuvm
    # Append to the original arrays
    Jnut = np.append(Jnurev, Jnuadd)
    nut = np.append(nurev, nuadd)
    argsrt = np.argsort(nut, kind='mergesort')
    #plt.plot(np.log10(nu[::-1]),np.log10(Jnu[::-1]),'bo')
    #plt.plot(np.log10(nut[argsrt]),np.log10(Jnut[argsrt]),'rx')
    #plt.show()
    return Jnut[argsrt], nut[argsrt]
Beispiel #5
0
def initialize_matrix_for_robot(map_width, map_length, shelf_pos, charging_pos,
                                unload_pos):
    n = int(map_width / constants.get('robot_radius'))
    m = int(map_length / constants.get('robot_radius'))
    # Create map nxm
    map = []
    for i in range(n):
        map.append([])
        for j in range(m):
            map[i].append(0)

    for i in shelf_pos:
        map[i[0]][i[1]] = 1
    for i in charging_pos:
        map[i[0]][i[1]] = 1
    for i in unload_pos:
        map[i[0]][i[1]] = 1
    return map
def _HM_background_impl(elID, redshift, version, alpha_UV):
    if version in {'12', '15'}:
        usecols = tuple(range(60))
    elif version == '05':
        usecols = tuple(range(50))
    data = np.loadtxt(
        os.path.join(os.path.dirname(__file__),
                     "data/radfields/HM{:s}_UVB.dat").format(version),
        usecols=usecols)
    rdshlist = data[0, :]
    amin = np.argmin(np.abs(rdshlist - redshift))
    waveAt, Jnut = data[1:, 0], data[1:, amin + 1]
    waveA = waveAt[1:] * 1.0E-10
    #w = np.where(waveAt < 912.0)
    Jnu = Jnut[1:]
    nu = 299792458.0 / waveA
    # Interpolate the Haardt & Madau background around each of the ionization potentials

    nut, Jnut, egyt = extra_interp(elID, nu, Jnu)

    # Shape parameter (Crighton et al 2015, https://arxiv.org/pdf/1406.4239.pdf)
    if alpha_UV != 0:
        const = constants.get()
        elvolt = const["elvolt"]
        logJ = np.log10(Jnut)
        e0 = elID["H I"].ip * elvolt
        e1 = 10 * elID["H I"].ip * elvolt
        rge0 = np.logical_and(e0 <= egyt, egyt <= e1)
        rge1 = egyt > e1
        idx1 = np.searchsorted(egyt, e1)
        logJ[rge0] = logJ[rge0] + alpha_UV * np.log10(egyt[rge0] / e0)
        logJ[rge1] = logJ[rge1] + alpha_UV * np.log10(e1 / e0)
        Jnut = 10**logJ

    #plt.figure()
    #plt.plot(np.log10(nut), np.log10(Jnut))
    #plt.show()

    return Jnut, nut, rdshlist[amin]
def buildRIRMatrix(mics, sources, Lg, Fs, epsilon=5e-3, unit_damping=False):
    """
    A function to build the channel matrix for many sources and microphones

    mics is a dim-by-M ndarray where each column is the position of a microphone
    sources is a list of SoundSource objects
    Lg is the length of the beamforming filters
    Fs is the sampling frequency
    epsilon determines how long the sinc is let to decay. Defaults to epsilon=5e-3
    unit_damping determines if the wall damping parameters are used or not. Default to false.

    returns the RIR matrix H = 

    --------------------
    | H_{11} H_{12} ...
    | ...
    |
    --------------------

    where H_{ij} is channel matrix between microphone i and source j.
    H is of type (M*Lg)x((Lg+Lh-1)*S) where Lh is the channel length (determined by epsilon),
    and M, S are the number of microphones, sources, respectively.
    """

    from beamforming import distance
    from utilities import lowPassDirac, convmtx
    from scipy.linalg import toeplitz

    # set the boundaries of RIR filter for given epsilon
    d_min = np.inf
    d_max = 0.0
    dmp_max = 0.0
    for s in xrange(len(sources)):
        dist_mat = distance(mics, sources[s].images)
        if unit_damping == True:
            dmp_max = np.maximum((1.0 / (4 * np.pi * dist_mat)).max(), dmp_max)
        else:
            dmp_max = np.maximum((sources[s].damping[np.newaxis, :] / (4 * np.pi * dist_mat)).max(), dmp_max)
        d_min = np.minimum(dist_mat.min(), d_min)
        d_max = np.maximum(dist_mat.max(), d_max)

    t_max = d_max / constants.get("c")
    t_min = d_min / constants.get("c")

    offset = dmp_max / (np.pi * Fs * epsilon)

    # RIR length
    Lh = int((t_max - t_min + 2 * offset) * float(Fs))

    # build the channel matrix
    L = Lg + Lh - 1
    H = np.zeros((Lg * mics.shape[1], len(sources) * L))

    for s in xrange(len(sources)):
        for r in np.arange(mics.shape[1]):

            dist = sources[s].distance(mics[:, r])
            time = dist / constants.get("c") - t_min + offset
            if unit_damping == True:
                dmp = 1.0 / (4 * np.pi * dist)
            else:
                dmp = sources[s].damping / (4 * np.pi * dist)

            h = lowPassDirac(time[:, np.newaxis], dmp[:, np.newaxis], Fs, Lh).sum(axis=0)
            H[r * Lg : (r + 1) * Lg, s * L : (s + 1) * L] = convmtx(h, Lg).T

    return H
def extra_interp(elID, nu, Jnu):
    """add finer interpolation to radiation field around ionisation potentials"""
    const = constants.get()
    planck = const["planck"]
    elvolt = const["elvolt"]
    ediff = 1.0E-10
    ekeys = elID.keys()
    Jnurev = Jnu[::-1]
    nurev = nu[::-1]
    Jnuadd = np.zeros(
        2 * len(ekeys) +
        2 * 7)  # 7 additional points for secondary heat/ionizations
    nuadd = np.zeros(
        2 * len(ekeys) +
        2 * 7)  # 7 additional points for secondary heat/ionizations
    for i in range(len(ekeys)):
        nup = (elID[ekeys[i]].ip + ediff) * elvolt / planck
        num = (elID[ekeys[i]].ip - ediff) * elvolt / planck
        Jnuvp = np.interp(nup, nurev, Jnurev)
        Jnuvm = np.interp(num, nurev, Jnurev)
        nuadd[2 * i] = nup
        nuadd[2 * i + 1] = num
        Jnuadd[2 * i] = Jnuvp
        Jnuadd[2 * i + 1] = Jnuvm
    # Now include the additional points for secondary heat/ionizations
    ekeysA = ["H I", "D I", "He I", "He II"]
    #	ekeysA = ["H I", "He I", "He II"]
    extra = 28.0
    cntr = 2 * len(ekeys)
    for i in range(len(ekeysA)):
        nup = (elID[ekeysA[i]].ip + extra + ediff) * elvolt / planck
        num = (elID[ekeysA[i]].ip + extra - ediff) * elvolt / planck
        Jnuvp = np.interp(nup, nurev, Jnurev)
        Jnuvm = np.interp(num, nurev, Jnurev)
        nuadd[2 * i + cntr] = nup
        nuadd[2 * i + cntr + 1] = num
        Jnuadd[2 * i + cntr] = Jnuvp
        Jnuadd[2 * i + cntr + 1] = Jnuvm
    ekeysB = ["H I", "D I", "He I"]
    #	ekeysB = ["H I", "He I"]
    extra = 11.0
    cntr = 2 * len(ekeys) + 2 * 4
    for i in range(len(ekeysB)):
        nup = (elID[ekeysB[i]].ip + extra + ediff) * elvolt / planck
        num = (elID[ekeysB[i]].ip + extra - ediff) * elvolt / planck
        Jnuvp = np.interp(nup, nurev, Jnurev)
        Jnuvm = np.interp(num, nurev, Jnurev)
        nuadd[2 * i + cntr] = nup
        nuadd[2 * i + cntr + 1] = num
        Jnuadd[2 * i + cntr] = Jnuvp
        Jnuadd[2 * i + cntr + 1] = Jnuvm
    # Append to the original arrays
    Jnut = np.append(Jnurev, Jnuadd)
    nut = np.append(nurev, nuadd)
    argsrt = np.argsort(nut, kind='mergesort')

    Jnut = Jnut[argsrt]
    nut = nut[argsrt]
    egyt = nut * planck  # energies

    return nut, Jnut, egyt
def buildRIRMatrix(mics, sources, Lg, Fs, epsilon=5e-3, unit_damping=False):
    '''
    A function to build the channel matrix for many sources and microphones

    mics is a dim-by-M ndarray where each column is the position of a microphone
    sources is a list of SoundSource objects
    Lg is the length of the beamforming filters
    Fs is the sampling frequency
    epsilon determines how long the sinc is let to decay. Defaults to epsilon=5e-3
    unit_damping determines if the wall damping parameters are used or not. Default to false.

    returns the RIR matrix H = 

    --------------------
    | H_{11} H_{12} ...
    | ...
    |
    --------------------

    where H_{ij} is channel matrix between microphone i and source j.
    H is of type (M*Lg)x((Lg+Lh-1)*S) where Lh is the channel length (determined by epsilon),
    and M, S are the number of microphones, sources, respectively.
    '''

    from beamforming import distance
    from utilities import lowPassDirac, convmtx
    from scipy.linalg import toeplitz

    # set the boundaries of RIR filter for given epsilon
    d_min = np.inf
    d_max = 0.
    dmp_max = 0.
    for s in xrange(len(sources)):
        dist_mat = distance(mics, sources[s].images)
        if unit_damping == True:
            dmp_max = np.maximum((1. / (4 * np.pi * dist_mat)).max(), dmp_max)
        else:
            dmp_max = np.maximum((sources[s].damping[np.newaxis, :] /
                                  (4 * np.pi * dist_mat)).max(), dmp_max)
        d_min = np.minimum(dist_mat.min(), d_min)
        d_max = np.maximum(dist_mat.max(), d_max)

    t_max = d_max / constants.get('c')
    t_min = d_min / constants.get('c')

    offset = dmp_max / (np.pi * Fs * epsilon)

    # RIR length
    Lh = int((t_max - t_min + 2 * offset) * float(Fs))

    # build the channel matrix
    L = Lg + Lh - 1
    H = np.zeros((Lg * mics.shape[1], len(sources) * L))

    for s in xrange(len(sources)):
        for r in np.arange(mics.shape[1]):

            dist = sources[s].distance(mics[:, r])
            time = dist / constants.get('c') - t_min + offset
            if unit_damping == True:
                dmp = 1. / (4 * np.pi * dist)
            else:
                dmp = sources[s].damping / (4 * np.pi * dist)

            h = lowPassDirac(time[:, np.newaxis], dmp[:, np.newaxis], Fs,
                             Lh).sum(axis=0)
            H[r * Lg:(r + 1) * Lg, s * L:(s + 1) * L] = convmtx(h, Lg).T

    return H
Beispiel #10
0
def is_binom(expression):
    match = re.match(constants.get("REGEX_BINOM"), expression)
    if match:
        return len(match.group(0))
    return 0
Beispiel #11
0
def is_polar(expression):
    match = re.match(constants.get("REGEX_POLAR"), expression)
    if match:
        return len(match.group(0))
    return 0
Beispiel #12
0
def run_grid(opt, cosmopar, ions, dryrun=False):
    # Get arrays defining the grid of models to run
    gridparams = init_grid(opt)
    virialm   = gridparams['virialm'  ]
    redshift  = gridparams['redshift' ]
    baryscale = gridparams['baryscale']
    
    nummvir, numreds, numbary = map(len, [virialm, redshift, baryscale])

    prev_fname, (smvir, sbary, sreds) = init_resume(opt, [nummvir, numreds, numbary])

    # build list of parameters for each model to run
    models = []
    for i in range(sreds, numreds):     
        for j in range(sbary, numbary):
            for k in range(smvir, nummvir):
                models.append((i, j, k))
    models.reverse()

    # Load baryon fraction as a function of halo mass
    halomass, barymass = np.loadtxt('data/baryfrac.dat', unpack=True)
    baryfracvals = 10.0**barymass / 10.0**halomass
    baryfrac = np.interp(virialm, halomass, baryfracvals)

    # Get some constants needed to define the halo model
    const  = constants.get()
    hztos  = const['hztos' ]
    Gcons  = const['Gcons' ]
    somtog = const['somtog']
    
    while models:
        j, k, l = models.pop()
        logger.log('info', "###########################")
        logger.log('info', "###########################")
        logger.log('info', " virialm 10**{2:.3f}  ({0:d}/{1:d})".format(l+1,nummvir, virialm[l]))
        logger.log('info', " redshift {2:.2f}     ({0:d}/{1:d})".format(k+1,numreds, redshift[k]))
        logger.log('info', " baryon scale {2:.2f} ({0:d}/{1:d})".format(j+1,numbary, baryscale[j]))
        logger.log('info', "###########################")
        logger.log('info', "###########################")
        if opt['geometry']['concrel'] == "Prada":
            concentration = cosmo.massconc_Prada12(10**virialm[l], cosmopar, redshift[k])
        elif opt['geometry']['concrel'] == "Ludlow":
            concentration = cosmo.massconc_Ludlow16(10**virialm[l], cosmopar, redshift[k])
        elif opt['geometry']['concrel'] == "Bose":
            concentration = cosmo.massconc_Bose16(10**virialm[l], cosmopar, redshift[k])
        else:
            raise ValueError("Unknown concentration relation")

        hubpar = cosmo.hubblepar(redshift[k], cosmopar)
        rhocrit = 3.0*(hubpar*hztos)**2/(8.0*np.pi*Gcons)
        hmodel = halomodel.make_halo(opt['geometry']['profile'],
                                    10**virialm[l] * somtog,
                                    baryfrac[l] * baryscale[j],
                                    rhocrit,
                                    concentration)
                                    #acore=opt['geometry']['acore'])
        # Let's go!
        if not dryrun:
            ok, res = gethalo.get_halo(hmodel, redshift[k], cosmopar, ions, prevfile=prev_fname, options=opt)
            if ok == True:
                # model complete
                prev_fname = res
            else:
                # something went wrong with the model
                logger.log('error', res)
                # move onto next grid
                # (keep popping elements till mass counter wraps back to 0)
                while models and (models[-1][3] > l):
                    models.pop()
        # once a run over increasing halo masses is complete, clear the previous filename
        # if doing subsequent runs varying other parameters, don't want to load this run's output!
        if l == nummvir - 1:
            prev_fname = None
    return