Mlrose TSPOpt Genetic Algorithm own cost function - algorithm

I want to program my own cost function for my own TSP problem. I do not want to use the mlrose one, because I want to optimize real coords with time.
First of all, I created a coords_List which looks like this: [(49.321,8.213),[50.321,9.124]...)
Then I created my own fitness function which accepts the guess array and returns a float.
fitnessF = mlrose.CustomFitness(coords_list)
Now I set up mlRose:
problem_fit = mlrose.TSPOpt(length = len(coords_list),fitness_fn =fitnessF, maximize=False)
best_state, best_fitness = mlrose.genetic_alg(problem_fit, random_state = 2)
This returns:
Exception: fitness_fn must have problem type 'tsp'.
Now I set up the code like this:
fitnessF = mlrose.TravellingSales(check_fitness)
Now it will return:
object of type 'function' has no len()
Thanks in advance
Ps: I would also be ready to share my notebook over Email

I could figure out where the problem was. It is right that I have to define my custom fitness function, but for TSP I have to add the problem type:
fitnessF = mlrose.CustomFitness(coords_list,"tsp")
Now it will work.

Related

For/in probem. What is the difference between object.variable and object[variable]?

Why can we use a code like this:
let student = {name:"John", surname:"Doe", index:386754};
let text = "";
let x;
for (x in student) {
text += student[x] + " "; }
And it would preview: John Doe 386754.
But when I formulated it like this:
let student = {name:"John", surname:"Doe", index:386754};
let text = "";
let x;
for (x in student) {
text += student.x + " "; }
, it returnes: undefined undefined undefined.
I suppose it's a pretty basic thing, but I had to ask because I can't find an appropriate answer.
Thank you ahead!
You should check out the data structures. You create a hash table using the variable student. So you can call inner variables (key-value pairs) by using brackets as you did student[name]. The second one student.name means you are calling a method of a class, which you don't have.
I recommend you to check what data structures exist, and how to use them.
The usage of object.something vs object[something] varies in different languages, and JavaScript is particularly loose in this aspect. The big difference here is that in object[something], something must reference a string corresponding to a key in object. So if you had something = 'myKey', and myKey was the name of a key in something (so object = {'myKey': 'value', ...}), you would get value. If you use object.something, you are asking JavaScript to look for a key in object with the name something. Even if you write something = 'myKey', using a dot means that you are looking within the scope of the object, making variables in your program effectively invisible.
So when you write student.x, you get undefined because there is no key 'x': 'value' in student for your program to find. Defining x as a key in your for loop does not change this. On the other hand, writing student[x] means that your program is finding the value x is referencing and plugging it in. When x is 'name', the program is actually looking for student['name'].
Hope that clarifies your issue. Good luck!

Ti Nspire: Convert solve(...) output to a callable Function

in order to calculate the inverse function of f(x) I defined following function:
inv(fx):=exp▶list(solve(fx=y,x),x)
which output is:
inv(x^(2)) {piecewise(−√(y),y≥0),piecewise(√(y),y≥0)}
So that part works already, but how can I use this result as a callable function i(y)?
Thanks for your help
Outside of your program, you can turn the result into function i(y) with:
i(y):=piecewise(-√(y),y≥0,√(y),y≥0)
I do not have a CAS, so your results may differ, but, because the function can only return one value, it would only return (and display in the graph) the first value, in this case, -√(y). If you want to display on the graph or get the values of both, you would be better off creating two separate functions (-√(y), and √(y)). Hope this helps you "use the result as a callable function."

Algorithm for visiting nodes only once

