Does anyone know how to access specific outputs of the Dymola built-in function getExperiment();?
Unfortunately it only returns the Real scalar StartTime.
The function seems to be defined as follows:
function getExperiment "Get current experiment setting"
output Real StartTime := 0.0 "Start of simulation";
output Real StopTime := 1.0 "End of simulation";
output Integer NumberOfIntervals := 0 "Number of output points";
output Real OutputInterval := 0.0 "Distance between output points";
output String Algorithm := "" "Integration method";
output Real Tolerance := 0.0001 "Tolerance of integration";
output Real FixedStepSize := 0.0 "Fixed step size for Euler";
end getExperiment;
My test model is:
model GetExpTest
Real staTime;
Real outInterval;
equation
(staTime,outInterval)=receiveInfo();
end GetExpTest;code here
With the function:
function receiveInfo
output Real startT;
output Real outputInterv;
algorithm
(startT,,,outputInterv,,,):=getExperiment();
end receiveInfo;
And the error message I get is:
Compiling and linking the model (Visual C++).
dsmodel.c
dsmodel.c(32) : error C2079: 'dummy_mult_' uses undefined struct 'getExperiment_struct'
dsmodel.c(32) : warning C4013: 'getExperiment' undefined; assuming extern returning int
dsmodel.c(33) : error C2224: left of '.StartTime0_0_0member' must have struct/union type
dsmodel.c(34) : error C2224: left of '.OutputInterval0_0_0member' must have struct/union type
Error generating Dymosim.
Thank you in Advance for help!
If I do: getExperiment(), the following is returned:
= 0.0, 1.0, 500, 0.0, "dassl", 0.0001, 0.0
So you can access the values using a regular assignment taking multiple outputs. For example:
(StartTime,,NumberOfIntervals) := getExperiment()
Which returns:
Declaring variable: Real StartTime ;
Declaring variable: Integer NumberOfIntervals ;
StartTime
= 0.0
NumberOfIntervals
= 500
Related
I follow a python course on finance about portfolio theory. I have to create a function with a nested function in it.
My problem is I have a error message of "neg_sharpe_ratio() missing 2 required positional arguments: 'er' and 'cov'" whereas to my mind 'er' and 'cov' are already defined in my function msr below. So I understand how they are missing.
from scipy.optimize import minimize
def msr(riskfree_rate, er, cov):
n= er.shape[0]
init_guess= np.repeat(1/n, n)
bounds=((0.00, 1.0),)*n
weights_sum_to_1 = {
'type' :'eq' , #
'fun' : lambda weights: np.sum(weights) - 1 ##
}
def neg_sharpe_ratio(weights,riskfree_rate, er, cov):
r = erk.portfolio_return(weights, er)
vol = erk.portfolio_vol(weights,cov)
return -(r-riskfree_rate)/vol
results = minimize( neg_sharpe_ratio, init_guess,
args=(cov,), method="SLSQP",
options={'disp': False},
constraints=( weights_sum_to_1),
bounds=bounds
)
return results.x
TypeError: neg_sharpe_ratio() missing 2 required positional arguments: 'er' and 'cov'
The function neg_sharpe_ratio is able to reference any of the variables passed in and made by the function msr without needing those same variables passed into it itself. Therefore you should be able to remove the paramters riskfree_rate, er, and cov from the neq_sharpe_ratio function definition and have it work, as those variables are passed into its parent function, leaving you with:
def neg_sharpe_ratio(weights):
For those who might be interested, I find my mistake..
Indeed, I forgot to define correctly the arguments of my function neg_share_ratio in my function minimize.
Here is the code amended:
from scipy.optimize import minimize
def msr(riskfree_rate, er, cov):
n= er.shape[0]
init_guess= np.repeat(1/n, n)
bounds=((0.00, 1.0),)*n
weights_sum_to_1 = {
'type' :'eq' , #
'fun' : lambda weights: np.sum(weights) - 1 ##
}
def neg_sharpe_ratio(weights,riskfree_rate, er, cov):
r = erk.portfolio_return(weights, er)
vol = erk.portfolio_vol(weights,cov)
return -(r-riskfree_rate)/vol
results = minimize( neg_sharpe_ratio, init_guess,
args=(weights,riskfree_rate,er,cov), method="SLSQP",
options={'disp': False},
constraints=( weights_sum_to_1),
bounds=bounds
)
return results.x code here
I've got a little MatLab script, which I try to understand. It doesn't do very much. It only reads a text from a file and encode and decode it with the Huffman-functions.
But it throws an error while decoding:
"error: out of memory or dimension too large for Octave's index type
error: called from huffmandeco>dict2tree at line 95 column 19"
I don't know why, because I debugged it and don't see a large index type.
I added the part which calculates p from the input text.
%text is a random input text file in ASCII
%calculate the relative frequency of every Symbol
for i=0:127
nlet=length(find(text==i));
p(i+1)=nlet/length(text);
end
symb = 0:127;
dict = huffmandict(symb,p); % Create dictionary
compdata = huffmanenco(fdata,dict); % Encode the data
dsig = huffmandeco(compdata,dict); % Decode the Huffman code
I can oly use octave instead of MatLab. I don't know, if there is an unexpected error. I use the Octave Version 6.2.0 on Win10. I tried the version for large data, it didn't change anything.
Maybe anyone knows the error in this context?
EDIT:
I debugged the code again. In the function huffmandeco I found the following function:
function tree = dict2tree (dict)
L = length (dict);
lengths = zeros (1, L);
## the depth of the tree is limited by the maximum word length.
for i = 1:L
lengths(i) = length (dict{i});
endfor
m = max (lengths);
tree = zeros (1, 2^(m+1)-1)-1;
for i = 1:L
pointer = 1;
word = dict{i};
for bit = word
pointer = 2 * pointer + bit;
endfor
tree(pointer) = i;
endfor
endfunction
The maximum length m in this case is 82. So the function calculates:
tree = zeros (1, 2^(82+1)-1)-1.
So it's obvious why the error called a too large index type.
But there must be a solution or another error, because the code is tested before.
I haven't weeded through the code enough to know why yet, but huffmandict is not ignoring zero-probability symbols the way it claims to. Nor have I been able to find a bug report on Savannah, but again I haven't searched thoroughly.
A workaround is to limit the symbol list and their probabilities to only the symbols that actually occur. Using containers.Map would be ideal, but in Octave you can do that with a couple of the outputs from unique:
% Create a symbol table of the unique characters in the input string
% and the indices into the table for each character in the string.
[symbols, ~, inds] = unique(textstr);
inds = inds.'; % just make it easier to read
For the string
textstr = 'Random String Input.';
the result is:
>> symbols
symbols = .IRSadgimnoprtu
>> inds
inds =
Columns 1 through 19:
4 6 11 7 12 10 1 5 15 14 9 11 8 1 3 11 13 16 15
Column 20:
2
So the first symbol in the input string is symbols(4), the second is symbols(6), and so on.
From there, you just use symbols and inds to create the dictionary and encode/decode the signal. Here's a quick demo script:
textstr = 'Random String Input.';
fprintf("Starting string: %s\n", textstr);
% Create a symbol table of the unique characters in the input string
% and the indices into the table for each character in the string.
[symbols, ~, inds] = unique(textstr);
inds = inds.'; % just make it easier to read
% Calculate the frequency of each symbol in table
% max(inds) == numel(symbols)
p = histc(inds, 1:max(inds))/numel(inds);
dict = huffmandict(symbols, p);
compdata = huffmanenco(inds, dict);
dsig = huffmandeco(compdata, dict);
fprintf("Decoded string: %s\n", symbols(dsig));
And the output:
Starting string: Random String Input.
Decoded string: Random String Input.
To encode strings other than the original input string, you would have to map the characters to symbol indices (ensuring that all symbols in the string are actually present in the symbol table, obviously):
>> [~, s_idx] = ismember('trogdor', symbols)
s_idx =
15 14 12 8 7 12 14
>> compdata = huffmanenco(s_idx, dict);
>> dsig = huffmandeco(compdata, dict);
>> fprintf("Decoded string: %s\n", symbols(dsig));
Decoded string: trogdor
I am trying to write a method which returns a new value. Following code is modified from here:
| stripChars |
stripChars := [ :string :chars |
str := string reject: [ :c | chars includes: c ].
str displayNl. "THIS WORKS."
^ str "THIS DOES NOT WORK."
].
newstr := stripChars
value: 'She was a soul stripper. She took my heart!'
value: 'aei'.
newstr displayNl.
Although above function creates new string and displays it, there is error in returning or receiving returned new string:
$ gst make_fn_ques.st
Sh ws soul strppr. Sh took my hrt!
Object: 'Sh ws soul strppr. Sh took my hrt!' error: return from a dead method context
SystemExceptions.BadReturn(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.BadReturn class(Exception class)>>signal (ExcHandling.st:151)
String(Object)>>badReturnError (Object.st:1389)
UndefinedObject>>executeStatements (make_fn_ques.st:10)
nil
Where is the problem and how can this be solved? Thanks for your help.
The
^ str
does not return from the block (stripChars), but from the enclosing method instead (non-local return).
Apparently GNU Smalltalk does not allow you to return from the script that you pass to gst in this way.
Just drop the ^, and keep only str as the last expression of the block. That will cause str to be the return value of the block.
{'PCCandidateDetails': {'BatchId': '456279',
'Candidate': 'Noori sahi ',
'CandidateId': '9124657',
'CenterName': 'K',
'ProjectName': 'PKKVY',
'QPName': 'Domestic Data Entry Operator(SSC/Q2212)',
'TrainingProviderName': 'OrionEdutechPrivateLimited'},
'PCTestScores': [{'MaxScore': 12,
'PCId': 'SRC/N3022_PC1',
'PCName': 'obtain sufficient information from the customer /client to understand the need and perform initial task',
'Percentage': 0,
'YourScore': 0},
{'MaxScore': 15,
'PCId': 'SRC/N3022_PC10',
'PCName': 'compares transcribed data, as displayed on a visual screen, document and corrects any errors with the source',
'Percentage': 0,
'YourScore': 0},
{'MaxScore': 5,
'PCId': 'SSC/N3022_PC11',
'PCName': 'obtain help or advice from specialist if the problem is outside his/her area of competence or experience',
'Percentage': 0,
'YourScore': 0}]}
I want to loop over this json object which I have got using web request.
import requests,ast
r = requests.get("some url")
data = r.text
data_dic = ast.literal_eval(data)
When I try to loop over the Json I am not able to fetch the expected output in key- Value pair. I want output like this
BatchId : 456279
Candidate : Noori sahi
CandidateId :9124657 ...
and so on. Below code is My approach but dictionary inside the list is causing problem in looping.
for i in data_dic:
for k,v in i.iteritems():
print k,v
What I'm getting as error is 'str' object has no attribute 'iteritems'. What is the right approach for looping this kind of data.
This works for your example (python 3.5.2) but i don't know if is the best approach (I mean, maybe there are some json parsing functions easier to use):
for v, k in itms.items():
if not isinstance(k, list):
for x, y in k.items():
print(x,':', y)
else:
for i in k:
for s, m in i.items():
print(s,':', m)
with the result:
CandidateId : 9124657
BatchId : 456279
QPName : Domestic Data Entry Operator(SSC/Q2212)
CenterName : K
ProjectName : PKKVY
Candidate : Noori sahi
TrainingProviderName : OrionEdutechPrivateLimited
Percentage : 0
PCName : obtain sufficient information from the customer /client to understand the need and perform initial task
MaxScore : 12
YourScore : 0
PCId : SRC/N3022_PC1
Percentage : 0
PCName : compares transcribed data, as displayed on a visual screen, document and corrects any errors with the source
MaxScore : 15
YourScore : 0
PCId : SRC/N3022_PC10
Percentage : 0
PCName : obtain help or advice from specialist if the problem is outside his/her area of competence or experience
MaxScore : 5
YourScore : 0
PCId : SSC/N3022_PC11
for python 2.7. only remove the parentheses from print
for v, k in itms.items():
if not isinstance(k, list):
for x, y in k.items():
print x,':', y
else:
for i in k:
for s, m in i.items():
print s,':', m
To get data use:
import json
data = json.loads(request.body)
print data['PCTestScores']
for values in data['PCTestScores']:
print values
print values['PCId']
print values['PCName']
print values['Percentage']
print values['MaxScore']
print values['YourScore']
I am interested in using the monotone spline, but I get an error when R tries to use it. I am using R 2.12.0, and the method 'monoH.FC' says that it has been supported since 2.8.0
Reproducible example (same result for more complicated (x,y) relationships)
x<-1:2
y<-1:2
spline(x,y,method="monoH.FC")
Error in spline(x, y, method = "monoH.FC") : invalid interpolation method
What I have tried
?spline returns:
...
Usage:
...
spline(x, y = NULL, n = 3*length(x), method = "fmm",
xmin = min(x), xmax = max(x), xout, ties = mean)
...
Arguments:
method: specifies the type of spline to be used. Possible values are
‘"fmm"’, ‘"natural"’, ‘"periodic"’ and ‘"monoH.FC"’.
...
But the spline function itself indicates that the 'monoH.FC' method is not supported:
...
method <- pmatch(method, c("periodic", "natural", "fmm"))
if (is.na(method))
stop("invalid interpolation method")
...
Question
How can I use method = 'monoH.FC' with spline?
Use splinefun; it supports method=monoH.FC.
The last example in ?spline shows you how to do it.
## An example of monotone interpolation
n <- 20
set.seed(11)
x. <- sort(runif(n)) ; y. <- cumsum(abs(rnorm(n)))
plot(x.,y.)
curve(splinefun(x.,y.)(x), add=TRUE, col=2, n=1001)
curve(splinefun(x.,y., method="mono")(x), add=TRUE, col=3, n=1001)
legend("topleft", paste("splinefun( \"", c("fmm", "monoH.CS"), "\" )", sep=''),
col=2:3, lty=1)