spacing in numpy array - numpy

I have a beginner question for numpy arrays. Why does the output have random spacing in between the elements and commas?
input:
list_weight_pounds = [150, 140, 220, 205, 265]
array_weight_pounds = np.array([150, 140, 220, 205, 265])
array_weight_kg = array_weight_pounds / 2.2046
array_weight_kg
output
array([ 68.03955366, 63.50358342, 99.79134537, 92.98739 ,
120.20321147])

this is because the default floatmode is 'maxprec':
‘maxprec’: Print at most precision fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many.
You can set it to 'fixed' to get trailing zeroes instead of spaces:
np.set_printoptions(floatmode='fixed')
array_weight_kg
#array([ 68.03955366, 63.50358342, 99.79134537, 92.98739000,
# 120.20321147])
You can also use the printoptions context manager. See set_printoptions for further formatting options.

Related

How to add colormap renderer from a classified single band "QgsRasterLayer" with PyQGIS

I'm trying to add a colormap to a TMS service which is serving single band PNG with values ranging from 1 to 11. At this point, the layer renders in black (low values between 1 and 11) but I would like it to render with a specific color for each of the 11 values. This is for a QGIS plugin that adds layer to the map.
Here is a sample of my code, any help would be very much appreciated!
# Create rlayer
urlWithParams = 'type=xyz&url=https://bucket_name.s3.ca-central-1.amazonaws.com/z/x/-y.png&zmax=19&zmin=0&crs=EPSG3857'
layerName = 'Classified image'
rlayer = QgsRasterLayer(urlWithParams, layerName, 'wms')
# One of my attempt to create the renderer
fcn = QgsColorRampShader()
fcn.setColorRampType(QgsColorRampShader.Discrete)
lst = [QgsColorRampShader.ColorRampItem(1, QColor(0, 255, 0)),
QgsColorRampShader.ColorRampItem(2, QColor(65, 123, 23)),
QgsColorRampShader.ColorRampItem(3, QColor(123, 76, 34)),
QgsColorRampShader.ColorRampItem(4, QColor(45, 234, 223)),
QgsColorRampShader.ColorRampItem(5, QColor(90, 134, 23)),
QgsColorRampShader.ColorRampItem(6, QColor(45, 255, 156)),
QgsColorRampShader.ColorRampItem(7, QColor(245, 23, 123)),
QgsColorRampShader.ColorRampItem(8, QColor(233, 167, 87)),
QgsColorRampShader.ColorRampItem(9, QColor(123, 125, 23)),
QgsColorRampShader.ColorRampItem(10, QColor(213, 231, 123)),
QgsColorRampShader.ColorRampItem(11, QColor(255, 255, 0))]
fcn.setColorRampItemList(lst)
shader = QgsRasterShader()
shader.setRasterShaderFunction(fcn)
renderer = QgsSingleBandColorDataRenderer(rlayer.dataProvider(), 1, shader)
rlayer.setRenderer(renderer)
rlayer.triggerRepaint()
# Add rendered layer to QGIS map
QgsProject.instance().addMapLayer(rlayer)
It looks like the type of renderer is QgsSingleBandColorDataRenderer. Any idea how to make this work? Thanks!

Represent a 3d vector as a single numerical value

Is it possible to convert a 3d vector representing a colour into a single numerical value (x)? Something ideally that is a float value between 0 and 1. Math's is not my strong suit at all so from my googling I think I either need to use vectorization or convert the value to a tensor to achieve my objective. Would that be correct?
An example of what I am trying to achieve is:
labColour = (112, 48, 0)
labAsFloat = colour_to_float(luvColour, cspace='LAB')
print(labAsFloat) # outputs something like 0.74673543
def colour_to_float(colour, cspace):
return ??? somehow vectorise??
Not quite sure I understand your question correctly. If the objective is merely a unique floating number representation then this might work.
def colour_to_float(colour):
int_arr = list(colour)
int_arr.append(0)
data_bytes = np.array(int_arr, dtype=np.uint8)
return (data_bytes.view(dtype=np.float32))[0]
def float_to_colour(num):
return np.array([num], dtype=np.float32).view(dtype=np.uint8)[:3].tolist()
Results:
labColour = (230, 140, 50)
f = colour_to_float(labColour)
print(f)
4.64232e-39
lab = float_to_colour(f)
print(lab)
[230, 140, 50]

PyQt5 QColor conversion from HSV

