noUiSlider: how to allow to slide till the end, even if the end value is less than step value - nouislider

I am creating a slider with the following config
step: 60,
range: {
'min': 0,
'max': 1439
}
Now if i have max: 1339 instead of 1440 then how to allow the slider to step 59 as last step i.e till the end.
currently its steps 60 and says invalid value.

You can add multiple ranges to the slider, and only set a step of 60 for the first range.
Documentation
range: {
'min': [0, 60],
'90%': [1380],
'max': [1439]
}

Related

Find '.dng' image resolution using Python

I am trying to get the '.dng' image resolution but I am getting incorrect resolutions. But I am getting correct resolutions for '.jpg' images
img = Image.open("01109677451NasiLemakBiasa.dng")
width = img.width
height = img.height
print(width, height)
# Output 256 171
The actual resolution of the image (01109677451NasiLemakBiasa.dng) is 1024 x 683
Please help me to get the correct width and height of the image
PIL doesn't read DNG files, nor does it like 16-bit per channel RGB. I think you'll need something like rawpy
import rawpy
path = '/Users/mark/Desktop/RAW_LEICA_M8.DNG'
with rawpy.imread(path) as raw:
rgb = raw.postprocess()
print(rgb.shape) # It's a Numpy array
Sanple Output
Out[9]: (2638, 3920, 3)
Another option is Exiftool, which you can install like this:
pip3 install PyExifTool
and use like this:
import exiftool
with exiftool.ExifTool() as et:
metadata = et.get_metadata('/path/to/RAW_LEICA_M8.DNG')
print(metadata)
{'SourceFile': '/path/to/RAW_LEICA_M8.DNG',
'ExifTool:ExifToolVersion': 12.0,
'File:FileName': 'RAW_LEICA_M8.DNG',
'File:Directory': '/path/to',
'File:FileSize': 10575296,
'File:FileModifyDate': '2021:08:16 08:54:30+01:00',
'File:FileAccessDate': '2021:08:16 09:56:33+01:00',
'File:FileInodeChangeDate': '2021:08:16 09:56:31+01:00',
'File:FilePermissions': 644,
'File:FileType': 'DNG',
'File:FileTypeExtension': 'DNG',
'File:MIMEType': 'image/x-adobe-dng',
'File:ExifByteOrder': 'II',
'EXIF:Make': 'Leica Camera AG',
'EXIF:Model': 'M8 Digital Camera',
'EXIF:Orientation': 1,
'EXIF:Software': 1.107,
'EXIF:Artist': '',
'EXIF:SubfileType': 0,
'EXIF:ImageWidth': 3920, <--- HERE IS THE WIDTH
'EXIF:ImageHeight': 2638, <--- HERE IS THE HEIGHT
'EXIF:BitsPerSample': 8,
'EXIF:Compression': 1,
'EXIF:PhotometricInterpretation': 32803,
'EXIF:StripOffsets': '(Binary data 1315 bytes, use -b option to extract)',
'EXIF:SamplesPerPixel': 1,
'EXIF:RowsPerStrip': 16,
'EXIF:StripByteCounts': '(Binary data 989 bytes, use -b option to extract)',
'EXIF:XResolution': 300,
'EXIF:YResolution': 300,
'EXIF:PlanarConfiguration': 1,
'EXIF:ResolutionUnit': 2,
'EXIF:CFARepeatPatternDim': '2 2',
'EXIF:CFAPattern2': '0 1 1 2',
'EXIF:LinearizationTable': '(Binary data 1244 bytes, use -b option to extract)',
'EXIF:WhiteLevel': 16383,
'EXIF:DefaultCropOrigin': '2 2',
'EXIF:DefaultCropSize': '3916 2634',
'EXIF:BayerGreenSplit': 500,
'EXIF:AntiAliasStrength': 0,
'EXIF:Copyright': '',
'EXIF:ExposureTime': 12,
'EXIF:ExposureProgram': 1,
'EXIF:ISO': 160,
'EXIF:ExifVersion': '0220',
'EXIF:CreateDate': '2007:08:02 22:13:49',
'EXIF:ShutterSpeedValue': 11.3137084989848,
'EXIF:ExposureCompensation': 0,
'EXIF:MaxApertureValue': 2,
'EXIF:MeteringMode': 2,
'EXIF:LightSource': 0,
'EXIF:Flash': 0,
'EXIF:FocalLength': 50,
'EXIF:FileSource': 3,
'EXIF:SceneType': 1,
'EXIF:WhiteBalance': 0,
'EXIF:DigitalZoomRatio': 0,
'EXIF:FocalLengthIn35mmFormat': 67,
'EXIF:SceneCaptureType': 0,
'EXIF:ImageUniqueID': '00000000000000000000000000000147',
'EXIF:SelfTimerMode': 0,
'EXIF:DateTimeOriginal': '2007:08:02 22:13:49',
'EXIF:FocalPlaneXResolution': 3729,
'EXIF:FocalPlaneYResolution': 3764,
'EXIF:FocalPlaneResolutionUnit': 2,
'EXIF:TIFF-EPStandardID': '0 0 0 1',
'EXIF:DNGVersion': '1 0 0 0',
'EXIF:UniqueCameraModel': 'M8 Digital Camera',
'EXIF:ColorMatrix1': '1.0469 -0.5314 0.128 -0.4326 1.2176 0.2419 -0.0886 0.2473 0.716',
'EXIF:ColorMatrix2': '0.7675 -0.2195 -0.0305 -0.586 1.4118 0.1857 -0.2425 0.4007 0.6578',
'EXIF:CameraCalibration1': '1 0 0 0 1 0 0 0 1',
'EXIF:CameraCalibration2': '1 0 0 0 1 0 0 0 1',
'EXIF:AsShotNeutral': '0.4750637903 1 0.7966159382',
'EXIF:BaselineNoise': 1,
'EXIF:BaselineSharpness': 1,
'EXIF:CameraSerialNumber': 3106091,
'EXIF:CalibrationIlluminant1': 17,
'EXIF:CalibrationIlluminant2': 21,
'MakerNotes:UserProfile': 1,
'MakerNotes:SerialNumber': 3106091,
'MakerNotes:WhiteBalance': 0,
'MakerNotes:LensType': '33 3',
'MakerNotes:ExternalSensorBrightnessValue': -5.16796875,
'MakerNotes:MeasuredLV': -4.359375,
'MakerNotes:ApproximateFNumber': 4,
'MakerNotes:CameraTemperature': 19,
'MakerNotes:ColorTemperature': 5515,
'MakerNotes:UV-IRFilterCorrection': 0,
'MakerNotes:CCDVersion': 0,
'MakerNotes:CCDBoardVersion': 1,
'MakerNotes:ControllerBoardVersion': 0,
'MakerNotes:M16CVersion': 0,
'MakerNotes:ImageIDNumber': 327,
'Composite:CFAPattern': '2 2 0 1 1 2',
'Composite:ImageSize': '3920 2638',
'Composite:LensID': '33 3',
'Composite:Megapixels': 10.34096,
'Composite:ScaleFactor35efl': 1.34,
'Composite:ShutterSpeed': 12,
'Composite:CircleOfConfusion': 0.0224225825588557,
'Composite:FOV': 30.0756572109854,
'Composite:FocalLength35efl': 67}
Sample raw images downloaded from Raw Samples.

