Microsoft Solver Foundation - Results Are Not Good Enough ( Stock Portfolio Optimization ) - optimization

I'm trying to code a markowitz optimization class in C# but the optimization results not good enough. Portfolio weights are differing from matlab's and excel's solutions by average 0.2%. I checked my covariance matrix calculation and the other calculations and find that they are true. Is there a way to calibrate model's tolerance or something other for getting better results? There is my code.
public List<OptimalWeight> CalcOptimalWeights(bool isNegativeAllowed,string method)
{
List<OptimalWeight> weightsResult = new List<OptimalWeight>();
List<List<CovarItem>> covariances = new List<List<CovarItem>>();
covariances = CalcCovariances();
int n = this.AssetReturnList.Count();
SolverContext solver = SolverContext.GetContext();
Model model = solver.CreateModel();
if(isNegativeAllowed == false)
{
Decision[] weights = new Decision[n];
for (int i = 0; i < n; i++)
{
model.AddDecision(weights[i] = new Decision(Domain.RealNonnegative, null));
}
model.AddConstraint("SumWeights", Model.Sum(weights) == 1);
if(this.Constraints.Count() == 0)
{
if (method == "MinVar")
{
Term portVar = 0.0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
portVar += weights[j] * covariances[j][i].Covar * weights[i];
}
}
model.AddGoal("MinVarPort", GoalKind.Minimize, portVar);
Solution solution = solver.Solve();
var report = solution.GetReport();
var decisions = solution.Decisions;
List<double> d = decisions.Select(x => x.GetDouble()).ToList();
for(int i = 0 ; i < n; i++)
{
weightsResult.Add(new OptimalWeight {AssetId = AssetReturnList[i].AssetId,
Symbol = AssetReturnList[i].Symbol,
Weight = d[i] });
}
double pvar = solution.Goals.First().ToDouble();
}
}
}
return weightsResult;
}

Related

How to access the values of a dictionary property in a grid using Ocean for Petrel?

I'm tring to access the values of a dictionary property in a grid,such as Fluvial facies or lithologies etc.I have read the coursebook and help docs, but didn't find anything relevant.The coursebook only has examples of creating properties, but not accessing properties.Below is the code I tried:
Grid grid = arguments.Input_Grid;
if (grid == null)
{
PetrelLogger.ErrorStatus("HelloGrid: Arguments cannot be empty.");
return;
}
Index3 currentCell = new Index3();
int maxI = grid.NumCellsIJK.I;
int maxJ = grid.NumCellsIJK.J;
int maxK = grid.NumCellsIJK.K;
for (int i = 0; i < maxI; i++)
{
for (int j = 0; j < maxJ; j++)
{
for (int k = 0; k < maxK; k++)
{
currentCell.I = i; currentCell.J = j; currentCell.K = k;
if (grid.IsCellDefined(currentCell) && grid.HasCellVolume(currentCell))
{
//DictionaryProperty p = ???
//int val = p[currentCell] ???
}
}
}
}
You need to use the "FastDictionaryPropertyIndexer" or "FastPropertyIndexer" for regular properties.
foreach (var dictProp in grid.DictionaryProperties)
{
int numCellsI = dictProp.NumCellsIJK[0];
int numCellsJ = dictProp.NumCellsIJK[1];
int numCellsK = dictProp.NumCellsIJK[2];
float[] values = new float[dictProp.NumCells];
var dpsa = dictProp.SpecializedAccess;
using (var fdpi = dpsa.OpenFastDictionaryPropertyIndexer())
{
int index = 0;
for (int k = 0; k < numCellsK; k++)
{
for (int j = 0; j < numCellsJ; j++)
{
for (int i = 0; i < numCellsI; i++)
{
values[index] = fdpi[i, j, k];
index++;
}
}
}
}
}
You also need to be careful about the indexing since it varies by project. For instance, you may need to reverse the order of traversal in the J direction or you could end up with some strange results.

Dijkstras Algorithmn Vue

