Creating excell file with Django workbook and worksheet - django

I am trying to create excell report with django workbook and workseet as below.
def print_assistant_notes(request):
if request.method == 'GET':
notes = AssistantNotes.objects.filter(notedate=datetime.today().date()).order_by("time")
workbook = load_workbook(os.path.join(settings.BASE_DIR, "export_templates", "assistant_notes.xlsx"))
worksheet = workbook.active
title_cell = worksheet["A%d" % (1,)]
title_cell.value = "Assistant Notes [ "+str(datetime.today().date())+" ] "
row = 3
for note in notes:
time_cell = worksheet["A%d" % (row,)]
category_cell = worksheet["B%d" % (row,)]
note_cell = worksheet["C%d" % (row,)]
time_cell.value = note.time
category_cell.value = note.categories
note_cell.value = note.dailynote
row = row + 1
tmp_file = tempfile.NamedTemporaryFile()
workbook.save(tmp_file.name)
response = HttpResponse(smart_str(tmp_file.read()), content_type='application/vnd.ms-excel')
response["Content-Disposition"] = 'attachment; filename="assistant_notes.xlsx"'
return response
When i print report i get excell report as below in red color data. But i want it to be formatted as blue colored format. Because notes colum does not fit in print area as i mentioned it with blue arrow.
So i can say that my codes are generating report as the red part.
But i want it to fit in the printable area in blue part. So i want to be able to set cell sizes. And text will fit in that cell size left to right. Up to down cell size will be dynamic as text size may change.

If you're using openpyxl, you can actually change the styles of your cells, as outlined in the documentation:
from openpyxl.styles import Alignment
note_cell.alignment = Alignment(wrap_text=True)
Or create an alignment object before your for... loop and reuse it:
al = Alignment(wrap_text=True)
for note in notes:
...
note_cell = worksheet["C%d" % (row,)]
note_cell.alignment = al
which will be more memory-efficient.

Related

Joining of curve fitting models

