def randomrun(LogLikelihood,Prior,n_dims,n_params,n_live_points,n_print,outputfiles_basename,outputfiles_filename):
    f_out = open(os.path.join(outputfiles_basename,outputfiles_filename),'w')
    
    cube = []
    for i in range(n_params): cube.append(0.0)
    # Initialise the cube

    sf.Info('Begin random scan ...')
    Naccept = 0
    for Nrun in range(n_live_points) :
        for j in range(n_dims):
            cube[j] = random()
        
        Prior(cube, n_dims, n_params)
        loglike = LogLikelihood(cube, n_dims, n_params)
        if loglike > sf.log_zero:
            Naccept += 1
            f_out.write('\t'.join([str(x) for x in cube])+'\t'+str(loglike)+'\n')
            f_out.flush()
        if (Nrun+1)%n_print == 0:
            print '------------ Num: %i ------------'%(Nrun+1)
            print 'Input    par   = '+str(cube[0:n_dims])
            print 'Output   par   = '+str(cube[n_dims:n_params])
            print '     loglike   = '+str(loglike)
            print 'Accepted Num   = '+str(Naccept)
            print 'Total    Num   = '+str(Nrun+1)
def gridrun(LogLikelihood,Prior,n_dims,n_params,inpar,bin_num,n_print,outputfiles_basename,outputfiles_filename):
    f_out = open(os.path.join(outputfiles_basename,outputfiles_filename),'w')

    print "llllllllllllllllllllllllllllllllllllllllllllllllllllllllll"
    print outputfiles_basename
    print outputfiles_filename
    print "n_dims", n_dims
    print "n_params", n_params
    
    ntotal = 1
    cube = []
    interval = {}
    for i,name in enumerate(inpar):
        print "01lllllllllllllllllllllllllllllllllllllllllllllllllll"
        print i, name
        interval[name] = 1.0 / bin_num[name]
        bin_num[name] += 1
        ntotal     *= bin_num[name]
    for i in range(n_params): cube.append(0)

    sf.Info('Begin grid scan ...')
    
    Naccept = 0

    for Nrun in range(ntotal):
        iner = 1
        for i,name in enumerate(inpar):
            print "01lllllllllllllllllllllllllllllllllllllllllllllllllll"
            print i,name
            cube[i] = ( int(Nrun/iner) )%bin_num[name] * interval[name]
            print "Nrun", Nrun
            print "iner", iner
            print int(Nrun/iner) 
            print "bin_num", bin_num[name]
            print ( int(Nrun/iner) )%bin_num[name] 
            print "interval", interval[name]
            print ( int(Nrun/iner) )%bin_num[name] * interval[name]
            print cube[i] 
            iner   *= bin_num[name]
       
        Prior(cube, n_dims, n_params)
        #raw_input()
        #continue 
        loglike = LogLikelihood(cube, n_dims, n_params)
        if loglike > sf.log_zero:
            Naccept += 1
            f_out.write('\t'.join([str(x) for x in cube])+'\t'+str(loglike)+'\n')
            f_out.flush()

        if (Nrun+1)%n_print == 0:
            print '------------ Num: %i ------------'%(Nrun+1)
            print 'Input    par   = '+str(cube[0:n_dims])
            print 'Output   par   = '+str(cube[n_dims:n_params])
            print '     loglike   = '+str(loglike)
            print 'Accepted Num   = '+str(Naccept)
            print 'Total    Num   = '+str(Nrun+1)
def readrun(LogLikelihood,Prior,n_dims,n_params,inpar,bin_num,n_print,outputfiles_basename,outputfiles_filename):
    #print "readrun() in scanmanner.py 01llllllll"
    #print outputfiles_basename,outputfiles_filename
    f_out = open(os.path.join(outputfiles_basename,outputfiles_filename),'w')
    import manfun as mf 
    Ploter = mf.plot() 
    Ploter.setPlotPar(outputfiles_basename)

    for i,name in enumerate(inpar):
      try:
        Ploter._data[name]
      except:
        sf.ErrorStop('Input parameter "%s" could not found in ScanInf.txt.'%name)
 
    for i,name in enumerate(inpar):
      ntotal = len(Ploter._data[name])
      break

    cube = []
    for i in range(n_params): cube.append(0)

    sf.Info('Begin read scan ...')
    
    Naccept = 0

    for Nrun in range(ntotal):
        iner = Nrun
        for i,name in enumerate(inpar):
            cube[i] = Ploter._data[name][iner]
        
        loglike = LogLikelihood(cube, n_dims, n_params)
        #if loglike > sf.log_zero:
        if True:
            Naccept += 1
            f_out.write('\t'.join([str(x) for x in cube])+'\t'+str(loglike)+'\n')
            f_out.flush()

        if (Nrun+1)%n_print == 0:
            print '------------ Num: %i ------------'%(Nrun+1)
            print 'Input    par   = '+str(cube[0:n_dims])
            print 'Output   par   = '+str(cube[n_dims:n_params])
            print '     loglike   = '+str(loglike)
            print 'Accepted Num   = '+str(Naccept)
            print 'Total    Num   = '+str(Nrun+1)
