Esempio n. 1
0
def main():
    # Number of trials.
    n = 10

    # Other parameters.
    baseline = 90.  # days
    minutes_per_day = 24. * 60.
    signal_to_noise = 10000.
    nsamples = np.ceil(baseline * minutes_per_day)
    segsize, mindur, maxdur, nbins = (2., 0.01, 0.5, 1000)

    # To make it deterministic, seed the PRNG.
    np.random.seed(4)

    period = np.random.uniform(segsize, 30.)  # days
    duration = np.random.uniform(1. / 24., 5. / 24.)  # days
    depth = np.random.uniform(-0.01, -0.5)
    phase = 0.5

    # Create logarithmically spaced numbers of lightcurves.
    num_lightcurves = np.logspace(0., 3., n).astype('int64')

    # Allocate memory to store results.
    cython_times = np.zeros((n, ), dtype='float64')

    for i in xrange(n):
        # Print a status update message.
        print 'BENCHMARK: # lightcurves =', num_lightcurves[
            i], '/', i + 1, 'of', n, '...'

        for j in xrange(num_lightcurves[i]):
            # Simulate the lightcurve.
            time, flux, fluxerr, _, _, _ = simulate_box_lightcurve(
                period, duration, depth, phase, signal_to_noise, nsamples,
                baseline)

            cython_start = clock()
            out_cython = bls_pulse_cython(time,
                                          flux,
                                          fluxerr,
                                          nbins,
                                          segsize,
                                          mindur,
                                          maxdur,
                                          detrend_order=0,
                                          direction=0)
            cython_end = clock()

            cython_times[i] += cython_end - cython_start

    np.savez('unittests/benchmark2.npz',
             num_lightcurves=num_lightcurves,
             cython_times=cython_times)
    __generate_figure()
Esempio n. 2
0
def main():
    # Number of trials.
    n = 10

    # Other parameters.
    baseline = 90.      # days
    minutes_per_day = 24. * 60.
    signal_to_noise = 10000.
    nsamples = np.ceil(baseline * minutes_per_day)
    segsize, mindur, maxdur, nbins = (2., 0.01, 0.5, 1000)

    # To make it deterministic, seed the PRNG.
    np.random.seed(4)

    period = np.random.uniform(segsize, 30.)            # days
    duration = np.random.uniform(1. / 24., 5. / 24.)    # days
    depth = np.random.uniform(-0.01, -0.5)
    phase = 0.5

    # Create logarithmically spaced numbers of lightcurves.
    num_lightcurves = np.logspace(0., 3., n).astype('int64')

    # Allocate memory to store results.
    cython_times = np.zeros((n,), dtype='float64')

    for i in xrange(n):
        # Print a status update message.
        print 'BENCHMARK: # lightcurves =', num_lightcurves[i], '/', i + 1, 'of', n, '...'

        for j in xrange(num_lightcurves[i]):
            # Simulate the lightcurve.
            time, flux, fluxerr, _, _, _ = simulate_box_lightcurve(period,
                duration, depth, phase, signal_to_noise, nsamples, baseline)

            cython_start = clock()
            out_cython = bls_pulse_cython(time, flux, fluxerr, nbins, segsize, mindur, maxdur,
                detrend_order=0, direction=0)
            cython_end = clock()

            cython_times[i] += cython_end - cython_start

    np.savez('unittests/benchmark2.npz', num_lightcurves=num_lightcurves, cython_times=cython_times)
    __generate_figure()
