LIBDVM2 (1158351), страница 17

Файл №1158351 LIBDVM2 (Раздаточные материалы) 17 страницаLIBDVM2 (1158351) страница 172019-09-18СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 17)

where:

InitIndex

- initial value of the index variable of the parallel loop for the dimension *AxisPtr;

LastIndex

- last value of the index variable of the parallel loop for the dimension *AxisPtr

Step

- step of the index variable of the parallel loop for the dimension *AxisPtr;

Ceil

- a function to get the least integer, not less than value of its argument.

If *AxisPtr = 0, the size of the object (product of sizes of all dimensions) is returned.

If the pointer *ObjectRefPtr is not a pointer to any of the mentioned above objects, then the function returns zero.

long locsiz_(

ObjectRef
long

*ObjectRefPtr,
*AxisPtr);

The function locsiz_ is similar to the function getsiz_, but it returns the local size of dimension *AxisPtr (or the local size of the object), i.e. the size of the object part, mapped on the current processor. If the object is a processor system, then the values, returned by the functions getsiz_ and locsiz_ are the same.

Note, that a local size of the object, having no a local part on the current processor, is equal to zero.

17.3. Requesting if object is distributed array.

long tstda_ (ObjectRef *ObjectRefPtr);

The function tstda_ allowes to determine whether the object, specified by the pointer *ObjectRefPtr, is a distributed array.

The following values are returned:

0 - the object is not a distributed array;

1 - the object is a distributed array;

2 - the object is a fully replicated distributed array.

17.4. Requesting size of distributed array element.

long getlen_ (long ArrayHeader[]);

ArrayHeader - header of the distributed array.

The function getlen_ returns the size in bytes of element of specified distributed array in bytes.

17.5. Deleting object.

long delobj_(ObjectRef *ObjectRefPtr);

*ObjectRefPtr - pointer to the deleted object.

It is possible to use the followings as an object:

  • distributed array (in that case the pointer is the first word of the header of the array);

  • the representation of the abstract machine;

  • the processor system;

  • map of abstract machine representation;

  • map of distributed array;

  • reduction;

  • reduction group;

  • shadow edge group.

Note, that non-static object can be deleted by the function delobj_ only in the case, if it was created in the current program block.

The function returns zero.

17.6. Requesting whether current processor is I/O processor.

long tstio_(void);

The function returns 1 if the current processor is the I/O processor, and returns zero in another case.

17.7. Sending memory areas of I/O processor.

long srmem_(

long
AddrType
long

*MemoryCountPtr,
StartAddrArray[],
LengthArray[]);

*MemoryCountPtr

- the number of the sent areas of the memory.

StartAddrArray

- array, which i-th element is the start address of (i+1)-th area (adjusted to AddrType type).

LengthArray

- array, which i-th element is the size of the (i+1)-th area (in bytes).

The function srmem_ sends the memory areas of the I/O processor to another processors. During this operation the I/O processor sends the data, and the other processors receive the data. The number of the parameters in the arrays LenghtArray and StartAddrArray has to be equal to *MemoryCountPtr. The length of the each sent area has not to exceed the maximum of the positive integer (LengthArray[i] (unsigned int)-1 >> 1).

The function returns zero.

To receive an address acceptable for the function srmem_, Run-Time Library has the function:

AddrType dvmadr_(void *VarPtr) ,

This function is intended for usage in Fortran.

The following functions can be also used for Fortran variables of different types:

AddrType

getai_

(void *VatPtr),

AddrType

getal_

(void *VatPtr),

AddrType

getaf_

(void *VatPtr),

AddrType

getad_

(void *VatPtr),

AddrType

getac_

(void *VatPtr),

AddrType

getach_

(void *VatPtr, long StrLength),

These functions are similar to the function dvmadr_ (in the function getach_ VarPtr is the address of text string, and StrLength is its size, formed by Fortran compiler.

The functions srmem_ and dvmadr_ (getai_, getal_, getaf_, getad_, getac_, getach_) can be used for implementation of input/output operations).

18. Using Run-Time Library in Fortran language.

To coordinate allocation of the arrays in the memory, (along the columns in the Fortran , and along the rows in the C) inverse order of specifying the array indexes (in comparison with the order in the C ) is required. In addition, in this document it is supposed that the initial array index value is equal to zero, that is conformed to the C language. In the Fortran language this index is equal to 1.

The type of the returned values is a four-bytes field (the exception is the «long» , DVMFILE* and DVMHANDLE* types). For these types it is allowable only assignment operations and the using as a parameters in the calls of the functions and subroutines. In the Fortran language the base type «long» has to be associated with integer type, which has equivalent memory representation (the particular type depends on the C and Fortran language implementations).

19. Example of program using Run-Time Library functions.

The usage of main functions of Run-Time Library is shown on the example of numerical solution of two-dimensional Laplas equation in specified rectangular area with specified boundary conditions (Dirixle task).

2U
----- +
x2

2U
----- = 0 (1)
y2

Three-point approximation of partial derivatives of the equation (1) on squared grid using five-point pattern