I have this 7 quasi-lorentzian curves which are fitted to my data.
and I would like to join them, to make one connected curved line. Do You have any ideas how to do this? I've read about ComposingModel at lmfit documentation, but it's not clear how to do this.
Here is a sample of my code of two fitted curves.
for dataset in [Bxfft]:
dataset = np.asarray(dataset)
freqs, psd = signal.welch(dataset, fs=266336/300, window='hamming', nperseg=16192, scaling='spectrum')
plt.semilogy(freqs[0:-7000], psd[0:-7000]/dataset.size**0, color='r', label='Bx')
x = freqs[100:-7900]
y = psd[100:-7900]
# 8 Hz
model = Model(lorentzian)
params = model.make_params(amp=6, cen=5, sig=1, e=0)
result = model.fit(y, params, x=x)
final_fit = result.best_fit
print "8 Hz mode"
print(result.fit_report(min_correl=0.25))
plt.plot(x, final_fit, 'k-', linewidth=2)
# 14 Hz
x2 = freqs[220:-7780]
y2 = psd[220:-7780]
model2 = Model(lorentzian)
pars2 = model2.make_params(amp=6, cen=10, sig=3, e=0)
pars2['amp'].value = 6
result2 = model2.fit(y2, pars2, x=x2)
final_fit2 = result2.best_fit
print "14 Hz mode"
print(result2.fit_report(min_correl=0.25))
plt.plot(x2, final_fit2, 'k-', linewidth=2)
UPDATE!!!
I've used some hints from user #MNewville, who posted an answer and using his code I got this:
So my code is similar to his, but extended with each peak. What I'm struggling now is replacing ready LorentzModel with my own.
The problem is when I do this, the code gives me an error like this.
C:\Python27\lib\site-packages\lmfit\printfuncs.py:153: RuntimeWarning:
invalid value encountered in double_scalars [[Model]] spercent =
'({0:.2%})'.format(abs(par.stderr/par.value))
About my own model:
def lorentzian(x, amp, cen, sig, e):
return (amp*(1-e)) / ((pow((1.0 * x - cen), 2)) + (pow(sig, 2)))
peak1 = Model(lorentzian, prefix='p1_')
peak2 = Model(lorentzian, prefix='p2_')
peak3 = Model(lorentzian, prefix='p3_')
# make composite by adding (or multiplying, etc) components
model = peak1 + peak2 + peak3
# make parameters for the full model, setting initial values
# using the prefixes
params = model.make_params(p1_amp=6, p1_cen=8, p1_sig=1, p1_e=0,
p2_ampe=16, p2_cen=14, p2_sig=3, p2_e=0,
p3_amp=16, p3_cen=21, p3_sig=3, p3_e=0,)
rest of the code is similar like at #MNewville
[![enter image description here][3]][3]
A composite model for 3 Lorentzians would look like this:
from lmfit import Model, LorentzianModel
peak1 = LorentzianModel(prefix='p1_')
peak2 = LorentzianModel(prefix='p2_')
peak3 = LorentzianModel(prefix='p3_')
# make composite by adding (or multiplying, etc) components
model = peak1 + peaks2 + peak3
# make parameters for the full model, setting initial values
# using the prefixes
params = model.make_params(p1_amplitude=10, p1_center=8, p1_sigma=3,
p2_amplitude=10, p2_center=15, p2_sigma=3,
p3_amplitude=10, p3_center=20, p3_sigma=3)
# perhaps set bounds to prevent peaks from swapping or crazy values
params['p1_amplitude'].min = 0
params['p2_amplitude'].min = 0
params['p3_amplitude'].min = 0
params['p1_sigma'].min = 0
params['p2_sigma'].min = 0
params['p3_sigma'].min = 0
params['p1_center'].min = 2
params['p1_center'].max = 11
params['p2_center'].min = 10
params['p2_center'].max = 18
params['p3_center'].min = 17
params['p3_center'].max = 25
# then do a fit over the full data range
result = model.fit(y, params, x=x)
I think the key parts you were missing were: a) just add models together, and b) use prefix to avoid name collisions of parameters.
I hope that is enough to get you started...

Creating tables using plotly

I am using plotly offline to create a table.But the output is displayed as a single row,not as shown in the output format given in the following link(i.e not as a table)
https://plot.ly/python/table/#changing-row-and-column-size(“Changing Row and column size”)
Here is the code,
import plotly
import plotly.graph_objs as go
#plotly.offline.init_notebook_mode()
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
values = [[['geneNames', 'uniprotIDs', 'ec-code', 'subcellularLocation', 'tissueSpecificity',
'proteinName', 'subunit', 'species']], [[' G6PC', ' P35575', ' 3.1.3.9',
' Endoplasmic reticulum membrane', 'No Data', ' Glucose-6-phosphatase alpha',
'No Data', ' Homo sapiens']]]
trace0 = go.Table(
type = 'table',
columnorder = [1,2],
columnwidth = [80,400],
header = dict(
values = [['<b>PARAMETERS</b>'],
['<b>VALUES</b>']],
line = dict(color = '#506784'),
fill = dict(color = '#119DFF'),
align = ['left','center'],
font = dict(color = 'white', size = 12),
height = 40
),
cells = dict(
values = values,
line = dict(color = '#506784'),
fill = dict(color = ['#25FEFD', 'white']),
align = ['left', 'center'],
font = dict(color = '#506784', size = 12),
height = 30
))
data = [trace0]
plot(data)
I would like to ask for some help
EDIT:
Would it be possible to save the table in png/txt format?I tried replacing 'uniprot.html' with 'uniprot.png'. But the file gets saved as uniprot.png.html.
Looks like as if the document and the current version of Plotly are out of sync. Try using a simple of list of two lists (column 1 and column 2).
values = [['geneNames', 'uniprotIDs', 'ec-code', 'subcellularLocation', 'tissueSpecificity', 'proteinName', 'subunit', 'species'],
[' G6PC', ' P35575', ' 3.1.3.9', ' Endoplasmic reticulum membrane', 'No Data', ' Glucose-6-phosphatase alpha', 'No Data', ' Homo sapiens']
]
Regarding your question about saving (figures) as PNG, check out orca. This is the graphing engine which sits behind plotly.
To be honest, it's a little fiddly at first, but easy once you get going, and it provides PNG support!