Esempio n. 3
0
def main(err_on_fail=True, allow_straddling=True, ofile=None):
    if ofile is not None:
        ofile.write('#\tMeas. mid.\tAct. mid.\tMeas. dpth.\tAct. dpth.\tMeas. '
            'dur.\tAct. dur\n')

    # Define absolute/relative tolerances.
    midtime_atol = 0.1
    duration_rtol = 0.1
    depth_rtol = 0.1

    # Other parameters.
    minutes_per_day = 24. * 60.
    sigma, baseline = (1.e-5, 100.)
    nsamples = np.ceil(baseline * minutes_per_day)
    segsize, mindur, maxdur, nbins = (2., 0.05, 0.5, 1000)

    # To make it deterministic, seed the PRNG.
    np.random.seed(4)

    # Simulate the lightcurve.
    time, flux, fluxerr, duration, depth, midtime = \
        simulate_compound_signal(baseline, nsamples, sigma, segsize, mindur,
            maxdur)

    dtime, dflux, dfluxerr, dsamples, segstart, segend = \
        bin_and_detrend(time, flux, fluxerr, nbins, segsize, detrend_order=0)

    out = bls_pulse_cython(dtime, dflux, dfluxerr, dsamples, nbins, segsize,
        mindur, maxdur, direction=2)

    bls_du_dip = out['duration_dip']
    bls_dp_dip = out['depth_dip']
    bls_mid_dip = out['midtime_dip']
    bls_du_blip = out['duration_blip']
    bls_dp_blip = out['depth_blip']
    bls_mid_blip = out['midtime_blip']

    bls_du = np.concatenate((bls_du_dip, bls_du_blip))
    bls_dp = np.concatenate((bls_dp_dip, bls_dp_blip))
    bls_mid = np.concatenate((bls_mid_dip, bls_mid_blip))

    for j in xrange(len(midtime)):
        ndx = np.nanargmin(np.absolute(midtime[j] - bls_mid))

        if ofile:
            ofile.write('%d\t%f\t%f\t%f\t%f\t%f\t%f\n' % (j, bls_mid[ndx],
                midtime[j], bls_dp[ndx], depth[j], bls_du[ndx], duration[j]))

        if is_straddling(midtime[j], duration[j], segsize, time):
            print 'Test segment %02d.....PASS (straddling)' % j
            continue

        try:
            diff_midtime = np.absolute(midtime[j] - bls_mid[ndx])
            diff_depth = np.absolute(depth[j] - bls_dp[ndx])
            diff_duration = np.absolute(duration[j] - bls_du[ndx])

            errstring = 'Test segment %02d.....FAIL\n' % j

            if diff_midtime > midtime_atol:
                errstring += 'MIDTIME: Expected ' + str(midtime[j]) + \
                    ', measured ' + str(bls_mid[ndx]) + ', diff. ' + \
                    str(diff_midtime) + ', allowed diff. ' + str(midtime_atol)
                print errstring
                raise RuntimeError
            #elif abs(diff_depth / depth[j]) > depth_rtol:
            #    errstring += 'DEPTH: Expected ' + str(depth[j]) + \
            #        ', measured ' + str(bls_dp[ndx]) + ', rel. diff. ' + \
            #        str(diff_depth / depth[j] * 100) + \
            #        '%, allowed rel. diff. ' + str(depth_rtol * 100) + '%'
            #    print errstring
            #    raise RuntimeError
            elif abs(diff_duration / duration[j]) > duration_rtol:
                errstring += 'DURATION: Expected ' + str(duration[j]) + \
                    ', measured ' + str(bls_du[ndx]) + ', rel. diff. ' + \
                    str(diff_duration / duration[j] * 100) + \
                    '%, allowed diff. ' + str(duration_rtol * 100) + '%'
                print errstring
                raise RuntimeError
            else:
                # All values within relative or absolute tolerances.
                print 'Test segment %02d.....PASS' % j
        except RuntimeError:
            if err_on_fail:
                sys.exit(1)
