예제 #1
0
파일: sigp.py 프로젝트: phdenzel/glass
def rho3d(objmodel, alphalim=3.5, interpnts=None, intpnts=None, rspan=None):
    obj, data = objmodel

    arcsec2kpc = convert('arcsec to kpc', 1, obj.dL, data['nu'])

    #-------------------------------------------------------------------------
    # Find the inner and outer images for the object.
    #-------------------------------------------------------------------------
    if rspan is None:
        rs = [abs(img.pos) for src in obj.sources for img in src.images]
        imagemin, imagemax = amin(rs) * arcsec2kpc, amax(rs) * arcsec2kpc
    else:
        imagemin, imagemax = np.array(rspan) * arcsec2kpc

    mass2d = data['M(<R)']
    R = data['R']['kpc']
    sigma = data['Sigma(R)']

    #-------------------------------------------------------------------------
    # Calculate the Abel integral to obtain rho(r)
    #-------------------------------------------------------------------------
    if not interpnts: interpnts = len(R) * 2
    r = logspace(log10(amin(R) / 10), log10(amax(R) * 10), num=interpnts)

    #print 'min(R)=%f, max(R)=%f' % (amin(R), amax(R))
    #print r

    #print 'abelsolve'
    #print '!!!!', imagemin, imagemax
    rho, mass3d = cumsolve(r, imagemin, imagemax, integrator, intpnts,
                           alphalim, R, sigma, mass2d)

    #   rhoa, mass3da = abelsolve(r, imagemin, imagemax,
    #                             integrator, intpnts, alphalim,
    #                             R, sigma, mass)

    drho = dlnrhodlnr(imagemin, imagemax, alphalim, r, rho, mass3d, R, sigma,
                      mass2d, r)

    rscale = convert('kpc to arcsec', 1, obj.dL, data['nu'])
    r = DArray(r, r'$r$', {
        'arcsec': [rscale, r'$\mathrm{arcsec}$'],
        'kpc': [1, r'$\mathrm{kpc}$']
    })
    rho = DArray(rho, r'$\rho(r)$',
                 {'Msun/kpc^3': [1, r'$M_\odot/\mathrm{kpc}^3$']})
    drho = DArray(drho, r'$d\ln \rho / d\ln r$',
                  {'Msun/kpc': [1, r'$M_\odot/\mathrm{kpc}$']})

    data['rho3d:r'] = r
    data['rho3d:rho'] = rho
    data['rho3d:drho'] = drho
    data['rho3d:mass'] = mass3d
예제 #2
0
def universe_age(env, *args):
    """Set age of the Universe in Gyr"""
    if len(env.objects) != 0:
        raise GLInputError(
            'universe_age() must be used before any objects are created.')
    nu = convert('age in Gyr to nu', array(args), glass.cosmo.age_factor(env))
    env.nu = array([nu[-1], nu[0]])
예제 #3
0
def hubble_time(env, *args):
    """Set H0^-1 (or a range) in Gyr"""
    #print env, args
    if len(env.objects) != 0:
        raise GLInputError(
            'hubble_time() must be used before any objects are created.')
    nu = convert('H0^-1 in Gyr to nu', array(args))
    env.nu = array([nu[-1], nu[0]])
예제 #4
0
파일: plots.py 프로젝트: jpcoles/glass
def chi2_plot(env, models, model0, **kwargs):
    v = []
    n_chi2 = 0
    d_chi2 = 0
    for m in models:
        total_chi2 = 0
        for m1, m2 in izip(m['obj,data'], model0['obj,data']):
            obj, data = m1
            obj0, data0 = m2
            mass0 = data0['kappa'] * convert('kappa to Msun/arcsec^2', 1,
                                             obj0.dL, data0['nu'])
            mass1 = data['kappa'] * convert('kappa to Msun/arcsec^2', 1,
                                            obj.dL, data['nu'])
            n_chi2 += np.sum((mass1 - mass0)**2)
            d_chi2 += np.sum(mass0**2)
        v.append(np.log(n_chi2 / d_chi2))
    pl.hist(v, histtype='step', log=False, **kwargs)
    pl.xlabel(_chi2_xlabel)
    pl.ylabel(r'Count')
