initialization of variable in pre in Modelica - initialization

I wrote the codes in Modelica as below:
model TestIniitial
extends Modelica.Icons.Example;
parameter Integer nWri= 2;
Real u[nWri](each start= 10, fixed=false);
Real uPre[nWri];
parameter Real _uStart[nWri] = fill(10, nWri);
parameter Modelica.SIunits.Time startTime = 0;
parameter Modelica.SIunits.Time samplePeriod = 1;
Boolean sampleTrigger "True, if sample time instant";
initial equation
u[1] = 1;
u[2] = 2;
equation
sampleTrigger = sample(startTime, samplePeriod);
when sampleTrigger then
for i in 1: nWri loop
uPre[i] = pre(u[i]);
end for;
end when;
for i in 1:nWri loop
u[i] = (i+1)*time;
end for;
end TestIniitial;
Basically I want to initialize the u before simulation. However, I got below complaints(the initialization of u is over-specified) from translation:
The Modelica Language Specification 3.2.1 specifies that if a real variable, v,
is appearing in an expression as pre(v), but not assigned by a when equation,
then the equation v = pre(v) should be added to the initialization problem.
For this problem the following equations were added:
u[1] = pre(u[1]);
u[2] = pre(u[2]);
I can't understand the complaints since pre(v) was assigned in when equation already. What can I do if I want to initialize the u in above codes?
Thanks.

Looking at this, my guess is that the error message is trying to provide you some diagnostics but it is incorrect about the source. I suspect (again, I do not know for sure) that it sees the fact that pre(u) appears in the model and that there is an initialization problem and assumes a specific issue.
My guess is that the issue stems from the fact that you have fixed=true set on u. I see no reason to do that and my guess is that it will lead to too many constraints on the initialization problem as well. Get rid of the fixed=true and see what happens. Report back if that doesn't address the problem.
Good luck.

Related

BertModel transformers outputs string instead of tensor

I'm following this tutorial that codes a sentiment analysis classifier using BERT with the huggingface library and I'm having a very odd behavior. When trying the BERT model with a sample text I get a string instead of the hidden state. This is the code I'm using:
import transformers
from transformers import BertModel, BertTokenizer
print(transformers.__version__)
PRE_TRAINED_MODEL_NAME = 'bert-base-cased'
PATH_OF_CACHE = "/home/mwon/data-mwon/paperChega/src_classificador/data/hugingface"
tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME,cache_dir = PATH_OF_CACHE)
sample_txt = 'When was I last outside? I am stuck at home for 2 weeks.'
encoding_sample = tokenizer.encode_plus(
sample_txt,
max_length=32,
add_special_tokens=True, # Add '[CLS]' and '[SEP]'
return_token_type_ids=False,
padding=True,
truncation = True,
return_attention_mask=True,
return_tensors='pt', # Return PyTorch tensors
)
bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME,cache_dir = PATH_OF_CACHE)
last_hidden_state, pooled_output = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask']
)
print([last_hidden_state,pooled_output])
that outputs:
4.0.0
['last_hidden_state', 'pooler_output']
While the answer from Aakash provides a solution to the problem, it does not explain the issue. Since one of the 3.X releases of the transformers library, the models do not return tuples anymore but specific output objects:
o = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask']
)
print(type(o))
print(o.keys())
Output:
transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions
odict_keys(['last_hidden_state', 'pooler_output'])
You can return to the previous behavior by adding return_dict=False to get a tuple:
o = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask'],
return_dict=False
)
print(type(o))
Output:
<class 'tuple'>
I do not recommend that, because it is now unambiguous to select a specific part of the output without turning to the documentation as shown in the example below:
o = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'], return_dict=False, output_attentions=True, output_hidden_states=True)
print('I am a tuple with {} elements. You do not know what each element presents without checking the documentation'.format(len(o)))
o = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'], output_attentions=True, output_hidden_states=True)
print('I am a cool object and you can acces my elements with o.last_hidden_state, o["last_hidden_state"] or even o[0]. My keys are; {} '.format(o.keys()))
Output:
I am a tuple with 4 elements. You do not know what each element presents without checking the documentation
I am a cool object and you can acces my elements with o.last_hidden_state, o["last_hidden_state"] or even o[0]. My keys are; odict_keys(['last_hidden_state', 'pooler_output', 'hidden_states', 'attentions'])
I faced the same issue while learning how to implement Bert. I noticed that using
last_hidden_state, pooled_output = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'])
is the issue. Use:
outputs = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'])
and extract the last_hidden state using
output[0]
You can refer to the documentation here which tells you what is returned by the BertModel