I am doing a HSV color picker for Krita that has PyQt5.
I wanted to make use of the QColor class to take care of display color conversions, however i am not able to convert the color with success.
I used this color selector as a reference for my output:
https://www.google.com/search?sxsrf=ACYBGNR9_2R1jGyxkqbdM8DVZfU-8hogYg%3A1583142187803&source=hp&ei=K9VcXqrKLuyMlwTorLH4Dg&q=color+picker+hex&oq=color+picker&gs_l=psy-ab.3.0.35i39l2j0l8.3060.6761..8026...2.0..0.310.1102.11j3-1......0....1..gws-wiz.....10..35i362i39j0i10.C-faeoukSfM
a random color of choice was:
HEX=(#eb4034)
HSV=(7, 78, 92)
When I try to convert it with this code:
from PyQt5.QtGui import QColor
hsv = QColor.fromHsv(7,78,92,255)
color = str(hsv.redF()*255)+" | "+str(hsv.greenF()*255)+" | "+str(hsv.blueF()*255)
print(str( color ))
my output is:
92.0 | 67.14007782101167 | 63.85992217898833
[Finished in 0.168s]
instead of:
235, 64, 52
How do I input a HSV color into the QColor and then convert it to RGB for display purposes?
thank you in advance
The reference values for the HVS color (i.e. (7, 78, 92)) are in units degree, percent, and percent, respectively, whereas QColor.fromHSV expects values in the range 0-255. To convert the reference values to something that can be used by QColor you could try something like this
HSV=(7, 78, 92)
hue, sat, value = HSV
hue = int(hue*255/360)
sat = int(sat*255/100)
value = int(value*255/100)
hsv = QColor.fromHsv(hue, sat, value, 255)
color = str(hsv.redF()*255)+" | "+str(hsv.greenF()*255)+" | "+str(hsv.blueF()*255)
print(str( color ))
# output: 234.0 | 64.42023346303502 | 52.307392996108945
You can use the getRgb() method to get a tuple with the values:
>>> hsv = QColor.fromHsv(7,78,92,255)
>>> hsv.getRgb()
(92, 67, 64, 255)
You will notice the values are different than what you expected, this is because the color hex #eb4034 is not the same as HSV (7, 78, 92).
>>> hsv.name()
'#5c4340'
>>> QColor('#eb4034').getHsv()
(3, 199, 235, 255)
Make sure you are using the correct HSV values.

Pandas HDFStore: append fails when min_itemsize is set to the maximum of the string column

I'm detecting the maximum lengths of all string columns of multiple dataframes, then attempting to build a HDFStore:
import pandas as pd
# Detect max string length for each column across all DataFrames
max_lens = {}
for df_path in paths:
df = pd.read_pickle(df_path)
for col in df.columns:
ser = df[col]
if ser.dtype == 'object' and isinstance(
ser.loc[ser.first_valid_index()], str
):
max_lens[col] = max(
ser.dropna().map(len).max(), max_lens.setdefault(col, 0)
)
print('Setting min itemsizes:', max_lens)
hdf_path.unlink() # Delete of file for clean retry
store = pd.HDFStore(hdf_path, complevel=9)
for df_path in paths:
df = pd.read_pickle(df_path)
store.append(hdf_key, df, min_itemsize=max_lens, data_columns=True)
store.close()
The detected maximum string lengths are as follows:
max_lens = {'hashtags': 139,
'id': 19,
'source': 157,
'text': 233,
'urls': 2352,
'user_mentions_user_ids': 199,
'in_reply_to_screen_name': 17,
'in_reply_to_status_id': 19,
'in_reply_to_user_id': 19,
'media': 286,
'place': 56,
'quoted_status_id': 19,
'user_id': 19}
Yet still I'm getting this error:
ValueError: Trying to store a string with len [220] in [hashtags] column but
this column has a limit of [194]!
Consider using min_itemsize to preset the sizes on these columns
Which is weird, because the detected maximum length of hashtags is 139.
HDF stores strings in UTF-8, and thus you need to encode the strings as UTF-8 and then find the maximum length.
a_pandas_string_series.str.encode('utf-8').str.len().max()

Formatting Manipulate output to have 2 cells in Mathematica

The following output code outputs an array from the manipulate statement. I would like to output the fitting and plot as two separate output cells that update dynamically. I think it should be pretty simple, but I am having trouble with it. I've tried using the CellPrint[] function, but did not get it to work.
Thanks,
Tal
temperatures(*mK*)= {300, 200, 150, 100, 75, 50, 25, 11, 10};
F[t_, \[Nu]_] := t^\[Nu];
rd (*uOhms*)= {27173.91304, 31250., 42372.88136, 200601.80542,
1.05263*10^6, 1.33333*10^7, 1.33333*10^8, 2.*10^8, 2.1*10^8};
logRd = Log10[rd];
f[\[Nu]0_] := Module[{\[Nu]},
\[Nu] = \[Nu]0;
data = Transpose[{F[temperatures, \[Nu]]*10^3, logRd}];
fitToHexatic = LinearModelFit[data[[4 ;; 6]], x, x];
plota =
Plot[fitToHexatic["BestFit"], {x, 0, data[[-1]][[1]]},
Axes -> False];
plotb = ListPlot[data, Axes -> False];
{fitToHexatic, Show[{plota, plotb}, Axes -> True]}
]
Manipulate[
f[nu],
{nu, -0.2, -1}
]
Screenshot of the output:
You don't need to use a Manipulate. You can get more control with lower level functions. E.g.
Slider[Dynamic[nu, (f[#]; nu = #) &], {-0.2, -1}]
Dynamic[Normal[fitToHexatic]]
Dynamic[Show[{plota, plotb}, Axes -> True]]
See also Prototypical Manipulate in lower level functions.