I am trying to implement dijkstras pathfinding algorithm in vue. I am following the psuedocode from https://medium.com/#nicholas.w.swift/easy-dijkstras-pathfinding-324a51eeb0f. This is what I have come up with so far, however I am struggling to translate the psuedocode into vue js. How would I be able to check every node and pop the visited nodes off the list?
Dijkstra() {
this.unexploredset = [];
for (let i = 0; i < 16; i++){
for (let j = 0; j < 16; j++){
this.nodes[i][j].position = '∞';
this.nodes[i][j].distance = '∞';
if(this.nodes[i][j].hasWall == false){
this.unexploredset.push(this.nodes[i][j])
}
}
}
let current = this.nodes[3][4];
let goal = this.nodes[14][14];
for(let i = 0; i < 255; i++) {
for (let k = 0; k < 4; k++) {
if (current.distance <= current.neighbours[k].distance && current.unvisited == true)
{
current.unvisited = false;
let temp = current.neighbours[k];
current = temp
this.unexploredset.pop(current);
current = temp
if (current == goal)
{
console.log("found");
break
}
console.log(this.unexploredset.length)
}
}
}
}

combine assimp bone data with other vertex data

My problem is that I am trying to load in joint/bone data from an fbx file in Direct X c++ using Assimp, but I want to store the eights and indices inside the same vertex struct that I store position, uv, etc.
I can make a loop for every vertex, but I also want to make a loop over each bone.
That means I can't have both the joint data and the other data in the same loop.
Should I create multilpe vertec objects then combine them afterwards?
I also am not sure how to find the bone ID and the weight for each vertex, I am counting on 4 per bone, but maybe I should not have that last loop at all?
Im not sure how to set it up.
I would appreciate some help, thank you very much.
for (UINT k = 0; k < currentMesh->mNumBones; k++)
{
aiBone* bone = currentMesh->mBones[k];
for (UINT m = 0; m < bone->mNumWeights; m++)
{
aiVertexWeight weight = bone->mWeights[m];
for (UINT n = 0; n < 4; n++)
{
//if
}
}
}
//////////////////////////////////////////////
for (UINT k = 0; k < currentMesh->mNumVertices; k++)
{
Vertex vert;
vert.position.x = currentMesh->mVertices[k].x;
vert.position.y = currentMesh->mVertices[k].y;
vert.position.z = currentMesh->mVertices[k].z;
vert.TexCoord.x = currentMesh->mTextureCoords[0][k].x;
vert.TexCoord.y = currentMesh->mTextureCoords[0][k].y;
vert.normal.x = currentMesh->mNormals[k].x;
vert.normal.y = currentMesh->mNormals[k].y;
vert.normal.z = currentMesh->mNormals[k].z;
vertexVector.push_back(vert);
}
for (UINT k = 0; k < currentMesh->mNumBones; k++)
{
aiBone* bone = currentMesh->mBones[k];
for (UINT m = 0; m < bone->mNumWeights; m++)
{
aiVertexWeight weight = bone->mWeights[m];
if (vertexVector[weight.mVertexId].joints.x == 0)
{
vertexVector[weight.mVertexId].joints.x = k;
vertexVector[weight.mVertexId].weights.x = weight.mWeight;
}
else if (vertexVector[weight.mVertexId].joints.y == 0)
{
vertexVector[weight.mVertexId].joints.y = k;
vertexVector[weight.mVertexId].weights.y = weight.mWeight;
}
else if (vertexVector[weight.mVertexId].joints.z == 0)
{
vertexVector[weight.mVertexId].joints.z = k;
vertexVector[weight.mVertexId].weights.z = weight.mWeight;
}
else if (vertexVector[weight.mVertexId].joints.w == 0)
{
vertexVector[weight.mVertexId].joints.w = k;
vertexVector[weight.mVertexId].weights.w = weight.mWeight;
}
}
}
I accessed the same structure I already have and added the stuff afterwards.

Zedgraph - Change X-Axis from points to frequency

