Working in Dymola, failing in OpenModelica - openmodelica

I have a code generated in Dymola and working there but failing in translation when run in OpenModelica.
Error:
Component cellGeometry of variability parameter has binding 'cellGeometry' of higher variability continuous.
..in code part:
Lib_thermosyphon.Thermosyphon.ThermosiphonCells.RefrigerantCellExt refrigerantCell[nCells](each refrigerantType = refrigerantType, each cellGeometry = cellGeometry, each hInit = hInit, each pInit = pInit, each initialSteadyState = initialSteadyState, each steadyPressureInit = steadyPressureInit, each m_flowStart = m_flowStart, redeclare each HTmodel heatTransfer, redeclare each PressureDropModel dpl, each dp_g(start = 0)) annotation(Placement(transformation(extent = {{-10, 12}, {10, 32}})));
Lib_thermosyphon.Thermosyphon.ThermosiphonCells.Geometry.CellGeometry cellGeometry(length = length / nCells, volume = volume / nCells, hydraulicDiameter = diameter, freeFlowArea = diameter ^ 2 * pi / 4, heatTransferArea = diameter * pi * length / nCells) annotation(
Placement(transformation(extent = {{-12, 36}, {8, 56}})));
...where RefrigerantCellExt has the following in the code:
model RefrigerantCellExt "represents a control volume of a refrigerant cell with extensions"
import Modelica.SIunits;
parameter Geometry.CellGeometry cellGeometry "used for HT and pressure drop correlations" annotation(
Placement(transformation(extent = {{-40, 20}, {-20, 40}}, rotation = 0)));
/****************** connectors *******************/
Lib_thermosyphon.Thermosyphon.Ports.RefrigerantPortA portA(m_flow(start = m_flowStart), mediumName = refrigerant.name) annotation(
Placement(transformation(extent = {{-110, -10}, {-90, 10}}, rotation = 0)));
Lib_thermosyphon.Thermosyphon.Ports.RefrigerantPortB portB(m_flow(start = -m_flowStart), mediumName = refrigerant.name) annotation(
Placement(transformation(extent = {{90, -10}, {110, 10}}, rotation = 0)));
Modelica.Thermal.HeatTransfer.Interfaces.HeatPort_a heatPort annotation(
Placement(transformation(extent = {{-10, -90}, {10, -70}}, rotation = 0)));
/****************** Init values *******************/
parameter SIunits.SpecificEnthalpy hInit "|Initinit value for specific enthalpy";
parameter SIunits.Pressure pInit "|Initinit value for pressure";
parameter Boolean initialSteadyState = true "|Initif true, simulation starts in steady state";
parameter Boolean steadyPressureInit = false "|Init|if true, pressure initialize in steady state";
parameter SIunits.MassFlowRate m_flowStart = 0.02 "start value for mass flow";
Real eVec[3];
SIunits.Pressure dp_g;
SIunits.Pressure dp_im_counter;
/****************** Refrigerant models *******************/
Lib_thermosyphon.Media.Refrigerant_Media.Refrigerant_StandardCell refrigerant(final refrigerantType = refrigerantType, p(start = pInit, fixed = false), h(start = hInit, fixed = false)) "Refrigerant model" annotation(
Placement(transformation(extent = {{-10, -10}, {10, 10}}, rotation = 0)));
replaceable parameter Lib_thermosyphon.Media.Refrigerant_Media.Refrigerant_Constants.R134a refrigerantType constrainedby Lib_thermosyphon.Media.Refrigerant_Media.Refrigerant_Constants.Refrigerant_Base annotation(
choicesAllMatching = true);
/****************** Properties of control volumes *******************/
SIunits.Mass mass "Mass of refrigerant in cell";
Real dpdt "Derivative of pressure wrt time";
Real drhodt "Derivative of density wrt time";
/****************** heat transfer *******************/
SIunits.HeatFlowRate Q_dot "transfered heat";
replaceable HeatExchangers.TransportPhenomena.TubeSideHeatTransfer.PartialTubeSideHeatTransfer heatTransfer(cellGeometry = cellGeometry, m_flow = m_flow, properties = properties, Q_dot = Q_dot, h_A = portA.h, h_B = portB.h, wallTemp = heatPort.T) annotation(
Placement(transformation(extent = {{-10, -42}, {10, -22}})));
/****************** pressure drop *******************/
SIunits.Pressure dp(start = 100) "pressure drop";
replaceable HeatExchangers.TransportPhenomena.TubeSidePressureDrop_ext.PartialTubeSidePressureDrop dpl(cellGeometry = cellGeometry, m_flow = m_flow, properties = properties, dp_g = dp_g) annotation(
Placement(transformation(extent = {{26, -10}, {46, 10}})));
/****************** hydraulic properties for HT and pressure drop correlation *******************/
SIunits.MassFlowRate m_flow "refrigerant massflow";
/****************** properties *******************/
protected
Lib_thermosyphon.Media.FluidPropertyRecord properties(final d = refrigerant.d, final h = refrigerant.h, final p = refrigerant.p, final T = refrigerant.T, final x = refrigerant.x1, final Pr = refrigerant.Pr, final Pr_l = refrigerant.Prl, final Pr_v = refrigerant.Prv, final nu = refrigerant.nu, final lambda = refrigerant.lambda, final p_crit = refrigerant.pc, final nu_l = refrigerant.nul, final nu_v = refrigerant.nuv, final lambda_l = refrigerant.lambdal, final medium = refrigerant.name, final h_l = refrigerant.hl, final h_v = refrigerant.hv, final d_l = refrigerant.dl, final d_v = refrigerant.dv);
...and so on.
...and cellGeometry has the following code:
record CellGeometry "geometry of fluid cell"
extends Lib_thermosyphon.Utilities.Types.RecordIcon;
import Modelica.SIunits;
import Modelica.Constants;
constant Real pi = Constants.pi;
parameter SIunits.Length length "length";
parameter SIunits.Volume volume = length * freeFlowArea "volume";
parameter SIunits.Diameter hydraulicDiameter "hydraulic diameter";
parameter SIunits.Area freeFlowArea = hydraulicDiameter * hydraulicDiameter * pi / 4 "flow cross section area";
parameter SIunits.Area heatTransferArea = hydraulicDiameter * pi * length "area of heat transfer";
end CellGeometry;
Could you please help?

