当前位置: 首页>>代码示例>>Python>>正文


Python GeneralMethods.getRandomColor方法代码示例

本文整理汇总了Python中library.classes.GeneralMethods.getRandomColor方法的典型用法代码示例。如果您正苦于以下问题:Python GeneralMethods.getRandomColor方法的具体用法?Python GeneralMethods.getRandomColor怎么用?Python GeneralMethods.getRandomColor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在library.classes.GeneralMethods的用法示例。


在下文中一共展示了GeneralMethods.getRandomColor方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: addLocationPointsWithTitles

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
 def addLocationPointsWithTitles(self, points, color=None):
     if not color:
         color = GeneralMethods.getRandomColor()
     for point, title in ((list(reversed(point)), title) for point, title in points):
         pnt = self.kml.newpoint(description=title, coords=[point])
         pnt.iconstyle.icon.href = "http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png"
         pnt.iconstyle.color = "ff" + color[1:]
开发者ID:kykamath,项目名称:users_and_geo,代码行数:9,代码来源:__init__.py

示例2: addLocationPointsWithHull

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
 def addLocationPointsWithHull(self, points, color=None, withAllPoints=False):
     if not color:
         color = GeneralMethods.getRandomColor()
     points = [list(reversed(point)) for point in points]
     if not withAllPoints:
         self.kml.newpoint(coords=[points[0]])
     else:
         [self.kml.newpoint(coords=[point]) for point in points]
     pol = self.kml.newpolygon(outerboundaryis=geographicConvexHull(points))
     pol.polystyle.color = "99" + color[1:]
     pol.polystyle.outline = 0
开发者ID:kykamath,项目名称:users_and_geo,代码行数:13,代码来源:__init__.py

示例3: plot_local_influencers

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
    def plot_local_influencers(ltuo_model_id_and_hashtag_tag):
        tuples_of_boundary_and_boundary_label = [
                ([[24.527135,-127.792969], [49.61071,-59.765625]], 'USA', GeneralMethods.getRandomColor()),
                ([[10.107706,-118.660469], [26.40009,-93.699531]], 'Mexico', GeneralMethods.getRandomColor()),
                ([[-16.6695,88.409841], [30.115057,119.698904]], 'SE-Asia', GeneralMethods.getRandomColor()),
                ([[-29.565473,-58.191719], [7.327985,-30.418282]], 'Brazil', GeneralMethods.getRandomColor()),
            ]
        for model_id, hashtag_tag in ltuo_model_id_and_hashtag_tag:
            print model_id, hashtag_tag
            tuples_of_location_and_color = []
            for boundary, boundary_label, boundary_color in tuples_of_boundary_and_boundary_label:
                tuo_location_and_influence_scores = Experiments.load_tuo_location_and_boundary_influence_score(model_id, hashtag_tag, boundary)
                tuo_location_and_influence_scores = sorted(tuo_location_and_influence_scores, key=itemgetter(1))[:10]
                locations = zip(*tuo_location_and_influence_scores)[0]
                for location in locations: tuples_of_location_and_color.append([getLocationFromLid(location.replace('_', ' ')), boundary_color])
            locations, colors = zip(*tuples_of_location_and_color)
            plotPointsOnWorldMap(locations, blueMarble=False, bkcolor='#CFCFCF', c=colors,  lw = 0, alpha=1.)
            for _, boundary_label, boundary_color in tuples_of_boundary_and_boundary_label: plt.scatter([0], [0], label=boundary_label, c=boundary_color, lw = 0)
            plt.legend(loc=3, ncol=4, mode="expand",)
#            plt.show()
            savefig(fld_results%(GeneralMethods.get_method_id()) +'%s_%s.png'%(model_id, hashtag_tag))
开发者ID:kykamath,项目名称:hashtags_and_geo,代码行数:23,代码来源:plots.py