Calling values from dict to create boolean column in dataframe

Searched multiple threads on here for an answer but nothing is quite like what I am looking to do. I am trying to make a boolean column in a dataframe where one of the parameters is based on metal and associated cost maximum, see Dict below.
Cost_ranges = {'Metals': ["Cu", "Pb", "Zn", "Ni", "Mo", "Co", "Sn", "U3O8", "Ag", "Au", "Pt", "Pd", "Rh", "Os", "Ru", "Ir"],
'Cost Maximum': [350, 200, 200, 500, 800, 1000, 250, 2500, 30, 2500, 500, 1000, 6000, 2500, 2500, 2500]}
The dict is used to complete the below formula:
df_Cost['Total Cost'] >= Cost_ranges['Cost Maximum']
i.e. df_Cost['Metal'] contains to value 'Cu', it calls the 'Cost Maximum' of 350 from the dict and uses this for the boolean expression hence formula would read:
df_Cost[Total Cost] >= 350
I need it to apply to all rows in a dataframe. I have been using df.eval() but need an extra layer of processing to match up the right limit per metal.
I have tried using df.eval(), df.query(), df.loc and df.apply() but keep getting 'TypeError: 'Series' objects are mutable, thus they cannot be hashed' or 'ValueError: ('Lengths must match to compare', (9999,), (16,))' for each solution.
Look forward to the responses.
Depending on your actual data, you could do something like:
import numpy as np
import pandas as pd
Cost_ranges = {'Metals': ["Cu", "Pb", "Zn", "Ni", "Mo", "Co", "Sn", "U3O8", "Ag", "Au", "Pt", "Pd", "Rh", "Os", "Ru", "Ir"],
'Cost Maximum': [350, 200, 200, 500, 800, 1000, 250, 2500, 30, 2500, 500, 1000, 6000, 2500, 2500, 2500]}
N = 20
d = pd.DataFrame({'Metals': np.random.choice(["Cu", "Pb", "Zn", "Ni"], N),
'Cost': np.random.random(N) * 1000})
d.merge(pd.DataFrame(Cost_ranges).astype({'Cost Maximum': float}),
on = "Metals", how = "left")\
.eval('want = Cost > `Cost Maximum`')
# Metals Cost Cost Maximum want
# 0 Cu 297.386007 350.0 False
# 1 Pb 55.570657 200.0 False
# 2 Pb 91.803336 200.0 False
# 3 Cu 916.273995 350.0 True
# 4 Zn 796.383326 200.0 True
# 5 Pb 112.504581 200.0 False
Assuming your df_Cost looks a little like this (with potentially more rows and columns):
>>> df_Cost
Total Cost Metal
0 315 Cu
1 420 Cu
The easiest way is to use a dictionary to translate from Metal to max cost. Then you need to make Cost_ranges into a dictionary mapping metal name to cost:
>>> cost_lookup = dict(zip(Cost_ranges['Metals'], Cost_ranges['Cost Maximum']))
>>> cost_lookup
{'Cu': 350, 'Pb': 200, 'Zn': 200, 'Ni': 500, 'Mo': 800, 'Co': 1000, 'Sn': 250, 'U3O8': 2500, 'Ag': 30, 'Au': 2500, 'Pt': 500, 'Pd': 1000, 'Rh': 6000, 'Os': 2500, 'Ru': 2500, 'Ir': 2500}
>>> df_Cost['Metal'].map(cost_lookup)
0 350
1 350
Name: Metal, dtype: int64
>>> df_Cost['Total Cost'] >= df_Cost['Metal'].map(cost_lookup)
0 False
1 True
dtype: bool