i have a working program where i can add an array to a Zedgraph and show this in a form.
Now i only want to change the display of the x-axis from points (0..400) to frequency (9e3..6e9 Hz).
Here are my currently working functions:
public void AddGraph(double[] Values, string LegendName)
{
int i = 0;
PointPairList list = new PointPairList();
for (i = 0; i < Values.Length; i++)
{
list.Add(i, Values[i]);
}
if (i > MaxXAxis)
MaxXAxis = i;
SList.Add(list);
SListColor.Add(Color.Black);
}
SListName.Add(LegendName);
}
public void ShowDiagram(string Title, string XAxisName, string YAxisName,
int Timeout_ms)
{
ZedGraph.ZedGraphControl zgc = new ZedGraphControl();
GraphPane myPane = zgc.GraphPane;
LineItem myCurve = null;
// Set the titles and axis labels
myPane.Title.Text = Title;
myPane.XAxis.Title.Text = XAxisName;
myPane.YAxis.Title.Text = YAxisName;
for (int i = 0; i < SList.Count(); i++)
{
myCurve = myPane.AddCurve(SListName[i], SList[i], SListColor[i],
SymbolType.None);
myCurve.Line.Width = 2;
}
// Add gridlines to the plot, and make them gray
myPane.XAxis.MinorGrid.IsVisible = true;
myPane.YAxis.MinorGrid.IsVisible = true;
myPane.XAxis.MinorGrid.Color = Color.LightGray;
myPane.YAxis.MinorGrid.Color = Color.LightGray;
myPane.XAxis.MinorGrid.DashOff = 0;
myPane.YAxis.MinorGrid.DashOff = 0;
myPane.XAxis.MajorGrid.IsVisible = true;
myPane.YAxis.MajorGrid.IsVisible = true;
myPane.XAxis.MajorGrid.Color = Color.Gray;
myPane.YAxis.MajorGrid.Color = Color.Gray;
myPane.XAxis.MajorGrid.DashOff = 0;
myPane.YAxis.MajorGrid.DashOff = 0;
// Move Legend to bottom
myPane.Legend.Position = LegendPos.Bottom;
zgc.AxisChange();
myPane.XAxis.Scale.Max = MaxXAxis;
zgc.Location = new Point(0, 0);
zgc.Size = new Size(panel_diagramm.ClientRectangle.Width, panel_diagramm.ClientRectangle.Height);
panel_diagramm.Controls.Add(zgc);
}
How can i change the above two functions that they display the frequency in the x-axis?
I already tried to change the AddGraph-function to pass the needed parameters and to calculate the list to have the correct values. But what then...?
public void AddGraph_Frequency(int **Points**, double **StartFrequency**,
double **StopFrequency**, double[] Values, string GraphColor, string LegendName)
{
...
double frequency = StartFrequency; //der erste Punkt
double Intervall = (StopFrequency - StartFrequency) / Points;
for (i = 0; i < Points; i++)
{
list.Add(frequency, Values[i]);
frequency = frequency + Intervall;
}
....
}
Thanks for any help
best regards
Solved.
Missing was:
myPane.XAxis.Scale.Max = Stopfrequency;
myPane.XAxis.Scale.Min = Startfrequency;

Sum up elements in matrix arraylist

I am trying to sum up each arraylist within an arraylist. I am assuming you use the get method. but I am not sure how to do this exactly. This is what I have so far. As indicated by the arrows is were I am trying to add up the arraylist before it starts on the new arraylist. Any ideas?????
public void sparseCountTimer(ArrayList arraylist)
{
double totalRowsCount = 0.0;
long totalTime = 0;
for (int x = 0; x < iteration; x++)
{
long startTime2 = 0,
estimatedTime2 = 0;
double rowTotal = 0.0,
lastRowTotal = 0.0;
for( int i = 0; i < matrixDimension; ++i)
{
if (lastRowTotal < rowTotal)
{
lastRowTotal = rowTotal;
startTime2 = System.nanoTime();
}
rowTotal = 0.0;
for (int j = 0; j < matrixDimension; ++j)
{
>>>>>>>>> rowTotal += arraylist.get(j).get(i); <<<<<<<<<<<<<<
}
estimatedTime2 = System.nanoTime() - startTime2;
}
totalRowsCount += lastRowTotal;
totalTime += estimatedTime2;
}
}