Let's say I have an array of N elements. I call a recursive function somehow like this: (no specific language here, just pseudocode)
recursive(myArray){
// do something awesome and provide base case etc
// also get mySecondArray based on myArray
for(i=0;i<mySecondArray.length;i++){
recursive(mySecondArray[i];
}
}
As you can see I need to call this function on every element of another array created inside based on some conditions and other functions called on myArray.
The problem I am having is that mySecondArray always has some of the elements that were already in myArray. I do not want to call recursion again on those elements.
Q: What would be the best algorithm approach to solve this?
If you need more info just let me know (I didn't get into details since it gets more complicated)
Thanks
You can have a hashmap/set/dictionary/whatever-you-call-it to look up the elements.
Python solution:
def recursive(myArray, mySet = None):
if mySet is None:
mySet = { myArray }
else:
mySet.add(myArray)
for mySecondArray in myArray:
if mySecondArray not in mySet:
recursive(myArray, mySet)
By the way writing recursive functions like that is a very bad idea in general. You should use a single function and a stack of the arguments if possible.
P.S.: Your code was incomplete by the way but the idea is the same.

Order $each by name

I am trying to figure why my ajax $each alters the way my list of names gets printed?
I have an json string like this:
[{"name":"Adam","len":1,"cid":2},{"name":"Bo","len":1,"cid":1},{"name":"Bob","len":1,"cid":3},{"name":"Chris","len":1,"cid":7},{"name":"James","len":1,"cid":5},{"name":"Michael","len":1,"cid":6},{"name":"Nick","len":1,"cid":4},{"name":"OJ","len":1,"cid":8}]
Here all the names are sorted in alphabetic order, but when getting them out they are sorted by "cid"? Why, and how can I change this?
Here is my jQuery:
var names = {};
$.getJSON('http://mypage.com/json/names.php', function(data){
$.each(data.courses, function (k, vali) {
names[vali.cid] = vali.name;
});
});
I guess its because "names[vali.cid]", but I need that part to stay that way. Can it still be done?
Hoping for help and thanks in advance :-.)
Ordering inside an object is not really defined or predictable when you iterate over it. I would suggest sorting the array based on an internal property:
var names = [];
$.getJSON('http://mypage.com/json/names.php', function(data){
$.each(data.courses, function (k, vali) {
names.push({name: vali.name, cid: vali.cid});
});
names.sort(function(a, b) {
return a.name.localeCompare(b.name);
});
});
Now you have an array that is ordered and you can iterate over it in a predictable order as well.
There is no "ajax $each" - you probably mean the jQuery function.
With "when getting them out" I presume you mean something like console.debug(names) after your $each call
Objects aren't ordered in javascript per definition, so there is no more order in your variable "names". Still, most javascript implementations today (and all the ones probably important to you - the ones used in the most used browsers) employ a stable order in objects which normally depends on the order you insert stuff.
All this said, there can probably be 3 reasons you're not getting what you're expecting:
Try console.debug(data) and see what you get - the order as you want it?
As you don't explicitly state how you debug your stuff, the problem could be in the way you output and not the data is stored. Here too try console.debug(names).
You're using a function which dereferences on expection, like console.*. This means if you console.debug() an object, the displayed values will depend on the moment you unfold the displayed tree in your browser, not when the line was called!

Why/How to use passed constants in function?

I've seen classes where constants are passed to methods, I guess its done to define some kind of setting in that function. I cant find it anywhere now to try to find out the logic, so I though I could ask here. How and why do you use this concept and where can I find more information about it?
The example below is written in PHP, but any language that handles constants would do I guess..
// Declaring class
class ExampleClass{
const EXAMPLE_CONST_1 = 0;
const EXAMPLE_CONST_2 = 1;
function example_method($constant(?)){
if($constant == ExampleClass::EXAMPLE_CONST_1)
// do this
else if($constant == ExampleClass::EXAMPLE_CONST_2)
// do that
}
}
// Using class
$inst = new ExampleClass();
$inst->example_method(ExampleClass::EXAMPLE_CONST_1);
To me its more clear to pass "ExampleClass::EXAMPLE_CONST_1" than to just pass "1", but it's that the only reason to pass constant?
Simply passing 1 doesn't say much. By having a constant you can have a description about the settings in the name.
example:
constant RAIN = 1;
method setWeather(RAIN);
Atleast that's how and why I use it.
It is always a good idea to avoid literals being passed around. By assigning a name, anyone reading your code has a chance to understand what that value means - a number has no meaning. It might also help you maintaining your code: If for some requirement the value has to be changed, you can easily do it in one place, instead of checking each and every value occurrence.

Resources