Esempio n. 4
0
def main():
    '''
    Main function for this module. Parses all command line arguments, reads in data
    from stdin, and sends it to the proper BLS algorithm.
    '''
    # This is a global list of default values that will be used by the argument parser
    # and the configuration parser.
    defaults = {
        'min_duration': '0.0416667',
        'max_duration': '0.5',
        'n_bins': '100',
        'direction': '0',
        'mode': 'vec',
        'print_format': 'encoded',
        'verbose': '0',
        'profiling': '0'
    }

    # Set up the parser for command line arguments and read them.
    parser = __init_parser(defaults)
    args = parser.parse_args()

    if not args.config:
        # No configuration file specified -- read in command line arguments.
        if not args.segment:
            parser.error(
                'No trial segment specified and no configuration file given.')

        segment = args.segment
        mindur = args.mindur
        maxdur = args.maxdur
        nbins = args.nbins
        direction = args.direction
        mode = args.mode
        fmt = args.fmt
        verbose = args.verbose
        profile = args.profile
    else:
        # Configuration file was given; read in that instead.
        cp = SafeConfigParser(defaults)
        cp.read(args.config)

        segment = cp.getfloat('DEFAULT', 'segment')
        mindur = cp.getfloat('DEFAULT', 'min_duration')
        maxdur = cp.getfloat('DEFAULT', 'max_duration')
        nbins = cp.getint('DEFAULT', 'n_bins')
        direction = cp.getint('DEFAULT', 'direction')
        mode = cp.get('DEFAULT', 'mode')
        fmt = cp.get('DEFAULT', 'print_format')
        verbose = cp.getboolean('DEFAULT', 'verbose')
        profile = cp.getboolean('DEFAULT', 'profiling')

    # Perform any sanity-checking on the arguments.
    __check_args(segment, mindur, maxdur, nbins, direction)

    # Send the data to the algorithm.
    for k, q, time, flux, fluxerr in read_mapper_output(sys.stdin):
        # Extract the array columns.
        time = np.array(time, dtype='float64')
        flux = np.array(flux, dtype='float64')
        fluxerr = np.array(fluxerr, dtype='float64')

        if profile:
            # Turn on profiling.
            pr = cProfile.Profile()
            pr.enable()

        if mode == 'python':
            raise NotImplementedError
            out = bls_pulse_python(time,
                                   flux,
                                   fluxerr,
                                   nbins,
                                   segment,
                                   mindur,
                                   maxdur,
                                   direction=direction)
        elif mode == 'vec':
            raise NotImplementedError
            out = bls_pulse_vec(time,
                                flux,
                                fluxerr,
                                nbins,
                                segment,
                                mindur,
                                maxdur,
                                direction=direction)
        elif mode == 'cython':
            out = bls_pulse_cython(time,
                                   flux,
                                   fluxerr,
                                   nbins,
                                   segment,
                                   mindur,
                                   maxdur,
                                   direction=direction)
        else:
            raise ValueError('Invalid mode: %s' % mode)

        if profile:
            # Turn off profiling.
            pr.disable()
            ps = pstats.Stats(pr, stream=sys.stderr).sort_stats('time')
            ps.print_stats()

        if direction == 2:
            srsq_dip = out['srsq_dip']
            duration_dip = out['duration_dip']
            depth_dip = out['depth_dip']
            midtime_dip = out['midtime_dip']
            srsq_blip = out['srsq_blip']
            duration_blip = out['duration_blip']
            depth_blip = out['depth_blip']
            midtime_blip = out['midtime_blip']
            segstart = out['segstart']
            segend = out['segend']

            # Print output.
            if fmt == 'encoded':
                print "\t".join([
                    k, q,
                    encode_array(segstart),
                    encode_array(segend),
                    encode_array(srsq_dip),
                    encode_array(duration_dip),
                    encode_array(depth_dip),
                    encode_array(midtime_dip),
                    encode_array(srsq_blip),
                    encode_array(duration_blip),
                    encode_array(depth_blip),
                    encode_array(midtime_blip)
                ])
            elif fmt == 'normal':
                print "-" * 120
                print "Kepler " + k
                print "Quarters: " + q
                print "-" * 120
                print '{0: <7s} {1: <13s} {2: <13s} {3: <13s} {4: <13s} {5: <13s} {6: <13s} {7: <13s} ' \
                    '{8: <13s}'.format('Segment', 'Dip SR^2', 'Dip dur.', 'Dip depth', 'Dip mid.',
                    'Blip SR^2', 'Blip dur.', 'Blip depth', 'Blip mid.')
                for i in xrange(len(srsq_dip)):
                    print '{0: <7d} {1: <13.6f} {2: <13.6f} {3: <13.6f} {4: <13.6f} ' \
                        '{5: <13.6f} {6: <13.6f} {7: <13.6f} {8: <13.6f}'.format(i,
                        srsq_dip[i], duration_dip[i], depth_dip[i], midtime_dip[i],
                        srsq_blip[i], duration_blip[i], depth_blip[i], midtime_blip[i])
                print "-" * 120
                print
                print
        else:
            srsq = out['srsq']
            duration = out['duration']
            depth = out['depth']
            midtime = out['midtime']
            segstart = out['segstart']
            segend = out['segend']

            # Print output.
            if fmt == 'encoded':
                print "\t".join([
                    k, q,
                    encode_array(segstart),
                    encode_array(segend),
                    encode_array(srsq),
                    encode_array(duration),
                    encode_array(depth),
                    encode_array(midtime)
                ])
            elif fmt == 'normal':
                print "-" * 80
                print "Kepler " + k
                print "Quarters: " + q
                print "-" * 80
                print '{0: <7s} {1: <13s} {2: <10s} {3: <9s} {4: <13s}'.format(
                    'Segment', 'SR^2', 'Duration', 'Depth', 'Midtime')
                for i in xrange(len(srsq)):
                    print '{0: <7d} {1: <13.6f} {2: <10.6f} {3: <9.6f} {4: <13.6f}'.format(
                        i, srsq[i], duration[i], depth[i], midtime[i])
                print "-" * 80
                print
                print
