Beispiel #1
0
def findShortestPath(startNode):
    global candidateList
    global graph
    global endNode
    global minCandidateFromList
    visitedList  = []

    
    nodeList = list(graph.nodes)
    # check if start or end node even exist in the graph
    if (startNode or endNode) not in nodeList:
        minCandidateFromList.pathList  = str("NO PATH")
        minCandidateFromList.pathCosts = math.inf
        return

    # check if the the adjacency of start or end node is empty
    # so these nodes are isolated graph components
    if bool(not adjDict[startNode]) or bool(not adjDict[endNode]):
        minCandidateFromList.pathList  = str("NO PATH")
        minCandidateFromList.pathCosts = math.inf
        return
    
    for i in range(0, len(nodeList)):
            candidateList.append(candidate.Candidate(nodeList[i],math.inf, visitedList))
    candidateList[getIndexOfNode(startNode, candidateList)] = candidate.Candidate(startNode, 0.0, visitedList)
    
    while len(candidateList)>0:
        try:
            minCandidateFromList = candidateList.pop(getIndexOfNode(getMinCandidateId(), candidateList))
            if minCandidateFromList.idNumber == endNode:
                minCandidateFromList.pathList.append(endNode)
                break
        except:
            pass
        popedCandList.append(minCandidateFromList)
        
        if minCandidateFromList.idNumber not in minCandidateFromList.pathList:
            minCandidateFromList.pathList.append(minCandidateFromList.idNumber)
        else:  # to handle isolated graph components
            minCandidateFromList.pathList  = str("NO PATH")
            minCandidateFromList.pathCosts = math.inf
            break
        try: # for the consistency of data
            candidateList[getIndexOfNode(minCandidateFromList, candidateList)].pathList = minCandidateFromList.pathList
        except:
            pass
        
        for key in adjDict[minCandidateFromList.idNumber]:
            try:
                if not (listContainsKey(key, popedCandList)):
                    updateNode(str(minCandidateFromList.idNumber), str(key))
            except:
                pass
Beispiel #2
0
def main():
    pfdfn = sys.argv[1]

    pfd = prepfold.pfd(pfdfn)

    cand = candidate.Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                        psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                        psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                        pfdfn)

    print "Loaded %s" % cand.pfdfn
    print "    Best topo period (s): %f" % cand.topo_period
    print "    Best bary period (s): %f" % cand.bary_period
    print "    Best DM (cm^-3/pc): %f" % cand.dm
    print "    RA (J2000 - deg): %f" % cand.raj_deg
    print "    Dec (J2000 - deg): %f" % cand.decj_deg

    print "-"*10
    pprint.pprint(cand.__dict__)
    print "-"*10

    gauss.add_data(cand)

    print "Added gaussian fit to cand"
    pprint.pprint(cand.__dict__)
    print "-"*10
    fit_and_plot(cand)