Exemple #4
0
def ReadIn(Configfile, ES, Programs, CS, Ploter):
    cf = ConfigParser.ConfigParser()
    cf.read(Configfile)

    ## Read the basic scan parameters
    try:
        ES.setScanMethod(cf.get('scan', 'Scan method'))
    except ConfigParser.NoOptionError:
        sf.WarningWait(
            'Can not find "Scan method" in the input configure file, it will take the default value, "Random".'
        )

    try:
        if ES.getScanMethod() == 'PolyChord'.upper(
        ):  # yuanfang  modified for parallel polychord
            # from random import random
            ES.setFileName(cf.get('scan', 'Result file name'))
        else:
            ES.setFileName(cf.get('scan', 'Result file name'))
    except ConfigParser.NoOptionError:
        sf.ErrorStop(
            'Please provide "Result file name" in the input configure file.')

    ## If the scan method is 'plot', go directly to the 'plot' section
    ## Read the plot information
    plot_items = cf.options("plot")
    if 'histogram' in plot_items:
        Ploter.setHistogram(cf.get('plot', 'Histogram'))
    if 'scatter' in plot_items:
        Ploter.setScatter(cf.get('plot', 'Scatter'))
    if 'color' in plot_items:
        Ploter.setColor(cf.get('plot', 'Color'))
    if 'contour' in plot_items:
        Ploter.setContour(cf.get('plot', 'Contour'))
    if ES.getScanMethod() == 'PLOT': return float('nan')

    ## Back to Read the basic scan parameters
    try:
        ES.setPointNum(cf.getint('scan', 'Points number'))
    except ConfigParser.NoOptionError:
        sf.WarningWait(
            'Can not find "Points number" in the input configure file, it will take the default value, 100.'
        )
    except ValueError:
        sf.ErrorStop(
            'The "Points number" in the input configure file must be an integer.'
        )

    try:
        ES.setRandomSeed(cf.getint('scan', 'Random seed'))
    except ConfigParser.NoOptionError:
        sf.WarningWait(
            'Can not find "Random seed" in the input configure file, it will take current system time as ramdom seed.'
        )
    except ValueError:
        sf.ErrorStop(
            'The "Random seed" in the input configure file must be an integer.'
        )

    try:
        ES.setPrintNum(cf.getint('scan', 'Interval of print'))
    except ConfigParser.NoOptionError:
        sf.WarningNoWait(
            'Can not find "Interval of print" in the input configure file, it will take the default value, 1.'
        )
    except ValueError:
        sf.WarningNoWait(
            'The "Interval of print" in the input configure file must be an integer, it will take the default value, 1.'
        )

    try:
        ES.setInputPar(cf.get('scan', 'Input parametes'))
    except ConfigParser.NoOptionError:
        sf.ErrorStop(
            'Can not find "Input parametes" in the input configure file.')

    try:
        ES.setAccepRate(cf.get('scan', 'Acceptance rate'))
    except ConfigParser.NoOptionError:
        pass

    ## Read the program(s) setting
    ProgID = filter(lambda x: x.startswith('program'), cf.sections())
    ProgID.sort(key=lambda x: int(filter(str.isdigit, x)))
    for ii in ProgID:
        items = cf.options(ii)
        fullitems = [
            'program name', 'execute command', 'command path', 'input file',
            'input variable', 'output file', 'output variable'
        ]
        for jj in fullitems:
            if not jj in items:
                sf.ErrorStop('For "%s", item "%s" missed.' % (ii, jj))
        Programs[ii] = mf.program()
        Programs[ii].setProgName(cf.get(ii, 'Program name'))
        Programs[ii].setCommand(cf.get(ii, 'Execute command'))
        Programs[ii].setComPath(cf.get(ii, 'Command path'))
        Programs[ii].setInputFile(cf.get(ii, 'Input file'))
        Programs[ii].setInputVar(cf.get(ii, 'Input variable'))
        Programs[ii].setOutputFile(cf.get(ii, 'Output file'))
        Programs[ii].setOutputVar(cf.get(ii, 'Output variable'))
        try:
            Programs[ii].setRunFlag(cf.get(ii, 'Run flag'))
        except:
            sf.Info('No Run flag.')

    ## manage the vars
#    ES.setProgID(ProgID)
    ES.setProgram(Programs)

    ## Read the constraints
    constraint_items = cf.options("constraint")
    sf.Info('...............................................')
    sf.Info('...............................................')
    sf.Debug('constraint_items', constraint_items)
    if 'gaussian' in constraint_items:
        CS.setGaussian(cf.get('constraint', 'Gaussian'))

    if 'limit' in constraint_items:
        CS.setLimit(cf.get('constraint', 'Limit'))
    if 'chi^2' in constraint_items:
        CS.setLoglike(cf.get('constraint', 'chi^2'))

    return ProgID