Esempio n. 5
0
def main():
    '''
    Main function for this module. Parses all command line arguments, reads in data
    from stdin, and sends it to the proper BLS algorithm.
    '''
    # This is a global list of default values that will be used by the argument parser
    # and the configuration parser.
    defaults = {'min_duration':'0.0416667', 'max_duration':'0.5', 'n_bins':'100',
        'direction':'0', 'mode':'vec', 'print_format':'encoded', 'verbose':'0', 'profiling':'0'}

    # Set up the parser for command line arguments and read them.
    parser = __init_parser(defaults)
    args = parser.parse_args()

    if not args.config:
        # No configuration file specified -- read in command line arguments.
        if not args.segment:
            parser.error('No trial segment specified and no configuration file given.')

        segment = args.segment
        mindur = args.mindur
        maxdur = args.maxdur
        nbins = args.nbins
        direction = args.direction
        mode = args.mode
        fmt = args.fmt
        verbose = args.verbose
        profile = args.profile
    else:
        # Configuration file was given; read in that instead.
        cp = SafeConfigParser(defaults)
        cp.read(args.config)

        segment = cp.getfloat('DEFAULT', 'segment')
        mindur = cp.getfloat('DEFAULT', 'min_duration')
        maxdur = cp.getfloat('DEFAULT', 'max_duration')
        nbins = cp.getint('DEFAULT', 'n_bins')
        direction = cp.getint('DEFAULT', 'direction')
        mode = cp.get('DEFAULT', 'mode')
        fmt = cp.get('DEFAULT', 'print_format')
        verbose = cp.getboolean('DEFAULT', 'verbose')
        profile = cp.getboolean('DEFAULT', 'profiling')

    # Perform any sanity-checking on the arguments.
    __check_args(segment, mindur, maxdur, nbins, direction)

    # Send the data to the algorithm.
    for k, q, time, flux, fluxerr in read_mapper_output(sys.stdin):
        # Extract the array columns.
        time = np.array(time, dtype='float64')
        flux = np.array(flux, dtype='float64')
        fluxerr = np.array(fluxerr, dtype='float64')

        if profile:
            # Turn on profiling.
            pr = cProfile.Profile()
            pr.enable()

        if mode == 'python':
            raise NotImplementedError
            out = bls_pulse_python(time, flux, fluxerr, nbins, segment, mindur, maxdur,
                direction=direction)
        elif mode == 'vec':
            raise NotImplementedError
            out = bls_pulse_vec(time, flux, fluxerr, nbins, segment, mindur, maxdur,
                direction=direction)
        elif mode == 'cython':
            out = bls_pulse_cython(time, flux, fluxerr, nbins, segment, mindur, maxdur,
                direction=direction)
        else:
            raise ValueError('Invalid mode: %s' % mode)

        if profile:
            # Turn off profiling.
            pr.disable()
            ps = pstats.Stats(pr, stream=sys.stderr).sort_stats('time')
            ps.print_stats()

        if direction == 2:
            srsq_dip = out['srsq_dip']
            duration_dip = out['duration_dip']
            depth_dip = out['depth_dip']
            midtime_dip = out['midtime_dip']
            srsq_blip = out['srsq_blip']
            duration_blip = out['duration_blip']
            depth_blip = out['depth_blip']
            midtime_blip = out['midtime_blip']
            segstart = out['segstart']
            segend = out['segend']

            # Print output.
            if fmt == 'encoded':
                print "\t".join([k, q, encode_array(segstart), encode_array(segend), encode_array(srsq_dip),
                    encode_array(duration_dip), encode_array(depth_dip), encode_array(midtime_dip),
                    encode_array(srsq_blip), encode_array(duration_blip),
                    encode_array(depth_blip), encode_array(midtime_blip)])
            elif fmt == 'normal':
                print "-" * 120
                print "Kepler " + k
                print "Quarters: " + q
                print "-" * 120
                print '{0: <7s} {1: <13s} {2: <13s} {3: <13s} {4: <13s} {5: <13s} {6: <13s} {7: <13s} ' \
                    '{8: <13s}'.format('Segment', 'Dip SR^2', 'Dip dur.', 'Dip depth', 'Dip mid.',
                    'Blip SR^2', 'Blip dur.', 'Blip depth', 'Blip mid.')
                for i in xrange(len(srsq_dip)):
                    print '{0: <7d} {1: <13.6f} {2: <13.6f} {3: <13.6f} {4: <13.6f} ' \
                        '{5: <13.6f} {6: <13.6f} {7: <13.6f} {8: <13.6f}'.format(i,
                        srsq_dip[i], duration_dip[i], depth_dip[i], midtime_dip[i],
                        srsq_blip[i], duration_blip[i], depth_blip[i], midtime_blip[i])
                print "-" * 120
                print
                print
        else:
            srsq = out['srsq']
            duration = out['duration']
            depth = out['depth']
            midtime = out['midtime']
            segstart = out['segstart']
            segend = out['segend']

            # Print output.
            if fmt == 'encoded':
                print "\t".join([k, q, encode_array(segstart), encode_array(segend), encode_array(srsq),
                    encode_array(duration), encode_array(depth), encode_array(midtime)])
            elif fmt == 'normal':
                print "-" * 80
                print "Kepler " + k
                print "Quarters: " + q
                print "-" * 80
                print '{0: <7s} {1: <13s} {2: <10s} {3: <9s} {4: <13s}'.format('Segment',
                    'SR^2', 'Duration', 'Depth', 'Midtime')
                for i in xrange(len(srsq)):
                    print '{0: <7d} {1: <13.6f} {2: <10.6f} {3: <9.6f} {4: <13.6f}'.format(i,
                        srsq[i], duration[i], depth[i], midtime[i])
                print "-" * 80
                print
                print