Beispiel #3
0
def explore(heatmap):

    customer_coordinates = [(c.row, c.col) for c in heatmap.customers]
    to_visit = queue.Queue()
    row = heatmap.customer.row
    col = heatmap.customer.col
    cand = candidate.Candidate(False, None, None, row, col,
                               heatmap.motw[row][col].cost,
                               heatmap.customer.reward)
    to_visit.put(cand)
    heatmap.map[row][col] = cand

    while not to_visit.empty():
        cand = to_visit.get()

        for i in range(4):
            if i == 0:
                new_row = cand.row - 1
                new_col = cand.col
                if new_row < 0:
                    continue

            if i == 1:
                new_row = cand.row + 1
                new_col = cand.col
                if new_row >= len(heatmap.motw):
                    continue
            if i == 2:
                new_row = cand.row
                new_col = cand.col - 1
                if new_col < 0:
                    continue

            if i == 3:
                new_row = cand.row
                new_col = cand.col + 1
                if new_col >= len(heatmap.motw[0]):
                    continue

            if heatmap.map[new_row][new_col] == None:
                if not heatmap.motw[new_row][new_col].walkable:
                    cand_sverg = candidate.Candidate(
                        True, cand.row, cand.col, new_row, new_col,
                        heatmap.motw[new_row][new_col].cost, -float('inf'))
                    heatmap.map[new_row][new_col] = cand_sverg
                    continue

                cand_sverg = candidate.Candidate(
                    False, cand.row, cand.col, new_row, new_col,
                    heatmap.motw[new_row][new_col].cost,
                    cand.prize_up_to - cand.cost)
                heatmap.map[new_row][new_col] = cand_sverg
                to_visit.put(cand_sverg)
            elif heatmap.map[new_row][new_col].out:
                continue
            else:
                our_prize_up_to = cand.prize_up_to - cand.cost
                if our_prize_up_to > heatmap.map[new_row][new_col].prize_up_to:
                    heatmap.map[new_row][new_col].prize_up_to = our_prize_up_to
                    heatmap.map[new_row][new_col].row_dad = cand.row
                    heatmap.map[new_row][new_col].col_dad = cand.col

    for i in range(len(heatmap.map)):
        for j in range(len(heatmap.map[0])):
            if heatmap.map[i][j] is None:
                heatmap.map[i][j] = candidate.Candidate(
                    True, i, j, -1, -1, heatmap.motw[i][j].cost, -float('inf'))

    for (row, col) in customer_coordinates:
        heatmap.map[row][col].prize_up_to = -float('inf')
def main():
    pfdfn = sys.argv[1]

    pfd = prepfold.pfd(pfdfn)

    cand = candidate.Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                        psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                        psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                        pfdfn)

    print "Loaded %s" % cand.pfdfn
    print "    Best topo period (s): %f" % cand.topo_period
    print "    Best bary period (s): %f" % cand.bary_period
    print "    Best DM (cm^-3/pc): %f" % cand.dm
    print "    RA (J2000 - deg): %f" % cand.raj_deg
    print "    Dec (J2000 - deg): %f" % cand.decj_deg

    print "-" * 10
    pprint.pprint(cand.__dict__)
    print "-" * 10

    from rating_classes import freq_vs_phase
    fvph = freq_vs_phase.FreqVsPhaseClass()
    fvph.add_data(cand)

    print "Added freq vs phase data to cand"
    pprint.pprint(cand.__dict__)
    print "-" * 10

    pprint.pprint(cand.freq_vs_phase.__dict__)

    print "Check if freq_vs_phase rotates out and back to same array"
    orig = cand.freq_vs_phase.data.copy()
    orig_dm = cand.freq_vs_phase.curr_dm
    cand.freq_vs_phase.dedisperse(0)
    mod = cand.freq_vs_phase.data.copy()
    cand.freq_vs_phase.dedisperse(orig_dm)
    new = cand.freq_vs_phase.data.copy()

    print "Compare orig/mod"
    print(orig == mod).all()
    print "Compare mod/new"
    print(mod == new).all()
    print "Compare orig/new"
    print(orig == new).all()

    print "Compare with best prof"
    # Create best prof file
    print "show_pfd -noxwin %s" % cand.info['pfdfn']
    subprocess.call("show_pfd -noxwin %s" % cand.info['pfdfn'],
                    shell=True,
                    stdout=open(os.devnull))
    pfd_bestprof = np.loadtxt(os.path.split(cand.pfd.pfd_filename +
                                            ".bestprof")[-1],
                              usecols=(1, ))

    cand.freq_vs_phase.dedisperse(cand.pfd.bestdm)
    fvph_prof = cand.freq_vs_phase.data.sum(axis=0).squeeze()
    print test_profiles(pfd_bestprof, fvph_prof, 1e-6)

    print "Testing dedispersion"
    for dm in np.random.randint(0, 1000, size=10):
        print "DM: %g" % dm,
        cand.freq_vs_phase.dedisperse(dm)
        fvph_prof = cand.freq_vs_phase.get_profile()

        cand.pfd.dedisperse(dm, doppler=1)
        cand.pfd.adjust_period()
        pfd_prof = cand.pfd.time_vs_phase().sum(axis=0).squeeze()
        print test_profiles(fvph_prof, pfd_prof, 1e-6)
        plt.figure(dm)
        plt.plot(fvph_prof, label="FvsPh")
        plt.plot(pfd_prof, label="PFD")
        plt.title("DM: %g" % dm)
        plt.legend(loc='best')
    plt.show()