示例4: plotLocationClustersOnMap

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
def plotLocationClustersOnMap(graph):
    noOfClusters, clusters = clusterUsingAffinityPropagation(graph)
    nodeToClusterIdMap = dict(clusters)
    colorMap = dict([(i, GeneralMethods.getRandomColor()) for i in range(noOfClusters)])
    clusters = [(c, list(l)) for c, l in groupby(sorted(clusters, key=itemgetter(1)), key=itemgetter(1))]
    points, colors = zip(*map(lambda  l: (getLocationFromLid(l.replace('_', ' ')), colorMap[nodeToClusterIdMap[l]]), graph.nodes()))
    _, m =plotPointsOnUSMap(points, s=0, lw=0, c=colors, returnBaseMapObject=True)
    for u, v, data in graph.edges(data=True):
        if nodeToClusterIdMap[u]==nodeToClusterIdMap[v]:
            color, u, v, w = colorMap[nodeToClusterIdMap[u]], getLocationFromLid(u.replace('_', ' ')), getLocationFromLid(v.replace('_', ' ')), data['w']
            m.drawgreatcircle(u[1],u[0],v[1],v[0],color=color, alpha=0.5)
    plt.show()
开发者ID:kykamath,项目名称:hashtags_and_geo,代码行数:14,代码来源:analysis.py

示例5: __init__

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
 def __init__(self, id):
     self.id = id
     self.totalCount = 0
     self.countDistribution = defaultdict(int)
     self.age = 0
     self.topicClass = random.choice(topicClasses)
     self.decayCoefficient = -3
     if GeneralMethods.trueWith(0.05): self.stickiness = random.uniform(stickinessLowerThreshold, 1.0)
     else: self.stickiness = random.uniform(0.0, 0.1)
     self.payloads = PayLoad.generatePayloads(self.id, noOfPayloadsPerTopic)
     #Non-modeling attributes.
     self.color = GeneralMethods.getRandomColor()
开发者ID:kykamath,项目名称:spam_model,代码行数:14,代码来源:objects_original.py

示例6: writeUserClusters

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
def writeUserClusters(place):
    numberOfTopFeatures = 10000
#    GeneralMethods.runCommand('rm -rf %s'%placesUserClustersFile%place['name'])
    userVectors = defaultdict(dict)
    locationToUserMap = dict((l['location'], l) for l in locationToUserMapIterator(place, minCheckins=50))
    for lid in locationToUserMap:
        for user in locationToUserMap[lid]['users']: 
            userVectors[user][lid.replace(' ', '_')]=sum(len(locationToUserMap[lid]['users'][user][d][db]) for d in locationToUserMap[lid]['users'][user] for db in locationToUserMap[lid]['users'][user][d])
    for user in userVectors.keys()[:]: 
        if sum(userVectors[user].itervalues())<place['minUserCheckins']: del userVectors[user]
    resultsForVaryingK = []
    for k in range(2,200):
        try:
            print 'Clustering with k=%s'%k
            clusters = KMeansClustering(userVectors.iteritems(), k, documentsAsDict=True).cluster(normalise=True, assignAndReturnDetails=True, repeats=5, numberOfTopFeatures=numberOfTopFeatures, algorithmSource='biopython')
            error=clusters['error']
            for clusterId, features in clusters['bestFeatures'].items()[:]: clusters['bestFeatures'][str(clusterId)]=[(lid.replace('_', ' '), score)for lid, score in features]; del clusters['bestFeatures'][clusterId]
            for clusterId, users in clusters['clusters'].items()[:]: clusters['clusters'][str(clusterId)]=users; del clusters['clusters'][clusterId]
            if error: 
                resultsForVaryingK.append((k, error, clusters, dict((clusterId, GeneralMethods.getRandomColor()) for clusterId in clusters['clusters'])))
                FileIO.writeToFileAsJson((k, error, clusters, dict((clusterId, GeneralMethods.getRandomColor()) for clusterId in clusters['clusters'])), placesUserClustersFile%place['name'])
            else: resultsForVaryingK.append((k, meanClusteringDistance(clusters['bestFeatures'].itervalues()), clusters, dict((clusterId, GeneralMethods.getRandomColor()) for clusterId in clusters['clusters'])))
        except Exception as e: print '*********** Exception while clustering k = %s; %s'%(k, e); pass
