コード例 #1
0
ファイル: main.py プロジェクト: AlexRArmstrong/Optichart
def main():
	'''
	The main entry point.
	'''
	parser = argparse.ArgumentParser(description = 'Run an optichart projector.\
									If no arguments are given will run a projector.\
									Options allow testing of different modules.')
	parser.add_argument('-c','--chart', action = 'store_true', help = 'Run the Chart class test code.')
	args = parser.parse_args()
	
	if args.chart:
		# Test the Chart class.
		from Chart import Chart
		cn = '/home/alex/programing/optichart/charts/10-chart.chart'
		chart = Chart(cn)
		print chart
		for el in chart.lines():
			print el
			for es in el.sections():
				print es
				print es.text()
	else:
		# If we are executed, we start up a projector.
		from Projector import Projector
		projector = Projector()
		projector.startEventLoop()
コード例 #2
0
ファイル: Charts.py プロジェクト: mrozekma/spades
	def __init__(self, placeholder, data):
		Chart.__init__(self, placeholder)
		self.chart.type = 'pie'
		self.title.text = ''
		self.tooltip.enabled = False

		partnerData, resultData = [], []
		self.series = [
			{'name': 'Partners', 'data': partnerData, 'size': '60%', 'dataLabels': {'distance': 50}},
			{'name': 'Results', 'data': resultData, 'size': '80%', 'innerSize': '60%', 'dataLabels': {'enabled': False}},
		]
		for partner in sorted(data):
			info = data[partner]
			clr = "#%02x%02x%02x" % getPlayerColor(partner)
			partnerData.append({
				'name': partner,
				'y': info['games'],
				'color': clr,
			})
			resultData.append({
				'name': 'Wins',
				'y': info['wins'],
				'color': clr,
			})
			resultData.append({
				'name': 'Losses',
				'y': info['games'] - info['wins'],
				'color': clr,
			})
コード例 #3
0
ファイル: Charts.py プロジェクト: mrozekma/spades
	def __init__(self, placeholder, data):
		Chart.__init__(self, placeholder)
		self.chart.type = 'column'
		self.title.text = ''
		self.tooltip.shared = True
		self.tooltip.formatter = raw("function() {return 'Made <b>' + this.points[1].y + '</b>/<b>' + this.points[0].y + '</b> when bidding <b>' + this.x + '</b>';}")
		self.plotOptions.column.grouping = False
		self.plotOptions.column.borderWidth = 0

		with self.xAxis as axis:
			axis.title.text = 'Bid'
			axis.min = 0
			axis.max = 13
			axis.tickInterval = 1
			axis.categories = ['Nil'] + range(1, 14)

		with self.yAxis as axis:
			axis.title.text = 'Times'
			axis.min = 0
			axis.tickInterval = 1

		bid, made = [], []
		self.series = [
			{'name': 'Bid', 'pointPadding': .3, 'data': bid},
			{'name': 'Made', 'pointPadding': .4, 'data': made},
		]

		for i in range(14):
			bid.append(data[i]['count'])
			made.append(data[i]['made'])
コード例 #4
0
def h_index_over_time():
    def calculate_h_index(pubs, year):
        pubs = list(
            filter(
                lambda pub: pub['year'].isdigit() and pub['citation'].isdigit(
                ) and int(pub['year']) <= year, pubs))
        h_index = 0
        for index, pub in enumerate(pubs):
            if int(pub['citation']) >= index:
                h_index = index
            else:
                break
        return h_index

    # researcher.aggregate([
    # 	{'$match':{'gender':{'$exists':1}}},
    # 	{'pubs.year':{'$gt'}}
    # 	])
    # print(len(docs))
    h_index_arr = []
    start = 1980
    end = 2018
    for year in range(start, end):
        docs = researcher.find({'gender': {'$exists': 1}})
        h_indexs = [calculate_h_index(doc['pubs'], year) for doc in docs]
        print(sum(h_indexs))
        h_index_arr.append(sum(h_indexs))

    chart = Chart(30, 30)
    labels = [str(year) for year in range(start, end)]
    chart.bar(h_index_arr, end - start, labels, 'h-index change over time',
              'time', 'cumulative h_index', True, False)
    chart.save(charts_path + '/h_index_over_time.eps')
    chart.clear()
    chart.close()
コード例 #5
0
ファイル: Main.py プロジェクト: sedjrodonan/lositan
def createChartPanel():
    global chartPanel
    if isDominant:
        chartPanel = Chart(980, 380)
    else:
        chartPanel = Chart(980, 480, isTemporal)
    return chartPanel
コード例 #6
0
    def renderChart(self, width, height):
        chart = Chart()
        chart.chs = "%dx%d" % (width, height)

        configureChart(chart)
        earliestDay, maxValueCount = self.renderChartData(chart)
        renderMetadata(chart, earliestDay, maxValueCount)

        return chart
コード例 #7
0
ファイル: Charts.py プロジェクト: mrozekma/spades
	def __init__(self, placeholder, round):
		Chart.__init__(self, placeholder)

		self.chart.type = 'column'
		self.title.text = ''
		self.xAxis.categories = ["Trick %d" % (i + 1) for i in range(13)]
		# self.yAxis = [
			# {'title': {'text': 'Tricks'}, 'min': 0, 'max': 13, 'tickInterval': 1},
			# {'title': {'text': 'Bids'}, 'opposite': True, 'min': 0, 'max': 13},
		# ]
		with self.yAxis as axis:
			axis.title.text = 'Tricks'
			axis.min = 0
			axis.max = 13
			axis.tickInterval = 1

			axis.plotLines = plotLines = []
			clrs = ['red', 'green']
			import sys
			for team in round.game.teams:
				plotLines.append({
					'label': {'text': annotatedTeamName(round.game, team)},
					'width': 2,
					'color': clrs.pop(0),
					'value': sum(bidValue(round.bidsByPlayer.get(player, 0)) for player in team),
				})
			if plotLines[0]['value'] == plotLines[1]['value']:
				plotLines[0]['label']['text'] = 'Both teams'
				plotLines.pop(1)
		self.tooltip.enabled = False
		self.plotOptions.column.stacking = 'normal'

		# Not sure if there's a nice use for flags
		# Was planning to mark when players made their bid, but it doesn't look good and the team bids are obvious from the plotlines
		# flagSeries = {
			# 'type': 'flags',
			# 'data': [],
			# 'color': '#4572a7',
			# 'shape': 'flag',
			# 'onSeries': '',
			# 'showInLegend': False,
			# 'shape': 'squarepin',
		# }

		winners = [trick.winner if trick else None for trick in round.tricks]
		taken = {player: [0] for player in round.game.players}
		for winner in winners:
			for player, l in taken.iteritems():
				l.append(l[-1] + (1 if player == winner else 0))
		for l in taken.values():
			l.pop(0)
		self.series = [{
			'name': player,
			'stack': "Team %d" % (i%2 + 1),
			'color': "#%02x%02x%02x" % getPlayerColor(player),
			'data': taken[player],
		} for i, player in enumerate(round.game.players)]
コード例 #8
0
    def renderChart(self, width, height):
        chart = Chart()
        chart.chs = "%dx%d" % (width, height)

        configureChart(chart)
        earliestDay, maxValueCount = self.renderChartData(chart)
        renderMetadata(chart, earliestDay, maxValueCount)

        return chart
コード例 #9
0
 def plot(self):
     figure = pyplot.figure(figsize=self.figsize, dpi=200)
     for chart_cmd in self.chart_list:
         chart = Chart(chart_cmd)
         chart.plot(figure)
     pyplot.savefig(self.outfile,
                    bbox_inches='tight',
                    dpi=200,
                    transparent=True)
     pyplot.close(figure)
コード例 #10
0
ファイル: SprintCharts.py プロジェクト: mrozekma/Sprint
	def __init__(self, placeholder, sprint, tasks, **_):
		Chart.__init__(self, placeholder)
		start = tsToDate(sprint.start)

		self.title.text = ''
		self.tooltip.formatter = "function() {return '<b>' + this.series.name + '</b><br>' + this.point.name + ': '+ this.point.x + ' (' + this.y + '%)';}"
		self.credits.enabled = False
		self.series = seriesList = []

		series = {
			'type': 'pie',
			'name': 'Start',
			'size': '45%',
			'innerSize': '20%',
			'showInLegend': True,
			'dataLabels': {'enabled': False},
			'data': []
		}
		seriesList.append(series)

		originalTasks = filter(None, (task.getStartRevision(False) for task in tasks))
		clrGen = cycle(colors)
		total = sum(t.effectiveHours() for t in originalTasks)
		for user in sorted(sprint.members):
			hours = sum(t.effectiveHours() for t in originalTasks if user in t.assigned)
			series['data'].append({
				'name': user.username,
				'x': hours,
				'y': float("%2.2f" % (100 * hours / total if total > 0 else 0)),
				'color': clrGen.next()
			})

		series = {
			'type': 'pie',
			'name': 'Now',
			'innerSize': '45%',
			'dataLabels': {'enabled': False},
			'data': []
		}
		seriesList.append(series)

		clrGen = cycle(colors)
		total = sum(t.effectiveHours() for t in tasks)
		for user in sorted(sprint.members):
			hours = sum(t.effectiveHours() for t in tasks if user in t.assigned)
			series['data'].append({
				'name': user.username,
				'x': hours,
				'y': float("%2.2f" % (100 * hours / total if total > 0 else 0)),
				'color': clrGen.next()
			})
コード例 #11
0
def main():

    stateCovidHandler = CovidDataHandler(state_data)
    covidHandler = CovidDataHandler(data)

    date_list = covidHandler.get_date_list()
    death_list = covidHandler.get_data_list("deathIncrease")
    currently_hosp_list = covidHandler.get_data_list("hospitalizedCurrently")
    test_list = covidHandler.get_sum_two_lists("positiveIncrease",
                                               "negativeIncrease")
    case_list = covidHandler.get_data_list("positiveIncrease")
    on_ventilator = covidHandler.get_data_list("onVentilatorCurrently")

    SC_death_list = stateCovidHandler.get_state_data_list(
        "SC", "deathIncrease")
    SC_date_list = stateCovidHandler.get_state_date_list("SC")
    Chart(SC_date_list, SC_death_list)
    #print(date_list)
    #Chart(date_list, on_ventilator)
    '''Chart(date_list, case_list)
    Chart(date_list, test_list)
    Chart(date_list, currently_hosp_list)
    '''
    #Chart(date_list, death_list)

    plt.show()
コード例 #12
0
    def update(self, *args):
        """Updates the graph with the altered sliders"""
        #Fetches slider information
        s1 = self.s1.get()
        s2 = self.s2.get()
        r1 = self.r1.get()
        r2 = self.r2.get()
        p = self.p.get()

        #Changes the number next to the bar
        self.r1_string.configure(text="%.2f" % r1)
        self.r2_string.configure(text="%.2f" % r2)
        self.s1_string.configure(text="%.2f" % s1)
        self.s2_string.configure(text="%.2f" % s2)
        self.p_string.configure(text="%.2f" % self.p.get())

        #Creates two asset objects
        self.I1 = Instrument(r1, s1, "Asset 1", "Equity")
        self.I2 = Instrument(r2, s2, "Asset 2", "Bond")

        #Builds a portfolio object
        self.port = Portfolio([self.I1, self.I2])
        self.port.addcorr([[0, p]])

        #Displays the new graph to the graph frame
        fff = Frame(height=400, width=400, bd=10, bg='white')
        Chart(self.port, 0.02).scatter(fff)
        fff.grid(row=1, column=0)
コード例 #13
0
ファイル: sprints.py プロジェクト: mrozekma/Sprint
def showMetrics(handler, id):
	requirePriv(handler, 'User')
	id = int(id)
	sprint = Sprint.load(id)
	if not sprint or sprint.isHidden(handler.session['user']):
		ErrorBox.die('Sprints', "No sprint with ID <b>%d</b>" % id)
	elif not sprint.canView(handler.session['user']):
		ErrorBox.die('Private', "You must be a sprint member to view this sprint")

	context = {}
	context['sprint'] = sprint
	context['allTasks'] = sprint.getTasks(includeDeleted = True)
	context['tasks'] = tasks = filter(lambda task: not task.deleted, context['allTasks'])
	context['revisions'] = {(task.id, day): task.getRevisionAt(day) for task, day in product(context['allTasks'], sprint.getDays())}

	handler.title(sprint.safe.name)
	drawNavArrows(sprint, handler.session['user'], 'metrics')

	print "<style type=\"text/css\">"
	print "h2 a {color: #000;}"
	print "</style>"

	charts = [
		('general', 'Hours (general)', HoursChart('chart-general', **context)),
		('commitment-by-user', 'Commitment (by user)', CommitmentByUserChart(**context)),
		('earned-value', 'Earned Value', EarnedValueChart('chart-earned-value', **context)),
		('by-user', 'Hours (by user)', HoursByUserChart('chart-by-user', **context)),
		('status', 'Task status', StatusChart('chart-status', **context)),
		('commitment', 'Total commitment', CommitmentChart('chart-commitment', **context)),
		('goals', 'Sprint goals', GoalsChart(**context)),
	]

	Chart.include()
	map(lambda (anchor, title, chart): chart.js(), charts)
	print tabs(sprint, 'metrics')

	if not sprint.isOver():
		noHours = filter(lambda task: task.stillOpen() and task.hours == 0, tasks)
		if noHours != []:
			print WarningBox("There are <a href=\"/sprints/%d?search=status:not-started,in-progress,blocked hours:0\">open tasks with no hour estimate</a>. These unestimated tasks can artifically lower the tasking lines in the following charts" % sprint.id)

	for anchor, title, chart in charts:
		print "<a name=\"%s\">" % anchor
		print "<h2><a href=\"#%s\">%s</a></h2>" % (anchor, title)
		chart.placeholder()

	print "<br><br>"
コード例 #14
0
ファイル: techtales.py プロジェクト: davechallis/techtales
	def default(self, url=None, fields=None):
		if not url or not fields:
			return dumps({'status':'error', 'message':'Need URI and fields'})
		extract = Extract(url, datapath, cachepath, extractorpath)
		data = extract.run()
		chart = GoogleChart(data)
		field_arr = fields.split(",")
		nfield_arr = []
		for field in field_arr:
			field = field.strip()
			if field != '':
				nfield_arr.append(field)

		if len(nfield_arr) == 1:
			url = chart.get_graph_url_for_field(nfield_arr[0])
		else:
			url = chart.get_graph_url_for_fields(nfield_arr)
		return dumps({'status':'ok', 'url':url})		
コード例 #15
0
ファイル: SprintCharts.py プロジェクト: mrozekma/Sprint
	def __init__(self, placeholder, sprint, tasks, revisions, **_):
		Chart.__init__(self, placeholder)
		days = [day for day in sprint.getDays()]
		now = Weekday.today()
		futureStarts = minOr(filter(lambda day: day > now, days), None)
		futureIndex = days.index(futureStarts) if futureStarts else None

		self.chart.type = 'area'
		self.title.text = ''
		self.plotOptions.area.stacking = 'percent'
		self.plotOptions.area.marker.enabled = False
		self.tooltip.shared = True
		self.credits.enabled = False
		with self.xAxis as xAxis:
			xAxis.tickmarkPlacement = 'on'
			xAxis.maxZoom = 1
			xAxis.title.text = 'Day'
			xAxis.categories = [day.strftime('%a') for day in sprint.getDays()]
			# Future bar
			if futureIndex:
				xAxis.plotBands = [{
					'color': '#DDD',
					'from': futureIndex - 0.75,
					'to': len(days) - 0.5,
					# 'zIndex': 5
				}]
		self.yAxis.min = 0
		self.yAxis.title.text = 'Percentage of tasks'
		self.series = seriesList = []

		counts = OrderedDict((name, []) for block in statusMenu for name in block)
		self.colors = [colorMap[type] for type in counts]
		for type, count in counts.iteritems():
			seriesList.append({
				'name': statuses[type].text,
				'data': count
			})

		for day in days:
			tasksToday = [revisions[t.id, day] for t in tasks]
			for type, count in counts.iteritems():
				count.append(len(filter(lambda task: task and task.status == type, tasksToday)))

		setupTimeline(self, sprint)