def main():
    pfdfn = sys.argv[1]

    pfd = myprepfold.pfd(pfdfn)

    cand = candidate.Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                        psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                        psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                        pfdfn)

    print "Loaded %s" % cand.pfdfn
    print "    Best topo period (s): %f" % cand.topo_period
    print "    Best bary period (s): %f" % cand.bary_period
    print "    Best DM (cm^-3/pc): %f" % cand.dm
    print "    RA (J2000 - deg): %f" % cand.raj_deg
    print "    Dec (J2000 - deg): %f" % cand.decj_deg

    print "-" * 10
    pprint.pprint(cand.__dict__)
    print "-" * 10

    from rating_classes import time_vs_phase
    time_vs_phase.TimeVsPhaseClass().add_data(cand)
    tvph = cand.time_vs_phase

    print "Added time vs phase data to cand"
    pprint.pprint(cand.__dict__)
    print "-" * 10

    pprint.pprint(cand.time_vs_phase.__dict__)

    print "DEBUG: tvph.pdelays_bins", tvph.pdelays_bins
    print "DEBUG: pfd.pdelays_bins", pfd.pdelays_bins

    pfd.dedisperse(doppler=1)
    print "DEBUG: tvph.dm, pfd.currdm", tvph.dm, pfd.currdm

    if pfd.fold_pow == 1.0:
        bestp = pfd.bary_p1
        bestpd = pfd.bary_p2
        bestpdd = pfd.bary_p3
    else:
        bestp = pfd.topo_p1
        bestpd = pfd.topo_p2
        bestpdd = pfd.topo_p3

    pfd.adjust_period()
    tvph.adjust_period(bestp, bestpd, bestpdd)
    mypfd_tvph = pfd.time_vs_phase()
    print test_img(tvph.data, mypfd_tvph, 1e-6)
    plt.figure()
    plt.plot(tvph.data.sum(axis=0), label='TvPh')
    plt.plot(mypfd_tvph.sum(axis=0), label='PFD')
    plt.title("P=%g s, Pd=%g s/s, Pdd=%g s/s^2" % (bestp, bestpd, bestpdd))
    plt.legend(loc='best')
    for ii in range(10):
        frac_p = 1 + (np.random.rand(1) * 2 - 1) / 100.0
        frac_pd = 1 + (np.random.rand(1) * 2 - 1) / 100.0
        frac_pdd = 1 + (np.random.rand(1) * 2 - 1) / 100.0
        p = frac_p * bestp
        pd = frac_pd * bestpd
        pdd = frac_pdd * bestpdd
        print "Shuffling for the %dth time" % ii
        print "frac_p, frac_pd, frac_pdd", frac_p, frac_pd, frac_pdd

        tvph.adjust_period(p, pd, pdd)
        mypfd_tvph = pfd.time_vs_phase(p, pd, pdd)
        print test_img(tvph.data, mypfd_tvph, 1e-9)

        plt.figure()
        plt.plot(tvph.data.sum(axis=0), label='TvPh')
        plt.plot(mypfd_tvph.sum(axis=0), label='PFD')
        plt.title("P=%g s, Pd=%g s/s, Pdd=%g s/s^2" % (p, pd, pdd))
        plt.legend(loc='best')
    plt.show()
    sys.exit(1)

    print "Check if time_vs_phase rotates out and back to same array"
    orig = cand.time_vs_phase.data.copy()
    orig_p = cand.time_vs_phase.curr_p
    orig_pd = cand.time_vs_phase.curr_pd
    orig_pdd = cand.time_vs_phase.curr_pdd
    cand.time_vs_phase.adjust_period(p=orig_p - 0.00123, pd=0, pdd=0)
    mod = cand.time_vs_phase.data.copy()
    cand.time_vs_phase.adjust_period(p=orig_p, pd=orig_pd, pdd=orig_pdd)
    new = cand.time_vs_phase.data.copy()

    print "Compare orig/mod"
    print(orig == mod).all()
    print "Compare mod/new"
    print(mod == new).all()
    print "Compare orig/new"
    print(orig == new).all()

    print "Compare with best prof"
    # Create best prof file
    print "show_pfd -noxwin %s" % cand.info['pfdfn']
    subprocess.call("show_pfd -noxwin %s" % cand.info['pfdfn'],
                    shell=True,
                    stdout=open(os.devnull))
    prof = np.loadtxt(os.path.split(cand.pfd.pfd_filename + ".bestprof")[-1],
                      usecols=(1, ))

    pfd = cand.pfd
    if pfd.fold_pow == 1.0:
        bestp = pfd.bary_p1
        bestpd = pfd.bary_p2
        bestpdd = pfd.bary_p3
    else:
        bestp = pfd.topo_p1
        bestpd = pfd.topo_p2
        bestpdd = pfd.topo_p3
    cand.time_vs_phase.adjust_period(bestp, bestpd, bestpdd)
    tvph = pfd.time_vs_phase()
    print test_img(cand.time_vs_phase.data, tvph, 1e-6)
    plt.plot(cand.time_vs_phase.get_profile())
    plt.plot(tvph.sum(axis=0).squeeze())
    plt.show()