The cellGeometry that you send to refrigerantCell as modifier needs to be defined as parameter:
Lib_thermosyphon.Thermosyphon.ThermosiphonCells.RefrigerantCellExt refrigerantCell[nCells](each refrigerantType = refrigerantType, each cellGeometry = cellGeometry, each hInit = hInit, each pInit = pInit, each initialSteadyState = initialSteadyState, each steadyPressureInit = steadyPressureInit, each m_flowStart = m_flowStart, redeclare each HTmodel heatTransfer, redeclare each PressureDropModel dpl, each dp_g(start = 0)) annotation(Placement(transformation(extent = {{-10, 12}, {10, 32}})));
parameter Lib_thermosyphon.Thermosyphon.ThermosiphonCells.Geometry.CellGeometry cellGeometry(length = length / nCells, volume = volume / nCells, hydraulicDiameter = diameter, freeFlowArea = diameter ^ 2 * pi / 4, heatTransferArea = diameter * pi * length / nCells) annotation(
Placement(transformation(extent = {{-12, 36}, {8, 56}})));
as in RefrigerantCellExt, cellGeometry is defined as parameter.

Related

How to change color of mark on topoplot interactively?

I want to create interactive line- and topoplot depending on menu. I figured out how to make red the line chosen in menu, but it doesn't work for topoplot marks (black circles inside topoplot). I can change it manually (cmap[][4] = RGB{N0f8}(1.0,0.0,0.0)), but how to do that interactively?
f = Figure(backgroundcolor = RGBf(0.98, 0.98, 0.98), resolution = (1500, 700))
ax = Axis(f[1:3, 1], xlabel = "Time [s]", ylabel = "Voltage amplitude [µV]")
N = 1:length(pos) #1:4
hidespines!(ax, :t, :r)
GLMakie.xlims!(-0.3, 1.2)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
times = range(-0.3, length=size(dat_e,2), step=1 ./ 128)
lines = Dict()
for i in N
mean_trial = mean(dat_e[i,:,:],dims=2)[:,1]
line = lines!(times, mean_trial, color = "black")
lines[i] = line
end
hidedecorations!(ax, label = false, ticks = false, ticklabels = false)
topo_axis = Axis(f[2, 2], width = 178, height = 178, aspect = DataAspect())
Makie.xlims!(low = -0.2, high = 1.2)
Makie.ylims!(low = -0.2, high = 1.2)
topoMatrix = eegHeadMatrix(pos[N], (0.5, 0.5), 0.5)
cmap = Observable(collect(ColorScheme(range(colorant"black", colorant"black", length=30))))
#cmap[][4] = RGB{N0f8}(1.0,0.0,0.0)
topo = eeg_topoplot!(topo_axis, N, # averaging all trial of 30 participants on Xth msec
raw.ch_names[1:30];
positions=pos, # produced automatically from ch_names
interpolation=NullInterpolator(),
enlarge=1,
#colorrange = (0, 1), # add the 0 for the white-first color
colormap = cmap[],
label_text=false)
hidedecorations!(current_axis())
hidespines!(current_axis())
num_prev = 0
menu = Menu(f[3, 2], options = raw.ch_names[1:30], default = nothing)#, default = "second")
on(menu.selection) do selected
if selected != nothing
num = findall(x->x==menu.selection[], raw.ch_names[1:30])[]
if num_prev != 0
lines[num_prev].color = "black"
cmap[][num] = RGB{N0f8}(1.0,0.0,0.0)
end
lines[num].color = "red"
cmap[][num] = RGB{N0f8}(1.0,0.0,0.0)
num_prev = num
end
end
notify(menu.selection)
#print(cmap[])
f
We solved this by putting this string at the end of the menu.selection section:
notify(lines)
It works, because lines() automatically creates Observable.

