I was trying to make an extension to a mcedit filter, originally by CrushedPixel, edited by NanoRex. That version they made doesn't support 1.9 snapshots / blocks, so I decided to make a better, lagless version that does!
Here's the code:
# MCEdit Filter by CrushedPixel
# http://youtube.com/CrushedPixel
# Heavily Modified by NanoRex
# Major bug (and some minor ones) fixed by NanoRex
# http://youtube.com/thecaptainrex7567
from pymclevel import TAG_List
from pymclevel import TAG_Byte
from pymclevel import TAG_Int
from pymclevel import TAG_Compound
from pymclevel import TAG_Short
from pymclevel import TAG_Double
from pymclevel import TAG_String
import math
from pymclevel import MCSchematic
import mcplatform
displayName = "JetDirectionsMod"
CmdBlockTypes = {
"Normal" : 137,
"Chain" : 211,
"Repeating" : 210,
}
CmdDataTypes = {
"Facing DOWN": 0,
"Facing UP": 1,
"Facing NORTH": 2,
"Facing SOUTH": 3,
"Facing WEST": 4,
"Facing EAST": 5,
}
DataKeys = ()
for key in CmdBlockTypes.keys():
DataKeys = DataKeys + (key,)
DataTypeKeys = ()
for key in CmdDataTypes.keys():
DataTypeKeys = DataTypeKeys + (key,)
inputs = (
("Placeholders: $rot | $mot | $dir","label"),
("Accuracy (Degrees)", (5,1,20)),
("Motion Factor", (0.1,9.0)),
("Set Position to In Front of Player:","label"),
("Placeholder: $pos","label"),
("Set Position", False),
("Distance From Player", (1,5)),
("Relative Y Position", (0,-1000,1000)),
("Command Block Type:", DataKeys),
("Commandblock Rotation:", DataTypeKeys),
)
def perform(level, box, options):
fac = options["Accuracy (Degrees)"]
speed = options["Motion Factor"]
adjustPos = options["Set Position"]
adjustAmount = options["Distance From Player"]
ypos = options["Relative Y Position"]
C = CmdBlockTypes[options["Command Block Type:"]]
D = CmdDataTypes[options["Commandblock Rotation:"]]
C = C, ' ', D
found = False
for x in xrange(box.minx,box.maxx):
if not found:
for y in xrange(box.miny,box.maxy):
if not found:
for z in xrange(box.minz,box.maxz):
te = level.tileEntityAt(x,y,z)
if te != None:
try:
text = te["Command"].value
found = True
break
except:
pass
commands = []
if not found:
raise Exception("Please select a command block in order to run this filter.")
for y in range(-90/fac,90/fac):
rxm = y*fac
rx = ((y+1)*fac)-1
if rx == 89 :
rx += 1
for x in range(-180/fac,180/fac):
rym = x*fac
ry = ((x+1)*fac)-1
if ry == 179 :
ry +=1
xdeg = math.radians(((x+1)*fac)-(fac/2))
ydeg = math.radians(((y+1)*fac)-(fac/2))
xmov = -speed*(math.sin(xdeg)*math.cos(ydeg))
ymov = -speed*math.sin(ydeg) + 0.1
zmov = speed*(math.cos(xdeg)*math.cos(ydeg))
cmd = text.replace("$rot", "rxm="+str(rxm)+",rx="+str(rx)+",rym="+str(rym)+",ry="+str(ry))
cmd = cmd.replace("$mot", "Motion:["+str(xmov)+","+str(ymov)+","+str(zmov)+"]")
cmd = cmd.replace("$dir", "direction:["+str(xmov)+","+str(ymov)+","+str(zmov)+"]")
if adjustPos == True :
if -67.5 < ((x+1)*fac)-(fac/2) < 67.5 :
zadj = adjustAmount
elif -180 <= ((x+1)*fac)-(fac/2) < -112.5 or 180 >= ((x+1)*fac)-(fac/2) > 112.5 :
zadj = -adjustAmount
else:
zadj = 0
if 22.5 < ((x+1)*fac)-(fac/2) < 157.5 :
xadj = -adjustAmount
elif -22.5 > ((x+1)*fac)-(fac/2) > -157.5 :
xadj = adjustAmount
else:
xadj = 0
cmd = cmd.replace("$pos", "~"+str(xadj)+" ~"+str(ypos)+" "+"~"+str(zadj))
commands.append(cmd)
number = len(commands)
size = math.sqrt(number/2)
rs = math.ceil(size)
if rs ** 2 > 4096 :
raise Exception("Too many command blocks for the /fill command. Increase \"Accuracy (Degrees)\" to solve this.")
schematic = MCSchematic((rs+2,4,rs+2), mats = level.materials)
i = 0
xc = 1
zc = -1
schematic.setBlockAt(1,3,0,210)
schematic.TileEntities.append(cmdBlockTe(1,3,0,"/fill ~ ~-2 ~1 ~"+str(int(rs))+" ~-2 ~"+str(int(rs+1))+" minecraft:redstone_block"))
schematic.setBlockAt(0,3,1,210)
schematic.TileEntities.append(cmdBlockTe(0,3,1,"/fill ~1 ~-2 ~ ~"+str(int(rs+1))+" ~-2 ~"+str(int(rs))+" minecraft:stone"))
for x in range(1, int(rs+2)):
xc += 1
for z in range(1, int(rs+2)):
zc += 1
y = 2
if i < number:
cmd = commands[i]
schematic.setBlockAt(x, y, z, C, D)
control = cmdBlockTe(x, y, z, cmd)
schematic.TileEntities.append(control)
i += 1
y = 0
if i < number:
cmd = commands[i]
schematic.setBlockAt(x, y, z, C)
control = cmdBlockTe(x, y, z, cmd)
schematic.TileEntities.append(control)
i += 1
zc = -1
schematic_file = mcplatform.askSaveFile(mcplatform.lastSchematicsDir or mcplatform.schematicsDir, "Save Schematic As...", "", "Schematic\0*.schematic\0\0", ".schematic")
if schematic_file == None:
print "ERROR: No schematic filename provided!"
return
schematic.saveToFile(schematic_file)
def cmdBlockTe(x,y,z,cmd):
control = TAG_Compound()
control["Command"] = TAG_String(cmd)
control["id"] = TAG_String(u'Control')
control["CustomName"] = TAG_String(u'#')
control["z"] = TAG_Int(z)
control["y"] = TAG_Int(y)
control["x"] = TAG_Int(x)
return control
This gives me the error: "Setting up an array element with senquence."
Here's some screens of what is this used to, and what's the problem:
Screen 1, Screen 2. Okay, so now I know what causes the problem. How can I solve it? I really want to get it working :l
C = C, ' ', D that creates a sequence, ie. something like (<Original C>, ' ', <Original D>), so when you're doing schematic.setBlockAt(x, y, z, C) your argument of C is a sequence, when it's expecting a single item.
Related
I'm trying to standardize street address by converting the abbreviations to the full word (e.g. RD - Road). I created many lines to account for different spellings and ran into an issue where one replace code overrode another one
import pandas as pd
mydata = {'Street_type': ['PL', 'pl', 'Pl', 'PLACE', 'place']}
mydata = pd.DataFrame(mydata)
mydata['Street_type'] = mydata['Street_type'].replace('PL','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('pl','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('Pl','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('PLACE','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('place','Place',regex=True)
Instead of Place, I got Placeace. What is the best way to avoid this error? Do I write a if-else statement or any function? Thanks in advance!
Among other problems, you have overlapping logic: you fail to check that the target ("old") string is a full word before you replace it. For instance, with the input type of "PLACE", you trigger both the first and third replacements, generating PlaceACE and then PlaceaceACE before you get to the condition you wanted.
You need to work through your tracking and exclusion logic carefully, and then apply only one of the replacements. You can check the length of the street_type and apply the unique transition you need for that length.
If you're trying to convert a case statement, then you need to follow that logic pattern, rather than the successive applications you coded. You can easily look up how to simulate a "case" statement in Python.
Also consider using a translation dictionary, such as
type_trans = {
"pl": "Place",
"Pl": "Place",
"PLACE": "Place",
...
}
Then your change is simply
mydata['Street_type'] = type_trans[mydata['Street_type']]
Also, you might list all of the variants in a tuple, such as:
type_place = ("PL", "Pl", "pl", "PLACE", "place")
if mydata['Street_type'] in type_place
mydata['Street_type'] = "Place"
... but be sure to generalize this properly for your entire list of street types.
You can do this correctly with a single pass if you use a proper regex here, e.g. use word boundaries (\b):
In [11]: places = ["PL", "pl", "Pl", "PLACE", "Place", "place"]
In [12]: mydata.Street_type
Out[12]:
0 PL
1 pl
2 Pl
3 PLACE
4 place
Name: Street_type, dtype: object
In [13]: mydata.Street_type.replace("(^|\b)({})(\b|$)".format("|".join(places)), "Place", regex=True)
Out[13]:
0 Place
1 Place
2 Place
3 Place
4 Place
Name: Street_type, dtype: object
#Needlemanwunch
def zeros(shape):
retval = []
for x in range(shape[0]):
retval.append([])
for y in range(shape[1]):
retval[-1].append(0)
return retval
match_award = 10
mismatch_penalty = -3
gap_penalty = -4 # both for opening and extanding
def match_score(alpha, beta):
if alpha == beta:
return match_award
elif alpha == '-' or beta == '-':
return gap_penalty
else:
return mismatch_penalty
def finalize(align1, align2):
align1 = align1[::-1] #reverse sequence 1
align2 = align2[::-1] #reverse sequence 2
i,j = 0,0
#calcuate identity, score and aligned sequeces
symbol = ''
found = 0
score = 0
identity = 0
for i in range(0,len(align1)):
# if two AAs are the same, then output the letter
if align1[i] == align2[i]:
symbol = symbol + align1[i]
identity = identity + 1
score += match_score(align1[i], align2[i])
# if they are not identical and none of them is gap
elif align1[i] != align2[i] and align1[i] != '-' and align2[i] != '-':
score += match_score(align1[i], align2[i])
symbol += ' '
found = 0
#if one of them is a gap, output a space
elif align1[i] == '-' or align2[i] == '-':
symbol += ' '
score += gap_penalty
identity = float(identity) / len(align1) * 100
print('Similarity =', "%3.3f" % identity, 'percent')
print('Score =', score)
# print(align1)
# print(symbol)
# print(align2)
def needle(seq1, seq2):
m, n = len(seq1), len(seq2) # length of two sequences
# Generate DP table and traceback path pointer matrix
score = zeros((m+1, n+1)) # the DP table
# Calculate DP table
for i in range(0, m + 1):
score[i][0] = gap_penalty * i
for j in range(0, n + 1):
score[0][j] = gap_penalty * j
for i in range(1, m + 1):
for j in range(1, n + 1):
match = score[i - 1][j - 1] + match_score(seq1[i-1], seq2[j-1])
delete = score[i - 1][j] + gap_penalty
insert = score[i][j - 1] + gap_penalty
score[i][j] = max(match, delete, insert)
# Traceback and compute the alignment
align1, align2 = '', ''
i,j = m,n # start from the bottom right cell
while i > 0 and j > 0: # end toching the top or the left edge
score_current = score[i][j]
score_diagonal = score[i-1][j-1]
score_up = score[i][j-1]
score_left = score[i-1][j]
if score_current == score_diagonal + match_score(seq1[i-1], seq2[j-1]):
align1 += seq1[i-1]
align2 += seq2[j-1]
i -= 1
j -= 1
elif score_current == score_left + gap_penalty:
align1 += seq1[i-1]
align2 += '-'
i -= 1
elif score_current == score_up + gap_penalty:
align1 += '-'
align2 += seq2[j-1]
j -= 1
# Finish tracing up to the top left cell
while i > 0:
align1 += seq1[i-1]
align2 += '-'
i -= 1
while j > 0:
align1 += '-'
align2 += seq2[j-1]
j -= 1
finalize(align1, align2)
needle('kizlerlo','killerpo' )
***********************************************************************************************************************
#import textdistance as txd
import numpy
txd.overlap('kizlerlo','kilerpo' )
txd.jaro('kizlerlo','killerpo' )
txd.cosine('kizlerlo','killerpo' )
#txd.needleman_wunsch('kizlerlo','killerpo' )
txd.jaro_winkler('kizlerlo','killerpo' )
#txd.smith_waterman('Loans and Accounts','Loans Accounts' )
#txd.levenshtein.normalized_similarity('Loans and Accounts','Loans Accounts' )
from scipy.spatial import distance
a = 'kizlerlo'
b = 'kilerpoo'
#txd.gotoh('Loans and Accounts','Loans Accounts' )
print(txd.needleman_wunsch.normalized_similarity('Loans and Accounts','Loans Accounts' ))
***************************************************************************************************************************
#Euclidean
import math
import numpy as np
def euclid(str1,str2):
dist=0.0
x=str1
y=str2
set1=set()
for a in range(0,len(x)):
set1.add(x[a])
for a in range(0,len(y)):
set1.add(y[a])
vec1=[None]*len(set1)
vec2=[None]*len(set1)
for counter,each_char in enumerate(set1):
vec1[counter]=x.count(each_char)
vec2[counter]=y.count(each_char)
dist=1/(1+math.sqrt(sum([(a - b) ** 2 for a, b in zip(vec1, vec2)])))
print(dist)
euclid('kizlerlo','killerpo')
***************************************************************************************************************************
from similarity.qgram import QGram
import affinegap
qgram = QGram(2)
#print(qgram.distance('kizlerlo', 'killerpo'))
affinegap.affineGapDistance('kizlerlokill' ,'erpozlerlzler')
***************************************************************************************************************************
#manhattan
def manhattan(str1,str2):
dist=0.0
x=str1
y=str2
set1=set()
for a in range(0,len(x)):
set1.add(x[a])
for a in range(0,len(y)):
set1.add(y[a])
vec1=[None]*len(set1)
vec2=[None]*len(set1)
for counter,each_char in enumerate(set1):
vec1[counter]=x.count(each_char)
vec2[counter]=y.count(each_char)
#dist= sum([np.abs(a - b) for a, b in zip(vec1, vec2)])
dist=1/(1+sum([np.abs(a - b) for a, b in zip(vec1, vec2)]))
print(dist)
manhattan('kizlerlo','killerpo')
import jellyfish
import json
from Levenshtein import distance,jaro_winkler,jaro,ratio,seqratio
def comp(a,b):
return jellyfish.jaro_winkler(a,b)*100 + distance(a,b) + jaro(a,b)*100
ip = {"CED":"WALMART INC_10958553"}
ala = {}
for index,row in df_ala.iterrows():
a = ip.get("CED")
b = row['NN_UID']
c = comp(a,b)
ala.update({row['N_UID'] : c})
ala_max = max(ala, key=ala.get)
ala_f = {"ALACRA" : ala_max}
ces_f = {"CESIUM" : "WALMART_10958553_CESIUM"}
dun_f = {"DUNS" : "WALMART_10958053_DUNS"}
ref_f = {"REF" : "WALMART INC_10958553_REF"}
cax_f = {"CAX" : "WALMART LTD_10958553_CAX"}
final_op = {**ala_f,**ces_f,**dun_f,**ref_f,**cax_f }
final_json = json.dumps(final_op)
print(final_json)
from flask import Flask,request, jsonify
app = Flask(__name__)
#app.route('/test',methods = ['GET','POST'])
def test():
if request.method == "GET":
return jsonify({"response":"Get request called"})
elif request.method == "POST":
req_Json = request.json
name = req_Json['name']
return jsonify({"response": "Hi" + name})
if __name__ == '__main__':
app.run(debug = True,port = 9090)
{
"name": "Mike"
}
import usaddress
import pandas as pd
import statistics
#sa = dict(usaddress.parse('123 Main St. Suite Chicago, IL' ))
adr = pd.read_excel('C:\\VINAYAK\\Address.xlsx')
adr.columns = ['Address']
strlen = []
scr = []
loop = adr['Address'].tolist()
for i in loop:
strlen.append(len(i))
x = statistics.median(strlen)
for i in loop:
sa = dict(usaddress.parse(i))
sa = list(sa.values())
a = 0
if len(i) > x :
a+= 5
if 'AddressNumber' in sa :
a+= 23
if 'StreetName' in sa :
#a = a + 20
a+= 17
if 'OccupancyType' in sa :
a+= 6
if 'OccupancyIdentifier' in sa :
a+= 12
if 'PlaceName' in sa :
a+= 12
if 'StateName' in sa :
a+= 13
if 'ZipCode' in sa :
a+= 12
scr.append(a)
adr['Adr_Score'] = scr
adr.head()
#(pd.DataFrame([(key) for key in sa.items()])).transpose()
#pd.DataFrame(dict([(value, key) for key, value in sa.items()]))
#pd.DataFrame(dict([(value, key) for key, value in sa.items()]))
# df_ts = pd.DataFrame(columns = ['AddressNumber' , 'Age', 'City' , 'Country'])
# df_ts.append(sa, ignore_index=False, verify_integrity=False, sort=None)
# df_ts.head()
import pandas as pd
from zipfile import ZipFile
# core = []
# f = open('C:/Users/s.natarajakarayalar/1.txt','r')
# core.append(str(f.readlines()))
# print(core)
import os
import zipfile
import re
import nltk
import os
core = []
with zipfile.ZipFile('C:/Users/s.natarajakarayalar/TF.zip') as z:
a = 0
for filename in z.namelist():
#if a < 1:
#if not os.path.isdir(filename):
# read the file
with z.open(filename) as f:
#a = 2
x = f.readlines()
core = core + x
with open('C:/Users/s.natarajakarayalar/fins.txt', 'w') as f:
for item in core:
f.write("%s\n" % item)
# for i in core:
# if k < 5:
# tkt = re.sub(r'.*CONTENT', '', i)
# new_core.append(tkt)
# k = k+1
# for item in core:
# new_core.append(len(item.split()))
# print(sum(new_core))
# from nltk.tokenize import word_tokenize
# new_core = []
# stp = ['URL:https://','TITLE:b','META-KEYWORDS:','None','DOC ID:','CONTENT:b','URL:','TITLE:','META-CONTENT:']
# #new_core = [word for word in core if word not in stopwords]
# for i in core:
# wk = word_tokenize(i)
# for w in wk:
# if w not in stp:
# new_core.append(w)
I'm trying to make biggest ellipse inside arbitrary polygon.
So, I made the equation of ellipse and constraint .
objective : minimize A*B (mimimaze 1/area)
st. A**2*(x-x0)**2+B**2*(y-y0)**2 = 0
x/100.0 + y/80.0 < 1
x/-20.0 + y/80.0 < 1
x/-40.0 + y/-40.0 > 1
x/100.0 + y/-60.0 > 1
then I made optimization code using Scipy like below
But my code makes False result. (Success : False).
Can you explain why my code cannot make successful result? due to false constraint? wrong coding? Note that I don't need tilted ellipse.
import numpy as np
from scipy.optimize import minimize
def objective(C):
A = C[0] ; B = C[1] ; x0 = C[2] ; y0 = C[3] ; x = C[4] ; y = C[5]
return A*B
def constraint1(C):
A = C[0] ; B = C[1] ; x0 = C[2] ; y0 = C[3] ; x = C[4] ; y = C[5]
return (x/100.0+y/80.0-1)*-1
def constraint2(C):
A = C[0] ; B = C[1] ; x0 = C[2] ; y0 = C[3] ; x = C[4] ; y = C[5]
return (x/-100.0+y/80.0-1)*-1
def constraint3(C):
A = C[0] ; B = C[1] ; x0 = C[2] ; y0 = C[3] ; x = C[4] ; y = C[5]
return (x/-100.0+y/-80.0-1)*-1
def constraint4(C):
A = C[0] ; B = C[1] ; x0 = C[2] ; y0 = C[3] ; x = C[4] ; y = C[5]
return (x/100.0+y/-80.0-1)*-1
def constraint5(C):
A = C[0] ; B = C[1] ; x0 = C[2] ; y0 = C[3] ; x = C[4] ; y = C[5]
return A**2*(x-x0)**2+B**2*(y-y0)**2-1
xeval = [1,1,0,0,0,0]
bnds = ( (0.001,1),(0.001,1),(-100,100),(-100,100),(-500,500),(-500,500) )
con1 = {'type': 'ineq','fun':constraint1}
con2 = {'type': 'ineq' , 'fun':constraint2}
con3 = {'type': 'ineq','fun':constraint3}
con4 = {'type': 'ineq' , 'fun':constraint4}
con5 = {'type': 'eq' , 'fun':constraint5}
cons = [con1,con2,con3,con4,con5]
sol = minimize(objective,xeval,method='SLSQP',bounds=bnds,constraints=cons)
I made poor answer for some arbitrary polygon. I found using convex optimization might be bad for non-ideal polygon. I made this application to calculate lithography pw window. I hope someone make better solution.
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 14 00:20:43 2018
#author: hafss
"""
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import numpy as np
step = 0.3
px_old = [1,8,11,20,25,40, 30,5 ,2 ,1,1 ]
py_old = [1,2,5, 4 ,2, 8 , 15,14,11,5,1 ]
init_point = [5,4]
init_radius = step
px = []
py = []
for i in range(len(px_old)-1):
dx = px_old[i+1]-px_old[i]
dy = py_old[i+1]-py_old[i]
len1 = (dx*dx+dy*dy)**0.5
px.append(px_old[i])
py.append(py_old[i])
if len1 > step:
count = int(len1/step)
for ii in range(count):
#print px_old[i]+ 1.0*ii/count*dx
#print py_old[i]+ 1.0*ii/count*dy
px.append(px_old[i]+ 1.0*ii/count*dx )
py.append(py_old[i]+ 1.0*ii/count*dy )
px.append(px_old[-1])
py.append(py_old[-1])
plt.figure()
plt.plot(px,py,color='r')
#plt.plot(px_old,py_old,)
ax = plt.gca()
minrr = 6
def check_inner(poly_x,poly_y,a,b,x0,y0 ):
minrr = 5
for i in range(len(poly_x)):
x=poly_x[i]
y=poly_y[i]
rr = ((x-x0)/a)**2+((y-y0)/b)**2
if rr < minrr:
minrr = rr
#if rr < 1 :
# badpoint.append([x,y])
return minrr
def draw_ellips(handle,xc,yc,a,b,color,lw):
ellipse = Ellipse(xy=(xc, yc), width=a*2, height=b*2,
edgecolor=color, fc='None', lw=lw)
handle.add_patch(ellipse)
def get_jumperpoint(poly_x,poly_y,sizeup,a,b,x0,y0 ):
badx = []
bady = []
for i in range(len(poly_x)):
x=poly_x[i]
y=poly_y[i]
rr = ((x-x0)/(a+sizeup))**2+((y-y0)/(b+sizeup))**2
if rr < 1 :
badx.append(x)
bady.append(y)
xmean = np.asarray(badx).mean()
ymean = np.asarray(bady).mean()
xmove = x0-xmean
ymove = y0-ymean
return [xmove,ymove]
rx = init_radius
ry = init_radius
xc = init_point[0]
yc = init_point[1]
maxarea = step*step
for iterat in range(90):
print "iterate start %s (%s,%s)->(%s,%s)" % (iterat,xc,yc,rx,ry)
s1 = step
s2 = step
s3 = step
draw_ellips(ax,xc,yc,rx,ry,'blue',0.5)
rxprev = rx
ryprev = ry
xcprev = xc
ycprev = yc
if check_inner(px,py,rx+s1,ry+s2,xc,yc) >= 1 :
rx = rx+s1
ry = ry+s2
# enlarge
if check_inner(px,py,rx+s1,ry,xc,yc) >= 1 :
rx = rx+s1
if check_inner(px,py,rx,ry+s1,xc,yc) >= 1 :
ry = ry+s1
#distortion
if check_inner(px,py,rx+s1,ry-s2,xc,yc) >= 1 and (rx+s1)*(ry-s2) > rx*ry :
rx = rx+s1
ry = ry-s2
if check_inner(px,py,rx-s1,ry+s2,xc,yc) >= 1 and (rx-s1)*(ry+s2) > rx*ry :
rx = rx-s1
ry = ry+s2
#shift # enlarge (right dir )
if check_inner(px,py,rx+s1,ry,xc+s2,yc) >= 1 :
rx = rx+s1
xc = xc+s2
if check_inner(px,py,rx+s1,ry,xc-s2,yc) >= 1 :
rx = rx+s1
xc = xc-s2
if check_inner(px,py,rx,ry+s1,xc,yc+s2) >= 1 :
ry = ry+s1
yc = yc+s2
if check_inner(px,py,rx,ry+s1,xc,yc-s2) >= 1 :
ry = ry+s1
yc = yc-s2
if check_inner(px,py,rx,ry,xc,yc) < 1 :
rx = rx-2*step-0.001
ry = ry-2*step-0.001
if rx < 0.001 : rx = 0.001
if ry < 0.001 : ry = 0.001
print "reduce"
print "iterate end %s (%s,%s)->(%s,%s) best %s " % (iterat,xc,yc,rx,ry,maxarea)
if rx == rxprev and ry == ryprev and xcprev == xc and ycprev== yc and check_inner(px,py,rx,ry,xc,yc) >= 1 :
[jx,jy] = get_jumperpoint(px,py,step*5,rx,ry,xc,yc )
print "jump %s %s -> %s %s" % (xc,yc,xc+jx,yc+jy)
xc = xc+jx
yc = yc+jy
if rx*ry > maxarea :
bestiter = iterat
bestx = xc
besty = yc
besta = rx
bestb = ry
maxarea = rx*ry
print "best iter %s center %s %s radius %s %s" % (bestiter,bestx,besty,besta,besty)
draw_ellips(ax,bestx,besty,besta,bestb,'red',2) # best ellipse
draw_ellips(ax,xc,yc,rx,ry,'green',3) # final iter
check_inner(px,py,11.8,4.3,13.6,9.4)
import os
import sys
import math
import cvxopt as cvx
import picos as pic
import pandas as pd
import matplotlib.pyplot as plt
from gurobipy import *
from statsmodels.tsa.arima_model import ARIMA
import numpy as np
from scipy import *
#import DeferableLoad
OPTmodel = Model('OPTIMIZER')
#general parameters
Tamb =22
N = 1440 # maximum iteration
i = range(1, N)
COP= 3.4 # Coeffient of performance
'''
Prediction need to be added here
'''
# Datacenter room defintion
R = 10 #length of room
B = 7
H = 9 #Height of room
L = 10
dT = 60
A = 2*((L*B)+(B*H)+(H*L))
Thick = 0.33 # thickness of wall
k = 0.7 # thermal conductivity of wall
mAir = 1.2 * (L * B * H)
C = 718
landa = k * A / Thick
a0 = 0.05 / dT
a1 = 1
ki = math.exp(-(landa * 60) / (mAir * C)) # value that constant and its related to property of room
kc = (1 - ki) * a0
ko = (1 - ki) * a1
kp = (1 - ki) * (COP / landa)
Tmin= 18
Tmax= 27
Tamb= 22
PcoolingRated = 100
Pbess_rated = 30.462
Pbess_ratedN = -30.462
Ebess_min = 0
Ebess_max = 300
with open ('Pcooling.csv','r') as f:
Pcooling = []
for line in f:
Pcooling.append(line)
f.close()
with open ('ITpower.csv','r') as f1:
ITload = []
for line1 in f1:
ITload.append(line1)
f1.close()
with open ('DR.csv','r') as f2:
DR =[]
for line2 in f2:
DR.append(line2)
f2.close()
print ITload
print Pcooling
print DR
for i in range(1,200):
for it in range(1, 1440):
Tm = np.empty(1440)
Tm.fill(18)
TmA = np.empty(1440)
TmA.fill(27)
Phvac_flex = {}
Phvac_up = {}
Phvac_down_= {}
Phvac_up_ = {}
Pbess_out_ = {}
Pbess_in_ = {}
Phvac_down = {}
Pbess_flex_ = {}
Pbess_flex = {}
Phvac_flex_ = {}
Pbess_in = {}
Pdc = {}
Pdc_base = {}
Pflex_i = {}
Tdc_i = {}
Pbess_out ={}
Ebess_i = {}
Phvac_flex[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS,name="PHVAC_flex"+str(i))
Phvac_up[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_up" + str(i))
Phvac_up_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_up_" + str(i))
Phvac_down_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_down_" + str(i))
Pbess_out_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_out_" + str(i))
Pbess_in_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_in_" + str(i))
Phvac_down[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_down" + str(i))
Pbess_flex_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_flex_" + str(i))
Pbess_flex[i] = OPTmodel.addVar(lb=-GRB.INFINITY,ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_flex" + str(i))
Phvac_flex_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_flex_" + str(i))
Pbess_in[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_in" + str(i))
Pdc[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PDC" + str(i))
Pdc_base[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PDC_base" + str(i))
Pflex_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="Pflex_i" + str(i))
Tdc_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype = GRB.CONTINUOUS, name = "Tdc_i" + str(i))
Pbess_out[i] = OPTmodel.addVar(lb=-GRB.INFINITY,ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_out" + str(i))
Ebess_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS,name="Ebess_i" + str(i))
Pflex_i[1] = 0
Pflex_i[1] = 0
Tdc_i[0] = 18
Phvac_flex[1] = 0
# Phvac_flex_[1] = 0
Phvac_down[1] = 0
Phvac_up[1] = 0
Phvac_down_[1] = 0
Phvac_up_[1] = 0
# Phvac_down_pos[1] = 0
# Phvac_up_pos(1) = 0;
Pbess_flex[1] = 0
# Pbess_flex_[1] = 0
Pbess_out[1] = 0
Pbess_in[1] = 0
# Pbess_out_[1] = 0
Pbess_in_[1] = 0
# Pbess_out_pos[1] = -250
# Pbess_in_pos(1) = 250;
Ebess_i[1] = 150
OPTmodel.update()
'''
if float(DR[i]) > 0:
Phvac_down_[i] = 0
Phvac_up_[i] = float(DR[i])
Pbess_out_[i] = 0
Pbess_in_[i] = float(DR[i])
#Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
#Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
OPTmodel.update()
elif float(DR[i]) < 0:
Phvac_down_[i] = float(DR[i])
Phvac_up_[i] = 0
#Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
Pbess_out_[i] = float(DR[i])
Pbess_in_[i] = 0
#Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
OPTmodel.update()
else:
Phvac_down_[i] = 0
Phvac_up_[i] = 0
Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
Pbess_out_[i] = 0
Pbess_in_[i] = 0
Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
OPTmodel.update()
'''
#print Phvac_up.values()
#print Phvac_flex_[i]
print OPTmodel
OPTmodel.update()
ConHVAC1 = OPTmodel.addConstr(Phvac_flex[i] == Phvac_up[i] + Phvac_down[i], name='ConHVAC1')
ConHVAC2 = OPTmodel.addConstr(0 <= Phvac_flex[i] , name='ConHVAC2')
ConHVAC3 = OPTmodel.addConstr(Phvac_flex[i] <= PcoolingRated, name='ConHVAC3')
PH = pd.read_csv('Pcooling.csv')
PHVAC = PH.values
newList2 = map(lambda x: x / 1000, PHVAC)
p=[]
p=PcoolingRated-newList2[i]
#CONHVAC4 = OPTmodel.addConstr(Phvac_up[i]==np.minimum((Phvac_up_[i]),(float(newList2[i]))))
#Phvac_u(1:MaxIter) == min(Phvac_u_(1:MaxIter), (repelem(Phvac_max, MaxIter) - (Pcooling(1:MaxIter)'/1000)))
ConTemp1 = OPTmodel.addConstr(Tm[it] <= Tdc_i[i] <= TmA[it], name='ConTemp1')
ConBESS1 = OPTmodel.addConstr(Pbess_ratedN <= Pbess_flex[i] <= Pbess_rated, name='ConBESS1')
ConBESS2 = OPTmodel.addConstr(Pbess_flex[i] == Pbess_in[i] + Pbess_out[i], name='ConBESS2')
ConBESS3 = OPTmodel.addConstr(0 <= Pbess_in[i] <= min(Pbess_rated, Pbess_in_[i]), name='ConBESS3')
ConBESS4 = OPTmodel.addConstr(np.maximum(Pbess_ratedN,Pbess_out_[i]) <= Pbess_out[i]<=0 , name='ConBESS4') # need to modifty
ConEBESS1 = OPTmodel.addConstr(Ebess_min <= Ebess_i[i], name='ConEBESS1')
ConEBESS2 = OPTmodel.addConstr(Ebess_i[i] <= Ebess_max, name='ConEBESS2')
D = pd.read_csv('DR.csv').values
DRN = map(lambda x: x / 1000, D)
PDRN=map(lambda x: x / 4.8, DRN)
if float((PDRN[i])) > 0:
CON1 = OPTmodel.addConstr(Pbess_flex_[i] == Pbess_in_[i] + Pbess_out_[i],'CON1')
CON2 = OPTmodel.addConstr(Phvac_flex_[i] == Phvac_up_[i] + Phvac_down_[i],'CON2')
CON3=OPTmodel.addConstr(Phvac_down_[i] == 0, name='CON3')
CON4=OPTmodel.addConstr(Phvac_up_[i] == float((PDRN[i])),name='CON4')
CON5=OPTmodel.addConstr(Pbess_out_[i] == 0,name='CON5')
CON6=OPTmodel.addConstr(Pbess_in_[i] == float((PDRN[i])),name='CON6')
elif float(np.transpose(PDRN[i])) < 0:
CON7=OPTmodel.addConstr(Phvac_down_[i] == float(np.transpose(PDRN[i])),name='CON7')
CON8=OPTmodel.addConstr(Phvac_up_[i] == 0,name='CON8')
# Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
CON9=OPTmodel.addConstr(Pbess_out_[i] == float((PDRN[i])),name='CON9')
CON10=OPTmodel.addConstr(Pbess_in_[i] == 0,name='CON10')
else:
CON11=OPTmodel.addConstr(Phvac_down_[i] == 0,name='CON11')
CON12=OPTmodel.addConstr(Phvac_up_[i] == 0,name='CON12')
CON13=OPTmodel.addConstr(Phvac_flex_[i] == Phvac_down_[i] + Phvac_up_[i],name='CON13')
CON14=OPTmodel.addConstr(Pbess_out_[i] == 0)
CON15=OPTmodel.addConstr(Pbess_in_[i] == 0,name='CON15')
CON16=OPTmodel.addConstr(Pbess_flex_[i] == Pbess_in_[i] + Pbess_out_[i],name='CON16')
OPTmodel.update()
ConPDC = OPTmodel.addConstr(Pdc[i] == Pflex_i[i] + float(ITload[i]), name='ConPDC')
# OPTmodel.addConstr(Tdc_i[i]==(ki*Tdc_i[i-1]+(ko*Tamb)))
#for x in Ebess_i:
#ConEBESS2 = OPTmodel.addConstr(Ebess_i[i] ==((Pbess_in[i] / 0.75) + (Pbess_out[i] * 0.75)))
cooling = np.array(pd.read_csv('Pcooling.csv'))
DRR = pd.read_csv('DR.csv')
DR = DRR.values
IT = pd.read_csv('ITpower.csv')
ITload = IT.values
newList = map(lambda x: x / 1000, ITload)
PH = pd.read_csv('Pcooling.csv')
PHVAC = PH.values
newList2 = map(lambda x: x / 1000, PHVAC)
#for y in Tdc_i:
T=pd.read_csv('TT.csv').values
OPTmodel.addConstr(Tdc_i[i]==((ki*float(T[i]))+(ko*Tamb)+(kc*float(newList[i]))-((kp*(float(newList2[i])))+(Phvac_flex[i]*3.14))))
print Tdc_i.values()
OPTmodel.addConstr(Pbess_out_[i]<=Phvac_flex[i] + Pbess_flex[i]<=Pbess_in_[i])
# Tdc_i[1:len(i)]==(Ki*Tdc_i[1:1438])+(Kc*array2[1:1438])+(Ko*Tamb))
ConBESS5 = OPTmodel.addConstr(Pbess_flex[i] == Pbess_in[i] + Pbess_out[i], name='ConBESS5')
#OPTmodel.addConstr(defIT[i]==DeferableLoad.j2 + DeferableLoad.j3)
# OPTmodel.addConstr(Pdc_base[i]==predictions[i])
ConFLEX = OPTmodel.addConstr(Pflex_i[i] == Pbess_flex[i] + Phvac_flex[i], name='ConFLEX')
PcoolingPredicted = pd.read_csv('PcoolingPredictionResult.csv')
PcoolingPredictedValue = PcoolingPredicted.values
ITPredicted = pd.read_csv('ITpredictionResult.csv')
ITPredictedValue = ITPredicted.values
ConPDCbase = OPTmodel.addConstr(Pdc_base[i] == np.transpose(ITPredictedValue[i]) + np.transpose(PcoolingPredictedValue[i]))
OPTmodel.update()
# OPTmodel.addConstr(Pdc_base[i]==prediction[i])
OPTmodel.setObjective((np.transpose(Pdc_base[i])-float(DR[i]) - (Pdc[i]) ), GRB.MINIMIZE)
OPTmodel.update()
OPTmodel.optimize()
print Pdc_base[i].X
#print Ebess_i[i].X
#print Phvac_flex[i].X
print Tdc_i[i]
print Pdc[i]
print Phvac_flex[i]
print Pbess_flex[i]
print Pbess_out[i]
print Pbess_in[i]
print Ebess_i[i]
print Pbess_flex_[i]
print Phvac_down[i]
print Phvac_up[i]
'''
def get_results(self):
"""
This function gets the results of the current optimization model
Returns
-------
"""
HVACresult = np.zeros(1,N)
BatteryResult = np.zeros(1,N)
SOC = np.zeros(1,N)
#r_Q_dot = np.zeros((self.gp.N_H, self.N_S))
#r_P = np.zeros((self.gp.N_H, self.N_S))
#r_P_self = np.zeros((self.gp.N_H, self.N_S))
#r_P_ex = np.zeros((self.gp.N_H, self.N_S))
#r_Q_dot_gas = np.zeros((self.gp.N_H, self.N_S))
#Load = np.zeros((self.gp.N_H, self.N_S))
try:
for t in range(1,N):
HVACresult[t]= Phvac_flex[t].X
BatteryResult[t]=Pbess_flex[t].X
SOC[t] = Ebess_i[t].X / Ebess_max
except:
pass
return { 'SOC' : SOC , 'BatteryResult': BatteryResult }
print OPTmodel.getVars()
# get results
Temp = {}
Battery = {}
Ebess_result = {}
ITloadd = {}
for t in range(1,N):
Temp[t] = OPTmodel.getVarByName("Tdc_i" )
Battery[t] = OPTmodel.getVarByName("PBESS_flex" )
Ebess_result[t] = OPTmodel.getVarByName("Ebess_i" )
#r_P_e[t] = model.getVarByName("P_export_%s_0" % t).X
fig, axes = plt.subplots(4, 1)
# plot elctricity
ax5 = axes[2]
ax6 = ax5.twinx()
ax5.plot( [Temp[t] for t in range(1,N)], 'g-')
ax6.plot([Ebess_result[t] for t in range(1,N)], 'b-')
ax5.set_xlabel('Time index')
ax5.set_ylabel('Power Import [W]', color='g')
ax6.set_ylabel('Power CHP [W]', color='b')
ax7 = axes[3]
ax7.plot([Battery[t] for t in range(1,N)], 'g-')
ax7.set_ylabel('Power Export [W]', color='g')
'''
print Pflex_i.values()
# print OPTmodel.getVars()
print OPTmodel.feasibility()
print OPTmodel.getObjective()
print Pdc_base.values()
'''
b = map(float, Phvac_flex)
plt.plot(b)
plt.show()
'''
#c = map(float, Pbess_flex_)
#plt.plot(c)
#plt.show()
print OPTmodel
print Tdc_i.values()
# get results
print OPTmodel.getVars()
# print OPTmodel.getAttr('EBESS_i')
status = OPTmodel.status
print status
# print Con10,Con12
print Phvac_flex.values()
print Pbess_flex.values()
print Ebess_i.values()
print OPTmodel.objval
print Tdc_i
print Pbess_in
print Pbess_out.values()
# print Pbess_flex
# print Phvac_flex
# print Ebess_i
print Pflex_i.values()
print Pbess_flex_.values()
#print OPTmodel.getVars()
print OPTmodel.feasibility()
print OPTmodel.getObjective()
print Ebess_i.values()
if OPTmodel.status == GRB.Status.INF_OR_UNBD:
# Turn presolve off to determine whether model is infeasible
# or unbounded
OPTmodel.setParam(GRB.Param.Presolve, 0)
OPTmodel.optimize()
OPTmodel.write("mymodel.lp")
if OPTmodel.status == GRB.Status.OPTIMAL:
print('Optimal objective: %g' % OPTmodel.objVal)
OPTmodel.write('model.sol')
exit(0)
elif OPTmodel.status != GRB.Status.INFEASIBLE:
print('Optimization was stopped with status %d' % OPTmodel.status)
exit(0)
# Model is infeasible - compute an Irreducible Inconsistent Subsystem (IIS)
print('')
print('Model is infeasible')
OPTmodel.computeIIS()
OPTmodel.write("model.ilp")
print("IIS written to file 'model.ilp'")
I want to plot the computed values from gurobi but when I want to get the X attribute of gurobi variable it says that AttributeError: it has no attribute 'X' and the when I cast the value from float to int it just showed me the empty plot but at the lp file I could see the result of each iteration
I am anxiously waiting for your response
cherrs
We have a code to draw circles on the Location on the map with the name of each category. Now the circles and text are one color. How do we get them in different color's by category? Example: Category Garden: Blue, Category Stone: Grey.
So far the code:
size(1500,800)
background(1)
nofill()
stroke('#f91')
pen(.2)
fill('#f91', 0.05)
rotate(90)
font("Avenir", "bold", 10)
align('left')
def mapValue(value, fromMin, fromMax, toMin, toMax):
# Figure out how 'wide' each range is
fromSpan = fromMax - fromMin
toSpan = toMax - toMin
# Convert the from range into a 0-1 range (float)
valueScaled = float(value - fromMin) / float(fromSpan)
# Convert the 0-1 range into a value in the to range.
return toMin + (valueScaled * toSpan)
def xOfDot(lon):
return mapValue(lon, -100, 100, 0, WIDTH)
def yOfDot(lat):
return mapValue(lat, -90, 90, HEIGHT, 0)
with open('theft-alerts.json', 'r') as inputFile:
data = json.load(inputFile)
print len(data)
artworksPerCity = {}
for stolenArt in data:
if stolenArt.has_key('Category'):
city = stolenArt['Category']
if stolenArt.has_key('nItemsStolen'):
numbersStolen = int(stolenArt['nItemsStolen'])
if artworksPerCity.has_key(city):
# Adjust the value stored for this city
artworksPerCity[city] = artworksPerCity[city] + numbersStolen
else:
# Create new key with new value
artworksPerCity[city] = numbersStolen
# Draw circle on the map
radius = artworksPerCity[city] /2
x = xOfDot(stolenArt['Lon'])
y = yOfDot(stolenArt['Lat'])
arc(x, y, radius)
text(city, x, y)
print artworksPerCity
Here is a sketch of what I intend to include in my pure python data utility.
def hexidecimalDiget(n,deHex = false):
if(n<0):
print "negitive values not supported by call to hexidecimalDiget("+str(n)+")"
return None
elif(n < 10):
return str(n)
elif(n < 15):
return ["a","b","c","d","e"][n-10]
elif(n in ["a","b","c","d","e"]):
if deHex:
return ["a","b","c","d","e"].index(n)
return n
else:
print "call to hexidecimalDiget("+str(n)+") not supported!"
return None
def colorFormHexArray(arr):
if len(arr)!=3 and len(arr)!=6:
print "invalid length for color on call to colorFormHexArray("+str(arr)+")"
return None
elif None in arr:
print "cannot make color from None arguments in "+str(arr)
return None
else:
ret = "#"
for k in arr:
if(type(k) == list):
for k2 in k:
ret+=hexidecimalDiget(k)
else:
ret+=hexidecimalDiget(k)
return ret
def arrayFromColor(c):
c = c.replace("#","")
col = []
for n,k in enumerate(c):
if(len(c) == 3):
col.append([hexidecimalDiget(k,deHex = True)])
elif(len(c) == 6):
col.append([hexidecimalDiget(c[(n+1)*2-2],deHex = True),hexidecimalDiget(c[(n+1)*2-2],deHex = True)])
return(col)
def intFromHexPair(hp):
ret = 0
for n,k in enumerate(hp):
digBase = 16**(len(hp)-n-1)
ret+=digBase*hexidecimalDiget(hp[0],deHex = True)
return ret
def hexPairFromInt(I,minDigits = 1,maxDigits = 256):
if I<0:
print "negitive numbers not supported by hexPairFromInt"
k= 0
while(16**(k+1) <= I):
k+=1
if k < minDigits:
k = minDigits
if k > minDigits:
print("maxDigitsExceeded")
ret = []
while k>=0
dig = 16**k
ret.append(hexidecimalDiget(int(I)%(dig))
I -= dig
k-=1
return ret
def specColor(start,end,bottom,top):
start = arrayFromColor(start)
end = arrayFromColor(end)
def ret(v):
if( v<start or c>end ):
print("value out of range "+str([start,end]))
return('#aa0000') #eyo <- error red
else:
starts = [intFromHexPair(k) for k in start]
ends = [intFromHexPair(hp) for k in end]
normalized = (v-bottom)/(top-bottom)
return colorFormHexArray([hexPairFromInt(int((starts[n]-ends[n])*normalized),minDigits = 1,maxDigits = 256) for n,k in enumerate(starts)])
return ret
This seems excessive and hasn't even been slightly tested yet (just a stetch up atm) but I'll be testing and incorporating this code here tonight :: http://krewn.github.io/KPlot/
I have some information (a list of participants to an event) which I want to print out easily. No need for fancy layout, just a table with several columns, and if possible a drawn line in between the lines of text for better readability. Will need to print landscape to make it all fit (can be done via a GtkPageSetup).
I'm using Python, and I'm on Linux so will have to use the GtkPrintUnixDialog interface. I've been searching on Internet but can't find any example on how this could possibly be achieved.
To simplify the problem: it's for my own use only, so known paper size (A4).
The problem that I have is basically two-fold: 1) create a properly formatted text, suitable for printing, and 2) send this to the printer.
Any suggestions on where to start? Or better, complete examples?
I search for my old print examples, but for a start:
You could write to pdf surface, and print pdf, or
put the drawing code on on_print function. Note, it does not print what you see, but what you draw on print surface. Draw the context like a regular cairo context, but a few methods are not available(don't fit in print context) while others, like new page, are added. If I find the example, I will come with a answer more self-explanatory.
Edit: find an ex:
def on_button_clicked(self, widget):
ps = Gtk.PaperSize.new_custom("cc", "cc", 210, 297, Gtk.Unit.MM)
st = Gtk.PrintSettings()
s = Gtk.PageSetup()
s.set_paper_size(ps)
s.set_bottom_margin(4.3, Gtk.Unit.MM)
s.set_left_margin(4.3, Gtk.Unit.MM)
s.set_right_margin(4.3, Gtk.Unit.MM)
s.set_top_margin(4.3, Gtk.Unit.MM)
s.set_orientation(Gtk.PageOrientation.LANDSCAPE)
# ret = Gtk.print_run_page_setup_dialog(self, s, st)
pd = Gtk.PrintOperation()
pd.set_n_pages(1)
pd.set_default_page_setup(s)
pd.connect("begin_print", self.bg)
pd.connect("draw_page", self.draw_page)
# print(ret, s, st)
pd.set_export_filename("test.pdf")
result = pd.run(Gtk.PrintOperationAction.EXPORT, None) #play with action, but for test export first; if it's ok, then action.PRINT
print (result) # handle errors etc.
# Gtk.PaperSize.free(ps) - not needed in py
the above may be on button press or whatever
def draw_page (self, operation, context, page_number):
end = self.layout.get_line_count()
cr = context.get_cairo_context()
cr.set_source_rgb(0, 0, 0)
i = 0
start = 0
start_pos = 0
iter = self.layout.get_iter()
while 1:
if i >= start:
line = iter.get_line()
print(line)
_, logical_rect = iter.get_line_extents()
# x_bearing, y_bearing, lwidth, lheight = logical_rect
baseline = iter.get_baseline()
if i == start:
start_pos = 12000 / 1024.0 # 1024.0 is float(pango.SCALE)
cr.move_to(0 / 1024.0, baseline / 1024.0 - start_pos)
PangoCairo.show_layout_line(cr, line)
i += 1
if not (i < end and iter.next_line()):
break
That's just a basic example. Note that layout is a pango layout:
self.layout = cx.create_pango_layout()
self.layout.set_width(int(w / 4 * Pango.SCALE))
self.layout.set_text(text, len(text))
num_lines = self.layout.get_line_count()
page_height = 0
self.layout.set_font_description(Pango.FontDescription("Georgia Bold 12"))
k = 0
for line in range(num_lines):
if k == 4:
self.layout.set_font_description(Pango.FontDescription("Georgia 10"))
layout_line = self.layout.get_line(line)
ink_rect, logical_rect = layout_line.get_extents()
lheight = 1200
line_height = lheight / 1024.0 # 1024.0 is float(pango.SCALE)
page_height += line_height
k += 1
print ("page_height ", page_height)
copy/paste functional example:
#!/usr/bin/python
from gi.repository import Gtk, Pango, PangoCairo
import cairo
text = '''
Text.
I have some information (a list of participants to an event) which I
want to print out easily.
No need for fancy layout,
just a table with several columns,
and if possible a drawn line in between the lines of
text for better readability.
'''
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Hello World Printing")
self.button = Gtk.Button(label="Print A Rectangle")
self.button.connect("clicked", self.on_button_clicked)
self.add(self.button)
def on_button_clicked(self, widget):
ps = Gtk.PaperSize.new_custom("cc", "cc", 210, 297, Gtk.Unit.MM)
st = Gtk.PrintSettings()
s = Gtk.PageSetup()
s.set_paper_size(ps)
s.set_bottom_margin(4.3, Gtk.Unit.MM)
s.set_left_margin(4.3, Gtk.Unit.MM)
s.set_right_margin(4.3, Gtk.Unit.MM)
s.set_top_margin(4.3, Gtk.Unit.MM)
s.set_orientation(Gtk.PageOrientation.LANDSCAPE)
# ret = Gtk.print_run_page_setup_dialog(self, s, st)
pd = Gtk.PrintOperation()
pd.set_n_pages(1)
pd.set_default_page_setup(s)
pd.connect("begin_print", self.bg)
pd.connect("draw_page", self.draw_page)
# print(ret, s, st)
pd.set_export_filename("test.pdf")
result = pd.run(Gtk.PrintOperationAction.EXPORT, None)
print (result) # handle errors etc.
# Gtk.PaperSize.free(ps)
def bg(self, op, cx):
w = cx.get_width()
h = cx.get_height()
self.layout = cx.create_pango_layout()
self.layout.set_width(int(w / 4 * Pango.SCALE))
self.layout.set_text(text, len(text))
num_lines = self.layout.get_line_count()
page_height = 0
self.layout.set_font_description(Pango.FontDescription("Georgia Bold 12"))
k = 0
for line in range(num_lines):
if k == 4:
self.layout.set_font_description(Pango.FontDescription("Georgia 10"))
layout_line = self.layout.get_line(line)
ink_rect, logical_rect = layout_line.get_extents()
# print(logical_rect, ink_rect)
# x_bearing, y_bearing, lwidth, lheight = logical_rect
lheight = 1200
line_height = lheight / 1024.0 # 1024.0 is float(pango.SCALE)
page_height += line_height
# page_height is the current location on a page.
# It adds the the line height on each pass through the loop
# Once it is greater then the height supplied by context.get_height
# it marks the line and sets the current page height back to 0
k += 1
print ("page_height ", page_height)
def box(self, w, h, x, y, cx):
w, h = int(w), int(h)
cx.set_font_size(100)
cx.set_source_rgb(0, 0, 0)
cx.rectangle(x, y, w, h)
cx.stroke()
yy = 120
cx.select_font_face("Times", 0, 1)
ex = cx.text_extents("TEGOLA ROMÂNIA SRL")[2]
cx.move_to(w / 2 - ex / 2 + x, 105 + y)
cx.show_text("TEGOLA ROMÂNIA SRL")
ex = cx.text_extents("Str. Plevnei, nr. 5, Buzău")[2]
cx.move_to(w / 2 - ex / 2 + x, 210 + y)
cx.show_text("Str. Plevnei, nr. 5, Buzău")
ex = cx.text_extents("Tel.: 0238/710.280")[2]
cx.move_to(w / 2 - ex / 2 + x, 320 + y)
cx.show_text("Tel.: 0238/710.280")
ex = cx.text_extents("Fax : 0238/710021")[2]
cx.move_to(w / 2 - ex / 2 + x, 415 + y)
cx.show_text("Fax : 0238/710021")
cx.set_font_size(90)
cx.move_to(x + 120, 520 + y)
ex = cx.text_extents("Compoziție:")[2]
cx.show_text("Compoziție:")
cx.select_font_face("Times", 0, 0)
cx.move_to(x + 125 + ex, 520 + y)
cx.show_text("Polimer bituminos, liant și")
cx.move_to(x + 5, 620 + y)
cx.show_text("material de umplutură de înaltă calitate.")
cx.move_to(x + 5, 720 + y)
cx.show_text("Nu conține gudron.")
cx.move_to(x + 5, 800 + y)
cx.select_font_face("Times", 0, 1)
ex = cx.text_extents("Instrucțiuni de utilizare:")[2]
cx.show_text("Instrucțiuni de utilizare:")
cx.select_font_face("Times", 0, 0)
cx.move_to(x + 10 + ex, 800 + y)
cx.show_text("Suprafețele se")
def draw_page1(self, operation, context, page_nr=None):
ctx = context.get_cairo_context()
w = context.get_width()
h = context.get_height()
ww, hh = int(w / 4), int(h / 2)
self.k = 0
for x in range(2):
for y in range(4):
self.box(ww, hh, y * ww, x * hh, ctx)
self.k += 1
print(ctx.get_font_matrix())
def draw_page (self, operation, context, page_number):
end = self.layout.get_line_count()
cr = context.get_cairo_context()
cr.set_source_rgb(0, 0, 0)
i = 0
start = 0
start_pos = 0
iter = self.layout.get_iter()
while 1:
if i >= start:
line = iter.get_line()
print(line)
_, logical_rect = iter.get_line_extents()
# x_bearing, y_bearing, lwidth, lheight = logical_rect
baseline = iter.get_baseline()
if i == start:
start_pos = 12000 / 1024.0 # 1024.0 is float(pango.SCALE)
cr.move_to(0 / 1024.0, baseline / 1024.0 - start_pos)
PangoCairo.show_layout_line(cr, line)
i += 1
if not (i < end and iter.next_line()):
break
win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
Don't forget to change action to Gtk.PrintOperationAction.PRINT for real printing.