开发者ID:kykamath,项目名称:users_and_geo,代码行数:25,代码来源:places.py

示例7: writeTopClusterFeatures

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
 def writeTopClusterFeatures(place):
     locationNames = {}
     def getLocationName(lid): 
         if lid not in locationNames:
             locationObject = venuesCollection.find_one({'lid':lid})
             if locationObject: locationNames[lid] = unicode(locationObject['n']).encode("utf-8")
             else: locationNames[lid] = ''
         return locationNames[lid]
     GeneralMethods.runCommand('rm -rf %s'%placesUserClusterFeaturesFile%place['name'])
     documents = [userVector.values() for user, userVector in FileIO.iterateJsonFromFile(placesUserClustersFile%place['name'])]
     for data in getTopFeaturesForClass(documents, 1000): 
         clusterId, features = data
         modifiedFeatures = []
         for feature in features: modifiedFeatures.append(list(feature) + [getLocationName(feature[0].replace('_', ' '))])
         FileIO.writeToFileAsJson([clusterId, GeneralMethods.getRandomColor(), modifiedFeatures], placesUserClusterFeaturesFile%place['name'])
开发者ID:kykamath,项目名称:users_and_geo,代码行数:17,代码来源:places1.py

示例8: plot_location_plots_with_zones

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
    def plot_location_plots_with_zones(ltuo_model_id_and_hashtag_tag, no_of_bins_for_influence_score=100):
        output_file_format = fld_results+'/%s_%s.png'
        for model_id, hashtag_tag in ltuo_model_id_and_hashtag_tag:
            no_of_zones, ltuo_location_and_influence_score_and_zone_id = \
                Experiments.get_location_with_zone_ids(model_id, hashtag_tag)
            locations, influence_scores, zone_ids = zip(*ltuo_location_and_influence_score_and_zone_id)
#            print len(locations)
#            print [zone_id for _, _, zone_id in sorted(zip(locations, influence_scores, zone_ids), key=itemgetter(1))]
#            exit()
            # Plot influence plot
            ltuo_location_and_global_influence_score = zip(locations, influence_scores)
            max_y_tick = InfluenceAnalysis._plot_scores(ltuo_location_and_global_influence_score, [], no_of_bins_for_influence_score, smooth=True)
            # Plot zones
            ltuo_influence_score_and_zone_id = zip(influence_scores, zone_ids)
            ltuo_zone_id_and_influence_scores = [(zone_id, zip(*ito_tuo_influence_score_and_zone_id)[0])
                                                    for zone_id, ito_tuo_influence_score_and_zone_id in
                                                        groupby(
                                                                sorted(ltuo_influence_score_and_zone_id, key=itemgetter(1)),
                                                                key=itemgetter(1)
                                                        )
                                                ]
            ltuo_zone_id_and_tuo_min_influence_score_and_max_influence_score = \
                [(zone_id, (min(influence_scores), max(influence_scores))) for zone_id, influence_scores in ltuo_zone_id_and_influence_scores]
            ltuo_zone_id_and_tuo_box_start_and_box_width = \
                [(zone_id, (min_influence_score, abs(min_influence_score-max_influence_score))) 
                     for zone_id, (min_influence_score, max_influence_score) in 
                        ltuo_zone_id_and_tuo_min_influence_score_and_max_influence_score
                ]
            zone_ids, ltuo_box_start_and_box_width = zip(*ltuo_zone_id_and_tuo_box_start_and_box_width)
            zone_colors = [GeneralMethods.getRandomColor() for zone_id in zone_ids]
            plt.broken_barh(ltuo_box_start_and_box_width , (0, max_y_tick), facecolors=zone_colors, alpha=0.25, lw=0)