Python: Data limit in Plotly frames?

I have recently started to use Plotly to make 3D plots in python and I wanted to create an animation of what is going on in terms of column vectos of a 3 by 3 matrix when applying Gaussain elimination.
I wrote a function to get the row echelon form and the history of the matrix obtained at each step.
Then I wanted to plot the comuns vectors at each step of the algorithm.
At first I was able to get an animation of the the evolution of the three vectors by adpating this code : https://plotly.com/python/visualizing-mri-volume-slices/
But then I wanted to show on each frame the three row vectors of a given step and the three row vectors from the matrix of the previous step with opacity 0.2.
And when I added that part of the code I got a strange behavior from Plotly. It only showed me the three first vectors which are given to the frame and not all of them.
Here the code I have so far :
import numpy as np
import numpy.linalg as la
import plotly.graph_objects as go
v1 = np.array([5,2,1])
v2 = np.array([2,3,2])
v3 = np.array([3,-1,1])
A = np.transpose(np.vstack([v1,v2,v3]))
# G, H = pivot_Gauss(A)
H = [np.array([[ 5, 2, 3],[ 2, 3, -1],[ 1, 2, 1]]), np.array([[ 1, 0, 0],[ 2, 3, -1],[ 1, 2, 1]]),
np.array([[ 1, 0, 0],[ 0, 3, -1],[ 1, 2, 1]]), np.array([[ 1, 0, 0],[ 0, 3, -1],[ 0, 2, 1]]),
np.array([[1, 0, 0],[0, 1, 0],[0, 2, 1]]), np.array([[1, 0, 0],[0, 1, 0],[0, 0, 1]]),
np.array([[1, 0, 0],[0, 1, 0],[0, 0, 1]]) ]
G = np.array([[1,0,0],[0,1,0],[0,0,1]]) # results obtained using the function pivot_Gauss(A)
nb_frames = len(H)
frames = []
v_norm = 5
colors = ["blue","red","green"]
for k in range(nb_frames): # go.Frame(data,name=str(k))
dat = []
for j in range(np.shape(A)[1]):
v = H[k][:,j]
if la.norm(v) != 0 :
d1 = go.Scatter3d( x=[0,v[0]],y=[0,v[1]],z=[0,v[2]],name="v"+str(k+j+1),hoverinfo='name',
marker=dict(size=0), line=dict(color=colors[j], width=10 ))
dat.append(d1)
d2 = go.Cone(x=[v[0]],y=[v[1]],z=[v[2]],
u=[v[0]/v_norm],v=[v[1]/v_norm],w=[v[2]/v_norm],sizeref=1,
sizemode="scaled",anchor="cm",name="v"+str(k+j+1),hoverinfo='x+y+z+name',
colorscale=[[0, colors[j]], [1,colors[j]]],showscale=False)
dat.append(d2)
if k>0 : # add column vectors of previous Gaussain elimination step (causes some troubles,
#if this if section is commented I get an animation of the three clumn vectors of current step)
vk = H[k-1][:,j]
if la.norm(v) != 0 :
d3 = go.Scatter3d( x=[0,vk[0]],y=[0,vk[1]],z=[0,vk[2]],name="v"+str(k+j+1),hoverinfo='name',
marker=dict(size=0), line=dict(color=colors[j], width=10), opacity = 0.2 )
dat.append(d3)
d4 = go.Cone(x=[vk[0]],y=[vk[1]],z=[vk[2]],
u=[vk[0]/v_norm],v=[vk[1]/v_norm],w=[vk[2]/v_norm],sizeref=1,
sizemode="scaled",anchor="cm",name="v"+str(k+j+1),hoverinfo='x+y+z+name',
colorscale=[[0, colors[j]], [1,colors[j]]],showscale=False,opacity=0.2)
dat.append(d4)
frames.append(go.Frame(data=dat,name=str(k)))
fig = go.Figure(frames=frames)
# Add data to be displayed before animation starts
for j in range(A.shape[1]):
v = A[:,j]
if la.norm(v) != 0 :
fig.add_trace( go.Scatter3d( x=[0,v[0]],y=[0,v[1]],z=[0,v[2]],name="v"+str(k+1),hoverinfo='name',
marker=dict(size=0), line=dict(color=colors[j], width=10 )) )
fig.add_trace( go.Cone(x=[v[0]],y=[v[1]],z=[v[2]],
u=[v[0]/v_norm],v=[v[1]/v_norm],w=[v[2]/v_norm],sizeref=1,
sizemode="scaled",anchor="cm",name="v"+str(k+1),hoverinfo='x+y+z+name',
colorscale=[[0, colors[j]], [1,colors[j]]],showscale=False) )
### This remained almost exactly as the Plotly example
def frame_args(duration):
return {
"frame": {"duration": duration},
"mode": "immediate",
"fromcurrent": True,
"transition": {"duration": duration, "easing": "linear"},
}
sliders = [
{
"pad": {"b": 10, "t": 60},
"len": 0.9,
"x": 0.1,
"y": 0,
"steps": [
{
"args": [[f.name], frame_args(0)],
"label": str(k),
"method": "animate",
}
for k, f in enumerate(fig.frames)
],
}
]
matrix_but = [
{"buttons: [{},{},{},{},{},{}]"}
]
# Layout
fig.update_layout(
title='Pivot de Gauss',
width=600,
height=400,
scene=dict(xaxis=dict(autorange=True),
yaxis=dict(autorange=True),
zaxis=dict(autorange=True),
aspectratio=dict(x=1, y=1, z=1),
),
updatemenus = [
{
"buttons": [
{
"args": [None, frame_args(200)],
"label": "▶", # play symbol
"method": "animate",
},
{
"args": [[None], frame_args(0)],
"label": "◼", # pause symbol
"method": "animate",
},
],
"direction": "left",
"pad": {"r": 10, "t": 70},
"type": "buttons",
"x": 0.1,
"y": 0,
}
],
sliders=sliders
)
fig.show()
You will notice that for each vector I first draw a 3D line and then use cone to get the it arrow_shaped. It might not be the best way to do it, but I do not want to use cone alone as the apsect does not fit what I would like.
I stumbled across a (I think) similar question here : https://community.plotly.com/t/only-one-trace-showing-per-frame-in-animated-plot/25803
But I did not undestand the answer nor the example.
It seems from what I get that only the first six elemetns of the data contained in each frame is taken into account, but I do not understand why and I would like to show everything.
If someone has some insight (and a solution) on the subject, it would be warmly welcomed.
I can clarify things if needed.
Image of the two first column vectors of matrix from current step and first column vector of matrix from previous step
Image of the three column vectors of current matrix when part below if k>0 is commented
It seems from what I get that only the first six elemetns of the data contained in each frame is taken into account, but I do not understand why and I would like to show everything.
There's this paragraph under the heading 'Current Animation Limitations and Caveats':
Animations are designed to work well when each row of input is present across all animation frames, and when categorical values mapped to symbol, color and facet are constant across frames. Animations may be misleading or inconsistent if these constraints are not met.
Though in your first frame you have only three vectors (three lines plus three coneheads) to plot, it violates the above constraint when following frames contain six vectors. To overcome this restriction, we could insert the three vectors in the first frame (and also in the data to be displayed before animation starts) twice, i. e. to the
if k>0 : # add column vectors of previous Gaussain elimination step (causes some troubles,
block add an
else:
dat.append(d1)
dat.append(d2)
block, and in the
if la.norm(v) != 0 :
block duplicate the two fig.add_trace calls.