(i-1,j) , (i+1,j) , (i,j) , (i,j-1) , (i,j+1)

gives differential equation ("cross" scheme), reduced to the equation

ui,j = (ui+1,j + ui-1,j + ui,j+1 + ui,j-1)/4 (i,j=1, ... ,k-2) (2),

where:

k

- a number of grid points of each dimension;

ui,j

- a value of grid function in a note (i,j).

The value of the grid function

u0,j , uk-1,j , ui,0 , ui,k-1 (i,j=0, ... ,k-1)

is determined by boundary conditions.

In the programs below (Fortran and C) the solution of the equation (1) is seached by formulas (2) using method of sequential approximations. The iterational proccess is completed if maximal diviation of the grid function ui,j on all knots for to sequential iterations will become less, then a value of variable maxeps. The solution is searched as function ui,j = 1 + i + j. on the square[0:7, 0:7]. The boundary conditions are zero.

PROGRAM IN FORTRAM LANGUAGE

program cross

integer linit, lexit,getam, getps, crtamv, distr, crtda, align,

+ crtpl, dvmadr, mappl, endpl, exfrst, imlast, dopl,

+ tstio, crtrg, crtred, insred, strtrd, waitrd,

+ crtshg, inssh, strtsh, waitsh, delrg, delshg

real bptr(1)

integer dvm

integer amref, psref, mvref, plref, rgref, redref, shgref

integer amdim(2), disaxs(2), dispar(2)

integer shwdth(2), axis(2), coeff(2), const(2)

integer lvaddr(2), iiniti(2), ilasti(2), istep(2)

integer oiniti(2), olasti(2), ostep(2)

C A number of grid points by each dimension and

C max. number of iterations.

parameter (k = 8, itmax = 20)

real eps, maxeps

C Array header with previous values of the grid function

integer ahdr(3)

C Array header with next values of the grid function

integer bhdr(3)

maxeps = 0.5e-7

C Run-Time Library initialisation

dvm = linit (0)

C Creating abstract machine representation

C and mapping it onto processor subsystem

amref = getam ()

psref = getps (amref)

amdim(1) = k

amdim(2) = k

mvref = crtamv (amref, 2, amdim,0)

disaxs(1) = 1

disaxs(2) = 2

dispar(1) = 0

dispar(2) = 0

dvm = distr (mvref, psref, 2, disaxs, dispar)

C Creating and mapping arrays

C with the values of the grid function

shwdth(1) = 1

shwdth(2) = 1

dvm = crtda (ahdr, bptr, 2, 4, amdim, 0, 0, shwdth, shwdth)

dvm = crtda (bhdr, bptr, 2, 4, amdim, 0, 0, shwdth, shwdth)

axis(1) = 1

axis(2) = 2

coeff(1) = 1

coeff(2) = 1

const(1) = 0

const(2) = 0

dvm = align (ahdr, mvref, axis, coeff, const)

dvm = align (bhdr, mvref, axis, coeff, const)

C Parallel loop of initializing arrays

C with values of the grid function

C (parallel loop with the base array ahdr).

plref = crtpl (2)

lvaddr(1) = dvmadr (j)

lvaddr(2) = dvmadr (i)

iiniti(1) = 0

iiniti(2) = 0

ilasti(1) = k - 1

ilasti(2) = k - 1

istep(1) = 1

istep(2) = 1

dvm = mappl (plref, ahdr, axis, coeff, const, lvaddr,

+ iiniti, ilasti, istep, oiniti, olasti, ostep)

99999 if (dopl (plref) .eq. 0) goto 99998

do 1 j = oiniti(1), olasti(1), ostep(1)

do 1 i = oiniti(2), olasti(2), ostep(2)

bptr( ahdr(3) + 1 + i + ahdr(2) * j ) = 0.

bptr( bhdr(3) + 1 + i + bhdr(2) * j ) = 1. + i + j

1 continue

goto 99999

99998 dvm = endpl (plref)

C Creating reduction variable and reduction group

C to calculate maximal deviation of the grid function for

C two sequential iterations.

redref = crtred ( 3, eps, 3, 1, 0, 0, 0)

rgref = crtrg (0, 0)

dvm = insred (rgref, redref)

C Creating shadow edge group for renewing shadow edges

shgref = crtshg (0)

dvm = inssh (shgref, ahdr, shwdth, shwdth, 0)

C MAIN ITERATION LOOP

do 2 it = 1,itmax

C Parallel loop to calculate maximal deviation

C of the grid function in variable eps

C (parallel loop with base array ahdr).

plref = crtpl (2)

iiniti(1) = 1

iiniti(2) = 1

ilasti(1) = k - 2

ilasti(2) = k - 2

dvm = mappl (plref, ahdr, axis, coeff, const, lvaddr,

+ iiniti, ilasti, istep, oiniti, olasti, ostep)

eps = 0.

99997 if (dopl (plref) .eq. 0) goto 99996

Характеристики

Список файлов учебной работы

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
7026
Авторов
на СтудИзбе
260
Средний доход
с одного платного файла
Обучение Подробнее