#            temp_ltuo_box_start_and_box_width = []
#            for box_start, box_width in ltuo_box_start_and_box_width:
#                if box_width!=0: temp_ltuo_box_start_and_box_width.append((box_start, box_width))
#                else: temp_ltuo_box_start_and_box_width.append((box_start, 0.0001))

#            zero_size_cluster_ltuo_box_start_and_box_width = []
#            for box_start, box_width in ltuo_box_start_and_box_width:
#                if box_width==0: zero_size_cluster_ltuo_box_start_and_box_width.append((box_start, 0.0001))
#            plt.broken_barh(zero_size_cluster_ltuo_box_start_and_box_width , (0, max_y_tick), facecolors='r', alpha=0.25, lw=0)
#            plt.xlim(xmin=-0.0025, xmax=0.0025)
            output_file = output_file_format%(GeneralMethods.get_method_id(), model_id, hashtag_tag)
            savefig(output_file)
开发者ID:kykamath,项目名称:hashtags_and_geo,代码行数:45,代码来源:plots.py

示例9: influence_clusters

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
    def influence_clusters(model_ids, min_cluster_size=15):
        influence_type = InfluenceMeasuringModels.TYPE_INCOMING_INFLUENCE
        for model_id in model_ids:
            digraph_of_location_and_location_similarity = nx.DiGraph()
            for line_count, (location, tuo_neighbor_location_and_mf_influence_type_and_similarity) in \
                        enumerate(FileIO.iterateJsonFromFile(tuo_location_and_tuo_neighbor_location_and_mf_influence_type_and_similarity_file%model_id)):
#                print line_count
                for neighbor_location, mf_influence_type_to_similarity in tuo_neighbor_location_and_mf_influence_type_and_similarity: 
                    if isWithinBoundingBox(getLocationFromLid(location.replace('_', ' ')), PARTIAL_WORLD_BOUNDARY) and \
                            isWithinBoundingBox(getLocationFromLid(neighbor_location.replace('_', ' ')), PARTIAL_WORLD_BOUNDARY):
                        digraph_of_location_and_location_similarity.add_edge(location, neighbor_location, {'w': mf_influence_type_to_similarity[influence_type]})

            no_of_clusters, tuo_location_and_cluster_id = clusterUsingAffinityPropagation(digraph_of_location_and_location_similarity)
            tuo_cluster_id_to_locations = [ (cluster_id, zip(*ito_tuo_location_and_cluster_id)[0])
                                            for cluster_id, ito_tuo_location_and_cluster_id in 
                                            groupby(
                                                  sorted(tuo_location_and_cluster_id, key=itemgetter(1)),
                                                  key=itemgetter(1)
                                                  )
                                           ]
            mf_location_to_cluster_id = dict(tuo_location_and_cluster_id)
            mf_cluster_id_to_cluster_color = dict([(i, GeneralMethods.getRandomColor()) for i in range(no_of_clusters)])
            mf_valid_locations_to_color = {}
            for cluster_id, locations in \
                    sorted(tuo_cluster_id_to_locations, key=lambda (cluster_id, locations): len(locations))[-10:]:
