• Welcome to the new Internet Infidels Discussion Board, formerly Talk Freethought.

Python

Executing C/C++ code from Python

I copied the following from the widows folder to a folder c:\executables and one from the GCC folder.

Plus the C misc.exe.

cmd.exe
libatomic-1.dll
libgcc_s_seh-1.dll
libgomp-1.dll
libquadmath-0
libssp-0.dll
libstdc++-6.dll
libwinpthread-1.dllmisc.exe

misc.exe

To execute the C code from Python

import os
os.chdir('c:\\executables')
os.system('cmd.exe')
os.system('misc.exe')
 
Numpy and Matplotlib were easy installs.

Numpy matrix function are similar to Mat;lab and Scilab.

Intel as a math library for Python but it will not install on my computer fro some reason.


 
A handy dandy xy plot function with a save option. You can look up the supported file types. Easy to expand to multiple curves on one plot or multiple sub plots.

I always hated rewriting the same code.

Code:
import matplotlib.pyplot as plt
import numpy as np

def plotxys(xlo,xhi,ylo,yhi,x,y,title,xlabel,ylabel,fname):
        font1 = {'family': 'arial',
        'color':  'black',
        'weight': 'heavy',
        'size': 15,
        }
        [fig, p1] = plt.subplots(1)
        p1.plot(x,y,linewidth=2.0,color="k")
        p1.grid(color='k', linestyle='-', linewidth=1)
        p1.grid(which='major', color='k',linestyle='-', linewidth=0.8)
        p1.grid(which='minor', color='k', linestyle='-', linewidth=0.3)
        p1.set_xlim(xlo,xhi)
        p1.set_ylim(ylo,yhi)           
        p1.set_title(title, fontdict = font1)
        p1.set_xlabel(xlabel, fontdict = font1)
        p1.set_ylabel(ylabel, fontdict = font1)
        p1.minorticks_on()
        plt.show()
        if fname != "":fig.savefig(fname)



n = 100
t = np.linspace(0,2*np.pi,n)
y = np.sin(t)
plotxys(min(t),max(t),2*min(y),2*max(y),t,y,"Sine Wave","Radians","Volts","test.png")
 
Scilab has a simple function mpritf() to print arrays to the console. A useful function.

In Python.

Code:
import numpy as np
#------------------------------------------------------------------
def print_arrays(lo,hi,format,*args):
        # format string %IntDigits.DecimalDigitsf or %IntDigitsd, single space delimited
        # arrays mut gave same number of rows
        nrows = len(args[0])
        fs = format.split()
        # check number of rows the same
        for i in range(len(args)):
            if len(args[i]) != nrows :
                    print("rows mismatch error")
                    return 1
        if(hi > nrows):
                print("too many rows error")
                return 1
        #------------------------------------------------
        for i in range(lo,hi):
                j = 0
                for x in args:
                       print(fs[j] %x[i],end="")
                       j += 1
                       print("\t",end="")
                print("\n",end="")
        return 0
#------------------------------------------------------------------
n = 50
a    = np.ndarray(shape=(n),dtype=np.double)
b    = np.ndarray(shape=(n),dtype=np.int_)
c    = np.ndarray(shape=(n),dtype=np.double)
            
for i in range(n):
        a[i]  = i  + np.random.random()
        b[i] = i*10
        c[i] = i*100. + np.random.random()


print_arrays(0,n,"%5.10f %10d %5.2f",a,b,c)

Code:
0.8742003551             0     0.16  
1.6848611577            10    100.75  
2.6543970969            20    200.16  
3.0168302308            30    300.25  
4.1054405007            40    400.01  
5.0646616378            50    500.82  
6.8556757155            60    600.59  
7.5936159771            70    700.51  
8.1211377082            80    800.69  
9.7605494941            90    900.71  
10.9358751801           100    1000.96  
11.6217653247           110    1100.87  
12.6563357613           120    1200.65  
13.8162727129           130    1300.97  
14.2563308117           140    1400.61


The console disply formatting does not exactly copy over.
 
So an array save function. The data I dealt with usually had the same lengths referenced to time and frequency. With a liittle work it could handle arrays of different lengths.

At this point te math of Python seems to be ok, but the rest of it sucks. There are incumbencies that remind me of the early C compiles. You figured out work arounds for things that did not quite work right.
f[1] = "5.5f"
s1 = "{:" + f[1] + "}
s2 = "{:5.5f}" is a newer print form of format specifier.
s1 and s3 look the same when displayed and have the same lengths.
Passing s1 to a write function as a format specifier generates an error, S2 works. If I change "{:"
to "{: " adding a space after : s1 works.