Problem with dynamically changing which command a button calls in tkinter

In this simple calculator GUI, I'm creating a frame template using classes. The frame has 2 labels, 2 entry boxes, and a button. I'd like the button to run a specific command depending on the function_call variable passed when initializing - but this doesn't work. The two_points function should be called for the first object, and one_point should be called for the second. How do I dynamically change which command is called based on which object I'm using? Thank you for taking the time to read this.
from tkinter import *
root = Tk()
root.title("Simple Slope Calculator")
class Slope_Calc:
# Variable info that changes within the frame
def __init__(self, master, num_1, num_2, frame_name, label_1_name, label_2_name, function_call):
self.num_1 = int(num_1)
self.num_2 = int(num_2)
self.frame_name = frame_name
self.label_1_name = label_1_name
self.label_2_name = label_2_name
self.function_call = function_call
# Frame template
self.frame_1 = LabelFrame(master, text = self.frame_name, padx = 5, pady = 5)
self.frame_1.grid(row = self.num_1, column = self.num_2, padx = 10, pady = 10)
self.label_1 = Label(self.frame_1, text = self.label_1_name)
self.label_1.grid(row = 0, column = 0)
self.entry_1 = Entry(self.frame_1)
self.entry_1.grid(row = 0, column = 1)
self.label_2 = Label(self.frame_1, text = self.label_2_name)
self.label_2.grid(row = 1, column = 0)
self.entry_2 = Entry(self.frame_1)
self.entry_2.grid(row = 1, column = 1)
self.calc_button = Button(self.frame_1, text = "Calculate", command = self.function_call) # This is what doesn't work
self.calc_button.grid(row = 1, column = 2, padx = 5)
# Strips string of spaces and parentheses
# Returns a list of relevant ordered pair
def strip_string(self, entry_num):
ordered_pair = entry_num.get().split(", ")
ordered_pair[0] = ordered_pair[0].replace("(", "")
ordered_pair[1] = ordered_pair[1].replace(")", "")
return(ordered_pair)
# Calculates slope based on one point and y-intercept
def one_point(self):
pair_1 = self.strip_string(self.entry_1)
b = int(self.entry_2.get())
m = (int(pair_1[1]) - b)/(float(pair_1[1]))
label_3 = Label(self.frame_1, text = "SLOPE-INTERCEPT EQUATION: y = " + str(m) + "x + " + str(b))
label_3.grid(row = 2, column = 0, columnspan = 2)
# Calculates slope based on two points given
def two_points(self):
pair_1 = self.strip_string(self.entry_1)
pair_2 = self.strip_string(self.entry_2)
m = (int(pair_2[1]) - int(pair_1[1]))/float(int(pair_2[0]) - int(pair_1[0]))
b = (int(pair_1[1])) - (m*int(pair_1[0]))
label_3 = Label(self.frame_1, text = "SLOPE-INTERCEPT EQUATION: y = " + str(m) + "x + " + str(b))
label_3.grid(row = 2, column = 0, columnspan = 2)
# Calling each object
two_p = Slope_Calc(root, 0, 0, "Two Points", "First Ordered Pair", "Second Ordered Pair", "two_points")
one_p = Slope_Calc(root, 0, 1, "One Point and Y-Intercept", "Ordered Pair", "Y-intercept", "one_point")
root.mainloop()
The command keyword argument of the Button constructor is supposed to be a function.
Here you give it instead a string which is the name of the method of self that should be called. So you must first get this method using setattr to be able to call it. This should do it:
def call():
method = getattr(self, self.function_call)
method()
self.calc_button = Button(
self.frame_1,
text = "Calculate",
command = call)
You then have an error in strip_string but that's another story.

