Extending MMpy objects

Yan 10 years ago in Scripting updated 10 years ago 0

We choose to use python as the scripting language in Micromine because of its flexibility. An interesting feature that I will talk about in this post is extending a Micromine python object.

Let's say you play with colours using the MMpy.Colour object, but you don't like the fact that you have to use the RGB colour space. You would like to use colour spaces like HSV or YIQ to represent your data, but it is not available yet ... What you can do is extend the MMpy.Colour object.

Let's start with something simple : a function HSV() that returns the hue, saturation and value corresponding to a RGB triplet. This is pretty easy, using the build-in colorsys python module, we can do something like:

import colorsys
def HSV(R,G,B):
  return colorsys.rgb_to_hsv(R,G,B)

Now, it would be nice to be able to call that from a MMpy.Colour object. This can be done the following way

import colorsys
def HSV(self):
  return colorsys.rgb_to_hsv(self.R,self.G,self,B)
MMpy.Colour.HSV = HSV

Let me explain that piece of code. We still import the colorsys module, this time the only argument in the function is self. This is because each time you are calling a member function, the first parameter is always going to be the object itself. So in that case self would be a MMpy.Colour object. 

Instead of using R,G,B values from the function's parameter, we use the one from the object. After that, we assign the HSV function to MMpy.Colour.HSV and 'voila', we can now use the HSV() function on any MMpy.Colour object:

col = MMpy.Colour(124,122,4)

This is still pretty basic, what could be really interesting is to populate a colorset using HSV value. If you record a colorset, you will get results that looks like:

DataGrid0.set_row(1, ["03.00",MMpy.Colour(121,100,25).serialise(),"3.00 to 5.27"])

A MMpy.Colour object is created, before being serialised to a string. In order to do something similar with HSV colorspace we could have

def CreateFromHSV(H,S,V):
  colour = MMpy.Colours()
  temp = colorsys.hsv_to_rgb(H,S,V)
  #Convert to integer: R,G,B are int in MMpy.Colour
  colour.R = int(temp[0])
  colour.G = int(temp[1])
  colour.B = int(temp[2])
  return colour
MMpy.Colour.CreateFromHSV = CreateFromHSV

You can see that this function doesn't take self as a first parameter, because we create the MMpy.Colour object inside the function before returning it at the end; this function act like a constructor.

Now, I can create a colorset using HSV:

DataGrid0.set_row(1, ["03.00",MMpy.Colour.CreateFromHSV(0,0.7,181).serialise(),"3.00 to 5.27"])

If we want to make everything clean, we can package our new function to an external module and import it before our scripts. I'll add my new module and a script that I recorded that load points using a HSV created colorset.

Image 90