コード例 #16
0
ファイル: Charts.py プロジェクト: mrozekma/spades
	def __init__(self, placeholder, round):
		Chart.__init__(self, placeholder)

		self.chart.type = 'heatmap'
		self.title.text = ''
		self.legend.enabled = False
		self.xAxis.categories = round.game.players
		self.yAxis.categories = ['Spades', 'Diamonds', 'Clubs', 'Hearts']
		self.yAxis.title = ''
		with self.colorAxis as axis:
			axis.min = 0
			axis.max = 13. / 2 # I don't know why, but halving the max makes the axis come out right
			# We assume most people will have <= 5 cards in a suit, so we bunch the gradient around the lower numbers. #ff3f3f is 75% of the way to #ff0000 (HSV 0/.75/1)
			axis.stops = [[0, '#ffffff'], [5./13, '#ff3f3f'], [1, '#ff0000']]

		# player: ['As', '10c', ...]
		deal = round.deal
		data = [[xI, yI, sum(card[-1] == y[0].lower() for card in deal.get(x, []))] for xI, x in enumerate(self.xAxis.categories.get()) for yI, y in enumerate(self.yAxis.categories.get())]
		self.series = [{'data': data}]
コード例 #17
0
ファイル: sprints.py プロジェクト: mrozekma/Sprint
def showSprintHistory(handler, id, assigned = None):
	requirePriv(handler, 'User')
	id = int(id)
	sprint = Sprint.load(id)
	if not sprint or sprint.isHidden(handler.session['user']):
		ErrorBox.die('Sprints', "No sprint with ID <b>%d</b>" % id)
	elif not sprint.canView(handler.session['user']):
		ErrorBox.die('Private', "You must be a sprint member to view this sprint")
	tasks = sprint.getTasks(includeDeleted = True)

	handler.title(sprint.safe.name)
	drawNavArrows(sprint, handler.session['user'], 'history')

	Chart.include()
	chart = TaskChart('chart', sprint.getTasks())
	chart.js()
	print "<script type=\"text/javascript\">"
	tasksByAssigned = {member.username: [task.id for task in tasks if member in task.assigned] for member in sprint.members}
	print "var tasks_by_assigned = %s;" % toJS(tasksByAssigned)
	print "$(document).ready(function() {"
	if assigned:
		print "    $('%s').addClass('selected');" % ', '.join("#filter-assigned a[assigned=\"%s\"]" % username for username in assigned.split(','))
	print "    setup_filter_buttons();"
	print "    apply_filters();"
	print "});"
	print "</script>"

	print tabs(sprint, 'history')
	if len(tasks) == 0:
		print ErrorBox("This sprint has no tasks")
		print "<br>"
		return

	print "<div id=\"filter-assigned\">"
	print "<a class=\"fancy danger\" href=\"#\"><img src=\"/static/images/cross.png\">&nbsp;None</a>"
	for member in sorted(sprint.members):
		print "<a class=\"fancy\" assigned=\"%s\" href=\"/sprints/%d/history?assigned=%s\"><img src=\"%s\">&nbsp;%s</a>" % (member.username, id, member.username, member.getAvatar(16), member.username)
	print "</div><br>"

	chart.placeholder()
	showHistory(tasks, True)
	print "<br>"
コード例 #18
0
ファイル: Slide.py プロジェクト: AlexRArmstrong/Optichart
	def setChartName(self, chart_name):
		'''
		Takes the path to a chart file and creates a chart object. Additionally
		sets the chart name variable.
		'''
		try:
			self._chart_name = chart_name
			self._chart = Chart(chart_name)
			return True
		except:
			return False
コード例 #19
0
def get_frame_data(info):
    # load data
    def map_depth(item):
        result = ",".join([
            str(round(map_range(item[0], info.frame_time - 60, info.frame_time, 0, 100), 3)),
            str(round(map_range(item[1], map_depth.start, map_depth.end, 0, 100), 3))
        ])

        # print("{0} became {1}".format(item, result))
        return result

    depth_data = data_manager.select_depths(info.frame_time - 60, info.frame_time)

    if len(depth_data) > 0:
        map_depth.start = depth_data[-1][1] - 50
        map_depth.end = depth_data[-1][1] + 50
        depth_text = "{0:0.2f} ft".format(depth_data[-1][1])
        depth_path_data = "M" + " ".join(map(map_depth, depth_data))
    else:
        depth_text = "-- ft"
        depth_path_data = ""

    def map_temperature(item):
        result = ",".join([
            str(round(map_range(item[0], info.frame_time - 60, info.frame_time, 0, 100), 3)),
            str(round(map_range(item[1], 40, 55, 100, 0), 3))
        ])

        # print("{0} became {1}".format(item, result))
        return result

    temperature_data = data_manager.select_temperatures(info.frame_time - 60, info.frame_time)

    if len(temperature_data) > 0:
        temperature_text = "{0:0.2f} °F".format(temperature_data[-1][1])
        temperature_path_data = "M" + " ".join(map(map_temperature, temperature_data))
    else:
        temperature_text = "-- °F"
        temperature_path_data = ""

    # for testing
    depth_chart = Chart("Depth", depth_text, depth_path_data)
    depth_chart.x = 5
    depth_chart.y = 972 - 5 - 110

    temperature_chart = Chart("Temperature", temperature_text, temperature_path_data)
    temperature_chart.x = 5 + 5 + 100 + 5 + 5
    temperature_chart.y = 972 - 5 - 110

    # print(depth_path_data)
    return Data(info.frame_time, depth_chart, temperature_chart, info.input_path)
コード例 #20
0
ファイル: main.py プロジェクト: easyDiffraction/CoDE
def calculator_test():
    """
    Test the calculator(s)
    """
    # instantiate default Calculator object
    # and define initial state
    calc = Calculator(structure=dna, wavelength=1.2)

    # calculate XRD for the structure, using defined engine
    #data_out = calc.calculateXRD(structure=diamond, engine="ASE")

    # calculate XRD for the structure, using default engine
    data_out = calc.calculateXRD()

    # create a chart object
    chart = Chart()

    # add powder data to the chart. This needs to be made such that
    # setData doesn't need a type (setData1D/setDataCrystal) but rather
    # gets set depending on the type of the argument passed
    chart.setData1D(data_out)

    # create MPL representation of the Chart object
    #mpl_chart = chart.getMplChart()
    #mpl_chart.show()

    # or just show it directly
    chart.show()
コード例 #21
0
ファイル: SprintCharts.py プロジェクト: mrozekma/Sprint
	def __init__(self, group):
		Chart.__init__(self, 'group-goals-chart')
		tasks = group.getTasks()
		goals = set(task.goal for task in tasks)

		self.title.text = ''
		self.plotOptions.pie.dataLabels.enabled = True
		self.tooltip.formatter = "function() {return this.point.name + ': '+ this.point.x + (this.point.x == 1 ? ' task' : ' tasks') + ' (' + this.y + '%)';}"
		self.credits.enabled = False
		self.series = [{
			'type': 'pie',
			'name': 'Sprint Goals',
			'data': [{
				'name': goal.name if goal else 'Other',
				'color': goal.getHTMLColor() if goal else '#ccc',
				'x': sum(task.goal == goal or False for task in tasks)
			} for goal in goals]
		}]

		# Percentages
		for m in self.series[0].data.get():
			m['y'] = float("%2.2f" % (m['x'] * 100 / len(tasks)))
コード例 #22
0
ファイル: SprintCharts.py プロジェクト: mrozekma/Sprint
	def __init__(self, placeholder, sprint, allTasks, revisions, **_):
		Chart.__init__(self, placeholder)
		days = [day for day in sprint.getDays()]
		now = Weekday.today()
		futureStarts = minOr(filter(lambda day: day > now, days), None)
		futureIndex = days.index(futureStarts) if futureStarts else None

		self.chart.defaultSeriesType = 'line'
		self.chart.zoomType = 'x'
		self.title.text = ''
		self.tooltip.shared = True
		self.credits.enabled = False
		with self.xAxis as xAxis:
			xAxis.tickmarkPlacement = 'on'
			xAxis.maxZoom = 1
			xAxis.title.text = 'Day'
			# Future bar
			if futureIndex:
				xAxis.plotBands = [{
					'color': '#DDD',
					'from': futureIndex - 0.75,
					'to': len(days) - 0.5
				}]
		self.yAxis.min = 0
		self.yAxis.title.text = 'Hours'
		self.series = seriesList = []

		for user in sorted(sprint.members):
			series = {
				'name': user.username,
				'data': []
			}
			seriesList.append(series)

			for day in days:
				series['data'].append(sum(t.effectiveHours() if t and user in t.assigned and not t.deleted else 0 for t in [revisions[t.id, day] for t in allTasks]))

		setupTimeline(self, sprint)
コード例 #23
0
def main():
    """Defines assets, creates portfolios, and displays a scatter plot 
    of the different portfolios"""
    s1 = Instrument(0.01, 0.01, "Asset 1", "Equity")
    s2 = Instrument(0.02, 0.02, "Asset 2", "Bond")
    s3 = Instrument(0.03, 0.03, "Asset 3", "Commodity")
    s4 = Instrument(0.04, 0.04, "Asset 4", "Equity")

    p1 = Portfolio([s1, s2])
    p2 = Portfolio([s1, s3])
    p3 = Portfolio([s1, s4])
    p4 = Portfolio([s2, s3])
    p5 = Portfolio([s2, s4])
    p6 = Portfolio([s3, s4])

    p1.addcorr([[0, -0.1]])
    p2.addcorr([[0, -0.1]])
    p3.addcorr([[0, -0.1]])
    p4.addcorr([[0, -0.1]])
    p5.addcorr([[0, -0.1]])
    p6.addcorr([[0, -0.1]])

    c = Chart([p1, p2, p3, p4, p5, p6], 0.004)
    c.scatters(size=3)
コード例 #24
0
ファイル: neugen.py プロジェクト: wsgan001/junk
def draw_chart(x, yy):
    """
	Create an svg file with 3 plots:
	 * best environment result
	 * first (previous best) environment result
	 * second (previous best) environment result

	One point on each plot after every revolution
	"""

    chart_x.append(x)
    chart1_y.append(max(yy))
    chart2_y.append(yy[0])
    chart3_y.append(yy[1])

    chart = Chart.LineChart(chart_x, chart1_y, chart2_y, chart3_y)
コード例 #25
0
def gender_favorite(top_k, sex='M'):
    docs = table.aggregate([{
        '$match': {
            'gender': sex
        }
    }, {
        '$unwind': '$labels'
    }, {
        '$group': {
            '_id': {
                'label': '$labels'
            },
            'count': {
                '$sum': 1
            }
        }
    }, {
        '$sort': {
            'count': -1
        }
    }])
    number_arr = []
    count_arr = []
    labels = []
    docs = [doc for doc in docs]
    for doc in docs[:top_k]:
        count_arr.append(doc['count'])
        labels.append(doc['_id']['label'])

    chart = Chart(100, 180)
    chart.bar(count_arr,
              top_k,
              labels,
              "The Top {0} females' favorite disciplines".format(top_k),
              'discipline',
              'researcher number',
              True,
              log=False,
              fontsize=120)
    chart.save(chart_path + '/{1}_favorite_{0}'.format(top_k, sex),
               format='eps')
    chart.clear()
コード例 #26
0
def year_distribution(start, end):
    os.mkdir(chart_path) if not os.path.exists(chart_path) else ''
    pubs_per_year = [0 for x in range(start, end)]
    citation_per_year = [0 for x in range(start, end)]
    # print(pubs_per_year)
    year_labels = [str(x) for x in range(start, end)]
    docs = copy.find({}, {'pubs': 1})
    for doc in docs:
        for pub in doc['pubs']:
            if pub['year'] == '':
                continue
            year = int(pub['year'])
            index = year - start
            if 0 > index or index >= end - start:
                continue
            try:
                pubs_per_year[index] += 1
                if pub['citation'].isdigit():
                    citation_per_year[index] += int(pub['citation'])
            except Exception as e:
                print(pub['citation'])
                print(len(pub['citation']))
                print(index)
                sys.exit()

    # pubs_per_year = [year/1000 for year in pubs_per_year]
    chart = Chart(50, 50)
    chart.bar(citation_per_year,
              end - start,
              year_labels,
              'publication number per year',
              'year',
              'number',
              log=False,
              fontsize=10)
    # chart.bar(pubs_per_year,end-start,year_labels,'publication number per year','year','number',log=False,fontsize=10)
    chart.save('pub_per_year', format='png')
    chart.show()
コード例 #27
0
ファイル: main.py プロジェクト: easyDiffraction/CoDE
def chart_test():

    chart_exp = Chart(filename=some_exp_chart)
コード例 #28
0
def discipline_proportion(top_k):
    docs = table.aggregate([{
        '$match': {
            'gender': {
                '$exists': 1
            }
        }
    }, {
        '$unwind': '$labels'
    }, {
        '$group': {
            '_id': {
                'label': '$labels'
            },
            'count': {
                '$sum': 1
            }
        }
    }, {
        '$sort': {
            'count': -1
        }
    }])

    docs = [doc for doc in docs]
    # print(docs[:10])
    total = table.count({'gender': {'$exists': 1}})
    count_arr = [doc['count'] for doc in docs[:top_k]]
    proportion_arr = [doc['count'] / total for doc in docs[:top_k]]

    cumulative_arr = []
    c = 0
    for i in proportion_arr:
        c += i
        cumulative_arr.append(c)

    labels = [doc['_id']['label'] for doc in docs[:top_k]]

    # chart = Chart()
    # print(len(labels))
    # print(len(arr))
    # chart.pie([arr],'test',labels)
    # chart.show()
    # chart.single_unnomarlized_CDF(arr,'disciplines CDF','disciplines','percentage')
    # chart.save(chart_path+'cdf.eps')

    # s = ''
    # print(np.median())
    # for label in labels:
    # 	s = s+label+', '
    # print(s)

    # os.mkdir(chart_path) if not os.path.exists(chart_path) else ''
    chart = Chart(100, 150)
    # chart.bar(count_arr,top_k,labels,'The Top {0} popular disciplines'.format(top_k),'discipline','researcher number',True,log=False,fontsize=100)
    # chart.show()
    # chart.save(chart_path+'/number_{0}'.format(top_k),format='eps')
    # chart.clear()

    chart.bar(cumulative_arr,
              top_k,
              labels,
              'Cumulative propotion of most popular disciplines',
              'discipline',
              'propotion',
              True,
              log=False,
              fontsize=100)
    chart.save(chart_path + '/cumulative_{0}'.format(top_k), format='eps')
    chart.clear()
