TinyURL widget - shorten your URL's for free!

Enter a long URL to make tiny:

Monday, April 11, 2016

Creating and using a .this pointer in C language structs



This blog post contains examples of how to create a this pointer in C. You may know "this.xxxx" is a C++ attribute of objects. Well like many things you can emulate it in C because C is far more flexible without the bloating that object oriented languages provide for lazy programmers to make mistakes.

Of course, in order to emulate in C it requires more knowledge/experience than the average starting programmer can do. And as websites develop bit rot for older technology these things get lost unless others decide to pick up the challenge to maintain them.  I do not claim to be the first to do this, I am sure it's been done, but I am the one making a clear explanation and re-introducing it as it were.

I tried to post to stack exchange but I do not meet the process nazi's interpretation of a good question so I won't bother providing them my help. I would rather be helpful than process-correct and I don't get paid to educate so I stick to the facts without superfluity in a non-educational idiom.

<\whining>

One can make a resident pointer to a struct of the same type like so:


You don't need the first cca_t I just use it to make my understanding easier.

Before a struct has been defined one can't refer to it. Some sort of causal loop error in programming form.  But one can declare it as a struct while defining the struct- itself?!? Another metaphysical argument I don't need to go into. I know this will work on GCC with default warnings and error flags and that's all I care about. I cannot confirm if it works with C-XXXX standard in general terms. CAVEAT EMPTOR. If you do find out it works I would appreciate 40 ms of your time to respond back below and we can leave all the comments in one spot for people to find them. Like me in 6 months when I return.

So the "this" pointer is a pointer without an array. Notice I include a pointer to a pointer to  the same struct being defined. In this case I am making a same-typed pointer (to pointer) that will be the receptor of similar pointers from neighbouring cells. I was making a cellular automata at the time so that was the context. I wanted to be able to define modular units that might end up on different threads in this version. So they can access in the same program frame addressing but not necessarily the same operation unit / lightweight process.

So far so good. Now, when you initialize / construct the dynamic struct with malloc:




You point the this at the pointer you will return at the end of the function.

In this instantiation, I make cell surfaces dependent on the same neighbour number to 0 cell means neighbour 0 and also state[0] for any values passed back and forth. Now I can iterate once and get it all.  I don't make a set pattern for cell walls because they might have arbitrary connectedness.

Now when I want to assign a neighbour to a cell it works something like this:




I assign b's b->this variable to the neighbour slot open in a's neighbour list.
And likewise assign a's this to b. I also assign the cell walls (neighbour connection) using the ADDRESS OF of the pointer not the VALUE of the pointer. Since the neighbour is inside the larger struct passed and we are using  a pointer -> pointer -> struct we are accessing the value by default when we aim at the second struct within a struct that was passed inside a function variable declaration because these are nested structs within structs.  I know that sounds like double talk but I am unrolling the order of operations and presenting it in a way that when you look at other explanations will make sense.

Pointers take time to understand and remember that pointers give a value or an address, not an array, when accessed. That's why a pointer to element with offset indexing leads to another pointed-to element. An array is guaranteed for your program's sake (as far as it can see) to be a contiguous length of memory of type.

The struct is a value when accessed one way, it is an address when accessed the other.

I don't like the *( a + i).element method of writing C structs because it is a babyish technique taught by naive professors that have never dared to make more complicated nested code. Some claim it is faster and I don't dispute that but I doubt they've tried harder because they stop teaching at the semester end. Probably because when you present the same material every year no one challenges you to prove you can do more. It makes sense for basic applications which is what they can show you. But working code lives and gets more complex. Programmers don't.

I claim it's babyish because I dare them to keep this kind of nested logic straight in their mind when writing it.

*((((a+i)+j)+k)+l)+m).element

So

&(b->state[b->neighbour_number]).st

gives us the address of the pointed to state address (.st) inside the nested pointers and this can continue with a rational understanding of the content within like so:

&(b->state[b->neighbour_number]->neuron[b->cell_number]->synapse[b->geo_number]).st

ad infinitum with a rational way to understand what was written. I can make iterator names that make sense and I can understand 10 files all at once. All the element indices can be maintained at the top level and iterated which is really the operation that most code undergoes. But what is different here is people can make a direct understanding of the things operating on things because that is the level humans work at. That is what costs the most time; understanding what code does not writing perfect code. Machines are better in most cases for optimization except for ATLAS as far as I know. R. Clint Whaley is an uber nerd and he writes sparse matrix optimizations by hand.

I follow the unix philosophy  writing understandable code and leaving optimization as another step:

"Worse is better"

I work in research so I don't worry about development as much as making sure it works. But with a top level iteration mechanism the GCC compiler can then unroll for loops for speed or optimize for memory. But the human being writes code and then goes off for 3 months and then has to come back to it.

This is why writing things like a .this pointer make it easier to grasp what you wrote and then evolve it quickly with patterns that make sense.







Sunday, March 20, 2016

Writing time to vector data output in ngspice control block


If you want to store the time as a vector alongside the columns of data in an ngspice simulation output, then you call the vector 't' which is the internal name for the time-stepped finite difference. 

For example, this control block prints out the time into a wrdata command.