extensions or even observation empty with Chainer

I am kind of new on Chainer and I have been struggling with a weird situation recently.
I have a Chain to compute a CNN which I feed with a labeledDataSet.
But no results appears when I use the extensions. When I display the observation value it is empty. But the loss is indeed calculated and the parameters updated (at least they change) so I don't know where is the connection problem.
def convert(batch, device):
return chainer.dataset.convert.concat_examples(batch, device, padding=0)
def print_obs(t):
print("trainer.observation", trainer.observation)
print("updater.loss", updater.loss_func)
print("conv1", model.predictor.conv1.W[0][0])
print("conv20", model.predictor.conv20.W[0][0])
model.predictor.train = True
model.predictor.finetune = False ####or True ??
cuda.get_device(0).use()
model.to_gpu()
optimizer = optimizers.MomentumSGD(lr=learning_rate, momentum=momentum)
optimizer.use_cleargrads()
optimizer.setup(model)
optimizer.add_hook(chainer.optimizer.WeightDecay(weight_decay))
train, test = imageNet_data.train_val_test()
train_iter = iterators.SerialIterator(train, batch_size)
test_iter = iterators.SerialIterator(test, batch_size, repeat=False,shuffle=False)
with chainer.using_config('debug', True):
# Set up a trainer
updater = training.StandardUpdater(train_iter, optimizer, loss_func=model, converter=convert)
trainer = training.Trainer(updater, (10, 'epoch'), out="./backup/result")
trainer.extend(print_obs, trigger=(3, 'iteration'))
trainer.extend(extensions.LogReport())
trainer.extend(extensions.PrintReport(
['epoch', 'main/loss', 'validation/main/loss',
'main/accuracy', 'validation/main/accuracy', 'elapsed_time']))
trainer.run()
Maybe this is something is miss completely and which is quite obvious.. Thank you for all remarks that would help me a lot.
Chainer4.1, Ubuntu16
If you are using your own Link with the Trainer, you need to report metrics using chainer.report by your own.
See https://docs.chainer.org/en/stable/guides/report.html for instructions.
You can see some examples in Chainer repository:
https://github.com/chainer/chainer/blob/v4.1.0/chainer/links/model/classifier.py#L116
https://github.com/chainer/chainer/blob/v4.1.0/examples/imagenet/alex.py#L40

Filter vertices on several properties - Julia