How to get real Landsat image conrers

How I can get actual coordinates of Landsat image corners (see image to understand) ?
From metadata file (..._MTL.txt) I can get coordinates of red corners, but I need to get coordinates of green corners.
I work with GeoTIFF files using GDAL.
I need to get correct latitude and longitude of green points.
Can I do it using python3?
Thanks for help
Metadata file
GROUP = L1_METADATA_FILE
GROUP = METADATA_FILE_INFO
ORIGIN = "Image courtesy of the U.S. Geological Survey"
REQUEST_ID = "9991103150002_00325"
PRODUCT_CREATION_TIME = 2011-03-16T20:14:24Z
STATION_ID = "EDC"
LANDSAT5_XBAND = "1"
GROUND_STATION = "IKR"
LPS_PROCESSOR_NUMBER = 0
DATEHOUR_CONTACT_PERIOD = "1016604"
SUBINTERVAL_NUMBER = "01"
END_GROUP = METADATA_FILE_INFO
GROUP = PRODUCT_METADATA
PRODUCT_TYPE = "L1T"
ELEVATION_SOURCE = "GLS2000"
PROCESSING_SOFTWARE = "LPGS_11.3.0"
EPHEMERIS_TYPE = "DEFINITIVE"
SPACECRAFT_ID = "Landsat5"
SENSOR_ID = "TM"
SENSOR_MODE = "BUMPER"
ACQUISITION_DATE = 2010-06-15
SCENE_CENTER_SCAN_TIME = 04:57:44.2830500Z
WRS_PATH = 145
STARTING_ROW = 26
ENDING_ROW = 26
BAND_COMBINATION = "1234567"
PRODUCT_UL_CORNER_LAT = 49.8314223
PRODUCT_UL_CORNER_LON = 84.0018859
PRODUCT_UR_CORNER_LAT = 49.8694055
PRODUCT_UR_CORNER_LON = 87.4313889
PRODUCT_LL_CORNER_LAT = 47.8261840
PRODUCT_LL_CORNER_LON = 84.1192898
PRODUCT_LR_CORNER_LAT = 47.8615913
PRODUCT_LR_CORNER_LON = 87.4144676
PRODUCT_UL_CORNER_MAPX = 284400.000
PRODUCT_UL_CORNER_MAPY = 5524200.000
PRODUCT_UR_CORNER_MAPX = 531000.000
PRODUCT_UR_CORNER_MAPY = 5524200.000
PRODUCT_LL_CORNER_MAPX = 284400.000
PRODUCT_LL_CORNER_MAPY = 5301000.000
PRODUCT_LR_CORNER_MAPX = 531000.000
PRODUCT_LR_CORNER_MAPY = 5301000.000
PRODUCT_SAMPLES_REF = 8221
PRODUCT_LINES_REF = 7441
PRODUCT_SAMPLES_THM = 4111
PRODUCT_LINES_THM = 3721
BAND1_FILE_NAME = "L5145026_02620100615_B10.TIF"
BAND2_FILE_NAME = "L5145026_02620100615_B20.TIF"
BAND3_FILE_NAME = "L5145026_02620100615_B30.TIF"
BAND4_FILE_NAME = "L5145026_02620100615_B40.TIF"
BAND5_FILE_NAME = "L5145026_02620100615_B50.TIF"
BAND6_FILE_NAME = "L5145026_02620100615_B60.TIF"
BAND7_FILE_NAME = "L5145026_02620100615_B70.TIF"
GCP_FILE_NAME = "L5145026_02620100615_GCP.txt"
METADATA_L1_FILE_NAME = "L5145026_02620100615_MTL.txt"
CPF_FILE_NAME = "L5CPF20100401_20100630_09"
END_GROUP = PRODUCT_METADATA
GROUP = MIN_MAX_RADIANCE
LMAX_BAND1 = 193.000
LMIN_BAND1 = -1.520
LMAX_BAND2 = 365.000
LMIN_BAND2 = -2.840
LMAX_BAND3 = 264.000
LMIN_BAND3 = -1.170
LMAX_BAND4 = 221.000
LMIN_BAND4 = -1.510
LMAX_BAND5 = 30.200
LMIN_BAND5 = -0.370
LMAX_BAND6 = 15.303
LMIN_BAND6 = 1.238
LMAX_BAND7 = 16.500
LMIN_BAND7 = -0.150
END_GROUP = MIN_MAX_RADIANCE
GROUP = MIN_MAX_PIXEL_VALUE
QCALMAX_BAND1 = 255.0
QCALMIN_BAND1 = 1.0
QCALMAX_BAND2 = 255.0
QCALMIN_BAND2 = 1.0
QCALMAX_BAND3 = 255.0
QCALMIN_BAND3 = 1.0
QCALMAX_BAND4 = 255.0
QCALMIN_BAND4 = 1.0
QCALMAX_BAND5 = 255.0
QCALMIN_BAND5 = 1.0
QCALMAX_BAND6 = 255.0
QCALMIN_BAND6 = 1.0
QCALMAX_BAND7 = 255.0
QCALMIN_BAND7 = 1.0
END_GROUP = MIN_MAX_PIXEL_VALUE
GROUP = PRODUCT_PARAMETERS
CORRECTION_METHOD_GAIN_BAND1 = "CPF"
CORRECTION_METHOD_GAIN_BAND2 = "CPF"
CORRECTION_METHOD_GAIN_BAND3 = "CPF"
CORRECTION_METHOD_GAIN_BAND4 = "CPF"
CORRECTION_METHOD_GAIN_BAND5 = "CPF"
CORRECTION_METHOD_GAIN_BAND6 = "IC"
CORRECTION_METHOD_GAIN_BAND7 = "CPF"
CORRECTION_METHOD_BIAS = "IC"
SUN_AZIMUTH = 141.2669762
SUN_ELEVATION = 59.9909680
OUTPUT_FORMAT = "GEOTIFF"
END_GROUP = PRODUCT_PARAMETERS
GROUP = CORRECTIONS_APPLIED
STRIPING_BAND1 = "NONE"
STRIPING_BAND2 = "NONE"
STRIPING_BAND3 = "NONE"
STRIPING_BAND4 = "NONE"
STRIPING_BAND5 = "NONE"
STRIPING_BAND6 = "NONE"
STRIPING_BAND7 = "NONE"
BANDING = "N"
COHERENT_NOISE = "N"
MEMORY_EFFECT = "Y"
SCAN_CORRELATED_SHIFT = "Y"
INOPERABLE_DETECTORS = "N"
DROPPED_LINES = "N"
END_GROUP = CORRECTIONS_APPLIED
GROUP = PROJECTION_PARAMETERS
REFERENCE_DATUM = "WGS84"
REFERENCE_ELLIPSOID = "WGS84"
GRID_CELL_SIZE_THM = 60.000
GRID_CELL_SIZE_REF = 30.000
ORIENTATION = "NUP"
RESAMPLING_OPTION = "CC"
MAP_PROJECTION = "UTM"
END_GROUP = PROJECTION_PARAMETERS
GROUP = UTM_PARAMETERS
ZONE_NUMBER = 45
END_GROUP = UTM_PARAMETERS
END_GROUP = L1_METADATA_FILE
END
You might first find the contour with the biggest area. Then try some algorithm to find the points you want. It seems that the satellite picture in the image is not a perfect rectangle, so you can't fit a rectangle on it using OpenCV's built-in methods.
You should try something like that:
import cv2
import numpy as np
img = cv2.imread('z_edited.jpg')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(imgray, (11, 11), 0)
ret, thresh = cv2.threshold(blurred, 27, 255, 0)
cnts, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
max_area = 0
max_area_index = 0
for i, cnt in enumerate(cnts):
area = cv2.contourArea(cnt)
if area > max_area:
max_area = area
max_area_index = i
x_min = np.min(cnts[max_area_index][:, 0, 0])
x_max = np.max(cnts[max_area_index][:, 0, 0])
y_min = np.min(cnts[max_area_index][:, 0, 1])
y_max = np.max(cnts[max_area_index][:, 0, 1])
(x_left, y_left) = (x_min, cnts[max_area_index][np.max(np.where(cnts[max_area_index][:, 0, 0] == x_min)), 0, 1])
(x_right, y_right) = (x_max, cnts[max_area_index][np.max(np.where(cnts[max_area_index][:, 0, 0] == x_max)), 0, 1])
(x_down, y_down) = (cnts[max_area_index][np.max(np.where(cnts[max_area_index][:, 0, 1] == y_max)), 0, 0], y_max)
(x_top, y_top) = (cnts[max_area_index][np.max(np.where(cnts[max_area_index][:, 0, 1] == y_min)), 0, 0], y_min)
cv2.circle(img, (x_left, y_left), 10, (0, 0, 255), thickness=8)
cv2.circle(img, (x_right, y_right), 10, (0, 0, 255), thickness=8)
cv2.circle(img, (x_down, y_down), 10, (0, 0, 255), thickness=8)
cv2.circle(img, (x_top, y_top), 10, (0, 0, 255), thickness=8)
# cv2.drawContours(img, cnts, max_area_index, (0, 255, 0), 2)
cv2.namedWindow('s', cv2.WINDOW_NORMAL)
cv2.imshow('s', img)
cv2.waitKey(0)
And the result looks like:
Using this code you can find the coordinates of the corners of the satellite picture inside the image(red points).
Also need to say I have assumed that your satellite picture background is completely black(the image you have uploaded, has a thin gray strip around the whole image).