예제 #5
0
    def add_time_delay(self, A,B, delay):
        assert A in self.images
        assert B in self.images
        assert delay != (None,None), "Time delays can't have infinite range."

        if not isinstance(delay, (list, tuple)):
            delay = [delay]

        delay = [ convert('days to years', td) if td else td for td in delay ]

        self.time_delays.append((A,B,delay))
예제 #6
0
파일: raytrace.py 프로젝트: phdenzel/glass
def observables(model, obj_index, src_index, seq):
    obj,ps = model['obj,data'][obj_index]

    if not seq: return

    imglist = [[seq[0][0], seq[0][3], None]]

    _,prev,_,_ = seq[0]
    for img,t,_,parity in seq[1:]:
        #print parity, t-prev, obj.z, ps['nu']
        t0 = convert('arcsec^2 to days', t-prev, obj.dL, obj.z, ps['nu'])
        imglist.append([img, parity,t0])
        prev = t

    return imglist
예제 #7
0
파일: plots.py 프로젝트: jpcoles/glass
def time_delays_plot(env, **kwargs):

    models = kwargs.pop('models', env.models)
    obj_index = kwargs.pop('obj_index', 0)
    src_index = kwargs.pop('src_index', 0)
    key = kwargs.pop('key', 'accepted')

    d = defaultdict(list)
    for m in models:
        obj, data = m['obj,data'][obj_index]
        t0 = data['arrival times'][src_index][0]
        for i, t in enumerate(data['arrival times'][src_index][1:]):
            d[i].append(
                float('%0.6f' % convert('arcsec^2 to days', t - t0, obj.dL,
                                        obj.z, data['nu'])))
            t0 = t

    s = product(range(1, 1 + len(d)), ['solid', 'dashed', 'dashdot', 'dotted'])
    for k, v in d.iteritems():
        #print 'td plot', k, len(v)
        #print v
        lw, ls = s.next()
        pl.hist(v,
                bins=25,
                histtype='step',
                color='k',
                ls=ls,
                lw=lw,
                label='%s - %s' % (str(k + 1), str(k + 2)),
                **kwargs)

    #pl.xlim(xmin=0)
    pl.ylim(ymin=0)
    pl.xlim(xmin=pl.xlim()[0] - 0.01 * (pl.xlim()[1] - pl.xlim()[0]))
    pl.legend()

    pl.xlabel(_time_delays_xlabel)
    pl.ylabel(r'Count')
예제 #8
0
def hubble_constant(env, *args):
    """Set H0 (or a range) in km/s/Mpc"""
    if len(env.objects) != 0:
        raise GLInputError(
            'hubble_constant() must be used before any objects are created.')
    env.nu = convert('H0 in km/s/Mpc to nu', array(args))