コード例 #29
0
ファイル: groups.py プロジェクト: mrozekma/Sprint
def editGroup(handler, id):
	requirePriv(handler, 'User')
	handler.title('Manage Group')

	id = int(id)
	group = Group.load(id)
	if not group:
		ErrorBox.die('Invalid Group', "No group with ID <b>%d</b>" % id)
	tasks = group.getTasks()

	chart = GroupGoalsChart(group)
	Chart.include()
	chart.js()

	print "<style type=\"text/css\">"
	print "table.list td.left {position: relative; top: 4px;}"
	print "table.list td.right *, button {width: 400px;}"
	print "table.list td.right button {width: 200px;}" # Half of the above value
	print "</style>"

	print "<h2>Edit Group</h2>"
	print "<form method=\"post\" action=\"/groups/%d/rename\">" % id
	print "<table class=\"list\">"
	print "<tr><td class=\"left\">Name:</td><td class=\"right\"><input type=\"text\" name=\"name\" value=\"%s\">" % (group.safe.name)
	print "<tr><td class=\"left\">Predecessor:</td><td class=\"right\">"

	#TODO Waiting on group moving
	print "<select name=\"predecessor\" disabled>"
	print "<option>%s</option>" % ('None' if group.seq == 1 else Group.load(sprintid = group.sprintid, seq = group.seq-1).safe.name)
	print "</select>"

	print "</td></tr>"
	print "<tr><td class=\"left\">&nbsp;</td><td class=\"right\">"
	print Button('Save', type = 'submit').positive()
	print Button('Cancel', "/sprints/%d#group%d" % (group.sprintid, id), type = 'button').negative()
	print "</td></tr>"
	print "</table>"
	print "</form>"

	print "<h2>Assign Goal</h2>"
	print "This is a quick way to set all the tasks in the group to the same sprint goal. The current breakdown is:"
	chart.placeholder()

	# The default is whichever goal currently has the most occurrences
	defaultGoal = max((sum(task.goal == goal or False for task in tasks), goal) for goal in group.sprint.getGoals() + [None])[1]

	print "<form method=\"post\" action=\"/groups/%d/goal\">" % id
	for goal in group.sprint.getGoals():
		if goal.name:
			print "<input type=\"radio\" id=\"goal%d\" name=\"goal\" value=\"%d\"%s>&nbsp;<label for=\"goal%d\"><img class=\"bumpdown\" src=\"/static/images/tag-%s.png\">&nbsp;%s</label><br>" % (goal.id, goal.id, ' checked' if goal == defaultGoal else '', goal.id, goal.color, goal.name)
	print "<input type=\"radio\" id=\"goal0\" name=\"goal\" value=\"0\"%s>&nbsp;<label for=\"goal0\"><img class=\"bumpdown\" src=\"/static/images/tag-none.png\">&nbsp;Other</label><br><br>" % ('' if defaultGoal else ' checked')
	print Button('Assign', type = 'submit').positive()
	print "</form>"

	print "<h2>Delete Group</h2>"
	if len(group.sprint.getGroups()) == 1:
		print "You can't delete the last group in a sprint"
	elif not group.deletable:
		print "This group is undeletable"
	else:
		print "<form method=\"post\" action=\"/groups/%d/delete\">" % id
		if len(tasks):
			print "This group has %d %s. Move %s to the <select name=\"newGroup\">" % (len(tasks), 'task' if len(tasks) == 1 else 'tasks', 'it' if len(tasks) == 1 else 'them')
			for thisGroup in group.sprint.getGroups('name'):
				if group == thisGroup: continue
				print "<option value=\"%d\">%s</option>" % (thisGroup.id, thisGroup.safe.name)
			print "<option value=\"0\">None (delete)</option>"
			print "</select> group<br><br>"
		print Button('Delete', type = 'submit')
		print "</form>"
コード例 #30
0
ファイル: ChartConf.py プロジェクト: sedjrodonan/lositan
        self.balPanel = self.createColorPanel(chart.balColor, pane)

        self.add(JLabel('Label candidate selected loci'))
        self.selLabel = JCheckBox()
        self.selLabel.setSelected(chart.labelSelected)
        self.add(self.selLabel)
        self.add(JLabel('Label candidate neutral loci'))
        self.neuLabel = JCheckBox()
        self.neuLabel.setSelected(chart.labelNeutral)
        self.add(self.neuLabel)

        change = JButton('Change')
        change.setActionCommand('Change')
        change.addActionListener(self)
        pane.add(change)
        exit = JButton('Exit')
        exit.setActionCommand('Exit')
        exit.addActionListener(self)
        pane.add(exit)
        self.pack()


if __name__ == '__main__':
    frame = JFrame("Selection Workbench")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    chart = Chart(300, 200)
    cc = ChartConf(frame, chart, None)
    frame.pack()
    frame.setVisible(1)
    cc.show()
コード例 #31
0
def gender_ratio(top_k):
	top_n = researcher.aggregate([
		{'$match':{'gender':{'$exists':1}}},
		{'$unwind':'$labels'},
		{'$group':{
		'_id':{'label':'$labels'},
		'count':{'$sum':1}
		}},
		{'$sort':{'count':-1}}])
	label_ratios = []
	labels = []
	ratios = []
	top_n = [x['_id']['label'] for x in top_n][:top_k]
	for discipline in top_n:
		male_size = researcher.count({'gender':'M','labels':discipline})
		female_size = researcher.count({'gender':'F','labels':discipline})
		# ratio = female_size/male_size
		ratio = male_size/female_size
		label_ratios.append((discipline,ratio))
		labels.append(discipline)
		ratios.append(ratio)

	chart = Chart(top_k/3,top_k/2)
	chart.bar(ratios,top_k,labels,'Gender Ratio in Top %s Disciplines'%top_k,'discipline','ratio',True,log=False,fontsize=top_k/2)
	chart.save(charts_path+'/gender_ratio_top_{0}.eps'.format(top_k))
	chart.clear()
	chart.close()

	label_ratios.sort(key=lambda x:x[1],reverse=True)
	labels = [x[0] for x in label_ratios]
	ratios = [x[1] for x in label_ratios]

	chart = Chart(100,180)
	chart.bar(ratios,top_k,labels,'Ranked Gender Ratio in Top %s Disciplines'%top_k,'discipline','ratio',True,log=False,fontsize=120)
	chart.save(charts_path+'/ranked_gender_ratio_top_{0}'.format(top_k),format='eps')
	chart.clear()
	chart.close()
コード例 #32
0
ファイル: Slide.py プロジェクト: AlexRArmstrong/Optichart
class Slide(object):
	'''
	The text of a chart layed out and rendered.
	'''
	def __init__(self, chart_name = None):
		'''
		Initilize a Slide Class. Call Slide([chart-name]) to create a Slide
		object.  Optionally passing a fully pathed chart name.
		'''
		# These variables are created in Slide.
		# The chart object to display.
		self._chart = None
		self._chart_name = ''
		if chart_name:
			self.setChartName(chart_name)
		# The coordinates of pages breaks.
		self._pages = [[0, 0]]
		# TODO: def chrs. ???
		self._default_characters = []
		# The text of the chart layed out and rendered.
		self._surface = None
		
		# These variables must be set before calling slide.layout()
		# The width and height of the slide display surface.
		self._width = 0 # Pixels
		self._height = 0 # Pixels
		# Fonts.
		self._default_font = ''
		self._font_dir = ''
		# Factors for size calculations.
		self._dpi = 72 # dots/inch
		self._lane_length = 240 # inches
		
		
	def chart(self):
		'''
		Returns a chart object.
		'''
		return self._chart
	
	def chartName(self):
		'''
		Return the current chart name.
		'''
		return self._chart_name
	
	def setChartName(self, chart_name):
		'''
		Takes the path to a chart file and creates a chart object. Additionally
		sets the chart name variable.
		'''
		try:
			self._chart_name = chart_name
			self._chart = Chart(chart_name)
			return True
		except:
			return False
	
	def pageCoordinates(self):
		'''
		Return a list of the (x,y) coordinates of the page breakes.
		'''
		return self._pages
	
	def defaultCharacters(self):
		'''
		Return a list of the default characters coordinates and size information.
		The line scale factor (ie. 1.25 - the Snellen ratio divided out). Also 
		included is the width of a character and the space between characters on that line.
		Data Structure:
		list = [[x, y, line scale factor, character width, space width],
				[x, y, scale factor, chr width, space width]]
		'''
		return self._default_characters
	
	def surface(self):
		'''
		Returns the rendered surface.
		'''
		return self._surface
		# TODO: Maybe calling layout() should return the rendered surface?
	
	def slideWidth(self):
		'''
		Returns the slide width in pixels.
		'''
		return self._width
	
	def setSlideWidth(self, w):
		'''
		Set the width for the slide to w. This is the
		slide's display area in inches.  If using a custom dpi,
		Must call setDpi first - else will have the default 72 dpi.
		Returns True on succes, False otherwise.
		'''
		try:
			w_px = w * self._dpi
			self._width = int(w_px)
			return True
		except:
			return False
	
	def slideHeight(self):
		'''
		Returns the height of the slide in pixels.
		'''
		return self._height
	
	def setSlideHeight(self, h):
		'''
		Set the height of the slides display area to h.
		Takes the height in inches to set.
		Returns True on succes, False otherwise.
		'''
		try:
			h_px = h * self._dpi
			self._height = int(h_px)
			return True
		except:
			return False
	def dpi(self):
		'''
		Returns the slide's current dpi.
		'''
		return self._dpi
	
	def setDpi(self, dpi):
		'''
		Set the dpi for the slide.
		Returns True on succes, False otherwise.
		'''
		try:
			self._dpi = dpi
			return True
		except:
			return False
	
	def laneLength(self):
		'''
		Return the length of the lane for this slide.
		'''
		return self._lane_length
	
	def setLaneLength(self, length):
		'''
		Set the lane length for the slide.
		Returns True on succes, False otherwise.
		'''
		try:
			self._lane_length = int(length)
			return True
		except:
			return False
	
	def defaultFont(self):
		'''
		Return the default font used by this slide.
		'''
		return self._default_font
	
	def setDefaultFont(self, font_name):
		'''
		Sets the default font to use for this slide.
		Returns True on succes, False otherwise.
		'''
		try:
			self._default_font = font_name
			return True
		except:
			return False
	
	def fontDirectory(self):
		'''
		Returns the directory searched for fonts.
		'''
		return self._font_dir
	
	def setFontDirectory(self, font_dir):
		'''
		Sets the directory containing the fonts to 'font_dir'.
		Returns True on succes, False otherwise.
		'''
		try:
			self._font_dir = font_dir
			return True
		except:
			return False
	
	def fixFontName(self, font_name):
		'''
		Takes a font name and fixes the path so it can be used with pygame.
		Returns the full path name of the font.
		'''
		import os.path
		# First check to see if we have a font specified or should use default.
		if not font_name:
			return os.path.join(self._font_dir, self._default_font)
		elif os.path.isabs(font_name):
			return font_name
		elif os.path.exists(os.path.join(self._font_dir, font_name)):
			return os.path.join(self._font_dir, font_name)
		else:
			return os.path.join(self._font_dir, self._default_font)
	
	def calculateSize(self, lane_length, scale_factor, dpi):
		'''
		Calculates the vertical size for a letter with a given scale factor at
		a distance on a specified resoulation monitor.
		'''
		# TODO: Question? Should this be here or part of a line?
		vertical_inch_size = float(lane_length) * math.tan(math.radians(5.0 / 60.0)) * float(scale_factor)
		vertical_dpi_size = vertical_inch_size * dpi
		return vertical_dpi_size	
	
	def layout(self):
		'''
		Lays out the currently set chart.
		This needs to be called before trying to display the anything.
		Does display layout and renders the text onto a big surface.  Also
		checks for pages and default characters while doing this.
		'''
#		# Clear per slide/chart variables.
		self._pages = [[0, 0]]
		self._default_characters = []
		self._surface = None
		
		all_rendered_lines = []
		all_lines = self._chart.lines()
		page_numbers = self._chart.pages()
		slide_width = self._width # the width of the slide display area from config file.
		lane_length = self._lane_length
		dpi = self._dpi
		
		for line_no, current_line in enumerate(all_lines):
			line_font = current_line.font()
			full_font_name = self.fixFontName(line_font)
			num_sections = len(current_line.sections())
			all_section_widths = current_line.columnSizes()
			sect_x = 0
			sect_y = 0
			all_rendered_sections = []
			line_height = 0
			default_chr_position = 0
			for i, each_section in enumerate(current_line.sections()):
				# Figure the current section width.
				section_width = slide_width * all_section_widths[i] / 100
				# Get the scaling factor and calculate the size in pixels
				scale_factor = each_section.scaleFactor()
				line_size = self.calculateSize(lane_length, scale_factor, dpi)
				# Create a font.
				section_font = pygame.font.Font(full_font_name, int(line_size))
				# Get the text for this section.
				text = each_section.text()
				# Calculate the spacing of the letters for this section.
				num_chrs = len(text)
				text_width, text_height = section_font.size(text)
				chr_width = text_width / num_chrs
				space_width = (section_width - text_width) / (num_chrs + 1.0)
				# Create a surface for this section.
				section_surface = pygame.Surface([section_width, text_height])
				section_surface.fill(WHITE)
				# Keep track of how big the line is - different sections will change this.
				if text_height > line_height:
					line_height = text_height
				# Render each character onto a surface at the correctly spaced position.
				x_pos = 0
				y_pos = 0
				x_pos += space_width
				for each_chr in text:
					chr_surface = section_font.render(each_chr, True, BLACK, NOTBLACK)
					chr_surface.set_colorkey(NOTBLACK)
					chr_position = [x_pos, y_pos]
					section_surface.blit(chr_surface, chr_position)
					# Check for default character position.
					if default_chr_position == current_line.defaultCharacterPosition():
						self._default_characters.append([x_pos, y_pos, scale_factor, chr_width, space_width])
					x_pos = x_pos + chr_width + space_width
					default_chr_position += 1
				all_rendered_sections.append(section_surface)
			# Now blit all the section surfaces onto a line surface.
			line_surface = pygame.Surface([slide_width, line_height])
			line_surface.fill(WHITE)
			for i, each_sect_surf in enumerate(all_rendered_sections):
				# Get the correct width for this section.
				section_width = slide_width * all_section_widths[i] / 100
				sect_y = (line_surface.get_height() - each_sect_surf.get_height()) / 2.0
				section_position = [sect_x, sect_y]
				line_surface.blit(each_sect_surf, section_position)
				sect_x += section_width
			all_rendered_lines.append(line_surface)
		
		# Find the total height of the chart.
		total_chart_heigh_px = 0
		total_chart_width_px = 0
		num_lines = range(len(all_rendered_lines))
		for i in num_lines:
			cur_ren_line = all_rendered_lines[i]
			ln_width, ln_height = cur_ren_line.get_size()
			# Calculate the space between each line - can vary per line.
			scale_factor = all_lines[i].lineSpaceingScaleFactor()
			line_spaceing = self.calculateSize(lane_length, scale_factor, dpi)
			total_chart_heigh_px = total_chart_heigh_px + ln_height + line_spaceing
				
		# Make a big surface to hold all the lines.
		#total_size = [total_chart_width_px, total_chart_heigh_px]
		total_size = [slide_width, total_chart_heigh_px]
		self._surface = pygame.Surface(total_size)
		self._surface.fill(WHITE)
		
		# Now render all the text to the big surface.
		position = [slide_width / 2, 0]
		for line_no, each_line in enumerate(all_rendered_lines):
			x_r, y_r = each_line.get_size()
			position[0] = position[0] - (x_r / 2)
			self._surface.blit(each_line, position)
			# Y for def chrs.
			self._default_characters[line_no][1] = position[1]
			# Figure out the coordinates for the page breaks.
			if line_no in page_numbers:
				x = 0
				y = position[1]
				pg_coords = [x, y]
				self._pages.append(pg_coords)
			# Find the line spaceing for this line.
			scale_factor = all_lines[line_no].lineSpaceingScaleFactor()
			line_spaceing = self.calculateSize(lane_length, scale_factor, dpi)
			# Incriment the position for the next line.
			position[0] = slide_width / 2
			position[1] += y_r + line_spaceing