Why isn’t NUTS sampling with tt.dot or pm.math.dot?

I am trying to implement parts of Facebook's prophet with some help from this example.
https://github.com/luke14free/pm-prophet/blob/master/pmprophet/model.py
This goes well :), but I am having some problems with the dot product I don't understand. Note that I am implementing the linear trends.
ds = pd.to_datetime(df['dagindex'], format='%d-%m-%y')
m = pm.Model()
changepoint_prior_scale = 0.05
n_changepoints = 25
changepoints = pd.date_range(
start=pd.to_datetime(ds.min()),
end=pd.to_datetime(ds.max()),
periods=n_changepoints + 2
)[1: -1]
with m:
# priors
sigma = pm.HalfCauchy('sigma', 10, testval=1)
#trend
growth = pm.Normal('growth', 0, 10)
prior_changepoints = pm.Laplace('changepoints', 0, changepoint_prior_scale, shape=len(changepoints))
y = np.zeros(len(df))
# indexes x_i for the changepoints.
s = [np.abs((ds - i).values).argmin() for i in changepoints]
g = growth
x = np.arange(len(ds))
# delta
d = prior_changepoints
regression = x * g
base_piecewise_regression = []
for i in s:
local_x = x.copy()[:-i]
local_x = np.concatenate([np.zeros(i), local_x])
base_piecewise_regression.append(local_x)
piecewise_regression = np.array(base_piecewise_regression)
# this dot product doesn't work?
piecewise_regression = pm.math.dot(theano.shared(piecewise_regression).T, d)
# If I comment out this line and use that one as dot product. It works fine
# piecewise_regression = (piecewise_regression.T * d[None, :]).sum(axis=-1)
regression += piecewise_regression
y += regression
obs = pm.Normal('y',
mu=(y - df.gebruikers.mean()) / df.gebruikers.std(),
sd=sigma,
observed=(df.gebruikers - df.gebruikers.mean()) / df.gebruikers.std())
start = pm.find_MAP(maxeval=10000)
trace = pm.sample(500, step=pm.NUTS(), start=start)
If I run the snippet above with
piecewise_regression = (piecewise_regression.T * d[None, :]).sum(axis=-1)
the model works as expected. However I cannot get it to work with a dot product. The NUTS sampler doesn't sample at all.
piecewise_regression = pm.math.dot(theano.shared(piecewise_regression).T, d)
EDIT
Ive got a minimal working example
The problem still occurs with theano.shared. I’ve got a minimal working example:
np.random.seed(5)
n_changepoints = 10
t = np.arange(1000)
s = np.sort(np.random.choice(t, size=n_changepoints, replace=False))
a = (t[:, None] > s) * 1
real_delta = np.random.normal(size=n_changepoints)
y = np.dot(a, real_delta) * t
with pm.Model():
sigma = pm.HalfCauchy('sigma', 10, testval=1)
delta = pm.Laplace('delta', 0, 0.05, shape=n_changepoints)
g = tt.dot(a, delta) * t
obs = pm.Normal('obs',
mu=(g - y.mean()) / y.std(),
sd=sigma,
observed=(y - y.mean()) / y.std())
trace = pm.sample(500)
It seems to have something to do with the size of matrix a. NUTS doesnt’t sample if I start with
t = np.arange(1000)
however the example above does sample when I reduce the size of t to:
t = np.arange(100)