I have seen several irregularities like this.
The syntax can be overly complicated and indirect.

Saving arrays with formatting for each array.


Code:
def save_arrays(fname,format,delim,*args):
        # saves arrays of equal rows
        # format string nd or n.mf separated by a single space
        # delimiter '\t' for tab spacing or ',' for CSV
        #args any number of arrays of equal length a,b,c.....
        print(" Save Start   "+fname)
        nrows = len(args[0])
        fs = format.split()
        # check number of rows the same
        for i in range(len(args)):
            if len(args[i]) != nrows :
                    print("file save rows mismatch error")
                    return 1
        f = open(fname,'w')
        for i in range(nrows):
                j = 0
                for x in args:
                        fm =  "{: "+ fs[j]+"}"                    
                        f.write( fm.format(x[i]) )
                        j += 1
                        f.write(delim)
                f.write("\n")
               
        f.close()
        print(" Save Done   "+fname)
        return 0
 
A handy dandy xy plot function with a save option. You can look up the supported file types. Easy to expand to multiple curves on one plot or multiple sub plots.

I always hated rewriting the same code.

Code:
import matplotlib.pyplot as plt
import numpy as np

def plotxys(xlo,xhi,ylo,yhi,x,y,title,xlabel,ylabel,fname):
        font1 = {'family': 'arial',
        'color':  'black',
        'weight': 'heavy',
        'size': 15,
        }
        [fig, p1] = plt.subplots(1)
        p1.plot(x,y,linewidth=2.0,color="k")
        p1.grid(color='k', linestyle='-', linewidth=1)
        p1.grid(which='major', color='k',linestyle='-', linewidth=0.8)
        p1.grid(which='minor', color='k', linestyle='-', linewidth=0.3)
        p1.set_xlim(xlo,xhi)
        p1.set_ylim(ylo,yhi)          
        p1.set_title(title, fontdict = font1)
        p1.set_xlabel(xlabel, fontdict = font1)
        p1.set_ylabel(ylabel, fontdict = font1)
        p1.minorticks_on()
        plt.show()
        if fname != "":fig.savefig(fname)



n = 100
t = np.linspace(0,2*np.pi,n)
y = np.sin(t)
plotxys(min(t),max(t),2*min(y),2*max(y),t,y,"Sine Wave","Radians","Volts","test.png")
Steve

Will this keep the y axis the same? Or does it modify based on the data? I am trying to keep the y axis the same (yearly) starting with 2018 for several sets of data. Not all data starts in 2018.
 
A handy dandy xy plot function with a save option. You can look up the supported file types. Easy to expand to multiple curves on one plot or multiple sub plots.

I always hated rewriting the same code.

Code:
import matplotlib.pyplot as plt
import numpy as np

def plotxys(xlo,xhi,ylo,yhi,x,y,title,xlabel,ylabel,fname):
        font1 = {'family': 'arial',
        'color':  'black',
        'weight': 'heavy',
        'size': 15,
        }
        [fig, p1] = plt.subplots(1)
        p1.plot(x,y,linewidth=2.0,color="k")
        p1.grid(color='k', linestyle='-', linewidth=1)
        p1.grid(which='major', color='k',linestyle='-', linewidth=0.8)
        p1.grid(which='minor', color='k', linestyle='-', linewidth=0.3)
        p1.set_xlim(xlo,xhi)
        p1.set_ylim(ylo,yhi)       
        p1.set_title(title, fontdict = font1)
        p1.set_xlabel(xlabel, fontdict = font1)
        p1.set_ylabel(ylabel, fontdict = font1)
        p1.minorticks_on()
        plt.show()
        if fname != "":fig.savefig(fname)



n = 100
t = np.linspace(0,2*np.pi,n)
y = np.sin(t)
plotxys(min(t),max(t),2*min(y),2*max(y),t,y,"Sine Wave","Radians","Volts","test.png")
Steve

Will this keep the y axis the same? Or does it modify based on the data? I am trying to keep the y axis the same (yearly) starting with 2018 for several sets of data. Not all data starts in 2018.


The plot function takes min and max values for x and y. You can specify fixed values or use min(x),max(x), min(y),max(y) as the lo-hi parameters which will scale the x and y axes to the data..


in the example this will scale the plot to the x and y data.

Code:
plotxys(min(t),max(t),min(y),max(y),t,y,"Sine Wave","Radians","Volts","test.png")

It is easy to plot multiple plot planes simultaneously for multiple data sets.

 
Back
Top Bottom