Multiply each row of an array with coefficients in list - Python

I am very new to Python an need help. This is the problem statement:
I want to calculate the value of each of the three houses by multiplying the rows of the arraym X (each row representing one house) with the coefficients in list c, so for the first house: Price = (66x3000)+(5x200)+ (15x-50) + (2x5000) + (500x100) = 258.000
Do not use numpy
Print the price of the three houses
This is what I have so far:
# input values for three houses:
# - size [m^2],
# - size of the sauna [m^2],
# - distance to water [m],
# - number of indoor bathrooms,
# - proximity of neighbors [m]
X = [[66, 5, 15, 2, 500],
[21, 3, 50, 1, 100],
[120, 15, 5, 2, 1200]]
# coefficient values
c = [3000, 200 , -50, 5000, 100]
def predict(X, c):
price = 0
for i in range (len(X)):
for j in range (len(X[i])):
price += (c[j]*X[i][j])
print(price)
predict(X, c)
The output is
258250
334350
827100.
The program adds the value of the 2nd an 3rd hourse the the previous result, rather than returning each house's value. How can I fix this?
Many thanks!
Move the line
price = 0
into the outer for loop:
def predict(X, c):
for i in range (len(X)):
price = 0
for j in range (len(X[i])):
...

Pandas groupby dataframe then return single value result (sum, total)

