How can I optimize this pile of if/then statements?

Discussion in 'Programmer's Corner' started by strantor, Nov 6, 2014.

  1. strantor

    Thread Starter AAC Fanatic!

    Oct 3, 2010
    4,302
    1,988
    This is copied from plctalk.net, and it is in reference to an Omron PLC program I am writing. I know only a few people here are PLC-aware, but this is textual programming (IEC 61131-3 Structured Text) that should look familiar or at least intelligible to most of you, so maybe you can help me out. The problem is that, as it is written, this function block consumes 989 available steps, and I call on it 4 times in the main program, and I have only 6100 steps total allowable; so this function block *4 leaves me with very little room for the rest of my program.
     
  2. mitko89

    Member

    Sep 20, 2012
    123
    19
    Generally if you have statements that follow a pattern you can try to form an expression for a switch statement. The other option is to permorm checks into a for or a while statement (and again use breaks).
     
  3. WBahn

    Moderator

    Mar 31, 2012
    17,771
    4,804
    How well does a PLC handle array data? If you could define a parallel array that contains the corner points of your calibration curve, then it should be a simple matter of stepping up through the first array to determine the appropriate index and then computing the slope and intercepts in a single part of lines and then apply them. You could also precompute the slopes and intercepts once and store those in the array and then just use them. An even better way might be to store the X breakpoints and the incremental slopes in order to cut down on the amount of data stored.

    Here's a simple example.

    X is my desired output (in %) and Y is the output (in V, let's say) I need to command to achieve it.

    X Y
    -100.0 -12.0
    -50.0 1.3
    -0.1 3.1
    0.1 4.6
    50.0 7.9
    100.0 15.0


    As you can see, this is highly non-linear, is not centered, and has a significant dead band.

    Let's say that you want an output of -11.4%. First you identify that this is more than -50% but less than -0.1%, so you know you are working between these two end points.:

    -50.0|1.3
    -0.1|3.1

    Now, you know that you are 40% points higher than the start of this region (-11.4% - -50.0%) = 38.6% and you know that, in this region, the slope from the first point to the second point is

    slope = (3.1 V-1.3 V)/(-0.1% - -50.0%) = 36.072 mV/%

    So your commanded output needs to be what it is at the beginning of the segment, 1.3 V, and the amount it needs to climb the slop from there, (36.072 mV/%)(38.6%) = 1.392 V, for a total commanded output of 2.692 V.

    So how to capture this efficiently in a table look up? Simple, preprocess the slopes to give you a tables that looks like this:

    X Vo m
    -100.0 -12.0 0.266000
    -50.0 1.3 0.036072
    -0.1 3.1 7.5
    0.1 4.6 0.067347
    50.0 7.9 0.142000
    100.0 15.0 0.000000


    Now your code is pretty straight-forward (pseudocode using C-like syntax):

    Code (Text):
    1.  
    2. #define X_MIN (-100.0)
    3. #define X_MAX (100.0)
    4.  
    5. // Define Lookup Table
    6. #define LOOKUPS (6) // Number of entries in table
    7. double lookup_x[LOOKUPS] = {-100.0, -50.0, -0.1, 0.1, 50.0, 100.0};
    8. double lookup_vo[LOOKUPS] = {-12.0, 1.3, 3.1, 4.6, 7.9, 15.0};
    9. double lookup_vm[LOOKUPS] = {0.266000, 0.036072, 7.5, 0.067347, 0.142000, 0.000000};
    10.  
    11. x = whatever; // Code to determine the desired output
    12.  
    13. if (x < X_MIN) x = X_MIN;
    14. if (x > X_MAX) x = X_MAX;
    15.  
    16. // Find the appropriate index
    17. index = 1;
    18. while ( (index < LOOKUPS) && (x > lookup_x[index]) )
    19.    index++;
    20. index--;
    21.  
    22. v = lookup_vo[index] + (x - lookup_x[index])*lookup_m[index];
    23.  
    24.  
     
    strantor likes this.
  4. strantor

    Thread Starter AAC Fanatic!

    Oct 3, 2010
    4,302
    1,988
    Thank you for that very informative and detailed reply WBahn, and I apologize for taking so long to reply; I wanted to wait until I had something intelligent to say. Your input has been very helpful and led me on a quest to better understand arrays and loops. Unfortunately the array capabilities of my software are a bit crippled; I cannot specify an input as an array; only internal variables can be arrays - so I have to copy all my endpoints data from an input to the array, which adds more steps and has a diminished effect on optimizing the code. Also, I can find no way to specify the array as you show in one step ("double lookup_x[LOOKUPS] = {-100.0, -50.0, -0.1, 0.1, 50.0, 100.0};"); Apparently I must treat every element of the array as its own entity and issue a separate command to write to it. Also the documentation for my software states that it "only supports one-dimensional arrays" - I'm not quite sure what that means, but I think it means that it is not conducive to establishing a "table". If I'm right about that, and if I'm as clever as I think I am, I think I have gotten around that by using 2 different arrays with corresponding integers so I need only all one integer and reference both arrays with it. Please see below and let me know if there's any more tree I should be barking up.

    From plctalk.net:

     
  5. NorthGuy

    Active Member

    Jun 28, 2014
    604
    121
    I don't understand why you use PLC. It is enoumously expensive compare to a microcontroller, very bulky, and is extremely difficult to program.
     
  6. WBahn

    Moderator

    Mar 31, 2012
    17,771
    4,804
    As I presented things, there are three one-dimensional arrays. Since they are intended to be used by having the same index refer into each array, they are known as "parallel arrays", which is basically a means of effectively getting a NxM two-dimensional array using N, 1xM one-dimensional arrays.
     
    strantor likes this.
  7. strantor

    Thread Starter AAC Fanatic!

    Oct 3, 2010
    4,302
    1,988
    Yes I suppose I made that sound as if I had invented the concept, right after you had clearly illustrated it. I was just reveling in my new-found understanding of it. Thank you again for the help.
     
  8. strantor

    Thread Starter AAC Fanatic!

    Oct 3, 2010
    4,302
    1,988
    How can one know the best tool without knowing the application? I need a PLC because:
    • I need to interface with common industrial sensors, 24VDC and 120VAC digital I/O, and 0-10V and 4-20mA analog I/O.
    • I need to interface with common industrial communications bus/protocols; DeviceNET, J1939 CANbus, and EthernetI/P
    • I do not have the resources to design and manufacture circuits to support the above interfaces, or power supply, or any circuits at all.
    • Even if I did have the above manufacture capability, I do not have the time or money to submit my microcontroller-based design to all the rigorous testing and global certification required of devices used in my realm (IEC, NEMA, JIS, UL, NK, LR, EC, ISO, et. al.).
    • Even if I did have the time and money for the testing and certification above, I don't want the finger pointed at me in the event of a hardware failure.
    • I need the flexibility with respect to interfaces that is provided by a PLC; swap out a Pulse I/O module for an analog I/O module, add 5 new digital I/O modules, add a second DeviceNET node, add thermocouple & RTD modules to the remote I/O rack and have them be accessible over DeviceNET, etc.
    • I Like PLCs

      Money is not high on the list of priorities, nor is space. The only thing that you mention that is really applicable is "extremely difficult to program" - and I would argue that it isn't extremely difficult; in fact in most cases, it's fairly idiot proof. It just takes a bigger idiot (like me) to muck it up. In my case I would say it's only moderately difficult.
     
    panic mode likes this.
  9. NorthGuy

    Active Member

    Jun 28, 2014
    604
    121
    Microcontrollers can do all that. There's one inside your PLC. Count in all the time you spent developing programs for PLCs, all the money you spend on purchasing PLCs and modules. This would be more than enough to print and assemble the corresponding number of PCB boards. And I'm 100% sure that if you go with microcntrollers, after some time, you'll like them more :)
     
  10. WBahn

    Moderator

    Mar 31, 2012
    17,771
    4,804
    Oh, I wasn't complaining about that, just wanted you to see that they were the same thing and also add a bit of vernacular to your vocabulary.

    And, to some degree, you probably did reinvent the concept -- that a head slap might be warranted shortly thereafter doesn't necessarily diminish the achievement.
     
    strantor likes this.
  11. WBahn

    Moderator

    Mar 31, 2012
    17,771
    4,804
    Don't forget to count in the time getting the code and hardware compatible with all of the needed protocols. Don't forget to count in all the time and cost of getting all of the necessary certification testing performed and past. Don't forget to count in the cost of getting the type of huge liability insurance policy that should be carried.
     
  12. NorthGuy

    Active Member

    Jun 28, 2014
    604
    121
    The standard protocols are common and have been done with microcontrollers many times. You don't need to spend much time/effort on this. I'm not an expert in certifications, and I might be wrong, but I don't think using PLCs somehow alleviates you of any legal liabilities.
     
  13. WBahn

    Moderator

    Mar 31, 2012
    17,771
    4,804
    I gives you quite a bit of protection, actually. If the hardware fails then you can point the lawyers at the company that designed and manufactured the hardware (who will typically have deeper pockets than you, anyway). But if you ARE the company that designed and manufactured the hardware.... On top of that, there are many, many projects for which the moment you mention that you plan to use custom, uncertified hardware they will simply tell you not to bother submitting your bid.
     
  14. NorthGuy

    Active Member

    Jun 28, 2014
    604
    121
    That's how big companies stall the progress and maintain their status quo :)
     
  15. strantor

    Thread Starter AAC Fanatic!

    Oct 3, 2010
    4,302
    1,988
    I'm not uninitiated to microcontrollers (I've played with atmels and pics, and Like you said, there's one in the PLC) , and I really don't understand your position. From my side of the table the discussion looks like this:
    me: "I need some help tracing out the wires to truck's brake lights."
    you: "why are you using a truck? They're terribly inefficient, over priced, gaudy looking, and have smelly exhaust. You should use an internal combustion engine."
    me: "I would use an internal combusion engine, but then I would have to design a truck up around it, and I don't have time for that, nor do I have time to submit my reinvented wheel to the department of transportation for a certificate of roadworthiness."
    you:"well an engine can do anything that a truck can do; in fact, there's an engine in your truck."
    me:" yes, you're right, there is. I know what an engine is and have worked on them from time to time, and I really don't understand your position. From my side of the table the discussion looks like this: ... LOOP"
     
    panic mode and joeyd999 like this.
  16. panic mode

    Senior Member

    Oct 10, 2011
    1,321
    304
    I love your reply...

    btw. why are you stuck at 6k steps? CJ2M family has range of CPUs supporting up to 60k steps. simply replacing CPU will keep everything else same and you can get more elbow room for rest of the code...
     
  17. NorthGuy

    Active Member

    Jun 28, 2014
    604
    121
    Not like that. The task you want to accomplish can be done in few lines of code on anything that can be programmed in a normal way. You cannot accomplish it with a tool at hands and yet you believe that your tool is the best for the task.

    It's like I would see you opening a can of tuna with a mauler and I would mention that a can opener would work better, but you'd tell me back: "I know all about can openers, but I prefer to do it with mauler, and I also need to stand only on my left leg to do this. I love maulers. You see, it's already difficult as it is, and your can opener suggestions don't help me a bit".

    Yes, by all means, continue ...
     
  18. NorthGuy

    Active Member

    Jun 28, 2014
    604
    121
    I'll try to suggest something useful.

    You can plot your curve in Excel, or other similar tool, and fit it with a polynomial curve. For example, the table from post #2 can be approximated as

    y = 9E-06*x^3 - 0.0003*x^2 + 0.0431*x + 4.4673

    This looses some precision. If more precision is needed, you can break it into regions and do regions separately.

    Such calculalation should not be too hard on the PLC.
     
    strantor likes this.
  19. strantor

    Thread Starter AAC Fanatic!

    Oct 3, 2010
    4,302
    1,988
    Thank you for the value added post. That was my first instinct as well. I spent almost a whole day fussing around with excel and learning how to use the trend line. I even had a thread here about it. But I tabled that idea for the reason described below (quote from the linked thread):
     
  20. strantor

    Thread Starter AAC Fanatic!

    Oct 3, 2010
    4,302
    1,988
    Good point, [NorthGuy, avert your eyes ;) ] I may look into handing over several more thousand dollars to "The Man" to upgrade my CPU if I am unable to obtain acceptable results by optimizing my code.
     
Loading...