예제 #9
0
파일: plots.py 프로젝트: jpcoles/glass
def _data_error_plot(models, X, Y, **kwargs):
    with_legend = False
    use = [0, 0, 0]

    if isinstance(X, basestring): X = [X, None]
    if isinstance(Y, basestring): Y = [Y, None]

    x_prop, x_units = X
    y_prop, y_units = Y

    ret_list = []

    every = kwargs.pop('every', 1)
    upto = kwargs.pop('upto', len(models))
    mark_images = kwargs.pop('mark_images', True)
    hilite_model = kwargs.pop('hilite_model', None)
    hilite_color = kwargs.pop('hilite_color', 'm')
    yscale = kwargs.pop('yscale', 'log')
    xscale = kwargs.pop('xscale', 'linear')
    xlabel = kwargs.pop('xlabel', None)
    ylabel = kwargs.pop('ylabel', None)
    sigma = kwargs.pop('sigma', '1sigma')

    kwargs.setdefault('color', 'k')
    kwargs.setdefault('marker', '.')
    kwargs.setdefault('ls', '-')

    normal_kw = {'zorder': 0, 'drawstyle': 'steps', 'alpha': 1.0}
    hilite_kw = {
        'zorder': 1000,
        'drawstyle': 'steps',
        'alpha': 1.0,
        'lw': 4,
        'ls': '--'
    }
    accepted_kw = {'zorder': 500, 'drawstyle': 'steps', 'alpha': 0.5}

    normal = []
    hilite = []
    accepted = []
    #imgs = set()
    imgs = defaultdict(set)
    xmin, xmax = np.inf, -np.inf
    ymin, ymax = np.inf, -np.inf

    objplot = defaultdict(dict)
    for mi in xrange(0, upto, every):
        m = models[mi]

        si = m.get('accepted', 2)
        #print si
        tag = ''
        if si == False: tag = 'rejected'
        if si == True: tag = 'accepted'

        for [obj, data] in m['obj,data']:

            try:
                xs = data[x_prop][x_units]
                ys = data[y_prop][y_units]

                xlabel = _axis_label(xs, x_units) if not xlabel else xlabel
                ylabel = _axis_label(ys, y_units) if not ylabel else ylabel

                objplot[obj].setdefault(tag, {'ys': [], 'xs': None})
                objplot[obj][tag]['ys'].append(ys)
                objplot[obj][tag]['xs'] = xs

                #objplot[obj].setdefault('%s:xs'%tag, xs)
                #objplot[obj].setdefault('%s:ymax'%tag, ys)
                #objplot[obj].setdefault('%s:ymin'%tag, ys)
                #objplot[obj].setdefault('%s:ysum'%tag, np.zeros_like(ys))
                #objplot[obj].setdefault('%s:count'%tag, 0)

                #objplot[obj]['%s:ymax'%tag]  = np.amax((objplot[obj]['%s:ymax'%tag], ys), axis=0)
                #objplot[obj]['%s:ymin'%tag]  = np.amin((objplot[obj]['%s:ymin'%tag], ys), axis=0)
                #objplot[obj]['%s:ysum'%tag] += ys
                #objplot[obj]['%s:count'%tag] += 1

                if mark_images:
                    for i, src in enumerate(obj.sources):
                        for img in src.images:
                            imgs[i].add(
                                convert('arcsec to %s' % x_units,
                                        np.abs(img.pos), obj.dL, data['nu']))

            except KeyError as bad_key:
                Log("Missing information for object %s with key %s. Skipping plot."
                    % (obj.name, bad_key))
                continue

            use[si] = 1

            s = _styles[si]

            #xmin, xmax = min(xmin, amin(data[X])), max(xmax, amax(data[X]))
            #ymin, ymax = min(ymin, amin(data[Y])), max(ymax, amax(data[Y]))

    for i, tag in enumerate(['rejected', 'accepted', '']):
        for k, v in objplot.iteritems():
            if tag not in v: break
            #if not v.has_key('%s:count'%tag): break

            avg, errp, errm = dist_range(v[tag]['ys'], sigma=sigma)
            errp = errp - avg
            errm = avg - errm
            #s = np.sort(v[tag]['ys'], axis=0)
            #avg = s[len(s)//2] if len(s)%2==1 else (s[len(s)//2] + s[len(s)//2+1])/2
            #print s
            #avg = np.median(v[tag]['ys'], axis=0)
            #print avg
            #print np.median(v[tag]['ys'], axis=1)
            #errp = s[len(s) * .841] - avg
            #errm = avg - s[len(s) * .159]

            #errp = np.amax(v[tag]['ys'], axis=0) - avg
            #errm = avg - np.amin(v[tag]['ys'], axis=0)
            #errp = errm = np.std(v[tag]['ys'], axis=0, dtype=np.float64)
            xs = v[tag]['xs']

            #           print [x[1] for x in v[tag]['ys']]
            #           pl.hist([x[1] for x in v[tag]['ys']])
            #           break

            #avg = v['%s:ysum'%tag] / v['%s:count'%tag]
            #errp = v['%s:ymax'%tag]-avg
            #errm = avg-v['%s:ymin'%tag]
            #errm = errp = np.std(

            #print len(v['xs'])
            #print len(avg)
            #assert 0
            #print len(xs)
            #print len(avg)

            ret_list.append([xs, avg, errm, errp])
            yerr = (errm, errp) if not np.all(errm == errp) else None
            if tag == 'rejected':
                pl.errorbar(xs,
                            avg,
                            yerr=yerr,
                            c=_styles[0]['c'],
                            zorder=_styles[0]['z'])
            else:
                pl.errorbar(xs, avg, yerr=yerr, **kwargs)

#   return

    pl.xscale(xscale)
    pl.yscale(yscale)

    si = style_iterator()
    for k, v in imgs.iteritems():
        lw, ls, c = si.next()
        for img_pos in v:
            pl.axvline(img_pos, c=c, ls=ls, lw=lw, zorder=-2, alpha=0.5)