#                if len(locations)>min_cluster_size:
                print cluster_id, len(locations)
                for location in locations: mf_valid_locations_to_color[location] \
                    = mf_cluster_id_to_cluster_color[mf_location_to_cluster_id[location]]
            locations, colors = zip(*mf_valid_locations_to_color.iteritems())
            locations = [getLocationFromLid(location.replace('_', ' ')) for location in locations]
            _, m = plotPointsOnWorldMap(locations, blueMarble=False, bkcolor='#CFCFCF', c=colors, s=0, returnBaseMapObject=True, lw = 0)
            for u, v, data in digraph_of_location_and_location_similarity.edges(data=True):
                if u in mf_valid_locations_to_color and v in mf_valid_locations_to_color \
                        and mf_location_to_cluster_id[u]==mf_location_to_cluster_id[v]:
                    color, u, v, w = mf_cluster_id_to_cluster_color[mf_location_to_cluster_id[u]], getLocationFromLid(u.replace('_', ' ')), getLocationFromLid(v.replace('_', ' ')), data['w']
                    m.drawgreatcircle(u[1], u[0], v[1], v[0], color=color, alpha=0.6)
            plt.show()
开发者ID:kykamath,项目名称:hashtags_and_geo,代码行数:40,代码来源:plots.py

示例10: sampleCrowds

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
    def sampleCrowds(self):
        # Set dates for experts as startingDay=datetime(2011,3,19), endingDay=datetime(2011,3, 30) with a minimum of 7 users at a time.
        AnalyzeData.reset(), AnalyzeData.constructCrowdDataStructures(self.stream_settings['data_iterator'])
        fig = plt.figure(); ax = fig.gca()
#        expectedTags = set(['#redsox', '#mlb', '#sfgiants', '#49ers', '#mariners', '#twins', '#springtraining', '#mets', '#reds'])
#        expectedTags = set(['#ctia']); title = 'CTIA 2011'
#        expectedTags = set(['#55', '#hcr', '#hcrbday', '#oklahomas', '#aca', '#hcworks', '#npr', '#teaparty'])
#        expectedTags = set(['#budget11', '#taxdodgers', '#budget', '#pmqs', '#budget11', '#indybudget'])
#        expectedTags = set(['#egypt2dc', '#libyan', '#yemen', '#egypt', '#syria', '#gaddaficrimes', '#damascus', '#jan25', 
#                '#daraa', '#feb17', '#gaddafi', '#libya', '#feb17', '#gadhafi', '#muslimbrotherhood', '#gaddafis']); title = 'Middle East'
        expectedTags = set(['#libya']); title = 'Libya'
        for crowd in self._filteredCrowdIterator():
            if expectedTags.intersection(set(list(crowd.hashtagDimensions))):
                x, y = zip(*[(datetime.fromtimestamp(clusterGenerationTime), len(crowd.clusters[clusterGenerationTime].documentsInCluster)) for clusterGenerationTime in sorted(crowd.clusters)])
                plt.plot_date(x, y, '-', color=GeneralMethods.getRandomColor(), lw=2, label=' '.join([crowd.crowdId]+list(crowd.hashtagDimensions)[:1]))
        fig.autofmt_xdate(rotation=30)
        ax.xaxis.set_major_locator(matplotlib.dates.HourLocator(interval=24))
        ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%a %d %b'))
#        plt.legend()
        plt.xlim((datetime(2011, 3, 19), datetime(2011, 3, 30)))
        plt.title(getLatexForString('Crowds for '+title))
        plt.ylabel(getLatexForString('Crowd size'))
        plt.show()
开发者ID:greeness,项目名称:hd_streams_clustering,代码行数:25,代码来源:data_generation_and_crowd_analysis.py

示例11: load_checkins_graph

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
    def load_checkins_graph(checkins_graph_file):
        graph = nx.Graph()
        for data in iterateJsonFromFile(checkins_graph_file):
            (u, v) = data['e'].split('__')
            graph.add_edge(u , v, {'w': data['w']})
        noOfClusters, clusters = clusterUsingAffinityPropagation(graph)