Esempio n. 6
0
def main(err_on_fail=True, allow_straddling=True, ofile=None, mode='python'):
    if ofile is not None:
        ofile.write('#\tMeas. mid.\tAct. mid.\tMeas. dpth.\tAct. dpth.\tMeas. '
            'dur.\tAct. dur\n')

    # Define absolute/relative tolerances.
    midtime_atol = 0.1
    duration_rtol = 0.1
    depth_rtol = 0.1

    # How many lightcurves to simulate.
    n = 10

    # Other parameters.
    minutes_per_day = 24. * 60.
    signal_to_noise, baseline = (1.e5, 90.)
    nsamples = np.ceil(baseline * minutes_per_day)
    segsize, mindur, maxdur, nbins = (2., 0.01, 0.5, 1000)

    # To make it deterministic, seed the PRNG.
    np.random.seed(4)

    period_list = np.random.uniform(segsize, 30., size=n)           # days
    duration_list = np.random.uniform(1. / 24., 5. / 24., size=n)   # days
    depth_list = np.random.uniform(-0.01, -0.5, size=n)
    phase_list = np.random.uniform(0., 1., size=n)

    for i, p, du, dp, ph in zip(np.arange(n), period_list, duration_list,
    depth_list, phase_list):
        # Print a status update message.
        print 'TEST_BLS_PULSE: Test case', i + 1, 'of', n, '...'

        # Simulate the lightcurve.
        time, flux, fluxerr, duration, depth, midtime = \
            simulate_box_lightcurve(p, du, dp, ph, signal_to_noise, nsamples,
                baseline)

        if mode == 'python':
            out = bls_pulse_python(time, flux, fluxerr, nbins, segsize, mindur,
                maxdur, detrend_order=0, direction=0)
        elif mode == 'vec':
            out = bls_pulse_vec(time, flux, fluxerr, nbins, segsize, mindur,
                maxdur, detrend_order=0, direction=0)
        elif mode == 'cython':
            dtime, dflux, dfluxerr, dsamples, segstart, segend = \
                bin_and_detrend(time, flux, fluxerr, nbins, segsize,
                    detrend_order=0)
            out = bls_pulse_cython(dtime, dflux, dfluxerr, dsamples, nbins,
                segsize, mindur, maxdur, direction=0)
        else:
            raise ValueError('Invalid test mode: %s' % mode)

        bls_du = out['duration'].ravel()
        bls_dp = out['depth'].ravel()
        bls_mid = out['midtime'].ravel()

        for j in xrange(len(midtime)):
            ndx = np.nanargmin(np.absolute(midtime[j] - bls_mid))

            if ofile:
                ofile.write('%d\t%f\t%f\t%f\t%f\t%f\t%f\n' % (j, bls_mid[ndx],
                    midtime[j], bls_dp[ndx], depth[j], bls_du[ndx],
                    duration[j]))

            if is_straddling(midtime[j], duration[j], segsize, time):
                print '    Transit %02d.....PASS (straddling)' % j
                continue

            try:
                diff_midtime = np.absolute(midtime[j] - bls_mid[ndx])
                diff_depth = np.absolute(depth[j] - bls_dp[ndx])
                diff_duration = np.absolute(duration[j] - bls_du[ndx])

                errstring = '    Transit %02d.....FAIL\n' % j

                if diff_midtime > midtime_atol:
                    errstring += 'MIDTIME: Expected ' + str(midtime[j]) + \
                        ', measured ' + str(bls_mid[ndx]) + ', diff. ' + \
                        str(diff_midtime) + ', allowed diff. ' + \
                        str(midtime_atol)
                    print errstring
                    raise RuntimeError
                #elif abs(diff_depth / depth[j]) > depth_rtol:
                #    errstring += 'DEPTH: Expected ' + str(depth[j]) + \
                #        ', measured ' + str(bls_dp[ndx]) + ', rel. diff. ' + \
                #        str(diff_depth / depth[j] * 100) + \
                #        '%, allowed rel. diff. ' + str(depth_rtol * 100) + '%'
                #    print errstring
                #    raise RuntimeError
                elif abs(diff_duration / duration[j]) > duration_rtol:
                    errstring += 'DURATION: Expected ' + str(duration[j]) + \
                        ', measured ' + str(bls_du[ndx]) + ', rel. diff. ' + \
                        str(diff_duration / duration[j] * 100) + \
                        '%, allowed diff. ' + str(duration_rtol * 100) + '%'
                    print errstring
                    raise RuntimeError
                else:
                    # All values within relative or absolute tolerances.
                    print '    Transit %02d.....PASS' % j
            except RuntimeError:
                if err_on_fail:
                    sys.exit(1)