I am working on julia with the Metagraphs.jl library.
In order to conduct an optimization problem, I would like to get the set/list of edges in the graph that point to a special set of vertices having 2 particular properties in common.
My first guess was to first get the set/list of vertices. But I am facing a first issue which is that the filter_vertices function doesn't seem to accept to apply a filter on more than one property.
Here is below an example of what I would like to do:
g = DiGraph(5)
mg = MetaDiGraph(g, 1.0)
add_vertex!(mg)
add_edge!(mg,1,2)
add_edge!(mg,1,3)
add_edge!(mg,1,4)
add_edge!(mg,2,5)
add_edge!(mg,3,5)
add_edge!(mg,5,6)
add_edge!(mg,4,6)
set_props!(mg,3,Dict(:prop1=>1,:prop2=>2))
set_props!(mg,1,Dict(:prop1=>1,:prop2=>0))
set_props!(mg,2,Dict(:prop1=>1,:prop2=>0))
set_props!(mg,4,Dict(:prop1=>0,:prop2=>2))
set_props!(mg,5,Dict(:prop1=>0,:prop2=>2))
set_props!(mg,6,Dict(:prop1=>0,:prop2=>0))
col=collect(filter_vertices(mg,:prop1,1,:prop2,2))
And I want col to find vertex 3 and no others.
But the filter_vertices would only admit one property at a time and then it makes it more costly to do a loop with 2 filters and then try to compare in order to sort a list with the vertices that have both properties.
Considering the size of my graph I would like to avoid defining this set with multiple and costly loops. Would any one of you have an idea of how to solve this issue in an easy and soft way?
I ended up making this to answer my own question:
fil3=Array{Int64,1}()
fil1=filter_vertices(mg,:prop1,1)
for f in fil1
if get_prop(mg,f,:prop2)==2
push!(fil3,f)
end
end
println(fil3)
But tell me if you get anything more interesting
Thanks for your help!
Please provide a minimal working example in a way we can simply copy and paste, and start right away. Please also indicate where the problem occurs in the code. Below is an example for your scenario:
Pkg.add("MetaGraphs")
using LightGraphs, MetaGraphs
g = DiGraph(5)
mg = MetaDiGraph(g, 1.0)
add_vertex!(mg)
add_edge!(mg,1,2)
add_edge!(mg,1,3)
add_edge!(mg,1,4)
add_edge!(mg,2,5)
add_edge!(mg,3,5)
add_edge!(mg,5,6)
add_edge!(mg,4,6)
set_props!(mg,3,Dict(:prop1=>1,:prop2=>2))
set_props!(mg,1,Dict(:prop1=>1,:prop2=>0))
set_props!(mg,2,Dict(:prop1=>1,:prop2=>0))
set_props!(mg,4,Dict(:prop1=>0,:prop2=>2))
set_props!(mg,5,Dict(:prop1=>0,:prop2=>2))
set_props!(mg,6,Dict(:prop1=>0,:prop2=>0))
function my_vertex_filter(g::AbstractMetaGraph, v::Integer, prop1, prop2)
return has_prop(g, v, :prop1) && get_prop(g, v, :prop1) == prop1 &&
has_prop(g, v, :prop2) && get_prop(g, v, :prop2) == prop2
end
prop1 = 1
prop2 = 2
col = collect(filter_vertices(mg, (g,v)->my_vertex_filter(g,v,prop1,prop2)))
# returns Int[3]
Please check ?filter_vertices --- it gives you a hint on what/how to write to define your custom filter.
EDIT. For filtering the edges, you can have a look at ?filter_edges to see what you need to achieve the edge filtering. Append the below code excerpt to the solution above to get your results:
function my_edge_filter(g, e, prop1, prop2)
v = dst(e) # get the edge's destination vertex
return my_vertex_filter(g, v, prop1, prop2)
end
myedges = collect(filter_edges(mg, (g,e)->my_edge_filter(g,e,prop1,prop2)))
# returns [Edge 1 => 3]
I found this solution:
function filter_function1(g,prop1,prop2)
fil1=filter_vertices(g,:prop1,prop1)
fil2=filter_vertices(g,:prop2,prop2)
filter=intersect(fil1,fil2)
return filter
end
This seems to work and is quite easy to implement.
Just I don't know if the filter_vertices function is taking a lot of computational power.
Otherwise a simple loop like this seems to also work:
function filter_function2(g,prop1,prop2)
filter=Set{Int64}()
fil1=filter_vertices(g,:prop1,prop1)
for f in fil1
if get_prop(g,f,:prop2)==prop2
push!(filter,f)
end
end
return filter
end
I am open to any other answers if you have some more elegant ones.

Scilab - gui - many unknown variables error messages