**************************************************************
*  CONTROL BLOCK                                             *
**************************************************************
.control
set hcopydevtype=postscript
* allow color and set background color if set to value > 0
set hcopypscolor=1
*color0 is background color
*color1 is the grid and text color
*colors 2-15 are for the vectors
set color0=rgb:f/f/f
set color1=rgb:0/0/0
set color2=rgb:5/5/5
set color3=rgb:0/9/9
set color4=rgb:7/9/0
op
run
*  V(1) V(2) V(3) I(vss) V(7) V(6) V(5)
gnuplot   V(1) V(2) V(3) I(vss) V(7) V(6) V(5)
hardcopy multi-switch.ps  V(1) V(2) V(3) I(vss) V(7) V(6) V(5)
wrdata multiswitch.data  t V(1) V(2) V(3) I(vss) V(7) V(6) V(5)
.endc

which resulted in the following output:


 

Friday, March 4, 2016

Example of a MOSFET switch in SPICE model

I was reading this OK tutorial to refresh myself on how to make a MOSFET switch. They do a good job explaining theory but they dont' take it that one step further. You can find more information here.




I took a n-channel depletion MOSFET model from here Simon Bramble
and I made a SPICE model circuit around it.

I stepped the voltage on the gate - look at the V(1) voltage in grey - and it activates the MOSFET conducting channel via the field effect when the blue line V(3) (which is the drain node ) drops from 6 volts down to zero.   This causes the current to flow through the drain to source and this turns on the load which is flowing through I(Vss).


Erratum: First version explained effect as transconductance, that's not accurate I've changed it to field effect. That's how rusty I am I mixed the phenomena.Transconductance is a generalization relating transfer function in this case of gate voltage to compared to source current / voltage but the phenomena is the field effect. My first explanation was partly correct but the second one is completely accurate.

Thursday, November 19, 2015

Ring Buffers in GNU C from Learn C The Hard Way



I took the ring buffers exercise from  http://c.learncodethehardway.org/book/
and I fixed it and expanded it. Not that it wasn't a good starting point but it was a good learning function list I didn't know how ring buffers worked.  I wanted to understand how ring buffers work and they do make sense for a lot of string reads and writes.

I had to fix some faulty logic in the functions, and I  took out the references to the bstring library in favour of GNU C and I put it all into an autotools format like I do.  In this way, one can expand and improve the code for open source applications. Of course then I open source the modified version and put in on GIT.



I had one comment about his code.


Note; one way to fool a compiler is to put function calls into define statements.  Example from his code:

#define RingBuffer_puts(B, D) RingBuffer_write((B), bdata((D)), blength((D)))


Now if this is the only reference to the bstring library, then it might be missed by compilers. GCC choked on this and missed it up until library linking. Otherwise it was a well written library function set.

My ringbuffers expand the original thinking.

 In Zed A. Shaw's original string of chars case the ring buffer is a conceptual ring of memory each one memory space wide.  Increase one memory increases one char.   But in my version there is an analog of a ring buffer of ROWS as the memory element in a ring where the row size and element size are arbitrary and determined by type. This allows one to conduct matrix and vector multiplications to them with pointers aimed at specific rows.


You can find my ringbuffers version here.  GNU Ring Buffers

Autoversion under Autoheader / Autoconf / Automake under git repositories


 https://www.gnu.org/graphics/heckert_gnu.small.png

There is a way to make the library update it's version number automagically is to use the

git describe --tags

function to get the current library version, the GPG signage, and store that value in a temporary file that you shouldn't track inside the repository.


In configure.ac:

AC_INIT([library], m4_esyscmd([build-aux/git-version-gen.sh .version]), [email@shaw.ca])
 Add this line to update the library version from a shell script. There is an unquoted version of m4_esyscmd_s that strips newlines but I found storing straight to file did not add any.

I got this from libqb's git repository but I modified their file to include git describe --tags rather than the original version.


Inside Makefile.am I added .phony targets unlike how libqb did with this:

.version:
    git describe --tags > build-aux/.version
dist-hook:
    git describe --tags  > $(distdir)/.tarball-version

.PHONY:  .version

commit:
    DATE='date'
    git commit -m  " $DATE "
    git push
    
.PHONY: commit

to make a version that then gets read by the autoheader when it sets up configure.

I added an auto commit as well but I may not use that. 

I added another shellscript to the top folder for priming the pump and inserting the first version number into the .version file.

#!/bin/sh
# uprev.sh - shell script to update the latest library tags.

git describe --tags > build-aux/.version

Friday, November 13, 2015

efunda: engineering fundamentals


I found this great website today, and used a couple of their java-script plotters to explain parametric equations. 

efunda stands for engineering fundamentals. 

Here is an excerpt from their website:

eFunda stands for engineering Fundamentals. Its mission is to create an online destination for the engineering community, where working professionals can quickly find concise and reliable information to meet the majority of their daily reference needs.
eFunda is all about the basics, for most part, that means college level material covered in engineering schools. If you practice engineering, more often than not you would find yourself searching for something you knew but could not quite remember. eFunda wants to be your reminder of these formulas. Not only that, eFunda wants to tell you exactly under what conditions those formulas apply, so you don't have to read an entire chapter of the good old textbook.

http://www.efunda.com/about/about.cfm


This is the java applet I was playing with.