Dears,
Please help me, I am stucked.I guess it should not be difficult but I feel overwhelmed.
Need to make ageing of receivables, therefore they must be separated in different buckets.
Suppose we have only 3 groups: current, above_10Days and above_20Days and the following table:
d = {'Cust': [Dfg, Ers, Dac, Vds, Mhf, Kld, Xsd, Hun],
'Amount': [10000, 100000, 4000, 5411, 756000, 524058, 4444785, 54788,
'Days': 150, 21, 30, 231, 48, 15, -4, -14 }
I need to group the amounts to a total sum, depending on the Ageing group.
Example:
Current: 4499573, etc.
For that purpose, I tried to group the receivables with such code:
above_10Days = df.groupby((df['Days'] > 0) & (df['Days'] <= 10))
above10sum = above_10Days.Amount.sum().iloc[1]
It works perfect but only when they are actual amount in this group.
When they are no such A/R it throws an exception and stop executing. I tried to use function or to make 'None' value to 0, but no success.
Hopefully someone could know the solution.
Thanks in advance
IIUC:
d = {'Cust': ['Dfg', 'Ers', 'Dac', 'Vds', 'Mhf', 'Kld', 'Xsd', 'Hun'],
'Amount': [10000, 100000, 4000, 5411, 756000, 524058, 4444785, 54788],
'Days': [150, 21, 30, 231, 48, 15, -4, -14] }
df = pd.DataFrame(d)
#Updated to assign to output dataframe
df_out = (df.groupby(pd.cut(df.Days,
[-np.inf,10,20,np.inf],
labels=['Current','Above 10 Days','Above 20 Days']))['Amount']
.sum())
Output:
Days
Current 4499573
Above 10 Days 524058
Above 20 Days 875411
Name: Amount, dtype: int64
Varible assignent using .loc:
varCurrent = df_out.loc['Current']
var10 = df_out.loc['Above 10 Days']
var20 = df_out.loc['Above 20 Days']
print(varCurrent,var10,var20)
Output:
4499573 524058 875411

Resources