コード例 #33
0
ファイル: SprintCharts.py プロジェクト: mrozekma/Sprint
	def __init__(self, placeholder, sprint, allTasks, revisions, **_):
		Chart.__init__(self, placeholder)
		days = [day for day in sprint.getDays()]
		now = Weekday.today()
		futureStarts = minOr(filter(lambda day: day > now, days), None)
		futureIndex = days.index(futureStarts) if futureStarts else None

		self.chart.defaultSeriesType = 'line'
		self.chart.zoomType = 'x'
		self.title.text = ''
		self.plotOptions.line.dataLabels.enabled = True
		self.tooltip.shared = True
		self.credits.enabled = False
		with self.xAxis as xAxis:
			xAxis.tickmarkPlacement = 'on'
			xAxis.maxZoom = 1
			xAxis.title.text = 'Day'
			# Future bar
			if futureIndex is not None:
				xAxis.plotBands = [{
					'color': '#DDD',
					'from': futureIndex - 0.75,
					'to': len(days) - 0.5
				}]
		self.yAxis.min = 0
		self.yAxis.title.text = 'Hours'
		self.series = seriesList = []

		taskSeries = {
			'id': 'taskSeries',
			'name': 'Tasking',
			'data': [],
			'color': '#4572a7',
			'zIndex': 2
		}
		seriesList.append(taskSeries)

		availSeries = {
			'name': 'Availability',
			'data': [],
			'color': '#aa4643',
			'zIndex': 2
		}
		seriesList.append(availSeries)

		flagSeries = {
			'type': 'flags',
			'data': [],
			'color': '#4572a7',
			'shape': 'flag',
			'onSeries': 'taskSeries',
			'showInLegend': False,
			'y': 16
		}
		seriesList.append(flagSeries)

		if futureIndex == 0:
			futureIndex = 1

		statusToday, hoursToday = None, None
		for day in days[:futureIndex]:
			tasksToday = [revisions[t.id, day] for t in allTasks]
			statusYesterday, hoursYesterday = statusToday, hoursToday
			statusToday = {t: t.status for t in tasksToday if t and not t.deleted}
			hoursToday = {t: t.manHours() for t in tasksToday if t and not t.deleted}
			taskSeries['data'].append(sum(hoursToday.values()))

			if hoursYesterday:
				hoursDiff = {t: hoursToday.get(t, 0) - hoursYesterday.get(t, 0) for t in hoursToday}
				largeChanges = [t for t, h in hoursDiff.iteritems() if abs(h) >= 16]
				if largeChanges:
					texts = []
					for t in largeChanges:
						if t not in hoursYesterday:
							texts.append("<span style=\"color: #f00\">(New +%d)</span> %s" % (t.effectiveHours(), t.name))
						elif hoursDiff[t] > 0:
							texts.append("<span style=\"color: #f00\">(+%d)</span> %s" % (hoursDiff[t], t.name))
						else:
							if t.status in ('in progress', 'not started'):
								texts.append("<span style=\"color: #0a0\">(%d)</span> %s" % (hoursDiff[t], t.name))
							elif t.status == 'complete':
								texts.append("<span style=\"color: #0a0\">(Complete %d)</span> %s" % (hoursDiff[t], t.name))
							else:
								texts.append("<span style=\"color: #999\">(%s %d)</span> %s" % (statuses[t.status].getRevisionVerb(statusYesterday.get(t, 'not started')), hoursDiff[t], t.name))
					flagSeries['data'].append({'x': days.index(day), 'title': alphabet[len(flagSeries['data']) % len(alphabet)], 'text': '<br>'.join(texts)})

		avail = Availability(sprint)
		for day in days:
			availSeries['data'].append(avail.getAllForward(day))

		setupTimeline(self, sprint, ['Projected tasking'])

		# Add commitment percentage to the axis label
		labels = self.xAxis.categories.get()
		for i in range(len(labels)):
			# For future percentages, use today's hours (i.e. don't use the projected hours)
			needed = taskSeries['data'][min(i, futureIndex - 1) if futureIndex else i][1]
			thisAvail = availSeries['data'][i][1]
			pcnt = "%d" % (needed * 100 / thisAvail) if thisAvail > 0 else "inf"
			labels[i] += "<br>%s%%" % pcnt
		self.xAxis.categories = labels
		self.xAxis.labels.formatter = "function() {return this.value.replace('inf', '\u221e');}"

		# Trendline
		data = self.series[0].data.get()
		dailyAvail = dict((day, avail.getAll(day)) for day in days)
		totalAvail = 0
		for daysBack in range(1, (futureIndex or 0) + 1):
			midPoint = [futureIndex - daysBack, data[futureIndex - daysBack][1]]
			if dailyAvail[days[midPoint[0]]] > 0:
				daysBack = min(daysBack + 2, futureIndex)
				startPoint = [futureIndex - daysBack, data[futureIndex - daysBack][1]]
				totalAvail = sum(dailyAvail[day] for day in days[startPoint[0] : midPoint[0]])
				break

		if totalAvail > 0 and startPoint[0] != midPoint[0]:
			slope = (midPoint[1] - startPoint[1]) / (midPoint[0] - startPoint[0])
			slopePerAvail = slope * (midPoint[0] - startPoint[0]) / totalAvail
			points, total = [], midPoint[1]
			total = taskSeries['data'][futureIndex - 1][1]
			points.append([futureIndex - 1, total])
			for i in range(futureIndex, len(days)):
				total += slopePerAvail * dailyAvail[days[i]]
				points.append([i, total])
			seriesList.append({
				'name': 'Projected tasking',
				'data': points,
				'color': '#666',
				'dataLabels': {'formatter': "function() {return (this.point.x == %d) ? parseInt(this.y, 10) : null;}" % (len(days) - 1)},
				'marker': {'symbol': 'circle'},
				'zIndex': 1
			})
コード例 #34
0
ファイル: Charts.py プロジェクト: mrozekma/spades
	def __init__(self, placeholder, game):
		Chart.__init__(self, placeholder)

		teams = game.teams
		# This is O(n log n) internally out of laziness; it could be O(n) if we calculated the round scores manually with round.scoreChange instead of round.score
		# We skip the active round as it has no score change (it will show as the same score as the previous round)
		scores = [{team: 0 for team in teams}] + [round.score for round in game.rounds if round.finished]

		self.chart.type = 'line'
		self.chart.marginTop = 30
		self.title.text = ''
		self.tooltip.shared = True
		self.plotOptions.line.dataLabels.enabled = True
		self.xAxis.categories = [''] + ["Round %d" % (i + 1) for i in range(len(game.rounds))]
		self.yAxis.title.enabled = False
		self.yAxis.plotLines = [{
			'value': game.goal,
			'color': '#0a0',
			'width': 2,
		}]

		# Largest score seen or goal score, rounded up to next multiple of 100
		self.yAxis.max = int(ceil(max(max(max(*score.values()) for score in scores), game.goal) / 100.)) * 100

		# Show a line every 100 points, unless the score is gigantic; then just let highcharts choose automatically
		if game.goal <= 1000:
			self.yAxis.tickInterval = 100

		flags = {team: [] for team in teams}
		flagSeries = [{
			'type': 'flags',
			'data': data,
			'color': '#4572a7',
			'shape': 'flag',
			'onSeries': '/'.join(team),
			'showInLegend': False,
			'shape': 'squarepin',
			'y': -50,
		} for team, data in flags.iteritems()]

		for team in teams:
			bags = 0
			for i, round in enumerate(game.rounds):
				if not round.finished:
					continue
				toShow = []
				bids = [round.bidsByPlayer[player] for player in team]
				taken = [len(round.tricksByWinner[player]) for player in team]
				for player, bid, took in zip(team, bids, taken):
					if bid in ('nil', 'blind'):
						toShow.append(('N', "%s %s %s" % (player, 'made' if took == 0 else 'failed', 'nil' if bid == 'nil' else 'blind nil')))
				thisBags = sum(taken) - sum(map(bidValue, bids))
				if thisBags > 0:
					bags += thisBags
					if bags >= game.bagLimit:
						bags %= game.bagLimit
						toShow.append(('B', 'Bagged out'))
				if toShow:
					flags[team].append({'x': i + 1, 'title': ','.join(title for title, text in toShow), 'text': '<br>'.join(text for title, text in toShow)})

		self.series = [{'id': '/'.join(team), 'name': game.teamNames[team], 'data': [score[team] for score in scores]} for team in teams] + flagSeries
		self.series[0]['color'] = '#a00';
		self.series[1]['color'] = '#00a';
コード例 #35
0
ファイル: gui.py プロジェクト: tahhan/imageProc
    def setupUi(self, MainWindow):
        MainWindow.showMaximized()
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        # MainWindow.resize(1014, 682)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))

        self.gridLayout_4 = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))

        self.frame_2 = QtGui.QFrame(self.centralwidget)
        self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_2.setObjectName(_fromUtf8("frame_2"))

        self.gridLayout_3 = QtGui.QGridLayout(self.frame_2)
        self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))

        self.scrollArea_2 = QtGui.QScrollArea(self.frame_2)
        self.scrollArea_2.setWidgetResizable(True)
        self.scrollArea_2.setObjectName(_fromUtf8("scrollArea_2"))

        self.scrollAreaWidgetContents_2 = QtGui.QWidget()
        self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 459, 448))
        self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8("scrollAreaWidgetContents_2"))

        self.gridLayout_6 = QtGui.QGridLayout(self.scrollAreaWidgetContents_2)
        self.gridLayout_6.setObjectName(_fromUtf8("gridLayout_6"))

        self.modifided_image = ImageWidget(self.scrollAreaWidgetContents_2)
        self.modifided_image.setObjectName(_fromUtf8("modifided_image"))

        self.gridLayout_6.addWidget(self.modifided_image, 0, 0, 1, 1)

        self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)

        self.gridLayout_3.addWidget(self.scrollArea_2, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.frame_2, 0, 1, 1, 1)

        self.frame = QtGui.QFrame(self.centralwidget)
        self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName(_fromUtf8("frame"))

        self.gridLayout_2 = QtGui.QGridLayout(self.frame)
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))

        self.scrollArea = QtGui.QScrollArea(self.frame)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName(_fromUtf8("scrollArea"))

        self.scrollAreaWidgetContents = QtGui.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 459, 448))
        self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))

        self.gridLayout_5 = QtGui.QGridLayout(self.scrollAreaWidgetContents)
        self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5"))

        self.original_image = ImageWidget(self.scrollAreaWidgetContents)
        self.original_image.setObjectName(_fromUtf8("original_image"))

        self.gridLayout_5.addWidget(self.original_image, 0, 0, 1, 1)

        self.scrollArea.setWidget(self.scrollAreaWidgetContents)

        self.gridLayout_2.addWidget(self.scrollArea, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.frame, 0, 0, 1, 1)

        MainWindow.setCentralWidget(self.centralwidget)

        self.dockWidget = QtGui.QDockWidget(MainWindow)
        self.dockWidget.setObjectName(_fromUtf8("dockWidget"))
        self.dockWidget.setFloating(True)
        self.dockWidget.setGeometry(QtCore.QRect(0, 0, 620, 220))

        self.dockWidgetContents = QtGui.QWidget()
        self.dockWidgetContents.setObjectName(_fromUtf8("dockWidgetContents"))

        self.horizontalLayout = QtGui.QHBoxLayout(self.dockWidgetContents)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))

        self.frame_4 = QtGui.QFrame(self.dockWidgetContents)
        self.frame_4.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_4.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_4.setObjectName(_fromUtf8("frame_4"))

        self.gridLayout_8 = QtGui.QGridLayout(self.frame_4)
        self.gridLayout_8.setObjectName(_fromUtf8("gridLayout_8"))

        self.original_histogram = Chart(self.frame_4)
        self.original_histogram.setObjectName(_fromUtf8("original_histogram"))

        self.gridLayout_8.addWidget(self.original_histogram, 0, 0, 1, 1)

        self.horizontalLayout.addWidget(self.frame_4)

        self.frame_3 = QtGui.QFrame(self.dockWidgetContents)
        self.frame_3.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_3.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_3.setObjectName(_fromUtf8("frame_3"))

        self.gridLayout_7 = QtGui.QGridLayout(self.frame_3)
        self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7"))

        self.modifided_histogram = Chart(self.frame_3)
        self.modifided_histogram.setObjectName(_fromUtf8("modifided_histogram"))

        self.gridLayout_7.addWidget(self.modifided_histogram, 0, 0, 1, 1)

        self.horizontalLayout.addWidget(self.frame_3)

        self.dockWidget.setWidget(self.dockWidgetContents)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(8), self.dockWidget)

        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1014, 22))
        self.menubar.setObjectName(_fromUtf8("menubar"))

        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))

        self.menuOperations = QtGui.QMenu(self.menubar)
        self.menuOperations.setObjectName(_fromUtf8("menuOperations"))
        self.menuOperations.setEnabled(False)

        self.menuHistogram_Modification = QtGui.QMenu(self.menuOperations)
        self.menuHistogram_Modification.setObjectName(_fromUtf8("menuHistogram_Modification"))

        self.menuSlide_Histogram = QtGui.QMenu(self.menuHistogram_Modification)
        self.menuSlide_Histogram.setObjectName(_fromUtf8("menuSlide_Histogram"))

        self.menuMapping_Equations = QtGui.QMenu(self.menuOperations)
        self.menuMapping_Equations.setObjectName(_fromUtf8("menuMapping_Equations"))

        self.menuLocal_Mask_Operations = QtGui.QMenu(self.menuOperations)
        self.menuLocal_Mask_Operations.setObjectName(_fromUtf8("menuLocal_Mask_Operations"))

        self.menuSegmentation = QtGui.QMenu(self.menuOperations)
        self.menuSegmentation.setObjectName(_fromUtf8("menuSegmentation"))

        MainWindow.setMenuBar(self.menubar)

        self.actionOpen = QtGui.QAction(MainWindow)
        self.actionOpen.setObjectName(_fromUtf8("action_Open"))
        self.actionOpen.setShortcut("Ctrl+O")
        self.actionOpen.triggered.connect(self.showOpen)

        self.actionExit = QtGui.QAction(MainWindow)
        self.actionExit.setObjectName(_fromUtf8("actionExit"))
        self.actionExit.setShortcut("Ctrl+Q")
        self.actionExit.setStatusTip("Exit application")
        self.actionExit.triggered.connect(QtGui.qApp.quit)

        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionExit)

        self.actionStretch_Histogram = QtGui.QAction(MainWindow)
        self.actionStretch_Histogram.setObjectName(_fromUtf8("actionStretch_Histogram"))
        self.actionStretch_Histogram.triggered.connect(self.stretchHisto)

        self.actionShrink_Histogram = QtGui.QAction(MainWindow)
        self.actionShrink_Histogram.setObjectName(_fromUtf8("actionShrink_Histogram"))
        self.actionShrink_Histogram.triggered.connect(self.shrinkHisto)

        self.actionLeft = QtGui.QAction(MainWindow)
        self.actionLeft.setObjectName(_fromUtf8("actionLeft"))
        self.actionLeft.triggered.connect(self.slidesLeftHisto)

        self.actionRight = QtGui.QAction(MainWindow)
        self.actionRight.setObjectName(_fromUtf8("actionRight"))
        self.actionRight.triggered.connect(self.slidesRightHisto)

        self.actionHistogram_Equalization = QtGui.QAction(MainWindow)
        self.actionHistogram_Equalization.setObjectName(_fromUtf8("actionHistogram_Equalization"))
        self.actionHistogram_Equalization.triggered.connect(self.histogramEqualization)

        self.actionNegative = QtGui.QAction(MainWindow)
        self.actionNegative.setObjectName(_fromUtf8("actionNegative"))
        self.actionNegative.triggered.connect(self.negative)

        self.actionMean_Local_Filtering = QtGui.QAction(MainWindow)
        self.actionMean_Local_Filtering.setObjectName(_fromUtf8("actionMean_Local_Filtering"))
        self.actionMean_Local_Filtering.triggered.connect(self.meanFilter)

        self.actionMedian_Local_Filtering = QtGui.QAction(MainWindow)
        self.actionMedian_Local_Filtering.setObjectName(_fromUtf8("actionMedian_Local_Filtering"))
        self.actionMedian_Local_Filtering.triggered.connect(self.medianFilter)

        self.actionSobel_Edge_Detector = QtGui.QAction(MainWindow)
        self.actionSobel_Edge_Detector.setObjectName(_fromUtf8("actionSobel_Edge_Detector"))
        self.actionSobel_Edge_Detector.triggered.connect(self.edgeDetection)

        self.menuSlide_Histogram.addAction(self.actionLeft)
        self.menuSlide_Histogram.addAction(self.actionRight)

        self.menuHistogram_Modification.addAction(self.actionStretch_Histogram)
        self.menuHistogram_Modification.addAction(self.actionShrink_Histogram)
        self.menuHistogram_Modification.addAction(self.menuSlide_Histogram.menuAction())
        self.menuHistogram_Modification.addAction(self.actionHistogram_Equalization)

        self.menuMapping_Equations.addAction(self.actionNegative)

        self.menuLocal_Mask_Operations.addAction(self.actionMean_Local_Filtering)
        self.menuLocal_Mask_Operations.addAction(self.actionMedian_Local_Filtering)

        self.menuSegmentation.addAction(self.actionSobel_Edge_Detector)

        self.menuOperations.addAction(self.menuHistogram_Modification.menuAction())
        self.menuOperations.addAction(self.menuMapping_Equations.menuAction())
        self.menuOperations.addAction(self.menuLocal_Mask_Operations.menuAction())
        self.menuOperations.addAction(self.menuSegmentation.menuAction())

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuOperations.menuAction())

        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