Python - reading text file delimited by semicolon, ploting chart using openpyxl

I have copied the text file to excel sheet separating cells by ; delimiter.
I need to plot a chart using the same file which I achieved. Since all the values copied are type=str my chart gives me wrong points.
Please suggest to overcome this. Plot is should be made of int values
from datetime import date
from openpyxl import Workbook,load_workbook
from openpyxl.chart import (
LineChart,
Reference,
Series,
)
from openpyxl.chart.axis import DateAxis
excelfile = "C:\Users\lenovo\Desktop\how\openpychart.xlsx"
wb = Workbook()
ws = wb.active
f = open("C:\Users\lenovo\Desktop\sample.txt")
data = []
num = f.readlines()
for line in num:
line = line.split(";")
ws.append(line)
f.close()
wb.save(excelfile)
wb.close()
wb = load_workbook(excelfile, data_only=True)
ws = wb.active
c1 = LineChart()
c1.title = "Line Chart"
##c1.style = 13
c1.y_axis.title = 'Size'
c1.x_axis.title = 'Test Number'
data = Reference(ws, min_col=6, min_row=2, max_col=6, max_row=31)
series = Series(data, title='4th average')
c1.append(series)
data = Reference(ws, min_col=7, min_row=2, max_col=7, max_row=31)
series = Series(data, title='Defined Capacity')
c1.append(series)
##c1.add_data(data, titles_from_data=True)
# Style the lines
s1 = c1.series[0]
s1.marker.symbol = "triangle"
s1.marker.graphicalProperties.solidFill = "FF0000" # Marker filling
s1.marker.graphicalProperties.line.solidFill = "FF0000" # Marker outline
s1.graphicalProperties.line.noFill = True
s2 = c1.series[1]
s2.graphicalProperties.line.solidFill = "00AAAA"
s2.graphicalProperties.line.dashStyle = "sysDot"
s2.graphicalProperties.line.width = 100050 # width in EMUs
##s2 = c1.series[2]
##s2.smooth = True # Make the line smooth
ws.add_chart(c1, "A10")
##
##from copy import deepcopy
##stacked = deepcopy(c1)
##stacked.grouping = "stacked"
##stacked.title = "Stacked Line Chart"
##ws.add_chart(stacked, "A27")
##
##percent_stacked = deepcopy(c1)
##percent_stacked.grouping = "percentStacked"
##percent_stacked.title = "Percent Stacked Line Chart"
##ws.add_chart(percent_stacked, "A44")
##
### Chart with date axis
##c2 = LineChart()
##c2.title = "Date Axis"
##c2.style = 12
##c2.y_axis.title = "Size"
##c2.y_axis.crossAx = 500
##c2.x_axis = DateAxis(crossAx=100)
##c2.x_axis.number_format = 'd-mmm'
##c2.x_axis.majorTimeUnit = "days"
##c2.x_axis.title = "Date"
##
##c2.add_data(data, titles_from_data=True)
##dates = Reference(ws, min_col=1, min_row=2, max_row=7)
##c2.set_categories(dates)
##
##ws.add_chart(c2, "A61")
### setup and append the first series
##values = Reference(ws, (1, 1), (9, 1))
##series = Series(values, title="First series of values")
##chart.append(series)
##
### setup and append the second series
##values = Reference(ws, (1, 2), (9, 2))
##series = Series(values, title="Second series of values")
##chart.append(series)
##
##ws.add_chart(chart)
wb.save(excelfile)
wb.close()
I have modified below code in for loop and it worked.
f = open("C:\Users\lenovo\Desktop\sample.txt")
data = []
num = f.readlines()
for line in num:
line = line.split(";")
new_line=[]
for x in line:
if x.isdigit():
x=int(x)
new_line.append(x)
else:
new_line.append(x)
ws.append(new_line)
f.close()
wb.save(excelfile)
wb.close()
For each list,for each value check if its a digit, if yes converts to integer and store in another list.
Using x=map(int,x) didnt work since I have character values too.
I felt above is much more easy than using x=map(int,x) with try and Except
Thanks
Basha