Still trying to understand the logic of Scilab, I created a small calculation tool for a mechanical element. The main problem I have is finding the right order (or syntax) for the calculation code... I get a lot of "unknown variable" errors and I don't understand why?
I tried to change the order of definitions for the functions, declare the variables as global, etc. but nothing seems to help.
The code for the calculation is not long and also not complicated, but the gui was built using guibuilder, so the uicontrols definitions are probably much longer than they need to be.
Could somebody help me make this code working, as I would learn and understand a lot by this example, althought it contains more than one "problem zones"?
Here what I've done:
G = 78500;
table_titles = ["" "Wire diameter" "Wp" "Tau alwd" "M alwd" "Angle alwd"];
f=figure('figure_position',[910,163],'figure_size',
[903,537],'auto_resize','on','background',[33],'figure_name','Graphic
window number %d');
//////////
delmenu(f.figure_id,gettext('File'))
delmenu(f.figure_id,gettext('?'))
delmenu(f.figure_id,gettext('Tools'))
toolbar(f.figure_id,'off')
handles.dummy = 0;
handles.sl_dwire=uicontrol(f,'unit','normalized','BackgroundColor',
[-1,-1,-1],'Enable','on','FontAngle','normal','FontName','Tahoma',
'FontSize',[12],'FontUnits','points','FontWeight','normal',
'ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left','ListboxTop',
[],'Max',[12],'Min',[0],'Position',
[0.0058208,0.77875,0.124375,0.06875],'Relief','default','SliderStep',
[0.1,1],'Style','slider','String',"Wire diameter",'Value',
[6],'VerticalAlignment','middle','Visible','on','Tag','sl_dwire',
'Callback','sl_dwire_callback(handles)')
handles.ed_dwire=uicontrol(f,'unit','normalized','BackgroundColor',
[-1,-1,-1],'Enable','off','FontAngle','normal','FontName','Tahoma',
'FontSize',[12],'FontUnits','points','FontWeight','normal',
'ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left','ListboxTop',
[],'Max',[1],'Min',[0],
'Position',[0.0058208,0.71875,0.124375,0.06875],'Relief',
'default','SliderStep',[0.01,0.1],'String',"wire diameter: " +
msprintf('%2.1f',handles.sl_dwire.Value) + "mm",'Style','text',
'Value',[0],'VerticalAlignment','middle','Visible','on','Tag',
'ed_dwire','Callback','auto')
handles.sl_wangle=uicontrol(f,'unit','normalized','BackgroundColor',
[-1,-1,-1],'Enable','on','FontAngle','normal','FontName','Tahoma',
'FontSize',[12],'FontUnits','points','FontWeight','normal',
'ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left',
'ListboxTop',[],'Max',[180],'Min',[5],'Position',
[0.0090625,0.5191667,0.25625,0.0645833],'Relief','default',
'SliderStep',[0.1,1],'String','Working angle','Style','slider','Value',
[50],'VerticalAlignment','middle','Visible','on','Tag','sl_wangle',
'Callback','sl_wangle_callback(handles)')
handles.ed_wangle=uicontrol(f,'unit','normalized','BackgroundColor',
[-1,-1,-1],'Enable','off','FontAngle','normal','FontName','Tahoma',
'FontSize',[12],'FontUnits','points','FontWeight','normal',
'ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left',
'ListboxTop',[],'Max',[1],'Min',[0],'Position',
[0.0090625,0.4591667,0.25625,0.0645833],'Relief','default',
'SliderStep',[0.01,0.1],'String',"Working angle: " +
msprintf('%2.1f',handles.sl_wangle.Value) + "°",'Style','text',
'Value',[0],'VerticalAlignment','middle','Visible','on','Tag',
'ed_wangle','Callback','auto')
handles.sl_activel=uicontrol(f,'unit','normalized',
'BackgroundColor',[-1,-1,-1],'Enable','on','FontAngle','normal',
'FontName','Tahoma','FontSize',[12],'FontUnits','points','FontWeight',
'normal','ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left',
'ListboxTop',[],'Max',[1000],'Min',[10],'Position',
[0.0090625,0.365,0.25625,0.0645833],'Relief','default',
'SliderStep',[0.1,1],'String','Active length' ,'Style','slider',
'Value',[10],'VerticalAlignment','middle','Visible','on','Tag',
'sl_activel','Callback','sl_activel_callback(handles)')
handles.ed_activel=uicontrol(f,'unit','normalized',
'BackgroundColor',[-1,-1,-1],'Enable','off','FontAngle','normal',
'FontName','Tahoma','FontSize',[12],'FontUnits','points','FontWeight',
'normal','ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left',
'ListboxTop',[],'Max',[1],'Min',[0],'Position',
[0.0090625,0.305,0.25625,0.0645833],'Relief','default',
'SliderStep',[0.01,0.1],'String','Active length: ' +
msprintf('%2.1f',handles.sl_activel.Value) +
"mm",'Style','text','Value',[0],'VerticalAlignment','middle','Visible',
'on','Tag','ed_activel','Callback','auto')
handles.ax_graph= newaxes();handles.ax_graph.margins = [ 0 0 0 0];
handles.ax_graph.axes_bounds = [0.4274266,0.0619266,0.3995485,0.5191743];
handles.tab_param=uicontrol(f,'unit','normalized','BackgroundColor',
[-1,-1,-1],'Enable','on','FontAngle','normal','FontName',
'Tahoma','FontSize',[12],'FontUnits','points','FontWeight','normal',
'ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left',
'ListboxTop',[],'Max',[1],'Min',[0],
'Position',[0.4308126,0.1690826,0.3950339,0.2178899],'Relief',
'default','SliderStep',[0.01,0.1],'String',string(table_param),'Style',
'table','Value',[0],'VerticalAlignment','middle','Visible',
'on','Tag','tab_param','Callback','tab_param_callback(handles)')
handles.sl_sfactor=uicontrol(f,'unit','normalized',
'BackgroundColor',[-1,-1,-1],'Enable','on','FontAngle','normal',
'FontName','Tahoma','FontSize',[12],'FontUnits','points','FontWeight',
'normal','ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left',
'ListboxTop',[],'Max',[1],'Min',[0],
'Position',[0.0058208,0.6525688,0.124375,0.06875],'Relief','default',
'SliderStep',[0.01,0.1],'String',"Safety factor",'Style',
'slider','Value',[0.58],'VerticalAlignment','middle','Visible','on',
'Tag','ed_sfactor','Callback','sl_sfactor_callback(handles)')
handles.ed_sfactor=uicontrol(f,'unit','normalized',
'BackgroundColor',[-1,-1,-1],'Enable','off','FontAngle','normal',
'FontName','Tahoma','FontSize',[12],'FontUnits','points','FontWeight',
'normal','ForegroundColor',[-1,-1,-1],'HorizontalAlignment',
'left','ListboxTop',[],'Max',[1],'Min',[0],'Position',
[0.0058208,0.5925688,0.124375,0.06875],'Relief','default',
'SliderStep',[0.01,0.1],'String',"Safety factor : " +
msprintf('%2.1f',handles.sl_sfactor.Value),'Style',
'text','Value',[0.58],'VerticalAlignment','middle','Visible','on',
'Tag','ed_dwire','Callback','auto')
handles.popm_wtype=uicontrol(f,'unit','normalized',
'BackgroundColor',[-1,-1,-1],'Enable','on','FontAngle','normal',
'FontName','Tahoma','FontSize',[12],'FontUnits','points','FontWeight',
'normal','ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left',
'ListboxTop',[],'Max',[1],'Min',[0],'Position',
[0.0058208,0.8618349,0.124375,0.0639450],'Relief','default',
'SliderStep',[0.01,0.1],'String',gettext("SL/DL|SM/DM|SH/DH"),'Style',
'popupmenu','Value',[2],'VerticalAlignment','middle','Visible','on',
'Tag','popm_wtype','Callback','popm_wtype_callback(handles)')
//////////
// Callbacks are defined as below. Please do not delete the comments
as it will be used in coming version
//////////
function sl_sfactor_callback(handles)
sf=handles.sl_sfactor.Value;
handles.ed_sfactor.String="Safety factor: " + msprintf('%3.2f',sf);
endfunction
function sl_dwire_callback(handles)
wd=handles.sl_dwire.Value;
Wp = %pi*wd^3/16;
Ip =%pi*wd^4/32;
Kt = G*%pi*Ip/(180*L);
Talwd = sf * calcform;
Malwd = Wp * Talwd;
alphaalwd = Malwd / Kt;
x=0:0.1:alphaalwd*1.5;
plot(x,Kt*x);
handles.ed_dwire.String="Wire diameter: " +
msprintf('%2.1f',wd) + "mm";
endfunction
function popm_wtype_callback(handles)
//Write your callback for popm_wtype here
if selected == 1 then
calcform =(1845 - 700*log10(wd));
elseif selected == 2 then
calcform =(2105 - 780*log10(wd));
elseif selected == 3 then
calcform = (2220 - 820*log10(wd));
end
endfunction
function sl_wangle_callback(handles)
handles.ed_wangle.String="Working angle: " +
msprintf('%2.1f',handles.sl_wangle.Value) + "°";
endfunction
function sl_activel_callback(handles)
//Write your callback for sl_activel here
handles.ed_activel.String="Active length: " +
msprintf('%2.1f',handles.sl_activel.Value) + "mm";
L=handles.sl_activel.Value;
endfunction
function tab_param_callback(handles)
//Write your callback for tab_param here
table_values = string([ wd Wp Talwd Malwd alphaalwd]);
table_param = [table_titles; [table_values]];
endfunction
I expect the code to dynamically update the graph and the parameters table according to the positions of input sliders and popup-menu.
Again, it would be very helpful if somebody could help me get this code working, as I would get answers for a lot of my questions concerning programming with scilab.
Thank you very much in advance!
First of all, your code is not directly executable, caused by the linebreaks. Please add ... after each line of a statement. This improves also the readability.
As mentioned by #luispauloml, you try to use variables, which exist just inside of another function. For example you try to reach table_param, which is just alive in tab_param_callback(handles).
To get rid of this, you have to define the output for the function:
function [table_values, table_param] = tab_param_callback(handles)
table_values = string([ wd Wp Talwd Malwd alphaalwd]);
table_param = [table_titles; [table_values]];
endfunction
Now you can call this function to get the variable:
string(tab_param_callback(handles))
I corrected just this case and added the dots as explained. For the other variables, it can be done analogously. Furthermore, I moved the function definition to the beginning of the code. Because if your scrips crashed in the middle, the compiler has no chance to read the function definitions.
Please find the code in this file .
I hope this helps. Good luck!

K nearest neighbors with Gower distance measure in R

I hope everyone is well; I have a question it is may be looked as a dumb one but I really need someone to explain it for me. I also though it will be useful for some, since it has been asked before with no satisfactory answer.
Since , I have mixed data type matrix, I was looking for K-nearst neighbors algorithem that works with gower distance in R. I found the function Knngow under the package dprep that claims to perform this.
http://finzi.psych.upenn.edu/library/dprep/html/knngow.html
The function take three argument knngow( Training_Set, Testing_set, K_number) and return the predicted class.
I was playing around with it and was wondering how the function can recognize what is my target vector? Put differently, how does it return the predicted class, without me acknowledging it in advance with my target column.
please find the source code below ( I retrieved it using the function edit)
function (train, test, k)
{
p = dim(train)[2]
ntest = dim(test)[1]
ntrain = dim(train)[1]
classes = rep(0, ntest)
if (ntest == ntrain) {
for (i in 1:ntest) {
tempo = order(gower.dist(test[i, -p], train[-i,
-p]))[1:k]
classes[i] = moda(train[tempo, p])[1]
}
}
else {
for (i in 1:ntest) {
tempo = order(StatMatch::gower.dist(test[i, -p],
train[, -p]))[1:k]
classes[i] = moda(train[tempo, p])[1]
}
}
classes
}
please can someone explain for me the code?
I hope I have post the question in the correct form, please let me know if I have to move it to somewhere else.
Thank you very much for your time.
knngow function takes the last column of the train as the target attribute. Also p = dim(train)[2]) indicates your column number.
Column p (the last column of your training data) is not used for calculating Gower dist. It is only taken into account when it comes to predict the class label of test samples.

Resources