#   if use[0] or use[1]:
#       lines  = [s['line']  for s,u in zip(_styles, use) if u]
#       labels = [s['label'] for s,u in zip(_styles, use) if u]
#       pl.legend(lines, labels)

    if use[0]:
        lines = [_styles[0]['line']]
        labels = [_styles[0]['label']]
        pl.legend(lines, labels)

    #axis('scaled')
    if xlabel: pl.xlabel(xlabel)
    if ylabel: pl.ylabel(ylabel)
    pl.xlim(xmin=pl.xlim()[0] - 0.01 * (pl.xlim()[1] - pl.xlim()[0]))
    #pl.ylim(0, ymax)

    return ret_list
예제 #10
0
파일: plots.py 프로젝트: jpcoles/glass
def _data_plot(models, X, Y, **kwargs):
    with_legend = False
    use = [0, 0, 0]

    if isinstance(X, basestring): X = [X, None]
    if isinstance(Y, basestring): Y = [Y, None]

    x_prop, x_units = X
    y_prop, y_units = Y

    ret_list = []

    every = kwargs.pop('every', 1)
    upto = kwargs.pop('upto', len(models))
    mark_images = kwargs.pop('mark_images', True)
    hilite_model = kwargs.pop('hilite_model', None)
    hilite_color = kwargs.pop('hilite_color', 'm')
    yscale = kwargs.pop('yscale', 'log')
    xscale = kwargs.pop('xscale', 'linear')
    xlabel = kwargs.pop('xlabel', None)
    ylabel = kwargs.pop('ylabel', None)

    kwargs.setdefault('color', 'k')
    kwargs.setdefault('marker', '.')
    kwargs.setdefault('ls', '-')

    normal_kw = {'zorder': 0, 'drawstyle': 'steps', 'alpha': 1.0}
    hilite_kw = {
        'zorder': 1000,
        'drawstyle': 'steps',
        'alpha': 1.0,
        'lw': 4,
        'ls': '--'
    }
    accepted_kw = {'zorder': 500, 'drawstyle': 'steps', 'alpha': 0.5}

    normal = []
    hilite = []
    accepted = []
    #imgs = set()
    imgs = defaultdict(set)
    xmin, xmax = np.inf, -np.inf
    ymin, ymax = np.inf, -np.inf

    objplot = defaultdict(dict)
    for mi in xrange(0, upto, every):
        m = models[mi]

        si = m.get('accepted', 2)
        tag = ''
        if si == False: tag = 'rejected'
        if si == True: tag = 'accepted'

        for [obj, data] in m['obj,data']:

            try:
                xs = data[x_prop][x_units]
                ys = data[y_prop][y_units]

                xlabel = _axis_label(xs, x_units) if not xlabel else None
                ylabel = _axis_label(ys, y_units) if not ylabel else None

                objplot[obj].setdefault(tag, {'ys': [], 'xs': None})
                objplot[obj][tag]['ys'].append(ys)
                objplot[obj][tag]['xs'] = xs

                #objplot[obj].setdefault('%s:xs'%tag, xs)
                #objplot[obj].setdefault('%s:ymax'%tag, ys)
                #objplot[obj].setdefault('%s:ymin'%tag, ys)
                #objplot[obj].setdefault('%s:ysum'%tag, np.zeros_like(ys))
                #objplot[obj].setdefault('%s:count'%tag, 0)

                #objplot[obj]['%s:ymax'%tag]  = np.amax((objplot[obj]['%s:ymax'%tag], ys), axis=0)
                #objplot[obj]['%s:ymin'%tag]  = np.amin((objplot[obj]['%s:ymin'%tag], ys), axis=0)
                #objplot[obj]['%s:ysum'%tag] += ys
                #objplot[obj]['%s:count'%tag] += 1

                if mark_images:
                    for i, src in enumerate(obj.sources):
                        for img in src.images:
                            imgs[i].add(
                                convert('arcsec to %s' % x_units,
                                        np.abs(img.pos), obj.dL, data['nu']))

            except KeyError as bad_key:
                Log("Missing information for object %s with key %s. Skipping plot."
                    % (obj.name, bad_key))
                continue

            use[si] = 1

            s = _styles[si]

            #xmin, xmax = min(xmin, amin(data[X])), max(xmax, amax(data[X]))
            #ymin, ymax = min(ymin, amin(data[Y])), max(ymax, amax(data[Y]))

    for i, tag in enumerate(['rejected', 'accepted', '']):
        for k, v in objplot.iteritems():
            if tag not in v: break

            ys = np.array(v[tag]['ys'])
            xs = np.repeat(np.atleast_2d(v[tag]['xs']), len(ys), axis=0)

            ret_list.append([xs, ys])
            if tag == 'rejected':
                pl.plot(xs, ys, c=_styles[0]['c'], zorder=_styles[0]['z'])
            else:
                pl.plot(xs.T, ys.T, **kwargs)