Esempio n. 7
0
def main():
    # Number of baselines to try.
    n = 10

    # Other parameters.
    minutes_per_day = 24. * 60.
    signal_to_noise = 10000.
    segsize, mindur, maxdur, nbins = (2., 0.01, 0.5, 1000)

    # To make it deterministic, seed the PRNG.
    np.random.seed(4)

    duration = np.random.uniform(1. / 24., 5. / 24.)  # days
    depth = np.random.uniform(-0.01, -0.5)
    phase = 0.5

    # Create logarithmically spaced baselines.
    baselines = np.logspace(1., 3., n)

    # Allocate memory to store results.
    python_times = np.empty_like(baselines)
    vec_times = np.empty_like(baselines)
    cython_times = np.empty_like(baselines)

    for i in xrange(n):
        # Print a status update message.
        print 'BENCHMARK: Baseline =', baselines[i], '/', i + 1, 'of', n, '...'

        # Simulate the lightcurve.
        nsamples = np.ceil(baselines[i] * minutes_per_day)
        period = np.random.uniform(segsize, baselines[i])  # days
        time, flux, fluxerr, _, _, _ = simulate_box_lightcurve(
            period, duration, depth, phase, signal_to_noise, nsamples,
            baselines[i])

        sys.stdout.write('  Running Python test...')
        sys.stdout.flush()
        python_start = clock()
        out_python = bls_pulse_python(time,
                                      flux,
                                      fluxerr,
                                      nbins,
                                      segsize,
                                      mindur,
                                      maxdur,
                                      detrend_order=0,
                                      direction=0)
        python_end = clock()
        sys.stdout.write(' done.\n')
        sys.stdout.flush()

        sys.stdout.write('  Running vectorized test...')
        sys.stdout.flush()
        vec_start = clock()
        out_vec = bls_pulse_vec(time,
                                flux,
                                fluxerr,
                                nbins,
                                segsize,
                                mindur,
                                maxdur,
                                detrend_order=0,
                                direction=0)
        vec_end = clock()
        sys.stdout.write(' done.\n')
        sys.stdout.flush()

        sys.stdout.write('  Running Cython test...')
        sys.stdout.flush()
        cython_start = clock()
        out_cython = bls_pulse_cython(time,
                                      flux,
                                      fluxerr,
                                      nbins,
                                      segsize,
                                      mindur,
                                      maxdur,
                                      detrend_order=0,
                                      direction=0)
        cython_end = clock()
        sys.stdout.write(' done.\n')
        sys.stdout.flush()

        python_times[i] = python_end - python_start
        vec_times[i] = vec_end - vec_start
        cython_times[i] = cython_end - cython_start

    np.savez('unittests/benchmark.npz',
             baselines=baselines,
             python_times=python_times,
             vec_times=vec_times,
             cython_times=cython_times)
    __generate_figure()