Calculating entropy in ID3 log2(0) in formula

import numpy as np
udacity_set = np.array(
[[1,1,1,0],
[1,0,1,0],
[0,1,0,1],
[1,0,0,1]])
label = udacity_set[:,udacity_set.shape[1]-1]
fx = label.size
positive = label[label == 1].shape[0]
positive_probability = positive/fx
negative = label[label == 0].shape[0]
negative_probability = negative/fx
entropy = -negative_probability*np.log2(negative_probability) - positive_probability*np.log2(positive_probability)
atribute = 0
V = 1
attribute_set = udacity_set[np.where(udacity_set[:,atribute] == 1)] #selecting positive instance of occurance in attribute 14
instances = attribute_set.shape[0]
negative_labels = attribute_set[np.where(attribute_set[:,attribute_set.shape[1]-1]== 0)].shape[0]
positive_labels = attribute_set[np.where(attribute_set[:,attribute_set.shape[1]-1]== 1)].shape[0]
p0 = negative_labels/instances
p1 = positive_labels/instances
entropy2 = - p0*np.log2(p0) - p1*np.log2(p1)
attribute_set2 = udacity_set[np.where(udacity_set[:,atribute] == 0)] #selecting positive instance of occurance in attribute 14
instances2 = attribute_set2.shape[0]
negative_labels2 = attribute_set[np.where(attribute_set2[:,attribute_set2.shape[1]-1]== 0)].shape[0]
positive_labels2 = attribute_set[np.where(attribute_set2[:,attribute_set2.shape[1]-1]== 1)].shape[0]
p02 = negative_labels2/instances2
p12 = positive_labels2/instances2
entropy22 = - p02*np.log2(p02) - p12*np.log2(p12)
Problem is when attribute is pure and entropy is meant to be 0. But when i put this into a formula i get NaN. I know how to code workaround, but why is this formula rigged?

Resources