#   return

    pl.yscale(yscale)
    pl.xscale(xscale)

    si = style_iterator()
    for k, v in imgs.iteritems():
        lw, ls, c = si.next()
        for img_pos in v:
            pl.axvline(img_pos, c=c, ls=ls, lw=lw, zorder=-2, alpha=0.5)


#   if use[0] or use[1]:
#       lines  = [s['line']  for s,u in zip(_styles, use) if u]
#       labels = [s['label'] for s,u in zip(_styles, use) if u]
#       pl.legend(lines, labels)

    if use[0]:
        lines = [_styles[0]['line']]
        labels = [_styles[0]['label']]
        pl.legend(lines, labels)

    #axis('scaled')
    if xlabel: pl.xlabel(xlabel)
    if ylabel: pl.ylabel(ylabel)
    pl.xlim(xmin=pl.xlim()[0] - 0.01 * (pl.xlim()[1] - pl.xlim()[0]))
    #pl.ylim(0, ymax)

    return ret_list
예제 #11
0
def report(env):
    Log('=' * 80)
    Log('COSMOLOGY')
    Log('=' * 80)
    Log(pp('Omega Matter = %.4g' % env.omega_matter, ''))
    Log(pp('Omega Lambda = %.4g' % env.omega_lambda, ''))
    if (hasattr(env.nu, '__len__') and any(env.nu)) or env.nu:
        Log(
            pp(
                'H0inv        = %s' %
                str_range(convert('nu to H0^-1 in Gyr', env.nu), '%.4g'),
                '[Gyr]'))
        Log(
            pp(
                'H0           = %s' %
                str_range(convert('nu to H0 in km/s/Mpc', env.nu), '%.4g'),
                '[km/s/Mpc]'))
    Log(pp('H0inv ref    = %s' % str_range(env.H0inv_ref, '%.4g'), '[Gyr]'))
    Log(pp('filled_beam  = %s' % env.filled_beam, ''))
    Log()
    Log('=' * 80)
    Log('OBJECTS')
    Log('=' * 80)
    H0inv_ref_as_nu = convert('H0^-1 in Gyr to nu', env.H0inv_ref)
    for i, o in enumerate(env.objects):
        Log(
            pp(
                '%i. %s at z=%.4g  Distance(Obs->Lens) = %.4f' %
                (i + 1, o.name, o.z, angdist(env, 0, o.z)), ''))
        if o.maprad:
            Log(pp('    Map radius       = %.4g' % o.maprad, '[arcsec]'))
            Log(
                pp(
                    '    Map radius       = %.4g (H0inv=%4.1f)' %
                    (convert('arcsec to kpc', o.maprad, o.dL,
                             H0inv_ref_as_nu), env.H0inv_ref), '[kpc]'))
        else:
            Log(pp('    Map radius       = Not specified', ''))
        #Log( pp('    Time scale            = %.4g' % o.scales['time'],    '[g days/arcsec^2]') )
        #Log( pp('    Angular distance      = %.4g' % o.scales['angdist'], '[g kpc/arcsec]') )
        #Log( pp('    Critical density      = %.4e' % convert('kappa to Msun/arcsec^2', 1, o.dL, '[Msun/arcsec^2]') )
        Log( pp('    Critical density = %.4e (H0inv=%.1f)' \
            % (convert('kappa to Msun/kpc^2', 1, o.dL, H0inv_ref_as_nu), env.H0inv_ref), '[Msun/kpc^2]') )
        #       if o.shear:
        #           pass
        #           #Log( pp('    Shear                 = %.4g' % o.shear.phi, '') )
        #       else:
        #           Log( pp('    NO SHEAR', '') )
        #           #Log( pp('    Shear                 = Not specified', '') )
        #       Log( pp('    Steepness             = %s' % str_range(o.steep, '%.4g'), '') )
        Log()
        for src in o.sources:
            Log('    Source at z=%.4f %s' %
                (src.z, '[NO IMAGES]' if len(src.images) == 0 else ''))
            Log(
                pp(
                    '        Distance (Obs->Src)  = %.4f' %
                    angdist(env, 0, src.z), '[arcsec]'))
            Log(
                pp(
                    '        Distance (Lens->Src) = %.4f' %
                    angdist(env, o.z, src.z), '[arcsec]'))
            Log(pp('        Dos/Dls              = %.4f' % src.zcap, ''))
            for img in src.images:
                Log('        Image at (% .3f,% .3f) : |*|=% 5.3f angle=% 8.3f parity=%s '
                    % (img.pos.real, img.pos.imag, abs(
                        img.pos), img.angle, img.parity_name))
            #for img in src.images:
            #    Log( '        Image at (% .3f,% .3f) : angle=% 8.3f parity=%s elongation=[%.4g,%.4g,%.4g]'
            #        % (img.pos.real, img.pos.imag, img.angle, img.parity_name, img.elongation[0], img.elongation[1], img.elongation[2]) )

    Log()
    Log('=' * 80)
    Log('MISCELLANEOUS')
    Log('=' * 80)
    Log('Graphics %s' %
        ('enabled' if Environment.global_opts['withgfx'] else 'disabled'))
    Log()
    Log('=' * 80)
    Log('SYSTEM')
    Log('=' * 80)
    Log('Number of CPUs detected = %i' %
        Environment.global_opts['ncpus_detected'])
    Log('Number of CPUs used     = %i' % Environment.global_opts['ncpus'])
    oo = Environment.global_opts['omp_opts']
    if oo:
        Log('OpenMP supported. Compiling with "%s"' %
            ' '.join(oo['extra_compile_args'] + oo['extra_link_args']))
    else:
        Log('OpenMP not supported.')
    Log()