Esempio n. 8
0
def main():
    # Number of baselines to try.
    n = 10

    # Other parameters.
    minutes_per_day = 24. * 60.
    signal_to_noise = 10000.
    segsize, mindur, maxdur, nbins = (2., 0.01, 0.5, 1000)

    # To make it deterministic, seed the PRNG.
    np.random.seed(4)

    duration = np.random.uniform(1. / 24., 5. / 24.)    # days
    depth = np.random.uniform(-0.01, -0.5)
    phase = 0.5

    # Create logarithmically spaced baselines.
    baselines = np.logspace(1., 3., n)

    # Allocate memory to store results.
    python_times = np.empty_like(baselines)
    vec_times = np.empty_like(baselines)
    cython_times = np.empty_like(baselines)

    for i in xrange(n):
        # Print a status update message.
        print 'BENCHMARK: Baseline =', baselines[i], '/', i + 1, 'of', n, '...'

        # Simulate the lightcurve.
        nsamples = np.ceil(baselines[i] * minutes_per_day)
        period = np.random.uniform(segsize, baselines[i])   # days
        time, flux, fluxerr, _, _, _ = simulate_box_lightcurve(period,
            duration, depth, phase, signal_to_noise, nsamples, baselines[i])

        sys.stdout.write('  Running Python test...')
        sys.stdout.flush()
        python_start = clock()
        out_python = bls_pulse_python(time, flux, fluxerr, nbins, segsize, mindur, maxdur,
            detrend_order=0, direction=0)
        python_end = clock()
        sys.stdout.write(' done.\n')
        sys.stdout.flush()

        sys.stdout.write('  Running vectorized test...')
        sys.stdout.flush()
        vec_start = clock()
        out_vec = bls_pulse_vec(time, flux, fluxerr, nbins, segsize, mindur, maxdur,
            detrend_order=0, direction=0)
        vec_end = clock()
        sys.stdout.write(' done.\n')
        sys.stdout.flush()

        sys.stdout.write('  Running Cython test...')
        sys.stdout.flush()
        cython_start = clock()
        out_cython = bls_pulse_cython(time, flux, fluxerr, nbins, segsize, mindur, maxdur,
            detrend_order=0, direction=0)
        cython_end = clock()
        sys.stdout.write(' done.\n')
        sys.stdout.flush()

        python_times[i] = python_end - python_start
        vec_times[i] = vec_end - vec_start
        cython_times[i] = cython_end - cython_start

    np.savez('unittests/benchmark.npz', baselines=baselines, python_times=python_times,
        vec_times=vec_times, cython_times=cython_times)
    __generate_figure()
