Unable to make ReportLab correctly print unicode fonts - python-3.x

I am trying to print Korean characters using the hygothic-medium font. I have font as 'korean.h2gtrm.ttf'file under the site-packages\reportlab\fonts folder.
I did the following :-
pdfmetrics.registerFont(UnicodeCIDFont(TTFont('HYGothic-
Medium','korean.h2gtrm.ttf')))
pdfmetrics.registerFontFamily('HYGothic-Medium',normal='HYGothic-
Medium',bold='HYGothic-Medium',italic='HYGothic-
Medium',boldItalic='HYGothic-
Medium')
addMapping('HYGothic-Medium',0, 0, 'korean.h2gtrm') #normal
addMapping('HYGothic-Medium', 0, 1, 'korean.h2gtrm')
addMapping('HYGothic-Medium',1, 0, 'korean.h2gtrm')
addMapping('HYGothic-Medium',1, 1, 'korean.h2gtrm')
pstyle= ParagraphStyle(name='KOR', fontName = 'HYGothic-Medium',
fontSize = 10 ))
p=Paragraph(text,pstyle)) # where text is my Korean characters
story.append(p) # error !!
I get the following error:-
Can't map determine family/bold/italic for hygothic-medium
paragraph text '<para>\uc724\uadfc Machine</para>' caused exception
Any suggestions ?.

Related

Undesired lines in FilledCurve (Wolfram Mathematica)

I am trying to make a custom arrowhead with Wolfram Mathematica (v. 10.0) using function FilledCurve. The result is looking fine on the Wolfram output. When I save the picture as pdf, some undesirable vertical line appears on the left border of my arrowhead. It is visible also in the latex document where I insert my pictures.
The code is
px = 0.7; py = 0.14; mpx = -0.2;
pts = {{-px, py}, {mpx, 0}, {-px, -py}};
ah = Graphics[{FilledCurve[{BSplineCurve[pts], Line[{{-px, -py}, {0, 0}, {-px, py}}]}]}]
To see the problem you need to save the output as pdf and open it in Adobe Acrobat Reader (or insert it in latex document).
Any suggestions?
Thank you!
It seems there is some bag in WM.
I solves the problem just by creating the required curve "manually" from lines.
The final code (with some minor improvements) is as follows:
px = 0.7; py = 0.14; mpx = -0.3;
pts = {{-px, py}, {mpx, 0}, {-px, -py}};
curpts = Table[f[t], {t, 0, 1, 0.02}];
f = BSplineFunction[pts];
linpts = {{-px, -py}, {0, 0}, {-px, py}};
allpts = Join[curpts, {linpts[[-2]], linpts[[-1]]}];
ah = Graphics[{FilledCurve[Line[allpts]], Line[linpts]}]
Result:

Python converting images in TIF format to PNG

I am running the code below to convert files from tifs to PNGs but the converted images isn't converting properly the new files are disrupted and with lines in half of the file as can be seen in the attached image. Any idea why would this happen please?.
import os
from PIL import Image
yourpath = os.getcwd()
for root, dirs, files in os.walk(yourpath, topdown=False):
for name in files:
print(os.path.join(root, name))
if os.path.splitext(os.path.join(root, name))[1].lower() == ".tif":
if os.path.isfile(os.path.splitext(os.path.join(root, name))[0] + ".png"):
print ("A png file already exists for %s" % name)
# If a PNG is *NOT* present, create one from the tiff.
else:
outfile = os.path.splitext(os.path.join(root, name))[0] + ".png"
try:
im = Image.open(os.path.join(root, name))
print("Generating jpeg for %s" % name)
im.thumbnail(im.size)
im.save(outfile, "png", quality=100)
except Exception as e:
print (e)
Running tiffinfo gives the following details:
TIFF Directory at offset 0x8 (8)
Image Width: 1024 Image Length: 1024
Resolution: 5000, 5000 pixels/cm
Bits/Sample: 8
Sample Format: unsigned integer
Compression Scheme: LZW
Photometric Interpretation: RGB color
Samples/Pixel: 3
Rows/Strip: 1
Planar Configuration: separate image planes
ImageDescription: <?xml version="1.0" encoding="UTF-8"?><!-- Warning: this comment is an OME-XML metadata block, which contains crucial dimensional parameters and other important metadata. Please edit cautiously (if at all), and back up the original data before doing so. For more information, see the OME-TIFF web site: https://docs.openmicroscopy.org/latest/ome-model/ome-tiff/. --><OME xmlns="http://www.openmicroscopy.org/Schemas/OME/2016-06" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Creator="OME Bio-Formats 5.9.2" UUID="urn:uuid:5d7dfdcc-e0e9-4899-9aa2-64717b405232" xsi:schemaLocation="http://www.openmicroscopy.org/Schemas/OME/2016-06 http://www.openmicroscopy.org/Schemas/OME/2016-06/ome.xsd"><Image ID="Image:0" Name="p1_Bromophenol_1mM - Mark_and_Find 001/Position026 (RGB rendering)"><Pixels BigEndian="true" DimensionOrder="XYCZT" ID="Pixels:0" PhysicalSizeX="2.0" PhysicalSizeXUnit="┬Ám" PhysicalSizeY="2.0" PhysicalSizeYUnit="┬Ám" PhysicalSizeZ="1.0" PhysicalSizeZUnit="┬Ám" SizeC="3" SizeT="1" SizeX="1024" SizeY="1024" SizeZ="1" TimeIncrement="1.0" TimeIncrementUnit="s" Type="uint8"><Channel ID="Channel:0:0" Name="red" SamplesPerPixel="3"><LightPath/></Channel><TiffData FirstC="0" FirstT="0" FirstZ="0" IFD="0" PlaneCount="1"><UUID FileName="Position026 (RGB rendering) - 1024 x 1024 x 1 x 1 - 3 ch (8 bits).tif">urn:uuid:5d7dfdcc-e0e9-4899-9aa2-64717b405232</UUID></TiffData></Pixels></Image></OME>
Software: OME Bio-Formats 5.9.2

View exported console coloured logs

Is there a way to view exported coloured logs as in console (with colour)?
My program uses colour coding for errors, warnings, etc. If I redirect output of my program to file.log, I get records like:
[32m[1m(INF)[0m /environment/converter: State map: [ 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18 ][0m
[32m[1m(INF)[0m /environment/converter: Action map: [ -1, -1, -1, 0, 1, 2, 3, 4, 5 ][0m
[32m[1m(INF)[0m PyEnv: Observation dims: 15[0m
[32m[1m(INF)[0m PyEnv: Action dims: 6[0m
Random seed None
[32m[1m(INF)[0m GRL seed 1428[0m
Now I want to see file.log, but without colour codes or even better with colours preserved.
I have tried nano, vi and gedit but they all do not do what I want.
Here are some ideas if you're still wondering for a good way to do this.
A text editor won't be able to read the color codes, as those are Bash specific. However, cat works because it can interpret the color codes. However, the way you're storing the colors isn't formatted correctly in the first place.
I'm not sure how you are writing into your log file, but I echoed your example and redirected the output into a file. I didn't see colors either. The reason is that you have to escape every square bracket for the codes to be interpreted by Bash.
So the way that I escaped the brackets is by manually adding \e before every square bracket and using echo -e to evaluate the escape characters:
`echo -e "\e[32m\e[1m(INF)\e[0m /environment/converter: State map: [ 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18 ]\e[0m`
`\e[32m\e[1m(INF)\e[0m /environment/converter: Action map: [ -1, -1, -1, 0, 1, 2, 3, 4, 5 ]\e[0m`
`\e[32m\e[1m(INF)\e[0m PyEnv: Observation dims: 15\e[0m`
`\e[32m\e[1m(INF)\e[0m PyEnv: Action dims: 6\e[0m`
`Random seed None`
`\e[32m\e[1m(INF)\e[0m GRL seed 1428\e[0m " > example.txt`
Now when I open the file with cat I see correctly colored text:
The color codes are now stored and escaped correctly in the .txt file:
^[[32m[1m(INF)[0m GRL seed 1428^[[0m
vs
[32m[1m(INF)[0m GRL seed 1428[0m
An alternative solution is to use a package like Ansi Html Adapter (Aha).
It will produce HTML instead of plain text. Then you can open the output in your browser, and it would have the right color coding.
However, you would meet with the same problem. If the color codes aren't escaped correctly, the output is not going to be colored.
I ran the following command to convert the correctly formatted text to HTML:
aha -f example.txt > example.html
Here's the result in the browser:
You can find more info on how to use colors in bash in this Bash Tips article.

R simplify heatmap to pdf

I want to plot a simplified heatmap that is not so difficult to edit with the scalar vector graphics program I am using (inkscape). The original heatmap as produced below contains lots of rectangles, and I wonder if they could be merged together in the different sectors to simplify the output pdf file:
nentries=100000
ci=rainbow(nentries)
set.seed=1
mean=10
## Generate some data (4 factors)
i = data.frame(
a=round(abs(rnorm(nentries,mean-2))),
b=round(abs(rnorm(nentries,mean-1))),
c=round(abs(rnorm(nentries,mean+1))),
d=round(abs(rnorm(nentries,mean+2)))
)
minvalue = 10
# Discretise values to 1 or 0
m0 = matrix(as.numeric(i>minvalue),nrow=nrow(i))
# Remove rows with all zeros
m = m0[rowSums(m0)>0,]
# Reorder with 1,1,1,1 on top
ms =m[order(as.vector(m %*% matrix(2^((ncol(m)-1):0),ncol=1)), decreasing=TRUE),]
rowci = rainbow(nrow(ms))
colci = rainbow(ncol(ms))
colnames(ms)=LETTERS[1:4]
limits=c(which(!duplicated(ms)),nrow(ms))
l=length(limits)
toname=round((limits[-l]+ limits[-1])/2)
freq=(limits[-1]-limits[-l])/nrow(ms)
rn=rep("", nrow(ms))
for(i in toname) rn[i]=paste(colnames(ms)[which(ms[i,]==1)],collapse="")
rn[toname]=paste(rn[toname], ": ", sprintf( "%.5f", freq ), "%")
heatmap(ms,
Rowv=NA,
labRow=rn,
keep.dendro = FALSE,
col=c("black","red"),
RowSideColors=rowci,
ColSideColors=colci,
)
dev.copy2pdf(file="/tmp/file.pdf")
Why don't you try RSvgDevice? Using it you could save your image as svg file, which is much convenient to Inkscape than pdf
I use the Cairo package for producing svg. It's incredibly easy. Here is a much simpler plot than the one you have in your example:
require(Cairo)
CairoSVG(file = "tmp.svg", width = 6, height = 6)
plot(1:10)
dev.off()
Upon opening in Inkscape, you can ungroup the elements and edit as you like.
Example (point moved, swirl added):
I don't think we (the internet) are being clear enough on this one.
Let me just start off with a successful export example
png("heatmap.png") #Ruby dev's think of this as kind of like opening a `File.open("asdfsd") do |f|` block
heatmap(sample_matrix, Rowv=NA, Colv=NA, col=terrain.colors(256), scale="column", margins=c(5,10))
dev.off()
The dev.off() bit, in my mind, reminds me of an end call to a ruby block or method, in that, the last line of the "nested" or enclosed (between png() and dev.off()) code's output is what gets dumped into the png file.
For example, if you ran this code:
png("heatmap4.png")
heatmap(sample_matrix, Rowv=NA, Colv=NA, col=terrain.colors(32), scale="column", margins=c(5,15))
heatmap(sample_matrix, Rowv=NA, Colv=NA, col=greenred(32), scale="column", margins=c(5,15))
dev.off()
it would output the 2nd (greenred color scheme, I just tested it) heatmap to the heatmap4.png file, just like how a ruby method returns its last line by default

How to increase resolution of gif image?

How to increase resolution of gif image generated by rgl package of R (plot3d and movie3d functions) - either externally or through R ?
R Code :
MyX<-rnorm(10,5,1)
MyY<-rnorm(10,5,1)
MyZ<-rnorm(10,5,1)
plot3d(MyX, MyY, MyZ, xlab="X", ylab="Y", zlab="Z", type="s", box=T, axes=F)
text3d(MyX, MyY, MyZ, text=c(1:10), cex=5, adj=1)
movie3d(spin3d(axis = c(0, 0, 1), rpm = 4), duration=15, movie="TestMovie",
type="gif", dir=("~/Desktop"))
Output :
Update
Adding this line at the beginning of code solved the problem
r3dDefaults$windowRect <- c(0, 100, 1400, 1400)
I don't think you can do much about the resolution of the gif itself. I think you have to make the image much larger as an alternative, and then when you display it smaller it looks better. This is untested as a recent upgrade broke a thing or two for me, but this did work under 2.15:
par3d(windowRect = c(0, 0, 500, 500)) # make the window large
par3d(zoom = 1.1) # larger values make the image smaller
# you can test your settings interactively at this point
M <- par3d("userMatrix") # save your settings to pass to the movie
movie3d(par3dinterp(userMatrix=list(M,
rotate3d(M, pi, 1, 0, 0),
rotate3d(M, pi, 0, 1, 0) ) ),
duration = 5, fps = 50,
movie = "MyMovie")
HTH. If it doesn't quite work for you, check out the functions used and tune up the settings.

Resources