コード例 #36
0
ファイル: SprintCharts.py プロジェクト: mrozekma/Sprint
	def __init__(self, placeholder, tasks):
		Chart.__init__(self, placeholder)

		many = isinstance(tasks, list)
		if not many:
			tasks = [tasks]
		if len(set(task.sprint for task in tasks)) > 1:
			raise Exception("All tasks must be in the same sprint")

		sprint = tasks[0].sprint if len(tasks) > 0 else None

		self.chart.defaultSeriesType = 'line'
		self.chart.zoomType = 'x'
		self.title.text = ''
		self.tooltip.shared = False
		
		# Non-shared tooltip doesn't support overlapping points, which is stupid, so for now
		# manually format the tooltip to include the hover point and any other overlapping points.
		self.tooltip.formatter = """function() { 
				// Date Header
				var tooltip = '<small>' + Highcharts.dateFormat('%A, %B %e, %Y', this.x) + '</small><br>'; 

				// Index of current X and value of Y at current X in hovered series
				var xIndex = this.series.xData.indexOf(this.point.x); 
				var yRefValue = this.point.y; 

				// Grab all series in chart
				var allSeries = this.series.chart.series; 

				// For each series, check if its Y value at current X index is overlapping with the reference Y value
				for (var i = 0; i < allSeries.length; i++) {
					var yValue = allSeries[i].yData[xIndex];

					// If there is overlap, add it to the tooltip along with the hovered value
					if (allSeries[i].visible && yValue == yRefValue) {
						// HACK: hiding meta-data (task ID) in the name and slicing it off before displaying.
						idx = allSeries[i].name.indexOf(':');
						tooltip += '<span style=\"color: ' + allSeries[i].color + '\">' + allSeries[i].name.slice(idx + 1) + '</span>: ' + yValue + (yValue == 1 ? ' hour' : ' hours') + '<br>';
					}
				}
				return tooltip; 
			}"""

		self.plotOptions.line.dataLabels.enabled = not many
		self.plotOptions.line.dataLabels.x = -10
		self.plotOptions.line.step = True
		self.legend.enabled = False
		self.credits.enabled = False
		with self.xAxis as x:
			x.type = 'datetime'
			x.dateTimeLabelFormats.day = '%a'
			x.tickInterval = 24 * 3600 * 1000
			x.maxZoom = 24 * 3600 * 1000
			if sprint:
				x.min = (sprint.start - 24*3600) * 1000
				x.max = (sprint.end - 24*3600) * 1000
			x.title.text = 'Day'
		with self.yAxis as y:
			y.min = 0
			y.tickInterval = 4
			y.minorTickInterval = 1
			y.title.text = 'Hours'

		self.series = seriesList = []
		for task in tasks:
			revs = task.getRevisions()
			series = {
				'name': "%d:%s" % (task.id, task.name) if many else 'Hours',
				'data': [],
				}
			if many:
				series['events'] = {'click': "function() {window.location = '/tasks/%d';}" % task.id}
			seriesList.append(series)

			hoursByDay = dict((tsStripHours(rev.timestamp), rev.effectiveHours()) for rev in revs)
			hoursByDay[tsStripHours(min(dateToTs(getNow()), task.historyEndsOn()))] = task.effectiveHours()
			series['data'] += [(utcToLocal(date) * 1000, hours) for (date, hours) in sorted(hoursByDay.items())]
コード例 #37
0
def declare_prefrence_distribution(discipline='all researchers'):

	male_declare = researcher.count({'gender':'M','labels.0':{'$exists':1}})
	female_declare = researcher.count({'gender':'F','labels.0':{'$exists':1}})

	female_not_declare = researcher.count({'gender':'F','labels.0':{'$exists':0}})
	male_not_declare = researcher.count({'gender':'M','labels.0':{'$exists':0}})

	chart = Chart()

	chart.pie([female_not_declare,female_declare],'Females\' preference in declaration of research domain',['not declared','declared'])
	chart.save(charts_path+'/{0}/female_declare_preference'.format(discipline))
	chart.clear()

	chart.close()

	chart = Chart()
	chart.pie([male_not_declare,male_declare],'Males\' prefrence in declaration research of domain',['not declared','declared'])
	chart.save(charts_path+'/{0}/male_declare_preference'.format(discipline))
	chart.clear()

	chart.close()
コード例 #38
0
ファイル: SprintCharts.py プロジェクト: mrozekma/Sprint
	def __init__(self, placeholder, sprint, tasks, revisions, **_):
		Chart.__init__(self, placeholder)
		days = [day for day in sprint.getDays()]
		now = Weekday.today()
		futureStarts = minOr(filter(lambda day: day > now, days), None)
		futureIndex = days.index(futureStarts) if futureStarts else None

		self.chart.type = 'waterfall'
		self.tooltip.enabled = False
		self.title.text = ''
		self.legend.enabled = False
		self.credits.enabled = False
		with self.plotOptions.series.dataLabels as labels:
			labels.enabled = True
			labels.formatter = """
function() {
	sum = 0;
	max_x = this.point.x;
	for(i in this.series.points) {
		point = this.series.points[i];
		sum += point.y;
		if(point.x == max_x) {
			break;
		}
	}
	return sum;
}
"""
			# labels.color = '#fff'
			labels.verticalAlign = 'top'
			labels.y = -20

		with self.xAxis as xAxis:
			xAxis.type = 'category'
			xAxis.tickmarkPlacement = 'on'
			xAxis.categories = [day.strftime('%a') for day in sprint.getDays()]
			# Future bar
			if futureIndex:
				xAxis.plotBands = [{
					'color': '#DDD',
					'from': futureIndex - 0.75,
					'to': len(days) - 0.5
				}]
		self.yAxis.min = 0
		self.yAxis.title.text = 'Hours'
		self.series = seriesList = []

		series = {
			'type': 'waterfall',
			'name': 'Earned value',
			'data': [],
			'upColor': '#4572a7',
			'color': '#aa4643'
		}
		seriesList.append(series)

		yesterdaySum = 0
		for day in days:
			dayTasks = [revisions[t.id, day] for t in tasks]
			todaySum = sum(t.earnedValueHours() for t in dayTasks if t)
			series['data'].append(todaySum - yesterdaySum)
			yesterdaySum = todaySum

		setupTimeline(self, sprint)
コード例 #39
0
def pubs_distribution(discipline='all researchers'):
	os.mkdir(charts_path+'/'+discipline) if not os.path.exists(charts_path+'/'+discipline) else ''
	male = researcher.aggregate([{'$match':{'gender':'M','labels':discipline}},{'$project':{'_id':'$_id','pubs_count':{'$size':'$pubs'}}},{'$sort':{'pubs_count':1}}])if discipline != 'all researchers' else researcher.aggregate([{'$match':{'gender':'M'}},{'$project':{'_id':'$_id','pubs_count':{'$size':'$pubs'}}},{'$sort':{'pubs_count':1}}])
	female = researcher.aggregate([{'$match':{'gender':'F','labels':discipline}},{'$project':{'_id':'$_id','pubs_count':{'$size':'$pubs'}}},{'$sort':{'pubs_count':1}}]) if discipline !='all researchers' else researcher.aggregate([{'$match':{'gender':'F'}},{'$project':{'_id':'$_id','pubs_count':{'$size':'$pubs'}}},{'$sort':{'pubs_count':1}}])

	male = [doc['pubs_count'] for doc in male]
	female = [doc['pubs_count'] for doc in female]

	chart = Chart()
	# chart.normalized_CDF(male,female,"publication CDF of {0}".format(discipline),"personal publication number","cumulative proportion",15)
	# chart.save(charts_path+'/{0}/publication_cdf'.format(discipline),format='png')
	# chart.clear()

	chart.histogram(male,female,"publication distribution of {0} ".format(discipline),"personal publication number","research count",15)

	chart.save(charts_path+'/{0}/publication_histogram'.format(discipline),format='png')
	chart.clear()

	chart = Chart(15,10)
	chart.unnormalized_CDF(male,female,"cumulative publication number of {0}".format(discipline),"personal publication number","cumulative publication",15)
	chart.save(charts_path+'/{0}/unnormalized_publication_cdf'.format(discipline),format='png')
	chart.clear()

	chart.close()
コード例 #40
0
    def setupUi(self, MainWindow):
        MainWindow.showMaximized()
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        #MainWindow.resize(1014, 682)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))

        self.gridLayout_4 = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))

        self.frame_2 = QtGui.QFrame(self.centralwidget)
        self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_2.setObjectName(_fromUtf8("frame_2"))

        self.gridLayout_3 = QtGui.QGridLayout(self.frame_2)
        self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))

        self.scrollArea_2 = QtGui.QScrollArea(self.frame_2)
        self.scrollArea_2.setWidgetResizable(True)
        self.scrollArea_2.setObjectName(_fromUtf8("scrollArea_2"))

        self.scrollAreaWidgetContents_2 = QtGui.QWidget()
        self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 459, 448))
        self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8("scrollAreaWidgetContents_2"))

        self.gridLayout_6 = QtGui.QGridLayout(self.scrollAreaWidgetContents_2)
        self.gridLayout_6.setObjectName(_fromUtf8("gridLayout_6"))

        self.modifided_image = ImageWidget(self.scrollAreaWidgetContents_2)
        self.modifided_image.setObjectName(_fromUtf8("modifided_image"))

        self.gridLayout_6.addWidget(self.modifided_image, 0, 0, 1, 1)

        self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)

        self.gridLayout_3.addWidget(self.scrollArea_2, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.frame_2, 0, 1, 1, 1)

        self.frame = QtGui.QFrame(self.centralwidget)
        self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName(_fromUtf8("frame"))

        self.gridLayout_2 = QtGui.QGridLayout(self.frame)
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))

        self.scrollArea = QtGui.QScrollArea(self.frame)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName(_fromUtf8("scrollArea"))

        self.scrollAreaWidgetContents = QtGui.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 459, 448))
        self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))

        self.gridLayout_5 = QtGui.QGridLayout(self.scrollAreaWidgetContents)
        self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5"))

        self.original_image = ImageWidget(self.scrollAreaWidgetContents)
        self.original_image.setObjectName(_fromUtf8("original_image"))

        self.gridLayout_5.addWidget(self.original_image, 0, 0, 1, 1)

        self.scrollArea.setWidget(self.scrollAreaWidgetContents)

        self.gridLayout_2.addWidget(self.scrollArea, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.frame, 0, 0, 1, 1)

        MainWindow.setCentralWidget(self.centralwidget)

        self.dockWidget = QtGui.QDockWidget(MainWindow)
        self.dockWidget.setObjectName(_fromUtf8("dockWidget"))
        self.dockWidget.setFloating(True)
        self.dockWidget.setGeometry(QtCore.QRect(0, 0, 620, 220))

        self.dockWidgetContents = QtGui.QWidget()
        self.dockWidgetContents.setObjectName(_fromUtf8("dockWidgetContents"))

        self.horizontalLayout = QtGui.QHBoxLayout(self.dockWidgetContents)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))

        self.frame_4 = QtGui.QFrame(self.dockWidgetContents)
        self.frame_4.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_4.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_4.setObjectName(_fromUtf8("frame_4"))

        self.gridLayout_8 = QtGui.QGridLayout(self.frame_4)
        self.gridLayout_8.setObjectName(_fromUtf8("gridLayout_8"))

        self.original_histogram = Chart(self.frame_4)
        self.original_histogram.setObjectName(_fromUtf8("original_histogram"))

        self.gridLayout_8.addWidget(self.original_histogram, 0, 0, 1, 1)

        self.horizontalLayout.addWidget(self.frame_4)

        self.frame_3 = QtGui.QFrame(self.dockWidgetContents)
        self.frame_3.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_3.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_3.setObjectName(_fromUtf8("frame_3"))

        self.gridLayout_7 = QtGui.QGridLayout(self.frame_3)
        self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7"))

        self.modifided_histogram = Chart(self.frame_3)
        self.modifided_histogram.setObjectName(_fromUtf8("modifided_histogram"))

        self.gridLayout_7.addWidget(self.modifided_histogram, 0, 0, 1, 1)

        self.horizontalLayout.addWidget(self.frame_3)

        self.dockWidget.setWidget(self.dockWidgetContents)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(8), self.dockWidget)

        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1014, 22))
        self.menubar.setObjectName(_fromUtf8("menubar"))

        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))

        self.menuOperations = QtGui.QMenu(self.menubar)
        self.menuOperations.setObjectName(_fromUtf8("menuOperations"))
        self.menuOperations.setEnabled(False)

        self.menuHistogram_Modification = QtGui.QMenu(self.menuOperations)
        self.menuHistogram_Modification.setObjectName(_fromUtf8("menuHistogram_Modification"))

        self.menuSlide_Histogram = QtGui.QMenu(self.menuHistogram_Modification)
        self.menuSlide_Histogram.setObjectName(_fromUtf8("menuSlide_Histogram"))

        self.menuMapping_Equations = QtGui.QMenu(self.menuOperations)
        self.menuMapping_Equations.setObjectName(_fromUtf8("menuMapping_Equations"))

        self.menuLocal_Mask_Operations = QtGui.QMenu(self.menuOperations)
        self.menuLocal_Mask_Operations.setObjectName(_fromUtf8("menuLocal_Mask_Operations"))

        self.menuSegmentation = QtGui.QMenu(self.menuOperations)
        self.menuSegmentation.setObjectName(_fromUtf8("menuSegmentation"))

        MainWindow.setMenuBar(self.menubar)

        self.actionOpen = QtGui.QAction(MainWindow)
        self.actionOpen.setObjectName(_fromUtf8("action_Open"))
        self.actionOpen.setShortcut('Ctrl+O')
        self.actionOpen.triggered.connect(self.showOpen)

        self.actionExit = QtGui.QAction(MainWindow)
        self.actionExit.setObjectName(_fromUtf8("actionExit"))
        self.actionExit.setShortcut('Ctrl+Q')
        self.actionExit.setStatusTip('Exit application')
        self.actionExit.triggered.connect(QtGui.qApp.quit)

        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionExit)

        self.actionStretch_Histogram = QtGui.QAction(MainWindow)
        self.actionStretch_Histogram.setObjectName(_fromUtf8("actionStretch_Histogram"))
        self.actionStretch_Histogram.triggered.connect(self.stretchHisto)

        self.actionShrink_Histogram = QtGui.QAction(MainWindow)
        self.actionShrink_Histogram.setObjectName(_fromUtf8("actionShrink_Histogram"))
        self.actionShrink_Histogram.triggered.connect(self.shrinkHisto)

        self.actionLeft = QtGui.QAction(MainWindow)
        self.actionLeft.setObjectName(_fromUtf8("actionLeft"))
        self.actionLeft.triggered.connect(self.slidesLeftHisto)

        self.actionRight = QtGui.QAction(MainWindow)
        self.actionRight.setObjectName(_fromUtf8("actionRight"))
        self.actionRight.triggered.connect(self.slidesRightHisto)

        self.actionHistogram_Equalization = QtGui.QAction(MainWindow)
        self.actionHistogram_Equalization.setObjectName(_fromUtf8("actionHistogram_Equalization"))
        self.actionHistogram_Equalization.triggered.connect(self.histogramEqualization)

        self.actionNegative = QtGui.QAction(MainWindow)
        self.actionNegative.setObjectName(_fromUtf8("actionNegative"))
        self.actionNegative.triggered.connect(self.negative)

        self.actionMean_Local_Filtering = QtGui.QAction(MainWindow)
        self.actionMean_Local_Filtering.setObjectName(_fromUtf8("actionMean_Local_Filtering"))
        self.actionMean_Local_Filtering.triggered.connect(self.meanFilter)

        self.actionMedian_Local_Filtering = QtGui.QAction(MainWindow)
        self.actionMedian_Local_Filtering.setObjectName(_fromUtf8("actionMedian_Local_Filtering"))
        self.actionMedian_Local_Filtering.triggered.connect(self.medianFilter)

        self.actionSobel_Edge_Detector = QtGui.QAction(MainWindow)
        self.actionSobel_Edge_Detector.setObjectName(_fromUtf8("actionSobel_Edge_Detector"))
        self.actionSobel_Edge_Detector.triggered.connect(self.edgeDetection)

        self.menuSlide_Histogram.addAction(self.actionLeft)
        self.menuSlide_Histogram.addAction(self.actionRight)

        self.menuHistogram_Modification.addAction(self.actionStretch_Histogram)
        self.menuHistogram_Modification.addAction(self.actionShrink_Histogram)
        self.menuHistogram_Modification.addAction(self.menuSlide_Histogram.menuAction())
        self.menuHistogram_Modification.addAction(self.actionHistogram_Equalization)

        self.menuMapping_Equations.addAction(self.actionNegative)

        self.menuLocal_Mask_Operations.addAction(self.actionMean_Local_Filtering)
        self.menuLocal_Mask_Operations.addAction(self.actionMedian_Local_Filtering)

        self.menuSegmentation.addAction(self.actionSobel_Edge_Detector)

        self.menuOperations.addAction(self.menuHistogram_Modification.menuAction())
        self.menuOperations.addAction(self.menuMapping_Equations.menuAction())
        self.menuOperations.addAction(self.menuLocal_Mask_Operations.menuAction())
        self.menuOperations.addAction(self.menuSegmentation.menuAction())

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuOperations.menuAction())

        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
