Tuesday, March 3, 2015

Brief Intro to Structures in Fortran

In Matlab, the cell variable type can be very useful.  For those not familiar, a cell (in Matlab) is kinda like a variable inside a variable.  For instance I could have a cell called FieldVariables.  There are 4 elements inside this cell: 1 each for pressure, density, Vx, Vy.  Each of these 5 cell elements has Nx by Ny elements inside relating to the value of the variable at the gridpoints.  This can be a convenient way to collect related data while incurring minimal overhead.

In Fortran, something similar can be done in the form of structures.  A structure allows you to define a custom variable type that can be used similarly integer by coding integer:: i .  It's maybe not exactly the same.

For this example, I need a variable named PointsInCell
Inside PointsInCell, I want to store variables associated with x and y gridpoints.  So, at every gridpoint I want to store:
1) an integer counter NumInCell
2) an allocatable integer array called pIndex
3) an integer called pcounter

I want to do this because NumInCell, pIndex, and pcounter are all related to information local to a specific cell and it's convenient later in the code to have them all collected together.  So first, I define a type that declares NumInVox, pIndex, and pCounter

type CellIndex
        ! Contains:
        integer:: NumInCell ! # points in each Cell
        integer,dimension(:),allocatable:: pIndex ! array storing index of all points in Cell
        integer:: pcounter ! # counter for dynamic array sizing
end type
this takes care of defining what is to be stored AT each gridpoint

Next, I define another type to define the gridpoints where CellIndex will be stored:

type Cells
        type(CellIndex),dimension(:,:),allocatable:: Cell ! each element contains NumInVox, pIndex
end type

This defines the variable Cell as rows and columns were CellIndex will be stored

Lastly, I want to define a single variable that will contain all this information

type(Cells):: PointsInCell

Now to allocate these variables in the structure

allocate(PointsInCell % Cell(yNum,xNum))
do i=1,yNum,1
        do j=1,xNum,1
            allocate(PointsInCell % Cell(i,j) % pIndex(10))
        end do
end do
PointsInCell % Cell(:,:) % pcounter = 10

so if I want to change the pcounter at Cell(10,20) to 20, I'd write
PointsInCell % Cell(10,20) % pcounter = 20

the percent sign defines another level deeper in the structure.

No comments: