Python Example - Getting Started

From SysCAD Documentation
Jump to navigation Jump to search

Navigation: User Guide -> COM Automation -> Python Automation Examples -> Python Example - Getting Started

Basic Usage: Opening, running, setting and getting tags

This basic example opens up the Demo Gold steady state ProBal project, looks at the amount of gold in the product, changes the feed composition tag, runs the project, then looks at the new value of gold in product.

 ## Example Automation Using python.
import sys
import time
try:
  import win32com.client as wc    ## PyWin32 COM Client
except:
  print ("Win32 python extensions not found")
  print ("Install pywin32:  https://pypi.org/project/pywin32/")
  sys.exit(1)
ver = 93     ## Recent versions of SysCAD use a different COM ID
 
ProgID = "SysCADSimulator.Application" if ver<93 else "SysCADSimulator93.Application"
 
 
SysCAD = wc.DispatchEx(ProgID)  ## Fire up SysCAD
build = SysCAD.VersionNumber(2) ## You can now query the build number
 
ScdDir = r'C:\SysCAD%d' % build
print ("Using Build", build, "Install Directory is ", ScdDir)
 
ScdPrj = r'\Examples\25 Gold\Demo Gold Project.spf\Project.spj'
#### If you use \ in file and directory strings use a raw string or escape \'s 
#### eg Prj = SysCAD.OpenProject('C:\\SysCADProjectFiles\\Sample.spf\\Project.spj')
####    Prj = SysCAD.OpenProject('C:/SysCADProjectFiles/Sample.spf/Project.spj')  ## also works
 
Prj = SysCAD.OpenProject(ScdDir+ScdPrj)  ## Open project 
 
Tags = Prj.Tags         
#### The tag naming was changed in the distributed examples for 138
goldFlow = "P_007.Qo.QM.Au(s) (oz/d)" if build==138 else "P_7.Qo.QM.Au(s) (oz/d)"
print ("Gold in product", end=" ")
print (Tags.TagValue(goldFlow))  ## Get a tag value

Solver = Prj.Solver
ProBal = Solver.ProBal
 
ProBal.Start()                        ## Start ProBal
while True:                           ## Wait until solved 
   print ("Solving...")                 
   time.sleep(.5)
   if ProBal.IsStopped:
       break
print ("Feed ppm in gold ore", Tags.TagValue("FEED_ppm_SET.TC[1].User.Value"))   ## Print another tag
print ("Changing value to 45 ppm")
Tags.SetTagValue("FEED_ppm_SET.TC[1].User.Value", 45)  ## Change tag value
ProBal.Start()          ## and re-solve
while True:
   print ("Solving...")
   time.sleep(.5)
   if ProBal.IsStopped:
       break
print ("Gold in product", end = " ")
print (Tags.TagValue(goldFlow))   ## Print the same tag
 
SysCAD.CloseProject(False)
##
time.sleep(5)
del(Solver)
del(Tags)
del(Prj)
del(SysCAD)
 

The output will be something like:

Using Build 138 Install Directory is  C:\SysCAD138
Gold in product 57.6095546633
Solving...
Feed ppm in gold ore 40.0
Changing value to 45 ppm
Solving...
Gold in product 64.8079746073


See Notes for general information and troubleshooting on using SysCAD COM with Python.

Further Usage: Scenarios, plots, etc

Running a series of scenarios

Extending on the first example, we can easily make plots:

Comexample1.png

We define a useful function to run a series of scenarios and collect the values of any number of tags

import sys
import time
 
try:
  import win32com.client as wc    ## PyWin32 COM Client
except:
  print ("Win32 python extensions not found")
  sys.exit(1)
 
try:
    import matplotlib.pyplot as plt
    showGraphics = True
except:
    print ("Matplotlib not installed, no graphical output")
    showGraphics = False
 
 
def RunScenarios(XVals, setTag, getTagLis, verbose=True, sleepTime = 2):
    """Run a number of scenarios with setTag set to the values in vals, and accumulate the
    values of tags in getTagLis"""
    Y = []
    for x in XVals:
        if verbose: print (x)
        Tags.SetTagValue(setTag, x)  ## Change tag value
        ProBal.Start()
        while True:                           ## Wait until solved 
           if verbose: print ("Solving...")                 
           time.sleep(sleepTime)
           if ProBal.IsStopped:
               break
        Y.append([Tags.TagValue(s) for s in getTagLis])
    return Y
 
ver = 93     ## Recent versions of SysCAD use a different COM ID
ProgID = "SysCADSimulator.Application" if ver<93 else "SysCADSimulator93.Application"
SysCAD = wc.DispatchEx(ProgID)  ## Fire up SysCAD
build = SysCAD.VersionNumber(2) ## Query the build number
ScdDir = r'C:\SysCAD%d' % build
ScdPrj = r'\Examples\25 Gold\Demo Gold Project.spf\Project.spj'
 
Prj = SysCAD.OpenProject(ScdDir+ScdPrj)  ## Open project 
Tags = Prj.Tags         
Solver = Prj.Solver
ProBal = Solver.ProBal

X = list(range(40, 85, 5))  ## for Python3 since since range() is now a generator and we need to reuse X
Y = RunScenarios(X, "FEED_ppm_SET.TC[1].User.Value", ["P_007.Qo.QM.Au(s) (oz/d)", "P_011.Qo.QM.Au(s) (oz/d)"])
 
if showGraphics:
    Z = [y[0] for y in Y]  # flatten
    Z1 = [y[1] for y in Y]
    plt.plot(X, Z, label="Production")
    plt.plot(X, Z, "ro")
    plt.plot(X, Z1, label = "Recycle in P_11")
    plt.xlabel("Ore Gold Concentration")
    plt.ylabel("Gold Production")
    plt.legend(loc=2)
    plt.show()
else:  ## No graphics, just print some stuff
    print ("Ore Gold Concentrations", X)
    print ("Gold Production", Y)
 
SysCAD.CloseProject(False)
##
time.sleep(5)
del(Solver)
del(Tags)
del(Prj)
del(SysCAD)

Getting tags to make useful 3D plots

This example pulls tag data from a running instance of SysCAD: particle size distributions for a series of tanks. It then makes a 3d plot showing the variation in PSD curve along the tank row.

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import win32com.client
SysCAD = win32com.client.DispatchEx("SysCADSimulator93.Application")  ## Use SysCADSimulator.Application for older versions
Tags = SysCAD.Project.Tags

tanklist = ["P_FS_Agglom_1"] + ["P_TK%03d_out" % i for i in range(10, 200, 10)] +["P_CS_Charge_3"]
sizetags = [".Qo.Sz.I%d.FP.Al[OH]3(s) (%%)" % i for i in range(28)] 

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(np.arange(len(tanklist)),
                  np.arange(len(sizetags)))
Z = np.array([ [Tags.TagValue(tank+s) for tank in tanklist] for s in sizetags])
ax.plot_wireframe(X, Y, Z)
plt.show()

Comexample.png