Beispiel #6
0
def main():
    pfdfn = sys.argv[1]

    pfd = prepfold.pfd(pfdfn)

    cand = candidate.Candidate(pfd.topo_p1, pfd.bary_p1, pfd.bestdm, \
                        psr_utils.ra_to_rad(pfd.rastr)*psr_utils.RADTODEG, \
                        psr_utils.dec_to_rad(pfd.decstr)*psr_utils.RADTODEG, \
                        pfdfn)

    print "Loaded %s" % cand.pfdfn
    print "    Best topo period (s): %f" % cand.topo_period
    print "    Best bary period (s): %f" % cand.bary_period
    print "    Best DM (cm^-3/pc): %f" % cand.dm
    print "    RA (J2000 - deg): %f" % cand.raj_deg
    print "    Dec (J2000 - deg): %f" % cand.decj_deg

    print "-"*10
    pprint.pprint(cand.__dict__)
    print "-"*10

    intstats.add_data(cand)

    print "Added subint stats to cand"
    pprint.pprint(cand.__dict__)
    print "-"*10

    print "Subint stats object:"
    pprint.pprint(cand.subint_stats.__dict__)
    print "-"*10

    print "Sub-int Stats:"
    print "On-fraction (area): %g" % cand.subint_stats.get_on_frac()
    print "On-fraction (peak): %g" % cand.subint_stats.get_peak_on_frac()
    print "Area SNR stddev: %g" % cand.subint_stats.get_snr_stddev()
    print "Peak SNR stddev: %g" % cand.subint_stats.get_peak_snr_stddev()
    print "Avg correlation coefficient: %g" % cand.subint_stats.get_avg_corrcoef()
    
    mgauss = cand.multigaussfit
    tvph = cand.time_vs_phase
    onpulse_region = mgauss.get_onpulse_region(tvph.nbin)
    offpulse_region = np.bitwise_not(onpulse_region)
    m = np.ma.masked_array(onpulse_region, mask=offpulse_region)
    onpulse_ranges = np.ma.notmasked_contiguous(m)
    print onpulse_ranges
    prof = utils.get_scaled_profile(cand.profile, cand.pfd.varprof)
    imax = plt.axes([0.1,0.1,0.5,0.7])
    plt.imshow(scale2d(tvph.data), interpolation='nearest', \
            aspect='auto', origin='lower', cmap=matplotlib.cm.gist_yarg)
    for opr in onpulse_ranges:
        onpulse_bin = (opr.start, opr.stop)
        if onpulse_bin[0] < onpulse_bin[1]:
            plt.axvspan(onpulse_bin[0], onpulse_bin[1]+1, fc='g', alpha=0.2, lw=0)
        else:
            plt.axvspan(onpulse_bin[0], tvph.nbin, fc='g', alpha=0.2, lw=0)
            plt.axvspan(-0.5, onpulse_bin[1]+1, fc='g', alpha=0.2, lw=0)
        

    plt.axes([0.1,0.8,0.5,0.15], sharex=imax)
    plt.plot(prof, 'k-', label='Profile')
    plt.plot(mgauss.make_gaussians(len(prof)), 'r--', label='Fit')
    for ii, opr in enumerate(onpulse_ranges):
        onpulse_bin = (opr.start, opr.stop)
        if ii == 0:
            lbl = 'On-pulse'
        else:
            lbl = '_nolabel_'
        if onpulse_bin[0] < onpulse_bin[1]:
            plt.axvspan(onpulse_bin[0], onpulse_bin[1]+1, fc='g', alpha=0.2, lw=0, label=lbl)
        else:
            plt.axvspan(onpulse_bin[0], tvph.nbin, fc='g', alpha=0.2, lw=0, label=lbl)
            plt.axvspan(-0.5, onpulse_bin[1]+1, fc='g', alpha=0.2, lw=0, label='_nolabel_')
    plt.legend(loc='best', prop=dict(size='xx-small'))
    
    plt.axes([0.6,0.1,0.15,0.7], sharey=imax)
    snrs = cand.subint_stats.snrs
    plt.plot(snrs, np.arange(len(snrs)), 'mo', label='SNR (area)')
    plt.axvline(5.0, c='m', ls='--', lw=2)
    peaksnrs = cand.subint_stats.peak_snrs
    plt.plot(peaksnrs, np.arange(len(peaksnrs)), 'cD', label='SNR (peak)')
    plt.axvline(3.0, c='c', ls='--', lw=2)
    plt.legend(loc='best', prop=dict(size='xx-small'))
   
    plt.axes([0.75,0.1,0.15,0.7], sharey=imax)
    corrcoefs = cand.subint_stats.corr_coefs
    plt.plot(corrcoefs, np.arange(len(corrcoefs)), 'k.')
    imax.set_xlim(-0.5,tvph.nbin-0.5)
    imax.set_ylim(-0.5,tvph.nsubint-0.5)
    plt.show()
Beispiel #7
0
# candidate list contains a key or not.
#
# @param: key
#         The key to be checked.
#         listOfCandidates
#         A list with candidates (nodes).
# @return: boolean
#          If the list of candidates contains the key, True, else False.
def listContainsKey(key, listOfCandidates):
    for i in range(0, len(listOfCandidates)):
        if key == listOfCandidates[i].idNumber:
            return True
    return False

# A proper path candidate
minCandidateFromList = candidate.Candidate(0, 0.0, [])

# List of node candidates for the shortest path.
candidateList = []

# List of poped (visited) candidates
popedCandList = []

# The method performs an update on the node. Therefore it is checked if the
# path costs of the next node, which is currently in the regular candidates list
# are higher than the path costs of the start node, which is already in the poped
# list, plus the current edge costs to the next node. If yes, than the path
# costs of the next node member from the candidates list are updated to the lower
# costs and the path is also updated to the path with the lower costs. The list
# constructor is necessary to avoid different identifiers pointing to the same list.
#