コード例 #41
0
ファイル: gui.py プロジェクト: tahhan/imageProc
class Ui_MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        self.imgPreProc = imagePreProcessor()

    def setupUi(self, MainWindow):
        MainWindow.showMaximized()
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        # MainWindow.resize(1014, 682)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))

        self.gridLayout_4 = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))

        self.frame_2 = QtGui.QFrame(self.centralwidget)
        self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_2.setObjectName(_fromUtf8("frame_2"))

        self.gridLayout_3 = QtGui.QGridLayout(self.frame_2)
        self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))

        self.scrollArea_2 = QtGui.QScrollArea(self.frame_2)
        self.scrollArea_2.setWidgetResizable(True)
        self.scrollArea_2.setObjectName(_fromUtf8("scrollArea_2"))

        self.scrollAreaWidgetContents_2 = QtGui.QWidget()
        self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 459, 448))
        self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8("scrollAreaWidgetContents_2"))

        self.gridLayout_6 = QtGui.QGridLayout(self.scrollAreaWidgetContents_2)
        self.gridLayout_6.setObjectName(_fromUtf8("gridLayout_6"))

        self.modifided_image = ImageWidget(self.scrollAreaWidgetContents_2)
        self.modifided_image.setObjectName(_fromUtf8("modifided_image"))

        self.gridLayout_6.addWidget(self.modifided_image, 0, 0, 1, 1)

        self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)

        self.gridLayout_3.addWidget(self.scrollArea_2, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.frame_2, 0, 1, 1, 1)

        self.frame = QtGui.QFrame(self.centralwidget)
        self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName(_fromUtf8("frame"))

        self.gridLayout_2 = QtGui.QGridLayout(self.frame)
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))

        self.scrollArea = QtGui.QScrollArea(self.frame)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName(_fromUtf8("scrollArea"))

        self.scrollAreaWidgetContents = QtGui.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 459, 448))
        self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))

        self.gridLayout_5 = QtGui.QGridLayout(self.scrollAreaWidgetContents)
        self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5"))

        self.original_image = ImageWidget(self.scrollAreaWidgetContents)
        self.original_image.setObjectName(_fromUtf8("original_image"))

        self.gridLayout_5.addWidget(self.original_image, 0, 0, 1, 1)

        self.scrollArea.setWidget(self.scrollAreaWidgetContents)

        self.gridLayout_2.addWidget(self.scrollArea, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.frame, 0, 0, 1, 1)

        MainWindow.setCentralWidget(self.centralwidget)

        self.dockWidget = QtGui.QDockWidget(MainWindow)
        self.dockWidget.setObjectName(_fromUtf8("dockWidget"))
        self.dockWidget.setFloating(True)
        self.dockWidget.setGeometry(QtCore.QRect(0, 0, 620, 220))

        self.dockWidgetContents = QtGui.QWidget()
        self.dockWidgetContents.setObjectName(_fromUtf8("dockWidgetContents"))

        self.horizontalLayout = QtGui.QHBoxLayout(self.dockWidgetContents)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))

        self.frame_4 = QtGui.QFrame(self.dockWidgetContents)
        self.frame_4.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_4.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_4.setObjectName(_fromUtf8("frame_4"))

        self.gridLayout_8 = QtGui.QGridLayout(self.frame_4)
        self.gridLayout_8.setObjectName(_fromUtf8("gridLayout_8"))

        self.original_histogram = Chart(self.frame_4)
        self.original_histogram.setObjectName(_fromUtf8("original_histogram"))

        self.gridLayout_8.addWidget(self.original_histogram, 0, 0, 1, 1)

        self.horizontalLayout.addWidget(self.frame_4)

        self.frame_3 = QtGui.QFrame(self.dockWidgetContents)
        self.frame_3.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_3.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_3.setObjectName(_fromUtf8("frame_3"))

        self.gridLayout_7 = QtGui.QGridLayout(self.frame_3)
        self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7"))

        self.modifided_histogram = Chart(self.frame_3)
        self.modifided_histogram.setObjectName(_fromUtf8("modifided_histogram"))

        self.gridLayout_7.addWidget(self.modifided_histogram, 0, 0, 1, 1)

        self.horizontalLayout.addWidget(self.frame_3)

        self.dockWidget.setWidget(self.dockWidgetContents)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(8), self.dockWidget)

        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1014, 22))
        self.menubar.setObjectName(_fromUtf8("menubar"))

        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))

        self.menuOperations = QtGui.QMenu(self.menubar)
        self.menuOperations.setObjectName(_fromUtf8("menuOperations"))
        self.menuOperations.setEnabled(False)

        self.menuHistogram_Modification = QtGui.QMenu(self.menuOperations)
        self.menuHistogram_Modification.setObjectName(_fromUtf8("menuHistogram_Modification"))

        self.menuSlide_Histogram = QtGui.QMenu(self.menuHistogram_Modification)
        self.menuSlide_Histogram.setObjectName(_fromUtf8("menuSlide_Histogram"))

        self.menuMapping_Equations = QtGui.QMenu(self.menuOperations)
        self.menuMapping_Equations.setObjectName(_fromUtf8("menuMapping_Equations"))

        self.menuLocal_Mask_Operations = QtGui.QMenu(self.menuOperations)
        self.menuLocal_Mask_Operations.setObjectName(_fromUtf8("menuLocal_Mask_Operations"))

        self.menuSegmentation = QtGui.QMenu(self.menuOperations)
        self.menuSegmentation.setObjectName(_fromUtf8("menuSegmentation"))

        MainWindow.setMenuBar(self.menubar)

        self.actionOpen = QtGui.QAction(MainWindow)
        self.actionOpen.setObjectName(_fromUtf8("action_Open"))
        self.actionOpen.setShortcut("Ctrl+O")
        self.actionOpen.triggered.connect(self.showOpen)

        self.actionExit = QtGui.QAction(MainWindow)
        self.actionExit.setObjectName(_fromUtf8("actionExit"))
        self.actionExit.setShortcut("Ctrl+Q")
        self.actionExit.setStatusTip("Exit application")
        self.actionExit.triggered.connect(QtGui.qApp.quit)

        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionExit)

        self.actionStretch_Histogram = QtGui.QAction(MainWindow)
        self.actionStretch_Histogram.setObjectName(_fromUtf8("actionStretch_Histogram"))
        self.actionStretch_Histogram.triggered.connect(self.stretchHisto)

        self.actionShrink_Histogram = QtGui.QAction(MainWindow)
        self.actionShrink_Histogram.setObjectName(_fromUtf8("actionShrink_Histogram"))
        self.actionShrink_Histogram.triggered.connect(self.shrinkHisto)

        self.actionLeft = QtGui.QAction(MainWindow)
        self.actionLeft.setObjectName(_fromUtf8("actionLeft"))
        self.actionLeft.triggered.connect(self.slidesLeftHisto)

        self.actionRight = QtGui.QAction(MainWindow)
        self.actionRight.setObjectName(_fromUtf8("actionRight"))
        self.actionRight.triggered.connect(self.slidesRightHisto)

        self.actionHistogram_Equalization = QtGui.QAction(MainWindow)
        self.actionHistogram_Equalization.setObjectName(_fromUtf8("actionHistogram_Equalization"))
        self.actionHistogram_Equalization.triggered.connect(self.histogramEqualization)

        self.actionNegative = QtGui.QAction(MainWindow)
        self.actionNegative.setObjectName(_fromUtf8("actionNegative"))
        self.actionNegative.triggered.connect(self.negative)

        self.actionMean_Local_Filtering = QtGui.QAction(MainWindow)
        self.actionMean_Local_Filtering.setObjectName(_fromUtf8("actionMean_Local_Filtering"))
        self.actionMean_Local_Filtering.triggered.connect(self.meanFilter)

        self.actionMedian_Local_Filtering = QtGui.QAction(MainWindow)
        self.actionMedian_Local_Filtering.setObjectName(_fromUtf8("actionMedian_Local_Filtering"))
        self.actionMedian_Local_Filtering.triggered.connect(self.medianFilter)

        self.actionSobel_Edge_Detector = QtGui.QAction(MainWindow)
        self.actionSobel_Edge_Detector.setObjectName(_fromUtf8("actionSobel_Edge_Detector"))
        self.actionSobel_Edge_Detector.triggered.connect(self.edgeDetection)

        self.menuSlide_Histogram.addAction(self.actionLeft)
        self.menuSlide_Histogram.addAction(self.actionRight)

        self.menuHistogram_Modification.addAction(self.actionStretch_Histogram)
        self.menuHistogram_Modification.addAction(self.actionShrink_Histogram)
        self.menuHistogram_Modification.addAction(self.menuSlide_Histogram.menuAction())
        self.menuHistogram_Modification.addAction(self.actionHistogram_Equalization)

        self.menuMapping_Equations.addAction(self.actionNegative)

        self.menuLocal_Mask_Operations.addAction(self.actionMean_Local_Filtering)
        self.menuLocal_Mask_Operations.addAction(self.actionMedian_Local_Filtering)

        self.menuSegmentation.addAction(self.actionSobel_Edge_Detector)

        self.menuOperations.addAction(self.menuHistogram_Modification.menuAction())
        self.menuOperations.addAction(self.menuMapping_Equations.menuAction())
        self.menuOperations.addAction(self.menuLocal_Mask_Operations.menuAction())
        self.menuOperations.addAction(self.menuSegmentation.menuAction())

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuOperations.menuAction())

        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))

        self.menuFile.setTitle(_translate("MainWindow", "File", None))
        self.menuOperations.setTitle(_translate("MainWindow", "Operations", None))
        self.menuHistogram_Modification.setTitle(_translate("MainWindow", "Histogram Modification", None))
        self.menuSlide_Histogram.setTitle(_translate("MainWindow", "Slide Histogram", None))
        self.menuMapping_Equations.setTitle(_translate("MainWindow", "Mapping Equations", None))
        self.menuLocal_Mask_Operations.setTitle(_translate("MainWindow", "Local (Mask) Operations", None))
        self.menuSegmentation.setTitle(_translate("MainWindow", "Segmentation", None))

        self.actionOpen.setText(_translate("MainWindow", "Open", None))
        self.actionExit.setText(_translate("MainWindow", "Exit", None))
        self.actionStretch_Histogram.setText(_translate("MainWindow", "Stretch Histogram", None))
        self.actionShrink_Histogram.setText(_translate("MainWindow", "Shrink Histogram", None))
        self.actionLeft.setText(_translate("MainWindow", "Left", None))
        self.actionRight.setText(_translate("MainWindow", "Right", None))
        self.actionHistogram_Equalization.setText(_translate("MainWindow", "Histogram Equalization", None))
        self.actionNegative.setText(_translate("MainWindow", "Negative", None))
        self.actionMean_Local_Filtering.setText(_translate("MainWindow", "Mean Local Filtering", None))
        self.actionMedian_Local_Filtering.setText(_translate("MainWindow", "Median Local Filtering", None))
        self.actionSobel_Edge_Detector.setText(_translate("MainWindow", "Sobel Edge Detector", None))

    def showOpen(self):
        """Shows the file opening dialog."""
        filepath = QtGui.QFileDialog.getOpenFileName(
            self, "Open File", "", "All Files (*.*);;jpeg (*.jpeg);;jpg (*.jpg);;png (*.png)"
        )

        if filepath:
            self.open(filepath)

    def showIntDialog(self, title, text):
        amount, ok = QtGui.QInputDialog.getInt(self, title, text)

        if ok:
            return amount
        else:
            return 0

    def open(self, filepath):
        self.imgPreProc.loadImage(str(filepath))
        self.original_image.Qimg = ImageQt.ImageQt(
            self.imgPreProc.img.convert("RGB") if self.imgPreProc.img.mode == "L" else self.imgPreProc.img
        )
        self.original_image.repaint()
        self.original_histogram.setData(self.imgPreProc.histo)
        self.refreshAll()
        self.menuOperations.setEnabled(True)

    def repaintImage(self):
        self.modifided_image.Qimg = ImageQt.ImageQt(
            self.imgPreProc.img.convert("RGB") if self.imgPreProc.img.mode == "L" else self.imgPreProc.img
        )
        self.modifided_image.repaint()

    def rebuildHisto(self):
        self.modifided_histogram.setData(self.imgPreProc.histo)

    def refreshAll(self):
        self.rebuildHisto()
        self.repaintImage()

    def stretchHisto(self):
        self.imgPreProc.stretchHisto()
        self.refreshAll()

    def shrinkHisto(self):
        minR = self.showIntDialog("Histogram Min Shrink", "Shrink Min:")
        if minR:
            maxR = self.showIntDialog("Histogram Max Shrink", "Shrink Max:")
            if maxR:
                self.imgPreProc.shrinkHisto(minR, maxR)
                self.refreshAll()
            else:
                QtGui.QMessageBox.critical(self, "Error", "Provide the the Max")
        else:
            QtGui.QMessageBox.critical(self, "Error", "Provide the the Min")

    def slidesLeftHisto(self):
        amount = self.showIntDialog("Slide Histogram, Left", "Sliding Amount:")
        if amount:
            self.imgPreProc.slidesLeftHisto(amount)
            self.refreshAll()
        else:
            QtGui.QMessageBox.critical(self, "Error", "Provide the amount of sliding")

    def slidesRightHisto(self):
        amount = self.showIntDialog("Slide Histogram, Right", "Sliding Amount:")
        if amount:
            self.imgPreProc.slidesRightHisto(amount)
            self.refreshAll()
        else:
            QtGui.QMessageBox.critical(self, "Error", "You have to fill the By")

    def histogramEqualization(self):
        self.imgPreProc.histogramEqualization()
        self.refreshAll()

    def negative(self):
        self.imgPreProc.negative()
        self.refreshAll()

    def meanFilter(self):
        self.imgPreProc.meanFilter()
        self.refreshAll()

    def medianFilter(self):
        self.imgPreProc.medianFilter()
        self.refreshAll()

    def edgeDetection(self):
        self.imgPreProc.edgeDetection()
        self.refreshAll()