#        for cluster in clusters:
#            print len(cluster), cluster
            
        nodeToClusterIdMap = dict(clusters)
        colorMap = dict([(i, GeneralMethods.getRandomColor()) for i in range(noOfClusters)])
        clusters = [(c, list(l)) for c, l in groupby(sorted(clusters, key=itemgetter(1)), key=itemgetter(1))]
        points, colors = zip(*map(lambda  l: (getLocationFromLid(l.replace('_', ' ')), colorMap[nodeToClusterIdMap[l]]), graph.nodes()))
        _, m =plotPointsOnWorldMap(points[:1], s=0, lw=0, c=colors[:1], returnBaseMapObject=True)
        for u, v, data in graph.edges(data=True):
            if nodeToClusterIdMap[u]==nodeToClusterIdMap[v]:
                color, u, v, w = colorMap[nodeToClusterIdMap[u]], getLocationFromLid(u.replace('_', ' ')), getLocationFromLid(v.replace('_', ' ')), data['w']
                m.drawgreatcircle(u[1],u[0],v[1],v[0],color=color, alpha=1.5)
#        plt.title(title)
        plt.show()
        print noOfClusters
        print graph.number_of_edges()
        print graph.number_of_nodes()
开发者ID:kykamath,项目名称:hashtags_and_geo,代码行数:25,代码来源:plots.py

示例12: drawKMLsForPoints

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
 def drawKMLsForPoints(pointsIterator, outputKMLFile, color=None):
     kml = SpotsKML()
     if not color:
         color = GeneralMethods.getRandomColor()
     kml.addLocationPoints(pointsIterator, color=color)
     kml.write(outputKMLFile)
开发者ID:kykamath,项目名称:users_and_geo,代码行数:8,代码来源:__init__.py

示例13: writeLocationClusters

# 需要导入模块: from library.classes import GeneralMethods [as 别名]
# 或者: from library.classes.GeneralMethods import getRandomColor [as 别名]
def writeLocationClusters(place):
    GeneralMethods.runCommand('rm -rf %s'%placesLocationClustersFile%place['name'])
    clusterId = place.get('k')
    locations = getLocationWithClusterDetails(place, clusterId)
    locationVectorsToCluster = [(location, dict((clusterId, len(epochs)) for clusterId, epochs in checkins['checkins'].iteritems())) for location, checkins in locations.values()[0].iteritems()]
    resultsForVaryingK = []
    for k in range(60,80):
        try:
            print 'Clustering with k=%s'%k
            clusters = KMeansClustering(locationVectorsToCluster, k, documentsAsDict=True).cluster(normalise=True, assignAndReturnDetails=True, repeats=5, algorithmSource='biopython')
            error=clusters['error']
            for clusterId, features in clusters['bestFeatures'].items()[:]: clusters['bestFeatures'][str(clusterId)]=[(lid.replace('_', ' '), score)for lid, score in features]; del clusters['bestFeatures'][clusterId]
            for clusterId, users in clusters['clusters'].items()[:]: clusters['clusters'][str(clusterId)]=users; del clusters['clusters'][clusterId]
            if error: resultsForVaryingK.append((k, error, clusters, dict((clusterId, GeneralMethods.getRandomColor()) for clusterId in clusters['clusters'])))
            else: resultsForVaryingK.append((k, meanClusteringDistance(clusters['bestFeatures'].itervalues()), clusters, dict((clusterId, GeneralMethods.getRandomColor()) for clusterId in clusters['clusters'])))
#            resultsForVaryingK.append((k, meanClusteringDistance(clusters['bestFeatures'].itervalues()), clusters, dict((clusterId, GeneralMethods.getRandomColor()) for clusterId in clusters['clusters'])))
        except Exception as e: print '*********** Exception while clustering k = %s; %s'%(k, e); pass
    FileIO.writeToFileAsJson(min(resultsForVaryingK, key=itemgetter(1)), placesLocationClustersFile%place['name'])
    for data in resultsForVaryingK: FileIO.writeToFileAsJson(data, placesLocationClustersFile%place['name'])
开发者ID:kykamath,项目名称:users_and_geo,代码行数:21,代码来源:places.py


注:本文中的library.classes.GeneralMethods.getRandomColor方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。