예제 #12
0
파일: sigp.py 프로젝트: phdenzel/glass
def sigp(objmodel,
         lightC,
         lpars,
         aperture,
         beta,
         alphalim=3.5,
         interpnts=None,
         intpnts=None,
         rspan=None):

    obj, data = objmodel

    arcsec2kpc = convert('arcsec to kpc', 1, obj.dL, data['nu'])

    rho3d(objmodel,
          alphalim=alphalim,
          interpnts=interpnts,
          intpnts=intpnts,
          rspan=rspan)
    r = data['rho3d:r']
    rho = data['rho3d:rho']
    drho = data['rho3d:drho']
    mass3d = data['rho3d:mass']
    mass2d = data['M(<R)']
    R = data['R']['kpc']
    sigma = data['Sigma(R)']

    aperture_phys = aperture * arcsec2kpc
    lpars_phys = lpars[:]
    #lpars_phys[1] = lpars_phys[1] * arcsec2kpc

    #print aperture_phys, lpars_phys

    #-------------------------------------------------------------------------
    # Calculate the integral to obtain sigp(r)
    #-------------------------------------------------------------------------
    #units of M=Msun, L=kpc, V=km/s:
    Gsp = 6.67e-11 * 1.989e30 / 3.086e19
    #light.set_pars(lpars_phys)
    light = lightC(lpars_phys, intpnts)

    sigp = sigpsolve(r, rho, mass3d, R, sigma, mass2d, integrator, intpnts,
                     alphalim, Gsp, light, beta) / 1000
    sigpsing = sigpsingle(r, sigp, light, aperture_phys, integrator)

    #rhint   = rhoint(imagemin,imagemax,alphalim,r,rho,mass3d,r)

    #   sigpa     = sigpsolve(r,rhoa,mass3da,integrator,intpnts,alphalim,Gsp,light,lpars_phys,beta) / 1000
    #   sigpsinga = sigpsingle(r,sigpa,light,lpars_phys,aperture_phys,integrator)
    #   rhinta   = rhoint(imagemin,imagemax,alphalim,r,rhoa,mass3da,r)
    #   drhoa    = dlnrhodlnr(r,rhinta)

    #data['sigp:rhoint'   ] = rhint
    data['sigp:sigp'] = sigp
    data['sigp:sigp_sing'] = sigpsing
    data['sigp:scale-factor'] = lpars_phys[1]

    #   data['sigp:rhoa'      ] = rhoa
    #   data['sigp:rhointa'   ] = rhinta
    #   data['sigp:drhoa'     ] = drhoa
    #   data['sigp:mass3da'   ] = mass3da
    #   data['sigp:sigpa'     ] = sigpa
    #   data['sigp:sigp_singa'] = sigpsinga

    #print data['R_phys']
    #print data['sigma_phys']
    #print data['encmass_phys']

    Log('Final rms mean projected vel. dispersion: %f' % sigpsing)