コード例 #42
0
class Ui_MainWindow(QtGui.QMainWindow):
    
    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        self.imgPreProc = imagePreProcessor()

    def setupUi(self, MainWindow):
        MainWindow.showMaximized()
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        #MainWindow.resize(1014, 682)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))

        self.gridLayout_4 = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))

        self.frame_2 = QtGui.QFrame(self.centralwidget)
        self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_2.setObjectName(_fromUtf8("frame_2"))

        self.gridLayout_3 = QtGui.QGridLayout(self.frame_2)
        self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))

        self.scrollArea_2 = QtGui.QScrollArea(self.frame_2)
        self.scrollArea_2.setWidgetResizable(True)
        self.scrollArea_2.setObjectName(_fromUtf8("scrollArea_2"))

        self.scrollAreaWidgetContents_2 = QtGui.QWidget()
        self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 459, 448))
        self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8("scrollAreaWidgetContents_2"))

        self.gridLayout_6 = QtGui.QGridLayout(self.scrollAreaWidgetContents_2)
        self.gridLayout_6.setObjectName(_fromUtf8("gridLayout_6"))

        self.modifided_image = ImageWidget(self.scrollAreaWidgetContents_2)
        self.modifided_image.setObjectName(_fromUtf8("modifided_image"))

        self.gridLayout_6.addWidget(self.modifided_image, 0, 0, 1, 1)

        self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)

        self.gridLayout_3.addWidget(self.scrollArea_2, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.frame_2, 0, 1, 1, 1)

        self.frame = QtGui.QFrame(self.centralwidget)
        self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName(_fromUtf8("frame"))

        self.gridLayout_2 = QtGui.QGridLayout(self.frame)
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))

        self.scrollArea = QtGui.QScrollArea(self.frame)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName(_fromUtf8("scrollArea"))

        self.scrollAreaWidgetContents = QtGui.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 459, 448))
        self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))

        self.gridLayout_5 = QtGui.QGridLayout(self.scrollAreaWidgetContents)
        self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5"))

        self.original_image = ImageWidget(self.scrollAreaWidgetContents)
        self.original_image.setObjectName(_fromUtf8("original_image"))

        self.gridLayout_5.addWidget(self.original_image, 0, 0, 1, 1)

        self.scrollArea.setWidget(self.scrollAreaWidgetContents)

        self.gridLayout_2.addWidget(self.scrollArea, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.frame, 0, 0, 1, 1)

        MainWindow.setCentralWidget(self.centralwidget)

        self.dockWidget = QtGui.QDockWidget(MainWindow)
        self.dockWidget.setObjectName(_fromUtf8("dockWidget"))
        self.dockWidget.setFloating(True)
        self.dockWidget.setGeometry(QtCore.QRect(0, 0, 620, 220))

        self.dockWidgetContents = QtGui.QWidget()
        self.dockWidgetContents.setObjectName(_fromUtf8("dockWidgetContents"))

        self.horizontalLayout = QtGui.QHBoxLayout(self.dockWidgetContents)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))

        self.frame_4 = QtGui.QFrame(self.dockWidgetContents)
        self.frame_4.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_4.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_4.setObjectName(_fromUtf8("frame_4"))

        self.gridLayout_8 = QtGui.QGridLayout(self.frame_4)
        self.gridLayout_8.setObjectName(_fromUtf8("gridLayout_8"))

        self.original_histogram = Chart(self.frame_4)
        self.original_histogram.setObjectName(_fromUtf8("original_histogram"))

        self.gridLayout_8.addWidget(self.original_histogram, 0, 0, 1, 1)

        self.horizontalLayout.addWidget(self.frame_4)

        self.frame_3 = QtGui.QFrame(self.dockWidgetContents)
        self.frame_3.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_3.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_3.setObjectName(_fromUtf8("frame_3"))

        self.gridLayout_7 = QtGui.QGridLayout(self.frame_3)
        self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7"))

        self.modifided_histogram = Chart(self.frame_3)
        self.modifided_histogram.setObjectName(_fromUtf8("modifided_histogram"))

        self.gridLayout_7.addWidget(self.modifided_histogram, 0, 0, 1, 1)

        self.horizontalLayout.addWidget(self.frame_3)

        self.dockWidget.setWidget(self.dockWidgetContents)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(8), self.dockWidget)

        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1014, 22))
        self.menubar.setObjectName(_fromUtf8("menubar"))

        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))

        self.menuOperations = QtGui.QMenu(self.menubar)
        self.menuOperations.setObjectName(_fromUtf8("menuOperations"))
        self.menuOperations.setEnabled(False)

        self.menuHistogram_Modification = QtGui.QMenu(self.menuOperations)
        self.menuHistogram_Modification.setObjectName(_fromUtf8("menuHistogram_Modification"))

        self.menuSlide_Histogram = QtGui.QMenu(self.menuHistogram_Modification)
        self.menuSlide_Histogram.setObjectName(_fromUtf8("menuSlide_Histogram"))

        self.menuMapping_Equations = QtGui.QMenu(self.menuOperations)
        self.menuMapping_Equations.setObjectName(_fromUtf8("menuMapping_Equations"))

        self.menuLocal_Mask_Operations = QtGui.QMenu(self.menuOperations)
        self.menuLocal_Mask_Operations.setObjectName(_fromUtf8("menuLocal_Mask_Operations"))

        self.menuSegmentation = QtGui.QMenu(self.menuOperations)
        self.menuSegmentation.setObjectName(_fromUtf8("menuSegmentation"))

        MainWindow.setMenuBar(self.menubar)

        self.actionOpen = QtGui.QAction(MainWindow)
        self.actionOpen.setObjectName(_fromUtf8("action_Open"))
        self.actionOpen.setShortcut('Ctrl+O')
        self.actionOpen.triggered.connect(self.showOpen)

        self.actionExit = QtGui.QAction(MainWindow)
        self.actionExit.setObjectName(_fromUtf8("actionExit"))
        self.actionExit.setShortcut('Ctrl+Q')
        self.actionExit.setStatusTip('Exit application')
        self.actionExit.triggered.connect(QtGui.qApp.quit)

        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionExit)

        self.actionStretch_Histogram = QtGui.QAction(MainWindow)
        self.actionStretch_Histogram.setObjectName(_fromUtf8("actionStretch_Histogram"))
        self.actionStretch_Histogram.triggered.connect(self.stretchHisto)

        self.actionShrink_Histogram = QtGui.QAction(MainWindow)
        self.actionShrink_Histogram.setObjectName(_fromUtf8("actionShrink_Histogram"))
        self.actionShrink_Histogram.triggered.connect(self.shrinkHisto)

        self.actionLeft = QtGui.QAction(MainWindow)
        self.actionLeft.setObjectName(_fromUtf8("actionLeft"))
        self.actionLeft.triggered.connect(self.slidesLeftHisto)

        self.actionRight = QtGui.QAction(MainWindow)
        self.actionRight.setObjectName(_fromUtf8("actionRight"))
        self.actionRight.triggered.connect(self.slidesRightHisto)

        self.actionHistogram_Equalization = QtGui.QAction(MainWindow)
        self.actionHistogram_Equalization.setObjectName(_fromUtf8("actionHistogram_Equalization"))
        self.actionHistogram_Equalization.triggered.connect(self.histogramEqualization)

        self.actionNegative = QtGui.QAction(MainWindow)
        self.actionNegative.setObjectName(_fromUtf8("actionNegative"))
        self.actionNegative.triggered.connect(self.negative)

        self.actionMean_Local_Filtering = QtGui.QAction(MainWindow)
        self.actionMean_Local_Filtering.setObjectName(_fromUtf8("actionMean_Local_Filtering"))
        self.actionMean_Local_Filtering.triggered.connect(self.meanFilter)

        self.actionMedian_Local_Filtering = QtGui.QAction(MainWindow)
        self.actionMedian_Local_Filtering.setObjectName(_fromUtf8("actionMedian_Local_Filtering"))
        self.actionMedian_Local_Filtering.triggered.connect(self.medianFilter)

        self.actionSobel_Edge_Detector = QtGui.QAction(MainWindow)
        self.actionSobel_Edge_Detector.setObjectName(_fromUtf8("actionSobel_Edge_Detector"))
        self.actionSobel_Edge_Detector.triggered.connect(self.edgeDetection)

        self.menuSlide_Histogram.addAction(self.actionLeft)
        self.menuSlide_Histogram.addAction(self.actionRight)

        self.menuHistogram_Modification.addAction(self.actionStretch_Histogram)
        self.menuHistogram_Modification.addAction(self.actionShrink_Histogram)
        self.menuHistogram_Modification.addAction(self.menuSlide_Histogram.menuAction())
        self.menuHistogram_Modification.addAction(self.actionHistogram_Equalization)

        self.menuMapping_Equations.addAction(self.actionNegative)

        self.menuLocal_Mask_Operations.addAction(self.actionMean_Local_Filtering)
        self.menuLocal_Mask_Operations.addAction(self.actionMedian_Local_Filtering)

        self.menuSegmentation.addAction(self.actionSobel_Edge_Detector)

        self.menuOperations.addAction(self.menuHistogram_Modification.menuAction())
        self.menuOperations.addAction(self.menuMapping_Equations.menuAction())
        self.menuOperations.addAction(self.menuLocal_Mask_Operations.menuAction())
        self.menuOperations.addAction(self.menuSegmentation.menuAction())

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuOperations.menuAction())

        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))

        self.menuFile.setTitle(_translate("MainWindow", "File", None))
        self.menuOperations.setTitle(_translate("MainWindow", "Operations", None))
        self.menuHistogram_Modification.setTitle(_translate("MainWindow", "Histogram Modification", None))
        self.menuSlide_Histogram.setTitle(_translate("MainWindow", "Slide Histogram", None))
        self.menuMapping_Equations.setTitle(_translate("MainWindow", "Mapping Equations", None))
        self.menuLocal_Mask_Operations.setTitle(_translate("MainWindow", "Local (Mask) Operations", None))
        self.menuSegmentation.setTitle(_translate("MainWindow", "Segmentation", None))

        self.actionOpen.setText(_translate("MainWindow", "Open", None))
        self.actionExit.setText(_translate("MainWindow", "Exit", None))
        self.actionStretch_Histogram.setText(_translate("MainWindow", "Stretch Histogram", None))
        self.actionShrink_Histogram.setText(_translate("MainWindow", "Shrink Histogram", None))
        self.actionLeft.setText(_translate("MainWindow", "Left", None))
        self.actionRight.setText(_translate("MainWindow", "Right", None))
        self.actionHistogram_Equalization.setText(_translate("MainWindow", "Histogram Equalization", None))
        self.actionNegative.setText(_translate("MainWindow", "Negative", None))
        self.actionMean_Local_Filtering.setText(_translate("MainWindow", "Mean Local Filtering", None))
        self.actionMedian_Local_Filtering.setText(_translate("MainWindow", "Median Local Filtering", None))
        self.actionSobel_Edge_Detector.setText(_translate("MainWindow", "Sobel Edge Detector", None))

    def showOpen(self):
        """Shows the file opening dialog."""
        filepath = QtGui.QFileDialog.getOpenFileName(
        self, 'Open File', '', 'All Files (*.*);;jpeg (*.jpeg);;jpg (*.jpg);;png (*.png)')

        if filepath:
            self.open(filepath)

    def showIntDialog(self, title, text):
        amount, ok = QtGui.QInputDialog.getInt(self, title, text)

        if ok:
            return amount
        else:
            return 0

    def open(self, filepath):
        self.imgPreProc.loadImage(str(filepath))
        self.original_image.Qimg = ImageQt.ImageQt(self.imgPreProc.img.convert("RGB") if self.imgPreProc.img.mode == "L" else self.imgPreProc.img)
        self.original_image.repaint()
        self.original_histogram.setData(self.imgPreProc.histo)
        self.refreshAll()
        self.menuOperations.setEnabled(True)

    def repaintImage(self):
        self.modifided_image.Qimg = ImageQt.ImageQt(self.imgPreProc.img.convert("RGB") if self.imgPreProc.img.mode == "L" else self.imgPreProc.img) 
        self.modifided_image.repaint()

    def rebuildHisto(self):
        self.modifided_histogram.setData(self.imgPreProc.histo)

    def refreshAll(self):
        self.rebuildHisto()
        self.repaintImage()

    def stretchHisto(self):
        self.imgPreProc.stretchHisto()
        self.refreshAll()

    def shrinkHisto(self):
        minR = self.showIntDialog('Histogram Min Shrink', 'Shrink Min:')
        if minR:
            maxR = self.showIntDialog('Histogram Max Shrink', 'Shrink Max:')
            if maxR:
                self.imgPreProc.shrinkHisto(minR, maxR)
                self.refreshAll()
            else :
                QtGui.QMessageBox.critical(self, "Error", "Provide the the Max")
        else :
            QtGui.QMessageBox.critical(self, "Error", "Provide the the Min")
            

    def slidesLeftHisto(self):
        amount = self.showIntDialog('Slide Histogram, Left', 'Sliding Amount:')
        if amount:
            self.imgPreProc.slidesLeftHisto(amount)
            self.refreshAll()
        else :
            QtGui.QMessageBox.critical(self, "Error", "Provide the amount of sliding")            

    def slidesRightHisto(self):
        amount = self.showIntDialog('Slide Histogram, Right', 'Sliding Amount:')
        if amount:
            self.imgPreProc.slidesRightHisto(amount)
            self.refreshAll()
        else :
            QtGui.QMessageBox.critical(self, "Error", "You have to fill the By")

    def histogramEqualization(self):
        self.imgPreProc.histogramEqualization()
        self.refreshAll()

    def negative(self):
        self.imgPreProc.negative()
        self.refreshAll()

    def meanFilter(self):
        self.imgPreProc.meanFilter()
        self.refreshAll()

    def medianFilter(self):
        self.imgPreProc.medianFilter()
        self.refreshAll()

    def edgeDetection(self):
        self.imgPreProc.edgeDetection()
        self.refreshAll()
コード例 #43
0
ファイル: application.py プロジェクト: 3thirty/strava_charts
def chart(type: str = 'average', metric: str = 'average_watts',
          period: str = 'week'):
    """
    Produce a page with a chart

    Accepted arguments:
        limit: Maximum number of activities to chart
        after: Only chart events with a start date after this (expected to be
               a date in format YYYY-mm-dd)
    """
    log = logging.getLogger('strava')

    if (request.query.force):
        force = True
    else:
        force = False

    token_store = CookieTokenStorage(request, response)

    try:
        strava = Strava(
            token_storage=token_store,
            debug=True,
            force=force
        )
    except AuthenticationException:
        session = bottle.request.environ.get('beaker.session')

        url = Authentication.start(
            session=session
        )

        redirect(url)

    chart = Chart()

    chart_title = "%s by %s" % (metric, period)
    chart.options.title.text = chart_title

    chart.labels.labels = []
    chart.data.Metric.data = []

    if (request.query.limit):
        activities = strava.getActivities(int(request.query.limit))
    else:
        activities = strava.getAllActivities()

    if (request.query.after):
        try:
            after_date = datetime.fromisoformat(request.query.after)
            activities = ActivityList.trimBeforeDate(activities, after_date)
        except ValueError:
            pass

    if (type == 'total'):
        data = activities.aggregateTotalMetricByPeriod(
                    metric=metric,
                    period=AggregationPeriod.strToEnum(period))
    else:
        data = activities.aggregateAverageMetricByPeriod(
                    metric=metric,
                    period=AggregationPeriod.strToEnum(period))

    log.debug("chart data: %s" % data)

    for label in data:
        chart.labels.labels.append(label)
        chart.data.Metric.data.append(data[label])

    chartJSON = chart.get()

    return template('chart', chartJSON=chartJSON)