Printing Results from Loops

I currently have a piece of code that works in two segments. The first segment opens the existing text file from a specific path on my local drive and then arranges, based on certain indices, into a list of sub list. In the second segment I take the sub-lists I have created and group them on a similar index to simplify them (starts at def merge_subs). I am getting no error code but I am not receiving a result when I try to print the variable answer. Am I not correctly looping the original list of sub-lists? Ultimately I would like to have a variable that contains the final product from these loops so that I may write the contents of it to a new text file. Here is the code I am working with:
from itertools import groupby, chain
from operator import itemgetter
with open ("somepathname") as g:
# reads text from lines and turns them into a list sub-lists
lines = g.readlines()
for line in lines:
matrix = line.split()
JD = matrix [2]
minTime= matrix [5]
maxTime= matrix [7]
newLists = [JD,minTime,maxTime]
L = newLists
def merge_subs(L):
dates = {}
for sub in L:
date = sub[0]
if date not in dates:
dates[date] = []
dates[date].extend(sub[1:])
answer = []
for date in sorted(dates):
answer.append([date] + dates[date])
new code
def openfile(self):
filename = askopenfilename(parent=root)
self.lines = open(filename)
def simplify(self):
g = self.lines.readlines()
for line in g:
matrix = line.split()
JD = matrix[2]
minTime = matrix[5]
maxTime = matrix[7]
self.newLists = [JD, minTime, maxTime]
print(self.newLists)
dates = {}
for sub in self.newLists:
date = sub[0]
if date not in dates:
dates[date] = []
dates[date].extend(sub[1:])
answer = []
for date in sorted(dates):
print(answer.append([date] + dates[date]))
enter code here
enter code here

How to store the user selected input from a Listbox

This is much like a traveling salesman problem. I have a Listbox with college names in it(backed with coordinates I grabbed from the Facebook Graph). I have the selection mode set to multiple. I need to know the code that will allow me to use the colleges they selected so i can put them through a distance method. I only need to know the code to see what they selected. I tried using curselection() but I still do not understand it.
Here is some code:
self.listbox = Listbox(self.mid_frame,width = 42,selectmode ="multiple",
highlightcolor = "orange",
highlightthickness = "10",bd = "5")
coordinates = []
collegelist = []
f = open(sys.argv[1],'r')
# grab the college's lat and long from facebook graph
for identity in f:
urlquery='https://graph.facebook.com/'+identity
obj = json.load(urllib2.urlopen(urlquery))
college = obj["name"]
latitude = obj["location"]["latitude"]
longitude = obj["location"]["longitude"]
coordinates.append((college,latitude, longitude))
collegelist.append(college)
#sort the colleges so they appear alphabetical order
sortcollege = sorted(collegelist)
#fill Listbox with the College names imported from a text file
for college in sortcollege:
self.listbox.insert(END, college)
self.listbox.pack(side = LEFT)
#The label where I would put the total distance
self.output_totaldist_label = Label(self.mid_frame,
width = 11,
textvariable = self.totaldistance)
self.totaldistance = StringVar()
self.output_label = Label(self.mid_frame,
textvariable = self.totaldistance)
self.output_totaldist_label.pack(side = LEFT)
self.output_label.pack(side = LEFT)
It would have been nice to see how you tried curselection to see what went wrong.
Something like:
for idx in self.listbox.curselection():
selitem = self.listbox.get(idx)
should do the trick. Have you tried that?