예제 #13
0
파일: raytrace.py 프로젝트: phdenzel/glass
def gen_code(model, obj_index, src_index, seq, simple=False):

    obj,ps = model['obj,data'][obj_index]

    if not seq: return

    letters = [ x for x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']
    
    while len(seq) > len(letters):
        letters += [ x+x[0] for x in letters[-26:] ]

    obs = observables(model, obj_index, src_index, seq)

    #def img2str(img, time_delay, l, parity):
        #return "['%s', (% 9.5f,% 9.5f), '%s', %.4f]" % (l, img.real, img.imag, parity, time_delay)

    def img2str(a):
        if a[1][2] is None:
            return "['%s', (% 9.15f,% 9.15f), '%s']" % (a[0],a[1][0].real,a[1][0].imag, a[1][1])
        else:
            return "['%s', (% 9.15f,% 9.15f), '%s', %.4f]" % (a[0],a[1][0].real,a[1][0].imag, a[1][1], a[1][2])
        
    return map(img2str, zip(letters, obs))
        
    imglist = ["['%s', (% 9.5f,% 9.5f), '%s']" % (letters[0], seq[0][0].real, seq[0][0].imag,seq[0][3])]
    prev = seq[0][1]
    for [img,t,m,parity],l in zip(seq[1:], letters[1:]):
        t0 = convert('arcsec^2 to days', t-prev, obj.z, ps['nu'])
        imglist.append(img2str(img,t0,l,parity))
        prev = t

    print "%.2f, [%.4f, %.4f]," % (obj.sources[src_index].z, ps['src'][src_index].real, ps['src'][src_index].imag)
    print "[" + ",\n ".join(imglist) + "]"

    #---------------------------------------------------------------------------
    # Old stuff.
    #---------------------------------------------------------------------------
    if 0:
        if not simple:
            letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
            for [img,t,_,_], l in zip(seq, letters):
                sys.stdout.write('%s = %-.4f, %-.4f\n' % (l, img.real, img.imag))

            sys.stdout.write("source :: [%.2f, [%.4f, %.4f]]\n" % (obj.sources[src_index].z, ps['src'][src_index].real, ps['src'][src_index].imag))

            sys.stdout.write("source(%.2f,A,'min'" % obj.sources[src_index].z)
            prev = seq[0][1]
            for [img,t],l in zip(seq[1:], letters[1:]):
                print '@', t-prev, ps['1/H0'], obj.basis.top_level_cell_size**2
                t0 = (t-prev) * ps['1/H0'] * obj.scales['time'] # / obj.basis.top_level_cell_size**2
                #t0 = time_to_physical(obj, t-prev) * ps['1/H0'] / obj.basis.top_level_cell_size**2
                if -1e-4 < t0 < 1e-4:
                    sys.stdout.write(", %s,'',%.4e" % (l, t0))
                else:
                    sys.stdout.write(", %s,'',%.4f" % (l, t0))
                prev = t
            sys.stdout.write(')\n')

        else:

            sys.stdout.write("source(%.2f, (%-.4g,%-.4g),'min'" % (
                obj.sources[src_index].z, seq[0][0].real, seq[0][0].imag))

            p = ''
            prev = seq[0][1]
            for i,[img,t] in enumerate(seq[1:]):

                if len(seq) in [4,5]:
                    if i <  1: p = 'min'
                    if i >= 2: p = 'sad'
                    if i >= 3: p = 'max'

                t0 = time_to_physical(obj, t-prev) * ps['1/H0']
                sys.stdout.write(", (%-.4g,%-.4g),'%s',%.4g" % (img.real, img.imag, p,t0))
                prev = t
            sys.stdout.write(')\n')