コード例 #44
0
def main():
    analyzer = WeatherAnalyzer("CalgaryWeather.csv")
    chart = Chart()
    on = True
    menu = ("1- Get Maximum Temperature of 1990-2019"
            "\n2- Get Minimum Temperature of 1990-2019"
            "\n3- Get Maximum Temperature of 1990-2019 Annually"
            "\n4- Get Minimum Temperature of 1990-2019 Annually"
            "\n5- Get Average Snowfall Between 1990-2019 Annually"
            "\n6- Get Average Temperature of 1990-2019 Annually"
            "\n7- Line Graph of Maximum Temperature by Year"
            "\n8- Line Graph of Minimum Temperature by Year"
            "\n9- Bar Graph of Average Snow Fall by Year"
            "\n10- Bar Graph of Average Temperature by Year"
            "\nType 'Exit' to End Program")
    while on == True:
        print(menu)
        selection = input("Choose a Selection: ")
        if selection == "1":
            print("----------------------")
            analyzer.getMaxTemp()
        elif selection == "2":
            print("----------------------")
            analyzer.getMinTemp()
        elif selection == "3":
            print("----------------------")
            analyzer.getMaxTempAnnually()
        elif selection == "4":
            analyzer.getMinTempAnnually()
            print("----------------------")
        elif selection == "5":
            print("----------------------")
            analyzer.getAverageSnowFallAnnually()
        elif selection == "6":
            print("----------------------")
            analyzer.getAverageTempAnnually()
        elif selection == "7":
            print("----------------------")
            chart.lineChart(analyzer.getMaxTempAnnually("Off"),
                            "Max Temp by Year", "Max Temp by Year")
        elif selection == "8":
            print("----------------------")
            chart.lineChart(analyzer.getMinTempAnnually("Off"),
                            "Min Temp by Year", "Min Temp by Year")
        elif selection == "9":
            print("----------------------")
            chart.barChart(analyzer.getAverageSnowFallAnnually("Off"),
                           "Average Snow Fall", "Average Snow Fall")
        elif selection == "10":
            print("----------------------")
            chart.barChart(analyzer.getAverageTempAnnually("Off"),
                           "Average Temp", "Average Temp")
        elif selection == "exit" or selection == "Exit":
            on = False
            print("----------------------")
        else:
            print("Please Input an Valid Integer Response")
        if input("Press Enter to Continue or Type 'Exit' to End Program: "
                 ) == "Exit":
            on = False
        print("----------------------")
コード例 #45
0
def citation_and_index_distribution(discipline='all researchers'):

	docs = researcher.find({'gender':{'$exists':1},'labels':discipline},{'gender':1,'pubs':1,'index':1}) if discipline !='all researchers' else researcher.find({'gender':{'$exists':1}},{'gender':1,'pubs':1,'index':1})
	male_citation = []
	female_citation = []
	male_index = []
	female_index = []

	pub_not_given_ciatation = 0
	profile_not_given_index = 0

	for doc in docs:
		researcher_citation_count = []
		citation_sum = 0
		if doc['gender'] == 'M':
			for pub in doc['pubs']:
				if pub['citation'].isdigit():
					citation_sum+=int(pub['citation'])
					# researcher_citation_count.append(int(pub['citation']))
				else:
					pub_not_given_ciatation+=1
			# researcher_citation_count = researcher_citation_count if researcher_citation_count else [0]
			# male_citation.append(np.mean(researcher_citation_count))
			male_citation.append(citation_sum)
			male_index.append(int(doc['index']))
		else:
			for pub in doc['pubs']:
				if pub['citation'].isdigit():
					citation_sum+=int(pub['citation'])
					# researcher_citation_count.append(int(pub['citation']))
				else:
					pub_not_given_ciatation+=1
			# researcher_citation_count = researcher_citation_count if researcher_citation_count else [0]
			# female_citation.append(np.mean(researcher_citation_count))
			female_citation.append(citation_sum)
			female_index.append(int(doc['index']))

	# chart = Chart()
	# chart.normalized_CDF(male_citation,female_citation,"citation CDF of {0}".format(discipline),"personal citation number","cumulative proportion")
	# chart.save(charts_path+'/{0}/citation_cdf'.format(discipline))
	# chart.clear()

	chart = Chart()
	chart.unnormalized_CDF(male_citation,female_citation,"cumulative citation number of {0}".format(discipline),"personal citation number","cumulative number")
	chart.save(charts_path+'/{0}/unormalized_citation_cdf'.format(discipline))
	chart.clear()

	# chart.normalized_CDF(male_index,female_index,"h-index CDF of {0}".format(discipline),"personal h-index","cumulative proportion")
	# chart.save(charts_path+'/{0}/h-index_cdf'.format(discipline))
	# chart.clear()

	chart = Chart(15,10)
	chart.unnormalized_CDF(male_index,female_index,"cumulative h-index number of {0}".format(discipline),"personal h-index","cumulative number")
	chart.save(charts_path+'/{0}/unnormalized_h-index_cdf'.format(discipline))
	chart.clear()

	chart.histogram(male_citation,female_citation,"citation distribution of {0}".format(discipline),"personal citation number","number of researcher")
	chart.save(charts_path+'/{0}/citation_histogram'.format(discipline))
	chart.clear()

	chart.histogram(male_index,female_index,"h-index distribution of {0}".format(discipline),"personal h-index","number of researcher")
	chart.save(charts_path+'/{0}/h-index_histogram'.format(discipline))
	chart.clear()

	chart.close()
コード例 #46
0
ファイル: users.py プロジェクト: mrozekma/Sprint
def user(handler, username):
	user = User.load(username = username)
	if not user:
		ErrorBox.die('User', "No user named <b>%s</b>" % stripTags(username))

	Markdown.head('form#message-form .body pre code')
	print "<script src=\"/static/jquery.typing-0.2.0.min.js\" type=\"text/javascript\"></script>"
	print "<script src=\"/static/users.js\" type=\"text/javascript\"></script>"
	Chart.include()
	undelay(handler)

	handler.title(user.safe.username)
	handler.replace('$bodytitle$', '', 1)
	print "<img src=\"%s\" class=\"gravatar\">" % user.getAvatar(64)
	print "<h1>%s</h1>" % user.safe.username
	if isDevMode(handler):
		print "<div class=\"debugtext\">User ID: %d</div>" % user.id
	print "<div class=\"clear\"></div>"

	if handler.session['user'] and handler.session['user'].hasPrivilege('Admin'):
		print "<h3>Admin</h3>"
		print "<form method=\"post\" action=\"/admin/users\">"
		print "<input type=\"hidden\" name=\"username\" value=\"%s\">" % user.username
		print "<button type=\"submit\" class=\"btn\" name=\"action\" value=\"resetpw\">Reset password</button>"
		print "<button type=\"submit\" class=\"btn\" name=\"action\" value=\"impersonate\">Impersonate</button>"
		print "<button type=\"submit\" class=\"btn\" name=\"action\" value=\"sessions\">Manage sessions</button>"
		print "<button type=\"submit\" class=\"btn\" name=\"action\" value=\"privileges\">Manage privileges</button>"
		print "</form>"

	if user == handler.session['user']:
		print "<h3>Avatar</h3>"
		if user.hasLocalAvatar():
			print "Your avatar is currently <a href=\"/users/%s/avatar/set\">locally hosted</a>" % user.username
		else:
			print "Your avatar can be changed at <a href=\"http://gravatar.com/\" target=\"_new\">http://gravatar.com/</a>. It must be associated with the e-mail <b>%s</b>, and be rated PG. You can also host an avatar <a href=\"/users/%s/avatar/set\">locally</a>, if necessary" % (user.getEmail(), user.username)

		print "<h3>Authentication</h3>"
		print "Your sprint tool password can be changed <a href=\"/resetpw\">here</a>.",
		if settings.kerberosRealm:
			print "You can also use your %s kerberos password to login" % settings.kerberosRealm,
		print "<br><br>"
		if user.hotpKey == '':
			print "You also have the option to use two-factor authentication via <a href=\"http://en.wikipedia.org/wiki/HOTP\">HOTP</a>. You can use <a href=\"http://support.google.com/a/bin/answer.py?hl=en&answer=1037451\">Google Authenticator</a> to generate verification codes<br><br>"
			print "<form method=\"post\" action=\"/security/two-factor\">"
			print "<button type=\"submit\" class=\"btn danger\" name=\"action\" value=\"enable\">Enable two-factor authentication</button>"
			print "</form>"
		else:
			print "You are currently using two-factor authentication<br><br>"
			print "<form method=\"post\" action=\"/security/two-factor\">"
			print "<button type=\"submit\" class=\"btn danger\" name=\"action\" value=\"enable\">Reset HOTP key</button>"
			print "<button type=\"submit\" class=\"btn danger\" name=\"action\" value=\"disable\">Disable two-factor authentication</button>"
			print "</form>"

		print "<h3>Messages</h3>"
		print "Your inbox and sent messages can be viewed <a href=\"/messages/inbox\">here</a><br>"

	print "<h3>Last seen</h3>"
	if not user.lastseen:
		print "Never"
	elif dateToTs(getNow()) - user.lastseen < 60:
		print "Just now"
	else:
		print "%s ago" % timesince(tsToDate(user.lastseen))

	if handler.session['user'] and handler.session['user'] != user:
		print "<h3>Message</h3>"
		print "<small>(Messages are formatted in <a target=\"_blank\" href=\"/help/markdown\">markdown</a>)</small>"
		print "<form id=\"message-form\" method=\"post\" action=\"/messages/send\">"
		print "<input type=\"hidden\" name=\"userid\" value=\"%d\">" % user.id
		print "<textarea name=\"body\" class=\"large\"></textarea>"
		print "<div class=\"body markdown\"><div id=\"preview\"></div></div>"
		print Button('Send').post().positive()
		print "</form>"

	print "<h3>Project distribution</h3>"
	sprints = filter(lambda s: user in s.members, Sprint.loadAllActive())
	sprintHours = map(lambda s: (s, Availability(s).getAllForward(getNow(), user)), sprints)
	projectHours = map(lambda (p, g): (p, sum(hours for sprint, hours in g)), groupby(sprintHours, lambda (s, a): s.project))

	# For now at least, don't show projects with no hours
	projectHours = filter(lambda (p, h): h > 0, projectHours)
	if len(projectHours) > 0:
		chart = Chart('chart')
		chart.title.text = ''
		chart.tooltip.formatter = "function() {return '<b>' + this.point.name + '</b>: ' + this.point.y + '%';}"
		chart.plotOptions.pie.allowPointSelect = True
		chart.plotOptions.pie.cursor = 'pointer'
		chart.plotOptions.pie.dataLabels.enabled = False
		chart.plotOptions.pie.showInLegend = True
		chart.credits.enabled = False
		chart.series = seriesList = []

		series = {
			'type': 'pie',
			'name': '',
			'data': []
		}
		seriesList.append(series)

		total = sum(hours for project, hours in projectHours)
		for project, hours in projectHours:
			series['data'].append([project.name, float("%2.2f" % (100 * hours / total))])

		chart.js()
		chart.placeholder()
	else:
		print "Not a member of any active sprints"
コード例 #47
0
ファイル: tasks.py プロジェクト: nolandda/Sprint
def task(handler, ids):
    requirePriv(handler, "User")
    Chart.include()

    Markdown.head(".note .text .body pre code")
    print '<script src="/static/jquery.typing-0.2.0.min.js" type="text/javascript"></script>'
    undelay(handler)

    tasks = {}
    if "," not in ids:  # Single ID
        ids = [int(ids)]
        tasks[ids[0]] = Task.load(ids[0])

        def header(task, text, level):
            if level == 1:
                handler.title(text)
            else:
                print "<h%d>%s</h%d>" % (level, text, level)

    else:  # Many IDs
        ids = map(int, uniq(ids.split(",")))
        tasks = {id: Task.load(id) for id in ids}
        handler.title("Task Information")

        if not all(tasks.values()):
            ids = [str(id) for (id, task) in tasks.iteritems() if not task]
            ErrorBox.die(
                "No %s with %s %s"
                % ("task" if len(ids) == 1 else "tasks", "ID" if len(ids) == 1 else "IDs", ", ".join(ids))
            )

        if len(set(task.sprint for task in tasks.values())) == 1:  # All in the same sprint
            print '<small>(<a href="/sprints/%d?search=highlight:%s">Show in backlog view</a>)</small><br><br>' % (
                tasks.values()[0].sprint.id,
                ",".join(map(str, ids)),
            )

        for id in ids:
            print '<a href="#task%d">%s</a><br>' % (id, tasks[id].safe.name)

        def header(task, text, level):
            if level == 1:
                print "<hr>"
                print '<a name="task%d"></a>' % task.id
                print '<a href="#task%d"><h2>%s</h2></a>' % (task.id, text)
            else:
                print "<h%d>%s</h%d>" % (level + 1, text, level + 1)

    for id in ids:
        task = tasks[id]
        if not task or task.sprint.isHidden(handler.session["user"]):
            ErrorBox.die("Tasks", "No task with ID <b>%d</b>" % id)
        elif not task.sprint.canView(handler.session["user"]):
            ErrorBox.die("Private", "You must be a sprint member to view this sprint's tasks")
        revs = task.getRevisions()
        startRev = task.getStartRevision()

        header(task, task.safe.name, 1)

        header(task, "Info", 2)
        print 'Part of <a href="/sprints/%d">%s</a>, <a href="/sprints/%d#group%d">%s</a>' % (
            task.sprintid,
            task.sprint,
            task.sprintid,
            task.groupid,
            task.group,
        ),
        if task.goal:
            print 'to meet the goal&nbsp;&nbsp;<img class="bumpdown" src="/static/images/tag-%s.png">&nbsp;<a href="/sprints/%d?search=goal:%s">%s</a>' % (
                task.goal.color,
                task.sprintid,
                task.goal.color,
                task.goal.safe.name,
            ),
        print "<br>"
        print "Assigned to %s<br>" % ", ".join(map(str, task.assigned))
        print "Last changed %s ago<br><br>" % timesince(tsToDate(task.timestamp))
        hours, total, lbl = task.hours, startRev.hours, "<b>%s</b>" % statuses[task.status].text
        if task.deleted:
            if task.sprint.canEdit(handler.session["user"]):
                print '<form method="post" action="/sprints/%d">' % task.sprint.id
                print '<input type="hidden" name="id" value="%d">' % task.id
                print '<input type="hidden" name="rev_id" value="%d">' % task.revision
                print '<input type="hidden" name="field" value="deleted">'
                print '<input type="hidden" name="value" value="false">'
                print "Deleted (%s)" % Button("undelete", id="undelete").mini().positive()
                print "</form>"
            else:
                print "Deleted"
            print "<br>"
        elif task.status == "complete":
            print ProgressBar(lbl, total - hours, total, zeroDivZero=True, style="progress-current-green")
        elif task.status in ("blocked", "canceled", "deferred", "split"):
            hours = filter(lambda rev: rev.hours > 0, revs)
            hours = hours[-1].hours if len(hours) > 0 else 0
            print ProgressBar(lbl, total - hours, total, zeroDivZero=True, style="progress-current-red")
        else:
            print ProgressBar(lbl, total - hours, total, zeroDivZero=True)

        header(task, "Notes", 2)
        for note in task.getNotes():
            print '<div id="note%d" class="note">' % note.id
            print '<form method="post" action="/tasks/%d/notes/%d/modify">' % (id, note.id)
            print '<div class="avatar"><img src="%s"></div>' % note.user.getAvatar()
            print '<div class="text">'
            print '<div class="title"><a class="timestamp" href="#note%d">%s</a> by <span class="author">%s</span>' % (
                note.id,
                tsToDate(note.timestamp).replace(microsecond=0),
                note.user.safe.username,
            )
            if note.user == handler.session["user"]:
                print '<button name="action" value="delete" class="fancy mini danger">delete</button>'
            print "</div>"
            print '<div class="body markdown">%s</div>' % note.render()
            print "</div>"
            print "</form>"
            print "</div>"

        print '<div class="note new-note">'
        print '<form method="post" action="/tasks/%d/notes/new">' % id
        print '<div class="avatar"><div><img src="%s"></div></div>' % handler.session["user"].getAvatar()
        print '<div class="text">'
        print '<div class="title">'
        print "<b>New note</b>"
        print '<a target="_blank" href="/help/markdown" class="fancy mini">help</a>'
        print "</div>"
        print '<div class="body"><textarea name="body" class="large"></textarea></div>'
        print Button("Post").post().positive()
        print "<hr>"
        print '<div class="body markdown"><div id="preview"></div></div>'
        print "</div>"
        print "</form>"
        print "</div>"

        print '<button class="btn start-new-note">Add Note</button>'
        print '<div class="clear"></div>'

        header(task, "History", 2)
        chart = TaskChart("chart%d" % id, task)
        chart.js()

        chart.placeholder()
        showHistory(task, False)
        print "<br>"