Esempio n. 9
0
def main(err_on_fail=True, allow_straddling=True, ofile=None, mode='python'):
    if ofile is not None:
        ofile.write(
            '#\tMeas. mid.\tAct. mid.\tMeas. dpth.\tAct. dpth.\tMeas. dur.\tAct. dur\n'
        )

    # Define absolute/relative tolerances.
    midtime_atol = 0.1
    duration_rtol = 0.1
    depth_rtol = 0.1

    # How many lightcurves to simulate.
    n = 10

    # Other parameters.
    minutes_per_day = 24. * 60.
    signal_to_noise, baseline = (10000., 90.)
    nsamples = np.ceil(baseline * minutes_per_day)
    segsize, mindur, maxdur, nbins = (2., 0.01, 0.5, 1000)

    # To make it deterministic, seed the PRNG.
    np.random.seed(4)

    period_list = np.random.uniform(segsize, 30., size=n)  # days
    duration_list = np.random.uniform(1. / 24., 5. / 24., size=n)  # days
    depth_list = np.random.uniform(-0.01, -0.5, size=n)
    phase_list = np.random.uniform(0., 1., size=n)

    for i, p, du, dp, ph in zip(np.arange(n), period_list, duration_list,
                                depth_list, phase_list):
        # Print a status update message.
        print 'TEST_BLS_PULSE: Test case', i + 1, 'of', n, '...'

        # Simulate the lightcurve.
        time, flux, fluxerr, duration, depth, midtime = simulate_box_lightcurve(
            p, du, dp, ph, signal_to_noise, nsamples, baseline)

        if mode == 'python':
            out = bls_pulse_python(time,
                                   flux,
                                   fluxerr,
                                   nbins,
                                   segsize,
                                   mindur,
                                   maxdur,
                                   detrend_order=0,
                                   direction=0)
        elif mode == 'vec':
            out = bls_pulse_vec(time,
                                flux,
                                fluxerr,
                                nbins,
                                segsize,
                                mindur,
                                maxdur,
                                detrend_order=0,
                                direction=0)
        elif mode == 'cython':
            out = bls_pulse_cython(time,
                                   flux,
                                   fluxerr,
                                   nbins,
                                   segsize,
                                   mindur,
                                   maxdur,
                                   detrend_order=0,
                                   direction=0)
        else:
            raise ValueError('Invalid test mode: %s' % mode)

        bls_du = out['duration'].ravel()
        bls_dp = out['depth'].ravel()
        bls_mid = out['midtime'].ravel()

        for j in xrange(len(midtime)):
            ndx = np.nanargmin(np.absolute(midtime[j] - bls_mid))

            if ofile:
                ofile.write('%d\t%f\t%f\t%f\t%f\t%f\t%f\n' %
                            (j, bls_mid[ndx], midtime[j], bls_dp[ndx],
                             depth[j], bls_du[ndx], duration[j]))

            if is_straddling(midtime[j], duration[j], segsize, time):
                print '    Transit %02d.....PASS (straddling)' % j
                continue

            try:
                diff_midtime = np.absolute(midtime[j] - bls_mid[ndx])
                diff_depth = np.absolute(depth[j] - bls_dp[ndx])
                diff_duration = np.absolute(duration[j] - bls_du[ndx])

                errstring = '    Transit %02d.....FAIL\n' % j

                if diff_midtime > midtime_atol:
                    errstring += 'MIDTIME: Expected ' + str(midtime[j]) + ', measured ' + \
                        str(bls_mid[ndx]) + ', diff. ' + str(diff_midtime) + \
                        ', allowed diff. ' + str(midtime_atol)
                    print errstring
                    raise RuntimeError
                elif diff_depth / depth[j] > depth_rtol:
                    errstring += 'DEPTH: Expected ' + str(depth[j]) + ', measured ' + \
                        str(bls_dp[ndx]) + ', rel. diff. ' + \
                        str(diff_depth / depth[j] * 100) + '%, allowed rel. diff. ' + \
                        str(depth_rtol * 100) + '%'
                    print errstring
                    raise RuntimeError
                elif diff_duration / duration[j] > duration_rtol:
                    errstring += 'DURATION: Expected ' + str(duration[j]) + ', measured ' + \
                        str(bls_du[ndx]) + ', rel. diff. ' + \
                        str(diff_duration / duration[j] * 100) + '%, allowed diff. ' + \
                        str(duration_rtol * 100) + '%'
                    print errstring
                    raise RuntimeError
                else:
                    # All values within relative or absolute tolerances.
                    print '    Transit %02d.....PASS' % j
            except RuntimeError:
                if err_on_fail:
                    sys.exit(1)