keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
3D | mcellteam/mcell | src/mcell_react_out.h | .h | 2,624 | 65 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_init.h"
struct output_column_list {
struct output_column *column_head;
struct output_column *column_tail;
};
struct output_set_list {
struct output_set *set_head;
struct output_set *set_tail;
};
struct output_times_inlist {
enum output_timer_type_t type;
double step;
struct num_expr_list_head values;
};
int mcell_get_count(char *mol_name, char *reg_name, struct volume *world);
struct output_request *mcell_new_output_request(MCELL_STATE *state,
struct sym_entry *target,
short orientation,
struct sym_entry *location,
struct periodic_image *img,
int report_flags);
struct output_set *mcell_create_new_output_set(const char *comment, int exact_time,
struct output_column *col_head,
int file_flags,
const char *outfile_name);
MCELL_STATUS mcell_prepare_single_count_expr(struct output_column_list *list,
struct output_expression *expr,
char *custom_header);
MCELL_STATUS
mcell_add_reaction_output_block(MCELL_STATE *state,
struct output_set_list *osets, int buffer_size,
struct output_times_inlist *otimes);
MCELL_STATUS mcell_create_count(MCELL_STATE *state, struct sym_entry *target,
short orientation, struct sym_entry *location,
int report_flags, char *custom_header,
struct output_column_list *count_list);
MCELL_STATUS mcell_get_counter_value(MCELL_STATE *state,
const char *counter_name, int column,
double *count_data,
enum count_type_t *count_data_type);
| Unknown |
3D | mcellteam/mcell | src/util.c | .c | 68,351 | 2,267 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <assert.h>
#include <float.h>
#include <math.h>
#include <inttypes.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <vector>
#ifndef _MSC_VER
#include <unistd.h>
#include <sys/resource.h> // Linux include
#else
typedef unsigned int uint;
#endif
#include "logging.h"
#include "util.h"
#include "mcell_structs.h"
#include "bng/shared_defines.h"
#include "bng/filesystem_utils.h"
/*******************************************************************
new_bit_array: mallocs an array of the desired number of bits
In:
bits: how many bits to place in the array
Out:
A pointer to a newly allocated bit_array struct, or NULL
on memory error.
*******************************************************************/
struct bit_array *new_bit_array(int bits) {
int n = (bits + 8 * sizeof(int) - 1) / (8 * sizeof(int));
/* Allocate contiguous memory for struct bit_array and its associated bits */
struct bit_array *ba = (struct bit_array *)malloc(sizeof(struct bit_array) +
sizeof(int) * n);
if (ba == NULL) {
return NULL;
}
ba->nbits = bits;
ba->nints = n;
return ba;
}
/*************************************************************************
duplicate_bit_array: mallocs an array and copies an existing bit array
In:
old: existing bit array to duplicate (in newly malloced memory)
Out:
A pointer to a newly allocated bit_array struct, or NULL
on memory error.
*************************************************************************/
struct bit_array *duplicate_bit_array(struct bit_array *old) {
struct bit_array *ba = (struct bit_array *)malloc(sizeof(struct bit_array) +
sizeof(int) * old->nints);
if (ba == NULL) {
return NULL;
}
memcpy(ba, old, sizeof(struct bit_array) + sizeof(int) * old->nints);
return ba;
}
/*******************************************************************
get_bit: returns the value of a bit in a bit_array
In:
ba: pointer to a bit_array struct
idx: the index of the bit to return
Out:
0 or 1, depending on whether the idx'th bit is set. No
bounds checking is performed.
*******************************************************************/
int get_bit(struct bit_array *ba, int idx) {
int *data = &(ba->nints);
data++; /* At start of bit array memory */
size_t ofs = idx & (8 * sizeof(int) - 1);
idx = idx / (8 * sizeof(int));
ofs = 1u << ofs;
if ((data[idx] & ofs) != 0) {
return 1;
} else {
return 0;
}
}
/*******************************************************************
set_bit: set a value in a bit array
In:
ba: pointer to a bit_array struct
idx: the index of the bit to set
value: 0 = turn bit off; nonzero = turn bit on
Out:
Nothing
*******************************************************************/
void set_bit(struct bit_array *ba, int idx, int value) {
int *data = &(ba->nints);
data++; /* At start of bit array memory */
size_t ofs = idx & (8 * sizeof(int) - 1);
idx = idx / (8 * sizeof(int));
ofs = (1u << ofs);
if (value) {
value = ofs;
} else {
value = 0;
}
data[idx] = (data[idx] & ~ofs) | value;
}
/*******************************************************************
set_bit_range: set many bits to a value in a bit array
In:
ba: pointer to a bit_array struct
idx1: the index of the first bit to set
idx2: the index of the last bit to set
value: 0 = turn bits off; nonzero = turn bits on
Out:
Nothing
*******************************************************************/
void set_bit_range(struct bit_array *ba, int idx1, int idx2, int value) {
int *data = &(ba->nints);
data++; /* At start of bit array memory */
int ofs1 = idx1 & (8 * sizeof(int) - 1);
int ofs2 = idx2 & (8 * sizeof(int) - 1);
idx1 = idx1 / (8 * sizeof(int));
idx2 = idx2 / (8 * sizeof(int));
unsigned int mask, cmask;
if (idx1 == idx2) {
mask = 0;
for (int i = ofs1; i <= ofs2; i++) {
mask |= (1u << i);
}
cmask = ~mask;
if (value) {
data[idx1] = (data[idx1] & cmask) | mask;
} else {
data[idx1] = data[idx1] & cmask;
}
} else {
if (value) {
value = ~0;
} else {
value = 0;
}
for (int i = idx1 + 1; i < idx2; i++) {
data[i] = value;
}
mask = 0;
for (unsigned int i = ofs1; i < 8 * sizeof(int); i++) {
mask |= (1u << i);
}
cmask = ~mask;
if (value) {
data[idx1] = (data[idx1] & cmask) | mask;
} else {
data[idx1] = data[idx1] & cmask;
}
mask = 0;
for (int i = 0; i <= ofs2; i++) {
mask |= (1u << i);
}
cmask = ~mask;
if (value) {
data[idx2] = (data[idx2] & cmask) | mask;
} else {
data[idx2] = data[idx2] & cmask;
}
}
}
/*******************************************************************
set_all_bits: sets all values in a bit array
In:
ba: pointer to a bit_array struct
value: 0 = turn bits off; nonzero = turn bits on
Out:
Nothing
*******************************************************************/
void set_all_bits(struct bit_array *ba, int value) {
if (value) {
value = ~0;
}
int *data = &(ba->nints);
data++; /* At start of bit array memory */
for (int i = 0; i < ba->nints; i++) {
data[i] = value;
}
}
/*******************************************************************
bit operation: performs a logical operation on two bit arrays
In:
ba: pointer to a bit_array struct
bb: pointer to another bit_array struct
op: character that determines which operation to perform
'!' -- ba = NOT ba
'~' -- same
'|' -- ba = ba OR bb
'+' -- same
'&' -- ba = ba AND bb
'^' -- ba = ba XOR bb
'-' -- ba = ba AND NOT bb
Out:
Nothing
*******************************************************************/
void bit_operation(struct bit_array *ba, struct bit_array *bb, char op) {
int *da, *db;
if (op == '!' || op == '~') {
da = &(ba->nints);
da++;
for (int i = 0; i < ba->nints; i++) {
da[i] = ~da[i];
}
return;
}
if (ba->nbits != bb->nbits) {
return;
}
da = &(ba->nints);
da++;
db = &(bb->nints);
db++;
switch (op) {
case '^':
for (int i = 0; i < ba->nints; i++) {
da[i] ^= db[i];
}
break;
case '|':
case '+':
for (int i = 0; i < ba->nints; i++) {
da[i] |= db[i];
}
break;
case '-':
for (int i = 0; i < ba->nints; i++) {
da[i] &= ~db[i];
}
break;
case '&':
for (int i = 0; i < ba->nints; i++) {
da[i] &= db[i];
}
break;
default:
break;
}
}
/**********************************************************************
count_bits: count how many bits are set in a bit array
In:
ba: pointer to a bit_array struct
Out:
int containing number of nonzero bits
**********************************************************************/
int count_bits(struct bit_array *ba) {
static const int cb_table[256] = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4,
2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4,
2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6,
4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5,
3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6,
4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
int *dd = &(ba->nints);
dd++;
unsigned char *d = (unsigned char *)dd;
int n = (ba->nints - 1) * sizeof(int);
int cnt = 0;
for (int i = 0; i < n; i++) {
cnt += cb_table[(*d++)];
}
n = ba->nbits - n * 8;
if (n == 0)
return cnt;
int j = dd[ba->nints - 1];
while (n >= 8) {
cnt += cb_table[j & 0xFF];
n -= 8;
j >>= 8;
}
if (n > 0) {
cnt += cb_table[j & 0xFF] - cb_table[(j & 0xFF) >> n];
}
return cnt;
}
/**********************************************************************
free_bit_array: frees a bit array (just a wrapper to free() for now)
In:
ba: pointer to a bit_array struct
Out:
Nothing
**********************************************************************/
void free_bit_array(struct bit_array *ba) { free(ba); }
/*************************************************************************
bisect:
In: array of doubles, sorted low to high
int saying how many doubles there are
double we are using to bisect the array
Out: index of the largest element in the array smaller than the bisector
*************************************************************************/
int bisect(double *list, int n, double val) {
int lo = 0;
int hi = n;
int mid = 0;
while (hi - lo > 1) {
mid = (hi + lo) / 2;
if (list[mid] > val)
{
hi = mid;
} else {
lo = mid;
}
}
return lo;
}
/*************************************************************************
bisect_near:
In: array of doubles, sorted low to high
int saying how many doubles there are
double we are using to bisect the array
Out: index of the element closest to val
*************************************************************************/
int bisect_near(double *list, int n, double val) {
int lo = 0;
int hi = n - 1;
int mid = 0;
while (hi - lo > 1) {
mid = (hi + lo) / 2;
if (list[mid] > val)
{
hi = mid;
} else {
lo = mid;
}
}
if (val > list[hi]) {
return hi;
} else if (val < list[lo]) {
return lo;
} else if (val - list[lo] < list[hi] - val) {
return lo;
} else {
return hi;
}
}
/*************************************************************************
bisect_high:
In: array of doubles, sorted low to high
int saying how many doubles there are
double we are using to bisect the array
Out: index of the smallest element in the array larger than the bisector
*************************************************************************/
int bisect_high(double *list, int n, double val) {
int lo = 0;
int hi = n - 1;
int mid = 0;
while (hi - lo > 1) {
mid = (hi + lo) / 2;
if (list[mid] > val) {
hi = mid;
} else {
lo = mid;
}
}
if (list[lo] > val)
{
return lo;
} else {
return hi;
}
}
/**********************************************************************
distinguishable: reports whether two doubles are measurably different
In:
a: first double
b: second double
eps: fractional difference that we think is different
Out:
1 if the numbers are different, 0 otherwise
**********************************************************************/
int distinguishable(double a, double b, double eps) {
double c = fabs(a - b);
a = fabs(a);
if (a < 1) {
a = 1;
}
b = fabs(b);
if (b < a) {
eps *= a;
} else {
eps *= b;
}
return (c > eps);
}
/**********************************************************************
is_reverse_abbrev: reports whether the first string is a reverse
abbreviation of the second, i.e. whether it matches the end of
the second string.
**********************************************************************/
int is_reverse_abbrev(const char *abbrev, const char *full) {
size_t na = strlen(abbrev);
size_t nf = strlen(full);
if (na > nf) {
return 0;
}
return (strcmp(abbrev, full + (nf - na)) == 0);
}
/*************************************************************************
void_list_sort:
In: linked list contining void pointers
Out: linked list is mergesorted by memory address
*************************************************************************/
struct void_list *void_list_sort(struct void_list *vl) {
struct void_list *stack[64];
int stack_n[64];
struct void_list *left, *right, *merge, *tail;
int si = 0;
/* HACK: If vl == NULL, we return stack[0] unmodified, so initialize it to
* NULL. */
stack[0] = NULL;
while (vl != NULL) {
if (vl->next == NULL) {
stack[si] = vl;
stack_n[si] = 1;
vl = NULL;
si++;
} else if ((intptr_t)vl->data <= (intptr_t)vl->next->data) {
stack[si] = vl;
stack_n[si] = 2;
vl = vl->next->next;
stack[si]->next->next = NULL;
si++;
} else {
stack[si] = vl->next;
stack_n[si] = 2;
left = vl;
vl = vl->next->next;
stack[si]->next = left;
left->next = NULL;
si++;
}
while (si > 1 && stack_n[si - 1] * 2 >= stack_n[si - 2]) {
stack_n[si - 2] += stack_n[si - 1];
left = stack[si - 2];
right = stack[si - 1];
if ((intptr_t)left->data <= (intptr_t)right->data) {
merge = left;
left = left->next;
} else {
merge = right;
right = right->next;
}
merge->next = NULL;
tail = merge;
while (1) {
if (left == NULL) {
tail->next = right;
break;
}
if (right == NULL) {
tail->next = left;
break;
}
if ((intptr_t)left->data <= (intptr_t)right->data) {
tail->next = left;
tail = left;
left = left->next;
} else {
tail->next = right;
tail = right;
right = right->next;
}
}
stack[si - 2] = merge;
si--;
}
}
while (si > 1) /* Exact duplicate of code in loop--keep it this way! */
{
stack_n[si - 2] += stack_n[si - 1];
left = stack[si - 2];
right = stack[si - 1];
if ((intptr_t)left->data <= (intptr_t)right->data) {
merge = left;
left = left->next;
} else {
merge = right;
right = right->next;
}
merge->next = NULL;
tail = merge;
while (1) {
if (left == NULL) {
tail->next = right;
break;
}
if (right == NULL) {
tail->next = left;
break;
}
if ((intptr_t)left->data <= (intptr_t)right->data) {
tail->next = left;
tail = left;
left = left->next;
} else {
tail->next = right;
tail = right;
right = right->next;
}
}
stack[si - 2] = merge;
si--;
}
return stack[0];
}
/*************************************************************************
void_list_sort_by:
In: linked list containing void pointers
comparison function that compares two void pointers
Out: linked list is mergesorted according to function
Note: function should implement "less than or equal to", i.e., it
should return a nonzero value if the first pointer is considered
to be less than or equal to the second (based on contents or
whatever), and it should return zero otherwise.
*************************************************************************/
struct void_list *void_list_sort_by(struct void_list *vl,
int (*leq)(void *, void *)) {
struct void_list *stack[64];
int stack_n[64];
struct void_list *left, *right, *merge, *tail;
int si = 0;
/* HACK: If vl == NULL, we return stack[0] unmodified, so initialize it to
* NULL. */
stack[0] = NULL;
while (vl != NULL) {
if (vl->next == NULL) {
stack[si] = vl;
stack_n[si] = 1;
vl = NULL;
si++;
} else if ((*leq)(vl->data, vl->next->data)) {
stack[si] = vl;
stack_n[si] = 2;
vl = vl->next->next;
stack[si]->next->next = NULL;
si++;
} else {
stack[si] = vl->next;
stack_n[si] = 2;
left = vl;
vl = vl->next->next;
stack[si]->next = left;
left->next = NULL;
si++;
}
while (si > 1 && stack_n[si - 1] * 2 >= stack_n[si - 2]) {
stack_n[si - 2] += stack_n[si - 1];
left = stack[si - 2];
right = stack[si - 1];
if ((*leq)(left->data, right->data)) {
merge = left;
left = left->next;
} else {
merge = right;
right = right->next;
}
merge->next = NULL;
tail = merge;
while (1) {
if (left == NULL) {
tail->next = right;
break;
}
if (right == NULL) {
tail->next = left;
break;
}
if ((*leq)(left->data, right->data)) {
tail->next = left;
tail = left;
left = left->next;
} else {
tail->next = right;
tail = right;
right = right->next;
}
}
stack[si - 2] = merge;
si--;
}
}
while (si > 1) /* Exact duplicate of code in loop--keep it this way! */
{
stack_n[si - 2] += stack_n[si - 1];
left = stack[si - 2];
right = stack[si - 1];
if ((*leq)(left->data, right->data)) {
merge = left;
left = left->next;
} else {
merge = right;
right = right->next;
}
merge->next = NULL;
tail = merge;
while (1) {
if (left == NULL) {
tail->next = right;
break;
}
if (right == NULL) {
tail->next = left;
break;
}
if ((*leq)(left->data, right->data)) {
tail->next = left;
tail = left;
left = left->next;
} else {
tail->next = right;
tail = right;
right = right->next;
}
}
stack[si - 2] = merge;
si--;
}
return stack[0];
}
/*************************************************************************
void_array_search:
In: array of void pointers sorted by memory address
length of the array
void pointer we're trying to find
Out: index of the void pointer in the array, or -1 if there is no
matching pointer in the list
*************************************************************************/
int void_array_search(void **array, int n, void *to_find) {
int lo = 0;
int hi = n - 1;
int m;
while (hi - lo > 1) {
m = (hi + lo) / 2;
if (to_find == array[m]) {
return m;
} else if ((intptr_t)to_find > (intptr_t)array[m]) {
lo = m;
} else {
hi = m;
}
}
if (to_find == array[lo]) {
return lo;
}
if (to_find == array[hi]) {
return hi;
}
return -1;
}
/*************************************************************************
void_ptr_compare:
Utility function to allow sorting an array of pointers by address.
Conventions are appropriate for use with qsort.
In: void const *v1 - first pointer
void const *v2 - second pointer
Out: -1, 0, or 1 as *(void **)v1 <, =, or > *(void **)v2 resp.
*************************************************************************/
int void_ptr_compare(void const *v1, void const *v2) {
void const **v1p = (void const **)v1;
void const **v2p = (void const **)v2;
intptr_t i1 = (intptr_t) * v1p;
intptr_t i2 = (intptr_t) * v2p;
if (i1 < i2) {
return -1;
} else if (i1 > i2) {
return 1;
}
return 0;
}
/*********************************************************************
allocate_uint_array:
In: int size - length of the array to allocate
u_int value - value with which to initialize elements
Out: the newly allocated array, with all elements initialized to 'value'
***********************************************************************/
u_int *allocate_uint_array(int size, u_int value) {
u_int *arr;
if ((arr = CHECKED_MALLOC_ARRAY_NODIE(u_int, size, NULL)) == NULL) {
return NULL;
}
for (int i = 0; i < size; ++i) {
arr[i] = value;
}
return arr;
}
/*********************************************************************
allocate_ptr_array:
Allocate an array of pointers. Use free_ptr_array to free if you want the
pointers in the array to be freed as well.
In: int size - length of the array to allocate
Out: the newly allocated array, with all elements initialized to NULL.
***********************************************************************/
void **allocate_ptr_array(int size) {
if (size == 0) {
size = 1;
}
void **arr;
if ((arr = CHECKED_MALLOC_ARRAY_NODIE(void *, size, NULL)) == NULL) {
return NULL;
}
memset(arr, 0, size * sizeof(void *));
return arr;
}
/*************************************************************************
free_ptr_array:
Free an array of pointers, freeing any non-NULL pointers within the array.
In: void **pa - pointer array to free
int count - length of pointer array
Out: All non-NULL pointers in the array are freed, as is the array
itself.
**************************************************************************/
void free_ptr_array(void **pa, int count) {
for (int i = 0; i < count; ++i) {
if (pa[i] != NULL) {
free(pa[i]);
}
}
free(pa);
}
/*************************************************************************
free_num_expr_list:
Free a num_expr_list.
In: struct num_expr_list *nlist - the list to free
Out: All elements in the list are freed.
**************************************************************************/
void free_num_expr_list(struct num_expr_list *nlist) {
struct num_expr_list *nnext;
while (nlist != NULL) {
nnext = nlist->next;
free(nlist);
nlist = nnext;
}
}
/*************************************************************************
dir_exists:
Utility to check if a given directory exists.
In: char const *path - absolute or relative path of dir
Out: 1 if it's a directory, 0 if not
**************************************************************************/
int dir_exists(char const *path) {
#ifdef _MSC_VER // TODO
release_assert(false);
return false;
#else
struct stat sb;
if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
return 1;
}
return 0;
#endif
}
/*************************************************************************
is_writable_dir:
Utility to check if a given directory exists and is readable/writable.
In: char const *path - absolute or relative path of dir
Out: 1 if writable, 0 if not
**************************************************************************/
int is_writable_dir(char const *path) {
#ifdef _MSC_VER // TODO
release_assert(false);
return false;
#else
if (dir_exists(path) && !access(path, R_OK | W_OK | X_OK)) {
return 1;
}
return 0;
#endif
}
/*************************************************************************
make_parent_dir:
Utility to make the (possibly nested) parent directory of a file.
If the directory already exists. this function will
return success.
In: char const *path - absolute or relative path of file
Out: 0 on success, terminates with exit(1) on failure
**************************************************************************/
int make_parent_dir(char const *path) {
FSUtils::make_dir_for_file_w_multiple_attempts(path);
return 0;
}
/*************************************************************************
mkdirs:
Utility to make a (possibly nested) directory. Will attempt to create a
directory with full rwx permission. If the directory already exists and
has rwx permission for the user, this function will return success.
In: char const *path - absolute or relative path for dir
Out: 0 on success, 1 on failure
**************************************************************************/
int mkdirs(char const *path) {
char *pathtmp = CHECKED_STRDUP(path, "directory path");
char *curpos = pathtmp;
/* we need to skip leading '/' in case we have absolute paths */
while (curpos != NULL && *curpos == '/') {
++curpos;
}
while (curpos != NULL) {
/* Find next '/', turn it into '\0' */
char *nextel = strchr(curpos, '/');
if (nextel != NULL) {
*nextel = '\0';
}
/* if this directory exists */
if (dir_exists(pathtmp)) {
/* Turn '\0' back to '/' */
if (nextel) {
*nextel = '/';
curpos = nextel + 1;
} else {
curpos = NULL;
}
continue;
}
/* Make the directory */
if (!is_writable_dir(pathtmp) && mkdir(pathtmp, 0777) != 0) {
mcell_perror_nodie(errno, "Failed to create directory '%s'", path);
free(pathtmp);
return 1;
}
/* Turn '\0' back to '/' */
if (nextel) {
*nextel = '/';
curpos = nextel + 1;
} else {
curpos = NULL;
}
}
free(pathtmp);
return 0;
}
/*************************************************************************
open_file:
Utility to open a file, printing a sensible error message if opening
fails.
In: char const *fname - filename for new file
char const *mode - mode for file access
Out: file handle for file, NULL on error
**************************************************************************/
FILE *open_file(const char *fname, const char *mode) {
FILE *f;
if ((f = fopen(fname, mode)) == NULL) {
mcell_perror_nodie(errno, "Failed to open file %s.", fname);
return NULL;
}
return f;
}
/*************************************************************************
erfcinv:
Fast rational function approximation to inverse of the error function,
based upon algorithm for inverse of Normal cumulative distribution
function at http://home.online.no/~pjacklam/notes/invnorm/index.html
by Peter J. Acklam. Accurate to about 4e-9 in absolute value.
In: a value between 0 and 1 (not including endpoints)
Out: the value y such that erfc(y) = input value
*************************************************************************/
double erfcinv(double x) {
/* Misc constants */
static const double tail_cutoff = 0.0485;
static const double neg_twice_log_half = 1.386294361119891;
// static const double sqrt_half_pi = 1.253314137315501; /* For refinement */
static const double scaling_const = -0.7071067811865475;
/* Tail numerator */
static const double tn0 = 2.938163982698783;
static const double tn1 = 4.374664141464968;
static const double tn2 = -2.549732539343734;
static const double tn3 = -2.400758277161838;
static const double tn4 = -3.223964580411365e-1;
static const double tn5 = -7.784894002430293e-3;
/* Tail denominator */
static const double td1 = 3.754408661907416;
static const double td2 = 2.445134137142996;
static const double td3 = 3.224671290700398e-1;
static const double td4 = 7.784695709041462e-3;
/* Central numerator */
static const double cn0 = 2.506628277459239;
static const double cn1 = -3.066479806614716e1;
static const double cn2 = 1.383577518672690e2;
static const double cn3 = -2.759285104469687e2;
static const double cn4 = 2.209460984245205e2;
static const double cn5 = -3.969683028665376e1;
/* Central denominator */
static const double cd1 = -1.328068155288572e1;
static const double cd2 = 6.680131188771972e1;
static const double cd3 = -1.556989798598866e2;
static const double cd4 = 1.615858368580409e2;
static const double cd5 = -5.447609879822406e1;
double p, q, r;
if (x < tail_cutoff) {
p = sqrt(-2 * log(x) + neg_twice_log_half);
r = (tn0 + p * (tn1 + p * (tn2 + p * (tn3 + p * (tn4 + p * tn5))))) /
(1.0 + p * (td1 + p * (td2 + p * (td3 + p * td4))));
} else {
p = 0.5 * x - 0.5;
q = p * p;
r = p * (cn0 + q * (cn1 + q * (cn2 + q * (cn3 + q * (cn4 + q * cn5))))) /
(1.0 + q * (cd1 + q * (cd2 + q * (cd3 + q * (cd4 + q * cd5)))));
}
return scaling_const * r;
/*
Use the code below to refine to macine precision. Rather slow, though.
p = (erfc(scaling_const*r)-x)*sqrt_half_pi*exp(0.5*r*r);
return scaling_const*(r - p/(1 + r*p/2));
*/
}
/*************************************************************************
poisson_dist:
In: mean value
random number distributed uniformly between 0 and 1
Out: integer sampled from the Poisson distribution.
Note: This does not sample the CDF. Instead, it works its way outwards
from the peak of the PDF. Kinda weird. It is not the case
that low values of the random number will give low values. It
is also not super-efficient, but it works.
*************************************************************************/
int poisson_dist(double lambda, double p) {
int i, lo, hi;
double plo, phi, pctr;
double lambda_i;
i = (int)lambda;
pctr = exp(-lambda + i * log(lambda) -
lgamma(i + 1)); /* Highest probability bin */
if (p < pctr)
return i;
lo = hi = i;
plo = phi = pctr; /* Start at highest-probability bin and work outwards */
p -= pctr;
lambda_i = 1.0 / lambda;
while (p > 0) /* Keep going until we exhaust probabilities */
{
if (lo > 0) /* We still have a low tail, test it */
{
plo *= lo * lambda_i; /* Recursive formula for p for this bin */
lo--;
if (p < plo)
return lo;
p -= plo;
}
/* Always test the high tail (it's infinite) */
hi++;
phi = phi * lambda / hi; /* Recursive formula for p for this bin */
if (p < phi)
return hi;
p -= phi + DBL_EPSILON; /* Avoid infinite loop from poor roundoff */
}
/* should never get here */
assert(false);
return -1;
}
/*************************************************************************
byte_swap:
In: array of bytes to be swapped
size of this array
Out: array of bytes swapped so that the last byte becomes the first one, etc.
No return value
*************************************************************************/
void byte_swap(void *data, int size) {
if (size < 2){
return;
}
unsigned char temp;
unsigned char *c = (unsigned char *)data;
for (int i = 0, j = size - 1; i < j; i++, j--) {
temp = c[i];
c[i] = c[j];
c[j] = temp;
}
}
/************************************************************************\
Begin Rex's string matching code
\************************************************************************/
/*************************************************************************
wild strings have wildcard characters * ? [...] and \ as an escape char
feral strings have the same except no * character
tame strings don't have any wildcard characters
*************************************************************************/
/* Measure the length of the tame string matched by a feral string of
* length<=n*/
int feral_strlenn(char *feral, int n) {
int real_n = 0;
int i;
for (i = 0; i < n; i++) {
if (feral[i] == '\\') {
i++;
if (feral[i] == '\0')
return real_n;
} else if (feral[i] == '[') {
while (i < n && feral[i] != ']') {
if (feral[i] == '\0')
return real_n;
if (feral[i] == '\\') {
i += 2;
if (i > n || feral[i - 1] == '\0')
return real_n;
} else if (feral[i] == '-') {
i += 2;
if (i > n || feral[i - 1] == '\0')
return real_n;
} else
i++;
}
} else if (feral[i] == '\0')
return real_n;
real_n++;
}
return real_n;
}
/* Check if the first n characters in the feral string is
an abbreviation for the tame string (i.e. matches the first
part of the tame string); return 0 if not found or the number
of matched characters if they are found */
int is_feral_nabbrev(char *feral, int n, char *tame) {
char c, cc;
int i = 0;
int nfound = 0;
int ok;
if (n <= 0)
return 0;
while (*tame != '\0') {
if (feral[i] == '[') /* Try to match character set */
{
i++;
ok = 0;
while (i < n && feral[i] != ']') {
c = feral[i++];
if (c == '\0')
return 0; /* Malformed feral string */
if (c == '\\') {
if (i >= n)
return 0; /* Malformed feral string */
c = feral[i++];
if (c == '\0')
return 0; /* Malformed feral string */
}
if (i < n && feral[i] == '-') {
i++;
if (i >= n)
return 0; /* Malformed feral string */
cc = feral[i++];
if (cc == '\0')
return 0; /* Malformed feral string */
if (cc == '\\') {
if (i >= n)
return 0; /* Malformed feral string */
cc = feral[i++];
if (cc == '\0')
return 0; /* Malformed feral string */
}
if (c <= *tame && *tame <= cc) {
ok = 1;
break;
}
} else if (c == *tame) {
ok = 1;
break;
}
}
if (i >= n)
return 0; /* Malformed feral string */
if (!ok)
return 0; /* Set never matched */
tame++; /* Matched */
while (i < n && feral[i] != ']') /* Find trailing ] */
{
if (feral[i] == '\0')
return 0; /* Malformed feral string */
if (feral[i] == '\\') {
i += 2;
if (i > n || feral[i - 1] == '\0')
return 0; /* Malformed feral string */
} else
i++;
}
if (i >= n)
return 0; /* Malformed feral string */
i++;
} else /* Match single possibly escaped character */
{
c = feral[i++];
if (c == '\\') {
if (i >= n)
return 0; /* Malformed feral string */
c = feral[i++];
if (c != *tame++)
return 0; /* Mismatch */
} else if (c != *tame++ && c != '?')
return 0; /* Mismatch */
}
nfound++;
if (i >= n)
return nfound; /* Ran out of feral string--it's an abbreviation! */
}
return 0; /* Ran out of tame string with feral string left--not abbrev */
}
/* Find a substring of a tame haystack string that matches the first n
characters of the feral string needle (same syntax as strstr except using
a feral string with a length delimiter). Returns NULL if matching substring not
found. */
char *feral_strstrn(char *tame_haystack, char *feral_needle, int n) {
char c = 0;
char cc;
char set[256];
int isset = 0;
int i, j;
int scoot = 0;
for (i = 0; i < n; i++)
if (feral_needle[i] == '\0')
break;
n = i;
/* Toss leading ?'s */
i = 0;
while (feral_needle[i] == '?' && i < n && *tame_haystack != '\0') {
i++;
tame_haystack++;
scoot++;
}
if (i >= n)
return tame_haystack - scoot;
/* Beginning of needle is either a single character to match or a set of
* characters */
/* Efficiently search character set if it's first */
if (feral_needle[i] == '[') {
isset = 1;
memset(set, 0, 256);
set[0] = 1;
i++;
while (i < n && feral_needle[i] != ']') {
c = feral_needle[i++];
if (feral_needle[i] == '\0')
return NULL; /* Can't match broken pattern */
if (c == '\\') {
if (i >= n)
return NULL; /* Can't match broken pattern */
c = feral_needle[i++];
}
if (i < n && feral_needle[i] == '-') {
i++;
if (i >= n)
return NULL; /* Can't match broken pattern */
cc = feral_needle[i++];
if (cc == '\0')
return NULL; /* Can't match broken pattern */
if (cc == '\\') {
if (i >= n)
return NULL; /* Can't match broken pattern */
cc = feral_needle[i++];
if (cc == '\0')
return NULL; /* Can't match broken pattern */
}
for (j = (int)c; j <= (int)cc; j++)
set[j] = 1;
} else
set[(int)c] = 1;
}
if (i >= n)
return NULL; /* Can't match broken pattern */
i++; /* Skip ] */
} else {
c = feral_needle[i++];
if (c == '\\') {
if (i >= n)
return NULL; /* Can't match broken pattern */
c = feral_needle[i++];
}
if (c == '\0')
return NULL; /* Can't match broken pattern */
}
/* Match needle with haystack */
while (*tame_haystack != '\0') {
/* Try to match the first non-'?' character in needle with haystack */
if (isset) /* Find next position in haystack that matches a set of
characters */
{
while (!set[(int)*tame_haystack])
tame_haystack++;
if (*tame_haystack == '\0')
return NULL;
} else /* Find next position in haystack that matches a single character */
{
while (*tame_haystack != c && *tame_haystack != '\0')
tame_haystack++;
if (*tame_haystack == '\0')
return NULL;
}
if (i == n)
return tame_haystack - scoot;
else if (is_feral_nabbrev(feral_needle + i, n - i,
tame_haystack + 1)) /* Try to match the rest of
the needle */
{
return tame_haystack - scoot;
}
tame_haystack++;
}
return NULL;
}
/* Returns 1 if the wildcard string wild matches the tame string tame */
int is_wildcard_match(char *wild, char *tame) {
int nstars;
int n;
if (*wild == '\0' && *tame == '\0')
return 1;
for (n = 0, nstars = 0; wild[n] != '\0'; n++) {
if (wild[n] == '[') {
n++;
while (wild[n] != '\0' && wild[n] != ']') {
if (wild[n] == '\\') {
n++;
if (wild[n] == '\0')
return 0; /* Malformed wild string */
}
n++;
}
if (wild[n] == '\0')
return 0; /* Malformed wild string */
} else if (wild[n] == '\\') {
n++;
if (wild[n] == '\0')
return 0; /* Malformed wild string */
} else if (wild[n] == '*')
nstars++;
}
if (nstars == 0)
return (is_feral_nabbrev(wild, n, tame) == (int)strlen(tame));
else {
std::vector<int> staridx;
staridx.resize(nstars);
std::vector<int> idxA;
idxA.resize(nstars + 1);
std::vector<int> idxB;
idxB.resize(nstars + 1);
char *m;
int nidx;
int i, j;
int tail_len;
int old_length;
for (i = n = 0; wild[n] != '\0'; n++) {
if (wild[n] == '[') {
do {
n++;
if (wild[n] == '\\')
n++;
} while (wild[n] != ']');
} else if (wild[n] == '\\')
n++;
else if (wild[n] == '*')
staridx[i++] = n;
}
for (i = 0; i < nstars && staridx[i] == i; i++) {
} /* Skip over '*'s at the beginning of wild string */
if (i >= nstars)
return 1; /* All stars, of course it matches */
if (i == 0) /* First character is not a star */
{
j = is_feral_nabbrev(wild, staridx[0], tame);
if (j == 0)
return 0; /* Didn't match start string */
tame += j; /* Matched first j characters, toss them */
wild += staridx[0]; /* And advance to star */
n -= staridx[0];
for (i = nstars - 1; i >= 0; i--)
staridx[i] -= staridx[0];
}
if (staridx[nstars - 1] < n - 1) /* Last character is not a star */
{
j = staridx[nstars - 1] + 1;
tail_len = feral_strlenn(wild + j, n - j);
j = is_feral_nabbrev(wild + j, n - j, tame + (strlen(tame) - tail_len));
if (j == 0)
return 0; /* Didn't match tail string */
} else
tail_len = 0;
/* Head and tail are matched, if any. Now build rest of list to match */
nidx = 0;
for (i = 1; i < nstars; i++) {
idxA[nidx] = staridx[i - 1] + 1;
idxB[nidx] = staridx[i];
nidx++;
}
/* And now we match all the pieces */
old_length = 0;
m = tame;
for (i = 0; i < nidx; i++) {
idxB[i] -= idxA[i]; /* Calculate length of feral string */
if (idxB[i] == 0)
continue; /* Just more stars */
m = m + old_length;
m = feral_strstrn(m, wild + idxA[i], idxB[i]);
if (m == NULL)
return 0; /* Couldn't find appropriate substring */
old_length = feral_strlenn(wild + idxA[i], idxB[i]);
}
m = m + old_length;
if (strlen(m) < (size_t)tail_len)
return 0; /* Ran over tail string--no good */
return 1;
}
}
/************************************************************************\
End Rex's string matching code
\************************************************************************/
/*************************************************************************
initialize_string_buffer:
Initialize the state of a string buffer.
In: struct string_buffer *sb - the string buffer
int maxstr - the maximum number of strings to add to this buffer
Out: 0 on success; 1 if allocation fails. All fields in the buffer are
filled in.
**************************************************************************/
int initialize_string_buffer(struct string_buffer *sb, int maxstr) {
if (maxstr > 0) {
if ((sb->strings = (char **)allocate_ptr_array(maxstr)) == NULL)
mcell_allocfailed("Failed to allocate buffer of %d strings.", maxstr);
}
sb->max_strings = maxstr;
sb->n_strings = 0;
return 0;
}
/*************************************************************************
destroy_string_buffer:
Destroy the state of a string buffer.
In: struct string_buffer *sb - the string buffer
Out: The fields of the string buffer are freed, as are all strings
added to the string buffer. The string buffer itself is not freed.
**************************************************************************/
int destroy_string_buffer(struct string_buffer *sb) {
if (sb->strings) {
free_ptr_array((void **)sb->strings, sb->max_strings);
}
sb->strings = NULL;
sb->max_strings = 0;
sb->n_strings = 0;
return 0;
}
/*************************************************************************
add_string_to_buffer:
Add a string to the string buffer. The string becomes "owned" by the
buffer if this function is successful. If this function fails, it is the
caller's responsibility to free it.
In: struct string_buffer *sb - the string buffer
char *str - the string to add
Out: 0 on success; 1 if the string is not stored because the buffer is
full already.
**************************************************************************/
int add_string_to_buffer(struct string_buffer *sb, char *str) {
if (sb->n_strings >= sb->max_strings) {
mcell_internal_error("Attempt to overrun string buffer (max fill is %d).",
sb->max_strings);
/*return 1;*/
}
sb->strings[sb->n_strings++] = str;
return 0;
}
/*******************************************************************
Pointer hashes implementation
*******************************************************************/
/*************************************************************************
Initialize a pointer hash to a given initial size. Returns 0 on success.
Note that the desired table size may be exceeded. Presently, the
implementation always rounds the table size up to the nearest integer power
of two.
In: struct pointer_hash *ht - the hash table to initialize
int size - the desired table size
Out: 0 on success; 1 if memory allocation fails.
**************************************************************************/
int pointer_hash_init(struct pointer_hash *ht, int size) {
assert(size >= 0);
memset(ht, 0, sizeof(struct pointer_hash));
/* Don't allow size 0 tables. Otherwise, the key & (tablesize-1) trick fails
* spectacularly. */
if (size == 0) {
++size;
}
/* Fold size to next larger power of 2 if it isn't a power of 2 already */
if ((size) & (size - 1)) {
size |= (size >> 1);
size |= (size >> 2);
size |= (size >> 4);
size |= (size >> 8);
size |= (size >> 16);
++size;
}
/* Initialize fields */
ht->num_items = 0;
ht->table_size = size;
if ((ht->hashes = (unsigned int *)malloc(sizeof(unsigned int) *size)) ==
NULL ||
(ht->keys = (void const **)malloc(sizeof(void const *) *size)) == NULL ||
(ht->values = (void **)malloc(sizeof(void *) * size)) == NULL)
goto failure;
/* Make sure our table starts out empty */
memset(ht->hashes, 0, sizeof(unsigned int) * size);
memset(ht->keys, 0, sizeof(void *) * size);
memset(ht->values, 0, sizeof(void *) * size);
return 0;
failure:
pointer_hash_destroy(ht);
return 1;
}
/*************************************************************************
Destroy a pointer hash, freeing all memory associated with it.
In: struct pointer_hash *ht - the hash table to destroy
Out: hash table is destroyed and associated memory is freed
**************************************************************************/
void pointer_hash_destroy(struct pointer_hash *ht) {
if (ht->hashes)
free(ht->hashes);
if (ht->keys)
free(ht->keys);
if (ht->values)
free(ht->values);
ht->num_items = 0;
ht->table_size = 0;
ht->hashes = NULL;
ht->keys = NULL;
ht->values = NULL;
}
/*************************************************************************
Manually resize a pointer hash to have at least 'new_size' bins. New size
may exceed requested size. Works exactly like pointer_hash_init, except
values are copied from the old table to the new one.
In: struct pointer_hash *ht - the hash table to resize
int new_size - the desired table size
Out: 0 on success; 1 if memory allocation fails.
On failure, the hash table is left unchanged from its prior state.
**************************************************************************/
int pointer_hash_resize(struct pointer_hash *ht, int new_size) {
if (new_size == ht->table_size)
return 0;
if (new_size < ht->num_items)
return 1;
/* Save old hash, allocate new hash */
struct pointer_hash old = *ht;
if (pointer_hash_init(ht, new_size)) {
*ht = old;
return 1;
}
/* Copy items over to new hash */
for (int old_item_idx = 0; old_item_idx < old.table_size; ++old_item_idx) {
if (old.keys[old_item_idx] == NULL)
continue;
if (pointer_hash_add(ht, old.keys[old_item_idx], old.hashes[old_item_idx],
old.values[old_item_idx]))
goto failure;
}
/* Destroy the old hash */
pointer_hash_destroy(&old);
return 0;
failure:
pointer_hash_destroy(ht);
*ht = old;
return 1;
}
/*************************************************************************
Add a value to a pointer hash. If a previous item was added for that key,
the new value will replace the old value.
In: struct pointer_hash *ht - the hash table to receive a new item
void const *key - the key
unsigned int keyhash - the hash value associated with the key
void *value - the value to store
Out: 0 on success; 1 if memory allocation fails.
**************************************************************************/
int pointer_hash_add(struct pointer_hash *ht, void const *key,
unsigned int keyhash, void *value) {
/* In case pointer hash was initialized using memset, we'll allocate space
* on-demand. */
if (ht->table_size == 0) {
if (pointer_hash_resize(ht, 2))
return 1;
}
/* Make sure our table always has free space */
if (ht->num_items >= (ht->table_size >> 1)) {
if (pointer_hash_resize(ht, ht->table_size << 1))
return 1;
}
/* Scan over entries until the end of the table */
unsigned int start_index = keyhash & (ht->table_size - 1);
for (unsigned int i = 0; i < (unsigned int)ht->table_size; i++) {
unsigned int cur_index = (start_index + i) & (ht->table_size - 1);
/* Found an old value for this key. Replace it. Do not increment the item
* count. */
if (ht->keys[cur_index] == key) {
ht->values[cur_index] = value;
return 0;
}
/* Found an empty slot. Fill it. */
if (ht->keys[cur_index] == NULL) {
ht->hashes[cur_index] = keyhash;
ht->keys[cur_index] = key;
ht->values[cur_index] = value;
goto done;
}
}
/* This shouldn't happen unless the pointer hash is corrupted, since we've
* already ensured that we have enough space */
return 1;
done:
++ht->num_items;
return 0;
}
/*************************************************************************
Look up a value in a pointer hash. Returns default_value if no item was
found, or if the value associated with the key was default_value.
In: struct pointer_hash *ht - the hash table to search
void const *key - the key to find
unsigned int keyhash - the hash value associated with the key
void const *default_value - value to return if item is not found
Out: the value, or default_value if not found
**************************************************************************/
void *pointer_hash_lookup_ext(struct pointer_hash const *ht, void const *key,
unsigned int keyhash, void *default_value) {
/* Empty table. Not found. */
if (ht->table_size == 0)
return default_value;
/* Search from start position to end of table */
unsigned int start_index = keyhash & (ht->table_size - 1);
for (unsigned int i = 0; i < (unsigned int)ht->table_size; i++) {
unsigned int cur_index = (start_index + i) & (ht->table_size - 1);
/* Empty slot - key not found. */
if (ht->keys[cur_index] == NULL)
return default_value;
/* Found our value. */
if (ht->keys[cur_index] == key)
return ht->values[cur_index];
}
/* Worst case scenario. We searched the entire table. Shouldn't happen with
* the current tuning parameters, which do not permit the table to be full.
*/
return default_value;
}
/*************************************************************************
Remove a value from a pointer hash. Returns 0 if the item was
successfully removed, or 0 if the item was not found. Note that a
NULL key is not allowed in a pointer hash.
In: struct pointer_hash *ht - the hash table to remove from
void const *key - the key to remove
unsigned int keyhash - the hash value associated with the key
Out: 0 on success; 1 on failure
Regardless of success or failure, the table will remain in a valid
state.
**************************************************************************/
int pointer_hash_remove(struct pointer_hash *ht, void const *key,
unsigned int keyhash) {
/* If the key is NULL, we're done */
if (key == NULL)
return 1;
/* If the table is empty, we're done */
if (ht->table_size == 0)
return 1;
int start = keyhash & (ht->table_size - 1); /* Where do we start? */
int next_slot = -1; /* Next vacant slot to fill */
/* Scan through the table to remove the item, and resituate any
* entries which would, due to the streaming collision-avoidance
* approach, be orphaned.
*/
int cur = start;
do {
/* If we found the item to remove, remove it */
if (key != NULL && ht->keys[cur] == key) {
/* Clear this value */
ht->keys[cur] = NULL;
ht->values[cur] = NULL;
ht->hashes[cur] = 0;
--ht->num_items;
if (ht->table_size > (ht->num_items << 2)) {
/* If resizing the pointer hash succeeded, we don't need to do
* any more work, since it will have prevented orphans. */
if (!pointer_hash_resize(ht, ht->num_items << 1))
return 0;
}
/* We may need to move something into this empty slot, so
* remember where we were. */
next_slot = cur;
/* This indicates that we've already removed the value and are
* now just fixing the table contents */
key = NULL;
}
/* We found a NULL entry, so stop scanning -- the table is in a
* valid state */
else if (ht->keys[cur] == NULL) {
if (key == NULL)
return 0;
else
return 1;
}
/* This entry may need to be reseated */
else if (next_slot != -1) {
/* This is the slot where we'd start looking for this entry */
int desiredSlot = ht->hashes[cur] & (ht->table_size - 1);
/* If we would have hit our newly introduced NULL entry after we
* started searching for this entry, but before we found what we
* were looking for, resituate this entry.
*/
if ((next_slot < cur &&
(desiredSlot <= next_slot || desiredSlot > cur)) ||
(next_slot > cur &&
(desiredSlot <= next_slot && desiredSlot > cur))) {
/* Move this entry to its new location */
ht->hashes[next_slot] = ht->hashes[cur];
ht->keys[next_slot] = ht->keys[cur];
ht->values[next_slot] = ht->values[cur];
/* Free this slot */
ht->hashes[cur] = 0;
ht->keys[cur] = NULL;
ht->values[cur] = NULL;
/* We may need to move something into this empty slot, so
* remember where we were. */
next_slot = cur;
}
}
/* Advance to the next entry */
if (++cur == ht->table_size)
cur = 0;
} while (cur != start);
/* If we found our entry, success, else failure. */
if (key == NULL)
return 0;
else
return 1;
}
/*************************************************************************
remove_both_duplicates:
In: sorted linked list containing void pointers
Out: if linked list contains two duplicates they are both removed
Returns number of unique items in the linked list
after removal
Note: linked list should be sorted in advance.
Also this function is used in the way that we do not expect more
than two duplicates.
Example: input = (a,b,c,d,d, e,f,g)
output = (a,b,c,e,f,g)
*************************************************************************/
int remove_both_duplicates(struct void_list **head) {
struct void_list *curr = *head, *tmp, *prev, *next_Next;
int count = 0;
tmp = curr;
prev = NULL;
while ((tmp != NULL) && (tmp->next != NULL)) {
if (tmp->data == tmp->next->data) {
next_Next = tmp->next->next;
free(tmp->next);
free(tmp);
tmp = next_Next;
if (prev != NULL) {
prev->next = tmp;
} else {
curr = tmp;
}
} else {
prev = tmp;
tmp = tmp->next; /* only advance if there is no deletion */
}
}
*head = curr;
for (tmp = *head; tmp != NULL; tmp = tmp->next) {
count++;
}
return count;
}
/*********************************************************************
delete_void_list:
In: linked list
Out: none. The memory is freed.
*********************************************************************/
void delete_void_list(struct void_list *head) {
struct void_list *nnext;
while (head != NULL) {
nnext = head->next;
free(head);
head = nnext;
}
}
/*************************************************************************
double_cmp:
Comparison function for doubles, to be passed to qsort.
In: i1: first item for comparison
i2: second item for comparison
Out: -1, 0, or 1 if the first item is less than, equal to, or greater than the
second, resp.
*************************************************************************/
int double_cmp(void const *i1, void const *i2) {
double const *d1 = (double const *)i1;
double const *d2 = (double const *)i2;
if (*d1 < *d2)
return -1;
else if (*d1 > *d2)
return 1;
else
return 0;
}
/**************************************************************************
is_string_present_in_string_array:
In: string "str"
array of strings "strings"
length of the array of strings "length"
Out: Return 1 if string "str" is present in the array of strings "strings",
and 0 otherwise.
**************************************************************************/
int is_string_present_in_string_array(const char * str, char ** strings, int length)
{
int found = 0, i;
for (i = 0; i < length; i++) {
if (strcmp(str, strings[i]) == 0) {
found = 1;
break;
}
}
return found;
}
/******************************************************************************
convert_seconds_to_iterations:
Converts time in seconds to iterations. This is offset by the number of
iterations at the start of the simulation, which is usually 0 unless you're
checkpointing. Alternatively, this function could be thought of as converting
seconds to the internal/scaled time (i.e. the time in units of the timestep),
but this doesn't really make sense if one changes the timestep during a
checkpointing event (e.g. 1e-6 to 1e-7 seconds).
*****************************************************************************/
double convert_seconds_to_iterations(
long long start_iterations,
double time_step_seconds,
double simulation_start_seconds,
double seconds) {
double delta_iterations =
(seconds - simulation_start_seconds) / time_step_seconds;
return (start_iterations + delta_iterations);
}
/******************************************************************************
convert_iterations_to_seconds:
As you might imagine, this is essentially the inverse of
convert_seconds_to_iterations.
NOTE: Do not use iteration values that happened in the past or delta iteration
values. Only input values that are greater the starting number of iterations
In other words, use either the current number of iterations or some number
corresponding to some time in the future.
*****************************************************************************/
double convert_iterations_to_seconds(
long long start_iterations,
double time_step_seconds,
double simulation_start_seconds,
double iterations) {
// Probably should add an assert here
double delta_time = (iterations - start_iterations) * time_step_seconds;
return (simulation_start_seconds + delta_time);
}
/*************************************************************************
generate_range:
Generate a num_expr_list containing the numeric values from start to end,
incrementing by step.
In: state: the simulation state
list: destination to receive list of values
start: start of range
end: end of range
step: increment
Out: 0 on success, 1 on failure. On success, list is filled in.
*************************************************************************/
int generate_range(struct num_expr_list_head *list, double start, double end,
double step) {
list->value_head = NULL;
list->value_tail = NULL;
list->value_count = 0;
list->shared = 0;
if (step > 0) {
/* JW 2008-03-31: In the guard on the loop below, it seems to me that
* the third condition is redundant with the second.
*/
for (double tmp_dbl = start;
tmp_dbl < end || !distinguishable(tmp_dbl, end, EPS_C) ||
fabs(end - tmp_dbl) <= EPS_C;
tmp_dbl += step) {
if (advance_range(list, tmp_dbl))
return 1;
}
} else /* if (step < 0) */
{
/* JW 2008-03-31: In the guard on the loop below, it seems to me that
* the third condition is redundant with the second.
*/
for (double tmp_dbl = start;
tmp_dbl > end || !distinguishable(tmp_dbl, end, EPS_C) ||
fabs(end - tmp_dbl) <= EPS_C;
tmp_dbl += step) {
if (advance_range(list, tmp_dbl))
return 1;
}
}
// MCell4
list->start_end_step_set = true;
list->start = start;
list->end = end;
list->step = step;
return 0;
}
// Maybe move this somewhere else
int advance_range(struct num_expr_list_head *list, double tmp_dbl) {
struct num_expr_list *nel;
nel = CHECKED_MALLOC_STRUCT(struct num_expr_list, "numeric list");
if (nel == NULL) {
free_numeric_list(list->value_head);
list->value_head = list->value_tail = NULL;
return 1;
}
nel->value = tmp_dbl;
nel->next = NULL;
++list->value_count;
if (list->value_tail != NULL)
list->value_tail->next = nel;
else
list->value_head = nel;
list->value_tail = nel;
return 0;
}
/*************************************************************************
free_numeric_list:
Free a num_expr_list.
In: nel: the list to free
Out: all elements are freed
*************************************************************************/
void free_numeric_list(struct num_expr_list *nel) {
while (nel != NULL) {
struct num_expr_list *n = nel;
nel = nel->next;
free(n);
}
}
#define hashsize(n) ((ub4)1 << (n))
/* ================ Bob Jenkin hash function ======================== */
/*--------------------------------------------------------------------
mix -- mix 3 32-bit values reversibly.
For every delta with one or two bits set, and the deltas of all three
high bits or all three low bits, whether the original value of a,b,c
is almost all zero or is uniformly distributed,
* If mix() is run forward or backward, at least 32 bits in a,b,c
have at least 1/4 probability of changing.
* If mix() is run forward, every bit of c will change between 1/3 and
2/3 of the time. (Well, 22/100 and 78/100 for some 2-bit deltas.)
mix() was built out of 36 single-cycle latency instructions in a
structure that could supported 2x parallelism, like so:
a -= b;
a -= c; x = (c>>13);
b -= c; a ^= x;
b -= a; x = (a<<8);
c -= a; b ^= x;
c -= b; x = (b>>13);
...
Unfortunately, superscalar Pentiums and Sparcs can't take advantage
of that parallelism. They've also turned some of those single-cycle
latency instructions into multi-cycle latency instructions. Still,
this is the fastest good hash I could find. There were about 2^^68
to choose from. I only looked at a billion or so.
--------------------------------------------------------------------*/
#define mix(a, b, c) \
{ \
a -= b; \
a -= c; \
a ^= (c >> 13); \
b -= c; \
b -= a; \
b ^= (a << 8); \
c -= a; \
c -= b; \
c ^= (b >> 13); \
a -= b; \
a -= c; \
a ^= (c >> 12); \
b -= c; \
b -= a; \
b ^= (a << 16); \
c -= a; \
c -= b; \
c ^= (b >> 5); \
a -= b; \
a -= c; \
a ^= (c >> 3); \
b -= c; \
b -= a; \
b ^= (a << 10); \
c -= a; \
c -= b; \
c ^= (b >> 15); \
}
/*--------------------------------------------------------------------
hash() -- hash a variable-length key into a 32-bit value
k : the key (the unaligned variable-length array of bytes)
len : the length of the key, counting by bytes
initval : can be any 4-byte value
Returns a 32-bit value. Every bit of the key affects every bit of
the return value. Every 1-bit and 2-bit delta achieves avalanche.
About 6*len+35 instructions.
The best hash table sizes are powers of 2. There is no need to do
mod a prime (mod is sooo slow!). If you need less than 32 bits,
use a bitmask. For example, if you need only 10 bits, do
h = (h & hashmask(10));
In which case, the hash table should have hashsize(10) elements.
If you are hashing n strings (ub1 **)k, do it like this:
for (i=0, h=0; i<n; ++i) h = hash(k[i], len[i], h);
By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use this
code any way you wish, private, educational, or commercial. It's free.
See http://burtleburtle.net/bob/hash/evahash.html
Use for hash table lookup, or anything where one collision in 2^^32 is
acceptable. Do NOT use for cryptographic purposes.
--------------------------------------------------------------------*/
ub4 jenkins_hash(ub1 *k, ub4 length) {
ub4 a, b, c, len, initval;
/* Set up the internal state */
initval = 0;
len = length;
a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
c = initval; /* the previous hash value */
length++;
/*---------------------------------------- handle most of the key */
while (len >= 12) {
a += (k[0] + ((ub4)k[1] << 8) + ((ub4)k[2] << 16) + ((ub4)k[3] << 24));
b += (k[4] + ((ub4)k[5] << 8) + ((ub4)k[6] << 16) + ((ub4)k[7] << 24));
c += (k[8] + ((ub4)k[9] << 8) + ((ub4)k[10] << 16) + ((ub4)k[11] << 24));
mix(a, b, c);
k += 12;
len -= 12;
}
/*------------------------------------- handle the last 11 bytes */
c += length;
switch (len) /* all the case statements fall through */
{
case 11:
c += ((ub4)k[10] << 24); /* fallthrough */
case 10:
c += ((ub4)k[9] << 16); /* fallthrough */
case 9:
c += ((ub4)k[8] << 8); /* fallthrough */
/* the first byte of c is reserved for the length */
case 8:
b += ((ub4)k[7] << 24); /* fallthrough */
case 7:
b += ((ub4)k[6] << 16); /* fallthrough */
case 6:
b += ((ub4)k[5] << 8); /* fallthrough */
case 5:
b += k[4]; /* fallthrough */
case 4:
a += ((ub4)k[3] << 24); /* fallthrough */
case 3:
a += ((ub4)k[2] << 16); /* fallthrough */
case 2:
a += ((ub4)k[1] << 8); /* fallthrough */
case 1:
a += k[0]; /* fallthrough */
/* case 0: nothing left to add */
}
mix(a, b, c);
/*-------------------------------------------- report the result */
return (c);
}
// initializer list for rusage causes many compilation warnings when used
void reset_rusage(rusage* r) {
r->ru_utime.tv_sec = 0;
r->ru_utime.tv_usec = 0;
r->ru_stime.tv_sec = 0;
r->ru_stime.tv_usec = 0;
}
#ifdef _MSC_VER
int _win_rename(const char *old, const char *new_name) {
DWORD dwAttrib = GetFileAttributes(new_name);
if (dwAttrib != INVALID_FILE_ATTRIBUTES &&
!(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) {
/* new_name file exists */
if (ReplaceFile(new_name, old, NULL, REPLACEFILE_WRITE_THROUGH, NULL, NULL)) {
return 0;
}
/* fixme: set errno based on GetLastError() [possibly doing some filtering
* before] */
errno = EACCES;
return -1;
} else {
return rename(old, new_name);
}
}
#endif
| C |
3D | mcellteam/mcell | src/edge_util.h | .h | 1,651 | 48 | /******************************************************************************
*
* Copyright (C) 2006-2017,2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
/* Temporary data stored about an edge of a polygon */
struct poly_edge {
struct poly_edge *next; /* Next edge in a hash table. */
double v1x; /* X coord of starting point */
double v1y; /* Y coord of starting point */
double v1z; /* Z coord of starting point */
double v2x; /* X coord of ending point */
double v2y; /* Y coord of ending point */
double v2z; /* Z coord of ending point */
int face[2]; /* wall indices on side of edge */
int edge[2]; /* which edge of wall1/2 are we? */
int n; /* How many walls share this edge? */
};
/* Hash table for rapid order-invariant lookup of edges. */
struct edge_hashtable {
struct poly_edge *data; /* Array of polygon edges */
int nkeys; /* Length of array */
int stored; /* How many things do we have in the table? */
int distinct; /* How many of those are distinct? */
};
int edge_equals(struct poly_edge *e1, struct poly_edge *e2);
int edge_hash(struct poly_edge *pe, int nkeys);
int ehtable_init(struct edge_hashtable *eht, int nkeys);
int ehtable_add(struct edge_hashtable *eht, struct poly_edge *pe);
void ehtable_kill(struct edge_hashtable *eht);
| Unknown |
3D | mcellteam/mcell | src/pymcell_helpers.py | .py | 48,110 | 1,298 | """pyMCell helper functions.
Currently, this contains a mix of the original pyMCell functions and classes
and a set of more refined intuitive functions and classes. Future versions will
provide a cleaner separation between these two with the aim of eventually
deprecating or removing the original ones.
"""
import pymcell as m
from typing import List, Dict, Iterable, Tuple, Any
import logging
from enum import Enum
# import uuid
import random
class Orient(Enum):
up = 1
down = 2
mix = 3
class SC(Enum):
reflect = 1
transp = 2
absorb = 3
conc_clamp = 3
class MolType(Enum):
surface_mols = 1
volume_mols = 2
all_mols = 3
def single_true(iterable):
i = iter(iterable)
return any(i) and not any(i)
class MeshObj:
""" An entire polygon geom_object and its associated surface regions. """
def __init__(
self,
name: str,
vert_list: List[Tuple[float, float, float]],
face_list: List[Tuple[int, int, int]],
translation: Tuple[float, float, float] = None) -> None:
self.name = name
self.vert_list = vert_list
self.face_list = face_list
self.regions = [] # type: List[SurfaceRegion]
self.translation = translation
logging.info("Creating mesh geom_object '%s'" % name)
def __str__(self):
return self.name
class Species:
""" A type of molecule.
Surface molecules have names, diffusion constants , and can either be a
surface molecule (embedded in a membrane) or a volume molecule (e.g. free
in the cytocol). The units for the diffusion constant is cm2/s. An
instance of Species is still a *type* of molecule, not an individual
molecule. For example, an instance of Species could be the ACh Species, but
it would not be an individual ACh molecule.
"""
def __init__(
self,
name: str,
diffusion_constant: float,
surface: bool = False) -> None:
self.name = name
self.diffusion_constant = diffusion_constant
self.surface = surface
vol_surf = "surface" if surface else "volume"
logging.info("Creating %s species '%s'" % (vol_surf, name))
def up(self):
return OrientedSpecies(self, Orient.up)
def down(self):
return OrientedSpecies(self, Orient.down)
def mix(self):
return OrientedSpecies(self, Orient.mix)
def __str__(self):
return self.name
class OrientedSpecies:
""" A type of molecule with an orientation.
This is like a normal Species geom_object, but it also contains information
about its relative orientation (up, down, or mixed) with respect to a
surface membrane.
"""
def __init__(
self,
spec: Species,
orient: Orient) -> None:
self.spec = spec
odict_str = {Orient.up: "'", Orient.down: ",", Orient.mix: ";"}
odict_num = {Orient.up: 1, Orient.down: -1, Orient.mix: 0}
self.orient = orient
self.orient_num = odict_num[orient]
self.orient_str = odict_str[orient]
self.name = self.spec.name + self.orient_str
def __str__(self):
return self.name
class Reaction:
""" A reaction involving one or more molecules.
ex: vm1 -> vm2 + vm3 [1e3]
- Can be unimolecular or bimolecular.
- Involves surface and/or volume molecules.
- If a single surface molecule is involved, then all species in the
reaction must be OrientedSpecies.
"""
def __init__(
self,
reactants: List[Any], # List of Species or OrientedSpecies
products: List[Any], # List of Species or OrientedSpecies
rate_constant: float,
bkwd_rate_constant=None,
name=None) -> None:
self.reactants = reactants
self.products = products
self.rate_constant = rate_constant
self.bkwd_rate_constant = bkwd_rate_constant
self.name = name
# These variable names are terrible...
# reactants_so = all(isinstance(r, m.OrientedSpecies) for r in reactants)
# products_so = all(isinstance(p, m.OrientedSpecies) for p in products)
# reactants_s = all(isinstance(r, m.Species) for r in reactants)
# products_s = all(isinstance(p, m.Species) for p in products)
# if (reactants_so and (products_so or not products)) or (reactants_s and products_s):
# # make sure either everything is oriented (aside from possible NULL
# # product) or nothing is.
# pass
# else:
# logging.info(
# "Mixing oriented with non oriented species in reaction")
try:
reactant_names = [r.name for r in reactants]
reactants_str = " + ".join(reactant_names)
except TypeError:
# must be unimolecular
reactants_str = reactants.name
try:
if products:
product_names = [p.name for p in products]
products_str = " + ".join(product_names)
else:
products_str = "NULL"
except TypeError:
products_str = products.name
arrow = "<->" if bkwd_rate_constant else "->"
self.print_friendly_repr = ""
if bkwd_rate_constant:
self.print_friendly_repr = "%s <-> %s [%.2E, %.2E]" % (reactants_str, products_str, rate_constant, bkwd_rate_constant)
else:
self.print_friendly_repr = "%s -> %s [%.2E]" % (reactants_str, products_str, rate_constant)
logging.info("Creating reaction %s" % self.print_friendly_repr)
def __str__(self):
return self.name
class SurfaceRegion:
""" Subsets of a surface.
Examples of uses: molecules can be released on to these and surface classes
can be assigned to them.
"""
def __init__(self,
mesh_obj: MeshObj,
reg_name: str,
surf_reg_face_list: List) -> None:
self.reg_name = reg_name
self.full_reg_name = "%s[%s]" % (mesh_obj.name, reg_name)
self.surf_reg_face_list = surf_reg_face_list
# Relationship is symmetrical. Every region knows its geom_object. Object
# knows its regions.
self.mesh_obj = mesh_obj
mesh_obj.regions.append(self)
logging.info("Creating region '%s'" % self.reg_name)
def __str__(self):
return self.reg_name
class ListRelease:
""" A release of molecules specified as a series of XYZ coordinates. """
def __init__(
self,
spec,
pos_list: Iterable[Tuple[float, float, float]])-> None:
self.spec = spec
self.pos_list = pos_list
logging.info("Creating list release")
class ObjectRelease:
""" An entire polygon geom_object and its associated surface regions. """
def __init__(
self,
spec,
number: int = None,
conc: float = None,
density: float = None,
mesh_obj: MeshObj = None,
region: SurfaceRegion = None) -> None:
if not single_true((number, conc, density)):
raise Exception(
"Multiple release methods (e.g. number and conc) specified")
self.spec = spec
self.number = number
self.conc = conc
self.density = density
self.region = region
self.what_in_where = ""
if self.region:
self.mesh_obj = self.region.mesh_obj
self.what_in_where = "{} in/on {}".format(self.spec.name, self.region.reg_name)
else:
self.mesh_obj = mesh_obj
self.what_in_where = "{} in/on {}".format(self.spec.name, self.mesh_obj.name)
logging.info("Creating release of {}".format(self.what_in_where))
class Vector3:
""" Just a generic 3d vector to be used for positions and whatnot. """
def __init__(self, x: float = 0.0, y: float = 0.0, z: float = 0.0) -> None:
self.x = x
self.y = y
self.z = z
def __str__(self):
return "({}, {}, {})".format(self.x, self.y, self.z)
class SurfaceClass:
""" A SurfaceClass describes how species interact with various surfaces.
ex: Species x are absorbed when they hit the front of a surface.
"""
def __init__(
self, sc_type: SC, species, name=None) -> None:
self.sc_type = sc_type
self.species = species
sc_dict = {SC.transp: "transparent", SC.reflect: "reflective", SC.absorb: "absorptive" }
if name:
self.name = name
else:
self.name = "{}_{}".format(sc_dict[sc_type], species.name)
logging.info(
"Creating surface class that is {} to {}".format(sc_dict[sc_type], species.name))
def __str__(self):
return self.name
class MCellSim:
""" The main class required to run a pyMCell simulation. """
def __init__(self, seed: int) -> None:
self._world = m.mcell_create()
self._started = False
# the value for _species & _surface_classes is a swig wrapped sym_entry
self._species = {} # type: Dict[str, Any]
self._surface_classes = {} # type: Dict[str, Any]
# the value for _mesh_objects is a swig wrapped "geom_object"
self._mesh_objects = {} # type: Dict[str, Any]
# the value for _mesh_objects is a swig wrapped "region"
self._regions = {} # type: Dict[str, Any]
self._releases = {} # type: Dict[str, Any]
self._counts = {} # type: Dict[str, Any]
self._iterations = 0
self._current_iteration = 0
self._finished = False
self._output_freq = 10
self._seed = seed
m.mcell_set_seed(self._world, seed)
# m.mcell_silence_notifications(self._world)
m.mcell_init_state(self._world)
# This is the top level instance geom_object. We just call it "Scene" here
# to be consistent with the MDL output from Blender.
self.scene_name = "Scene"
self._scene = m.create_instance_object(self._world, self.scene_name)
# this is different than _species. instead of swig wrapped sym_entry,
# this contains Species objects
self.species = {}
# These allow you to have surface properties affect all molecules.
self._all_mol_sym = m.mcell_get_all_mol_sym(self._world)
self._species['ALL_MOLECULES'] = self._all_mol_sym
self._all_volume_mol_sym = m.mcell_get_all_volume_mol_sym(self._world)
self._species['ALL_VOLUME_MOLECULES'] = self._all_volume_mol_sym
self._all_surface_mol_sym = m.mcell_get_all_mol_sym(self._world)
self._species['ALL_SURFACE_MOLECULES'] = self._all_surface_mol_sym
def __str__(self):
return self.scene_name
def __del__(self):
self.end_sim()
def dump(self):
mcell_dump_state(self._world)
def silence_warnings(self):
m.mcell_silence_warnings(self._world)
def silence_notifications(self):
m.mcell_silence_notifications(self._world)
def enable_logging(self):
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
def set_output_freq(self, output_freq: int) -> None:
""" The interval of iterations to create reaction data output.
For example, if you set this to 10, reaction data would be created at
every 10th iteration.
"""
self._output_freq = output_freq
def set_time_step(self, time_step: float) -> None:
""" Set time step in seconds. """
m.mcell_set_time_step(self._world, time_step)
def set_iterations(self, iterations: int) -> None:
""" Set number of iterations """
m.mcell_set_iterations(self._world, iterations)
self._iterations = iterations
# def set_seed(self, seed):
# self._seed = seed
# m.mcell_set_seed(self._world, seed)
def add_single_species(self, spec):
if spec.name not in self._species:
spec_sym = m.create_species(
self._world, spec.name, spec.diffusion_constant, spec.surface)
self._species[spec.name] = spec_sym
self.species[spec.name] = spec
logging.info("Add species '%s' to simulation" % spec.name)
def add_species(self, spec):
if isinstance(spec, m.Species):
self.add_single_species(spec)
else:
for s in spec:
self.add_single_species(s)
def add_reaction(self, rxn: Reaction) -> None:
""" Add a Reaction geom_object to the simulation. """
r_spec_list = None
p_spec_list = None
# Figure out if it's an iterable of reactants or a single reactant
try:
for r in rxn.reactants:
if isinstance(r, m.OrientedSpecies):
r_sym = self._species[r.spec.name]
r_spec_list = m.mcell_add_to_species_list(
r_sym, True, r.orient_num, r_spec_list)
else:
r_sym = self._species[r.name]
r_spec_list = m.mcell_add_to_species_list(
r_sym, False, 0, r_spec_list)
except TypeError:
r = rxn.reactants
if isinstance(r, m.OrientedSpecies):
r_sym = self._species[r.spec.name]
r_spec_list = m.mcell_add_to_species_list(
r_sym, True, r.orient_num, r_spec_list)
else:
r_sym = self._species[r.name]
r_spec_list = m.mcell_add_to_species_list(
r_sym, False, 0, r_spec_list)
try:
for p in rxn.products:
if isinstance(r, m.OrientedSpecies):
p_sym = self._species[p.spec.name]
p_spec_list = m.mcell_add_to_species_list(
p_sym, True, p.orient_num, p_spec_list)
else:
p_sym = self._species[p.name]
p_spec_list = m.mcell_add_to_species_list(
p_sym, False, 0, p_spec_list)
except TypeError:
p = rxn.products
if isinstance(r, m.OrientedSpecies):
p_sym = self._species[p.spec.name]
p_spec_list = m.mcell_add_to_species_list(
p_sym, True, p.orient_num, p_spec_list)
else:
p_sym = self._species[p.name]
p_spec_list = m.mcell_add_to_species_list(
p_sym, False, 0, p_spec_list)
logging.info("Add reaction '%s' to simulation" % rxn.print_friendly_repr)
m.create_reaction(
self._world,
r_spec_list,
p_spec_list,
rxn.rate_constant,
rxn.bkwd_rate_constant,
name=rxn.name)
def add_geometry(self, mesh_obj: MeshObj) -> None:
""" Add a mesh geom_object to the simulation. """
mesh = m.create_polygon_object(
self._world,
mesh_obj.vert_list,
mesh_obj.face_list,
self._scene,
mesh_obj.name,
mesh_obj.translation)
if mesh_obj.name not in self._mesh_objects:
self._mesh_objects[mesh_obj.name] = mesh
for reg in mesh_obj.regions:
region_swig_obj = m.create_surface_region(
self._world, mesh, reg.surf_reg_face_list, reg.reg_name)
full_reg_name = "%s[%s]" % (mesh_obj.name, reg.reg_name)
if reg.reg_name not in self._regions:
self._regions[full_reg_name] = region_swig_obj
logging.info("Add geometry '%s' to simulation" % mesh_obj.name)
def add_viz(self, species: Iterable[Species], ascii_output = False) -> None:
""" Set all the species in an Iterable to be visualized. """
viz_list = None
for spec in species:
viz_list = m.mcell_add_to_species_list(
self._species[spec.name], False, 0, viz_list)
logging.info("Output '%s' for viz data." % spec.name)
m.mcell_create_viz_output(
self._world, "./viz_data/seed_%04i/Scene" % self._seed, viz_list,
0, self._iterations, 1, ascii_output)
def release(self, relobj):
""" Release molecules in/on an geom_object or as a ListRelease. """
if isinstance(relobj, ObjectRelease):
self.release_into_mesh_obj(relobj)
logging.info("Add release of '%s' to simulation" % relobj.what_in_where)
elif isinstance(relobj, ListRelease):
self.release_as_list(relobj.spec, relobj.pos_list)
logging.info("Add list release to simulation")
else:
raise ValueError("Invalid release site type")
def release_as_list(self, spec, pos_list):
length_pos_list = len(pos_list)
try:
spec_list = []
surf_flags = []
orient = []
for s in spec:
if isinstance(s, OrientedSpecies):
spec_list.append(self._species[s.spec.name])
surf_flags.append(True)
orient.append(s.orient_num)
else:
spec_list.append(self._species[s.spec.name])
surf_flags.append(False)
orient.append(0)
except TypeError:
if isinstance(spec, OrientedSpecies):
spec_sym = self._species[spec.spec.name]
spec_list = [spec_sym] * length_pos_list
surf_flags = [True] * length_pos_list
orient = [spec.orient_num] * length_pos_list
else:
spec_sym = self._species[spec.name]
surf_flags = None
orient = None
spec_list = [spec_sym] * length_pos_list
# XXX: HACK. This is definitely not guaranteed to be unique, but I
# can't UUID to work for some reason
rel_name = "rel_{}".format(random.randint(1,1000))
# rel_name = "rel_{}".format(uuid.uuid1())
x_pos = []
y_pos = []
z_pos = []
for pos in pos_list:
x_pos.append(pos[0])
y_pos.append(pos[1])
z_pos.append(pos[2])
(rel_obj, return_status) = m.create_list_release_site(
self._world, self._scene, spec_list, x_pos, y_pos, z_pos,
rel_name, surf_flags=surf_flags, orientations=orient)
if rel_name not in self._releases:
self._releases[rel_name] = (rel_obj, return_status)
def release_into_mesh_obj(self, relobj) -> None:
""" Release the specified amount of species into an geom_object. """
mesh_obj = relobj.mesh_obj
species = relobj.spec
region = relobj.region
if isinstance(species, m.OrientedSpecies):
orient = species.orient_num
species = species.spec
else:
orient = None
if species.surface and orient is None:
logging.info(
"Error: must specify orientation when releasing surface "
"molecule")
if region:
rel_name = "%s_%s_%s_rel" % (
species.name, mesh_obj.name, region.reg_name)
else:
rel_name = "%s_%s_rel" % (species.name, mesh_obj.name)
mol_sym = self._species[species.name]
if orient:
mol_list = m.mcell_add_to_species_list(mol_sym, True, orient, None)
else:
mol_list = m.mcell_add_to_species_list(mol_sym, False, 0, None)
rel_object = m.geom_object()
if relobj.number:
number_type = 0
rel_amt = relobj.number
elif relobj.conc:
number_type = 1
rel_amt = relobj.conc
if region:
reg_name = region.reg_name
else:
reg_name = "ALL"
release_object = m.mcell_create_region_release(
self._world, self._scene, self._mesh_objects[mesh_obj.name],
rel_name, reg_name, mol_list, float(rel_amt),
number_type, 1, None, rel_object)
if rel_name not in self._releases:
self._releases[rel_name] = release_object
m.mcell_delete_species_list(mol_list)
# logging.info("Creating release site '%s'" % rel_name)
def create_release_site(
self, species: Species, count: int, shape: str,
pos_vec3: Vector3 = None, diam_vec3=None) -> None:
""" Create a spherical/cubic release site. """
if pos_vec3 is None:
pos_vec3 = m.Vector3()
if diam_vec3 is None:
diam_vec3 = m.Vector3()
species_sym = self._species[species.name]
rel_name = "%s_%s_rel" % (species.name, shape)
if shape == "spherical":
shape = m.SHAPE_SPHERICAL
elif shape == "cubic":
shape = m.SHAPE_CUBIC
position, diameter, release_object = m.create_release_site(
self._world, self._scene, pos_vec3, diam_vec3, shape,
count, 0, species_sym, rel_name)
if rel_name not in self._releases:
self._releases[rel_name] = (position, diameter, release_object)
def add_partitions(
self, axis: str, start: float, stop: float, step: float) -> None:
""" Add partitions to speed up the simulation. """
if axis == "x":
axis_num = 0
elif axis == "y":
axis_num = 1
elif axis == "z":
axis_num = 2
m.create_partitions(self._world, axis_num, start, stop, step)
def add_count(self, species: Species, mesh_obj: MeshObj = None, reg: SurfaceRegion = None) -> None:
""" Set a species (possibly in/on a surface) to be counted """
species_sym = self._species[species.name]
if mesh_obj:
mesh = self._mesh_objects[mesh_obj.name]
mesh_sym = m.mcell_get_obj_sym(mesh)
count_str = "react_data/seed_%04d/%s_%s" % (
self._seed, species.name, mesh_obj.name)
count_list, os, out_times, output = m.create_count(
self._world, mesh_sym, species_sym, count_str, 1e-5)
elif reg:
reg_swig_obj = self._regions[reg.full_reg_name]
reg_sym = m.mcell_get_reg_sym(reg_swig_obj)
count_str = "react_data/seed_%04d/%s_%s_%s" % (
self._seed, species.name, reg.mesh_obj.name, reg.reg_name)
count_list, os, out_times, output = m.create_count(
self._world, reg_sym, species_sym, count_str, 1e-5)
else:
count_str = "react_data/seed_%04d/%s_WORLD" % (
self._seed, species.name)
count_list, os, out_times, output = m.create_count(
self._world, None, species_sym, count_str, 1e-5)
self._counts[count_str] = (count_list, os, out_times, output)
def add_rxn_count(self, rxn_name: str, mesh_obj: MeshObj = None, reg: SurfaceRegion = None) -> None:
""" Set a species (possibly in/on a surface) to be counted """
if mesh_obj:
mesh = self._mesh_objects[mesh_obj.name]
mesh_sym = m.mcell_get_obj_sym(mesh)
count_str = "react_data/seed_%04d/%s_%s" % (
self._seed, species.name, mesh_obj.name)
count_list, os, out_times, output = m.create_rxn_count(
self._world, mesh_sym, rxn_name, count_str, 1e-5)
elif reg:
reg_swig_obj = self._regions[reg.full_reg_name]
reg_sym = m.mcell_get_reg_sym(reg_swig_obj)
count_str = "react_data/seed_%04d/%s_%s_%s" % (
self._seed, species.name, reg.mesh_obj.name, reg.reg_name)
count_list, os, out_times, output = m.create_rxn_count(
self._world, reg_sym, rxn_name, count_str, 1e-5)
else:
count_str = "react_data/seed_%04d/%s_WORLD" % (
self._seed, species.name)
count_list, os, out_times, output = m.create_rxn_count(
self._world, None, rxn_name, count_str, 1e-5)
self._counts[count_str] = (count_list, os, out_times, output)
def _get_sc_type(self, sc_type):
if sc_type == SC.reflect:
sc_type = m.RFLCT
elif sc_type == SC.transp:
sc_type = m.TRANSP
elif sc_type == SC.absorb:
sc_type = m.SINK
return sc_type
def assign_surface_property_to_all_mols(self, sc_name, sc_type, region, moltype=MolType.all_mols):
sc_type = self._get_sc_type(sc_type)
if moltype == MolType.surface_mols:
moltype = 'ALL_SURFACE_MOLECULES'
elif moltype == MolType.volume_mols:
moltype = 'ALL_VOLUME_MOLECULES'
elif moltype == MolType.all_mols:
moltype = 'ALL_MOLECULES'
try:
sc_sym = self._surface_classes[sc_name]
except KeyError:
sc_sym = m.create_surf_class(self._world, sc_name)
self._surface_classes[sc_name] = sc_sym
spec_sym = self._species[moltype]
# XXX: add support for orientation
m.mcell_add_surf_class_properties(
self._world, sc_type, sc_sym, spec_sym, 0)
region_swig_obj = self._regions[region.full_reg_name]
m.mcell_assign_surf_class_to_region(sc_sym, region_swig_obj)
def assign_surf_class(
self, sc: SurfaceClass, region: SurfaceRegion) -> None:
""" Assign a surface class to a region. """
sc_type = self._get_sc_type(sc.sc_type)
if isinstance(sc.species, m.OrientedSpecies):
orient = sc.species.orient_num
spec_name = sc.species.spec.name
else:
orient = 0
spec_name = sc.species.name
try:
sc_sym = self._surface_classes[sc.name]
except KeyError:
sc_sym = m.create_surf_class(self._world, sc.name)
self._surface_classes[sc.name] = sc_sym
spec_sym = self._species[spec_name]
m.mcell_add_surf_class_properties(
self._world, sc_type, sc_sym, spec_sym, orient)
region_swig_obj = self._regions[region.full_reg_name]
m.mcell_assign_surf_class_to_region(sc_sym, region_swig_obj)
def get_species_count(self, species: Species, mesh_obj: MeshObj) -> int:
""" Get the current count of a molecule species. """
return m.mcell_get_count(
species.name, "Scene.%s,ALL" % mesh_obj.name, self._world)
def modify_rate_constant(
self, rxn: Reaction, new_rate_constant: float) -> None:
""" Modify the rate constant of the specified reaction. """
if not rxn.name:
print("You can only change a named reaction.")
else:
m.mcell_modify_rate_constant(
self._world, rxn.name, new_rate_constant)
def run_iteration(self) -> None:
""" Run a single iteration. """
if self._finished:
print("The simulation is done running")
return
if not self._started:
m.mcell_init_simulation(self._world)
m.mcell_init_output(self._world)
self._started = True
if self._current_iteration <= self._iterations:
m.mcell_run_iteration(self._world, self._output_freq, 0)
# You have to kill it now or it will hang
if self._current_iteration == self._iterations:
m.mcell_flush_data(self._world)
m.mcell_print_final_warnings(self._world)
m.mcell_print_final_statistics(self._world)
self._finished = True
self._current_iteration += 1
def run_sim(self) -> None:
""" Run the entire simulation without interruption. """
if self._finished:
print("The simulation is done running")
return
m.mcell_init_simulation(self._world)
m.mcell_init_output(self._world)
for i in range(self._iterations+1):
m.mcell_run_iteration(self._world, self._output_freq, 0)
m.mcell_flush_data(self._world)
m.mcell_print_final_warnings(self._world)
m.mcell_print_final_statistics(self._world)
self._finished = True
def end_sim(self) -> None:
""" Call this if we end the simulation early """
if self._started and not self._finished:
m.mcell_flush_data(self._world)
m.mcell_print_final_warnings(self._world)
m.mcell_print_final_statistics(self._world)
self._finished = True
def create_partitions(world, axis, start, stop, step):
expr_list = m.num_expr_list_head()
expr_list.value_head = None
expr_list.value_tail = None
expr_list.value_count = 0
expr_list.shared = 1
m.mcell_generate_range(expr_list, start, stop, step)
expr_list.shared = 1
m.mcell_set_partition(world, axis, expr_list)
def create_release_pattern(
world, name, delay=0, release_interval=1e20, train_interval=1e20,
train_duration=1e20, number_of_trains=1):
"""Create a release pattern
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
name -- name of the release pattern
other arguments -- as listed
"""
return m.mcell_create_release_pattern(
world, name, delay, release_interval, train_interval, train_duration,
number_of_trains)
def create_count(world, where, mol_sym, file_path, step, report_flags=0, exact_time=0, buffer_size=10000):
"""Creates a count for a specified molecule in a specified region
and initializes an output block for the count data that will be
generated.
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
where (sym_entry) -- symbol entry for the location you want to
record
mol_sym (sym_entry) -- symbol entry for the molecule
file_path (dir) -- name of the file path to output the data to
step -- frequency of output in seconds
Returns:
The return values count list, output set, output times and
output structure
"""
# REPORT_CONTENTS are defined later and the identifier cannot be used as
# default arg value
if report_flags == 0:
report_flags = m.REPORT_CONTENTS
c_list = m.output_column_list()
# XXX: m.ORIENT_NOT_SET is using -100 instead of SHRT_MIN (used typemap
# for mcell_create_count in mcell_react_out.i) because limits.h does not
# work well with swig
c_list.thisown = 0
count_list = m.mcell_create_count(
world, mol_sym, m.ORIENT_NOT_SET, where, report_flags, None, c_list)
os = m.output_set()
os = m.mcell_create_new_output_set(
None, exact_time, count_list.column_head, m.FILE_SUBSTITUTE, file_path)
out_times = m.output_times_inlist()
out_times.type = m.OUTPUT_BY_STEP
out_times.step = step
output = m.output_set_list()
output.set_head = os
output.set_tail = os
m.mcell_add_reaction_output_block(world, output, buffer_size, out_times)
return (count_list, os, out_times, output)
def create_rxn_count(world, where, rxn_sym, file_path, step, report_flags=0, exact_time=0, buffer_size=10000):
"""Creates a count for a specified reaction in a specified region
and initializes an output block for the count data that will be
generated.
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
where (sym_entry) -- symbol entry for the location you want to
record
mol_sym (sym_entry) -- symbol entry for the molecule
file_path (dir) -- name of the file path to output the data to
step -- frequency of output in seconds
Returns:
The return values count list, output set, output times and
output structure
"""
# REPORT_CONTENTS are defined later and the identifier cannot be used as
# default arg value
if report_flags == 0:
report_flags = m.REPORT_RXNS
c_list = m.output_column_list()
# XXX: m.ORIENT_NOT_SET is using -100 instead of SHRT_MIN (used typemap
# for mcell_create_count in mcell_react_out.i) because limits.h does not
# work well with swig
c_list.thisown = 0
count_list = m.mcell_create_count(
world, rxn_sym, m.ORIENT_NOT_SET, where, report_flags, None, c_list)
os = m.output_set()
os = m.mcell_create_new_output_set(
None, exact_time, count_list.column_head, m.FILE_SUBSTITUTE, file_path)
out_times = m.output_times_inlist()
out_times.type = m.OUTPUT_BY_STEP
out_times.step = step
output = m.output_set_list()
output.set_head = os
output.set_tail = os
m.mcell_add_reaction_output_block(world, output, buffer_size, out_times)
return (count_list, os, out_times, output)
def create_species(world, name, D, is_2d, custom_time_step=0):
"""Creates a molecule species
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
name (string) -- Name of the molecule species that will be
generated
D (double) -- Diffusion Coefficient for the molecule species
that will be generated.
is_2d (bool) -- Boolean describing whether new species is a
surface molecule
custom_time_step -- Custom time step (< 0.0 for a custom space step,
>0.0 for custom timestep, 0.0 for default timestep)
Returns:
(mcell_symbol) Returns a species sym_entry
"""
species_def = m.mcell_species_spec()
species_def.name = name
species_def.D = D
is_2d = 1 if is_2d else 0
species_def.is_2d = is_2d
species_def.custom_time_step = custom_time_step
species_def.target_only = 0
species_def.max_step_length = 0
species_temp_sym = m.mcell_symbol()
species_sym = m.mcell_create_species(
world, species_def, species_temp_sym)
return species_sym
def create_reaction(
world, reactants, products, rate_constant,
backward_rate_constant=0.0, surf_class=None, name=None):
"""Creates a molecular reaction
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
reactants (mcell_species_list) -- list of species that are the
reactants for the reaction
products (mcell_species_list) -- list of species that are the
products for the reaction
rate_constant (double) -- the rate constant for the forward
direction reaction -> product
backward_rate_constant (double)(optional) -- the rate constant
for the backward direction reaction <- product
surf_class (mcell species list surface class)(optional) -- the
surface class upon which the reaction will happen
name (string)(optional) -- Name of the reaction
Returns:
void -- creates a reaction, by generating reaction_rates
structure
"""
if surf_class:
# Do nothing, surf_class has been added and a null geom_object is not needed
pass
else:
surf_class = m.mcell_add_to_species_list(None, False, 0, None)
arrow = m.reaction_arrow()
# reversible reaction e.g. A<->B
if backward_rate_constant != 0.0:
arrow.flags = m.REGULAR_ARROW
new_fwd_rate_constant = m.mcell_create_reaction_rates(
m.RATE_CONSTANT, rate_constant, m.RATE_UNSET, 0)
new_bkwd_rate_constant = m.mcell_create_reaction_rates(
m.RATE_CONSTANT, backward_rate_constant, m.RATE_UNSET, 0)
# irreversible reaction e.g. A->B
else:
arrow.flags = m.REGULAR_ARROW
new_fwd_rate_constant = m.mcell_create_reaction_rates(
m.RATE_CONSTANT, rate_constant, m.RATE_UNSET, 0)
arrow.catalyst = m.mcell_species()
arrow.catalyst.next = None
arrow.catalyst.mol_type = None
arrow.catalyst.orient_set = 0
arrow.catalyst.orient = 0
if name:
if backward_rate_constant:
raise ValueError("Name cannot be specified for reversible reactions because internally the reactions are split into two reactions.")
name_sym = m.mcell_new_rxn_pathname(world, name)
else:
name_sym = None
m.mcell_add_reaction_simplified(
world, reactants, arrow, surf_class, products, new_fwd_rate_constant, name_sym)
if backward_rate_constant:
m.mcell_add_reaction_simplified(
world, products, arrow, surf_class, reactants, new_bkwd_rate_constant, name_sym)
return name_sym
def create_instance_object(world, name):
"""Creates an instance geom_object. Simple translation from wrapped code
to python function. Frees the user from having to initialize the
scene geom_object and then pass it in and generate the geom_object.
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
name (string) -- name of the instance geom_object
Returns:
instance geom_object
"""
scene_temp = m.geom_object()
return m.mcell_create_instance_object(world, name, scene_temp)
def create_surf_class(world, name):
"""Creates a surface class. Simple translation from wrapped code to
python function Frees the user from having to initialize the surface
class symbol and then pass it in and generate the geom_object.
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
name (string) -- name of the instance geom_object
Returns:
mcell_symbol for surface class
"""
sc_temp = m.mcell_symbol()
return m.mcell_create_surf_class(world, name, sc_temp)
def create_list_release_site(
world, scene, mol_list, xpos, ypos, zpos, name, surf_flags=None,
orientations=None, diameter=1e-4):
'''
Creates a list release site
All is self explanatory except mol_list:
This is a list of "mol_sym" that you get back when you create the species.
This is a Python list - it is converted to a species list in this function
for you. By default, assumes all molecules are volume molecules. Else, need
to pass surf_flags=[True,True,False,...] and their orientations =
[1,0,1,...] Diameter is the diameter we search for to place a surface mol
It can be None (= NULL in C) but then we do a poor job of placing surface
mols
'''
# Check that they're all the same length
n = len(mol_list)
if len(xpos) != n or len(ypos) != n or len(zpos) != n:
raise ValueError("All lists must have the same length.")
# Check that if there are surface molecules
if surf_flags is not None:
# Check that there are enough
if len(surf_flags) != n or len(orientations) != n:
raise ValueError(
"surf_flags and orientations lists must have the same lengths "
"as the others.")
# Convert to floats (can't be int)
xpos = [float(q) for q in xpos]
ypos = [float(q) for q in ypos]
zpos = [float(q) for q in zpos]
# Diameter
diam = m.vector3()
diam.x = diameter
diam.y = diameter
diam.z = diameter
# Mols
mol_list.reverse()
species_list = None
# All volume molecules
if surf_flags is None:
for mol_sym in mol_list:
species_list = m.mcell_add_to_species_list(
mol_sym, False, 0, species_list)
else:
for i, mol_sym in enumerate(mol_list):
species_list = m.mcell_add_to_species_list(
mol_sym, surf_flags[i], orientations[i], species_list)
rel_object = m.geom_object()
ret = m.mcell_create_list_release_site(
world, scene, name, species_list, xpos, ypos, zpos, n, diam,
rel_object)
# Delete the species list
m.mcell_delete_species_list(species_list)
# VERY IMPORTANT HERE - MUST RETURN "ret"
# If we throw this away, all is lost....
return (rel_object, ret)
def create_release_site(
world, scene, pos, diam, shape, number, number_type, mol_sym, name):
"""Creates a molecule release site
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
scene (instance geom_object) -- scene for mcell simulation
pos (vector3) -- position of release site
diam (vector3) -- diameter of release site
number (int or float) -- number to be release at release site
number_type (int) -- 0 for NUMBER, 1 for CONCENTRATION
mol_sym (mcell_symbol) -- species to be released
name (string) -- name of the release site
Returns:
void -- generates a species release site
"""
position = m.vector3()
position.x = pos.x
position.y = pos.y
position.z = pos.z
diameter = m.vector3()
diameter.x = diam.x
diameter.y = diam.y
diameter.z = diam.z
mol_list = m.mcell_add_to_species_list(mol_sym, False, 0, None)
rel_object = m.geom_object()
release_object = m.mcell_create_geometrical_release_site(
world, scene, name, shape, position, diameter, mol_list, float(number),
number_type, 1, None, rel_object)
m.mcell_delete_species_list(mol_list)
return (position, diameter, release_object)
def create_region_release_site( # lala
world, scene, mesh, release_name, reg_name, number, number_type,
mol_sym, is_oriented=True, orientation=0):
"""Creates a release site on a specific region
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
scene (instance geom_object) -- scene for mcell simulation
mesh (mesh geom_object) -- scene geom_object where the release will occur
release_name (string) -- name of the region release site
reg_name (string) -- name of the region for the release site
number (int or float) -- number to be released at the region release
site
number_type (int) -- 0 for NUMBER, 1 for CONCENTRATION
mol_sym (mcell_symbol) -- species to be released
is_oriented -- True if the orientation holds a valid value
orientation -- used if is_oriented is True, -1 - down, 1 - up
Returns:
release geom_object (geom_object)
"""
mol_list = m.mcell_add_to_species_list(mol_sym, is_oriented, orientation, None)
rel_object = m.geom_object()
release_object = m.mcell_create_region_release(
world, scene, mesh, release_name, reg_name, mol_list, float(number),
number_type, 1, None, rel_object)
m.mcell_delete_species_list(mol_list)
return release_object
def create_box(world, scene, half_length, name):
"""Creates the verteces and lines of a cube geom_object at the origin
Args:
half_length (double) -- half length of the cube
Returns:
vertex list and element connection list
"""
hl = half_length
verts = m.mcell_add_to_vertex_list(hl, hl, -hl, None)
verts = m.mcell_add_to_vertex_list(hl, -hl, -hl, verts)
verts = m.mcell_add_to_vertex_list(-hl, -hl, -hl, verts)
verts = m.mcell_add_to_vertex_list(-hl, hl, -hl, verts)
verts = m.mcell_add_to_vertex_list(hl, hl, hl, verts)
verts = m.mcell_add_to_vertex_list(hl, -hl, hl, verts)
verts = m.mcell_add_to_vertex_list(-hl, -hl, hl, verts)
verts = m.mcell_add_to_vertex_list(-hl, hl, hl, verts)
elems = m.mcell_add_to_connection_list(1, 2, 3, None)
elems = m.mcell_add_to_connection_list(7, 6, 5, elems)
elems = m.mcell_add_to_connection_list(0, 4, 5, elems)
elems = m.mcell_add_to_connection_list(1, 5, 6, elems)
elems = m.mcell_add_to_connection_list(6, 7, 3, elems)
elems = m.mcell_add_to_connection_list(0, 3, 7, elems)
elems = m.mcell_add_to_connection_list(0, 1, 3, elems)
elems = m.mcell_add_to_connection_list(4, 7, 5, elems)
elems = m.mcell_add_to_connection_list(1, 0, 5, elems)
elems = m.mcell_add_to_connection_list(2, 1, 6, elems)
elems = m.mcell_add_to_connection_list(2, 6, 3, elems)
elems = m.mcell_add_to_connection_list(4, 0, 7, elems)
pobj = m.poly_object()
pobj.obj_name = name
pobj.vertices = verts
pobj.num_vert = 8
pobj.connections = elems
pobj.num_conn = 12
mesh_temp = m.geom_object()
mesh = m.mcell_create_poly_object(world, scene, pobj, mesh_temp)
return mesh
def change_geometry(world, scene_name, obj_list):
pobj_list = None
verts = None
elems = None
for p in obj_list:
verts = None
for x, y, z in p.vert_list:
verts = m.mcell_add_to_vertex_list(x, y, z, verts)
elems = None
for x, y, z in p.face_list:
elems = m.mcell_add_to_connection_list(x, y, z, elems)
pobj = m.poly_object()
pobj.obj_name = p.obj_name
pobj.vertices = verts
pobj.num_vert = len(p.vert_list)
pobj.connections = elems
pobj.num_conn = len(p.face_list)
surf_reg_faces = None
for idx in p.surf_reg_face_list:
surf_reg_faces = m.mcell_add_to_region_list(surf_reg_faces, idx)
pobj_list = m.mcell_add_to_poly_obj_list(
pobj_list, p.obj_name, verts, len(p.vert_list), elems,
len(p.face_list), surf_reg_faces, p.reg_name)
m.mcell_change_geometry(world, pobj_list)
def create_polygon_object(world, vert_list, face_list, scene, name, translation=None):
"""Creates a polygon geom_object from a vertex and element lest
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
vert_list (vertex list) -- verteces for the polygon
face_list (element connection list) -- faces for the polygon
scene (instance geom_object) -- scene for mcell simulation
name (string) -- name of polygon geom_object that will be created
Returns:
polygon geom_object
"""
verts = None
vert_list = vert_list[::-1]
t = translation
if t:
for x, y, z in vert_list:
verts = m.mcell_add_to_vertex_list(x+t[0], y+t[1], z+t[2], verts)
else:
for x, y, z in vert_list:
verts = m.mcell_add_to_vertex_list(x, y, z, verts)
elems = None
face_list = face_list[::-1]
for x, y, z in face_list:
elems = m.mcell_add_to_connection_list(x, y, z, elems)
pobj = m.poly_object()
pobj.obj_name = name
pobj.vertices = verts
pobj.num_vert = len(vert_list)
pobj.connections = elems
pobj.num_conn = len(face_list)
mesh_temp = m.geom_object()
mesh = m.mcell_create_poly_object(world, scene, pobj, mesh_temp)
return mesh
def create_surface_region(world, mesh, surf_reg_face_list, region_name):
"""Creates a surface region
Args:
world (geom_object) -- the world geom_object which has been generated by
mcell create_instance_object
mesh (polygon geom_object) -- geom_object where surface region will reside
surf_reg_face_list (element connection list) -- list of surface
region faces
region_name (string) -- name of the surface region being created
Returns:
region geom_object
"""
surface_region = m.mcell_create_region(world, mesh, region_name)
surf_reg_faces = None
for idx in surf_reg_face_list:
surf_reg_faces = m.mcell_add_to_region_list(surf_reg_faces, idx)
m.mcell_set_region_elements(surface_region, surf_reg_faces, 1)
return surface_region
| Python |
3D | mcellteam/mcell | src/bng_util.h | .h | 540 | 16 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <string>
// transforms graph pattern into a more readable BNGL representation
std::string graph_pattern_to_bngl(const char* graph_pattern);
| Unknown |
3D | mcellteam/mcell | src/mcell_structs_shared.h | .h | 2,252 | 74 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "vector.h"
#include "rng.h"
#define MY_PI 3.14159265358979323846
#define N_AV 6.0221417930e23
/* Direction Bit Flags */
#define X_NEG_BIT 0x01
#define X_POS_BIT 0x02
#define Y_NEG_BIT 0x04
#define Y_POS_BIT 0x08
#define Z_NEG_BIT 0x10
#define Z_POS_BIT 0x20
/* Reaction flags */
/* RX_ABSORB_REGION_BORDER signifies that a reaction is between a surface
molecule and an ABSORPTIVE region border */
/* RX_REFLEC signifies that a reaction is between a molecule and a REFLECTIVE
wall */
/* RX_TRANSP signifies that a reaction is between a molecule and a TRANSPARENT
wall */
/* Any value equal to or less than RX_SPECIAL refers to a special wall type */
/* RX_BLOCKED signals a reaction that cannot take place because the grid is
full */
/* Any value equal to or less than RX_NO_RX indicates that a reaction did not
take place */
/* RX_FLIP signals that a molecule flips its orientation (crosses a wall if
it's free) */
/* RX_DESTROY signals that the molecule no longer exists (so don't try to keep
using it) */
/* RX_A_OK signals that all is OK with a reaction, proceed as normal (reflect
if you're free) */
#define RX_ABSORB_REGION_BORDER -5
#define RX_REFLEC -4
#define RX_TRANSP -3
#define RX_SPECIAL -3
#define RX_BLOCKED -2
#define RX_NO_RX -2
#define RX_FLIP -1
#define RX_LEAST_VALID_PATHWAY 0
#define RX_DESTROY 0
#define RX_A_OK 1
#define MAX_MATCHING_RXNS 64
/* Number of times to try diffusing on a surface before we give up (we might
* fail if the target grid is full) */
#define SURFACE_DIFFUSION_RETRIES 10
/* Visualization modes. */
enum viz_mode_t {
VIZ_MODE_INVALID = -1,
NO_VIZ_MODE = 0,
ASCII_MODE = 1,
CELLBLENDER_MODE_V1 = 2,
CELLBLENDER_MODE_V2 = 3,
};
int distinguishable(double a, double b, double eps);
| Unknown |
3D | mcellteam/mcell | src/argparse.c | .c | 14,499 | 420 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include "argparse.h"
#include "mcell_structs.h" /* for struct volume */
#include "logging.h"
#include "version_info.h" /* for print_version, print_full_version */
#include <stdarg.h> /* for va_start, va_end, va_list */
#include <string.h> /* for strdup */
#include <stdio.h> /* for *printf functions */
#include <stdlib.h> /* for strtol, strtoll, strtoul, free */
#ifndef _MSC_VER
#include <getopt.h>
#else
#include "win_getopt/win_getopt.h"
#endif
#include <nfsim_c.h> /* for the nfsim initialization stuff */
/* Display a formatted error message. */
static void argerror(char const *s, ...) PRINTF_FORMAT(1);
/* Command-line arguments structure:
* long arg name
* has argument
* pointer to flag (should always be 0)
* short argument letter
*
* To add an argument, add a new entry to this array, assigning it a unique
* short-argument letter. Then add the short argument letter to the gibberish
* string passed to getopt_long_only below, followed by a colon if the flag
* takes an argument. Finally, add a case to the switch statement to handle
* the letter you selected for the argument.
*/
static struct option long_options[] = { { "help", 0, 0, 'h' },
{ "version", 0, 0, 'v' },
{ "fullversion", 0, 0, 'V' },
{ "seed", 1, 0, 's' },
{ "iterations", 1, 0, 'i' },
{ "checkpoint_infile", 1, 0, 'c' },
{ "checkpoint_outfile", 1, 0, 'C' },
{ "logfile", 1, 0, 'l' },
{ "logfreq", 1, 0, 'f' },
{ "errfile", 1, 0, 'e' },
{ "bond_angle", 1, 0, 'b'},
{ "z_options", 1, 0, 'z' },
{ "dump", 1, 0, 'd'},
{ "quiet", 0, 0, 'q' },
{ "with_checks", 1, 0, 'w' },
{ "rules", 1, 0, 'r'},
{ "mcell4", 0, 0, 'n'},
{ "dump_mcell3", 0, 0, 't'},
{ "dump_mcell4", 0, 0, 'o'},
{ "dump_mcell4_with_geometry", 0, 0, 'g'},
{ "mdl2datamodel4", 0, 0, 'u'},
{ "mdl2datamodel4viz", 0, 0, 'a'},
{ NULL, 0, 0, 0 } };
/* print_usage: Write the usage message for mcell to a file handle.
*
* f: file handle to which to write message
* argv0: command name to use for executable in message
*/
void print_usage(FILE *f, char const *argv0) {
fprintf(f, "Usage: %s [options] mdl_file_name\n\n", argv0);
fprintf(
f,
" options:\n"
" [-help] print this help message\n"
" [-version] print the program version and exit\n"
" [-fullversion] print the detailed program version report and exit\n"
" [-seed n] choose random sequence number (default: 1)\n"
" [-iterations n] override iterations in mdl_file_name\n"
" [-logfile log_file_name] send output log to file (default: stdout)\n"
" [-logfreq n] output log frequency\n"
" [-errfile err_file_name] send errors log to file (default: stderr)\n"
" [-checkpoint_infile checkpoint_file_name] read checkpoint file\n"
" [-checkpoint_outfile checkpoint_file_name] write checkpoint file\n"
" [-z_options opt_int] additional visualization options (defaults to 0 which is none)\n"
" [-bond_angle angle] bond angle to use for all bonds (defaults to 0)\n"
" [-dump level] print additional information based on level (0 is none, >0 is more)\n"
" [-quiet] suppress all unrequested output except for errors\n"
" [-with_checks ('yes'/'no', default 'yes')] performs check of the geometry for coincident walls\n"
" [-rules rules_file_name] run in MCell-R mode\n"
" [-mcell4] run new experimental MCell 4 version\n"
" [-dump_mcell3] dump initial MCell 3 state for MCell 4 development\n"
" [-dump_mcell4] dump initial MCell 4 state without geometry\n"
" [-dump_mcell4_with_geometry] dump initial MCell 4 state with geometry\n"
" [-mdl2datamodel4] convert MDL to datamodel using mcell 4 state, the resulting file will be called 'data_model.json'\n"
" [-mdl2datamodel4viz] convert MDL to datamodel using mcell 4 state, only for visualization purposes the resulting file will be called 'data_model_viz.json'\n"
"\n");
}
/* argerror: Display a message about an error which occurred during the
* argument parsing. The message goes into the current "err_file",
* which defaults to stderr.
*
* vol: the volume into which to imbue the parsed options
* fmt: a C "printf"-style format string
*/
static void argerror(char const *fmt, ...) {
mcell_error_raw("\nMCell: command-line argument syntax error: ");
va_list args;
va_start(args, fmt);
char error_msg[256];
vsnprintf(error_msg, sizeof(error_msg), fmt, args);
va_end(args);
mcell_error_raw("%s", error_msg);
mcell_error_raw("\n");
}
/* argparse_init: Parse the command-line arguments, imbuing the options into
* 'vol'.
*
* argc: the number of command-line arguments including the program name
* argv: an array of the command-line arguments
* vol: the volume into which to imbue our options
*
* Returns 1 if for any reason the simulation should not be run (i.e. an
* error, or '-help'), 0 if the simulation should proceed. If 1 is returned,
* the caller should display a usage message. (Perhaps the usage message
* should actually be displayed from here?)
*/
int argparse_init(int argc, char *const argv[], struct volume *vol) {
char *endptr = NULL;
int log_file_specified = 0, err_file_specified = 0;
FILE *fhandle = NULL;
char *with_checks_option;
char *rules_xml_file = NULL; // for nfsim
//argerror('whats up');
/* Loop over all arguments */
while (1) {
/* get the next argument */
int c = getopt_long_only(argc, argv, "?h", long_options, NULL);
if (c == -1)
break;
switch (c) {
case '?':
case 'h': /* -help */
return 1;
case 'v': /* -version */
print_version(mcell_get_log_file());
exit(1);
case 'V': /* -fullversion */
print_full_version(mcell_get_log_file());
exit(1);
case 'q': /* -quiet */
vol->quiet_flag = 1;
break;
case 'd': /* -dump */
vol->dump_level = strtol(optarg, &endptr, 0);
if (endptr == optarg || *endptr != '\0') {
argerror("Dump level must be an integer: %s", optarg);
return 1;
}
if (vol->dump_level < 0) {
argerror("Dump level %ld is less than 0", vol->dump_level);
return 1;
}
if (vol->dump_level > 0) {
fprintf(stdout, "Dump level has been set to %ld\n", vol->dump_level);
}
break;
case 'b': /* -bond_angle */
vol->bond_angle = (double)strtod(optarg, &endptr);
if (endptr == optarg || *endptr != '\0') {
argerror("Bond angle must be a double: %s", optarg);
return 1;
}
break;
case 'z': /* -viz_options */
vol->viz_options = strtol(optarg, &endptr, 0);
fprintf ( stdout, "Parsed Visualization Options = %lx\n", vol->viz_options );
if (endptr == optarg || *endptr != '\0') {
argerror("viz_options must be an integer: %s", optarg);
return 1;
}
break;
case 'w': /* walls coincidence check (maybe other checks in future) */
with_checks_option = strdup(optarg);
if (with_checks_option == NULL) {
argerror("File '%s', Line %u: Out of memory while parsing "
"command-line arguments: %s\n",
__FILE__, __LINE__, optarg);
return 1;
}
if (((strcmp(with_checks_option, "yes") == 0) ||
(strcmp(with_checks_option, "YES") == 0))) {
vol->with_checks_flag = 1;
} else if (((strcmp(with_checks_option, "no") == 0) ||
(strcmp(with_checks_option, "NO") == 0))) {
vol->with_checks_flag = 0;
} else {
argerror("-with_checks option should be 'yes' or 'no'.");
free(with_checks_option);
return 1;
}
free(with_checks_option);
break;
case 's': /* -seed */
vol->seed_seq = (int)strtol(optarg, &endptr, 0); // initialized to '1'
if (endptr == optarg || *endptr != '\0') {
argerror("Random seed must be an integer: %s", optarg);
return 1;
}
break;
case 'i': /* -iterations */
vol->iterations = strtoll(optarg, &endptr, 0);
if (endptr == optarg || *endptr != '\0') {
argerror("Iteration count must be an integer: %s", optarg);
return 1;
}
if (vol->iterations < 0) {
argerror("Iteration count %lld is less than 0",
(long long int)vol->iterations);
return 1;
}
break;
case 'c': /* -checkpoint_infile */
vol->chkpt_infile = strdup(optarg);
if (vol->chkpt_infile == NULL) {
argerror("File '%s', Line %u: Out of memory while parsing "
"command-line arguments: %s\n",
__FILE__, __LINE__, optarg);
return 1;
}
if ((fhandle = fopen(vol->chkpt_infile, "rb")) == NULL) {
argerror("Cannot open input checkpoint file: %s", vol->chkpt_infile);
free(vol->chkpt_infile);
vol->chkpt_infile = NULL;
vol->chkpt_init = 1;
return 1;
}
vol->chkpt_init = 0;
vol->chkpt_flag = 1;
fclose(fhandle);
break;
case 'C': /* -checkpoint_outfile */
vol->chkpt_outfile = strdup(optarg);
if (vol->chkpt_outfile == NULL) {
argerror("File '%s', Line %u: Out of memory while parsing "
"command-line arguments: %s\n",
__FILE__, __LINE__, optarg);
return 1;
}
vol->chkpt_flag = 1;
break;
case 'r': /* nfsim */
vol->nfsim_flag = 1;
rules_xml_file = strdup(optarg);
break;
case 'l': /* -logfile */
if (log_file_specified) {
argerror("-logfile argument specified more than once: %s", optarg);
return 1;
}
if ((fhandle = fopen(optarg, "w")) == NULL) {
argerror("Cannot open output log file: %s", optarg);
return 1;
} else {
mcell_set_log_file(fhandle);
log_file_specified = 1;
}
break;
case 'f': /* -logfreq */
if (vol->log_freq != ULONG_MAX) {
argerror("-logfreq specified more than once: %s", optarg);
return 1;
}
vol->log_freq = strtoul(optarg, &endptr, 0);
if (endptr == optarg || *endptr != '\0') {
argerror("Iteration report interval must be an integer: %s", optarg);
return 1;
}
if (vol->log_freq == ULONG_MAX) {
argerror("Iteration report interval must be an integer n such "
"that 1 <= n < %lu: %s",
ULONG_MAX, optarg);
return 1;
}
if (vol->log_freq < 1) {
argerror("Iteration report interval must be at least 1 iteration: %s",
optarg);
return 1;
}
break;
case 'e': /* -errfile */
if (err_file_specified) {
// XXX: This is almost identical to the -logfile error but doesn't work
// for some reason.
argerror("-errfile argument specified more than once: %s", optarg);
return 1;
}
if ((fhandle = fopen(optarg, "w")) == NULL) {
argerror("Cannot open output error file: %s", optarg);
return 1;
} else {
mcell_set_error_file(fhandle);
err_file_specified = 1;
}
break;
case 'n':
vol->use_mcell4 = 1;
break;
case 't':
vol->dump_mcell3 = 1;
break;
case 'o':
vol->dump_mcell4 = 1;
break;
case 'g':
vol->dump_mcell4_with_geometry = 1;
break;
case 'u':
vol->mdl2datamodel4 = 1;
vol->mdl2datamodel4_only_viz = 0;
break;
case 'a':
vol->mdl2datamodel4 = 1;
vol->mdl2datamodel4_only_viz = 1;
break;
default:
argerror("Internal error: getopt returned character code 0x%02x",
(unsigned int)c);
return 1;
}
}
/* Handle any left-over arguments, which we assume to be MDL files. */
if (optind < argc) {
FILE *f;
if (argc - optind > 1) {
argerror("%d MDL file names specified: %s, %s, ...", argc - optind,
argv[optind], argv[optind + 1]);
return 1;
}
vol->mdl_infile_name = strdup(argv[optind]);
if (vol->mdl_infile_name == NULL) {
argerror("File '%s', Line %ld: Out of memory while parsing command "
"line arguments: %s",
__FILE__, (long)__LINE__, argv[optind]);
return 1;
}
if ((f = fopen(argv[optind], "r")) == NULL) {
/* XXX: Should probably use perror to explain why... */
argerror("Cannot read MDL file: %s", argv[optind]);
return 1;
}
fclose(f);
} else {
argerror("No MDL file name specified");
return 1;
}
/* Initialize NFSim if requested */
if (vol->nfsim_flag) {
int nfsimStatus = setupNFSim_c(rules_xml_file, vol->seed_seq, vol->dump_level > 0);
free(rules_xml_file);
if (nfsimStatus != 0){
argerror("nfsim model could not be properly initialized: %s", optarg);
return 1;
}
}
return 0;
}
| C |
3D | mcellteam/mcell | src/test_api.c | .c | 10,649 | 245 | #include "config.h"
#include <stdlib.h>
#include "mcell_misc.h"
#include "mcell_objects.h"
#include "mcell_react_out.h"
#include "mcell_reactions.h"
#include "mcell_release.h"
#include "mcell_species.h"
#include "mcell_viz.h"
#include "mcell_surfclass.h"
#define CHECKED_CALL_EXIT(function, error_message) \
{ \
if (function) { \
mcell_print(error_message); \
exit(1); \
} \
}
/***************************************************************************
* Test code for the libmcell API
***************************************************************************/
void test_api(MCELL_STATE *state) {
/* set timestep and number of iterations */
CHECKED_CALL_EXIT(mcell_set_time_step(state, 1e-6), "Failed to set timestep");
CHECKED_CALL_EXIT(mcell_set_iterations(state, 1000),
"Failed to set iterations");
/* create range for partitions */
struct num_expr_list_head list;
list.value_head = NULL;
list.value_tail = NULL;
list.value_count = 0;
list.shared = 1;
mcell_generate_range(&list, -0.5, 0.5, 0.05);
list.shared = 1;
/* set partitions */
CHECKED_CALL_EXIT(mcell_set_partition(state, X_PARTS, &list),
"Failed to set X partition");
CHECKED_CALL_EXIT(mcell_set_partition(state, Y_PARTS, &list),
"Failed to set Y partition");
CHECKED_CALL_EXIT(mcell_set_partition(state, Z_PARTS, &list),
"Failed to set Z partition");
/* create species */
struct mcell_species_spec molA = { "A", 1e-6, 1, 0.0, 0, 0.0, 0.0, 0 };
mcell_symbol *molA_ptr;
CHECKED_CALL_EXIT(mcell_create_species(state, &molA, &molA_ptr),
"Failed to create species A");
struct mcell_species_spec molB = { "B", 1e-5, 0, 0.0, 0, 0.0, 0.0, 0 };
mcell_symbol *molB_ptr;
CHECKED_CALL_EXIT(mcell_create_species(state, &molB, &molB_ptr),
"Failed to create species B");
struct mcell_species_spec molC = { "C", 2e-5, 0, 0.0, 0, 0.0, 0.0, 0 };
mcell_symbol *molC_ptr;
CHECKED_CALL_EXIT(mcell_create_species(state, &molC, &molC_ptr),
"Failed to create species C");
struct mcell_species_spec molD = { "D", 1e-6, 1, 0.0, 0, 0.0, 0.0, 0 };
mcell_symbol *molD_ptr;
CHECKED_CALL_EXIT(mcell_create_species(state, &molD, &molD_ptr),
"Failed to create species D");
/* create reactions */
struct mcell_species *reactants =
mcell_add_to_species_list(molA_ptr, true, 1, NULL);
reactants = mcell_add_to_species_list(molB_ptr, true, -1, reactants);
struct mcell_species *products =
mcell_add_to_species_list(molC_ptr, true, -1, NULL);
struct mcell_species *surfs =
mcell_add_to_species_list(NULL, false, 0, NULL);
struct reaction_arrow arrow = { REGULAR_ARROW, { NULL, NULL, 0, 0 } };
struct reaction_rates rates =
mcell_create_reaction_rates(RATE_CONSTANT, 1e7, RATE_UNSET, 0.0);
if (mcell_add_reaction(state->notify, &state->r_step_release,
state->rxn_sym_table, state->radial_subdivisions,
state->vacancy_search_dist2, reactants, &arrow, surfs,
products, NULL, &rates, NULL, NULL) == MCELL_FAIL) {
mcell_print("error ");
exit(1);
}
mcell_delete_species_list(reactants);
mcell_delete_species_list(products);
mcell_delete_species_list(surfs);
// create surface class
mcell_symbol *sc_ptr;
CHECKED_CALL_EXIT(mcell_create_surf_class(state, "SC_test", &sc_ptr),
"Failed to create surface class SC_test");
// create releases using a surface class (i.e. not a release object)
// mdl equivalent: MOLECULE_DENSITY {A' = 1000}
struct mcell_species *A =
mcell_add_to_species_list(molA_ptr, true, 1, NULL);
struct sm_dat *smd = mcell_add_mol_release_to_surf_class(
state, sc_ptr, A, 1000, 0, NULL);
// mdl equivalent: MOLECULE_NUMBER {D, = 1000}
struct mcell_species *D =
mcell_add_to_species_list(molD_ptr, true, -1, NULL);
mcell_add_mol_release_to_surf_class(state, sc_ptr, D, 1000, 1, smd);
// mdl equivalent: ABSORPTIVE = D
CHECKED_CALL_EXIT(
mcell_add_surf_class_properties(state, SINK, sc_ptr, molD_ptr, 0),
"Failed to add surface class property");
// mdl equivalent: REFLECTIVE = D
/*CHECKED_CALL_EXIT(*/
/* mcell_add_surf_class_properties(state, RFLCT, sc_ptr, molD_ptr, 0),*/
/* "Failed to add surface class property");*/
mcell_delete_species_list(A);
mcell_delete_species_list(D);
/*****************************************************************************
* create world meta object
*****************************************************************************/
struct geom_object *world_object = NULL;
CHECKED_CALL_EXIT(mcell_create_instance_object(state, "world", &world_object),
"could not create meta object");
/****************************************************************************
* begin code for creating a polygon mesh
****************************************************************************/
struct vertex_list *verts = mcell_add_to_vertex_list(0.5, 0.5, -0.5, NULL);
verts = mcell_add_to_vertex_list(0.5, -0.5, -0.5, verts);
verts = mcell_add_to_vertex_list(-0.5, -0.5, -0.5, verts);
verts = mcell_add_to_vertex_list(-0.5, 0.5, -0.5, verts);
verts = mcell_add_to_vertex_list(0.5, 0.5, 0.5, verts);
verts = mcell_add_to_vertex_list(0.5, -0.5, 0.5, verts);
verts = mcell_add_to_vertex_list(-0.5, -0.5, 0.5, verts);
verts = mcell_add_to_vertex_list(-0.5, 0.5, 0.5, verts);
struct element_connection_list *elems =
mcell_add_to_connection_list(1, 2, 3, NULL);
elems = mcell_add_to_connection_list(7, 6, 5, elems);
elems = mcell_add_to_connection_list(0, 4, 5, elems);
elems = mcell_add_to_connection_list(1, 5, 6, elems);
elems = mcell_add_to_connection_list(6, 7, 3, elems);
elems = mcell_add_to_connection_list(0, 3, 7, elems);
elems = mcell_add_to_connection_list(0, 1, 3, elems);
elems = mcell_add_to_connection_list(4, 7, 5, elems);
elems = mcell_add_to_connection_list(1, 0, 5, elems);
elems = mcell_add_to_connection_list(2, 1, 6, elems);
elems = mcell_add_to_connection_list(2, 6, 3, elems);
elems = mcell_add_to_connection_list(4, 0, 7, elems);
struct poly_object polygon = { "aBox", verts, 8, elems, 12 };
struct geom_object *new_mesh = NULL;
CHECKED_CALL_EXIT(
mcell_create_poly_object(state, world_object, &polygon, &new_mesh),
"could not create polygon_object")
/****************************************************************************
* begin code for creating a region
****************************************************************************/
struct region *test_region = mcell_create_region(state, new_mesh, "reg");
struct element_list *region_list = mcell_add_to_region_list(NULL, 0);
region_list = mcell_add_to_region_list(region_list, 1);
CHECKED_CALL_EXIT(mcell_set_region_elements(test_region, region_list, 1),
"could not finish creating region");
/****************************************************************************
* Assign surface class to "test_region"
****************************************************************************/
mcell_assign_surf_class_to_region(sc_ptr, test_region);
/***************************************************************************
* begin code for creating release sites
***************************************************************************/
/*struct object *A_releaser = NULL;*/
/*struct mcell_species *A =*/
/* mcell_add_to_species_list(molA_ptr, true, 1, 0, NULL);*/
/*CHECKED_CALL_EXIT(mcell_create_region_release(state, world_object, new_mesh,*/
/* "A_releaser", "reg", A, 1000, 1,*/
/* NULL, &A_releaser),*/
/* "could not create A_releaser");*/
/*mcell_delete_species_list(A);*/
struct vector3 position = { 0.0, 0.0, 0.0 };
struct vector3 diameter = { 0.00999, 0.00999, 0.00999 };
struct geom_object *B_releaser = NULL;
struct mcell_species *B =
mcell_add_to_species_list(molB_ptr, false, 0, NULL);
CHECKED_CALL_EXIT(mcell_create_geometrical_release_site(
state, world_object, "B_releaser", SHAPE_SPHERICAL,
&position, &diameter, B, 5000, 0, 1, NULL, &B_releaser),
"could not create B_releaser");
mcell_delete_species_list(B);
/***************************************************************************
* begin code for creating count statements
***************************************************************************/
struct sym_entry *where = NULL; // we count in the world
// struct sym_entry *where = new_mesh->sym;
// byte report_flags = REPORT_WORLD;
//report_flags |= REPORT_CONTENTS;
byte report_flags = REPORT_CONTENTS;
struct output_column_list count_list;
CHECKED_CALL_EXIT(mcell_create_count(state, molA_ptr, ORIENT_NOT_SET, where,
report_flags, NULL, &count_list),
"Failed to create COUNT expression");
struct output_set *os =
mcell_create_new_output_set(NULL, 0, count_list.column_head,
FILE_SUBSTITUTE, "react_data/foobar.dat");
struct output_times_inlist outTimes;
outTimes.type = OUTPUT_BY_STEP;
outTimes.step = 1e-5;
struct output_set_list output;
output.set_head = os;
output.set_tail = os;
CHECKED_CALL_EXIT(
mcell_add_reaction_output_block(state, &output, 10000, &outTimes),
"Error setting up the reaction output block");
struct mcell_species *mol_viz_list =
mcell_add_to_species_list(molA_ptr, false, 0, NULL);
mol_viz_list = mcell_add_to_species_list(molB_ptr, false, 0, mol_viz_list);
mol_viz_list = mcell_add_to_species_list(molC_ptr, false, 0, mol_viz_list);
mol_viz_list = mcell_add_to_species_list(molD_ptr, false, 0, mol_viz_list);
CHECKED_CALL_EXIT(mcell_create_viz_output(state, "./viz_data/test",
mol_viz_list, 0, 1000, 2, false),
"Error setting up the viz output block");
mcell_delete_species_list(mol_viz_list);
}
| C |
3D | mcellteam/mcell | src/strfunc.c | .c | 2,766 | 101 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/* Character string handling functions */
#include "config.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "strfunc.h"
/*************************************************************************
my_strcat:
In: two strings
Out: the two strings concatenated, in a newly malloced block of memory,
or NULL if there isn't enough memory.
Note: the calling function is responsible for freeing the memory.
*************************************************************************/
char *my_strcat(char const *s1, char const *s2) {
char *temp = NULL;
size_t len1, len2;
len1 = (s1 == NULL) ? 0 : strlen(s1);
len2 = (s2 == NULL) ? 0 : strlen(s2);
if ((temp = (char *)malloc(len1 + len2 + 1)) != NULL) {
if (len1)
strcpy(temp, s1);
if (len2)
strcpy(temp + len1, s2);
temp[len1 + len2] = '\0';
}
return (temp);
}
/*************************************************************************
strip_quotes:
In: a string that must be at least two characters long
Out: a copy of the string, newly malloced, missing the first and
last characters (might even be quotes!); NULL is returned if
malloc fails.
Note: this function does NOT do any error checking!
*************************************************************************/
char *strip_quotes(char const *s) {
char *temp = NULL;
size_t len = strlen(s);
if ((temp = (char *)malloc(len - 1)) != NULL) {
strncpy(temp, s + 1, len - 2);
temp[len - 2] = '\0';
}
return (temp);
}
/*
* Format a string into an allocated buffer.
*/
char *alloc_vsprintf(char const *fmt, va_list args) {
char stack_buffer[256];
int len;
char *retval = NULL;
va_list saved_args;
va_copy(saved_args, args);
len = vsnprintf(stack_buffer, sizeof(stack_buffer), fmt, args);
if (len >= (int)sizeof(stack_buffer)) {
retval = (char *)malloc(len + 1);
if (retval != NULL)
vsnprintf(retval, len + 1, fmt, saved_args);
} else
retval = strdup(stack_buffer);
va_end(saved_args);
return retval;
}
/*
* Format a string into an allocated buffer.
*/
char *alloc_sprintf(char const *fmt, ...) {
char *retval;
va_list args;
va_start(args, fmt);
retval = alloc_vsprintf(fmt, args);
va_end(args);
return retval;
}
| C |
3D | mcellteam/mcell | src/react_util_nfsim.c | .c | 2,931 | 90 | #include "react.h"
#include "mcell_reactions.h"
#include "react_nfsim.h"
#include <stdlib.h>
#include <string.h>
void calculate_reactant_orientation(struct abstract_molecule *reac,
struct abstract_molecule *reac2,
bool *orientation_flag1,
bool *orientation_flag2,
int *reactantOrientation1,
int *reactantOrientation2) {
// calculate orientation information
if (reac2 != NULL) {
const char *compartment1 =
extractSpeciesCompartmentFromNauty_c(reac->graph_data->graph_pattern);
const char *compartment2 =
extractSpeciesCompartmentFromNauty_c(reac2->graph_data->graph_pattern);
if (strcmp(compartment1, "") == 0 && strcmp(compartment2, "") == 0) {
// no compartment
// both volume molecules
*orientation_flag1 = 0;
*orientation_flag2 = 0;
*reactantOrientation1 = 0;
*reactantOrientation2 = 0;
return;
}
compartmentStruct reactantCompartmentInfo1;
compartmentStruct reactantCompartmentInfo2;
// what compartment is the species now in
reactantCompartmentInfo1 = getCompartmentInformation_c(compartment1);
reactantCompartmentInfo2 = getCompartmentInformation_c(compartment2);
//
// reac is volume, reac2 is surface
if ((reac->flags & ON_GRID) == 0 && (reac2->flags & ON_GRID) != 0) {
*orientation_flag1 = 1;
*orientation_flag2 = 1;
*reactantOrientation2 = 1;
if (strcmp(reactantCompartmentInfo1.outside,
reactantCompartmentInfo2.name) == 0) {
*reactantOrientation1 = -1;
} else {
*reactantOrientation1 = 1;
}
}
// reac2 is volume, reac is surface
else if ((reac2->flags & ON_GRID) == 0 && (reac->flags & ON_GRID) != 0) {
*orientation_flag1 = 1;
*orientation_flag2 = 1;
*reactantOrientation1 = 1;
if (strcmp(reactantCompartmentInfo2.outside,
reactantCompartmentInfo1.name) == 0) {
*reactantOrientation2 = -1;
} else {
*reactantOrientation2 = 1;
}
}
// both surface molecules
else if ((reac2->flags & ON_GRID) != 0 && (reac->flags & ON_GRID) != 0) {
*orientation_flag1 = 1;
*orientation_flag2 = 1;
*reactantOrientation1 = 1;
*reactantOrientation2 = 1;
}
// both volume molecules
else {
*orientation_flag1 = 0;
*orientation_flag2 = 0;
*reactantOrientation1 = 0;
*reactantOrientation2 = 0;
}
free((char *)compartment1);
free((char *)compartment2);
freeCompartmentInformation_c(&reactantCompartmentInfo1);
freeCompartmentInformation_c(&reactantCompartmentInfo2);
} else if ((reac->flags & ON_GRID) != 0) {
*orientation_flag1 = 1;
*reactantOrientation1 = 1;
*orientation_flag2 = 1;
}
}
| C |
3D | mcellteam/mcell | src/init.h | .h | 5,040 | 116 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
#include "mdlparse_aux.h"
int init_notifications(struct volume *world);
int init_variables(struct volume *world);
int init_data_structures(struct volume *world);
int init_species(struct volume *world);
int init_bounding_box(struct volume *world);
int init_partitions(struct volume *world);
int init_vertices_walls(struct volume *world);
int init_regions(struct volume *world);
int init_checkpoint_state(struct volume *world, long long *exec_iterations);
int init_viz_data(struct volume *world);
int init_reaction_data(struct volume *world);
int init_timers(struct volume *world);
int init_counter_name_hash(struct sym_table_head **counter_by_name,
struct output_block *output_block_head);
int parse_input(struct volume *world);
int load_checkpoint(struct volume *world, bool only_time_and_iter);
int instance_obj(struct volume *world, struct geom_object *objp, double (*im)[4]);
int instance_release_site(struct mem_helper *magic_mem,
struct schedule_helper *releaser, struct geom_object *objp,
double (*im)[4]);
int instance_polygon_object(enum warn_level_t degenerate_polys,
struct geom_object *objp);
void init_clamp_lists(struct clamp_data *clamp_list);
int instance_obj_regions(struct volume *world, struct geom_object *objp);
int init_wall_regions(double length_unit, struct clamp_data *clamp_list,
struct species **species_list, int n_species,
struct geom_object *objp);
int init_surf_mols(struct volume *world);
int instance_obj_surf_mols(struct volume *world, struct geom_object *objp);
int init_wall_surf_mols(struct volume *world, struct geom_object *objp);
int init_surf_mols_by_density(struct volume *world, struct wall *w,
struct sm_dat *sm_dat_head);
int init_surf_mols_by_number(struct volume *world, struct geom_object *objp,
struct region_list *rlp);
void cube_corners(struct vector3 *p1, struct vector3 *p2,
struct vector3 *corner);
void cube_face(struct vector3 *corner, struct vector3 **face, int i);
void cube_faces(struct vector3 *corner, struct vector3 *(*face)[4]);
int init_releases(struct schedule_helper *releaser);
int init_dynamic_geometry(struct volume *state);
int schedule_dynamic_geometry(struct mdlparse_vars *parse_state);
int reschedule_release_events(struct volume *world);
void publish_special_reactions_report(struct species *sp,
struct name_list *vol_species_name_list,
struct name_list *surf_species_name_list,
int n_species,
struct species **species_list);
int accumulate_vertex_counts_per_storage(struct volume *world,
struct geom_object *objp,
int *num_vertices_this_storage,
double (*im)[4]);
int accumulate_vertex_counts_per_storage_polygon_object(
struct volume *world, struct geom_object *objp, int *num_vertices_this_storage,
double (*im)[4]);
int which_storage_contains_vertex(struct volume *world, struct vector3 *v);
int fill_world_vertices_array(struct volume *world, struct geom_object *objp,
int *num_vertices_this_storage, double (*im)[4]);
int fill_world_vertices_array_polygon_object(struct volume *world,
struct geom_object *objp,
int *num_vertices_this_storage,
double (*im)[4]);
void check_for_conflicting_surface_classes(struct wall *w, int n_species,
struct species **species_list);
void check_for_conflicts_in_surface_class(struct volume *world,
struct species *sp);
struct species *get_species_by_name(const char *name, int n_species,
struct species **species_list);
void create_name_lists_of_volume_and_surface_mols(
struct volume *world, struct name_list **vol_species_name_list,
struct name_list **surf_species_name_list);
void remove_molecules_name_list(struct name_list **nlist);
int check_for_overlapped_walls(
struct rng_state *rng, int n_subvols, struct subvolume *subvol);
struct vector3 *create_region_bbox(struct region *r);
| Unknown |
3D | mcellteam/mcell | src/dyngeom_parse_extras.c | .c | 13,761 | 406 | #include <stdlib.h>
#include <string.h>
#include "dyngeom_parse_extras.h"
#include "mcell_structs.h"
#include "sym_table.h"
#include "logging.h"
/***************************************************************************
setup_root_obj_inst:
This needs to be called before reading every new DG file.
In: dg_parse_vars: state of dynamic geometry parser
Out: none
***************************************************************************/
void setup_root_obj_inst(
struct dyngeom_parse_vars *dg_parse_vars,
struct volume *state) {
struct sym_entry *sym;
dg_parse_vars->obj_sym_table = state->obj_sym_table;
dg_parse_vars->reg_sym_table = state->reg_sym_table;
sym = retrieve_sym("WORLD_OBJ", state->obj_sym_table);
if (sym == NULL) {
mcell_error("Cannot create WORLD_OBJ for dynamic geometry.");
}
dg_parse_vars->root_object = (struct geom_object *)sym->value;
sym = retrieve_sym("WORLD_INSTANCE", state->obj_sym_table);
if (sym == NULL) {
mcell_error("Cannot create WORLD_INSTANCE for dynamic geometry.");
}
dg_parse_vars->root_instance = (struct geom_object *)sym->value;
dg_parse_vars->current_object = dg_parse_vars->root_object;
dg_parse_vars->object_name_list = NULL;
dg_parse_vars->object_name_list_end = NULL;
}
/***************************************************************************
dg_start_object:
Create a new object, adding it to the DG symbol table. The qualified name
of the object will be built by adding to the object_name_list, and the
object is made the "current_object" in the mdl parser state. Because of
these side effects, it is vital to call dg_finish_object at the end of the
scope of the object created here.
In: dg_parse_vars: state of dynamic geometry parser
obj_name: unqualified object name
Out: the newly created object or NULL on error
Note: This is similar to mdl_start_object.
***************************************************************************/
struct sym_entry *dg_start_object(
struct dyngeom_parse_vars *dg_parse_vars,
char *obj_name) {
// Create new fully qualified name.
char *new_name;
struct object_creation obj_creation;
obj_creation.object_name_list = dg_parse_vars->object_name_list;
obj_creation.object_name_list_end = dg_parse_vars->object_name_list_end;
if ((new_name = push_object_name(&obj_creation, obj_name)) == NULL) {
free(obj_name);
return NULL;
}
dg_parse_vars->object_name_list = obj_creation.object_name_list;
dg_parse_vars->object_name_list_end = obj_creation.object_name_list_end;
// Create the symbol, if it doesn't exist yet.
int error_code = 0;
struct geom_object *obj_ptr = make_new_object(
dg_parse_vars, dg_parse_vars->obj_sym_table, new_name, &error_code);
if (obj_ptr == NULL) {
mcell_error("Object already defined: %s", new_name);
}
struct sym_entry *sym_ptr = obj_ptr->sym;
obj_ptr->last_name = obj_name;
// Set parent object, make this object "current".
obj_ptr->parent = dg_parse_vars->current_object;
dg_parse_vars->current_object = obj_ptr;
return sym_ptr;
}
/***************************************************************************
dg_start_object_simple:
In: dg_parse_vars: state of dynamic geometry parser
obj_creation: information about object being created
name: unqualified object name
Out: the polygon object
NOTE: This is similar to start_object.
XXX: There are too many ways to create objects. This needs to be consolidated
with dg_start_object.
***************************************************************************/
struct geom_object *dg_start_object_simple(struct dyngeom_parse_vars *dg_parse_vars,
struct object_creation *obj_creation,
char *name) {
// Create new fully qualified name.
char *new_name;
if ((new_name = push_object_name(obj_creation, name)) == NULL) {
free(name);
return NULL;
}
// Create the symbol, if it doesn't exist yet.
int error_code = 0;
struct geom_object *obj_ptr = make_new_object(
dg_parse_vars,
dg_parse_vars->obj_sym_table,
new_name,
&error_code);
if (obj_ptr == NULL) {
mcell_error("Object already defined: %s", new_name);
}
obj_ptr->last_name = name;
// Set parent object, make this object "current".
obj_ptr->parent = obj_creation->current_object;
return obj_ptr;
}
/***************************************************************************
dg_new_polygon_list:
In: dg_parse_vars: state of dynamic geometry parser
obj_ptr:
Out: the polygon object
Note: This is similar to mdl_new_polygon_list.
***************************************************************************/
struct geom_object *dg_new_polygon_list(
struct dyngeom_parse_vars *dg_parse_vars,
char *obj_name) {
struct object_creation obj_creation;
obj_creation.object_name_list = dg_parse_vars->object_name_list;
obj_creation.object_name_list_end = dg_parse_vars->object_name_list_end;
obj_creation.current_object = dg_parse_vars->current_object;
struct geom_object *obj = dg_start_object_simple(
dg_parse_vars, &obj_creation, obj_name);
obj->object_type = POLY_OBJ;
dg_create_region(dg_parse_vars->reg_sym_table, obj, "ALL");
dg_parse_vars->object_name_list = obj_creation.object_name_list;
dg_parse_vars->object_name_list_end = obj_creation.object_name_list_end;
dg_parse_vars->current_object = obj;
return obj;
}
/***************************************************************************
dg_finish_object:
"Finishes" a new object, undoing the state changes that occurred when the
object was "started". This means popping the name off of the object name
stack, and resetting current_object to its value before this object was
defined.
In: dg_parse_vars: state of dynamic geometry parser
Out: none
Note: This is similar to mdl_finish_object.
***************************************************************************/
void dg_finish_object(struct dyngeom_parse_vars *dg_parse_vars) {
struct object_creation obj_creation;
obj_creation.object_name_list_end = dg_parse_vars->object_name_list_end;
pop_object_name(&obj_creation);
dg_parse_vars->object_name_list_end = obj_creation.object_name_list_end;
dg_parse_vars->current_object = dg_parse_vars->current_object->parent;
}
/***************************************************************************
dg_create_region:
Create a named region on an object.
In: reg_sym_table: the symbol table for all the regions
objp: fully qualified object name
reg_name: reg_name of the region to define
Out: The new region.
Note: This is similar to mdl_create_region.
***************************************************************************/
struct region *dg_create_region(
struct sym_table_head *reg_sym_table,
struct geom_object *objp,
const char *reg_name) {
struct region *reg;
struct region_list *reg_list;
if ((reg = dg_make_new_region(reg_sym_table, objp->sym->name, reg_name)) ==
NULL) {
mcell_error("Region already defined: %s", reg_name);
}
if ((reg_list = CHECKED_MALLOC_STRUCT(struct region_list, "region list")) ==
NULL) {
return NULL;
}
reg->flags = 0;
reg->region_last_name = reg_name;
reg->manifold_flag = IS_MANIFOLD;
reg->parent = objp;
reg_list->reg = reg;
reg_list->next = objp->regions;
objp->regions = reg_list;
objp->num_regions++;
return reg;
}
/***************************************************************************
dg_make_new_region:
Create a new region, adding it to the DG symbol table.
full region names of REG type symbols stored in main symbol table have the
form:
metaobj.metaobj.poly,region_last_name
In: reg_sym_table: the symbol table for all the regions
objp: fully qualified object name
region_last_name: name of the region to define
Out: The newly created region
Note: This is similar to mdl_make_new_region.
***************************************************************************/
struct region *dg_make_new_region(
struct sym_table_head *reg_sym_table,
const char *obj_name,
const char *region_last_name) {
char *region_name;
region_name = CHECKED_SPRINTF("%s,%s", obj_name, region_last_name);
if (region_name == NULL) {
return NULL;
}
struct sym_entry *sym_ptr;
if ((sym_ptr = retrieve_sym(region_name, reg_sym_table)) != NULL) {
free(region_name);
if (sym_ptr->count == 0) {
sym_ptr->count = 1;
return (struct region *)sym_ptr->value;
}
else {
return NULL;
}
}
if ((sym_ptr = store_sym(region_name, REG, reg_sym_table, NULL)) == NULL) {
free(region_name);
return NULL;
}
free(region_name);
return (struct region *)sym_ptr->value;
}
/***************************************************************************
dg_copy_object_regions:
Duplicate src_obj's regions on dst_obj.
In: dst_obj: destination object
src_obj: object from which to copy
Out: 0 on success, 1 on failure
Note: This is similar to mdl_copy_object_regions.
***************************************************************************/
int dg_copy_object_regions(
struct dyngeom_parse_vars *dg_parse_vars,
struct geom_object *dst_obj,
struct geom_object *src_obj) {
struct region_list *src_rlp;
struct region *dst_reg, *src_reg;
/* Copy each region */
for (src_rlp = src_obj->regions; src_rlp != NULL; src_rlp = src_rlp->next) {
src_reg = src_rlp->reg;
if ((dst_reg = dg_create_region(
dg_parse_vars->reg_sym_table, dst_obj, src_reg->region_last_name)) == NULL)
return 1;
/* Copy over simple region attributes */
dst_reg->surf_class = src_reg->surf_class;
dst_reg->flags = src_reg->flags;
dst_reg->area = src_reg->area;
dst_reg->bbox = src_reg->bbox;
dst_reg->manifold_flag = src_reg->manifold_flag;
}
return 0;
}
/***************************************************************************
dg_deep_copy_object:
Deep copy an object. The destination object should already be added to the
symbol table, but should be otherwise unpopulated, as no effort is made to
free any existing data contained in the object.
In: dst_obj: object into which to copy
src_obj: object from which to copy
Out: The newly created object
Note: This is similar to mdl_deep_copy_object.
***************************************************************************/
int dg_deep_copy_object(
struct dyngeom_parse_vars *dg_parse_vars,
struct geom_object *dst_obj,
struct geom_object *src_obj) {
struct geom_object *src_child;
/* Copy over simple object attributes */
dst_obj->object_type = src_obj->object_type;
/* Copy over regions */
if (dg_copy_object_regions(dg_parse_vars, dst_obj, src_obj))
return 1;
struct sym_entry *src_sym = retrieve_sym(src_obj->sym->name, dg_parse_vars->obj_sym_table);
if (src_sym == NULL) {
mcell_error("Cannot retrieve %s", src_obj->sym->name);
}
struct sym_entry *dst_sym = retrieve_sym(dst_obj->sym->name, dg_parse_vars->obj_sym_table);
if (dst_sym == NULL) {
mcell_error("Cannot retrieve %s", dst_obj->sym->name);
}
src_sym->value = src_obj;
dst_sym->value = dst_obj;
switch (dst_obj->object_type) {
case META_OBJ:
/* Copy children */
for (src_child = src_obj->first_child; src_child != NULL;
src_child = src_child->next) {
struct geom_object *dst_child;
char *child_obj_name =
CHECKED_SPRINTF("%s.%s", dst_obj->sym->name, src_child->last_name);
if (child_obj_name == NULL)
return 1;
/* Create child object */
int error_code = 0;
if ((dst_child = make_new_object(dg_parse_vars, dg_parse_vars->obj_sym_table, child_obj_name, &error_code)) == NULL) {
free(child_obj_name);
return 1;
}
free(child_obj_name);
/* Copy in last name */
dst_child->last_name = strdup(src_child->last_name);
free(src_child->last_name);
src_child->last_name = NULL;
if (dst_child->last_name == NULL)
return 1;
/* Recursively copy object and its children */
if (dg_deep_copy_object(dg_parse_vars, dst_child, src_child))
return 1;
dst_child->parent = dst_obj;
dst_child->next = NULL;
add_child_objects(dst_obj, dst_child, dst_child);
}
break;
case POLY_OBJ:
case REL_SITE_OBJ:
case BOX_OBJ:
case VOXEL_OBJ:
default:
return 0;
}
return 0;
}
/***************************************************************************
dg_existing_object:
Find an existing object.
In: parse_state: parser state
name: fully qualified object name
Out: the object
Note: This is similar to mdl_existing_object.
***************************************************************************/
struct sym_entry *dg_existing_object(struct dyngeom_parse_vars *dg_parse_vars, char *name) {
// Check to see if it is one of the objects that will be added in
// the future via a dynamic geometry event.
return retrieve_sym(name, dg_parse_vars->obj_sym_table);
}
char *find_include_file(char const *path, char const *cur_path) {
char *candidate = NULL;
if (path[0] == '/')
candidate = strdup(path);
else {
const char *last_slash = strrchr(cur_path, '/');
#ifdef _WIN64
const char *last_bslash = strrchr(cur_path, '\\');
if (last_bslash > last_slash)
last_slash = last_bslash;
#endif
if (last_slash == NULL)
candidate = strdup(path);
else
candidate = CHECKED_SPRINTF("%.*s/%s", (int)(last_slash - cur_path),
cur_path, path);
}
return candidate;
}
| C |
3D | mcellteam/mcell | src/util.h | .h | 10,201 | 301 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include <stdio.h>
#include <stdint.h>
#define COUNT_OF(arr) (sizeof((arr)) / sizeof((arr[0])))
#define BLOCK_SIZE 10000
struct num_expr_list_head {
// we cannot define ctor because it is used in bison's uniopn for
// semantic values
// however, the start_end_step_set is used only for partition setup
// and for this case the structure is initialized correctly
/*num_expr_list_head()
: start_end_step_set(false) {}*/
struct num_expr_list *value_head;
struct num_expr_list *value_tail;
int value_count;
int shared;
// MCell4 - original values used to create the list
bool start_end_step_set;
double start;
double end;
double step;
};
struct iteration_counter {
long long *iterations; /* array of iteration numbers, should be
memory allocated */
int max_iterations; /* size of the above array */
int n_iterations; /* number of the filled positions in an above array */
};
struct string_buffer {
char **strings; /* array of strings, should be memory allocated */
int max_strings; /* size of the above array */
int n_strings; /* number of the filled positions in an above array */
};
struct bit_array {
int nbits;
int nints;
/* Bit array data runs off the end of this struct */
};
struct bit_array *new_bit_array(int bits);
struct bit_array *duplicate_bit_array(struct bit_array *old);
int get_bit(struct bit_array *ba, int idx);
void set_bit(struct bit_array *ba, int idx, int value);
void set_bit_range(struct bit_array *ba, int idx1, int idx2, int value);
void set_all_bits(struct bit_array *ba, int value);
void bit_operation(struct bit_array *ba, struct bit_array *bb, char op);
int count_bits(struct bit_array *ba);
void free_bit_array(struct bit_array *ba);
int bisect(double *list, int n, double val);
int bisect_near(double *list, int n, double val);
int bisect_high(double *list, int n, double val);
int distinguishable(double a, double b, double eps);
int is_reverse_abbrev(const char *abbrev, const char *full);
struct void_list {
struct void_list *next;
void *data;
};
struct void_list *void_list_sort(struct void_list *vl);
struct void_list *void_list_sort_by(struct void_list *vl,
int (*leq)(void *, void *));
int remove_both_duplicates(struct void_list **head);
void delete_void_list(struct void_list *head);
int void_array_search(void **array, int n, void *to_find);
int void_ptr_compare(void const *v1, void const *v2);
unsigned int *allocate_uint_array(int size, unsigned int value);
void **allocate_ptr_array(int size);
void free_ptr_array(void **pa, int count);
struct num_expr_list;
void free_num_expr_list(struct num_expr_list *nel);
int dir_exists(char const *path);
int is_writable_dir(char const *path);
int mkdirs(char const *path);
int make_parent_dir(char const *path);
FILE *open_file(char const *fname, char const *mode);
double erfcinv(double v);
int poisson_dist(double lambda, double p);
void byte_swap(void *data, int size);
int feral_strlenn(char *feral, int n);
int is_feral_nabbrev(char *feral, int n, char *tame);
char *feral_strstrn(char *tame_haystack, char *feral_needle, int n);
int is_wildcard_match(char *wild, char *tame);
int initialize_string_buffer(struct string_buffer *sb, int maxstr);
int destroy_string_buffer(struct string_buffer *sb);
int add_string_to_buffer(struct string_buffer *sb, char *str);
double convert_seconds_to_iterations(
long long start_iterations,
double time_step_seconds,
double simulation_start_seconds,
double seconds);
double convert_iterations_to_seconds(
long long start_iterations,
double time_step_seconds,
double simulation_start_seconds,
double iterations);
/*******************************************************************
Pointer hashes
Essentially, pointer hashes are pointer -> pointer hash tables. There is no
restriction on the type of pointer used for the key, but a hash value must
be supplied along with the pointer whenever performing any operation that
requires a key. Neither the key, nor the value pointer are ever dereferenced
or freed by the pointer hash code.
Usage:
struct pointer_hash hash;
if (pointer_hash_init(&hash)) { fail }
pointer_hash_add(&hash, key1, hash1, value1);
pointer_hash_add(&hash, key2, hash2, value2);
..
pointer_hash_add(&hash, keyN, hashN, valueN);
..
void *value1 = pointer_hash_lookup(&hash, key1, hash1);
..
pointer_hash_destroy(&hash);
Note: The pointer hash allocates some memory, which will be orphaned
if pointer_hash_destroy is not called on the hash before it goes out
of scope.
The hash table collision strategy implemented by this structure is a
streaming strategy, rather than a chaining strategy. This means that
when we try to insert a value into the n-th bin, if the n-th bin is
already occupied, we will move to the n+1-th bin (modulo table size)
until we find an insertion point. When we do a lookup, therefore, we
need to scan forward until we either find our key, or until we find
an empty bin. We can ensure that at least one of these conditions is
met by always keeping the table size greater than the number of
entries.
Currently, the pointer hash is tuned to keep the table size between 2
and 4 times the number of items it contains.
*******************************************************************/
struct pointer_hash {
int num_items; /* num items in table */
int table_size; /* size of table */
unsigned int *hashes; /* hash values for each entry */
void const **keys; /* keys for each entry */
void **values; /* values for each entry */
};
/* Initialize a pointer hash to a given initial size. Returns 0 on
* success. */
int pointer_hash_init(struct pointer_hash *ht, int size);
/* Quickly clear all values from a pointer hash. Does not free any
* memory. */
void pointer_hash_clear(struct pointer_hash *ht);
/* Destroy a pointer hash, freeing all memory associated with it. */
void pointer_hash_destroy(struct pointer_hash *ht);
/* Manually resize a pointer hash to have at least 'new_size' bins.
* New size may exceed requested size. */
int pointer_hash_resize(struct pointer_hash *ht, int new_size);
/* Add a value to a pointer hash. If a previous item was added for
* that key, the new value will replace the old value. */
int pointer_hash_add(struct pointer_hash *ht, void const *key,
unsigned int keyhash, void *value);
/* Look up a value in a pointer hash. Returns NULL if no item was
* found, or if the value associated with the key was NULL. */
#define pointer_hash_lookup(ht, key, keyhash) \
pointer_hash_lookup_ext(ht, key, keyhash, NULL)
/* Look up a value in a pointer hash. Returns NULL if no item was
* found, or if the value associated with the key was NULL. */
void *pointer_hash_lookup_ext(struct pointer_hash const *ht, void const *key,
unsigned int keyhash, void *default_value);
/* Remove a value from a pointer hash. Returns 0 if the item was
* successfully removed, or 0 if the item was not found.
*/
int pointer_hash_remove(struct pointer_hash *ht, void const *key,
unsigned int keyhash);
int double_cmp(void const *i1, void const *i2);
int is_string_present_in_string_array(const char * str, char ** strings, int length);
int generate_range(struct num_expr_list_head *list, double start, double end,
double step);
int advance_range(struct num_expr_list_head *list, double tmp_dbl);
void free_numeric_list(struct num_expr_list *nel);
/*******************************************************************
Inline min/max functions
*******************************************************************/
static inline double min2d(double x, double y) { return (x < y) ? x : y; }
static inline int min2i(int x, int y) { return (x < y) ? x : y; }
static inline double max2d(double x, double y) { return (x > y) ? x : y; }
static inline int max2i(int x, int y) { return (x > y) ? x : y; }
static inline double min3d(double x, double y, double z) {
return (z < y) ? ((z < x) ? z : x) : ((y < x) ? y : x);
}
static inline int min3i(int x, int y, int z) {
return (z < y) ? ((z < x) ? z : x) : ((y < x) ? y : x);
}
static inline double max3d(double x, double y, double z) {
return (z > y) ? ((z > x) ? z : x) : ((y > x) ? y : x);
}
static inline int max3i(int x, int y, int z) {
return (z > y) ? ((z > x) ? z : x) : ((y > x) ? y : x);
}
static inline long long min3ll(long long x, long long y, long long z) {
return (z < y) ? ((z < x) ? z : x) : ((y < x) ? y : x);
}
static inline long long max3ll(long long x, long long y, long long z) {
return (z > y) ? ((z > x) ? z : x) : ((y > x) ? y : x);
}
/* Return minimum value from the array of N doubles */
static inline double minNd(double *array, int N) {
double smallest;
N -= 2;
for (smallest = array[N + 1]; N >= 0; N--) {
if (array[N] < smallest)
smallest = array[N];
}
return smallest;
}
/* Return minimum value from the array of N integers */
static inline int minNi(int *array, int N) {
int smallest;
N -= 2;
for (smallest = array[N + 1]; N >= 0; N--) {
if (array[N] < smallest)
smallest = array[N];
}
return smallest;
}
struct rusage;
void reset_rusage(rusage* r);
#ifndef ISAAC64_H
/* These guys come in for free if we're using Jenkins' random numbers */
typedef uint32_t ub4; /* unsigned 4-byte quantities */
typedef unsigned char ub1; /* unsigned 1-byte quantities */
#endif
ub4 jenkins_hash(ub1 *sym, ub4 length);
| Unknown |
3D | mcellteam/mcell | src/triangle_overlap.c | .c | 6,430 | 201 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/* The triangle overlap code in this file is based on the triangle/triangle
* intersection test routine by by Tomas Moller, 1997.
*
* See article "A Fast Triangle-Triangle Intersection Test",
* Journal of Graphics Tools, 2(2), 1997
*
* In contrast to Moller's general triangle-triangle intersection routine
* our code only tests for area overlap of coplanar triangles.
* In particular it will treat triangles which share an edge or vertex as
* non-overlapping. Only triangles with a bona-fide area overlap will be
* flagged.
*
* The code returns 1 if the provided triangles have an area overlap and 0
* otherwise.
*/
#include <stdbool.h>
#include <math.h>
#include "triangle_overlap.h"
#define EPSILON EPS_C
/* some macros */
#define CROSS(dest, v1, v2) \
{ \
dest[0] = v1[1] * v2[2] - v1[2] * v2[1]; \
dest[1] = v1[2] * v2[0] - v1[0] * v2[2]; \
dest[2] = v1[0] * v2[1] - v1[1] * v2[0]; \
}
#define SUB(dest, v1, v2) \
{ \
dest[0] = v1[0] - v2[0]; \
dest[1] = v1[1] - v2[1]; \
dest[2] = v1[2] - v2[2]; \
}
/* this edge to edge test is based on Franlin Antonio's gem:
* "Faster Line Segment Intersection", in Graphics Gems III,
* pp. 199-202 */
static inline int edge_edge_test(double* V0, double* U0, double* U1, short i0,
short i1, double Ax, double Ay) {
double Bx = U0[i0] - U1[i0];
double By = U0[i1] - U1[i1];
double Cx = V0[i0] - U0[i0];
double Cy = V0[i1] - U0[i1];
double f = Ay * Bx - Ax * By;
double d = By * Cx - Bx * Cy;
if ((f > 0 && d >= 0 && d <= f) || (f < 0 && d <= 0 && d >= f)) {
double e = Ax * Cy - Ay * Cx;
// ignore edge or vertex overlaps
bool dz = !distinguishable(d, 0.0, EPSILON);
bool ez = !distinguishable(e, 0.0, EPSILON);
bool df = !distinguishable(d, f, EPSILON);
bool ef = !distinguishable(e, f, EPSILON);
if ((dz && ez) || (dz && ef) || (df && ez) || (df && ef)) {
return 0;
}
if (f > 0) {
if (e >= 0 && e <= f) return 1;
} else {
if (e <= 0 && e >= f) return 1;
}
}
return 0;
}
/* edge_against_tri_edges tests if edge V0V1 intersects with any edge of
* triangle U0U1U2 */
static inline int edge_against_tri_edges(double* V0, double* V1, double* U0,
double* U1, double* U2, short i0,
short i1) {
double Ax = V1[i0] - V0[i0];
double Ay = V1[i1] - V0[i1];
/* test edge U0,U1 against V0,V1 */
if (edge_edge_test(V0, U0, U1, i0, i1, Ax, Ay)) {
return 1;
}
/* test edge U1,U2 against V0,V1 */
if (edge_edge_test(V0, U1, U2, i0, i1, Ax, Ay)) {
return 1;
};
/* test edge U2,U1 against V0,V1 */
if (edge_edge_test(V0, U2, U0, i0, i1, Ax, Ay)) {
return 1;
}
return 0;
}
/* point_in_tri tests if point V0 is contained in triangle U0U1U2 */
static inline int point_in_tri(double* V0, double* U0, double* U1, double* U2,
short i0, short i1) {
/* is T1 completly inside T2? */
/* check if V0 is inside tri(U0,U1,U2) */
double a = U1[i1] - U0[i1];
double b = -(U1[i0] - U0[i0]);
double c = -a * U0[i0] - b * U0[i1];
double d0 = a * V0[i0] + b * V0[i1] + c;
a = U2[i1] - U1[i1];
b = -(U2[i0] - U1[i0]);
c = -a * U1[i0] - b * U1[i1];
double d1 = a * V0[i0] + b * V0[i1] + c;
a = U0[i1] - U2[i1];
b = -(U0[i0] - U2[i0]);
c = -a * U2[i0] - b * U2[i1];
double d2 = a * V0[i0] + b * V0[i1] + c;
if (d0 * d1 > 0.0) {
if (d0 * d2 > 0.0) return 1;
}
return 0;
}
/* coplanar_tri_tri checks if triangles V0V1V2 and U0U1U2 have area overlap. */
static inline int coplanar_tri_tri(double* N, double* V0, double* V1,
double* V2, double* U0, double* U1,
double* U2) {
double A[3];
short i0, i1;
/* first project onto an axis-aligned plane, that maximizes the area */
/* of the triangles, compute indices: i0,i1. */
A[0] = fabs(N[0]);
A[1] = fabs(N[1]);
A[2] = fabs(N[2]);
if (A[0] > A[1]) {
if (A[0] > A[2]) {
i0 = 1; /* A[0] is greatest */
i1 = 2;
} else {
i0 = 0; /* A[2] is greatest */
i1 = 1;
}
} else /* A[0]<=A[1] */
{
if (A[2] > A[1]) {
i0 = 0; /* A[2] is greatest */
i1 = 1;
} else {
i0 = 0; /* A[1] is greatest */
i1 = 2;
}
}
/* test all edges of triangle 1 against the edges of triangle 2 */
if (edge_against_tri_edges(V0, V1, U0, U1, U2, i0, i1) ||
edge_against_tri_edges(V1, V2, U0, U1, U2, i0, i1) ||
edge_against_tri_edges(V2, V0, U0, U1, U2, i0, i1)) {
return 1;
}
/* finally, test if tri1 is totally contained in tri2 or vice versa */
if (point_in_tri(V0, U0, U1, U2, i0, i1) ||
point_in_tri(U0, V0, V1, V2, i0, i1)) {
return 1;
}
return 0;
}
/* coplanar_tri_operlap tests if w1 and w2 overlap and returns 1 if yes
* and 0 otherwise.
*
* NOTE 1: w1 and w2 are assumed to be coplanar.
* NOTE 2: this function will only return 1 if w1 and w2 have a bona
* fide area overlap. If w1 and w2 share an edge or vertex
* this will *not* be treated as an overlap.
*/
int coplanar_tri_overlap(struct wall* w1, struct wall* w2) {
double V0[3] = {w1->vert[0]->x, w1->vert[0]->y, w1->vert[0]->z};
double V1[3] = {w1->vert[1]->x, w1->vert[1]->y, w1->vert[1]->z};
double V2[3] = {w1->vert[2]->x, w1->vert[2]->y, w1->vert[2]->z};
double U0[3] = {w2->vert[0]->x, w2->vert[0]->y, w2->vert[0]->z};
double U1[3] = {w2->vert[1]->x, w2->vert[1]->y, w2->vert[1]->z};
double U2[3] = {w2->vert[2]->x, w2->vert[2]->y, w2->vert[2]->z};
/* compute plane equation of triangle(V0,V1,V2) */
double E1[3], E2[3];
SUB(E1, V1, V0);
SUB(E2, V2, V0);
double N1[3];
CROSS(N1, E1, E2);
/* plane equation 1: N1.X+d1=0 */
return coplanar_tri_tri(N1, V0, V1, V2, U0, U1, U2);
}
| C |
3D | mcellteam/mcell | src/minrng.c | .c | 857 | 33 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include "minrng.h"
ub4 mrng_generate(struct mrng_state *x) {
ub4 e = x->a - rot(x->b, 27);
x->a = x->b ^ rot(x->c, 17);
x->b = x->c + x->d;
x->c = x->d + e;
x->d = e + x->a;
return x->d;
}
void mrng_init(struct mrng_state *x, ub4 seed) {
ub4 i;
x->a = 0xf1ea5eed, x->b = x->c = x->d = seed;
for (i = 0; i < 20; ++i) {
(void)mrng_generate(x);
}
}
| C |
3D | mcellteam/mcell | src/wall_util.c | .c | 98,572 | 2,961 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "rng.h"
#include "logging.h"
#include "vector.h"
#include "util.h"
#include "init.h"
#include "sym_table.h"
#include "vol_util.h"
#include "mdlparse_util.h"
#include "grid_util.h"
#include "count_util.h"
#include "wall_util.h"
#include "react.h"
#include "nfsim_func.h"
#include "strfunc.h"
#include "debug_config.h"
#include "dump_state.h"
/* tetrahedralVol returns the (signed) volume of the tetrahedron spanned by
* the vertices a, b, c, and d.
* The formula was taken from "Computational Geometry" (2nd Ed) by J. O'Rourke
*/
static double tetrahedralVol(struct vector3 *a, struct vector3 *b,
struct vector3 *c, struct vector3 *d) {
return 1.0 / 6.0 * (-1 * (a->z - d->z) * (b->y - d->y) * (c->x - d->x) +
(a->y - d->y) * (b->z - d->z) * (c->x - d->x) +
(a->z - d->z) * (b->x - d->x) * (c->y - d->y) -
(a->x - d->x) * (b->z - d->z) * (c->y - d->y) -
(a->y - d->y) * (b->x - d->x) * (c->z - d->z) +
(a->x - d->x) * (b->y - d->y) * (c->z - d->z));
}
/* abs_max_2vec picks out the largest (absolute) value found among two vectors
* (useful for properly handling floating-point rounding error). */
static inline double abs_max_2vec(struct vector3 *v1, struct vector3 *v2) {
return max2d(max3d(fabs(v1->x), fabs(v1->y), fabs(v1->z)),
max3d(fabs(v2->x), fabs(v2->y), fabs(v2->z)));
}
// have_common_region checks if wall1 and wall2 located on the (same) object
// are part of a common region or not
static bool have_common_region(struct geom_object *obj, int wall1, int wall2);
/**************************************************************************\
** Edge construction section--builds permanent edges from hash table **
\**************************************************************************/
/***************************************************************************
compatible_edges:
In: array of pointers to walls
index of first wall
index of edge in first wall
index of second wall
index of edge in second wall
Out: 1 if the edge joins the two walls
0 if not (i.e. the wall doesn't contain the edge or the edge is
traversed in the same direction in each or the two walls are
actually the same wall)
***************************************************************************/
static int compatible_edges(struct wall **faces, int wA, int eA, int wB,
int eB) {
struct vector3 *vA0, *vA1, *vA2, *vB0, *vB1, *vB2;
if ((wA < 0) || (eA < 0) || (wB < 0) || (eB < 0))
return 0;
vA0 = faces[wA]->vert[eA];
if (eA == 2)
vA1 = faces[wA]->vert[0];
else
vA1 = faces[wA]->vert[eA + 1];
if (eA == 0)
vA2 = faces[wA]->vert[2];
else
vA2 = faces[wA]->vert[eA - 1];
vB0 = faces[wB]->vert[eB];
if (eB == 2)
vB1 = faces[wB]->vert[0];
else
vB1 = faces[wB]->vert[eB + 1];
if (eB == 0)
vB2 = faces[wB]->vert[2];
else
vB2 = faces[wB]->vert[eB - 1];
return ((vA0 == vB1 && vA1 == vB0 && vA2 != vB2) ||
(vA0->x == vB1->x && vA0->y == vB1->y && vA0->z == vB1->z &&
vA1->x == vB0->x && vA1->y == vB0->y && vA1->z == vB0->z &&
!(vA2->x == vB2->x && vA2->y == vB2->y && vA2->z == vB2->z)));
}
/*****************************************************************************
have_common_region checks if wall1 and wall2 located on the (same) object
are part of a common region or not
******************************************************************************/
bool have_common_region(struct geom_object *obj, int wall1, int wall2) {
struct region_list *rl = obj->regions;
bool common_region = false;
while (rl != NULL) {
struct region *r = rl->reg;
if (strcmp(r->region_last_name, "ALL") == 0) {
rl = rl->next;
continue;
}
if (get_bit(r->membership, wall1) && get_bit(r->membership, wall2)) {
common_region = true;
break;
}
rl = rl->next;
}
return common_region;
}
/***************************************************************************
refine_edge_pairs:
In: the head of a linked list of shared edges
array of pointers to walls
Out: No return value. The best-matching pair of edges percolates up
to be first in the list. "Best-matching" means that the edge
is traversed in different directions by each face, and that the
normals of the two faces are as divergent as possible.
***************************************************************************/
static void refine_edge_pairs(struct poly_edge *p, struct wall **faces) {
#define TSWAP(x, y) \
temp = (x); \
(x) = (y); \
(y) = temp
int temp;
double best_align = 2;
bool share_region = false;
struct poly_edge *best_p1 = p, *best_p2 = p;
int best_n1 = 1;
int best_n2 = 2;
struct poly_edge *p1 = p;
int n1 = 1;
while (p1 != NULL && p1->n >= n1) {
int wA, eA;
if (n1 == 1) {
wA = p1->face[0];
eA = p1->edge[0];
} else {
wA = p1->face[1];
eA = p1->edge[1];
}
struct poly_edge *p2;
int n2;
if (n1 == 1) {
n2 = n1 + 1;
p2 = p1;
} else {
n2 = 1;
p2 = p1->next;
}
while (p2 != NULL && p2->n >= n2) {
int wB, eB;
if (n2 == 1) {
wB = p2->face[0];
eB = p2->edge[0];
} else {
wB = p2->face[1];
eB = p2->edge[1];
}
// as soon as we hit an incompatible edge we can break out of the p2 loop
// and continue scanning the next p1
if (compatible_edges(faces, wA, eA, wB, eB)) {
double align = faces[wA]->normal.x * faces[wB]->normal.x +
faces[wA]->normal.y * faces[wB]->normal.y +
faces[wA]->normal.z * faces[wB]->normal.z;
// as soon as two walls have a common region we only consider walls who
// share (any) region. We need to reset the best_align to make sure we
// don't pick any wall that don't share a region discovered previously
bool common_region = have_common_region(faces[wA]->parent_object, wA, wB);
if (common_region) {
if (!share_region) {
best_align = 2;
}
share_region = true;
}
if (common_region || !share_region) {
if (align < best_align) {
best_p1 = p1;
best_p2 = p2;
best_n1 = n1;
best_n2 = n2;
best_align = align;
}
}
} else {
break;
}
if (n2 == 1)
n2++;
else {
p2 = p2->next;
n2 = 1;
}
}
if (n1 == 1)
n1++;
else {
p1 = p1->next;
n1 = 1;
}
}
/* swap best match into top spot */
if (best_align > 1.0)
return; /* No good pairs. */
TSWAP(best_p1->face[best_n1-1], p->face[0]);
TSWAP(best_p1->edge[best_n1-1], p->edge[0]);
TSWAP(best_p2->face[best_n2-1], p->face[1]);
TSWAP(best_p2->edge[best_n2-1], p->edge[1]);
#undef TSWAP
}
/***************************************************************************
surface_net:
In: array of pointers to walls
integer length of array
Out: -1 if the surface is a manifold, 0 if it is not, 1 on malloc failure
Walls end up connected across their edges.
Note: Two edges must have their vertices listed in opposite order (i.e.
connect two faces pointing the same way) to be linked. If more than
two faces share the same edge and can be linked, the faces with
normals closest to each other will be linked. We do not assume that
the object is connected. All pieces must be a manifold, however,
for the entire object to be a manifold. (That is, there must not
be any free edges anywhere.) It is possible to build weird, twisty
self-intersecting things. The behavior of these things during a
simulation is not guaranteed to be well-defined.
***************************************************************************/
int surface_net(struct wall **facelist, int nfaces) {
struct edge *e;
int is_closed = 1;
struct edge_hashtable eht;
int nkeys = (3 * nfaces) / 2;
if (ehtable_init(&eht, nkeys))
return 1;
for (int i = 0; i < nfaces; i++) {
if (facelist[i] == NULL)
continue;
int k;
int nedge = 3;
for (int j = 0; j < nedge; j++) {
if (j + 1 < nedge)
k = j + 1;
else
k = 0;
struct poly_edge pe;
pe.v1x = facelist[i]->vert[j]->x;
pe.v1y = facelist[i]->vert[j]->y;
pe.v1z = facelist[i]->vert[j]->z;
pe.v2x = facelist[i]->vert[k]->x;
pe.v2y = facelist[i]->vert[k]->y;
pe.v2z = facelist[i]->vert[k]->z;
pe.face[0] = i;
pe.edge[0] = j;
if (ehtable_add(&eht, &pe))
return 1;
}
}
for (int i = 0; i < nkeys; i++) {
struct poly_edge *pep = (eht.data + i);
#ifdef DEBUG_GEOM_OBJ_INITIALIZATION
dump_poly_edge(i, pep);
#endif
while (pep != NULL) {
if (pep->n > 2) {
refine_edge_pairs(pep, facelist);
}
if (pep->n >= 2) {
if (pep->face[0] != -1 && pep->face[1] != -1) {
if (compatible_edges(facelist, pep->face[0], pep->edge[0], pep->face[1],
pep->edge[1])) {
facelist[pep->face[0]]->nb_walls[pep->edge[0]] = facelist[pep->face[1]];
facelist[pep->face[1]]->nb_walls[pep->edge[1]] = facelist[pep->face[0]];
e = (struct edge *)CHECKED_MEM_GET_NODIE(
facelist[pep->face[0]]->birthplace->join, "edge");
if (e == NULL)
return 1;
e->forward = facelist[pep->face[0]];
e->backward = facelist[pep->face[1]];
init_edge_transform(e, pep->edge[0]);
facelist[pep->face[0]]->edges[pep->edge[0]] = e;
facelist[pep->face[1]]->edges[pep->edge[1]] = e;
}
} else {
is_closed = 0;
}
} else if (pep->n == 1) {
is_closed = 0;
e = (struct edge *)CHECKED_MEM_GET_NODIE(
facelist[pep->face[0]]->birthplace->join, "edge");
if (e == NULL)
return 1;
e->forward = facelist[pep->face[0]];
e->backward = NULL;
/* Don't call init_edge_transform unless both edges are set */
facelist[pep->face[0]]->edges[pep->edge[0]] = e;
}
pep = pep->next;
}
}
ehtable_kill(&eht);
return -is_closed; /* We use 1 to indicate malloc failure so return 0/-1 */
}
/***************************************************************************
init_edge_transform
In: e: pointer to an edge
edgenum: integer telling which edge (0-2) of the "forward" face we are
Out: No return value. Coordinate transform in edge struct is set.
Note: Don't call this on a non-shared edge.
***************************************************************************/
void init_edge_transform(struct edge *e, int edgenum) {
struct vector2 O_f, O_b;
struct vector2 ehat_f, ehat_b;
struct vector2 fhat_f, fhat_b;
struct wall *wf = e->forward;
struct wall *wb = e->backward;
int i = edgenum;
int j = i + 1;
if (j > 2)
j = 0;
#ifdef DEBUG_EDGE_INITIALIZATION
std::cout << "Edge initialization, edgenum: " << edgenum << "\n";
dump_wall(wf, "", true);
dump_wall(wb, "", true);
#endif
// only for mcell4
e->edge_num_used_for_init = edgenum;
/* Intermediate basis from the perspective of the forward frame */
struct vector3 temp3d;
temp3d.x = wf->vert[i]->x - wf->vert[0]->x;
temp3d.y = wf->vert[i]->y - wf->vert[0]->y;
temp3d.z = wf->vert[i]->z - wf->vert[0]->z;
O_f.u = dot_prod(&temp3d, &(wf->unit_u));
O_f.v = dot_prod(&temp3d, &(wf->unit_v)); /* Origin */
temp3d.x = wf->vert[j]->x - wf->vert[0]->x;
temp3d.y = wf->vert[j]->y - wf->vert[0]->y;
temp3d.z = wf->vert[j]->z - wf->vert[0]->z;
struct vector2 temp;
temp.u = dot_prod(&temp3d, &(wf->unit_u)) - O_f.u;
temp.v = dot_prod(&temp3d, &(wf->unit_v)) - O_f.v; /* Far side of e */
assert(temp.u * temp.u + temp.v * temp.v != 0);
double d = 1.0 / sqrt(temp.u * temp.u + temp.v * temp.v);
ehat_f.u = temp.u * d;
ehat_f.v = temp.v * d; /* ehat along edge */
fhat_f.u = -ehat_f.v;
fhat_f.v = ehat_f.u; /* fhat 90 degrees CCW */
/* Intermediate basis from the perspective of the backward frame */
temp3d.x = wf->vert[i]->x - wb->vert[0]->x;
temp3d.y = wf->vert[i]->y - wb->vert[0]->y;
temp3d.z = wf->vert[i]->z - wb->vert[0]->z;
O_b.u = dot_prod(&temp3d, &(wb->unit_u));
O_b.v = dot_prod(&temp3d, &(wb->unit_v)); /* Origin */
temp3d.x = wf->vert[j]->x - wb->vert[0]->x;
temp3d.y = wf->vert[j]->y - wb->vert[0]->y;
temp3d.z = wf->vert[j]->z - wb->vert[0]->z;
temp.u = dot_prod(&temp3d, &(wb->unit_u)) - O_b.u;
temp.v = dot_prod(&temp3d, &(wb->unit_v)) - O_b.v; /* Far side of e */
assert(temp.u * temp.u + temp.v * temp.v != 0);
d = 1.0 / sqrt(temp.u * temp.u + temp.v * temp.v);
ehat_b.u = temp.u * d;
ehat_b.v = temp.v * d; /* ehat along edge */
fhat_b.u = -ehat_b.v;
fhat_b.v = ehat_b.u; /* fhat 90 degrees CCW */
/* Calculate transformation matrix */
double mtx[2][2];
mtx[0][0] = ehat_f.u * ehat_b.u + fhat_f.u * fhat_b.u;
mtx[0][1] = ehat_f.v * ehat_b.u + fhat_f.v * fhat_b.u;
mtx[1][0] = ehat_f.u * ehat_b.v + fhat_f.u * fhat_b.v;
mtx[1][1] = ehat_f.v * ehat_b.v + fhat_f.v * fhat_b.v;
/* Calculate translation vector */
struct vector2 q;
q.u = O_b.u;
q.v = O_b.v;
q.u -= mtx[0][0] * O_f.u + mtx[0][1] * O_f.v;
q.v -= mtx[1][0] * O_f.u + mtx[1][1] * O_f.v;
/* Store the results */
e->cos_theta = mtx[0][0];
e->sin_theta = mtx[0][1];
e->translate.u = q.u;
e->translate.v = q.v;
#ifdef DEBUG_EDGE_INITIALIZATION
dump_edge(e, "", true);
#endif
}
/***************************************************************************
sharpen_object:
In: parent: pointer to an object
Out: 0 on success, 1 on failure.
Adds edges to the object and all its children.
***************************************************************************/
int sharpen_object(struct geom_object *parent) {
if (parent->object_type == POLY_OBJ || parent->object_type == BOX_OBJ) {
int i = surface_net(parent->wall_p, parent->n_walls);
if (i == 1) {
mcell_allocfailed(
"Failed to connect walls of object %s along shared edges.",
parent->sym->name);
}
else {
parent->is_closed = -i;
}
} else if (parent->object_type == META_OBJ) {
for (struct geom_object *o = parent->first_child; o != NULL; o = o->next) {
if (sharpen_object(o))
return 1;
}
}
return 0;
}
/***************************************************************************
sharpen_world:
In: nothing. Assumes if there are polygon objects then they have been
initialized and placed in the world in their correct memory locations.
Out: 0 on success, 1 on failure. Adds edges to every object.
***************************************************************************/
int sharpen_world(struct volume *world) {
for (struct geom_object *o = world->root_instance; o != NULL; o = o->next) {
if (sharpen_object(o))
return 1;
}
return 0;
}
/**************************************************************************\
** Geometry section--report on and use geometrical properties of object **
\**************************************************************************/
/***************************************************************************
closest_interior_point:
In: a point in 3D
a wall
the surface coordinates of the closest interior point on the wall
how far away the point can be before we give up
Out: return the distance^2 between the input point and closest point.
Sets closest interior point.
Note: the search distance currently isn't used. This function is just
a wrapper for closest_pt_point_triangle. If the closest point is
on an edge or corner, we scoot the point towards the centroid of
the triangle so we're contained fully within the triangle.
***************************************************************************/
double closest_interior_point(struct vector3 *pt, struct wall *w,
struct vector2 *ip, double r2) {
UNUSED(r2);
#ifdef DEBUG_CLOSEST_INTERIOR_POINT
std::cout << "closest_interior_point: " << *pt << "\n";
dump_wall(w, "", true);
#endif
struct vector3 v;
closest_pt_point_triangle(pt, w->vert[0], w->vert[1], w->vert[2], &v);
xyz2uv(&v, w, ip);
/* Check to see if we're lying on an edge; if so, scoot towards centroid. */
/* ip lies on edge of wall if cross products are zero */
int give_up_ctr = 0;
int give_up = 10;
double a1 = ip->u * w->uv_vert2.v - ip->v * w->uv_vert2.u;
double a2 = w->uv_vert1_u * ip->v;
struct vector2 vert_0 = {0, 0};
struct vector2 vert_1 = {w->uv_vert1_u, 0};
while (give_up_ctr < give_up &&
(!distinguishable(ip->v, 0, EPS_C) ||
!distinguishable(a1, 0, EPS_C) ||
!distinguishable(a1 + a2, 2.0 * w->area, EPS_C) ||
!point_in_triangle_2D(ip, &vert_0, &vert_1, &w->uv_vert2))) {
/* Move toward centroid. It's possible for this movement to be so small
* that we are essentially stuck in this loop, so bail out after a set
* number of tries. The number chosen is somewhat arbitrary. In most cases,
* one try is sufficent. */
ip->u = (1.0 - 5 * EPS_C) * ip->u +
5 * EPS_C * 0.333333333333333 * (w->uv_vert1_u + w->uv_vert2.u);
ip->v = (1.0 - 5 * EPS_C) * ip->v +
5 * EPS_C * 0.333333333333333 * w->uv_vert2.v;
a1 = ip->u * w->uv_vert2.v - ip->v * w->uv_vert2.u;
a2 = w->uv_vert1_u * ip->v;
give_up_ctr++;
}
double res = (v.x - pt->x) * (v.x - pt->x) + (v.y - pt->y) * (v.y - pt->y) +
(v.z - pt->z) * (v.z - pt->z);
#ifdef DEBUG_CLOSEST_INTERIOR_POINT
std::cout << "res: " << res << ", ip: " << *ip << "\n";
#endif
return res;
}
/***************************************************************************
find_edge_point:
In: here: a wall
loc: a point in the coordinate system of that wall where we are now
(assumed to be on or inside triangle)
disp: a 2D displacement vector to move
edgept: a place to store the coordinate on the edge, if we hit it
Out: index of the edge we hit (0, 1, or 2), or -1 if the new location
is within the wall, or -2 if we can't tell. If the result is
0, 1, or 2, edgept is set to the new location.
***************************************************************************/
int find_edge_point(struct wall *here,
struct vector2 *loc,
struct vector2 *disp,
struct vector2 *edgept) {
double f, s, t;
double lxd = loc->u * disp->v - loc->v * disp->u;
double lxc1 = -loc->v * here->uv_vert1_u;
double dxc1 = -disp->v * here->uv_vert1_u;
// Make sure that the displacement vector isn't on v0v1
if (dxc1 < -EPS_C || dxc1 > EPS_C) {
f = 1.0 / dxc1; /* f>0 is passing outwards */
s = -lxd * f;
if (0.0 < s && s < 1.0 && f > 0.0) {
t = -lxc1 * f;
if (EPS_C < t && t < 1.0) {
edgept->u = loc->u + t * disp->u;
edgept->v = loc->v + t * disp->v;
return 0;
} else if (t > 1.0 + EPS_C)
return -1;
/* else can't tell if we hit this edge, assume not */
}
}
double lxc2 = loc->u * here->uv_vert2.v - loc->v * here->uv_vert2.u;
double dxc2 = disp->u * here->uv_vert2.v - disp->v * here->uv_vert2.u;
// Make sure that the displacement vector isn't on v1v2
if (dxc2 < -EPS_C || dxc2 > EPS_C) {
f = 1.0 / dxc2; /* f<0 is passing outwards */
s = 1.0 + lxd * f;
if (0.0 < s && s < 1.0 && f < 0.0) {
t = -lxc2 * f;
if (EPS_C < t && t < 1.0) {
edgept->u = loc->u + t * disp->u;
edgept->v = loc->v + t * disp->v;
return 2;
} else if (t > 1.0 + EPS_C)
return -1;
/* else can't tell */
}
}
f = dxc2 - dxc1;
if (f < -EPS_C || f > EPS_C) {
f = 1.0 / f; /* f>0 is passing outwards */
s = -(lxd + dxc1) * f;
if (0.0 < s && s < 1.0 && f > 0.0) {
t = (here->uv_vert1_u * here->uv_vert2.v + lxc1 - lxc2) * f;
if (EPS_C < t && t < 1.0) {
edgept->u = loc->u + t * disp->u;
edgept->v = loc->v + t * disp->v;
return 1;
} else if (t > 1.0 + EPS_C)
return -1;
/* else can't tell */
}
}
return -2; /* Couldn't tell whether we hit or not--calling function should
pick another displacement */
}
/***************************************************************************
traverse_surface:
In: here: a wall
loc: a point in the coordinate system of that wall
which: which edge to travel off of
newloc: a vector to set for the new wall
Out: NULL if the edge is not shared, or a pointer to the wall in that
direction if it is shared. newloc is set to loc in the coordinate system
of the new wall (after flattening the walls along their shared edge)
***************************************************************************/
struct wall *traverse_surface(struct wall *here, struct vector2 *loc, int which,
struct vector2 *newloc) {
struct wall *there;
double u, v;
struct edge *e = here->edges[which];
if (e == NULL)
return NULL;
if (e->forward == here) {
/* Apply forward transform to loc */
there = e->backward;
/* rotation */
u = e->cos_theta * loc->u + e->sin_theta * loc->v;
v = -e->sin_theta * loc->u + e->cos_theta * loc->v;
/* translation */
newloc->u = u + e->translate.u;
newloc->v = v + e->translate.v;
return there;
} else {
/* Apply inverse transform to loc */
there = e->forward;
/* inverse translation */
u = loc->u - e->translate.u;
v = loc->v - e->translate.v;
/* inverse rotation */
newloc->u = e->cos_theta * u - e->sin_theta * v;
newloc->v = e->sin_theta * u + e->cos_theta * v;
return there;
}
}
/***************************************************************************
is_manifold:
In: r: A region. This region must already be painted on walls. The edges must
have already been added to the object (i.e. sharpened).
count_regions_flag: This is usually set, unless we are only checking
volumes for dynamic geometries.
Out: 1 if the region is a manifold, 0 otherwise.
Note: by "manifold" we mean "orientable compact two-dimensional
manifold without boundaries embedded in R3"
***************************************************************************/
int is_manifold(struct region *r, int count_regions_flag) {
struct wall **wall_array = NULL, *w = NULL;
struct region_list *rl = NULL;
if (r->bbox == NULL)
r->bbox = create_region_bbox(r);
wall_array = r->parent->wall_p;
if (wall_array == NULL) {
mcell_internal_error("Region '%s' has NULL wall array!", r->sym->name);
/*return 1;*/
}
// use the center of the region bounding box as reference point for
// computing the volume
struct vector3 llc = r->bbox[0];
struct vector3 urc = r->bbox[1];
struct vector3 d;
d.x = (llc.x + 0.5 * urc.x);
d.y = (llc.y + 0.5 * urc.y);
d.z = (llc.z + 0.5 * urc.z);
r->volume = 0.0;
for (int n_wall = 0; n_wall < r->parent->n_walls; n_wall++) {
if (!get_bit(r->membership, n_wall))
continue; /* Skip wall not in region */
w = wall_array[n_wall];
if (count_regions_flag) {
for (int nb = 0; nb < 3; nb++) {
if (w->nb_walls[nb] == NULL) {
mcell_error_nodie("BARE EDGE on wall %u edge %d.", n_wall, nb);
return 0; /* Bare edge--not a manifold */
}
for (rl = w->nb_walls[nb]->counting_regions; rl != NULL; rl = rl->next) {
if (rl->reg == r)
break;
}
if (rl == NULL) {
mcell_error_nodie("Wall %u edge %d leaves region!", n_wall, nb);
return 0; /* Can leave region--not a manifold */
}
}
}
// compute volume of tetrahedron with w as its face
r->volume += tetrahedralVol(w->vert[0], w->vert[1], w->vert[2], &d);
}
return 1;
}
/**************************************************************************\
** Collision section--detect whether rays intersect walls **
\**************************************************************************/
/***************************************************************************
jump_away_line:
In: starting coordinate
vector we were going to move along and need to change
fraction of way we moved before noticing we were hitting a edge
location of the first vertex of the edge
location of the second vertex of the edge
normal vector to the surface containing our edge
Out: No return value. Movement vector is slightly changed.
***************************************************************************/
void jump_away_line(struct vector3 *p, struct vector3 *v, double k,
struct vector3 *A, struct vector3 *B, struct vector3 *n,
struct rng_state *rng) {
ASSERT_FOR_MCELL4(false && "Called jump_away_line");
struct vector3 e, f;
double le_1, tiny;
e.x = B->x - A->x;
e.y = B->y - A->y;
e.z = B->z - A->z;
le_1 = 1.0 / sqrt(e.x * e.x + e.y * e.y + e.z * e.z);
e.x *= le_1;
e.y *= le_1;
e.z *= le_1;
f.x = n->y * e.z - n->z * e.y;
f.y = n->z * e.x - n->x * e.z;
f.z = n->x * e.y - n->y * e.x;
tiny = EPS_C * (abs_max_2vec(p, v) + 1.0) /
(k * max3d(fabs(f.x), fabs(f.y), fabs(f.z)));
if ((rng_uint(rng) & 1) == 0) {
tiny = -tiny;
}
v->x -= tiny * f.x;
v->y -= tiny * f.y;
v->z -= tiny * f.z;
}
/***************************************************************************
collide_wall:
In: point: starting coordinate
move: vector to move along
face: wall we're checking for a collision
t: double to store time of collision
hitpt: vector to store the location of the collision
update_move: flag to signal whether we should modify the movement vector
in an ambiguous case (i.e. if we hit an edge or corner); if not, any
ambiguous cases are treated as a miss.
Out: Integer value indicating what happened
COLLIDE_MISS missed
COLLIDE_FRONT hit the front face (face normal points out of)
COLLIDE_BACK hit the back face
COLLIDE_REDO hit an edge and modified movement vector; redo
Note: t and/or hitpt may be modified even if there is no collision
Not highly optimized yet. May want to project to Cartesian
coordinates for speed (as MCell2 did, and Rex implemented
in pre-40308 backups in vol_utils.c). When reflecting, use
the value of t returned, not hitpt (reflections happen slightly
early to avoid rounding errors with superimposed planes).
***************************************************************************/
int collide_wall(struct vector3 *point, struct vector3 *move, struct wall *face,
double *t, struct vector3 *hitpt, int update_move,
struct rng_state *rng, struct notifications *notify,
long long *ray_polygon_tests) {
double dp, dv, dd;
double nx, ny, nz;
double a, b, c;
double f, g, h;
double d_eps;
struct vector3 local;
if (notify->final_summary == NOTIFY_FULL) {
(*ray_polygon_tests)++;
}
nx = face->normal.x;
ny = face->normal.y;
nz = face->normal.z;
dp = nx * point->x + ny * point->y + nz * point->z;
dv = nx * move->x + ny * move->y + nz * move->z;
dd = dp - face->d;
if (dd > 0.0) {
d_eps = EPS_C;
if (dd < d_eps)
d_eps = 0.5 * dd;
/* Start & end above plane */
if (dd + dv > d_eps)
return COLLIDE_MISS;
} else {
d_eps = -EPS_C;
if (dd > d_eps)
d_eps = 0.5 * dd;
/* Start & end below plane */
if (dd < 0.0 && dd + dv < d_eps)
return COLLIDE_MISS;
}
if (dd == 0.0) {
/* Start beside plane, end above or below */
if (dv != 0.0)
return COLLIDE_MISS;
if (update_move) {
a = (abs_max_2vec(point, move) + 1.0) * EPS_C;
if ((rng_uint(rng) & 1) == 0)
a = -a;
if (dd == 0.0) {
move->x -= a * nx;
move->y -= a * ny;
move->z -= a * nz;
} else {
move->x *= (1.0 - a);
move->y *= (1.0 - a);
move->z *= (1.0 - a);
}
return COLLIDE_REDO;
} else
return COLLIDE_MISS;
}
a = 1.0 / dv;
a *= -dd; /* Time we actually hit */
*t = a;
hitpt->x = point->x + a * move->x;
hitpt->y = point->y + a * move->y;
hitpt->z = point->z + a * move->z;
local.x = hitpt->x - face->vert[0]->x;
local.y = hitpt->y - face->vert[0]->y;
local.z = hitpt->z - face->vert[0]->z;
b = local.x * face->unit_u.x + local.y * face->unit_u.y +
local.z * face->unit_u.z;
c = local.x * face->unit_v.x + local.y * face->unit_v.y +
local.z * face->unit_v.z;
if (face->uv_vert2.v < 0.0) {
c = -c;
f = -face->uv_vert2.v;
} else
f = face->uv_vert2.v;
if (c > 0) {
g = b * f;
h = c * face->uv_vert2.u;
if (g > h) {
if (c * face->uv_vert1_u + g < h + face->uv_vert1_u * face->uv_vert2.v) {
if (dv > 0)
return COLLIDE_BACK;
else
return COLLIDE_FRONT;
} else if ((!distinguishable(
c * face->uv_vert1_u + g,
h + face->uv_vert1_u * face->uv_vert2.v,
EPS_C))) {
if (update_move) {
jump_away_line(point, move, a, face->vert[1], face->vert[2],
&(face->normal), rng);
return COLLIDE_REDO;
} else
return COLLIDE_MISS;
} else
return COLLIDE_MISS;
} else if (!distinguishable(g, h, EPS_C)) {
if (update_move) {
jump_away_line(point, move, a, face->vert[2], face->vert[0],
&(face->normal), rng);
return COLLIDE_REDO;
} else
return COLLIDE_MISS;
} else
return COLLIDE_MISS;
} else if (!distinguishable(c, 0, EPS_C)) /* Hit first edge! */
{
if (update_move) {
jump_away_line(point, move, a, face->vert[0], face->vert[1],
&(face->normal), rng);
return COLLIDE_REDO;
} else
return COLLIDE_MISS;
} else
return COLLIDE_MISS;
}
/***************************************************************************
collide_mol:
In: starting coordinate
vector to move along
molecule we're checking for a collision
double to store time of collision
vector to store the location of the collision
Out: Integer value indicating what happened
COLLIDE_MISS missed
COLLIDE_VOL_M hit
Note: t and/or hitpt may be modified even if there is no collision
Not highly optimized yet.
***************************************************************************/
int collide_mol(struct vector3 *point, struct vector3 *move,
struct abstract_molecule *a, double *t, struct vector3 *hitpt,
double rx_radius_3d) {
struct vector3 dir; /* From starting point of moving molecule to target */
struct vector3 *pos; /* Position of target molecule */
double movelen2; /* Square of distance the moving molecule travels */
double dirlen2; /* Square of distance between moving and target molecules */
double d; /* Dot product of movement vector and vector to target */
double sigma2; /* Square of interaction radius */
if ((a->properties->flags & ON_GRID) != 0)
return COLLIDE_MISS; /* Should never call on surface molecule! */
pos = &(((struct volume_molecule *)a)->pos);
sigma2 = rx_radius_3d * rx_radius_3d;
dir.x = pos->x - point->x;
dir.y = pos->y - point->y;
dir.z = pos->z - point->z;
d = dir.x * move->x + dir.y * move->y + dir.z * move->z;
/* Miss the molecule if it's behind us */
if (d < 0)
return COLLIDE_MISS;
movelen2 = move->x * move->x + move->y * move->y + move->z * move->z;
/* check whether the test molecule is further than the displacement. */
if (d > movelen2)
return COLLIDE_MISS;
dirlen2 = dir.x * dir.x + dir.y * dir.y + dir.z * dir.z;
/* check whether the moving molecule will miss interaction disk of the
test molecule.*/
if (movelen2 * dirlen2 - d * d > movelen2 * sigma2)
return COLLIDE_MISS;
*t = d / movelen2;
// *t = d/sqrt(movelen2*dirlen2);
hitpt->x = point->x + (*t) * move->x;
hitpt->y = point->y + (*t) * move->y;
hitpt->z = point->z + (*t) * move->z;
return COLLIDE_VOL_M;
}
/***************************************************************************
wall_in_box:
In: array of pointers to vertices for wall (should be 3)
normal vector for wall
distance from wall to origin (point normal form)
first corner of bounding box
opposite corner of bounding box
Out: 1 if the wall intersects the box. 0 otherwise.
***************************************************************************/
static int wall_in_box(struct vector3 **vert, struct vector3 *normal, double d,
struct vector3 *b0, struct vector3 *b1) {
#define n_vert 3
int temp;
int i, j, k;
struct vector3 *v1, *v2;
struct vector3 n, u, v;
struct vector3 ba, bb, c;
double r, a1, a2, a3, a4, cu, cv;
double vu_[6]; /* Assume wall has 3 vertices */
double *vv_;
double d_box[8];
int n_opposite;
/* Lookup table for vertex-edge mapping for a cube */
int which_x1[12] = { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1 };
int which_y1[12] = { 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0 };
int which_z1[12] = { 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0 };
int which_x2[12] = { 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0 };
int which_y2[12] = { 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1 };
int which_z2[12] = { 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0 };
int edge1_vt[12] = { 0, 1, 3, 2, 6, 7, 5, 4, 0, 1, 3, 4 };
int edge2_vt[12] = { 1, 3, 2, 6, 7, 5, 4, 0, 2, 5, 7, 2 };
/* Check if any vertex of the wall is in the box. */
for (i = 0; i < n_vert; i++) {
v2 = vert[i];
if (v2->x >= b0->x && v2->x <= b1->x && v2->y >= b0->y && v2->y <= b1->y &&
v2->z >= b0->z && v2->z <= b1->z)
return 1;
}
/* Check if any wall edge intersects any face of the box */
for (i = 0; i < n_vert; i++) {
v2 = vert[i];
v1 = (i == 0) ? vert[n_vert - 1] : vert[i - 1];
/* x-faces */
if ((v1->x <= b0->x && b0->x < v2->x) ||
(v1->x > b0->x && b0->x >= v2->x)) {
r = (b0->x - v1->x) / (v2->x - v1->x);
a3 = v1->y + r * (v2->y - v1->y);
a4 = v1->z + r * (v2->z - v1->z);
if (b0->y <= a3 && a3 <= b1->y && b0->z <= a4 && a4 <= b1->z)
return 2;
}
if ((v1->x <= b1->x && b1->x < v2->x) ||
(v1->x > b1->x && b1->x >= v2->x)) {
r = (b1->x - v1->x) / (v2->x - v1->x);
a3 = v1->y + r * (v2->y - v1->y);
a4 = v1->z + r * (v2->z - v1->z);
if (b0->y <= a3 && a3 <= b1->y && b0->z <= a4 && a4 <= b1->z)
return 3;
}
/* y-faces */
if ((v1->y <= b0->y && b0->y < v2->y) ||
(v1->y > b0->y && b0->y >= v2->y)) {
r = (b0->y - v1->y) / (v2->y - v1->y);
a3 = v1->x + r * (v2->x - v1->x);
a4 = v1->z + r * (v2->z - v1->z);
if (b0->x <= a3 && a3 <= b1->x && b0->z <= a4 && a4 <= b1->z)
return 4;
}
if ((v1->y <= b1->y && b1->y < v2->y) ||
(v1->y > b1->y && b1->y >= v2->y)) {
r = (b1->y - v1->y) / (v2->y - v1->y);
a3 = v1->x + r * (v2->x - v1->x);
a4 = v1->z + r * (v2->z - v1->z);
if (b0->x <= a3 && a3 <= b1->x && b0->z <= a4 && a4 <= b1->z)
return 5;
}
/* z-faces */
if ((v1->z <= b0->z && b0->z < v2->z) ||
(v1->z > b0->z && b0->z >= v2->z)) {
r = (b0->z - v1->z) / (v2->z - v1->z);
a3 = v1->y + r * (v2->y - v1->y);
a4 = v1->x + r * (v2->x - v1->x);
if (b0->y <= a3 && a3 <= b1->y && b0->x <= a4 && a4 <= b1->x)
return 6;
}
if ((v1->z <= b1->z && b1->z < v2->z) ||
(v1->z > b1->z && b1->z >= v2->z)) {
r = (b1->z - v1->z) / (v2->z - v1->z);
a3 = v1->y + r * (v2->y - v1->y);
a4 = v1->x + r * (v2->x - v1->x);
if (b0->y <= a3 && a3 <= b1->y && b0->x <= a4 && a4 <= b1->x)
return 7;
}
}
/* Check if any box edge intersects the wall */
n_opposite = 0;
vv_ = &(vu_[n_vert]);
/* Wall coordinate system n,u,v */
n.x = normal->x;
n.y = normal->y;
n.z = normal->z;
u.x = vert[1]->x - vert[0]->x;
u.y = vert[1]->y - vert[0]->y;
u.z = vert[1]->z - vert[0]->z;
r = 1 / sqrt(u.x * u.x + u.y * u.y + u.z * u.z);
u.x *= r;
u.y *= r;
u.z *= r;
v.x = n.y * u.z - n.z * u.y;
v.y = -(n.x * u.z - n.z * u.x);
v.z = n.x * u.y - n.y * u.x;
for (j = 0; j < n_vert; j++) {
vu_[j] = vert[j]->x * u.x + vert[j]->y * u.y + vert[j]->z * u.z;
vv_[j] = vert[j]->x * v.x + vert[j]->y * v.y + vert[j]->z * v.z;
}
/* Test every edge. */
bb.x = b0->x;
bb.y = b0->y;
bb.z = b0->z;
d_box[0] = bb.x * n.x + bb.y * n.y + bb.z * n.z;
for (i = 0; i < 12; i++) {
if (i < 7) /* Visiting new vertices in order */
{
ba.x = bb.x;
ba.y = bb.y;
ba.z = bb.z;
bb.x = (which_x2[i]) ? b1->x : b0->x;
bb.y = (which_y2[i]) ? b1->y : b0->y;
bb.z = (which_z2[i]) ? b1->z : b0->z;
a2 = d_box[edge2_vt[i]] = bb.x * n.x + bb.y * n.y + bb.z * n.z;
a1 = d_box[edge1_vt[i]];
if ((a1 - d < 0 && a2 - d < 0) || (a1 - d > 0 && a2 - d > 0))
continue;
else
n_opposite++;
} else /* Revisiting old vertices out of order */
{
/* if (!n_opposite) return 0; */
a1 = d_box[edge1_vt[i]];
a2 = d_box[edge2_vt[i]];
if ((a1 - d < 0 && a2 - d < 0) || (a1 - d > 0 && a2 - d > 0))
continue;
n_opposite++;
ba.x = (which_x1[i]) ? b1->x : b0->x;
ba.y = (which_y1[i]) ? b1->y : b0->y;
ba.z = (which_z1[i]) ? b1->z : b0->z;
bb.x = (which_x2[i]) ? b1->x : b0->x;
bb.y = (which_y2[i]) ? b1->y : b0->y;
bb.z = (which_z2[i]) ? b1->z : b0->z;
}
/* Now ba,bb = box edge endpoints ; a1,a2 = distances along wall normal */
r = (d - a1) / (a2 - a1);
c.x = ba.x + r * (bb.x - ba.x);
c.y = ba.y + r * (bb.y - ba.y);
c.z = ba.z + r * (bb.z - ba.z);
cu = c.x * u.x + c.y * u.y + c.z * u.z;
cv = c.x * v.x + c.y * v.y + c.z * v.z;
/* Test for internal intersection point in wall coordinate space */
temp = 0;
for (j = 0; j < n_vert; j++) {
k = (j == 0) ? n_vert - 1 : j - 1;
if ((vu_[k] < cu && cu <= vu_[j]) || (vu_[k] >= cu && cu > vu_[j])) {
r = (cu - vu_[k]) / (vu_[j] - vu_[k]);
if ((vv_[k] + r * (vv_[j] - vv_[k])) > cv)
temp++;
}
}
if (temp & 1)
return 8 + i;
}
return 0;
#undef n_vert
}
/***************************************************************************
init_tri_wall:
In: object to which the wall belongs
index of the wall within that object
three vectors defining the vertices of the wall.
Out: No return value. The wall is properly initialized with normal
vectors, local coordinate vectors, and so on.
***************************************************************************/
void init_tri_wall(struct geom_object *objp, int side, struct vector3 *v0,
struct vector3 *v1, struct vector3 *v2) {
struct wall *w; /* The wall we're working with */
double f, fx, fy, fz;
struct vector3 vA, vB, vX;
w = &objp->walls[side];
w->next = NULL;
w->surf_class_head = NULL;
w->num_surf_classes = 0;
w->side = side;
w->vert[0] = v0;
w->vert[1] = v1;
w->vert[2] = v2;
w->edges[0] = NULL;
w->edges[1] = NULL;
w->edges[2] = NULL;
w->nb_walls[0] = NULL;
w->nb_walls[1] = NULL;
w->nb_walls[2] = NULL;
vectorize(v0, v1, &vA);
vectorize(v0, v2, &vB);
cross_prod(&vA, &vB, &vX);
w->area = 0.5 * vect_length(&vX);
if (!distinguishable(w->area, 0, EPS_C)) {
/* this is a degenerate polygon.
* perform initialization and quit. */
w->unit_u.x = 0;
w->unit_u.y = 0;
w->unit_u.z = 0;
w->normal.x = 0;
w->normal.y = 0;
w->normal.z = 0;
w->unit_v.x = 0;
w->unit_v.y = 0;
w->unit_v.z = 0;
w->d = 0;
w->uv_vert1_u = 0;
w->uv_vert2.u = 0;
w->uv_vert2.v = 0;
w->grid = NULL;
w->parent_object = objp;
w->flags = 0;
w->counting_regions = NULL;
return;
}
fx = (v1->x - v0->x);
fy = (v1->y - v0->y);
fz = (v1->z - v0->z);
f = 1 / sqrt(fx * fx + fy * fy + fz * fz);
w->unit_u.x = fx * f;
w->unit_u.y = fy * f;
w->unit_u.z = fz * f;
fx = (v2->x - v0->x);
fy = (v2->y - v0->y);
fz = (v2->z - v0->z);
w->normal.x = w->unit_u.y * fz - w->unit_u.z * fy;
w->normal.y = w->unit_u.z * fx - w->unit_u.x * fz;
w->normal.z = w->unit_u.x * fy - w->unit_u.y * fx;
f = 1 / sqrt(w->normal.x * w->normal.x + w->normal.y * w->normal.y +
w->normal.z * w->normal.z);
w->normal.x *= f;
w->normal.y *= f;
w->normal.z *= f;
w->unit_v.x = w->normal.y * w->unit_u.z - w->normal.z * w->unit_u.y;
w->unit_v.y = w->normal.z * w->unit_u.x - w->normal.x * w->unit_u.z;
w->unit_v.z = w->normal.x * w->unit_u.y - w->normal.y * w->unit_u.x;
w->d = v0->x * w->normal.x + v0->y * w->normal.y + v0->z * w->normal.z;
w->uv_vert1_u = (w->vert[1]->x - w->vert[0]->x) * w->unit_u.x +
(w->vert[1]->y - w->vert[0]->y) * w->unit_u.y +
(w->vert[1]->z - w->vert[0]->z) * w->unit_u.z;
w->uv_vert2.u = (w->vert[2]->x - w->vert[0]->x) * w->unit_u.x +
(w->vert[2]->y - w->vert[0]->y) * w->unit_u.y +
(w->vert[2]->z - w->vert[0]->z) * w->unit_u.z;
w->uv_vert2.v = (w->vert[2]->x - w->vert[0]->x) * w->unit_v.x +
(w->vert[2]->y - w->vert[0]->y) * w->unit_v.y +
(w->vert[2]->z - w->vert[0]->z) * w->unit_v.z;
w->grid = NULL;
w->parent_object = objp;
w->flags = 0;
w->counting_regions = NULL;
}
/***************************************************************************
wall_bounding_box:
In: a wall
vector to store one corner of the bounding box for that wall
vector to store the opposite corner
Out: No return value. The vectors are set to define the smallest box
that contains the wall.
***************************************************************************/
static void wall_bounding_box(struct wall *w, struct vector3 *llf,
struct vector3 *urb) {
llf->x = urb->x = w->vert[0]->x;
llf->y = urb->y = w->vert[0]->y;
llf->z = urb->z = w->vert[0]->z;
if (w->vert[1]->x < llf->x)
llf->x = w->vert[1]->x;
else if (w->vert[1]->x > urb->x)
urb->x = w->vert[1]->x;
if (w->vert[2]->x < llf->x)
llf->x = w->vert[2]->x;
else if (w->vert[2]->x > urb->x)
urb->x = w->vert[2]->x;
if (w->vert[1]->y < llf->y)
llf->y = w->vert[1]->y;
else if (w->vert[1]->y > urb->y)
urb->y = w->vert[1]->y;
if (w->vert[2]->y < llf->y)
llf->y = w->vert[2]->y;
else if (w->vert[2]->y > urb->y)
urb->y = w->vert[2]->y;
if (w->vert[1]->z < llf->z)
llf->z = w->vert[1]->z;
else if (w->vert[1]->z > urb->z)
urb->z = w->vert[1]->z;
if (w->vert[2]->z < llf->z)
llf->z = w->vert[2]->z;
else if (w->vert[2]->z > urb->z)
urb->z = w->vert[2]->z;
}
/***************************************************************************
wall_to_vol:
In: a wall
the subvolume to which the wall belongs
Out: The updated list of walls for that subvolume that now contains the
wall requested.
***************************************************************************/
struct wall_list *wall_to_vol(struct wall *w, struct subvolume *sv) {
struct wall_list *wl =
(struct wall_list *)CHECKED_MEM_GET_NODIE(sv->local_storage->list, "wall list");
if (wl == NULL)
return NULL;
wl->this_wall = w;
wl->next = sv->wall_head;
sv->wall_head = wl;
return wl;
}
/***************************************************************************
localize_wall:
In: a wall
the local memory storage area where this wall should be stored
Out: A pointer to the copy of that wall in local memory, or NULL on
memory allocation failure.
***************************************************************************/
struct wall *localize_wall(struct wall *w, struct storage *stor) {
struct wall *ww;
ww = (struct wall *)CHECKED_MEM_GET_NODIE(stor->face, "wall");
if (ww == NULL)
return NULL;
memcpy(ww, w, sizeof(struct wall));
ww->next = stor->wall_head;
stor->wall_head = ww;
stor->wall_count++;
ww->birthplace = stor;
return ww;
}
/***************************************************************************
distribute_wall:
In: a wall belonging to an object
Out: A pointer to the wall as copied into appropriate local memory, or
NULL on memory allocation error. Also, the wall is added to the
appropriate wall lists for all subvolumes it intersects; if this
fails due to memory allocation errors, NULL is also returned.
***************************************************************************/
static struct wall *distribute_wall(struct volume *world, struct wall *w) {
struct wall *where_am_i; /* Version of the wall in local memory */
struct vector3 llf, urb, cent; /* Bounding box for wall */
int x_max, x_min, y_max, y_min, z_max,
z_min; /* Enlarged box to avoid rounding */
int h, i, j, k; /* Iteration variables for subvolumes */
double leeway = 1.0; /* Margin of error */
wall_bounding_box(w, &llf, &urb);
if (llf.x < -leeway)
leeway = -llf.x;
if (llf.y < -leeway)
leeway = -llf.y;
if (llf.z < -leeway)
leeway = -llf.z;
if (urb.x > leeway)
leeway = urb.x;
if (urb.y > leeway)
leeway = urb.y;
if (urb.z > leeway)
leeway = urb.z;
leeway = EPS_C + leeway * EPS_C;
if (world->use_expanded_list) {
leeway += world->rx_radius_3d;
}
llf.x -= leeway;
llf.y -= leeway;
llf.z -= leeway;
urb.x += leeway;
urb.y += leeway;
urb.z += leeway;
cent.x = 0.33333333333 * (w->vert[0]->x + w->vert[1]->x + w->vert[2]->x);
cent.y = 0.33333333333 * (w->vert[0]->y + w->vert[1]->y + w->vert[2]->y);
cent.z = 0.33333333333 * (w->vert[0]->z + w->vert[1]->z + w->vert[2]->z);
x_min = bisect(world->x_partitions, world->nx_parts, llf.x);
if (urb.x < world->x_partitions[x_min + 1])
x_max = x_min + 1;
else
x_max = bisect(world->x_partitions, world->nx_parts, urb.x) + 1;
y_min = bisect(world->y_partitions, world->ny_parts, llf.y);
if (urb.y < world->y_partitions[y_min + 1])
y_max = y_min + 1;
else
y_max = bisect(world->y_partitions, world->ny_parts, urb.y) + 1;
z_min = bisect(world->z_partitions, world->nz_parts, llf.z);
if (urb.z < world->z_partitions[z_min + 1])
z_max = z_min + 1;
else
z_max = bisect(world->z_partitions, world->nz_parts, urb.z) + 1;
if ((z_max - z_min) * (y_max - y_min) * (x_max - x_min) == 1) {
h = z_min + (world->nz_parts - 1) * (y_min + (world->ny_parts - 1) * x_min);
where_am_i = localize_wall(w, world->subvol[h].local_storage);
if (where_am_i == NULL)
return NULL;
if (wall_to_vol(where_am_i, &(world->subvol[h])) == NULL)
return NULL;
return where_am_i;
}
for (i = x_min; i < x_max; i++) {
if (cent.x < world->x_partitions[i])
break;
}
for (j = y_min; j < y_max; j++) {
if (cent.y < world->y_partitions[j])
break;
}
for (k = z_min; k < z_max; k++) {
if (cent.z < world->z_partitions[k])
break;
}
h = (k - 1) +
(world->nz_parts - 1) * ((j - 1) + (world->ny_parts - 1) * (i - 1));
where_am_i = localize_wall(w, world->subvol[h].local_storage);
if (where_am_i == NULL)
return NULL;
for (k = z_min; k < z_max; k++) {
for (j = y_min; j < y_max; j++) {
for (i = x_min; i < x_max; i++) {
h = k + (world->nz_parts - 1) * (j + (world->ny_parts - 1) * i);
llf.x = world->x_fineparts[world->subvol[h].llf.x] - leeway;
llf.y = world->y_fineparts[world->subvol[h].llf.y] - leeway;
llf.z = world->z_fineparts[world->subvol[h].llf.z] - leeway;
urb.x = world->x_fineparts[world->subvol[h].urb.x] + leeway;
urb.y = world->y_fineparts[world->subvol[h].urb.y] + leeway;
urb.z = world->z_fineparts[world->subvol[h].urb.z] + leeway;
if (wall_in_box(w->vert, &(w->normal), w->d, &llf, &urb)) {
if (wall_to_vol(where_am_i, &(world->subvol[h])) == NULL)
return NULL;
}
}
}
}
return where_am_i;
}
/***************************************************************************
distribute_object:
In: an object
Out: 0 on success, 1 on memory allocation failure. The object's walls
are copied to local memory and the wall lists in the appropriate
subvolumes are set to refer to that wall. The object's own copy
of the wall is deallocated and it is set to point to the new version.
Note: this function is recursive and is called on any children of the
object passed to it.
***************************************************************************/
int distribute_object(struct volume *world, struct geom_object *parent) {
struct geom_object *o; /* Iterator for child objects */
int i;
long long vert_index; /* index of the vertex in the global array
"world->all_vertices" */
if (parent->object_type == BOX_OBJ || parent->object_type == POLY_OBJ) {
for (i = 0; i < parent->n_walls; i++) {
if (parent->wall_p[i] == NULL)
continue; /* Wall removed. */
parent->wall_p[i] = distribute_wall(world, parent->wall_p[i]);
if (parent->wall_p[i] == NULL)
mcell_allocfailed("Failed to distribute wall %d on object %s.", i,
parent->sym->name);
/* create information about shared vertices */
if (world->create_shared_walls_info_flag) {
vert_index = (long long)(parent->wall_p[i]->vert[0] - world->all_vertices);
push_wall_to_list(&(world->walls_using_vertex[vert_index]),
parent->wall_p[i]);
vert_index = (long long)(parent->wall_p[i]->vert[1] - world->all_vertices);
push_wall_to_list(&(world->walls_using_vertex[vert_index]),
parent->wall_p[i]);
vert_index = (long long)(parent->wall_p[i]->vert[2] - world->all_vertices);
push_wall_to_list(&(world->walls_using_vertex[vert_index]),
parent->wall_p[i]);
}
}
if (parent->walls != NULL) {
free(parent->walls);
parent->walls = NULL; /* Use wall_p from now on! */
}
} else if (parent->object_type == META_OBJ) {
for (o = parent->first_child; o != NULL; o = o->next) {
if (distribute_object(world, o) != 0)
return 1;
}
}
return 0;
}
/***************************************************************************
distribute_world:
In: No arguments.
Out: 0 on success, 1 on memory allocation failure. Every geometric object
is distributed to local memory and into appropriate subvolumes.
***************************************************************************/
int distribute_world(struct volume *world) {
struct geom_object *o; /* Iterator for objects in the world */
for (o = world->root_instance; o != NULL; o = o->next) {
if (distribute_object(world, o) != 0)
return 1;
}
return 0;
}
/***************************************************************************
closest_pt_point_triangle:
In: p - point
a,b,c - vectors defining the vertices of the triangle.
Out: final_result - closest point on triangle ABC to a point p.
The code is adapted from "Real-time Collision Detection" by Christer
Ericson, ISBN 1-55860-732-3, p.141.
***************************************************************************/
void closest_pt_point_triangle(struct vector3 *p, struct vector3 *a,
struct vector3 *b, struct vector3 *c,
struct vector3 *final_result) {
struct vector3 ab, ac, ap, bp, cp, result1;
double d1, d2, d3, d4, vc, d5, d6, vb, va, denom, v, w;
/* Check if P in vertex region outside A */
vectorize(a, b, &ab);
vectorize(a, c, &ac);
vectorize(a, p, &ap);
d1 = dot_prod(&ab, &ap);
d2 = dot_prod(&ac, &ap);
if (d1 <= 0.0f && d2 <= 0.0f) {
memcpy(final_result, a,
sizeof(struct vector3)); /* barycentric coordinates (1,0,0) */
return;
}
/* Check if P in vertex region outside B */
vectorize(b, p, &bp);
d3 = dot_prod(&ab, &bp);
d4 = dot_prod(&ac, &bp);
if (d3 >= 0.0f && d4 <= d3) {
memcpy(final_result, b,
sizeof(struct vector3)); /* barycentric coordinates (0,1,0) */
return;
}
/* Check if P in edge region of AB, if so return projection of P onto AB */
vc = d1 * d4 - d3 * d2;
if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f) {
v = d1 / (d1 - d3);
scalar_prod(&ab, v, &result1);
vect_sum(a, &result1, final_result);
return; /* barycentric coordinates (1-v,v,0) */
}
/* Check if P in vertex region outside C */
vectorize(c, p, &cp);
d5 = dot_prod(&ab, &cp);
d6 = dot_prod(&ac, &cp);
if (d6 >= 0.0f && d5 <= d6) {
memcpy(final_result, c,
sizeof(struct vector3)); /* barycentric coordinates (0,0,1) */
return;
}
/* Check if P in edge region of AC, if so return projection of P onto AC */
vb = d5 * d2 - d1 * d6;
if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f) {
w = d2 / (d2 - d6);
scalar_prod(&ac, w, &result1);
vect_sum(a, &result1, final_result);
return; /* barycentric coordinates (0, 1-w,w) */
}
/* Check if P in edge region of BC, if so return projection of P onto BC */
va = d3 * d6 - d5 * d4;
if (va <= 0.0f && (d4 - d3) >= 0.0f && (d5 - d6) >= 0.0f) {
w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
vectorize(b, c, &result1);
scalar_prod(&result1, w, &result1);
vect_sum(b, &result1, final_result);
return; /*barycentric coordinates (0,1-w, w) */
}
/* P inside face region. Compute Q through its barycentric
coordinates (u,v,w) */
denom = 1.0f / (va + vb + vc);
v = vb * denom;
w = vc * denom;
scalar_prod(&ab, v, &ab);
scalar_prod(&ac, w, &ac);
vect_sum(&ab, &ac, &result1);
vect_sum(a, &result1, final_result);
return; /* = u*a + v*b + w*c, u = va * denom = 1.0f - v -w */
}
/***************************************************************************
test_bounding_boxes:
In: llf1 - lower left corner of the 1st box
urb1 - upper right back corner of the 1st box
llf2 - lower left corner of the 2nd box
urb2 - upper right back corner of the 2nd box
Out: Returns 1 if boxes intersect, 0 - otherwise
The code is adapted from "Real-time Collision Detection"
by Christer Ericson, ISBN 1-55860-732-3, p.79.
***************************************************************************/
int test_bounding_boxes(struct vector3 *llf1, struct vector3 *urb1,
struct vector3 *llf2, struct vector3 *urb2) {
/* Two boxes overlap only if they overlap on all three axes
while their extent along each dimension is seen as an interval
on the corresponding axis. */
/* exit with no intersection is separated along axis */
if ((urb1->x < llf2->x) || (llf1->x > urb2->x))
return 0;
if ((urb1->y < llf2->y) || (llf1->y > urb2->y))
return 0;
if ((urb1->z < llf2->z) || (llf1->z > urb2->z))
return 0;
/* Overlapping on all axis means that boxes are intersecting. */
return 1;
}
/* Helper struct for release_onto_regions and vacuum_from_regions */
struct reg_rel_helper_data {
struct reg_rel_helper_data *next;
struct surface_grid *grid;
unsigned int index;
double my_area;
};
/***************************************************************************
vacuum_from_regions:
In: a release site object
a template surface molecule we're going to remove
the number of molecules to remove
Out: 0 on success, 1 on failure. Molecules of the specified type are
removed uniformly at random from the free area in the regions
specified by the release site object.
Note: if the user requests to remove more molecules than actually exist,
the function will return success and not give a warning. The only
reason to return failure is an out of memory condition.
***************************************************************************/
static int vacuum_from_regions(struct volume *world,
struct release_site_obj *rso,
struct surface_molecule *sm, int n) {
struct release_region_data *rrd;
struct mem_helper *mh;
struct reg_rel_helper_data *rrhd_head, *p;
int n_rrhd;
struct wall *w;
struct surface_molecule *smp;
rrd = rso->region_data;
mh = create_mem(sizeof(struct reg_rel_helper_data), 1024);
if (mh == NULL)
return 1;
rrhd_head = NULL;
n_rrhd = 0;
for (int n_object = 0; n_object < rrd->n_objects; n_object++) {
if (rrd->walls_per_obj[n_object] == 0)
continue;
for (int n_wall = 0; n_wall < rrd->in_release[n_object]->nbits; n_wall++) {
if (!get_bit(rrd->in_release[n_object], n_wall))
continue;
w = rrd->owners[n_object]->wall_p[n_wall];
if (w->grid == NULL)
continue;
for (unsigned int n_tile = 0; n_tile < w->grid->n_tiles; n_tile++) {
struct surface_molecule_list *sm_list = w->grid->sm_list[n_tile];
if (sm_list && sm_list->sm) {
smp = w->grid->sm_list[n_tile]->sm;
if (smp != NULL) {
if (smp->properties == sm->properties) {
p = (struct reg_rel_helper_data *)CHECKED_MEM_GET_NODIE(mh, "release region helper data");
if (p == NULL)
return 1;
p->next = rrhd_head;
p->grid = w->grid;
p->index = n_tile;
rrhd_head = p;
n_rrhd++;
}
}
}
}
}
}
for (p = rrhd_head; n < 0 && n_rrhd > 0 && p != NULL; p = p->next, n_rrhd--) {
if (rng_dbl(world->rng) < ((double)(-n)) / ((double)n_rrhd)) {
smp = p->grid->sm_list[p->index]->sm;
smp->properties->population--;
if ((smp->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) != 0)
count_region_from_scratch(world, (struct abstract_molecule *)smp, NULL,
-1, NULL, smp->grid->surface, smp->t, NULL);
smp->properties = NULL;
p->grid->sm_list[p->index]->sm = NULL;
p->grid->n_occupied--;
if (smp->flags & IN_SCHEDULE) {
smp->grid->subvol->local_storage->timer->defunct_count++; /* Tally for
garbage
collection
*/
}
n++;
}
}
delete_mem(mh);
return 0;
}
/***************************************************************************
release_onto_regions:
In: a release site object
a template surface molecule we're going to release
the number of molecules to release
Out: 0 on success, 1 on failure. Molecules are released uniformly at
random onto the free area in the regions specified by the release
site object.
Note: if the CCNNUM method is used, the number passed in is ignored.
***************************************************************************/
int release_onto_regions(struct volume *world, struct release_site_obj *rso,
struct surface_molecule *sm, int n) {
struct mem_helper *mh;
int i;
unsigned int grid_index;
double A, num_to_release;
struct wall *w;
struct release_region_data *rrd = rso->region_data;
int success = 0, failure = 0;
double seek_cost = 0;
double max_A = rrd->cum_area_list[rrd->n_walls_included - 1];
double est_sites_avail = (int)max_A;
const double rel_list_gen_cost = 10.0; /* Just a guess */
double pick_cost = rel_list_gen_cost * est_sites_avail;
if (rso->release_number_method == DENSITYNUM) {
num_to_release = rso->concentration * est_sites_avail / world->grid_density;
if (num_to_release > (double)INT_MAX)
mcell_error("Release site \"%s\" tries to release more than INT_MAX "
"(2147483647) molecules.",
rso->name);
n = (int)(num_to_release);
}
if (n < 0)
return vacuum_from_regions(world, rso, sm, n);
const int too_many_failures = 10; /* Just a guess */
while (n > 0) {
if (failure >= success + too_many_failures) {
seek_cost =
n * (((double)(success + failure + 2)) / ((double)(success + 1)));
}
if (seek_cost < pick_cost) {
A = rng_dbl(world->rng) * max_A;
i = bisect_high(rrd->cum_area_list, rrd->n_walls_included, A);
w = rrd->owners[rrd->obj_index[i]]->wall_p[rrd->wall_index[i]];
if (w->grid == NULL) {
if (create_grid(world, w, NULL))
return 1;
}
if (i)
A -= rrd->cum_area_list[i - 1];
grid_index = (unsigned int)((w->grid->n * w->grid->n) * (A / w->area));
if (grid_index >= w->grid->n_tiles) {
grid_index = w->grid->n_tiles - 1;
}
struct surface_molecule_list *sm_list = w->grid->sm_list[grid_index];
if (sm_list && sm_list->sm) {
failure++;
}
else {
struct vector3 pos3d = {0, 0, 0};
if (place_single_molecule(world, w, grid_index, sm->properties,
sm->graph_data, sm->flags, rso->orientation, sm->t, sm->t2,
sm->birthday, sm->periodic_box, &pos3d) == NULL) {
if (world->periodic_box_obj) {
struct polygon_object *p = (struct polygon_object*)(world->periodic_box_obj->contents);
struct subdivided_box *sb = p->sb;
struct vector3 llf = {sb->x[0], sb->y[0], sb->z[0]};
struct vector3 urb = {sb->x[1], sb->y[1], sb->z[1]};
if (!point_in_box(&llf, &urb, &pos3d)) {
mcell_log("Cannot release '%s' outside of periodic boundaries.",
sm->properties->sym->name);
failure++;
continue;
}
}
return 1;
}
//JJT: copy over nfsim graph pattern information
success++;
n--;
}
} else {
if (world->periodic_box_obj) {
return 1;
}
mh = create_mem(sizeof(struct reg_rel_helper_data), 1024);
if (mh == NULL)
return 1;
struct reg_rel_helper_data *rrhd_head = NULL;
int n_rrhd = 0;
max_A = 0;
for (int n_object = 0; n_object < rrd->n_objects; n_object++) {
if (rrd->walls_per_obj[n_object] == 0)
continue;
for (int n_wall = 0; n_wall < rrd->in_release[n_object]->nbits;
n_wall++) {
if (!get_bit(rrd->in_release[n_object], n_wall))
continue;
w = rrd->owners[n_object]->wall_p[n_wall];
if (w->grid == NULL) {
if (create_grid(world, w, NULL)) {
delete_mem(mh);
return 1;
}
} else if (w->grid->n_occupied == w->grid->n_tiles)
continue;
A = w->area / (w->grid->n_tiles);
for (unsigned int n_tile = 0; n_tile < w->grid->n_tiles; n_tile++) {
if (w->grid->sm_list[n_tile] == NULL || w->grid->sm_list[n_tile]->sm == NULL) {
struct reg_rel_helper_data *new_rrd =
(struct reg_rel_helper_data *)CHECKED_MEM_GET_NODIE(mh, "release region helper data");
if (new_rrd == NULL)
return 1;
new_rrd->next = rrhd_head;
new_rrd->grid = w->grid;
new_rrd->index = n_tile;
new_rrd->my_area = A;
max_A += A;
rrhd_head = new_rrd;
n_rrhd++;
}
}
}
}
for (struct reg_rel_helper_data *this_rrd = rrhd_head;
this_rrd != NULL && n > 0; this_rrd = this_rrd->next) {
if (n >= n_rrhd ||
rng_dbl(world->rng) < (this_rrd->my_area / max_A) * ((double)n)) {
struct vector3 pos3d = {0, 0, 0};
if (place_single_molecule(world, this_rrd->grid->surface,
this_rrd->index, sm->properties, sm->graph_data, sm->flags,
rso->orientation, sm->t, sm->t2,
sm->birthday, sm->periodic_box, &pos3d) == NULL) {
return 1;
}
//JJT: copy over nfsim graph pattern information
n--;
n_rrhd--;
}
max_A -= this_rrd->my_area;
}
delete_mem(mh);
if (n > 0) {
switch (world->notify->mol_placement_failure) {
case WARN_COPE:
break;
case WARN_WARN:
mcell_warn("Could not release %d of %s (surface full).", n,
sm->properties->sym->name);
break;
case WARN_ERROR:
mcell_error("Could not release %d of %s (surface full).", n,
sm->properties->sym->name);
/*return 1;*/
default:
UNHANDLED_CASE(world->notify->mol_placement_failure);
}
break;
}
}
}
return 0;
}
/****************************************************************************
place_single_molecule:
In: state: the simulation state
w: the wall to receive the surface molecule
grid_index:
spec: the molecule
flags:
orientation: the orientation of the molecule
Out: the new surface molecule is returned on success, NULL otherwise
*****************************************************************************/
struct surface_molecule *place_single_molecule(struct volume *state,
struct wall *w,
unsigned int grid_index,
struct species *spec,
struct graph_data* graph,
short flags, short orientation,
double t, double t2,
double birthday,
struct periodic_image *periodic_box,
struct vector3 *pos3d) {
struct vector2 s_pos;
if (state->randomize_smol_pos)
grid2uv_random(w->grid, grid_index, &s_pos, state->rng);
else
grid2uv(w->grid, grid_index, &s_pos);
uv2xyz(&s_pos, w, pos3d);
if (state->periodic_box_obj) {
struct polygon_object *p = (struct polygon_object*)(state->periodic_box_obj->contents);
struct subdivided_box *sb = p->sb;
struct vector3 llf = {sb->x[0], sb->y[0], sb->z[0]};
struct vector3 urb = {sb->x[1], sb->y[1], sb->z[1]};
if (!point_in_box(&llf, &urb, pos3d)) {
mcell_log("Cannot release '%s' outside of periodic boundaries.",
spec->sym->name);
return NULL;
}
}
struct subvolume *gsv = NULL;
gsv = find_subvolume(state, pos3d, gsv);
struct surface_molecule *new_sm;
new_sm = (struct surface_molecule *)CHECKED_MEM_GET(gsv->local_storage->smol,
"surface molecule");
if (new_sm == NULL)
return NULL;
new_sm->t = t;
new_sm->t2 = t2;
new_sm->birthday = birthday;
new_sm->birthplace = w->birthplace->smol;
new_sm->id = state->current_mol_id++;
new_sm->grid_index = grid_index;
new_sm->s_pos.u = s_pos.u;
new_sm->s_pos.v = s_pos.v;
new_sm->properties = spec;
new_sm->graph_data = graph;
initialize_diffusion_function((struct abstract_molecule *)new_sm);
new_sm->periodic_box = CHECKED_MALLOC_STRUCT(struct periodic_image,
"periodic image descriptor");
new_sm->periodic_box->x = periodic_box->x;
new_sm->periodic_box->y = periodic_box->y;
new_sm->periodic_box->z = periodic_box->z;
if (orientation == 0)
new_sm->orient = (rng_uint(state->rng) & 1) ? 1 : -1;
else
new_sm->orient = orientation;
new_sm->grid = w->grid;
if (w->grid->sm_list[grid_index] == NULL) {
struct surface_molecule_list *sm_entry = CHECKED_MALLOC_STRUCT(
struct surface_molecule_list, "surface molecule list");
sm_entry->next = NULL;
w->grid->sm_list[grid_index] = sm_entry;
}
w->grid->sm_list[grid_index]->sm = new_sm;
w->grid->n_occupied++;
new_sm->properties->population++;
new_sm->flags = flags;
if (new_sm->get_space_step(new_sm) > 0)
new_sm->flags |= ACT_DIFFUSE;
if ((new_sm->properties->flags & COUNT_ENCLOSED) != 0)
new_sm->flags |= COUNT_ME;
if (new_sm->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED))
count_region_from_scratch(state, (struct abstract_molecule *)new_sm, NULL,
1, NULL, new_sm->grid->surface, new_sm->t,
new_sm->periodic_box);
if (schedule_add_mol(gsv->local_storage->timer, new_sm)) {
mcell_allocfailed("Failed to add volume molecule '%s' to scheduler.",
new_sm->properties->sym->name);
return NULL;
}
return new_sm;
}
/****************************************************************************
push_wall_to_list:
In: head of the linked list of walls
wall to be added to the list
Out: none. The linked list is updated.
Note: No check for duplicates is performed
*****************************************************************************/
void push_wall_to_list(struct wall_list **wall_nbr_head, struct wall *w) {
struct wall_list *old_head, *wlp;
old_head = *wall_nbr_head;
wlp = CHECKED_MALLOC_STRUCT(struct wall_list, "wall_list");
wlp->this_wall = w;
if (old_head == NULL) {
wlp->next = NULL;
old_head = wlp;
} else {
wlp->next = old_head;
old_head = wlp;
}
*wall_nbr_head = old_head;
}
/*************************************************************************
delete_wall_list:
In: linked list of walls
Out: none. The memory is freed.
*************************************************************************/
void delete_wall_list(struct wall_list *wl_head) {
struct wall_list *nnext;
while (wl_head != NULL) {
nnext = wl_head->next;
free(wl_head);
wl_head = nnext;
}
}
/*************************************************************************
find_nbr_walls_shared_one_vertex:
In: the origin wall
array with information about which vertices of the origin wall
are shared with neighbor wall (they are indices in the
global "world->walls_using_vertex" array).
Out: linked list of the neighbor walls that have only one common
vertex with the origin wall (not edge-to-edge walls, but
vertex-to-vertex walls).
Note: the "origin" wall is not included in the list
**************************************************************************/
struct wall_list *find_nbr_walls_shared_one_vertex(struct volume *world,
struct wall *origin,
long long int *shared_vert) {
int i;
struct wall_list *wl;
struct wall_list *head = NULL;
if (!world->create_shared_walls_info_flag)
mcell_internal_error("Function 'find_nbr_walls_shared_one_vertex()' is "
"called but shared walls information is not created.");
for (i = 0; i < 3; i++) {
if (shared_vert[i] >= 0) {
for (wl = world->walls_using_vertex[shared_vert[i]]; wl != NULL;
wl = wl->next) {
if (wl->this_wall == origin)
continue;
if (!walls_share_full_edge(origin, wl->this_wall)) {
push_wall_to_list(&head, wl->this_wall);
}
}
}
}
return head;
}
/***********************************************************************
walls_share_full_edge:
In: two walls
Out: 1 if the walls share a full edge, 0 - otherwise.
Here by "full" we mean that the shared edge has two endpoints
that are the vertices of both walls w1 and w2.
************************************************************************/
int walls_share_full_edge(struct wall *w1, struct wall *w2) {
int i, k;
int count = 0; /* count number of shared vertices between two walls */
for (i = 0; i < 3; i++) {
for (k = 0; k < 3; k++) {
if (!distinguishable_vec3(w1->vert[i], w2->vert[k], EPS_C))
count++;
}
}
if (count == 2)
return 1;
return 0;
}
/***********************************************************************
find_region_by_wall:
In: wall
Out: an object's region list if the wall belongs to one, NULL - otherwise.
Note: regions called "ALL" or the ones that have ALL_ELEMENTS are not
included in the return "region list". This is done intentionally
since the function is used to determine region border and the
above regions do not have region borders.
************************************************************************/
struct region_list *find_region_by_wall(struct wall *this_wall) {
struct region_list *rlp_head = NULL;
for (struct region_list *rlp = this_wall->parent_object->regions; rlp != NULL;
rlp = rlp->next) {
struct region *rp = rlp->reg;
if ((strcmp(rp->region_last_name, "ALL") == 0) ||
(rp->region_has_all_elements))
continue;
if (rp->membership == NULL)
mcell_internal_error("Missing region membership for '%s'.",
rp->sym->name);
if (get_bit(rp->membership, this_wall->side)) {
struct region_list *rlps = CHECKED_MALLOC_STRUCT(struct region_list,
"region_list");
rlps->reg = rp;
if (rlp_head == NULL) {
rlps->next = NULL;
rlp_head = rlps;
} else {
rlps->next = rlp_head;
rlp_head = rlps;
}
}
}
return rlp_head;
}
/************************************************************************
find_regions_names_by_wall:
In: wall:
ignore_regs:
Out: linked list of wall's regions names if wall belongs to region,
NULL - otherwise. Also number of regions is set.
Note: regions called "ALL" or the ones that have ALL_ELEMENTS are not
included in the return regions names list. This is done intentionally
since the function is used with dynamic geometries to place a surface
molecule.
************************************************************************/
struct name_list *find_regions_names_by_wall(
struct wall *w, struct string_buffer *ignore_regs)
{
struct name_list *nl_head = NULL;
struct region_list *reg_list_ptr_head = find_region_by_wall(w);
struct region_list *reg_list_ptr;
for (reg_list_ptr = reg_list_ptr_head; reg_list_ptr != NULL;) {
struct region *reg_ptr = reg_list_ptr->reg;
// Disregard regions which were just added during a dynamic geometry event
if ((ignore_regs) && (is_string_present_in_string_array(
reg_ptr->sym->name, ignore_regs->strings, ignore_regs->n_strings))) {
reg_list_ptr_head = reg_list_ptr->next;
free(reg_list_ptr);
reg_list_ptr = reg_list_ptr_head;
continue;
}
struct name_list *nl = CHECKED_MALLOC_STRUCT(struct name_list, "name_list");
nl->name = alloc_sprintf("%s", reg_ptr->sym->name);
nl->prev = NULL;
if (nl_head == NULL) {
nl->next = NULL;
nl_head = nl;
}
else {
nl->next = nl_head;
nl_head = nl;
}
reg_list_ptr_head = reg_list_ptr->next;
free(reg_list_ptr);
reg_list_ptr = reg_list_ptr_head;
}
return nl_head;
}
/***********************************************************************
find_restricted_regions_by_wall:
In: wall
surface molecule
Out: an object's region list if the wall belongs to the region
that is restrictive (REFL/ABSORB) to the surface molecule
NULL - if no such regions found
Note: regions called "ALL" or the ones that have ALL_ELEMENTS are not
included in the return "region list".
************************************************************************/
struct region_list *
find_restricted_regions_by_wall(struct volume *world, struct wall *this_wall,
struct surface_molecule *sm) {
if ((sm->properties->flags & CAN_REGION_BORDER) == 0)
return NULL;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
for (int kk = 0; kk < MAX_MATCHING_RXNS; kk++) {
matching_rxns[kk] = NULL;
}
int num_matching_rxns = trigger_intersect(
world->reaction_hash, world->rx_hashsize, world->all_mols,
world->all_volume_mols, world->all_surface_mols, sm->properties->hashval,
(struct abstract_molecule *)sm, sm->orient, this_wall, matching_rxns, 1,
1, 1);
struct species *restricted_surf_class[MAX_MATCHING_RXNS];
int num_res = 0;
for (int kk = 0; kk < num_matching_rxns; kk++) {
if ((matching_rxns[kk]->n_pathways == RX_REFLEC) ||
(matching_rxns[kk]->n_pathways == RX_ABSORB_REGION_BORDER)) {
restricted_surf_class[num_res++] = matching_rxns[kk]->players[1];
}
}
struct region *rp;
struct region_list *rlp_head = NULL;
for (struct region_list *rlp = this_wall->parent_object->regions; rlp != NULL;
rlp = rlp->next) {
rp = rlp->reg;
if (rp->membership == NULL) {
mcell_internal_error("Missing region membership for '%s'.", rp->sym->name);
}
if (rp->surf_class == NULL) {
continue;
}
if ((strcmp(rp->region_last_name, "ALL") == 0) ||
(rp->region_has_all_elements)) {
continue;
}
if (get_bit(rp->membership, this_wall->side)) {
/* is this region's boundary restricted for surface molecule? */
for (int i = 0; i < num_res; ++i) {
if (rp->surf_class == restricted_surf_class[i]) {
struct region_list *rlps = CHECKED_MALLOC_STRUCT(struct region_list,
"region_list");
rlps->reg = rp;
if (rlp_head == NULL) {
rlps->next = NULL;
rlp_head = rlps;
} else {
rlps->next = rlp_head;
rlp_head = rlps;
}
break;
}
}
}
}
return rlp_head;
}
/***********************************************************************
find_restricted_regions_by_object:
In: object
surface molecule
Out: an object's region list that are restrictive (REFL/ABSORB)
to the surface molecule
NULL - if no such regions found
Note: regions called "ALL" or the ones that have ALL_ELEMENTS are not
included in the return "region list".
************************************************************************/
struct region_list *
find_restricted_regions_by_object(struct volume *world, struct geom_object *obj,
struct surface_molecule *sm) {
struct region *rp;
struct region_list *rlp, *rlps, *rlp_head = NULL;
int kk, i, wall_idx = INT_MIN;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
if ((sm->properties->flags & CAN_REGION_BORDER) == 0)
return NULL;
for (kk = 0; kk < MAX_MATCHING_RXNS; kk++) {
matching_rxns[kk] = NULL;
}
for (rlp = obj->regions; rlp != NULL; rlp = rlp->next) {
rp = rlp->reg;
if ((strcmp(rp->region_last_name, "ALL") == 0) ||
(rp->region_has_all_elements)) {
continue;
}
/* find any wall that belongs to this region */
for (i = 0; i < obj->n_walls; i++) {
if (get_bit(rp->membership, i)) {
wall_idx = i;
break;
}
}
if (wall_idx < 0)
mcell_internal_error("Cannot find wall in the region.");
int num_matching_rxns = 0;
if (rp->surf_class) {
num_matching_rxns = find_unimol_reactions_with_surf_classes(
world->reaction_hash, world->rx_hashsize,
(struct abstract_molecule *)sm, obj->wall_p[wall_idx],
sm->properties->hashval, sm->orient, num_matching_rxns, 1, 1, 1,
matching_rxns);
num_matching_rxns = find_surface_mol_reactions_with_surf_classes(
world->reaction_hash, world->rx_hashsize, world->all_mols,
world->all_surface_mols, sm->orient, rp->surf_class,
num_matching_rxns, 1, 1, 1, matching_rxns);
}
for (kk = 0; kk < num_matching_rxns; kk++) {
if ((matching_rxns[kk]->n_pathways == RX_REFLEC) ||
(matching_rxns[kk]->n_pathways == RX_ABSORB_REGION_BORDER)) {
rlps = CHECKED_MALLOC_STRUCT(struct region_list, "region_list");
rlps->reg = rp;
if (rlp_head == NULL) {
rlps->next = NULL;
rlp_head = rlps;
} else {
rlps->next = rlp_head;
rlp_head = rlps;
}
}
}
}
return rlp_head;
}
/***********************************************************************
are_restricted_regions_for_species_on_object:
In: object
surface molecule
Out: 1 if there are regions that are restrictive (REFL/ABSORB)
to the surface molecule on this object
0 - if no such regions found
************************************************************************/
int are_restricted_regions_for_species_on_object(struct volume *world,
struct geom_object *obj,
struct surface_molecule *sm) {
int wall_idx = INT_MIN;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
if ((sm->properties->flags & CAN_REGION_BORDER) == 0)
return 0;
for (int kk = 0; kk < MAX_MATCHING_RXNS; kk++) {
matching_rxns[kk] = NULL;
}
for (struct region_list *rlp = obj->regions; rlp != NULL; rlp = rlp->next) {
struct region *rp = rlp->reg;
if ((strcmp(rp->region_last_name, "ALL") == 0) ||
(rp->region_has_all_elements)) {
continue;
}
/* find any wall that belongs to this region */
for (int i = 0; i < obj->n_walls; i++) {
if (get_bit(rp->membership, i)) {
wall_idx = i;
break;
}
}
if (wall_idx < 0) {
mcell_internal_error("Cannot find wall in the region.");
}
int num_matching_rxns = trigger_intersect(
world->reaction_hash, world->rx_hashsize, world->all_mols,
world->all_volume_mols, world->all_surface_mols,
sm->properties->hashval, (struct abstract_molecule *)sm, sm->orient,
obj->wall_p[wall_idx], matching_rxns, 1, 1, 1);
if (num_matching_rxns > 0) {
for (int kk = 0; kk < num_matching_rxns; kk++) {
if ((matching_rxns[kk]->n_pathways == RX_REFLEC) ||
(matching_rxns[kk]->n_pathways == RX_ABSORB_REGION_BORDER)) {
return 1;
}
}
}
}
return 0;
}
/***********************************************************************
is_wall_edge_region_border:
In: wall
wall's edge
Out: 1 if the edge is a region's border, and 0 - otherwise.
Note: we do not specify any particular region here, any region will
suffice
************************************************************************/
int is_wall_edge_region_border(struct wall *this_wall, struct edge *this_edge) {
struct region_list *rlp, *rlp_head;
struct region *rp;
void *key;
unsigned int keyhash;
int is_region_border = 0; /* flag */
rlp_head = find_region_by_wall(this_wall);
/* If this wall is not a part of any region (note that we do not consider
region called ALL here) */
if (rlp_head == NULL)
return is_region_border;
for (rlp = rlp_head; rlp != NULL; rlp = rlp->next) {
rp = rlp->reg;
if (rp->boundaries == NULL)
mcell_internal_error("Region '%s' of the object '%s' has no boundaries.",
rp->region_last_name,
this_wall->parent_object->sym->name);
keyhash = (unsigned int)(intptr_t)(this_edge);
key = (void *)(this_edge);
if (pointer_hash_lookup(rp->boundaries, key, keyhash)) {
is_region_border = 1;
break;
}
}
if (rlp_head != NULL)
delete_void_list((struct void_list *)rlp_head);
return is_region_border;
}
/***********************************************************************
is_wall_edge_restricted_region_border:
In: wall
wall's edge
surface molecule
Out: 1 if the edge is a restricted region's border for above surface molecule
0 - otherwise.
Note: we do not specify any particular region here, any region will
suffice for which special reactions (REFL/ABSORB) are defined.
************************************************************************/
int is_wall_edge_restricted_region_border(struct volume *world,
struct wall *this_wall,
struct edge *this_edge,
struct surface_molecule *sm) {
struct region_list *rlp, *rlp_head;
struct region *rp;
void *key;
unsigned int keyhash;
int is_region_border = 0; /* flag */
rlp_head = find_restricted_regions_by_wall(world, this_wall, sm);
/* If this wall is not a part of any region (note that we do not consider
region called ALL here) */
if (rlp_head == NULL)
return is_region_border;
for (rlp = rlp_head; rlp != NULL; rlp = rlp->next) {
rp = rlp->reg;
if (rp->boundaries == NULL)
mcell_internal_error("Region '%s' of the object '%s' has no boundaries.",
rp->region_last_name,
this_wall->parent_object->sym->name);
keyhash = (unsigned int)(intptr_t)(this_edge);
key = (void *)(this_edge);
if (pointer_hash_lookup(rp->boundaries, key, keyhash)) {
is_region_border = 1;
break;
}
}
if (rlp_head != NULL)
delete_void_list((struct void_list *)rlp_head);
return is_region_border;
}
/*************************************************************************
find_shared_edge_index_of_neighbor_wall:
In: original wall
neighbor wall
Out: index of the shared edge in the coordinate system of neighbor wall.
**************************************************************************/
int find_shared_edge_index_of_neighbor_wall(struct wall *orig_wall,
struct wall *nbr_wall) {
int nbr_edge_ind = -1;
int shared_vert_ind_1 = -1, shared_vert_ind_2 = -1;
find_shared_vertices_for_neighbor_walls(
orig_wall, nbr_wall, &shared_vert_ind_1, &shared_vert_ind_2);
if ((shared_vert_ind_1 + shared_vert_ind_2) == 1) {
nbr_edge_ind = 0;
} else if ((shared_vert_ind_1 + shared_vert_ind_2) == 2) {
nbr_edge_ind = 2;
} else if ((shared_vert_ind_1 + shared_vert_ind_2) == 3) {
nbr_edge_ind = 1;
} else {
mcell_internal_error(
"Error in the function 'find_shared_edge_index_of_neighbor_wall()");
}
return nbr_edge_ind;
}
/****************************************************************************
find_neighbor_wall_and_edge:
In: orig_wall: wall
orig_edge_ind: wall edge index (in the coordinate system of "wall")
nbr_wall: neighbor wall (return value)
nbr_edge_ind: index of the edge in the coordinate system of "neighbor
wall" that is shared with "wall" and coincides with the
edge with "wall edge index" (return value)
****************************************************************************/
void find_neighbor_wall_and_edge(struct wall *orig_wall, int orig_edge_ind,
struct wall **nbr_wall, int *nbr_edge_ind) {
struct wall *w;
struct vector3 *vert_A = NULL, *vert_B = NULL;
switch (orig_edge_ind) {
case 0:
vert_A = orig_wall->vert[0];
vert_B = orig_wall->vert[1];
break;
case 1:
vert_A = orig_wall->vert[1];
vert_B = orig_wall->vert[2];
break;
case 2:
vert_A = orig_wall->vert[2];
vert_B = orig_wall->vert[0];
break;
default:
mcell_internal_error("Error in function 'find_neighbor_wall_and_edge()'.");
/*break;*/
}
for (int ii = 0; ii < 3; ii++) {
w = orig_wall->nb_walls[ii];
if (w == NULL)
continue;
if (wall_contains_both_vertices(w, vert_A, vert_B)) {
*nbr_wall = w;
*nbr_edge_ind = find_shared_edge_index_of_neighbor_wall(orig_wall, w);
break;
}
}
}
/***************************************************************************
wall_contains_both_vertices:
In: wall
two vertices
Out: Returns 1 if the wall contains both vertices above, and 0 otherwise.
***************************************************************************/
int wall_contains_both_vertices(struct wall *w, struct vector3 *vert_A,
struct vector3 *vert_B) {
int count = 0;
for (int ii = 0; ii < 3; ii++) {
struct vector3 *v = w->vert[ii];
if ((!distinguishable_vec3(v, vert_A, EPS_C)) ||
(!(distinguishable_vec3(v, vert_B, EPS_C)))) {
count++;
}
}
if (count == 2)
return 1;
else
return 0;
}
/*******************************************************************
are_walls_coincident:
In: first wall
second wall
accuracy of the comparison
Out: 0 if the walls are not coincident
1 if the walls are coincident
*******************************************************************/
int are_walls_coincident(struct wall *w1, struct wall *w2, double eps) {
if ((w1 == NULL) || (w2 == NULL))
return 0;
int count = 0;
if (!distinguishable_vec3(w1->vert[0], w2->vert[0], eps))
count++;
if (!distinguishable_vec3(w1->vert[0], w2->vert[1], eps))
count++;
if (!distinguishable_vec3(w1->vert[0], w2->vert[2], eps))
count++;
if (!distinguishable_vec3(w1->vert[1], w2->vert[0], eps))
count++;
if (!distinguishable_vec3(w1->vert[1], w2->vert[1], eps))
count++;
if (!distinguishable_vec3(w1->vert[1], w2->vert[2], eps))
count++;
if (!distinguishable_vec3(w1->vert[2], w2->vert[0], eps))
count++;
if (!distinguishable_vec3(w1->vert[2], w2->vert[1], eps))
count++;
if (!distinguishable_vec3(w1->vert[2], w2->vert[2], eps))
count++;
if (count >= 3)
return 1;
return 0;
}
/******************************************************************
are_walls_coplanar:
In: first wall
second wall
accuracy of the comparison
Out: 1 if the walls are coplanar
0 if walls are not coplanar
Note: see "Real-time rendering" 2nd Ed., by Tomas Akenine-Moller and
Eric Haines, pp. 590-591
******************************************************************/
int are_walls_coplanar(struct wall *w1, struct wall *w2, double eps) {
/* find the plane equation of the second wall in the form (n*x + d2 = 0) */
double d2, d1_0, d1_1, d1_2;
d2 = -dot_prod(&(w2->normal), w2->vert[0]);
/* check whether all vertices of the first wall satisfy
plane equation of the second wall */
d1_0 = dot_prod(&(w2->normal), w1->vert[0]) + d2;
d1_1 = dot_prod(&(w2->normal), w1->vert[1]) + d2;
d1_2 = dot_prod(&(w2->normal), w1->vert[2]) + d2;
if ((!distinguishable(d1_0, 0, eps)) && (!distinguishable(d1_1, 0, eps)) &&
(!distinguishable(d1_2, 0, eps))) {
return 1;
}
return 0;
}
/**********************************************************************
* sorted_insert_wall_aux_list:
* In: linked list
* new node
* Out: new node is added to the linked list in the sorted order
***********************************************************************/
void sorted_insert_wall_aux_list(struct wall_aux_list **headRef,
struct wall_aux_list *newNode) {
/* special case for the head end */
if (*headRef == NULL || (*headRef)->d_prod >= newNode->d_prod) {
newNode->next = *headRef;
*headRef = newNode;
} else {
/* Locate the node before the point of insertion */
struct wall_aux_list *curr = *headRef;
while (curr->next != NULL && curr->next->d_prod < newNode->d_prod) {
curr = curr->next;
}
newNode->next = curr->next;
curr->next = newNode;
}
}
/*******************************************************************
delete_wall_aux_list:
In: linked list
Out: None. The linked list is deleted and memory is freed.
*******************************************************************/
void delete_wall_aux_list(struct wall_aux_list *head) {
struct wall_aux_list *nnext;
while (head != NULL) {
nnext = head->next;
free(head);
head = nnext;
}
}
/*****************************************************************
walls_belong_to_at_least_one_different_restricted_region:
In: wall and surface molecule on it
wall and surface molecule on it
Out: 1 if both walls belong to at least one different restricted region
relative to the properties of surface molecule,
0 otherwise.
Note: Wall can be belong to several regions simultaneously.
Restricted region is one for the boundary of which the reactions
REFL/ABSORB are declared.
******************************************************************/
int walls_belong_to_at_least_one_different_restricted_region(
struct volume *world, struct wall *w1, struct surface_molecule *sm1,
struct wall *w2, struct surface_molecule *sm2) {
if ((w1 == NULL) || (w2 == NULL))
return 0;
struct region_list *rl_1 = find_restricted_regions_by_wall(world, w1, sm1);
struct region_list *rl_2 = find_restricted_regions_by_wall(world, w2, sm2);
if ((rl_1 == NULL) && (rl_2 == NULL))
return 0;
int error_code = 0;
if (rl_1 == NULL) {
/* Is wall 1 part of all restricted regions rl_2, then these restricted
* regions just encompass wall 1 */
if (wall_belongs_to_all_regions_in_region_list(w1, rl_2))
error_code = 0;
else
error_code = 1;
delete_region_list(rl_2);
return error_code;
}
if (rl_2 == NULL) {
/* Is wall 2 part of all restricted regions rl_1, then these restricted
* regions just encompass wall 2 */
if (wall_belongs_to_all_regions_in_region_list(w2, rl_1))
error_code = 0;
else
error_code = 1;
delete_region_list(rl_1);
return error_code;
}
for (struct region_list *rl_t1 = rl_1; rl_t1 != NULL; rl_t1 = rl_t1->next) {
struct region *rp_1 = rl_t1->reg;
if (!region_belongs_to_region_list(rp_1, rl_2)) {
error_code = 1;
break;
}
}
delete_region_list(rl_1);
delete_region_list(rl_2);
return error_code;
}
/**************************************************************************
region_belongs_to_region_list:
In: region
linked list of regions
Out: 1 if region is present in the linked list of regions
0 otherwise
***************************************************************************/
int region_belongs_to_region_list(struct region *rp, struct region_list *head) {
int found = 0;
for (struct region_list *rlp = head; rlp != NULL; rlp = rlp->next) {
if (rlp->reg == rp)
found = 1;
}
if (!found)
return 0;
return 1;
}
/*****************************************************************
wall_belongs_to_all_regions_in_region_list:
In: wall
region_list
Out: 1 if wall belongs to all regions in the region list
0 otherwise.
Note: Wall can belong to several regions simultaneously.
******************************************************************/
int wall_belongs_to_all_regions_in_region_list(struct wall *this_wall,
struct region_list *rlp_head) {
struct region_list *rlp;
struct region *rp;
if (rlp_head == NULL)
return 0;
for (rlp = rlp_head; rlp != NULL; rlp = rlp->next) {
rp = rlp->reg;
if (!get_bit(rp->membership, this_wall->side))
return 0;
}
return 1;
}
/*****************************************************************
wall_belongs_to_any_region_in_region_list:
In: wall
region_list
Out: 1 if wall belongs to any region in the region list
0 otherwise.
Note: Wall can be belong to several regions simultaneously.
Note: It is assumed that both wall and region list are defined for
the same object.
******************************************************************/
int wall_belongs_to_any_region_in_region_list(struct wall *this_wall,
struct region_list *rlp_head) {
struct region_list *rlp;
struct region *rp;
if (rlp_head == NULL)
return 0;
for (rlp = rlp_head; rlp != NULL; rlp = rlp->next) {
rp = rlp->reg;
if (get_bit(rp->membership, this_wall->side))
return 1;
}
return 0;
}
/*********************************************************************
* find_wall_center:
* In: wall
* wall center (return value)
* Out: the center of the wall is found and assigned to vector "center"
**********************************************************************/
void find_wall_center(struct wall *w, struct vector3 *center)
{
if(center == NULL) {
mcell_internal_error("Error in function 'find_wall_center()'.");
}
center->x = (w->vert[0]->x + w->vert[1]->x + w->vert[2]->x) / 3;
center->y = (w->vert[0]->y + w->vert[1]->y + w->vert[2]->y) / 3;
center->z = (w->vert[0]->z + w->vert[1]->z + w->vert[2]->z) / 3;
}
| C |
3D | mcellteam/mcell | src/mdlparse_aux.h | .h | 5,486 | 199 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
#include "mcell_react_out.h"
#include "mcell_reactions.h"
#define WILDCARD_PRESENT 0x1
#define TRIGGER_PRESENT 0x2
#define COUNT_PRESENT 0x4
#define EXPRESSION_PRESENT 0x8
/***************************************************************************
* Miscellaneous parse-time structures
***************************************************************************/
struct arg {
struct arg *next;
unsigned char arg_type; /* DBL, STR */
void *arg_value;
};
struct arg_list {
struct arg *arg_head;
struct arg *arg_tail;
};
struct sm_dat_list {
struct sm_dat *sm_head;
struct sm_dat *sm_tail;
};
struct element_list_head {
struct element_list *elml_head;
struct element_list *elml_tail;
};
#if 0
struct output_set_list {
struct output_set *set_head;
struct output_set *set_tail;
};
struct num_expr_list_head {
struct num_expr_list *value_head;
struct num_expr_list *value_tail;
int value_count;
int shared;
};
struct output_times_inlist {
enum output_timer_type_t type;
double step;
struct num_expr_list_head values;
};
#endif
struct diffusion_constant {
double D;
int is_2d;
};
struct output_times {
enum output_timer_type_t timer_type;
double step_time;
int num_times;
double *times;
};
struct element_connection_list_head {
struct element_connection_list *connection_head;
struct element_connection_list *connection_tail;
int connection_count;
};
struct vertex_list_head {
struct vertex_list *vertex_head;
struct vertex_list *vertex_tail;
int vertex_count;
};
struct parse_mcell_species_list_item {
struct parse_mcell_species_list_item *next;
struct mcell_species_spec *spec;
};
struct parse_mcell_species_list {
struct parse_mcell_species_list_item *species_head;
struct parse_mcell_species_list_item *species_tail;
int species_count;
};
struct species_list_item {
struct species_list_item *next;
struct species *spec;
};
struct species_list {
struct species_list_item *species_head;
struct species_list_item *species_tail;
int species_count;
};
/***************************************************************************
* Parser state structure
***************************************************************************/
struct mdlparse_vars {
/* Line number where last top-level (i.e. non-nested) multi-line (C-style)
* comment was started in the current MDL file. */
int comment_started;
/* Line numbers and filenames for all of the currently parsing files */
u_int line_num[MAX_INCLUDE_DEPTH];
char const *include_filename[MAX_INCLUDE_DEPTH];
/* Stack pointer for filename/line number stack */
u_int include_stack_ptr;
/* The world we are constructing */
struct volume *vol;
/* Stack of object names used to build up qualified names as objects are
* created */
struct name_list *object_name_list;
struct name_list *object_name_list_end;
/* --------------------------------------------- */
/* Pointers to objects being created or modified */
/* Object currently being created or modified. */
struct geom_object *current_object;
/* Pointer to surface class currently being created or modified */
struct species *current_surface_class;
/* Release site currently being created or modified */
struct release_site_obj *current_release_site;
/* Current polygon object being created or modified */
struct polygon_object *current_polygon;
/* Current region object being created or modified */
struct region *current_region;
/* Current bngl_molecule being created or modified */
struct sym_entry *current_bngl_molecule;
/* Current bngl_component being created or modified */
struct mol_comp_ss *current_bngl_component;
/* --------------------------------------------- */
/* Intermediate state for counting */
/* Tracks the count statement types seen in the current output block
* (currently only COUNT and TRIGGER). */
int count_flags;
/* Custom header for reaction output */
char *header_comment;
/* Flag indicating whether to display the exact time */
unsigned char exact_time_flag;
/* --------------------------------------------- */
/* Intermediate state for regions */
int allow_patches;
/* --------------------------------------------- */
/* Temporary allocators */
struct mem_helper *species_list_mem;
struct mem_helper *mol_data_list_mem;
struct mem_helper *output_times_mem;
struct mem_helper *sym_list_mem;
struct mem_helper *path_mem;
struct mem_helper *prod_mem;
};
/***************************************************************************
* Declarations for functions defined in mdlparse.y
***************************************************************************/
void mdlerror(struct mdlparse_vars *parse_state, char const *str);
void mdlerror_fmt(struct mdlparse_vars *parse_state, char const *fmt, ...)
PRINTF_FORMAT(2);
int mdlparse_init(struct volume *vol);
int mdlparse_file(struct mdlparse_vars *parse_state, char const *name);
| Unknown |
3D | mcellteam/mcell | src/minrng.h | .h | 833 | 33 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include <inttypes.h>
typedef uint32_t ub4;
#define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k))))
struct mrng_state {
ub4 a;
ub4 b;
ub4 c;
ub4 d;
};
ub4 mrng_generate(struct mrng_state *x);
void mrng_init(struct mrng_state *x, ub4 seed);
#define mrng_uint32(rng) (mrng_generate(rng))
#define mrng_dbl32(rng) (DBL32 *(double)mrng_uint32(rng))
| Unknown |
3D | mcellteam/mcell | src/diffuse_util.c | .c | 8,714 | 285 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "logging.h"
#include "diffuse_util.h"
#include "mcell_structs.h"
#ifndef MY_PI
#define MY_PI 3.14159265358979324
#endif
/***************************************************************************
r_func:
In: double containing distance (arbitrary units, mean=1.0)
Out: double containing probability of diffusing that distance
***************************************************************************/
double r_func(double s) {
double f, s_sqr, val;
f = 2.2567583341910251478; /* 4.0/sqrt(pi) */
s_sqr = s * s;
val = f * s_sqr * exp(-s_sqr);
return (val);
}
/***************************************************************************
init_r_step:
In: number of desired radial subdivisions
Out: pointer to array of doubles containing those subdivisions
returns NULL on malloc failure
Note: This is for 3D diffusion from a point source (molecule movement)
***************************************************************************/
double *init_r_step(int radial_subdivisions) {
double inc, target, accum, r, r_max, delta_r, delta_r2;
double *r_step = NULL;
int j;
r_step = CHECKED_MALLOC_ARRAY_NODIE(double, radial_subdivisions,
"radial step length table");
if (r_step == NULL)
return NULL;
inc = 1.0 / radial_subdivisions;
accum = 0;
r_max = 3.5;
delta_r = r_max / (1000 * radial_subdivisions);
delta_r2 = 0.5 * delta_r;
r = 0;
target = 0.5 * inc;
j = 0;
while (j < radial_subdivisions) {
accum = accum + (delta_r * r_func(r + delta_r2));
r = r + delta_r;
if (accum >= target) {
r_step[j] = r;
target = target + inc;
j++;
}
}
no_printf("Min r step = %20.17g Max r step = %20.17g\n", r_step[0],
r_step[radial_subdivisions - 1]);
return r_step;
}
/***************************************************************************
init_r_step_surface:
In: number of desired radial subdivisions
Out: pointer to array of doubles containing those subdivisions
returns NULL on malloc failure
Note: This is for 3D molecules emitted from a plane
***************************************************************************/
double *init_r_step_surface(int radial_subdivisions) {
static const double sqrt_pi = 1.7724538509055160273;
double *r_step_s = CHECKED_MALLOC_ARRAY_NODIE(
double, radial_subdivisions, "radial step length table (surface)");
if (r_step_s == NULL)
return NULL;
double step = 1.0 / radial_subdivisions;
int i = 0;
double p = (1.0 - 1e-6) * step;
double r = 0;
for (; p < 1.0; p += step, i++) {
double r_min = 0;
double r_max = 3.0; /* 17 bit high-end CDF cutoff */
for (int j = 0; j < 20; j++) /* 20 bits of accuracy */
{
r = 0.5 * (r_min + r_max);
double cdf = 1.0 - exp(-r * r) + sqrt_pi * r * erfc(r);
if (cdf > p)
r_max = r;
else
r_min = r;
}
r_step_s[i] = r;
}
return r_step_s;
}
/***************************************************************************
init_r_step_3d_release:
In: number of desired radial subdivisions
Out: pointer to array of doubles containing those subdivisions
returns NULL on malloc failure
Note: This is for 3D molecules emitted from a plane
***************************************************************************/
double *init_r_step_3d_release(int radial_subdivisions) {
double *r_step_r = NULL;
double p, r_max, r_min, step, cdf;
double r = 0.0;
int i, j;
static const double sqrt_pi_over_2 = 0.886226925452758015;
r_step_r = CHECKED_MALLOC_ARRAY_NODIE(
double, radial_subdivisions, "radial step length table (3d release)");
if (r_step_r == NULL)
return NULL;
step = 1.0 / radial_subdivisions;
for (i = 0, p = step * 0.5; i < radial_subdivisions; p += step, i++) {
r_min = 0;
r_max = 3.5; /* 18 bit high-end CDF cutoff */
for (j = 0; j < 20; j++) /* 20 bits accuracy */
{
r = 0.5 * (r_min + r_max);
cdf = 1.0 - exp(-r * r) + sqrt_pi_over_2 * r * erfc(r);
if (cdf > p)
r_max = r;
else
r_min = r;
}
r_step_r[i] = r;
}
return r_step_r;
}
/***************************************************************************
init_d_step:
In: number of desired angular subdivisions
pointer to an int that will contain the actual number of subdivisions
Out: returns a pointer to array of doubles containing the subdivisions
returns NULL on malloc failure
Note: no longer calls init_r_step itself, so you must call both
data contains three doubles (x,y,z) per requested subdivision
***************************************************************************/
#define DEG_2_RAD 0.01745329251994329576
#define RAD_2_DEG 57.29577951308232087684
/* Multiply by this factor (Pi/180) to convert from degrees to radians */
double *init_d_step(int radial_directions, unsigned int *actual_directions) {
double z;
double d_phi, phi_mid, phi_edge_prev, phi_edge_approx, phi_factor, theta_mid;
double *phi_edge = NULL;
double x_bias, y_bias, z_bias;
double x, y;
int i, j, k, n_tot, n_edge, n_patches;
int *n = NULL;
double *d_step = NULL;
n_edge = (int)sqrt(radial_directions * MY_PI / 2.0);
n_patches = (int)(2 * (n_edge * n_edge) / MY_PI);
no_printf("desired n_patches in octant = %d\n", radial_directions);
no_printf("approximate n_patches in octant = %d\n", n_patches);
phi_edge =
CHECKED_MALLOC_ARRAY_NODIE(double, n_edge, "directional step table");
if (phi_edge == NULL)
return NULL;
n = CHECKED_MALLOC_ARRAY_NODIE(int, n_edge, "directional step table");
if (n == NULL) {
free(phi_edge);
return NULL;
}
for (i = 0; i < n_edge; i++) {
phi_edge[i] = 0;
n[i] = 0;
}
x_bias = 0;
y_bias = 0;
z_bias = 0;
phi_edge_prev = 0;
d_phi = MY_PI / (2.0 * n_edge);
n_tot = 0;
for (i = 0; i < n_edge; i++) {
phi_edge_approx = phi_edge_prev + d_phi;
phi_mid = phi_edge_prev + (d_phi / 2.0);
if (phi_mid < 60 * DEG_2_RAD) {
n[i] = (int)((n_patches * (cos(phi_edge_prev) - cos(phi_edge_approx))) +
0.5);
} else {
n[i] = (int)((n_patches * (cos(phi_edge_prev) - cos(phi_edge_approx))) -
0.5);
}
n_tot += n[i];
no_printf("i = %d phi mid = %f n = %d n_tot = %d\n", i,
phi_mid * RAD_2_DEG, n[i], n_tot);
phi_edge[i] = acos(cos(phi_edge_prev) - ((double)n[i] / n_patches));
phi_edge_prev = phi_edge[i];
}
phi_factor = phi_edge[n_edge - 1] * 2.0 / MY_PI;
for (i = 0; i < n_edge; i++) {
phi_edge[i] = phi_edge[i] / phi_factor;
}
*actual_directions = n_tot;
no_printf("actual n_patches in octant = %d\n", n_tot);
no_printf("phi factor = %f\n", phi_factor);
d_step = CHECKED_MALLOC_ARRAY(double, 3 * n_tot, "directional step table");
if (d_step == NULL) {
free(n);
free(phi_edge);
return NULL;
}
k = 0;
phi_edge_prev = 0;
for (i = 0; i < n_edge; i++) {
phi_mid = (phi_edge_prev + phi_edge[i]) / 2.0;
for (j = 0; j < n[i]; j++) {
theta_mid = (j * (MY_PI / (2.0 * n[i]))) + (0.5 * MY_PI / (2.0 * n[i]));
x = sin(phi_mid) * cos(theta_mid);
y = sin(phi_mid) * sin(theta_mid);
z = cos(phi_mid);
d_step[k++] = x;
d_step[k++] = y;
d_step[k++] = z;
x_bias += x;
y_bias += y;
z_bias += z;
}
phi_edge_prev = phi_edge[i];
}
#ifdef DEBUG
{
FILE *fp;
mcell_log("x_bias = %.17g\n", x_bias);
mcell_log("y_bias = %.17g\n", y_bias);
mcell_log("z_bias = %.17g\n", z_bias);
fp = fopen("vector_table.rib", "w");
for (i = 0; i < radial_directions; i++) {
j = 3 * i;
/*
fprintf(fp,"[ %8.5e %8.5e %8.5e
]\n",d_step[j],d_step[j+1],d_step[j+2]);
*/
fprintf(fp, "AttributeBegin\n");
fprintf(fp, "Translate %.9g %.9g %.9g\n", d_step[j], d_step[j + 1],
d_step[j + 2]);
fprintf(fp, "ObjectInstance 1\n");
fprintf(fp, "AttributeEnd\n");
}
fclose(fp);
}
#endif
free(n);
free(phi_edge);
return d_step;
}
#undef DEG_2_RAD
#undef RAD_2_DEG
| C |
3D | mcellteam/mcell | src/mdlparse_util.c | .c | 303,068 | 8,656 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
*USA.
*
******************************************************************************/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <errno.h>
#include <sys/stat.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <signal.h>
#include <ctype.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include "logging.h"
#include "strfunc.h"
#include "sym_table.h"
#include "mdlparse_util.h"
#include "react_output.h"
#include "diffuse_util.h"
#include "mcell_misc.h"
#include "mcell_structs.h"
#include "mcell_viz.h"
#include "mcell_release.h"
#include "dyngeom_parse_extras.h"
#include "mem_util.h"
extern void chkpt_signal_handler(int sn);
/* Free a variable value, leaving the symbol free for reassignment to another
* type. */
static int mdl_free_variable_value(struct mdlparse_vars *parse_state,
struct sym_entry *sym);
/*************************************************************************
mdl_strip_quotes:
Strips the quotes from a quoted string.
In: in: string to strip
Out: stripped string, or NULL on error
*************************************************************************/
char *mdl_strip_quotes(char *in) {
char *q = strip_quotes(in);
free(in);
if (q != NULL)
return q;
else {
mcell_allocfailed("Failed to strip quotes from a quoted string.");
return NULL;
}
}
/*************************************************************************
mdl_strcat:
Concatenates two strings, freeing the original strings.
In: s1: first string to concatenate
s2: second string to concatenate
Out: conjoined string, or NULL if an error occurred
*************************************************************************/
char *mdl_strcat(char *s1, char *s2) {
char *cat = my_strcat(s1, s2);
free(s1);
free(s2);
if (cat != NULL)
return cat;
else {
mcell_allocfailed("Failed to concatenate two strings.");
return NULL;
}
}
/*************************************************************************
mdl_strdup:
Duplicates a string.
In: s1: string to duplicate
Out: allocated string, or NULL if an error occurred
*************************************************************************/
char *mdl_strdup(char const *s1) {
char *s = strdup(s1);
if (s1 == NULL)
mcell_allocfailed("Failed to duplicate a string.");
return s;
}
/*************************************************************************
mdl_warning:
Display a warning message about something encountered during the parse
process.
In: parse_state: parser state
fmt: Format string (as for printf)
...: arguments
Out: Warning message is printed in the log_file
*************************************************************************/
void mdl_warning(struct mdlparse_vars *parse_state, char const *fmt, ...) {
va_list arglist;
if (parse_state->vol->procnum != 0)
return;
mcell_log_raw("MCell: Warning on line: %d of file: %s ",
parse_state->line_num[parse_state->include_stack_ptr - 1],
parse_state->vol->curr_file);
va_start(arglist, fmt);
mcell_logv_raw(fmt, arglist);
va_end(arglist);
mcell_log_raw("\n");
}
/**************************************************************************
mdl_valid_file_mode:
Check that the speficied file mode string is valid for an fopen statement.
In: parse_state: parser state
mode: mode string to check
Out: 1 if
**************************************************************************/
int mdl_valid_file_mode(struct mdlparse_vars *parse_state, const char *mode) {
char c = mode[0];
if (c != 'r' && c != 'w' && c != 'a') {
mdlerror_fmt(parse_state, "Invalid file mode: %s", mode);
return 1;
}
if (c == 'r') {
mdlerror(parse_state,
"MCell models do not currently support opening files for reading");
return 1;
}
return 0;
}
/**************************************************************************
mdl_expr_log:
Compute a natural log, reporting any range or domain errors.
In: parse_state: parser state
in: value whose log to compute
out: destination for computed value
Out: 0 on success, 1 on failure. *out is updated on success
**************************************************************************/
int mdl_expr_log(struct mdlparse_vars *parse_state, double in, double *out) {
if (in <= 0.0) {
mdlerror_fmt(parse_state,
"Attempt to compute LOG(%.15g), which is not defined.", in);
return 1;
}
*out = log(in);
return 0;
}
/**************************************************************************
mdl_expr_log10:
Compute a base-10 log, reporting any range or domain errors.
In: parse_state: parser state
in: value whose log to compute
out: destination for computed value
Out: 0 on success, 1 on failure. *out is updated on success
**************************************************************************/
int mdl_expr_log10(struct mdlparse_vars *parse_state, double in, double *out) {
if (in <= 0.0) {
mdlerror_fmt(parse_state,
"Attempt to compute LOG10(%.15g), which is not defined.", in);
return 1;
}
*out = log10(in);
return 0;
}
/**************************************************************************
mdl_expr_mod:
Compute a floating point modulo operator, reporting any domain errors.
In: parse_state: parser state
in: value
divisor: divisor for modulo operator
out: destination for computed value
Out: 0 on success, 1 on failure. *out is updated on success
**************************************************************************/
int mdl_expr_mod(struct mdlparse_vars *parse_state, double in, double divisor,
double *out) {
if (divisor == 0.0) {
mdlerror_fmt(parse_state,
"Attempt to compute MOD(%.15g, 0.0), which is not defined.",
in);
return 1;
}
*out = fmod(in, divisor);
return 0;
}
/**************************************************************************
mdl_expr_div:
Compute a division, reporting any domain or range errors.
In: parse_state: parser state
in: value
divisor: divisor
out: destination for computed value
Out: 0 on success, 1 on failure. *out is updated on success
**************************************************************************/
int mdl_expr_div(struct mdlparse_vars *parse_state, double in, double divisor,
double *out) {
if (divisor == 0.0) {
mdlerror_fmt(parse_state, "Attempt to divide %.15g by zero", in);
return 1;
}
*out = in / divisor;
if (isinf(*out)) {
mdlerror_fmt(parse_state,
"Cannot compute %.15g / %.15g: result is too large", in,
divisor);
return 1;
}
return 0;
}
/**************************************************************************
mdl_expr_pow:
Compute an exponentiation, reporting any domain or range errors.
In: parse_state: parser state
in: value
exponent: exponent for exponentiation
out: destination for computed value
Out: 0 on success, 1 on failure. *out is updated on success
**************************************************************************/
int mdl_expr_pow(struct mdlparse_vars *parse_state, double in, double exponent,
double *out) {
if (in < 0.0) {
if (exponent != (int)exponent) {
mdlerror_fmt(parse_state, "Cannot compute %.15g^%.15g: negative value "
"raised to non-integral power would be complex",
in, exponent);
return 1;
}
}
*out = pow(in, exponent);
if (isinf(*out)) {
mdlerror_fmt(parse_state, "Cannot compute %.15g^%.15g: result is too large",
in, exponent);
return 1;
}
return 0;
}
/**************************************************************************
mdl_expr_rng_uniform:
Compute a uniform random variate.
In: parse_state: parser state
Out: random variate, uniform on [0, 1)
**************************************************************************/
double mdl_expr_rng_uniform(struct mdlparse_vars *parse_state) {
return rng_dbl(parse_state->vol->rng);
}
/**************************************************************************
mdl_expr_roundoff:
Round the input value off to n significant figures.
In: in: value to round off
ndigits: number of digits
Out: value rounded to n digits
**************************************************************************/
double mdl_expr_roundoff(double in, int ndigits) {
char fmt_string[1024];
fmt_string[0] = '\0';
snprintf(fmt_string, 1024, "%.*g", ndigits, in);
return strtod(fmt_string, (char **)NULL);
}
/**************************************************************************
mdl_expr_string_to_double:
Convert a string value to a double, freeing the string value.
In: parse_state: parser state
str: string form of value
out: location to receive parsed value
Out: 0 on success, 1 on failure. *out is updated.
**************************************************************************/
int mdl_expr_string_to_double(struct mdlparse_vars *parse_state, char *str,
double *out) {
*out = strtod(str, (char **)NULL);
if (errno == ERANGE) {
mdlerror_fmt(parse_state, "Error converting string to number: %s", str);
free(str);
return 1;
}
free(str);
return 0;
}
/**************************************************************************
mdl_new_filehandle:
Create a new filehandle in the global symbol table.
In: parse_state: parser state
name: name for file symbol
Out: symbol or NULL on error
**************************************************************************/
struct sym_entry *mdl_new_filehandle(struct mdlparse_vars *parse_state,
char *name) {
struct sym_entry *sym;
sym = retrieve_sym(name, parse_state->vol->fstream_sym_table);
/* If this file is already open, close it. */
if (sym != NULL) {
struct file_stream *filep = (struct file_stream *)sym->value;
if (filep->stream != NULL) {
fclose(filep->stream);
free(filep->name);
filep->stream = NULL;
filep->name = NULL;
}
}
/* Otherwise, create it */
else if ((sym = store_sym(name, FSTRM, parse_state->vol->fstream_sym_table,
NULL)) == NULL) {
mdlerror_fmt(parse_state, "Out of memory while creating file stream: %s",
name);
free(name);
return NULL;
}
free(name);
return sym;
}
/**************************************************************************
mdl_fopen:
Process an fopen statement, opening a new file handle.
In: parse_state: parser state
filesym: symbol for the file
name: filename
mode: file open mode
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_fopen(struct mdlparse_vars *parse_state, struct sym_entry *filesym,
char *name, char *mode) {
struct file_stream *filep = (struct file_stream *)filesym->value;
filep->name = name;
if ((filep->stream = fopen(filep->name, mode)) == NULL) {
mdlerror_fmt(parse_state, "Cannot open file: %s", filep->name);
free(mode);
/* XXX: Free filep? */
return 1;
}
free(mode);
return 0;
}
/**************************************************************************
mdl_fclose:
Process an fclose statement, closing an existing file handle.
In: parse_state: parser state
filesym: symbol for the file
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_fclose(struct mdlparse_vars *parse_state, struct sym_entry *filesym) {
struct file_stream *filep = (struct file_stream *)filesym->value;
if (filep->stream == NULL)
return 0;
if (fclose(filep->stream) != 0) {
filep->stream = NULL;
mdlerror_fmt(parse_state, "Error closing file: %s", filep->name);
free(filep->name);
filep->name = NULL;
return 1;
}
filep->stream = NULL;
free(filep->name);
filep->name = NULL;
return 0;
}
/**************************************************************************
double_dup:
In: parse_state: parser state
value: value for newly allocated double
Out: new double value that is copy of the input double value
**************************************************************************/
static double *double_dup(double value) {
double *dup_value;
dup_value = CHECKED_MALLOC_STRUCT(double, "numeric variable");
if (dup_value != NULL)
*dup_value = value;
return dup_value;
}
/*************************************************************************
mdl_new_printf_arg_double:
Create a new double argument for a printf argument list.
In: d: value for argument
Out: The new argument, or NULL if an error occurred.
*************************************************************************/
struct arg *mdl_new_printf_arg_double(double d) {
struct arg *a = CHECKED_MALLOC_STRUCT(struct arg, "format argument");
if (a == NULL)
return NULL;
if ((a->arg_value = double_dup(d)) == NULL) {
free(a);
return NULL;
}
a->arg_type = DBL;
a->next = NULL;
return a;
}
/*************************************************************************
mdl_new_printf_arg_string:
Create a new string argument for a printf argument list.
In: str: value for argument
Out: The new argument, or NULL if an error occurred.
*************************************************************************/
struct arg *mdl_new_printf_arg_string(char const *str) {
struct arg *a = CHECKED_MALLOC_STRUCT(struct arg, "format argument");
if (a == NULL)
return NULL;
a->arg_value = (void *)str;
a->arg_type = STR;
a->next = NULL;
return a;
}
/*************************************************************************
mdl_free_printf_arg_list:
Frees a printf argument list.
In: args: list to free
Out: all arguments are freed
*************************************************************************/
static void mdl_free_printf_arg_list(struct arg *args) {
while (args != NULL) {
struct arg *arg_next = args->next;
if (args->arg_type == DBL)
free(args->arg_value);
free(args);
args = arg_next;
}
}
/*************************************************************************
mdl_expand_string_escapes:
Expands C-style escape sequences in the string.
In: in: string to expand
Out: string with expanded escape sequences
*************************************************************************/
char *mdl_expand_string_escapes(char *in) {
char *out;
char *in_start = in;
/* Allocate buffer for new string */
char *expanded = (char *)CHECKED_MALLOC(strlen(in) + 1, "printf format string");
if (expanded == NULL)
return NULL;
/* Copy expanded string to new buffer */
out = expanded;
while (*in != '\0') {
if (*in != '\\')
*out++ = *in++;
else {
++in;
if (*in == 'n')
*out++ = '\n';
else if (*in == 't')
*out++ = '\t';
else if (*in == 'e')
*out++ = '\x1b';
else if (*in == 'a')
*out++ = '\a';
else if (*in == 'f')
*out++ = '\f';
else if (*in == 'v')
*out++ = '\v';
else if (*in == 'b')
*out++ = '\b';
else if (*in == 'x') {
if (isxdigit(in[1]) && isxdigit(in[2])) {
char buffer[3];
buffer[0] = in[1];
buffer[1] = in[2];
buffer[2] = '\0';
*out++ = (char)strtol(buffer, NULL, 16);
if (out[-1] == '\0')
out[-1] = ' ';
in += 2;
} else
*out++ = 'x';
} else if (*in == '0') {
if ('0' <= in[1] && in[1] <= '7' && '0' <= in[2] && in[2] <= '7' &&
'0' <= in[3] && in[3] <= '7') {
char buffer[4];
buffer[0] = in[1];
buffer[1] = in[2];
buffer[2] = in[3];
buffer[3] = '\0';
*out++ = (char)strtol(buffer, NULL, 8);
if (out[-1] == '\0')
out[-1] = ' ';
in += 3;
} else
*out++ = '0';
} else if (*in == '\\')
*out++ = '\\';
else if (*in == '"')
*out++ = '"';
else if (*in == '\0') {
*out++ = '\\';
break;
} else
*out++ = *in;
++in;
}
}
*out++ = '\0';
free(in_start);
return expanded;
}
/*************************************************************************
Internal code used to designate the type required to fulfill a particular
format specifier within a printf-style format string.
*************************************************************************/
enum {
PRINTF_INVALID = -1,
PRINTF_DOUBLE,
PRINTF_SIGNED_CHAR,
PRINTF_UNSIGNED_CHAR,
PRINTF_SHORT_INT,
PRINTF_U_SHORT_INT,
PRINTF_INT,
PRINTF_U_INT,
PRINTF_LONG_INT,
PRINTF_U_LONG_INT,
PRINTF_LONG_LONG_INT,
PRINTF_U_LONG_LONG_INT,
PRINTF_STRING
};
/*************************************************************************
get_printf_conversion_specifier:
Find the details of the conversion specifier found in the given segment of
format string.
In: parse_state: parse arguments
fmt: format string to scan
num_asterisks: counter for number of asterisks in conversion specifier
Out: code indicating the type required for this conversion specifier, or
PRINTF_INVALID if it's invalid or disallowed.
*************************************************************************/
static int get_printf_conversion_specifier(struct mdlparse_vars *parse_state,
char const *fmt,
int *num_asterisks) {
static char CONVERSION_SPECIFIERS[] = "diouxXeEfFgGaAcCsSpnm";
char const *const fmt_orig = fmt;
char length = '\0';
*num_asterisks = 0;
for (++fmt; *fmt != '\0'; ++fmt) {
if (isalpha(*fmt) && strchr(CONVERSION_SPECIFIERS, *fmt) != NULL)
break;
/* Scan any options in the string, bombing out if we find something
* invalid, and keeping track of the length specifiers and asterisks we
* find. */
switch (*fmt) {
case 'l':
if (length == '\0')
length = 'l';
else if (length == 'l')
length = 'L';
else {
mdlerror_fmt(parse_state, "Format string segment '%s' has an invalid "
"length modifier inside a conversion "
"specification.",
fmt_orig);
return PRINTF_INVALID;
}
break;
case 'h':
if (length == '\0')
length = 'h';
else if (length == 'h')
length = 'H';
else {
mdlerror_fmt(parse_state, "Format string segment '%s' has an invalid "
"length modifier inside a conversion "
"specification.",
fmt_orig);
return PRINTF_INVALID;
}
break;
case 'L':
case 'q':
case 'j':
case 'z':
case 't':
mdlerror_fmt(parse_state, "Format string segment '%s' has an unsupported "
"length modifier (%c) inside a conversion "
"specification.",
fmt_orig, *fmt);
return PRINTF_INVALID;
case '*':
++*num_asterisks;
if (*num_asterisks > 2) {
mdlerror_fmt(parse_state, "Format string segment '%s' has more than "
"two asterisks inside a conversion "
"specification, which is unsupported by "
"MCell.",
fmt_orig);
return PRINTF_INVALID;
}
break;
case '$':
mdlerror_fmt(parse_state, "Format string segment '%s' has a '$' inside a "
"conversion specification, which is "
"unsupported by MCell.",
fmt_orig);
return PRINTF_INVALID;
default:
/* Skip this char. */
break;
}
}
/* Filter invalid types */
if (*fmt == '\0') {
mdlerror_fmt(parse_state,
"Format string segment '%s' contains no conversion specifier.",
fmt_orig);
return PRINTF_INVALID;
} else if (*fmt == 'n') {
mdlerror_fmt(parse_state, "Format string segment '%s' attempts to use "
"dangerous conversion specifier 'n'.",
fmt_orig);
return PRINTF_INVALID;
}
/* Now, handle the format specifier itself */
switch (*fmt) {
case 'd':
case 'i':
if (length == '\0')
return PRINTF_INT;
else if (length == 'l')
return PRINTF_LONG_INT;
else if (length == 'L')
return PRINTF_LONG_LONG_INT;
else if (length == 'h')
return PRINTF_SHORT_INT;
else if (length == 'H')
return PRINTF_SIGNED_CHAR;
else {
mdlerror_fmt(parse_state, "Format string segment '%s' uses unsupported "
"length specifier '%c' for integer.",
fmt_orig, length);
return PRINTF_INVALID;
}
case 'o':
case 'u':
case 'x':
case 'X':
if (length == '\0')
return PRINTF_U_INT;
else if (length == 'l')
return PRINTF_U_LONG_INT;
else if (length == 'L')
return PRINTF_U_LONG_LONG_INT;
else if (length == 'h')
return PRINTF_U_SHORT_INT;
else if (length == 'H')
return PRINTF_UNSIGNED_CHAR;
else {
mdlerror_fmt(parse_state, "Format string segment '%s' uses unsupported "
"length specifier '%c' for unsigned integer.",
fmt_orig, length);
return PRINTF_INVALID;
}
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
case 'a':
case 'A':
if (length == '\0')
return PRINTF_DOUBLE;
else if (length == 'l')
return PRINTF_DOUBLE;
else {
mdlerror_fmt(parse_state, "Format string segment '%s' uses unsupported "
"length specifier '%c' for double-precision "
"floating point.",
fmt_orig, length);
return PRINTF_INVALID;
}
case 'c':
if (length == '\0')
return PRINTF_SIGNED_CHAR;
else {
mdlerror_fmt(parse_state, "Format string segment '%s' uses unsupported "
"length specifier '%c' for char.",
fmt_orig, length);
return PRINTF_INVALID;
}
case 's':
if (length == '\0')
return PRINTF_STRING;
else {
mdlerror_fmt(parse_state, "Format string segment '%s' uses unsupported "
"length specifier '%c' for string.",
fmt_orig, length);
return PRINTF_INVALID;
}
case 'C':
case 'S':
case 'p':
case 'm':
default:
mdlerror_fmt(parse_state, "Format string segment '%s' uses unsupported "
"conversion specifier '%c'.",
fmt_orig, *fmt);
return PRINTF_INVALID;
}
return PRINTF_INVALID;
}
/*************************************************************************
my_sprintf_segment:
fprintf a segment of a format string, accounting for data type conversions.
In: parse_state: parse arguments
fmt_seg: format string segment
argpp: pointer to args list (will be advanced if we consume arguments)
Out: formatted segment on success, NULL on failure; *argpp is updated.
*************************************************************************/
static char *my_sprintf_segment(struct mdlparse_vars *parse_state,
const char *fmt_seg, struct arg **argpp) {
int num_asterisks = 0;
struct arg *argp = *argpp;
int spec_type =
get_printf_conversion_specifier(parse_state, fmt_seg, &num_asterisks);
if (spec_type == PRINTF_INVALID)
return NULL;
/* Pull out arguments for asterisks */
int ast1 = 0, ast2 = 0;
switch (num_asterisks) {
case 0:
break;
case 2:
if (argp->arg_type == DBL)
ast2 = (int)(*(double *)(argp->arg_value) + EPS_C);
else {
mdlerror_fmt(parse_state, "Argument to be consumed by '*' in conversion "
"specification segment '%s' is not numeric",
fmt_seg);
return NULL;
}
if ((argp = argp->next) == NULL) {
mdlerror_fmt(
parse_state,
"Too few arguments for conversion specification segment '%s'",
fmt_seg);
return NULL;
}
/* FALL THROUGH */
case 1:
if (argp->arg_type == DBL)
ast1 = (int)(*(double *)(argp->arg_value) + EPS_C);
else {
mdlerror_fmt(parse_state, "Argument to be consumed by '*' in conversion "
"specification segment '%s' is not numeric",
fmt_seg);
return NULL;
}
if ((argp = argp->next) == NULL) {
mdlerror_fmt(
parse_state,
"Too few arguments for conversion specification segment '%s'",
fmt_seg);
return NULL;
}
break;
default:
mdlerror_fmt(
parse_state,
"Invalid asterisk count in conversion specification segment '%s'",
fmt_seg);
return NULL;
}
/* Type check */
if (argp->arg_type == STR) {
if (spec_type != PRINTF_STRING && spec_type != PRINTF_SIGNED_CHAR &&
spec_type != PRINTF_UNSIGNED_CHAR) {
mdlerror_fmt(parse_state, "Argument in conversion specification segment "
"'%s' is a string, but a numeric value is "
"required",
fmt_seg);
return NULL;
}
} else {
if (spec_type == PRINTF_STRING) {
mdlerror_fmt(parse_state, "Argument in conversion specification segment "
"'%s' is numeric, but a string value is "
"required",
fmt_seg);
return NULL;
}
}
/* Now, convert! */
int arg_value;
char *formatted = NULL;
switch (spec_type) {
case PRINTF_STRING:
switch (num_asterisks) {
case 0:
formatted = alloc_sprintf(fmt_seg, (char *)argp->arg_value);
break;
case 1:
formatted = alloc_sprintf(fmt_seg, ast1, (char *)argp->arg_value);
break;
case 2:
formatted = alloc_sprintf(fmt_seg, ast2, ast1, (char *)argp->arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
case PRINTF_SIGNED_CHAR:
case PRINTF_UNSIGNED_CHAR:
if (argp->arg_type == STR) {
if (strlen((char *)argp->arg_value) > 1) {
mdlerror_fmt(parse_state, "Argument in conversion specification "
"segment '%s' has too many characters",
fmt_seg);
return NULL;
}
if (spec_type == PRINTF_SIGNED_CHAR)
arg_value = *(signed char *)argp->arg_value;
else
arg_value = *(unsigned char *)argp->arg_value;
} else {
if (spec_type == PRINTF_SIGNED_CHAR)
arg_value = (signed char)*(double *)argp->arg_value;
else
arg_value = (unsigned char)*(double *)argp->arg_value;
}
switch (num_asterisks) {
case 0:
formatted = alloc_sprintf(fmt_seg, arg_value);
break;
case 1:
formatted = alloc_sprintf(fmt_seg, ast1, arg_value);
break;
case 2:
formatted = alloc_sprintf(fmt_seg, ast2, ast1, arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
case PRINTF_DOUBLE:
switch (num_asterisks) {
case 0:
formatted = alloc_sprintf(fmt_seg, *(double *)argp->arg_value);
break;
case 1:
formatted = alloc_sprintf(fmt_seg, ast1, *(double *)argp->arg_value);
break;
case 2:
formatted =
alloc_sprintf(fmt_seg, ast2, ast1, *(double *)argp->arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
case PRINTF_INT:
switch (num_asterisks) {
case 0:
formatted = alloc_sprintf(fmt_seg, (int)*(double *)argp->arg_value);
break;
case 1:
formatted = alloc_sprintf(fmt_seg, ast1, (int)*(double *)argp->arg_value);
break;
case 2:
formatted =
alloc_sprintf(fmt_seg, ast2, ast1, (int)*(double *)argp->arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
case PRINTF_LONG_INT:
switch (num_asterisks) {
case 0:
formatted = alloc_sprintf(fmt_seg, (long int)*(double *)argp->arg_value);
break;
case 1:
formatted =
alloc_sprintf(fmt_seg, ast1, (long int)*(double *)argp->arg_value);
break;
case 2:
formatted = alloc_sprintf(fmt_seg, ast2, ast1,
(long int)*(double *)argp->arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
case PRINTF_LONG_LONG_INT:
switch (num_asterisks) {
case 0:
formatted =
alloc_sprintf(fmt_seg, (long long int)*(double *)argp->arg_value);
break;
case 1:
formatted = alloc_sprintf(fmt_seg, ast1,
(long long int)*(double *)argp->arg_value);
break;
case 2:
formatted = alloc_sprintf(fmt_seg, ast2, ast1,
(long long int)*(double *)argp->arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
case PRINTF_SHORT_INT:
switch (num_asterisks) {
case 0:
formatted = alloc_sprintf(fmt_seg, (short int)*(double *)argp->arg_value);
break;
case 1:
formatted =
alloc_sprintf(fmt_seg, ast1, (short int)*(double *)argp->arg_value);
break;
case 2:
formatted = alloc_sprintf(fmt_seg, ast2, ast1,
(short int)*(double *)argp->arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
case PRINTF_U_INT:
switch (num_asterisks) {
case 0:
formatted =
alloc_sprintf(fmt_seg, (unsigned int)*(double *)argp->arg_value);
break;
case 1:
formatted = alloc_sprintf(fmt_seg, ast1,
(unsigned int)*(double *)argp->arg_value);
break;
case 2:
formatted = alloc_sprintf(fmt_seg, ast2, ast1,
(unsigned int)*(double *)argp->arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
case PRINTF_U_LONG_INT:
switch (num_asterisks) {
case 0:
formatted =
alloc_sprintf(fmt_seg, (unsigned long int)*(double *)argp->arg_value);
break;
case 1:
formatted = alloc_sprintf(fmt_seg, ast1,
(unsigned long int)*(double *)argp->arg_value);
break;
case 2:
formatted = alloc_sprintf(fmt_seg, ast2, ast1,
(unsigned long int)*(double *)argp->arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
case PRINTF_U_LONG_LONG_INT:
switch (num_asterisks) {
case 0:
formatted = alloc_sprintf(
fmt_seg, (unsigned long long int)*(double *)argp->arg_value);
break;
case 1:
formatted = alloc_sprintf(
fmt_seg, ast1, (unsigned long long int)*(double *)argp->arg_value);
break;
case 2:
formatted =
alloc_sprintf(fmt_seg, ast2, ast1,
(unsigned long long int)*(double *)argp->arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
case PRINTF_U_SHORT_INT:
switch (num_asterisks) {
case 0:
formatted = alloc_sprintf(fmt_seg,
(unsigned short int)*(double *)argp->arg_value);
break;
case 1:
formatted = alloc_sprintf(fmt_seg, ast1,
(unsigned short int)*(double *)argp->arg_value);
break;
case 2:
formatted = alloc_sprintf(fmt_seg, ast2, ast1,
(unsigned short int)*(double *)argp->arg_value);
break;
default:
UNHANDLED_CASE(num_asterisks);
}
break;
default:
UNHANDLED_CASE(spec_type);
}
if (formatted == NULL)
mcell_allocfailed("Failed to format a string for an MDL "
"printf/fprintf/spritnf statement.");
else
*argpp = argp->next;
return formatted;
}
/*************************************************************************
Temporary structure used by sprintf implementation.
*************************************************************************/
struct sprintf_output_list {
struct sprintf_output_list *next; /* Next item in list */
size_t len; /* Length of this item */
char *segment; /* Data for this item */
};
/*************************************************************************
my_sprintf:
sprintf-like formatting of MDL arguments.
In: parse_state: parser state
format: string to expand
argp: argument list
Out: 0 on success, 1 on failure
*************************************************************************/
static char *my_sprintf(struct mdlparse_vars *parse_state, char *format,
struct arg *argp) {
char *this_start, *this_end;
char const *const format_orig = format;
int total_len = 0;
char *buffer = NULL;
char *pos = NULL;
struct sprintf_output_list head, *tail;
head.segment = NULL;
head.next = NULL;
head.len = 0u;
tail = &head;
/* Find the start of the first format code */
this_start = strchr(format, '%');
while (this_start != NULL && this_start[1] == '%')
this_start = strchr(this_start + 2, '%');
/* If we have text before the first conversion specification, copy it. */
if (this_start != NULL) {
tail = tail->next = CHECKED_MALLOC_STRUCT(struct sprintf_output_list,
"SPRINTF output list segment");
if (tail == NULL)
goto failure;
memset(tail, 0, sizeof(*tail));
*this_start = '\0';
tail->segment = mdl_strdup(format);
*this_start = '%';
if (tail->segment == NULL)
goto failure;
tail->len = strlen(tail->segment);
head.len += tail->len;
format = this_start;
}
/* Process each format code */
while (this_start != NULL) {
/* If we've run out of arguments... */
if (argp == NULL) {
mdlerror_fmt(parse_state,
"Insufficient arguments for printf-style format string '%s'",
format_orig);
goto failure;
}
/* Find the start of the first format code */
this_end = strchr(this_start + 1, '%');
while (this_end != NULL && this_end[1] == '%')
this_end = strchr(this_end + 2, '%');
/* If we have only a single format code, do the rest of the string */
if (this_end == NULL) {
tail = tail->next = CHECKED_MALLOC_STRUCT(struct sprintf_output_list,
"SPRINTF output list segment");
if (tail == NULL)
goto failure;
memset(tail, 0, sizeof(*tail));
tail->segment = my_sprintf_segment(parse_state, format, &argp);
if (tail->segment == NULL)
goto failure;
tail->len = strlen(tail->segment);
head.len += tail->len;
format = NULL;
break;
}
/* Otherwise, print the entire string up to this point. */
else {
/* Print this segment */
*this_end = '\0';
tail = tail->next = CHECKED_MALLOC_STRUCT(struct sprintf_output_list,
"SPRINTF output list segment");
if (tail == NULL)
goto failure;
memset(tail, 0, sizeof(*tail));
tail->segment = my_sprintf_segment(parse_state, format, &argp);
if (tail->segment == NULL)
goto failure;
tail->len = strlen(tail->segment);
head.len += tail->len;
*this_end = '%';
/* Advance to the next segment of the format string */
format = this_end;
this_start = strchr(format, '%');
while (this_start != NULL && this_start[1] == '%')
this_start = strchr(this_start + 2, '%');
}
}
/* Now, build the string! */
total_len = head.len + 1;
if (format != NULL)
total_len += strlen(format);
buffer = CHECKED_MALLOC_ARRAY(char, total_len, "SPRINTF data");
pos = buffer;
if (buffer == NULL)
goto failure;
while (head.next != NULL) {
struct sprintf_output_list *l = head.next;
memcpy(pos, l->segment, l->len);
pos += l->len;
free(l->segment);
head.next = l->next;
free(l);
}
if (format != NULL)
strcpy(pos, format);
else
*pos = '\0';
return buffer;
failure:
while (head.next != NULL) {
struct sprintf_output_list *l = head.next;
if (l->segment != NULL)
free(l->segment);
head.next = l->next;
free(l);
}
return NULL;
}
/*************************************************************************
my_fprintf:
fprintf-like formatting of MDL arguments.
In: parse_state: parser state
outfile: file stream to which to write
format: string to expand
argp: argument list
Out: 0 on success, 1 on failure
*************************************************************************/
static int my_fprintf(struct mdlparse_vars *parse_state, FILE *outfile,
char *format, struct arg *argp) {
char *str = my_sprintf(parse_state, format, argp);
if (str == NULL)
return 1;
if (fputs(str, outfile) < 0) {
free(str);
return 1;
}
free(str);
return 0;
}
/*************************************************************************
defang_format_string:
Remove any potentially dangerous characters from a format string so it can
be safely used in error reporting.
In: fmt: string to defang
Out: None. fmt string is updated
*************************************************************************/
static void defang_format_string(char *fmt) {
while (*fmt != '\0') {
if (iscntrl(*fmt))
*fmt = '.';
else if (!isascii(*fmt))
*fmt = '.';
++fmt;
}
}
/*************************************************************************
mdl_printf:
printf-like formatting of MDL arguments. Prints to the defined log_file.
In: parse_state: parser state
fmt: string to expand
arg_head: argument list
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_printf(struct mdlparse_vars *parse_state, char *fmt,
struct arg *arg_head) {
if (my_fprintf(parse_state, mcell_get_log_file(), fmt, arg_head)) {
mdl_free_printf_arg_list(arg_head);
defang_format_string(fmt);
mdlerror_fmt(parse_state, "Could not print to logfile: %s", fmt);
free(fmt);
return 1;
}
mdl_free_printf_arg_list(arg_head);
free(fmt);
return 0;
}
/*************************************************************************
mdl_fprintf:
fprintf-like formatting of MDL arguments.
In: parse_state: parser state
filep: file stream to receive output
fmt: string to expand
arg_head: argument list
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_fprintf(struct mdlparse_vars *parse_state, struct file_stream *filep,
char *fmt, struct arg *arg_head) {
if (my_fprintf(parse_state, filep->stream, fmt, arg_head)) {
mdl_free_printf_arg_list(arg_head);
free(fmt);
mdlerror_fmt(parse_state, "Could not print to file: %s", filep->name);
return 1;
}
mdl_free_printf_arg_list(arg_head);
free(fmt);
return 0;
}
/*************************************************************************
mdl_string_format:
Expression-friendly sprintf-like formatting of MDL arguments.
In: parse_state: parser state
fmt: string to expand
arg_head: argument list
Out: string on success, NULL on failure
*************************************************************************/
char *mdl_string_format(struct mdlparse_vars *parse_state, char *fmt,
struct arg *arg_head) {
char *str = my_sprintf(parse_state, fmt, arg_head);
if (str == NULL) {
mdl_free_printf_arg_list(arg_head);
free(fmt);
mdlerror_fmt(parse_state, "Could not format string\n");
return NULL;
}
free(fmt);
mdl_free_printf_arg_list(arg_head);
return str;
}
/*************************************************************************
mdl_sprintf:
sprintf-like formatting of MDL arguments.
In: parse_state: parser state
assign_var: variable to receive formatted string
fmt: string to expand
arg_head: argument list
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_sprintf(struct mdlparse_vars *parse_state, struct sym_entry *assign_var,
char *fmt, struct arg *arg_head) {
char *str = my_sprintf(parse_state, fmt, arg_head);
if (str == NULL) {
mdl_free_printf_arg_list(arg_head);
free(fmt);
mdlerror_fmt(parse_state, "Could not sprintf to variable: %s",
assign_var->name);
return 1;
}
free(fmt);
mdl_free_printf_arg_list(arg_head);
/* If the symbol had a value, try to free it */
if (assign_var->value && mdl_free_variable_value(parse_state, assign_var)) {
free(str);
return 1;
}
/* Store new value */
assign_var->sym_type = STR;
assign_var->value = str;
/* Log the updated value */
no_printf("\n%s is equal to: %s\n", assign_var->name, str);
return 0;
}
/*************************************************************************
mdl_fprint_time:
strtime-like formatting of current time.
In: parse_state: parser state
filep_sym: file stream to receive output
fmt: string to expand
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_fprint_time(struct mdlparse_vars *parse_state,
struct sym_entry *filep_sym, char *fmt) {
char time_str[128];
time_t the_time;
struct file_stream *filep = (struct file_stream *)filep_sym->value;
the_time = time(NULL);
strftime(time_str, 128, fmt, localtime(&the_time));
free(fmt);
if (fprintf(filep->stream, "%s", time_str) == EOF) {
mdlerror_fmt(parse_state, "Could not print to file: %s", filep_sym->name);
return 1;
}
return 0;
}
/*************************************************************************
mdl_print_time:
strtime-like formatting of current time. Prints to logfile.
In: parse_state: parser state
filep: file stream to receive output
fmt: string to expand
Out: 0 on success, 1 on failure
*************************************************************************/
void mdl_print_time(struct mdlparse_vars *parse_state, char *fmt) {
char time_str[128];
time_t the_time = time(NULL);
strftime(time_str, 128, fmt, localtime(&the_time));
free(fmt);
if (parse_state->vol->procnum == 0)
fprintf(mcell_get_log_file(), "%s", time_str);
}
/*************************************************************************
mdl_generate_range:
Generate a num_expr_list containing the numeric values from start to end,
incrementing by step.
In: parse_state: parser state
list: destination to receive list of values
start: start of range
end: end of range
step: increment
Out: 0 on success, 1 on failure. On success, list is filled in.
*************************************************************************/
int mdl_generate_range(struct mdlparse_vars *parse_state,
struct num_expr_list_head *list, double start,
double end, double step) {
if (step == 0.0) {
mdlerror(parse_state, "A step size of 0 was requested, which would "
"generate an infinite list.");
return 1;
}
/* Above a certain point, we probably don't want this. If we need arrays
* this large, we need to reengineer this. */
if (fabs((end - start) / step) > 100000000.) {
mdlerror(parse_state, "A range was requested that encompasses too many "
"values (maximum 100,000,000)");
return 1;
}
mcell_generate_range(list, start, end, step);
return 0;
}
/*************************************************************************
mdl_add_range_value:
Add a value to a numeric list.
In: lh: list to receive value
value: value for list
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_add_range_value(struct num_expr_list_head *lh, double value) {
if (lh->value_head == NULL)
return mcell_generate_range_singleton(lh, value);
struct num_expr_list *nel =
CHECKED_MALLOC_STRUCT(struct num_expr_list, "numeric array");
if (nel == NULL)
return 1;
nel->next = NULL;
nel->value = value;
lh->value_tail = lh->value_tail->next = nel;
++lh->value_count;
return 0;
}
#ifdef DEBUG
/*************************************************************************
mdl_debug_dump_array:
Display a human-readable representation of the array to stdout.
In: nel: the list to free
Out: displayed to stdout
*************************************************************************/
void mdl_debug_dump_array(struct num_expr_list *nel) {
struct num_expr_list *elp;
no_printf("\nArray expression: [");
for (elp = nel; elp != NULL; elp = elp->next) {
no_printf("%lf", elp->value);
if (elp->next != NULL)
no_printf(",");
}
no_printf("]\n");
}
#endif
/*************************************************************************
num_expr_list_to_array:
Convert a numeric list into an array. The list count will be stored into
the count pointer, if it is not NULL.
In: lh: list head
count: location to receive count of items in list
Out: an array of all doubles in the list, or NULL if allocation fails or if
the list is empty. If count is non-zero and NULL is returned, allocation
has failed.
*************************************************************************/
static double *num_expr_list_to_array(struct num_expr_list_head *lh,
int *count) {
double *arr = NULL, *ptr = NULL;
struct num_expr_list *i;
if (count != NULL)
*count = lh->value_count;
if (lh->value_count == 0)
return NULL;
arr = CHECKED_MALLOC_ARRAY(double, lh->value_count, "numeric array");
if (arr != NULL) {
for (i = (struct num_expr_list *)lh->value_head, ptr = arr; i != NULL;
i = i->next)
*ptr++ = i->value;
}
return arr;
}
/*************************************************************************
mdl_point:
Create a 3-D vector from a numeric array.
In: parse_state: parser state
vals: values to put into vector
Out: a 3-D vector, or NULL if an error occurs.
*************************************************************************/
struct vector3 *mdl_point(struct mdlparse_vars *parse_state,
struct num_expr_list_head *vals) {
if (vals->value_count != 3) {
mdlerror(parse_state, "Three dimensional value required");
return NULL;
}
struct vector3 *vec = CHECKED_MALLOC_STRUCT(struct vector3, "3-D vector");
if (!vec)
return NULL;
vec->x = vals->value_head->value;
vec->y = vals->value_head->next->value;
vec->z = vals->value_tail->value;
if (!vals->shared)
mcell_free_numeric_list(vals->value_head);
return vec;
}
/*************************************************************************
mdl_point_scalar:
Create a 3-D vector equal to s*[1, 1, 1] for some scalar s.
In: val: scalar
Out: a 3-D vector, or NULL if an error occurs.
*************************************************************************/
struct vector3 *mdl_point_scalar(double val) {
struct vector3 *vec = CHECKED_MALLOC_STRUCT(struct vector3, "3-D vector");
if (!vec)
return NULL;
vec->x = val;
vec->y = val;
vec->z = val;
return vec;
}
/**************************************************************************
mdl_free_variable_value:
Free the value in a given variable entry. Currently, arrays are not freed,
as they are also not copied when variable assignments occur. We would need
to either reference count arrays or directly copy them on assignment in
order to be able to free them.
In: parse_state: the parse variables structure
sym: the symbol whose value to free
Out: 0 on success, 1 if the symbol is not a double, string, or array
**************************************************************************/
static int mdl_free_variable_value(struct mdlparse_vars *parse_state,
struct sym_entry *sym) {
switch (sym->sym_type) {
case DBL:
case STR:
free(sym->value);
break;
case ARRAY:
/* XXX: For the moment, we can't free these since they might be shared by
* two different variables... */
break;
default:
mdlerror_fmt(
parse_state,
"Internal error: Attempt to free variable value of incorrect type: %s",
sym->name);
return 1;
}
return 0;
}
/**************************************************************************
mdl_get_or_create_variable:
Get a named variable if it exists, or create it if it doesn't. Caller is
no longer responsible for deallocation of 'name'.
In: parse_state: the parse variables structure
name: the name of the variable
Out: a symbol table entry, or NULL if we ran out of memory
**************************************************************************/
struct sym_entry *mdl_get_or_create_variable(struct mdlparse_vars *parse_state,
char *name) {
/* Attempt to fetch existing variable */
struct sym_entry *st = NULL;
if ((st = retrieve_sym(name, parse_state->vol->var_sym_table)) != NULL) {
free(name);
return st;
}
/* Create the variable */
if ((st = store_sym(name, TMP, parse_state->vol->var_sym_table, NULL)) ==
NULL)
mcell_allocfailed("Failed to store a variable symbol in the symbol table.");
free(name);
return st;
}
/**************************************************************************
mdl_assign_variable_double:
Assign a "double" value to a variable, freeing any previous value.
In: parse_state: the parse variables structure
sym: the symbol whose value to free
value: the value to assign
Out: 0 on success, 1 if the symbol is not a double, string, or array, or if
memory allocation fails
**************************************************************************/
int mdl_assign_variable_double(struct mdlparse_vars *parse_state,
struct sym_entry *sym, double value) {
/* If the symbol had a value, try to free it */
if (sym->value && mdl_free_variable_value(parse_state, sym))
return 1;
/* Allocate space for the new value */
if ((sym->value = CHECKED_MALLOC_STRUCT(double, "numeric variable")) == NULL)
return 1;
/* Update the value */
*(double *)sym->value = value;
sym->sym_type = DBL;
no_printf("\n%s is equal to: %f\n", sym->name, value);
return 0;
}
/**************************************************************************
mdl_assign_variable_string:
Assign a string value to a variable, freeing any previous value.
In: parse_state: the parse variables structure
sym: the symbol whose value to free
value: the value to assign
Out: 0 on success, 1 if the symbol is not a double, string, or array, or if
memory allocation fails.
**************************************************************************/
int mdl_assign_variable_string(struct mdlparse_vars *parse_state,
struct sym_entry *sym, char *value) {
/* If the symbol had a value, try to free it */
if (sym->value && mdl_free_variable_value(parse_state, sym))
return 1;
/* Allocate space for the new value */
if ((sym->value = mdl_strdup(value)) == NULL)
return 1;
free(value);
/* Update the value */
sym->sym_type = STR;
no_printf("\n%s is equal to: %s\n", sym->name, value);
return 0;
}
/**************************************************************************
mdl_assign_variable_array:
Assign an array value to a variable, freeing any previous value.
In: parse_state: the parse variables structure
sym: the symbol whose value to free
value: the value to assign
Out: 0 on success, 1 if the symbol is not a double, string, or array
**************************************************************************/
int mdl_assign_variable_array(struct mdlparse_vars *parse_state,
struct sym_entry *sym,
struct num_expr_list *value) {
/* If the symbol had a value, try to free it */
if (sym->value && mdl_free_variable_value(parse_state, sym))
return 1;
sym->sym_type = ARRAY;
sym->value = value;
#ifdef DEBUG
struct num_expr_list *elp = (struct num_expr_list *)sym->value;
no_printf("\n%s is equal to: [", sym->name);
while (elp != NULL) {
no_printf("%lf", elp->value);
elp = elp->next;
if (elp != NULL) {
no_printf(",");
}
}
no_printf("]\n");
#endif
return 0;
}
/**************************************************************************
mdl_assign_variable:
Assign one variable value to another variable, freeing any previous value.
In: parse_state: the parse variables structure
sym: the symbol whose value to free
value: the value to assign
Out: 0 on success, 1 if the symbol is not a double, string, or array
**************************************************************************/
int mdl_assign_variable(struct mdlparse_vars *parse_state,
struct sym_entry *sym, struct sym_entry *value) {
switch (value->sym_type) {
case DBL:
if (mdl_assign_variable_double(parse_state, sym, *(double *)value->value))
return 1;
break;
case STR:
if (mdl_assign_variable_string(parse_state, sym,
(char *)value->value))
return 1;
break;
case ARRAY:
if (mdl_assign_variable_array(parse_state, sym,
(struct num_expr_list *)value->value))
return 1;
break;
default:
UNHANDLED_CASE(value->sym_type);
}
return 0;
}
/*************************************************************************
mdl_set_all_notifications:
Set all notification levels to a particular value. Corresponds to
ALL_NOTIFICATIONS rule in grammar.
In: vol: the world
notify_value: level to which to set notifications
Out: notification levels are changed
*************************************************************************/
void mdl_set_all_notifications(struct volume *vol, byte notify_value) {
enum notify_level_t n = (enum notify_level_t)notify_value;
vol->notify->progress_report = n;
vol->notify->diffusion_constants = n;
vol->notify->reaction_probabilities = n;
vol->notify->time_varying_reactions = n;
vol->notify->partition_location = n;
vol->notify->box_triangulation = n;
if (vol->log_freq == ULONG_MAX)
vol->notify->iteration_report = n;
vol->notify->throughput_report = n;
vol->notify->checkpoint_report = n;
vol->notify->release_events = n;
vol->notify->file_writes = n;
vol->notify->final_summary = n;
vol->notify->molecule_collision_report = n;
}
/*************************************************************************
mdl_set_iteration_report_freq:
Set the iteration report frequency.
In: parse_state: parser state
interval: report frequency to request
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_iteration_report_freq(struct mdlparse_vars *parse_state,
long long interval) {
/* Only if not set on command line */
if (parse_state->vol->log_freq == ULONG_MAX) {
if (interval < 1) {
mdlerror(parse_state,
"Invalid iteration number reporting interval: use value >= 1");
return 1;
} else {
parse_state->vol->notify->custom_iteration_value = interval;
parse_state->vol->notify->iteration_report = NOTIFY_FULL;
}
}
return 0;
}
/*************************************************************************
mdl_set_all_warnings:
Set all warning levels to a particular value. Corresponds to
ALL_WARNINGS rule in grammar.
In: vol: the world
warning_value: level to which to set warnings
Out: warning levels are changed
*************************************************************************/
void mdl_set_all_warnings(struct volume *vol, byte warning_level) {
enum warn_level_t w = (enum warn_level_t)warning_level;
vol->notify->neg_diffusion = w;
vol->notify->neg_reaction = w;
vol->notify->high_reaction_prob = w;
vol->notify->close_partitions = w;
vol->notify->degenerate_polys = w;
vol->notify->overwritten_file = w;
vol->notify->mol_placement_failure = w;
if (w == WARN_ERROR)
w = WARN_WARN;
vol->notify->short_lifetime = w;
vol->notify->missed_reactions = w;
vol->notify->missed_surf_orient = w;
vol->notify->useless_vol_orient = w;
vol->notify->invalid_output_step_time = w;
vol->notify->large_molecular_displacement = w;
vol->notify->add_remove_mesh_warning = w;
}
/*************************************************************************
mdl_set_lifetime_warning_threshold:
Set the lifetime warning threshold.
In: parse_state: parser state
lifetime: threshold to set
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_lifetime_warning_threshold(struct mdlparse_vars *parse_state,
long long lifetime) {
if (lifetime < 0) {
mdlerror(
parse_state,
"Molecule lifetimes are measured in iterations and cannot be negative");
return 1;
}
parse_state->vol->notify->short_lifetime_value = lifetime;
return 0;
}
/*************************************************************************
mdl_set_missed_reaction_warning_threshold:
Set the missed reaction warning threshold.
In: parse_state: parser state
rxfrac: threshold to set
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_missed_reaction_warning_threshold(struct mdlparse_vars *parse_state,
double rxfrac) {
if (rxfrac < 0.0 || rxfrac > 1.0) {
mdlerror(
parse_state,
"Values for fraction of reactions missed should be between 0 and 1");
return 1;
}
parse_state->vol->notify->missed_reaction_value = rxfrac;
return 0;
}
/*************************************************************************
mdl_set_time_step:
Set the global timestep for the simulation.
In: parse_state: parser state
step: timestep to set
Out: 0 on success, 1 on failure; global timestep is updated
*************************************************************************/
int mdl_set_time_step(struct mdlparse_vars *parse_state, double step) {
int error_code = mcell_set_time_step(parse_state->vol, step);
if (error_code == 2) {
mdlerror_fmt(
parse_state,
"Time step of %.15g requested; time step must be a positive value",
step);
return 1;
} else if (error_code == 3) {
mdlerror_fmt(parse_state, "Time step of %.15g requested, but the time step "
"was already set to %.15g",
step, parse_state->vol->time_unit);
return 1;
}
no_printf("Time unit = %g\n", parse_state->vol->time_unit);
return 0;
}
/*************************************************************************
mdl_set_max_time_step:
Set the maximum timestep for the simulation.
In: parse_state: parser state
step: maximum timestep to set
Out: 0 on success, 1 on failure; on success, maximum timestep is updated
*************************************************************************/
int mdl_set_max_time_step(struct mdlparse_vars *parse_state, double step) {
if (step <= 0) {
mdlerror_fmt(parse_state, "Maximum time step of %.15g requested; maximum "
"time step must be a positive value",
step);
return 1;
}
if (distinguishable(parse_state->vol->time_step_max, 0, EPS_C)) {
mdlerror_fmt(parse_state, "Maximum time step of %.15g requested, but the "
"maximum time step was already set to %.15g",
step, parse_state->vol->time_step_max);
return 1;
}
parse_state->vol->time_step_max = step;
no_printf("Maximum time step = %g\n", parse_state->vol->time_step_max);
return 0;
}
/*************************************************************************
mdl_set_space_step:
Set the global space step for the simulation.
In: parse_state: parser state
step: global space step to set
Out: 0 on success, 1 on failure; on success, global space step is updated
*************************************************************************/
int mdl_set_space_step(struct mdlparse_vars *parse_state, double step) {
if (step <= 0) {
mdlerror_fmt(
parse_state,
"Space step of %.15g requested; space step must be a positive value",
step);
return 1;
}
if (distinguishable(parse_state->vol->space_step, 0, EPS_C)) {
mdlerror_fmt(parse_state, "Space step of %.15g requested, but the space "
"step was already set to %.15g",
step, parse_state->vol->space_step *
parse_state->vol->r_length_unit);
return 1;
}
parse_state->vol->space_step = step;
no_printf("Space step = %g\n", parse_state->vol->space_step);
/* Use internal units */
parse_state->vol->space_step *= parse_state->vol->r_length_unit;
return 0;
}
/*************************************************************************
mdl_set_num_iterations:
Set the number of iterations for the simulation.
In: parse_state: parser state
numiters: number of iterations to run
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_num_iterations(struct mdlparse_vars *parse_state,
long long numiters) {
/* If the iteration count was not overridden on the command-line... */
if (parse_state->vol->iterations == INT_MIN) {
parse_state->vol->iterations = numiters;
if (parse_state->vol->iterations < 0) {
mdlerror(parse_state, "ITERATIONS value is negative");
return 1;
}
}
no_printf("Iterations = %lld\n", parse_state->vol->iterations);
return 0;
}
/*************************************************************************
mdl_set_num_radial_directions:
Set the number of radial directions.
In: parse_state: parser state
numdirs: number of radial directions to use
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_num_radial_directions(struct mdlparse_vars *parse_state,
int numdirs) {
parse_state->vol->radial_directions = numdirs;
if (parse_state->vol->radial_directions <= 0) {
mdlerror(parse_state, "RADIAL_DIRECTIONS must be a positive number.");
return 1;
}
parse_state->vol->num_directions = 0;
if (parse_state->vol->d_step != NULL)
free(parse_state->vol->d_step);
if ((parse_state->vol->d_step =
init_d_step(parse_state->vol->radial_directions,
&parse_state->vol->num_directions)) == NULL) {
mcell_allocfailed("Failed to allocate the diffusion directions table.");
/*return 1;*/
}
/* Mask must contain at least every direction */
/* Num directions, rounded up to the nearest 2^n - 1 */
parse_state->vol->directions_mask = parse_state->vol->num_directions;
parse_state->vol->directions_mask |= (parse_state->vol->directions_mask >> 1);
parse_state->vol->directions_mask |= (parse_state->vol->directions_mask >> 2);
parse_state->vol->directions_mask |= (parse_state->vol->directions_mask >> 4);
parse_state->vol->directions_mask |= (parse_state->vol->directions_mask >> 8);
parse_state->vol->directions_mask |=
(parse_state->vol->directions_mask >> 16);
if (parse_state->vol->directions_mask > (1 << 18)) {
mdlerror(parse_state, "Too many RADIAL_DIRECTIONS requested (max 131072).");
return 1;
}
no_printf("desired radial directions = %d\n",
parse_state->vol->radial_directions);
no_printf("actual radial directions = %d\n",
parse_state->vol->num_directions);
return 0;
}
/*************************************************************************
mdl_set_num_radial_subdivisions:
Set the number of radial subdivisions.
In: parse_state: parser state
numdivs: number of radial subdivisions to use
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_num_radial_subdivisions(struct mdlparse_vars *parse_state,
int numdivs) {
parse_state->vol->radial_subdivisions = numdivs;
if (parse_state->vol->radial_subdivisions <= 0) {
mdlerror(parse_state, "RADIAL_SUBDIVISIONS must be a positive number.");
return 1;
}
/* 'x & (x-1)' clears the lowest-order bit of x. thus, only for 0 or a */
/* power of 2 will the expression be zero. we've eliminated the case of */
/* zero in the previous test. (this condition is required so that we */
/* use 'x & (RSD - 1)' as an optimized form of 'x % RSD'.) */
if ((parse_state->vol->radial_subdivisions &
(parse_state->vol->radial_subdivisions - 1)) != 0) {
mdlerror(parse_state, "Radial subdivisions must be a power of two");
return 1;
}
if (parse_state->vol->r_step != NULL)
free(parse_state->vol->r_step);
if (parse_state->vol->r_step_surface != NULL)
free(parse_state->vol->r_step_surface);
if (parse_state->vol->r_step_release != NULL)
free(parse_state->vol->r_step_release);
parse_state->vol->r_step = init_r_step(parse_state->vol->radial_subdivisions);
parse_state->vol->r_step_surface =
init_r_step_surface(parse_state->vol->radial_subdivisions);
parse_state->vol->r_step_release =
init_r_step_3d_release(parse_state->vol->radial_subdivisions);
if (parse_state->vol->r_step == NULL ||
parse_state->vol->r_step_surface == NULL ||
parse_state->vol->r_step_release == NULL) {
mcell_allocfailed(
"Failed to allocate the diffusion radial subdivisions table.");
/*return 1;*/
}
no_printf("radial subdivisions = %d\n",
parse_state->vol->radial_subdivisions);
return 0;
}
/*************************************************************************
mdl_set_interaction_radius:
Set the interaction radius.
In: parse_state: parser state
interaction_radius
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_interaction_radius(struct mdlparse_vars *parse_state,
double interaction_radius) {
parse_state->vol->rx_radius_3d = interaction_radius;
if (parse_state->vol->rx_radius_3d <= 0) {
mdlerror(parse_state, "INTERACTION_RADIUS must be a positive number.");
return 1;
}
no_printf("interaction radius = %f\n", parse_state->vol->rx_radius_3d);
return 0;
}
/*************************************************************************
mdl_set_grid_density:
Set the surface grid density.
In: parse_state: parser state
density: global surface grid density for simulation
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_grid_density(struct mdlparse_vars *parse_state, double density) {
if (density <= 0) {
mdlerror_fmt(parse_state, "EFFECTOR_GRID_DENSITY must be greater than 0.0 "
"(value provided was %lg)",
density);
return 1;
}
parse_state->vol->grid_density = density;
no_printf("Max density = %f\n", parse_state->vol->grid_density);
parse_state->vol->space_step *= parse_state->vol->length_unit;
parse_state->vol->r_length_unit = sqrt(parse_state->vol->grid_density);
parse_state->vol->length_unit = 1.0 / parse_state->vol->r_length_unit;
parse_state->vol->space_step *= parse_state->vol->r_length_unit;
no_printf("Length unit = %f\n", parse_state->vol->length_unit);
return 0;
}
/*************************************************************************
schedule_async_checkpoint:
Schedule an asynchronous checkpoint.
In: parse_state: parser state
dur: length of real (wall-clock) time until we should checkpoint
Out: 0 on success, 1 on failure; signal handler is installed and an alarm is
scheduled.
*************************************************************************/
static int schedule_async_checkpoint(struct mdlparse_vars *parse_state,
unsigned int dur) {
#ifdef _WIN64
set_alarm_handler(&chkpt_signal_handler);
#else
struct sigaction sa, saPrev;
sa.sa_sigaction = NULL;
sa.sa_handler = &chkpt_signal_handler;
sa.sa_flags = SA_RESTART;
sigfillset(&sa.sa_mask);
if (sigaction(SIGALRM, &sa, &saPrev) != 0) {
mdlerror(parse_state, "Failed to install ALRM signal handler");
return 1;
}
#endif
alarm(dur);
return 0;
}
/*************************************************************************
mdl_set_realtime_checkpoint:
Schedule an asynchronous checkpoint.
In: parse_state: parser state
duration: length of real (wall-clock) time until we should checkpoint
cont_after_cp: 1 if we should continue after checkpoint, 0 if we should
exit
Out: 0 on success, 1 on failure; signal handler is installed and an alarm is
scheduled.
*************************************************************************/
int mdl_set_realtime_checkpoint(struct mdlparse_vars *parse_state,
long duration, int cont_after_cp) {
time_t t;
time(&t);
if (duration <= 0) {
mdlerror_fmt(parse_state, "Realtime checkpoint requested at %ld seconds, "
"but the checkpoint interval must be positive.",
duration);
return 1;
} else if (parse_state->vol->checkpoint_alarm_time != 0) {
mdlerror_fmt(parse_state, "Realtime checkpoint requested at %ld seconds, "
"but a checkpoint is already scheduled for %u "
"seconds.",
duration, parse_state->vol->checkpoint_alarm_time);
return 1;
}
parse_state->vol->checkpoint_alarm_time = (unsigned int)duration;
parse_state->vol->continue_after_checkpoint = cont_after_cp;
parse_state->vol->chkpt_flag = 1;
if (t - parse_state->vol->begin_timestamp > 0) {
if (duration <= t - parse_state->vol->begin_timestamp) {
mdlerror_fmt(parse_state, "Checkpoint scheduled for %ld seconds, but %ld "
"seconds have already elapsed during parsing. "
"Exiting.",
duration, (long)(t - parse_state->vol->begin_timestamp));
return 1;
}
duration -= (t - parse_state->vol->begin_timestamp);
}
if (schedule_async_checkpoint(parse_state, (unsigned int)duration)) {
mdlerror_fmt(parse_state, "Failed to schedule checkpoint for %ld seconds",
duration);
return 1;
}
return 0;
}
/*************************************************************************
mdl_set_checkpoint_infile:
Set the input checkpoint file to use.
In: parse_state: parser state
name: name of checkpoint file
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_checkpoint_infile(struct mdlparse_vars *parse_state, char *name) {
FILE *file;
if (parse_state->vol->chkpt_infile == NULL) {
parse_state->vol->chkpt_infile = name;
if ((file = fopen(parse_state->vol->chkpt_infile, "r")) == NULL) {
parse_state->vol->chkpt_init = 1;
} else {
parse_state->vol->chkpt_init = 0;
fclose(file);
}
parse_state->vol->chkpt_flag = 1;
}
return 0;
}
/*************************************************************************
mdl_set_checkpoint_outfile:
Set the output checkpoint file to use.
In: parse_state: parser state
name: name of checkpoint file
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_checkpoint_outfile(struct mdlparse_vars *parse_state, char *name) {
if (parse_state->vol->chkpt_outfile == NULL) {
parse_state->vol->chkpt_outfile = name;
parse_state->vol->chkpt_flag = 1;
}
return 0;
}
/*************************************************************************
mdl_set_checkpoint_iterations:
Set the number of iterations between checkpoints.
In: parse_state: parser state
iters: number of iterations between checkpoints
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_set_checkpoint_interval(struct mdlparse_vars *parse_state,
long long iters, int continueAfterChkpt) {
parse_state->vol->chkpt_iterations = iters;
if (parse_state->vol->chkpt_iterations <= 0) {
mdlerror(parse_state, "CHECKPOINT_ITERATIONS must be a positive integer");
return 1;
}
parse_state->vol->chkpt_flag = 1;
parse_state->vol->continue_after_checkpoint = continueAfterChkpt;
return 0;
}
/*************************************************************************
mdl_keep_checkpoint_files:
Select if previous checkpoint files should be kept rather than be
overwritten each time a new checkpoint starts. This option only
affects checkpointed simulations run with the NOEXIT option.
In: parse_state: parser state
keepFiles: boolean variables selecting if intermediate checkpointing
files should be kept or not
Out: 0 on success, 1 on failure
*************************************************************************/
int mdl_keep_checkpoint_files(struct mdlparse_vars *parse_state,
int keepFiles) {
parse_state->vol->keep_chkpts = keepFiles;
return 0;
}
/*************************************************************************
mdl_make_new_object:
Create a new object, adding it to the global symbol table. the object must
not be defined yet.
In: parse_state: parser state
obj_name: fully qualified object name
Out: the newly created object
*************************************************************************/
static struct geom_object *mdl_make_new_object(struct mdlparse_vars *parse_state,
char *obj_name) {
int error_code = 0;
struct geom_object *obj_ptr = make_new_object(
parse_state->vol->dg_parse,
parse_state->vol->obj_sym_table,
obj_name,
&error_code);
return obj_ptr;
}
/*************************************************************************
mdl_start_object:
Create a new object, adding it to the global symbol table. the object must
not be defined yet. The qualified name of the object will be built by
adding to the object_name_list, and the object is made the "current_object"
in the mdl parser state. Because of these side effects, it is vital to
call mdl_finish_object at the end of the scope of the object created here.
In: parse_state: parser state
obj_name: unqualified object name
Out: the newly created object
*************************************************************************/
struct sym_entry *mdl_start_object(struct mdlparse_vars *parse_state,
char *name) {
// Create new fully qualified name.
char *new_name;
struct object_creation obj_creation;
obj_creation.object_name_list = parse_state->object_name_list;
obj_creation.object_name_list_end = parse_state->object_name_list_end;
if ((new_name = push_object_name(&obj_creation, name)) == NULL) {
mdlerror_fmt(parse_state, "Out of memory while creating object: %s", name);
free(name);
return NULL;
}
parse_state->object_name_list = obj_creation.object_name_list;
parse_state->object_name_list_end = obj_creation.object_name_list_end;
// Create the symbol, if it doesn't exist yet.
int error_code = 0;
struct geom_object *obj_ptr = make_new_object(
parse_state->vol->dg_parse,
parse_state->vol->obj_sym_table,
new_name,
&error_code);
if (error_code == 1) {
mdlerror_fmt(parse_state,"Object '%s' is already defined", new_name);
}
else if (error_code == 2) {
mdlerror_fmt(parse_state, "Out of memory while creating object: %s",
new_name);
}
struct sym_entry *sym_ptr = obj_ptr->sym;
obj_ptr->last_name = name;
no_printf("Creating new object: %s\n", new_name);
// Set parent object, make this object "current".
obj_ptr->parent = parse_state->current_object;
parse_state->current_object = obj_ptr;
return sym_ptr;
}
/*************************************************************************
mdl_finish_object:
"Finishes" a new object, undoing the state changes that occurred when the
object was "started". (This means popping the name off of the object name
stack, and resetting current_object to its value before this object was
defined.
In: parse_state: parser state
obj_name: unqualified object name
Out: the newly created object
*************************************************************************/
void mdl_finish_object(struct mdlparse_vars *parse_state) {
struct object_creation obj_creation;
obj_creation.object_name_list_end = parse_state->object_name_list_end;
pop_object_name(&obj_creation);
parse_state->object_name_list_end = obj_creation.object_name_list_end;
parse_state->current_object = parse_state->current_object->parent;
}
/*************************************************************************
object_list_singleton:
Adds the first element to an empty object list.
In: head: object list head
objp: object to add
Out: none
*************************************************************************/
void mdl_object_list_singleton(struct object_list *head, struct geom_object *objp) {
objp->next = NULL;
head->obj_tail = head->obj_head = objp;
}
/*************************************************************************
add_object_to_list:
Adds an element to an object list.
In: head: object list head
objp: object to add
Out: none
*************************************************************************/
void mdl_add_object_to_list(struct object_list *head, struct geom_object *objp) {
objp->next = NULL;
head->obj_tail = head->obj_tail->next = objp;
}
/*************************************************************************
SYMBOL_TYPE_DESCRIPTIONS:
Human-readable symbol type descriptions, indexed by symbol type (MOL, OBJ,
STR, etc.)
*************************************************************************/
static const char *SYMBOL_TYPE_DESCRIPTIONS[] = {
"reaction", "reaction pathway", "molecule", "object",
"release pattern", "region", "numeric variable", "string variable",
"array variable", "file stream", "placeholder value", "trigger",
};
/*************************************************************************
SYMBOL_TYPE_ARTICLES:
Indefinite articles to go with human-readable symbol type descriptions,
indexed by symbol type (MOL, OBJ, STR, etc.)
*************************************************************************/
static const char *SYMBOL_TYPE_ARTICLES[] = { "a", "a", "a", "an", "a", "a",
"a", "a", "an", "a", "a", "a", };
/*************************************************************************
mdl_symbol_type_name:
Get a human-readable description of a symbol type, given its numerical
code.
In: type: numeric type code
Out: the symbol type name
*************************************************************************/
static char const *mdl_symbol_type_name(enum symbol_type_t type) {
if (type <= 0 || type >= (int)COUNT_OF(SYMBOL_TYPE_DESCRIPTIONS)) {
mcell_internal_error("Invalid symbol type '%d'", type);
/*return "(unknown symbol type)";*/
}
return SYMBOL_TYPE_DESCRIPTIONS[type];
}
/*************************************************************************
mdl_symbol_type_name_article:
Get an indefinite article to precede the human-readable description of a
symbol type, given its numerical code.
In: type: numeric type code
Out: the article
*************************************************************************/
static char const *mdl_symbol_type_name_article(enum symbol_type_t type) {
if (type <= 0 || type >= (int)COUNT_OF(SYMBOL_TYPE_ARTICLES)) {
mcell_internal_error("Invalid symbol type '%d'", type);
/*return "an";*/
}
return SYMBOL_TYPE_ARTICLES[type];
}
/*************************************************************************
mdl_existing_symbol:
Find an existing symbol or print an error message. Also print an error
message if the symbol is not of the right type.
In: parse_state: parser state
name: name of symbol to find
tab: table to search
type: type of symbol to find
Out: returns the symbol, or NULL if none found
*************************************************************************/
static struct sym_entry *mdl_existing_symbol(struct mdlparse_vars *parse_state,
char *name,
struct sym_table_head *tab,
int type) {
struct sym_entry *symp = retrieve_sym(name, tab);
if (symp == NULL)
mdlerror_fmt(parse_state, "Undefined %s: %s", mdl_symbol_type_name((enum symbol_type_t)type),
name);
else if (symp->sym_type != type) {
mdlerror_fmt(
parse_state, "Invalid type for symbol %s: expected %s, but found %s",
name, mdl_symbol_type_name((enum symbol_type_t)type), mdl_symbol_type_name((enum symbol_type_t)symp->sym_type));
symp = NULL;
} else if (strcmp(symp->name, "GENERIC_MOLECULE") == 0) {
mdlerror_fmt(parse_state, "The keyword 'GENERIC_MOLECULE' is obsolete. "
"Please use instead 'ALL_VOLUME_MOLECULES', "
"'ALL_SURFACE_MOLECULES' or 'ALL_MOLECULES'.");
symp = NULL;
}
free(name);
return symp;
}
/*************************************************************************
mdl_existing_symbol_2types:
Find an existing symbol or print an error message.
In: parse_state: parser state
name: name of symbol to find
type1: 1st type of symbol to find
tab1: 1st table
type2: 2nd type of symbol to find
tab2: 2nd table
Out: returns the symbol, or NULL if none found
*************************************************************************/
static struct sym_entry *
mdl_existing_symbol_2types(struct mdlparse_vars *parse_state, char *name,
struct sym_table_head *tab1, int type1,
struct sym_table_head *tab2, int type2) {
struct sym_entry *symp;
symp = retrieve_sym(name, tab1);
if (symp == NULL) {
symp = retrieve_sym(name, tab2);
if (symp == NULL)
mdlerror_fmt(parse_state, "Undefined %s or %s: %s",
mdl_symbol_type_name((enum symbol_type_t)type1), mdl_symbol_type_name((enum symbol_type_t)type2),
name);
} else {
if (retrieve_sym(name, tab2) != NULL) {
mdlerror_fmt(parse_state, "Named object '%s' could refer to %s %s or %s "
"%s. Please rename one of them.",
name, mdl_symbol_type_name_article((enum symbol_type_t)type1),
mdl_symbol_type_name((enum symbol_type_t)type1),
mdl_symbol_type_name_article((enum symbol_type_t)type2),
mdl_symbol_type_name((enum symbol_type_t)type2));
symp = NULL;
}
}
free(name);
return symp;
}
/*************************************************************************
mdl_find_symbols_by_wildcard:
Find all symbols of a particular type matching a particular wildcard.
In: parse_state: parser state
wildcard: wildcard to match
tab: table to search for symbols
type: type of symbol to match
Out: linked list of matching symbols
*************************************************************************/
static struct sym_table_list *
mdl_find_symbols_by_wildcard(struct mdlparse_vars *parse_state,
char const *wildcard, struct sym_table_head *tab,
int type) {
struct sym_table_list *symbols = NULL, *stl;
for (int i = 0; i < tab->n_bins; i++) {
for (struct sym_entry *sym_t = tab->entries[i]; sym_t != NULL;
sym_t = sym_t->next) {
if (sym_t->sym_type != type)
continue;
if (is_wildcard_match((char *)wildcard, sym_t->name)) {
stl =
(struct sym_table_list *)CHECKED_MEM_GET(parse_state->sym_list_mem, "wildcard symbol list");
if (stl == NULL) {
if (symbols)
mem_put_list(parse_state->sym_list_mem, symbols);
return NULL;
}
stl->node = sym_t;
stl->next = symbols;
symbols = stl;
}
}
}
if (symbols == NULL) {
switch (type) {
case OBJ:
mdlerror_fmt(parse_state, "No objects found matching wildcard \"%s\"",
wildcard);
break;
case MOL:
mdlerror_fmt(parse_state, "No molecules found matching wildcard \"%s\"",
wildcard);
break;
default:
mdlerror_fmt(parse_state, "No items found matching wildcard \"%s\"",
wildcard);
break;
}
}
return symbols;
}
/*************************************************************************
compare_sym_names:
Comparator for symbol list sorting.
In: a: first symbol for comparison
b: second symbol for comparison
Out: 0 if a > b, 1 if a <= b
*************************************************************************/
static int compare_sym_names(void *a, void *b) {
return strcmp(((struct sym_entry *)a)->name, ((struct sym_entry *)b)->name) <=
0;
}
/*************************************************************************
sort_sym_list_by_name:
Sort a symbol list in collation order by name.
In: unsorted: unsorted list
Out: a sorted list of symbols
*************************************************************************/
static struct sym_table_list *
sort_sym_list_by_name(struct sym_table_list *unsorted) {
return (struct sym_table_list *)void_list_sort_by(
(struct void_list *)unsorted, compare_sym_names);
}
/*************************************************************************
mdl_existing_object:
Find an existing object. Print an error message if the object isn't found.
In: parse_state: parser state
name: fully qualified object name
Out: the object, or NULL if not found
*************************************************************************/
struct sym_entry *mdl_existing_object(struct mdlparse_vars *parse_state,
char *name) {
return mdl_existing_symbol(
parse_state, name, parse_state->vol->obj_sym_table, OBJ);
}
/*************************************************************************
mdl_existing_objects_wildcard:
Find a list of existing objects matching a particular wildcard.
In: parse_state: parser state
wildcard: fully qualified object name
Out: the meshes, or NULL if none were found or allocation failed
*************************************************************************/
struct sym_table_list *
mdl_existing_objects_wildcard(struct mdlparse_vars *parse_state,
char *wildcard) {
char *stripped = mdl_strip_quotes(wildcard);
return mdl_meshes_by_wildcard(parse_state, stripped);
}
/*************************************************************************
mdl_existing_region:
Find an existing region. Print an error message if it isn't found.
In: parse_state: parser state
obj_symp: object on which to find the region
name: region name
Out: the region, or NULL if not found
*************************************************************************/
struct sym_entry *mdl_existing_region(struct mdlparse_vars *parse_state,
struct sym_entry *obj_symp, char *name) {
char *region_name = CHECKED_SPRINTF("%s,%s", obj_symp->name, name);
if (region_name == NULL) {
free(name);
return NULL;
}
free(name);
return mdl_existing_symbol(
parse_state, region_name, parse_state->vol->reg_sym_table, REG);
}
/*************************************************************************
mdl_existing_molecule:
Find an existing molecule species. Print an error message if it isn't
found.
In: parse_state: parser state
name: species name
Out: the symbol, or NULL if not found
*************************************************************************/
struct sym_entry *mdl_existing_molecule(struct mdlparse_vars *parse_state,
char *name) {
return mdl_existing_symbol(parse_state, name, parse_state->vol->mol_sym_table,
MOL);
}
/**************************************************************************
mdl_singleton_symbol_list:
Turn a single symbol into a singleton symbol list.
In: parse_state: parser state
sym: the symbol
Out: the symbol list, or NULL
**************************************************************************/
struct sym_table_list *
mdl_singleton_symbol_list(struct mdlparse_vars *parse_state,
struct sym_entry *sym) {
struct sym_table_list *stl =
(struct sym_table_list *)CHECKED_MEM_GET(parse_state->sym_list_mem, "symbol list item");
if (stl != NULL) {
stl->next = NULL;
stl->node = sym;
}
return stl;
}
/*************************************************************************
mdl_existing_molecule_list:
Find an existing molecule species, and return it in a singleton list.
Print an error message if it isn't found.
In: parse_state: parser state
name: species name
Out: a list containing only the symbol, or NULL if not found or allocation
failed
*************************************************************************/
struct sym_table_list *
mdl_existing_molecule_list(struct mdlparse_vars *parse_state, char *name) {
struct sym_entry *symp = mdl_existing_molecule(parse_state, name);
if (symp == NULL)
return NULL;
return mdl_singleton_symbol_list(parse_state, symp);
}
/*************************************************************************
mdl_existing_molecules_wildcard:
Find a list of all molecule species matching the specified wildcard. Print
an error message if it doesn't match any.
In: parse_state: parser state
wildcard: species wildcard (will be freed by this function)
Out: a list containing the symbols, or NULL if an error occurred
*************************************************************************/
struct sym_table_list *
mdl_existing_molecules_wildcard(struct mdlparse_vars *parse_state,
char *wildcard) {
struct sym_table_list *stl;
char *wildcard_string;
if (!(wildcard_string = mdl_strip_quotes(wildcard)))
return NULL;
stl = mdl_find_symbols_by_wildcard(parse_state, wildcard_string,
parse_state->vol->mol_sym_table, MOL);
if (stl == NULL) {
free(wildcard_string);
return NULL;
}
free(wildcard_string);
return sort_sym_list_by_name(stl);
}
/*************************************************************************
mdl_existing_surface_molecule:
Find an existing surface molecule species. Print an error message if it
isn't found, or isn't a surface molecule.
In: parse_state: parser state
name: species name
Out: the symbol, or NULL if not found
*************************************************************************/
struct sym_entry *
mdl_existing_surface_molecule(struct mdlparse_vars *parse_state, char *name) {
struct sym_entry *symp = mdl_existing_molecule(parse_state, name);
if (symp == NULL)
return NULL;
struct species *sp = (struct species *)symp->value;
if (!(sp->flags & ON_GRID)) {
mdlerror_fmt(parse_state, "Molecule '%s' is not a surface molecule",
symp->name);
return NULL;
}
return symp;
}
/*************************************************************************
mdl_existing_surface_class:
Find an existing surface class species. Print an error message if it isn't
found, or isn't a surface class.
In: parse_state: parser state
name: species name
Out: the symbol, or NULL if not found
*************************************************************************/
struct sym_entry *mdl_existing_surface_class(struct mdlparse_vars *parse_state,
char *name) {
struct sym_entry *symp = mdl_existing_molecule(parse_state, name);
if (symp == NULL)
return NULL;
struct species *sp = (struct species *)symp->value;
if (!(sp->flags & IS_SURFACE)) {
mdlerror_fmt(parse_state, "Species '%s' is not a surface class",
sp->sym->name);
return NULL;
}
return symp;
}
/**************************************************************************
mdl_existing_variable:
Find a named variable if it exists, or print an error if it does not.
In: parse_state: parser state
name: the name of the variable
Out: a symbol table entry, or NULL if we couldn't find the variable
**************************************************************************/
struct sym_entry *mdl_existing_variable(struct mdlparse_vars *parse_state,
char *name) {
struct sym_entry *st = NULL;
/* Attempt to fetch existing variable */
if ((st = retrieve_sym(name, parse_state->vol->var_sym_table)) != NULL) {
free(name);
return st;
}
mdlerror_fmt(parse_state, "Undefined variable: %s", name);
free(name);
return NULL;
}
/*************************************************************************
mdl_existing_array:
Find an existing array symbol. Print an error message if it isn't found.
In: parse_state: parser state
name: symbol name
Out: the symbol, or NULL if not found
*************************************************************************/
struct sym_entry *mdl_existing_array(struct mdlparse_vars *parse_state,
char *name) {
return mdl_existing_symbol(parse_state, name, parse_state->vol->var_sym_table,
ARRAY);
}
/**************************************************************************
mdl_existing_double:
Find a named numeric variable if it exists. Print an error message if it
isn't found.
In: parse_state: the parse variables structure
name: the name of the variable
Out: a symbol table entry, or NULL if we couldn't find the variable
**************************************************************************/
struct sym_entry *mdl_existing_double(struct mdlparse_vars *parse_state,
char *name) {
return mdl_existing_symbol(parse_state, name, parse_state->vol->var_sym_table,
DBL);
}
/**************************************************************************
mdl_existing_string:
Find a named string variable if it exists. Print an error message if it
isn't found.
In: parse_state: the parse variables structure
name: the name of the variable
Out: a symbol table entry, or NULL if we couldn't find the variable
**************************************************************************/
struct sym_entry *mdl_existing_string(struct mdlparse_vars *parse_state,
char *name) {
return mdl_existing_symbol(parse_state, name, parse_state->vol->var_sym_table,
STR);
}
/**************************************************************************
mdl_existing_num_or_array:
Find a named numeric or array variable if it exists. Print an error message
if it isn't found.
In: parse_state: the parse variables structure
name: the name of the variable
Out: a symbol table entry, or NULL if we couldn't find the variable
**************************************************************************/
struct sym_entry *mdl_existing_num_or_array(struct mdlparse_vars *parse_state,
char *name) {
struct sym_entry *st = NULL;
/* Attempt to fetch existing variable */
if ((st = retrieve_sym(name, parse_state->vol->var_sym_table)) != NULL) {
if (st->sym_type == STR) {
mdlerror_fmt(parse_state,
"Incorrect type (got string, expected number or array): %s",
name);
return NULL;
}
return st;
}
mdlerror_fmt(parse_state, "Undefined variable: %s", name);
return NULL;
}
/*************************************************************************
mdl_existing_rxn_pathname_or_molecule:
Find an existing named reaction pathway or molecule. Print an error
message if it isn't found.
In: parse_state: parser state
name: symbol name
Out: the symbol, or NULL if not found
*************************************************************************/
struct sym_entry *
mdl_existing_rxn_pathname_or_molecule(struct mdlparse_vars *parse_state,
char *name) {
return mdl_existing_symbol_2types(parse_state, name,
parse_state->vol->rxpn_sym_table, RXPN,
parse_state->vol->mol_sym_table, MOL);
}
/*************************************************************************
mdl_existing_release_pattern_or_rxn_pathname:
Find an existing reaction pathway or release pattern. Print an error
message if it isn't found, or if the name could refer to either a release
pattern or a reaction pathway.
In: parse_state: parser state
name: symbol name
Out: the symbol, or NULL if not found
*************************************************************************/
struct sym_entry *
mdl_existing_release_pattern_or_rxn_pathname(struct mdlparse_vars *parse_state,
char *name) {
return mdl_existing_symbol_2types(parse_state, name,
parse_state->vol->rpat_sym_table, RPAT,
parse_state->vol->rxpn_sym_table, RXPN);
}
/*************************************************************************
mdl_existing_file_stream:
Find an existing file stream. Print an error message if the stream isn't
found.
In: parse_state: parser state
name: stream name
Out: the stream, or NULL if not found
*************************************************************************/
struct sym_entry *mdl_existing_file_stream(struct mdlparse_vars *parse_state,
char *name) {
struct sym_entry *sym = mdl_existing_symbol(
parse_state, name, parse_state->vol->fstream_sym_table, FSTRM);
if (sym == NULL)
return sym;
struct file_stream *filep = (struct file_stream *)sym->value;
if (filep->stream == NULL) {
mdlerror_fmt(parse_state, "File stream '%s' has already been closed",
sym->name);
return NULL;
}
return sym;
}
/*************************************************************************
mdl_meshes_by_wildcard:
Find all mesh objects (polygons and boxes) that match a given wildcard.
XXX: Should we include meta-objects in this list?
In: parse_state: parser state
wildcard: the wildcard to match
Out: a list of all matching symbols
*************************************************************************/
struct sym_table_list *mdl_meshes_by_wildcard(struct mdlparse_vars *parse_state,
char *wildcard) {
/* Scan for objects matching the wildcard */
struct sym_table_list *matches = mdl_find_symbols_by_wildcard(
parse_state, wildcard, parse_state->vol->obj_sym_table, OBJ);
if (matches == NULL) {
free(wildcard);
return NULL;
}
/* Scan through the list, discarding inappropriate objects */
struct sym_table_list *cur_match, *next_match, **prev = &matches;
for (cur_match = matches; cur_match != NULL; cur_match = next_match) {
next_match = cur_match->next;
struct geom_object *objp = (struct geom_object *)cur_match->node->value;
if (objp->object_type != POLY_OBJ && objp->object_type != BOX_OBJ) {
*prev = cur_match->next;
mem_put(parse_state->sym_list_mem, cur_match);
} else
prev = &cur_match->next;
}
if (matches == NULL) {
mdlerror_fmt(parse_state,
"No matches for the wildcard '%s' were mesh objects",
wildcard);
free(wildcard);
return NULL;
}
free(wildcard);
return sort_sym_list_by_name(matches);
}
/*************************************************************************
mdl_transform_rotate:
Apply a rotation to the given transformation matrix.
In: parse_state: parser state
mat: transformation matrix
axis: axis of rotation
angle: angle of rotation (degrees!)
Out: 0 on success, 1 on failure; rotation is right-multiplied into the
transformation matrix
*************************************************************************/
int mdl_transform_rotate(struct mdlparse_vars *parse_state, double (*mat)[4],
struct vector3 *axis, double angle) {
if (transform_rotate(mat, axis, angle)) {
mdlerror(parse_state, "Rotation vector has zero length.");
return 1;
}
free(axis);
return 0;
}
/*************************************************************************
mdl_make_new_region:
Create a new region, adding it to the global symbol table. The region must
not be defined yet. The region is not added to the object's list of
regions.
full region names of REG type symbols stored in main symbol table have the
form:
metaobj.metaobj.poly,region_last_name
In: parse_state: parse vars for error reporting
obj_name: fully qualified object name
region_last_name: name of the region to define
Out: The newly created region
*************************************************************************/
static struct region *mdl_make_new_region(struct mdlparse_vars *parse_state,
char *obj_name,
const char *region_last_name) {
char *region_name;
region_name = CHECKED_SPRINTF("%s,%s", obj_name, region_last_name);
if (region_name == NULL)
return NULL;
struct sym_entry *gp;
if ((gp = retrieve_sym(region_name, parse_state->vol->reg_sym_table)) != NULL) {
if (gp->count == 0) {
gp->count = 1;
free(region_name);
return (struct region *)gp->value;
}
else {
mdlerror_fmt(parse_state, "Region already defined: %s", region_name);
}
}
if ((gp = store_sym(region_name, REG, parse_state->vol->reg_sym_table,
NULL)) == NULL) {
free(region_name);
mcell_allocfailed("Failed to store a region in the region symbol table.");
}
free(region_name);
return (struct region *)gp->value;
}
/*************************************************************************
mdl_copy_object_regions:
Duplicate src_obj's regions on dst_obj.
In: parse_state: parser state
dst_obj: destination object
src_obj: object from which to copy
Out: 0 on success, 1 on failure
*************************************************************************/
static int mdl_copy_object_regions(struct mdlparse_vars *parse_state,
struct geom_object *dst_obj,
struct geom_object *src_obj) {
struct region_list *src_rlp;
struct region *dst_reg, *src_reg;
struct sm_dat *dst_sm, *src_sm;
/* Copy each region */
for (src_rlp = src_obj->regions; src_rlp != NULL; src_rlp = src_rlp->next) {
src_reg = src_rlp->reg;
if ((dst_reg = mdl_create_region(parse_state, dst_obj,
src_reg->region_last_name)) == NULL)
return 1;
/* Copy over simple region attributes */
dst_reg->surf_class = src_reg->surf_class;
dst_reg->flags = src_reg->flags;
dst_reg->area = src_reg->area;
dst_reg->bbox = src_reg->bbox;
dst_reg->manifold_flag = src_reg->manifold_flag;
/* Copy membership data */
if (src_reg->membership != NULL) {
dst_reg->membership = duplicate_bit_array(src_reg->membership);
if (dst_reg->membership == NULL) {
mcell_allocfailed("Failed allocation for membership array in %s",
dst_obj->sym->name);
/*return 1;*/
}
} else
mdl_warning(parse_state, "No membership data for %s\n",
src_reg->sym->name);
/* Copy surface molecule data list */
struct sm_dat *smdp_tail = NULL;
for (src_sm = src_reg->sm_dat_head; src_sm != NULL; src_sm = src_sm->next) {
dst_sm = CHECKED_MALLOC_STRUCT(struct sm_dat, "surface molecule info");
if (dst_sm == NULL)
return 1;
if (smdp_tail != NULL)
smdp_tail->next = dst_sm;
else
dst_reg->sm_dat_head = dst_sm;
smdp_tail = dst_sm;
dst_sm->sm = src_sm->sm;
dst_sm->quantity_type = src_sm->quantity_type;
dst_sm->quantity = src_sm->quantity;
dst_sm->orientation = src_sm->orientation;
dst_sm->next = NULL;
}
}
return 0;
}
/*************************************************************************
find_corresponding_region:
When an object is instantiated or included in another object, we may need
to fix up region references for region releases. This function performs
this fixup.
In: old_r: a region
old_ob: the object that referred to that region
new_ob: a new object that should refer to its corresponding region
instance: the root object that begins the instance tree
symhash: the main symbol hash table for the world
Out: a pointer to the region that has the same relationship to the new object
as the given region has to the old object, or NULL if there is no
corresponding region.
Note: correspondence is computed by name mangling; if an object A.B.C refers
to region A.B.D,R and we have a new object E.F.G.H, then the
corresponding region is considered to be E.F.G.D,R (i.e. go back one to
find common ancestor, then go forward into the thing labeled "D,R").
*************************************************************************/
static struct region *
find_corresponding_region(struct region *old_r, struct geom_object *old_ob,
struct geom_object *new_ob, struct geom_object *instance,
struct sym_table_head *symhash) {
struct geom_object *ancestor;
struct geom_object *ob;
struct sym_entry *gp;
ancestor = common_ancestor(old_ob, old_r->parent);
if (ancestor == NULL) {
for (ob = old_r->parent; ob != NULL; ob = ob->parent) {
if (ob == instance)
break;
}
if (ob == NULL)
return NULL;
else
return old_r; /* Point to same already-instanced object */
} else {
/* Length of old prefix and name */
const size_t old_prefix_idx = strlen(ancestor->sym->name);
const size_t old_name_len = strlen(old_ob->sym->name);
/* Suffix is everything in the old name after the old prefix. */
const size_t suffix_len = old_name_len - old_prefix_idx;
/* New prefix length is new name, less suffix length. */
const size_t new_name_len = strlen(new_ob->sym->name);
/* If we get here, we must have a common ancestor, so this had better work.
*/
assert(new_name_len > suffix_len);
const size_t new_prefix_idx = new_name_len - suffix_len;
/* Length of the "region" spec from the old region name is the length of
* the region symbol, less the length of the old object symbol. */
const size_t region_name_len = strlen(old_r->sym->name);
assert(region_name_len > old_prefix_idx);
const size_t just_region_name_len = region_name_len - old_prefix_idx;
/* Buffer size needed for new name is new object name length + region name
* length + 1 (for NUL-termination). */
const size_t max_name_len = new_name_len + just_region_name_len + 1;
/* Build new name. */
char* new_name = new char[max_name_len];
strncpy(new_name, new_ob->sym->name, new_prefix_idx);
strncpy(new_name + new_prefix_idx, /* new prefix */
old_r->sym->name + old_prefix_idx, /* old suffix + region name */
max_name_len - new_prefix_idx);
/* Finally, retrieve symbol from newly-constructed name. */
gp = retrieve_sym(new_name, symhash);
delete new_name;
if (gp == NULL)
return NULL;
else
return (struct region *)gp->value;
}
}
/*************************************************************************
duplicate_rel_region_expr:
Create a deep copy of a region release expression.
In: parse_state: parser state
expr: a region expression tree
old_self: the object containing that tree
new_self: a new object for which we want to build a corresponding tree
instance: the root object that begins the instance tree
Out: the newly constructed expression tree for the new object, or
NULL if no such tree can be built
*************************************************************************/
static struct release_evaluator *duplicate_rel_region_expr(
struct mdlparse_vars *parse_state, struct release_evaluator *expr,
struct geom_object *old_self, struct geom_object *new_self, struct geom_object *instance) {
struct release_evaluator *nexp = CHECKED_MALLOC_STRUCT(
struct release_evaluator, "region release expression");
if (nexp == NULL)
return NULL;
nexp->op = expr->op;
struct region *r;
if (expr->left != NULL) {
if (expr->op & REXP_LEFT_REGION) {
r = find_corresponding_region((struct region *)expr->left, old_self, new_self, instance,
parse_state->vol->reg_sym_table);
if (r == NULL) {
mdlerror_fmt(
parse_state,
"Can't find new region corresponding to %s for %s (copy of %s)",
((struct region *)expr->left)->sym->name, new_self->sym->name,
old_self->sym->name);
free(nexp);
return NULL;
}
nexp->left = r;
} else
nexp->left = duplicate_rel_region_expr(parse_state, (struct release_evaluator *)expr->left, old_self,
new_self, instance);
} else
nexp->left = NULL;
if (expr->right != NULL) {
if (expr->op & REXP_RIGHT_REGION) {
r = find_corresponding_region((struct region *)expr->right, old_self, new_self, instance,
parse_state->vol->reg_sym_table);
if (r == NULL) {
mdlerror_fmt(
parse_state,
"Can't find new region corresponding to %s for %s (copy of %s)",
((struct region *)expr->right)->sym->name, new_self->sym->name,
old_self->sym->name);
free(nexp);
return NULL;
}
nexp->right = r;
} else
nexp->right = duplicate_rel_region_expr(parse_state, (struct release_evaluator *)expr->right,
old_self, new_self, instance);
} else
nexp->right = NULL;
return nexp;
}
/*************************************************************************
duplicate_release_site:
Create a deep copy of a release-site.
In: parse_state: parser state
old: an existing release site object
new_self: the object that is to contain a duplicate release site object
instance: the root object that begins the instance tree
Out: a duplicated release site object, or NULL if the release site cannot be
duplicated.
N.B.: In order to give a proper report, we always need to duplicate the
release site, since the copy of the release site needs to have a
different name. Otherwise, the user will see confusing reports of
several releases from the same release site.
*************************************************************************/
static struct release_site_obj *
duplicate_release_site(struct mdlparse_vars *parse_state,
struct release_site_obj *old, struct geom_object *new_self,
struct geom_object *instance) {
struct release_site_obj *rel_site_obj =
CHECKED_MALLOC_STRUCT(struct release_site_obj, "release site");
if (rel_site_obj == NULL) {
return NULL;
}
if (old->location != NULL) {
if ((rel_site_obj->location = CHECKED_MALLOC_STRUCT(
struct vector3, "release site location")) == NULL) {
free(rel_site_obj);
return NULL;
}
*(rel_site_obj->location) = *(old->location);
} else {
rel_site_obj->location = NULL;
}
rel_site_obj->mol_type = old->mol_type;
rel_site_obj->release_number_method = old->release_number_method;
rel_site_obj->release_shape = old->release_shape;
rel_site_obj->orientation = old->orientation;
rel_site_obj->release_number = old->release_number;
rel_site_obj->mean_diameter = old->mean_diameter;
rel_site_obj->concentration = old->concentration;
rel_site_obj->standard_deviation = old->standard_deviation;
rel_site_obj->diameter = old->diameter;
rel_site_obj->release_prob = old->release_prob;
rel_site_obj->pattern = old->pattern;
rel_site_obj->graph_pattern = old->graph_pattern;
rel_site_obj->mol_list = old->mol_list;
rel_site_obj->periodic_box = old->periodic_box;
rel_site_obj->name = NULL;
if (old->region_data != NULL) {
struct release_region_data *rel_reg_data = CHECKED_MALLOC_STRUCT(
struct release_region_data, "release region data");
if (rel_reg_data == NULL) {
free(rel_site_obj);
return NULL;
}
memcpy(&(rel_reg_data->llf), &(old->region_data->llf),
sizeof(struct vector3));
memcpy(&(rel_reg_data->urb), &(old->region_data->urb),
sizeof(struct vector3));
rel_reg_data->n_walls_included = -1;
rel_reg_data->cum_area_list = NULL;
rel_reg_data->wall_index = NULL;
rel_reg_data->obj_index = NULL;
rel_reg_data->n_objects = -1;
rel_reg_data->owners = NULL;
rel_reg_data->in_release = NULL;
rel_reg_data->self = new_self;
rel_reg_data->expression =
duplicate_rel_region_expr(parse_state, old->region_data->expression,
old->region_data->self, new_self, instance);
if (rel_reg_data->expression == NULL) {
free(rel_site_obj);
free(rel_reg_data);
return NULL;
}
rel_site_obj->region_data = rel_reg_data;
} else {
rel_site_obj->region_data = NULL;
}
return rel_site_obj;
}
/*************************************************************************
mdl_deep_copy_object:
Deep copy an object. The destination object should already be added to the
symbol table, but should be otherwise unpopulated, as no effort is made to
free any existing data contained in the object.
In: parse_state: parse vars for error reporting
dst_obj: object into which to copy
src_obj: object from which to copy
Out: The newly created region
*************************************************************************/
int mdl_deep_copy_object(struct mdlparse_vars *parse_state,
struct geom_object *dst_obj, struct geom_object *src_obj) {
/* Copy over simple object attributes */
dst_obj->object_type = src_obj->object_type;
dst_obj->n_walls = src_obj->n_walls;
dst_obj->n_walls_actual = src_obj->n_walls_actual;
dst_obj->walls = src_obj->walls;
dst_obj->wall_p = src_obj->wall_p;
dst_obj->n_verts = src_obj->n_verts;
dst_obj->vertices = src_obj->vertices;
/* Copy over regions */
if (mdl_copy_object_regions(parse_state, dst_obj, src_obj))
return 1;
/* Inherit object coordinate transformations */
mult_matrix(dst_obj->t_matrix, src_obj->t_matrix, dst_obj->t_matrix, 4, 4, 4);
switch (dst_obj->object_type) {
case META_OBJ:
/* Copy children */
for (struct geom_object *src_child = src_obj->first_child; src_child != NULL;
src_child = src_child->next) {
struct geom_object *dst_child;
char *child_obj_name =
CHECKED_SPRINTF("%s.%s", dst_obj->sym->name, src_child->last_name);
if (child_obj_name == NULL)
return 1;
/* Create child object */
if ((dst_child = mdl_make_new_object(parse_state, child_obj_name)) ==
NULL) {
free(child_obj_name);
return 1;
}
free(child_obj_name);
/* Copy in last name */
dst_child->last_name = mdl_strdup(src_child->last_name);
if (dst_child->last_name == NULL)
return 1;
/* Recursively copy object and its children */
if (mdl_deep_copy_object(parse_state, dst_child, src_child))
return 1;
dst_child->parent = dst_obj;
dst_child->next = NULL;
add_child_objects(dst_obj, dst_child, dst_child);
}
break;
case REL_SITE_OBJ: {
dst_obj->contents =
duplicate_release_site(parse_state, (struct release_site_obj *)src_obj->contents, dst_obj,
parse_state->vol->root_instance);
if (dst_obj->contents == NULL)
return 1;
struct release_site_obj *rso = (struct release_site_obj *)dst_obj->contents;
rso->name = mdl_strdup(dst_obj->sym->name);
if (rso->name == NULL)
return 1;
}
break;
case BOX_OBJ:
case POLY_OBJ: {
if (parse_state->vol->disable_polygon_objects) {
mdlerror(
parse_state,
"When using dynamic geometries, polygon objects should only be "
"defined/instantiated through the dynamic geometry file.");
}
dst_obj->contents = src_obj->contents;
struct polygon_object *poly_obj = \
(struct polygon_object *)src_obj->contents;
// Effectively, this tracks the instances of this object, which we need for
// cleaning up after dynamic geometry events.
poly_obj->references++;
dst_obj->periodic_x = src_obj->periodic_x;
dst_obj->periodic_y = src_obj->periodic_y;
dst_obj->periodic_z = src_obj->periodic_z;
}
break;
case VOXEL_OBJ:
default:
mdlerror_fmt(parse_state, "Error: bad object type %d",
dst_obj->object_type);
return 1;
}
return 0;
}
/*************************************************************************
* Cuboid processing
************************************************************************/
/*************************************************************************
init_cuboid:
In: parse_state: parser state
p1: llf corner of a cube
p2: urb corner of a cube
Out: returns a subdivided_box struct, with no subdivisions and corners as
specified. NULL is returned if there is no memory or the urb corner is
not up from, to the right of, and behind the llf corner
*************************************************************************/
static struct subdivided_box *init_cuboid(struct mdlparse_vars *parse_state,
struct vector3 *p1,
struct vector3 *p2) {
if (p2->x - p1->x < EPS_C || p2->y - p1->y < EPS_C || p2->z - p1->z < EPS_C) {
mdlerror(parse_state, "Box vertices out of order or box is degenerate.");
return NULL;
}
struct subdivided_box *b = CHECKED_MALLOC_STRUCT(
struct subdivided_box, "subdivided box");
if (b == NULL)
return NULL;
b->nx = b->ny = b->nz = 2;
if ((b->x = CHECKED_MALLOC_ARRAY(
double, b->nx, "subdivided box X partitions")) == NULL) {
free(b);
return NULL;
}
if ((b->y = CHECKED_MALLOC_ARRAY(
double, b->ny, "subdivided box Y partitions")) == NULL) {
free(b);
return NULL;
}
if ((b->z = CHECKED_MALLOC_ARRAY(
double, b->nz, "subdivided box Z partitions")) == NULL) {
free(b);
return NULL;
}
b->x[0] = p1->x;
b->x[1] = p2->x;
b->y[0] = p1->y;
b->y[1] = p2->y;
b->z[0] = p1->z;
b->z[1] = p2->z;
return b;
}
/*************************************************************************
refine_cuboid:
In: parse_state: parser state
p1: 3D vector that is one corner of the patch
p2: 3D vector that is the other corner of the patch
b: a subdivided box upon which the patch will be placed
egd: the surface molecule grid density, which limits how fine divisions
can be
Out: returns 1 on failure, 0 on success. The box has additional subdivisions
added that fall at the edges of the patch so that the patch can be
specified in terms of subdivisions (i.e. can be constructed by triangles
that tile each piece of the subdivided surface).
*************************************************************************/
static int refine_cuboid(struct mdlparse_vars *parse_state, struct vector3 *p1,
struct vector3 *p2, struct subdivided_box *b,
double egd) {
int j, k;
double *new_list;
int new_n;
int i = check_patch(b, p1, p2, egd);
if (i == 0) {
mdlerror(parse_state,
"Could not refine box to include patch: Invalid patch specified");
return 1;
}
if (i & BRANCH_X) {
new_n = b->nx + 2;
for (j = 0; j < b->nx; j++) {
if (!distinguishable(p1->x, b->x[j], EPS_C))
new_n--;
if (!distinguishable(p2->x, b->x[j], EPS_C))
new_n--;
}
if (new_n > b->nx) {
new_list = CHECKED_MALLOC_ARRAY(double, new_n,
"refined subdivided box X partitions");
if (new_list == NULL)
return 1;
for (j = k = 0; b->x[j] < p1->x; j++)
new_list[k++] = b->x[j];
if (distinguishable(b->x[j], p1->x, EPS_C))
new_list[k++] = p1->x;
for (; b->x[j] < p2->x; j++)
new_list[k++] = b->x[j];
if ((distinguishable(p1->x, p2->x, EPS_C)) &&
(distinguishable(b->x[j], p2->x, EPS_C))) {
new_list[k++] = p2->x;
}
for (; j < b->nx; j++)
new_list[k++] = b->x[j];
free(b->x);
b->x = new_list;
b->nx = new_n;
}
}
if (i & BRANCH_Y) /* Same as above with x->y */
{
new_n = b->ny + 2;
for (j = 0; j < b->ny; j++) {
if (!distinguishable(p1->y, b->y[j], EPS_C))
new_n--;
if (!distinguishable(p2->y, b->y[j], EPS_C))
new_n--;
}
if (new_n > b->ny) {
new_list = CHECKED_MALLOC_ARRAY(double, new_n,
"refined subdivided box Y partitions");
if (new_list == NULL)
return 1;
for (j = k = 0; b->y[j] < p1->y; j++)
new_list[k++] = b->y[j];
if (distinguishable(b->y[j], p1->y, EPS_C))
new_list[k++] = p1->y;
for (; b->y[j] < p2->y; j++)
new_list[k++] = b->y[j];
if ((distinguishable(p1->y, p2->y, EPS_C)) &&
(distinguishable(b->y[j], p2->y, EPS_C))) {
new_list[k++] = p2->y;
}
for (; j < b->ny; j++)
new_list[k++] = b->y[j];
free(b->y);
b->y = new_list;
b->ny = new_n;
}
}
if (i & BRANCH_Z) /* Same again, x->z */
{
new_n = b->nz + 2;
for (j = 0; j < b->nz; j++) {
if (!distinguishable(p1->z, b->z[j], EPS_C))
new_n--;
if (!distinguishable(p2->z, b->z[j], EPS_C))
new_n--;
}
if (new_n > b->nz) {
new_list = CHECKED_MALLOC_ARRAY(double, new_n,
"refined subdivided box Z partitions");
if (new_list == NULL)
return 1;
for (j = k = 0; b->z[j] < p1->z; j++)
new_list[k++] = b->z[j];
if (distinguishable(b->z[j], p1->z, EPS_C))
new_list[k++] = p1->z;
for (; b->z[j] < p2->z; j++)
new_list[k++] = b->z[j];
if ((distinguishable(p1->z, p2->z, EPS_C) &&
(distinguishable(b->z[j], p2->z, EPS_C)))) {
new_list[k++] = p2->z;
}
for (; j < b->nz; j++)
new_list[k++] = b->z[j];
free(b->z);
b->z = new_list;
b->nz = new_n;
}
}
return 0;
}
/*************************************************************************
divide_cuboid:
In: parse_state: parser state
b: a subdivided box to further subdivide
axis: which axis to divide
idx: which of the existing divisions should be subdivided
ndiv: the number of subdivisions to make
Out: returns 1 on failure, 0 on success. The requested subdivision(s) are
added.
*************************************************************************/
static int divide_cuboid(struct mdlparse_vars *parse_state,
struct subdivided_box *b, int axis, int idx,
int ndiv) {
double *old_list;
double *new_list;
int old_n;
int new_n;
int i, j, k;
if (ndiv < 2)
ndiv = 2;
switch (axis) {
case BRANCH_X:
old_list = b->x;
old_n = b->nx;
break;
case BRANCH_Y:
old_list = b->y;
old_n = b->ny;
break;
case BRANCH_Z:
old_list = b->z;
old_n = b->nz;
break;
default:
mdlerror_fmt(parse_state, "File '%s', Line %ld: Unknown flag is used.",
__FILE__, (long)__LINE__);
return 1;
}
new_n = old_n + ndiv - 1;
new_list =
CHECKED_MALLOC_ARRAY(double, new_n, "refined subdivided box partitions");
if (new_list == NULL)
return 1;
for (i = j = 0; i <= idx; i++, j++)
new_list[j] = old_list[i];
for (k = 1; k < ndiv; k++)
new_list[j++] =
(((double)k / (double)ndiv)) * (old_list[i] - old_list[i - 1]) +
old_list[i - 1];
for (; i < old_n; i++, j++)
new_list[j] = old_list[i];
switch (axis) {
case BRANCH_X:
b->x = new_list;
b->nx = new_n;
break;
case BRANCH_Y:
b->y = new_list;
b->ny = new_n;
break;
case BRANCH_Z:
b->z = new_list;
b->nz = new_n;
break;
default:
return 1;
/*break;*/
}
free(old_list);
return 0;
}
/*************************************************************************
reaspect_cuboid:
In: parse_state: parser state
b: a subdivided box whose surface is a bunch of rectangles
ratio: the maximum allowed aspect ratio (long side / short side) of a
rectangle
Out: returns 1 on failure, 0 on success. The subdivided box is further
divided to ensure that all surface subdivisions meet the aspect ratio
criterion.
Note: This is not, in general, possible if max_ratio is less than sqrt(2), and
it is diffucult if max_ratio is less than 2.
*************************************************************************/
static int reaspect_cuboid(struct mdlparse_vars *parse_state,
struct subdivided_box *b, double max_ratio) {
double min_x, min_y, min_z, max_x, max_y, max_z;
int jx, jy, jz;
int i, j;
int changed;
do {
changed = 0;
max_x = min_x = b->x[1] - b->x[0];
jx = 0;
for (i = 1; i < b->nx - 1; i++) {
if (min_x > b->x[i + 1] - b->x[i]) {
min_x = b->x[i + 1] - b->x[i];
} else if (max_x < b->x[i + 1] - b->x[i]) {
max_x = b->x[i + 1] - b->x[i];
jx = i;
}
}
max_y = min_y = b->y[1] - b->y[0];
jy = 0;
for (i = 1; i < b->ny - 1; i++) {
if (min_y > b->y[i + 1] - b->y[i]) {
min_y = b->y[i + 1] - b->y[i];
} else if (max_y < b->y[i + 1] - b->y[i]) {
max_y = b->y[i + 1] - b->y[i];
jy = i;
}
}
max_z = min_z = b->z[1] - b->z[0];
jz = 0;
for (i = 1; i < b->nz - 1; i++) {
if (min_z > b->z[i + 1] - b->z[i]) {
min_z = b->z[i + 1] - b->z[i];
} else if (max_z < b->z[i + 1] - b->z[i]) {
max_z = b->z[i + 1] - b->z[i];
jz = i;
}
}
if (max_y / min_x > max_ratio) {
j = divide_cuboid(parse_state, b, BRANCH_Y, jy,
(int)ceil(max_y / (max_ratio * min_x)));
if (j)
return 1;
changed |= BRANCH_Y;
} else if (max_x / min_y > max_ratio) {
j = divide_cuboid(parse_state, b, BRANCH_X, jx,
(int)ceil(max_x / (max_ratio * min_y)));
if (j)
return 1;
changed |= BRANCH_X;
}
if ((changed & BRANCH_X) == 0 && max_z / min_x > max_ratio) {
j = divide_cuboid(parse_state, b, BRANCH_Z, jz,
(int)ceil(max_z / (max_ratio * min_x)));
if (j)
return 1;
changed |= BRANCH_Z;
} else if ((changed & BRANCH_X) == 0 && max_x / min_z > max_ratio) {
j = divide_cuboid(parse_state, b, BRANCH_X, jx,
(int)ceil(max_x / (max_ratio * min_z)));
if (j)
return 1;
changed |= BRANCH_X;
}
if ((changed & (BRANCH_Y | BRANCH_Z)) == 0 && max_z / min_y > max_ratio) {
j = divide_cuboid(parse_state, b, BRANCH_Z, jz,
(int)ceil(max_z / (max_ratio * min_y)));
if (j)
return 1;
changed |= BRANCH_Z;
} else if ((changed & (BRANCH_Y | BRANCH_Z)) == 0 &&
max_y / min_z > max_ratio) {
j = divide_cuboid(parse_state, b, BRANCH_Y, jy,
(int)ceil(max_y / (max_ratio * min_z)));
if (j)
return 1;
changed |= BRANCH_Y;
}
} while (changed);
return 0;
}
/*************************************************************************
count_cuboid_vertices:
Trivial utility function that counts # vertices in a box
In: sb: a subdivided box
Out: the number of vertices in the box
*************************************************************************/
static int count_cuboid_vertices(struct subdivided_box *sb) {
return 2 * sb->ny * sb->nz + 2 * (sb->nx - 2) * sb->nz +
2 * (sb->nx - 2) * (sb->ny - 2);
}
/*************************************************************************
mdl_normalize_elements:
Prepare a region description for use in the simulation by creating a
membership bitmask on the region object.
In: parse_state: parser state
reg: a region
existing: a flag indicating whether the region is being modified or
created
Out: returns 1 on failure, 0 on success. Lists of element specifiers
are converted into bitmasks that specify whether a wall is in or
not in that region. This also handles combinations of regions.
*************************************************************************/
int mdl_normalize_elements(struct mdlparse_vars *parse_state,
struct region *reg, int existing) {
struct bit_array *temp = NULL;
char op;
unsigned int num_elems;
if (reg->element_list_head == NULL) {
return 0;
}
struct polygon_object *poly_obj = NULL;
if (reg->parent->object_type == BOX_OBJ) {
poly_obj = (struct polygon_object *)reg->parent->contents;
num_elems = count_cuboid_elements(poly_obj->sb);
} else {
num_elems = reg->parent->n_walls;
}
struct bit_array *elem_array;
if (reg->membership == NULL) {
elem_array = new_bit_array(num_elems);
if (elem_array == NULL) {
mcell_allocfailed("Failed to allocate a region membership bitmask.");
/*return 1;*/
}
reg->membership = elem_array;
} else {
elem_array = reg->membership;
}
if (reg->element_list_head->special == NULL) {
set_all_bits(elem_array, 0);
}
// Special flag for exclusion
else if ((void *)reg->element_list_head->special ==
(void *)reg->element_list_head) {
set_all_bits(elem_array, 1);
} else {
if (reg->element_list_head->special->exclude) {
set_all_bits(elem_array, 1);
} else {
set_all_bits(elem_array, 0);
}
}
int i = 0;
struct element_list *elem_list;
for (elem_list = reg->element_list_head; elem_list != NULL;
elem_list = elem_list->next) {
if (reg->parent->object_type == BOX_OBJ) {
assert(poly_obj != NULL);
i = elem_list->begin;
switch (i) {
case X_NEG:
elem_list->begin = 0;
elem_list->end =
2 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1) - 1;
break;
case X_POS:
elem_list->begin = 2 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1);
elem_list->end =
4 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1) - 1;
break;
case Y_NEG:
elem_list->begin = 4 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1);
elem_list->end = elem_list->begin +
2 * (poly_obj->sb->nx - 1) * (poly_obj->sb->nz - 1) -
1;
break;
case Y_POS:
elem_list->begin = 4 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1) +
2 * (poly_obj->sb->nx - 1) * (poly_obj->sb->nz - 1);
elem_list->end = elem_list->begin +
2 * (poly_obj->sb->nx - 1) * (poly_obj->sb->nz - 1) -
1;
break;
case Z_NEG:
elem_list->begin = 4 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1) +
4 * (poly_obj->sb->nx - 1) * (poly_obj->sb->nz - 1);
elem_list->end = elem_list->begin +
2 * (poly_obj->sb->nx - 1) * (poly_obj->sb->ny - 1) -
1;
break;
case Z_POS:
elem_list->end = num_elems - 1;
elem_list->begin = elem_list->end + 1 -
2 * (poly_obj->sb->nx - 1) * (poly_obj->sb->ny - 1);
break;
case ALL_SIDES:
elem_list->begin = 0;
elem_list->end = num_elems - 1;
break;
default:
UNHANDLED_CASE(i);
/*return 1;*/
}
} else if (elem_list->begin >= (u_int)num_elems ||
elem_list->end >= (u_int)num_elems) {
mdlerror_fmt(parse_state, "Region element specifier for region %s[%s] refers to sides "
"%u...%u, but polygon has only %u sides.",
reg->parent->sym->name, reg->region_last_name, elem_list->begin, elem_list->end, num_elems);
return 1;
}
if (elem_list->special == NULL) {
set_bit_range(elem_array, elem_list->begin, elem_list->end, 1);
} else if ((void *)elem_list->special == (void *)elem_list) {
set_bit_range(elem_array, elem_list->begin, elem_list->end, 0);
} else {
if (elem_list->special->referent != NULL) {
if (elem_list->special->referent->membership == NULL) {
if (elem_list->special->referent->element_list_head != NULL) {
i = mdl_normalize_elements(parse_state,
elem_list->special->referent, existing);
if (i) {
free_bit_array(temp);
return i;
}
}
}
if (elem_list->special->referent->membership != NULL) {
// What does it mean for the membership array to have length zero?
if (elem_list->special->referent->membership->nbits == 0) {
if (elem_list->special->exclude) {
set_all_bits(elem_array, 0);
} else {
set_all_bits(elem_array, 1);
}
} else {
if (elem_list->special->exclude) {
op = '-';
} else {
op = '+';
}
bit_operation(elem_array, elem_list->special->referent->membership,
op);
}
}
} else {
int ii;
if (temp == NULL) {
temp = new_bit_array(num_elems);
if (temp == NULL) {
mcell_allocfailed(
"Failed to allocate a region membership bitmask.");
/*return 1;*/
}
}
if (poly_obj == NULL) {
mcell_internal_error("Attempt to create a PATCH on a POLYGON_LIST.");
/*return 1;*/
}
if (existing) {
mcell_internal_error(
"Attempt to create a PATCH on an already triangulated BOX.");
/*return 1;*/
}
if (elem_list->special->exclude) {
op = '-';
} else {
op = '+';
}
ii = cuboid_patch_to_bits(poly_obj->sb, &(elem_list->special->corner1),
&(elem_list->special->corner2), temp);
if (ii) {
// Something wrong with patch.
free_bit_array(temp);
return 1;
}
bit_operation(elem_array, temp, op);
}
}
}
if (temp != NULL) {
free_bit_array(temp);
}
if (existing) {
bit_operation(
elem_array,
((struct polygon_object *)reg->parent->contents)->side_removed, '-');
}
while (reg->element_list_head) {
struct element_list *next = reg->element_list_head->next;
if (reg->element_list_head->special) {
if (reg->element_list_head->special !=
(struct element_special *)reg->element_list_head) {
free(reg->element_list_head->special);
}
}
free(reg->element_list_head);
reg->element_list_head = next;
}
#ifdef DEBUG
printf("Normalized membership of %s: ", reg->sym->name);
for (i = 0; i < reg->membership->nbits; i++) {
if (get_bit(reg->membership, i)) {
printf("X");
} else {
printf("_");
}
}
printf("\n");
#endif
return 0;
}
/*************************************************************************
vertex_at_index:
In: sb: a subdivided box from which we want to retrieve one surface patch
ix: the x index of the patch
iy: the y index of the patch
iz: the z index of the patch
Out: returns the index into the array of walls for the first wall in the
patch; add 1 to get the second triangle. If an invalid coordinate is
given, -1 is returned.
Note: since the patch must be on the surface, at least one of ix, iy, iz must
be either 0 or at its maximum.
*************************************************************************/
static int vertex_at_index(struct subdivided_box *sb, int ix, int iy, int iz) {
if (ix == 0 || ix == sb->nx - 1) {
int i = sb->ny * iz + iy;
if (ix == 0)
return i;
else
return i + sb->ny * sb->nz;
} else if (iy == 0 || iy == sb->ny - 1) {
int i = 2 * sb->ny * sb->nz + (sb->nx - 2) * iz + (ix - 1);
if (iy == 0)
return i;
else
return i + (sb->nx - 2) * sb->nz;
} else if (iz == 0 || iz == sb->nz - 1) {
int i = 2 * sb->ny * sb->nz + 2 * (sb->nx - 2) * sb->nz +
(sb->nx - 2) * (iy - 1) + (ix - 1);
if (iz == 0)
return i;
else
return i + (sb->nx - 2) * (sb->ny - 2);
} else {
mcell_internal_error(
"Asking for point %d %d %d but limits are [0 0 0] to [%d %d %d].", ix,
iy, iz, sb->nx - 1, sb->ny - 1, sb->nz - 1);
/*return -1;*/
}
}
/*************************************************************************
polygonalize_cuboid:
In: opp: an ordered polygon object that we will create
sb: a subdivided box
Out: returns 1 on failure, 0 on success. The partitions along each axis of
the subdivided box are considered to be grid lines along which we
subdivide the surface of the box. Walls corresponding to these surface
elements are created and placed into the polygon_object.
*************************************************************************/
static int polygonalize_cuboid(struct polygon_object *pop,
struct subdivided_box *sb) {
struct vector3 *v;
struct element_data *e;
struct vertex_list *head = NULL;
pop->n_verts = count_cuboid_vertices(sb);
struct vector3 *vert_array =
CHECKED_MALLOC_ARRAY(struct vector3, pop->n_verts, "cuboid vertices");
if (vert_array == NULL)
return 1;
pop->n_walls = count_cuboid_elements(sb);
pop->element =
CHECKED_MALLOC_ARRAY(struct element_data, pop->n_walls, "cuboid walls");
if (pop->element == NULL) {
free(vert_array);
vert_array = NULL;
return 1;
}
/* for (a=0;a<2;a++) for (b=0;b<2;b++) for (c=0;c<2;c++)
* printf("%d,%d,%d->%d\n",a,b,c,vertex_at_index(sb,a,b,c)); */
/* Set vertices and elements on X faces */
int ii = 0;
int bb = 0;
int cc = 2 * (sb->nz - 1) * (sb->ny - 1);
int b = 0;
int c = sb->nz * sb->ny;
for (int j = 0; j < sb->nz; j++) {
int a = sb->ny;
for (int i = 0; i < sb->ny; i++) {
/*printf("Setting indices %d %d\n",b+j*a+i,c+j*a+i);*/
v = &(vert_array[b + j * a + i]);
v->x = sb->x[0];
v->y = sb->y[i];
v->z = sb->z[j];
v = &(vert_array[c + j * a + i]);
v->x = sb->x[sb->nx - 1];
v->y = sb->y[i];
v->z = sb->z[j];
if (i > 0 && j > 0) {
e = &(pop->element[bb + ii]);
e->vertex_index[0] = vertex_at_index(sb, 0, i - 1, j - 1);
e->vertex_index[2] = vertex_at_index(sb, 0, i, j - 1);
e->vertex_index[1] = vertex_at_index(sb, 0, i - 1, j);
e = &(pop->element[bb + ii + 1]);
e->vertex_index[0] = vertex_at_index(sb, 0, i, j);
e->vertex_index[1] = vertex_at_index(sb, 0, i, j - 1);
e->vertex_index[2] = vertex_at_index(sb, 0, i - 1, j);
e = &(pop->element[cc + ii]);
e->vertex_index[0] = vertex_at_index(sb, sb->nx - 1, i - 1, j - 1);
e->vertex_index[1] = vertex_at_index(sb, sb->nx - 1, i, j - 1);
e->vertex_index[2] = vertex_at_index(sb, sb->nx - 1, i - 1, j);
e = &(pop->element[cc + ii + 1]);
e->vertex_index[0] = vertex_at_index(sb, sb->nx - 1, i, j);
e->vertex_index[2] = vertex_at_index(sb, sb->nx - 1, i, j - 1);
e->vertex_index[1] = vertex_at_index(sb, sb->nx - 1, i - 1, j);
/*printf("Setting elements %d %d %d %d of
* %d\n",bb+ii,bb+ii+1,cc+ii,cc+ii+1,pop->n_walls);*/
ii += 2;
}
}
}
/* Set vertices and elements on Y faces */
bb = ii;
cc = bb + 2 * (sb->nx - 1) * (sb->nz - 1);
b = 2 * sb->nz * sb->ny;
c = b + sb->nz * (sb->nx - 2);
for (int j = 0; j < sb->nz; j++) {
int a = sb->nx - 2;
for (int i = 1; i < sb->nx; i++) {
if (i < sb->nx - 1) {
/*printf("Setting indices %d %d of
* %d\n",b+j*a+(i-1),c+j*a+(i-1),pop->n_verts);*/
v = &(vert_array[b + j * a + (i - 1)]);
v->x = sb->x[i];
v->y = sb->y[0];
v->z = sb->z[j];
v = &(vert_array[c + j * a + (i - 1)]);
v->x = sb->x[i];
v->y = sb->y[sb->ny - 1];
v->z = sb->z[j];
}
if (j > 0) {
e = &(pop->element[bb + ii]);
e->vertex_index[0] = vertex_at_index(sb, i - 1, 0, j - 1);
e->vertex_index[1] = vertex_at_index(sb, i, 0, j - 1);
e->vertex_index[2] = vertex_at_index(sb, i - 1, 0, j);
e = &(pop->element[bb + ii + 1]);
e->vertex_index[0] = vertex_at_index(sb, i, 0, j);
e->vertex_index[2] = vertex_at_index(sb, i, 0, j - 1);
e->vertex_index[1] = vertex_at_index(sb, i - 1, 0, j);
e = &(pop->element[cc + ii]);
e->vertex_index[0] = vertex_at_index(sb, i - 1, sb->ny - 1, j - 1);
e->vertex_index[2] = vertex_at_index(sb, i, sb->ny - 1, j - 1);
e->vertex_index[1] = vertex_at_index(sb, i - 1, sb->ny - 1, j);
e = &(pop->element[cc + ii + 1]);
e->vertex_index[0] = vertex_at_index(sb, i, sb->ny - 1, j);
e->vertex_index[1] = vertex_at_index(sb, i, sb->ny - 1, j - 1);
e->vertex_index[2] = vertex_at_index(sb, i - 1, sb->ny - 1, j);
/*printf("Setting elements %d %d %d %d of
* %d\n",bb+ii,bb+ii+1,cc+ii,cc+ii+1,pop->n_walls);*/
ii += 2;
}
}
}
/* Set vertices and elements on Z faces */
bb = ii;
cc = bb + 2 * (sb->nx - 1) * (sb->ny - 1);
b = 2 * sb->nz * sb->ny + 2 * (sb->nx - 2) * sb->nz;
c = b + (sb->nx - 2) * (sb->ny - 2);
for (int j = 1; j < sb->ny; j++) {
int a = sb->nx - 2;
for (int i = 1; i < sb->nx; i++) {
if (i < sb->nx - 1 && j < sb->ny - 1) {
/*printf("Setting indices %d %d of
* %d\n",b+(j-1)*a+(i-1),c+(j-1)*a+(i-1),pop->n_verts);*/
v = &(vert_array[b + (j - 1) * a + (i - 1)]);
v->x = sb->x[i];
v->y = sb->y[j];
v->z = sb->z[0];
v = &(vert_array[c + (j - 1) * a + (i - 1)]);
v->x = sb->x[i];
v->y = sb->y[j];
v->z = sb->z[sb->nz - 1];
}
e = &(pop->element[bb + ii]);
e->vertex_index[0] = vertex_at_index(sb, i - 1, j - 1, 0);
e->vertex_index[2] = vertex_at_index(sb, i, j - 1, 0);
e->vertex_index[1] = vertex_at_index(sb, i - 1, j, 0);
e = &(pop->element[bb + ii + 1]);
e->vertex_index[0] = vertex_at_index(sb, i, j, 0);
e->vertex_index[1] = vertex_at_index(sb, i, j - 1, 0);
e->vertex_index[2] = vertex_at_index(sb, i - 1, j, 0);
e = &(pop->element[cc + ii]);
e->vertex_index[0] = vertex_at_index(sb, i - 1, j - 1, sb->nz - 1);
e->vertex_index[1] = vertex_at_index(sb, i, j - 1, sb->nz - 1);
e->vertex_index[2] = vertex_at_index(sb, i - 1, j, sb->nz - 1);
e = &(pop->element[cc + ii + 1]);
e->vertex_index[0] = vertex_at_index(sb, i, j, sb->nz - 1);
e->vertex_index[2] = vertex_at_index(sb, i, j - 1, sb->nz - 1);
e->vertex_index[1] = vertex_at_index(sb, i - 1, j, sb->nz - 1);
/*printf("Setting elements %d %d %d %d of
* %d\n",bb+ii,bb+ii+1,cc+ii,cc+ii+1,pop->n_walls);*/
ii += 2;
}
}
/* build the head node of the linked list "pop->parsed_vertices" */
struct vertex_list *vlp = CHECKED_MALLOC_STRUCT(
struct vertex_list, "vertex_list");
if (vlp == NULL) {
free(vert_array);
return 1;
}
vlp->vertex = CHECKED_MALLOC_STRUCT(struct vector3, "vertex");
if (vlp->vertex == NULL) {
free(vert_array);
free(vlp);
return 1;
}
memcpy(vlp->vertex, &vert_array[0], sizeof(struct vector3));
vlp->next = head;
head = vlp;
struct vertex_list *tail = head;
/* build other nodes of the linked list "pop->parsed_vertices" */
int error_code = 0;
for (int i = 1; i < pop->n_verts; i++) {
vlp = CHECKED_MALLOC_STRUCT(struct vertex_list, "vertex_list");
if (vlp == NULL) {
error_code = 1;
break;
}
vlp->vertex = CHECKED_MALLOC_STRUCT(struct vector3, "vertex");
if (vlp->vertex == NULL) {
free(vlp);
error_code = 1;
break;
}
memcpy(vlp->vertex, &vert_array[i], sizeof(struct vector3));
vlp->next = tail->next;
tail->next = vlp;
tail = tail->next;
}
if (error_code == 1) {
free_vertex_list(head);
if (vert_array != NULL)
free(vert_array);
vert_array = NULL;
return 1;
}
pop->parsed_vertices = head;
#ifdef DEBUG
printf("BOX has vertices:\n");
for (int i = 0; i < pop->n_verts; i++)
printf(" %.5e %.5e %.5e\n", vert_array[i].x, vert_array[i].y,
vert_array[i].z);
printf("BOX has walls:\n");
for (int i = 0; i < pop->n_walls; i++)
printf(" %d %d %d\n", pop->element[i].vertex_index[0],
pop->element[i].vertex_index[1], pop->element[i].vertex_index[2]);
printf("\n");
#endif
if (vert_array != NULL)
free(vert_array);
vert_array = NULL;
return 0;
}
/*************************************************************************
mdl_triangulate_box_object:
Finalizes the polygonal structure of the box, normalizing all regions.
In: parse_state: parser state
box_sym: symbol for the box object
pop: polygon object for the box
box_aspect_ratio: aspect ratio for the box
Out: 0 on success, 1 on failure. Box is polygonalized and regions normalized.
*************************************************************************/
int mdl_triangulate_box_object(struct mdlparse_vars *parse_state,
struct sym_entry *box_sym,
struct polygon_object *pop,
double box_aspect_ratio) {
struct geom_object *objp = (struct geom_object *)box_sym->value;
if (box_aspect_ratio >= 2.0) {
if (reaspect_cuboid(parse_state, pop->sb, box_aspect_ratio)) {
mdlerror(parse_state, "Error setting up box geometry");
return 1;
}
}
for (struct region_list *rlp = objp->regions; rlp != NULL; rlp = rlp->next) {
if (mdl_normalize_elements(parse_state, rlp->reg, 0))
return 1;
}
if (polygonalize_cuboid(pop, pop->sb)) {
mdlerror(parse_state, "Could not turn box object into polygons");
return 1;
} else if (parse_state->vol->notify->box_triangulation == NOTIFY_FULL) {
mcell_log("Box object %s converted into %d polygons.", box_sym->name,
pop->n_walls);
}
const unsigned int n_walls = pop->n_walls;
pop->side_removed = new_bit_array(n_walls);
if (pop->side_removed == NULL) {
mcell_allocfailed("Failed to allocate a box object removed side bitmask.");
/*return 1;*/
}
set_all_bits(pop->side_removed, 0);
return 0;
}
/**************************************************************************
mdl_check_diffusion_constant:
Check that the specified diffusion constant is valid, correcting it if
appropriate.
In: parse_state: parser state
d: pointer to the diffusion constant
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_check_diffusion_constant(struct mdlparse_vars *parse_state, double *d) {
if (parse_state->vol->notify->neg_diffusion == WARN_COPE) {
if (*d < 0)
*d = 0.0;
} else if (parse_state->vol->notify->neg_diffusion == WARN_WARN) {
if (*d < 0.0) {
mcell_warn(
"negative diffusion constant found, setting to zero and continuing.");
*d = 0.0;
}
} else {
if (*d < 0.0) {
mdlerror(parse_state, "diffusion constants should be zero or positive.");
return 1;
}
}
return 0;
}
/*************************************************************************
report_diffusion_distances:
Helper function to print average diffusion distances per species.
In: spec: the species
time_unit:
length_unit:
lvl:
Out: Nothing.
*************************************************************************/
static void report_diffusion_distances(struct mcell_species_spec *spec,
double time_unit, double length_unit,
int lvl) {
double l_perp_bar = 0;
double l_perp_rms = 0;
double l_r_bar = 0;
double l_r_rms = 0;
if (spec->custom_time_step == 1.0) {
/* Theoretical average diffusion distances for the molecule need to
* distinguish between 2D and 3D molecules for computing l_r_bar and
* friends */
// Volume molecule
if ((spec->is_2d) == 0) {
l_perp_bar = sqrt(4 * 1.0e8 * spec->D * time_unit / MY_PI);
l_perp_rms = sqrt(2 * 1.0e8 * spec->D * time_unit);
l_r_bar = 2 * l_perp_bar;
l_r_rms = sqrt(6 * 1.0e8 * spec->D * time_unit);
}
// Surface molecule
else {
l_r_bar = sqrt(MY_PI * 1.0e8 * spec->D * time_unit);
}
if (lvl == NOTIFY_FULL) {
mcell_log(
"MCell: Theoretical average diffusion distances for molecule %s:\n"
"\tl_r_bar = %.9g microns\n"
"\tl_r_rms = %.9g microns\n"
"\tl_perp_bar = %.9g microns\n"
"\tl_perp_rms = %.9g microns",
spec->name, l_r_bar, l_r_rms, l_perp_bar, l_perp_rms);
} else if (lvl == NOTIFY_BRIEF) {
mcell_log(" l_r_bar=%.9g um for %s", l_r_bar, spec->name);
}
} else {
if (lvl == NOTIFY_FULL) {
/* the size of the length unit depends on if the molecule is
* 2D or 3D; the values for step length simply follow from
* converting space_step = sqrt(4Dt) into the 2D/3D expression
* for l_r_bar */
double step_length = 0.0;
if ((spec->is_2d) == 0) {
step_length = length_unit * spec->space_step * 2.0 / sqrt(MY_PI);
} else {
step_length = length_unit * spec->space_step * sqrt(MY_PI) / 2.0;
}
mcell_log("MCell: Theoretical average diffusion time for molecule %s:\n"
"\tl_r_bar fixed at %.9g microns\n"
"\tPosition update every %.3e seconds (%.3g timesteps)",
spec->name, step_length, spec->custom_time_step * time_unit,
spec->custom_time_step);
} else if (lvl == NOTIFY_BRIEF) {
mcell_log(" delta t=%.3g timesteps for %s", spec->custom_time_step,
spec->name);
}
}
}
// TODO: Remove by merging with mdl_print_species_summaries or at least
// eliminate redundancies
void mdl_print_species_summary(MCELL_STATE *state,
struct mcell_species_spec *species) {
if (state->procnum == 0) {
if (state->notify->diffusion_constants == NOTIFY_BRIEF) {
mcell_log("Defining molecule with the following diffusion constant:");
}
report_diffusion_distances(species, state->time_unit, state->length_unit,
state->notify->diffusion_constants);
no_printf("Molecule %s defined with D = %g\n", species->name, species->D);
free((char*)species->name);
free(species);
}
}
/*************************************************************************
mdl_print_species_summaries:
Finish the creation of a series of molecules, undoing any state changes we
made during the creation of the molecules. Presently, this just means
"print the diffusion distances report".
In: state: the simulation state
Out: A report is printed to the file handle.
*************************************************************************/
void
mdl_print_species_summaries(struct volume *state,
struct parse_mcell_species_list_item *spec_items) {
if (state->procnum == 0) {
if (state->notify->diffusion_constants == NOTIFY_BRIEF) {
mcell_log("Defining molecules with the following theoretical average "
"diffusion distances:");
}
struct parse_mcell_species_list_item *spec_item;
for (spec_item = spec_items; spec_item != NULL;
spec_item = spec_item->next) {
struct mcell_species_spec *spec = spec_item->spec;
report_diffusion_distances(spec, state->time_unit, state->length_unit,
state->notify->diffusion_constants);
no_printf("Molecule %s defined with D = %g\n", spec->name, spec->D);
}
struct parse_mcell_species_list_item *next;
for (spec_item = spec_items; NULL != spec_item; spec_item = next) {
next = spec_item->next;
free((char*)spec_item->spec->name);
free(spec_item->spec);
free(spec_item);
}
if (state->notify->diffusion_constants == NOTIFY_BRIEF) {
mcell_log_raw("\n");
}
}
}
/*************************************************************************
mdl_add_to_species_list:
Helper function to add a species to a species list.
In: species_list_mem:
list: the list of species
spec: the species to be added
Out: 0 on success
*************************************************************************/
int mdl_add_to_species_list(struct parse_mcell_species_list *list,
struct mcell_species_spec *spec) {
struct parse_mcell_species_list_item *spec_item =
CHECKED_MALLOC_STRUCT(struct parse_mcell_species_list_item,
"struct parse_mcell_species_list_item");
spec_item->spec = spec;
spec_item->next = NULL;
if (list->species_count == 0) {
list->species_tail = list->species_head = spec_item;
list->species_count = 1;
} else {
list->species_tail = list->species_tail->next = spec_item;
++list->species_count;
}
return 0;
}
/**************************************************************************
mdl_start_release_site:
Start parsing the innards of a release site.
In: parse_state: parser state
symp: symbol for the release site
shape: shape for the release site
Out: 0 on success, 1 on failure
NOTE: This is just a thin wrapper around start_release_site
**************************************************************************/
int mdl_start_release_site(struct mdlparse_vars *parse_state,
struct sym_entry *symp, int shape) {
struct geom_object *obj_ptr = NULL;
if (mcell_start_release_site(parse_state->vol, symp, &obj_ptr)) {
return 1;
}
parse_state->current_release_site = (struct release_site_obj *)obj_ptr->contents;
if (obj_ptr->contents == NULL) {
return 1;
}
parse_state->current_release_site->release_shape = (int8_t)shape;
return 0;
}
/**************************************************************************
mdl_finish_release_site:
Finish parsing the innards of a release site.
In: parse_state: parser state
symp: symbol for the release site
Out: the object, on success, or NULL on failure
NOTE: This is just a thin wrapper around finish_release_site
**************************************************************************/
struct geom_object *mdl_finish_release_site(struct mdlparse_vars *parse_state,
struct sym_entry *symp) {
struct geom_object *objp_new = NULL;
if (mcell_finish_release_site(symp, &objp_new)) {
mcell_error_nodie("Failed to create release site %s", symp->name);
return NULL;
}
if (objp_new == NULL) {
return NULL;
}
parse_state->current_release_site = NULL;
return objp_new;
}
/**************************************************************************
mdl_is_release_site_valid:
Validate a release site.
In: parse_state: parser state
rel_site_obj_ptr: the release site object to validate
Out: 0 if it is valid, 1 if not
NOTE: This is just a thin wrapper around is_release_site_valid
**************************************************************************/
/*
//XXX: Remove this but port over error messages first
int mdl_is_release_site_valid(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr) {
switch (is_release_site_valid(rel_site_obj_ptr)) {
case 2:
mdlerror(parse_state,
"Must specify molecule to release using MOLECULE=molecule_name.");
return 1;
case 3:
mdlerror_fmt(parse_state,
"Cannot release surface class '%s' from release site",
rel_site_obj_ptr->mol_type->sym->name);
return 1;
case 4:
mdlerror(parse_state, "CONCENTRATION may only be used with molecules that "
"can diffuse in 3D.\n"
" Use DENSITY for molecules diffusing in 2D.");
return 1;
case 5:
mdlerror(parse_state,
"DENSITY may only be used with molecules that can diffuse in 2D.\n"
" Use CONCENTRATION for molecules diffusing in 3D.");
return 1;
case 6:
mdlerror(parse_state, "Release site is missing location.");
return 1;
}
return 0;
}
*/
/*************************************************************************
mdl_check_release_regions:
In: parse_state: parser state
rel_eval: an release evaluator (set operations applied to regions)
parent: the object that owns this release evaluator
instance: the root object that begins the instance tree
Out: 0 if all regions refer to instanced objects or to a common ancestor of
the object with the evaluator, meaning that the object can be found. 1
if any referred-to region cannot be found.
NOTE: This is just a thin wrapper around check_release_regions
*************************************************************************/
static int mdl_check_release_regions(struct mdlparse_vars *parse_state,
struct release_evaluator *rel_eval,
struct geom_object *parent,
struct geom_object *instance) {
switch (check_release_regions(rel_eval, parent, instance)) {
case 1:
return 1;
case 2:
mdlerror(parse_state,
"Region neither instanced nor grouped with release site.");
return 1;
case 3:
mdlerror(parse_state, "Region not grouped with release site.");
return 1;
}
return 0;
}
/**************************************************************************
mdl_set_release_site_geometry_region:
Set the geometry for a particular release site to be a region expression.
In: parse_state: parser state
rel_site_obj_ptr: the release site object to validate
obj_ptr: the object representing this release site
rel_eval: the release evaluator representing the region of release
Out: 0 on success, 1 on failure
**************************************************************************/
int
mdl_set_release_site_geometry_region(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
struct geom_object *obj_ptr,
struct release_evaluator *rel_eval) {
switch (mcell_set_release_site_geometry_region(
parse_state->vol, rel_site_obj_ptr, obj_ptr, rel_eval)) {
case 1:
return 1;
case 2:
mdlerror(
parse_state,
"Trying to release on a region that the release site cannot see!\n "
"Try grouping the release site and the corresponding geometry with an "
"OBJECT.");
return 1;
}
return 0;
}
/**************************************************************************
mdl_set_release_site_geometry_object:
Set the geometry for a particular release site to be an entire object.
In: parse_state: parser state
rel_site_obj_ptr: the release site object to validate
obj_ptr: the object upon which to release
Out: 0 on success, 1 on failure
**************************************************************************/
int
mdl_set_release_site_geometry_object(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
struct geom_object *obj_ptr) {
if ((obj_ptr->object_type == META_OBJ) ||
(obj_ptr->object_type == REL_SITE_OBJ)) {
mdlerror(
parse_state,
"only BOX or POLYGON_LIST objects may be assigned to the SHAPE keyword "
"in the RELEASE_SITE definition. Metaobjects or release objects are "
"not allowed here.");
return 1;
}
char *obj_name = obj_ptr->sym->name;
char *region_name = CHECKED_SPRINTF("%s,ALL", obj_name);
if (region_name == NULL) {
return 1;
}
struct sym_entry *sym_ptr;
if (((sym_ptr = retrieve_sym(
region_name, parse_state->vol->reg_sym_table)) == NULL) ||
sym_ptr->count == 0) {
mdlerror_fmt(parse_state, "Undefined region: %s", region_name);
free(region_name);
return 1;
}
free(region_name);
struct release_evaluator *rel_eval =
CHECKED_MALLOC_STRUCT(struct release_evaluator, "release site on region");
if (rel_eval == NULL) {
return 1;
}
rel_eval->op = REXP_NO_OP | REXP_LEFT_REGION;
rel_eval->left = sym_ptr->value;
rel_eval->right = NULL;
((struct region *)rel_eval->left)->flags |= COUNT_CONTENTS;
rel_site_obj_ptr->release_shape = SHAPE_REGION;
parse_state->vol->place_waypoints_flag = 1;
if (mdl_check_release_regions(parse_state, rel_eval, obj_ptr,
parse_state->vol->root_instance)) {
mdlerror(
parse_state,
"Trying to release on a region that the release site cannot see!\n "
"Try grouping the release site and the corresponding geometry with an "
"OBJECT.");
free(rel_eval);
return 1;
}
struct release_region_data *rel_reg_data = CHECKED_MALLOC_STRUCT(
struct release_region_data, "release site on region");
if (rel_reg_data == NULL) {
mdlerror(parse_state,
"Out of memory while trying to create release site on region");
free(rel_eval);
return 1;
}
rel_reg_data->n_walls_included = -1; /* Indicates uninitialized state */
rel_reg_data->cum_area_list = NULL;
rel_reg_data->wall_index = NULL;
rel_reg_data->obj_index = NULL;
rel_reg_data->n_objects = -1;
rel_reg_data->owners = NULL;
rel_reg_data->in_release = NULL;
rel_reg_data->self = parse_state->current_object;
rel_reg_data->expression = rel_eval;
rel_site_obj_ptr->region_data = rel_reg_data;
return 0;
}
/**************************************************************************
mdl_check_valid_molecule_release:
Check that a particular molecule type is valid for inclusion in a release
site. Checks that orientations are present if required, and absent if
forbidden, and that we aren't trying to release a surface class.
In: parse_state: parser state
mol_type: molecule species and (optional) orientation for release
Out: 0 on success, 1 on failure
**************************************************************************/
static int mdl_check_valid_molecule_release(struct mdlparse_vars *parse_state,
struct mcell_species *mol_type) {
static const char *EXTRA_ORIENT_MSG =
"surface orientation not specified for released surface molecule\n"
"(use ; or ', or ,' for random orientation)";
static const char *MISSING_ORIENT_MSG =
"orientation not used for released volume molecule";
struct species *mol = (struct species *)mol_type->mol_type->value;
if (mol->flags & ON_GRID) {
if (!mol_type->orient_set) {
if (parse_state->vol->notify->missed_surf_orient == WARN_ERROR) {
mdlerror_fmt(parse_state, "Error: %s", EXTRA_ORIENT_MSG);
return 1;
} else if (parse_state->vol->notify->missed_surf_orient == WARN_WARN) {
mdlerror_fmt(parse_state, "Warning: %s", EXTRA_ORIENT_MSG);
}
}
} else if ((mol->flags & NOT_FREE) == 0) {
if (mol_type->orient_set) {
if (parse_state->vol->notify->useless_vol_orient == WARN_ERROR) {
mdlerror_fmt(parse_state, "Error: %s", MISSING_ORIENT_MSG);
return 1;
} else if (parse_state->vol->notify->useless_vol_orient == WARN_WARN) {
mdlerror_fmt(parse_state, "Warning: %s", MISSING_ORIENT_MSG);
}
}
} else {
mdlerror(parse_state,
"cannot release a surface class instead of a molecule.");
return 1;
}
return 0;
}
/**************************************************************************
mdl_set_release_site_molecule:
Set the molecule to be released from this release site.
In: parse_state: parser state
rel_site_obj_ptr: release site object
mol_type: molecule species and (optional) orientation for release
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_set_release_site_molecule(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
struct mcell_species *mol_type) {
// Store molecule information
rel_site_obj_ptr->mol_type = (struct species *)mol_type->mol_type->value;
if ((rel_site_obj_ptr->mol_type->flags & NOT_FREE) == 0) {
if (rel_site_obj_ptr->release_shape == SHAPE_REGION)
parse_state->vol->place_waypoints_flag = 1;
} else {
if (rel_site_obj_ptr->release_shape != SHAPE_REGION &&
rel_site_obj_ptr->release_shape != SHAPE_LIST) {
mdlerror_fmt(parse_state, "The release site '%s' is a geometric release "
"site, and may not be used to \n"
" release the surface molecule '%s'. Surface "
"molecule release sites must \n"
" be either LIST or region release sites.",
rel_site_obj_ptr->name, mol_type->mol_type->name);
return 1;
}
}
rel_site_obj_ptr->orientation = mol_type->orient;
/* Now, validate molecule information */
return mdl_check_valid_molecule_release(parse_state, mol_type);
}
/**************************************************************************
mdl_set_release_site_diameter:
Set the diameter of a release site.
In: parse_state: parser state
rel_site_obj_ptr: the release site object to validate
diam: the desired diameter of this release site
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_set_release_site_diameter(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
double diam) {
diam *= parse_state->vol->r_length_unit;
rel_site_obj_ptr->diameter =
CHECKED_MALLOC_STRUCT(struct vector3, "release site diameter");
if (rel_site_obj_ptr->diameter == NULL) {
return 1;
}
rel_site_obj_ptr->diameter->x = diam;
rel_site_obj_ptr->diameter->y = diam;
rel_site_obj_ptr->diameter->z = diam;
return 0;
}
/**************************************************************************
mdl_set_release_site_diameter_array:
Set the diameter of the release site along the X, Y, and Z axes.
In: parse_state: parser state
rel_site_obj_ptr: the release site object to validate
n_diams: dimensionality of the diameters array (should be 3)
diams: list containing X, Y, and Z diameters for release site
factor: factor to scale diameter -- 2.0 if diameters are actually radii,
1.0 for actual diameters
Out: 0 on success, 1 on failure
**************************************************************************/
int
mdl_set_release_site_diameter_array(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
int n_diams, struct num_expr_list *diams,
double factor) {
factor *= parse_state->vol->r_length_unit;
if (rel_site_obj_ptr->release_shape == SHAPE_LIST) {
mdlerror(parse_state, "Release list diameters must be single valued.");
return 1;
}
if (n_diams != 3) {
mdlerror(parse_state, "Three dimensional value required");
return 1;
}
rel_site_obj_ptr->diameter =
CHECKED_MALLOC_STRUCT(struct vector3, "release site diameter");
if (rel_site_obj_ptr->diameter == NULL) {
return 1;
}
rel_site_obj_ptr->diameter->x = diams->value * factor;
rel_site_obj_ptr->diameter->y = diams->next->value * factor;
rel_site_obj_ptr->diameter->z = diams->next->next->value * factor;
return 0;
}
/**************************************************************************
mdl_set_release_site_diameter_var:
Set the diameters of the release site along the X, Y, and Z axes from a
variable, either scalar or vector.
In: parse_state: parser state
rel_site_obj_ptr: the release site object to validate
factor: factor to scale diameter -- 2.0 if diameters are actually radii,
1.0 for actual diameters
symp: the variable from which to set
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_set_release_site_diameter_var(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
double factor, struct sym_entry *symp) {
struct num_expr_list *expr_list_ptr;
int count = 0;
rel_site_obj_ptr->diameter =
CHECKED_MALLOC_STRUCT(struct vector3, "release site diameter");
if (rel_site_obj_ptr->diameter == NULL) {
return 1;
}
switch (symp->sym_type) {
case DBL:
if (mdl_set_release_site_diameter(parse_state, rel_site_obj_ptr,
*(double *)symp->value * factor)) {
return 1;
}
break;
case ARRAY:
// Count up to 4 elements -- that's all we need to count to know if it's
// valid
for (expr_list_ptr = (struct num_expr_list *)symp->value;
expr_list_ptr != NULL && count < 4;
++count, expr_list_ptr = expr_list_ptr->next)
;
expr_list_ptr = (struct num_expr_list *)symp->value;
if (mdl_set_release_site_diameter_array(parse_state, rel_site_obj_ptr,
count, expr_list_ptr, factor)) {
return 1;
}
break;
default:
mdlerror(parse_state,
"Diameter must either be a number or a 3-valued vector.");
return 1;
}
return 0;
}
/**************************************************************************
mdl_set_release_site_periodic_box:
In: parse_state: parser state
rel_site_obj_ptr: the release site object
periodic_box: the periodic box that we want to release molecules into
Out: 0 on success
**************************************************************************/
int mdl_set_release_site_periodic_box(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
struct vector3 *periodic_box) {
rel_site_obj_ptr->periodic_box->x = (int16_t)periodic_box->x;
rel_site_obj_ptr->periodic_box->y = (int16_t)periodic_box->y;
rel_site_obj_ptr->periodic_box->z = (int16_t)periodic_box->z;
return 0;
}
/**************************************************************************
mdl_set_release_site_probability:
Set the release probability for a release site.
In: parse_state: parser state
rel_site_obj_ptr: the release site object to validate
prob: the release probability
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_set_release_site_probability(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
double prob) {
if (!distinguishable(rel_site_obj_ptr->release_prob,
MAGIC_PATTERN_PROBABILITY, EPS_C)) {
mdlerror(parse_state,
"Ignoring release probability for reaction-triggered releases.");
} else {
rel_site_obj_ptr->release_prob = prob;
if (rel_site_obj_ptr->release_prob < 0) {
mdlerror(parse_state, "Release probability cannot be less than 0.");
return 1;
}
if (rel_site_obj_ptr->release_prob > 1) {
mdlerror(parse_state, "Release probability cannot be greater than 1.");
return 1;
}
}
return 0;
}
/*************************************************************************
*************************************************************************/
int mdl_set_release_site_graph_pattern(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
char* graph_pattern){
int total_len = strlen(graph_pattern);
rel_site_obj_ptr->graph_pattern = CHECKED_MALLOC_ARRAY(char, total_len+1, "graph pattern string");
strcpy(rel_site_obj_ptr->graph_pattern, graph_pattern);
return 0;
}
/**************************************************************************
mdl_set_release_site_pattern:
Set the release pattern to be used by a particular release site.
In: parse_state: parser state
rel_site_obj_ptr: the release site object to validate
pattern: the release pattern
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_set_release_site_pattern(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
struct sym_entry *pattern) {
rel_site_obj_ptr->pattern = (struct release_pattern *)pattern->value;
// Careful! We've put a rxn_pathname into the "pattern" pointer!
if (pattern->sym_type == RXPN) {
if (rel_site_obj_ptr->release_prob != 1.0) {
mdlerror(parse_state,
"Ignoring release probability for reaction-triggered releases.");
}
// Magic number indicating a reaction-triggered release
rel_site_obj_ptr->release_prob = MAGIC_PATTERN_PROBABILITY;
}
return 0;
}
/**************************************************************************
mdl_set_release_site_molecule_positions:
Set the molecule positions for a LIST release.
In: parse_state: parser state
rel_site_obj_ptr: the release site object to validate
list: list of release_single_molecule structs
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_set_release_site_molecule_positions(
struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
struct release_single_molecule_list *list) {
if (rel_site_obj_ptr->release_shape != SHAPE_LIST) {
mdlerror(parse_state,
"You must use the LIST shape to specify molecule positions in a "
"release.");
return 1;
}
struct release_single_molecule *rsm;
if (rel_site_obj_ptr->mol_list == NULL) {
rel_site_obj_ptr->mol_list = list->rsm_head;
} else {
for (rsm = rel_site_obj_ptr->mol_list; rsm->next != NULL; rsm = rsm->next)
;
rsm->next = list->rsm_head;
}
rel_site_obj_ptr->release_number += list->rsm_count;
return 0;
}
/**************************************************************************
mdl_new_release_single_molecule:
Create a mew single molecule release position for a LIST release site.
In: parse_state: parser state
mol_type: molecule type and optional orientation
pos: 3D position in the world
Out: molecule release description, or NULL if an error occurred
**************************************************************************/
struct release_single_molecule *
mdl_new_release_single_molecule(struct mdlparse_vars *parse_state,
struct mcell_species *mol_type,
struct vector3 *pos) {
struct vector3 temp_v3;
memcpy(&temp_v3, pos, sizeof(struct vector3));
free(pos);
struct release_single_molecule *rsm = CHECKED_MALLOC_STRUCT(
struct release_single_molecule, "release site molecule position");
if (rsm == NULL) {
mdlerror(parse_state, "Out of memory reading molecule positions");
return NULL;
}
rsm->orient = mol_type->orient;
rsm->loc.x = temp_v3.x * parse_state->vol->r_length_unit;
rsm->loc.y = temp_v3.y * parse_state->vol->r_length_unit;
rsm->loc.z = temp_v3.z * parse_state->vol->r_length_unit;
rsm->mol_type = (struct species *)(mol_type->mol_type->value);
rsm->next = NULL;
if (mdl_check_valid_molecule_release(parse_state, mol_type)) {
free(rsm);
return NULL;
}
return rsm;
}
/**************************************************************************
mdl_set_release_site_concentration:
Set a release quantity from this release site based on a fixed
concentration within the release-site's area.
In: parse_state: parser state
rel_site_obj_ptr: the release site
conc: concentration for release
Out: 0 on success, 1 on failure. release site object is updated
NOTE: This is just a thin wrapper around set_release_site_concentration
**************************************************************************/
int
mdl_set_release_site_concentration(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
double conc) {
if (set_release_site_concentration(rel_site_obj_ptr, conc)) {
mdlerror_fmt(parse_state,
"Release site '%s' is a spherical shell; concentration-based "
"release is not supported on a spherical shell",
rel_site_obj_ptr->name);
return 1;
}
return 0;
}
/**************************************************************************
mdl_vertex_list_singleton:
Set an item to be the sole element of a vertex list.
In: head: the list
item: ite item
Out: none. list is updated
**************************************************************************/
void mdl_vertex_list_singleton(struct vertex_list_head *head,
struct vertex_list *item) {
item->next = NULL;
head->vertex_tail = head->vertex_head = item;
head->vertex_count = 1;
}
/**************************************************************************
mdl_add_vertex_to_list:
Append a vertex to a list.
In: head: the list
item: ite item
Out: none. list is updated
**************************************************************************/
void mdl_add_vertex_to_list(struct vertex_list_head *head,
struct vertex_list *item) {
item->next = NULL;
head->vertex_tail = head->vertex_tail->next = item;
++head->vertex_count;
}
/**************************************************************************
mdl_new_vertex_list_item:
Allocate an item for a vertex list.
In: vertex: this vertex
normal: surface normal at this vertex, or NULL
Out: the vertex list item, or NULL if an error occurred
**************************************************************************/
struct vertex_list *mdl_new_vertex_list_item(struct vector3 *vertex) {
struct vertex_list *vlp =
CHECKED_MALLOC_STRUCT(struct vertex_list, "vertices");
if (vlp == NULL)
return NULL;
vlp->vertex = vertex;
vlp->next = NULL;
return vlp;
}
/**************************************************************************
mdl_element_connection_list_singleton:
Set an item to be the sole element of an element connection list.
In: head: the list
item: ite item
Out: none. list is updated
**************************************************************************/
void
mdl_element_connection_list_singleton(struct element_connection_list_head *head,
struct element_connection_list *item) {
item->next = NULL;
head->connection_tail = head->connection_head = item;
head->connection_count = 1;
}
/**************************************************************************
mdl_add_element_connection_to_list:
Append an element connection to a list.
In: head: the list
item: ite item
Out: none. list is updated
**************************************************************************/
void
mdl_add_element_connection_to_list(struct element_connection_list_head *head,
struct element_connection_list *item) {
item->next = NULL;
head->connection_tail = head->connection_tail->next = item;
++head->connection_count;
}
/**************************************************************************
mdl_new_element_connection:
Create an element connection (essentially a triplet of vertex indices).
In: parse_state: parser state
indices: the element connections
Out: the list, or NULL if an error occurred
**************************************************************************/
struct element_connection_list *
mdl_new_element_connection(struct mdlparse_vars *parse_state,
struct num_expr_list_head *indices) {
if (indices->value_count != 3) {
mdlerror(parse_state,
"Non-triangular element found in polygon list object");
return NULL;
}
struct element_connection_list *eclp = CHECKED_MALLOC_STRUCT(
struct element_connection_list, "polygon element commections");
if (eclp == NULL)
return NULL;
eclp->indices = CHECKED_MALLOC_ARRAY(int, 3, "polygon element connections");
if (eclp->indices == NULL) {
free(eclp);
return NULL;
}
eclp->indices[0] = (int)indices->value_head->value;
eclp->indices[1] = (int)indices->value_head->next->value;
eclp->indices[2] = (int)indices->value_tail->value;
eclp->n_verts = indices->value_count;
eclp->next = NULL;
if (!indices->shared)
mcell_free_numeric_list(indices->value_head);
return eclp;
}
/**************************************************************************
mdl_new_tet_element_connection:
Create a tetrahedral element connection (essentially a quadruplet of vertex
indices).
In: parse_state: parser state
indices: the element connections
Out: the list, or NULL if an error occurred
**************************************************************************/
struct element_connection_list *
mdl_new_tet_element_connection(struct mdlparse_vars *parse_state,
struct num_expr_list_head *indices) {
if (indices->value_count != 4) {
mdlerror(parse_state, "Non-tetrahedron element found in voxel list object");
return NULL;
}
struct element_connection_list *eclp = CHECKED_MALLOC_STRUCT(
struct element_connection_list, "polygon element commections");
if (eclp == NULL)
return NULL;
eclp->indices = CHECKED_MALLOC_ARRAY(int, 4, "polygon element connections");
if (eclp->indices == NULL) {
free(eclp);
return NULL;
}
eclp->indices[0] = (int)indices->value_head->value;
eclp->indices[1] = (int)indices->value_head->next->value;
eclp->indices[2] = (int)indices->value_head->next->next->value;
eclp->indices[3] = (int)indices->value_tail->value;
eclp->n_verts = indices->value_count;
eclp->next = NULL;
if (!indices->shared)
mcell_free_numeric_list(indices->value_head);
return eclp;
}
/**************************************************************************
mdl_new_polygon_list:
Create a new polygon list object.
In: parse_state: parser state
sym: symbol for this polygon list
n_vertices: count of vertices
vertices: list of vertices
n_connections: count of walls
connections: list of walls
Out: polygon object, or NULL if there was an error
**************************************************************************/
struct geom_object *
mdl_new_polygon_list(struct mdlparse_vars *parse_state, char *obj_name,
int n_vertices, struct vertex_list *vertices,
int n_connections,
struct element_connection_list *connections) {
struct object_creation obj_creation;
obj_creation.object_name_list = parse_state->object_name_list;
obj_creation.object_name_list_end = parse_state->object_name_list_end;
obj_creation.current_object = parse_state->current_object;
if (parse_state->vol->disable_polygon_objects) {
mdlerror(
parse_state,
"When using dynamic geometries, polygon objects should only be "
"defined/instantiated through the dynamic geometry file.");
}
int error_code = 0;
struct geom_object *obj_ptr =
start_object(parse_state->vol, &obj_creation, obj_name, &error_code);
if (error_code == 1) {
mdlerror_fmt(parse_state,"Object '%s' is already defined", obj_name);
}
else if (error_code == 2) {
mdlerror_fmt(parse_state, "Out of memory while creating object: %s",
obj_name);
}
struct polygon_object *poly_obj_ptr =
new_polygon_list(parse_state->vol, obj_ptr, n_vertices, vertices,
n_connections, connections);
parse_state->object_name_list = obj_creation.object_name_list;
parse_state->object_name_list_end = obj_creation.object_name_list_end;
parse_state->current_object = obj_ptr;
parse_state->allow_patches = 0;
parse_state->current_polygon = poly_obj_ptr;
return obj_ptr;
}
/**************************************************************************
mdl_finish_polygon_list:
Finalize the polygon list, cleaning up any state updates that were made
when we started creating the polygon.
In: parse_state: parser state
symp: symbol for the completed polygon
Out: 1 on failure, 0 on success
**************************************************************************/
int mdl_finish_polygon_list(struct mdlparse_vars *parse_state,
struct geom_object *obj_ptr) {
struct object_creation obj_creation;
obj_creation.object_name_list_end = parse_state->object_name_list_end;
int error_code = 0;
if (finish_polygon_list(obj_ptr, &obj_creation)) {
error_code = 1;
}
parse_state->object_name_list_end = obj_creation.object_name_list_end;
parse_state->current_object = parse_state->current_object->parent;
parse_state->current_polygon = NULL;
return error_code;
}
/**************************************************************************
allocate_voxel_object:
Create a new voxel object.
In: Nothing
Out: voxel object, or NULL if allocation fails
**************************************************************************/
static struct voxel_object *allocate_voxel_object() {
struct voxel_object *vop;
if ((vop = CHECKED_MALLOC_STRUCT(struct voxel_object, "voxel list object")) ==
NULL)
return NULL;
vop->vertex = NULL;
vop->element = NULL;
vop->neighbor = NULL;
vop->n_verts = 0;
vop->n_voxels = 0;
return vop;
}
/**************************************************************************
mdl_new_voxel_list:
Create a new voxel list object.
In: parse_state: parser state
sym: the symbol for this voxel list
n_vertices: count of vertices in this object
vertices: list of vertices for this object
n_connections: count of tetrahedra in this object
connections: list of tetrahedra
Out: voxel object, or NULL if there is an error
**************************************************************************/
struct voxel_object *
mdl_new_voxel_list(struct mdlparse_vars *parse_state, struct sym_entry *sym,
int n_vertices, struct vertex_list *vertices,
int n_connections,
struct element_connection_list *connections) {
struct tet_element_data *tedp;
struct geom_object *objp = (struct geom_object *)sym->value;
struct voxel_object *vop = allocate_voxel_object();
if (vop == NULL)
goto failure;
objp->object_type = VOXEL_OBJ;
objp->contents = vop;
vop->n_voxels = n_connections;
vop->n_verts = n_vertices;
/* Allocate vertices */
if ((vop->vertex = CHECKED_MALLOC_ARRAY(
struct vector3, vop->n_verts, "voxel list object vertices")) == NULL)
goto failure;
/* Populate vertices */
for (int i = 0; i < vop->n_verts; i++) {
struct vertex_list *vlp_temp = vertices;
vop->vertex[i].x = vertices->vertex->x;
vop->vertex[i].y = vertices->vertex->y;
vop->vertex[i].z = vertices->vertex->z;
free(vertices->vertex);
vertices = vertices->next;
free(vlp_temp);
}
/* Allocate tetrahedra */
if ((tedp = CHECKED_MALLOC_ARRAY(struct tet_element_data, vop->n_voxels,
"voxel list object tetrahedra")) == NULL)
goto failure;
vop->element = tedp;
/* Copy in tetrahedra */
for (int i = 0; i < vop->n_voxels; i++) {
if (connections->n_verts != 4) {
mdlerror(parse_state, "All voxels must have four vertices.");
goto failure;
}
struct element_connection_list *eclp_temp = connections;
memcpy(tedp[i].vertex_index, connections->indices, 4 * sizeof(int));
connections = connections->next;
free(eclp_temp);
}
return vop;
failure:
free_vertex_list(vertices);
free_connection_list(connections);
if (vop) {
if (vop->element)
free(vop->element);
if (vop->vertex)
free(vop->vertex);
free(vop);
}
return NULL;
}
struct polygon_object *mdl_create_periodic_box(
struct mdlparse_vars *parse_state,
struct vector3 *llf,
struct vector3 *urb,
bool isPeriodicX,
bool isPeriodicY,
bool isPeriodicZ) {
struct polygon_object *pop;
struct region *rp;
const char *name_tmp = "PERIODIC_BOX_OBJ";
int name_len = strlen(name_tmp) + 1;
char *name = (char*)malloc(name_len * sizeof(char));
strcpy(name, name_tmp);
struct sym_entry *sym = mdl_start_object(parse_state, name);
struct geom_object *objp = (struct geom_object *)sym->value;
/* Allocate polygon object */
pop = allocate_polygon_object("box object");
if (pop == NULL) {
free(llf);
free(urb);
return NULL;
}
objp->object_type = BOX_OBJ;
objp->contents = pop;
/* Create object default region on box object: */
if ((rp = mdl_create_region(parse_state, objp, "ALL")) == NULL) {
free(pop);
free(llf);
free(urb);
return NULL;
}
if ((rp->element_list_head = new_element_list(ALL_SIDES, ALL_SIDES)) ==
NULL) {
free(pop);
free(llf);
free(urb);
return NULL;
}
/* Scale corners to internal units */
llf->x *= parse_state->vol->r_length_unit;
llf->y *= parse_state->vol->r_length_unit;
llf->z *= parse_state->vol->r_length_unit;
urb->x *= parse_state->vol->r_length_unit;
urb->y *= parse_state->vol->r_length_unit;
urb->z *= parse_state->vol->r_length_unit;
/* Initialize our subdivided box */
pop->sb = init_cuboid(parse_state, llf, urb);
free(llf);
free(urb);
if (pop->sb == NULL) {
free(pop);
return NULL;
}
// mark box as periodic or not
objp->periodic_x = isPeriodicX;
objp->periodic_y = isPeriodicY;
objp->periodic_z = isPeriodicZ;
parse_state->allow_patches = 1;
parse_state->current_polygon = pop;
mdl_triangulate_box_object(parse_state, sym, parse_state->current_polygon, 0.0);
return pop;
}
int mdl_finish_periodic_box(struct mdlparse_vars *parse_state) {
struct sym_entry *symp = retrieve_sym("PERIODIC_BOX_OBJ", parse_state->vol->obj_sym_table);
if (symp == NULL) {
mcell_error("Cannot create PERIODIC_BOX_OBJ.");
}
struct geom_object *objp = (struct geom_object *)symp->value;
remove_gaps_from_regions(objp);
objp->n_walls = parse_state->current_polygon->n_walls;
objp->n_verts = parse_state->current_polygon->n_verts;
if (check_degenerate_polygon_list(objp)) {
parse_state->current_polygon = NULL;
return 1;
}
parse_state->current_polygon = NULL;
// This next bit is a little strange. We are essentially, creating a meta
// object that contains an instance of the periodic box object. The meta
// object will be added to the root instance, like a user would do with their
// "Scene" or "World" objects.
parse_state->current_object = parse_state->vol->root_instance;
// Create meta object
const char *meta_name_tmp = "PERIODIC_BOX_META";
int meta_name_len = strlen(meta_name_tmp) + 1;
char *meta_name = (char*)malloc(meta_name_len * sizeof(char));
strcpy(meta_name, meta_name_tmp);
struct sym_entry *meta_sym = mdl_start_object(parse_state, meta_name);
struct geom_object *meta_objp = (struct geom_object *)meta_sym->value;
meta_objp->object_type = META_OBJ;
// Create instance of PERIODIC_BOX_OBJECT
const char *inst_name_tmp = "PERIODIC_BOX_INSTANT";
int inst_name_len = strlen(inst_name_tmp) + 1;
char *inst_name = (char*)malloc(inst_name_len * sizeof(char));
strcpy(inst_name, inst_name_tmp);
struct sym_entry *inst_sym = mdl_start_object(parse_state, inst_name);
struct geom_object *inst_objp = (struct geom_object *)inst_sym->value;
mdl_deep_copy_object(parse_state, inst_objp, objp);
// Finish instance object
mdl_finish_object(parse_state);
add_child_objects(meta_objp, inst_objp, inst_objp);
parse_state->vol->periodic_box_obj = inst_objp;
// Finish meta object
mdl_finish_object(parse_state);
add_child_objects(parse_state->vol->root_instance, meta_objp, meta_objp);
parse_state->current_object = parse_state->vol->root_object;
return 0;
}
/**************************************************************************
mdl_new_box_object:
Create a new box object, with particular corners.
In: parse_state: parser state
sym: symbol for this box object
llf: lower left front corner
urb: upper right back corner
Out: polygon object for this box, or NULL if there's an error
**************************************************************************/
struct polygon_object *mdl_new_box_object(struct mdlparse_vars *parse_state,
struct sym_entry *sym,
struct vector3 *llf,
struct vector3 *urb) {
struct polygon_object *pop;
struct region *rp;
struct geom_object *objp = (struct geom_object *)sym->value;
/* Allocate polygon object */
pop = allocate_polygon_object("box object");
if (pop == NULL) {
free(llf);
free(urb);
return NULL;
}
objp->object_type = BOX_OBJ;
objp->contents = pop;
/* Create object default region on box object: */
if ((rp = mdl_create_region(parse_state, objp, "ALL")) == NULL) {
free(pop);
free(llf);
free(urb);
return NULL;
}
if ((rp->element_list_head = new_element_list(ALL_SIDES, ALL_SIDES)) ==
NULL) {
free(pop);
free(llf);
free(urb);
return NULL;
}
/* Scale corners to internal units */
llf->x *= parse_state->vol->r_length_unit;
llf->y *= parse_state->vol->r_length_unit;
llf->z *= parse_state->vol->r_length_unit;
urb->x *= parse_state->vol->r_length_unit;
urb->y *= parse_state->vol->r_length_unit;
urb->z *= parse_state->vol->r_length_unit;
/* Initialize our subdivided box */
pop->sb = init_cuboid(parse_state, llf, urb);
free(llf);
free(urb);
if (pop->sb == NULL) {
free(pop);
return NULL;
}
parse_state->allow_patches = 1;
parse_state->current_polygon = pop;
return pop;
}
/**************************************************************************
mdl_finish_box_object:
Finalize the box object, cleaning up any state updates that were made when
we started creating the box.
In: parse_state: parser state
symp: symbol for the completed box
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_finish_box_object(struct mdlparse_vars *parse_state,
struct sym_entry *symp) {
struct geom_object *objp = (struct geom_object *)symp->value;
remove_gaps_from_regions(objp);
objp->n_walls = parse_state->current_polygon->n_walls;
objp->n_verts = parse_state->current_polygon->n_verts;
if (check_degenerate_polygon_list(objp)) {
parse_state->current_polygon = NULL;
return 1;
}
parse_state->current_polygon = NULL;
return 0;
}
/**************************************************************************
mdl_create_region:
Create a named region on an object.
In: parse_state: parser state
objp: object upon which to create a region
name: region name to create
Out: region object, or NULL if there was an error (region already exists or
allocation failed)
**************************************************************************/
struct region *mdl_create_region(struct mdlparse_vars *parse_state,
struct geom_object *objp, const char *name) {
struct region *rp;
struct region_list *rlp;
no_printf("Creating new region: %s\n", name);
if ((rp = mdl_make_new_region(parse_state, objp->sym->name, name)) == NULL)
return NULL;
if ((rlp = CHECKED_MALLOC_STRUCT(struct region_list, "region list")) ==
NULL) {
mdlerror_fmt(parse_state, "Out of memory while creating object region '%s'",
rp->sym->name);
return NULL;
}
rp->region_last_name = name;
rp->parent = objp;
char *region_name = CHECKED_SPRINTF("%s,%s", objp->sym->name, name);
if (!mcell_check_for_region(region_name, objp)) {
rlp->reg = rp;
rlp->next = objp->regions;
objp->regions = rlp;
objp->num_regions++;
}
else {
free(rlp);
}
free(region_name);
return rp;
}
/**************************************************************************
mdl_get_region:
Get a region on an object, creating it if it does not exist yet.
In: parse_state: parser state
objp: object upon which to create
name: region to get
Out: region, or NULL if allocation fails
**************************************************************************/
struct region *mdl_get_region(struct mdlparse_vars *parse_state,
struct geom_object *objp, const char *name) {
struct sym_entry *reg_sym;
char *region_name;
struct region *rp;
region_name = CHECKED_SPRINTF("%s,%s", objp->sym->name, name);
if (region_name == NULL)
return NULL;
reg_sym = retrieve_sym(region_name, parse_state->vol->reg_sym_table);
free(region_name);
if (reg_sym == NULL)
rp = mdl_create_region(parse_state, objp, name);
else
rp = (struct region *)reg_sym->value;
return rp;
}
/**************************************************************************
mdl_start_existing_obj_region_def:
Begin construction of a region on an existing object.
In: parse_state: parser state
obj_symp: symbol of object upon which to create region
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_start_existing_obj_region_def(struct mdlparse_vars *parse_state,
struct sym_entry *obj_symp) {
struct geom_object *objp = (struct geom_object *)obj_symp->value;
if (objp->object_type != BOX_OBJ && objp->object_type != POLY_OBJ) {
mdlerror_fmt(parse_state, "Cannot define region on non-surface object: %s",
obj_symp->name);
return 1;
}
parse_state->current_polygon = (struct polygon_object*)objp->contents;
parse_state->current_object = objp;
parse_state->allow_patches = 0;
return 0;
}
/**************************************************************************
mdl_add_elements_to_list:
Append an element to an element list.
In: list: list for element
head: first element to add
tail: last element to add
Out: none. list is updated
**************************************************************************/
void mdl_add_elements_to_list(struct element_list_head *list,
struct element_list *head,
struct element_list *tail) {
tail->next = NULL;
list->elml_tail->next = head;
list->elml_tail = tail;
}
/**************************************************************************
mdl_set_elements_to_exclude:
Marks elements as being excluded, rather than included. This is done by
setting the "special" pointer on each element to point to the element
itself. The resultant "special" pointer, then, points to the wrong type of
object, but the pointer itself is used as a signal to the rest of the code.
In: els: elements to set to exclude
Out: none. list is updated
**************************************************************************/
void mdl_set_elements_to_exclude(struct element_list *els) {
/* HACK: els->special actually points to an element_list. Don't dereference
* it now. */
for (; els != NULL; els = els->next)
els->special = (struct element_special *)els;
}
/**************************************************************************
mdl_new_element_side:
Create a new element list for a region description based on a side name.
In: parse_state: parser state
side: side name constant (ALL_SIDES, etc.)
Out: element list, or NULL if allocation fails
**************************************************************************/
struct element_list *mdl_new_element_side(struct mdlparse_vars *parse_state,
unsigned int side) {
unsigned int begin, end;
if (side == ALL_SIDES &&
parse_state->current_object->object_type == POLY_OBJ) {
begin = 0;
end = parse_state->current_polygon->n_walls - 1;
} else if (parse_state->current_object->object_type == POLY_OBJ) {
mdlerror(parse_state,
"Illegal reference to polygon list element by side-name");
return NULL;
} else {
begin = side;
end = side;
}
return new_element_list(begin, end);
}
/**************************************************************************
mdl_new_element_previous_region:
Create a new element list for a "previous region" include/exclude
statement.
In: parse_state: parser state
objp: object containing referent region
rp_container: region for whom we're creating this element list
name_region_referent: name of referent region
exclude: 1 if we're excluding, 0 if including
Out: element list, or NULL if an error occrs
**************************************************************************/
struct element_list *mdl_new_element_previous_region(
struct mdlparse_vars *parse_state, struct geom_object *objp,
struct region *rp_container, char *name_region_referent, int exclude) {
struct sym_entry *stp;
char *full_reg_name = NULL;
struct element_list *elmlp = NULL;
/* Create element list */
elmlp = new_element_list(0, 0);
if (elmlp == NULL)
goto failure;
/* Create "special" element description */
elmlp->special =
CHECKED_MALLOC_STRUCT(struct element_special, "region element");
if (elmlp->special == NULL)
goto failure;
elmlp->special->exclude = (byte)exclude;
/* Create referent region full name */
full_reg_name =
CHECKED_SPRINTF("%s,%s", objp->sym->name, name_region_referent);
if (full_reg_name == NULL)
goto failure;
/* Look up region or die */
stp = retrieve_sym(full_reg_name, parse_state->vol->reg_sym_table);
if (stp == NULL) {
mdlerror_fmt(parse_state, "Undefined region: %s", full_reg_name);
goto failure;
}
free(full_reg_name);
full_reg_name = NULL;
/* Store referent region */
elmlp->special->referent = (struct region *)stp->value;
if (elmlp->special->referent == rp_container) {
mdlerror_fmt(parse_state,
"Self-referential region include. No paradoxes, please.");
goto failure;
}
free(name_region_referent);
return elmlp;
failure:
free(name_region_referent);
if (full_reg_name)
free(full_reg_name);
if (elmlp) {
if (elmlp->special)
free(elmlp->special);
free(elmlp);
}
return NULL;
}
/**************************************************************************
mdl_new_element_patch:
Allocate a new region element list item for an include/exclude PATCH
statement.
In: parse_state: parser state
polygon: polygon upon which we're making a patch
llf: first corner of patch
urb: second corner of patch
exclude: 1 if we're excluding, 0 if including
Out: element list, or NULL if an error occrs
**************************************************************************/
struct element_list *mdl_new_element_patch(struct mdlparse_vars *parse_state,
struct polygon_object *poly,
struct vector3 *llf,
struct vector3 *urb, int exclude) {
if (parse_state->current_object->object_type != BOX_OBJ) {
mdlerror(
parse_state,
"INCLUDE_PATCH and EXCLUDE_PATCH may only be used on a BOX object.");
return NULL;
}
if (!parse_state->allow_patches) {
mdlerror(
parse_state,
"Cannot create PATCH on a BOX outside of the original declaration.");
return NULL;
}
struct element_list *elmlp = new_element_list(0, 0);
if (elmlp == NULL)
goto failure;
/* Allocate special element description */
elmlp->special =
CHECKED_MALLOC_STRUCT(struct element_special, "region element");
if (elmlp->special == NULL)
goto failure;
elmlp->special->referent = NULL;
elmlp->special->exclude = (byte)exclude;
/* Convert to internal units */
llf->x *= parse_state->vol->r_length_unit;
llf->y *= parse_state->vol->r_length_unit;
llf->z *= parse_state->vol->r_length_unit;
urb->x *= parse_state->vol->r_length_unit;
urb->y *= parse_state->vol->r_length_unit;
urb->z *= parse_state->vol->r_length_unit;
memcpy(&(elmlp->special->corner1), llf, sizeof(struct vector3));
memcpy(&(elmlp->special->corner2), urb, sizeof(struct vector3));
/* Refine the cuboid's mesh to accomodate the new patch */
if (refine_cuboid(parse_state, llf, urb, poly->sb,
parse_state->vol->grid_density))
goto failure;
free(llf);
free(urb);
return elmlp;
failure:
free(llf);
free(urb);
if (elmlp) {
free(elmlp->special);
free(elmlp);
}
return NULL;
}
/**************************************************************************
mdl_set_region_elements:
Set the elements for a region, normalizing the region if it's on a polygon
list object.
In: parse_state: parser state
rgn: region to receive elements
elements: elements comprising region
normalize_now: flag indicating whether to normalize right now
Out: symbol for new pathway, or NULL if an error occurred
**************************************************************************/
int mdl_set_region_elements(struct mdlparse_vars *parse_state,
struct region *rgn, struct element_list *elements,
int normalize_now) {
rgn->element_list_head = elements;
if (normalize_now)
return mdl_normalize_elements(parse_state, rgn, 0);
else
return 0;
}
/**************************************************************************
mdl_new_rxn_pathname:
Create a new named reaction pathway name structure.
In: parse_state: parser state
name: name for new named pathway
Out: symbol for new pathway, or NULL if an error occurred
**************************************************************************/
struct sym_entry *mdl_new_rxn_pathname(struct mdlparse_vars *parse_state,
char *name) {
if ((retrieve_sym(name, parse_state->vol->rxpn_sym_table)) != NULL) {
mdlerror_fmt(parse_state, "Named reaction pathway already defined: %s",
name);
free(name);
return NULL;
} else if ((retrieve_sym(name, parse_state->vol->mol_sym_table)) != NULL) {
mdlerror_fmt(parse_state,
"Named reaction pathway already defined as a molecule: %s",
name);
free(name);
return NULL;
}
struct sym_entry *symp =
store_sym(name, RXPN, parse_state->vol->rxpn_sym_table, NULL);
if (symp == NULL) {
mdlerror_fmt(parse_state, "Out of memory while creating reaction name: %s",
name);
free(name);
return NULL;
}
free(name);
return symp;
}
/**************************************************************************
mdl_add_surf_mol_to_region:
Adds an surface molecule (or list of surface molecules) to a region. These
surface molecules will be placed on the surface at initialization time.
In: rgn: the region
lst: a list of surface molecules to place
Out: none. list is merged into region
**************************************************************************/
void mdl_add_surf_mol_to_region(struct region *rgn, struct sm_dat_list *lst) {
lst->sm_tail->next = rgn->sm_dat_head;
rgn->sm_dat_head = lst->sm_head;
}
/**************************************************************************
mdl_set_region_surface_class:
Set the surface class of this region, possibly inheriting the viz_value.
In: parse_state: parser state
rgn: the region
scsymp: symbol for the surface class
Out: none. region is updated.
**************************************************************************/
void mdl_set_region_surface_class(struct mdlparse_vars *parse_state,
struct region *rgn,
struct sym_entry *scsymp) {
if (rgn->surf_class != NULL) {
mdlerror(parse_state, "ATTENTION: region definition allows only one "
"SURFACE_CLASS statement.");
}
rgn->surf_class = (struct species *)scsymp->value;
}
/*************************************************************************
* Reaction output
*************************************************************************/
/**************************************************************************
mdl_new_output_set:
Populate an output set.
In: parse_state: parser state
os: output set
col_head: head of linked list of output columns
file_flags: file creation disposition
outfile_name: file output name
Out: output set, or NULL if an error occurs
**************************************************************************/
struct output_set *mdl_populate_output_set(struct mdlparse_vars *parse_state,
char *comment, int exact_time,
struct output_column *col_head,
int file_flags, char *outfile_name) {
if ((parse_state->count_flags & (TRIGGER_PRESENT | COUNT_PRESENT)) ==
(TRIGGER_PRESENT | COUNT_PRESENT)) {
mdlerror(parse_state,
"Cannot mix TRIGGER and COUNT statements. Use separate files.");
return NULL;
}
struct output_set *os =
mcell_create_new_output_set(comment, exact_time,
col_head, file_flags, outfile_name);
free(outfile_name);
return os;
}
/**************************************************************************
mdl_add_reaction_output_block_to_world:
Construct and add an output block to the world.
In: parse_state: parser state
buffer_size: size of output buffer for this block
otimes: output timing information for this block
osets: output sets for this block
Out: 0 on success, 1 on failure; world is updated with new output block
**************************************************************************/
int mdl_add_reaction_output_block_to_world(struct mdlparse_vars *parse_state,
int buffer_size,
struct output_times_inlist *otimes,
struct output_set_list *osets) {
int return_state = mcell_add_reaction_output_block(
parse_state->vol, osets, buffer_size, otimes);
if (parse_state->header_comment && strcmp(parse_state->header_comment, "")) {
free(parse_state->header_comment);
parse_state->header_comment = NULL;
}
return return_state;
}
/**************************************************************************
mdl_join_oexpr_tree:
Joins two subtrees into a reaction data output expression tree, with a
specified operation.
In: parse_state: parser state
left: left subtree
right: right subtree
oper: specified operation
Out: joined output expression, or NULL if an error occurs
**************************************************************************/
struct output_expression *mdl_join_oexpr_tree(struct mdlparse_vars *parse_state,
struct output_expression *left,
struct output_expression *right,
char oper) {
struct output_expression *joined;
struct output_expression *leaf, *new_oe, *up;
int first_leaf = 1;
joined = NULL;
if (left->oper == ',' && (right == NULL || right->oper == ',')) {
mdlerror(parse_state, "Can't do math on multiple wildcard expressions");
return NULL;
}
if (left->oper != ',' && (right == NULL || right->oper != ',')) {
joined = new_output_expr(parse_state->vol->oexpr_mem);
if (joined == NULL)
return NULL;
joined->left = (void *)left;
joined->right = (void *)right;
joined->oper = oper;
left->up = joined;
if (right != NULL)
right->up = joined;
learn_oexpr_flags(joined);
if (joined->expr_flags & OEXPR_TYPE_CONST)
eval_oexpr_tree(joined, 0);
return joined;
} else if (left->oper == ',') {
for (leaf = first_oexpr_tree(left); leaf != NULL;
leaf = next_oexpr_tree(leaf)) {
if (first_leaf) {
new_oe = right;
first_leaf = 0;
} else if (right != NULL) {
new_oe = dupl_oexpr_tree(right, parse_state->vol->oexpr_mem);
if (new_oe == NULL)
return NULL;
} else
new_oe = NULL;
up = leaf->up;
joined = mdl_join_oexpr_tree(parse_state, leaf, new_oe, oper);
if (joined == NULL)
return NULL;
joined->up = up;
if (leaf == up->left)
up->left = joined;
else
up->right = joined;
if (joined->expr_flags & OEXPR_TYPE_CONST)
eval_oexpr_tree(joined, 0);
learn_oexpr_flags(up);
leaf = joined;
}
return left;
} else /* right->oper==',' */
{
for (leaf = first_oexpr_tree(right); leaf != NULL;
leaf = next_oexpr_tree(leaf)) {
if (first_leaf) {
new_oe = left;
first_leaf = 0;
} else {
new_oe = dupl_oexpr_tree(left, parse_state->vol->oexpr_mem);
if (new_oe == NULL)
return NULL;
}
up = leaf->up;
joined = mdl_join_oexpr_tree(parse_state, new_oe, leaf, oper);
if (joined == NULL)
return NULL;
joined->up = up;
if (leaf == up->left)
up->left = joined;
else
up->right = joined;
if (joined->expr_flags & OEXPR_TYPE_CONST)
eval_oexpr_tree(joined, 0);
learn_oexpr_flags(up);
leaf = joined;
}
return right;
}
return NULL; /* Should never get here */
}
/**************************************************************************
mdl_sum_expression:
Convert an output expression tree into a summation.
In: expr: expression to convert
Out: modified expression
**************************************************************************/
struct output_expression *mdl_sum_oexpr(struct output_expression *expr) {
oexpr_flood_convert(expr, ',', '+');
eval_oexpr_tree(expr, 0);
return expr;
}
/**************************************************************************
mdl_new_oexpr_constant:
Creates a constant output expression for reaction data output.
In: parse_state: parser state
value: the value of the constantj
Out: the output expression, or NULL if allocation fails
**************************************************************************/
struct output_expression *
mdl_new_oexpr_constant(struct mdlparse_vars *parse_state, double value) {
struct output_expression *oe = new_output_expr(parse_state->vol->oexpr_mem);
if (oe == NULL) {
mdlerror(parse_state, "Out of memory creating output expression");
return NULL;
}
oe->expr_flags = OEXPR_TYPE_DBL | OEXPR_TYPE_CONST;
oe->value = value;
oe->oper = '=';
return oe;
}
/**************************************************************************
mdl_count_syntax_periodic_1:
Generates a reaction data output expression from the first count syntax
form (simple molecule, unquoted, no orientation) within a certain
periodic box.
example:
COUNT[foo, region, [periodic_box_x, periodic_box_y, periodic_box_z]]
In: parse_state: parser state
what: symbol representing the molecule type
where: symbol representing the count location (or NULL for WORLD)
periodicBox: what box are we counting in?
hit_spec: what are we counting?
count_flags: is this a count or a trigger?
Out: 0 on success, 1 on failure
**************************************************************************/
struct output_expression *mdl_count_syntax_periodic_1(
struct mdlparse_vars *parse_state,
struct sym_entry *what,
struct sym_entry *where,
struct vector3 *periodicBox,
int hit_spec,
int count_flags) {
if (parse_state->vol->periodic_traditional) {
mdlerror(parse_state, "Counting in virtual periodic boxes is invalid if PERIODIC_TRADITIONAL is TRUE");
}
// cannot combine world counting with periodic box since world means everything
if (where == NULL) {
mdlerror(parse_state, "Invalid combination of WORLD with periodic box counting");
}
byte report_flags = 0;
if (count_flags & TRIGGER_PRESENT)
report_flags |= REPORT_TRIGGER;
if (hit_spec & REPORT_ENCLOSED)
report_flags |= REPORT_ENCLOSED;
if (what->sym_type == MOL) {
if ((hit_spec & REPORT_TYPE_MASK) == REPORT_NOTHING)
report_flags |= REPORT_CONTENTS;
else
report_flags |= (hit_spec & REPORT_TYPE_MASK);
} else {
report_flags |= REPORT_RXNS;
if ((hit_spec & REPORT_TYPE_MASK) != REPORT_NOTHING) {
mdlerror_fmt(parse_state,
"Invalid counting options used with reaction pathway %s",
what->name);
return NULL;
}
}
/* extract image for periodic image we would like to count */
struct periodic_image *img = CHECKED_MALLOC_STRUCT(struct periodic_image,
"periodic image descriptor");
img->x = (int16_t)periodicBox->x;
img->y = (int16_t)periodicBox->y;
img->z = (int16_t)periodicBox->z;
free(periodicBox);
struct output_request *orq;
if ((orq = mcell_new_output_request(parse_state->vol, what, ORIENT_NOT_SET,
where, img, report_flags)) == NULL)
return NULL;
orq->next = parse_state->vol->output_request_head;
parse_state->vol->output_request_head = orq;
return orq->requester;
}
/**************************************************************************
mdl_count_syntax_1:
Generates a reaction data output expression from the first count syntax
form (simple molecule, unquoted, no orientation).
example:
COUNT(foo,WORLD)
In: parse_state: parser state
what: symbol representing the molecule type
where: symbol representing the count location (or NULL for WORLD)
hit_spec: what are we counting?
count_flags: is this a count or a trigger?
Out: 0 on success, 1 on failure
**************************************************************************/
struct output_expression *mdl_count_syntax_1(struct mdlparse_vars *parse_state,
struct sym_entry *what,
struct sym_entry *where,
int hit_spec, int count_flags) {
byte report_flags = 0;
struct output_request *orq;
if (where != NULL && parse_state->vol->periodic_box_obj && !(parse_state->vol->periodic_traditional)) {
mdlerror(parse_state,
"If PERIODIC_TRADITIONAL is FALSE, then you must specify virtual counting box.\n"
"(e.g. COUNT,vm,Scene.box,[1,0,0]).");
}
if (where == NULL) {
report_flags = REPORT_WORLD;
if (hit_spec != REPORT_NOTHING) {
mdlerror(parse_state,
"Invalid combination of WORLD with other counting options");
return NULL;
} else if (count_flags & TRIGGER_PRESENT) {
mdlerror(parse_state, "Invalid combination of WORLD with TRIGGER option");
return NULL;
}
} else
report_flags = 0;
if (count_flags & TRIGGER_PRESENT)
report_flags |= REPORT_TRIGGER;
if (hit_spec & REPORT_ENCLOSED)
report_flags |= REPORT_ENCLOSED;
if (what->sym_type == MOL) {
if ((hit_spec & REPORT_TYPE_MASK) == REPORT_NOTHING)
report_flags |= REPORT_CONTENTS;
else
report_flags |= (hit_spec & REPORT_TYPE_MASK);
} else {
report_flags |= REPORT_RXNS;
if ((hit_spec & REPORT_TYPE_MASK) != REPORT_NOTHING) {
mdlerror_fmt(parse_state,
"Invalid counting options used with reaction pathway %s",
what->name);
return NULL;
}
}
if ((orq = mcell_new_output_request(parse_state->vol, what, ORIENT_NOT_SET,
where, NULL, report_flags)) == NULL)
return NULL;
orq->next = parse_state->vol->output_request_head;
parse_state->vol->output_request_head = orq;
return orq->requester;
}
/**************************************************************************
mdl_count_syntax_periodic_2:
Generates a reaction data output expression from the second count syntax
form (simple molecule, unquoted, orientation in braces) within a certain
periodic box
example:
COUNT[foo{1}, region, [periodic_box_x, periodic_box_y, periodic_box_z]]
In: parse_state: parser state
mol_type: symbol representing the molecule type
orient: orientation specified for the molecule
where: symbol representing the count location (or NULL for WORLD)
periodicBox: what box are we counting in?
hit_spec: what are we counting?
count_flags: is this a count or a trigger?
Out: 0 on success, 1 on failure
**************************************************************************/
struct output_expression *mdl_count_syntax_periodic_2(
struct mdlparse_vars *parse_state,
struct sym_entry *mol_type,
short orient,
struct sym_entry *where,
struct vector3 *periodicBox,
int hit_spec,
int count_flags) {
if (parse_state->vol->periodic_traditional) {
mdlerror(
parse_state,
"Counting in virtual periodic boxes is invalid if PERIODIC_TRADITIONAL "
"is TRUE");
}
// cant combine world counting with periodic box since world means everything
if (where == NULL) {
mdlerror(
parse_state,
"Invalid combination of WORLD with periodic box counting");
}
byte report_flags = 0;
if (count_flags & TRIGGER_PRESENT)
report_flags |= REPORT_TRIGGER;
if (hit_spec & REPORT_ENCLOSED)
report_flags |= REPORT_ENCLOSED;
if ((hit_spec & REPORT_TYPE_MASK) == REPORT_NOTHING)
report_flags |= REPORT_CONTENTS;
else
report_flags |= (hit_spec & REPORT_TYPE_MASK);
/* extract image for periodic image we would like to count */
struct periodic_image *img = CHECKED_MALLOC_STRUCT(struct periodic_image,
"periodic image descriptor");
img->x = (int16_t)periodicBox->x;
img->y = (int16_t)periodicBox->y;
img->z = (int16_t)periodicBox->z;
free(periodicBox);
/* Grab orientation and reset orientation state in parser */
short orientation;
if (orient < 0)
orientation = -1;
else if (orient > 0)
orientation = 1;
else
orientation = 0;
struct output_request *orq;
if ((orq = mcell_new_output_request(parse_state->vol, mol_type, orientation,
where, img, report_flags)) == NULL)
return NULL;
orq->next = parse_state->vol->output_request_head;
parse_state->vol->output_request_head = orq;
return orq->requester;
}
/**************************************************************************
mdl_count_syntax_2:
Generates a reaction data output expression from the second count syntax
form (simple molecule, unquoted, orientation in braces)
example:
COUNT(foo{1},WORLD)
In: parse_state: parser state
mol_type: symbol representing the molecule type
orient: orientation specified for the molecule
where: symbol representing the count location (or NULL for WORLD)
hit_spec: what are we counting?
count_flags: is this a count or a trigger?
Out: 0 on success, 1 on failure
**************************************************************************/
struct output_expression *mdl_count_syntax_2(struct mdlparse_vars *parse_state,
struct sym_entry *mol_type,
short orient,
struct sym_entry *where,
int hit_spec, int count_flags) {
byte report_flags = 0;
struct output_request *orq;
short orientation;
if (where != NULL && parse_state->vol->periodic_box_obj && !(parse_state->vol->periodic_traditional)) {
mdlerror(parse_state,
"If PERIODIC_TRADITIONAL is FALSE, then you must specify virtual counting box.\n"
"(e.g. COUNT,vm,Scene.box,[1,0,0]).");
}
if (where == NULL) {
mdlerror(parse_state, "Counting of an oriented molecule in the WORLD is "
"not implemented.\nAn oriented molecule may only be "
"counted in a regions.");
return NULL;
} else
report_flags = 0;
if (count_flags & TRIGGER_PRESENT)
report_flags |= REPORT_TRIGGER;
if (hit_spec & REPORT_ENCLOSED)
report_flags |= REPORT_ENCLOSED;
if ((hit_spec & REPORT_TYPE_MASK) == REPORT_NOTHING)
report_flags |= REPORT_CONTENTS;
else
report_flags |= (hit_spec & REPORT_TYPE_MASK);
/* Grab orientation and reset orientation state in parser */
if (orient < 0)
orientation = -1;
else if (orient > 0)
orientation = 1;
else
orientation = 0;
if ((orq = mcell_new_output_request(parse_state->vol, mol_type, orientation,
where, NULL, report_flags)) == NULL)
return NULL;
orq->next = parse_state->vol->output_request_head;
parse_state->vol->output_request_head = orq;
return orq->requester;
}
/**************************************************************************
mdl_get_orientation_from_string:
Get the orientation from a molecule name+orientation string, removing the
orientation marks from the string. This only supports the "tick" notation.
In: mol_string: string to parse
Out: the orientation. mol_string has been modified to remove the orientation
part
**************************************************************************/
static int mdl_get_orientation_from_string(char *mol_string) {
short orientation = 0;
int pos = strlen(mol_string) - 1;
if (mol_string[pos] == ';') {
mol_string[pos] = '\0';
return 0;
}
/* Peel off any apostrophes or commas at the end of the string */
while (pos >= 0) {
switch (mol_string[pos]) {
case '\'':
++orientation;
break;
case ',':
--orientation;
break;
default:
mol_string[pos + 1] = '\0';
pos = 0;
break;
}
--pos;
}
if (orientation < 0)
return -1;
else if (orientation > 0)
return 1;
else
return 0;
}
/**************************************************************************
mdl_string_has_orientation:
Check if the string looks like a molecule name+orientation string.
Otherwise, it will be considered a wildcard. This only supports the "tick"
notation.
In: mol_string: string to parse
Out: 1 if the string has orientation, 0 if it does not
**************************************************************************/
static int mdl_string_has_orientation(char const *mol_string) {
char last_char = mol_string[strlen(mol_string) - 1];
return (last_char == '\'' || last_char == ',' || last_char == ';');
}
/*************************************************************************
mdl_new_output_requests_from_list:
Create an output expression from a list that resulted from a wildcard
match. The generated output requests are added to the global linked list
of count output requests.
In: parse_state: parser state
targets: linked list of what to count
location: where are we counting?
report_flags: what do we report
hit_spec: how do we report
Out: an output expression representing the requested targets
*************************************************************************/
static struct output_expression *mdl_new_output_requests_from_list(
struct mdlparse_vars *parse_state,
struct sym_table_list *targets,
struct sym_entry *location,
int report_flags,
int hit_spec,
struct periodic_image *img) {
struct output_expression *oe_head = NULL, *oe_tail = NULL;
struct output_request *or_head = NULL, *or_tail = NULL;
int report_type;
assert(targets != NULL);
for (; targets != NULL; targets = targets->next) {
if (targets->node->sym_type == MOL) {
if ((hit_spec & REPORT_TYPE_MASK) == REPORT_NOTHING)
report_type = REPORT_CONTENTS;
else
report_type = (hit_spec & REPORT_TYPE_MASK);
} else {
report_type = REPORT_RXNS;
if ((hit_spec & REPORT_TYPE_MASK) != REPORT_NOTHING) {
mdlerror_fmt(parse_state,
"Invalid counting options used with reaction pathway %s",
targets->node->name);
return NULL;
}
}
struct output_request *orq = mcell_new_output_request(
parse_state->vol, targets->node, ORIENT_NOT_SET, location, img,
report_type | report_flags);
if (orq == NULL)
return NULL;
struct output_expression *oe = orq->requester;
if (oe_tail == NULL) {
oe_head = oe_tail = oe;
or_head = or_tail = orq;
} else {
or_tail->next = orq;
or_tail = orq;
struct output_expression *oet =
new_output_expr(parse_state->vol->oexpr_mem);
if (oet == NULL) {
mdlerror(parse_state, "Out of memory storing requested counts");
return NULL;
}
if (oe_tail->up == NULL) {
oe_head = oet;
} else {
oet->up = oe_tail->up;
if (oet->up->left == oe_tail)
oet->up->left = oet;
else
oet->up->right = oet;
}
oet->left = oe_tail;
oe_tail->up = oet;
oet->right = oe;
oe->up = oet;
oet->oper = ',';
oet->expr_flags = OEXPR_LEFT_OEXPR | OEXPR_RIGHT_OEXPR |
(oe->expr_flags & OEXPR_TYPE_MASK);
oe_tail = oe;
}
}
or_tail->next = parse_state->vol->output_request_head;
parse_state->vol->output_request_head = or_head;
return oe_head;
}
/**************************************************************************
mdl_find_rxpns_and_mols_by_wildcard:
Find all molecules and named reaction pathways matching a particular
wildcard, and return them in a list.
In: parse_state: parser state
wildcard: the wildcard to match
Out: the symbol list, or NULL if an error occurs.
**************************************************************************/
static struct sym_table_list *
mdl_find_rxpns_and_mols_by_wildcard(struct mdlparse_vars *parse_state,
char const *wildcard) {
struct sym_table_list *symbols = NULL, *stl;
for (int i = 0; i < parse_state->vol->mol_sym_table->n_bins; i++) {
for (struct sym_entry *sym_t = parse_state->vol->mol_sym_table->entries[i];
sym_t != NULL; sym_t = sym_t->next) {
if (is_wildcard_match((char *)wildcard, sym_t->name)) {
stl = (struct sym_table_list *)CHECKED_MEM_GET(
parse_state->sym_list_mem,
"list of named reactions and molecules for counting");
if (stl == NULL) {
if (symbols)
mem_put_list(parse_state->sym_list_mem, symbols);
return NULL;
}
stl->node = sym_t;
stl->next = symbols;
symbols = stl;
}
}
}
for (int i = 0; i < parse_state->vol->rxpn_sym_table->n_bins; i++) {
for (struct sym_entry *sym_t = parse_state->vol->rxpn_sym_table->entries[i];
sym_t != NULL; sym_t = sym_t->next) {
if (is_wildcard_match((char *)wildcard, sym_t->name)) {
stl = (struct sym_table_list *)CHECKED_MEM_GET(
parse_state->sym_list_mem,
"list of named reactions and molecules for counting");
if (stl == NULL) {
if (symbols)
mem_put_list(parse_state->sym_list_mem, symbols);
return NULL;
}
stl->node = sym_t;
stl->next = symbols;
symbols = stl;
}
}
}
if (symbols == NULL)
mdlerror_fmt(
parse_state,
"No molecules or named reactions found matching wildcard \"%s\"",
wildcard);
return symbols;
}
/**************************************************************************
mdl_count_syntax_periodic_3:
Generates a reaction data output expression from the third count syntax
form (quoted string, possibly a wildcard, possibly an oriented molecule)
within a certain periodic box.
examples:
COUNT["foo'", region, [periodic_box_x, periodic_box_y, periodic_box_z]]
COUNT["foo*", region, [periodic_box_x, periodic_box_y, periodic_box_z]]
In: parse_state: parser state
what: string representing the target of this count
orient: orientation specified for the molecule
where: symbol representing the count location (or NULL for WORLD)
hit_spec: what are we counting?
count_flags: is this a count or a trigger?
Out: 0 on success, 1 on failure
**************************************************************************/
struct output_expression *mdl_count_syntax_periodic_3(
struct mdlparse_vars *parse_state,
char *what,
struct sym_entry *where,
struct vector3 *periodicBox,
int hit_spec,
int count_flags) {
if (parse_state->vol->periodic_traditional) {
mdlerror(
parse_state,
"Counting in virtual periodic boxes is invalid if PERIODIC_TRADITIONAL "
"is TRUE");
}
// cant combine world counting with periodic box since world means everything
if (where == NULL) {
mdlerror(
parse_state,
"Invalid combination of WORLD with periodic box counting");
}
byte report_flags = 0;
if (count_flags & TRIGGER_PRESENT)
report_flags |= REPORT_TRIGGER;
if (hit_spec & REPORT_ENCLOSED)
report_flags |= REPORT_ENCLOSED;
/* extract image for periodic image we would like to count */
struct periodic_image *img = CHECKED_MALLOC_STRUCT(struct periodic_image,
"periodic image descriptor");
img->x = (int16_t)periodicBox->x;
img->y = (int16_t)periodicBox->y;
img->z = (int16_t)periodicBox->z;
free(periodicBox);
struct output_expression *oe;
char *what_to_count;
if ((what_to_count = mdl_strip_quotes(what)) == NULL)
return NULL;
/* Oriented molecule specified inside a string */
if (mdl_string_has_orientation(what_to_count)) {
struct output_request *orq;
struct sym_entry *sp;
short orientation;
if (where == NULL) {
mdlerror(parse_state, "Counting of an oriented molecule in the WORLD is "
"not implemented.\nAn oriented molecule may only "
"be counted in a region.");
free(img);
free(what_to_count);
return NULL;
}
orientation = mdl_get_orientation_from_string(what_to_count);
if ((sp = mdl_existing_molecule(parse_state, what_to_count)) == NULL)
return NULL;
what_to_count = NULL;
if ((hit_spec & REPORT_TYPE_MASK) == REPORT_NOTHING)
report_flags |= REPORT_CONTENTS;
else
report_flags |= (hit_spec & REPORT_TYPE_MASK);
if ((orq = mcell_new_output_request(parse_state->vol, sp, orientation,
where, img, report_flags)) == NULL)
return NULL;
orq->next = parse_state->vol->output_request_head;
parse_state->vol->output_request_head = orq;
oe = orq->requester;
}
/* Wildcard specified inside a string */
else {
struct sym_table_list *stl =
mdl_find_rxpns_and_mols_by_wildcard(parse_state, what_to_count);
if (stl == NULL) {
mdlerror(parse_state,
"Wildcard matching found no matches for count output.");
free(img);
free(what_to_count);
return NULL;
}
if (where == NULL) {
report_flags |= REPORT_WORLD;
if (hit_spec != REPORT_NOTHING) {
mdlerror(parse_state,
"Invalid combination of WORLD with other counting options");
free(img);
free(what_to_count);
return NULL;
} else if (count_flags & TRIGGER_PRESENT) {
mdlerror(parse_state,
"Invalid combination of WORLD with TRIGGER option");
free(img);
free(what_to_count);
return NULL;
}
}
if ((oe = mdl_new_output_requests_from_list(
parse_state, stl, where, report_flags, hit_spec, img)) == NULL) {
free(img);
free(what_to_count);
return NULL;
}
/* free allocated memory */
mem_put_list(parse_state->sym_list_mem, stl);
}
free(what_to_count);
return oe;
}
/**************************************************************************
mdl_count_syntax_3:
Generates a reaction data output expression from the third count syntax
form (quoted string, possibly a wildcard, possibly an oriented molecule).
examples:
COUNT("Ca_*",WORLD)
COUNT("AChR'",WORLD)
In: parse_state: parser state
what: string representing the target of this count
orient: orientation specified for the molecule
where: symbol representing the count location (or NULL for WORLD)
hit_spec: what are we counting?
count_flags: is this a count or a trigger?
Out: 0 on success, 1 on failure
**************************************************************************/
struct output_expression *mdl_count_syntax_3(struct mdlparse_vars *parse_state,
char *what,
struct sym_entry *where,
int hit_spec, int count_flags) {
struct output_expression *oe;
char *what_to_count;
byte report_flags = 0;
if (where != NULL && parse_state->vol->periodic_box_obj && !(parse_state->vol->periodic_traditional)) {
mdlerror(parse_state,
"If PERIODIC_TRADITIONAL is FALSE, then you must specify virtual counting box.\n"
"(e.g. COUNT,vm,Scene.box,[1,0,0]).");
}
if ((what_to_count = mdl_strip_quotes(what)) == NULL)
return NULL;
if (count_flags & TRIGGER_PRESENT)
report_flags |= REPORT_TRIGGER;
if (hit_spec & REPORT_ENCLOSED)
report_flags |= REPORT_ENCLOSED;
/* Oriented molecule specified inside a string */
if (mdl_string_has_orientation(what_to_count)) {
struct output_request *orq;
struct sym_entry *sp;
short orientation;
if (where == NULL) {
mdlerror(parse_state, "Counting of an oriented molecule in the WORLD is "
"not implemented.\nAn oriented molecule may only "
"be counted in a regions.");
free(what_to_count);
return NULL;
}
orientation = mdl_get_orientation_from_string(what_to_count);
if ((sp = mdl_existing_molecule(parse_state, what_to_count)) == NULL)
return NULL;
if ((hit_spec & REPORT_TYPE_MASK) == REPORT_NOTHING)
report_flags |= REPORT_CONTENTS;
else
report_flags |= (hit_spec & REPORT_TYPE_MASK);
if ((orq = mcell_new_output_request(parse_state->vol, sp, orientation,
where, NULL, report_flags)) == NULL)
return NULL;
orq->next = parse_state->vol->output_request_head;
parse_state->vol->output_request_head = orq;
oe = orq->requester;
}
/* Wildcard specified inside a string */
else {
struct sym_table_list *stl =
mdl_find_rxpns_and_mols_by_wildcard(parse_state, what_to_count);
if (stl == NULL) {
mdlerror(parse_state,
"Wildcard matching found no matches for count output.");
free(what_to_count);
return NULL;
}
if (where == NULL) {
report_flags |= REPORT_WORLD;
if (hit_spec != REPORT_NOTHING) {
mdlerror(parse_state,
"Invalid combination of WORLD with other counting options");
free(what_to_count);
return NULL;
} else if (count_flags & TRIGGER_PRESENT) {
mdlerror(parse_state,
"Invalid combination of WORLD with TRIGGER option");
free(what_to_count);
return NULL;
}
}
if ((oe = mdl_new_output_requests_from_list(
parse_state, stl, where, report_flags, hit_spec, NULL)) == NULL) {
free(what_to_count);
return NULL;
}
free(what_to_count);
/* free allocated memory */
mem_put_list(parse_state->sym_list_mem, stl);
}
return oe;
}
/**************************************************************************
mdl_single_count_expr:
Prepare a single count expression for inclusion in an output set.
In: parse_state: parser state
list: list to receive output columns
expr: the expression whose columns to add
custom_header: custom header for this column
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_single_count_expr(struct mdlparse_vars *parse_state,
struct output_column_list *list,
struct output_expression *expr, char *custom_header) {
if (expr->oper == ',' && custom_header != NULL) {
mdlerror(parse_state,
"Cannot use custom column headers with wildcard expansion");
return 1;
}
return mcell_prepare_single_count_expr(list, expr, custom_header);
}
/*************************************************************************
* VIZ output
*************************************************************************/
/**************************************************************************
mdl_new_viz_output_block:
Build a new VIZ output block, containing parameters for an output set for
visualization.
In: parse_state: parser state
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_new_viz_output_block(struct mdlparse_vars *parse_state) {
struct viz_output_block *vizblk = CHECKED_MALLOC_STRUCT(
struct viz_output_block, "visualization data output parameters");
if (vizblk == NULL)
return 1;
mcell_new_viz_output_block(vizblk);
vizblk->next = parse_state->vol->viz_blocks;
parse_state->vol->viz_blocks = vizblk;
return 0;
}
/**************************************************************************
mdl_set_viz_mode:
Set the mode for a new VIZ output block.
In: vizblk: the viz block to check
mode: the mode to set
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_set_viz_mode(struct viz_output_block *vizblk, int mode) {
vizblk->viz_mode = (enum viz_mode_t)mode;
return 0;
}
/**************************************************************************
mdl_set_viz_filename_prefix:
Set the filename prefix for a new VIZ output block.
In: parse_state: parser state
vizblk: the viz block to check
filename: the filename
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_set_viz_filename_prefix(struct mdlparse_vars *parse_state,
struct viz_output_block *vizblk,
char *filename) {
if (vizblk->viz_mode == NO_VIZ_MODE)
return 0;
if (vizblk->file_prefix_name != NULL) {
mdlerror_fmt(parse_state,
"FILENAME may only appear once per output block.");
free(filename);
return 1;
}
vizblk->file_prefix_name = filename;
return 0;
}
/**************************************************************************
mdl_viz_state:
Sets a flag on all of the listed objects, requesting that they be
visualized.
In: parse_state: parser state
target: destination for the viz state
value: the raw (floating point!) value
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_viz_state(struct mdlparse_vars *parse_state, int *target,
double value) {
/* Disallow out-of-range values. */
if (value + 0.001 < (double)EXCLUDE_OBJ ||
value - 0.001 > (double)INCLUDE_OBJ) {
mdlerror(parse_state, "Visualization state is out of range "
"(must be between -(2^31 - 1) and (2^31 - 2).");
return 1;
}
/* Round to integer. */
int int_value;
if (value < 0.0)
int_value = (int)(value - 0.001);
else
int_value = (int)(value + 0.001);
/* Disallow "special" values. */
if (int_value == EXCLUDE_OBJ || int_value == INCLUDE_OBJ) {
mdlerror(parse_state, "Visualization states of -(2^31) and (2^31) - 1 "
"are reserved for MCell's internal bookkeeping.");
return 1;
}
*target = int_value;
return 0;
}
/**************************************************************************
mdl_set_viz_include_molecules:
Sets a flag on all of the listed species, requesting that they be
visualized.
In: parse_state: parser state
vizblk: the viz block to check
list: the list of symbols
viz_state: the desired viz state
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_set_viz_include_molecules(struct mdlparse_vars *parse_state,
struct viz_output_block *vizblk,
struct sym_table_list *list, int viz_state) {
if (vizblk->viz_mode == NO_VIZ_MODE)
return 0;
/* Mark all specified molecules */
struct sym_table_list *stl;
for (stl = list; stl != NULL; stl = stl->next) {
struct species *specp = (struct species *)stl->node->value;
if (mcell_set_molecule_viz_state(vizblk, specp, viz_state))
return 1;
}
/* free allocated memory */
mem_put_list(parse_state->sym_list_mem, list);
return 0;
}
/**************************************************************************
mdl_set_viz_include_all_molecules:
Sets a flag on a viz block, requesting that all species be visualized.
In: vizblk: the viz block to check
viz_state: the desired viz state
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_set_viz_include_all_molecules(struct viz_output_block *vizblk,
int viz_state) {
if (vizblk->viz_mode == NO_VIZ_MODE)
return 0;
if (viz_state == INCLUDE_OBJ &&
(vizblk->viz_output_flag & VIZ_ALL_MOLECULES)) {
/* Do nothing - we will not override the old value if we have no specific
* state value.
*/
} else
vizblk->default_mol_state = viz_state;
vizblk->viz_output_flag |= VIZ_ALL_MOLECULES;
return 0;
}
/**************************************************************************
mdl_create_viz_mol_frames:
Create one or more molecule frames for output in the visualization.
In: parse_state: parser state
time_type: either OUTPUT_BY_TIME_LIST or OUTPUT_BY_ITERATION_LIST
type: the type (MOL_POS, MOL_ORIENT, etc.)
viz_mode: visualization mode
times: list of iterations/times at which to output
Out: the frame_data_list object, if successful, or NULL if we ran out of memory
**************************************************************************/
static struct frame_data_list *
mdl_create_viz_mol_frames(struct mdlparse_vars *parse_state, int time_type,
int type, int viz_mode,
struct num_expr_list_head *times) {
struct frame_data_list *frames = NULL;
struct frame_data_list *new_frame;
struct num_expr_list *times_sorted;
if (times->shared) {
times_sorted = mcell_copysort_numeric_list(times->value_head);
if (times_sorted == NULL)
return NULL;
} else {
mcell_sort_numeric_list(times->value_head);
times_sorted = times->value_head;
}
if (type == MOL_POS || type == ALL_MOL_DATA) {
if ((new_frame = mcell_create_viz_frame(time_type, type, times_sorted)) ==
NULL)
return NULL;
new_frame->next = frames;
frames = new_frame;
} else if (viz_mode == NO_VIZ_MODE) {
/* Create viz frames consistent with other visualization modes */
if ((new_frame = mcell_create_viz_frame(time_type, type, times_sorted)) ==
NULL)
return NULL;
new_frame->next = frames;
frames = new_frame;
} else {
mdlerror_fmt(parse_state,
"This type of molecule output data (%d) is not valid "
"for the selected VIZ output mode (%d).",
type, viz_mode);
return NULL;
}
return frames;
}
/**************************************************************************
mdl_new_viz_mol_frames:
Adds some new molecule output frames to a list.
In: parse_state: parser state
vizblk: the viz block to check
frames: list to receive frames
time_type: timing type (OUTPUT_BY_TIME_LIST or ...ITERATION_LIST)
mol_item_type: MOLECULE_POSITIONS, etc.
timelist: list of times in appropriate units (as per time_type)
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_new_viz_mol_frames(struct mdlparse_vars *parse_state,
struct viz_output_block *vizblk,
struct frame_data_list_head *frames, int time_type,
int mol_item_type,
struct num_expr_list_head *timelist) {
frames->frame_head = frames->frame_tail = NULL;
// if (vizblk->viz_mode == NO_VIZ_MODE)
// return 0;
struct frame_data_list *fdlp;
fdlp = mdl_create_viz_mol_frames(parse_state, time_type, mol_item_type,
vizblk->viz_mode, timelist);
if (!fdlp)
return 1;
frames->frame_head = fdlp;
while (fdlp->next != NULL)
fdlp = fdlp->next;
frames->frame_tail = fdlp;
return 0;
}
/**************************************************************************
mdl_new_viz_all_times:
Build a list of times for VIZ output, one timepoint per iteration in the
simulation.
In: parse_state: parser state
list: location to receive timepoint list
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_new_viz_all_times(struct mdlparse_vars *parse_state,
struct num_expr_list_head *list) {
long long step;
list->value_head = NULL;
list->value_tail = NULL;
list->value_count = 0;
list->shared = 0;
for (step = 0; step <= parse_state->vol->iterations; step++) {
struct num_expr_list *nel;
nel = CHECKED_MALLOC_STRUCT(struct num_expr_list, "VIZ_OUTPUT time point");
if (nel == NULL)
return 1;
++list->value_count;
if (list->value_tail)
list->value_tail = list->value_tail->next = nel;
else
list->value_head = list->value_tail = nel;
list->value_tail->value = step * parse_state->vol->time_unit;
list->value_tail->next = NULL;
}
return 0;
}
/**************************************************************************
mdl_new_viz_all_iterations:
Build a list of iterations for VIZ output, one for each iteration in the
simulation.
In: parse_state: parser state
list: location to receive iteration list
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_new_viz_all_iterations(struct mdlparse_vars *parse_state,
struct num_expr_list_head *list) {
list->value_head = NULL;
list->value_tail = NULL;
list->value_count = 0;
list->shared = 0;
for (long long step = 0; step <= parse_state->vol->iterations; step++) {
struct num_expr_list *nel;
nel = CHECKED_MALLOC_STRUCT(struct num_expr_list, "VIZ_OUTPUT iteration");
if (nel == NULL)
return 1;
++list->value_count;
if (list->value_tail)
list->value_tail = list->value_tail->next = nel;
else
list->value_head = list->value_tail = nel;
list->value_tail->value = step;
list->value_tail->next = NULL;
}
return 0;
}
/*************************************************************************
* Volume output
*************************************************************************/
/*************************************************************************
species_list_to_array:
Convert a pointer list into an array. The list count will be stored into
the count pointer, if it is not NULL.
In: lh: list head
count: location to receive list item count
Out: array of pointers to species in list, or NULL if allocation fails, or if
the list is empty. If NULL is returned and the count field has a
non-zero value, no error has occurred.
*************************************************************************/
static struct species **species_list_to_array(struct species_list *lh,
int *count) {
struct species **arr = NULL, **ptr = NULL;
struct species_list_item *i;
if (count != NULL)
*count = lh->species_count;
if (lh->species_count == 0)
return NULL;
arr = CHECKED_MALLOC_ARRAY(struct species *, lh->species_count,
"species array");
if (arr) {
for (i = (struct species_list_item *)lh->species_head, ptr = arr; i != NULL;
i = i->next)
*ptr++ = i->spec;
}
return arr;
}
/**************************************************************************
mdl_new_volume_output_item:
Create a new volume output request.
In: parse_state: parser state
filename_prefix: filename prefix for all files produced from this request
molecules: list of molecules to output
location: lower, left, front corner of output box
voxel_size: dimensions of each voxel
voxel_count: counts of voxels in x, y, and z directions
ot: output times for this request
Out: volume output item, or NULL if an error occurred
**************************************************************************/
struct volume_output_item *mdl_new_volume_output_item(
struct mdlparse_vars *parse_state, char *filename_prefix,
struct species_list *molecules, struct vector3 *location,
struct vector3 *voxel_size, struct vector3 *voxel_count,
struct output_times *ot) {
struct volume_output_item *vo =
CHECKED_MALLOC_STRUCT(struct volume_output_item, "volume output request");
if (vo == NULL) {
free(filename_prefix);
mem_put_list(parse_state->species_list_mem, molecules->species_head);
free(location);
free(voxel_size);
free(voxel_count);
if (ot->times != NULL)
free(ot->times);
mem_put(parse_state->output_times_mem, ot);
return NULL;
}
memset(vo, 0, sizeof(struct volume_output_item));
vo->filename_prefix = filename_prefix;
vo->molecules = species_list_to_array(molecules, &vo->num_molecules);
if (vo->num_molecules != 0 && vo->molecules == NULL) {
free(filename_prefix);
mem_put_list(parse_state->species_list_mem, molecules->species_head);
free(location);
free(voxel_size);
free(voxel_count);
if (ot->times != NULL)
free(ot->times);
mem_put(parse_state->output_times_mem, ot);
free(vo);
return NULL;
}
qsort(vo->molecules, vo->num_molecules, sizeof(void *), &void_ptr_compare);
mem_put_list(parse_state->species_list_mem, molecules->species_head);
memcpy(&vo->location, location, sizeof(struct vector3));
free(location);
vo->location.x *= parse_state->vol->r_length_unit;
vo->location.y *= parse_state->vol->r_length_unit;
vo->location.z *= parse_state->vol->r_length_unit;
memcpy(&vo->voxel_size, voxel_size, sizeof(struct vector3));
free(voxel_size);
vo->voxel_size.x *= parse_state->vol->r_length_unit;
vo->voxel_size.y *= parse_state->vol->r_length_unit;
vo->voxel_size.z *= parse_state->vol->r_length_unit;
vo->nvoxels_x = (int)(voxel_count->x + 0.5);
vo->nvoxels_y = (int)(voxel_count->y + 0.5);
vo->nvoxels_z = (int)(voxel_count->z + 0.5);
free(voxel_count);
vo->timer_type = ot->timer_type;
vo->step_time = ot->step_time;
vo->num_times = ot->num_times;
vo->times = ot->times;
mem_put(parse_state->output_times_mem, ot);
if (vo->timer_type == OUTPUT_BY_ITERATION_LIST ||
vo->timer_type == OUTPUT_BY_TIME_LIST)
vo->next_time = vo->times;
else
vo->next_time = NULL;
switch (parse_state->vol->notify->volume_output_report) {
case NOTIFY_NONE:
break;
case NOTIFY_BRIEF:
mcell_log("Added volume output item '%s', counting in the region "
"[%.15g,%.15g,%.15g]-[%.15g,%.15g,%.15g]",
vo->filename_prefix,
vo->location.x * parse_state->vol->length_unit,
vo->location.y * parse_state->vol->length_unit,
vo->location.z * parse_state->vol->length_unit,
(vo->location.x + vo->voxel_size.x * vo->nvoxels_x) *
parse_state->vol->length_unit,
(vo->location.y + vo->voxel_size.x * vo->nvoxels_x) *
parse_state->vol->length_unit,
(vo->location.z + vo->voxel_size.x * vo->nvoxels_x) *
parse_state->vol->length_unit);
break;
case NOTIFY_FULL:
mcell_log("Added volume output item '%s', counting the following molecules "
"in the region [%.15g,%.15g,%.15g]-[%.15g,%.15g,%.15g]:\n",
vo->filename_prefix,
vo->location.x * parse_state->vol->length_unit,
vo->location.y * parse_state->vol->length_unit,
vo->location.z * parse_state->vol->length_unit,
(vo->location.x + vo->voxel_size.x * vo->nvoxels_x) *
parse_state->vol->length_unit,
(vo->location.y + vo->voxel_size.x * vo->nvoxels_x) *
parse_state->vol->length_unit,
(vo->location.z + vo->voxel_size.x * vo->nvoxels_x) *
parse_state->vol->length_unit);
for (int i = 0; i < vo->num_molecules; ++i)
mcell_log(" %s", vo->molecules[i]->sym->name);
break;
default:
UNHANDLED_CASE(parse_state->vol->notify->volume_output_report);
}
return vo;
}
/**************************************************************************
mdl_new_output_times_default:
Create new default output timing for volume output.
In: parse_state: parser state
Out: output times structure, or NULL if allocation fails
**************************************************************************/
struct output_times *
mdl_new_output_times_default(struct mdlparse_vars *parse_state) {
struct output_times *ot = (struct output_times *)CHECKED_MEM_GET(parse_state->output_times_mem,
"output times for volume output");
if (ot == NULL)
return NULL;
memset(ot, 0, sizeof(struct output_times));
ot->timer_type = OUTPUT_BY_STEP;
ot->step_time = parse_state->vol->time_unit;
return ot;
}
/**************************************************************************
mdl_new_output_times_step:
Create new "step" output timing for volume output.
In: parse_state: parser state
step: time step for volume output
Out: output times structure, or NULL if allocation fails
XXX: This is really similar to set_reaction_output_timer_step in
mcell_react_out.c. Consolidate these.
**************************************************************************/
struct output_times *
mdl_new_output_times_step(struct mdlparse_vars *parse_state, double step) {
long long output_freq;
struct output_times *ot = (struct output_times *)CHECKED_MEM_GET(parse_state->output_times_mem,
"output times for volume output");
if (ot == NULL)
return NULL;
memset(ot, 0, sizeof(struct output_times));
ot->timer_type = OUTPUT_BY_STEP;
ot->step_time = step;
/* Clip step_time to a reasonable range */
output_freq = ot->step_time / parse_state->vol->time_unit;
if (output_freq > parse_state->vol->iterations && output_freq > 1) {
output_freq =
(parse_state->vol->iterations > 1) ? parse_state->vol->iterations : 1;
ot->step_time = output_freq * parse_state->vol->time_unit;
if (parse_state->vol->notify->invalid_output_step_time != WARN_COPE)
mdl_warning(parse_state, "Output step time too long\n\tSetting output "
"step time to %g microseconds\n",
ot->step_time * 1.0e6);
} else if (output_freq < 1) {
ot->step_time = parse_state->vol->time_unit;
if (parse_state->vol->notify->invalid_output_step_time != WARN_COPE)
mdl_warning(parse_state, "Output step time too short\n\tSetting output "
"step time to %g microseconds\n",
ot->step_time * 1.0e6);
}
return ot;
}
/**************************************************************************
mdl_new_output_times_iterations:
Create new "iteration list" output timing for volume output.
In: parse_state: parser state
iters: iterations on which to give volume output
Out: output times structure, or NULL if allocation fails
**************************************************************************/
struct output_times *
mdl_new_output_times_iterations(struct mdlparse_vars *parse_state,
struct num_expr_list_head *iters) {
struct output_times *ot = (struct output_times *)CHECKED_MEM_GET(parse_state->output_times_mem,
"output times for volume output");
if (ot == NULL) {
if (!iters->shared)
mcell_free_numeric_list(iters->value_head);
return NULL;
}
memset(ot, 0, sizeof(struct output_times));
ot->timer_type = OUTPUT_BY_ITERATION_LIST;
ot->times = num_expr_list_to_array(iters, &ot->num_times);
if (ot->times != NULL)
qsort(ot->times, ot->num_times, sizeof(double), &double_cmp);
if (!iters->shared)
mcell_free_numeric_list(iters->value_head);
if (ot->num_times != 0 && ot->times == NULL) {
mem_put(parse_state->output_times_mem, ot);
return NULL;
}
return ot;
}
/**************************************************************************
mdl_new_output_times_time:
Create new "time list" output timing for volume output.
In: parse_state: parser state
times: simulation times at which to give volume output
Out: output times structure, or NULL if allocation fails
**************************************************************************/
struct output_times *
mdl_new_output_times_time(struct mdlparse_vars *parse_state,
struct num_expr_list_head *times) {
struct output_times *ot = (struct output_times *)CHECKED_MEM_GET(parse_state->output_times_mem,
"output times for volume output");
if (ot == NULL) {
if (!times->shared)
mcell_free_numeric_list(times->value_head);
return NULL;
}
memset(ot, 0, sizeof(struct output_times));
ot->timer_type = OUTPUT_BY_TIME_LIST;
ot->times = num_expr_list_to_array(times, &ot->num_times);
if (ot->times != NULL)
qsort(ot->times, ot->num_times, sizeof(double), &double_cmp);
if (!times->shared)
mcell_free_numeric_list(times->value_head);
if (ot->num_times != 0 && ot->times == NULL) {
mem_put(parse_state->output_times_mem, ot);
return NULL;
}
return ot;
}
/****************************************************************
* Release patterns
***************************************************************/
/**************************************************************************
mdl_new_release_pattern:
Create a new release pattern. There must not yet be a release pattern with
the given name.
In: parse_state: parser state
name: name for the new release pattern
Out: symbol of the release pattern, or NULL if an error occurred
**************************************************************************/
struct sym_entry *mdl_new_release_pattern(struct mdlparse_vars *parse_state,
char *name) {
struct sym_entry *st;
if (retrieve_sym(name, parse_state->vol->rpat_sym_table) != NULL) {
mdlerror_fmt(parse_state, "Release pattern already defined: %s", name);
free(name);
return NULL;
} else if ((st = store_sym(name, RPAT, parse_state->vol->rpat_sym_table,
NULL)) == NULL) {
mdlerror_fmt(parse_state,
"Out of memory while creating release pattern: %s", name);
free(name);
return NULL;
}
free(name);
return st;
}
/**************************************************************************
mdl_set_release_pattern:
Fill in the details of a release pattern.
In: parse_state: parser state
rpat_sym: symbol for the release pattern
rpat_data: data to fill in for release pattern
Out: 0 on succes, 1 on failure.
**************************************************************************/
int mdl_set_release_pattern(struct mdlparse_vars *parse_state,
struct sym_entry *rpat_sym,
struct release_pattern *rpat_data) {
struct release_pattern *rpatp = (struct release_pattern *)rpat_sym->value;
if (rpat_data->release_interval <= 0) {
mdlerror(parse_state, "Release interval must be set to a positive number.");
return 1;
}
if (rpat_data->train_interval <= 0) {
mdlerror(parse_state, "Train interval must be set to a positive number.");
return 1;
}
if (rpat_data->train_duration > rpat_data->train_interval) {
mdlerror(parse_state,
"Train duration must not be longer than the train interval.");
return 1;
}
if (rpat_data->train_duration <= 0) {
mdlerror(parse_state, "Train duration must be set to a positive number.");
return 1;
}
/* Copy in release pattern */
rpatp->delay = rpat_data->delay;
rpatp->release_interval = rpat_data->release_interval;
rpatp->train_interval = rpat_data->train_interval;
rpatp->train_duration = rpat_data->train_duration;
rpatp->number_of_trains = rpat_data->number_of_trains;
no_printf("Release pattern %s defined:\n", rpat_sym->name);
no_printf("\tdelay = %f\n", rpatp->delay);
no_printf("\trelease_interval = %f\n", rpatp->release_interval);
no_printf("\ttrain_interval = %f\n", rpatp->train_interval);
no_printf("\ttrain_duration = %f\n", rpatp->train_duration);
no_printf("\tnumber_of_trains = %d\n", rpatp->number_of_trains);
return 0;
}
/****************************************************************
* Molecules
***************************************************************/
/**************************************************************************
mdl_new_mol_species:
Create a new species. There must not yet be a molecule or named reaction
pathway with the supplied name.
In: parse_state: parser state
name: name for the new species
Out: symbol for the species, or NULL if an error occurred
**************************************************************************/
struct sym_entry *mdl_new_mol_species(struct mdlparse_vars *parse_state,
char *name) {
struct sym_entry *sym = NULL;
if (retrieve_sym(name, parse_state->vol->mol_sym_table) != NULL) {
mdlerror_fmt(parse_state, "Molecule already defined: %s", name);
free(name);
return NULL;
} else if (retrieve_sym(name, parse_state->vol->rxpn_sym_table) != NULL) {
mdlerror_fmt(parse_state,
"Molecule already defined as a named reaction pathway: %s",
name);
free(name);
return NULL;
} else if ((sym = store_sym(name, MOL, parse_state->vol->mol_sym_table,
NULL)) == NULL) {
mdlerror_fmt(parse_state, "Out of memory while creating molecule: %s",
name);
free(name);
return NULL;
}
free(name);
return sym;
}
/**************************************************************************
mdl_create_species:
Assemble a molecule species from its component pieces.
In: parse_state: parser state
name: name of the molecule
D: diffusion constant
is_2d: 1 if the species is a 2D molecule, 0 if 3D
custom_time_step: time_step for the molec (< 0.0 for a custom space step,
>0.0 for custom timestep, 0.0 for default timestep)
target_only: 1 if the molecule cannot initiate reactions
max_step_length:
Out: Nothing. The molecule is created.
**************************************************************************/
struct mcell_species_spec *mdl_create_species(struct mdlparse_vars *parse_state,
char *name, double D, int is_2d,
double custom_time_step,
int target_only,
double max_step_length,
int external_species) {
// Can't define molecule before we have a time step.
// Move this to mcell_create_species?
double global_time_unit = parse_state->vol->time_unit;
if (!distinguishable(global_time_unit, 0, EPS_C)) {
mdlerror_fmt(parse_state,
"TIME_STEP not yet specified. Cannot define molecule: %s",
name);
}
struct mcell_species_spec *species =
CHECKED_MALLOC_STRUCT(struct mcell_species_spec, "struct mcell_species");
species->name = name;
species->D = D;
species->is_2d = is_2d;
species->custom_time_step = custom_time_step;
species->target_only = target_only;
species->max_step_length = max_step_length;
species->external_species = external_species;
int error_code = mcell_create_species(parse_state->vol, species, NULL);
switch (error_code) {
case 2:
mdlerror_fmt(parse_state, "Molecule already defined: %s", name);
break;
case 3:
mdlerror_fmt(parse_state,
"Molecule already defined as a named reaction pathway: %s",
name);
break;
case 4:
mdlerror_fmt(parse_state, "Out of memory while creating molecule: %s",
name);
break;
case 5:
mdlerror(parse_state,
"Out of memory while creating r_step data for molecule");
break;
case 6:
mdlerror(parse_state, "Cannot store r_step_surface data.");
break;
case 7:
mdlerror(parse_state,
"Out of memory while creating d_step data for molecule");
break;
case 8:
mdlerror(parse_state, "Internal error: bad number of default "
"RADIAL_DIRECTIONS (max 131072).");
break;
}
return species;
}
/****************************************************************
* BNGL Molecules with Spatial Structure
***************************************************************/
/**************************************************************************
mdl_new_bngl_molecule:
Create a new BNGL molecule symbol. There must not yet be a BNGL molecule
with the supplied name.
In: parse_state: parser state
name: name for the new species
Out: symbol for the BNGL molecule, or NULL if an error occurred
**************************************************************************/
struct sym_entry *mdl_new_bngl_molecule(struct mdlparse_vars *parse_state,
char *name)
{
struct sym_entry *sym = NULL;
if (retrieve_sym(name, parse_state->vol->mol_ss_sym_table) != NULL) {
mdlerror_fmt(parse_state, "BNGL Molecule already defined: %s", name);
free(name);
return NULL;
} else if ((sym = store_sym(name, MOL_SS, parse_state->vol->mol_ss_sym_table,
NULL)) == NULL) {
mdlerror_fmt(parse_state, "Out of memory while creating molecule: %s",
name);
free(name);
return NULL;
}
free(name);
return sym;
}
/**************************************************************************
mdl_add_bngl_component:
Create a new BNGL component symbol. There must not yet be a BNGL component
with the supplied name associated with the BNGL molecule.
In: parse_state: parser state
bngl_mol_sym: ptr to symbol entry for a BNGL molecule
component_name: name for the new component to associate with the BNGL molecule
Out: pointer to the new BNGL component, or NULL if an error occurred
**************************************************************************/
struct mol_comp_ss *mdl_add_bngl_component(struct mdlparse_vars *parse_state,
struct sym_entry *bngl_mol_sym,
char *component_name)
{
struct mol_ss *mol_ssp = NULL;
struct mol_comp_ss *mol_comp_ssp = NULL;
/*
struct sym_entry *sym = NULL;
if (retrieve_sym(component_name, ((struct mol_ss *)(bngl_mol_sym->value))->mol_comp_ss_sym_table) != NULL) {
mdlerror_fmt(parse_state, "BNGL Molecule component already defined: %s(%s)", bngl_mol_sym->name, component_name);
free(component_name);
return NULL;
} else if ((sym = store_sym(component_name, MOL_COMP_SS, ((struct mol_ss *)(bngl_mol_sym->value))->mol_comp_ss_sym_table, NULL)) == NULL) {
mdlerror_fmt(parse_state, "Out of memory while creating BNGL molecule component: %s(%s)", bngl_mol_sym->name, component_name);
*/
mol_comp_ssp = CHECKED_MALLOC_STRUCT(struct mol_comp_ss, "BNGL molecule component");
if (mol_comp_ssp != NULL) {
mol_comp_ssp->name = component_name;
mol_ssp = (struct mol_ss *)bngl_mol_sym->value;
if (mol_ssp->mol_comp_ss_head == NULL) {
mol_ssp->mol_comp_ss_head = mol_comp_ssp;
mol_ssp->mol_comp_ss_tail = mol_comp_ssp;
}
else {
mol_ssp->mol_comp_ss_tail->next = mol_comp_ssp;
}
mol_ssp->mol_comp_ss_tail = mol_comp_ssp;
mol_comp_ssp->next = NULL;
}
return mol_comp_ssp;
}
/**************************************************************************
mdl_set_bngl_component_layout:
Set the transfomation matrix of a BNGL component.
In: parse_state: parser state
mol_comp_ssp: ptr to the BNGL component
loc_x: x location of the component
loc_y: y location of the component
loc_z: z location of the component
rot_axis_x: x part of rotation axis of the component
rot_axis_y: y part of rotation axis of the component
rot_axis_z: z part of rotation axis of the component
rot_angle: angle of rotation about the rotation axis for the component
**************************************************************************/
void mdl_set_bngl_component_layout(struct mdlparse_vars *parse_state,
struct mol_comp_ss *mol_comp_ssp,
double loc_x,
double loc_y,
double loc_z,
double rot_axis_x,
double rot_axis_y,
double rot_axis_z,
double rot_angle)
{
init_matrix(mol_comp_ssp->t_matrix);
if ((rot_axis_x == 0.0) && (rot_axis_y == 0.0) && (rot_axis_z == 0.0)) {
if ((loc_x == 0.0) && (loc_y == 0.0) && (loc_z == 0.0) && (rot_angle == 0.0)) {
mol_comp_ssp->spatial_type=COINCIDENT;
}
else if ((rot_angle != 0.0)) {
mol_comp_ssp->spatial_type=XYZA;
}
else {
mol_comp_ssp->spatial_type=XYZ;
}
}
else {
mol_comp_ssp->spatial_type=XYZVA;
}
mol_comp_ssp->loc_x = loc_x;
mol_comp_ssp->loc_y = loc_y;
mol_comp_ssp->loc_z = loc_z;
mol_comp_ssp->rot_axis_x = rot_axis_x;
mol_comp_ssp->rot_axis_y = rot_axis_y;
mol_comp_ssp->rot_axis_z = rot_axis_z;
mol_comp_ssp->rot_angle = rot_angle;
/*
struct vector3 scale, translate, axis;
double (*tm)[4];
tm = mol_comp_ssp->t_matrix;
scale.x = 1.0;
scale.y = 1.0;
scale.z = 1.0;
translate.x = loc_x;
translate.y = loc_y;
translate.z = loc_z;
axis.x = rot_axis_x;
axis.y = rot_axis_y;
axis.z = rot_axis_z;
tform_matrix(&scale, &translate, &axis, rot_angle, tm);
*/
}
/****************************************************************
* Reactions, surface classes
***************************************************************/
/**************************************************************************
mdl_valid_rate:
Check whether the reaction rate is valid.
In: parse_state: parser state
rate: the unidirectional (either forward or reverse) reaction rate
Out: 0 if valid, 1 if not
**************************************************************************/
int mdl_valid_rate(struct mdlparse_vars *parse_state,
struct reaction_rate *rate) {
if (rate->rate_type == RATE_UNSET) {
mdlerror_fmt(parse_state,
"File %s, Line %d: Internal error: Rate is not set", __FILE__,
__LINE__);
return 1;
} else if (rate->rate_type == RATE_CONSTANT) {
if (rate->v.rate_constant < 0.0) {
if (parse_state->vol->notify->neg_reaction == WARN_ERROR) {
mdlerror(parse_state,
"reaction rate constants should be zero or positive.");
return 1;
} else if (parse_state->vol->notify->neg_reaction == WARN_WARN) {
mcell_warn("negative reaction rate constant %f; setting to zero and "
"continuing.", rate->v.rate_constant);
rate->v.rate_constant = 0.0;
}
}
} else if (rate->rate_type == RATE_FILE) {
if (rate->v.rate_file == NULL) {
mdlerror_fmt(parse_state,
"File %s, Line %d: Internal error: Rate filename is not set",
__FILE__, __LINE__);
return 1;
}
}
return 0;
}
/**************************************************************************
mdl_new_reaction_player:
Create a new reaction player from a species with optional orientation.
In: parse_state: parser state
spec: species with optional orientation
Out: reaction player, or NULL if allocation failed
**************************************************************************/
static struct mcell_species *
mdl_new_reaction_player(struct mdlparse_vars *parse_state,
struct mcell_species *spec) {
struct mcell_species *new_spec;
if ((new_spec = (struct mcell_species *)CHECKED_MEM_GET(
parse_state->mol_data_list_mem, "molecule type")) == NULL)
return NULL;
*new_spec = *spec;
new_spec->next = NULL;
return new_spec;
}
/**************************************************************************
mdl_reaction_player_singleton:
Set the reactant/product list to contain a single item.
In: parse_state: parser state
list: list to receive player
spec: species with optional orientation
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_reaction_player_singleton(struct mdlparse_vars *parse_state,
struct mcell_species_list *list,
struct mcell_species *spec) {
struct mcell_species *player = mdl_new_reaction_player(parse_state, spec);
if (player == NULL)
return 1;
list->mol_type_head = list->mol_type_tail = player;
return 0;
}
/**************************************************************************
mdl_add_reaction_player:
Add a single item to a reactant/product player list.
In: parse_state: parser state
list: list to receive player
spec: species with optional orientation
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_add_reaction_player(struct mdlparse_vars *parse_state,
struct mcell_species_list *list,
struct mcell_species *spec) {
struct mcell_species *player = mdl_new_reaction_player(parse_state, spec);
if (player == NULL)
return 1;
list->mol_type_tail->next = player;
list->mol_type_tail = player;
return 0;
}
/**************************************************************************
mdl_reaction_rate_from_var:
Set a reaction rate from a variable.
In: parse_state: parser state
rate: reaction rate struct
symp: pointer to symbol for reaction rate
Out: 0 on success, 1 on failure
**************************************************************************/
int mdl_reaction_rate_from_var(struct mdlparse_vars *parse_state,
struct reaction_rate *rate,
struct sym_entry *symp) {
switch (symp->sym_type) {
case DBL:
rate->rate_type = RATE_CONSTANT;
rate->v.rate_constant = *(double *)symp->value;
break;
case STR:
rate->rate_type = RATE_FILE;
if ((rate->v.rate_file = mdl_strdup((char *)symp->value)) == NULL)
return 1;
break;
default:
mdlerror(parse_state, "Invalid variable used for reaction rate: must be a "
"number or a filename");
return 1;
}
return 0;
}
/**************************************************************************
mdl_assemble_reaction:
Assemble a standard reaction from its component parts.
In: parse_state: parser state
reactants: list of reactants
surface_class: optional surface class
react_arrow: reaction arrow (uni, bi, catalytic, etc)
products: list of products
rates: forward/reverse reaction rates
pathname: name reaction pathway name, or NULL
Out: the reaction, or NULL if an error occurred
**************************************************************************/
struct mdlparse_vars *mdl_assemble_reaction(struct mdlparse_vars *parse_state,
struct mcell_species *reactants,
struct mcell_species *surface_class,
struct reaction_arrow *react_arrow,
struct mcell_species *products,
struct reaction_rates *rate,
struct sym_entry *pathname) {
char *forward_rate_filename = NULL;
char *backward_rate_filename = NULL;
if (rate->forward_rate.rate_type == RATE_FILE) {
forward_rate_filename =
mcell_find_include_file(rate->forward_rate.v.rate_file,
parse_state->vol->curr_file);
}
if (rate->backward_rate.rate_type == RATE_FILE) {
backward_rate_filename =
mcell_find_include_file(rate->backward_rate.v.rate_file,
parse_state->vol->curr_file);
}
struct volume *state = parse_state->vol;
if (mcell_add_reaction(state->notify,
&state->r_step_release,
state->rxn_sym_table,
state->radial_subdivisions,
state->vacancy_search_dist2,
reactants, react_arrow, surface_class, products,
pathname, rate, forward_rate_filename,
backward_rate_filename)) {
return NULL;
}
return parse_state;
}
/**************************************************************************
mdl_assemble_surface_reaction:
Assemble a surface reaction from its component parts.
In: parse_state: parser state
reaction_type: RFLCT, TRANSP, or SINK
surface_class: surface class
reactant_sym: symbol for reactant molecule
orient: orientation
Out: the reaction, or NULL if an error occurred
**************************************************************************/
struct mdlparse_vars *
mdl_assemble_surface_reaction(struct mdlparse_vars *parse_state,
int reaction_type, struct species *surface_class,
struct sym_entry *reactant_sym, short orient) {
if (mcell_add_surface_reaction(parse_state->vol->rxn_sym_table, reaction_type,
surface_class, reactant_sym, orient)) {
return NULL;
}
return parse_state;
}
/**************************************************************************
mdl_assemble_clamp_reaction:
Assemble a concentration or flux clamp reaction from its component parts.
In: parse_state: parser state
surface_class: surface class
mol_sym: symbol for molecule being clamped
orient: orientation
clamp_type: clamp concentration or flux
clamp_value: desired concentration or flux
Out: the reaction, or NULL if an error occurred
**************************************************************************/
struct mdlparse_vars *mdl_assemble_clamp_reaction(
struct mdlparse_vars *parse_state, struct species *surface_class,
struct sym_entry *mol_sym, short orient, int clamp_type,
double clamp_value) {
if (mcell_add_clamp(parse_state->vol->rxn_sym_table, surface_class,
mol_sym, orient, clamp_type, clamp_value)) {
return NULL;
}
return parse_state;
}
/**************************************************************************
mdl_start_surface_class:
Start a surface class declaration.
SIDE EFFECT: sets current_surface_class in the parser state
In: parse_state: parser state
symp: symbol for the surface class
Out: 0 on success, 1 on failure
**************************************************************************/
void mdl_start_surface_class(struct mdlparse_vars *parse_state,
struct sym_entry *symp) {
struct species *specp = (struct species *)symp->value;
specp->flags = IS_SURFACE;
specp->refl_mols = NULL;
specp->transp_mols = NULL;
specp->absorb_mols = NULL;
specp->clamp_mols = NULL;
parse_state->current_surface_class = specp;
}
/**************************************************************************
mdl_finish_surface_class:
Finish a surface class declaration. Undoes side effects from
mdl_start_surface_class.
In: parse_state: parser state
Out: 0 on success, 1 on failure
**************************************************************************/
void mdl_finish_surface_class(struct mdlparse_vars *parse_state) {
parse_state->current_surface_class = NULL;
}
/**************************************************************************
mdl_new_surf_mol_data:
Create a new surface molecule data for surface molecule initialization.
In: parse_state: parser state
sm_info:
quant: the amount of surface molecules to release
Out: 0 on success, 1 on failure
**************************************************************************/
struct sm_dat *mdl_new_surf_mol_data(struct mdlparse_vars *parse_state,
struct mcell_species *sm_info,
double quant) {
struct sm_dat *smdp;
struct species *specp = (struct species *)sm_info->mol_type->value;
if (!(specp->flags & ON_GRID)) {
mdlerror_fmt(parse_state,
"Cannot initialize surface with non-surface molecule '%s'",
specp->sym->name);
return NULL;
} else if (mdl_check_valid_molecule_release(parse_state, sm_info)) {
return NULL;
}
if ((smdp = CHECKED_MALLOC_STRUCT(struct sm_dat, "surface molecule data")) ==
NULL)
return NULL;
smdp->next = NULL;
smdp->sm = specp;
smdp->quantity_type = 0;
smdp->quantity = quant;
smdp->orientation = sm_info->orient;
return smdp;
}
/**********************************************************************
*** helper functions for release sites creation
**********************************************************************/
/**************************************************************************
add_release_single_molecule_to_list:
Adds a release molecule descriptor to a list.
In: list: the list
mol: the descriptor
Out: none. list is updated
**************************************************************************/
void
add_release_single_molecule_to_list(struct release_single_molecule_list *list,
struct release_single_molecule *mol) {
list->rsm_tail = list->rsm_tail->next = mol;
++list->rsm_count;
}
/**************************************************************************
release_single_molecule_singleton:
Populates a list with a single LIST release molecule descriptor.
In: list: the list
mol: the descriptor
Out: none. list is updated
**************************************************************************/
void
release_single_molecule_singleton(struct release_single_molecule_list *list,
struct release_single_molecule *mol) {
list->rsm_tail = list->rsm_head = mol;
list->rsm_count = 1;
}
/**************************************************************************
set_release_site_density:
Set a release quantity from this release site based on a fixed
density within the release-site's area. (Hopefully we're talking about a
surface release here.)
In: rel_site_obj_ptr: the release site
dens: density for release
Out: 0 on success, 1 on failure. release site object is updated
**************************************************************************/
int set_release_site_density(struct release_site_obj *rel_site_obj_ptr,
double dens) {
rel_site_obj_ptr->release_number_method = DENSITYNUM;
rel_site_obj_ptr->concentration = dens;
return 0;
}
/**************************************************************************
set_release_site_volume_dependent_number:
Set a release quantity from this release site based on a fixed
concentration in a sphere of a gaussian-distributed diameter with a
particular mean and std. deviation.
In: rel_site_obj_ptr: the release site
mean: mean value of distribution of diameters
stdev: std. dev. of distribution of diameters
conc: concentration for release
Out: none. release site object is updated
**************************************************************************/
void set_release_site_volume_dependent_number(
struct release_site_obj *rel_site_obj_ptr, double mean, double stdev,
double conc) {
rel_site_obj_ptr->release_number_method = VOLNUM;
rel_site_obj_ptr->mean_diameter = mean;
rel_site_obj_ptr->standard_deviation = stdev;
rel_site_obj_ptr->concentration = conc;
}
/*************************************************************************
transform_translate:
Apply a translation to the given transformation matrix.
In: state: system state
mat: transformation matrix
xlat: translation vector
Out: translation is right-multiplied into the transformation matrix
*************************************************************************/
void transform_translate(MCELL_STATE *state, double (*mat)[4],
struct vector3 *xlat) {
double tm[4][4];
struct vector3 scaled_xlat = *xlat;
scaled_xlat.x *= state->r_length_unit;
scaled_xlat.y *= state->r_length_unit;
scaled_xlat.z *= state->r_length_unit;
init_matrix(tm);
translate_matrix(tm, tm, &scaled_xlat);
mult_matrix(mat, tm, mat, 4, 4, 4);
free(xlat);
}
/*************************************************************************
transform_scale:
Apply a scale to the given transformation matrix.
In: mat: transformation matrix
scale: scale vector
Out: scale is right-multiplied into the transformation matrix
*************************************************************************/
void transform_scale(double (*mat)[4], struct vector3 *scale) {
double tm[4][4];
init_matrix(tm);
scale_matrix(tm, tm, scale);
mult_matrix(mat, tm, mat, 4, 4, 4);
free(scale);
}
/*************************************************************************
transform_rotate:
Apply a rotation to the given transformation matrix.
In: mat: transformation matrix
axis: axis of rotation
angle: angle of rotation (degrees!)
Out: 0 on success, 1 on failure; rotation is right-multiplied into the
transformation matrix
*************************************************************************/
int transform_rotate(double (*mat)[4], struct vector3 *axis, double angle) {
double tm[4][4];
if (!distinguishable(vect_length(axis), 0.0, EPS_C)) {
return 1;
}
init_matrix(tm);
rotate_matrix(tm, tm, axis, angle);
mult_matrix(mat, tm, mat, 4, 4, 4);
return 0;
}
/*******************************************************************************
*
* check_release_regions makes sure that all regions used in release objects
* correspond to properly instantiated objects.
*
*******************************************************************************/
void check_regions(struct geom_object *rootInstance, struct geom_object *child) {
while (child != NULL) {
for (struct geom_object *fc = child->first_child; fc != NULL; fc = fc->next) {
if (fc->object_type == REL_SITE_OBJ) {
struct release_site_obj *rel =
(struct release_site_obj *)(fc->contents);
if (rel->region_data != NULL) {
struct release_evaluator *eval = rel->region_data->expression;
if (check_release_regions(eval, fc, rootInstance)) {
mcell_error("Release object %s contains at least one uninstantiated"
"region.",
fc->sym->name);
}
}
}
}
child = child->next;
}
}
/**************************************************************************
finish_polygon_list:
Finalize the polygon list, cleaning up any state updates that were made
when we started creating the polygon.
In: obj_ptr: contains information about the object (name, etc)
obj_creation: information about object being created
Out: 1 on failure, 0 on success
NOTE: This function call might be too low-level for what we want from the API,
but it is needed to create polygon objects for now.
**************************************************************************/
int finish_polygon_list(struct geom_object *obj_ptr,
struct object_creation *obj_creation) {
pop_object_name(obj_creation);
remove_gaps_from_regions(obj_ptr);
// no_printf(" n_verts = %d\n", mpvp->current_polygon->n_verts);
// no_printf(" n_walls = %d\n", mpvp->current_polygon->n_walls);
if (check_degenerate_polygon_list(obj_ptr)) {
return 1;
}
return 0;
}
/*************************************************************************
start_object:
Create a new object, adding it to the global symbol table. The object must
not be defined yet. The qualified name of the object will be built by
adding to the object_name_list, and the object is made the "current_object"
in the mdl parser state. Because of these side effects, it is vital to call
finish_object at the end of the scope of the object created here.
In: state: the simulation state
obj_creation: information about object being created
name: unqualified object name
Out: the newly created object
NOTE: This is very similar to mdl_start_object, but there is no parse state.
*************************************************************************/
struct geom_object *start_object(MCELL_STATE *state,
struct object_creation *obj_creation,
char *name,
int *error_code) {
// Create new fully qualified name.
char *new_name;
if ((new_name = push_object_name(obj_creation, name)) == NULL) {
free(name);
return NULL;
}
struct dyngeom_parse_vars *dg_parse = state->dg_parse;
// Create the symbol, if it doesn't exist yet.
struct geom_object *obj_ptr = make_new_object(
dg_parse,
state->obj_sym_table,
new_name,
error_code);
if (*error_code == 1) {
return NULL;
}
obj_ptr->last_name = name;
no_printf("Creating new object: %s\n", new_name);
// Set parent object, make this object "current".
obj_ptr->parent = obj_creation->current_object;
return obj_ptr;
}
/***********************************************************************
*
* parse the model's mdl files and update our global state
*
***********************************************************************/
int parse_input(struct volume *world) {
// Parse the MDL file:
no_printf("Node %d parsing MDL file %s\n", world->procnum,
world->mdl_infile_name);
if (mdlparse_init(world)) {
return (1);
}
no_printf("Done parsing MDL file: %s\n", world->mdl_infile_name);
// we do not want to count collisions if the policy is not to print
if (world->notify->final_summary == NOTIFY_NONE)
world->notify->molecule_collision_report = NOTIFY_NONE;
if (world->iterations == INT_MIN) {
mcell_error_nodie(
"Total number of iterations is not specified either "
"through the ITERATIONS keyword or through the command line option "
"'-iterations'.");
return 1;
}
return 0;
}
| C |
3D | mcellteam/mcell | src/logging.h | .h | 4,762 | 143 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include <stdarg.h>
#include <stdio.h>
#include "config.h"
#ifdef _MSC_VER
#define NORETURN
#else
#define NORETURN __attribute__((noreturn))
#endif
#ifdef DEBUG
#define no_printf(fmt, ...) printf(fmt, ##__VA_ARGS__)
#else
#define no_printf(fmt, ...) \
do { /* do nothing */ \
} while (0)
#ifdef printf
#undef printf
#endif
#define printf(fmt, ...) DO_NOT_USE_PRINTF(fmt, ##__VA_ARGS__)
#endif
#define UNHANDLED_CASE(v) \
mcell_internal_error("Unhandled case in switch statement (%d).", v)
/* Get the log file. */
FILE *mcell_get_log_file(void);
/* Get the error file. */
FILE *mcell_get_error_file(void);
/* Set the log file. */
void mcell_set_log_file(FILE *f);
/* Set the error file. */
void mcell_set_error_file(FILE *f);
/********************************************************
* Raw I/O to log and error streams
********************************************************/
/* Log a message. */
void mcell_log_raw(char const *fmt, ...);
/* Log a message (va_list version). */
void mcell_logv_raw(char const *fmt, va_list args);
/* Log a message. */
void mcell_error_raw(char const *fmt, ...);
/* Log a message (va_list version). */
void mcell_errorv_raw(char const *fmt, va_list args);
/********************************************************
* Standard I/O to log and error streams -- may add standard prefix/suffix to
* lines, may add newlines, etc. May terminate program execution.
********************************************************/
/* Log a message. */
void mcell_log(char const *fmt, ...);
/* Log a message (va_list version). */
void mcell_logv(char const *fmt, va_list args);
/* Log a warning. */
void mcell_warn(char const *fmt, ...);
/* Log a warning (va_list version). */
void mcell_warnv(char const *fmt, va_list args);
/* Log an error and carry on. */
void mcell_error_nodie(char const *fmt, ...);
/* Log an error and carry on (va_list version). */
void mcell_errorv_nodie(char const *fmt, va_list args);
/* Log an error and exit. */
void mcell_error(char const *fmt, ...) NORETURN;
/* Log an error and exit (va_list version). */
void mcell_errorv(char const *fmt, va_list args) NORETURN;
/* Log an internal error and exit. */
#define mcell_internal_error(fmt, ...) \
mcell_internal_error_(__FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
void mcell_internal_error_(char const *file, unsigned int line,
char const *func, char const *fmt, ...) NORETURN;
/* Log an internal error and exit (va_list version). */
#define mcell_internal_errorv(fmt, args) \
mcell_internal_errorv_(__FILE__, __LINE__, __func__, fmt, args)
void mcell_internal_errorv_(char const *file, unsigned int line,
char const *func, char const *fmt, va_list args) NORETURN;
/* Get a copy of a string giving an error message. */
char *mcell_strerror(int err);
/* Log an error due to a failed standard library call, but do not exit. */
void mcell_perror_nodie(int err, char const *fmt, ...);
/* Log an error due to a failed standard library call, but do not exit (va_list
* version). */
void mcell_perrorv_nodie(int err, char const *fmt, va_list args);
/* Log an error due to a failed standard library call, and exit. */
void mcell_perror(int err, char const *fmt, ...) NORETURN;
/* Log an error due to a failed standard library call, and exit (va_list
* version). */
void mcell_perrorv(int err, char const *fmt, va_list args) NORETURN;
/* Log an error due to failed memory allocation, but do not exit. */
void mcell_allocfailed_nodie(char const *fmt, ...);
/* Log an error due to failed memory allocation, but do not exit (va_list
* version). */
void mcell_allocfailedv_nodie(char const *fmt, va_list args);
/* Log an error due to failed memory allocation, and exit. */
void mcell_allocfailed(char const *fmt, ...) NORETURN;
/* Log an error due to failed memory allocation, and exit (va_list version). */
void mcell_allocfailedv(char const *fmt, va_list args) NORETURN;
/* Terminate program execution due to an error. */
void mcell_die(void) NORETURN;
| Unknown |
3D | mcellteam/mcell | src/diffuse.h | .h | 5,439 | 122 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
#define MULTISTEP_WORTHWHILE 2
#define MULTISTEP_PERCENTILE 0.99
#define MULTISTEP_FRACTION 0.9
#define MAX_UNI_TIMESKIP 100000
struct vector3* reflect_periodic_2D(
struct volume *state,
int index_edge_was_hit,
struct vector2 *origin_uv,
struct wall *curr_wall,
struct vector2 *disp_uv,
struct vector2 *boundary_uv,
struct vector3 *origin_xyz);
void pick_displacement(struct vector3 *v, double scale, struct rng_state *rng);
void pick_2D_displacement(struct vector2 *v, double scale,
struct rng_state *rng);
void pick_release_displacement(struct vector3 *in_disk, struct vector3 *away,
double scale, double *r_step_release,
double *d_step, u_int radial_subdivisions,
int directions_mask, u_int num_directions,
double rx_radius_3d, struct rng_state *rng);
void pick_clamped_displacement(struct vector3 *v, struct volume_molecule *m,
double *r_step_surfce, struct rng_state *rng,
u_int radial_subdivision);
struct wall *ray_trace_2D(struct volume *world, struct surface_molecule *sm,
struct vector2 *disp, struct vector2 *loc,
int *kill_me, struct rxn **rxp,
struct hit_data **hd_info);
struct collision *ray_trace(struct volume *world, struct vector3 *init_pos,
struct collision *c, struct subvolume *sv,
struct vector3 *v, struct wall *reflectee);
struct sp_collision *ray_trace_trimol(struct volume *world,
struct volume_molecule *m,
struct sp_collision *c,
struct subvolume *sv, struct vector3 *v,
struct wall *reflectee,
double walk_start_time);
struct volume_molecule *diffuse_3D(struct volume *world,
struct volume_molecule *m, double max_time);
struct volume_molecule *diffuse_3D_big_list(struct volume *world,
struct volume_molecule *m,
double max_time);
struct surface_molecule *diffuse_2D(struct volume *world,
struct surface_molecule *sm,
double max_time, double *advance_time);
struct surface_molecule *react_2D(struct volume *world,
struct surface_molecule *sm, double t,
enum notify_level_t molecule_collision_report,
int grid_grid_reaction_flag,
long long *surf_surf_colls);
struct surface_molecule *
react_2D_all_neighbors(struct volume *world, struct surface_molecule *sm,
double t, enum notify_level_t molecule_collision_report,
int grid_grid_reaction_flag, long long *surf_surf_colls);
struct surface_molecule *react_2D_trimol_all_neighbors(
struct volume *world, struct surface_molecule *sm, double t,
enum notify_level_t molecule_collision_report,
enum notify_level_t final_summary, int grid_grid_reaction_flag,
long long *surf_surf_colls);
void clean_up_old_molecules(struct storage *local);
void reschedule_surface_molecules(
struct volume *state, struct storage *local, struct abstract_molecule *am);
void run_timestep(struct volume *world, struct storage *local,
double release_time, double checkpt_time);
void run_clamp(struct volume *world, double t_now);
struct sp_collision *expand_collision_partner_list_for_neighbor(
struct subvolume *sv, struct volume_molecule *m, struct vector3 *mv,
struct subvolume *new_sv, struct vector3 *path_llf,
struct vector3 *path_urb, struct sp_collision *shead1, double trim_x,
double trim_y, double trim_z, double *x_fineparts, double *y_fineparts,
double *z_fineparts, int rx_hashsize, struct rxn **reaction_hash);
double safe_diffusion_step(struct volume_molecule *m, struct collision *shead,
u_int radial_subdivisions, double *r_step,
double *x_fineparts, double *y_fineparts,
double *z_fineparts);
double exact_disk(struct volume *world, struct vector3 *loc, struct vector3 *mv,
double R, struct subvolume *sv,
struct volume_molecule *moving,
struct volume_molecule *target, int use_expanded_list,
double *x_fineparts, double *y_fineparts,
double *z_fineparts);
bool periodicbox_in_surfmol_list(
struct periodic_image *periodic_box,
struct surface_molecule_list *sml);
| Unknown |
3D | mcellteam/mcell | src/bng_util.cpp | .cpp | 5,120 | 225 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "bng_util.h"
#include "debug_config.h"
#include <vector>
#include <cassert>
#include <map>
using namespace std;
struct Node {
bool is_mol; // not component
string name;
string state; // for component
string compartment; // for molecule
vector<size_t> connections;
};
// used in set to represent edges
// copied from rxn_rule.xpp
class UnorderedPair {
public:
UnorderedPair(const int a, const int b) : first(std::min(a,b)), second(std::max(a,b)) {
}
bool operator == (const UnorderedPair& b) const {
return first == b.first && second == b.second;
}
bool operator < (const UnorderedPair& b) const {
if (first < b.first) {
return true;
}
else if (first == b.first) {
return second < b.second;
}
else {
return false;
}
}
int first;
int second;
};
static Node convert_node_str(const string& s) {
assert(s.size() > 0);
Node res;
if (s[0] == 'c') {
res.is_mol = false;
}
else if (s[0] == 'm') {
res.is_mol = true;
}
else {
assert(false);
}
if (!res.is_mol) {
// component
size_t tilde = s.find('~');
assert(tilde != string::npos);
res.name = s.substr(2, tilde - 2);
size_t excl = s.find('!');
assert(excl != string::npos); // component must be connected
res.state = s.substr(tilde + 1, excl - (tilde + 1));
if (res.state == "NO_STATE") {
res.state = "";
}
}
else {
// molecule
size_t at = s.find('@');
res.name = s.substr(2, at - 2);
size_t excl = s.find('!');
if (excl == string::npos) {
excl = s.size();
}
res.compartment = s.substr(at + 1, excl - (at + 1));
if (res.compartment == "NOCOMPARTMENT") {
res.compartment = "";
}
}
// connections
size_t excl = s.find('!');
if (excl != string::npos) {
size_t pos = excl + 1;
do {
excl = s.find('!', pos);
if (excl == string::npos) {
excl = s.size();
}
string num = s.substr(pos, excl - pos);
res.connections.push_back(stoi(num));
pos = excl + 1;
} while (excl != s.size());
}
return res;
}
static void graph_pattern_to_nodes(const string pat, vector<Node>& nodes) {
size_t pos = 0;
size_t comma_or_end;
do {
comma_or_end = pat.find(',', pos);
if (comma_or_end == string::npos) {
comma_or_end = pat.size();
}
if (comma_or_end == string::npos) {
comma_or_end = pat.size();
}
string node_str = pat.substr(pos, comma_or_end - pos);
Node n = convert_node_str(node_str);
nodes.push_back(n);
pos = comma_or_end;
pos++;
} while (comma_or_end != pat.size() && pos != pat.size());
}
static std::string nodes_to_bngl(const vector<Node>& nodes) {
string res;
map<UnorderedPair, int> bonds;
for (size_t mol_index = 0; mol_index < nodes.size(); mol_index++) {
const Node& mol = nodes[mol_index];
if (mol.is_mol) {
res += mol.name;
if (!mol.connections.empty()) {
res += "(";
for (size_t i = 0; i < mol.connections.size(); i++) {
size_t component_index = mol.connections[i];
const Node& comp = nodes[component_index];
res += comp.name;
if (comp.state != "") {
res += "~" + comp.state;
}
for (size_t conn: comp.connections) {
if (conn == mol_index) {
// connection to myself
continue;
}
UnorderedPair bond(component_index, conn);
int bond_value;
auto it = bonds.find(bond);
if (it != bonds.end()) {
bond_value = it->second;
}
else {
int next_bond_index = bonds.size() + 1; // we start from 1
bonds[bond] = next_bond_index;
bond_value = next_bond_index;
}
res += "!" + to_string(bond_value);
}
if (i + 1!= mol.connections.size()) {
res += ",";
}
}
res += ")";
}
#ifndef MCELL3_NO_COMPARMTENT_IN_PRINTOUTS
if (mol.compartment != "") {
res += "@" + mol.compartment;
}
#endif
// expecting that all the molecules are at the end
if (mol_index + 1 != nodes.size()) {
res += ".";
}
}
}
return res;
}
std::string graph_pattern_to_bngl(const char* graph_pattern) {
assert(graph_pattern != nullptr);
// each c: or m: is a node on graph, ! specifies to what it is connected
// c:a~R!2!1,c:b~T!3!0,m:A@NOCOMPARTMENT!0,m:B@NOCOMPARTMENT!1
vector<Node> nodes;
// process the nauty string
graph_pattern_to_nodes(graph_pattern, nodes);
// make BNGL representation
return nodes_to_bngl(nodes);
}
| C++ |
3D | mcellteam/mcell | src/rng.h | .h | 1,570 | 55 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "debug_config.h"
#define ONE_OVER_2_TO_THE_33RD 1.16415321826934814453125e-10
#if defined(USE_MINIMAL_RNG)
#include "minrng.h"
#define rng_state mrng_state
#define rng_init(x, y) mrng_init((x), (y))
#define rng_dbl(x) mrng_dbl32((x))
#define rng_uint(x) mrng_uint32((x))
#else
/*******************ISAAC64*********************/
#include "isaac64.h"
#define rng_state isaac64_state
#define rng_uses(x) \
((RANDMAX *((x)->rngblocks - 1)) + (long long)(RANDMAX - (x)->randcnt))
#define rng_init(x, y) isaac64_init((x), (y))
#if !defined(NDEBUG) || defined(DEBUG_RNG_CALLS)
// we need functions to be able to dump the random number gen. info
static double rng_dbl(struct rng_state *rng);
static unsigned int rng_uint(struct rng_state *rng);
#else
#define rng_dbl(x) isaac64_dbl32((x))
#define rng_uint(x) isaac64_uint32((x))
#endif
/***********************************************/
#endif
#define rng_open_dbl(x) (rng_dbl(x) + ONE_OVER_2_TO_THE_33RD)
static double rng_gauss(struct rng_state *rng);
#include "rng.c"
| Unknown |
3D | mcellteam/mcell | src/chkpt.c | .c | 53,194 | 1,395 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/**************************************************************************\
** File: chkpt.c
**
** Purpose: Writes and reads MCell checkpoint files.
**
*/
#include "config.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <string.h>
#include "mcell_structs.h"
#include "mcell_reactions.h"
#include "nfsim_func.h"
#include "logging.h"
#include "vol_util.h"
#include "chkpt.h"
#include "grid_util.h"
#include "count_util.h"
#include "react.h"
#include "strfunc.h"
/* MCell checkpoint API version */
#define CHECKPOINT_API 1
/* Endian-ness markers */
#define MCELL_BIG_ENDIAN 16
#define MCELL_LITTLE_ENDIAN 17
/* Checkpoint section commands */
#define CURRENT_TIME_CMD 1
#define CURRENT_ITERATION_CMD 2
#define CHKPT_SEQ_NUM_CMD 3
#define RNG_STATE_CMD 4
#define MCELL_VERSION_CMD 5
#define SPECIES_TABLE_CMD 6
#define MOL_SCHEDULER_STATE_CMD 7
#define BYTE_ORDER_CMD 8
#define NUM_CHKPT_CMDS 9
#define CHECKPOINT_API_CMD 10
/* Newbie flags */
#define HAS_ACT_NEWBIE 1
#define HAS_NOT_ACT_NEWBIE 0
#define HAS_ACT_CHANGE 1
#define HAS_NOT_ACT_CHANGE 0
/* these are needed for the chkpt signal handler */
int *chkpt_continue_after_checkpoint;
const char **chkpt_initialization_state;
enum checkpoint_request_type_t *chkpt_checkpoint_requested;
/* ============================= */
/* General error-checking macros */
/* If 'op' is true, fail with a message about corrupt checkpoint data. msg,
* ... are printf-style. */
#define DATACHECK(op, msg, ...) \
do { \
if (op) { \
mcell_warn("Corrupted checkpoint data: " msg, ##__VA_ARGS__); \
return 1; \
} \
} while (0)
/* If 'op' is true, fail with a message about an internal error. msg, ... are
* printf-style. */
#define INTERNALCHECK(op, msg, ...) \
do { \
if (op) { \
mcell_warn("%s internal: " msg, __func__, ##__VA_ARGS__); \
return 1; \
} \
} while (0)
/* Wrapper for an I/O (write) operation to print out appropriate error messages
* in case of failure. */
#define WRITECHECK(op, sect) \
do { \
if (op) { \
mcell_perror_nodie(errno, "Error while writing '%s' to checkpoint file", \
SECTNAME); \
return 1; \
} \
} while (0)
/* Write a raw field to the output stream. */
#define WRITEFIELD(f) WRITECHECK(fwrite(&(f), sizeof(f), 1, fs) != 1, SECTNAME)
/* Write a raw array of fields to the output stream. */
#define WRITEARRAY(f, len) \
WRITECHECK(fwrite(f, sizeof(f[0]), (len), fs) != (len), SECTNAME)
/* Write an unsigned integer to the output stream in endian- and
* size-independent format. */
#define WRITEUINT(f) WRITECHECK(write_varint(fs, (f)), SECTNAME)
/* Write a signed integer to the output stream in endian- and size-independent
* format. */
#define WRITEINT(f) WRITECHECK(write_svarint(fs, (f)), SECTNAME)
/* Write an unsigned 64-bit niteger to the output stream in endian- and
* size-independent format. */
#define WRITEUINT64(f) WRITECHECK(write_varintl(fs, (f)), SECTNAME)
/* Write a string to the output stream as a count followed by raw ASCII
* character data. */
#define WRITESTRING(f) \
do { \
uint32_t len = (uint32_t)strlen(f); \
WRITEUINT(len); \
WRITEARRAY(f, len); \
} while (0)
/* Wrapper for an I/O (read) operation to print out appropriate error messages
* in case of failure. */
#define READCHECK(op, sect) \
do { \
if (op) { \
mcell_perror_nodie( \
errno, "Error while reading '%s' from checkpoint file", SECTNAME); \
return 1; \
} \
} while (0)
/* Read a raw field from the input stream (i.e. never byteswap). */
#define READFIELDRAW(f) READCHECK(fread(&(f), sizeof(f), 1, fs) != 1, SECTNAME)
/* Maybe byteswap a field. */
#define READBSWAP(f) \
do { \
if (state->byte_order_mismatch) \
byte_swap(&(f), sizeof(f)); \
} while (0)
/* Read a field from the input stream, byteswapping if needed. */
#define READFIELD(f) \
do { \
READFIELDRAW(f); \
READBSWAP(f); \
} while (0)
/* Read a raw array of chars from the input stream. */
#define READSTRING(f, len) \
do { \
READCHECK(fread(f, sizeof(f[0]), (len), fs) != (len), SECTNAME); \
f[len] = '\0'; \
} while (0)
/* Read an array of items from the input stream, byteswapping if needed. */
#define READARRAY(f, len) \
do { \
int i; \
READCHECK(fread(f, sizeof(f[0]), (len), fs) != (len), SECTNAME); \
for (i = 0; i < len; ++i) \
READBSWAP(f[i]); \
} while (0)
/* Read an unsigned integer from the input stream in endian- and
* size-independent format. */
#define READUINT(f) READCHECK(read_varint(fs, &(f)), SECTNAME)
/* Read a signed integer from the input stream in endian- and size-independent
* format. */
#define READINT(f) READCHECK(read_svarint(fs, &(f)), SECTNAME)
/* Read an unsigned 64-bit niteger from the input stream in endian- and
* size-independent format. */
#define READUINT64(f) READCHECK(read_varintl(fs, &(f)), SECTNAME)
/**
* Structure to hold any requisite state during the checkpoint read process.
*/
struct chkpt_read_state {
byte byte_order_mismatch;
};
/* Handlers for individual checkpoint commands */
static int read_current_time_seconds(struct volume *world, FILE *fs,
struct chkpt_read_state *state);
static int read_current_iteration(struct volume *world, FILE *fs,
struct chkpt_read_state *state);
static int read_chkpt_seq_num(struct volume *world, FILE *fs,
struct chkpt_read_state *state);
static int read_rng_state(struct volume *world, FILE *fs,
struct chkpt_read_state *state);
static int read_byte_order(FILE *fs, struct chkpt_read_state *state);
static int read_mcell_version(FILE *fs, struct chkpt_read_state *state);
static int read_api_version(FILE *fs, struct chkpt_read_state *state,
uint32_t *api_version);
static int read_species_table(struct volume *world, FILE *fs);
static int read_mol_scheduler_state_real(struct volume *world, FILE *fs,
struct chkpt_read_state *state,
uint32_t api_version);
static int write_mcell_version(FILE *fs, const char *mcell_version);
static int write_current_time_seconds(FILE *fs, double current_time_seconds);
static int write_current_iteration(FILE *fs, long long current_iterations,
double current_time_seconds);
static int write_chkpt_seq_num(FILE *fs, u_int chkpt_seq_num);
static int write_rng_state(FILE *fs, u_int seed_seq, struct rng_state *rng);
static int write_species_table(FILE *fs, int n_species,
struct species **species_list);
static int write_mol_scheduler_state_real(FILE *fs,
struct storage_list *storage_head,
double simulation_start_seconds,
double start_iterations,
double time_unit);
static int write_byte_order(FILE *fs);
static int write_api_version(FILE *fs);
static int create_molecule_scheduler(struct storage_list *storage_head,
long long start_iterations);
/********************************************************************
* this function initializes to global variables
*
* int chkpt_continue_after_checkpoint
* char *chkpt_initialization_state
* enum checkpoint_request_type_t chkpt_checkpoint_requested
*
* needed by the signal handler chkpt_signal_handler
*********************************************************************/
int set_checkpoint_state(struct volume *world) {
chkpt_continue_after_checkpoint = &world->continue_after_checkpoint;
chkpt_initialization_state = &world->initialization_state;
chkpt_checkpoint_requested = &world->checkpoint_requested;
return 0;
}
/***************************************************************************
chkpt_signal_handler:
In: signo - the signal number that triggered the checkpoint
Out: Records the checkpoint request
Note: This function is not to be called during normal program execution. It is
registered as a signal handler for SIGUSR1, SIGUSR2, and possibly SIGALRM
signals.
***************************************************************************/
void chkpt_signal_handler(int signo) {
if (*chkpt_initialization_state) {
if (signo != SIGALRM || !*chkpt_continue_after_checkpoint) {
mcell_warn("Checkpoint requested while %s. Exiting.",
*chkpt_initialization_state);
exit(EXIT_FAILURE);
}
}
#ifndef _WIN64 /* fixme: Windows does not support USR signals */
if (signo == SIGUSR1)
*chkpt_checkpoint_requested = CHKPT_SIGNAL_CONT;
else if (signo == SIGUSR2)
*chkpt_checkpoint_requested = CHKPT_SIGNAL_EXIT;
else
#endif
if (signo == SIGALRM) {
if (*chkpt_continue_after_checkpoint)
*chkpt_checkpoint_requested = CHKPT_ALARM_CONT;
else
*chkpt_checkpoint_requested = CHKPT_ALARM_EXIT;
}
}
/***************************************************************************
create_chkpt:
In: filename - the name of the checkpoint file to create
Out: returns 1 on failure, 0 on success. On success, checkpoint file is
written to the appropriate filename. On failure, the old checkpoint file
is left unmolested.
***************************************************************************/
int create_chkpt(struct volume *world, char const *filename) {
FILE *outfs = NULL;
/* Create temporary filename */
char *tmpname = alloc_sprintf("%s.tmp", filename);
if (tmpname == NULL)
mcell_allocfailed("Out of memory creating temporary checkpoint filename "
"for checkpoint '%s'.",
filename);
/* Open the file */
if ((outfs = fopen(tmpname, "wb")) == NULL)
mcell_perror(errno, "Failed to write checkpoint file '%s'", tmpname);
/* Write checkpoint */
world->current_time_seconds = world->current_time_seconds +
(world->current_iterations - world->start_iterations) * world->time_unit;
// These are normally set when reading a checkpoint. They need to be set here
// in case we checkpoint without exiting (i.e. using NOEXIT). Otherwise,
// world->current_time_seconds will be set incorrectly upon subsequent calls
// to create_chkpt
world->start_iterations = world->current_iterations;
world->simulation_start_seconds = world->current_time_seconds;
if (write_chkpt(world, outfs))
mcell_error("Failed to write checkpoint file %s\n", filename);
fclose(outfs);
/* keep previous checkpoint file if requested by appending the current
* iteration */
if (world->keep_chkpts) {
/* check if previous checkpoint file exists - may not exist initially */
struct stat buf;
if (stat(filename, &buf) == 0) {
char *keepName = alloc_sprintf("%s.%lld", filename, world->current_iterations);
if (keepName == NULL) {
mcell_allocfailed("Out of memory creating filename for checkpoint");
}
if (rename(filename, keepName) != 0) {
mcell_error("Failed to save previous checkpoint file %s to %s",
filename, keepName);
}
free(keepName);
}
}
/* Move it into place */
if (rename(tmpname, filename) != 0)
mcell_error("Successfully wrote checkpoint to file '%s', but failed to "
"atomically replace checkpoint file '%s'.\nThe simulation may "
"be resumed from '%s'.",
tmpname, filename, tmpname);
free(tmpname);
return 0;
}
/***************************************************************************
write_varintl: Size- and endian-agnostic saving of unsigned long long values.
In: fs - file handle to which to write
val - value to write to file
Out: returns 1 on failure, 0 on success. On success, value is written to file.
***************************************************************************/
static int write_varintl(FILE *fs, unsigned long long val) {
unsigned char buffer[40];
size_t len = 0;
buffer[sizeof(buffer) - 1 - len] = val & 0x7f;
val >>= 7;
++len;
while (val != 0) {
buffer[sizeof(buffer) - 1 - len] = (val & 0x7f) | 0x80;
val >>= 7;
++len;
}
if (fwrite(buffer + sizeof(buffer) - len, 1, len, fs) != len)
return 1;
return 0;
}
/***************************************************************************
write_svarintl: Size- and endian-agnostic saving of signed long long values.
In: fs - file handle to which to write
val - value to write to file
Out: returns 1 on failure, 0 on success. On success, value is written to file.
***************************************************************************/
static int write_svarintl(FILE *fs, long long val) {
if (val < 0)
return write_varintl(fs, (unsigned long long)(((-val) << 1) | 1));
else
return write_varintl(fs, (unsigned long long)(((val) << 1)));
}
/***************************************************************************
read_varintl: Size- and endian-agnostic loading of unsigned long long values.
In: fs - file handle from which to read
dest - pointer to value to receive data from file
Out: returns 1 on failure, 0 on success. On success, value is read from file.
***************************************************************************/
static int read_varintl(FILE *fs, unsigned long long *dest) {
unsigned long long accum = 0;
unsigned char ch;
do {
if (fread(&ch, 1, 1, fs) != 1)
return 1;
accum <<= 7;
accum |= ch & 0x7f;
} while (ch & 0x80);
*dest = accum;
return 0;
}
/***************************************************************************
read_svarintl: Size- and endian-agnostic loading of signed long long values.
In: fs - file handle from which to read
dest - pointer to value to receive data from file
Out: returns 1 on failure, 0 on success. On success, value is read from file.
***************************************************************************/
static int read_svarintl(FILE *fs, long long *dest) {
unsigned long long tmp = 0;
if (read_varintl(fs, &tmp))
return 1;
if (tmp & 1)
*dest = (long long)-(tmp >> 1);
else
*dest = (long long)(tmp >> 1);
return 0;
}
/***************************************************************************
write_varint: Size- and endian-agnostic saving of unsigned int values.
In: fs - file handle to which to write
val - value to write to file
Out: returns 1 on failure, 0 on success. On success, value is written to file.
***************************************************************************/
static int write_varint(FILE *fs, unsigned int val) {
return write_varintl(fs, (unsigned long long)val);
}
/***************************************************************************
write_svarint: Size- and endian-agnostic saving of signed int values.
In: fs - file handle to which to write
val - value to write to file
Out: returns 1 on failure, 0 on success. On success, value is written to file.
***************************************************************************/
static int write_svarint(FILE *fs, int val) {
return write_svarintl(fs, (long long)val);
}
/***************************************************************************
read_varint: Size- and endian-agnostic loading of unsigned int values.
In: fs - file handle from which to read
dest - pointer to value to receive data from file
Out: returns 1 on failure, 0 on success. On success, value is read from file.
***************************************************************************/
static int read_varint(FILE *fs, unsigned int *dest) {
unsigned long long val;
if (read_varintl(fs, &val))
return 1;
*dest = val;
if ((unsigned long long)*dest != val)
return 1;
return 0;
}
/***************************************************************************
read_svarint: Size- and endian-agnostic loading of signed int values.
In: fs - file handle from which to read
dest - pointer to value to receive data from file
Out: returns 1 on failure, 0 on success. On success, value is read from file.
***************************************************************************/
static int read_svarint(FILE *fs, int *dest) {
long long val;
if (read_svarintl(fs, &val))
return 1;
*dest = val;
if ((long long)*dest != val)
return 1;
return 0;
}
/***************************************************************************
write_chkpt:
In: fs - checkpoint file to write to.
Out: Writes the checkpoint file with all information needed for the
simulation to restart.
Returns 1 on error, and 0 - on success.
***************************************************************************/
int write_chkpt(struct volume *world, FILE *fs) {
return (write_byte_order(fs) ||
write_api_version(fs) ||
write_mcell_version(fs, world->mcell_version) ||
write_current_time_seconds(fs, world->current_time_seconds) ||
write_current_iteration(fs, world->current_iterations,
world->current_time_seconds) ||
write_chkpt_seq_num(fs, world->chkpt_seq_num) ||
write_rng_state(fs, world->seed_seq, world->rng) ||
write_species_table(fs, world->n_species, world->species_list) ||
write_mol_scheduler_state_real(fs, world->storage_head,
world->simulation_start_seconds, world->start_iterations,
world->time_unit));
}
/***************************************************************************
read_preamble:
Read the required first two sections of an MCell checkpoint file.
In: fs: checkpoint file to read from.
Out: Reads preamble from checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int read_preamble(FILE *fs, struct chkpt_read_state *state, uint32_t *api_version) {
byte cmd;
/* Read and handle required first command (byte order). */
size_t count = fread(&cmd, 1, sizeof(cmd), fs);
DATACHECK(feof(fs), "Checkpoint file is empty.");
if (count != sizeof(cmd)) {
return 1;
}
DATACHECK(cmd != BYTE_ORDER_CMD,
"Checkpoint file does not have the required byte-order command.");
if (read_byte_order(fs, state))
return 1;
/* Read the checkpoint API version if present. If it is missing we assume
* the lagacy API version 0 */
count = fread(&cmd, 1, sizeof(cmd), fs);
DATACHECK(feof(fs), "Checkpoint file is too short (no api or version info).");
if (count != sizeof(cmd)) {
return 1;
}
if (cmd != CHECKPOINT_API_CMD) {
*api_version = 0;
} else {
read_api_version(fs, state, api_version);
count = fread(&cmd, 1, sizeof(cmd), fs);
}
/* Read and handle required second command (version). */
DATACHECK(feof(fs), "Checkpoint file is too short (no version info).");
if (count != sizeof(cmd)) {
return 1;
}
DATACHECK(cmd != MCELL_VERSION_CMD,
"Checkpoint file does not contain required MCell version command.");
return read_mcell_version(fs, state);
}
/***************************************************************************
read_chkpt:
In: fs - checkpoint file to read from.
Out: Reads checkpoint file. Sets the values of multiple parameters
in the simulation.
Returns 1 on error, and 0 - on success.
***************************************************************************/
int read_chkpt(struct volume *world, FILE *fs, bool only_time_and_iter) {
byte cmd;
int seen_section[NUM_CHKPT_CMDS];
memset(seen_section, 0, sizeof(int)*NUM_CHKPT_CMDS);
struct chkpt_read_state state;
state.byte_order_mismatch = 0;
/* Read the required pre-amble sections */
uint32_t api_version;
if (read_preamble(fs, &state, &api_version))
return 1;
seen_section[BYTE_ORDER_CMD] = 1;
seen_section[MCELL_VERSION_CMD] = 1;
bool time_read = false;
bool iteration_read = false;
/* Handle all other commands */
while (1) {
size_t count = fread(&cmd, sizeof(cmd), 1, fs);
if (feof(fs)) {
break;
}
if (count != sizeof(cmd)) {
return 1;
}
/* Check that it's a valid command-type */
DATACHECK(cmd < 1 || cmd >= NUM_CHKPT_CMDS,
"Unrecognized command-type in checkpoint file. "
"Checkpoint file cannot be loaded.");
/* Check that we haven't seen it already */
DATACHECK(seen_section[cmd], "Duplicate command-type in checkpoint file.");
seen_section[cmd] = 1;
/* Process normal commands */
switch (cmd) {
case CURRENT_TIME_CMD:
if (read_current_time_seconds(world, fs, &state)) {
return 1;
}
time_read = true;
if (only_time_and_iter && iteration_read) {
return 0;
}
break;
case CURRENT_ITERATION_CMD:
if (read_current_iteration(world, fs, &state)) {
return 1;
}
iteration_read = true;
if (only_time_and_iter && time_read) {
return 0;
}
// do not create scheduler if we are reading just time and iteration
if (!only_time_and_iter) {
if (create_molecule_scheduler(world->storage_head, world->start_iterations)) {
return 1;
}
}
break;
case CHKPT_SEQ_NUM_CMD:
if (read_chkpt_seq_num(world, fs, &state))
return 1;
break;
case RNG_STATE_CMD:
if (read_rng_state(world, fs, &state))
return 1;
break;
case SPECIES_TABLE_CMD:
if (read_species_table(world, fs))
return 1;
break;
case MOL_SCHEDULER_STATE_CMD:
DATACHECK(
!seen_section[CURRENT_ITERATION_CMD],
"Current iteration command must precede molecule scheduler command.");
DATACHECK(
!seen_section[SPECIES_TABLE_CMD],
"Species table command must precede molecule scheduler command.");
if (read_mol_scheduler_state_real(world, fs, &state, api_version))
return 1;
break;
case BYTE_ORDER_CMD:
case MCELL_VERSION_CMD:
default:
/* We should have already filtered out these cases, so if we get here,
* an internal error has occurred. */
assert(0);
break;
}
}
/* Check for required sections */
DATACHECK(!seen_section[CURRENT_TIME_CMD],
"Current time command is not present.");
DATACHECK(!seen_section[CHKPT_SEQ_NUM_CMD],
"Checkpoint sequence number command is not present.");
DATACHECK(!seen_section[RNG_STATE_CMD], "RNG state command is not present.");
DATACHECK(!seen_section[MOL_SCHEDULER_STATE_CMD],
" Molecule scheduler state command is not present.");
return 0;
}
/***************************************************************************
write_byte_order:
In: fs - checkpoint file to write to.
Out: Writes byte order of the machine that creates checkpoint file
to the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int write_byte_order(FILE *fs) {
static const char SECTNAME[] = "byte order";
static const byte cmd = BYTE_ORDER_CMD;
#ifdef WORDS_BIGENDIAN
static const unsigned int byte_order = MCELL_BIG_ENDIAN;
#else
static const unsigned int byte_order = MCELL_LITTLE_ENDIAN;
#endif
WRITEFIELD(cmd);
WRITEFIELD(byte_order);
return 0;
}
/***************************************************************************
read_byte_order:
In: fs - checkpoint file to read from.
Out: Reads byte order from the checkpoint file.
Returns 1 on error, and 0 - on success.
Reports byte order mismatch between the machines that writes to and
reads from the checkpoint file,
***************************************************************************/
static int read_byte_order(FILE *fs, struct chkpt_read_state *state) {
static const char SECTNAME[] = "byte order";
#ifdef WORDS_BIGENDIAN
static const unsigned int byte_order_present = MCELL_BIG_ENDIAN;
#else
static const unsigned int byte_order_present = MCELL_LITTLE_ENDIAN;
#endif
unsigned int byte_order_read;
READFIELDRAW(byte_order_read);
/* find whether there is mismatch between two machines */
state->byte_order_mismatch = (byte_order_read != byte_order_present);
return 0;
}
/***************************************************************************
write_api_version:
In: fs - checkpoint file to write to.
Out: Writes the current checkpoint file api version to the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int write_api_version(FILE *fs) {
static const char SECTNAME[] = "api version";
static const byte cmd = CHECKPOINT_API_CMD;
uint32_t api_version = CHECKPOINT_API;
WRITEFIELD(cmd);
WRITEFIELD(api_version);
return 0;
}
/***************************************************************************
read_api_version:
In: fs - checkpoint file to read from.
Out: Reads the api version of the current checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int read_api_version(FILE *fs, struct chkpt_read_state *state,
uint32_t *api_version) {
static const char SECTNAME[] = "api version";
READFIELD(*api_version);
return 0;
}
/***************************************************************************
write_mcell_version:
In: fs - checkpoint file to write to.
Out: MCell3 software version is written to the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int write_mcell_version(FILE *fs, const char *mcell_version) {
static const char SECTNAME[] = "MCell version";
static const byte cmd = MCELL_VERSION_CMD;
uint32_t len = (uint32_t)strlen(mcell_version);
WRITEFIELD(cmd);
WRITEFIELD(len);
WRITEARRAY(mcell_version, len);
return 0;
}
/***************************************************************************
read_mcell_version:
In: fs - checkpoint file to read from.
Out: MCell3 software version is read from the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int read_mcell_version(FILE *fs, struct chkpt_read_state *state) {
static const char SECTNAME[] = "MCell version";
/* Read and error-check the MCell version string length */
unsigned int version_length;
READFIELD(version_length);
DATACHECK(version_length >= 100000,
"Length field for MCell version is too long (%u).", version_length);
char* mcell_version = new char[version_length + 1];
READSTRING(mcell_version, version_length);
mcell_log("Checkpoint file was created with MCell Version %s.",
mcell_version);
delete mcell_version;
return 0;
}
/***************************************************************************
write_current_time_seconds:
In: fs - checkpoint file to write to.
Out: Writes current real time (in the terms of sec) in the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int write_current_time_seconds(FILE *fs, double current_time_seconds) {
static const char SECTNAME[] = "current real time";
static const byte cmd = CURRENT_TIME_CMD;
WRITEFIELD(cmd);
WRITEFIELD(current_time_seconds);
return 0;
}
/***************************************************************************
read_current_time_seconds:
In: fs - checkpoint file to read from.
Out: Reads current real time (in the terms of sec) from the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int read_current_time_seconds(struct volume *world, FILE *fs,
struct chkpt_read_state *state) {
static const char SECTNAME[] = "current real time";
READFIELD(world->simulation_start_seconds);
return 0;
}
/***************************************************************************
create_molecule_scheduler:
In: none.
Out: Creates global molecule scheduler using checkpoint file values.
Returns 0 on success. Error message and exit on failure.
***************************************************************************/
static int create_molecule_scheduler(struct storage_list *storage_head,
long long start_iterations) {
struct storage_list *stg;
for (stg = storage_head; stg != NULL; stg = stg->next) {
if ((stg->store->timer = create_scheduler(1.0, 100.0, 100, start_iterations)) ==
NULL) {
mcell_error("Out of memory while creating molecule scheduler.");
}
stg->store->current_time = start_iterations;
}
return 0;
}
/***************************************************************************
write_current_iteration:
In: fs - checkpoint file to write to.
Out: Writes current iteration number to the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int write_current_iteration(FILE *fs, long long current_iterations,
double current_time_seconds) {
static const char SECTNAME[] = "current iteration";
static const byte cmd = CURRENT_ITERATION_CMD;
WRITEFIELD(cmd);
WRITEFIELD(current_iterations);
WRITEFIELD(current_time_seconds);
return 0;
}
/***************************************************************************
read_current_iteration:
In: fs - checkpoint file to read from.
Out: Reads current iteration number from the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int read_current_iteration(struct volume *world, FILE *fs,
struct chkpt_read_state *state) {
static const char SECTNAME[] = "current iteration";
READFIELD(world->start_iterations);
READFIELD(world->chkpt_start_time_seconds);
world->current_time_seconds = world->chkpt_start_time_seconds;
return 0;
}
/***************************************************************************
write_chkpt_seq_num:
In: fs - checkpoint file to write to.
Out: Writes checkpoint sequence number to the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int write_chkpt_seq_num(FILE *fs, u_int chkpt_seq_num) {
static const char SECTNAME[] = "checkpoint sequence number";
static const byte cmd = CHKPT_SEQ_NUM_CMD;
WRITEFIELD(cmd);
WRITEFIELD(chkpt_seq_num);
return 0;
}
/***************************************************************************
read_chkpt_seq_num:
In: fs - checkpoint file to read from.
Out: Reads checkpoint sequence number from the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int read_chkpt_seq_num(struct volume *world, FILE *fs,
struct chkpt_read_state *state) {
static const char SECTNAME[] = "checkpoint sequence number";
READFIELD(world->chkpt_seq_num);
++world->chkpt_seq_num;
return 0;
}
/***************************************************************************
write_an_rng_state:
In: fs: checkpoint file to write to.
rng: rng whose state to write
Out: Writes random number generator state to the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int write_an_rng_state(FILE *fs, struct rng_state *rng) {
static const char SECTNAME[] = "RNG state";
#ifdef USE_MINIMAL_RNG
static const char RNG_MINRNG = 'M';
WRITEFIELD(RNG_MINRNG);
WRITEFIELD(rng->a);
WRITEFIELD(rng->b);
WRITEFIELD(rng->c);
WRITEFIELD(rng->d);
#else
static const char RNG_ISAAC = 'I';
WRITEFIELD(RNG_ISAAC);
WRITEUINT(rng->randcnt);
WRITEFIELD(rng->aa);
WRITEFIELD(rng->bb);
WRITEFIELD(rng->cc);
WRITEARRAY(rng->randrsl, RANDSIZ);
WRITEARRAY(rng->mm, RANDSIZ);
#endif
return 0;
}
/***************************************************************************
write_rng_state:
In: fs - checkpoint file to write to.
Out: Writes random number generator state to the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int write_rng_state(FILE *fs, u_int seed_seq, struct rng_state *rng) {
static const char SECTNAME[] = "RNG state";
static const byte cmd = RNG_STATE_CMD;
WRITEFIELD(cmd);
WRITEUINT(seed_seq);
if (write_an_rng_state(fs, rng))
return 1;
return 0;
}
/***************************************************************************
read_an_rng_state:
In: fs: checkpoint file to read from.
state: contextual state for reading checkpoint file
rng: pointer to RNG state to read
Out: Reads random number generator state from the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int read_an_rng_state(FILE *fs, struct chkpt_read_state *state,
struct rng_state *rng) {
static const char SECTNAME[] = "RNG state";
#ifdef USE_MINIMAL_RNG
static const char RNG_MINRNG = 'M';
char rngtype;
READFIELD(rngtype);
DATACHECK(rngtype != RNG_MINRNG, "Invalid RNG type stored in checkpoint file "
"(in this version of MCell, only Bob "
"Jenkins' \"small PRNG\" is supported).");
READFIELD(rng->a);
READFIELD(rng->b);
READFIELD(rng->c);
READFIELD(rng->d);
#else
static const char RNG_ISAAC = 'I';
char rngtype;
READFIELD(rngtype);
DATACHECK(rngtype != RNG_ISAAC, "Invalid RNG type stored in checkpoint file "
"(in this version of MCell, only ISAAC64 is "
"supported).");
READUINT(rng->randcnt);
READFIELD(rng->aa);
READFIELD(rng->bb);
READFIELD(rng->cc);
READARRAY(rng->randrsl, RANDSIZ);
READARRAY(rng->mm, RANDSIZ);
rng->rngblocks = 1;
#endif
return 0;
}
/***************************************************************************
read_rng_state:
In: fs - checkpoint file to read from.
Out: Reads random number generator state from the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int read_rng_state(struct volume *world, FILE *fs,
struct chkpt_read_state *state) {
static const char SECTNAME[] = "RNG state";
/* Load seed_seq from chkpt file to compare with seed_seq from command line.
* If seeds match, we will continue with the saved RNG state from the chkpt
* file, otherwise, we'll reinitialize rng to beginning of new seed sequence.
*/
unsigned int old_seed;
READUINT(old_seed);
/* Whether we're going to use it or not, we need to read the RNG state in
* order to advance to the next cmd in the chkpt file.
*/
if (read_an_rng_state(fs, state, world->rng))
return 1;
/* Reinitialize rngs to beginning of new seed sequence, if necessary. */
if (world->seed_seq != old_seed)
rng_init(world->rng, world->seed_seq);
return 0;
}
/***************************************************************************
write_species_table:
In: fs - checkpoint file to write to.
Out: Writes species data to the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int write_species_table(FILE *fs, int n_species,
struct species **species_list) {
static const char SECTNAME[] = "species table";
static const byte cmd = SPECIES_TABLE_CMD;
WRITEFIELD(cmd);
/* Write total number of existing species with at least one representative. */
unsigned int non_empty_species_count = 0;
int i;
for (i = 0; i < n_species; i++) {
if (species_list[i]->population > 0)
++non_empty_species_count;
}
WRITEUINT(non_empty_species_count);
/* Write out all species which have at least one representative. */
unsigned int external_species_id = 0;
for (i = 0; i < n_species; i++) {
if (species_list[i]->population == 0)
continue;
/* Write species name and external id. */
WRITESTRING(species_list[i]->sym->name);
WRITEUINT(external_species_id);
/* Allocate and write the external species id for this species. Stored
* value is used in wrote_mol_scheduler_state to assign external species
* ids to mols as they are written out. */
species_list[i]->chkpt_species_id = external_species_id++;
}
return 0;
}
/***************************************************************************
read_species_table:
In: fs - checkpoint file to read from.
Out: Reads species data from the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int read_species_table(struct volume *world, FILE *fs) {
static const char SECTNAME[] = "species table";
/* Read total number of species contained in checkpoint file. */
unsigned int total_species;
READUINT(total_species);
/* Scan over species table, reading in species data */
for (unsigned int i = 0; i < total_species; i++) {
unsigned int species_name_length;
READUINT(species_name_length);
/* Jed, 2007-07-05: This check guards against the security flaw caused by
* allocating a variable-length array on the stack. We should have
* similar checks whenever we allocate a stack buffer based upon a
* user-supplied value rather than upon an actual count.
*/
DATACHECK(
species_name_length >= 100000,
"Species table has species name greater than 100000 characters (%u).",
species_name_length);
/* Read species fields. */
char* species_name = new char[species_name_length + 1];
unsigned int external_species_id;
READSTRING(species_name, species_name_length);
READUINT(external_species_id);
/* find this species among world->species */
int j;
for (j = 0; j < world->n_species; j++) {
if ((strcmp(world->species_list[j]->sym->name, species_name) == 0)) {
world->species_list[j]->chkpt_species_id = external_species_id;
break;
}
}
DATACHECK(j == world->n_species, "Checkpoint file contains data for "
"species '%s', which does not exist in "
"this simulation.",
species_name);
delete species_name;
}
return 0;
}
/***************************************************************************
count_items_in_scheduler:
In: None
Out: Number of non-defunct molecules in the molecule scheduler
***************************************************************************/
unsigned long long
count_items_in_scheduler(struct storage_list *storage_head) {
unsigned long long total_items = 0;
for (struct storage_list *slp = storage_head; slp != NULL; slp = slp->next) {
for (struct schedule_helper *shp = slp->store->timer; shp != NULL;
shp = shp->next_scale) {
for (int i = -1; i < shp->buf_len; i++) {
for (struct abstract_element *aep = (i < 0) ? shp->current
: shp->circ_buf_head[i];
aep != NULL; aep = aep->next) {
struct abstract_molecule *amp = (struct abstract_molecule *)aep;
if (amp->properties == NULL)
continue;
/* There should never be a surface class in the scheduler... */
assert(!(amp->properties->flags & IS_SURFACE));
++total_items;
}
}
}
}
return total_items;
}
/***************************************************************************
write_mol_scheduler_state_real:
In: fs - checkpoint file to write to.
Out: Writes molecule scheduler data to the checkpoint file.
Returns 1 on error, and 0 - on success.
***************************************************************************/
static int write_mol_scheduler_state_real(FILE *fs,
struct storage_list *storage_head,
double simulation_start_seconds,
double start_iterations,
double time_unit) {
static const char SECTNAME[] = "molecule scheduler state";
static const byte cmd = MOL_SCHEDULER_STATE_CMD;
WRITEFIELD(cmd);
/* write total number of items in the scheduler */
unsigned long long total_items = count_items_in_scheduler(storage_head);
WRITEUINT64(total_items);
/* Iterate over all molecules in the scheduler to produce checkpoint */
for (struct storage_list *slp = storage_head; slp != NULL; slp = slp->next) {
for (struct schedule_helper *shp = slp->store->timer; shp != NULL;
shp = shp->next_scale) {
for (int i = -1; i < shp->buf_len; i++) {
for (struct abstract_element *aep = (i < 0) ? shp->current
: shp->circ_buf_head[i];
aep != NULL; aep = aep->next) {
struct abstract_molecule *amp = (struct abstract_molecule *)aep;
if (amp->properties == NULL)
continue;
/* Grab the location and orientation for this molecule */
struct vector3 where;
short orient = 0;
byte act_newbie_flag =
(amp->flags & ACT_NEWBIE) ? HAS_ACT_NEWBIE : HAS_NOT_ACT_NEWBIE;
byte act_change_flag =
(amp->flags & ACT_CHANGE) ? HAS_ACT_CHANGE : HAS_NOT_ACT_CHANGE;
if ((amp->properties->flags & NOT_FREE) == 0) {
struct volume_molecule *vmp = (struct volume_molecule *)amp;
INTERNALCHECK(vmp->previous_wall != NULL && vmp->index >= 0,
"The value of 'previous_grid' is not NULL.");
where.x = vmp->pos.x;
where.y = vmp->pos.y;
where.z = vmp->pos.z;
orient = 0;
} else if ((amp->properties->flags & ON_GRID) != 0) {
struct surface_molecule *smp = (struct surface_molecule *)amp;
uv2xyz(&smp->s_pos, smp->grid->surface, &where);
orient = smp->orient;
} else
continue;
/* Check for valid chkpt_species ID. */
INTERNALCHECK(amp->properties->chkpt_species_id == UINT_MAX,
"Attempted to write out a molecule of species '%s', "
"which has not been assigned a checkpoint species id.",
amp->properties->sym->name);
/* write molecule fields */
WRITEUINT(amp->properties->chkpt_species_id);
WRITEFIELD(act_newbie_flag);
WRITEFIELD(act_change_flag);
// NOTE: we write all times as real times (seconds) *not* as
// "iterations" (or "scaled times") in order to be able to
// re-schedule them properly upon restart
// The scheduling time (t) is essentially iterations, and since time
// steps can change when checkpointing, we can't directly convert
// iterations to real time (seconds). We need to correct for this by
// only converting the iterations of the current simulation
// [(t-start_iterations)*time_unit] and adding the real time at the
// start of the simulation (simulation_start_seconds).
double t = convert_iterations_to_seconds(
start_iterations, time_unit, simulation_start_seconds, amp->t);
WRITEFIELD(t);
// We do a simple conversion for the lifetime t2, since this
// corresponds to some event in the future and can be directly
// computed without using an offset.
double t2 = amp->t2 * time_unit;
WRITEFIELD(t2);
// Birthday is now always treated as real time in seconds, not
// "scaled" time or iterations.
double bday = amp->birthday;
WRITEFIELD(bday);
WRITEFIELD(where);
WRITEINT(orient);
static const unsigned char NON_COMPLEX = '\0';
WRITEFIELD(NON_COMPLEX);
}
}
}
}
return 0;
}
/***************************************************************************
read_mol_scheduler_state_real:
In: fs - checkpoint file to read from.
Out: Reads molecule scheduler data from the checkpoint file.
Returns 0 on success. Error message and exit on failure.
***************************************************************************/
static int read_mol_scheduler_state_real(struct volume *world, FILE *fs,
struct chkpt_read_state *state,
uint32_t api_version) {
static const char SECTNAME[] = "molecule scheduler state";
struct volume_molecule vm;
struct volume_molecule *vmp = NULL;
struct abstract_molecule *amp = NULL;
struct volume_molecule *guess = NULL;
/* Clear template vol mol structure */
memset(&vm, 0, sizeof(struct volume_molecule));
vmp = &vm;
amp = (struct abstract_molecule *)vmp;
/* read total number of items in the scheduler. */
unsigned long long total_items;
READUINT64(total_items);
for (unsigned long long n_mol = 0; n_mol < total_items; n_mol++) {
/* Normal molecule fields */
unsigned int external_species_id;
byte act_newbie_flag;
byte act_change_flag;
double sched_time;
double lifetime;
double birthday;
double x_coord, y_coord, z_coord;
int orient;
/* read molecule fields */
READUINT(external_species_id);
READFIELDRAW(act_newbie_flag);
READFIELDRAW(act_change_flag);
READFIELD(sched_time);
READFIELD(lifetime);
READFIELD(birthday);
READFIELD(x_coord);
READFIELD(y_coord);
READFIELD(z_coord);
READINT(orient);
// starting with API version 1, convert the sched_time, lifetime and
// birthday into scaled time based on the current timestep
if (api_version >= 1) {
// This will force lifetimes to be recomputed. This is necessary if
// unimolecular rate constants change between checkpoints.
lifetime = 0;
sched_time = world->start_iterations;
act_change_flag = HAS_ACT_CHANGE;
}
unsigned int complex_no = 0;
READUINT(complex_no);
/* Find this species by its external species id */
struct species *properties = NULL;
for (int species_idx = 0; species_idx < world->n_species; species_idx++) {
if (world->species_list[species_idx]->chkpt_species_id ==
external_species_id) {
properties = world->species_list[species_idx];
break;
}
}
DATACHECK(properties == NULL,
"Found molecule with unknown species id (%d).",
external_species_id);
/* Create and add molecule to scheduler */
struct periodic_image periodic_box = { 0, 0, 0 };
if ((properties->flags & NOT_FREE) == 0) { /* 3D molecule */
/* set molecule characteristics */
amp->t = sched_time;
amp->t2 = lifetime;
amp->birthday = birthday;
amp->properties = properties;
initialize_diffusion_function(amp);
if(amp->properties->flags & EXTERNAL_SPECIES)
properties_nfsim(world, amp);
vmp->previous_wall = NULL;
vmp->index = -1;
vmp->pos.x = x_coord;
vmp->pos.y = y_coord;
vmp->pos.z = z_coord;
amp->periodic_box = &periodic_box;
/* Set molecule flags */
amp->flags = TYPE_VOL | IN_VOLUME;
if (act_newbie_flag == HAS_ACT_NEWBIE)
amp->flags |= ACT_NEWBIE;
if (act_change_flag == HAS_ACT_CHANGE)
amp->flags |= ACT_CHANGE;
amp->flags |= IN_SCHEDULE;
if ((amp->properties->flags & CAN_SURFWALL) != 0 ||
trigger_unimolecular(world->reaction_hash, world->rx_hashsize,
amp->properties->hashval, amp) != NULL)
amp->flags |= ACT_REACT;
if (amp->get_space_step(amp) > 0.0)
amp->flags |= ACT_DIFFUSE;
/* Insert copy of vm into world */
guess = insert_volume_molecule(world, vmp, guess);
if (guess == NULL) {
mcell_error("Cannot insert copy of molecule of species '%s' into "
"world.\nThis may be caused by a shortage of memory.",
vmp->properties->sym->name);
}
} else { /* surface_molecule */
struct vector3 where;
where.x = x_coord;
where.y = y_coord;
where.z = z_coord;
struct surface_molecule *smp = insert_surface_molecule(
world, properties, &where, orient, CHKPT_GRID_TOLERANCE, sched_time,
NULL, NULL, NULL, &periodic_box);
if (smp == NULL) {
mcell_warn("Could not place molecule %s at (%f,%f,%f).",
properties->sym->name, where.x * world->length_unit,
where.y * world->length_unit,
where.z * world->length_unit);
continue;
}
smp->t2 = lifetime;
smp->birthday = birthday;
if (act_newbie_flag == HAS_NOT_ACT_NEWBIE)
smp->flags &= ~ACT_NEWBIE;
if (act_change_flag == HAS_ACT_CHANGE) {
smp->flags |= ACT_CHANGE;
}
}
}
return 0;
}
| C |
3D | mcellteam/mcell | src/dyngeom.h | .h | 7,408 | 199 | /******************************************************************************
*
* Copyright (C) 2006-2014 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
*****************************************************************************/
#ifndef DYNGEOM_H
#define DYNGEOM_H
#include "mdlparse_aux.h"
#define MAX_NUM_REGIONS 100
#define MAX_NUM_OBJECTS 100
struct mesh_transparency {
struct mesh_transparency *next;
char *name;
int in_to_out;
int out_to_in;
int transp_top_front;
int transp_top_back;
};
struct name_hits {
struct name_hits *next;
char *name; /* molecule name */
int hits; /* molecule orientation */
};
struct n_parts {
int nx_parts;
int ny_parts;
int nz_parts;
};
struct molecule_info ** save_all_molecules(
struct volume *state, struct storage_list *storage_head);
void save_common_molecule_properties(struct molecule_info *mol_info,
struct abstract_molecule *am_ptr,
struct string_buffer *reg_names,
struct string_buffer *mesh_names,
char *mesh_name);
void save_volume_molecule(struct volume *state, struct molecule_info *mol_info,
struct abstract_molecule *am_ptr,
struct string_buffer **mesh_names);
int save_surface_molecule(struct molecule_info *mol_info,
struct abstract_molecule *am_ptr,
struct string_buffer **reg_names,
char **mesh_name);
void cleanup_names_molecs(
int num_all_molecules, struct molecule_info **all_molecules);
int place_all_molecules(
struct volume *state,
struct string_buffer *names_to_ignore,
struct string_buffer *regions_to_ignore);
void check_for_large_molecular_displacement(
struct vector3 *old_pos,
struct vector3 *new_pos,
struct volume_molecule *vm,
double *time_unit,
enum warn_level_t large_molecular_displacement_warning);
const char *compare_molecule_nesting(int *move_molecule,
int *out_to_in,
struct string_buffer *mesh_names_old,
struct string_buffer *mesh_names_new,
struct mesh_transparency *mesh_transp);
const char *check_overlapping_meshes(
int *move_molecule, int *out_to_in, int difference,
struct string_buffer *compare_this, const char *best_mesh,
struct mesh_transparency *mesh_transp);
const char *check_nonoverlapping_meshes(int *move_molecule,
int *out_to_in,
struct string_buffer *mesh_names_old,
struct string_buffer *mesh_names_new,
const char *best_mesh,
struct mesh_transparency *mesh_transp);
const char *check_outin_or_inout(
int start, int increment, int end, int *move_molecule,
int *out_to_in, const char *best_mesh, struct string_buffer *mesh_names,
struct mesh_transparency *mesh_transp);
struct volume_molecule *insert_volume_molecule_encl_mesh(
struct volume *state,
struct volume_molecule *vm,
struct volume_molecule *vm_guess,
struct string_buffer *mesh_names_old,
struct string_buffer *names_to_ignore);
int hit_wall(
struct wall *w, struct name_hits **name_head,
struct name_hits **name_tail, struct vector3 *rand_vector);
void hit_subvol(
struct n_parts *np, struct string_buffer *mesh_names,
struct collision *smash, struct collision *shead,
struct name_hits *name_head, struct subvolume *sv,
struct volume_molecule *virt_mol);
struct string_buffer *find_enclosing_meshes(
struct volume *state,
struct volume_molecule *vm,
struct string_buffer *names_to_ignore);
void place_mol_relative_to_mesh(
struct volume *state, struct vector3 *loc, struct subvolume *sv,
const char *mesh_name, struct vector3 *new_pos, int out_to_in);
void destroy_mesh_transp_data(
struct sym_table_head *mol_sym_table,
struct pointer_hash *species_mesh_transp);
int destroy_everything(struct volume *state);
void destroy_walls(struct volume *state);
void destroy_partitions(struct volume *state);
int destroy_objects(struct geom_object *obj_ptr, int free_poly_flag);
int destroy_poly_object(struct geom_object *obj_ptr, int free_poly_flag);
int reset_current_counts(struct sym_table_head *mol_sym_table,
int count_hashmask,
struct counter **count_hash);
void check_count_validity(struct output_request *output_request_head,
struct string_buffer *regions_to_ignore,
struct string_buffer *new_region_names,
struct string_buffer *meshes_to_ignore,
struct string_buffer *new_mesh_names);
void reset_count_type(const char *name,
struct output_request *request,
struct string_buffer *names_to_ignore,
struct string_buffer *new_names);
int init_species_mesh_transp(struct volume *world);
int find_sm_region_transp(struct geom_object *obj_ptr,
struct mesh_transparency **mesh_transp_head,
struct mesh_transparency **mesh_transp_tail,
const char *species_name);
void check_surf_class_properties(
const char *species_name, struct mesh_transparency *mesh_transp,
struct name_orient *surf_class_props);
int find_vm_obj_region_transp(struct geom_object *obj_ptr,
struct mesh_transparency **mesh_transp_head,
struct mesh_transparency **mesh_transp_tail,
const char *species_name);
int find_all_obj_region_transp(struct geom_object *obj_ptr,
struct mesh_transparency **mesh_transp_head,
struct mesh_transparency **mesh_transp_tail,
const char *species_name, int sm_flag);
int add_dynamic_geometry_events(
struct mdlparse_vars *parse_state,
const char *dynamic_geometry_filepath,
double timestep,
struct mem_helper *dynamic_geometry_events_mem,
struct dg_time_filename **dg_time_fname_head);
const char *get_mesh_instantiation_names(struct geom_object *obj_ptr,
struct string_buffer *mesh_names);
void diff_string_buffers(
struct string_buffer *diff_names,
struct string_buffer *names_a,
struct string_buffer *names_b);
void sym_diff_string_buffers(
struct string_buffer *diff_names,
struct string_buffer *names_a,
struct string_buffer *names_b,
enum warn_level_t add_remove_mesh_warning);
int get_reg_names_all_objects(
struct geom_object *obj_ptr, struct string_buffer *regions_to_ignore);
int get_reg_names_this_object(
struct geom_object *obj_ptr, struct string_buffer *regions_to_ignore);
void update_geometry(struct volume *state, struct dg_time_filename *dyn_geom);
#endif
| Unknown |
3D | mcellteam/mcell | src/argparse.h | .h | 629 | 22 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include <stdio.h>
struct volume;
void print_usage(FILE *f, char const *argv0);
int argparse_init(int argc, char *const argv[], struct volume *vol);
| Unknown |
3D | mcellteam/mcell | src/sym_table.c | .c | 12,685 | 517 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "logging.h"
#include "mcell_structs.h"
#include "sym_table.h"
/* ================================================================ */
unsigned long hash(char const *sym) {
ub4 hashval;
hashval = jenkins_hash((ub1 *)sym, (ub4)strlen(sym));
return (hashval);
}
struct sym_entry *retrieve_sym(char const *sym,
struct sym_table_head *hashtab) {
if (sym == NULL)
return NULL;
for (struct sym_entry *sp =
hashtab->entries[hash(sym) & (hashtab->n_bins - 1)];
sp != NULL; sp = sp->next) {
if (strcmp(sym, sp->name) == 0)
return sp;
}
return NULL;
}
/**
* new_species:
* Allocates a new species, initializing all values.
*
* In: none
* Out: the newly allocated species
*/
struct species *new_species(void) {
struct species *specp = CHECKED_MALLOC_STRUCT(struct species, "species");
specp->species_id = 0;
specp->chkpt_species_id = 0;
specp->sm_dat_head = NULL;
specp->population = 0;
specp->D = 0.0;
specp->space_step = 0.0;
specp->time_step = 0.0;
specp->custom_time_step_from_mdl = 0.0;
specp->max_step_length = 0.0;
specp->flags = 0;
specp->n_deceased = 0;
specp->cum_lifetime_seconds = 0.0;
specp->refl_mols = NULL;
specp->transp_mols = NULL;
specp->absorb_mols = NULL;
specp->clamp_mols = NULL;
return specp;
}
/**
* new_mol_ss:
* Allocates a new mol_ss, initializing all values.
*
* In: none
* Out: the newly allocated mol_ss
*/
struct mol_ss *new_mol_ss(void) {
struct mol_ss *mol_ssp = CHECKED_MALLOC_STRUCT(struct mol_ss, "mol_ss");
// mol_ssp->mol_comp_ss_sym_table = init_symtab(MOL_COMP_SS_SYM_TABLE_SIZE);
mol_ssp->mol_comp_ss_head = NULL;
mol_ssp->mol_comp_ss_tail = NULL;
return mol_ssp;
}
/**
* new_mol_comp_ss:
* Allocates a new mol_comp_ss, initializing all values.
*
* In: none
* Out: the newly allocated mol_comp_ss
*/
struct mol_comp_ss *new_mol_comp_ss(void) {
struct mol_comp_ss *mol_comp_ssp = CHECKED_MALLOC_STRUCT(struct mol_comp_ss, "mol_comp_ss");
init_matrix(mol_comp_ssp->t_matrix);
return mol_comp_ssp;
}
/**
* new_object:
* Allocates a new object, initializing all values.
*
* In: none
* Out: the newly allocated object
*/
struct geom_object *new_object(void) {
struct geom_object *objp = CHECKED_MALLOC_STRUCT(struct geom_object, "object");
objp->last_name = NULL;
objp->object_type = META_OBJ;
objp->contents = NULL;
objp->parent = NULL;
objp->next = NULL;
objp->first_child = NULL;
objp->last_child = NULL;
objp->num_regions = 0;
objp->regions = NULL;
objp->n_walls = 0;
objp->n_walls_actual = 0;
objp->walls = NULL;
objp->wall_p = NULL;
objp->n_verts = 0;
objp->vertices = NULL;
objp->total_area = 0;
objp->periodic_x = 0;
objp->periodic_y = 0;
objp->periodic_z = 0;
objp->n_tiles = 0;
objp->n_occupied_tiles = 0;
init_matrix(objp->t_matrix);
return objp;
}
/**
* new_release_pattern:
* Allocates a new release pattern, initializing all values.
*
* In: none
* Out: the newly allocated release pattern
*/
struct release_pattern *new_release_pattern(void) {
struct release_pattern *rpatp =
CHECKED_MALLOC_STRUCT(struct release_pattern, "release pattern");
rpatp->delay = 0;
rpatp->release_interval = FOREVER;
rpatp->train_interval = FOREVER;
rpatp->train_duration = FOREVER;
rpatp->number_of_trains = 1;
return rpatp;
}
/**
* new_reaction:
* Allocates a new reaction, initializing all values.
*
* In: none
* Out: the newly allocated reaction
*/
struct rxn *new_reaction(void) {
struct rxn *rxnp = CHECKED_MALLOC_STRUCT(struct rxn, "reaction");
rxnp->next = NULL;
rxnp->n_reactants = 0;
rxnp->n_pathways = 0;
rxnp->cum_probs = NULL;
rxnp->max_fixed_p = 0.0;
rxnp->min_noreaction_p = 0.0;
rxnp->pb_factor = 0.0;
rxnp->product_idx = NULL;
rxnp->players = NULL;
rxnp->nfsim_players = NULL;
rxnp->geometries = NULL;
rxnp->n_occurred = 0;
rxnp->n_skipped = 0;
rxnp->prob_t = NULL;
rxnp->pathway_head = NULL;
rxnp->info = NULL;
return rxnp;
}
/**
* new_reaction_pathname:
* Allocates a new reaction pathname, initializing all values.
*
* In: none
* Out: the newly allocated reaction pathname
*/
struct rxn_pathname *new_reaction_pathname(void) {
struct rxn_pathname *rxpnp =
CHECKED_MALLOC_STRUCT(struct rxn_pathname, "reaction pathname");
rxpnp->path_num = UINT_MAX;
rxpnp->rx = NULL;
rxpnp->magic = NULL;
return rxpnp;
}
/**
* new_region:
* Allocates a new region, initializing all values.
*
* In: none
* Out: the newly allocated region
*/
struct region *new_region(void) {
struct region *rp = CHECKED_MALLOC_STRUCT(struct region, "region");
rp->region_last_name = NULL;
rp->parent = NULL;
rp->element_list_head = NULL;
rp->membership = NULL;
rp->sm_dat_head = NULL;
rp->surf_class = NULL;
rp->bbox = NULL;
rp->area = 0.0;
rp->flags = 0;
rp->manifold_flag = MANIFOLD_UNCHECKED;
rp->volume = 0.0;
rp->boundaries = NULL;
rp->region_has_all_elements = 0;
return rp;
}
/**
* new_region:
* Allocates a new file stream, initializing all values.
*
* In: none
* Out: the newly allocated file stream
*/
struct file_stream *new_filestream(void) {
struct file_stream *filep =
CHECKED_MALLOC_STRUCT(struct file_stream, "file stream");
filep->name = NULL;
filep->stream = NULL;
return filep;
}
/**
* resize_symtab:
* Resize the symbol table, rehashing all values.
*
* In: hashtab: the symbol table
* size: new size for hash table
* Out: symbol table might be resized
*/
static int resize_symtab(struct sym_table_head *hashtab, int size) {
struct sym_entry **entries = hashtab->entries;
int n_bins = hashtab->n_bins;
/* Round up to a power of two */
size |= (size >> 1);
size |= (size >> 2);
size |= (size >> 4);
size |= (size >> 8);
size |= (size >> 16);
++size;
if (size > (1 << 28))
size = (1 << 28);
hashtab->entries =
CHECKED_MALLOC_ARRAY(struct sym_entry *, size, "symbol table");
if (hashtab->entries == NULL) {
/* XXX: Warning message? */
hashtab->entries = entries;
return 1;
}
memset(hashtab->entries, 0, size * sizeof(struct sym_entry *));
hashtab->n_bins = size;
for (int i = 0; i < n_bins; ++i) {
while (entries[i] != NULL) {
struct sym_entry *entry = entries[i];
entries[i] = entries[i]->next;
unsigned long hashval = hash(entry->name) & (size - 1);
entry->next = hashtab->entries[hashval];
hashtab->entries[hashval] = entry;
}
}
free(entries);
return 0;
}
/**
* dump_symtab:
* Dump the symbol table
*
* In: hashtab: the symbol table
* Out: number of symbols found
*/
int dump_symtab(struct sym_table_head *hashtab) {
struct sym_entry **entries = hashtab->entries;
int n_bins = hashtab->n_bins;
int num_total_entries;
num_total_entries = 0;
for (int i = 0; i < n_bins; ++i) {
struct sym_entry *entry;
entry = entries[i];
while (entry != NULL) {
num_total_entries += 1;
fprintf ( stdout, " symtab entry: %s\n", entry->name );
entry = entry->next;
}
}
return num_total_entries;
}
/**
* maybe_grow_symtab:
* Possibly grow the symbol table.
*
* In: hashtab: the symbol table
* Out: symbol table might be resized
*/
static void maybe_grow_symtab(struct sym_table_head *hashtab) {
if (hashtab->n_entries * 3 >= hashtab->n_bins)
resize_symtab(hashtab, hashtab->n_bins * 2);
}
/** Stores symbol in the symbol table.
Initializes value field of the symbol structure to the default value.
Returns: entry in the symbol table if successfully stored,
NULL - otherwise.
*/
struct sym_entry *store_sym(char const *sym, enum symbol_type_t sym_type,
struct sym_table_head *hashtab, void *data) {
struct sym_entry *sp;
unsigned long hashval;
void *vp = NULL;
double *fp;
unsigned long rawhash;
/* try to find sym in table */
if ((sp = retrieve_sym(sym, hashtab)) == NULL) {
maybe_grow_symtab(hashtab);
++hashtab->n_entries;
/* sym not found */
sp = CHECKED_MALLOC_STRUCT(struct sym_entry, "sym table entry");
sp->name = CHECKED_STRDUP(sym, "symbol name");
sp->sym_type = sym_type;
sp->count = 1;
rawhash = hash(sym);
hashval = rawhash & (hashtab->n_bins - 1);
sp->next = hashtab->entries[hashval];
hashtab->entries[hashval] = sp;
switch (sym_type) {
case DBL:
if (data == NULL) {
vp = CHECKED_MALLOC_STRUCT(double, "sym table value");
fp = (double *)vp;
*fp = 0.0;
} else
vp = data;
break;
case STR:
sp->value = data;
return (sp);
case ARRAY:
sp->value = data;
return (sp);
case MOL:
if (data == NULL)
vp = new_species();
else
vp = data;
((struct species *)vp)->sym = sp;
((struct species *)vp)->hashval = rawhash;
break;
case MOL_SS:
if (data == NULL)
vp = new_mol_ss();
else
vp = data;
((struct mol_ss *)vp)->sym = sp;
break;
/*
case MOL_COMP_SS:
if (data == NULL)
vp = new_mol_comp_ss();
else
vp = data;
((struct mol_comp_ss *)vp)->sym = sp;
break;
*/
case OBJ:
if (data == NULL)
vp = new_object();
else
vp = data;
((struct geom_object *)vp)->sym = sp;
break;
case RPAT:
if (data == NULL)
vp = new_release_pattern();
else
vp = data;
((struct release_pattern *)vp)->sym = sp;
break;
case RX:
if (data == NULL)
vp = new_reaction();
else
vp = data;
((struct rxn *)vp)->sym = sp;
break;
case RXPN:
if (data == NULL)
vp = new_reaction_pathname();
else
vp = data;
((struct rxn_pathname *)vp)->sym = sp;
((struct rxn_pathname *)vp)->hashval = rawhash;
break;
case REG:
if (data == NULL)
vp = new_region();
else
vp = data;
((struct region *)vp)->sym = sp;
((struct region *)vp)->hashval = rawhash;
break;
case FSTRM:
if (data == NULL)
vp = new_filestream();
else
vp = data;
break;
case TMP:
sp->value = data;
return sp;
case COUNT_OBJ_PTR:
sp->value = data;
return sp;
case VOID_PTR:
sp->value = data;
return (sp);
default:
mcell_internal_error("unknown symbol type in symbol table (%d)",
sym_type);
/*break;*/
}
sp->value = vp;
}
return sp;
}
/**
* init_symtab:
* Create a new symbol table.
*
* In: size: initial number of entries in the table
* Out: symbol table
*/
struct sym_table_head *init_symtab(int size) {
/* Round up to a power of two */
size |= (size >> 1);
size |= (size >> 2);
size |= (size >> 4);
size |= (size >> 8);
size |= (size >> 16);
++size;
if (size > (1 << 28))
size = (1 << 28);
/* Allocate the table and zero-initialize it. */
struct sym_table_head *symtab_head;
symtab_head =
CHECKED_MALLOC_STRUCT_NODIE(struct sym_table_head, "symbol table");
symtab_head->entries =
CHECKED_MALLOC_ARRAY_NODIE(struct sym_entry *, size, "symbol table");
memset(symtab_head->entries, 0, sizeof(struct sym_entry *) * size);
symtab_head->n_entries = 0;
symtab_head->n_bins = size;
return symtab_head;
}
/**
* destroy_symtab:
* Destroy and deallocate a symbol table.
*
* In: tab: table to destroy
* Out: table is deallocated
*/
void destroy_symtab(struct sym_table_head *tab) {
for (int i = 0; i < tab->n_bins; ++i) {
struct sym_entry *next;
for (struct sym_entry *sym = tab->entries[i]; sym != NULL; sym = next) {
next = sym->next;
free(sym);
sym = NULL;
}
}
free(tab->entries);
tab->entries = NULL;
free(tab);
tab = NULL;
}
| C |
3D | mcellteam/mcell | src/react_nfsim.h | .h | 1,547 | 39 | /******************************************************************************
*
* Copyright (C) 2006-2015 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef REACT_NFSIM_H
#define REACT_NFSIM_H
#include "mcell_structs.h"
/*
calculates particle orientation based on nfsim compartment information
*/
void calculate_reactant_orientation(struct abstract_molecule *reac,
struct abstract_molecule *reac2,
bool *orientation_flag1,
bool *orientation_flag2,
int *reactantOrientation1,
int *reactantOrientation2);
queryOptions initializeNFSimQueryForBimolecularReactions(struct graph_data *am,
struct graph_data *am2,
const char *onlyActive);
int trigger_bimolecular_preliminary_nfsim(struct abstract_molecule *reacA,
struct abstract_molecule *reacB);
struct rxn *pick_unimolecular_reaction_nfsim(struct volume *state,
struct abstract_molecule *am);
#endif
| Unknown |
3D | mcellteam/mcell | src/map_c.h | .h | 1,535 | 56 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
**/
#ifndef __MAP_C_H__
#define __MAP_C_H__
#define MAP_MISSING -3 /* No such element */
//#define MAP_FULL -2 /* Hashmap is full */
//#define MAP_OMEM -1 /* Out of Memory */
#define MAP_OK 0 /* OK */
/*
* any_t is a pointer. This allows you to put arbitrary structures in
* the hashmap.
*/
typedef void *any_t;
/*
* PFany is a pointer to a function that can take two any_t arguments
* and return an integer. Returns status code..
*/
typedef int (*PFany)(any_t, any_t);
/*
* map_t is a pointer to an internally maintained data structure.
* Clients of this package do not need to know how hashmaps are
* represented. They see and manipulate only map_t's.
*/
typedef any_t map_t;
/*
* Return an empty hashmap. Returns NULL if empty.
*/
map_t hashmap_new(void);
void hashmap_clear(map_t in);
//JJT: simplified functions without hash calculation (it is precalculated)
int hashmap_put_nohash(map_t in, unsigned long key, unsigned long key_hash, any_t value);
int hashmap_get_nohash(map_t in, unsigned long key, unsigned long key_hash, any_t *arg);
unsigned long crc32(const unsigned char *s, unsigned int len);
#endif //__MAP_C_H__
| Unknown |
3D | mcellteam/mcell | src/mcell_react_out.c | .c | 24,823 | 710 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include "sym_table.h"
#include "logging.h"
#include "react_output.h"
#include "mcell_misc.h"
#include "mcell_react_out.h"
#include "mdlparse_util.h"
#include "dyngeom_parse_extras.h"
#include "strfunc.h"
#include "count_util.h"
/* static helper functions */
static struct output_column *new_output_column(void);
static struct output_block *new_output_block(int buffersize);
static void set_reaction_output_timer_step(MCELL_STATE *state,
struct output_block *obp,
double step);
static int
set_reaction_output_timer_iterations(MCELL_STATE *state,
struct output_block *obp,
struct num_expr_list_head *step_values);
static int
set_reaction_output_timer_times(MCELL_STATE *state, struct output_block *obp,
struct num_expr_list_head *step_values);
static int output_block_finalize(struct output_block *obp);
static long long pick_buffer_size(MCELL_STATE *state, struct output_block *obp,
long long n_output);
static struct output_column *
get_counter_trigger_column(MCELL_STATE *state, const char *counter_name,
int column_id);
/*************************************************************************
mcell_get_count:
Get the count of a molecule in a certain region..
In: mol_name - molecule you want the count of
reg_name - region where you want the count
world - the instance world of the object volume.
Out: int mol_count - count of molecule in the region
*************************************************************************/
int mcell_get_count(char *mol_name, char *reg_name, struct volume *world) {
// Get the hash values for mol and reg---------------//
// Get hash value for molecule
struct sym_entry *mol_sym = NULL;
mol_sym = retrieve_sym(mol_name, world->mol_sym_table);
// Make sure mol_sym has been initialized. If not, return error code.
if (mol_sym == NULL)
return -5;
// Cast mol_sym (sym_entry, void pointer) to a species pointer
struct species *mol = (struct species *)mol_sym->value;
// Get hash value for molecule
u_int mol_hashval = mol->hashval;
// Get hash value for region
struct sym_entry *reg_sym = NULL;
reg_sym = retrieve_sym(reg_name, world->reg_sym_table);
// Make sure reg_sym has been initialized, if not return garbage
if (reg_sym == NULL)
return -6;
// Cast mol_sym (sym_entry,void pointer) to a species pointer
struct region *reg = (struct region *)reg_sym->value;
// Get hash value for region
u_int reg_hashval = reg-> hashval;
//---------------------------------------------------//
// Use the hash values to get the molecule count in the region from the count
// hash //
// Combine hash values for molecule in that region
int hash_bin = (mol_hashval + reg_hashval) & world->count_hashmask;
// Make sure hash_bin exists
if (world->count_hash[hash_bin] == NULL)
return -7;
// Get the count of molecule in and on the region
int mol_count_vol = world->count_hash[hash_bin]->data.move.n_enclosed;
int mol_count_sur = world->count_hash[hash_bin]->data.move.n_at;
return mol_count_vol + mol_count_sur;
}
/*************************************************************************
mcell_new_output_request:
Create a new output request.
In: state: MCell state
target: what are we counting
orientation: how is it oriented?
location: where are we counting?
report_flags: what type of events are we counting?
Out: output request item, or NULL if an error occurred
*************************************************************************/
struct output_request *mcell_new_output_request(MCELL_STATE *state,
struct sym_entry *target,
short orientation,
struct sym_entry *location,
struct periodic_image *img,
int report_flags) {
struct output_request *orq;
struct output_expression *oe;
orq = (struct output_request *)CHECKED_MEM_GET(state->outp_request_mem, "count request");
if (orq == NULL)
return NULL;
oe = new_output_expr(state->oexpr_mem);
if (oe == NULL) {
mem_put(state->outp_request_mem, orq);
mcell_allocfailed("Failed to allocate a count expression.");
return NULL;
}
orq->next = NULL;
orq->requester = oe;
orq->count_target = target;
orq->count_orientation = orientation;
orq->count_location = location;
orq->report_type = report_flags;
orq->periodic_box = img;
oe->left = orq;
oe->oper = '#';
oe->expr_flags = OEXPR_LEFT_REQUEST;
struct sym_entry *sym = NULL;
if (location) {
char *name = location->name;
// Counting in/on a region. XXX: Using strchr seems inefficient
if (strchr(location->name, ',')) {
sym = retrieve_sym(name, state->reg_sym_table);
}
// Counting in/on an object
else {
sym = retrieve_sym(name, state->obj_sym_table);
}
}
// If the object/region will exist at some point in the future, but not at
// the beginning of the simulation.
if (sym && !(is_object_instantiated(sym, state->root_instance)))
oe->expr_flags = OEXPR_TYPE_UNDEF;
else if (orq->report_type & REPORT_TRIGGER)
oe->expr_flags |= OEXPR_TYPE_TRIG;
else if ((orq->report_type & REPORT_TYPE_MASK) != REPORT_CONTENTS)
oe->expr_flags |= OEXPR_TYPE_DBL;
else
oe->expr_flags |= OEXPR_TYPE_INT;
return orq;
}
/******************************************************************************
*
* mcell_create_count creates a single count expression and returns it as a
* output_column_list.
* Inputs are:
* - symbol table entry for target (molecule or reaction)
* - orientation for molecule counts
* - symbol table entry for count location (NULL implies WORLD)
* - report flags (REPORT_WORLD, REPORT_CONTENTS, ...)
* - custom header (or NULL if not wanted)
* - pointer to empty count list to which count expression will be added
*
*****************************************************************************/
MCELL_STATUS
mcell_create_count(MCELL_STATE *state, struct sym_entry *target,
short orientation, struct sym_entry *location,
int report_flags, char *custom_header,
struct output_column_list *count_list) {
struct output_request *output_A = NULL;
if ((output_A = mcell_new_output_request(state, target, orientation, location,
NULL, report_flags)) == NULL) {
return MCELL_FAIL;
}
output_A->next = state->output_request_head;
state->output_request_head = output_A;
return mcell_prepare_single_count_expr(count_list, output_A->requester,
custom_header);
}
/*************************************************************************
mcell_create_new_output_set
Create a new output set. Here output set refers to a count/trigger
block which goes to a single data output file.
In: comment: textual comment describing the data set or NULL
exact_time: request exact_time output for trigger statements
col_head: head of linked list of output columns
file_flags: file creation flags for output file
outfile_name: name of output file
Out: output request item, or NULL if an error occurred
*************************************************************************/
struct output_set *mcell_create_new_output_set(const char *comment, int exact_time,
struct output_column *col_head,
int file_flags,
const char *outfile_name) {
struct output_set *os =
CHECKED_MALLOC_STRUCT(struct output_set, "reaction data output set");
if (os == NULL) {
return NULL;
}
os->outfile_name = CHECKED_STRDUP(outfile_name, "count outfile_name");
os->file_flags = (enum overwrite_policy_t)file_flags;
os->exact_time_flag = exact_time;
os->chunk_count = 0;
os->block = NULL;
os->next = NULL;
struct output_column *oc = col_head;
os->column_head = oc;
if (comment == NULL)
os->header_comment = NULL;
else if (comment[0] == '\0')
os->header_comment = "";
else {
os->header_comment = strdup(comment);
if (os->header_comment == NULL) {
free(os);
return NULL;
}
}
for (; oc != NULL; oc = oc->next)
oc->set = os;
if (check_reaction_output_file(os)) {
free(os);
return NULL;
}
return os;
}
/*****************************************************************************
*
* mcell_prepare_single_count_expression prepares a count expression for
* inclusion in an output set
*
*****************************************************************************/
MCELL_STATUS
mcell_prepare_single_count_expr(struct output_column_list *list,
struct output_expression *expr,
char *custom_header) {
list->column_head = NULL;
list->column_tail = NULL;
if (custom_header != NULL) {
expr->title = custom_header;
}
/* If we have a list of results, go through to build column stack */
struct output_expression *oe;
struct output_column *oc;
for (oe = first_oexpr_tree(expr); oe != NULL; oe = next_oexpr_tree(oe)) {
if ((oc = new_output_column()) == NULL)
return MCELL_FAIL;
if (!list->column_head)
list->column_head = list->column_tail = oc;
else
list->column_tail = list->column_tail->next = oc;
oc->expr = oe;
set_oexpr_column(oe, oc);
}
return MCELL_SUCCESS;
}
/*****************************************************************************
*
* mcell_add_reaction_output_block creates a new reaction data output block
* and adds it to the world.
*
*****************************************************************************/
MCELL_STATUS
mcell_add_reaction_output_block(MCELL_STATE *state,
struct output_set_list *osets, int buffer_size,
struct output_times_inlist *otimes) {
struct output_block *obp;
struct output_set *os;
if ((obp = new_output_block(buffer_size)) == NULL)
return 1;
if (otimes->type == OUTPUT_BY_STEP)
set_reaction_output_timer_step(state, obp, otimes->step);
else if (otimes->type == OUTPUT_BY_ITERATION_LIST) {
if (set_reaction_output_timer_iterations(state, obp, &otimes->values)) {
free(obp);
return MCELL_FAIL;
}
} else if (otimes->type == OUTPUT_BY_TIME_LIST) {
if (set_reaction_output_timer_times(state, obp, &otimes->values)) {
free(obp);
return MCELL_FAIL;
}
} else {
mcell_error("Internal error: Invalid output timer def (%d)", otimes->type);
free(obp);
return MCELL_FAIL;
}
obp->data_set_head = osets->set_head;
for (os = obp->data_set_head; os != NULL; os = os->next)
os->block = obp;
if (output_block_finalize(obp))
return 1;
obp->next = state->output_block_head;
state->output_block_head = obp;
return MCELL_SUCCESS;
}
/************************************************************************
*
* function for retrieving the current value of a given count
* expression
*
* The call expects:
*
* - MCELL_STATE
* - counter_name: a string containing the name of the count statement to
* be retrieved. Currently, the name is identical to the full path to which
* the corresponding reaction output will be written but this may change
* in the future
* - column: int describing the column to be retrieved
* - count_data: a *double which will receive the actual value
* - count_data_type: a *count_type_t which will receive the type of the
* data (for casting of count_data)
*
* NOTE: This function can be called anytime after the
* REACTION_DATA_OUTPUT has been either parsed or
* set up with API calls.
*
* Returns 1 on error and 0 on success
*
************************************************************************/
MCELL_STATUS
mcell_get_counter_value(MCELL_STATE *state,
const char *counter_name,
int column_id,
double *count_data,
enum count_type_t *count_data_type) {
struct output_column *column = NULL;
if ((column = get_counter_trigger_column(state, counter_name, column_id)) ==
NULL) {
return MCELL_FAIL;
}
// if we happen to encounter trigger data we bail
if (column->buffer[0].data_type == COUNT_TRIG_STRUCT) {
return MCELL_FAIL;
}
// evaluate the expression and retrieve it
eval_oexpr_tree(column->expr, 1);
*count_data = (double)column->expr->value;
*count_data_type = column->buffer[0].data_type;
return MCELL_SUCCESS;
}
/******************************************************************************
*
* static helper functions
*
*****************************************************************************/
/**************************************************************************
new_output_column:
Create a new output column for an output set.
In: Nothing
Out: output column, or NULL if allocation fails
**************************************************************************/
struct output_column *new_output_column() {
struct output_column *oc;
oc = CHECKED_MALLOC_STRUCT(struct output_column,
"reaction data output column");
if (oc == NULL)
return NULL;
oc->initial_value = 0.0;
oc->buffer = NULL;
oc->expr = NULL;
oc->next = NULL;
return oc;
}
/**************************************************************************
new_output_block:
Allocate a new reaction data output block, with a specified buffer size.
In: buffersize: requested buffer size
Out: output block, or NULL if an error occurs
**************************************************************************/
struct output_block *new_output_block(int buffersize) {
struct output_block *obp;
obp =
CHECKED_MALLOC_STRUCT(struct output_block, "reaction data output block");
if (obp == NULL)
return NULL;
obp->t = 0.0;
obp->timer_type = OUTPUT_BY_STEP;
obp->step_time = FOREVER;
obp->time_list_head = NULL;
obp->time_now = NULL;
obp->buffersize = 0;
obp->trig_bufsize = 0;
obp->buf_index = 0;
obp->data_set_head = NULL;
/* COUNT buffer size might get modified later if there isn't that much to
* output */
/* TRIGGER buffer size won't get modified since we can't know what to expect
*/
obp->buffersize = buffersize;
obp->trig_bufsize = obp->buffersize;
obp->time_array = CHECKED_MALLOC_ARRAY(double, obp->buffersize,
"reaction data output times array");
if (obp->time_array == NULL) {
free(obp);
return NULL;
}
return obp;
}
/**************************************************************************
set_reaction_output_timer_step:
Set the output timer for reaction data output to a time step.
In: parse_state: parser state
obp: output block whose timer is to be set
step: time step interval
Out: output timer is updated
**************************************************************************/
void set_reaction_output_timer_step(MCELL_STATE *state,
struct output_block *obp, double step) {
long long output_freq;
obp->timer_type = OUTPUT_BY_STEP;
obp->step_time = step;
output_freq = (long long)(obp->step_time / state->time_unit);
/* Clip the step time to a good range */
if (output_freq > state->iterations && output_freq > 1) {
output_freq = (state->iterations > 1) ? state->iterations : 1;
obp->step_time = output_freq * state->time_unit;
if (state->notify->invalid_output_step_time != WARN_COPE)
mcell_warn("output step time too long.\n Setting output step time to "
"%g seconds.", obp->step_time);
} else if (output_freq < 1) {
output_freq = 1;
obp->step_time = output_freq * state->time_unit;
if (state->notify->invalid_output_step_time != WARN_COPE)
mcell_warn("output step time too short.\n Setting output step time to "
"%g seconds.", obp->step_time);
}
/* Pick a good buffer size */
long long n_output;
if (state->chkpt_iterations)
n_output = (long long)(state->chkpt_iterations / output_freq + 1);
else
n_output = (long long)(state->iterations / output_freq + 1);
obp->buffersize = pick_buffer_size(state, obp, n_output);
no_printf("Default output step time definition:\n");
no_printf(" output step time = %g\n", obp->step_time);
no_printf(" output buffersize = %u\n", obp->buffersize);
}
/**************************************************************************
pick_buffer_size:
Choose an appropriate output buffer size for our reaction output data,
based on the total number of outputs expected and the requested buffer
size.
In: parse_state: parser state
obp: output block whose buffer_size to set
n_output: maximum number of outputs expected
Out: 0 on success, 1 on failure
**************************************************************************/
long long pick_buffer_size(MCELL_STATE *state, struct output_block *obp,
long long n_output) {
if (state->chkpt_iterations)
return min3ll(state->chkpt_iterations - state->start_iterations + 1, n_output,
obp->buffersize);
else
return min3ll(state->iterations - state->start_iterations + 1, n_output,
obp->buffersize);
}
/**************************************************************************
set_reaction_output_timer_iterations:
Set the output timer for reaction data output to a list of iterations.
In: parse_state: parser state
obp: output block whose timer is to be set
step_values: list of iterations
Out: 0 on success, 1 on failure; output timer is updated
**************************************************************************/
int
set_reaction_output_timer_iterations(MCELL_STATE *state,
struct output_block *obp,
struct num_expr_list_head *step_values) {
obp->timer_type = OUTPUT_BY_ITERATION_LIST;
obp->buffersize = pick_buffer_size(state, obp, step_values->value_count);
if (step_values->shared) {
obp->time_list_head = mcell_copysort_numeric_list(step_values->value_head);
if (obp->time_list_head == NULL)
return 1;
} else {
mcell_sort_numeric_list(step_values->value_head);
obp->time_list_head = step_values->value_head;
}
obp->time_now = NULL;
return 0;
}
/**************************************************************************
set_reaction_output_timer_times:
Set the output timer for reaction data output to a list of times.
In: parse_state: parser state
obp: output block whose timer is to be set
nstep: number of times
step_values: list of times
Out: output timer is updated
**************************************************************************/
int set_reaction_output_timer_times(MCELL_STATE *state,
struct output_block *obp,
struct num_expr_list_head *step_values) {
obp->timer_type = OUTPUT_BY_TIME_LIST;
obp->buffersize = pick_buffer_size(state, obp, step_values->value_count);
if (step_values->shared) {
obp->time_list_head = mcell_copysort_numeric_list(step_values->value_head);
if (obp->time_list_head == NULL)
return 1;
} else {
mcell_sort_numeric_list(step_values->value_head);
obp->time_list_head = step_values->value_head;
}
obp->time_now = NULL;
return 0;
}
/**************************************************************************
output_block_finalize:
Finalizes a reaction data output block, checking for errors, and allocating
the output buffer.
In: obp: the output block to finalize
Out: 0 on success, 1 on failure
**************************************************************************/
int output_block_finalize(struct output_block *obp) {
struct output_set *os1;
for (os1 = obp->data_set_head; os1 != NULL; os1 = os1->next) {
/* Check for duplicated filenames */
struct output_set *os2;
for (os2 = os1->next; os2 != NULL; os2 = os2->next) {
if (strcmp(os1->outfile_name, os2->outfile_name) == 0) {
mcell_error("COUNT statements in the same reaction data "
"output block should have unique output file "
"names (\"%s\" appears more than once)",
os1->outfile_name);
return MCELL_FAIL;
}
}
/* Allocate buffers */
struct output_column *oc;
for (oc = os1->column_head; oc != NULL; oc = oc->next) {
switch (oc->expr->expr_flags & OEXPR_TYPE_MASK) {
// Counting on meshes that don't exist at the beginning of the sim.
case OEXPR_TYPE_UNDEF:
oc->buffer = CHECKED_MALLOC_ARRAY(struct output_buffer,
obp->buffersize,
"reaction data output buffer");
for (u_int i = 0; i < obp->buffersize; ++i) {
oc->buffer[i].data_type = COUNT_UNSET;
oc->buffer[i].val.cval = 'X';
}
break;
case OEXPR_TYPE_INT:
oc->buffer = CHECKED_MALLOC_ARRAY(struct output_buffer,
obp->buffersize,
"reaction data output buffer");
for (u_int i = 0; i < obp->buffersize; ++i) {
oc->buffer[i].data_type = COUNT_INT;
oc->buffer[i].val.ival = 0;
}
break;
case OEXPR_TYPE_DBL:
oc->buffer = CHECKED_MALLOC_ARRAY(struct output_buffer,
obp->buffersize,
"reaction data output buffer");
for (u_int i = 0; i < obp->buffersize; ++i) {
oc->buffer[i].data_type = COUNT_DBL;
oc->buffer[i].val.dval = 0.0;
}
break;
case OEXPR_TYPE_TRIG:
oc->buffer = CHECKED_MALLOC_ARRAY(struct output_buffer,
obp->trig_bufsize,
"reaction data output buffer");
for (u_int i = 0; i < obp->trig_bufsize; ++i) {
oc->buffer[i].data_type = COUNT_TRIG_STRUCT;
oc->buffer[i].val.tval = CHECKED_MALLOC_STRUCT(
struct output_trigger_data,
"reaction data output buffer");
oc->buffer[i].val.tval->name = NULL;
}
break;
default:
mcell_error("Could not figure out what type of count data to store");
return MCELL_FAIL;
}
if (oc->buffer == NULL)
return MCELL_FAIL;
}
}
return MCELL_SUCCESS;
}
/************************************************************************
*
* get_counter_trigger_column retrieves the output_column corresponding
* to a given count or trigger statement.
*
************************************************************************/
struct output_column *get_counter_trigger_column(MCELL_STATE *state,
const char *counter_name,
int column_id) {
// retrieve the counter for the requested counter_name
struct sym_entry *counter_sym =
retrieve_sym(counter_name, state->counter_by_name);
if (counter_sym == NULL) {
mcell_log("Failed to retrieve symbol for counter %s.", counter_name);
return NULL;
}
struct output_set *counter = (struct output_set *)(counter_sym->value);
// retrieve the requested column
struct output_column *column = counter->column_head;
int count = 0;
while (count < column_id && column != NULL) {
count++;
column = column->next;
}
if (count != column_id || column == NULL) {
return NULL;
}
return column;
}
| C |
3D | mcellteam/mcell | src/volume_output.h | .h | 718 | 20 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
int update_volume_output(struct volume *wrld, struct volume_output_item *vo);
int output_volume_output_item(struct volume *wrld, char const *filename,
struct volume_output_item *vo);
| Unknown |
3D | mcellteam/mcell | src/react_output.h | .h | 1,886 | 48 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
/* Header file for reaction output routines */
extern int emergency_output_hook_enabled;
void install_emergency_output_hooks(struct volume *world);
int truncate_output_file(char *name, double start_value);
void add_trigger_output(struct volume *world, struct counter *c,
struct output_request *ear, int n, short flags,
u_long id);
int flush_reaction_output(struct volume *world);
int check_reaction_output_file(struct output_set *os);
int update_reaction_output(struct volume *world, struct output_block *block);
int write_reaction_output(struct volume *world, struct output_set *set);
struct output_expression *new_output_expr(struct mem_helper *oexpr_mem);
void set_oexpr_column(struct output_expression *oe, struct output_column *oc);
void learn_oexpr_flags(struct output_expression *oe);
struct output_expression *dupl_oexpr_tree(struct output_expression *root,
struct mem_helper *oexpr_mem);
struct output_expression *first_oexpr_tree(struct output_expression *root);
struct output_expression *next_oexpr_tree(struct output_expression *leaf);
void eval_oexpr_tree(struct output_expression *root, int skip_const);
void oexpr_flood_convert(struct output_expression *root, char old_oper,
char new_oper);
char *oexpr_title(struct output_expression *root);
| Unknown |
3D | mcellteam/mcell | src/nfsim_func.h | .h | 1,173 | 39 | #ifndef NFSIM_FUNC
#define NFSIM_FUNC
#include "mcell_structs.h"
// typedef double (*get_reactant_diffusion)(int a, int b);
void initialize_diffusion_function(struct abstract_molecule *mol_ptr);
void initialize_rxn_diffusion_functions(struct rxn *mol_ptr);
double get_standard_diffusion(void *self);
double get_nfsim_diffusion(void *self);
double get_standard_space_step(void *self);
double get_nfsim_space_step(void *self);
double get_standard_time_step(void *self);
double get_nfsim_time_step(void *self);
double rxn_get_nfsim_diffusion(struct rxn *, int);
double rxn_get_standard_diffusion(struct rxn *, int);
double rxn_get_nfsim_space_step(struct rxn *, int);
double rxn_get_standard_time_step(struct rxn *, int);
double rxn_get_nfsim_time_step(struct rxn *, int);
double rxn_get_standard_space_step(struct rxn *, int);
void initialize_graph_hashmap(void);
int get_graph_data(unsigned long graph_pattern_hash,
struct graph_data **graph_data);
int store_graph_data(unsigned long graph_pattern_hash,
struct graph_data *graph_data);
u_int get_nfsim_flags(void *mol_ptr);
u_int get_standard_flags(void *mol_ptr);
#endif
| Unknown |
3D | mcellteam/mcell | src/mem_util.c | .c | 19,418 | 621 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/**************************************************************************\
** File: mem_util.c **
** **
** Purpose: Handles various common memory-allocation tasks (stack,etc.) **
** **
** Testing status: counter broken. Everything else validated. **
** (See validate_mem_util.c.) **
\**************************************************************************/
#include "config.h"
#include <inttypes.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "strfunc.h"
#include "logging.h"
#include "mem_util.h"
#include "mcell_structs.h"
#ifdef MEM_UTIL_KEEP_STATS
#undef malloc
#undef free
#undef strdup
#undef realloc
#endif
#ifdef DEBUG
#define Malloc count_malloc
#else
#define Malloc malloc
#endif
#ifdef DEBUG
int howmany_count_malloc = 0;
void catch_me() {
printf("Allocating unreasonably many memory blocks--what are you doing?!\n");
exit(1);
}
void *count_malloc(size_t n) {
howmany_count_malloc++;
if (howmany_count_malloc > 200000) {
printf("Nuts!\n");
catch_me();
return NULL;
}
return malloc(n);
}
#endif
/*************************************************************************
* Checked malloc helpers
*************************************************************************/
static void memalloc_failure(char const *file, unsigned int line,
unsigned int size, char const *desc,
int onfailure) {
#ifdef MEM_UTIL_LINE_NUMBERS
if (desc)
mcell_error_nodie("File '%s', Line %u: Failed to allocate %u bytes for %s.",
file, line, size, desc);
else
mcell_error_nodie("File '%s', Line %u: Failed to allocate %u bytes.", file,
line, size);
#else
UNUSED(file);
UNUSED(line);
if (desc)
mcell_error_nodie("Failed to allocate %u bytes for %s.", size, desc);
else
mcell_error_nodie("Failed to allocate %u bytes.", size);
#endif
if (onfailure & CM_EXIT)
mcell_error("Out of memory.\n"); /* extra newline */
else
mcell_error_nodie("Out of memory.\n"); /* extra newline */
}
char *checked_strdup(char const *s, char const *file, unsigned int line,
char const *desc, int onfailure) {
if (s == NULL)
return NULL;
char *data = strdup(s);
if (data == NULL)
memalloc_failure(file, line, 1 + strlen(s), desc, onfailure);
return data;
}
void *checked_malloc(size_t size, char const *file, unsigned int line,
char const *desc, int onfailure) {
void *data = malloc(size);
if (data == NULL)
memalloc_failure(file, line, size, desc, onfailure);
return data;
}
char *checked_alloc_sprintf(char const *file, unsigned int line, int onfailure,
char const *fmt, ...) {
va_list args, saved_args;
va_start(args, fmt);
va_copy(saved_args, args);
char *data = alloc_vsprintf(fmt, args);
if (data == NULL) {
int needlen = vsnprintf(NULL, 0, fmt, saved_args);
memalloc_failure(file, line, needlen + 1, "formatted string", onfailure);
}
va_end(args);
va_end(saved_args);
return data;
}
void *checked_mem_get(struct mem_helper *mh, char const *file,
unsigned int line, char const *desc, int onfailure) {
void *data = mem_get(mh);
if (data == NULL)
memalloc_failure(file, line, mh->record_size, desc, onfailure);
return data;
}
/**************************************************************************\
** mem section: reusable block storage for small records of linked **
** lists. Each element is assumed to start with a "next" pointer. **
\**************************************************************************/
#ifdef MEM_UTIL_KEEP_STATS
struct mem_stats {
struct mem_stats *next;
char const *name;
long long int size;
long long int max_arenas;
long long int total_arenas;
long long int num_arenas_unfreed;
long long int non_head_arenas;
long long int max_non_head_arenas;
long long int total_non_head_arenas;
long long int unfreed_length;
long long int max_length;
long long int cur_free;
long long int max_free;
long long int cur_alloc;
long long int max_alloc;
};
static struct mem_stats *mem_stats_root = NULL;
static long long int mem_stats_cur_mallocs = 0;
static long long int mem_stats_cur_malloc_space = 0;
static long long int mem_stats_max_mallocs = 0;
static long long int mem_stats_max_malloc_space = 0;
static long long mem_stats_total_mallocs = 0;
static long long int mem_cur_overall_allocation = 0;
static long long int mem_max_overall_allocation = 0;
static long long int mem_cur_overall_wastage = 0;
static long long int mem_max_overall_wastage = 0;
void *mem_util_tracking_malloc(size_t size) {
unsigned char *bl = (unsigned char *)malloc(size + 16);
*(unsigned int *)bl = size;
if (bl != NULL) {
if (++mem_stats_cur_mallocs > mem_stats_max_mallocs)
mem_stats_max_mallocs = mem_stats_cur_mallocs;
if ((mem_stats_cur_malloc_space += size) > mem_stats_max_malloc_space)
mem_stats_max_malloc_space = mem_stats_cur_malloc_space;
if ((mem_cur_overall_allocation += size) > mem_max_overall_allocation)
mem_max_overall_allocation = mem_cur_overall_allocation;
++mem_stats_total_mallocs;
}
return (void *)(bl + 16);
}
void mem_util_tracking_free(void *data) {
unsigned char *bl = (unsigned char *)data;
bl -= 16;
--mem_stats_cur_mallocs;
mem_stats_cur_malloc_space -= *(unsigned int *)bl;
free(bl);
}
void *mem_util_tracking_realloc(void *data, size_t size) {
unsigned char *bl = (unsigned char *)data;
bl -= 16;
unsigned int oldsize = *(unsigned int *)bl;
if (oldsize >= size)
return data;
void *block = mem_util_tracking_malloc(size);
memcpy(block, data, oldsize);
mem_util_tracking_free(data);
return block;
}
char *mem_util_tracking_strdup(char const *in) {
size_t len = strlen(in);
void *block = mem_util_tracking_malloc(len + 1);
memcpy(block, in, len + 1);
return block;
}
static struct mem_stats *create_stats(char const *name, int size) {
struct mem_stats *s = (struct mem_stats *)malloc(sizeof(struct mem_stats));
s->next = mem_stats_root;
s->name = name;
s->size = size;
s->total_arenas = 0;
s->max_arenas = 0;
s->num_arenas_unfreed = 0;
s->non_head_arenas = 0;
s->max_non_head_arenas = 0;
s->total_non_head_arenas = 0;
s->unfreed_length = 0;
s->max_length = 0;
s->cur_free = 0;
s->max_free = 0;
s->cur_alloc = 0;
s->max_alloc = 0;
mem_stats_root = s;
return s;
}
static struct mem_stats *get_stats(char const *name, int size) {
struct mem_stats *s;
for (s = mem_stats_root; s != NULL; s = s->next) {
if (s->size != size)
continue;
if (name == NULL) {
if (s->name == NULL)
return s;
} else {
if (s->name != NULL && !strcmp(name, s->name))
return s;
}
}
return create_stats(name, size);
}
void mem_dump_stats(FILE *out) {
struct mem_stats *s;
for (s = mem_stats_root; s != NULL; s = s->next) {
char const *name = s->name;
if (name == NULL)
name = "(unnamed)";
fprintf(out, "%s [%lld]\n", s->name, s->size);
fprintf(out, "---------------------\n");
fprintf(out, "Num Arenas: %lld/%lld (%lld)\n",
s->num_arenas_unfreed, s->max_arenas, s->total_arenas);
fprintf(out, "Non-head arenas: %lld/%lld (%lld)\n", s->non_head_arenas,
s->max_non_head_arenas, s->total_non_head_arenas);
fprintf(out, "Total Items: %lld/%lld\n", s->unfreed_length,
s->max_length);
fprintf(out, "Free Items: %lld/%lld\n", s->cur_free, s->max_free);
fprintf(out, "Alloced Items: %lld/%lld\n", s->cur_alloc,
s->max_alloc);
fprintf(out, "Space usage: %lld/%lld\n", s->size * s->cur_alloc,
s->size * s->max_alloc);
fprintf(out, "Space wastage: %lld/%lld\n", s->size * s->cur_free,
s->size * s->max_free);
fprintf(out, "Arena overhead: %lld/%lld\n",
(int)sizeof(struct mem_helper) * s->num_arenas_unfreed,
(int)sizeof(struct mem_helper) * s->max_arenas);
fprintf(out, "\n");
}
fprintf(out, "Malloc stats:\n");
fprintf(out, "---------------------\n");
fprintf(out, "Mallocs: %lld/%lld (%lld)\n",
mem_stats_cur_mallocs, mem_stats_max_mallocs,
mem_stats_total_mallocs);
fprintf(out, "Space used: %lld/%lld\n", mem_stats_cur_malloc_space,
mem_stats_max_malloc_space);
fprintf(out, "\n");
fprintf(out, "Summary stats:\n");
fprintf(out, "---------------------\n");
fprintf(out, "Allocation: %lld/%lld\n", mem_cur_overall_allocation,
mem_max_overall_allocation);
fprintf(out, "Waste: %lld/%lld\n", mem_cur_overall_wastage,
mem_max_overall_wastage);
fprintf(out, "\n");
}
#endif
/*************************************************************************
create_mem_named:
In: Size of a single element (including the leading "next" pointer)
Number of elements to allocate at once
Name of "arena" (used for statistics)
Out: Pointer to a new mem_helper struct.
*************************************************************************/
struct mem_helper *create_mem_named(size_t size, int length, char const *name) {
struct mem_helper *mh;
mh = (struct mem_helper *)Malloc(sizeof(struct mem_helper));
if (mh == NULL)
return NULL;
mh->buf_len = (length > 0) ? length : 128;
mh->record_size =
(size > (int)sizeof(void *)) ? (size_t)size : sizeof(void *);
mh->buf_index = 0;
mh->defunct = NULL;
mh->next_helper = NULL;
#ifndef MEM_UTIL_NO_POOLING
#ifdef MEM_UTIL_TRACK_FREED
mh->heap_array =
(unsigned char *)Malloc(mh->buf_len * (mh->record_size + sizeof(int)));
memset(mh->heap_array, 0, mh->buf_len * (mh->record_size + sizeof(int)));
#else
mh->heap_array = (unsigned char *)Malloc(mh->buf_len * mh->record_size);
#endif
if (mh->heap_array == NULL) {
free(mh);
return NULL;
}
#else
mh->heap_array = NULL;
#endif
#ifdef MEM_UTIL_KEEP_STATS
struct mem_stats *s = mh->stats = get_stats(name, size);
++s->num_arenas_unfreed;
++s->total_arenas;
if (s->num_arenas_unfreed > s->max_arenas)
s->max_arenas = s->num_arenas_unfreed;
s->unfreed_length += length;
if (s->unfreed_length > s->max_length)
s->max_length = s->unfreed_length;
s->cur_free += length;
if (s->cur_free > s->max_free)
s->max_free = s->cur_free;
if ((mem_cur_overall_wastage += size * length) > mem_max_overall_wastage)
mem_max_overall_wastage = mem_cur_overall_wastage;
#else
UNUSED(name);
#endif
return mh;
}
/*************************************************************************
create_mem:
In: Size of a single element (including the leading "next" pointer)
Number of elements to allocate at once
Out: Pointer to a new mem_helper struct.
*************************************************************************/
struct mem_helper *create_mem(size_t size, int length) {
return create_mem_named(size, length, NULL);
}
/*************************************************************************
mem_get:
In: A mem_helper
Out: A pointer to new storage of the appropriate size.
Note: Use this instead of "Malloc".
*************************************************************************/
void *mem_get(struct mem_helper *mh) {
#ifdef MEM_UTIL_NO_POOLING
return malloc(mh->record_size);
#else
if (mh->defunct != NULL) {
struct abstract_list *retval;
retval = mh->defunct;
mh->defunct = retval->next;
#ifdef MEM_UTIL_KEEP_STATS
struct mem_stats *s = mh->stats;
--s->cur_free;
++s->cur_alloc;
if (s->cur_alloc > s->max_alloc)
s->max_alloc = s->cur_alloc;
if ((mem_cur_overall_allocation += mh->record_size) >
mem_max_overall_allocation)
mem_max_overall_allocation = mem_cur_overall_allocation;
mem_cur_overall_wastage -= mh->record_size;
#endif
#ifdef MEM_UTIL_ZERO_FREED
{
unsigned char *thisData = (unsigned char *)retval;
size_t i;
thisData += sizeof(struct abstract_element *);
for (i = 0; i < mh->record_size - sizeof(struct abstract_element *);) {
if (thisData[i] != '\0') {
mcell_warn("Memory block at %08lx: non-zero at byte %d: %02x %02x "
"%02x %02x...",
retval, i, thisData[i], thisData[i + 1], thisData[i + 2],
thisData[i + 3]);
i += 4;
} else
++i;
}
memset(thisData, 0, mh->record_size - sizeof(struct abstract_element *));
}
#endif
#ifdef MEM_UTIL_TRACK_FREED
if (((int *)retval)[-1]) {
mcell_warn("Duplicate allocation of ptr '%p'.", retval);
return NULL;
}
((int *)retval)[-1] = 1;
#endif
return (void *)retval;
} else if (mh->buf_index < mh->buf_len) {
#ifdef MEM_UTIL_TRACK_FREED
size_t offset = mh->buf_index * (mh->record_size + sizeof(int));
#else
size_t offset = mh->buf_index * mh->record_size;
#endif
mh->buf_index++;
#ifdef MEM_UTIL_KEEP_STATS
struct mem_stats *s = mh->stats;
--s->cur_free;
++s->cur_alloc;
if (s->cur_alloc > s->max_alloc)
s->max_alloc = s->cur_alloc;
if ((mem_cur_overall_allocation += mh->record_size) >
mem_max_overall_allocation)
mem_max_overall_allocation = mem_cur_overall_allocation;
mem_cur_overall_wastage -= mh->record_size;
#endif
#ifdef MEM_UTIL_TRACK_FREED
int *ptr = (int *)(mh->heap_array + offset);
if (*ptr) {
mcell_warn("Duplicate allocation of ptr '%p'.", ptr + 1);
return NULL;
}
*ptr++ = 1;
return (void *)ptr;
#else
return (void *)(mh->heap_array + offset);
#endif
} else {
struct mem_helper *mhnext;
unsigned char *temp;
#ifdef MEM_UTIL_KEEP_STATS
struct mem_stats *s = mh->stats;
mhnext = create_mem_named(mh->record_size, mh->buf_len, s->name);
++s->non_head_arenas;
if (s->non_head_arenas > s->max_non_head_arenas)
s->max_non_head_arenas = s->non_head_arenas;
++s->total_non_head_arenas;
#else
mhnext = create_mem(mh->record_size, mh->buf_len);
#endif
if (mhnext == NULL)
return NULL;
/* Swap contents of this mem_helper with new one */
/* Keeps mh at top of list but with freshly allocated space */
mhnext->next_helper = mh->next_helper;
temp = mhnext->heap_array;
mhnext->heap_array = mh->heap_array;
mh->heap_array = temp;
mhnext->buf_index = mh->buf_index;
mh->next_helper = mhnext;
mh->buf_index = 0;
return mem_get(mh);
}
#endif
}
/*************************************************************************
mem_put:
In: A mem_helper
A pointer to the memory you no longer need
Out: No return value. The defunct memory is stored for later use.
Note: Defunct memory need not have come from the same mem_helper.
Use this instead of "free".
*************************************************************************/
void mem_put(struct mem_helper *mh, void *defunct) {
#ifdef MEM_UTIL_NO_POOLING
free(defunct);
return;
#else
struct abstract_list *data = (struct abstract_list *)defunct;
#ifdef MEM_UTIL_TRACK_FREED
int *ptr = (int *)data;
if (ptr[-1] == 0) {
mcell_warn("Duplicate free of ptr '%p'.", defunct);
return;
}
ptr[-1] = 0;
#endif
#ifdef MEM_UTIL_ZERO_FREED
memset(data, 0, mh->record_size);
#endif
data->next = mh->defunct;
mh->defunct = data;
#ifdef MEM_UTIL_KEEP_STATS
struct mem_stats *s = mh->stats;
++s->cur_free;
--s->cur_alloc;
if (s->cur_free > s->max_free)
s->max_free = s->cur_free;
mem_cur_overall_allocation -= mh->record_size;
if ((mem_cur_overall_wastage += mh->record_size) > mem_max_overall_wastage)
mem_max_overall_wastage = mem_cur_overall_wastage;
#endif
#endif
}
/*************************************************************************
mem_put_list:
In: A mem_helper
A pointer to the memory you no longer need
Out: No return value. The input is taken to be a NULL-terminated
singly-linked list. Everything in that list is "freed" and
held for later use.
*************************************************************************/
void mem_put_list(struct mem_helper *mh, void *defunct) {
struct abstract_list *data = (struct abstract_list *)defunct;
struct abstract_list *alp;
#ifdef MEM_UTIL_NO_POOLING
struct abstract_list *alpNext;
for (alp = data; alp != NULL; alp = alpNext) {
alpNext = alp->next;
free(alp);
}
#else
#ifdef MEM_UTIL_ZERO_FREED
for (alp = data; alp != NULL; alp = alp->next) {
unsigned char *thisData = (unsigned char *)alp;
thisData += sizeof(struct abstract_element *);
memset(thisData, 0, mh->record_size - sizeof(struct abstract_element *));
}
#endif
#ifdef MEM_UTIL_TRACK_FREED
for (alp = data; alp != NULL; alp = alp->next) {
int *ptr = (int *)alp;
if (ptr[-1] == 0) {
mcell_warn("Duplicate free of ptr '%p'.", defunct);
return;
}
ptr[-1] = 0;
}
#endif
#ifdef MEM_UTIL_KEEP_STATS
int count = 1;
for (alp = data; alp->next != NULL; alp = alp->next)
++count;
struct mem_stats *s = mh->stats;
s->cur_free += count;
s->cur_alloc -= count;
if (s->cur_free > s->max_free)
s->max_free = s->cur_free;
mem_cur_overall_allocation -= mh->record_size * count;
if ((mem_cur_overall_wastage += mh->record_size * count) >
mem_max_overall_wastage)
mem_max_overall_wastage = mem_cur_overall_wastage;
#else
for (alp = data; alp->next != NULL; alp = alp->next) {
}
#endif
alp->next = mh->defunct;
mh->defunct = data;
#endif
}
/*************************************************************************
delete_mem:
In: A mem_helper
Out: All memory allocated by this mem_helper is freed, and the
mem_helper struct itself is also. However, defunct memory
from other mem_helpers (or elsewhere) is not freed.
*************************************************************************/
void delete_mem(struct mem_helper *mh) {
if (mh == NULL)
return;
#ifndef MEM_UTIL_NO_POOLING
#ifdef MEM_UTIL_KEEP_STATS
struct mem_stats *s = mh->stats;
--s->num_arenas_unfreed;
s->cur_alloc -= mh->buf_index;
s->cur_free -= (mh->buf_len - mh->buf_index);
s->unfreed_length -= mh->buf_len;
mem_cur_overall_allocation -= mh->record_size * mh->buf_len;
mem_cur_overall_wastage -= mh->record_size * (mh->buf_len - mh->buf_index);
if (mh->next_helper) {
delete_mem(mh->next_helper);
--s->max_non_head_arenas;
}
#else
if (mh->next_helper)
delete_mem(mh->next_helper);
#endif
free(mh->heap_array);
#endif
free(mh);
}
| C |
3D | mcellteam/mcell | src/viz_output.c | .c | 101,714 | 2,583 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <stdarg.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>
#ifndef _MSC_VER
#include <unistd.h>
#include <dirent.h>
#endif
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <assert.h>
#include "c_vector.h"
#include "debug_config.h"
/*
#include "isaac64.h"
#include "rng.h"
*/
#include "logging.h"
#include "mcell_structs.h"
#include "grid_util.h"
#include "sched_util.h"
#include "viz_output.h"
#include "strfunc.h"
#include "util.h"
#include "vol_util.h"
#include "sym_table.h"
#include "bng_util.h"
/*** Temporary Viz Options compared to world->viz_options ***/
#define VIZ_OPTS_NONE 0x00L
#define VIZ_COMP_NAMING_MASK 0x0FL /* Lowest hex digit */
#define VIZ_COMP_ALL_SAME 0x01L /* Name all component "molecules" with the same name */
#define VIZ_COMP_NAME_GLOBAL 0x02L /* Name all component "molecules" by their global component name */
#define VIZ_COMP_MOL_LOCAL 0x03L /* Name all component "molecules" by their molecule and component name */
#define VIZ_PROXY_OUTPUT 0x08L /* Force output of proxy molecules */
#define VIZ_ALT_FILES_MASK 0xF0L /* Second lowest hex digit */
#define VIZ_ALT_DUMP_FMT 0x10L /* Text format for human reading */
#define VIZ_JSON_MOLCOMP_FMT 0x20L /* Text format using JSON lists to represent a molecule/component list */
/* Output frame types. */
static int output_ascii_molecules(struct volume *world,
struct viz_output_block *,
struct frame_data_list *fdlp);
static int output_cellblender_molecules(struct volume *world,
struct viz_output_block *,
struct frame_data_list *fdlp);
/* == viz-specific Utilities == */
/*************************************************************************
frame_iteration:
Gets the iteration number for a given time/iteration value and "type".
In: double iterval - the time/iteration value
int type - the type of value
Out: the frame time as an iteration number
**************************************************************************/
static long long frame_iteration(struct volume *world, double iterval,
int type) {
switch (type) {
case OUTPUT_BY_ITERATION_LIST:
return (long long)iterval;
case OUTPUT_BY_TIME_LIST:
if (world->chkpt_seq_num == 1) {
return (long long)(iterval / world->time_unit + ROUND_UP);
} else {
if (iterval >= world->simulation_start_seconds) {
return (long long) convert_seconds_to_iterations(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, iterval) + ROUND_UP;
} else {
/* This iteration_time was in the past - just return flag.
We do this because TIME_STEP may have been changed between
checkpoints */
return INT_MIN;
}
}
default:
mcell_internal_error("Invalid frame_data_list list_type (%d).", type);
/*return -1;*/
}
}
/*************************************************************************
sort_molecules_by_species:
Scans over all molecules, sorting them into arrays by species.
In: struct abstract_molecule ****viz_molpp
u_int **viz_mol_countp
int include_volume - should the lists include vol mols?
int include_grid - should the lists include surface mols?
Out: 0 on success, 1 on error; viz_molpp and viz_mol_countp arrays are
allocated and filled with sorted data.
**************************************************************************/
static int sort_molecules_by_species(struct volume *world,
struct viz_output_block *vizblk,
struct abstract_molecule ****viz_molpp,
u_int **viz_mol_countp, int include_volume,
int include_grid) {
struct storage_list *slp;
u_int *counts;
int species_index;
/* XXX: May leave memory allocated on failure */
if ((*viz_molpp = (struct abstract_molecule ***)allocate_ptr_array(
world->n_species)) == NULL)
return 1;
if ((counts = *viz_mol_countp = allocate_uint_array(world->n_species, 0)) ==
NULL)
return 1;
/* Walk through the species allocating arrays for all molecules of that
* species */
for (species_index = 0; species_index < world->n_species; ++species_index) {
int mol_count;
u_int spec_id = world->species_list[species_index]->species_id;
if (vizblk->species_viz_states[species_index] == EXCLUDE_OBJ)
continue;
if (world->species_list[species_index]->flags & IS_SURFACE)
continue;
if (!include_grid && (world->species_list[species_index]->flags & ON_GRID))
continue;
if (!include_volume &&
!(world->species_list[species_index]->flags & ON_GRID))
continue;
mol_count = world->species_list[species_index]->population;
if (mol_count <= 0)
continue;
if (((*viz_molpp)[spec_id] =
(struct abstract_molecule **)allocate_ptr_array(mol_count)) ==
NULL)
return 1;
}
/* Sort molecules by species id */
for (slp = world->storage_head; slp != NULL; slp = slp->next) {
struct storage *sp = slp->store;
struct schedule_helper *shp;
struct abstract_molecule *amp;
int sched_slot_index;
for (shp = sp->timer; shp != NULL; shp = shp->next_scale) {
for (sched_slot_index = -1; sched_slot_index < shp->buf_len;
++sched_slot_index) {
for (amp = (struct abstract_molecule *)((sched_slot_index < 0)
? shp->current
: shp->circ_buf_head
[sched_slot_index]);
amp != NULL; amp = amp->next) {
u_int spec_id;
if (amp->properties == NULL)
continue;
spec_id = amp->properties->species_id;
if (vizblk->species_viz_states[spec_id] == EXCLUDE_OBJ)
continue;
if (!include_grid && (amp->flags & TYPE_MASK) != TYPE_VOL)
continue;
if (!include_volume && (amp->flags & TYPE_MASK) == TYPE_VOL)
continue;
if (counts[spec_id] < amp->properties->population)
(*viz_molpp)[spec_id][counts[spec_id]++] = amp;
else {
mcell_warn("Molecule count disagreement!\n"
" Species %s population = %d count = %d",
amp->properties->sym->name, amp->properties->population,
counts[spec_id]);
}
}
}
}
}
return 0;
}
/*************************************************************************
reset_time_values:
Scan over all frame data elements, resetting the "next" iteration state to
the soonest iteration following or equal to the specified iteration.
In: struct frame_data_list *fdlp - the head of the frame data list
long long curiter - the minimum iteration number
Out: 0 on success, 1 on failure
**************************************************************************/
static int reset_time_values(struct volume *world, struct frame_data_list *fdlp,
long long curiter) {
/* If we've loaded a checkpoint, don't output on the first iter */
if (curiter != 0)
++curiter;
for (; fdlp != NULL; fdlp = fdlp->next) {
fdlp->curr_viz_iteration = fdlp->iteration_list;
fdlp->viz_iteration = -1;
/* Scan for first iteration >= curiter */
while (fdlp->curr_viz_iteration != NULL) {
if (frame_iteration(world, fdlp->curr_viz_iteration->value,
fdlp->list_type) >= curiter)
break;
fdlp->curr_viz_iteration = fdlp->curr_viz_iteration->next;
}
/* If we had an iteration, use it to set viz_iteration */
if (fdlp->curr_viz_iteration != NULL)
fdlp->viz_iteration = frame_iteration(
world, fdlp->curr_viz_iteration->value, fdlp->list_type);
}
return 0;
}
/*************************************************************************
count_time_values:
Scan over all frame data elements, counting iterations. The number of
distinct iterations on which viz data will be output is returned. In the
process, each frame data elements n_viz_iterations is set, as is the "final
viz iteration". The total number of distinct iterations is returned.
In: struct frame_data_list *fdlp - the head of the frame data list
Out: num distinct iterations
**************************************************************************/
static int count_time_values(struct volume *world,
struct frame_data_list *const fdlp) {
int time_values = 0;
long long curiter = -1;
struct frame_data_list *fdlpcur = NULL;
for (fdlpcur = fdlp; fdlpcur != NULL; fdlpcur = fdlpcur->next) {
fdlpcur->curr_viz_iteration = fdlpcur->iteration_list;
fdlpcur->n_viz_iterations = 0;
fdlpcur->viz_iteration = -1;
}
while (1) {
curiter = -1;
/* Find the next iteration */
for (fdlpcur = fdlp; fdlpcur != NULL; fdlpcur = fdlpcur->next) {
long long thisiter;
if (fdlpcur->curr_viz_iteration == NULL)
continue;
thisiter = frame_iteration(world, fdlpcur->curr_viz_iteration->value,
fdlpcur->list_type);
if (curiter == -1)
curiter = thisiter;
else if (thisiter < curiter)
curiter = thisiter;
}
/* If we found no new iteration, quit */
if (curiter == -1)
break;
/* We won't create any more output frames after the apocalypse. */
if (curiter > world->iterations)
break;
/* We won't create any more output frames after we checkpoint. */
if (world->chkpt_iterations != 0 &&
curiter > world->start_iterations + world->chkpt_iterations)
break;
/* We found at least one more. Note that the only time we will output at
* iteration == start_iterations is when start_iterations is zero. This is because we
* do not output on the first iteration after we resume.
*/
if (curiter > world->start_iterations)
++time_values;
else if ((world->start_iterations | curiter) == 0)
++time_values;
/* Advance any frame data items which are set to this iteration */
for (fdlpcur = fdlp; fdlpcur != NULL; fdlpcur = fdlpcur->next) {
if (fdlpcur->curr_viz_iteration == NULL)
continue;
if (curiter > world->start_iterations || (world->start_iterations | curiter) == 0) {
if (frame_iteration(world, fdlpcur->curr_viz_iteration->value,
fdlpcur->list_type) == curiter)
++fdlpcur->n_viz_iterations;
}
while (fdlpcur->curr_viz_iteration &&
frame_iteration(world, fdlpcur->curr_viz_iteration->value,
fdlpcur->list_type) == curiter)
fdlpcur->curr_viz_iteration = fdlpcur->curr_viz_iteration->next;
}
}
return time_values;
}
/************************************************************************
output_ascii_molecules:
In: vizblk: VIZ_OUTPUT block for this frame list
a frame data list (internal viz output data structure)
Out: 0 on success, 1 on failure. The positions of molecules are output
in exponential floating point notation (with 8 decimal places)
*************************************************************************/
static int output_ascii_molecules(struct volume *world,
struct viz_output_block *vizblk,
struct frame_data_list *fdlp) {
FILE *custom_file;
char *cf_name;
struct storage_list *slp;
struct schedule_helper *shp;
struct abstract_element *aep;
struct abstract_molecule *amp;
struct volume_molecule *mp;
struct surface_molecule *gmp;
short orient = 0;
int ndigits, i;
long long lli;
struct vector3 where, norm;
no_printf("Output in ASCII mode (molecules only)...\n");
if ((fdlp->type == ALL_MOL_DATA) || (fdlp->type == MOL_POS)) {
lli = 10;
for (ndigits = 1; lli <= world->iterations && ndigits < 20;
lli *= 10, ndigits++) {
}
cf_name =
CHECKED_SPRINTF("%s.ascii.%.*lld.dat", vizblk->file_prefix_name,
ndigits, fdlp->viz_iteration);
if (cf_name == NULL)
return 1;
if (make_parent_dir(cf_name)) {
free(cf_name);
mcell_error(
"Failed to create parent directory for ASCII-mode VIZ output.");
/*return 1;*/
}
custom_file = open_file(cf_name, "w");
if (!custom_file)
mcell_die();
else {
no_printf("Writing to file %s\n", cf_name);
}
free(cf_name);
cf_name = NULL;
c_vector_t *vec = vector_create();
for (slp = world->storage_head; slp != NULL; slp = slp->next) {
for (shp = slp->store->timer; shp != NULL; shp = shp->next_scale) {
for (i = -1; i < shp->buf_len; i++) {
for (aep = (i < 0) ? shp->current : shp->circ_buf_head[i];
aep != NULL; aep = aep->next) {
amp = (struct abstract_molecule *)aep;
if (amp->properties == NULL)
continue;
// remember
vector_push_back(vec, amp);
}
}
}
}
#ifdef MCELL3_SORTED_VIZ_OUTPUT
// sort - necessary for comparison with mcell4 because
// molecules with diffusion constant zero are printed out in some "random" order
vector_sort_by_mol_id(vec);
#endif
// print
size_t sz = vector_get_size(vec);
for (size_t k = 0; k < sz; k++) {
amp = (struct abstract_molecule*)vector_at(vec, k);
int id = vizblk->species_viz_states[amp->properties->species_id];
if (id == EXCLUDE_OBJ)
continue;
if ((amp->properties->flags & NOT_FREE) == 0) {
mp = (struct volume_molecule *)amp;
where.x = mp->pos.x;
where.y = mp->pos.y;
where.z = mp->pos.z;
norm.x = 0;
norm.y = 0;
norm.z = 0;
} else if ((amp->properties->flags & ON_GRID) != 0) {
gmp = (struct surface_molecule *)amp;
uv2xyz(&(gmp->s_pos), gmp->grid->surface, &where);
orient = gmp->orient;
norm.x = orient * gmp->grid->surface->normal.x;
norm.y = orient * gmp->grid->surface->normal.y;
norm.z = orient * gmp->grid->surface->normal.z;
} else
continue;
where.x *= world->length_unit;
where.y *= world->length_unit;
where.z *= world->length_unit;
/*
fprintf(custom_file,"%d %15.8e %15.8e %15.8e
%2d\n",id,where.x,where.y,where.z,orient);
*/
std::string species_name = amp->properties->sym->name;
#ifdef ASCII_VIZ_EXTERNAL_SPECIES_NAME
if ((amp->properties->flags & EXTERNAL_SPECIES) != 0) {
/* This is complex molecule, so add a new viz molecule for each molecule in the complex */
/* The graph pattern will be something like: */
/* c:SH2~NO_STATE!5,c:U~NO_STATE!5!3,c:a~NO_STATE!6,c:b~Y!6!1,c:g~Y!6,m:Lyn@PM!0!1,m:Rec@PM!2!3!4, */
species_name = graph_pattern_to_bngl(amp->graph_data->graph_pattern);
}
#endif
if (id == INCLUDE_OBJ) {
/* write name of molecule */
fprintf(custom_file, "%s %lu %.9g %.9g %.9g %.9g %.9g %.9g\n",
species_name.c_str(), amp->id, where.x, where.y,
where.z, norm.x, norm.y, norm.z);
} else {
/* write state value of molecule */
fprintf(custom_file, "%d %lu %.9g %.9g %.9g %.9g %.9g %.9g\n", id,
amp->id, where.x, where.y, where.z, norm.x, norm.y,
norm.z);
}
}
vector_delete(vec);
fclose(custom_file);
}
return 0;
}
typedef struct external_mol_viz_struct {
char mol_type; /* s = surface, v = volume, n = none (don't display?) */
float pos_x, pos_y, pos_z;
float norm_x, norm_y, norm_z;
struct external_mol_viz_struct *next_mol;
} external_mol_viz;
typedef struct external_mol_viz_by_name_struct {
char *mol_name;
external_mol_viz *mol_list;
struct external_mol_viz_by_name_struct *next_name;
} external_mol_viz_by_name;
typedef struct external_mol_viz_entry_struct {
char *mol_id_string; /* Typically the NAUTY string (although that will be the key) */
} external_mol_viz_entry;
static struct sym_table_head *graph_pattern_table = NULL;
static long next_molcomp_id = 0L;
typedef struct external_molcomp_loc_struct {
bool is_mol;
bool has_coords;
bool is_final;
double x, y, z;
double kx, ky, kz;
char *name;
char *graph_string;
int num_peers;
int *peers;
char *states;
} external_molcomp_loc;
typedef struct molcomp_list_struct {
external_molcomp_loc *molcomp_array;
int num_molcomp_items;
long molcomp_id;
} molcomp_list;
static void dump_molcomp_array_to ( FILE *out_file, external_molcomp_loc *molcomp_array, int num_parts ) {
int i, j;
fprintf ( out_file, "%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%\n" );
for (i=0; i<num_parts; i++) {
fprintf ( out_file, "[%d] = %s (", i, molcomp_array[i].name );
if (molcomp_array[i].is_mol) {
fprintf ( out_file, "m" );
} else {
fprintf ( out_file, "c" );
}
fprintf ( out_file, ") at (%g, %g, %g) with peers [", molcomp_array[i].x, molcomp_array[i].y, molcomp_array[i].z );
for (j=0; j<molcomp_array[i].num_peers; j++) {
fprintf ( out_file, "%d", molcomp_array[i].peers[j] );
if (j < molcomp_array[i].num_peers - 1) {
fprintf ( out_file, "," );
}
}
fprintf ( out_file, "]\n" );
}
fprintf ( out_file, "%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%=%%\n" );
}
static void dump_molcomp_list_to ( FILE *out_file, molcomp_list *mcl ) {
fprintf ( out_file, "ID=%ld\n", mcl->molcomp_id );
dump_molcomp_array_to ( out_file, mcl->molcomp_array, mcl->num_molcomp_items );
}
static void dump_molcomp_array ( external_molcomp_loc *molcomp_array, int num_parts ) {
dump_molcomp_array_to ( stdout, molcomp_array, num_parts );
}
/* Currently unused except in commented code
static void dump_molcomp_list ( molcomp_list *mcl ) {
dump_molcomp_list_to ( stdout, mcl );
}
*/
double clipped_cos ( double angle ) {
double v = cos(angle);
if ((v > -1e-6) && (v < 1e-6)) v = 0;
return ( v );
}
double clipped_sin ( double angle ) {
double v = sin(angle);
if ((v > -1e-6) && (v < 1e-6)) v = 0;
return ( v );
}
static void set_component_positions_by_table ( struct volume *world, external_molcomp_loc *mc, int num_parts ) {
double scale = 0.02;
int mi;
//fprintf ( stdout, "Setting positions by table.\n" );
// Dump the table just to verify how to read it
//fprintf ( stdout, "==============================================\n" );
//dump_symtab(world->mol_ss_sym_table);
//fprintf ( stdout, "==============================================\n" );
for (mi=0; mi<num_parts; mi++) {
if (mc[mi].is_mol) {
// Look up this molecule in the table
//fprintf ( stdout, " Looking up component positions for %s\n", mc[mi].name );
struct sym_entry *sp;
sp = retrieve_sym(mc[mi].name, world->mol_ss_sym_table);
if (sp != NULL) {
//fprintf ( stdout, " Got an entry with symbol type %d and name %s\n", sp->sym_type, sp->name );
// Fill in all of the component positions in this molecule from the list
if (sp->sym_type == MOL_SS) {
//fprintf ( stdout, " It's a Spatially Structured Molecule!!\n" );
// Set the has_coords flag to false on each component of this molecule
for (int ci=0; ci<mc[mi].num_peers; ci++) {
mc[mc[mi].peers[ci]].has_coords = false;
}
// Walk through the list of component positions and for each one, find a matching mol_comp entry without coordinates
struct mol_ss *mol_ss_ptr = (struct mol_ss *)(sp->value);
struct mol_comp_ss *mc_ptr = mol_ss_ptr->mol_comp_ss_head;
int comp_count = 0;
// char *translations[5] = { "COINCIDENT", "XYZ", "XYZA", "XYZRef", "XYZVA" };
while (mc_ptr != NULL) {
//fprintf ( stdout, " Component %d is \"%s\" of type %s at (%g,%g,%g).\n", comp_count, mc_ptr->name, translations[mc_ptr->spatial_type], mc_ptr->loc_x, mc_ptr->loc_y, mc_ptr->loc_z );
for (int ci=0; ci<mc[mi].num_peers; ci++) {
if ( (!mc[mc[mi].peers[ci]].has_coords) && (strcmp(mc[mc[mi].peers[ci]].name, mc_ptr->name) == 0) ) {
mc[mc[mi].peers[ci]].x = mc_ptr->loc_x;
mc[mc[mi].peers[ci]].y = mc_ptr->loc_y;
mc[mc[mi].peers[ci]].z = mc_ptr->loc_z;
mc[mc[mi].peers[ci]].kx = mc_ptr->rot_axis_x; // These are currently key locations rather than rotation axis locations
mc[mc[mi].peers[ci]].ky = mc_ptr->rot_axis_y; // These are currently key locations rather than rotation axis locations
mc[mc[mi].peers[ci]].kz = mc_ptr->rot_axis_z; // These are currently key locations rather than rotation axis locations
mc[mc[mi].peers[ci]].has_coords = true;
if (world->dump_level >= 20) {
fprintf ( stdout, " Component %s is at (%g,%g,%g)\n", mc[mc[mi].peers[ci]].name, mc[mc[mi].peers[ci]].x, mc[mc[mi].peers[ci]].y, mc[mc[mi].peers[ci]].z );
fprintf ( stdout, " Ref key for %s is at (%g,%g,%g)\n", mc[mc[mi].peers[ci]].name, mc[mc[mi].peers[ci]].kx, mc[mc[mi].peers[ci]].ky, mc[mc[mi].peers[ci]].kz );
}
break;
}
}
comp_count += 1;
mc_ptr = mc_ptr->next;
}
//fprintf ( stdout, " This molecule has %d components.\n", comp_count );
// Just to be sure, set any unset coordinates to 0
for (int ci=0; ci<mc[mi].num_peers; ci++) {
if (!mc[mc[mi].peers[ci]].has_coords) {
mc[mc[mi].peers[ci]].x = 0.0;
mc[mc[mi].peers[ci]].y = 0.0;
mc[mc[mi].peers[ci]].z = 0.0;
mc[mc[mi].peers[ci]].kx = 0.0;
mc[mc[mi].peers[ci]].ky = 0.0;
mc[mc[mi].peers[ci]].kz = 0.0;
mc[mc[mi].peers[ci]].has_coords = true;
}
}
}
} else {
fprintf ( stdout, " No entry found for %s, using default. This is unexpected!!\n", mc[mi].name );
for (int ci=0; ci<mc[mi].num_peers; ci++) {
double angle = 2 * MY_PI * ci / mc[mi].num_peers;
mc[mc[mi].peers[ci]].x = scale * cos(angle);
mc[mc[mi].peers[ci]].y = scale * sin(angle);
mc[mc[mi].peers[ci]].z = 0.0;
mc[mc[mi].peers[ci]].kx = 0.0;
mc[mc[mi].peers[ci]].ky = 0.0;
mc[mc[mi].peers[ci]].kz = scale;
//#### fprintf ( stdout, " Component %s is at (%g,%g)\n", mc[mc[mi].peers[ci]].name, mc[mc[mi].peers[ci]].x, mc[mc[mi].peers[ci]].y );
}
}
}
}
}
static void bind_molecules_at_components ( struct volume *world, external_molcomp_loc *mc, int num_parts, int fixed_comp_index, int var_comp_index, bool as3D, bool with_rot ) {
// Bind these two molecules by aligning their axes and shifting to align their components
//#### fprintf ( stdout, "########## Binding %s to %s\n", mc[fixed_comp_index].name, mc[var_comp_index].name );
//#### dump_molcomp_array(mc,num_parts);
int fixed_mol_index = mc[fixed_comp_index].peers[0];
int var_mol_index = mc[var_comp_index].peers[0];
double fixed_vec[3] = {0, 0, 0}; // This will either hold 2 or 3 values, but since it's temporary, the allocation difference doesn't accumulate.
double var_vec[3] = {0, 0, 0};
fixed_vec[0] = mc[fixed_comp_index].x - mc[fixed_mol_index].x;
fixed_vec[1] = mc[fixed_comp_index].y - mc[fixed_mol_index].y;
var_vec[0] = mc[ var_comp_index].x - mc[ var_mol_index].x;
var_vec[1] = mc[ var_comp_index].y - mc[ var_mol_index].y;
if (as3D) {
fixed_vec[2] = mc[fixed_comp_index].z - mc[fixed_mol_index].z;
var_vec[2] = mc[ var_comp_index].z - mc[ var_mol_index].z;
}
double fixed_mag;
double var_mag;
if (as3D) {
fixed_mag = sqrt ( (fixed_vec[0]*fixed_vec[0]) + (fixed_vec[1]*fixed_vec[1]) + (fixed_vec[2]*fixed_vec[2]) );
var_mag = sqrt ( ( var_vec[0]* var_vec[0]) + ( var_vec[1]* var_vec[1]) + ( var_vec[2]* var_vec[2]) );
} else {
fixed_mag = sqrt ( (fixed_vec[0]*fixed_vec[0]) + (fixed_vec[1]*fixed_vec[1]) );
var_mag = sqrt ( ( var_vec[0]* var_vec[0]) + ( var_vec[1]* var_vec[1]) );
}
// Check to see if either are zero which indicates that it's not possible to bind them
if ((fixed_mag * var_mag) == 0) {
if (world->dump_level >= 10) {
fprintf ( stdout, "Molecules %s and %s are nonspatially bound.\n", mc[fixed_comp_index].name, mc[var_comp_index].name );
}
return;
}
double dot_prod;
if (as3D) {
dot_prod = (fixed_vec[0] * var_vec[0]) + (fixed_vec[1] * var_vec[1]) + (fixed_vec[2] * var_vec[2]);
} else {
dot_prod = (fixed_vec[0] * var_vec[0]) + (fixed_vec[1] * var_vec[1]);
}
// In general, the magnitudes should be checked for 0. However, in this case, they were generated as non-zero.
double norm_dot_prod = dot_prod / ( fixed_mag * var_mag );
// Ensure that the dot product is a legal argument for the "acos" function:
if (norm_dot_prod > 1) { norm_dot_prod = 1; }
if (norm_dot_prod < -1) { norm_dot_prod = -1; }
//#### fprintf ( stdout, "norm_dot_prod = %g\n", norm_dot_prod );
double angle = acos ( norm_dot_prod );
//#### fprintf ( stdout, "Angle (from acos) = %g\n", angle );
if (as3D) {
// This seems to be required to get everything right:
angle = -angle;
} else {
// Try using the cross product to fix the direction issue
//#### fprintf ( stdout, "Cross of (%g,%g) X (%g,%g) = %g\n", fixed_vec[0], fixed_vec[1], var_vec[0], var_vec[1], (fixed_vec[0] * var_vec[1]) - (fixed_vec[1] * var_vec[0]) );
if ( ( (fixed_vec[0] * var_vec[1]) - (fixed_vec[1] * var_vec[0]) ) > 0 ) {
angle = -angle;
}
}
// Reverse the direction since we want the components attached to each other
angle = MY_PI + angle;
// Normalize between -PI and PI
while (angle > MY_PI) {
angle = angle - (2 * MY_PI);
}
while (angle <= -MY_PI) {
angle = angle + (2 * MY_PI);
}
//angle = -angle;
//#### fprintf ( stdout, "Final corrected angle = %g\n", angle );
//#### fprintf ( stdout, "Binding between f(%s: %g,%g) and v(%s: %g,%g) is at angle %g deg\n", mc[fixed_comp_index].name, fixed_vec[0], fixed_vec[1], mc[var_comp_index].name, var_vec[0], var_vec[1], 180*angle/MY_PI );
// Rotate all of the components of the var_mol_index by the angle
double cos_angle = cos(angle);
double sin_angle = sin(angle);
if (as3D) {
double cross_prod[3];
cross_prod[0] = (fixed_vec[1] * var_vec[2]) - (fixed_vec[2] * var_vec[1]);
cross_prod[1] = (fixed_vec[2] * var_vec[0]) - (fixed_vec[0] * var_vec[2]);
cross_prod[2] = (fixed_vec[0] * var_vec[1]) - (fixed_vec[1] * var_vec[0]);
double xpx, xpy, xpz;
xpx = cross_prod[0] / (fixed_mag * var_mag);
xpy = cross_prod[1] / (fixed_mag * var_mag);
xpz = cross_prod[2] / (fixed_mag * var_mag);
double axis_length = sqrt ( (xpx*xpx) + (xpy*xpy) + (xpz*xpz) );
double R[3][3] = { { 1, 0, 0 },
{ 0, 1, 0 },
{ 0, 0, 1 } };
if (axis_length < 1e-30) {
// Can't compute a meaningful unit vector for the rotation matrix ... make it identity
if (norm_dot_prod < 0) {
// R is fine as defined
} else {
// Change the sign on the diagonal of R
for (int i=0; i<3; i++) {
R[i][i] = -1;
}
}
} else {
// Build the rotation matrix R
double ux = xpx / axis_length;
double uy = xpy / axis_length;
double uz = xpz / axis_length;
double omca = 1 - cos_angle;
R[0][0] = cos_angle + (ux*ux*omca);
R[0][1] = (ux*uy*omca) - (uz*sin_angle);
R[0][2] = (ux*uz*omca) + (uy*sin_angle);
R[1][0] = (uy*ux*omca) + (uz*sin_angle);
R[1][1] = cos_angle + (uy*uy*omca);
R[1][2] = (uy*uz*omca) - (ux*sin_angle);
R[2][0] = (uz*ux*omca) - (uy*sin_angle);
R[2][1] = (uz*uy*omca) + (ux*sin_angle);
R[2][2] = cos_angle + (uz*uz*omca);
}
for (int ci=0; ci<mc[var_mol_index].num_peers; ci++) {
// Rotate the component locations
double x = mc[mc[var_mol_index].peers[ci]].x;
double y = mc[mc[var_mol_index].peers[ci]].y;
double z = mc[mc[var_mol_index].peers[ci]].z;
mc[mc[var_mol_index].peers[ci]].x = (R[0][0]*x) + (R[0][1]*y) + (R[0][2]*z);
mc[mc[var_mol_index].peers[ci]].y = (R[1][0]*x) + (R[1][1]*y) + (R[1][2]*z);
mc[mc[var_mol_index].peers[ci]].z = (R[2][0]*x) + (R[2][1]*y) + (R[2][2]*z);
// Rotate the rotation key locations
x = mc[mc[var_mol_index].peers[ci]].kx;
y = mc[mc[var_mol_index].peers[ci]].ky;
z = mc[mc[var_mol_index].peers[ci]].kz;
mc[mc[var_mol_index].peers[ci]].kx = (R[0][0]*x) + (R[0][1]*y) + (R[0][2]*z);
mc[mc[var_mol_index].peers[ci]].ky = (R[1][0]*x) + (R[1][1]*y) + (R[1][2]*z);
mc[mc[var_mol_index].peers[ci]].kz = (R[2][0]*x) + (R[2][1]*y) + (R[2][2]*z);
}
} else {
// Note that the 2D branch is not expected to be used in MCell, so it may be out of date.
//#### fprintf ( stdout, "Rotating component positions for %s by %g\n", mc[var_mol_index].name, 180*angle/MY_PI );
for (int ci=0; ci<mc[var_mol_index].num_peers; ci++) {
//#### fprintf ( stdout, " Component %s before is at (%g,%g)\n", mc[mc[var_mol_index].peers[ci]].name, mc[mc[var_mol_index].peers[ci]].x, mc[mc[var_mol_index].peers[ci]].y );
double x = mc[mc[var_mol_index].peers[ci]].x;
double y = mc[mc[var_mol_index].peers[ci]].y;
mc[mc[var_mol_index].peers[ci]].x = (x * cos_angle) - (y * sin_angle);
mc[mc[var_mol_index].peers[ci]].y = (x * sin_angle) + (y * cos_angle);
//#### fprintf ( stdout, " Component %s after is at (%g,%g)\n", mc[mc[var_mol_index].peers[ci]].name, mc[mc[var_mol_index].peers[ci]].x, mc[mc[var_mol_index].peers[ci]].y );
}
}
// Now the molecules are aligned as they should be except for rotation along their bonding axis
if ( as3D && with_rot) {
// Rotate the variable molecule along its bonding axis to align based on the rotation key angle
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
double fixed_req_bond_angle = world->bond_angle / 2; // Radians ... should be a function of the bond!!
double var_req_bond_angle = world->bond_angle / 2; // Radians ... should be a function of the bond!!
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// fixed_vcomp (fvc) will be the vector from the fixed molecule to the fixed component
double fvc[3];
fvc[0] = mc[fixed_comp_index].x - mc[fixed_mol_index].x;
fvc[1] = mc[fixed_comp_index].y - mc[fixed_mol_index].y;
fvc[2] = mc[fixed_comp_index].z - mc[fixed_mol_index].z;
// var_vcomp (vvc) will be the vector from the var molecule to the var component
double vvc[3];
vvc[0] = mc[var_comp_index].x - mc[var_mol_index].x;
vvc[1] = mc[var_comp_index].y - mc[var_mol_index].y;
vvc[2] = mc[var_comp_index].z - mc[var_mol_index].z;
// fixed_vkey (fvk) will be the vector from the fixed molecule to the fixed key
double fvk[3];
fvk[0] = mc[fixed_comp_index].kx - mc[fixed_mol_index].x;
fvk[1] = mc[fixed_comp_index].ky - mc[fixed_mol_index].y;
fvk[2] = mc[fixed_comp_index].kz - mc[fixed_mol_index].z;
// var_vkey (vvk) will be the vector from the var molecule to the var key
double vvk[3];
vvk[0] = mc[var_comp_index].kx - mc[var_mol_index].x;
vvk[1] = mc[var_comp_index].ky - mc[var_mol_index].y;
vvk[2] = mc[var_comp_index].kz - mc[var_mol_index].z;
if (world->dump_level >= 20) {
fprintf ( stdout, " Fixed vcomp = [ %g %g %g ]\n", fvc[0], fvc[1], fvc[2] );
fprintf ( stdout, " Var vcomp = [ %g %g %g ]\n", vvc[0], vvc[1], vvc[2] );
fprintf ( stdout, " Fixed vkey = [ %g %g %g ]\n", fvk[0], fvk[1], fvk[2] );
fprintf ( stdout, " Var vkey = [ %g %g %g ]\n", vvk[0], vvk[1], vvk[2] );
}
// Use the cross product to get the normal to the fixed molecule-component-key plane
double fixed_normal[3];
fixed_normal[0] = (fvc[1] * fvk[2]) - (fvc[2] * fvk[1]);
fixed_normal[1] = (fvc[2] * fvk[0]) - (fvc[0] * fvk[2]);
fixed_normal[2] = (fvc[0] * fvk[1]) - (fvc[1] * fvk[0]);
// Use the cross product to get the normal to the variable molecule-component-key plane
double var_normal[3];
var_normal[0] = (vvc[1] * vvk[2]) - (vvc[2] * vvk[1]);
var_normal[1] = (vvc[2] * vvk[0]) - (vvc[0] * vvk[2]);
var_normal[2] = (vvc[0] * vvk[1]) - (vvc[1] * vvk[0]);
// Get the magnitudes of the two vectors for normalization
double fixed_norm_mag = sqrt ( (fixed_normal[0]*fixed_normal[0]) + (fixed_normal[1]*fixed_normal[1]) + (fixed_normal[2]*fixed_normal[2]) );
double var_norm_mag = sqrt ( ( var_normal[0]* var_normal[0]) + ( var_normal[1]* var_normal[1]) + ( var_normal[2]* var_normal[2]) );
// Calculate unit vectors
double fixed_unit[3];
fixed_unit[0] = fixed_normal[0] / fixed_norm_mag;
fixed_unit[1] = fixed_normal[1] / fixed_norm_mag;
fixed_unit[2] = fixed_normal[2] / fixed_norm_mag;
double var_unit[3];
var_unit[0] = var_normal[0] / var_norm_mag;
var_unit[1] = var_normal[1] / var_norm_mag;
var_unit[2] = var_normal[2] / var_norm_mag;
if (world->dump_level >= 20) {
fprintf ( stdout, " Fixed unit = [ %g %g %g ]\n", fixed_unit[0], fixed_unit[1], fixed_unit[2] );
fprintf ( stdout, " Var unit = [ %g %g %g ]\n", var_unit[0], var_unit[1], var_unit[2] );
}
double norm_dot_prod_again;
norm_dot_prod_again = (fixed_unit[0] * var_unit[0]) + (fixed_unit[1] * var_unit[1]) + (fixed_unit[2] * var_unit[2]);
// Ensure that the dot product is a legal argument for the "acos" function:
if (norm_dot_prod_again > 1) {
if (world->dump_level >= 20) {
fprintf ( stdout, "Numerical Warning: normalized dot product %g was greater than 1\n", norm_dot_prod_again );
}
norm_dot_prod_again = 1;
}
if (norm_dot_prod_again < -1) {
if (world->dump_level >= 20) {
fprintf ( stdout, "Numerical Warning: normalized dot product %g was less than -1\n", norm_dot_prod_again );
}
norm_dot_prod_again = -1;
}
if (world->dump_level >= 20) {
fprintf ( stdout, " Normalized Dot Product between fixed and var is %g\n", norm_dot_prod_again );
}
// Compute the amount of rotation to bring the planes into alignment offset by the requested bond angles
double cur_key_plane_angle = acos ( norm_dot_prod_again );
if (world->dump_level >= 20) {
fprintf ( stdout, "Current key plane angle = %g\n", (180*cur_key_plane_angle/MY_PI) );
}
double cross_prod[3];
cross_prod[0] = (fixed_unit[1] * var_unit[2]) - (fixed_unit[2] * var_unit[1]);
cross_prod[1] = (fixed_unit[2] * var_unit[0]) - (fixed_unit[0] * var_unit[2]);
cross_prod[2] = (fixed_unit[0] * var_unit[1]) - (fixed_unit[1] * var_unit[0]);
double dot_cross_rot = (cross_prod[0] * vvc[0]) + (cross_prod[1] * vvc[1]) + (cross_prod[2] * vvc[2]);
if (dot_cross_rot > 0) {
cur_key_plane_angle = (2*MY_PI) - cur_key_plane_angle;
}
if (world->dump_level >= 20) {
fprintf ( stdout, "Current key plane angle = %g, dot_cross_rot = %g\n", (180*cur_key_plane_angle/MY_PI), dot_cross_rot );
}
double composite_rot_angle = MY_PI + (var_req_bond_angle+fixed_req_bond_angle) + cur_key_plane_angle; // The "MY_PI" adds 180 degrees to make the components "line up"
if (world->dump_level >= 20) {
fprintf ( stdout, " Fixed angle is = %g degrees\n", 180 * fixed_req_bond_angle / MY_PI );
fprintf ( stdout, " Var angle is = %g degrees\n", 180 * var_req_bond_angle / MY_PI );
fprintf ( stdout, " Current angle between keys is = %g degrees\n", 180 * cur_key_plane_angle / MY_PI );
fprintf ( stdout, " Composite rotation angle is = %g degrees\n", 180 * composite_rot_angle / MY_PI );
}
// Build a 3D rotation matrix along the axis of the molecule to the component
double var_vcomp_mag = sqrt ( (vvc[0]*vvc[0]) + (vvc[1]*vvc[1]) + (vvc[2]*vvc[2]) );
double var_rot_unit[3];
var_rot_unit[0] = vvc[0] / var_vcomp_mag;
var_rot_unit[1] = vvc[1] / var_vcomp_mag;
var_rot_unit[2] = vvc[2] / var_vcomp_mag;
double ux = var_rot_unit[0];
double uy = var_rot_unit[1];
double uz = var_rot_unit[2];
// Build the rotation matrix directly
double cca = cos(composite_rot_angle);
double sca = sin(composite_rot_angle);
double omcca = 1 - cca;
double R[3][3] = { { 1, 0, 0 },
{ 0, 1, 0 },
{ 0, 0, 1 } };
R[0][0] = cca + (ux*ux*omcca);
R[0][1] = (ux*uy*omcca) - (uz*sca);
R[0][2] = (ux*uz*omcca) + (uy*sca);
R[1][0] = (uy*ux*omcca) + (uz*sca);
R[1][1] = cca + (uy*uy*omcca);
R[1][2] = (uy*uz*omcca) - (ux*sca);
R[2][0] = (uz*ux*omcca) - (uy*sca);
R[2][1] = (uz*uy*omcca) + (ux*sca);
R[2][2] = cca + (uz*uz*omcca);
// Apply the rotation matrix after subtracting the molecule center location from all components and keys
for (int ci=0; ci<mc[var_mol_index].num_peers; ci++) {
// Rotate the component locations
double x = mc[mc[var_mol_index].peers[ci]].x - mc[var_mol_index].x;
double y = mc[mc[var_mol_index].peers[ci]].y - mc[var_mol_index].y;
double z = mc[mc[var_mol_index].peers[ci]].z - mc[var_mol_index].z;
mc[mc[var_mol_index].peers[ci]].x = (R[0][0]*x) + (R[0][1]*y) + (R[0][2]*z) + mc[var_mol_index].x;
mc[mc[var_mol_index].peers[ci]].y = (R[1][0]*x) + (R[1][1]*y) + (R[1][2]*z) + mc[var_mol_index].y;
mc[mc[var_mol_index].peers[ci]].z = (R[2][0]*x) + (R[2][1]*y) + (R[2][2]*z) + mc[var_mol_index].z;
// Rotate the rotation key locations
x = mc[mc[var_mol_index].peers[ci]].kx - mc[var_mol_index].x;
y = mc[mc[var_mol_index].peers[ci]].ky - mc[var_mol_index].y;
z = mc[mc[var_mol_index].peers[ci]].kz - mc[var_mol_index].z;
mc[mc[var_mol_index].peers[ci]].kx = (R[0][0]*x) + (R[0][1]*y) + (R[0][2]*z) + mc[var_mol_index].x;
mc[mc[var_mol_index].peers[ci]].ky = (R[1][0]*x) + (R[1][1]*y) + (R[1][2]*z) + mc[var_mol_index].y;
mc[mc[var_mol_index].peers[ci]].kz = (R[2][0]*x) + (R[2][1]*y) + (R[2][2]*z) + mc[var_mol_index].z;
}
}
//#### dump_molcomp_array(mc,num_parts);
// Shift the var molecule location and the locations of all of its components by the difference of the binding components
double dx = mc[fixed_comp_index].x - mc[var_comp_index].x;
double dy = mc[fixed_comp_index].y - mc[var_comp_index].y;
double dz = mc[fixed_comp_index].z - mc[var_comp_index].z;
//#### fprintf ( stdout, "Shifting molecule and component positions for %s\n", mc[var_mol_index].name );
mc[var_mol_index].x += dx;
mc[var_mol_index].y += dy;
mc[var_mol_index].z += dz;
for (int ci=0; ci<mc[var_mol_index].num_peers; ci++) {
// Shift the component locations
mc[mc[var_mol_index].peers[ci]].x += dx;
mc[mc[var_mol_index].peers[ci]].y += dy;
mc[mc[var_mol_index].peers[ci]].z += dz;
// Shift the rotation key locations
mc[mc[var_mol_index].peers[ci]].kx += dx;
mc[mc[var_mol_index].peers[ci]].ky += dy;
mc[mc[var_mol_index].peers[ci]].kz += dz;
//#### fprintf ( stdout, " Component %s is at (%g,%g)\n", mc[mc[var_mol_index].peers[ci]].name, mc[mc[var_mol_index].peers[ci]].x, mc[mc[var_mol_index].peers[ci]].y );
}
//#### dump_molcomp_array(mc,num_parts);
//#### fprintf ( stdout, "########## Done Binding %s to %s\n", mc[fixed_comp_index].name, mc[var_comp_index].name );
}
static void bind_all_molecules ( struct volume *world, external_molcomp_loc *molcomp_array, int num_parts, bool as3D, bool with_rot ) {
// Compute positions for all molecules/components in a molcomp_array
int mi=0;
int pi=0;
// Find first molecule
for (mi=0; mi<num_parts; mi++) {
if (molcomp_array[mi].is_mol) break;
}
if (molcomp_array[mi].is_mol) {
// Set this first molecule and all of its components to final
molcomp_array[mi].is_final = true;
for (int ci=0; ci<molcomp_array[mi].num_peers; ci++) {
molcomp_array[molcomp_array[mi].peers[ci]].is_final = true;
}
int done = 0;
while (done == 0) {
// Look for a bond between a non-final and a final component
done = 1;
for (mi=0; mi<num_parts; mi++) {
if (!molcomp_array[mi].is_mol) {
// Only search components for bonds
if (molcomp_array[mi].num_peers > 1) {
// This component has bonds, so search them
for (int ci=1; ci<molcomp_array[mi].num_peers; ci++) {
pi = molcomp_array[mi].peers[ci]; // Peer index
if (molcomp_array[mi].is_final != molcomp_array[pi].is_final) {
done = 0;
// One of these is final and the other is not so join them and make them all final
int fci, vci; // Fixed comp index and Variable comp index
int vmi; // Fixed mol index and Variable mol index
// Figure out which is fixed and which is not
if (molcomp_array[mi].is_final) {
fci = mi;
vci = pi;
} else {
fci = pi;
vci = mi;
}
// Set the molecule index values for the bond
vmi = molcomp_array[vci].peers[0];
// Set the initial (relative) positions of the components with each molecule at (0,0)
// set_component_positions_2D ( world, molcomp_array, num_parts );
// Perform the bond (changes the locations)
bind_molecules_at_components ( world, molcomp_array, num_parts, fci, vci, as3D, with_rot );
// Set the variable molecule and its components to final
molcomp_array[vmi].is_final = true;
for (int vmici=0; vmici<molcomp_array[vmi].num_peers; vmici++) {
molcomp_array[molcomp_array[vmi].peers[vmici]].is_final = true;
}
}
}
}
}
}
}
}
}
static external_molcomp_loc *build_molcomp_array ( struct volume *world, char **graph_strings ) {
int part_num;
char *next_part;
/* Had trouble using the rng_state mechanism, skip for now
if (rng == NULL) {
rng = (rng_state *) malloc ( sizeof (struct rng_state) );
rng_init ( rng, 12345 );
}
*/
part_num = 0;
next_part = graph_strings[part_num];
while (next_part != NULL) {
part_num++;
next_part = graph_strings[part_num];
}
// Allocate the entire block at once ...
external_molcomp_loc *molcomp_loc_array = (external_molcomp_loc *) malloc ( part_num * sizeof(external_molcomp_loc) );
// Copy the data into the block
part_num = 0;
next_part = graph_strings[part_num];
while (next_part != NULL) {
molcomp_loc_array[part_num].has_coords = 0;
molcomp_loc_array[part_num].graph_string = (char *) malloc ( 1 + strlen(next_part) );
strcpy ( molcomp_loc_array[part_num].graph_string, next_part );
molcomp_loc_array[part_num].x = 0;
molcomp_loc_array[part_num].y = 0;
molcomp_loc_array[part_num].z = 0;
molcomp_loc_array[part_num].states = NULL;
if (strstr(next_part,"m:") == next_part) {
// This is a molecule
molcomp_loc_array[part_num].is_mol = 1;
// For molecules, the name ends with ! or possibly the end of the string
if (strchr(next_part,'!') == NULL) {
molcomp_loc_array[part_num].name = (char *) malloc ( 1 + strlen(next_part) - 2 );
strcpy ( molcomp_loc_array[part_num].name, &next_part[2] );
} else {
char *end_point = strchr(next_part,'!');
*end_point = '\0';
molcomp_loc_array[part_num].name = (char *) malloc ( 1 + strlen(next_part) - 2 );
strcpy ( molcomp_loc_array[part_num].name, &next_part[2] );
*end_point = '!';
}
// Remove any @ portions if they exist
char *at_sign = strchr(molcomp_loc_array[part_num].name, '@');
if (at_sign != NULL) {
// Make a copy up to that point
*at_sign = '\0';
char *shorter_name = (char *) malloc ( 1 + strlen(molcomp_loc_array[part_num].name) );
strcpy ( shorter_name, molcomp_loc_array[part_num].name );
*at_sign = '@';
free ( molcomp_loc_array[part_num].name );
molcomp_loc_array[part_num].name = shorter_name;
}
// Get the molecule's neighbors which should all be components
molcomp_loc_array[part_num].num_peers = 0;
molcomp_loc_array[part_num].peers = NULL;
char *next_excl = strchr(next_part,'!');
while (next_excl != NULL) {
molcomp_loc_array[part_num].num_peers++;
next_excl++;
next_excl = strchr(next_excl,'!');
}
if (molcomp_loc_array[part_num].num_peers > 0) {
molcomp_loc_array[part_num].peers = (int *) malloc ( molcomp_loc_array[part_num].num_peers * sizeof(int) );
next_excl = strchr(next_part,'!');
int peer_num = 0;
int comp_index;
while (next_excl != NULL) {
next_excl++;
comp_index = atoi(next_excl);
molcomp_loc_array[part_num].peers[peer_num] = comp_index;
peer_num++;
next_excl = strchr(next_excl,'!');
}
}
} else {
// This is a component
molcomp_loc_array[part_num].is_mol = 0;
char *first_exc = strchr(next_part,'!');
char *first_til = strchr(next_part,'~');
char *end_point;
char previous_end;
// For components, the name ends with ~ or ! or possibly the end of the string
if ( (first_exc != NULL) && (first_til != NULL) ) {
// Use whichever comes first
if (first_exc < first_til) {
end_point = first_exc;
} else {
end_point = first_til;
}
} else if (first_exc != NULL) {
// Name ends at exc
end_point = first_exc;
} else if (first_til != NULL) {
// Name ends at til
end_point = first_til;
} else {
// Name ends at end of string
end_point = strchr(next_part,'\0');
}
previous_end = *end_point;
*end_point = '\0';
molcomp_loc_array[part_num].name = (char *) malloc ( 1 + strlen(next_part) - 2 );
strcpy ( molcomp_loc_array[part_num].name, &next_part[2] );
*end_point = previous_end;
// For components, the state starts with ~ and ends with ! or possibly the end of the string
if (first_til != NULL) {
// There are states on this component
if (first_exc != NULL) {
// The states are bounded between first_til and first_exc
end_point = first_exc;
} else {
// The states are bounded between first_til and the end of the string
end_point = strchr(next_part,'\0');
}
previous_end = *end_point;
*end_point = '\0';
molcomp_loc_array[part_num].states = (char *) malloc ( 1 + strlen(first_til) );
strcpy ( molcomp_loc_array[part_num].states, first_til );
*end_point = previous_end;
}
// Get the component's neighbors (the first will be the molecule)
molcomp_loc_array[part_num].num_peers = 0;
molcomp_loc_array[part_num].peers = NULL;
char *next_excl = strchr(next_part,'!');
while (next_excl != NULL) {
molcomp_loc_array[part_num].num_peers++;
next_excl++;
next_excl = strchr(next_excl,'!');
}
if (molcomp_loc_array[part_num].num_peers > 0) {
molcomp_loc_array[part_num].peers = (int *) malloc ( molcomp_loc_array[part_num].num_peers * sizeof(int) );
next_excl = strchr(next_part,'!');
int peer_num = 0;
int comp_index;
while (next_excl != NULL) {
next_excl++;
comp_index = atoi(next_excl);
molcomp_loc_array[part_num].peers[peer_num] = comp_index;
peer_num++;
next_excl = strchr(next_excl,'!');
}
}
}
part_num++;
next_part = graph_strings[part_num];
}
// set_molcomp_positions_2D_first_try ( world, molcomp_loc_array, part_num );
// Set the initial (relative) positions of the components with each molecule at (0,0)
// set_component_positions_2D ( world, molcomp_loc_array, part_num );
set_component_positions_by_table ( world, molcomp_loc_array, part_num );
bind_all_molecules ( world, molcomp_loc_array, part_num, true, true );
if (world->dump_level >= 20) {
fprintf ( stdout, ">>>>>>>>>>>>>>>>>>>>>>> Final molcomp_loc_array <<<<<<<<<<<<<<<<<<<\n" );
dump_molcomp_array ( molcomp_loc_array, part_num );
fprintf ( stdout, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" );
}
return molcomp_loc_array;
}
static char **get_graph_strings ( char *nauty_string ) {
// Parse the graph pattern
// This code assumes that the graph pattern ends with a comma!!
int num_parts;
int part_num;
char **graph_parts;
char *first, *last;
// Start by just counting the parts
part_num = 0;
first = nauty_string;
last = strchr ( first, ',' );
while (last != NULL) {
first = last+1;
last = strchr ( first, ',' );
part_num++;
}
num_parts = part_num;
// Allocate the array and mark the end
graph_parts = (char **) malloc ( (num_parts+1) * sizeof(char *) );
graph_parts[num_parts] = NULL; // Marks the end of the "list"
// Copy the parts into the array of strings
part_num = 0;
first = nauty_string;
last = strchr ( first, ',' );
while (last != NULL) {
*last = '\0';
char *s = (char *) malloc ( strlen(first) + 1 );
strcpy ( s, first );
graph_parts[part_num] = s;
*last = ',';
first = last+1;
last = strchr ( first, ',' );
part_num++;
}
return graph_parts;
}
static void free_graph_parts ( char **graph_parts ) {
if (graph_parts != NULL) {
int part_num = 0;
char *next_part = graph_parts[part_num];
while (next_part != NULL) {
free ( next_part );
part_num++;
next_part = graph_parts[part_num];
}
free ( graph_parts );
}
}
static void end_line_opt_comma ( FILE *space_struct_file, bool add_comma ) {
if (add_comma) {
fprintf ( space_struct_file, "," );
}
fprintf ( space_struct_file, "\n" );
}
/************************************************************************
output_cellblender_molecules:
In: vizblk: VIZ_OUTPUT block for this frame list
a frame data list (internal viz output data structure)
Out: 0 on success, 1 on failure. The names and positions of molecules are
output in binary format designed for fast visualization in CellBlender
Format of binary file is:
Header:
A single four-byte u_int containing version number of binary file
format. This is value less than or equal to 16777215, which is
0x00ffffff. This allows automagic detection of ASCII and binary
format molecule viz files, as well as the endianness of the binary
format files during molecule viz in CellBlender.
Molecule Viz Data:
Version 0x00000001 files contain a block of binary data for each
molecule species structured as follows:
A single byte containing the length of the ASCII string of the
molecule species name or state value, not including the terminating
NULL. 32 chars max.
The ASCII string containing the molecule species name or state value,
not including the terminating NULL. 32 chars max.
A single byte containing the molecule species type.
Type 0 means volume molecule. Type 1 means surface surface molecule.
A four-byte u_int, N, whose value is 3 times the number of molecules
of this species contained in the block, i.e. the number of floats
in the block for the x,y,z coordinates of the molecule positions.
A block of N four-byte floats containing the x,y,z coordinates of
the molecule positions.
If the molecules are surface molecules then block of x,y,z positions
is followed by another block of N four-byte floats containing the
i,j,k components of the orientation vector of the surface molecules.
Note that the end of the file is indicated by the usual EOF only.
*************************************************************************/
static int output_cellblender_molecules(struct volume *world,
struct viz_output_block *vizblk,
struct frame_data_list *fdlp) {
no_printf("Output in CELLBLENDER mode (molecules only)...\n");
if ( (world->dump_level >= 20) && (world->viz_options != VIZ_OPTS_NONE) ) {
fprintf ( stdout, "vizblk->file_prefix_name = \"%s\"\n", vizblk->file_prefix_name );
}
if ( (world->dump_level >= 5) && (world->viz_options != VIZ_OPTS_NONE) ) {
fprintf ( stdout, "Visualization Options = 0x%lx\n", world->viz_options );
fprintf ( stdout, "Proxy = 0x%lx\n", world->viz_options & VIZ_PROXY_OUTPUT );
}
if (world->dump_level >= 50) {
fprintf ( stdout, ">>>>>>>>>>>>>>>>>>>>>>> Top of MolViz Output <<<<<<<<<<<<<<<<<<<\n" );
}
// Unfortunately, the file name in vizblk->file_prefix_name has the "Scene" attached to the end.
// This makes it difficult to use to build other paths that don't have a "Scene" in them.
// For example: vizblk->file_prefix_name = "./viz_data/seed_00001/Scene"
// So this will take some string "monkey business" to fix
// We want "./viz_data/seed_#..#/ without the "Scene" attached
char *file_prefix_no_Scene = NULL;
char *file_prefix_usually_Scene = NULL;
// Get the location of the last separator
char *last_sep = strrchr ( vizblk->file_prefix_name, '/' );
// Use the last_sep to copy the file part (usually Scene)
file_prefix_usually_Scene = my_strcat ( last_sep+1, NULL );
// Also use the last sep to copy the path part
// Set it to \0 to mark the end of the string
*last_sep = '\0';
// Copy it with the desired prefix
file_prefix_no_Scene = my_strcat ( vizblk->file_prefix_name, NULL );
// Restore the vizblk->file_prefix_name
*last_sep = '/';
//fprintf ( stdout, "path without file = %s\n", file_prefix_no_Scene );
//fprintf ( stdout, "file without path = %s\n", file_prefix_usually_Scene );
if ((fdlp->type == ALL_MOL_DATA) || (fdlp->type == MOL_POS)) {
long long lli = 10;
int ndigits = 1;
for (; lli <= world->iterations && ndigits < 20;
lli *= 10, ndigits++) {
}
char *cf_name =
CHECKED_SPRINTF("%s.cellbin.%.*lld.dat", vizblk->file_prefix_name,
ndigits, fdlp->viz_iteration);
if (cf_name == NULL)
return 1;
if (make_parent_dir(cf_name)) {
free(cf_name);
mcell_error(
"Failed to create parent directory for CELLBLENDER-mode VIZ output.");
/*return 1;*/
}
FILE *custom_file = open_file(cf_name, "wb");
if (!custom_file)
mcell_die();
else {
no_printf("Writing to file %s\n", cf_name);
}
free(cf_name);
cf_name = NULL;
FILE *space_struct_file = NULL;
if (world->viz_options & VIZ_ALT_FILES_MASK) {
// Create the output files (format need not be determined yet)
if (world->dump_level >= 20) {
fprintf ( stdout, "Spatially Structured Option = 0x%lx\n", world->viz_options & VIZ_ALT_FILES_MASK );
}
// Create the spatially structured mol file to hold the instances
cf_name =
CHECKED_SPRINTF("%s/viz_bngl/%s.bnglviz.%.*lld.dat", file_prefix_no_Scene, file_prefix_usually_Scene,
ndigits, fdlp->viz_iteration);
if (cf_name == NULL)
return 1;
if (make_parent_dir(cf_name)) {
free(cf_name);
mcell_error(
"Failed to create parent directory for SPATIAL-mode VIZ output.");
/*return 1;*/
}
space_struct_file = open_file(cf_name, "wb");
if (!space_struct_file) {
mcell_die();
} else {
no_printf("Writing to file %s\n", cf_name);
}
free(cf_name);
cf_name = NULL;
}
/* Get a list of molecules sorted by species. */
u_int *viz_mol_count = NULL;
struct abstract_molecule ***viz_molp = NULL;
if (sort_molecules_by_species(
world, vizblk, &viz_molp, &viz_mol_count, 1, 1)) {
fclose(custom_file);
custom_file = NULL;
return 1;
}
/* Write file header(s) */
u_int cellbin_version = 1;
fwrite(&cellbin_version, sizeof(cellbin_version), 1, custom_file);
/* Write all the molecules whether EXTERNAL_SPECIES or not (for now) */
for (int species_idx = 0; species_idx < world->n_species; species_idx++) {
const unsigned int this_mol_count = viz_mol_count[species_idx];
if (this_mol_count == 0)
continue;
const int id = vizblk->species_viz_states[species_idx];
if (id == EXCLUDE_OBJ)
continue;
struct abstract_molecule **const mols = viz_molp[species_idx];
if (mols == NULL)
continue;
struct abstract_molecule *amp = mols[0]; // Need to use one of the mols to get the flags
if ( (world->viz_options & VIZ_PROXY_OUTPUT) || ((amp->properties->flags & EXTERNAL_SPECIES) == 0) ) {
/* Write species name: */
char mol_name[33];
if (id == INCLUDE_OBJ) {
/* encode name of species as ASCII string, 32 chars max */
snprintf(mol_name, 33, "%s", amp->properties->sym->name);
} else {
/* encode state value of species as ASCII string, 32 chars max */
snprintf(mol_name, 33, "%d", id);
}
byte name_len = strlen(mol_name);
fwrite(&name_len, sizeof(name_len), 1, custom_file);
fwrite(mol_name, sizeof(char), name_len, custom_file);
/* Write species type: */
byte species_type = 0;
if ((amp->properties->flags & ON_GRID) != 0) {
species_type = 1;
}
fwrite(&species_type, sizeof(species_type), 1, custom_file);
/* write number of x,y,z floats for mol positions to follow: */
u_int n_floats = 3 * this_mol_count;
fwrite(&n_floats, sizeof(n_floats), 1, custom_file);
/* Write positions of volume and surface molecules: */
float pos_x = 0.0;
float pos_y = 0.0;
float pos_z = 0.0;
for (unsigned int n_mol = 0; n_mol < this_mol_count; ++n_mol) {
amp = mols[n_mol];
/* This is a normal molecule so write it out. EXTERNAL_SPECIES will be written later */
if ((amp->properties->flags & NOT_FREE) == 0) {
struct volume_molecule *mp = (struct volume_molecule *)amp;
struct vector3 pos_output = {0.0, 0.0, 0.0};
if (!convert_relative_to_abs_PBC_coords(
world->periodic_box_obj,
mp->periodic_box,
world->periodic_traditional,
&mp->pos,
&pos_output)) {
pos_x = pos_output.x;
pos_y = pos_output.y;
pos_z = pos_output.z;
}
else {
pos_x = mp->pos.x;
pos_y = mp->pos.y;
pos_z = mp->pos.z;
}
} else if ((amp->properties->flags & ON_GRID) != 0) {
struct surface_molecule *gmp = (struct surface_molecule *)amp;
struct vector3 where;
uv2xyz(&(gmp->s_pos), gmp->grid->surface, &where);
struct vector3 pos_output = {0.0, 0.0, 0.0};
if (!convert_relative_to_abs_PBC_coords(
world->periodic_box_obj,
gmp->periodic_box,
world->periodic_traditional,
&where,
&pos_output)) {
pos_x = pos_output.x;
pos_y = pos_output.y;
pos_z = pos_output.z;
}
else {
pos_x = where.x;
pos_y = where.y;
pos_z = where.z;
}
}
pos_x *= world->length_unit;
pos_y *= world->length_unit;
pos_z *= world->length_unit;
fwrite(&pos_x, sizeof(pos_x), 1, custom_file);
fwrite(&pos_y, sizeof(pos_y), 1, custom_file);
fwrite(&pos_z, sizeof(pos_z), 1, custom_file);
}
/* Write orientations of surface surface molecules: */
amp = mols[0];
/* This is a normal molecule so write as needed. EXTERNAL_SPECIES will be written later */
if ((amp->properties->flags & ON_GRID) != 0) {
for (unsigned int n_mol = 0; n_mol < this_mol_count; ++n_mol) {
struct surface_molecule *gmp = (struct surface_molecule *)mols[n_mol];
short orient = gmp->orient;
float norm_x = orient * gmp->grid->surface->normal.x;
float norm_y = orient * gmp->grid->surface->normal.y;
float norm_z = orient * gmp->grid->surface->normal.z;
if (world->periodic_box_obj && !(world->periodic_traditional)) {
if (gmp->periodic_box->x % 2 != 0) {
norm_x *= -1;
}
if (gmp->periodic_box->y % 2 != 0) {
norm_y *= -1;
}
if (gmp->periodic_box->z % 2 != 0) {
norm_z *= -1;
}
}
fwrite(&norm_x, sizeof(norm_x), 1, custom_file);
fwrite(&norm_y, sizeof(norm_y), 1, custom_file);
fwrite(&norm_z, sizeof(norm_z), 1, custom_file);
}
}
}
} // for (int species_idx = 0; species_idx < world->n_species; species_idx++) {
/* Add additional Viz blocks for all EXTERNAL_SPECIES molecules */
/* Note that this could be done while processing normal molecules, but separating makes code clearer. */
external_mol_viz_by_name *mol_name_list = NULL;
for (int species_idx = 0; species_idx < world->n_species; species_idx++) {
const unsigned int this_mol_count = viz_mol_count[species_idx];
if (this_mol_count == 0)
continue;
const int id = vizblk->species_viz_states[species_idx];
if (id == EXCLUDE_OBJ)
continue;
struct abstract_molecule **const mols = viz_molp[species_idx];
if (mols == NULL)
continue;
/* Get species name: */
struct abstract_molecule *amp;
amp = mols[0];
char mol_name[33];
if (id == INCLUDE_OBJ) {
/* encode name of species as ASCII string, 32 chars max */
snprintf(mol_name, 33, "%s", amp->properties->sym->name);
} else {
/* encode state value of species as ASCII string, 32 chars max */
snprintf(mol_name, 33, "%d", id);
}
/* Get species type: */
/*byte species_type = 0;*/
/*if ((amp->properties->flags & ON_GRID) != 0) {*/
/* species_type = 1;*/
/*}*/
/* Get and save positions of EXTERNAL_SPECIES volume and surface molecules: */
for (unsigned int n_mol = 0; n_mol < this_mol_count; ++n_mol) {
amp = mols[n_mol];
float pos_x = 0.0;
float pos_y = 0.0;
float pos_z = 0.0;
float norm_x = 0.0;
float norm_y = 0.0;
float norm_z = 0.0;
if ((amp->properties->flags & NOT_FREE) == 0) {
struct volume_molecule *mp = (struct volume_molecule *)amp;
pos_x = mp->pos.x;
pos_y = mp->pos.y;
pos_z = mp->pos.z;
} else if ((amp->properties->flags & ON_GRID) != 0) {
struct surface_molecule *gmp = (struct surface_molecule *)amp;
struct vector3 where;
uv2xyz(&(gmp->s_pos), gmp->grid->surface, &where);
pos_x = where.x;
pos_y = where.y;
pos_z = where.z;
}
pos_x *= world->length_unit;
pos_y *= world->length_unit;
pos_z *= world->length_unit;
char mol_type = 'v';
if ((amp->properties->flags & ON_GRID) != 0) {
mol_type = 's';
struct surface_molecule *gmp = (struct surface_molecule *)mols[n_mol];
short orient = gmp->orient;
norm_x = orient * gmp->grid->surface->normal.x;
norm_y = orient * gmp->grid->surface->normal.y;
norm_z = orient * gmp->grid->surface->normal.z;
}
float x_offset = 0.0;
if ((amp->properties->flags & EXTERNAL_SPECIES) != 0) {
/* This is complex molecule, so add a new viz molecule for each molecule in the complex */
/* The graph pattern will be something like: */
/* c:SH2~NO_STATE!5,c:U~NO_STATE!5!3,c:a~NO_STATE!6,c:b~Y!6!1,c:g~Y!6,m:Lyn@PM!0!1,m:Rec@PM!2!3!4, */
char *next_mol = amp->graph_data->graph_pattern;
/* BEGIN NEW PROCESSING */
// fprintf ( stdout, "=============== BEGIN NEW PROCESSING ===============\n" );
if (graph_pattern_table == NULL) {
graph_pattern_table = init_symtab ( 10 );
}
struct sym_entry *sp;
sp = retrieve_sym(next_mol, graph_pattern_table);
if (sp == NULL) {
// This pattern has not been saved yet, so parse it, save it, and possibly print it.
// Note that patterns stored in the graph_pattern_table are never purged.
// These patterns remain throughout the life of the simulation.
char **graph_parts = get_graph_strings ( next_mol );
// Print for use with external tools like the SpatialMols2D.java
if (world->dump_level >= 10) {
fprintf ( stdout, "=#= New Graph Pattern: %s\n", next_mol );
}
// Count the number of parts in graph_parts linked list
int num_parts = 0;
char *next_part = graph_parts[num_parts];
while (next_part != NULL) {
if (world->dump_level >= 20) {
fprintf ( stdout, " Graph Part %d: %s\n", num_parts, next_part );
}
num_parts++;
next_part = graph_parts[num_parts];
}
external_molcomp_loc *molcomp_array = build_molcomp_array ( world, graph_parts );
if (world->dump_level >= 10) {
fprintf ( stdout, "=============== molcomp_array ===============\n" );
dump_molcomp_array ( molcomp_array, num_parts );
fprintf ( stdout, "=============================================\n" );
}
molcomp_list *mcl = (molcomp_list *) malloc ( sizeof(molcomp_list) );
mcl->molcomp_array = molcomp_array;
mcl->num_molcomp_items = num_parts;
mcl->molcomp_id = next_molcomp_id;
next_molcomp_id += 1;
//#### fprintf ( stdout, "=============== molcomp_list ===============\n" );
//#### dump_molcomp_list ( mcl );
//#### fprintf ( stdout, "=============================================\n" );
/* store_sym ( symbol, sym_type, symbol_table, data ) */
sp = store_sym ( next_mol, VOID_PTR, graph_pattern_table, mcl );
//#### fprintf ( stdout, "=============== graph_pattern_table ===============\n" );
//#### dump_symtab ( graph_pattern_table );
//#### fprintf ( stdout, "===================================================\n" );
free_graph_parts ( graph_parts );
}
molcomp_list *mcl = NULL;
if (sp != NULL) {
mcl = (molcomp_list *) sp->value;
// fprintf ( stdout, " sp: %s\n", mcl->name );
// Look for component locations of all zero which indicates a non-spatial molecule
int part_num;
for (part_num = 0; part_num<mcl->num_molcomp_items; part_num++) {
// fprintf ( stdout, " Mol Viz part_num %d\n", part_num );
if ( mcl->molcomp_array[part_num].is_mol == false ) {
// Check component location
if ((mcl->molcomp_array[part_num].x==0) && (mcl->molcomp_array[part_num].y==0) && (mcl->molcomp_array[part_num].z==0) ) {
// A component cannot be at the origin
mcl = NULL;
break;
}
}
}
}
if (mcl != NULL) {
// This is the normal path for spatially structured molecules
// Note that this logic assumes that each part is either a molecule or a component
// That's fine at the time of this design, but be aware that adding anything else
// that's other than a molecule or component may break this logic!!
int part_num;
for (part_num = 0; part_num<mcl->num_molcomp_items; part_num++) {
// fprintf ( stdout, " Mol Viz part_num %d\n", part_num );
if ( mcl->molcomp_array[part_num].is_mol || (world->viz_options!=VIZ_OPTS_NONE) ) {
// fprintf ( stdout, " mcl %s\n", mcl->molcomp_array[part_num].name );
// Choose the name based on the type of item and the viz flags
char *name_to_find_or_add = NULL;
if (mcl->molcomp_array[part_num].is_mol) {
// Handle Molecule Viz
name_to_find_or_add = (char *) malloc (1+strlen(mcl->molcomp_array[part_num].name));
strcpy ( name_to_find_or_add, mcl->molcomp_array[part_num].name );
} else {
// Handle Component Viz
int viz_naming_bits = world->viz_options & VIZ_COMP_NAMING_MASK;
if (viz_naming_bits == VIZ_COMP_ALL_SAME) {
// Build a global component name alone (same glyph for all components and all molecules)
name_to_find_or_add = (char *) malloc (1+strlen("component"));
strcpy ( name_to_find_or_add, "component" );
} else if (viz_naming_bits == VIZ_COMP_NAME_GLOBAL) {
// Build the name from the component name alone (same glyph for all components with this name across all molecules)
name_to_find_or_add = (char *) malloc (1+strlen("comp_")+strlen(mcl->molcomp_array[part_num].name));
strcpy ( name_to_find_or_add, "comp_" );
strcpy ( &name_to_find_or_add[strlen("comp_")], mcl->molcomp_array[part_num].name );
} else if (viz_naming_bits == VIZ_COMP_MOL_LOCAL) {
// Build the name from the molecule name and the component name (glyph only applies to this mol/comp combination)
char *last_mol_name = NULL;
if (mcl->molcomp_array[part_num].num_peers < 1) {
// This shouldn't happen ...
last_mol_name = (char *) malloc (1+strlen("unknown_"));
strcpy ( last_mol_name, "unknown_" );
} else {
// Copy the molecule name
char *name_ptr = mcl->molcomp_array[mcl->molcomp_array[part_num].peers[0]].name;
last_mol_name = (char *) malloc (1+strlen(name_ptr));
strcpy ( last_mol_name, name_ptr );
}
name_to_find_or_add = (char *) malloc (1+strlen(last_mol_name)+strlen("_comp_")+strlen(mcl->molcomp_array[part_num].name));
strcpy ( name_to_find_or_add, last_mol_name );
strcpy ( &name_to_find_or_add[strlen(name_to_find_or_add)], "_comp_" );
strcpy ( &name_to_find_or_add[strlen(name_to_find_or_add)], mcl->molcomp_array[part_num].name );
if (last_mol_name != NULL) {
free ( last_mol_name );
}
}
}
/* Check to see if this name is already in the mol_name_list */
external_mol_viz_by_name *next_mol_name = mol_name_list;
int found = 0;
// Check for the actual mol name being in the list
do {
if (next_mol_name == NULL) {
break;
}
if (strcmp(name_to_find_or_add, next_mol_name->mol_name) == 0) {
found = 1;
break;
}
next_mol_name = next_mol_name->next_name;
} while ( found == 0 );
if (found == 0) {
/* This molecule or component name is not in the list, so add a new name to the front */
next_mol_name = (external_mol_viz_by_name *) malloc ( sizeof(external_mol_viz_by_name) );
next_mol_name->mol_name = name_to_find_or_add; /* This takes "ownership" of the allocated "name_to_find_or_add" memory */
next_mol_name->mol_list = NULL;
next_mol_name->next_name = mol_name_list;
mol_name_list = next_mol_name;
} else {
/* The name was already in the list so free the memory */
if (name_to_find_or_add != NULL) {
free ( name_to_find_or_add );
name_to_find_or_add = NULL;
}
}
/* next_mol_name now points to the list of molecules by this name */
/* Make a new molecule viz item to store this location */
external_mol_viz *new_mol_viz_item = (external_mol_viz *) malloc ( sizeof(external_mol_viz) );
/* Set its values */
new_mol_viz_item->mol_type = mol_type;
new_mol_viz_item->pos_x = pos_x + mcl->molcomp_array[part_num].x;
new_mol_viz_item->pos_y = pos_y + mcl->molcomp_array[part_num].y;
new_mol_viz_item->pos_z = pos_z + mcl->molcomp_array[part_num].z;
// fprintf ( stdout, "=MVM= Mol Viz Mol at: (%g,%g,%g)\n", new_mol_viz_item->pos_x, new_mol_viz_item->pos_y, new_mol_viz_item->pos_z );
new_mol_viz_item->norm_x = norm_x;
new_mol_viz_item->norm_y = norm_y;
new_mol_viz_item->norm_z = norm_z;
/* Add it to the top of the molecule list. This takes ownership of the allocated memory. */
new_mol_viz_item->next_mol = next_mol_name->mol_list;
next_mol_name->mol_list = new_mol_viz_item;
next_mol += 1;
}
}
// fprintf ( stdout, "=============== END NEW PROCESSING ===============\n" );
/* END NEW PROCESSING */
} else {
// Arriving here means that the molecules are non-spatial (at least one component is at the origin)
while ((next_mol = strstr(next_mol,"m:")) != NULL ) {
/* Pull the next actual molecule name out of the graph pattern */
char *end_mol = strpbrk ( next_mol, "@!,(~" );
if (end_mol == NULL) {
end_mol = next_mol + strlen(next_mol);
}
int ext_name_len = end_mol - next_mol;
char *ext_name = (char *) malloc ( ext_name_len + 1 );
strncpy ( ext_name, next_mol+2, ext_name_len-2 );
ext_name[ext_name_len-2] = '\0';
/* Check to see if this name is already in the list */
external_mol_viz_by_name *next_mol_name = mol_name_list;
int found = 0;
do {
if (next_mol_name == NULL) {
break;
}
if (strcmp(ext_name, next_mol_name->mol_name) == 0) {
found = 1;
break;
}
next_mol_name = next_mol_name->next_name;
} while ( found == 0 );
if (found == 0) {
/* This molecule name is not in the list, so add a new name to the front */
next_mol_name = (external_mol_viz_by_name *) malloc ( sizeof(external_mol_viz_by_name) );
next_mol_name->mol_name = ext_name; /* This takes "ownership" of the allocated name memory */
next_mol_name->mol_list = NULL;
next_mol_name->next_name = mol_name_list;
mol_name_list = next_mol_name;
} else {
/* This molecule name is already in the list and next_mol_name points to it, so just free the name. */
free ( ext_name );
}
/* next_mol_name now points to the list of molecules by this name */
/* Make a new molecule viz item to store this location */
external_mol_viz *new_mol_viz_item = (external_mol_viz *) malloc ( sizeof(external_mol_viz) );
/* Set its values */
new_mol_viz_item->mol_type = mol_type;
new_mol_viz_item->pos_x = pos_x + x_offset; // x_offset += 0.008;
new_mol_viz_item->pos_y = pos_y;
new_mol_viz_item->pos_z = pos_z;
new_mol_viz_item->norm_x = norm_x;
new_mol_viz_item->norm_y = norm_y;
new_mol_viz_item->norm_z = norm_z;
/* Add it to the top of the molecule list */
new_mol_viz_item->next_mol = next_mol_name->mol_list;
next_mol_name->mol_list = new_mol_viz_item;
next_mol += 1;
}
}
}
}
}
/* Write out the molecules with their proper names */
external_mol_viz_by_name *nl = mol_name_list;
external_mol_viz *mv;
while (nl != NULL) {
if ( (world->viz_options & VIZ_PROXY_OUTPUT) || ( (strcmp(nl->mol_name,"volume_proxy")!=0) && (strcmp(nl->mol_name,"volume_proxy")!=0) ) ) {
/* Write the name length and name */
byte name_len = strlen(nl->mol_name);
fwrite(&name_len, sizeof(name_len), 1, custom_file);
fwrite(nl->mol_name, sizeof(char), name_len, custom_file);
/* Write species type: */
byte species_type = 0;
if (nl->mol_list != NULL) {
if (nl->mol_list->mol_type == 's') {
species_type = 1;
}
}
fwrite(&species_type, sizeof(species_type), 1, custom_file);
/* write number of x,y,z floats for mol positions to follow: */
u_int n_floats = 0;
mv = nl->mol_list;
while (mv != NULL) {
n_floats += 3;
mv = mv->next_mol;
}
fwrite(&n_floats, sizeof(n_floats), 1, custom_file);
/* Write positions of volume and surface molecules: */
mv = nl->mol_list;
while (mv != NULL) {
float pos_x = mv->pos_x;
float pos_y = mv->pos_y;
float pos_z = mv->pos_z;
fwrite(&pos_x, sizeof(pos_x), 1, custom_file);
fwrite(&pos_y, sizeof(pos_y), 1, custom_file);
fwrite(&pos_z, sizeof(pos_z), 1, custom_file);
mv = mv->next_mol;
}
/* Write orientations of surface surface molecules: */
mv = nl->mol_list;
if (mv->mol_type == 's') {
while (mv != NULL) {
float norm_x = mv->norm_x;
float norm_y = mv->norm_y;
float norm_z = mv->norm_z;
fwrite(&norm_x, sizeof(norm_x), 1, custom_file);
fwrite(&norm_y, sizeof(norm_y), 1, custom_file);
fwrite(&norm_z, sizeof(norm_z), 1, custom_file);
mv = mv->next_mol;
}
}
nl = nl->next_name;
}
}
/*****************************************************/
/******** Write the new BNGL Viz format files ********/
/*****************************************************/
if (space_struct_file != NULL) {
if ( world->viz_options & VIZ_ALT_DUMP_FMT ) {
// Write the data in a human readable format
u_int ss_version = 2;
// fwrite(&ss_version, sizeof(ss_version), 1, space_struct_file );
fprintf ( space_struct_file, "%d\n", ss_version );
if (graph_pattern_table != NULL) {
// Traverse the symbol table to build a dictionary of molecule types
// A sym_table_head has: sym_entry **entries
// First dimension is n_bins
// Second dimension is a linked list
// fprintf ( stdout, "] ] ] ] ] ] ] ] graph pattern table has %d entries in %d bins\n", graph_pattern_table->n_entries, graph_pattern_table->n_bins );
for (int bin=0; bin<graph_pattern_table->n_bins; bin++) {
if (graph_pattern_table->entries[bin] != NULL) {
// fprintf ( stdout, " bin %d is non-empty\n", bin );
struct sym_entry *se = graph_pattern_table->entries[bin];
while (se != NULL) {
// fprintf ( stdout, " entry: %.200s\n", se->name );
fprintf ( space_struct_file, "Entry: %s\n", se->name );
molcomp_list *mcl = (molcomp_list *) se->value;
// fprintf ( stdout, "=============== MOL From graph_pattern_table ===============\n" );
dump_molcomp_list_to ( space_struct_file, mcl );
se = se->next;
}
}
}
}
/* Start with a simple output format */
for (int species_idx = 0; species_idx < world->n_species; species_idx++) {
const unsigned int this_mol_count = viz_mol_count[species_idx];
if (this_mol_count == 0)
continue;
const int id = vizblk->species_viz_states[species_idx];
if (id == EXCLUDE_OBJ)
continue;
struct abstract_molecule **const mols = viz_molp[species_idx];
if (mols == NULL)
continue;
/* Get and save positions of EXTERNAL_SPECIES volume and surface molecules: */
struct abstract_molecule *amp;
for (unsigned int n_mol = 0; n_mol < this_mol_count; ++n_mol) {
amp = mols[n_mol];
if ((amp->properties->flags & EXTERNAL_SPECIES) != 0) {
/* This is complex molecule */
/* The graph pattern will be something like: */
/* c:SH2~NO_STATE!5,c:U~NO_STATE!5!3,c:a~NO_STATE!6,c:b~Y!6!1,c:g~Y!6,m:Lyn@PM!0!1,m:Rec@PM!2!3!4, */
char *gp = amp->graph_data->graph_pattern;
// Write out text for now
// fprintf ( space_struct_file, "Mol Instance %d, name: %.80s\n", n_mol, gp );
long mol_class = -1;
if (graph_pattern_table != NULL) {
struct sym_entry *sp;
sp = retrieve_sym(gp, graph_pattern_table);
if (sp != NULL) {
molcomp_list *mcl = NULL;
mcl = (molcomp_list *) sp->value;
mol_class = -1 * mcl->molcomp_id; // The code to handle this is only implemented in the JSON branch at this time
// fprintf ( stdout, "=============== MOL From graph_pattern_table ===============\n" );
// dump_molcomp_list_to ( space_struct_file, mcl );
}
}
// fprintf ( space_struct_file, " Mol Class = %ld\n", mcl->molcomp_id );
float pos_x = 0.0;
float pos_y = 0.0;
float pos_z = 0.0;
float norm_x = 0.0;
float norm_y = 0.0;
float norm_z = 0.0;
if ((amp->properties->flags & NOT_FREE) == 0) {
struct volume_molecule *mp = (struct volume_molecule *)amp;
pos_x = mp->pos.x;
pos_y = mp->pos.y;
pos_z = mp->pos.z;
} else if ((amp->properties->flags & ON_GRID) != 0) {
struct surface_molecule *gmp = (struct surface_molecule *)amp;
struct vector3 where;
uv2xyz(&(gmp->s_pos), gmp->grid->surface, &where);
pos_x = where.x;
pos_y = where.y;
pos_z = where.z;
}
pos_x *= world->length_unit;
pos_y *= world->length_unit;
pos_z *= world->length_unit;
if ((amp->properties->flags & ON_GRID) != 0) {
struct surface_molecule *gmp = (struct surface_molecule *)mols[n_mol];
short orient = gmp->orient;
norm_x = orient * gmp->grid->surface->normal.x;
norm_y = orient * gmp->grid->surface->normal.y;
norm_z = orient * gmp->grid->surface->normal.z;
}
fprintf ( space_struct_file, "Mol %d: Class=%ld Position=(%g %g %g) Orientation=(%g %g %g)\n", n_mol, mol_class, pos_x, pos_y, pos_z, norm_x, norm_y, norm_z );
}
}
}
fflush ( space_struct_file );
fclose ( space_struct_file );
} else if ( world->viz_options & VIZ_JSON_MOLCOMP_FMT ) {
// Write the data as a JSON MOLCOMP format (list of lists)
int *gp_entry_for_id = NULL; // Graph Pattern Entry: Mapping from IDs to the index in the table
fprintf ( space_struct_file, "[\n" ); // Start of entire file as a single list
fprintf ( space_struct_file, " 2,\n" ); // File format number
fprintf ( space_struct_file, " [\n" ); // Start of molecule definitions
if (graph_pattern_table != NULL) {
// Traverse the symbol table to build a dictionary of molecule types
// A sym_table_head has: sym_entry **entries
// First dimension is n_bins
// Second dimension is a linked list
// fprintf ( stdout, "] ] ] ] ] ] ] ] graph pattern table has %d entries in %d bins\n", graph_pattern_table->n_entries, graph_pattern_table->n_bins );
int n_gp_entries = graph_pattern_table->n_entries;
int gp_entry_num = 0;
gp_entry_for_id = (int *) malloc ( n_gp_entries * sizeof(int) ); // This is the mapping from ids to index in the table
for (int bin=0; bin<graph_pattern_table->n_bins; bin++) {
if (graph_pattern_table->entries[bin] != NULL) {
// fprintf ( stdout, " bin %d is non-empty\n", bin );
struct sym_entry *se = graph_pattern_table->entries[bin];
while (se != NULL) {
// fprintf ( stdout, " entry: %.200s\n", se->name );
// fprintf ( space_struct_file, "Entry: %s\n", se->name );
molcomp_list *mcl = (molcomp_list *) se->value;
gp_entry_for_id[mcl->molcomp_id] = gp_entry_num; // Set the table entry for this id
external_molcomp_loc *mca = mcl->molcomp_array;
int num_parts = mcl->num_molcomp_items;
// fprintf ( stdout, "=============== MOL From graph_pattern_table ===============\n" );
{
int i, j;
fprintf ( space_struct_file, " [\n" ); // Start of a complex
for (i=0; i<num_parts; i++) {
fprintf ( space_struct_file, " [ " ); // Start of a molecule or component
if (mca[i].is_mol) {
fprintf ( space_struct_file, "\"m\"" );
} else {
fprintf ( space_struct_file, "\"c\"" );
}
fprintf ( space_struct_file, ", \"%s\"", mca[i].name );
fprintf ( space_struct_file, ", [%g, %g, %g], [", mca[i].x, mca[i].y, mca[i].z );
for (j=0; j<mca[i].num_peers; j++) {
fprintf ( space_struct_file, "%d", mca[i].peers[j] );
if (j < mca[i].num_peers - 1) {
fprintf ( space_struct_file, "," );
}
}
if (mca[i].states == NULL) {
fprintf ( space_struct_file, "], \"\" ]" ); // End of a molecule or component with no states
} else if (strcmp(mca[i].states,"~NO_STATE")==0) {
fprintf ( space_struct_file, "], \"\" ]" ); // End of a molecule or component with no states
} else {
fprintf ( space_struct_file, "], \"%s\" ]", mca[i].states ); // End of a molecule or component with states
}
end_line_opt_comma ( space_struct_file, i < (num_parts-1) );
}
fprintf ( space_struct_file, " ]" ); // End of a complex
gp_entry_num++;
end_line_opt_comma ( space_struct_file, gp_entry_num < n_gp_entries );
}
// dump_molcomp_list_to ( space_struct_file, mcl );
se = se->next;
}
}
}
}
fprintf ( space_struct_file, " ],\n" ); // End of molecule definitions
/* Write the molecule instances */
fprintf ( space_struct_file, " [" ); // Start of instances - newlines will be added as new elements are added to handle commas
int first_pass = 1;
for (int species_idx = 0; species_idx < world->n_species; species_idx++) {
const unsigned int this_mol_count = viz_mol_count[species_idx];
if (this_mol_count == 0)
continue;
const int id = vizblk->species_viz_states[species_idx];
if (id == EXCLUDE_OBJ)
continue;
struct abstract_molecule **const mols = viz_molp[species_idx];
if (mols == NULL)
continue;
/* Get and save positions of EXTERNAL_SPECIES volume and surface molecules: */
struct abstract_molecule *amp;
for (unsigned int n_mol = 0; n_mol < this_mol_count; ++n_mol) {
amp = mols[n_mol];
if ((amp->properties->flags & EXTERNAL_SPECIES) != 0) {
/* This is complex molecule */
/* The graph pattern will be something like: */
/* c:SH2~NO_STATE!5,c:U~NO_STATE!5!3,c:a~NO_STATE!6,c:b~Y!6!1,c:g~Y!6,m:Lyn@PM!0!1,m:Rec@PM!2!3!4, */
char *gp = amp->graph_data->graph_pattern;
// Write out text for now
// fprintf ( space_struct_file, "Mol Instance %d, name: %.80s\n", n_mol, gp );
long mol_class = -1;
if (graph_pattern_table != NULL) {
struct sym_entry *sp;
sp = retrieve_sym(gp, graph_pattern_table);
if (sp != NULL) {
molcomp_list *mcl = NULL;
mcl = (molcomp_list *) sp->value;
mol_class = gp_entry_for_id[mcl->molcomp_id];
// fprintf ( stdout, "=============== MOL From graph_pattern_table ===============\n" );
// dump_molcomp_list_to ( space_struct_file, mcl );
}
}
// fprintf ( space_struct_file, " Mol Class = %ld\n", mcl->molcomp_id );
float pos_x = 0.0;
float pos_y = 0.0;
float pos_z = 0.0;
float norm_x = 0.0;
float norm_y = 0.0;
float norm_z = 0.0;
if ((amp->properties->flags & NOT_FREE) == 0) {
struct volume_molecule *mp = (struct volume_molecule *)amp;
pos_x = mp->pos.x;
pos_y = mp->pos.y;
pos_z = mp->pos.z;
} else if ((amp->properties->flags & ON_GRID) != 0) {
struct surface_molecule *gmp = (struct surface_molecule *)amp;
struct vector3 where;
uv2xyz(&(gmp->s_pos), gmp->grid->surface, &where);
pos_x = where.x;
pos_y = where.y;
pos_z = where.z;
}
pos_x *= world->length_unit;
pos_y *= world->length_unit;
pos_z *= world->length_unit;
if ((amp->properties->flags & ON_GRID) != 0) {
struct surface_molecule *gmp = (struct surface_molecule *)mols[n_mol];
short orient = gmp->orient;
norm_x = orient * gmp->grid->surface->normal.x;
norm_y = orient * gmp->grid->surface->normal.y;
norm_z = orient * gmp->grid->surface->normal.z;
}
if ( first_pass ) {
fprintf ( space_struct_file, "\n" ); // End the previous line without a comma
first_pass = 0;
} else {
fprintf ( space_struct_file, ",\n" ); // End the previous line with a comma
}
// fprintf ( space_struct_file, " Mol %d: Class=%ld Position=(%g %g %g) Orientation=(%g %g %g)\n", n_mol, mol_class, pos_x, pos_y, pos_z, norm_x, norm_y, norm_z );
fprintf ( space_struct_file, " [%ld,[%g,%g,%g],[%g,%g,%g]]", mol_class, pos_x, pos_y, pos_z, norm_x, norm_y, norm_z );
// It's not clear why this should be (species_idx<(world->n_species-2). Why -2 and not -1? Is there an extra species?
// end_line_opt_comma ( space_struct_file, (species_idx<(world->n_species-2)) || (n_mol < (this_mol_count-1)) );
}
}
}
fprintf ( space_struct_file, "\n ]\n" ); // End of instances
fprintf ( space_struct_file, "]\n" ); // End of entire file as a single list
fflush ( space_struct_file );
fclose ( space_struct_file );
if ( gp_entry_for_id != NULL ) {
free ( gp_entry_for_id );
}
}
}
/* Free the structures used to build the molecule lists from the complexes */
while (mol_name_list != NULL) {
nl = mol_name_list;
/* Free the name block */
free ( nl->mol_name );
/* Free the list of molecule instances */
while (nl->mol_list != NULL) {
mv = nl->mol_list;
nl->mol_list = mv->next_mol;
free ( mv );
}
mol_name_list = nl->next_name;
free ( nl );
}
fclose(custom_file);
custom_file = NULL;
free_ptr_array((void **)viz_molp, world->n_species);
viz_molp = NULL;
free(viz_mol_count);
viz_mol_count = NULL;
} // if ((fdlp->type == ALL_MOL_DATA) || (fdlp->type == MOL_POS)) {
free ( file_prefix_no_Scene );
free ( file_prefix_usually_Scene );
if (world->dump_level >= 50) {
fprintf ( stdout, ">>>>>>>>>>>>>>>>>>>>>>> Bottom of MolViz Output <<<<<<<<<<<<<<<<<<<\n" );
}
return 0;
}
/*********************************************************************
init_frame_data_list:
In: vizblk: the VIZ_OUTPUT block to initialize
Out: 0 on success, 1 on error.
Initializes frame_data_list structure.
Sets the value of the current iteration step to the start value.
Sets the number of iterations.
***********************************************************************/
int init_frame_data_list(struct volume *world,
struct viz_output_block *vizblk) {
int mol_orient_frame_present = 0;
int mol_pos_frame_present = 0;
struct frame_data_list *fdlp;
if (vizblk->frame_data_head == NULL)
return 0;
switch (vizblk->viz_mode) {
case NO_VIZ_MODE:
count_time_values(world, vizblk->frame_data_head);
if (reset_time_values(world, vizblk->frame_data_head, world->start_iterations))
return 1;
break;
// return 0;
case ASCII_MODE:
count_time_values(world, vizblk->frame_data_head);
if (reset_time_values(world, vizblk->frame_data_head, world->start_iterations))
return 1;
break;
case CELLBLENDER_MODE_V1:
count_time_values(world, vizblk->frame_data_head);
if (reset_time_values(world, vizblk->frame_data_head, world->start_iterations))
return 1;
break;
default:
count_time_values(world, vizblk->frame_data_head);
if (reset_time_values(world, vizblk->frame_data_head, world->start_iterations))
return 1;
break;
}
for (fdlp = vizblk->frame_data_head; fdlp != NULL; fdlp = fdlp->next) {
if (fdlp->curr_viz_iteration == NULL)
continue;
switch (fdlp->type) {
case MOL_ORIENT:
mol_orient_frame_present = 1;
break;
case MOL_POS:
mol_pos_frame_present = 1;
break;
case ALL_MOL_DATA:
mol_pos_frame_present = 1;
mol_orient_frame_present = 1;
break;
default:
/* Do nothing */
;
}
} /* end while */
/* Check that the user hasn't selected a useless set of output info */
if ((mol_orient_frame_present) & (!mol_pos_frame_present))
mcell_warn("The input file contains ORIENTATIONS but not POSITIONS "
"statement in the MOLECULES block. The molecules cannot be "
"visualized.");
return 0;
}
/**************************************************************************
update_frame_data_list:
In: vizblk: VIZ_OUTPUT block
Out: 0 on success, 1 on failure.
Calls output visualization functions if necessary.
Updates value of the current iteration step and pointer
to the current iteration in the linked list.
**************************************************************************/
int update_frame_data_list(struct volume *world,
struct viz_output_block *vizblk) {
static char const *const FRAME_TYPES[NUM_FRAME_TYPES] = {
"MOL_POS", "MOL_ORIENT", "ALL_MOL_DATA",
};
if (vizblk == NULL)
return 0;
if (vizblk->frame_data_head == NULL)
return 0;
switch (world->notify->viz_output_report) {
case NOTIFY_NONE:
break;
case NOTIFY_BRIEF:
case NOTIFY_FULL:
mcell_log("Updating viz output on iteration %lld.", world->current_iterations);
break;
default:
UNHANDLED_CASE(world->notify->viz_output_report);
}
/* Scan over all frames, producing appropriate output. */
for (struct frame_data_list *fdlp = vizblk->frame_data_head; fdlp != NULL;
fdlp = fdlp->next) {
if (world->current_iterations != fdlp->viz_iteration)
continue;
if (world->notify->viz_output_report == NOTIFY_FULL) {
if (fdlp->type >= NUM_FRAME_TYPES)
mcell_warn(" Updating data frame of unknown type %d.", fdlp->type);
else
mcell_log(" Updating data frame of type %s.", FRAME_TYPES[fdlp->type]);
}
switch (vizblk->viz_mode) {
case ASCII_MODE:
if (output_ascii_molecules(world, vizblk, fdlp))
return 1;
break;
case CELLBLENDER_MODE_V1:
if (output_cellblender_molecules(world, vizblk, fdlp))
return 1;
break;
case NO_VIZ_MODE:
default:
/* Do nothing for vizualization */
break;
}
while (fdlp->curr_viz_iteration != NULL &&
fdlp->viz_iteration == world->current_iterations) {
fdlp->curr_viz_iteration = fdlp->curr_viz_iteration->next;
if (fdlp->curr_viz_iteration)
fdlp->viz_iteration = frame_iteration(
world, fdlp->curr_viz_iteration->value, fdlp->list_type);
}
if (world->notify->viz_output_report == NOTIFY_FULL)
mcell_log(" Next update on iteration %lld.", fdlp->viz_iteration);
}
return 0;
}
/**************************************************************************
finalize_viz_output:
In: vizblk: VIZ_OUTPUT block
Out: Returns 1 on error and zero otherwise. Writes final information
into visualization output files.
**************************************************************************/
int finalize_viz_output(struct volume *world, struct viz_output_block *vizblk) {
if (vizblk == NULL)
return 0;
switch (vizblk->viz_mode) {
case NO_VIZ_MODE:
case ASCII_MODE:
default:
/* Do nothing for vizualization */
break;
}
return 0;
}
| C |
3D | mcellteam/mcell | src/data_model_import.py | .py | 9,605 | 249 | import pymcell as m
import json
import pickle
import logging
from typing import List, Dict, Tuple, Any
def read_json_data_model(file_name: str) -> Dict[str, Any]:
""" Read a CellBlender data model in JSON format """
with open(file_name, 'r') as f:
json_model = f.read()
data_model = json.loads(json_model)
logging.info("Reading data model {}".format(file_name))
return data_model
def read_pickle_data_model(file_name) -> Dict[str, Any]:
""" Read a pickled CellBlender data model """
pickle_model = pickle.load( open( file_name, "rb" ) )
logging.info("Reading data model {}".format(file_name))
return pickle_model
def create_species_from_dm(
data_model: Dict[str, Any]) -> Dict[str, m.Species]:
""" Create a dictionary of Species from a CB data model """
logging.info("Creating species from data model")
species_dm_list = data_model['mcell']['define_molecules']['molecule_list']
species_dict = {}
for species_dm in species_dm_list:
species_name = species_dm['mol_name']
dc = float(species_dm['diffusion_constant'])
species_type = species_dm['mol_type']
surface = False
if species_type == '2D':
surface = True
species_dm = m.Species(species_name, dc, surface)
species_dict[species_name] = species_dm
return species_dict
def make_spec_orient_list(
mol_str_list: List[str],
species: Dict[str, m.Species]) -> List[Tuple[m.Species, m.Orient]]:
spec_orient_list = []
for r in mol_str_list:
if r.endswith("'") or r.endswith(",") or r.endswith(";"):
r_str = r[:-1]
r_orient = r[-1]
if r_orient == "'":
orient = m.Orient.up
elif r_orient == ",":
orient = m.Orient.down
elif r_orient == ";":
orient = m.Orient.mix
else:
orient = m.Orient.mix
spec = species[r_str]
spec_orient_list.append(m.OrientedSpecies(spec, orient))
else:
spec = species[r]
spec_orient_list.append(spec)
return spec_orient_list
def create_reactions_from_dm(
data_model: Dict[str, Any],
species: Dict[str, m.Species]) -> List[m.Reaction]:
""" Create a dictionary of Reactions from a CB data model """
logging.info("Creating reactions from data model")
rxn_dm_list = data_model['mcell']['define_reactions']['reaction_list']
rxn_list = []
for rxn_dm in rxn_dm_list:
# rxn_name = rxn_dm['rxn_name']
fwd_rate = float(rxn_dm['fwd_rate'])
# try:
# bkwd_rate = float(rxn_dm['bkwd_rate'])
# except ValueError:
# pass
reactants_str_list = rxn_dm['reactants'].split(" + ")
products_str_list = rxn_dm['products'].split(" + ")
r_list = make_spec_orient_list(reactants_str_list, species)
p_list = make_spec_orient_list(products_str_list, species)
# rxn_type = rxn_dm['rxn_type']
rxn_dm = m.Reaction(r_list, p_list, fwd_rate)
rxn_list.append(rxn_dm)
return rxn_list
def create_meshobjs_from_dm(
dm: Dict[str, Any]) -> Dict[str, m.MeshObj]:
""" Create a dictionary of MeshObj objects from a CB data model """
logging.info("Creating mesh objects from data model")
meshobj_dm_list = dm['mcell']['geometrical_objects']['object_list']
meshobj_dict = {}
for meshobj_dm in meshobj_dm_list:
name = meshobj_dm['name']
vert_list = meshobj_dm['vertex_list']
face_list = meshobj_dm['element_connections']
meshobj = m.MeshObj(name, vert_list, face_list)
try:
for reg_dm in meshobj_dm['define_surface_regions']:
reg_name = reg_dm['name']
face_list = reg_dm['include_elements']
m.SurfaceRegion(meshobj, reg_name, face_list)
except KeyError:
pass
meshobj_dict[name] = meshobj
return meshobj_dict
def create_surface_classes_from_dm(
dm: Dict[str, Any],
world: m.MCellSim,
spec_dict: Dict[str, m.Species]) -> Dict[str, m.SurfaceClass]:
""" Create a dictionary of SurfaceClass objects from a CB data model """
logging.info("Creating surface classes from data model")
sc_dm_list = dm['mcell']['define_surface_classes']['surface_class_list']
sc_dict = {}
for sc_dm in sc_dm_list:
sc_name = sc_dm['name']
for sc_prop_dm in sc_dm['surface_class_prop_list']:
if sc_prop_dm['affected_mols'] == 'SINGLE':
spec_name = sc_prop_dm['molecule']
else:
# XXX: Need to add in case for ALL_MOLECULES,
# ALL_SURFACE_MOLECULES, etc.
pass
spec = spec_dict[spec_name]
sc_enums = {"TRANSPARENT": m.SC.transp , "REFLECTIVE": m.SC.reflect, "ABSORPTIVE": m.SC.absorb }
surf_class_type = sc_enums[sc_prop_dm['surf_class_type']]
odict = {"'": Orient.up, ",": Orient.down, ";": Orient.mix}
orient = odict[sc_prop_dm['surf_class_orient']]
spec_orient = OrientedSpecies(spec, orient)
sc = m.SurfaceClass(surf_class_type, spec_orient, name=sc_name)
sc_dict[sc_name] = sc
return sc_dict
def create_mod_surf_reg_from_dm(
dm: Dict[str, Any],
world: m.MCellSim,
sc_dict: Dict[str, m.SurfaceClass],
meshobj_dict: Dict[str, m.MeshObj]) -> None:
logging.info("Creating surface region modifications from data model")
mod_sr_list = dm['mcell']['modify_surface_regions']['modify_surface_regions_list']
for mod_sr in mod_sr_list:
object_name = mod_sr['object_name']
region_name = mod_sr['region_name']
surf_class_name = mod_sr['surf_class_name']
sc = sc_dict[surf_class_name]
meshobj = meshobj_dict[object_name]
for reg in meshobj.regions:
if reg.reg_name == region_name:
world.assign_surf_class(sc, reg)
break
def create_release_sites_from_dm(
data_model: Dict[str, Any],
world: m.MCellSim,
meshobjs: Dict[str, m.MeshObj],
species: Dict[str, m.Species]) -> None:
logging.info("Creating release sites from data model")
rel_site_dm_list = \
data_model['mcell']['release_sites']['release_site_list']
for rel_site_dm in rel_site_dm_list:
rel_site_name = rel_site_dm['name']
object_expr = rel_site_dm['object_expr']
idx = object_expr.find("[")
if idx > 0:
object_name = object_expr[:idx]
reg_name = object_expr[idx+1:-1]
else:
object_name = object_expr
reg_name = ""
meshobj = meshobjs[object_name]
spec_name = rel_site_dm['molecule']
spec = species[spec_name]
quantity = int(rel_site_dm['quantity'])
orient = rel_site_dm['orient']
odict = {"'": Orient.up, ",": Orient.down, ";": Orient.mix}
spec_orient = OrientedSpecies(spec, odict[orient])
# XXX: this is really clunky.
reg = None
for r in meshobj.regions:
if r.reg_name == reg_name:
reg = r
break
if reg:
rel = m.ObjectRelease(spec_orient, number=quantity, region=reg)
else:
rel = m.ObjectRelease(spec_orient, number=quantity, mesh_obj=meshobj)
world.release(rel)
def create_reaction_data_from_dm(
data_model: Dict[str, Any],
world: m.MCellSim,
meshobjs: Dict[str, m.MeshObj],
species: Dict[str, m.Species]) -> None:
logging.info("Creating reactions from data model")
rxn_out_dm_list = \
data_model['mcell']['reaction_data_output']['reaction_output_list']
for rxn_out_dm in rxn_out_dm_list:
molecule_name = rxn_out_dm['molecule_name']
spec = species[molecule_name]
count_location = rxn_out_dm['count_location']
if count_location == "Object":
object_name = rxn_out_dm['object_name']
meshobj = meshobjs[object_name]
world.add_count(spec, mesh_obj=meshobj)
elif count_location == "Region":
region_name = rxn_out_dm['region_name']
object_name = rxn_out_dm['object_name']
meshobj = meshobjs[object_name]
for reg in meshobj.regions:
if reg.reg_name == region_name:
world.add_count(spec, reg=reg)
else:
world.add_count(spec)
def create_viz_data_from_dm(
data_model: Dict,
world: m.MCellSim,
species: Dict[str, m.Species]) -> None:
logging.info("Creating visualization data from data model")
species_dm_list = data_model['mcell']['define_molecules']['molecule_list']
export_all = data_model['mcell']['viz_output']['export_all']
species_list = []
for species_dm in species_dm_list:
if export_all or species_dm['export_viz']:
species_name = species_dm['mol_name']
spec = species[species_name]
species_list.append(spec)
world.add_viz(species_list)
def create_initializations_from_dm(
data_model: Dict,
world: m.MCellSim) -> None:
logging.info("Creating initializations from data model")
initialization = data_model['mcell']['initialization']
iterations = int(initialization['iterations'])
time_step = float(initialization['time_step'])
world.set_iterations(iterations)
world.set_time_step(time_step)
| Python |
3D | mcellteam/mcell | src/triangle_overlap.h | .h | 565 | 18 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
int coplanar_tri_overlap(struct wall* w1, struct wall* w2);
| Unknown |
3D | mcellteam/mcell | src/mcell_species.h | .h | 1,813 | 61 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include <stdbool.h>
//#include "mcell_engine.h"
#include "mcell_init.h"
#include "mcell_structs.h"
typedef struct sym_entry mcell_symbol;
struct mcell_species_spec {
const char *name;
double D;
int is_2d; // 3D = 0; 2D = 1
double custom_time_step; // default is 0.0
int target_only; // default is 0
double max_step_length; // default is 0.0
double space_step;
/*
* external species denotes a species whose participation in the system will
* be queried to an external algorithm (nfsim for now)
*/
int external_species; //default is 0
};
struct mcell_species {
struct mcell_species *next;
struct sym_entry *mol_type;
short orient_set;
short orient;
};
struct mcell_species_list {
struct mcell_species *mol_type_head;
struct mcell_species *mol_type_tail;
};
MCELL_STATUS mcell_create_species(MCELL_STATE *state,
struct mcell_species_spec *species,
mcell_symbol **species_ptr);
struct mcell_species *
mcell_add_to_species_list(mcell_symbol *species_ptr, bool is_oriented,
int orientation, struct mcell_species *species_list);
void mcell_delete_species_list(struct mcell_species *species);
int new_mol_species(MCELL_STATE *state, const char *name, struct sym_entry **sym_ptr);
| Unknown |
3D | mcellteam/mcell | src/dyngeom_parse_extras.h | .h | 2,521 | 71 | #ifndef DYNGEOM_PARSE_EXTRAS_H
#define DYNGEOM_PARSE_EXTRAS_H
#include "mcell_structs.h"
#define MAX_INCLUDE_DEPTH 16
struct dyngeom_parse_vars * create_dg_parse(struct volume *state);
struct dyngeom_parse_vars {
struct sym_table_head *reg_sym_table;
struct sym_table_head *obj_sym_table;
struct geom_object *root_object;
struct geom_object *root_instance;
struct geom_object *current_object;
struct region *current_region;
struct name_list *object_name_list;
struct name_list *object_name_list_end;
char const *curr_file; /* Name of MDL file currently being parsed */
/* Line numbers and filenames for all of the currently parsing files */
u_int line_num[MAX_INCLUDE_DEPTH];
char const *include_filename[MAX_INCLUDE_DEPTH];
/* Stack pointer for filename/line number stack */
u_int include_stack_ptr;
/* Line number where last top-level (i.e. non-nested) multi-line (C-style)
* comment was started in the current MDL file. */
int comment_started;
};
#include "mcell_objects.h"
int parse_dg(struct dyngeom_parse_vars *dg_parse, const char *dynamic_geometry_filename);
int parse_dg_init(struct dyngeom_parse_vars *dg_parse, const char *dynamic_geometry_filename, struct volume *state);
void setup_root_obj_inst(struct dyngeom_parse_vars *dg_parse_vars, struct volume *state);
struct sym_entry *dg_start_object(
struct dyngeom_parse_vars *dg_parse_vars,
char *name);
struct geom_object *dg_start_object_simple(struct dyngeom_parse_vars *dg_parse_vars,
struct object_creation *obj_creation,
char *name);
struct geom_object *dg_new_polygon_list(
struct dyngeom_parse_vars *dg_parse_vars,
char *obj_name);
void dg_finish_object(struct dyngeom_parse_vars *dg_parse_vars);
struct region *dg_create_region(
struct sym_table_head *reg_sym_table,
struct geom_object *objp,
const char *name);
struct region *dg_make_new_region(
struct sym_table_head *reg_sym_table,
const char *obj_name,
const char *region_last_name);
int dg_copy_object_regions(
struct dyngeom_parse_vars *dg_parse_vars,
struct geom_object *dst_obj,
struct geom_object *src_obj);
int dg_deep_copy_object(
struct dyngeom_parse_vars *dg_parse_vars,
struct geom_object *dst_obj,
struct geom_object *src_obj);
struct sym_entry *dg_existing_object(
struct dyngeom_parse_vars *dg_parse_vars,
char *name);
char *find_include_file(char const *path, char const *cur_path);
#endif
| Unknown |
3D | mcellteam/mcell | src/vector.c | .c | 18,751 | 760 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/* 3D vector routines */
#include "config.h"
#include <math.h>
#include <float.h>
#include "vector.h"
#include "mcell_structs.h"
#define MY_PI 3.14159265358979323846
/**
* Multiplies two matrices together.
* Allocates a local 4x4 matrix for computation and then copies result
* into om.
* @param m1 a 4 x m input matrix
* @param m2 a 4 x n input matrix
* @param om a 4 x n output matrix
* @param l number of rows in m1
* @param m number of columns in m1 == number of rows in m2
* @param n number of columns in m2
*/
void mult_matrix(double (*m1)[4], double (*m2)[4], double (*om)[4],
short unsigned int l, short unsigned int m,
short unsigned int n) {
double tm[4][4];
unsigned short i, j, k;
for (i = 0; i < l; i++) {
for (j = 0; j < n; j++) {
tm[i][j] = 0;
for (k = 0; k < m; k++) {
tm[i][j] = tm[i][j] + (m1[i][k]) * (m2[k][j]);
}
}
}
for (i = 0; i < l; i++) {
for (j = 0; j < n; j++) {
om[i][j] = tm[i][j];
}
}
}
/**
* Normalizes a vector3 v.
*/
void normalize(struct vector3 *v) {
double length;
length = vect_length(v);
v->x = v->x / length;
v->y = v->y / length;
v->z = v->z / length;
}
/**
* Initializes a 4x4 Identity matrix.
*/
void init_matrix(double (*im)[4]) {
im[0][0] = 1;
im[0][1] = 0;
im[0][2] = 0;
im[0][3] = 0;
im[1][0] = 0;
im[1][1] = 1;
im[1][2] = 0;
im[1][3] = 0;
im[2][0] = 0;
im[2][1] = 0;
im[2][2] = 1;
im[2][3] = 0;
im[3][0] = 0;
im[3][1] = 0;
im[3][2] = 0;
im[3][3] = 1;
}
/**
* Scales the rows of a matrix according to scaling vector3.
* Scales row0 of im by scale.x
* Scales row1 of im by scale.y
* Scales row2 of im by scale.z
* Scales row3 of im by 1 (no scaling)
* Result is placed in om.
*/
void scale_matrix(double (*im)[4], double (*om)[4], struct vector3 *scale) {
double sc[4][4];
unsigned short l, m, n;
sc[0][0] = scale->x;
sc[0][1] = 0;
sc[0][2] = 0;
sc[0][3] = 0;
sc[1][0] = 0;
sc[1][1] = scale->y;
sc[1][2] = 0;
sc[1][3] = 0;
sc[2][0] = 0;
sc[2][1] = 0;
sc[2][2] = scale->z;
sc[2][3] = 0;
sc[3][0] = 0;
sc[3][1] = 0;
sc[3][2] = 0;
sc[3][3] = 1;
l = 4;
m = 4;
n = 4;
mult_matrix(im, sc, om, l, m, n);
}
void translate_matrix(double (*im)[4], double (*om)[4],
struct vector3 *translate) {
double tm[4][4];
unsigned short l, m, n;
tm[0][0] = 1;
tm[0][1] = 0;
tm[0][2] = 0;
tm[0][3] = 0;
tm[1][0] = 0;
tm[1][1] = 1;
tm[1][2] = 0;
tm[1][3] = 0;
tm[2][0] = 0;
tm[2][1] = 0;
tm[2][2] = 1;
tm[2][3] = 0;
tm[3][0] = translate->x;
tm[3][1] = translate->y;
tm[3][2] = translate->z;
tm[3][3] = 1;
l = 4;
m = 4;
n = 4;
mult_matrix(im, tm, om, l, m, n);
}
void rotate_matrix(double (*im)[4], double (*om)[4], struct vector3 *axis,
double angle) {
double r1[4][4], r2[4][4], r3[4][4], rm[4][4];
double a, b, c, v;
double rad;
unsigned short l, m, n;
normalize(axis);
a = axis->x;
b = axis->y;
c = axis->z;
v = sqrt(b * b + c * c);
r1[0][0] = 1;
r1[0][1] = 0;
r1[0][2] = 0;
r1[0][3] = 0;
r1[1][0] = 0;
r1[1][1] = 1;
r1[1][2] = 0;
r1[1][3] = 0;
r1[2][0] = 0;
r1[2][1] = 0;
r1[2][2] = 1;
r1[2][3] = 0;
r1[3][0] = 0;
r1[3][1] = 0;
r1[3][2] = 0;
r1[3][3] = 1;
if (v != 0.0) {
r1[1][1] = c / v;
r1[1][2] = b / v;
r1[2][1] = -b / v;
r1[2][2] = c / v;
}
r2[0][0] = v;
r2[0][1] = 0;
r2[0][2] = a;
r2[0][3] = 0;
r2[1][0] = 0;
r2[1][1] = 1;
r2[1][2] = 0;
r2[1][3] = 0;
r2[2][0] = -a;
r2[2][1] = 0;
r2[2][2] = v;
r2[2][3] = 0;
r2[3][0] = 0;
r2[3][1] = 0;
r2[3][2] = 0;
r2[3][3] = 1;
rad = MY_PI / 180.0;
r3[0][0] = cos(angle * rad);
r3[0][1] = sin(angle * rad);
r3[0][2] = 0;
r3[0][3] = 0;
r3[1][0] = -sin(angle * rad);
r3[1][1] = cos(angle * rad);
r3[1][2] = 0;
r3[1][3] = 0;
r3[2][0] = 0;
r3[2][1] = 0;
r3[2][2] = 1;
r3[2][3] = 0;
r3[3][0] = 0;
r3[3][1] = 0;
r3[3][2] = 0;
r3[3][3] = 1;
l = 4;
m = 4;
n = 4;
mult_matrix(r1, r2, rm, l, m, n);
mult_matrix(rm, r3, rm, l, m, n);
r2[0][2] = -a;
r2[2][0] = a;
if (v != 0.0) {
r1[1][2] = -b / v;
r1[2][1] = b / v;
}
mult_matrix(rm, r2, rm, l, m, n);
mult_matrix(rm, r1, rm, l, m, n);
mult_matrix(im, rm, om, l, m, n);
}
void tform_matrix(struct vector3 *scale, struct vector3 *translate,
struct vector3 *axis, double angle, double (*om)[4]) {
double sc[4][4];
double tm[4][4];
double r1[4][4], r2[4][4], r3[4][4];
double a, b, c, v;
double rad;
unsigned short l, m, n;
init_matrix(om);
sc[0][0] = scale->x;
sc[0][1] = 0;
sc[0][2] = 0;
sc[0][3] = 0;
sc[1][0] = 0;
sc[1][1] = scale->y;
sc[1][2] = 0;
sc[1][3] = 0;
sc[2][0] = 0;
sc[2][1] = 0;
sc[2][2] = scale->z;
sc[2][3] = 0;
sc[3][0] = 0;
sc[3][1] = 0;
sc[3][2] = 0;
sc[3][3] = 1;
tm[0][0] = 1;
tm[0][1] = 0;
tm[0][2] = 0;
tm[0][3] = 0;
tm[1][0] = 0;
tm[1][1] = 1;
tm[1][2] = 0;
tm[1][3] = 0;
tm[2][0] = 0;
tm[2][1] = 0;
tm[2][2] = 1;
tm[2][3] = 0;
tm[3][0] = translate->x;
tm[3][1] = translate->y;
tm[3][2] = translate->z;
tm[3][3] = 1;
normalize(axis);
a = axis->x;
b = axis->y;
c = axis->z;
v = sqrt(b * b + c * c);
r1[0][0] = 1;
r1[0][1] = 0;
r1[0][2] = 0;
r1[0][3] = 0;
r1[1][0] = 0;
r1[1][1] = 1;
r1[1][2] = 0;
r1[1][3] = 0;
r1[2][0] = 0;
r1[2][1] = 0;
r1[2][2] = 1;
r1[2][3] = 0;
r1[3][0] = 0;
r1[3][1] = 0;
r1[3][2] = 0;
r1[3][3] = 1;
if (v != 0.0) {
r1[1][1] = c / v;
r1[1][2] = b / v;
r1[2][1] = -b / v;
r1[2][2] = c / v;
}
r2[0][0] = v;
r2[0][1] = 0;
r2[0][2] = a;
r2[0][3] = 0;
r2[1][0] = 0;
r2[1][1] = 1;
r2[1][2] = 0;
r2[1][3] = 0;
r2[2][0] = -a;
r2[2][1] = 0;
r2[2][2] = v;
r2[2][3] = 0;
r2[3][0] = 0;
r2[3][1] = 0;
r2[3][2] = 0;
r2[3][3] = 1;
rad = MY_PI / 180.0;
r3[0][0] = cos(angle * rad);
r3[0][1] = sin(angle * rad);
r3[0][2] = 0;
r3[0][3] = 0;
r3[1][0] = -sin(angle * rad);
r3[1][1] = cos(angle * rad);
r3[1][2] = 0;
r3[1][3] = 0;
r3[2][0] = 0;
r3[2][1] = 0;
r3[2][2] = 1;
r3[2][3] = 0;
r3[3][0] = 0;
r3[3][1] = 0;
r3[3][2] = 0;
r3[3][3] = 1;
l = 4;
m = 4;
n = 4;
mult_matrix(r1, r2, om, l, m, n);
mult_matrix(om, r3, om, l, m, n);
r2[0][2] = -a;
r2[2][0] = a;
if (v != 0.0) {
r1[1][2] = -b / v;
r1[2][1] = b / v;
}
mult_matrix(om, r2, om, l, m, n);
mult_matrix(om, r1, om, l, m, n);
mult_matrix(om, sc, om, l, m, n);
mult_matrix(om, tm, om, l, m, n);
}
/**
* Performs vector subtraction.
* Subtracts vector3 p1 from vector3 p2 placing the result in vector3 v.
*/
void vectorize(struct vector3 *p1, struct vector3 *p2, struct vector3 *v) {
v->x = p2->x - p1->x;
v->y = p2->y - p1->y;
v->z = p2->z - p1->z;
}
/**
* Computes the magnitude of a vector.
*/
double vect_length(struct vector3 *v) {
double length;
length = sqrt((v->x) * (v->x) + (v->y) * (v->y) + (v->z) * (v->z));
return (length);
}
/**
* Computes the dot product of two vector3's v1 and v2.
*/
double dot_prod(struct vector3 *v1, struct vector3 *v2) {
double dot;
dot = (v1->x) * (v2->x) + (v1->y) * (v2->y) + (v1->z) * (v2->z);
return (dot);
}
/**
* Performs vector cross product.
* Computes the cross product of two vector3's v1 and v2 storing the result
* in vector3 v3.
*/
void cross_prod(struct vector3 *v1, struct vector3 *v2, struct vector3 *v3) {
v3->x = (v1->y) * (v2->z) - (v1->z) * (v2->y);
v3->y = (v1->z) * (v2->x) - (v1->x) * (v2->z);
v3->z = (v1->x) * (v2->y) - (v1->y) * (v2->x);
}
/************************************************************************
vect_sum:
In: v1 - first vector3
v2 - second vector3
Out: v3 - the sum of the v1 and v2
************************************************************************/
void vect_sum(struct vector3 *v1, struct vector3 *v2, struct vector3 *v3) {
v3->x = v1->x + v2->x;
v3->y = v1->y + v2->y;
v3->z = v1->z + v2->z;
}
/***********************************************************************
scalar_prod:
In: v - vector3
a - scalar
Out: result - the product of the vector3 v by scalar a
***********************************************************************/
void scalar_prod(struct vector3 *v1, double a, struct vector3 *result) {
result->x = a * v1->x;
result->y = a * v1->y;
result->z = a * v1->z;
}
/***************************************************************************
distinguishable_vec3 -- reports whether two vectors are measurably different
(vector analog of distinguishable() in util.c)
Parameters
a -- first vector
b -- second vector
eps -- fractional difference that we think is different
Returns
1 if the vectors are different, 0 otherwise
***************************************************************************/
int distinguishable_vec3(struct vector3 *a, struct vector3 *b, double eps) {
double c, cc, d;
/* Find largest coordinate */
c = fabs(a->x);
d = fabs(a->y);
if (d > c)
c = d;
d = fabs(a->z);
if (d > c)
c = d;
d = fabs(b->x);
if (d > c)
c = d;
d = fabs(b->y);
if (d > c)
c = d;
d = fabs(b->z);
if (d > c)
c = d;
/* Find largest difference */
cc = fabs(a->x - b->x);
d = fabs(a->y - b->y);
if (d > cc)
cc = d;
d = fabs(a->z - b->z);
if (d > cc)
cc = d;
/* Make sure fractional difference is at least eps and absolute difference is
* at least (eps*eps) */
if (c < eps)
c = eps;
return (c * eps < cc);
}
/***************************************************************************
distinguishable_vec2 -- reports whether two vectors are measurably different
(vector analog of distinguishable() in util.c)
Parameters
a -- first vector2
b -- second vector2
eps -- fractional difference that we think is different
Returns
1 if the vectors are different, 0 otherwise
Note: similar to the function "distinguishable_vec3" but for the surface vectors
***************************************************************************/
int distinguishable_vec2(struct vector2 *a, struct vector2 *b, double eps) {
double c, cc, d;
/* Find largest coordinate */
c = fabs(a->u);
d = fabs(a->v);
if (d > c)
c = d;
d = fabs(b->u);
if (d > c)
c = d;
d = fabs(b->v);
if (d > c)
c = d;
/* Find largest difference */
cc = fabs(a->u - b->u);
d = fabs(a->v - b->v);
if (d > cc)
cc = d;
/* Make sure fractional difference is at least eps and absolute difference is
* at least (eps*eps) */
if (c < eps)
c = eps;
return (c * eps < cc);
}
/***************************************************************************
distance_vec3 -- calculates distance between two points in 3D
Parameters
a -- first point
b -- second point
Returns
distance between two points in 3D
***************************************************************************/
double distance_vec3(struct vector3 *a, struct vector3 *b) {
double dist;
dist = sqrt((a->x - b->x) * (a->x - b->x) + (a->y - b->y) * (a->y - b->y) +
(a->z - b->z) * (a->z - b->z));
return dist;
}
/****************************************************************************
parallel_segments:
In: segment defined by endpoints A, B
segment defined by endpoints R, S
Out: 1, if the segments are parallel.
0, otherwise
*****************************************************************************/
int parallel_segments(struct vector3 *A, struct vector3 *B, struct vector3 *R,
struct vector3 *S) {
double length;
struct vector3 prod; /* cross product */
struct vector3 ba, sr;
vectorize(A, B, &ba);
vectorize(S, R, &sr);
cross_prod(&ba, &sr, &prod);
length = vect_length(&prod);
if (!distinguishable(length, 0, EPS_C))
return 1;
return 0;
}
/**************************************************************************
same_side:
In: two points p1 and p2
line defined by the points a and b
Out: returns 1 if points p1 and p2 are on the same side of the line
defined by the points a and b
**************************************************************************/
int same_side(struct vector3 *p1, struct vector3 *p2, struct vector3 *a,
struct vector3 *b) {
struct vector3 cp1, cp2, b_a, p1_a, p2_a;
vectorize(a, b, &b_a);
vectorize(a, p1, &p1_a);
vectorize(a, p2, &p2_a);
cross_prod(&b_a, &p1_a, &cp1);
cross_prod(&b_a, &p2_a, &cp2);
if (dot_prod(&cp1, &cp2) >= 0) {
return 1;
} else
return 0;
}
/************************************************************************
point_in_triangle:
In: point p
triangle defined by points a,b,c
Out: returns 1 if point p is in the triangle defined by
points (a,b,c) or lies on edges (a,b), (b,c) or (a,c).
Note: If point p coincides with vertices (a,b,c) we consider that p
is in the triangle.
************************************************************************/
int point_in_triangle(struct vector3 *p, struct vector3 *a, struct vector3 *b,
struct vector3 *c) {
if (same_side(p, a, b, c) && same_side(p, b, a, c) && same_side(p, c, a, b)) {
return 1;
}
if (((!distinguishable(p->x, a->x, EPS_C)) &&
(!distinguishable(p->y, a->y, EPS_C)) &&
(!distinguishable(p->z, a->z, EPS_C))) ||
((!distinguishable(p->x, b->x, EPS_C)) &&
(!distinguishable(p->y, b->y, EPS_C)) &&
(!distinguishable(p->z, b->z, EPS_C))) ||
((!distinguishable(p->x, c->x, EPS_C)) &&
(!distinguishable(p->y, c->y, EPS_C)) &&
(!distinguishable(p->z, c->z, EPS_C)))) {
return 1;
}
return 0;
}
#undef MY_PI
/*******************************************************************
cross2D:
In: 2D vectors a and b
Out: 2D pseudo cross product Dot(Perp(a0,b)
Note: The code adapted from "Real-Time Collision Detection" by
Christer Ericson, p.205
*******************************************************************/
double cross2D(struct vector2 *a, struct vector2 *b) {
return ((a->v) * (b->u) - (a->u) * (b->v));
}
/*************************************************************************
vectorize2D:
In: 2D vectors p1 and p2
Out: Subtracts vector p1 from p2 and places result into p3
*************************************************************************/
void vectorize2D(struct vector2 *p1, struct vector2 *p2, struct vector2 *p3) {
p3->u = p2->u - p1->u;
p3->v = p2->v - p1->v;
}
/*********************************************************************
point_in_triangle_2D:
In: point p
triangle defined by vertices a, b, c
Out: Returns 1 if point p is inside the above defined triangle,
and 0 otherwise.
Note: The code adapted from "Real-Time Collision Detection" by
Christer Ericson, p.206
***********************************************************************/
int point_in_triangle_2D(struct vector2 *p, struct vector2 *a,
struct vector2 *b, struct vector2 *c) {
struct vector2 p_minus_a, b_minus_a, p_minus_b, c_minus_b, p_minus_c,
a_minus_c;
double pab, pbc, pca;
vectorize2D(a, p, &p_minus_a);
vectorize2D(a, b, &b_minus_a);
vectorize2D(b, p, &p_minus_b);
vectorize2D(b, c, &c_minus_b);
vectorize2D(c, p, &p_minus_c);
vectorize2D(c, a, &a_minus_c);
pab = cross2D(&p_minus_a, &b_minus_a);
pbc = cross2D(&p_minus_b, &c_minus_b);
/* if P left of one of AB and BC and right of the other, not inside triangle
- (pab and pbc have different signs */
if (((pab > 0) && (pbc < 0)) || ((pab < 0) && (pbc > 0)))
return 0;
pca = cross2D(&p_minus_c, &a_minus_c);
/* if P left of one of AB and CA and right of the other, not inside triangle
* - pab and pca have different signs */
if (((pab > 0) && (pca < 0)) || ((pab < 0) && (pca > 0)))
return 0;
/* if P left or right of all edges, so must be in (or on) the triangle */
return 1;
}
/*****************************************************************************
intersect_point_segment:
In: point P and segment AB
Out: 1 if the point P lies on the segment AB, and 0 - otherwise
******************************************************************************/
int intersect_point_segment(struct vector3 *P, struct vector3 *A,
struct vector3 *B) {
struct vector3 ba, pa;
double t; /* parameter in the line parametrical equation */
double ba_length, pa_length; /* length of the vectors */
double cosine_angle; /* cosine of the angle between ba and pa */
/* check for the end points */
if (!distinguishable_vec3(P, A, EPS_C))
return 1;
if (!distinguishable_vec3(P, B, EPS_C))
return 1;
vectorize(A, B, &ba);
vectorize(A, P, &pa);
ba_length = vect_length(&ba);
pa_length = vect_length(&pa);
/* if point intersects segment, vectors pa and ba should be collinear */
cosine_angle = dot_prod(&ba, &pa) / (ba_length * pa_length);
if (distinguishable(cosine_angle, 1.0, EPS_C)) {
return 0;
}
/* Project P on AB, computing parameterized position d(t) = A + t(B - A) */
t = dot_prod(&pa, &ba) / dot_prod(&ba, &ba);
if ((t > 0) && (t < 1))
return 1;
return 0;
}
/***************************************************************************
point_in_box:
In: low_left - lower left front corner of the box
up_right - upper right back corner of the box
point - we want to find out if this point is in the box
Out: Returns 1 if point is in box, 0 otherwise
This is very similar to test_bounding_boxes.
***************************************************************************/
int point_in_box(struct vector3 *low_left, struct vector3 *up_right,
struct vector3 *point) {
if ((up_right->x < point->x) || (low_left->x > point->x))
return 0;
if ((up_right->y < point->y) || (low_left->y > point->y))
return 0;
if ((up_right->z < point->z) || (low_left->z > point->z))
return 0;
return 1;
}
| C |
3D | mcellteam/mcell | src/mcell_dyngeom.c | .c | 7,248 | 190 | /******************************************************************************
*
* Copyright (C) 2006-2014 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
* ****************************************************************************/
#include <stdlib.h>
#include <string.h>
#include "mcell_misc.h"
#include "init.h"
#include "mcell_dyngeom.h"
#include "mcell_objects.h"
#include "count_util.h"
#include "logging.h"
#include "dyngeom.h"
/* simple wrapper for executing the supplied function call. In case
* of an error returns with MCELL_FAIL and prints out error_message */
#define CHECKED_CALL(function, error_message) \
{ \
if (function) { \
mcell_log(error_message); \
return MCELL_FAIL; \
} \
}
int mcell_add_dynamic_geometry_file(char *dynamic_geometry_filepath,
struct mdlparse_vars *parse_state) {
struct volume *state = parse_state->vol;
char *dynamic_geometry_filename =
mcell_find_include_file(dynamic_geometry_filepath, state->curr_file);
state->dynamic_geometry_filename = dynamic_geometry_filename;
#ifdef NOSWIG
schedule_dynamic_geometry(parse_state);
#endif
free(dynamic_geometry_filepath);
return 0;
}
int mcell_change_geometry(struct volume *state, struct poly_object_list *pobj_list) {
state->all_molecules = save_all_molecules(state, state->storage_head);
// Turn off progress reports to avoid spamming mostly useless info to stdout
state->notify->progress_report = NOTIFY_NONE;
if (state->dynamic_geometry_flag != 1) {
free(state->mdl_infile_name);
}
// Make list of already existing regions with fully qualified names.
struct string_buffer *old_region_names =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(old_region_names, MAX_NUM_OBJECTS);
get_reg_names_all_objects(state->root_instance, old_region_names);
// Make list of already existing meshes with fully qualified names.
struct string_buffer *old_inst_mesh_names =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(old_inst_mesh_names, MAX_NUM_OBJECTS);
get_mesh_instantiation_names(state->root_instance, old_inst_mesh_names);
// We set this mainly to take care of some issues with counting, triggers,
// memory cleanup.
state->dynamic_geometry_flag = 1;
CHECKED_CALL(reset_current_counts(
state->mol_sym_table,
state->count_hashmask,
state->count_hash),
"Error when reseting counters.");
struct vector3 llf;
struct vector3 urb;
if (state->periodic_box_obj) {
struct polygon_object* p = (struct polygon_object*)(state->periodic_box_obj->contents);
struct subdivided_box* sb = p->sb;
llf.x = sb->x[0];
llf.y = sb->y[0];
llf.z = sb->z[0];
urb.x = sb->x[1];
urb.y = sb->y[1];
urb.z = sb->z[1];
}
CHECKED_CALL(destroy_everything(state), "Error when freeing memory.");
// We need to reenable the ability to parse geometry
state->disable_polygon_objects = 0;
// Reparse the geometry and instantiations. Nothing else should be included
// in these other MDLs.
struct geom_object *world_object = NULL;
mcell_create_instance_object(state, "Scene", &world_object);
while (pobj_list != NULL) {
struct poly_object polygon = {
pobj_list->obj_name,
pobj_list->vertices,
pobj_list->num_vert,
pobj_list->connections,
pobj_list->num_conn
};
struct geom_object *new_mesh = NULL;
mcell_create_poly_object(state, world_object, &polygon, &new_mesh);
struct region *test_region = mcell_create_region(state, new_mesh, pobj_list->reg_name);
mcell_set_region_elements(test_region, pobj_list->surf_reg_faces, 1);
pobj_list = pobj_list->next;
}
CHECKED_CALL(init_bounding_box(state), "Error initializing bounding box.");
free(state->subvol);
if (state->periodic_box_obj) {
mcell_create_periodic_box(state, "PERIODIC_BOX_INST", &llf, &urb);
}
CHECKED_CALL(init_partitions(state), "Error initializing partitions.");
CHECKED_CALL(init_vertices_walls(state),
"Error initializing vertices and walls.");
CHECKED_CALL(init_regions(state), "Error initializing regions.");
if (state->place_waypoints_flag) {
CHECKED_CALL(place_waypoints(state), "Error while placing waypoints.");
}
if (state->with_checks_flag && !state->use_mcell4) {
CHECKED_CALL(check_for_overlapped_walls(
state->rng, state->n_subvols, state->subvol),
"Error while checking for overlapped walls.");
}
CHECKED_CALL(init_species_mesh_transp(state),
"Error while initializing species-mesh transparency list.");
// Make NEW list of fully qualified region names.
struct string_buffer *new_region_names =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(new_region_names, MAX_NUM_OBJECTS);
get_reg_names_all_objects(state->root_instance, new_region_names);
// Make NEW list of instantiated, fully qualified mesh names.
struct string_buffer *new_inst_mesh_names =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(new_inst_mesh_names, MAX_NUM_OBJECTS);
get_mesh_instantiation_names(state->root_instance, new_inst_mesh_names);
struct string_buffer *meshes_to_ignore =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(meshes_to_ignore, MAX_NUM_OBJECTS);
// Compare old list of mesh names with new list.
sym_diff_string_buffers(
meshes_to_ignore, old_inst_mesh_names, new_inst_mesh_names,
state->notify->add_remove_mesh_warning);
struct string_buffer *regions_to_ignore =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(regions_to_ignore, MAX_NUM_OBJECTS);
// Compare old list of region names with new list.
sym_diff_string_buffers(
regions_to_ignore, old_region_names, new_region_names,
state->notify->add_remove_mesh_warning);
check_count_validity(
state->output_request_head,
regions_to_ignore,
new_region_names,
meshes_to_ignore,
new_inst_mesh_names);
place_all_molecules(state, meshes_to_ignore, regions_to_ignore);
destroy_string_buffer(old_region_names);
destroy_string_buffer(new_region_names);
destroy_string_buffer(old_inst_mesh_names);
destroy_string_buffer(new_inst_mesh_names);
destroy_string_buffer(meshes_to_ignore);
destroy_string_buffer(regions_to_ignore);
free(old_region_names);
free(new_region_names);
free(old_inst_mesh_names);
free(new_inst_mesh_names);
free(meshes_to_ignore);
free(regions_to_ignore);
return 0;
}
| C |
3D | mcellteam/mcell | src/test_api.h | .h | 236 | 12 | #pragma once
#include "mcell_misc.h"
#include "mcell_objects.h"
#include "mcell_react_out.h"
#include "mcell_reactions.h"
#include "mcell_release.h"
#include "mcell_species.h"
#include "mcell_viz.h"
void test_api(MCELL_STATE *state);
| Unknown |
3D | mcellteam/mcell | src/chkpt.h | .h | 1,008 | 32 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include <stdio.h>
#include "mcell_structs.h"
/* header file for chkpt.c, MCell checkpointing functions */
int create_chkpt(struct volume *world, char const *filename);
int write_chkpt(struct volume *world, FILE *fs);
int read_chkpt(struct volume *world, FILE *fs, bool only_time_and_iter);
void chkpt_signal_handler(int signo);
int set_checkpoint_state(struct volume *world);
double compute_scaled_time(struct volume *world, double real_time);
unsigned long long
count_items_in_scheduler(struct storage_list *storage_head);
| Unknown |
3D | mcellteam/mcell | src/dyngeom_yacc.h | .h | 3,363 | 125 | /* A Bison parser, made by GNU Bison 3.0.4. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
#ifndef YY_DG_DYNGEOM_YACC_H_INCLUDED
# define YY_DG_DYNGEOM_YACC_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int dgdebug;
#endif
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
OBJECT = 258,
POLYGON_LIST = 259,
VERTEX_LIST = 260,
ELEMENT_CONNECTIONS = 261,
INSTANTIATE = 262,
PARTITION_X = 263,
PARTITION_Y = 264,
PARTITION_Z = 265,
VAR = 266,
REAL = 267,
LLINTEGER = 268,
TO = 269,
STEP = 270,
TRANSLATE = 271,
SCALE = 272,
ROTATE = 273,
INCLUDE_ELEMENTS = 274,
INCLUDE_FILE = 275,
DEFINE_SURFACE_REGIONS = 276,
STR_VALUE = 277,
UNARYMINUS = 278
};
#endif
/* Tokens. */
#define OBJECT 258
#define POLYGON_LIST 259
#define VERTEX_LIST 260
#define ELEMENT_CONNECTIONS 261
#define INSTANTIATE 262
#define PARTITION_X 263
#define PARTITION_Y 264
#define PARTITION_Z 265
#define VAR 266
#define REAL 267
#define LLINTEGER 268
#define TO 269
#define STEP 270
#define TRANSLATE 271
#define SCALE 272
#define ROTATE 273
#define INCLUDE_ELEMENTS 274
#define INCLUDE_FILE 275
#define DEFINE_SURFACE_REGIONS 276
#define STR_VALUE 277
#define UNARYMINUS 278
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 99 "dyngeom_parse.y" /* yacc.c:1909 */
int tok;
double dbl;
char *str;
long long llival;
struct sym_entry *sym;
struct vector3 *vec3;
struct num_expr_list_head nlist;
struct geom_object *obj;
struct object_list obj_list;
struct region *reg;
#line 113 "dyngeom_yacc.h" /* yacc.c:1909 */
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
int dgparse (struct dyngeom_parse_vars *dg_parse, yyscan_t scanner);
#endif /* !YY_DG_DYNGEOM_YACC_H_INCLUDED */
| Unknown |
3D | mcellteam/mcell | src/mcell_run.c | .c | 29,264 | 827 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <string.h>
#include <assert.h>
#include <float.h>
#include <math.h>
#ifndef _MSC_VER
#include <unistd.h>
#include <sys/resource.h>
#else
#include <process.h> // getpid
#endif
#if defined(__linux__)
#include <fenv.h>
#endif
#include "sym_table.h"
#include "logging.h"
#include "vol_util.h"
#include "react_output.h"
#include "viz_output.h"
#include "volume_output.h"
#include "diffuse.h"
#include "init.h"
#include "chkpt.h"
#include "argparse.h"
#include "dyngeom.h"
#include "mcell_run.h"
#include <nfsim_c.h>
#include "mcell_reactions.h"
#include "mcell_react_out.h"
#include "dump_state.h"
#include "debug_config.h"
// static helper functions
static long long mcell_determine_output_frequency(MCELL_STATE *state);
/***********************************************************************
process_volume_output:
Produce this round's volume output, if any.
In: struct volume *wrld - the world
double not_yet - earliest time which should not yet be output
Out: none. volume output files are updated as appropriate.
***********************************************************************/
static void process_volume_output(struct volume *wrld, double not_yet) {
struct volume_output_item *vo;
for (vo = (struct volume_output_item *)schedule_next(
wrld->volume_output_scheduler);
vo != NULL || not_yet >= wrld->volume_output_scheduler->now;
vo = (struct volume_output_item *)schedule_next(
wrld->volume_output_scheduler)) {
if (vo == NULL)
continue;
if (update_volume_output(wrld, vo))
mcell_error("Failed to update volume output.");
}
}
/***********************************************************************
process_reaction_output:
Produce this round's reaction output, if any.
In: wrld: the world
not_yet: earliest time which should not yet be output
Out: none. reaction output data structs/files are updated as appropriate.
***********************************************************************/
static void process_reaction_output(struct volume *wrld, double not_yet) {
struct output_block *obp;
for (obp = (struct output_block *)schedule_next(wrld->count_scheduler);
obp != NULL || not_yet >= wrld->count_scheduler->now;
obp = (struct output_block *)schedule_next(wrld->count_scheduler)) {
if (obp == NULL)
continue;
//nfsim observables update
if(wrld->nfsim_flag)
logNFSimObservables_c(wrld->current_iterations * wrld->time_unit, wrld->seed_seq);
if (update_reaction_output(wrld, obp))
mcell_error("Failed to update reaction output.");
}
if (wrld->count_scheduler->error)
mcell_internal_error("Scheduler reported an out-of-memory error while "
"retrieving next scheduled reaction output, but this "
"should never happen.");
}
#ifdef MCELL3_RELEASE_ACCORDING_TO_EVENT_TIME
#include <vector>
#include <algorithm>
static bool less_release_time(release_event_queue* r1, release_event_queue* r2) {
return r1->event_time < r2->event_time;
}
#endif
/***********************************************************************
process_molecule_releases:
Produce this round's release events, if any.
In: wrld: the world
not_yet: earliest time which should not yet be processed
Out: none. molecules are released into the world.
***********************************************************************/
void process_molecule_releases(struct volume *wrld, double not_yet) {
#ifdef MCELL3_RELEASE_ACCORDING_TO_EVENT_TIME
std::vector<release_event_queue *> releases;
#endif
for (struct release_event_queue *req = (struct release_event_queue *)schedule_next(wrld->releaser);
req != NULL || not_yet >= wrld->releaser->now;
req = (struct release_event_queue *)schedule_next(wrld->releaser)) {
if (req == NULL ||
!distinguishable(req->release_site->release_prob, MAGIC_PATTERN_PROBABILITY, EPS_C))
continue;
#ifndef MCELL3_RELEASE_ACCORDING_TO_EVENT_TIME
if (release_molecules(wrld, req))
mcell_error("Failed to release molecules of type '%s'.",
req->release_site->mol_type->sym->name);
#else
releases.push_back(req);
#endif
}
#ifdef MCELL3_RELEASE_ACCORDING_TO_EVENT_TIME
std::sort(releases.begin(), releases.end(), less_release_time);
for (release_event_queue* req: releases) {
if (release_molecules(wrld, req)) {
mcell_error("Failed to release molecules of type '%s'.",
req->release_site->mol_type->sym->name);
}
}
#endif
if (wrld->releaser->error)
mcell_internal_error("Scheduler reported an out-of-memory error while "
"retrieving next scheduled release event, but this "
"should never happen.");
}
/***********************************************************************
process_geometry_changes:
Produce this round's geometry changes, if any.
In: state: MCell state
not_yet: earliest time which should not yet be processed
Out: Nothing. Save molecules (with their positions, etc), trash the old
geometry, initialize new geometry, place all the molecules (moving them
if necessary to keep them in/out of the appropriate compartments).
***********************************************************************/
void process_geometry_changes(struct volume *state, double not_yet) {
for (struct dg_time_filename *dg_time_fname = (struct dg_time_filename *)schedule_next(
state->dynamic_geometry_scheduler);
dg_time_fname != NULL || not_yet >= state->dynamic_geometry_scheduler->now;
dg_time_fname = (struct dg_time_filename *)schedule_next(state->dynamic_geometry_scheduler)) {
if (dg_time_fname == NULL)
continue;
update_geometry(state, dg_time_fname);
}
if (state->dynamic_geometry_scheduler->error)
mcell_internal_error("Scheduler reported an out-of-memory error while "
"retrieving next scheduled geometry change, but this "
"should never happen.");
}
/***********************************************************************
make_checkpoint:
Produce a checkpoint file.
In: struct volume *wrld - the world
Out: 0 on success, 1 on failure.
On success, checkpoint file is created.
On failure, old checkpoint file, if any, is left intact.
***********************************************************************/
static int make_checkpoint(struct volume *wrld) {
/* Make sure we have a filename */
if (wrld->chkpt_outfile == NULL)
wrld->chkpt_outfile = CHECKED_SPRINTF("checkpt.%d", getpid());
/* Print a useful status message */
switch (wrld->checkpoint_requested) {
case CHKPT_ITERATIONS_CONT:
case CHKPT_ALARM_CONT:
if (wrld->notify->checkpoint_report != NOTIFY_NONE)
mcell_log("MCell: time = %lld, writing to checkpoint file %s (periodic).",
wrld->current_iterations, wrld->chkpt_outfile);
break;
case CHKPT_ALARM_EXIT:
if (wrld->notify->checkpoint_report != NOTIFY_NONE)
mcell_log("MCell: time = %lld, writing to checkpoint file %s (time limit "
"elapsed).",
wrld->current_iterations, wrld->chkpt_outfile);
break;
case CHKPT_SIGNAL_CONT:
case CHKPT_SIGNAL_EXIT:
if (wrld->notify->checkpoint_report != NOTIFY_NONE)
mcell_log("MCell: time = %lld, writing to checkpoint file %s (user "
"signal detected).",
wrld->current_iterations, wrld->chkpt_outfile);
break;
case CHKPT_ITERATIONS_EXIT:
if (wrld->notify->checkpoint_report != NOTIFY_NONE)
mcell_log("MCell: time = %lld, writing to checkpoint file %s.",
wrld->current_iterations, wrld->chkpt_outfile);
break;
default:
wrld->checkpoint_requested = CHKPT_NOT_REQUESTED;
return 0;
}
/* Make the checkpoint */
create_chkpt(wrld, wrld->chkpt_outfile);
wrld->last_checkpoint_iteration = wrld->current_iterations;
/* Break out of the loop, if appropriate */
if (wrld->checkpoint_requested == CHKPT_ALARM_EXIT ||
wrld->checkpoint_requested == CHKPT_SIGNAL_EXIT ||
wrld->checkpoint_requested == CHKPT_ITERATIONS_EXIT)
return 1;
/* Schedule the next checkpoint, if appropriate */
if (wrld->checkpoint_requested == CHKPT_ALARM_CONT) {
if (wrld->continue_after_checkpoint)
alarm(wrld->checkpoint_alarm_time);
else
return 1;
}
wrld->checkpoint_requested = CHKPT_NOT_REQUESTED;
return 0;
}
static double find_next_viz_output_frame(struct frame_data_list *fdl) {
double next_time = DBL_MAX;
for (; fdl != NULL; fdl = fdl->next) {
if (fdl->curr_viz_iteration == NULL)
continue;
if (fdl->viz_iteration < next_time)
next_time = fdl->viz_iteration;
}
return next_time;
}
static double find_next_viz_output(struct viz_output_block *vizblk) {
double next_time = DBL_MAX;
while (vizblk != NULL) {
double this_time = find_next_viz_output_frame(vizblk->frame_data_head);
if (this_time < next_time)
next_time = this_time;
vizblk = vizblk->next;
}
return next_time;
}
static int print_molecule_collision_report(
enum notify_level_t molecule_collision_report,
long long vol_vol_colls,
long long vol_surf_colls,
long long surf_surf_colls,
long long vol_wall_colls,
long long vol_vol_vol_colls,
long long vol_vol_surf_colls,
long long vol_surf_surf_colls,
long long surf_surf_surf_colls,
struct reaction_flags *rxn_flags) {
if (molecule_collision_report == NOTIFY_FULL) {
mcell_log_raw("\n");
mcell_log("\tCounts of Reaction Triggered Molecule Collisions");
mcell_log("(VM = volume molecule, SM = surface molecule, W = wall)");
if (rxn_flags->vol_vol_reaction_flag) {
mcell_log("Total number of VM-VM collisions: %lld", vol_vol_colls);
}
if (rxn_flags->vol_surf_reaction_flag) {
mcell_log("Total number of VM-SM collisions: %lld", vol_surf_colls);
}
if (rxn_flags->surf_surf_reaction_flag) {
mcell_log("Total number of SM-SM collisions: %lld", surf_surf_colls);
}
if (rxn_flags->vol_wall_reaction_flag) {
mcell_log("Total number of VM-W collisions: %lld", vol_wall_colls);
}
if (rxn_flags->vol_vol_vol_reaction_flag) {
mcell_log("Total number of VM-VM-VM collisions: %lld", vol_vol_vol_colls);
}
if (rxn_flags->vol_vol_surf_reaction_flag) {
mcell_log("Total number of VM-VM-SM collisions: %lld",
vol_vol_surf_colls);
}
if (rxn_flags->vol_surf_surf_reaction_flag) {
mcell_log("Total number of VM-SM-SM collisions: %lld",
vol_surf_surf_colls);
}
if (rxn_flags->surf_surf_surf_reaction_flag) {
mcell_log("Total number of SM-SM-SM collisions: %lld",
surf_surf_surf_colls);
}
mcell_log_raw("\n");
}
return 0;
}
/***********************************************************************
run_sim:
Simulation main loop.
In: pointer to simulation state
Out: None
***********************************************************************/
MCELL_STATUS
mcell_run_simulation(MCELL_STATE *world) {
if (world->dump_level > 0) {
fprintf ( stdout, "\n\nIn mcell_run_simulation: dump_level = %ld\n\n", world->dump_level );
}
if (world->notify->progress_report != NOTIFY_NONE)
mcell_log("Running simulation.");
/* If we're reloading a checkpoint, we want to skip all of the processing
* which happened on the last iteration before checkpointing. To do this, we
* skip the first part of run_timestep.
*/
int restarted_from_checkpoint = 0;
if (world->start_iterations != 0) {
assert(world->current_iterations - world->start_iterations == 0.0);
restarted_from_checkpoint = 1;
}
long long frequency = mcell_determine_output_frequency(world);
int status = 0;
world->it1_time_set = 0;
while (world->current_iterations <= world->iterations) {
if (world->current_iterations == 1) {
// for a better comparison, we are also reporting when 1st iteration
// started
struct rusage it1_time;
getrusage(RUSAGE_SELF, &it1_time);
world->u_it1_time.tv_sec = it1_time.ru_utime.tv_sec;
world->u_it1_time.tv_usec = it1_time.ru_utime.tv_usec;
world->s_it1_time.tv_sec = it1_time.ru_stime.tv_sec;
world->s_it1_time.tv_usec = it1_time.ru_stime.tv_usec;
world->it1_time_set = 1;
}
// XXX: A return status of 1 from mcell_run_iterations does not
// indicate an error but is used to break out of the loop.
// This behavior is non-conformant and should be changed.
if (mcell_run_iteration(world, frequency, &restarted_from_checkpoint) ==
1) {
break;
}
}
if (mcell_flush_data(world)) {
mcell_error_nodie("Failed to flush reaction and visualization data.");
status = 1;
}
if (mcell_print_final_warnings(world)) {
mcell_error_nodie("Failed to print final warnings.");
status = 1;
}
if (mcell_print_final_statistics(world)) {
mcell_error_nodie("Failed to print final statistics.");
status = 1;
}
if(world->nfsim_flag){
char buffer[1000];
memset(buffer, 0, 1000*sizeof(char));
sprintf(buffer, "mdlr_%d.gdat", world->seed_seq);
//outputNFSimObservablesF_c(buffer);
outputNFSimObservables_c(world->seed_seq);
deleteNFSimSystem_c();
}
return status;
}
/**************************************************************************
*
* Run multiple iterations at once
*
*************************************************************************/
MCELL_STATUS
mcell_run_n_iterations(MCELL_STATE *world, long long frequency,
int *restarted_from_checkpoint, int n_iter) {
int i_iter = 0;
while (i_iter < n_iter) {
// XXX: A return status of 1 from mcell_run_iterations does not
// indicate an error but is used to break out of the loop.
// This behavior is non-conformant and should be changed.
if (mcell_run_iteration(world, frequency, restarted_from_checkpoint) == 1) {
break;
}
i_iter += 1;
}
return 0;
}
/**************************************************************************
*
* this function runs a single mcell iteration
*
* parameters:
* frequency : the requested output frequency
* restart_from_checkpoint : does this iteration follow a checkpoint
*
*************************************************************************/
MCELL_STATUS
mcell_run_iteration(MCELL_STATE *world, long long frequency,
int *restarted_from_checkpoint) {
emergency_output_hook_enabled = 1;
long long iter_report_phase = world->current_iterations % frequency;
double not_yet = world->current_iterations + 1.0;
if (world->current_iterations != 0)
world->elapsed_time = world->current_iterations;
else
world->elapsed_time = 1.0;
if (!*restarted_from_checkpoint) {
/* Change geometry if needed */
process_geometry_changes(world, not_yet);
/* Release molecules */
process_molecule_releases(world, not_yet);
/* Produce output */
process_reaction_output(world, not_yet);
process_volume_output(world, not_yet);
for (struct viz_output_block *vizblk = world->viz_blocks; vizblk != NULL;
vizblk = vizblk->next) {
if (vizblk->frame_data_head && update_frame_data_list(world, vizblk))
mcell_error("Unknown error while updating frame data list.");
}
/* Produce iteration report */
if (iter_report_phase == 0 &&
world->notify->iteration_report != NOTIFY_NONE) {
mcell_log_raw("Iterations: %lld of %lld ", world->current_iterations,
world->iterations);
if (world->notify->throughput_report != NOTIFY_NONE) {
struct timeval cur_time;
gettimeofday(&cur_time, NULL);
if (world->last_timing_time.tv_sec > 0) {
double time_diff =
(double)(cur_time.tv_sec - world->last_timing_time.tv_sec) *
1000000.0 +
(double)(cur_time.tv_usec - world->last_timing_time.tv_usec);
time_diff /= (double)(world->current_iterations - world->last_timing_iteration);
mcell_log_raw(" (%.6lg iter/sec)", 1000000.0 / time_diff);
world->last_timing_iteration = world->current_iterations;
world->last_timing_time = cur_time;
} else {
world->last_timing_iteration = world->current_iterations;
world->last_timing_time = cur_time;
}
}
if (world->nfsim_flag){
mcell_log_raw(" | NFSim info: [");
mcell_log_raw(" Species: %d ",world->n_NFSimSpecies);
mcell_log_raw(" Reactions triggered: %d", world->n_NFSimReactions);
mcell_log_raw(" Total Reactions: %d", world->n_NFSimPReactions);
mcell_log_raw("]");
}
mcell_log_raw("\n");
}
/* Check for a checkpoint on this iteration */
if (world->chkpt_iterations && world->current_iterations != world->start_iterations &&
((world->current_iterations - world->start_iterations) % world->chkpt_iterations == 0)) {
if (world->continue_after_checkpoint) {
world->checkpoint_requested = CHKPT_ITERATIONS_CONT;
} else {
world->checkpoint_requested = CHKPT_ITERATIONS_EXIT;
}
}
/* No checkpoint signalled. Keep going. */
if (world->checkpoint_requested != CHKPT_NOT_REQUESTED) {
// This won't work with (non-trad) PBCs until we start saving the
// molecules' periodic box in the checkpoint file. In principle, it
// should probably work with the traditional form, but I'm disabling it
// here to be safe.
if (world->periodic_box_obj) {
mcell_error(
"periodic boundary conditions do not currently work with "
"checkpointing.");
}
/* Make a checkpoint, exiting the loop if necessary */
if (make_checkpoint(world))
return 1;
}
/* Even if no checkpoint, the last iteration is a half-iteration. */
if (world->current_iterations >= world->iterations)
return 1;
}
// reset this flag to zero
*restarted_from_checkpoint = 0;
run_clamp(world, world->current_iterations);
double next_release_time;
if (!schedule_anticipate(world->releaser, &next_release_time))
next_release_time = world->iterations + 1;
if (next_release_time < world->current_iterations + 1)
next_release_time = world->current_iterations + 1;
double next_vol_output;
if (!schedule_anticipate(world->volume_output_scheduler, &next_vol_output))
next_vol_output = world->iterations + 1;
double next_viz_output = find_next_viz_output(world->viz_blocks);
double next_barrier =
min3d(next_release_time, next_vol_output, next_viz_output);
#ifdef MCELL3_NEXT_BARRIER_IS_THE_NEXT_TIMESTEP
next_barrier = not_yet; // == iterations + 1
#endif
while (world->storage_head != NULL &&
world->storage_head->store->current_time <= not_yet) {
int done = 0;
while (!done) {
done = 1;
for (struct storage_list *local = world->storage_head; local != NULL;
local = local->next) {
if (local->store->timer->current != NULL) {
run_timestep(world, local->store, next_barrier,
(double)world->iterations + 1.0);
done = 0;
}
}
}
for (struct storage_list *local = world->storage_head; local != NULL;
local = local->next) {
/* Not using the return value -- just trying to advance the scheduler */
void *o = schedule_next(local->store->timer);
if (o != NULL)
mcell_internal_error("Scheduler dropped a molecule on the floor!");
local->store->current_time += 1.0;
}
}
world->current_iterations++;
return 0;
}
/**************************************************************************
*
* This function returns the output frequency.
*
* The returned value is either the one requested in the mdl file or
* is determined via a heuristic.
*
**************************************************************************/
long long mcell_determine_output_frequency(MCELL_STATE *world) {
long long frequency;
if (world->notify->custom_iteration_value != 0) {
frequency = world->notify->custom_iteration_value;
} else {
if (world->iterations < 10)
frequency = 1;
else if (world->iterations < 1000)
frequency = 10;
else if (world->iterations < 100000)
frequency = 100;
else if (world->iterations < 10000000)
frequency = 1000;
else if (world->iterations < 1000000000)
frequency = 10000;
else
frequency = 100000;
}
return frequency;
}
/************************************************************************
*
* function responsible for flushing any remaining reaction
* and viz data output to disk. Also sets a final simulation checkpoint
* if necessary.
*
***********************************************************************/
MCELL_STATUS
mcell_flush_data(MCELL_STATE *world) {
int status = 0;
if (world->chkpt_iterations &&
world->current_iterations > world->last_checkpoint_iteration) {
status = make_checkpoint(world);
}
emergency_output_hook_enabled = 0;
int num_errors = flush_reaction_output(world);
if (num_errors != 0) {
mcell_warn("%d errors occurred while flushing buffered reaction output.\n"
" Simulation complete anyway--continuing as normal.",
num_errors);
status = 1;
}
if (world->notify->progress_report != NOTIFY_NONE)
mcell_log("Exiting run loop.");
int warned = 0;
for (struct viz_output_block *vizblk = world->viz_blocks; vizblk != NULL;
vizblk = vizblk->next) {
if (finalize_viz_output(world, vizblk) && !warned) {
mcell_warn("VIZ output was not successfully finalized.\n"
" Visualization of results may not work correctly.");
warned = 1;
status = 1;
}
}
return status;
}
/***********************************************************************
*
* function printing final simulation warning about missed reactions,
* high reaction probabilities, etc.
*
***********************************************************************/
MCELL_STATUS
mcell_print_final_warnings(MCELL_STATE *world) {
int first_report = 1;
if (world->notify->missed_reactions != WARN_COPE) {
for (int i = 0; i < world->rx_hashsize; i++) {
for (struct rxn *rxp = world->reaction_hash[i]; rxp != NULL;
rxp = rxp->next) {
int do_not_print = 0;
/* skip printing messages if one of the reactants is a surface */
for (unsigned int j = 0; j < rxp->n_reactants; j++) {
if ((rxp->players[j]->flags & IS_SURFACE) != 0)
do_not_print = 1;
}
if (do_not_print == 1)
continue;
if (rxp->n_occurred * world->notify->missed_reaction_value <
rxp->n_skipped) {
if (first_report) {
mcell_log("Warning: Some reactions were missed because reaction "
"probability exceeded 1.");
first_report = 0;
}
mcell_log_raw(" ");
for (unsigned int j = 0; j < rxp->n_reactants; j++) {
mcell_log_raw("%s%s[%d]", j ? " + " : "",
rxp->players[j]->sym->name, rxp->geometries[j]);
}
mcell_log_raw(" -- %g%% of reactions missed.\n",
0.001 * round(1000 * rxp->n_skipped * 100 /
(rxp->n_skipped + rxp->n_occurred)));
}
}
}
if (!first_report)
mcell_log_raw("\n");
}
first_report += 1;
if (world->notify->short_lifetime != WARN_COPE) {
for (int i = 0; i < world->n_species; i++) {
if (world->species_list[i] == world->all_mols)
continue;
if ((world->species_list[i] == world->all_volume_mols) ||
(world->species_list[i] == world->all_surface_mols))
continue;
if (world->species_list[i]->n_deceased <= 0)
continue;
double mean_lifetime_seconds = world->species_list[i]->cum_lifetime_seconds /
world->species_list[i]->n_deceased;
double short_lifetime_seconds = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, world->notify->short_lifetime_value);
double mean_lifetime_timesteps = mean_lifetime_seconds/world->time_unit;
if (mean_lifetime_seconds < short_lifetime_seconds) {
if (first_report) {
if (first_report > 1)
mcell_log_raw("\n");
mcell_log("Warning: Some molecules had a lifetime short relative to "
"the timestep.");
first_report = 0;
}
mcell_log(" Mean lifetime of %s was %g timesteps.",
world->species_list[i]->sym->name, mean_lifetime_timesteps);
}
}
if (!first_report)
mcell_log_raw("\n");
}
return 0;
}
/***********************************************************************
*
* function printing final simulation statistics and timings
*
***********************************************************************/
MCELL_STATUS
mcell_print_final_statistics(MCELL_STATE *world) {
if (world->reaction_prob_limit_flag)
mcell_warn("during the simulation some reaction probabilities were greater "
"than 1. You may want to rerun the simulation with the WARNINGS "
"block enabled to get more detail.\n");
if (world->notify->final_summary == NOTIFY_FULL) {
mcell_log("iterations = %lld ; elapsed time = %1.15g seconds",
world->current_iterations,
world->chkpt_start_time_seconds +
((world->current_iterations - world->start_iterations) * world->time_unit));
if (world->diffusion_number > 0)
mcell_log("Average diffusion jump was %.2f timesteps (%.2f/%lld)\n",
world->diffusion_cumtime / (double)world->diffusion_number,
world->diffusion_cumtime, world->diffusion_number
);
mcell_log("Total number of random number use: %lld", rng_uses(world->rng));
mcell_log("Total number of ray-subvolume intersection tests: %lld",
world->ray_voxel_tests);
mcell_log("Total number of ray-polygon intersection tests: %lld",
world->ray_polygon_tests);
mcell_log("Total number of ray-polygon intersections: %lld",
world->ray_polygon_colls);
mcell_log("Total number of dynamic geometry molecule displacements: %lld",
world->dyngeom_molec_displacements);
mcell_log("Total number of diffuse 3d calls: %lld", world->diffuse_3d_calls);;
print_molecule_collision_report(
world->notify->molecule_collision_report,
world->vol_vol_colls,
world->vol_surf_colls,
world->surf_surf_colls,
world->vol_wall_colls,
world->vol_vol_vol_colls,
world->vol_vol_surf_colls,
world->vol_surf_surf_colls,
world->surf_surf_surf_colls,
&world->rxn_flags);
struct rusage run_time;
time_t t_end; /* global end time of MCell run */
double u_init_time,
s_init_time; /* initialization time (user) and (system) */
double u_run_time, s_run_time; /* run time (user) and (system) */
u_init_time = world->u_init_time.tv_sec +
(world->u_init_time.tv_usec / MAX_TARGET_TIMESTEP);
s_init_time = world->s_init_time.tv_sec +
(world->s_init_time.tv_usec / MAX_TARGET_TIMESTEP);
mcell_log("Initialization CPU time = %f (user) and %f (system)",
u_init_time, s_init_time);
getrusage(RUSAGE_SELF, &run_time);
u_run_time = run_time.ru_utime.tv_sec +
(run_time.ru_utime.tv_usec / MAX_TARGET_TIMESTEP);
s_run_time = run_time.ru_stime.tv_sec +
(run_time.ru_stime.tv_usec / MAX_TARGET_TIMESTEP);
mcell_log("Simulation CPU time = %f (user) and %f (system)",
u_run_time - u_init_time, s_run_time - s_init_time);
if (world->it1_time_set) {
double u_it1_time = world->u_it1_time.tv_sec +
(world->u_it1_time.tv_usec / MAX_TARGET_TIMESTEP);
double s_it1_time = world->s_it1_time.tv_sec +
(world->s_it1_time.tv_usec / MAX_TARGET_TIMESTEP);
mcell_log("Simulation CPU time without iteration 0 = %f (user) and %f (system)",
u_run_time - u_it1_time, s_run_time - s_it1_time);
}
t_end = time(NULL);
mcell_log("Total wall clock time = %ld seconds",
(long)difftime(t_end, world->t_start));
}
return 0;
}
| C |
3D | mcellteam/mcell | src/mcell_surfclass.c | .c | 6,043 | 179 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <string.h>
#include <stdlib.h>
#include "config.h"
#include "logging.h"
#include "sym_table.h"
#include "mcell_species.h"
#include "init.h"
#include "mcell_init.h"
#include "mcell_structs.h"
#include "mcell_reactions.h"
#include "mcell_surfclass.h"
static int check_valid_molecule_release(
MCELL_STATE *state, struct mcell_species *mol_type);
/**************************************************************************
mcell_add_surf_class_properties:
Add a property to a surface class
In: state: the simulation state
reaction_type: RFLCT, TRANSP, or SINK
sc_sym: symbol for surface class
reactant_sym: symbol for reactant molecule
orient: orientation for molecule
Out: 0 on success, 1 on failure.
**************************************************************************/
MCELL_STATUS mcell_add_surf_class_properties(
MCELL_STATE *state, int reaction_type, mcell_symbol *sc_sym,
mcell_symbol *reactant_sym, short orient) {
struct species *surf_class = (struct species *)sc_sym->value;
if (mcell_add_surface_reaction(state->rxn_sym_table, reaction_type,
surf_class, reactant_sym, orient)) {
return MCELL_FAIL;
}
return MCELL_SUCCESS;
}
/**************************************************************************
mcell_create_surf_class:
Start a surface class declaration.
In: state: the simulation state
surf_class_name: the surface class name
sc_sym: surface class symbol
Out: 0 on success, 1 on failure. The surface class is created
**************************************************************************/
MCELL_STATUS mcell_create_surf_class(
MCELL_STATE *state, const char *surf_class_name, mcell_symbol **sc_sym) {
struct sym_entry *sym = NULL;
int error_code = new_mol_species(state, surf_class_name, &sym);
if (error_code) {
return error_code;
}
struct species *surf_class = (struct species *)sym->value;
surf_class->flags = IS_SURFACE;
surf_class->refl_mols = NULL;
surf_class->transp_mols = NULL;
surf_class->absorb_mols = NULL;
surf_class->clamp_mols = NULL;
if (sc_sym != NULL) {
*sc_sym = sym;
}
return MCELL_SUCCESS;
}
/**************************************************************************
mcell_add_mol_release_to_surf_class:
Create a surface class "property" to release molecules. The surface class
still needs to be assigned to a region. Multiple properties can be added to
a single surface class.
In: state: the simulation state
sc_sym: surface class symbol
sm_info: info about the surface molecule to be released
quantity: the amount of surface molecules to release
density_or_num: 0 if density, 1 if number
smd_list:
Out: The surface molecule data
**************************************************************************/
struct sm_dat *mcell_add_mol_release_to_surf_class(
MCELL_STATE *state, struct sym_entry *sc_sym, struct mcell_species *sm_info,
double quantity, int density_or_num, struct sm_dat *smd_list) {
struct species *species_ptr = (struct species *)sm_info->mol_type->value;
if (!(species_ptr->flags & ON_GRID)) {
return NULL;
} else if (check_valid_molecule_release(state, sm_info)) {
return NULL;
}
struct sm_dat *sm_dat_ptr = CHECKED_MALLOC_STRUCT(
struct sm_dat, "surface molecule data");
if (sm_dat_ptr == NULL) {
return NULL;
}
sm_dat_ptr->next = smd_list;
sm_dat_ptr->sm = species_ptr;
sm_dat_ptr->quantity_type = density_or_num;
sm_dat_ptr->quantity = quantity;
sm_dat_ptr->orientation = sm_info->orient;
struct species *sc = (struct species *)sc_sym->value;
sc->sm_dat_head = sm_dat_ptr;
return sm_dat_ptr;
}
/**************************************************************************
check_valid_molecule_release:
Check that a particular molecule type is valid for inclusion in a release
site. Checks that orientations are present if required, and absent if
forbidden, and that we aren't trying to release a surface class.
In: state: the simulation state
mol_type: molecule species and (optional) orientation for release
Out: 0 on success, 1 on failure
**************************************************************************/
static int check_valid_molecule_release(MCELL_STATE *state,
struct mcell_species *mol_type) {
struct species *mol = (struct species *)mol_type->mol_type->value;
if (mol->flags & ON_GRID) {
if (!mol_type->orient_set) {
if (state->notify->missed_surf_orient == WARN_ERROR) {
return 1;
}
}
} else if ((mol->flags & NOT_FREE) == 0) {
if (mol_type->orient_set) {
if (state->notify->useless_vol_orient == WARN_ERROR) {
return 1;
}
}
} else {
return 1;
}
return 0;
}
/**************************************************************************
mcell_assign_surf_class_to_region:
Assign a surface class to a region
In: sg_name: the name of the surface class to be assigned
rgn: the region which will have the surface class assigned to it
Out: 0 on success, 1 on failure. Surface class is assigned
**************************************************************************/
MCELL_STATUS mcell_assign_surf_class_to_region(
struct sym_entry *sc_sym, struct region *rgn) {
if (rgn->surf_class != NULL)
return MCELL_FAIL;
rgn->surf_class = (struct species *)sc_sym->value;
return MCELL_SUCCESS;
}
| C |
3D | mcellteam/mcell | src/grid_util.c | .c | 112,822 | 3,068 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/**************************************************************************\
** File: grid_util.c **
** **
** Purpose: Translates between 3D world coordinates and surface grid index**
** **
** Testing status: partially tested (validate_grid_util.c). **
\**************************************************************************/
#include "config.h"
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include "logging.h"
#include "rng.h"
#include "grid_util.h"
#include "vol_util.h"
#include "wall_util.h"
#include "react.h"
#include "init.h"
#include "debug_config.h"
#include "dump_state.h"
/*************************************************************************
xyz2uv and uv2xyz:
In: 2D and 3D vectors and a wall
Out: first vector is converted to 2nd vector
WARNING: no error checking--point assumed to be valid!
*************************************************************************/
void xyz2uv(struct vector3 *a, struct wall *w, struct vector2 *b) {
if (w->grid) {
b->u = a->x * w->unit_u.x + a->y * w->unit_u.y + a->z * w->unit_u.z -
w->grid->vert0.u;
b->v = a->x * w->unit_v.x + a->y * w->unit_v.y + a->z * w->unit_v.z -
w->grid->vert0.v;
} else {
struct vector3 p;
p.x = a->x - w->vert[0]->x;
p.y = a->y - w->vert[0]->y;
p.z = a->z - w->vert[0]->z;
b->u = p.x * w->unit_u.x + p.y * w->unit_u.y + p.z * w->unit_u.z;
b->v = p.x * w->unit_v.x + p.y * w->unit_v.y + p.z * w->unit_v.z;
}
}
void uv2xyz(struct vector2 *a, struct wall *w, struct vector3 *b) {
b->x = a->u * w->unit_u.x + a->v * w->unit_v.x + w->vert[0]->x;
b->y = a->u * w->unit_u.y + a->v * w->unit_v.y + w->vert[0]->y;
b->z = a->u * w->unit_u.z + a->v * w->unit_v.z + w->vert[0]->z;
}
/*************************************************************************
xyz2grid and uv2grid:
In: a vector and a surface grid
Out: int containing the index on the grid of that vector
Note: xyz2grid just does a dot-product to uv coordinates first.
Error checking for a valid point is done.
*************************************************************************/
int xyz2grid(struct vector3 *v, struct surface_grid *g) {
struct vector3 *unit_u = &(g->surface->unit_u);
struct vector3 *unit_v = &(g->surface->unit_v);
double i, j;
double u0, u1_u0;
double striploc, striprem, stripeloc, striperem;
int strip, stripe, flip, idx;
int tile_idx_0, tile_idx_mid, tile_idx_last;
if (g->n_tiles == 1)
return 0;
/* find tile indices of the corner tiles */
tile_idx_0 = 0;
/* see function "move_strip_up()" */
tile_idx_mid = g->n_tiles - 2 * (g->n) + 1;
tile_idx_last = g->n_tiles - 1;
if (!(distinguishable_vec3(v, g->surface->vert[0], EPS_C)))
return tile_idx_mid;
if (!(distinguishable_vec3(v, g->surface->vert[1], EPS_C)))
return tile_idx_last;
if (!(distinguishable_vec3(v, g->surface->vert[2], EPS_C)))
return tile_idx_0;
if (!(point_in_triangle(v, g->surface->vert[0], g->surface->vert[1],
g->surface->vert[2]))) {
mcell_internal_error(
"Error in function 'xyz2grid()': point is outside wall.");
}
i = v->x * unit_u->x + v->y * unit_u->y + v->z * unit_u->z - g->vert0.u;
j = v->x * unit_v->x + v->y * unit_v->y + v->z * unit_v->z - g->vert0.v;
striploc = j * g->inv_strip_wid;
strip = (int)striploc;
striprem = striploc - strip;
strip = g->n - strip - 1;
u0 = j * g->vert2_slope;
u1_u0 = g->surface->uv_vert1_u - j * g->fullslope;
stripeloc = ((i - u0) / u1_u0) * (((double)strip) + (1.0 - striprem));
stripe = (int)(stripeloc);
striperem = stripeloc - stripe;
flip = (striperem < 1.0 - striprem) ? 0 : 1;
idx = strip * strip + 2 * stripe + flip;
if ((u_int)idx >= g->n_tiles) {
mcell_internal_error("Error in function 'xyz2grid()': returning tile index "
"%d while wall has %u tiles",
idx, g->n_tiles);
}
return idx;
}
int uv2grid(struct vector2 *v, struct surface_grid *g) {
double i, j;
double u0, u1_u0;
double striploc, striprem, stripeloc, striperem;
int strip, stripe, flip, idx;
struct vector2 vert_0, vert_1;
int tile_idx_0, tile_idx_mid, tile_idx_last;
if (g->n_tiles == 1)
return 0;
/* find tile indices of the corner tiles */
tile_idx_0 = 0;
/* see function "move_strip_up()" */
tile_idx_mid = g->n_tiles - 2 * (g->n) + 1;
tile_idx_last = g->n_tiles - 1;
vert_0.u = vert_0.v = 0;
vert_1.u = g->surface->uv_vert1_u;
vert_1.v = 0;
if (!distinguishable_vec2(v, &vert_0, EPS_C))
return tile_idx_mid;
if (!distinguishable_vec2(v, &vert_1, EPS_C))
return tile_idx_0;
if (!distinguishable_vec2(v, &g->surface->uv_vert2, EPS_C))
return tile_idx_last;
if (!(point_in_triangle_2D(v, &vert_0, &vert_1, &g->surface->uv_vert2))) {
mcell_internal_error(
"Error in function 'uv2grid()': point is outside wall.");
}
i = v->u;
j = v->v;
striploc = j * g->inv_strip_wid;
strip = (int)striploc;
striprem = striploc - strip;
strip = g->n - strip - 1;
u0 = j * g->vert2_slope;
u1_u0 = g->surface->uv_vert1_u - j * g->fullslope;
stripeloc = ((i - u0) / u1_u0) * (((double)strip) + (1.0 - striprem));
stripe = (int)(stripeloc);
striperem = stripeloc - stripe;
flip = (striperem < 1.0 - striprem) ? 0 : 1;
idx = strip * strip + 2 * stripe + flip;
if ((u_int)idx >= g->n_tiles) {
mcell_internal_error("Error in function 'xyz2grid()': returning tile index "
"%d while wall has %u tiles",
idx, g->n_tiles);
}
return idx;
}
/*************************************************************************
grid2xyz and grid2uv and grid2uv_random
In: a surface grid
index of a tile on that grid
vector to store the results
Out: vector contains the coordinates of the center of that tile, or
a random coordinate within that tile.
WARNING: no error checking--index assumed to be valid!
Note: grid2xyz just multiplies by uv unit vectors at the end.
*************************************************************************/
void grid2xyz(struct surface_grid *g, int idx, struct vector3 *v) {
struct vector3 *unit_u = &(g->surface->unit_u);
struct vector3 *unit_v = &(g->surface->unit_v);
int root;
int rootrem;
int k, j, i;
double ucoef, vcoef, over3n;
root = (int)(sqrt((double)idx));
rootrem = idx - root * root;
k = g->n - root - 1;
j = rootrem / 2;
i = rootrem - 2 * j;
over3n = 1.0 / (double)(3 * g->n);
ucoef = ((double)(3 * j + i + 1)) * over3n * g->surface->uv_vert1_u +
((double)(3 * k + i + 1)) * over3n * g->surface->uv_vert2.u;
vcoef = ((double)(3 * k + i + 1)) * over3n * g->surface->uv_vert2.v;
v->x = ucoef * unit_u->x + vcoef * unit_v->x + g->surface->vert[0]->x;
v->y = ucoef * unit_u->y + vcoef * unit_v->y + g->surface->vert[0]->y;
v->z = ucoef * unit_u->z + vcoef * unit_v->z + g->surface->vert[0]->z;
}
void grid2uv(struct surface_grid *g, int idx, struct vector2 *v) {
int root;
int rootrem;
int k, j, i;
double over3n;
root = (int)(sqrt((double)idx));
rootrem = idx - root * root;
k = g->n - root - 1;
j = rootrem / 2;
i = rootrem - 2 * j;
over3n = 1.0 / (double)(3 * g->n);
v->u = ((double)(3 * j + i + 1)) * over3n * g->surface->uv_vert1_u +
((double)(3 * k + i + 1)) * over3n * g->surface->uv_vert2.u;
v->v = ((double)(3 * k + i + 1)) * over3n * g->surface->uv_vert2.v;
}
void grid2uv_random(struct surface_grid *g, int idx, struct vector2 *v,
struct rng_state *rng) {
int root;
int rootrem;
int k, j, i;
double over_n;
double u_ran, v_ran;
root = (int)(sqrt((double)idx));
rootrem = idx - root * root;
k = g->n - root - 1;
j = rootrem / 2;
i = rootrem - 2 * j;
over_n = 1.0 / (double)(g->n);
u_ran = rng_dbl(rng);
v_ran = 1.0 - sqrt(rng_dbl(rng));
v->u =
((double)(j + i) + (1 - 2 * i) * (1.0 - v_ran) * u_ran) * over_n *
g->surface->uv_vert1_u +
((double)(k + i) + (1 - 2 * i) * v_ran) * over_n * g->surface->uv_vert2.u;
v->v =
((double)(k + i) + (1 - 2 * i) * v_ran) * over_n * g->surface->uv_vert2.v;
}
/*************************************************************************
init_grid_geometry:
In: a surface grid with correct # of divisions/edge and wall pointer
Out: all the precomputed geometry speedup values are properly set
*************************************************************************/
void init_grid_geometry(struct surface_grid *g) {
g->inv_strip_wid = 1.0 / (g->surface->uv_vert2.v / ((double)g->n));
g->vert2_slope = g->surface->uv_vert2.u / g->surface->uv_vert2.v;
g->fullslope = g->surface->uv_vert1_u / g->surface->uv_vert2.v;
g->vert0.u = g->surface->vert[0]->x * g->surface->unit_u.x +
g->surface->vert[0]->y * g->surface->unit_u.y +
g->surface->vert[0]->z * g->surface->unit_u.z;
g->vert0.v = g->surface->vert[0]->x * g->surface->unit_v.x +
g->surface->vert[0]->y * g->surface->unit_v.y +
g->surface->vert[0]->z * g->surface->unit_v.z;
g->n_tiles = g->n * g->n;
}
/*************************************************************************
create_grid:
In: a wall pointer that needs to have its grid created
a guess for the subvolume the center of the grid is in
Out: integer, 0 if grid exists or was created, 1 on memory error.
The grid is created and the wall is set to point at it.
*************************************************************************/
int create_grid(struct volume *world, struct wall *w, struct subvolume *guess) {
struct surface_grid *sg = NULL;
struct vector3 center;
if (w->grid != NULL)
return 0;
sg = (struct surface_grid *)CHECKED_MEM_GET(w->birthplace->grids,
"surface grid");
if (sg == NULL)
return 1;
center.x = 0.33333333333 * (w->vert[0]->x + w->vert[1]->x + w->vert[2]->x);
center.y = 0.33333333333 * (w->vert[0]->y + w->vert[1]->y + w->vert[2]->y);
center.z = 0.33333333333 * (w->vert[0]->z + w->vert[1]->z + w->vert[2]->z);
sg->surface = w;
sg->subvol = find_subvolume(world, ¢er, guess);
sg->n = (int)ceil(sqrt(w->area));
if (sg->n < 1)
sg->n = 1;
sg->n_tiles = sg->n * sg->n;
sg->n_occupied = 0;
sg->binding_factor = ((double)sg->n_tiles) / w->area;
init_grid_geometry(sg);
sg->sm_list = CHECKED_MALLOC_ARRAY(struct surface_molecule_list *, sg->n_tiles,
"surface grid");
for (unsigned int i = 0; i < sg->n_tiles; i++) {
sg->sm_list[i] = NULL;
}
w->grid = sg;
return 0;
}
/*************************************************************************
grid_neighbors:
In: a surface grid
an index on that grid
flag that tells whether we have to create a grid on the
neighbor wall if there is no grid there
an array[3] of pointers to be filled in with neighboring grid(s)
an array[3] of pointers to be filled in with neighboring indices
Out: no return value. The three nearest neighbors are returned,
which may be on a neighboring grid if the supplied index is
at an edge. If there is no neighbor in one of the three
directions, the neighboring grid pointer is set to NULL.
Note: the three neighbors are returned in the same order as the
edges, i.e. the 0th will be the nearest neighbor in the
direction of the 0th edge, and so on.
Note: If this code is used to find neighboring molecules,
the "create_grid_flag" should be set to zero.
In such case if a nearby wall exists but has no grid placed
on it, this function returns NULL for that grid, even though
there is space there (just no molecules).
If this code is used to find free spots, the "create_grid_flag"
should be set to 1 (or any positive value) and the function
returns newly created grid for this wall.
*************************************************************************/
void grid_neighbors(struct volume *world, struct surface_grid *grid, int idx,
int create_grid_flag, struct surface_grid **nb_grid,
int *nb_idx) {
int i, j, k, root, rootrem;
struct vector3 loc_3d;
struct vector2 near_2d;
double d;
/* Calculate strip (k), stripe (j), and flip (i) indices from idx */
root = (int)(sqrt((double)idx));
rootrem = idx - root * root;
k = root;
j = rootrem / 2;
i = rootrem - 2 * j;
/* First look "left" (towards edge 2) */
if (j > 0 || i > 0) /* all tiles except upright tiles in stripe 0 */
{
nb_grid[2] = grid;
nb_idx[2] = idx - 1;
} else /* upright tiles in stripe 0 */
{
if (grid->surface->nb_walls[2] == NULL)
nb_grid[2] = NULL;
else if ((grid->surface->nb_walls[2]->grid == NULL) && (!create_grid_flag))
nb_grid[2] = NULL;
else {
if ((grid->surface->nb_walls[2]->grid == NULL) && create_grid_flag) {
if (create_grid(world, grid->surface->nb_walls[2], NULL))
mcell_allocfailed("Failed to create grid for wall.");
}
if (grid->sm_list[idx]->sm != NULL)
uv2xyz(&grid->sm_list[idx]->sm->s_pos, grid->surface, &loc_3d);
else
grid2xyz(grid, idx, &loc_3d);
d = closest_interior_point(&loc_3d, grid->surface->nb_walls[2], &near_2d,
GIGANTIC);
if (!distinguishable(d, GIGANTIC, EPS_C))
nb_grid[2] = NULL;
else {
nb_grid[2] = grid->surface->nb_walls[2]->grid;
nb_idx[2] = uv2grid(&near_2d, nb_grid[2]);
}
}
}
/* Then "right" (towards edge 1) */
if (j < k) /* all tiles except upright tiles in last stripe */
{
nb_grid[1] = grid;
nb_idx[1] = idx + 1;
} else /* upright tiles in last stripe */
{
if (grid->surface->nb_walls[1] == NULL)
nb_grid[1] = NULL;
else if ((grid->surface->nb_walls[1]->grid == NULL) && (!create_grid_flag))
nb_grid[1] = NULL;
else {
if ((grid->surface->nb_walls[1]->grid == NULL) && create_grid_flag) {
if (create_grid(world, grid->surface->nb_walls[1], NULL))
mcell_allocfailed("Failed to create grid for wall.");
}
if (grid->sm_list[idx]->sm != NULL)
uv2xyz(&grid->sm_list[idx]->sm->s_pos, grid->surface, &loc_3d);
else
grid2xyz(grid, idx, &loc_3d);
d = closest_interior_point(&loc_3d, grid->surface->nb_walls[1], &near_2d,
GIGANTIC);
if (!distinguishable(d, GIGANTIC, EPS_C))
nb_grid[1] = NULL;
else {
nb_grid[1] = grid->surface->nb_walls[1]->grid;
nb_idx[1] = uv2grid(&near_2d, nb_grid[1]);
}
}
}
/* Finally "up/down" (towards edge 0 if not flipped) */
if (i || k + 1 < grid->n) /* all tiles except upright tiles in last strip */
{
nb_grid[0] = grid;
if (i)
nb_idx[0] =
2 * j + (k - 1) * (k - 1); /* unflip and goto previous strip */
else
nb_idx[0] = 1 + 2 * j + (k + 1) * (k + 1); /* flip and goto next strip */
} else /* upright tiles in last strip */
{
if (grid->surface->nb_walls[0] == NULL)
nb_grid[0] = NULL;
else if ((grid->surface->nb_walls[0]->grid == NULL) && (!create_grid_flag))
nb_grid[0] = NULL;
else {
if ((grid->surface->nb_walls[0]->grid == NULL) && create_grid_flag) {
if (create_grid(world, grid->surface->nb_walls[0], NULL))
mcell_allocfailed("Failed to create grid for wall.");
}
if (grid->sm_list[idx]->sm != NULL)
uv2xyz(&grid->sm_list[idx]->sm->s_pos, grid->surface, &loc_3d);
else
grid2xyz(grid, idx, &loc_3d);
d = closest_interior_point(&loc_3d, grid->surface->nb_walls[0], &near_2d,
GIGANTIC);
if (!distinguishable(d, GIGANTIC, EPS_C))
nb_grid[0] = NULL;
else {
nb_grid[0] = grid->surface->nb_walls[0]->grid;
nb_idx[0] = uv2grid(&near_2d, nb_grid[0]);
}
}
}
}
/*************************************************************************
nearest_free:
In: a surface grid
a vector in u,v coordinates on that surface
the maximum distance we can search for free spots
Out: integer containing the index of the closest unoccupied grid point
to the vector, or -1 if no unoccupied points are found in range
Note: we assume you've already checked the grid element that contains
the point, so we don't bother looking there first.
Note: if no unoccupied tile is found, found_dist2 contains distance to
closest occupied tile.
*************************************************************************/
int nearest_free(struct surface_grid *g, struct vector2 *v, double max_d2,
double *found_dist2) {
int h, i, j, k;
int span;
int can_flip;
int idx;
double d2;
double f, ff, fff;
double over3n = 0.333333333333333 / (double)(g->n);
/* check whether the grid is fully occupied */
if (g->n_occupied >= g->n_tiles) {
*found_dist2 = 0;
return -1;
}
idx = -1;
d2 = 2 * max_d2 + 1.0;
for (k = 0; k < g->n; k++) {
f = v->v - ((double)(3 * k + 1)) * over3n * g->surface->uv_vert2.v;
ff = f - over3n * g->surface->uv_vert2.v;
ff *= ff;
f *= f;
if (f > max_d2 && ff > max_d2)
continue; /* Entire strip is too far away */
span = (g->n - k);
for (j = 0; j < span; j++) {
can_flip = (j != span - 1);
for (i = 0; i <= can_flip; i++) {
fff =
v->u - over3n * ((double)(3 * j + i + 1) * g->surface->uv_vert1_u +
(double)(3 * k + i + 1) * g->surface->uv_vert2.u);
fff *= fff;
if (i)
fff += ff;
else
fff += f;
if (fff < max_d2 && (idx == -1 || fff < d2)) {
h = (g->n - k) - 1;
h = h * h + 2 * j + i;
if (!g->sm_list[h] || !g->sm_list[h]->sm) {
idx = h;
d2 = fff;
} else if (idx == -1) {
if (fff < d2)
d2 = fff;
}
}
}
}
}
if (found_dist2 != NULL)
*found_dist2 = d2;
return idx;
}
/*************************************************************************
verify_wall_regions_match:
In: char *mesh_name - the name of the polygon object to be checked
string_buffer *reg_names - contains the regions names to be checked
wall *w - we will compare the regions on this wall to those in reg_names
Out: 0 if region names in reg_names match those of the wall or if we aren't really
checking (mesh_name and/or reg_names are NULL), 1 otherwise.
*************************************************************************/
int verify_wall_regions_match(
const char *mesh_name, struct string_buffer *prev_reg_names, struct wall *w,
struct string_buffer *regions_to_ignore,
struct mesh_transparency *mesh_transp, const char *species_name) {
if ((mesh_name != NULL) && (prev_reg_names != NULL)) {
if (strcmp(w->parent_object->sym->name, mesh_name) != 0) {
return 1;
}
struct name_list *wall_reg_names = NULL;
wall_reg_names = find_regions_names_by_wall(w, regions_to_ignore);
struct name_list *wrn = NULL;
int i = 0;
int still_inside = 0;
// See if we moved *OUTSIDE* of a region we were previously *INSIDE*
// TODO: Really need to optimize this
for (char *prn = prev_reg_names->strings[i]; i < prev_reg_names->n_strings; i++) {
for (wrn = wall_reg_names; wrn != NULL; wrn = wrn->next) {
if (strcmp(prn, wrn->name) == 0) {
still_inside = 1;
break;
}
}
if (!still_inside) {
// We are now outside a region now that we were inside before
// See if we can legally be there (i.e. are we transparent to it)
struct mesh_transparency *mt = mesh_transp;
for (; mt != NULL; mt = mt->next) {
// Need to add test to discriminate between top front and top back
if ((strcmp(mt->name, prn) == 0) &&
(!mt->transp_top_front || !mt->transp_top_back)) {
if (wall_reg_names != NULL) {
remove_molecules_name_list(&wall_reg_names);
}
return 1;
}
}
}
still_inside = 0;
}
// See if we moved *INSIDE* a region we were *OUTSIDE* of before
for (wrn = wall_reg_names; wrn != NULL; wrn = wrn->next) {
// Disregard regions which were just removed
if (is_string_present_in_string_array(
wrn->name, regions_to_ignore->strings, regions_to_ignore->n_strings)) {
continue;
}
if (!is_string_present_in_string_array(
wrn->name, prev_reg_names->strings, prev_reg_names->n_strings)) {
// We are in a region now that we weren't in before
// See if we can legally be there (i.e. are we transparent to it)
int cont = 0;
struct mesh_transparency *mt = mesh_transp;
for (; mt != NULL; mt = mt->next) {
if (strcmp(mt->name, wrn->name) == 0) {
if (mt->transp_top_front || mt->transp_top_back) {
cont = 1;
break;
}
}
}
if (cont) {
continue;
}
remove_molecules_name_list(&wall_reg_names);
return 1;
}
}
if (wall_reg_names != NULL) {
remove_molecules_name_list(&wall_reg_names);
}
}
return 0;
}
/*************************************************************************
search_nbhd_for_free:
In: the wall that we ought to be in
a vector in u,v coordinates on that surface where we should go
the maximum distance we can search for free spots
a place to store the index of our free slot
a function that we'll call to make sure a wall is okay
context for that function passed in by whatever called us
Out: pointer to the wall that has the free slot, or NULL if no wall
exist in range.
Note: usually the calling function will create a grid if needed and
check the grid element at u,v; if that is not done this function
will return the correct result but not efficiently.
Note: This is not recursive. It should be made recursive.
*************************************************************************/
struct wall *search_nbhd_for_free(struct volume *world, struct wall *origin,
struct vector2 *point, double max_d2,
int *found_idx,
int (*ok)(void *, struct wall *),
void *context, const char *mesh_name,
struct string_buffer *reg_names) {
struct wall *there = NULL;
int i, j;
double d2 = 0;
struct vector2 pt, ed;
struct vector2 vurt0, vurt1;
int best_i;
double best_d2;
struct wall *best_w = NULL;
best_i = -1;
best_d2 = 2.0 * max_d2 + 1.0;
if (origin->grid == NULL && create_grid(world, origin, NULL))
mcell_allocfailed("Failed to create grid for wall.");
i = -1; /* default return value */
/* Find index and distance of nearest free grid element on origin wall */
if (origin->grid->n_occupied < origin->grid->n_tiles) {
i = nearest_free(origin->grid, point, max_d2, &d2);
}
if (i != -1) {
best_i = i;
best_d2 = d2;
best_w = origin;
}
/* if there are no free slots on the origin wall - look around */
if (best_w == NULL) {
/* Check for closer free grid elements on neighboring walls */
for (j = 0; j < 3; j++) {
if (origin->edges[j] == NULL || origin->edges[j]->backward == NULL)
continue;
if (origin->edges[j]->forward == origin)
there = origin->edges[j]->backward;
else
there = origin->edges[j]->forward;
if (ok != NULL && !(*ok)(context, there))
continue; /* Calling function doesn't like this wall */
if (verify_wall_regions_match(mesh_name, reg_names, there, NULL, NULL, NULL)) {
continue;
}
/* check whether there are any available spots on the neighbor wall */
if (there->grid != NULL) {
if (there->grid->n_occupied >= there->grid->n_tiles) {
continue;
}
}
/* Calculate distance between point and edge j of origin wall */
switch (j) {
case 0:
vurt0.u = vurt0.v = 0.0;
vurt1.u = origin->uv_vert1_u;
vurt1.v = 0;
break;
case 1:
vurt0.u = origin->uv_vert1_u;
vurt0.v = 0;
memcpy(&vurt1, &(origin->uv_vert2), sizeof(struct vector2));
break;
case 2:
memcpy(&vurt0, &(origin->uv_vert2), sizeof(struct vector2));
vurt1.u = vurt1.v = 0.0;
break;
default:
/* default case should not occur since 0<=j<=2 */
UNHANDLED_CASE(j);
}
ed.u = vurt1.u - vurt0.u;
ed.v = vurt1.v - vurt0.v;
pt.u = point->u - vurt0.u;
pt.v = point->v - vurt0.v;
d2 = pt.u * ed.u + pt.v * ed.v;
d2 = (pt.u * pt.u + pt.v * pt.v) -
d2 * d2 / (ed.u * ed.u + ed.v * ed.v); /* Distance squared to line */
/* Check for free grid element on neighbor if point to edge distance is
* closer than best_d2 */
if (d2 < best_d2) {
if (there->grid == NULL && create_grid(world, there, NULL))
mcell_allocfailed("Failed to create grid for wall.");
traverse_surface(origin, point, j, &pt);
i = nearest_free(there->grid, &pt, max_d2, &d2);
if (i != -1 && d2 < best_d2) {
best_i = i;
best_d2 = d2;
best_w = there;
}
}
}
}
*found_idx = best_i;
return best_w;
}
/***************************************************************************
delete_tile_neighbor_list:
In: linked list of tile_neighbors
Out: none. The memory is freed
****************************************************************************/
void delete_tile_neighbor_list(struct tile_neighbor *head) {
struct tile_neighbor *nnext;
while (head != NULL) {
nnext = head->next;
free(head);
head = nnext;
}
}
/***************************************************************************
delete_region_list:
In: linked list of regions
Out: none. The memory is freed
****************************************************************************/
void delete_region_list(struct region_list *head) {
struct region_list *next;
while (head != NULL) {
next = head->next;
free(head);
head = next;
}
}
/***************************************************************************
push_tile_neighbor_to_list:
In: head of the linked list
surface_grid of the wall the tile is on
index of the tile
Out: none. The linked list is expanded by one node (grid/idx).
****************************************************************************/
void push_tile_neighbor_to_list(struct tile_neighbor **head,
struct surface_grid *grid, int idx) {
struct tile_neighbor *old_head = *head;
struct tile_neighbor *tile_nbr = CHECKED_MALLOC_STRUCT(struct tile_neighbor,
"tile_neighbor");
tile_nbr->grid = grid;
tile_nbr->flag = 0;
tile_nbr->idx = idx;
if (old_head == NULL) {
tile_nbr->next = NULL;
old_head = tile_nbr;
} else {
tile_nbr->next = old_head;
old_head = tile_nbr;
}
*head = old_head;
}
/***************************************************************************
push_tile_neighbor_to_list_with_checking:
In: head of the linked list
surface_grid of the wall the tile is on
index of the tile
Out: number of added nodes (grid/idx). Should be zero or 1.
Note: we perform checking so that no duplicates are added
****************************************************************************/
int push_tile_neighbor_to_list_with_checking(struct tile_neighbor **head,
struct surface_grid *grid,
int idx) {
struct tile_neighbor *tile_nbr, *old_head;
old_head = *head;
for (tile_nbr = old_head; tile_nbr != NULL; tile_nbr = tile_nbr->next) {
if ((tile_nbr->grid == grid) && (tile_nbr->idx == (u_int)idx))
return 0;
}
tile_nbr = CHECKED_MALLOC_STRUCT(struct tile_neighbor, "tile_neighbor");
tile_nbr->grid = grid;
tile_nbr->flag = 0;
tile_nbr->idx = idx;
if (old_head == NULL) {
tile_nbr->next = NULL;
old_head = tile_nbr;
} else {
tile_nbr->next = old_head;
old_head = tile_nbr;
}
*head = old_head;
return 1;
}
/*********************************************************************
get_tile_neighbor_from_list_of_vacant_neighbors:
In: head of the linked list of tile_neighbors
index of the node in the list (indexing starts from zero)
surface_grid (return value)
tile index (return value)
Out: Only if the node was not previously selected, the surface_grid
and tile index on the surface grid are set.
Returns number of really vacant tiles at the start of the function
(some tiles may be already selected by the previous calls
to the function).
*********************************************************************/
int get_tile_neighbor_from_list_of_vacant_neighbors(struct tile_neighbor *head,
int list_index, struct surface_grid **grid, int *tile_idx) {
struct tile_neighbor *curr = head;
int iter = 0; /* iterator through the linked list like through the array */
int count = 0; /* number of really vacant tiles */
while (curr != NULL) {
if ((curr->flag & TILE_CHECKED) == 0) {
count++;
}
if ((iter == list_index) && ((curr->flag & TILE_CHECKED) == 0)) {
curr->flag |= TILE_CHECKED;
*grid = curr->grid;
*tile_idx = curr->idx;
}
iter++;
curr = curr->next;
}
return count;
}
/******************************************************************
uncheck_vacant_tile:
In: head of the linked list of tile_neighbors
index of the node in the list (indexing starts from zero)
Out: None. The flag on the tile_neighbor is cleared at
bit TILE_CHECKED.
******************************************************************/
void uncheck_vacant_tile(struct tile_neighbor *head, int list_index) {
struct tile_neighbor *curr = head;
int iter = 0; /* iterator through the linked list like through the array */
while (curr != NULL) {
if ((iter == list_index) && (curr->flag & TILE_CHECKED)) {
/* clear the bit */
curr->flag &= ~TILE_CHECKED;
}
iter++;
curr = curr->next;
}
}
/*************************************************************************
get_tile_vertices:
In: surface grid
tile index
tile flip information (return value)
first tile vertex R (return value)
second tile vertex S (return value)
third tile vertex T (return value)
Out: the tile vertices (R,S,T) coordinates are defined
Note: the vertices (R,S,T) are listed clockwise. For the upright tile
(orientation similar to the wall) two vertices R and S are
on the same line PQ parallel and closest to the u-axis.
For the inverted tile (orientation inverted compared to the wall)
two vertices S and T are on the same line XY parallel and furthest
to the u-axis.
*************************************************************************/
void get_tile_vertices(struct surface_grid *sg, int idx, int *flp,
struct vector2 *R, struct vector2 *S,
struct vector2 *T) {
/* indices of the barycentric subdivision */
int strip, stripe, flip;
int root, rootrem;
struct vector2 P, Q, X, Y;
/* length of the segments PQ and XY (see below) */
double pq, xy;
/* cotangent of the angle formed between the u-axis
and the wall edge opposite to the origin of the
uv-coordinate system */
double cot_angle;
/* Calculate strip, stripe, and flip indices from idx */
root = (int)(sqrt((double)idx));
rootrem = idx - root * root;
strip = sg->n - root - 1;
stripe = rootrem / 2;
flip = rootrem - 2 * stripe;
/* Let PQ to be the segment on the grid containing the vertex R
and the one closest to the u-axis. Let XY to be the segment
containing the vertex T and the one furthest to the u-axis.
Let point P to be on the left side of point Q.
Let point X to be on the left side of point Y.
*/
/* find v-coordinates of P, Q, X, Y */
P.v = Q.v = strip / sg->inv_strip_wid;
X.v = Y.v = (strip + 1) / sg->inv_strip_wid;
/* find u-coordinates of P, Q, X, Y */
P.u = (P.v) * (sg->vert2_slope);
X.u = (X.v) * (sg->vert2_slope);
cot_angle = (sg->surface->uv_vert1_u - sg->surface->uv_vert2.u) /
(sg->surface->uv_vert2.v);
Q.u = sg->surface->uv_vert1_u - (Q.v) * cot_angle;
Y.u = sg->surface->uv_vert1_u - (Y.v) * cot_angle;
pq = Q.u - P.u;
if (idx == 0) {
xy = 0;
} else {
xy = Y.u - X.u;
}
/* find coordinates of the tile vertices */
/* For the upright tile the vertices R and S lie on
the line PQ and vertex T - on the line XY.
For the inverted tile only the vertex R lies on the line PQ
while the vertices S and T lie on the line XY */
if (flip == 1) {
/* inverted tile */
R->v = P.v;
/* note: pq/(sg->n - strip) tells us
the number of slots on the line PQ */
R->u = P.u + pq * (stripe + 1) / (sg->n - strip);
S->v = T->v = X.v;
T->u = X.u + xy * stripe / (sg->n - strip - 1);
S->u = X.u + xy * (stripe + 1) / (sg->n - strip - 1);
} else {
/* upright tile */
R->v = S->v = P.v;
T->v = X.v;
/* note: pq/(sg->n - strip) tells us
the number of slots on the line PQ */
R->u = P.u + pq * stripe / (sg->n - strip);
S->u = P.u + pq * (stripe + 1) / (sg->n - strip);
if (idx == 0) {
T->u = X.u;
} else {
T->u = X.u + xy * stripe / (sg->n - strip - 1);
}
}
/* set the tile flip value */
*flp = flip;
}
/*************************************************************************
tile_orientation:
In: a vector to the point on the grid and a surface grid
Out: 0 if the triangle containg the point is upright,
and 1 if it is inverted.
WARNING: no error checking--point assumed to be valid.
*************************************************************************/
int tile_orientation(struct vector2 *v, struct surface_grid *g) {
double i, j;
double u0, u1_u0;
double striploc, striprem, stripeloc, striperem;
int strip, stripe, flip;
i = v->u;
j = v->v;
striploc = j * g->inv_strip_wid;
strip = (int)striploc;
striprem = striploc - strip;
strip = g->n - strip - 1;
u0 = j * g->vert2_slope;
u1_u0 = g->surface->uv_vert1_u - j * g->fullslope;
stripeloc = ((i - u0) / u1_u0) * (((double)strip) + (1.0 - striprem));
stripe = (int)(stripeloc);
striperem = stripeloc - stripe;
flip = (striperem < 1.0 - striprem) ? 0 : 1;
return flip;
}
/*****************************************************************************
grid_all_neighbors_for_inner_tile:
In: a surface grid
an index on that grid
a point on that tile
a linked list of neighbor tiles (return value)
a length of the linked list above (return value)
Out: The list and list length of nearest neighbors
are returned. Neighbors should share either common edge or
common vertice.
Note: The code below is valid only for the inner tile - the one that has 12
neighbor tiles all belonging to the same grid as the start tile.
*****************************************************************************/
void grid_all_neighbors_for_inner_tile(
struct volume *world, struct surface_grid *grid, int idx,
struct vector2 *pos, struct tile_neighbor **tile_neighbor_head,
int *list_length) {
struct tile_neighbor *tile_nbr_head = NULL;
int count = 0;
int vert_nbr_ind = -1;
/* The tile that has shape similar to the wall is called upright tile.
The tile that has shape inverted relative to the wall is
called inverted tile. */
int kk;
struct surface_grid *sg[3]; /* Neighboring surface grids (edge-to-edge) */
int si[3]; /* Indices on those grids (edge-to-edge) of neighbor molecules */
if ((u_int)idx >= grid->n_tiles) {
mcell_internal_error(
"Surface molecule tile index is greater than or equal of "
"the number of tiles on the grid\n");
}
for (kk = 0; kk < 3; kk++) {
sg[kk] = NULL;
si[kk] = -1;
}
/* find neighbors to react with */
grid_neighbors(world, grid, idx, 0, sg, si);
if ((grid != sg[0]) || (grid != sg[1]) || (grid != sg[2])) {
mcell_internal_error("The function 'grid_all_neighbors_for_inner_tile()' "
"is called for the tile %d that is not an inner tile.",
idx);
}
for (kk = 0; kk < 3; kk++) {
if ((si[kk] != idx - 1) && (si[kk] != idx + 1)) {
vert_nbr_ind = si[kk];
break;
}
}
/* The tile has 2 neighbors to the left and 2 neighbors to the right */
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx - 1);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx - 2);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx + 1);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx + 2);
count++;
/* find the orientation of the tile */
int tile_orient = tile_orientation(pos, grid);
int temp_ind;
if (tile_orient == 0) {
/* upright tile has 5 neighbors in the row above it */
push_tile_neighbor_to_list(&tile_nbr_head, grid, vert_nbr_ind);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, vert_nbr_ind - 1);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, vert_nbr_ind - 2);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, vert_nbr_ind + 1);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, vert_nbr_ind + 2);
count++;
/* upright tile has 3 neighbors in the row below it */
temp_ind = move_strip_down(grid, idx);
if (temp_ind == -1) {
mcell_internal_error("The function 'grid_all_neighbors_for_inner_tile() "
"is called for the tile %d that is not an inner "
"tile.",
idx);
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_ind);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_ind - 1);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_ind + 1);
count++;
} else {
/* inverted tile has 3 neighbors in the row above it */
temp_ind = move_strip_up(grid, idx);
if (temp_ind == -1) {
mcell_internal_error("The function 'grid_all_neighbors_for_inner_tile() "
"is called for the tile %d that is not an inner "
"tile.",
idx);
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_ind);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_ind - 1);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_ind + 1);
count++;
/* inverted tile has 5 neighbors in the row below it */
push_tile_neighbor_to_list(&tile_nbr_head, grid, vert_nbr_ind);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, vert_nbr_ind - 1);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, vert_nbr_ind - 2);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, vert_nbr_ind + 1);
count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, vert_nbr_ind + 2);
count++;
}
if (count != 12) {
mcell_internal_error("The function 'grid_all_neighbors_for_inner_tile() is "
"called for the tile %d that is not an inner tile.",
idx);
} else {
*list_length = count;
}
*tile_neighbor_head = tile_nbr_head;
}
/**************************************************************************
grid_all_neighbors_across_walls_through_vertices:
In: a surface molecule
linked list of the neighbor walls that share one vertex only
surface grid of thew all the molecule sits on or where the hit happens
flag that tells whether we need to create a grid on a neighbor wall
flag that tells whether we are searching for reactant
(value = 1) or doing product placement (value = 0)
a linked list of neighbor tiles (return value)
a length of the linked list above (return value)
Out: The list of nearest neighbors are returned,
Neighbors should share common vertex.
Note: This version allows looking for the neighbors at the neighbor walls
that are connected to the start wall through vertices only. Also
the function takes care of REFLECTIVE/ABSORPTIVE region borders.
****************************************************************************/
void grid_all_neighbors_across_walls_through_vertices(
struct volume *world, struct surface_molecule *sm,
struct wall_list *wall_nbr_head, struct surface_grid *grid,
int create_grid_flag, int search_for_reactant,
struct tile_neighbor **tile_neighbor_head, int *list_length) {
struct tile_neighbor *tile_nbr_head = NULL;
struct wall_list *wl;
struct wall *w;
long long nbr_wall_vertex_id; /* index of the neighbor wall vertex in
"world->all_vertices" array that coincides
with tile vertex */
int nbr_tile_idx; /* index of the neighbor tile */
/* arrays of vertex indices for the origin and neighbor walls
in the global array "world->all_vertices" */
long long origin_vert_indices[3], nbr_vert_indices[3];
int i, k;
int tiles_count = 0; /* number of tiles added */
/* list of restricted regions */
struct region_list *rlp_head_own_wall = NULL;
struct region_list *rlp_head_nbr_wall;
/* check for possible reflection (absorption) from the wall edges
that may be region borders. This is INSIDE_OUT check against
molecule's own wall */
if ((sm != NULL) && (sm->properties->flags & CAN_REGION_BORDER)) {
rlp_head_own_wall =
find_restricted_regions_by_wall(world, sm->grid->surface, sm);
}
/* only one corner tile from each neighbor wall
can be a neighbor to our start tile */
/* since the neighbor walls are connected to the origin wall by just
one vertex, and this code is valid only for the corner tile
on the origin wall, from each neighbor wall we will pick up
only one corner tile that shares a vertex with the origin wall */
for (wl = wall_nbr_head; wl != NULL; wl = wl->next) {
w = wl->this_wall;
rlp_head_nbr_wall = NULL;
if (w->grid == NULL) {
if (create_grid_flag) {
if (create_grid(world, w, NULL))
mcell_allocfailed("Failed to allocate grid for wall.");
} else {
continue;
}
}
/* if there is a restricted region list for own wall
and neighbor wall does NOT belong to all regions in this list -
we assume that neighbor wall lies outside the
restricted region boundary and we DO NOT add
tile on such wall to the list of neighbor tiles */
if (search_for_reactant && (rlp_head_own_wall != NULL)) {
if (!wall_belongs_to_all_regions_in_region_list(w, rlp_head_own_wall))
continue;
}
/* Similar test done OUTSIDE-IN */
if (sm != NULL) {
if (search_for_reactant && (sm->properties->flags & CAN_REGION_BORDER)) {
rlp_head_nbr_wall = find_restricted_regions_by_wall(world, w, sm);
if (rlp_head_nbr_wall != NULL) {
if (!wall_belongs_to_all_regions_in_region_list(sm->grid->surface,
rlp_head_nbr_wall)) {
delete_void_list((struct void_list *)rlp_head_nbr_wall);
continue;
} else {
/* we will add the tile on this wall to the list */
delete_void_list((struct void_list *)rlp_head_nbr_wall);
}
}
}
}
/* find the index of the neighbor tile */
if (w->grid->n_tiles == 1) {
nbr_tile_idx = 0;
} else {
nbr_wall_vertex_id = -1;
nbr_tile_idx = -1;
for (i = 0; i < 3; i++) {
origin_vert_indices[i] = (long long)(grid->surface->vert[i] - world->all_vertices);
}
for (i = 0; i < 3; i++) {
nbr_vert_indices[i] = (long long)(w->grid->surface->vert[i] - world->all_vertices);
}
for (i = 0; i < 3; i++) {
for (k = 0; k < 3; k++) {
if (origin_vert_indices[i] == nbr_vert_indices[k]) {
nbr_wall_vertex_id = nbr_vert_indices[k];
break;
}
}
}
if (nbr_wall_vertex_id == -1)
mcell_internal_error("Error identifying tile on the neighbor wall.");
/* find the index of the neighbor tile */
if (&world->all_vertices[nbr_wall_vertex_id] ==
w->grid->surface->vert[0]) {
nbr_tile_idx = w->grid->n_tiles - 2 * (w->grid->n) + 1;
} else if (&world->all_vertices[nbr_wall_vertex_id] ==
w->grid->surface->vert[1]) {
nbr_tile_idx = w->grid->n_tiles - 1;
} else if (&world->all_vertices[nbr_wall_vertex_id] ==
w->grid->surface->vert[2]) {
nbr_tile_idx = 0;
}
if (nbr_tile_idx == -1)
mcell_internal_error("Error identifying tile on the neighbor wall.");
}
push_tile_neighbor_to_list(&tile_nbr_head, w->grid, nbr_tile_idx);
tiles_count++;
}
*list_length = tiles_count;
*tile_neighbor_head = tile_nbr_head;
if (rlp_head_own_wall != NULL)
delete_void_list((struct void_list *)rlp_head_own_wall);
}
/**************************************************************************
grid_all_neighbors_across_walls_through_edges:
In: a surface molecule
surface grid of the wall where molecule sits on or where hit happens
index of the tile for the condition above
flag that tells whether we need to create a grid on a neighbor wall
flag that tells whether we are searching for reactant
(value = 1) or doing product placement (value = 0)
a linked list of neighbor tiles (return value)
a length of the linked list above (return value)
Out: The list of nearest neighbors are returned,
Neighbors should share common edge.
Note: This version allows looking for the neighbors at the neighbor walls
that are connected to the start wall through edges only.
****************************************************************************/
void grid_all_neighbors_across_walls_through_edges(
struct volume *world, struct surface_molecule *sm,
struct surface_grid *grid, int idx, int create_grid_flag,
int search_for_reactant, struct tile_neighbor **tile_neighbor_head,
int *list_length) {
struct tile_neighbor *tile_nbr_head = NULL;
int tiles_count = 0;
int tiles_added = 0; /* return value from the function
"add_more_tile_neighbors_to_list()" */
int kk;
int root, rootrem, strip, stripe, flip;
int temp_idx;
/* list of restricted regions */
struct region_list *rlp_head_own_wall = NULL;
struct region_list *rlp_head_nbr_wall_0 = NULL;
struct region_list *rlp_head_nbr_wall_1 = NULL;
struct region_list *rlp_head_nbr_wall_2 = NULL;
/* flags */
int move_thru_border_0 = 1;
int move_thru_border_1 = 1;
int move_thru_border_2 = 1;
/* check for possible reflection (absorption) from the wall edges
that may be region borders. These are INSIDE_OUT and OUTSIDE-IN
checks against molecule's own wall and neighbor wall */
if ((sm != NULL) && search_for_reactant &&
(sm->properties->flags & CAN_REGION_BORDER)) {
rlp_head_own_wall =
find_restricted_regions_by_wall(world, sm->grid->surface, sm);
if (sm->grid->surface->nb_walls[0] != NULL) {
rlp_head_nbr_wall_0 = find_restricted_regions_by_wall(
world, sm->grid->surface->nb_walls[0], sm);
if (rlp_head_own_wall != NULL) {
if (!wall_belongs_to_all_regions_in_region_list(
sm->grid->surface->nb_walls[0], rlp_head_own_wall))
move_thru_border_0 = 0;
}
if (rlp_head_nbr_wall_0 != NULL) {
if (!wall_belongs_to_all_regions_in_region_list(sm->grid->surface,
rlp_head_nbr_wall_0))
move_thru_border_0 = 0;
}
if (rlp_head_nbr_wall_0 != NULL)
delete_void_list((struct void_list *)rlp_head_nbr_wall_0);
} else {
move_thru_border_0 = 0;
}
if (sm->grid->surface->nb_walls[1] != NULL) {
rlp_head_nbr_wall_1 = find_restricted_regions_by_wall(
world, sm->grid->surface->nb_walls[1], sm);
if (rlp_head_own_wall != NULL) {
if (!wall_belongs_to_all_regions_in_region_list(
sm->grid->surface->nb_walls[1], rlp_head_own_wall))
move_thru_border_1 = 0;
}
if (rlp_head_nbr_wall_1 != NULL) {
if (!wall_belongs_to_all_regions_in_region_list(sm->grid->surface,
rlp_head_nbr_wall_1))
move_thru_border_1 = 0;
}
if (rlp_head_nbr_wall_1 != NULL)
delete_void_list((struct void_list *)rlp_head_nbr_wall_1);
} else {
move_thru_border_1 = 0;
}
if (sm->grid->surface->nb_walls[2] != NULL) {
rlp_head_nbr_wall_2 = find_restricted_regions_by_wall(
world, sm->grid->surface->nb_walls[2], sm);
if (rlp_head_own_wall != NULL) {
if (!wall_belongs_to_all_regions_in_region_list(
sm->grid->surface->nb_walls[2], rlp_head_own_wall))
move_thru_border_2 = 0;
}
if (rlp_head_nbr_wall_2 != NULL) {
if (!wall_belongs_to_all_regions_in_region_list(sm->grid->surface,
rlp_head_nbr_wall_2))
move_thru_border_2 = 0;
}
if (rlp_head_nbr_wall_2 != NULL)
delete_void_list((struct void_list *)rlp_head_nbr_wall_2);
} else {
move_thru_border_2 = 0;
}
if (rlp_head_own_wall != NULL)
delete_void_list((struct void_list *)rlp_head_own_wall);
}
if ((u_int)idx >= grid->n_tiles) {
mcell_internal_error("Surface molecule tile index %u is greater than or "
"equal of the number of tiles on the grid %u\n",
(u_int)idx, grid->n_tiles);
}
/* find (strip, stripe, flip) coordinates of the tile */
root = (int)(sqrt((double)idx));
rootrem = idx - root * root;
strip = grid->n - root - 1;
stripe = rootrem / 2;
flip = rootrem - 2 * stripe;
if (create_grid_flag) {
for (kk = 0; kk < 3; kk++) {
if ((grid->surface->nb_walls[kk] != NULL) &&
(grid->surface->nb_walls[kk]->grid == NULL)) {
if (create_grid(world, grid->surface->nb_walls[kk], NULL))
mcell_allocfailed("Failed to create grid for wall.");
}
}
}
if (stripe == 0) {
if (flip > 0) /* inverted tile */
{
/* put in the list tiles that are on the same strip */
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx + 1);
tiles_count++;
if (strip < grid->n - 2) {
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx + 2);
tiles_count++;
}
/* put in the list tiles that are on the row below the start tile
but on the same grid */
temp_idx = move_strip_down(grid, idx);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
if (strip < grid->n - 2) {
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 2);
tiles_count++;
}
if (strip > 0) {
/* put in the list tiles that are on the row above the start tile
but on the same grid */
temp_idx = move_strip_up(grid, idx);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 1);
tiles_count++;
}
/* get the neighbors from the neighbor walls */
if ((grid->surface->nb_walls[2] != NULL) &&
(grid->surface->nb_walls[2]->grid != NULL)) {
if (move_thru_border_2) {
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip, grid->surface->vert[0],
grid->surface->vert[2], 2, grid->surface->nb_walls[2]->grid);
tiles_count += tiles_added;
}
}
if (strip == 0) {
if ((grid->surface->nb_walls[0] != NULL) &&
(grid->surface->nb_walls[0]->grid != NULL)) {
if (move_thru_border_0) {
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip,
grid->surface->vert[0], grid->surface->vert[1], 0,
grid->surface->nb_walls[0]->grid);
tiles_count += tiles_added;
}
}
}
if (strip == (grid->n - 2)) {
if ((grid->surface->nb_walls[1] != NULL) &&
(grid->surface->nb_walls[1]->grid != NULL)) {
if (move_thru_border_1) {
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip,
grid->surface->vert[1], grid->surface->vert[2], 1,
grid->surface->nb_walls[1]->grid);
tiles_count += tiles_added;
}
}
}
} else { /* upright tile (flip == 0) */
if (idx == 0) /* it is a special case */
{
if (grid->n_tiles > 1) {
/* put in the list tiles that are on the row above the start tile */
temp_idx = move_strip_up(grid, idx);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 1);
tiles_count++;
} else {
if ((grid->surface->nb_walls[0] != NULL) &&
(grid->surface->nb_walls[0]->grid != NULL)) {
if (move_thru_border_0) {
/* get the neighbors from the neighbor walls */
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip,
grid->surface->vert[0], grid->surface->vert[1], 0,
grid->surface->nb_walls[0]->grid);
tiles_count += tiles_added;
}
}
}
if ((grid->surface->nb_walls[1] != NULL) &&
(grid->surface->nb_walls[1]->grid != NULL)) {
if (move_thru_border_1) {
/* get the neighbors from the neighbor walls */
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip,
grid->surface->vert[1], grid->surface->vert[2], 1,
grid->surface->nb_walls[1]->grid);
tiles_count += tiles_added;
}
}
if ((grid->surface->nb_walls[2] != NULL) &&
(grid->surface->nb_walls[2]->grid != NULL)) {
if (move_thru_border_2) {
/* get the neighbors from the neighbor walls */
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip,
grid->surface->vert[0], grid->surface->vert[2], 2,
grid->surface->nb_walls[2]->grid);
tiles_count += tiles_added;
}
}
} else { /* if (idx != 0) */
/* put in the list tiles that are on the same strip */
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx + 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx + 2);
tiles_count++;
/* put in the list tiles that are on the row below the start tile */
temp_idx = move_strip_down(grid, idx + 1);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
if (strip > 0) {
/* put in the list tiles that are on the row above the start tile
but on the same grid */
temp_idx = move_strip_up(grid, idx);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 2);
tiles_count++;
} else { /* strip == 0 */
/* put in the list tiles that are on the row above the start tile
but on the different grid */
/* it is the top left corner - special case */
if ((grid->surface->nb_walls[0] != NULL) &&
(grid->surface->nb_walls[0]->grid != NULL)) {
if (move_thru_border_0) {
/* get the neighbors from the neighbor walls */
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip,
grid->surface->vert[0], grid->surface->vert[1], 0,
grid->surface->nb_walls[0]->grid);
tiles_count += tiles_added;
}
}
if ((grid->surface->nb_walls[2] != NULL) &&
(grid->surface->nb_walls[2]->grid != NULL)) {
if (move_thru_border_2) {
/* get the neighbors from the neighbor walls */
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip,
grid->surface->vert[0], grid->surface->vert[2], 2,
grid->surface->nb_walls[2]->grid);
tiles_count += tiles_added;
}
}
}
} /* end if-else (idx == 0) */
} /* end upright or inverted tile */
} /* end if (stripe == 0) */
if ((strip == 0) && (stripe > 0)) {
/* put in the list tiles that are on the same row */
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx - 2);
tiles_count++;
if ((stripe < grid->n - 2) || ((stripe == grid->n - 2) && (flip == 0))) {
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx + 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx + 2);
tiles_count++;
} else if ((stripe == grid->n - 2) && (flip == 1)) {
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx + 1);
tiles_count++;
}
/* put in the list tiles that are on the row below */
if (flip > 0) {
temp_idx = move_strip_down(grid, idx);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 2);
tiles_count++;
if (stripe < grid->n - 2) {
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 2);
tiles_count++;
}
} else { /* (flip == 0) */
if ((unsigned int)idx < grid->n_tiles - 1) {
temp_idx = move_strip_down(grid, idx);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 1);
tiles_count++;
} else {
/* this is a corner tile */
temp_idx = move_strip_down(grid, idx - 1);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
}
}
/* put in the list tiles that are on the row above */
if ((grid->surface->nb_walls[0] != NULL) &&
(grid->surface->nb_walls[0]->grid != NULL)) {
if (move_thru_border_0) {
/* get the neighbors from the neighbor walls */
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip, grid->surface->vert[0],
grid->surface->vert[1], 0, grid->surface->nb_walls[0]->grid);
tiles_count += tiles_added;
}
}
/* put in the list tiles that are on the side */
if (((u_int)idx == (grid->n_tiles - 1)) ||
((u_int)idx == (grid->n_tiles - 2))) {
if ((grid->surface->nb_walls[1] != NULL) &&
(grid->surface->nb_walls[1]->grid != NULL)) {
if (move_thru_border_1) {
/* get the neighbors from the neighbor walls */
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip, grid->surface->vert[1],
grid->surface->vert[2], 1, grid->surface->nb_walls[1]->grid);
tiles_count += tiles_added;
}
}
}
} /* end if ((strip == 0) && (stripe > 0)) */
if ((strip > 0) && (stripe > 0)) {
/* We are guaranteed to be in the right layer of the wall.
Note that no extra checking is done here for that
assumption besides calling the function "is_inner_tile()"
before calling this function. */
if (flip > 0) {
/* put in the list tiles that are on the same row */
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx - 2);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx + 1);
tiles_count++;
/* put in the list tiles that are above the current row */
temp_idx = move_strip_up(grid, idx);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 1);
tiles_count++;
/* put in the list tiles that are below the current row */
temp_idx = move_strip_down(grid, idx);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 2);
tiles_count++;
} else { /* (flip == 0) */
/* put in the list tiles that are on the same row */
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, idx - 2);
tiles_count++;
/* put in the list tiles that are above the current row */
temp_idx = move_strip_up(grid, idx);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 1);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx - 2);
tiles_count++;
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx + 1);
tiles_count++;
/* put in the list tiles that are below the current row */
temp_idx = move_strip_down(grid, idx - 1);
if (temp_idx == -1) {
mcell_internal_error("Error in navigating on the grid");
}
push_tile_neighbor_to_list(&tile_nbr_head, grid, temp_idx);
tiles_count++;
}
/* put in the list tiles that are on the side */
if ((grid->surface->nb_walls[1] != NULL) &&
(grid->surface->nb_walls[1]->grid != NULL)) {
if (move_thru_border_1) {
/* get the neighbors from the neighbor walls */
tiles_added = add_more_tile_neighbors_to_list_fast(
&tile_nbr_head, grid, strip, stripe, flip, grid->surface->vert[1],
grid->surface->vert[2], 1, grid->surface->nb_walls[1]->grid);
tiles_count += tiles_added;
}
}
} /* end if ((strip > 0) && (stripe > 0)) */
*list_length = tiles_count;
*tile_neighbor_head = tile_nbr_head;
}
/**************************************************************************
add_more_tile_neighbors_to_list_fast:
In: a linked list of neighbor tiles
a surface grid of the start tile
(strip, stripe, flip) coordinates of the start tile
3D coordinates of the shared edge
(edge has a direction from "start" to "end")
index of the shared edge looking from the original orid
(0 - for edge between vert[0] and vert[1],
1 - for edge between vert[1] and vert[2],
2 - for edge between vert[0] and vert[2])
a surface grid of the neighbor wall
Out: Returns number of new neighbor tiles added to the original
linked list of neighbor tiles.
Neighbors should share either common edge or common vertex.
Note: The function looks only for the tiles that are the neighbors of
"orig_grid/orig_idx" and reside on the neighbor "new_grid".
***************************************************************************/
int add_more_tile_neighbors_to_list_fast(struct tile_neighbor **tile_nbr_head,
struct surface_grid *orig_grid,
int orig_strip, int orig_stripe,
int orig_flip, struct vector3 *start,
struct vector3 *end, int edge_index,
struct surface_grid *new_grid) {
int invert_orig_pos = 0; /* flag */
int check_side_flag; /* flag */
double edge_length; /* length of the shared edge */
/* positions of the shared vertices along the shared edge,
measured relative to the shared edge length for the original tile */
double orig_pos_1 = -1, orig_pos_2 = -1;
/* number of tile vertices on the common edge */
const int new_pos_size = new_grid->n + 1;
/* array of the positions of tile vertices on the common edge */
std::vector<double> new_pos(new_pos_size);
/* each tile vertex on the common shared edge is connected to
3 tiles (the end points of the shared edge are connected
to 1 tile). */
/* 2-dimensional array of the tile indices */
std::vector<std::vector<int>> new_tile_idx(new_pos_size);
for (auto& elem: new_tile_idx) {
elem.resize(3);
}
int i, k;
/* what vertices of new wall are shared with original wall */
int shared_vert_1 = -1, shared_vert_2 = -1;
/* what indices of the shared vertices refer to the vertex "start"
and "end" for "original" wall */
int new_start_index, new_end_index;
int tiles_added = 0; /* counter of added tiles */
if (orig_grid == new_grid) {
mcell_internal_error("Function 'add_more_tile_neighbors_to_list()' should "
"be called for different grids only");
}
/* find out relative positions of vertices of original tile
on the common edge */
edge_length = distance_vec3(start, end);
if (orig_stripe == 0) {
if (orig_strip > 0) {
if (orig_flip == 0) {
orig_pos_1 = orig_strip * edge_length / (orig_grid->n);
orig_pos_2 = (orig_strip + 1) * edge_length / (orig_grid->n);
} else { /* (orig_flip == 1) */
orig_pos_1 = (orig_strip + 1) * edge_length / (orig_grid->n);
}
} else {
/* find out common edge refers to what side of the original wall */
if (edge_index == 0) {
if (orig_flip == 0) {
orig_pos_1 = orig_stripe * edge_length / (orig_grid->n);
orig_pos_2 = (orig_stripe + 1) * edge_length / (orig_grid->n);
} else { /* (orig_flip == 1) */
orig_pos_1 = (orig_stripe + 1) * edge_length / (orig_grid->n);
}
} else if (edge_index == 1) {
if (orig_flip == 0) {
orig_pos_1 = (orig_strip) * edge_length / (orig_grid->n);
} else { /* (orig_flip == 1) */
orig_pos_1 = orig_strip * edge_length / (orig_grid->n);
orig_pos_2 = (orig_strip + 1) * edge_length / (orig_grid->n);
}
} else if (edge_index == 2) {
if (orig_flip == 0) {
orig_pos_1 = orig_strip * edge_length / (orig_grid->n);
orig_pos_2 = (orig_strip + 1) * edge_length / (orig_grid->n);
} else { /* (orig_flip == 1) */
orig_pos_1 = (orig_strip + 1) * edge_length / (orig_grid->n);
}
} else {
mcell_internal_error(
"Error in the function 'add_more_tile_neighbors_to_list_fast()'.");
}
}
}
check_side_flag = 0;
if ((orig_strip == 0) && (orig_stripe > 0)) {
if (orig_stripe == orig_grid->n - 1)
check_side_flag = 1;
if ((orig_stripe == orig_grid->n - 2) && (orig_flip == 1))
check_side_flag = 1;
if (!check_side_flag) {
if (orig_flip == 0) {
orig_pos_1 = orig_stripe * edge_length / (orig_grid->n);
orig_pos_2 = (orig_stripe + 1) * edge_length / (orig_grid->n);
} else { /* (orig_flip == 1) */
orig_pos_1 = (orig_stripe + 1) * edge_length / (orig_grid->n);
}
} else {
/* find out common edge refers to what side of the original wall */
if (edge_index == 0) {
if (orig_flip == 0) {
orig_pos_1 = orig_stripe * edge_length / (orig_grid->n);
orig_pos_2 = (orig_stripe + 1) * edge_length / (orig_grid->n);
} else { /* (orig_flip == 1) */
orig_pos_1 = (orig_stripe + 1) * edge_length / (orig_grid->n);
}
} else if (edge_index == 1) {
if (orig_flip == 0) {
orig_pos_1 = orig_strip * edge_length / (orig_grid->n);
orig_pos_2 = (orig_strip + 1) * edge_length / (orig_grid->n);
} else { /* (orig_flip == 1) */
orig_pos_1 = (orig_strip + 1) * edge_length / (orig_grid->n);
}
} else {
mcell_internal_error(
"Error in the function 'add_more_tile_neighbors_to_list_fast()'.");
}
}
}
if ((orig_strip > 0) && (orig_stripe > 0)) {
if (orig_flip == 0) {
orig_pos_1 = orig_strip * edge_length / (orig_grid->n);
orig_pos_2 = (orig_strip + 1) * edge_length / (orig_grid->n);
} else { /* (orig_flip == 1) */
orig_pos_1 = (orig_strip + 1) * edge_length / (orig_grid->n);
}
}
find_shared_vertices_for_neighbor_walls(orig_grid->surface, new_grid->surface,
&shared_vert_1, &shared_vert_2);
/* set the value of 'invert_orig_pos' flag */
if (!distinguishable_vec3(start, new_grid->surface->vert[shared_vert_1],
EPS_C)) {
new_start_index = shared_vert_1;
new_end_index = shared_vert_2;
} else {
new_start_index = shared_vert_2;
new_end_index = shared_vert_1;
}
if (new_start_index > new_end_index)
invert_orig_pos = 1;
/* our coordinate system here is effectively one-dimensional
shared edge. For the neighbor grid it's orientation is opposite
to the one we used for the original grid. Let's recalculate
the positions of the common points on the shared edge depending
on the neigbor grid shared edge direction */
if (invert_orig_pos) {
orig_pos_1 = edge_length - orig_pos_1;
if (orig_pos_2 > 0) {
orig_pos_2 = edge_length - orig_pos_2;
}
}
/* find out relative positions of vertices of tile structure
on the common edge for "new_grid" */
for (i = 0; i < new_pos_size; i++) {
new_pos[i] = i * edge_length / (new_grid->n);
}
/* index of the shared edge in terms of the "new_grid".
Here the edge between vert[0] and vert[1] has index 0,
the edge between vert[1] and vert[2] has index 1,
and the edge between vert[0] and vert[2] has index 2. */
int new_edge_index = 0;
if ((shared_vert_1 + shared_vert_2) == 1) {
new_edge_index = 0;
} else if ((shared_vert_1 + shared_vert_2) == 2) {
new_edge_index = 2;
} else if ((shared_vert_1 + shared_vert_2) == 3) {
new_edge_index = 1;
} else {
mcell_internal_error(
"Error in the function 'add_more_tile_neighbors_to_list_fast()'.");
}
/* fill out the array with tile indices for the border layer
adjacent to the shared edge */
int last_value;
if (new_edge_index == 0) {
new_tile_idx[0][0] = -1;
new_tile_idx[0][1] = -1;
new_tile_idx[0][2] = new_grid->n_tiles - 2 * (new_grid->n) + 1;
last_value = new_tile_idx[0][2];
for (i = 1; i < new_pos_size - 1; i++) {
for (k = 0; k < 3; k++) {
new_tile_idx[i][k] = last_value + k;
}
last_value = new_tile_idx[i][2];
}
new_tile_idx[new_pos_size - 1][0] = last_value;
new_tile_idx[new_pos_size - 1][1] = -1;
new_tile_idx[new_pos_size - 1][2] = -1;
} else if (new_edge_index == 1) {
new_tile_idx[0][0] = -1;
new_tile_idx[0][1] = -1;
new_tile_idx[0][2] = new_grid->n_tiles - 1;
last_value = new_tile_idx[0][2];
for (i = 1; i < new_pos_size - 1; i++) {
for (k = 0; k < 2; k++) {
new_tile_idx[i][k] = last_value - k;
}
last_value = new_tile_idx[i][1];
new_tile_idx[i][2] = move_strip_down(new_grid, last_value);
last_value = new_tile_idx[i][2];
}
new_tile_idx[new_pos_size - 1][0] = last_value;
new_tile_idx[new_pos_size - 1][1] = -1;
new_tile_idx[new_pos_size - 1][2] = -1;
} else { /* (new_edge_index == 2) */
new_tile_idx[0][0] = -1;
new_tile_idx[0][1] = -1;
new_tile_idx[0][2] = new_grid->n_tiles - 2 * (new_grid->n) + 1;
last_value = new_tile_idx[0][2];
for (i = 1; i < new_pos_size - 1; i++) {
for (k = 0; k < 2; k++) {
new_tile_idx[i][k] = last_value + k;
}
last_value = new_tile_idx[i][1];
new_tile_idx[i][2] = move_strip_down(new_grid, last_value);
last_value = new_tile_idx[i][2];
}
new_tile_idx[new_pos_size - 1][0] = last_value;
new_tile_idx[new_pos_size - 1][1] = -1;
new_tile_idx[new_pos_size - 1][2] = -1;
}
int ind_high, ind_low = -1;
if (orig_pos_1 > orig_pos_2) {
ind_high = bisect_high(&new_pos[0], new_pos_size, orig_pos_1);
if (orig_pos_2 > 0) {
ind_low = bisect(&new_pos[0], new_pos_size, orig_pos_2);
}
} else {
ind_high = bisect_high(&new_pos[0], new_pos_size, orig_pos_2);
if (orig_pos_1 > 0) {
ind_low = bisect(&new_pos[0], new_pos_size, orig_pos_1);
}
}
if (ind_low >= 0) {
for (i = ind_low + 1; i < ind_high; i++) {
for (k = 0; k < 3; k++) {
if (push_tile_neighbor_to_list_with_checking(tile_nbr_head, new_grid,
new_tile_idx[i][k]))
tiles_added++;
}
}
} else {
if (push_tile_neighbor_to_list_with_checking(tile_nbr_head, new_grid,
new_tile_idx[ind_high][0]))
tiles_added++;
}
return tiles_added;
}
/************************************************************************
find_closest_position:
In: surface grid of the first tile
first tile index
surface grid of the second tile
second (neighbor) tile index
Out: position of the product on the first tile that is closest
to the second tile. If the neighbor tiles have common edge
this position happens to be very close to the center of the
common edge but inward the first tile. If the neighbor tiles
have common vertex, this position happens to be very close to
to the vertex but inward the first tile.
*************************************************************************/
void find_closest_position(struct surface_grid *grid1, int idx1,
struct surface_grid *grid2, int idx2,
struct vector2 *p) {
/* vertices of the first tile */
struct vector2 R, S, T;
struct vector3 R_3d, S_3d, T_3d;
/* vertices of the second tile */
struct vector2 A, B, C;
struct vector3 A_3d, B_3d, C_3d;
/* vertices A,B,C in the coordinate system RST */
struct vector2 A_new, B_new, C_new;
/* the ratios in which we divide the segment */
double k1 = 1e-10; /* this is our good faith assumption */
double k2 = 1;
int flip1; /* flip information about first tile */
int flip2; /* flip information about second tile */
int num_exact_shared_vertices = 0;
/* flags */
int R_shared = 0, S_shared = 0, T_shared = 0;
int A_shared = 0, B_shared = 0, C_shared = 0;
/* find out the vertices of the first tile where we will put the product */
get_tile_vertices(grid1, idx1, &flip1, &R, &S, &T);
/* the code below tries to increase accuracy for the corner tiles */
if (is_corner_tile(grid1, idx1)) {
/* find out the shared vertex */
int shared_wall_vertex_id_1 = find_wall_vertex_for_corner_tile(grid1, idx1);
/* note that vertices R, S, T followed clockwise rule */
if (idx1 == 0) {
memcpy(&T_3d, grid1->surface->vert[shared_wall_vertex_id_1],
sizeof(struct vector3));
uv2xyz(&R, grid1->surface, &R_3d);
uv2xyz(&S, grid1->surface, &S_3d);
} else if ((u_int)idx1 == (grid1->n_tiles - 2 * (grid1->n) + 1)) {
memcpy(&R_3d, grid1->surface->vert[shared_wall_vertex_id_1],
sizeof(struct vector3));
uv2xyz(&S, grid1->surface, &S_3d);
uv2xyz(&T, grid1->surface, &T_3d);
} else {
memcpy(&S_3d, grid1->surface->vert[shared_wall_vertex_id_1],
sizeof(struct vector3));
uv2xyz(&R, grid1->surface, &R_3d);
uv2xyz(&T, grid1->surface, &T_3d);
}
} else {
uv2xyz(&R, grid1->surface, &R_3d);
uv2xyz(&S, grid1->surface, &S_3d);
uv2xyz(&T, grid1->surface, &T_3d);
}
/* find out the vertices of the second tile */
get_tile_vertices(grid2, idx2, &flip2, &A, &B, &C);
if (is_corner_tile(grid2, idx2)) {
/* find out the shared vertex */
int shared_wall_vertex_id_2 = find_wall_vertex_for_corner_tile(grid2, idx2);
/* note that vertices A, B, C followed clockwise rule */
if (idx2 == 0) {
memcpy(&C_3d, grid2->surface->vert[shared_wall_vertex_id_2],
sizeof(struct vector3));
uv2xyz(&A, grid2->surface, &A_3d);
uv2xyz(&B, grid2->surface, &B_3d);
} else if ((u_int)idx2 == (grid2->n_tiles - 2 * (grid2->n) + 1)) {
memcpy(&A_3d, grid2->surface->vert[shared_wall_vertex_id_2],
sizeof(struct vector3));
uv2xyz(&B, grid2->surface, &B_3d);
uv2xyz(&C, grid2->surface, &C_3d);
} else {
memcpy(&B_3d, grid2->surface->vert[shared_wall_vertex_id_2],
sizeof(struct vector3));
uv2xyz(&A, grid2->surface, &A_3d);
uv2xyz(&C, grid2->surface, &C_3d);
}
} else {
uv2xyz(&A, grid2->surface, &A_3d);
uv2xyz(&B, grid2->surface, &B_3d);
uv2xyz(&C, grid2->surface, &C_3d);
}
/* find shared vertices */
if (grid1 == grid2) {
if (!distinguishable_vec2(&R, &A, EPS_C) ||
(!distinguishable_vec2(&R, &B, EPS_C)) ||
(!distinguishable_vec2(&R, &C, EPS_C))) {
num_exact_shared_vertices++;
R_shared = 1;
}
if (!distinguishable_vec2(&S, &A, EPS_C) ||
(!distinguishable_vec2(&S, &B, EPS_C)) ||
(!distinguishable_vec2(&S, &C, EPS_C))) {
num_exact_shared_vertices++;
S_shared = 1;
}
if (!distinguishable_vec2(&T, &A, EPS_C) ||
(!distinguishable_vec2(&T, &B, EPS_C)) ||
(!distinguishable_vec2(&T, &C, EPS_C))) {
num_exact_shared_vertices++;
T_shared = 1;
}
} else {
/* below there are cases when the grid structures on the neighbor
walls are not shifted relative to one another */
if (!distinguishable_vec3(&R_3d, &A_3d, EPS_C) ||
(!distinguishable_vec3(&R_3d, &B_3d, EPS_C)) ||
(!distinguishable_vec3(&R_3d, &C_3d, EPS_C))) {
num_exact_shared_vertices++;
R_shared = 1;
}
if (!distinguishable_vec3(&S_3d, &A_3d, EPS_C) ||
(!distinguishable_vec3(&S_3d, &B_3d, EPS_C)) ||
(!distinguishable_vec3(&S_3d, &C_3d, EPS_C))) {
num_exact_shared_vertices++;
S_shared = 1;
}
if (!distinguishable_vec3(&T_3d, &A_3d, EPS_C) ||
(!distinguishable_vec3(&T_3d, &B_3d, EPS_C)) ||
(!distinguishable_vec3(&T_3d, &C_3d, EPS_C))) {
num_exact_shared_vertices++;
T_shared = 1;
}
}
if (num_exact_shared_vertices == 1) {
if (R_shared) {
place_product_shared_vertex(&R, &S, &T, p, k1, k2);
return;
} else if (S_shared) {
place_product_shared_vertex(&S, &R, &T, p, k1, k2);
return;
} else { /*T is shared */
place_product_shared_vertex(&T, &R, &S, p, k1, k2);
return;
}
}
if (num_exact_shared_vertices == 2) {
if (R_shared && S_shared) {
place_product_shared_segment(&R, &S, &T, p, k1, k2);
return;
} else if (R_shared && T_shared) {
place_product_shared_segment(&R, &T, &S, p, k1, k2);
return;
} else { /*S_shared and T_shared */
place_product_shared_segment(&S, &T, &R, p, k1, k2);
return;
}
}
if (num_exact_shared_vertices == 0) {
/* below are the cases when the grids on the neighbor walls
are shifted relative to one another */
/* find out whether the vertices of one tile cross the sides of
another tile */
if ((intersect_point_segment(&S_3d, &A_3d, &B_3d)) ||
(intersect_point_segment(&S_3d, &B_3d, &C_3d)) ||
(intersect_point_segment(&S_3d, &A_3d, &C_3d))) {
S_shared = 1;
}
if ((intersect_point_segment(&R_3d, &A_3d, &B_3d)) ||
(intersect_point_segment(&R_3d, &B_3d, &C_3d)) ||
(intersect_point_segment(&R_3d, &A_3d, &C_3d))) {
R_shared = 1;
}
if ((intersect_point_segment(&T_3d, &A_3d, &B_3d)) ||
(intersect_point_segment(&T_3d, &B_3d, &C_3d)) ||
(intersect_point_segment(&T_3d, &A_3d, &C_3d))) {
T_shared = 1;
}
if ((intersect_point_segment(&A_3d, &R_3d, &S_3d)) ||
(intersect_point_segment(&A_3d, &S_3d, &T_3d)) ||
(intersect_point_segment(&A_3d, &R_3d, &T_3d))) {
A_shared = 1;
}
if ((intersect_point_segment(&B_3d, &R_3d, &S_3d)) ||
(intersect_point_segment(&B_3d, &S_3d, &T_3d)) ||
(intersect_point_segment(&B_3d, &R_3d, &T_3d))) {
B_shared = 1;
}
if ((intersect_point_segment(&C_3d, &R_3d, &S_3d)) ||
(intersect_point_segment(&C_3d, &S_3d, &T_3d)) ||
(intersect_point_segment(&C_3d, &R_3d, &T_3d))) {
C_shared = 1;
}
/* two vertices shared from the same tile */
if (R_shared && S_shared) {
place_product_shared_segment(&R, &S, &T, p, k1, k2);
return;
} else if (R_shared && T_shared) {
place_product_shared_segment(&R, &T, &S, p, k1, k2);
return;
} else if (S_shared && T_shared) {
place_product_shared_segment(&S, &T, &R, p, k1, k2);
return;
}
/* two vertices shared from the same tile */
if (A_shared && B_shared) {
if (parallel_segments(&A_3d, &B_3d, &R_3d, &S_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
xyz2uv(&B_3d, grid1->surface, &B_new);
place_product_shared_segment(&A_new, &B_new, &T, p, k1, k2);
return;
} else if (parallel_segments(&A_3d, &B_3d, &R_3d, &T_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
xyz2uv(&B_3d, grid1->surface, &B_new);
place_product_shared_segment(&A_new, &B_new, &S, p, k1, k2);
return;
} else if (parallel_segments(&A_3d, &B_3d, &S_3d, &T_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
xyz2uv(&B_3d, grid1->surface, &B_new);
place_product_shared_segment(&A_new, &B_new, &R, p, k1, k2);
return;
}
} else if (A_shared && C_shared) {
if (parallel_segments(&A_3d, &C_3d, &R_3d, &S_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&A_new, &C_new, &T, p, k1, k2);
return;
} else if (parallel_segments(&A_3d, &C_3d, &R_3d, &T_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&A_new, &C_new, &S, p, k1, k2);
return;
} else if (parallel_segments(&A_3d, &C_3d, &S_3d, &T_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&A_new, &C_new, &R, p, k1, k2);
return;
}
} else if (B_shared && C_shared) {
if (parallel_segments(&B_3d, &C_3d, &R_3d, &S_3d)) {
xyz2uv(&B_3d, grid1->surface, &B_new);
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&B_new, &C_new, &T, p, k1, k2);
return;
} else if (parallel_segments(&B_3d, &C_3d, &R_3d, &T_3d)) {
xyz2uv(&B_3d, grid1->surface, &B_new);
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&B_new, &C_new, &S, p, k1, k2);
return;
} else if (parallel_segments(&B_3d, &C_3d, &S_3d, &T_3d)) {
xyz2uv(&B_3d, grid1->surface, &B_new);
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&B_new, &C_new, &R, p, k1, k2);
return;
}
}
/* one vertex shared from each tile */
if (R_shared) {
if (A_shared) {
if (parallel_segments(&R_3d, &A_3d, &R_3d, &S_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
place_product_shared_segment(&A_new, &R, &T, p, k1, k2);
return;
} else if (parallel_segments(&R_3d, &A_3d, &R_3d, &T_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
place_product_shared_segment(&A_new, &R, &S, p, k1, k2);
return;
}
} else if (B_shared) {
if (parallel_segments(&R_3d, &B_3d, &R_3d, &S_3d)) {
xyz2uv(&B_3d, grid1->surface, &B_new);
place_product_shared_segment(&B_new, &R, &T, p, k1, k2);
return;
} else if (parallel_segments(&R_3d, &B_3d, &R_3d, &T_3d)) {
xyz2uv(&B_3d, grid1->surface, &B_new);
place_product_shared_segment(&B_new, &R, &S, p, k1, k2);
return;
}
} else if (C_shared) {
if (parallel_segments(&R_3d, &C_3d, &R_3d, &S_3d)) {
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&C_new, &R, &T, p, k1, k2);
return;
} else if (parallel_segments(&R_3d, &C_3d, &R_3d, &T_3d)) {
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&C_new, &R, &S, p, k1, k2);
return;
}
} else {
place_product_shared_vertex(&R, &S, &T, p, k1, k2);
return;
}
} else if (S_shared) {
if (A_shared) {
if (parallel_segments(&S_3d, &A_3d, &S_3d, &T_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
place_product_shared_segment(&A_new, &S, &R, p, k1, k2);
return;
} else if (parallel_segments(&S_3d, &A_3d, &S_3d, &R_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
place_product_shared_segment(&A_new, &S, &T, p, k1, k2);
return;
}
} else if (B_shared) {
if (parallel_segments(&S_3d, &B_3d, &S_3d, &T_3d)) {
xyz2uv(&B_3d, grid1->surface, &B_new);
place_product_shared_segment(&B_new, &S, &R, p, k1, k2);
return;
} else if (parallel_segments(&S_3d, &B_3d, &S_3d, &R_3d)) {
xyz2uv(&B_3d, grid1->surface, &B_new);
place_product_shared_segment(&B_new, &S, &T, p, k1, k2);
return;
}
} else if (C_shared) {
if (parallel_segments(&S_3d, &C_3d, &S_3d, &T_3d)) {
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&C_new, &S, &R, p, k1, k2);
return;
} else if (parallel_segments(&S_3d, &C_3d, &S_3d, &R_3d)) {
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&C_new, &S, &T, p, k1, k2);
return;
}
} else {
place_product_shared_vertex(&S, &R, &T, p, k1, k2);
return;
}
} else if (T_shared) {
if (A_shared) {
if (parallel_segments(&T_3d, &A_3d, &T_3d, &S_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
place_product_shared_segment(&A_new, &T, &R, p, k1, k2);
return;
} else if (parallel_segments(&T_3d, &A_3d, &T_3d, &R_3d)) {
xyz2uv(&A_3d, grid1->surface, &A_new);
place_product_shared_segment(&A_new, &T, &S, p, k1, k2);
return;
}
} else if (B_shared) {
if (parallel_segments(&T_3d, &B_3d, &T_3d, &S_3d)) {
xyz2uv(&B_3d, grid1->surface, &B_new);
place_product_shared_segment(&B_new, &T, &R, p, k1, k2);
return;
} else if (parallel_segments(&T_3d, &B_3d, &T_3d, &R_3d)) {
xyz2uv(&B_3d, grid1->surface, &B_new);
place_product_shared_segment(&B_new, &T, &S, p, k1, k2);
return;
}
} else if (C_shared) {
if (parallel_segments(&T_3d, &C_3d, &T_3d, &S_3d)) {
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&C_new, &T, &R, p, k1, k2);
return;
} else if (parallel_segments(&T_3d, &C_3d, &T_3d, &R_3d)) {
xyz2uv(&C_3d, grid1->surface, &C_new);
place_product_shared_segment(&C_new, &T, &S, p, k1, k2);
return;
}
} else {
place_product_shared_vertex(&T, &R, &S, p, k1, k2);
return;
}
}
/* only one vertex is shared */
if (A_shared) {
xyz2uv(&A_3d, grid1->surface, &A_new);
if (intersect_point_segment(&A_3d, &R_3d, &S_3d)) {
place_product_close_to_segment_endpoint(&T, &A_new, p, k1, k2);
return;
} else if (intersect_point_segment(&A_3d, &R_3d, &T_3d)) {
place_product_close_to_segment_endpoint(&S, &A_new, p, k1, k2);
return;
} else if (intersect_point_segment(&A_3d, &S_3d, &T_3d)) {
place_product_close_to_segment_endpoint(&R, &A_new, p, k1, k2);
return;
}
} else if (B_shared) {
xyz2uv(&B_3d, grid1->surface, &B_new);
if (intersect_point_segment(&B_3d, &R_3d, &S_3d)) {
place_product_close_to_segment_endpoint(&T, &B_new, p, k1, k2);
return;
} else if (intersect_point_segment(&B_3d, &R_3d, &T_3d)) {
place_product_close_to_segment_endpoint(&S, &B_new, p, k1, k2);
return;
} else if (intersect_point_segment(&B_3d, &S_3d, &T_3d)) {
place_product_close_to_segment_endpoint(&R, &B_new, p, k1, k2);
return;
}
} else if (C_shared) {
xyz2uv(&C_3d, grid1->surface, &C_new);
if (intersect_point_segment(&C_3d, &R_3d, &S_3d)) {
place_product_close_to_segment_endpoint(&T, &C_new, p, k1, k2);
return;
} else if (intersect_point_segment(&C_3d, &R_3d, &T_3d)) {
place_product_close_to_segment_endpoint(&S, &C_new, p, k1, k2);
return;
} else if (intersect_point_segment(&C_3d, &S_3d, &T_3d)) {
place_product_close_to_segment_endpoint(&R, &C_new, p, k1, k2);
return;
}
}
} /* end if (num_exact_shared_vertices == 0) */
/* Apparently there are some round-up errors that force
the code to come to this place. Below we will try
again to place the product. */
/* find points on the triangle RST that are closest to A, B, C */
struct vector3 A_close_3d, B_close_3d, C_close_3d;
double dist_A_A_close_3d, dist_B_B_close_3d, dist_C_C_close_3d, min_dist;
struct vector3 prod_pos_3d;
struct vector2 prod_pos;
closest_pt_point_triangle(&A_3d, &R_3d, &S_3d, &T_3d, &A_close_3d);
closest_pt_point_triangle(&B_3d, &R_3d, &S_3d, &T_3d, &B_close_3d);
closest_pt_point_triangle(&C_3d, &R_3d, &S_3d, &T_3d, &C_close_3d);
dist_A_A_close_3d = distance_vec3(&A_3d, &A_close_3d);
dist_B_B_close_3d = distance_vec3(&B_3d, &B_close_3d);
dist_C_C_close_3d = distance_vec3(&C_3d, &C_close_3d);
min_dist = min3d(dist_A_A_close_3d, dist_B_B_close_3d, dist_C_C_close_3d);
if (!distinguishable(min_dist, dist_A_A_close_3d, EPS_C)) {
prod_pos_3d.x = A_close_3d.x;
prod_pos_3d.y = A_close_3d.y;
prod_pos_3d.z = A_close_3d.z;
} else if (!distinguishable(min_dist, dist_B_B_close_3d, EPS_C)) {
prod_pos_3d.x = B_close_3d.x;
prod_pos_3d.y = B_close_3d.y;
prod_pos_3d.z = B_close_3d.z;
} else {
prod_pos_3d.x = C_close_3d.x;
prod_pos_3d.y = C_close_3d.y;
prod_pos_3d.z = C_close_3d.z;
}
xyz2uv(&prod_pos_3d, grid1->surface, &prod_pos);
if (intersect_point_segment(&prod_pos_3d, &R_3d, &S_3d)) {
place_product_close_to_segment_endpoint(&T, &prod_pos, p, k1, k2);
return;
} else if (intersect_point_segment(&prod_pos_3d, &R_3d, &T_3d)) {
place_product_close_to_segment_endpoint(&S, &prod_pos, p, k1, k2);
return;
} else if (intersect_point_segment(&prod_pos_3d, &S_3d, &T_3d)) {
place_product_close_to_segment_endpoint(&R, &prod_pos, p, k1, k2);
return;
} else {
p->u = prod_pos.u;
p->v = prod_pos.v;
return;
}
/* I should not come here... */
mcell_internal_error("Error in the function 'find_closest_position()'.");
}
/*****************************************************************************
is_inner_tile:
In: Surface grid
Index of the tile on that grid
Out: Returns 1 if the tile is an inner tile
(not on the border with the neighbor walls).
Returns 0 if the tile is on the border with the neighbor wall.
*****************************************************************************/
int is_inner_tile(struct surface_grid *g, int idx) {
int root, rootrem, strip, stripe, flip;
root = (int)(sqrt((double)idx));
rootrem = idx - root * root;
strip = g->n - root - 1;
stripe = rootrem / 2;
flip = rootrem - 2 * stripe;
if ((strip == 0) || (stripe == 0))
return 0;
if ((strip + stripe) == g->n - 1) {
return 0;
}
if (((strip + stripe) == g->n - 2) && (flip == 1)) {
return 0;
}
return 1;
}
/*****************************************************************************
is_corner_tile:
In: Surface grid
Index of the tile on that grid
Out: Returns 1 if the tile is a corner tile
(there are only three corners on each wall).
Returns 0 if the tile is not a corner tile.
*****************************************************************************/
int is_corner_tile(struct surface_grid *g, int idx) {
/* tile index at the wall corner with vertex 0 */
int tile_idx_mid = g->n_tiles - 2 * (g->n) + 1;
if ((idx == 0) || ((u_int)idx == (g->n_tiles - 1)))
return 1;
if (idx == tile_idx_mid)
return 1;
return 0;
}
/*****************************************************************************
find_shared_vertices_corner_tile_parent_wall:
In: Surface grid
Index of the tile on that grid
3-member array of indices (in the global array "walls_using_vertex"
of parent wall vertices that are shared with other walls
(return value)
Out: Returns 3-member array of the indices of parent wall vertices
in the global "world->walls_using_vertex" array
that are shared with other neighbor walls.
If the wall vertex is not shared the corresponding value
in the return array is not set.
Note: Used only for corner tiles. Here some of the tile vertices
coincide with the wall vertices which in turn may be shared
with the neighbor walls.
*****************************************************************************/
void find_shared_vertices_corner_tile_parent_wall(struct volume *world,
struct surface_grid *sg,
int idx,
long long int *shared_vert) {
long long global_vert_index;
struct vector3 *v;
if (!world->create_shared_walls_info_flag)
mcell_internal_error("Function "
"'find_shared_vertices_corner_tile_parent_wall()' is "
"called but shared walls information is not created.");
/* check if we are at vertex 0 */
if ((u_int)idx == (sg->n_tiles - 2 * (sg->n) + 1)) {
v = sg->surface->vert[0];
global_vert_index = (long long)(v - world->all_vertices);
if (world->walls_using_vertex[global_vert_index] != NULL) {
shared_vert[0] = global_vert_index;
}
}
/* check if we are at vertex 1 */
if ((u_int)idx == (sg->n_tiles - 1)) {
v = sg->surface->vert[1];
global_vert_index = (long long)(v - world->all_vertices);
if (world->walls_using_vertex[global_vert_index] != NULL) {
shared_vert[1] = global_vert_index;
}
}
/* check if we are at vertex 2 */
if ((u_int)idx == 0) {
v = sg->surface->vert[2];
global_vert_index = (long long)(v - world->all_vertices);
if (world->walls_using_vertex[global_vert_index] != NULL) {
shared_vert[2] = global_vert_index;
}
}
}
/*****************************************************************************
move_strip_up:
In: Wall surface grid and tile index on that grid
Out: Returns index of the tile that is exactly above the tile
with index "idx". Both "idx" and return index should be
on the same surface grid.
Returns (-1) if there is no such tile that satisfies the above
condition (e.g. when the "idx" tile is in the (strip == 0).)
Note: The direction "up" means moving to the strip where tile indices
are greater than index "idx".
*****************************************************************************/
int move_strip_up(struct surface_grid *grid, int idx) {
int root;
int tile_up_idx; /* return value */
root = (int)(sqrt((double)idx)) + 1;
if (grid->n == root) {
/* tile above is on another wall */
tile_up_idx = -1;
} else {
tile_up_idx = idx + 2 * root;
}
return tile_up_idx;
}
/*****************************************************************************
move_strip_down:
In: Wall surface grid and tile index on that grid
Out: Returns index of the tile that is exactly below the tile
with index "idx". Both "idx" and return index should be
on the same surface grid. Both "idx" and "tile down"
should share the side.
Returns (-1) if there is no such tile that satisfies the above
conditions.
Note: The direction "down" means moving to the strip where tile indices
are less than index "idx".
*****************************************************************************/
int move_strip_down(struct surface_grid *grid, int idx) {
int root, rootrem, strip, stripe, flip;
int num_tiles_per_strip;
int tile_down_idx; /* return value */
/* find internal coordinates (strip, stripe, flip) */
root = (int)(sqrt((double)idx));
rootrem = idx - root * root;
strip = grid->n - root - 1;
stripe = rootrem / 2;
flip = rootrem - 2 * stripe;
num_tiles_per_strip = 2 * (grid->n) - 2 * strip - 1;
if (is_inner_tile(grid, idx)) {
tile_down_idx = idx - num_tiles_per_strip + 1;
} else {
if ((strip == 0) && (stripe > 0)) {
if ((unsigned int)idx == grid->n_tiles - 1) {
tile_down_idx = -1;
} else {
tile_down_idx = idx - num_tiles_per_strip + 1;
}
} else {
/* here we are at the left or right border layers */
if (flip == 0) {
tile_down_idx = -1;
} else {
tile_down_idx = idx - num_tiles_per_strip + 1;
}
}
}
return tile_down_idx;
}
/*****************************************************************************
place_product_shared_segment:
In: segment defined by points R_shared and S_shared
point T
position of the product (return value)
ratios k1 and k2
Out: coordinates of the point "prod" dividing the distance between T
and midpont on (R_shared, S_shared) in the ratio k1:k2, so that
midpoint_prod/midpoint_T = k1/k2
Note: all points are on the plane
******************************************************************************/
void place_product_shared_segment(struct vector2 *R_shared,
struct vector2 *S_shared, struct vector2 *T,
struct vector2 *prod, double k1, double k2) {
struct vector2 M; /* midpoint */
/* find midpoint on the segment (R_shared - S_shared) */
M.u = 0.5 * (R_shared->u + S_shared->u);
M.v = 0.5 * (R_shared->v + S_shared->v);
/* find coordinates of the point such that internally
divides the segment TM in the ratio (k1:k2)
We want to place the product close to the common edge.
*/
prod->u = (k1 * T->u + k2 * M.u) / (k1 + k2);
prod->v = (k1 * T->v + k2 * M.v) / (k1 + k2);
}
/*****************************************************************************
place_product_shared_vertex:
In: point R_shared
segment defined by points S and T
position of the product (return value)
ratios k1 and k2
Out: coordinates of the point "prod" dividing the distance between R_shared
and midpont on (S, T) in the ratio k1:k2, so that
R_shared_prod/prod_midpoint = k1/k2
Note: all points are on the plane
******************************************************************************/
void place_product_shared_vertex(struct vector2 *R_shared, struct vector2 *S,
struct vector2 *T, struct vector2 *prod,
double k1, double k2) {
struct vector2 M; /* midpoint */
/* find midpoint on the segment ST */
M.u = 0.5 * (S->u + T->u);
M.v = 0.5 * (S->v + T->v);
/* find coordinates of the point such that internally
divides the segment RM in the ratio (k1:k2)
*/
prod->u = (k1 * M.u + k2 * R_shared->u) / (k1 + k2);
prod->v = (k1 * M.v + k2 * R_shared->v) / (k1 + k2);
}
/*****************************************************************************
place_product_close_to_segment_endpoint:
In: segment defined by points S (start) and E (end)
position of the product (return value)
ratios k1 and k2
Out: coordinates of the point "prod" dividing the distance between S and E
in the ratio k1:k2, so that E_prod/S_prod = k1/k2
Note: all points are on the plane
******************************************************************************/
void place_product_close_to_segment_endpoint(struct vector2 *S,
struct vector2 *E,
struct vector2 *prod, double k1,
double k2) {
prod->u = (k1 * S->u + k2 * E->u) / (k1 + k2);
prod->v = (k1 * S->v + k2 * E->v) / (k1 + k2);
}
/***************************************************************************
append_tile_neighbor_list:
In: linked list of neighbor tiles head1
linked list of neighbor tiles head2
Out: list "head2" is appended to the list "head1"
The original "head2" head is set to NULL
***************************************************************************/
void append_tile_neighbor_list(struct tile_neighbor **head1,
struct tile_neighbor **head2) {
struct tile_neighbor *curr;
if (*head1 == NULL) /* special case if "head1" is empty */
{
*head1 = *head2;
} else {
curr = *head1;
while (curr->next != NULL) /* find the last node */
{
curr = curr->next;
}
curr->next = *head2;
}
*head2 = NULL;
}
/****************************************************************************
find_wall_vertex_for_corner_tile:
In: surface grid
tile index on the grid
Out: corner tile should share one of it's vertices with the wall.
Returns the shared wall vertex id (index in the array wall_vert[])
****************************************************************************/
int find_wall_vertex_for_corner_tile(struct surface_grid *grid, int idx) {
/* index of the wall vertex that is shared with the tile vertex */
int vertex_id = 0;
if (!is_corner_tile(grid, idx))
mcell_internal_error("Function 'find_wall_vertex_for_corner_tile()' is "
"called for the tile that is not the corner tile.");
if ((u_int)idx == (grid->n_tiles - 2 * (grid->n) + 1)) {
vertex_id = 0;
} else if ((u_int)idx == (grid->n_tiles - 1)) {
vertex_id = 1;
} else if (idx == 0) {
vertex_id = 2;
} else {
mcell_internal_error("Function 'find_wall_vertex_for_corner_tile()' is "
"called for the tile that is not the corner tile.");
}
return vertex_id;
}
/***********************************************************************
find_shared_vertices_for_neighbor_walls:
In: original wall
neighbor wall
index of the neighbor wall vertex that is
shared with original wall (return value)
index of the neighbor wall vertex that is
shared with original wall (return value)
Out: neighbor wall shared vertices indices are set up.
***********************************************************************/
void find_shared_vertices_for_neighbor_walls(struct wall *orig_wall,
struct wall *nb_wall,
int *shared_vert_1,
int *shared_vert_2) {
if ((!distinguishable_vec3(nb_wall->vert[0], orig_wall->vert[0], EPS_C)) ||
(!distinguishable_vec3(nb_wall->vert[0], orig_wall->vert[1], EPS_C)) ||
(!distinguishable_vec3(nb_wall->vert[0], orig_wall->vert[2], EPS_C))) {
*shared_vert_1 = 0;
}
if ((!distinguishable_vec3(nb_wall->vert[1], orig_wall->vert[0], EPS_C)) ||
(!distinguishable_vec3(nb_wall->vert[1], orig_wall->vert[1], EPS_C)) ||
(!distinguishable_vec3(nb_wall->vert[1], orig_wall->vert[2], EPS_C))) {
if (*shared_vert_1 < 0) {
*shared_vert_1 = 1;
} else {
*shared_vert_2 = 1;
}
}
if ((!distinguishable_vec3(nb_wall->vert[2], orig_wall->vert[0], EPS_C)) ||
(!distinguishable_vec3(nb_wall->vert[2], orig_wall->vert[1], EPS_C)) ||
(!distinguishable_vec3(nb_wall->vert[2], orig_wall->vert[2], EPS_C))) {
if (*shared_vert_1 < 0) {
*shared_vert_1 = 2;
} else {
*shared_vert_2 = 2;
}
}
}
/**************************************************************************
find_neighbor_tiles:
In: a surface molecule
surface grid of the wall where hit happens, or
surface molecule is located
index of the tile where hit happens, or surface molecule is located
flag that tells whether we need to create a grid on a neighbor wall
flag that tells whether we are searching for reactant
(value = 1) or doing product placement (value = 0)
a linked list of neighbor tiles (return value)
a length of the linked list above (return value)
Out: The list of nearest neighbors are returned,
Neighbors should share either common edge or common vertex.
Note: This version allows looking for the neighbors at the neighbor walls
that are connected to the start wall through vertices only.
****************************************************************************/
void find_neighbor_tiles(struct volume *world, struct surface_molecule *sm,
struct surface_grid *grid, int idx,
int create_grid_flag, int search_for_reactant,
struct tile_neighbor **tile_nbr_head,
int *list_length) {
int kk;
struct tile_neighbor *tile_nbr_head_vert = NULL, *tmp_head = NULL;
int list_length_vert = 0; /* length of the linked list */
int tmp_list_length = 0; /* length of the linked list */
struct vector2 pos; /* center of the tile */
/* corner tile may have one or more vertices that coincide with
the wall vertices which can be shared with the neighbor walls */
long long shared_vert[3]; /* indices of the vertices of the parent wall
in the global array "world->walls_using_vertex"
that are shared with the neighbor walls
(used only for the corner tile) */
struct wall_list *wall_nbr_head = NULL; /* linked list of neighbor walls */
for (kk = 0; kk < 3; kk++) {
shared_vert[kk] = -1;
}
if (is_inner_tile(grid, idx)) {
grid2uv(grid, idx, &pos);
grid_all_neighbors_for_inner_tile(world, grid, idx, &pos, &tmp_head,
&tmp_list_length);
} else {
if (is_corner_tile(grid, idx)) {
/* find tile vertices that are shared with the parent wall */
find_shared_vertices_corner_tile_parent_wall(world, grid, idx,
shared_vert);
/* create list of neighbor walls that share one vertex
with the start tile (not edge-to-edge neighbor walls) */
wall_nbr_head =
find_nbr_walls_shared_one_vertex(world, grid->surface, shared_vert);
if (wall_nbr_head != NULL) {
grid_all_neighbors_across_walls_through_vertices(
world, sm, wall_nbr_head, grid, create_grid_flag,
search_for_reactant, &tile_nbr_head_vert, &list_length_vert);
}
if (wall_nbr_head != NULL) {
delete_wall_list(wall_nbr_head);
wall_nbr_head = NULL;
}
grid_all_neighbors_across_walls_through_edges(
world, sm, grid, idx, create_grid_flag, search_for_reactant,
&tmp_head, &tmp_list_length);
} else {
grid_all_neighbors_across_walls_through_edges(
world, sm, grid, idx, create_grid_flag, search_for_reactant,
&tmp_head, &tmp_list_length);
}
}
if (tile_nbr_head_vert != NULL) {
append_tile_neighbor_list(&tmp_head, &tile_nbr_head_vert);
tmp_list_length += list_length_vert;
}
*tile_nbr_head = tmp_head;
*list_length = tmp_list_length;
#ifdef DEBUG_GRIDS
dump_tile_neighbors_list(*tile_nbr_head, __FUNCTION__, " ");
#endif
}
| C |
3D | mcellteam/mcell | src/react_outc.c | .c | 72,235 | 1,838 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <vector>
#include "logging.h"
#include "rng.h"
#include "util.h"
#include "grid_util.h"
#include "count_util.h"
#include "react.h"
#include "vol_util.h"
#include "wall_util.h"
#include "nfsim_func.h"
#include "mcell_reactions.h"
#include "diffuse.h"
#include "debug_config.h"
#include "debug.h"
#include "dump_state.h"
static int outcome_products_random(struct volume *world, struct wall *w,
struct vector3 *hitpt, double t,
struct rxn *rx, int path,
struct abstract_molecule *reacA,
struct abstract_molecule *reacB,
short orientA, short orientB);
static int cleanup_and_block_rx(struct tile_neighbor *tn1, struct tile_neighbor *tn2);
int is_compatible_surface(void *req_species, struct wall *w) {
struct surf_class_list *scl, *scl2;
struct surf_class_list *rs_head = (struct surf_class_list *)req_species;
if (rs_head == NULL)
return 1;
for (scl = w->surf_class_head; scl != NULL; scl = scl->next) {
for (scl2 = rs_head; scl2 != NULL; scl2 = scl2->next) {
if (scl->surf_class == scl2->surf_class)
return 1;
}
}
return 0;
}
void add_reactants_to_product_list(struct rxn *rx, struct abstract_molecule *reacA,
struct abstract_molecule *reacB, struct abstract_molecule *reacC,
struct abstract_molecule **player, char *player_type) {
/* Add reacA to the list of players, saving the reactant's type. */
player[0] = reacA;
player_type[0] = IS_SURF_MOL(reacA) ? PLAYER_SURF_MOL : PLAYER_VOL_MOL;
/* If we have a second reactant, add it to the list of players. */
if (rx->n_reactants > 1) {
/* If the second reactant is a wall... */
if (reacB == NULL) {
assert(rx->n_reactants == 2);
player[1] = NULL;
player_type[1] = PLAYER_WALL;
} else { // else 2nd reactant is a wall
player[1] = reacB;
player_type[1] = IS_SURF_MOL(reacB) ? PLAYER_SURF_MOL : PLAYER_VOL_MOL;
}
if (rx->n_reactants > 2) {
if (reacC == NULL) {
/* it's a wall. */
player[2] = NULL;
player_type[2] = PLAYER_WALL;
} else {
player[2] = reacC;
player_type[2] = IS_SURF_MOL(reacC) ? PLAYER_SURF_MOL : PLAYER_VOL_MOL;
}
}
}
}
static bool is_rxn_unimol(struct rxn *rx) {
if (rx->n_reactants == 1)
return true;
if (rx->n_reactants != 2)
return false;
if (!(rx->players[0]->flags & ON_GRID))
return false;
return (rx->players[1]->flags & IS_SURFACE) != 0;
}
void tiny_diffuse_3D(
struct volume *world,
struct subvolume *subvol,
struct vector3 *displacement,
struct vector3 *pos,
struct wall *w) {
struct vector3 temp_displacement = {
displacement->x,
displacement->y,
displacement->z
};
struct collision *shead = ray_trace(
world, pos, NULL, subvol, &temp_displacement, w);
if (shead->next != NULL) {
shead = (struct collision *)ae_list_sort((struct abstract_element *)shead);
}
struct collision *smash = NULL;
for (smash = shead; smash != NULL; smash = smash->next) {
if ((smash->what & COLLIDE_WALL) != 0) {
vectorize(pos, &(smash->loc), displacement);
scalar_prod(displacement, 0.5, displacement);
break;
}
}
pos->x += displacement->x;
pos->y += displacement->y;
pos->z += displacement->z;
subvol = find_subvolume(world, pos, subvol);
}
struct volume_molecule *
place_volume_product(struct volume *world, struct species *product_species, struct graph_data* graph,
struct surface_molecule *sm_reactant, struct wall *w,
struct subvolume *subvol, struct vector3 *hitpt,
short orient, double t, struct periodic_image *periodic_box) {
struct vector3 pos = *hitpt;
/* For an orientable reaction, we need to move products away from the surface
* to ensure they end up on the correct side of the plane. */
if (w) {
double bump = (orient > 0) ? EPS_C : -EPS_C;
struct vector3 displacement = {2 * bump * w->normal.x,
2 * bump * w->normal.y,
2 * bump * w->normal.z,
};
tiny_diffuse_3D(world, subvol, &displacement, &pos, w);
}
/* Allocate and initialize the molecule. */
struct volume_molecule *new_volume_mol;
new_volume_mol =
(struct volume_molecule *)CHECKED_MEM_GET(subvol->local_storage->mol, "volume molecule");
new_volume_mol->birthplace = subvol->local_storage->mol;
new_volume_mol->birthday = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, t);
new_volume_mol->id = world->current_mol_id++;
new_volume_mol->t = t;
new_volume_mol->t2 = 0.0;
new_volume_mol->periodic_box = CHECKED_MALLOC_STRUCT(struct periodic_image,
"periodic image descriptor");
new_volume_mol->periodic_box->x = periodic_box->x;
new_volume_mol->periodic_box->y = periodic_box->y;
new_volume_mol->periodic_box->z = periodic_box->z;
new_volume_mol->properties = product_species;
new_volume_mol->graph_data = graph;
initialize_diffusion_function((struct abstract_molecule*) new_volume_mol);
new_volume_mol->prev_v = NULL;
new_volume_mol->next_v = NULL;
new_volume_mol->pos = pos;
new_volume_mol->subvol = subvol;
new_volume_mol->index = 0;
new_volume_mol->flags = TYPE_VOL | ACT_NEWBIE | IN_VOLUME | IN_SCHEDULE;
//if the molecule is extern then inherit the reactant's diffusion.
//XXX: is this the best way?
if (new_volume_mol->get_space_step(new_volume_mol) > 0.0)
new_volume_mol->flags |= ACT_DIFFUSE;
if ((product_species->flags & COUNT_SOME_MASK) != 0)
new_volume_mol->flags |= COUNT_ME;
/* Check whether the product can undergo unimolecular rxns; if so, mark it. */
if (trigger_unimolecular(world->reaction_hash, world->rx_hashsize,
product_species->hashval,
(struct abstract_molecule *)new_volume_mol) != NULL)
new_volume_mol->flags |= ACT_REACT;
/* If this product resulted from a surface rxn, store the previous wall
* position. */
if (sm_reactant && distinguishable(new_volume_mol->get_diffusion(new_volume_mol), 0, EPS_C)) {
new_volume_mol->previous_wall = sm_reactant->grid->surface;
/* This will be overwritten with orientation in the CLAMPED/surf.
* reversibility case
*/
new_volume_mol->index = sm_reactant->grid_index;
}
/* Else clear the previous wall position. */
else {
new_volume_mol->previous_wall = NULL;
new_volume_mol->index = -1;
}
/* Set reversibility state for the new molecule. */
if (w) {
if (world->surface_reversibility) {
/* Which direction did we move? */
new_volume_mol->previous_wall = w;
new_volume_mol->index = (orient > 0) ? 1 : -1;
new_volume_mol->flags |= ACT_CLAMPED;
}
} else if (world->volume_reversibility) {
new_volume_mol->index = world->dissociation_index;
new_volume_mol->flags |= ACT_CLAMPED;
}
/* Add the molecule to the subvolume */
ht_add_molecule_to_list(&new_volume_mol->subvol->mol_by_species,
new_volume_mol);
++new_volume_mol->subvol->mol_count;
/* Add to the schedule. */
if (schedule_add_mol(subvol->local_storage->timer, new_volume_mol))
mcell_allocfailed("Failed to add newly created %s molecule to scheduler.",
product_species->sym->name);
return new_volume_mol;
}
struct surface_molecule *
place_sm_product(struct volume *world, struct species *product_species, struct graph_data* graph,
struct surface_grid *grid, int grid_index,
struct vector2 *mol_uv_pos, short orient, double t,
struct periodic_image *periodic_box) {
struct vector3 mol_xyz_pos;
uv2xyz(mol_uv_pos, grid->surface, &mol_xyz_pos);
struct subvolume *sv = find_subvolume(world, &mol_xyz_pos, grid->subvol);
/* Allocate and initialize the molecule. */
struct surface_molecule *new_surf_mol;
new_surf_mol = (struct surface_molecule *)CHECKED_MEM_GET(sv->local_storage->smol, "surface molecule");
new_surf_mol->birthplace = sv->local_storage->smol;
new_surf_mol->birthday = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, t);
new_surf_mol->id = world->current_mol_id++;
new_surf_mol->t = t;
new_surf_mol->t2 = 0.0;
new_surf_mol->properties = product_species;
//nfsim graph init
new_surf_mol->graph_data = graph;
initialize_diffusion_function((struct abstract_molecule*) new_surf_mol);
new_surf_mol->periodic_box = CHECKED_MALLOC_STRUCT(struct periodic_image,
"periodic image descriptor");
new_surf_mol->periodic_box->x = periodic_box->x;
new_surf_mol->periodic_box->y = periodic_box->y;
new_surf_mol->periodic_box->z = periodic_box->z;
new_surf_mol->flags = TYPE_SURF | ACT_NEWBIE | IN_SCHEDULE;
if (new_surf_mol->get_space_step(new_surf_mol) > 0)
new_surf_mol->flags |= ACT_DIFFUSE;
if (product_species->flags & COUNT_ENCLOSED)
new_surf_mol->flags |= COUNT_ME;
new_surf_mol->grid = grid;
new_surf_mol->grid_index = grid_index;
new_surf_mol->s_pos = *mol_uv_pos;
new_surf_mol->orient = orient;
/* Check whether the product can undergo unimolecular rxns; if so, mark it. */
if (trigger_unimolecular(world->reaction_hash, world->rx_hashsize,
product_species->hashval,
(struct abstract_molecule *)new_surf_mol) != NULL ||
(product_species->flags & CAN_SURFWALL) != 0)
new_surf_mol->flags |= ACT_REACT;
/* Add to the grid. */
++grid->n_occupied;
if (grid->sm_list[grid_index]) {
remove_surfmol_from_list(
&grid->sm_list[grid_index], grid->sm_list[grid_index]->sm);
}
grid->sm_list[grid_index] = add_surfmol_with_unique_pb_to_list(
grid->sm_list[grid_index], new_surf_mol);
/* Add to the schedule. */
if (schedule_add_mol(sv->local_storage->timer, new_surf_mol))
mcell_allocfailed("Failed to add newly created %s molecule to scheduler.",
product_species->sym->name);
return new_surf_mol;
}
/***************************************************************************
outcome_products_random:
In: world: simulation state
w: first wall in the reaction
hitpt: hit point (if any)
t: time of the reaction
rx: reaction
path: path of the reaction
reacA: first reactant (moving molecule)
reacB: second reactant
orientA: orientation of the first reactant
orientB: orientation of the second reactant
Out: Returns RX_A_OK, RX_FLIP or RX_BLOCKED.
Note: This function replaces surface reactants (if needed) by the surface
products picked in the random order from the list of products. Also
surface products are placed in the random order in the surrounding empty
tiles. After this function execution some walls that do not have surface
molecules and therefore do not have a grid may get a grid as side effect
of calling functions "grid_all_neigbors_across_walls_through_vertices()"
and "grid_all_neighbors_across_walls_through_edges()".
Note: If both reactants are surface molecules, and they are both located within
the same restricted region border (REFL/ABSORB), then reaction products -
surface molecules for which this region border is restrictive will be
placed inside this region. If any of the conditions above are not true,
the reaction products - surface molecules can be placed on any tile from
the list of vacant tiles.
Note: Policy on surface products placement is described in the document
"policy_surf_products_placement.doc" (see "src/docs").
****************************************************************************/
static int outcome_products_random(struct volume *world, struct wall *w,
struct vector3 *hitpt, double t,
struct rxn *rx, int path,
struct abstract_molecule *reacA,
struct abstract_molecule *reacB,
short orientA, short orientB) {
#ifdef DEBUG_RXNS
// NOTE: maybe make a single dump call out of this
DUMP_CONDITION3(
dump_processing_reaction(world->current_iterations, hitpt, t, rx, reacA, reacB, w);
dump_molecule_species(reacA);
if (reacB != nullptr) {
mcell_log(" + ");
dump_molecule_species(reacB);
}
mcell_log("\nreaction_index: %d\n", path);
dump_rxn(rx, "", true);
);
#endif
/* Did the moving molecule cross the plane? */
bool cross_wall = false;
/* index of the first player for the pathway */
int const i0 = rx->product_idx[path];
/* index of the first player for the next pathway */
int const iN = rx->product_idx[path + 1];
assert(iN > i0);
/* Players array from the reaction. */
struct species **rx_players = rx->players + i0;
int const n_players = iN - i0; /* number of reaction players */
std::vector<struct abstract_molecule *> product(n_players); /* array of products */
/* array that decodes the type of each product */
std::vector<char> product_type(n_players);
std::vector<short> product_orient(n_players); /* array of orientations for each product */
/* array of surface_grids for products */
std::vector<struct surface_grid *> product_grid(n_players);
std::vector<int> product_grid_idx(n_players); /* array of grid indices for products */
std::vector<byte> product_flag(n_players); /* array of placement flags for products */
/* Unimol rxn (not mol-mol, not mol-wall) */
bool const is_unimol = is_rxn_unimol(rx);
struct surface_grid *tile_grid; /* surface grid the tile belongs to */
int num_vacant_tiles = 0; /* number of vacant tiles */
/* used for product placement for the reaction of type A->B+C[rate] */
unsigned int reac_idx = UINT_MAX;
struct surface_grid *reac_grid = NULL, *mol_grid = NULL;
/* Clear the initial product info. */
for (int i = 0; i < n_players; ++i) {
product[i] = NULL;
product_type[i] = PLAYER_NONE;
product_orient[i] = 0;
product_grid[i] = NULL;
product_grid_idx[i] = -1;
product_flag[i] = PRODUCT_FLAG_NOT_SET;
}
/* Flag indicating that a surface is somehow involved with this reaction. */
struct surface_molecule *const sm_1 =
IS_SURF_MOL(reacA) ? (struct surface_molecule *)reacA : NULL;
struct surface_molecule *const sm_2 =
IS_SURF_MOL(reacB) ? (struct surface_molecule *)reacB : NULL;
struct surface_molecule *const sm_reactant = sm_1 ? sm_1 : sm_2;
bool const is_orientable = (w != NULL) || (sm_reactant != NULL);
/* list of the restricted regions for the reactants by wall */
struct region_list *rlp_head_wall_1 = NULL, *rlp_head_wall_2 = NULL;
/* list of the restricted regions for the reactants by object */
struct region_list *rlp_head_obj_1 = NULL, *rlp_head_obj_2 = NULL;
int sm_bitmask = determine_molecule_region_topology(
world, sm_1, sm_2, &rlp_head_wall_1, &rlp_head_wall_2, &rlp_head_obj_1,
&rlp_head_obj_2, is_unimol);
/* reacA is the molecule which initiated the reaction. */
struct abstract_molecule *const initiator = reacA;
short const initiatorOrient = orientA;
/* Ensure that reacA and reacB are sorted in the same order as the rxn players. */
assert(reacA != NULL);
if (reacA->properties != rx->players[0]) {
struct abstract_molecule *tmp_mol = reacA;
reacA = reacB;
reacB = tmp_mol;
short tmp_orient = orientA;
orientA = orientB;
orientB = tmp_orient;
}
assert(reacA != NULL);
add_reactants_to_product_list(rx, reacA, reacB, NULL, &product[0], &product_type[0]);
/* Determine whether any of the reactants can be replaced by a product.
This is only useful for surface molecules to make sure reactions of the
type A + B -> A don't push A to neighboring tiles */
int replace_p1 = (product_type[0] == PLAYER_SURF_MOL && rx_players[0] == NULL);
int replace_p2 = rx->n_reactants > 1 && (product_type[1] == PLAYER_SURF_MOL &&
rx_players[1] == NULL);
/* Determine the point of reaction on the surface. */
struct vector2 rxn_uv_pos; // position of reaction on wall
int rxn_uv_idx = -1; // tile index of where reaction occurred
int num_surface_static_reactants = 0; // number of reactants with (D_2D == 0)
if (is_orientable) {
if (sm_reactant) {
rxn_uv_pos = sm_reactant->s_pos;
} else {
xyz2uv(hitpt, w, &rxn_uv_pos);
}
assert(w != NULL);
if (w->grid == NULL) {
/* reacA must be a volume molecule, or this wall would have a grid already. */
assert(!IS_SURF_MOL(reacA));
if (create_grid(world, w, ((struct volume_molecule *)reacA)->subvol))
mcell_allocfailed("Failed to create a grid for a wall.");
}
rxn_uv_idx = uv2grid(&rxn_uv_pos, w->grid);
/* find out number of static surface reactants */
if ((sm_1 != NULL) && (!distinguishable(sm_1->get_diffusion(sm_1), 0, EPS_C))){
num_surface_static_reactants++;
}
if ((sm_2 != NULL) && (!distinguishable(sm_2->get_diffusion(sm_2), 0, EPS_C))){
num_surface_static_reactants++;
}
}
/* find out number of surface products */
int num_surface_products = 0;
int num_surface_static_products = 0; // number of products with (D_2D == 0)
for (int n_product = rx->n_reactants; n_product < n_players; ++n_product) {
if (rx_players[n_product] == NULL) {
continue;
}
if (rx_players[n_product]->flags & ON_GRID) {
num_surface_products++;
if (!distinguishable(rx_players[n_product]->D, 0, EPS_C))
num_surface_static_products++;
}
}
int mol_idx = INT_MAX;
/* If the reaction involves a surface, make sure there is room for each
* product. */
struct tile_neighbor *tile_nbr_head = NULL; // list of neighbor tiles
int tile_nbr_list_length = 0;
struct tile_neighbor *tile_vacant_nbr_head = NULL; // list of vacant neighbor tiles
if (is_orientable) {
if (num_surface_products > 0) {
if (sm_reactant != NULL) {
find_neighbor_tiles(world, sm_reactant, sm_reactant->grid,
sm_reactant->grid_index, 1, 0, &tile_nbr_head,
&tile_nbr_list_length);
} else {
find_neighbor_tiles(world, sm_reactant, w->grid, rxn_uv_idx, 1, 0,
&tile_nbr_head, &tile_nbr_list_length);
}
/* Create list of vacant tiles */
for (struct tile_neighbor *tile_nbr = tile_nbr_head; tile_nbr != NULL;
tile_nbr = tile_nbr->next) {
struct surface_molecule_list *sm_list = tile_nbr->grid->sm_list[tile_nbr->idx];
if (sm_list == NULL || sm_list->sm == NULL) {
num_vacant_tiles++;
push_tile_neighbor_to_list(&tile_vacant_nbr_head, tile_nbr->grid, tile_nbr->idx);
}
}
}
/* Can this reaction happen at all? */
int num_recycled_tiles = 0;
if (replace_p1 && replace_p2) {
num_recycled_tiles = 2;
} else if (replace_p1 || replace_p2) {
num_recycled_tiles = 1;
}
if (num_surface_products > num_vacant_tiles + num_recycled_tiles) {
return cleanup_and_block_rx(tile_nbr_head, tile_vacant_nbr_head);
}
/* set the orientations of the products. */
for (int n_product = 0; n_product < n_players; ++n_product) {
/* Skip NULL products */
if (rx_players[n_product] == NULL) {
continue;
}
int this_geometry = rx->geometries[i0 + n_product];
int relative_orient = (this_geometry < 0) ? -1 : 1;
this_geometry = abs(this_geometry);
/* Geometry of 0 means "random orientation" */
if (this_geometry == 0) {
product_orient[n_product] = (rng_uint(world->rng) & 1) ? 1 : -1;
} else {
if (this_geometry > (int)rx->n_reactants) {
product_orient[n_product] = relative_orient *
product_orient[this_geometry - rx->n_reactants - 1];
} else if (this_geometry == 1) {
product_orient[n_product] = relative_orient * orientA;
} else if (this_geometry == 2 && reacB != NULL) {
product_orient[n_product] = relative_orient * orientB;
} else {
product_orient[n_product] = relative_orient * 1;
}
}
/* If this is a reactant... */
if (n_product < (int)rx->n_reactants) {
/* If this is a surface molecule, we need to set its orientation. */
if (rx_players[n_product]->flags & ON_GRID) {
assert(IS_SURF_MOL(product[n_product]));
struct surface_molecule *sm =
(struct surface_molecule *)product[n_product];
/* If the new orientation doesn't match the old, we've got some work
* to do. */
if (sm->orient != product_orient[n_product]) {
/* We're about to update the molecule's orientation, so we will
* first remove it from the counts in case we have any
* orientation-sensitive counts. Then, we will update the
* orientation. Finally, we will add the molecule back into the
* counts in its new orientation. */
/* Remove molecule from counts in old orientation, if mol is
* counted. */
if (product[n_product]->properties->flags & (COUNT_CONTENTS|COUNT_ENCLOSED)) {
count_region_from_scratch(world,
product[n_product], /* molecule */
NULL, /* rxn pathway */
-1, /* remove count */
NULL, /* Location at which to count */
w, /* Wall on which this happened */
t, /* Time of occurrence */
NULL);
}
/* Force check for the unimolecular reactions
after changing orientation.
There are two possible cases to be covered here:
1) when (sm->t2) was previously set to FOREVER
2) there may be two or more unimolecular reactions involving surface
class that have different kinetics.
*/
if (((sm->flags & ACT_REACT) != 0) &&
((sm->properties->flags & CAN_SURFWALL) != 0)) {
sm->t2 = 0;
}
/* Set the molecule's orientation. */
sm->orient = product_orient[n_product];
/* Add molecule back to counts in new orientation, if mol is
* counted. */
if (product[n_product]->properties->flags & (COUNT_CONTENTS|COUNT_ENCLOSED)) {
count_region_from_scratch(world,
product[n_product], /* molecule */
NULL, /* rxn pathway */
1, /* add count */
NULL, /* Location at which to count */
w, /* Wall on which this happened */
t, /* Time of occurrence */
NULL);
}
}
} else if (!is_unimol) { /* Otherwise, check if we've crossed the plane. */
if (product[n_product] == initiator) {
if (product_orient[n_product] != initiatorOrient)
cross_wall = true;
}
}
}
}
/* find out where to place surface products */
/* Some special cases are listed below. */
if (num_surface_products == 1) {
if (is_unimol && replace_p1) {
for (int n_product = rx->n_reactants; n_product < n_players; n_product++) {
if (rx_players[n_product] == NULL ||
(rx_players[n_product]->flags & NOT_FREE) == 0) {
continue;
}
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[n_product] = ((struct surface_molecule *)reacA)->grid;
product_grid_idx[n_product] = ((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
break;
}
}
} else if ((num_surface_static_reactants == 1) && (num_surface_static_products == 1)
&& (replace_p1 || replace_p2)) {
/* the lonely static product always replaces lonely static reactant */
for (int n_product = rx->n_reactants; n_product < n_players; n_product++) {
if (rx_players[n_product] == NULL ||
(rx_players[n_product]->flags & NOT_FREE) == 0 ||
distinguishable(rx_players[n_product]->D, 0, EPS_C)) {
continue;
}
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET) {
if (replace_p1 && (!distinguishable(reacA->properties->D, 0, EPS_C))) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[n_product] = ((struct surface_molecule *)reacA)->grid;
product_grid_idx[n_product] = ((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
break;
} else if (replace_p2 && (!distinguishable(reacB->properties->D, 0, EPS_C))) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[n_product] = ((struct surface_molecule *)reacB)->grid;
product_grid_idx[n_product] = ((struct surface_molecule *)reacB)->grid_index;
break;
}
}
}
} else if (replace_p1 && replace_p2) {
/* if both reactants should be replaced and there is only one surface product
here we make sure that the initiator molecule is replaced */
for (int n_product = rx->n_reactants; n_product < n_players; n_product++) {
if ((rx_players[n_product] == NULL) ||
((rx_players[n_product]->flags & NOT_FREE) == 0)) {
continue;
}
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET) {
if (reacA == initiator) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[n_product] = ((struct surface_molecule *)reacA)->grid;
product_grid_idx[n_product] = ((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
} else {
product_flag[n_product] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[n_product] = ((struct surface_molecule *)reacB)->grid;
product_grid_idx[n_product] = ((struct surface_molecule *)reacB)->grid_index;
}
break;
}
}
} else if (replace_p1) {
for (int n_product = rx->n_reactants; n_product < n_players; n_product++) {
if ((rx_players[n_product] == NULL) ||
((rx_players[n_product]->flags & NOT_FREE) == 0)) {
continue;
}
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[n_product] = ((struct surface_molecule *)reacA)->grid;
product_grid_idx[n_product] = ((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
break;
}
}
} else if (replace_p2) {
for (int n_product = rx->n_reactants; n_product < n_players; n_product++) {
if ((rx_players[n_product] == NULL) |
((rx_players[n_product]->flags & NOT_FREE) == 0)) {
continue;
}
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[n_product] = ((struct surface_molecule *)reacB)->grid;
product_grid_idx[n_product] = ((struct surface_molecule *)reacB)->grid_index;
break;
}
}
}
} else if (num_surface_products > 1) {
/* more than one surface products */
if (num_surface_static_reactants > 0) {
bool replace_reacA = (!distinguishable(reacA->get_diffusion(reacA), 0, EPS_C)) && replace_p1;
bool replace_reacB =
(reacB == NULL) ? false : (!distinguishable(reacB->get_diffusion(reacB), 0, EPS_C)) && replace_p2;
if (replace_reacA || replace_reacB) {
int max_static_count = (num_surface_static_products < num_surface_static_reactants)
? num_surface_static_products : num_surface_static_reactants;
int count = 0;
while (count < max_static_count) {
unsigned int rnd_num = rng_uint(world->rng) % n_players;
/* pass reactants */
if ((rnd_num < rx->n_reactants) || (rx_players[rnd_num] == NULL) ||
((rx_players[rnd_num]->flags & NOT_FREE) == 0) ||
distinguishable(rx_players[rnd_num]->D, 0, EPS_C)) {
continue;
}
if (product_flag[rnd_num] == PRODUCT_FLAG_NOT_SET) {
if (replace_reacA) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[rnd_num] = ((struct surface_molecule *)reacA)->grid;
product_grid_idx[rnd_num] = ((struct surface_molecule *)reacA)->grid_index;
count++;
replace_p1 = 0;
replace_reacA = 0;
} else if (replace_reacB) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[rnd_num] = ((struct surface_molecule *)reacB)->grid;
product_grid_idx[rnd_num] = ((struct surface_molecule *)reacB)->grid_index;
count++;
replace_p2 = 0;
replace_reacB = 0;
}
}
} /* end while */
}
}
/* check whether there are any surface reactants left to replace with
* surface products since we are done with static reactants/products */
if (replace_p1 || replace_p2) {
int surf_prod_left = 0, surf_reactant_left = 0;
for (int n_product = rx->n_reactants; n_product < n_players; n_product++) {
if ((rx_players[n_product] == NULL) ||
((rx_players[n_product]->flags & NOT_FREE) == 0)) {
continue;
}
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET) {
surf_prod_left++;
}
}
if (replace_p1) {
surf_reactant_left++;
}
if (replace_p2) {
surf_reactant_left++;
}
if (surf_prod_left > 0) {
int num_to_place = surf_prod_left;
if (surf_prod_left >= surf_reactant_left) {
num_to_place = surf_reactant_left;
}
int count = 0;
while (count < num_to_place) {
unsigned int rnd_num = rng_uint(world->rng) % n_players;
if ((rnd_num < rx->n_reactants) || (rx_players[rnd_num] == NULL) ||
(rx_players[rnd_num]->flags & NOT_FREE) == 0) {
continue;
}
if (product_flag[rnd_num] == PRODUCT_FLAG_NOT_SET) {
if (replace_p1) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[rnd_num] = ((struct surface_molecule *)reacA)->grid;
product_grid_idx[rnd_num] = ((struct surface_molecule *)reacA)->grid_index;
count++;
replace_p1 = 0;
} else if (replace_p2) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[rnd_num] = ((struct surface_molecule *)reacB)->grid;
product_grid_idx[rnd_num] = ((struct surface_molecule *)reacB)->grid_index;
replace_p2 = 0;
count++;
}
}
} /* end while */
}
}
}
/* here we will find placement for the case of the reaction of type
* "vol_mol + w -> surf_mol + ...[rate] " */
if ((sm_reactant == NULL) && (w != NULL) && (num_surface_products >= 1)) {
assert(!IS_SURF_MOL(reacA));
assert(rxn_uv_idx != -1);
while (true) {
unsigned int rnd_num = rng_uint(world->rng) % (n_players);
if (rnd_num <= 1 || (rx_players[rnd_num] == NULL) ||
(rx_players[rnd_num]->flags & NOT_FREE) == 0) {
continue;
}
if (product_flag[rnd_num] == PRODUCT_FLAG_NOT_SET) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_UV_LOC;
product_grid[rnd_num] = w->grid;
product_grid_idx[rnd_num] = rxn_uv_idx;
break;
}
}
}
/* we will implement special placement policy for reaction of type of *
* A->B+C[rate] */
if (is_unimol && (sm_reactant != NULL) && (num_surface_products == 2)) {
reac_idx = sm_reactant->grid_index;
reac_grid = sm_reactant->grid;
}
// all other products are placed on one of the randomly chosen vacant tiles
int do_it_once = 0; /* flag */
int num_attempts = 0;
for (int n_product = rx->n_reactants; n_product < n_players; ++n_product) {
/* If the product is a volume product, no placement is required. */
if (rx_players[n_product]->flags & ON_GRID) {
if (product_flag[n_product] != PRODUCT_FLAG_NOT_SET) {
continue;
}
/* can't place products - reaction blocked */
if (num_vacant_tiles == 0) {
return cleanup_and_block_rx(tile_nbr_head, tile_vacant_nbr_head);
}
num_attempts = 0;
while (true) {
if (num_attempts > SURFACE_DIFFUSION_RETRIES) {
return cleanup_and_block_rx(tile_nbr_head, tile_vacant_nbr_head);
}
/* randomly pick a tile from the list */
unsigned int rnd_num = rng_uint(world->rng) % num_vacant_tiles;
int tile_idx = -1; /* index of the tile on the grid */
tile_grid = NULL;
if (get_tile_neighbor_from_list_of_vacant_neighbors(
tile_vacant_nbr_head, rnd_num, &tile_grid, &tile_idx) == 0) {
return cleanup_and_block_rx(tile_nbr_head, tile_vacant_nbr_head);
}
if (tile_idx < 0) {
continue; /* this tile was probed already */
}
assert(tile_grid != NULL);
/* make sure we can get to the tile given the surface regions defined
* in the model */
//ASSERT_FOR_MCELL4(sm_bitmask == 0); - should not be needed anymore but keeping it as a marker for future debugging
if (!product_tile_can_be_reached(tile_grid->surface, rlp_head_wall_1,
rlp_head_wall_2, rlp_head_obj_1, rlp_head_obj_2, sm_bitmask, is_unimol)) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
product_grid[n_product] = tile_grid;
product_grid_idx[n_product] = tile_idx;
product_flag[n_product] = PRODUCT_FLAG_USE_RANDOM;
if (!do_it_once && is_unimol && (sm_reactant != NULL) && (num_surface_products == 2)) {
/*remember this tile (used for the reaction A->B+C[rate]) */
mol_idx = tile_idx;
mol_grid = tile_grid;
do_it_once = 1;
}
break;
} /* end while */
}
}
} /* end if (is_orientable) */
/* Determine the location of the reaction for count purposes. */
struct vector3 count_pos_xyz;
struct periodic_image *periodic_box = ((struct volume_molecule *)reacA)->periodic_box;
if (hitpt != NULL) {
count_pos_xyz = *hitpt;
} else if (sm_reactant) {
uv2xyz(&sm_reactant->s_pos, sm_reactant->grid->surface, &count_pos_xyz);
} else {
count_pos_xyz = ((struct volume_molecule *)reacA)->pos;
}
/* Create and place each product. */
struct vector3 mol_pos_tmp;
struct subvolume *product_subvol = NULL;
/* Do we need to advance the dissociation index? */
bool update_dissociation_index = false;
for (int n_product = rx->n_reactants; n_product < n_players; ++n_product) {
struct graph_data* g_data = NULL;
if (rx->product_graph_data != NULL)
g_data = rx->product_graph_data[path][n_product - rx->n_reactants];
struct abstract_molecule *this_product = NULL;
struct species *const product_species = rx_players[n_product];
/* If the product is a surface molecule, place it on the grid. */
if (product_species->flags & ON_GRID) {
struct vector2 prod_uv_pos;
/* Pick an appropriate position for the new molecule. */
if (world->randomize_smol_pos) {
switch (product_flag[n_product]) {
case PRODUCT_FLAG_USE_REACA_UV:
if (is_unimol && (num_surface_products == 2) && (sm_reactant != NULL)) {
if (mol_grid == NULL) {
mcell_internal_error("Error in surface product placement for the "
"unimolecular reaction.");
}
find_closest_position(product_grid[n_product], product_grid_idx[n_product],
mol_grid, mol_idx, &prod_uv_pos);
} else {
prod_uv_pos = ((struct surface_molecule *)reacA)->s_pos;
}
break;
case PRODUCT_FLAG_USE_REACB_UV:
assert(reacB != NULL);
prod_uv_pos = ((struct surface_molecule *)reacB)->s_pos;
break;
case PRODUCT_FLAG_USE_UV_LOC:
prod_uv_pos = rxn_uv_pos;
break;
case PRODUCT_FLAG_USE_RANDOM:
if (is_unimol && replace_p1 && (num_surface_products == 2)) {
find_closest_position(product_grid[n_product],
product_grid_idx[n_product], reac_grid,
reac_idx, &prod_uv_pos);
} else {
grid2uv_random(product_grid[n_product], product_grid_idx[n_product],
&prod_uv_pos, world->rng);
}
break;
default:
UNHANDLED_CASE(product_flag[n_product]);
/*break;*/
}
} else {
grid2uv(product_grid[n_product], product_grid_idx[n_product], &prod_uv_pos);
}
this_product = (struct abstract_molecule *)place_sm_product(
world, product_species, g_data, product_grid[n_product],
product_grid_idx[n_product], &prod_uv_pos, product_orient[n_product],
t, reacA->periodic_box);
#ifdef DEBUG_RXNS
DUMP_CONDITION3(
dump_surface_molecule((struct surface_molecule*)this_product, "", true, " created sm:", world->current_iterations, this_product->t, true);
);
#endif
} else { /* else place the molecule in space. */
/* For either a unimolecular reaction, or a reaction between two surface
molecules we don't have a hitpoint. */
if (!hitpt) {
if (reacA->properties->flags & ON_GRID) {
/* Since we use reactA's position to compute the location of the reaction
we also need to use its wall for picking the displacement later in
place_volume_products */
w = ((struct surface_molecule *)reacA)->grid->surface;
uv2xyz(&((struct surface_molecule *)reacA)->s_pos,
w, &mol_pos_tmp);
product_subvol = find_subvolume(world, &mol_pos_tmp, NULL);
} else {
mol_pos_tmp = ((struct volume_molecule *)reacA)->pos;
product_subvol = ((struct volume_molecule *)reacA)->subvol;
}
hitpt = &mol_pos_tmp;
} else if (product_subvol == NULL) {
product_subvol = find_subvolume(world, hitpt, NULL);
}
this_product = (struct abstract_molecule *)place_volume_product(
world, product_species, g_data, sm_reactant, w, product_subvol, hitpt,
product_orient[n_product], t, reacA->periodic_box);
#ifdef DEBUG_RXNS
DUMP_CONDITION3(
dump_volume_molecule((struct volume_molecule*)this_product, "", true, " created vm:", world->current_iterations, this_product->t, true);
);
#endif
if (((struct volume_molecule *)this_product)->index < DISSOCIATION_MAX)
update_dissociation_index = true;
}
/* Provide new molecule with graph information if it exists */
if(rx->product_graph_data != NULL){
this_product->graph_data = g_data;
}
/* Update molecule counts */
++product_species->population;
if (product_species->flags & (COUNT_CONTENTS | COUNT_ENCLOSED))
count_region_from_scratch(world, this_product, NULL, 1, NULL, NULL, t, this_product->periodic_box);
#ifndef MCELL3_DO_NOT_REUSE_MOL_ID_UNIMOL_RXN
/* preserve molecule id if rxn is unimolecular with one product */
if (is_unimol && (n_players == 1)) {
this_product->id = reacA->id;
world->current_mol_id--; /* give back id we used */
continue;
}
/* preserve molecule id if rxn is surface rxn with one product */
if ((n_players == 3) && product_type[1] == PLAYER_WALL) {
this_product->id = reacA->id;
world->current_mol_id--; /* give back id we used */
continue;
}
#endif
}
/* If necessary, update the dissociation index. */
if (update_dissociation_index) {
ASSERT_FOR_MCELL4(false);
if (--world->dissociation_index < DISSOCIATION_MIN)
world->dissociation_index = DISSOCIATION_MAX;
}
/* Handle events triggered off of named reactions */
if (rx->info[path].pathname != NULL) {
/* No flags for reactions so we have to check regions if we have waypoints!
* Fix to be more efficient for WORLD-only counts? */
if (world->place_waypoints_flag)
count_region_from_scratch(world, NULL, rx->info[path].pathname, 1,
&count_pos_xyz, w, t, periodic_box);
/* Other magical stuff. For now, can only trigger releases. */
if (rx->info[path].pathname->magic != NULL) {
if (reaction_wizardry(world, rx->info[path].pathname->magic, w,
&count_pos_xyz, t))
mcell_allocfailed("Failed to complete reaction triggered release after "
"a '%s' reaction.",
rx->info[path].pathname->sym->name);
}
}
/* recover memory */
delete_tile_neighbor_list(tile_nbr_head);
delete_tile_neighbor_list(tile_vacant_nbr_head);
delete_region_list(rlp_head_wall_1);
delete_region_list(rlp_head_wall_2);
delete_region_list(rlp_head_obj_1);
delete_region_list(rlp_head_obj_2);
return cross_wall ? RX_FLIP : RX_A_OK;
}
/*************************************************************************
outcome_unimolecular:
In: world: simulation state
rx: the reaction that is occuring
path: the path that the reaction is taking
reac: the molecule that is taking that path
t: time that the reaction is occurring
Out: Value based on outcome:
RX_BLOCKED if there was no room to put products on grid
RX_DESTROY if molecule no longer exists.
RX_A_OK if it does.
Products are created as needed.
*************************************************************************/
int outcome_unimolecular(struct volume *world, struct rxn *rx, int path,
struct abstract_molecule *reac, double t) {
struct species *who_was_i = reac->properties;
int result = RX_A_OK;
struct volume_molecule *vm = NULL;
struct surface_molecule *sm = NULL;
//JJT: if this is a molecule marked as external leave it up to nfsim
/*if(reac->properties->flags & EXTERNAL_SPECIES){
vm = (struct volume_molecule *)reac;
//outcome_unimolecular_nfsim(world, rx, path, reac, t);
outcome_nfsim(world, rx, path, reac, NULL, t);
result = outcome_products_random(world, NULL, NULL, t, rx, path, reac, NULL, 0, 0);
}*/
if ((reac->properties->flags & NOT_FREE) == 0) {
vm = (struct volume_molecule *)reac;
//NFSim calculation
if(reac->properties->flags & EXTERNAL_SPECIES){
#if 0 // just to dump the whole rxn, fails later for some reason..
// populate all pathways
for (int path = 0; path < rx->n_pathways; path++) {
outcome_nfsim(world, rx, path, reac, NULL, t);
}
#else
outcome_nfsim(world, rx, path, reac, NULL, t);
#endif
}
result = outcome_products_random(world, NULL, NULL, t, rx, path, reac,
NULL, 0, 0);
} else {
sm = (struct surface_molecule *)reac;
/* we will not create products if the reaction is with an ABSORPTIVE
region border */
if ((strcmp(rx->players[0]->sym->name, "ALL_SURFACE_MOLECULES") == 0) ||
(strcmp(rx->players[0]->sym->name, "ALL_MOLECULES") == 0)) {
/* do nothing */
} else {
//NFSim calculations
if(reac->properties->flags & EXTERNAL_SPECIES){
outcome_nfsim(world, rx, path, reac, NULL, t);
}
result = outcome_products_random(world, sm->grid->surface, NULL, t, rx,
path, reac, NULL, sm->orient, 0);
}
}
if (result == RX_BLOCKED)
return RX_BLOCKED;
if (result != RX_BLOCKED) {
rx->info[path].count++;
rx->n_occurred++;
if(rx->product_graph_data != NULL){
logNFSimReactions_c(rx->external_reaction_data[path].reaction_name);
}
}
struct species *who_am_i = rx->players[rx->product_idx[path]];
if (who_am_i == NULL) {
if (vm != NULL) {
vm->subvol->mol_count--;
if (vm->flags & IN_SCHEDULE)
vm->subvol->local_storage->timer->defunct_count++;
if (vm->properties->flags & COUNT_SOME_MASK) {
count_region_from_scratch(world, (struct abstract_molecule *)vm, NULL,
-1, &(vm->pos), NULL, vm->t, vm->periodic_box);
}
} else {
#ifdef DEBUG_RXNS
DUMP_CONDITION3(
dump_surface_molecule(sm, "", true, "Unimolecular sm defunct:", world->current_iterations, sm->t, false);
);
#endif
remove_surfmol_from_list(&sm->grid->sm_list[sm->grid_index], sm);
sm->grid->n_occupied--;
if (sm->flags & IN_SCHEDULE) {
sm->grid->subvol->local_storage->timer->defunct_count++;
}
if (sm->properties->flags & COUNT_SOME_MASK) {
count_region_from_scratch(world, (struct abstract_molecule *)sm, NULL,
-1, NULL, NULL, sm->t, sm->periodic_box);
}
}
free(reac->periodic_box);
who_was_i->n_deceased++;
double t_time = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, t);
who_was_i->cum_lifetime_seconds += t_time - reac->birthday;
who_was_i->population--;
if (vm != NULL) {
#ifdef DEBUG_RXNS
DUMP_CONDITION3(
dump_volume_molecule(vm, "", true, "Unimolecular vm defunct:", world->current_iterations, vm->t, false);
);
#endif
collect_molecule(vm);
}
else {
reac->properties = NULL;
mem_put(reac->birthplace, reac);
}
return RX_DESTROY;
} else if (who_am_i != who_was_i) {
if (vm != NULL) {
#ifdef DEBUG_RXNS
DUMP_CONDITION3(
dump_volume_molecule(vm, "", true, "Unimolecular vm defunct:", world->current_iterations, vm->t, false);
);
#endif
collect_molecule(vm);
}
else
reac->properties = NULL;
return RX_DESTROY;
} else
return result;
}
/*************************************************************************
outcome_bimolecular:
In: reaction that's occurring
path the reaction's taking
two molecules that are reacting (first is moving one)
orientations of the two molecules
time that the reaction is occurring
location of collision between molecules
Out: Value based on outcome:
RX_BLOCKED if there was no room to put products on grid
RX_FLIP if the molecule goes across the membrane
RX_DESTROY if the molecule no longer exists
RX_A_OK if everything proceeded smoothly
Products are created as needed.
Note: reacA is the triggering molecule (e.g. moving)
*************************************************************************/
int outcome_bimolecular(struct volume *world, struct rxn *rx, int path,
struct abstract_molecule *reacA,
struct abstract_molecule *reacB, short orientA,
short orientB, double t, struct vector3 *hitpt,
struct vector3 *loc_okay) {
#ifdef DEBUG_TIMING
DUMP_CONDITION3(
MCell::dump_outcome_bimolecular_timing(t);
);
#endif
assert(periodic_boxes_are_identical(reacA->periodic_box, reacB->periodic_box));
struct surface_molecule *sm = NULL;
struct volume_molecule *vm = NULL;
struct wall *w = NULL;
/* struct storage *x; */
int result;
int reacB_was_free = 0;
int killA, killB;
if ((reacA->properties->flags & NOT_FREE) == 0) {
if ((reacB->properties->flags & ON_GRID) != 0) {
sm = (struct surface_molecule *)reacB;
w = sm->grid->surface;
}
} else { /* Surface molecule */
sm = (struct surface_molecule *)reacA;
w = sm->grid->surface;
}
//JJT: if this is a molecule marked as external leave it up to nfsim
if(reacA->properties->flags & EXTERNAL_SPECIES){
result = outcome_nfsim(world, rx, path, reacA, reacB, t);
result = outcome_products_random(world, w, hitpt, t, rx, path, reacA, reacB,
orientA, orientB);
}
else {
result = outcome_products_random(world, w, hitpt, t, rx, path, reacA, reacB,
orientA, orientB);
}
if (result == RX_BLOCKED)
return RX_BLOCKED;
rx->n_occurred++;
rx->info[path].count++;
if(rx->product_graph_data != NULL){
logNFSimReactions_c(rx->external_reaction_data[path].reaction_name);
}
/* Figure out if either of the reactants was destroyed */
if (rx->players[0] == reacA->properties) {
killB = (rx->players[rx->product_idx[path] + 1] == NULL);
killA = (rx->players[rx->product_idx[path]] == NULL);
} else {
killB = (rx->players[rx->product_idx[path]] == NULL);
killA = (rx->players[rx->product_idx[path] + 1] == NULL);
}
if (killB) {
#ifdef DEBUG_RXNS
DUMP_CONDITION3(
dump_volume_molecule((struct volume_molecule*)reacB, "", true, " defunct m:", world->current_iterations, 0.0, false);
);
#endif
vm = NULL;
if ((reacB->properties->flags & ON_GRID) != 0) {
sm = (struct surface_molecule *)reacB;
remove_surfmol_from_list(&sm->grid->sm_list[sm->grid_index], sm);
sm->grid->n_occupied--;
if (sm->flags & IN_SURFACE)
sm->flags -= IN_SURFACE;
if (sm->flags & IN_SCHEDULE) {
sm->grid->subvol->local_storage->timer->defunct_count++;
}
} else if ((reacB->properties->flags & NOT_FREE) == 0) {
vm = (struct volume_molecule *)reacB;
vm->subvol->mol_count--;
if (vm->flags & IN_SCHEDULE) {
vm->subvol->local_storage->timer->defunct_count++;
}
reacB_was_free = 1;
}
if ((reacB->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) != 0) {
count_region_from_scratch(world, reacB, NULL, -1, NULL, NULL, t, reacB->periodic_box);
}
free(reacB->periodic_box);
reacB->periodic_box = NULL;
reacB->properties->n_deceased++;
double t_time = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, t);
reacB->properties->cum_lifetime_seconds += t_time - reacB->birthday;
reacB->properties->population--;
if (vm != NULL)
collect_molecule(vm);
else
reacB->properties = NULL;
}
if (killA) {
#ifdef DEBUG_RXNS
DUMP_CONDITION3(
dump_volume_molecule((struct volume_molecule*)reacA, "", true, " defunct m:", world->current_iterations, 0.0, false);
);
#endif
vm = NULL;
if ((reacA->properties->flags & ON_GRID) != 0) {
sm = (struct surface_molecule *)reacA;
remove_surfmol_from_list(&sm->grid->sm_list[sm->grid_index], sm);
sm->grid->n_occupied--;
if (sm->flags & IN_SCHEDULE) {
sm->grid->subvol->local_storage->timer->defunct_count++;
}
} else if ((reacA->properties->flags & NOT_FREE) == 0) {
vm = (struct volume_molecule *)reacA;
vm->subvol->mol_count--;
if (vm->flags & IN_SCHEDULE) {
vm->subvol->local_storage->timer->defunct_count++;
}
}
if ((reacA->properties->flags & ON_GRID) !=
0) /* Surface molecule is OK where it is, doesn't obey COUNT_ME */
{
if (reacA->properties->flags &
COUNT_SOME_MASK) /* If we're ever counted, try to count us now */
{
count_region_from_scratch(world, reacA, NULL, -1, NULL, NULL, t, reacA->periodic_box);
}
} else if (reacA->flags & COUNT_ME) {
/* Subtlety: we made it up to hitpt, but our position is wherever we were
* before that! */
if (hitpt == NULL || reacB_was_free ||
(reacB->properties != NULL &&
(reacB->properties->flags & NOT_FREE) == 0)) {
/* Vol-vol rx should be counted at hitpt */
count_region_from_scratch(world, reacA, NULL, -1, hitpt, NULL, t, reacA->periodic_box);
} else /* Vol-surf but don't want to count exactly on a wall or we might
count on the wrong side */
{
struct vector3 fake_hitpt;
vm = (struct volume_molecule *)reacA;
/* Halfway in between where we were and where we react should be a safe
* away-from-wall place to remove us */
if (loc_okay == NULL)
loc_okay = &(vm->pos);
fake_hitpt.x = 0.5 * hitpt->x + 0.5 * loc_okay->x;
fake_hitpt.y = 0.5 * hitpt->y + 0.5 * loc_okay->y;
fake_hitpt.z = 0.5 * hitpt->z + 0.5 * loc_okay->z;
count_region_from_scratch(world, reacA, NULL, -1, &fake_hitpt, NULL, t, reacA->periodic_box);
}
}
free(reacA->periodic_box);
reacA->periodic_box = NULL;
reacA->properties->n_deceased++;
double t_time = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, t);
reacA->properties->cum_lifetime_seconds += t_time - reacA->birthday;
reacA->properties->population--;
if (vm != NULL)
collect_molecule(vm);
else
reacA->properties = NULL;
return RX_DESTROY;
}
return result;
}
/*************************************************************************
outcome_intersect:
In: world: simulation state
rx: reaction that's taking place
path: path the reaction's taking
surface: wall that is being struck
reac: molecule that is hitting the wall
orient: orientation of the molecule
t: time that the reaction is occurring
hitpt: location of collision with wall
loc_okay:
Out: Value depending on outcome:
RX_A_OK if the molecule reflects
RX_FLIP if the molecule passes through
RX_DESTROY if the molecule stops, is destroyed, etc.
Additionally, products are created as needed.
Note: Can assume molecule is always first in the reaction.
*************************************************************************/
int outcome_intersect(struct volume *world, struct rxn *rx, int path,
struct wall *surface, struct abstract_molecule *reac,
short orient, double t, struct vector3 *hitpt,
struct vector3 *loc_okay) {
if (rx->n_pathways <= RX_SPECIAL) {
rx->n_occurred++;
if (rx->n_pathways == RX_REFLEC)
return RX_A_OK;
else
return RX_FLIP; /* Flip = transparent is default special case */
}
int idx = rx->product_idx[path];
if ((reac->properties->flags & NOT_FREE) == 0) {
struct volume_molecule *vm = (struct volume_molecule *)reac;
/* If reaction object has ALL_MOLECULES or ALL_VOLUME_MOLECULES as the
* first reactant it means that reaction is of the type ABSORPTIVE =
* ALL_MOLECULES or ABSORPTIVE = ALL_VOLUME_MOLECULES since other cases
* (REFLECTIVE/TRANSPARENT) are taken care above. But there are no products
* for this reaction, so we do no need to go into "outcome_products()"
* function. */
int result;
if ((strcmp(rx->players[0]->sym->name, "ALL_MOLECULES") == 0) ||
(strcmp(rx->players[0]->sym->name, "ALL_VOLUME_MOLECULES") == 0)) {
result = RX_DESTROY;
} else {
result = outcome_products_random(world, surface, hitpt, t, rx, path,
reac, NULL, orient, 0);
}
if (result == RX_BLOCKED)
return RX_A_OK; /* reflect the molecule */
rx->info[path].count++;
rx->n_occurred++;
if (rx->players[idx] == NULL) {
/* The code below is also valid for the special reaction of the type
* ABSORPTIVE = ALL_MOLECULES (or ALL_VOLUME_MOLECULES) */
vm->subvol->mol_count--;
if (world->place_waypoints_flag && (reac->flags & COUNT_ME)) {
if (hitpt == NULL) {
count_region_from_scratch(
world, reac, NULL, -1, NULL, NULL, t, reac->periodic_box);
} else {
struct vector3 fake_hitpt;
/* Halfway in between where we were and where we react should be a
* safe away-from-wall place to remove us */
if (loc_okay == NULL)
loc_okay = &(vm->pos);
fake_hitpt.x = 0.5 * hitpt->x + 0.5 * loc_okay->x;
fake_hitpt.y = 0.5 * hitpt->y + 0.5 * loc_okay->y;
fake_hitpt.z = 0.5 * hitpt->z + 0.5 * loc_okay->z;
count_region_from_scratch(world, reac, NULL, -1, &fake_hitpt, NULL,
t, reac->periodic_box);
}
}
free(reac->periodic_box);
reac->properties->n_deceased++;
double t_time = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, t);
reac->properties->cum_lifetime_seconds += t_time - reac->birthday;
reac->properties->population--;
if (vm->flags & IN_SCHEDULE) {
vm->subvol->local_storage->timer->defunct_count++;
}
#ifdef DEBUG_RXNS
DUMP_CONDITION3(
dump_volume_molecule((struct volume_molecule*)vm, "", true, " defunct m:", world->current_iterations, 0.0, false);
);
#endif
collect_molecule(vm);
return RX_DESTROY;
} else
return result; /* RX_A_OK or RX_FLIP */
} else {
/* Should really be an error because we should never call
* outcome_intersect() on a surface molecule */
return RX_A_OK;
}
}
/*************************************************************************
reaction_wizardry:
In: a list of releases to magically cause
the wall associated with the release, if any
the location of the release
the time of the release
Out: 0 if successful, 1 on failure (usually out of memory).
Each release event in the list is triggered at a location that
is relative to the location of the release and the surface normal
of the wall. The surface normal of the wall is considered to be
the +Z direction. Other coordinates are rotated in the "natural"
way (i.e. the XYZ coordinate system has the Z-axis rotated directly
to the direction of the normal and the other coordinates follow
along naturally; if the normal is in the -Z direction, the rotation
is about the X-axis.)
Note: this function isn't all that cheap computationally because of
all the math required to compute the right coordinate transform.
If this gets really really heavily used, we should store the
coordinate transform off of the wall data structure.
Note: it would be more efficient to skip calculating the transform if
the release type didn't use it (e.g. release by region).
Note: if we wanted to be extra-super clever, we could actually schedule
this event instead of running it and somehow have it start a
time-shifted release pattern (so we could have delays and stuff).
*************************************************************************/
int reaction_wizardry(struct volume *world, struct magic_list *incantation,
struct wall *surface, struct vector3 *hitpt, double t) {
struct release_event_queue req; /* Create a release event on the fly */
/* Release event happens "now" */
req.next = NULL;
req.event_time = t;
req.train_counter = 0;
req.train_high_time = t;
/* Set up transform to place products at site of reaction */
if (hitpt == NULL) {
init_matrix(req.t_matrix);
} else if (surface == NULL ||
!distinguishable(surface->normal.z, 1.0,
EPS_C)) /* Just need a translation */
{
init_matrix(req.t_matrix);
req.t_matrix[3][0] = hitpt->x;
req.t_matrix[3][1] = hitpt->y;
req.t_matrix[3][2] = hitpt->z;
} else /* Set up transform that will translate and then rotate Z axis to align
with surface normal */
{
struct vector3 scale = { 1.0, 1.0, 1.0 }; /* No scaling */
struct vector3 axis = { 1.0, 0.0, 0.0 }; /* X-axis is default */
double cos_theta;
double degrees;
cos_theta = surface->normal.z; /* (0,0,1) . surface->normal */
if (!distinguishable(cos_theta, -1.0, EPS_C)) {
degrees = 180.0; /* Upside-down */
} else {
/* (0,0,1) x surface->normal */
axis.x = -surface->normal.y;
axis.y = surface->normal.x;
axis.z = 0.0;
degrees = acos(cos_theta) * 180.0 / MY_PI;
}
tform_matrix(&scale, hitpt, &axis, degrees, req.t_matrix);
}
/* Now we're ready to cast our spell! */
for (; incantation != NULL; incantation = incantation->next) {
if (incantation->type != magic_release)
continue; /* Only know how to magically release stuff */
req.release_site = (struct release_site_obj *)incantation->data;
if (release_molecules(world, &req))
return 1;
}
return 0;
}
/************************************************************************
*
* this function determines where reactants grid1 and grid2 are located
* (inside/outside) with respect to their restrictive region borders if
* they have any.
*
* in: surface molecule 1 (located on wall 1)
* surface molecule 2 (located on wall 2)
* pointer to array with restrictive regions which contain wall 1
* pointer to array with restrictive regions which contain wall 2
* pointer to array with restrictive regions which don't contain wall 1
* pointer to array with restrictive regions which don't contain wall 2
*
* out: the 4 arrays with pointers to restrictive regions will be filled
* and returned
*
***********************************************************************/
int determine_molecule_region_topology(
struct volume *world, struct surface_molecule *sm_1,
struct surface_molecule *sm_2, struct region_list **rlp_wall_1_ptr,
struct region_list **rlp_wall_2_ptr, struct region_list **rlp_obj_1_ptr,
struct region_list **rlp_obj_2_ptr, bool is_unimol) {
int sm_bitmask = 0;
struct wall *w_1, *w_2;
struct region_list *rlp_head_wall_1 = NULL;
struct region_list *rlp_head_wall_2 = NULL;
struct region_list *rlp_head_obj_1 = NULL;
struct region_list *rlp_head_obj_2 = NULL;
/* bimolecular reactions */
if ((sm_1 != NULL) && (sm_2 != NULL)) {
/* both reactants have restrictive region borders */
if ((sm_1->properties->flags & CAN_REGION_BORDER) &&
(sm_2->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1) &&
are_restricted_regions_for_species_on_object(
world, sm_2->grid->surface->parent_object, sm_2)) {
w_1 = sm_1->grid->surface;
w_2 = sm_2->grid->surface;
rlp_head_wall_1 = find_restricted_regions_by_wall(world, w_1, sm_1);
rlp_head_wall_2 = find_restricted_regions_by_wall(world, w_2, sm_2);
/* both reactants are inside their respective restricted regions */
if ((rlp_head_wall_1 != NULL) && (rlp_head_wall_2 != NULL)) {
sm_bitmask |= ALL_INSIDE;
}
/* both reactants are outside their respective restricted regions */
else if ((rlp_head_wall_1 == NULL) && (rlp_head_wall_2 == NULL)) {
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
sm_bitmask |= ALL_OUTSIDE;
}
/* grid1 is inside and grid2 is outside of its respective
* restrictive region */
else if ((rlp_head_wall_1 != NULL) && (rlp_head_wall_2 == NULL)) {
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
sm_bitmask |= SURF1_IN_SURF2_OUT;
}
/* grid2 is inside and grid1 is outside of its respective
* restrictive region */
else if ((rlp_head_wall_1 == NULL) && (rlp_head_wall_2 != NULL)) {
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
sm_bitmask |= SURF1_OUT_SURF2_IN;
}
}
/* only reactant sm_1 has restrictive region border property */
else if ((sm_1->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1) &&
(!(sm_2->properties->flags & CAN_REGION_BORDER) ||
!are_restricted_regions_for_species_on_object(
world, sm_2->grid->surface->parent_object, sm_2))) {
w_1 = sm_1->grid->surface;
rlp_head_wall_1 = find_restricted_regions_by_wall(world, w_1, sm_1);
if (rlp_head_wall_1 != NULL) {
sm_bitmask |= SURF1_IN;
} else {
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
sm_bitmask |= SURF1_OUT;
}
}
/* only reactant "sm_2" has restrictive region border property */
else if ((sm_2->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_2->grid->surface->parent_object, sm_2) &&
(!(sm_1->properties->flags & CAN_REGION_BORDER) ||
!are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1))) {
w_2 = sm_2->grid->surface;
rlp_head_wall_2 = find_restricted_regions_by_wall(world, w_2, sm_2);
if (rlp_head_wall_2 != NULL) {
sm_bitmask |= SURF2_IN;
} else {
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
sm_bitmask |= SURF2_OUT;
}
}
}
/* unimolecular reactions */
else if ((sm_1 != NULL) && is_unimol) {
if ((sm_1->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1)) {
w_1 = sm_1->grid->surface;
rlp_head_wall_1 = find_restricted_regions_by_wall(world, w_1, sm_1);
if (rlp_head_wall_1 != NULL) {
sm_bitmask |= ALL_INSIDE;
} else {
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
sm_bitmask |= ALL_OUTSIDE;
}
}
}
*rlp_wall_1_ptr = rlp_head_wall_1;
*rlp_wall_2_ptr = rlp_head_wall_2;
*rlp_obj_1_ptr = rlp_head_obj_1;
*rlp_obj_2_ptr = rlp_head_obj_2;
return sm_bitmask;
}
/***********************************************************************
*
* this function tests if wall target can be reached for product placement
* based on the previously stored reactant topology based on
* sm_bitmask. Below, wall 1 is the wall containing reactant 1 and
* wall 2 is the wall containing reactant 2.
*
* in: wall to test for product placement
* pointer to array with regions that contain wall 1
* pointer to array with regions that contain wall 2
* pointer to array with regions that do not contain wall 1
* pointer to array with regions that do not contain wall 2
*
* out: returns true or false depending if wall target can be
* used for product placement.
*
***********************************************************************/
bool product_tile_can_be_reached(struct wall *target,
struct region_list *rlp_head_wall_1,
struct region_list *rlp_head_wall_2,
struct region_list *rlp_head_obj_1,
struct region_list *rlp_head_obj_2,
int sm_bitmask, bool is_unimol) {
bool status = true;
if (sm_bitmask & ALL_INSIDE) {
if (is_unimol) {
if (!wall_belongs_to_all_regions_in_region_list(target,
rlp_head_wall_1)) {
status = false;
}
} else {
/* bimol reaction */
if (!wall_belongs_to_all_regions_in_region_list(target,
rlp_head_wall_1) ||
!wall_belongs_to_all_regions_in_region_list(target,
rlp_head_wall_2)) {
status = false;
}
}
} else if (sm_bitmask & ALL_OUTSIDE) {
if (is_unimol) {
if (wall_belongs_to_any_region_in_region_list(target, rlp_head_obj_1)) {
status = false;
}
} else {
if (wall_belongs_to_any_region_in_region_list(target, rlp_head_obj_1) ||
wall_belongs_to_any_region_in_region_list(target, rlp_head_obj_2)) {
status = false;
}
}
} else if (sm_bitmask & SURF1_IN_SURF2_OUT) {
if (!wall_belongs_to_all_regions_in_region_list(target, rlp_head_wall_1) ||
wall_belongs_to_any_region_in_region_list(target, rlp_head_obj_2)) {
status = false;
}
} else if (sm_bitmask & SURF1_OUT_SURF2_IN) {
if (wall_belongs_to_any_region_in_region_list(target, rlp_head_obj_1) ||
!wall_belongs_to_all_regions_in_region_list(target, rlp_head_wall_2)) {
status = false;
}
} else if (sm_bitmask & SURF1_IN) {
if (!wall_belongs_to_all_regions_in_region_list(target, rlp_head_wall_1)) {
status = false;
}
} else if (sm_bitmask & SURF1_OUT) {
if (wall_belongs_to_any_region_in_region_list(target, rlp_head_obj_1)) {
status = false;
}
} else if (sm_bitmask & SURF2_IN) {
if (!wall_belongs_to_all_regions_in_region_list(target, rlp_head_wall_2)) {
status = false;
}
} else if (sm_bitmask & SURF2_OUT) {
if (wall_belongs_to_any_region_in_region_list(target, rlp_head_obj_2)) {
status = false;
}
}
return status;
}
/*
* cleanup_and_block_rx is a simple helper function which deletes the provided
* linked lists of tile_neighbors and the return RX_BLOCKED
*/
int cleanup_and_block_rx(struct tile_neighbor *tn1, struct tile_neighbor *tn2) {
if (tn1 != NULL) {
delete_tile_neighbor_list(tn1);
}
if (tn2 != NULL) {
delete_tile_neighbor_list(tn2);
}
return RX_BLOCKED;
}
| C |
3D | mcellteam/mcell | src/diffuse_util.h | .h | 736 | 20 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
double r_func(double s);
double *init_r_step(int radial_subdivisions);
double *init_r_step_surface(int radial_subdivisions);
double *init_r_step_3d_release(int radial_subdivisions);
double *init_d_step(int radial_directions, unsigned int *actual_directions);
| Unknown |
3D | mcellteam/mcell | src/dump_state.cpp | .cpp | 109,945 | 2,339 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/*
Regex to replace struct member definition by dumping code:
^[ \t]+([^ ]+) ([\*]?)([^ ]+);[^ \t]*(.*)
cout << ind2 << "\3: \\t\\t" << block->\3 << " [\1\2] \\t\\t\4\\n";
*/
#define DUMP_SCHEDULERS
//#define DUMP_WALLS
//#define DUMP_WAYPOINTS
//#define DUMP_SUBVOLUMES
//#define DUMP_RELEASE_REGION_DATA
#include "dump_state.h"
#include <iostream>
#include <string>
#include <cassert>
#include <string.h>
#include "dyngeom_parse_extras.h"
#include "bng_util.h"
#include "debug_config.h"
#define MAX_ARRAY_ITEMS 16
#define MAX_SUBVOLUMES 27
#define DUMP_ARRAY_NEWLINE_COUNT 8
#define IND_ADD2(ind) (std::string(ind) + " ").c_str()
#define DECL_IND2(ind) std::string inds = ind; inds += " "; const char* ind2 = inds.c_str();
using namespace std;
void dump_species(species* spec, const char* name, const char* comment, const char* ind);
void dump_species_list(int n_species, const char* num_name, species** species_list, const char* name, const char* comment, const char* ind);
void dump_species_item(species* spec, const char* ind);
void dump_object_list(geom_object* obj, const char* name, const char* comment, const char* ind);
void dump_wall_list(wall_list* list, const char* ind);
void dump_wall_array(int num, wall** wall_array, const char* ind);
void dump_object(geom_object* o, const char* ind);
void dump_region_list(region_list *rl, const char* regions_name, const char* comment, const char* ind);
const char* str(const char* ptr) {
if (ptr != nullptr) {
return ptr;
}
else {
return "0";
}
}
static const char* get_sym_name(const sym_entry *s) {
if (s == nullptr) {
return "NULL SYMBOL";
}
else {
return s->name;
}
}
std::ostream & operator<<(std::ostream &out, const timeval &a) {
out << a.tv_sec << "s, " << a.tv_usec << "us";
return out;
}
std::ostream & operator<<(std::ostream &out, const vector2 &a) {
out << "(" << a.u << ", " << a.v << ")";
return out;
}
std::ostream & operator<<(std::ostream &out, const vector3 &a) {
out << "(" << a.x << ", " << a.y << ", " << a.z << ")";
return out;
}
std::ostream & operator<<(std::ostream &out, const periodic_image &a) {
out << "(" << a.x << ", " << a.y << ", " << a.z << ")";
return out;
}
std::ostream & operator<<(std::ostream &out, const int3D &a) {
out << "(" << a.x << ", " << a.y << ", " << a.z << ")";
return out;
}
std::ostream & operator<<(std::ostream &out, const name_orient* a) {
if (a == nullptr) {
out << "NULL";
}
else {
for (const name_orient* curr = a; curr != nullptr; curr = curr->next) {
out << "(" << ((curr->name == nullptr) ? "NULL" : curr->name) << "," << curr->orient << "), ";
}
}
return out;
}
std::ostream & operator<<(std::ostream &out, const viz_mode_t &a) {
switch (a) {
case NO_VIZ_MODE: out << "NO_VIZ_MODE"; break;
case ASCII_MODE: out << "ASCII_MODE"; break;
case CELLBLENDER_MODE_V1: out << "CELLBLENDER_MODE"; break;
default: assert(false);
}
return out;
}
std::ostream & operator<<(std::ostream &out, const output_timer_type_t &a) {
switch (a) {
case OUTPUT_BY_STEP: out << "OUTPUT_BY_STEP"; break;
case OUTPUT_BY_TIME_LIST: out << "OUTPUT_BY_TIME_LIST"; break;
case OUTPUT_BY_ITERATION_LIST: out << "OUTPUT_BY_ITERATION_LIST"; break;
default: assert(false);
}
return out;
}
std::ostream & operator<<(std::ostream &out, const viz_frame_type_t &a) {
switch (a) {
case MOL_POS: out << "MOL_POS"; break;
case MOL_ORIENT: out << "MOL_ORIENT"; break;
case ALL_MOL_DATA: out << "ALL_MOL_DATA"; break;
case NUM_FRAME_TYPES: out << "NUM_FRAME_TYPES"; break;
default: assert(false);
}
return out;
}
std::ostream & operator<<(std::ostream &out, const object_type_t &a) {
switch (a) {
case META_OBJ: out << "META_OBJ"; break;
case BOX_OBJ: out << "BOX_OBJ"; break;
case POLY_OBJ: out << "POLY_OBJ"; break;
case REL_SITE_OBJ: out << "REL_SITE_OBJ"; break;
case VOXEL_OBJ: out << "VOXEL_OBJ"; break;
default: assert(false);
}
return out;
}
std::ostream & operator<<(std::ostream &out, const overwrite_policy_t &a) {
switch (a) {
case FILE_UNDEFINED: out << "FILE_UNDEFINED"; break;
case FILE_OVERWRITE: out << "FILE_OVERWRITE"; break;
case FILE_SUBSTITUTE: out << "FILE_SUBSTITUTE"; break;
case FILE_APPEND: out << "FILE_APPEND"; break;
case FILE_APPEND_HEADER: out << "FILE_APPEND_HEADER"; break;
case FILE_CREATE: out << "FILE_CREATE"; break;
default: assert(false);
}
return out;
}
std::ostream & operator<<(std::ostream &out, const count_type_t &a) {
switch (a) {
case COUNT_UNSET: out << "COUNT_UNSET"; break;
case COUNT_DBL: out << "COUNT_DBL"; break;
case COUNT_INT: out << "COUNT_INT"; break;
case COUNT_TRIG_STRUCT: out << "COUNT_TRIG_STRUCT"; break;
default: assert(false);
}
return out;
}
std::ostream & operator<<(std::ostream &out, const num_expr_list* a) {
out << "(";
const num_expr_list* p = a;
while (p != nullptr) {
out << p->value << ", ";
p = p->next;
}
out << ")";
return out;
}
std::ostream & operator<<(std::ostream &out, const double a[4][4]) {
out << "(";
for (int x = 0; x < 4; x++) {
out << "(";
for (int y = 0; y < 4; y++) {
out << a[x][y];
if (y != 3)
out << ",";
}
out << ")";
if (x != 3)
out << ",";
}
return out;
}
std::ostream & operator<<(std::ostream &out, const pointer_hash &a) {
//out << "(" << a.x << ", " << a.y << ", " << a.z << ")";
out << "(pointer_hash - TODO)";
return out;
}
std::ostream & operator<<(std::ostream &out, const sym_entry *s) {
if (s != NULL) {
// TODO: sym_type - see store_sym
out << "sym_entry(next:" << (void*)s->next << ", sym_type:" << s->sym_type << ", name:" << s->name << ", value:" << (void*)s->value << ", count:" << s->count << ")";
}
else {
out << "sym_entry(NULL)";
}
return out;
}
std::ostream & operator<<(std::ostream &out, const reaction_flags &a) {
#define DUMP_ITEM(name) #name << "=" << a.name << ", "
out
<< DUMP_ITEM(vol_vol_reaction_flag)
<< DUMP_ITEM(vol_surf_reaction_flag)
<< DUMP_ITEM(surf_surf_reaction_flag)
<< DUMP_ITEM(vol_wall_reaction_flag)
<< DUMP_ITEM(vol_vol_vol_reaction_flag)
<< DUMP_ITEM(vol_vol_surf_reaction_flag)
<< DUMP_ITEM(vol_surf_surf_reaction_flag)
<< DUMP_ITEM(vol_surf_surf_reaction_flag)
;
#undef DUMP_ITEM
return out;
}
std::ostream & operator<<(std::ostream &out, const output_expression *e);
void dump_oexpr_element(std::ostream &out, const int flags, void* child, bool left) {
int specific_flags = flags & ((left) ? OEXPR_LEFT_MASK : OEXPR_RIGHT_MASK);
if (specific_flags == OEXPR_LEFT_INT || specific_flags == OEXPR_RIGHT_INT) {
out << *(int*)child << "(" << (void*)child << ")";
}
else if (specific_flags == OEXPR_LEFT_DBL || specific_flags == OEXPR_RIGHT_DBL) {
out << *(double*)child;
}
else if (specific_flags == OEXPR_LEFT_OEXPR || specific_flags == OEXPR_RIGHT_OEXPR) {
out << (const output_expression*)child;
}
else if (specific_flags == OEXPR_LEFT_CONST || specific_flags == OEXPR_RIGHT_CONST) {
out << "TODO const";
}
else if (specific_flags == OEXPR_LEFT_REQUEST || specific_flags == OEXPR_RIGHT_REQUEST) {
out << "TODO request";
}
else if (specific_flags == OEXPR_LEFT_TRIG || specific_flags == OEXPR_RIGHT_TRIG) {
out << "TODO trig";
}
else {
out << ""; /*no children*/
}
out.flush();
}
std::ostream & operator<<(std::ostream &out, const output_expression *e) {
// NOTE: the flags for column_head::expr are somehow messed up... everything seems to be an integer
if (e != NULL) {
out <<
"("
"[" << ( (e->title != nullptr) ? e->title : "") << ", v:" << e->value << "] ";
dump_oexpr_element(out, e->expr_flags, e->left, true);
out << e->oper << " ";
dump_oexpr_element(out, e->expr_flags, e->right, false);
out << ")";
}
else {
out << "(NULL)";
}
return out;
}
#define DUMP_FLAG(f, mask) if (((f) & (mask)) != 0) res += string(#mask) + ", ";
string get_species_flags_string(uint flags) {
string res;
DUMP_FLAG(flags, ON_GRID)
DUMP_FLAG(flags, IS_SURFACE)
//DUMP_FLAG(flags, NOT_FREE) == ON_GRID | IS_SURFACE
DUMP_FLAG(flags, TIME_VARY)
DUMP_FLAG(flags, CAN_VOLVOLVOL)
DUMP_FLAG(flags, CAN_VOLVOL)
DUMP_FLAG(flags, CAN_VOLSURF)
DUMP_FLAG(flags, CAN_VOLWALL)
DUMP_FLAG(flags, CAN_SURFSURF)
DUMP_FLAG(flags, CAN_SURFWALL)
DUMP_FLAG(flags, CAN_VOLVOLSURF)
DUMP_FLAG(flags, CANT_INITIATE)
DUMP_FLAG(flags, COUNT_TRIGGER)
DUMP_FLAG(flags, COUNT_CONTENTS)
DUMP_FLAG(flags, COUNT_HITS)
DUMP_FLAG(flags, COUNT_RXNS)
DUMP_FLAG(flags, COUNT_ENCLOSED)
DUMP_FLAG(flags, CAN_VOLSURFSURF)
DUMP_FLAG(flags, CAN_SURFSURFSURF)
DUMP_FLAG(flags, SET_MAX_STEP_LENGTH)
DUMP_FLAG(flags, CAN_REGION_BORDER)
DUMP_FLAG(flags, REGION_PRESENT)
DUMP_FLAG(flags, EXTERNAL_SPECIES)
return res;
}
string get_molecule_flags_string(short flags, bool full_dump = true) {
string res;
DUMP_FLAG(flags, TYPE_SURF)
DUMP_FLAG(flags, TYPE_VOL)
if (full_dump) {
DUMP_FLAG(flags, ACT_DIFFUSE)
DUMP_FLAG(flags, ACT_REACT)
DUMP_FLAG(flags, ACT_NEWBIE)
DUMP_FLAG(flags, ACT_CHANGE)
}
DUMP_FLAG(flags, ACT_CLAMPED)
if (full_dump) {
DUMP_FLAG(flags, IN_SCHEDULE)
DUMP_FLAG(flags, IN_SURFACE)
}
DUMP_FLAG(flags, IN_VOLUME)
return res;
}
string get_report_type_flags_string(char report_type) {
string res;
#define DUMP_MASKED_VALUE(f, val) if ( ((f) & REPORT_TYPE_MASK) == val) res += string(#val) + ", ";
DUMP_MASKED_VALUE(report_type, REPORT_NOTHING)
DUMP_MASKED_VALUE(report_type, REPORT_CONTENTS)
DUMP_MASKED_VALUE(report_type, REPORT_RXNS)
DUMP_MASKED_VALUE(report_type, REPORT_FRONT_HITS)
DUMP_MASKED_VALUE(report_type, REPORT_BACK_HITS)
DUMP_MASKED_VALUE(report_type, REPORT_FRONT_CROSSINGS)
DUMP_MASKED_VALUE(report_type, REPORT_BACK_CROSSINGS)
DUMP_MASKED_VALUE(report_type, REPORT_ALL_HITS)
DUMP_MASKED_VALUE(report_type, REPORT_ALL_CROSSINGS)
DUMP_MASKED_VALUE(report_type, REPORT_CONCENTRATION)
DUMP_MASKED_VALUE(report_type, REPORT_ELAPSED_TIME)
DUMP_FLAG(report_type, REPORT_WORLD)
DUMP_FLAG(report_type, REPORT_ENCLOSED)
DUMP_FLAG(report_type, REPORT_TRIGGER)
return res;
}
string get_region_expression_flags_string(char op) {
string res;
DUMP_FLAG(op, REXP_NO_OP)
DUMP_FLAG(op, REXP_UNION)
DUMP_FLAG(op, REXP_INTERSECTION)
DUMP_FLAG(op, REXP_SUBTRACTION)
DUMP_FLAG(op, REXP_LEFT_REGION)
DUMP_FLAG(op, REXP_RIGHT_REGION)
return res;
}
#undef DUMP_FLAG
string get_release_shape_name(int8_t release_shape) {
string res;
#define CASE_ITEM(n) case n: res = #n; break;
switch (release_shape) {
CASE_ITEM(SHAPE_UNDEFINED)
CASE_ITEM(SHAPE_SPHERICAL)
CASE_ITEM(SHAPE_CUBIC)
CASE_ITEM(SHAPE_ELLIPTIC)
CASE_ITEM(SHAPE_RECTANGULAR)
CASE_ITEM(SHAPE_SPHERICAL_SHELL)
CASE_ITEM(SHAPE_REGION)
CASE_ITEM(SHAPE_LIST)
default: res = "unknown!"; break;
}
#undef CASE_ITEM
return res;
}
string get_release_number_method_string(release_number_type_t rt) {
string res;
#define CASE_ITEM(n) case n: res = #n; break;
switch (rt) {
CASE_ITEM(CONSTNUM)
CASE_ITEM(GAUSSNUM)
CASE_ITEM(VOLNUM)
CASE_ITEM(CCNNUM)
CASE_ITEM(DENSITYNUM)
default: res = "unknown!"; break;
}
#undef CASE_ITEM
return res;
}
void dump_double_array(int num, const char* num_name, double* values, const char* values_name, const char* comment, const char* ind, const int max = MAX_ARRAY_ITEMS) {
cout << ind << values_name << "[" << num_name << "]: \t\t" << values << "[" << num << "]" << " [double[]] \t\t" << comment;
for (int i = 0; i < num && i < max; i++) {
if (i % DUMP_ARRAY_NEWLINE_COUNT == 0) {
cout << "\n" << ind << " ";
}
cout << i << ":" << values[i] << ", ";
}
if (num >= max) {
cout << "...";
}
cout << "\n";
}
void dump_int_array(int num, const char* num_name, int* values, const char* values_name, const char* comment, const char* ind) {
cout << ind << values_name << "[" << num_name << "]: \t\t" << values << "[" << num << "]" << " [int[]] \t\t" << comment;
for (int i = 0; i < num && i < MAX_ARRAY_ITEMS; i++) {
if (i % DUMP_ARRAY_NEWLINE_COUNT == 0) {
cout << "\n" << ind << " ";
}
cout << i << ":" << values[i] << ", ";
}
if (num >= MAX_ARRAY_ITEMS) {
cout << "...";
}
cout << "\n";
}
void dump_string_array(int num, const char* num_name, const char** values, const char* values_name, const char* comment, const char* ind) {
cout << ind << values_name << "[" << num_name << "]: \t\t" << values << "[" << num << "]" << " [char*[]] \t\t" << comment;
for (int i = 0; i < num && i < MAX_ARRAY_ITEMS; i++) {
if (i % DUMP_ARRAY_NEWLINE_COUNT == 0) {
cout << "\n" << ind << " ";
}
cout << i << ":" << str(values[i]) << ", ";
}
if (num >= MAX_ARRAY_ITEMS) {
cout << "...";
}
cout << "\n";
}
void dump_vector3_array(int num, const char* num_name, vector3* values, const char* values_name, const char* comment, const char* ind) {
cout << ind << values_name << "[" << num_name << "]: \t\t" << values << "[" << num << "]" << " [vector3[]] \t\t" << comment;
for (int i = 0; i < num && i < MAX_ARRAY_ITEMS; i++) {
if (i % DUMP_ARRAY_NEWLINE_COUNT == 0) {
cout << "\n" << ind << " ";
}
cout << i << ":" << values[i] << ", ";
}
if (num >= MAX_ARRAY_ITEMS) {
cout << "...";
}
cout << "\n";
}
void dump_object(geom_object* o, const char* ind) {
DECL_IND2(ind);
if (o == nullptr) {
return;
}
cout << ind << "next: *\t\t" << o->next << " [object] \t\t/* Next sibling object */\n";
cout << ind << "parent: *\t\t" << o->parent << " [object] \t\t/* Parent meta object */\n";
cout << ind << "first_child: *\t\t" << o->first_child << " [object] \t\t/* First child object */\n";
cout << ind << "last_child: *\t\t" << o->last_child << " [object] \t\t/* Last child object */\n";
cout << ind << "sym: *\t\t" << o->sym << " [sym_entry] \t\t/* Symbol hash table entry for this object */\n";
if (o->last_name != nullptr) {
cout << ind << "last_name: *\t\t" << o->last_name << " [char] \t\t/* Name of object without pre-pended parent object name */\n";
}
else {
cout << ind << "last_name: *\t\t" << (void*)o->last_name << " [char] \t\t/* Name of object without pre-pended parent object name */\n";
}
cout << ind << "object_type: \t\t" << o->object_type << " [object_type_flags_t] \t\t/* Object Type Flags */\n";
cout << ind << "contents: *\t\t" << o->contents << " [void] \t\t/* Actual physical object, cast according to object_type */\n";
cout << ind << "num_regions: \t\t" << o->num_regions << " [u_int] \t\t/* Number of regions defined on object */\n";
//cout << ind << "regions: *\t\t" << o->regions << " [region_list] \t\t/* List of regions for this object */\n";
dump_region_list(o->regions, "regions", "/* List of regions for this object */", ind2);
cout << ind << "n_walls: \t\t" << o->n_walls << " [int] \t\t/* Total number of walls in object */\n";
cout << ind << "n_walls_actual: \t\t" << o->n_walls_actual << " [int] \t\t/* Number of non-null walls in object */\n";
cout << ind << "n_verts: \t\t" << o->n_verts << " [int] \t\t/* Total number of vertices in object */\n";
cout << ind << "vertices: **\t\t" << o->vertices << " [vector3] \t\t/* Array of pointers to vertices (linked to all_vertices array) */\n";
cout << ind << "total_area: \t\t" << o->total_area << " [double] \t\t/* Area of object in length units */\n";
cout << ind << "n_tiles: \t\t" << o->n_tiles << " [u_int] \t\t/* Number of surface grid tiles on object */\n";
cout << ind << "n_occupied_tiles: \t\t" << o->n_occupied_tiles << " [u_int] \t\t/* Number of occupied tiles on object */\n";
cout << ind << "t_matrix: *\t\t" << o->t_matrix << " [double[4][4]] \t\t /* Transformation matrix for object */\n";
cout << ind << "is_closed: \t\t" << o->is_closed << " [short] \t\t/* Flag that describes the geometry of the polygon object (e.g. for sphere is_closed = 1 and for plane is 0) */\n";
cout << ind << "periodic_x: \t\t" << o->periodic_x << " [bool] \t\t// This flag only applies to box objects BOX_OBJ. If set\n";
cout << ind << "periodic_y: \t\t" << o->periodic_y << " [bool] \t\t// any volume molecules encountering the box surface in the x,\n";
cout << ind << "periodic_z: \t\t" << o->periodic_z << " [bool] \t\t// y or z direction are reflected back into the box as if they had entered the adjacent neighboring box */\n";
dump_object_list(o->first_child, "first_child", "", ind2);
#ifdef DUMP_WALLS
cout << ind << "walls: *\t\t" << o->walls << " [wall] \t\t/* Array of walls in object */\n";
cout << ind << "wall_p: **\t\t" << o->wall_p << " [wall] \t\t// Array of ptrs to walls in object (used at run-time)\n";
dump_wall_array(o->n_walls, o->wall_p, ind2);
#endif
}
void dump_object_list(geom_object* obj, const char* name, const char* comment, const char* ind) {
cout << ind << name << " " << comment << "\n";
geom_object* curr = obj;
int i = 0;
while (curr != NULL) {
cout << ind << i << ":\n";
dump_object(curr, IND_ADD2(ind));
i++;
curr = curr->next;
}
}
void dump_edge(edge* e, const char* ind, const bool for_diff) {
DECL_IND2(ind);
if (e == nullptr) {
cout << ind << "NULL\n";
}
if (for_diff) {
cout << ind <<
"Edge: translate: " << e->translate <<
", cos_theta: " << e->cos_theta <<
", sin_theta: " << e->sin_theta <<
", edge_num_used_for_init: " << e->edge_num_used_for_init << "\n";
}
else {
cout << ind2 << "translate: \t\t" << e->translate << " [vector2] \t\t /* Translation vector between coordinate systems */\n";
cout << ind2 << "cos_theta: \t\t" << e->cos_theta << " [double] \t\t /* Cosine of angle between coordinate systems */\n";
cout << ind2 << "sin_theta: \t\t" << e->sin_theta << " [double] \t\t /* Sine of angle between coordinate systems */\n";
cout << ind2 << "length: \t\t" << e->length << " [double] \t\t /* Length of the shared edge */\n";
cout << ind2 << "length_1: \t\t" << e->length_1 << " [double] \t\t /* Reciprocal of length of shared edge */\n";
cout << ind2 << "edge_num_used_for_init: \t\t" << e->edge_num_used_for_init << " [int] \t\t // edge used for initialization\n";
}
}
void dump_wall(wall* w, const char* ind, const bool for_diff) {
if (for_diff) {
if (w == nullptr) {
cout << "wall: NULL!!!";
return;
}
cout << "wall[side: " << w->side << "]: ";
for (uint i = 0; i < 3; i++) {
cout << *w->vert[i];
if (i != 2) {
cout << ", ";
}
}
cout << "\n";
}
else {
if (w == nullptr) {
return;
}
DECL_IND2(ind);
cout << ind << "this wall: " << (void*)w << "\n";
cout << ind << "next: *\t\t" << (void*)w->next << " [wall] \t\t/* Next wall in the universe */\n";
cout << ind << "surf_class_head: *\t\t" << (void*)w->surf_class_head << " [surf_class_list] \t\t/* linked list of surface classes for this wall (multiple surface classes may come from the overlapping regions */\n";
cout << ind << "num_surf_classes: \t\t" << w->num_surf_classes << " [int] \t\t/* number of attached surface classes */\n";
cout << ind << "side: \t\t" << w->side << " [int] \t\t/* index of this wall in its parent object */\n";
cout << ind << "vert[3]: 0: " << *w->vert[0] << ", 1: " << *w->vert[1] << ", 2: " << *w->vert[2] << "\n";
cout << ind << "uv_vert1_u: \t\t" << w->uv_vert1_u << " [double] \t\t/* Surface u-coord of 2nd corner (v=0) */\n";
cout << ind << "uv_vert2: \t\t" << w->uv_vert2 << " [vector2] \t\t/* Surface coords of third corner */\n";
cout << ind << "edges[3]: *\t\t" << (void*)w->edges << " [*edges[3]] \t\t/* /* Array of pointers to each edge. */ // TODO */\n";
for (int i = 0; i < 3; i++) {
cout << ind << i << ":\n";
dump_edge(w->edges[i], ind2);
}
cout << ind << "nb_walls[0]: *\t\t" << (void*)w->nb_walls[0] << " [wall] \t\t/* Array of pointers to walls that share an edge*/ // TODO\n";
cout << ind << "nb_walls[1]: *\t\t" << (void*)w->nb_walls[1] << " [wall] \t\t/* Array of pointers to walls that share an edge*/ // TODO\n";
cout << ind << "nb_walls[2]: *\t\t" << (void*)w->nb_walls[2] << " [wall] \t\t/* Array of pointers to walls that share an edge*/ // TODO\n";
cout << ind << "area: \t\t" << w->area << " [double] \t\t/* Area of this element */\n";
cout << ind << "normal: \t\t" << w->normal << " [vector3] \t\t/* Normal vector for this wall */\n";
cout << ind << "unit_u: \t\t" << w->unit_u << " [vector3] \t\t/* U basis vector for this wall */\n";
cout << ind << "unit_v: \t\t" << w->unit_v << " [vector3] \t\t/* V basis vector for this wall */\n";
cout << ind << "d: \t\t" << w->d << " [double] \t\t/* Distance to origin (point normal form) */\n";
cout << ind << "grid: *\t\t" << w->grid << " [surface_grid] \t\t/* Grid of effectors for this wall */\n";
cout << ind << "flags: \t\t" << w->flags << " [u_short] \t\t/* Count Flags: flags for whether and what we need to count */\n";
cout << ind << "parent_object: *\t\t" << w->parent_object << " [object] \t\t/* The object we are a part of */\n";
//dump_object(w->parent_object, ind2);
cout << ind << "birthplace: *\t\t" << w->birthplace << " [storage] \t\t/* Where we live in memory */\n";
cout << ind << "counting_regions: *\t\t" << w->counting_regions << " [region_list] \t\t/* Counted-on regions containing this wall */\n";
}
}
void dump_wall_array(int num, wall** wall_array, const char* ind) {
if (wall_array == NULL) {
cout << "\n";
return;
}
for (int i = 0; i < num && i < MAX_ARRAY_ITEMS; i++) {
if (i % DUMP_ARRAY_NEWLINE_COUNT == 0) {
cout << "\n" << ind << " ";
}
cout << ind << i << ":\n";
dump_wall(wall_array[i], IND_ADD2(ind), false);
}
}
void dump_wall_list(wall_list* list, const char* ind) {
wall_list* curr = list;
int i = 0;
while (curr != NULL) {
cout << ind << i << ":\n";
dump_wall(curr->this_wall, IND_ADD2(ind), false);
i++;
curr = curr->next;
}
}
void dump_wall_list_array(int num, const char* num_name, wall_list** values, const char* values_name, const char* comment, const char* ind) {
cout << ind << values_name << "[" << num_name << "]: \t\t" << values << "[" << num << "]" << " [wall_list*] \t\t" << comment;
if (values == NULL) {
cout << "\n";
return;
}
for (int i = 0; i < num && i < MAX_ARRAY_ITEMS; i++) {
if (i % DUMP_ARRAY_NEWLINE_COUNT == 0) {
cout << "\n" << ind << " ";
}
cout << ind << i << ":\n";
dump_wall_list(values[i], IND_ADD2(ind));
}
if (num >= MAX_ARRAY_ITEMS) {
cout << "...";
}
cout << "\n";
}
void dump_molecule_flags(short flags, const char* ind) {
cout << ind << "flags: \t\t" << flags << " [short] \t\t /* Abstract Molecule Flags: Who am I, what am I doing, etc. */\n";
cout << ind << " " << get_molecule_flags_string(flags) << "\n";
}
void dump_abstract_molecule(abstract_molecule* amp, const char* ind) {
cout << ind << "this: *\t\t" << (void*)amp << " [abstract_molecule] \t\t /* Current molecule */ //???\n";
cout << ind << "next: *\t\t" << (void*)amp->next << " [abstract_molecule] \t\t /* Next molecule in scheduling queue */ //???\n";
cout << ind << "t: \t\t" << amp->t << " [double] \t\t /* Scheduling time. */\n";
cout << ind << "t2: \t\t" << amp->t2 << " [double] \t\t /* Time of next unimolecular reaction */\n";
dump_molecule_flags(amp->flags, " ");
cout << ind << "properties: *\t\t" << (void*)amp->properties << " [species] \t\t /* What type of molecule are we? */\n";
cout << ind << "birthplace: *\t\t" << (void*)amp->birthplace << " [mem_helper] \t\t /* What was I allocated from? */\n";
cout << ind << "birthday: \t\t" << amp->birthday << " [double] \t\t /* Real time at which this particle was born */\n";
cout << ind << "id: \t\t" << amp->id << " [u_long] \t\t /* unique identifier of this molecule */\n";
cout << ind << "periodic_box: *\t\t" << (void*)amp->periodic_box << " [periodic_image] \t\t /* track the periodic box a molecule is in */\n";
cout << ind << "graph_data: *\t\t" << (void*)amp->graph_data << " [graph_data] \t\t /* nfsim graph structure data */\n";
#if 0 // nfsim function pointers, not important for now
u_int (*get_flags)(void *); /* (nfsim) returns the reactivity flags associated with this particle */
double (*get_diffusion)(void *); /* (nfsim) returns the diffusion value */
double (*get_time_step)(void *); /* (nfsim) function pointer to a method that returns the time step */
double (*get_space_step)(void *); /* (nfsim) function pointer to a method that returns the space step */
/* end structs used by the nfsim integration */
#endif
cout << ind << "mesh_name: *\t\t" << amp->mesh_name << " [char] \t\t /* Name of mesh that molecule is either in (volume molecule) or on (surface molecule) */\n";
}
void dump_surface_molecule(surface_molecule* amp, const char* ind) {
cout << "***TODO!\n";
}
void dump_molecules(int num_all_molecules, molecule_info **all_molecules) {
cout << "all_molecules: **\t\t" << (void**)all_molecules << " [molecule_info] \n";
cout << "num_all_molecules: \t\t" << num_all_molecules << " [int] \n";
for (int i = 0; i < num_all_molecules; i++) {
molecule_info *curr = all_molecules[i];
assert(curr != NULL);
abstract_molecule *amp = curr->molecule;
assert(amp != NULL);
if ((amp->properties->flags & NOT_FREE) == 0) {
volume_molecule *vmp = (volume_molecule *)amp;
dump_volume_molecule(vmp, " ", true, "", 0, 0.0, true);
} else if ((amp->properties->flags & ON_GRID) != 0) {
surface_molecule *smp = (surface_molecule *)amp;
dump_surface_molecule(smp, " ");
} else {
dump_abstract_molecule(amp, " ");
}
cout << "reg_names: *\t\t" << curr->reg_names << " [string_buffer] \t\t /* Region names */\n";
cout << "mesh_names: *\t\t" << curr->mesh_names << " [string_buffer] \t\t /* Mesh names that molec is nested in */\n";
cout << "pos: \t\t" << curr->pos << " [vector3] \t\t /* Position in space */\n";
cout << "orient: \t\t" << curr->orient << " [short] \t\t /* Which way do we point? */\n";
}
}
void dump_sm_dat(sm_dat* smd, const char* name, const char* comment, const char* ind) {
DECL_IND2(ind)
cout << ind << name << ": *\t\t" << (void*)smd << " [sm_dat] \t\t " << comment << "\n";
sm_dat* curr = smd;
int i = 0;
while (curr != nullptr) {
cout << ind << i << ":\n";
cout << ind2 << "sm: *\t\t" << get_sym_name(curr->sm->sym) << " [species name] \t\t /* Species to place on surface */\n";
cout << ind2 << "quantity_type: *\t\t" << ((curr->quantity_type == SURFMOLDENS) ? "SURFMOLDENS" : "SURFMOLNUM") << " [byte] \t\t // Placement Type Flags: either SURFMOLDENS or SURFMOLNUM\n";
cout << ind2 << "quantity: \t\t" << curr->quantity << " [double] \t\t // Amount of surface molecules to place by density or number\n";
cout << ind2 << "orientation: \t\t" << curr->orientation << " [short] \t\t /* Orientation of molecules to place */\n";
i++;
curr = curr->next;
}
}
void dump_region(region* reg, const char* ind) {
DECL_IND2(ind)
// TODO XXXXXXXX
cout << ind << "reg: *\t\t" << (void*)reg << " [region] \t\t\n";
if (reg == nullptr) {
return;
}
cout << ind << " " << "sym: *\t\t" << reg->sym << " [sym_entry] \t\t /* Symbol hash table entry for this region */\n";
cout << ind << " " << "hashval: \t\t" << reg->hashval << " [u_int] \t\t /* Hash value for counter hash table */\n";
cout << ind << " " << "region_last_name: *\t\t" << reg->region_last_name << " [char] \t\t /* Name of region without prepended object name */\n";
cout << ind << " " << "parent: *\t\t" << (void*)reg->parent << " [object] \t\t /* Parent of this region */\n";
cout << ind << " " << "element_list_head: *\t\t" << (void*)reg->element_list_head << " [element_list] \t\t /* List of element ranges comprising this region (used at parse time) */\n";
cout << ind << " " << "membership: *\t\t" << (void*)reg->membership << " [bit_array] \t\t /* Each bit indicates whether the corresponding wall is in the region */\n";
//cout << ind << " " << "sm_dat_head: *\t\t" << (void*)reg->sm_dat_head << " [sm_dat] \t\t /* List of surface molecules to add to region */\n";
dump_sm_dat(reg->sm_dat_head, "sm_dat_head", "/* List of surface molecules to add to region */", ind2);
dump_species(reg->surf_class, "surf_class", "/* Surface class of this region */", ind2);
cout << ind << " " << "bbox: *\t\t" << (void*)reg->bbox << " [vector3] \t\t /* Array of length 2 to hold corners of region bounding box (used for release in region) */\n";
cout << ind << " " << "area: \t\t" << reg->area << " [double] \t\t /* Area of region */\n";
cout << ind << " " << "flags: \t\t" << reg->flags << " [u_short] \t\t /* Counting subset of Species Flags */\n";
cout << ind << " " << "manifold_flag: \t\t" << (int)reg->manifold_flag << " [byte] \t\t /* Manifold Flags: If IS_MANIFOLD, region is a closed manifold and thus defines a volume */\n";
cout << ind << " " << "volume: \t\t" << reg->volume << " [double] \t\t /* volume of region for closed manifolds */\n";
cout << ind << " " << "boundaries: *\t\t" << (void*)reg->boundaries << " [pointer_hash] \t\t /* hash table of edges that constitute external boundary of the region */\n";
cout << ind << " " << "region_has_all_elements: \t\t" << reg->region_has_all_elements << " [int] \t\t /* flag that tells whether the region contains ALL_ELEMENTS (effectively comprises the whole object) */\n";
}
void dump_region_list(region_list *rl, const char* regions_name, const char* comment, const char* ind) {
cout << ind << regions_name << ": *\t\t" << rl << " [region_list] \t\t " << comment << "\n";
for (region_list *r = rl; r != NULL; r = r->next) {
dump_region(r->reg, IND_ADD2(ind) );
}
}
void dump_one_waypoint(waypoint* wp, const char* ind) {
assert(wp != NULL);
cout << ind << "waypoint: *\t\t" << (void*)wp << " [waypoint] \t\t\n";
cout << ind << " " << "loc: \t\t" << wp->loc << " [vector3] \t\t /* This is where the waypoint is */\n";
dump_region_list(wp->regions, "regions", "/* We are inside these regions */", IND_ADD2(ind));
dump_region_list(wp->antiregions, "antiregions", "/* We are outside of (but hit) these regions */", IND_ADD2(ind));
}
void dump_waypoints(int n_waypoints, waypoint* waypoints) {
cout << "n_waypoints: \t\t" << n_waypoints << " [int] \t\t/* How many waypoints (one per subvol) */\n";
cout << "waypoints: *\t\t" << (void*)waypoints << " [waypoint] \t\t/* Waypoints contain fully-closed region information */\n";
for (int i = 0; i < n_waypoints; i++) {
dump_one_waypoint(&waypoints[i], " ");
}
}
void dump_one_subvolume(subvolume* sv, const char* ind) {
assert(sv != NULL);
DECL_IND2(ind);
cout << ind << "subvolume: *\t\t" << (void*)sv << " [subvolume] \t\t\n";
#ifdef DUMP_WALLS
cout << ind << " " << "wall_head: *\t\t" << (void*)sv->wall_head << " [wall_list] \t\t /* Head of linked list of intersecting walls */\n";
dump_wall_list(sv->wall_head, ind2);
#endif
cout << ind << " " << "mol_by_species: \t\t" << sv->mol_by_species << " [pointer_hash] \t\t /* table of speciesv->molecule list */\n";
cout << ind << " " << "species_head: *\t\t" << (void*)sv->species_head << " [per_species_list] \t\t\n";
cout << ind << " " << "mol_count: \t\t" << sv->mol_count << " [int] \t\t /* How many molecules are here? */\n";
cout << ind << " " << "llf: \t\t" << sv->llf << " [int3D] \t\t /* Indices of left lower front corner */\n";
cout << ind << " " << "urb: \t\t" << sv->urb << " [int3D] \t\t /* Indices of upper right back corner */\n";
cout << ind << " " << "world_edge: \t\t" << sv->world_edge << " [short] \t\t /* Direction Bit Flags that are set for SSVs at edge of world */\n";
cout << ind << " " << "local_storage: *\t\t" << (void*)sv->local_storage << " [storage] \t\t /* Local memory and scheduler */\n";
}
void dump_subvolumes(int n_subvols, const char* num_name, const char* num_comment, subvolume* subvols, const char* subvols_name, const char* name_comment, const char* ind) {
cout << ind << num_name << ": \t\t" << n_subvols << " [int] \t\t" << num_comment << "\n";
cout << ind << subvols_name << ": *\t\t" << (void*)subvols << " [subvolume] \t\t" << name_comment << "\n";
for (int i = 0; i < n_subvols && i < MAX_SUBVOLUMES; i++) {
dump_one_subvolume(&subvols[i], " ");
}
if (n_subvols >= MAX_SUBVOLUMES) {
cout << ind << " " << "... (total " << n_subvols << ")\n";
}
}
void dump_product_list(product* prod, const char* ind) {
DECL_IND2(ind);
product* prod_ptr = prod;
int i = 0;
while (prod_ptr != nullptr) {
cout << ind << i << ":\n";
cout << ind2 << "orientation: \t\t" << prod_ptr->orientation << " [short] \t\t/* Orientation to place molecule */\n";
dump_species(prod_ptr->prod, "product", "", ind2);
prod_ptr = prod_ptr->next;
}
}
void dump_pathway(pathway* pathway_ptr, const char* ind) {
assert(pathway_ptr != nullptr);
//DECL_IND2(ind);
cout << ind << "next: *\t\t" << (void*)pathway_ptr->next << " [pathway] \t\t/* Next pathway for this reaction */\n";
cout << ind << "pathname: *\t\t" << (void*)pathway_ptr->pathname << " [rxn_pathname] \t\t/* Data for named reaction pathway or NULL */\n";
//cout << ind << "reactant1: *\t\t" << pathway_ptr->reactant1 << " [species] \t\t/* First reactant in reaction pathway */\n";
dump_species(pathway_ptr->reactant1, "reactant1", "/* First reactant in reaction pathway */", ind);
//cout << ind << "reactant2: *\t\t" << pathway_ptr->reactant2 << " [species] \t\t/* Second reactant (NULL if none) */\n";
dump_species(pathway_ptr->reactant2, "reactant2", "/* Second reactant in reaction pathway */", ind);
//cout << ind << "reactant3: *\t\t" << pathway_ptr->reactant3 << " [species] \t\t/* Third reactant (NULL if none) */\n";
dump_species(pathway_ptr->reactant3, "reactant3", "/* Third reactant in reaction pathway */", ind);
cout << ind << "km: \t\t" << pathway_ptr->km << " [double] \t\t/* Rate constant */\n";
cout << ind << "km_filename: *\t\t" << ((pathway_ptr->km_filename == nullptr) ? "NULL" : pathway_ptr->km_filename) << " [char*] \t\t/* Filename for time-varying rates */\n";
cout << ind << "orientation1: \t\t" << pathway_ptr->orientation1 << " [short] \t\t/* Orientation of first reactant */\n";
cout << ind << "orientation2: \t\t" << pathway_ptr->orientation2 << " [short] \t\t/* Orientation of second reactant */\n";
cout << ind << "orientation3: \t\t" << pathway_ptr->orientation3 << " [short] \t\t/* Orientation of third reactant */\n";
cout << ind << "product_head: *\t\t" << (void*)pathway_ptr->product_head << " [product] \t\t/* Linked lists of species created */\n";
dump_product_list(pathway_ptr->product_head, ind);
cout << ind << "prod_signature: *\t\t" << ((pathway_ptr->prod_signature == nullptr) ? "NULL" : pathway_ptr->prod_signature) << " [char*] \t\t/* string created from the names of products put in alphabetical order */\n";
cout << ind << "flags: \t\t" << pathway_ptr->flags << " [short] \t\t/* flags describing special reactions - REFLECTIVE, TRANSPARENT, CLAMP_CONCENTRATION */\n";
}
void dump_pathway_list(pathway* pathway_head, const char* name, const char* comment, const char* ind) {
DECL_IND2(ind);
if (pathway_head == nullptr) {
cout << ind << name << ": *\t\t" << (void*)pathway_head << " [pathway*] \t\t" << comment << "\n";
}
pathway* pathway_ptr = pathway_head;
int idx = 0;
while (pathway_ptr != nullptr) {
cout << ind << name << "[" << idx << "]" << ": *\t\t" << (void*)pathway_ptr << " [pathway*] \t\t" << comment << "\n";
dump_pathway(pathway_ptr, ind2);
pathway_ptr = pathway_ptr->next;
}
}
void dump_rxn_pathname(rxn_pathname* pathname, const char* ind) {
DECL_IND2(ind);
cout << ind << "pathname: *\t\t" << (void*)pathname << " [rxn_pathname]\n";
if (pathname == nullptr) {
return;
}
cout << ind2 << "sym: *\t\t" << pathname->sym << " [sym_entry] \t\t/* Ptr to symbol table entry for this rxn name */\n";
cout << ind2 << "hashval: \t\t" << pathname->hashval << " [u_int] \t\t/* Hash value for counting named rxns on regions */\n";
cout << ind2 << "path_num: \t\t" << pathname->path_num << " [u_int] \t\t/* Pathway number in rxn */\n";
cout << ind2 << "rx: *\t\t" << (void*)pathname->rx << " [rxn] \t\t/* The rxn associated with this name */\n";
cout << ind2 << "magic: *\t\t" << (void*)pathname->magic << " [magic_list] \t\t/* A list of stuff that magically happens when the reaction happens */\n";
}
void dump_pathway_infos(int n_pathways, const char* count_name, pathway_info* pathway_info_array, const char* name, const char* comment, const char* ind) {
DECL_IND2(ind);
if (pathway_info_array == nullptr) {
cout << ind << name << ": *\t\t" << (void*)pathway_info_array << " [pathway*] \t\t" << comment << "\n";
}
for (int i = 0; i < n_pathways; i++) {
cout << ind << name << "[" << i << "]" << ":\n";
cout << ind2 << "count: *\t\t" << pathway_info_array[i].count << " [double] \t\t/* How many times the pathway has been taken */\n";
//dump_pathway(&pathway_info_array[n_pathways], ind2);
dump_rxn_pathname(pathway_info_array[i].pathname, ind2);
}
}
void dump_variable_rxn_rates(t_func* prob_t, const char* name, const char* ind) {
DECL_IND2(ind);
cout << ind << "prob_t: *\t\t" << (void*)prob_t << " [t_func] \t\t/* List of probabilities changing over time, by pathway */\n";
int i = 0;
for (t_func* curr = prob_t; curr != nullptr; curr = curr->next) {
cout << ind2 << i << ": time: " << curr->time << ", value: " << curr->value << ", path: " << curr->path << "\n";
i++;
}
}
void dump_molecule_species(abstract_molecule *m) {
if ((m->properties->flags & EXTERNAL_SPECIES) == 0) {
cout << get_sym_name(m->properties->sym);
}
else {
assert(m->graph_data != nullptr);
cout << graph_pattern_to_bngl(m->graph_data->graph_pattern);
}
}
void dump_rxn_substance(species* s, short orient) {
if ((s->flags & EXTERNAL_SPECIES) == 0) {
cout << get_sym_name(s->sym);
}
else {
cout << "BNG";
}
}
void dump_rxn_pathway_for_diff(pathway* pw) {
dump_rxn_substance(pw->reactant1, pw->orientation1);
if (pw->reactant2 != nullptr) {
cout << " + ";
dump_rxn_substance(pw->reactant2, pw->orientation2);
}
cout << " -> ";
product* prod = pw->product_head;
while (prod != nullptr) {
dump_rxn_substance(prod->prod, prod->orientation);
prod = prod->next;
}
cout << "\n";
}
void dump_rxn_for_diff(rxn* rx) {
cout << "max_fixed_p: \t\t" << rx->max_fixed_p << " [double]\n";
cout << "min_noreaction_p: \t\t" << rx->min_noreaction_p << " [double]\n";
cout << "cum_probs: ";
for (int i = 0; i < rx->n_pathways; i++) {
cout << rx->cum_probs[i] << ", ";
}
cout << "\n";
if (rx->product_graph_data == NULL) {
pathway* current_pathway = rx->pathway_head;
for (int i = 0; i < rx->n_pathways && current_pathway != nullptr; i++) {
dump_rxn_pathway_for_diff(current_pathway);
current_pathway = current_pathway->next;
}
}
else {
cout << "BNG pathways:\n";
for (int path = 0; path < rx->n_pathways; path++) {
cout << " " << path << ": ";
/* index of the first player for the pathway */
int const i0 = rx->product_idx[path];
/* index of the first player for the next pathway */
int const iN = rx->product_idx[path + 1];
int const n_players = iN - i0;
if (n_players == 0) {
// this pathway was not set...
cout << "not set\n";
continue;
}
for (int n_product = rx->n_reactants; n_product < n_players; ++n_product) {
struct graph_data* g_data = rx->product_graph_data[path][n_product - rx->n_reactants];
cout << graph_pattern_to_bngl(g_data->graph_pattern);
if (n_product != n_players - 1) {
cout << " + ";
}
}
cout << "\n";
}
}
}
void dump_rxn(rxn* rx, const char* ind, bool for_diff) {
if (for_diff) {
dump_rxn_for_diff(rx);
return;
}
cout << ind << "sym: *\t\t" << rx->sym << " [sym_entry] \t\t/* Ptr to symbol table entry for this rxn */\n";
cout << ind << "n_reactants: \t\t" << rx->n_reactants << " [u_int] \t\t/* How many reactants? (At least 1.) */\n";
cout << ind << "n_pathways: \t\t" << rx->n_pathways << " [int] \t\t/* How many pathways lead away? (Negative = special reaction, i.e. transparent etc...) */\n";
#if 0
for (int j = 0; j < rx->n_pathways; ++j) {
struct rxn_pathname *path = rx->info[j].pathname;
if (path != NULL && strcmp(path->sym->name, rx_name) == 0) {
*found_rx = rx;
// XXX below we convert from u_int to int which is bad
// unfortunately MCell internally mixes u_int and int for
// the pathway id.
*path_id = path->path_num;
cout << "0: \t\t" << s->0 << " [return] \t\t\n";
}
}
#endif
dump_double_array(rx->n_pathways, "n_pathways", rx->cum_probs, "cum_probs", "/* Cumulative probabilities for (entering) all pathways */", ind);
cout << ind << "max_fixed_p: \t\t" << rx->max_fixed_p << " [double] \t\t/* Maximum 'p' for region of p-space for all non-cooperative pathways */\n";
cout << ind << "min_noreaction_p: \t\t" << rx->min_noreaction_p << " [double] \t\t/* Minimum 'p' for region of p-space which is always in the non-reacting pathway. (note that cooperativity may mean that some values of p less than this still do not produce a reaction) */\n";
cout << ind << "pb_factor: \t\t" << rx->pb_factor << " [double] \t\t/* Conversion factor from rxn rate to rxn probability (used for cooperativity) */\n";
cout << ind << "product_idx_aux: *\t\t" << (void*)rx->product_idx_aux << " [int] \t\t/* Number of unique players in each pathway. Used for on-the fly calculation of product_idx indexes TODO: nfsim*/\n";
//dump_int_array(rx->n_pathways, "n_pathways", rx->product_idx_aux, "product_idx_aux", "/* Number of unique players in each pathway. Used for on-the fly calculation of product_idx indexes */", ind);
cout << ind << "product_idx: *\t\t" << rx->product_idx << " [u_int] \t\t/* Index of 1st player for products of each pathway TODO: nfsim */\n";
//dump_int_array(rx->n_pathways, "n_pathways", (int*)rx->product_idx, "product_idx", "/* Index of 1st player for products of each pathway */", ind);
cout << ind << "players: **\t\t" << (void**)rx->players << " [species] \t\t/* Identities of reactants/products */\n";
dump_species_list(rx->n_reactants/*might be *n_pathways*/, "n_reactants", rx->players, "players", "/* Identities of reactants/products */", " ");
/* this information is kept in a separate array because with nfsim we dont know ahead of time how many paths/products per path are there, we only know when it fires*/
cout << ind << "nfsim_players: ***\t\t" << (void***)rx->nfsim_players << " [species] \t\t/* a matrix of the nfsim elements associated with each path */\n";
cout << ind << "geometries: *\t\t" << (void*)rx->geometries << " [short] \t\t/* Geometries of reactants/products */\n";
cout << ind << "nfsim_geometries: **\t\t" << (void**)rx->nfsim_geometries << " [short] \t\t/* geometries of the nfsim geometries associated with each path */\n";
cout << ind << "n_occurred: \t\t" << rx->n_occurred << " [long long] \t\t/* How many times has this reaction occurred? */\n";
cout << ind << "n_skipped: \t\t" << rx->n_skipped << " [double] \t\t/* How many reactions were skipped due to probability overflow? */\n";
dump_variable_rxn_rates(rx->prob_t, "prob_t", " ");
cout << ind << "pathway_head: *\t\t" << rx->pathway_head << " [pathway] \t\t/* List of pathways built at parse-time */\n";
dump_pathway_list(rx->pathway_head, "pathway_head", "/* List of pathways built at parse-time */", " ");
cout << ind << "info: *\t\t" << (void*)rx->info << " [pathway_info] \t\t/* Counts and names for each pathway */\n";
dump_pathway_infos(rx->n_pathways, "n_pathways", rx->info, "info", "/* Counts and names for each pathway */", " ");
cout << ind << "TODO: NFSIM callbacks\n";
#if 0
//char** external_reaction_names; /* Stores reaction results stored from an external program (like nfsim)*/
external_reaction_datastruct* external_reaction_data; /* Stores reaction results stored from an external program (like nfsim)*/
graph_data** reactant_graph_data; /* stores the graph patterns associated with the reactants for every path */
graph_data*** product_graph_data; /* Stores the graph patterns associated with our products for each path*/
double (*get_reactant_diffusion)(rxn*, int); /* returns the diffusion value associated with its reactants*/
double (*get_reactant_time_step)(rxn*, int); /* returns the diffusion value associated with its reactants*/
double (*get_reactant_space_step)(rxn*, int); /* returns the diffusion value associated with its reactants*/
#endif
}
void dump_reaction_hash_table(int rx_hashsize, const char* num_name, rxn **reaction_hash, const char* reaction_hash_name, const char* comment, const char* ind) {
cout << ind << reaction_hash_name << "[" << num_name << "]: \t\t" << (void*)reaction_hash << "[" << rx_hashsize << "]" << " [reaction_hash*] \t\t" << comment << "\n";
// used code from get_rxn_by_name
for (int i = 0; i < rx_hashsize; ++i) {
struct rxn *rx = NULL;
struct rxn *rx_array = reaction_hash[i];
cout << IND_ADD2(ind) << i << ": " << (void*)rx_array << "\n";
int k = 0;
for (rx = rx_array; rx != NULL; rx = rx->next) { // go over linked list
cout << IND_ADD2(IND_ADD2(ind)) << k << ":\n";
dump_rxn(rx, IND_ADD2(IND_ADD2(ind)));
}
}
}
void dump_region_data_owners(
int n_objects, int* obj_index, geom_object** owners, const char* name, const char* comments, const char* ind
) {
cout << ind << "owners: **\t\t" << owners << " [object] \t\t/* Array of pointers to each object */\n";
if (owners == nullptr) {
return;
}
DECL_IND2(ind);
// get max index for owners array
int max_idx = -1;
for (int i = 0; i < n_objects; i++) {
if (obj_index[i] > max_idx) {
max_idx = obj_index[i];
}
}
for (int i = 0; i <= max_idx; i++) {
cout << ind2 << i << ":";
dump_object(owners[i], ind2);
}
}
// recursive
void dump_release_evaluator(release_evaluator* expr, const char* ind) {
DECL_IND2(ind);
if (expr == nullptr) {
return;
}
cout << ind2 << "op: " << get_region_expression_flags_string(expr->op) << "\n";
cout << ind2 << "left: ";
if (expr->op & REXP_LEFT_REGION) {
region* r = (region *)expr->left;
dump_region(r, ind2);
}
else {
dump_release_evaluator((release_evaluator*)expr->left, ind2);
}
cout << ind2 << "right: ";
if (expr->op & REXP_RIGHT_REGION) {
region* r = (region *)expr->right;
dump_region(r, ind2);
}
else {
dump_release_evaluator((release_evaluator*)expr->right, ind2);
}
}
void dump_release_region_data(release_region_data* region_data, const char* name, const char* comment, const char* ind) {
DECL_IND2(ind);
cout << ind << name << ": *\t\t" << (void*)region_data << " [release_region_data] \t\t" << comment << "\n";
if (region_data != nullptr) {
cout << ind2 << "llf: \t\t" << region_data->llf << " [vector3] \t\t/* One corner of bounding box for release volume */\n";
cout << ind2 << "urb: \t\t" << region_data->urb << " [vector3] \t\t/* Opposite corner */\n";
//cout << ind2 << "n_walls_included: \t\t" << region_data->n_walls_included << " [int] \t\t/* How many walls total */\n";
//cout << ind2 << "cum_area_list: *\t\t" << region_data->cum_area_list << " [double] \t\t/* Cumulative area of all walls */\n";
dump_double_array(region_data->n_walls_included, "n_walls_included", region_data->cum_area_list, "cum_area_list", "/* Cumulative area of all walls */", ind2);
//cout << ind2 << "wall_index: *\t\t" << region_data->wall_index << " [int] \t\t/* Indices of each wall (by object) */\n";
dump_int_array(region_data->n_walls_included, "n_walls_included", region_data->wall_index, "wall_index", "/* Indices of each wall (by object) */", ind2);
cout << ind2 << "n_objects: \t\t" << region_data->n_objects << " [int] \t\t/* How many objects are there total */\n";
//cout << ind2 << "obj_index: *\t\t" << region_data->obj_index << " [int] \t\t/* Indices for objects (in owners array) */\n";
dump_int_array(region_data->n_walls_included, "n_walls_included", region_data->obj_index, "obj_index", "/* count: n_objects Indices for objects (in owners array) */", ind2);
// TODO - dump
dump_region_data_owners(region_data->n_objects, region_data->obj_index, region_data->owners, "owners", "Array of pointers to each object", ind2);
// TODO - dump
cout << ind2 << "in_release: **\t\t" << region_data->in_release << " [bit_array] \t\t/* Array of bit arrays; each bit array says which walls are in release for an object */\n";
// TODO - dump
cout << ind2 << "walls_per_obj: *\t\t" << region_data->walls_per_obj << " [int] \t\t/* Number of walls in release for each object */\n";
cout << ind2 << "self: *\t\t" << region_data->self << " [object] \t\t/* A pointer to our own release site object */\n";
dump_object(region_data->self, IND_ADD2(ind2));
cout << ind2 << "expression: *\t\t" << region_data->expression << " [release_evaluator] \t\t/* A set-construction expression combining regions to form this release site */\n";
dump_release_evaluator(region_data->expression, ind2);
}
}
void dump_release_pattern(release_pattern* pattern, const char* name, const char* comment, const char* ind) {
DECL_IND2(ind);
cout << ind << name << ": *\t\t" << (void*)pattern << " [release_pattern] \t\t" << comment << "\n";
if (pattern != nullptr) {
//cout << ind2 << "sym: *\t\t" << pattern->sym << " [sym_entry] \t\t/* Symbol hash table entry for the pattern */\n";
cout << ind2 << "sym.name: \t\t" << get_sym_name(pattern->sym) << " [sym_entry.name] \t\t/* Symbol hash table entry for the pattern */\n";
cout << ind2 << "delay: \t\t" << pattern->delay << " [double] \t\t/* Delay between time 0 and first release event. */\n";
cout << ind2 << "release_interval: \t\t" << pattern->release_interval << " [double] \t\t/* Time between release events within a train. */\n";
cout << ind2 << "train_interval: \t\t" << pattern->train_interval << " [double] \t\t/* Time from the start of one train to the start of the next one. */\n";
cout << ind2 << "train_duration: \t\t" << pattern->train_duration << " [double] \t\t/* Length of the train. */\n";
cout << ind2 << "number_of_trains: \t\t" << pattern->number_of_trains << " [int] \t\t/* How many trains are produced. */\n";
}
}
void dump_release_site_obj(release_site_obj* rel_site, const char* ind) {
DECL_IND2(ind);
if (rel_site->location != nullptr) {
cout << ind2 << "location: *\t\t" << *rel_site->location << " [vector3] \t\t/* location of release site */\n";
}
else {
cout << ind2 << "location: *\t\t" << (void*)rel_site->location << " [vector3*] \t\t/* location of release site */\n";
}
cout << ind2 << "mol_type: *\t\t" << (void*)rel_site->mol_type << " [species] \t\t/* species to be released */\n";
//dump_species(rel_site->mol_type, "mol_type", "/* species to be released */", ind2);
if (rel_site->mol_type != nullptr) {
cout << ind2 << " mol_type (name): *\t\t" << rel_site->mol_type->sym->name << "\n";
}
else {
cout << ind2 << " mol_type: *\t\t" << "NULL " << "\n";
}
cout << ind2 << "release_number_method: \t\t" << get_release_number_method_string((release_number_type_t)rel_site->release_number_method) << " [byte] \t\t/* Release Number Flags: controls how release_number is used (enum release_number_type_t) */\n";
cout << ind2 << "release_shape: \t\t" << get_release_shape_name(rel_site->release_shape) << " [int8_t] \t\t/* Release Shape Flags: controls shape over which to release (enum release_shape_t) */\n";
cout << ind2 << "orientation: \t\t" << rel_site->orientation << " [short] \t\t/* Orientation of released surface molecules */\n";
cout << ind2 << "release_number: \t\t" << rel_site->release_number << " [double] \t\t/* Number to release */\n";
cout << ind2 << "mean_diameter: \t\t" << rel_site->mean_diameter << " [double] \t\t/* Diameter for symmetric releases */\n";
cout << ind2 << "concentration: \t\t" << rel_site->concentration << " [double] \t\t/* Concentration of molecules to release. Units are Molar for volume molecules, and number per um^2 for surface molecules. */\n";
cout << ind2 << "standard_deviation: \t\t" << rel_site->standard_deviation << " [double] \t\t/* Standard deviation of release_number for GAUSSNUM, or of mean_diameter for VOLNUM */\n";
if (rel_site->diameter != nullptr) {
cout << ind2 << "diameter: *\t\t" << *rel_site->diameter << " [vector3] \t\t/* x,y,z diameter for geometrical release shapes */\n";
}
else {
cout << ind2 << "diameter: *\t\t" << (void*)rel_site->diameter << " [vector3*] \t\t/* x,y,z diameter for geometrical release shapes */\n";
}
#ifdef DUMP_RELEASE_REGION_DATA
dump_release_region_data(rel_site->region_data, "region_data", "/* Information related to release on regions */", ind2);
#else
cout << ind2 << "region_data: *\t\t" << (void*)rel_site->region_data << " [release_region_data] \t\t/* Information related to release on regions */\n";
#endif
cout << ind2 << "mol_list: *\t\t" << (void*)rel_site->mol_list << " [release_single_molecule] \t\t/* Information related to release by list */\n";
cout << ind2 << "release_prob: \t\t" << rel_site->release_prob << " [double] \t\t/* Probability of releasing at scheduled time */\n";
if (rel_site->periodic_box != nullptr) {
cout << ind2 << "periodic_box: *\t\t" << *rel_site->periodic_box << " [periodic_image] \t\t\n";
}
else {
cout << ind2 << "periodic_box: *\t\t" << (void*)rel_site->periodic_box << " [periodic_image] \t\t\n";
}
dump_release_pattern(rel_site->pattern, "pattern", "/* Timing of releases by virtual function generator */", ind2);
cout << ind2 << "name: *\t\t" << rel_site->name << " [char] \t\t/* Fully referenced name of the instantiated release_site */\n";
cout << ind2 << "graph_pattern: *\t\t" << (void*)rel_site->graph_pattern << " [char] \t\t/* JJT: Graph definition of the structured molecules being released in this site*/\n";
}
void dump_release_event_queue(release_event_queue* req, const char* ind) {
DECL_IND2(ind);
cout << ind << "release_event_queue :" << (void*)req << "\n";
cout << ind2 << "event_time: \t\t" << req->event_time << " [double] \t\t/* Time of the release */\n";
cout << ind2 << "release_site: *\t\t" << (void*)req->release_site << " [release_site_obj] \t\t/* What to release, where to release it, etc */\n";
dump_release_site_obj(req->release_site, ind2);
cout << ind2 << "t_matrix: *\t\t" << req->t_matrix << " [double[4][4]] \t\t // transformation matrix for location of release site\n";
cout << ind2 << "train_counter: \t\t" << req->train_counter << " [int] \t\t/* counts executed trains */\n";
cout << ind2 << "train_high_time: \t\t" << req->train_high_time << " [double] \t\t/* time of the train's start */\n";
cout << ind2 << "next: \t\t" << (void*)req->next << "\n";
//if (req->next != NULL)
// dump_release_event_queue(req->next, ind);
}
void dump_schedule_helper(schedule_helper* shp, const char* name, const char* comment, const char* ind, bool simplified_for_vm) {
if (simplified_for_vm) {
cout << "Scheduler '" << name << "', now: " << shp->now << "\n ";
for (schedule_helper* shp_curr = shp; shp_curr != NULL; shp_curr = shp_curr->next_scale) {
if (shp_curr->next_scale != NULL) {
cout << "\nnext_scale:\n";
}
abstract_molecule* am = (abstract_molecule*)shp_curr->current;
while (am != NULL) {
if (am->properties == NULL) {
cout << "!NULL properties!,";
}
else {
volume_molecule* vm = (volume_molecule*)am;
cout << "(t: " << vm->t << ", t2: " << vm->t2 << ", id: " << vm->id << "), ";
}
am = am->next;
}
cout << "\n";
}
}
else {
std::string inds = ind;
inds += " ";
const char* ind2 = inds.c_str();
cout << ind << name << ": *\t\t" << (void*)shp << " [schedule_helper] \t\t" << comment << "\n";
if (shp == nullptr) {
return;
}
#ifdef DUMP_SCHEDULERS
cout << ind2 <<"next_scale: *\t\t" << (void*)shp->next_scale << " [schedule_helper] \t\t/* Next coarser time scale */\n";
cout << ind2 <<"dt: \t\t" << shp->dt << " [double] \t\t/* Timestep per slot */\n";
cout << ind2 <<"dt_1: \t\t" << shp->dt_1 << " [double] \t\t/* dt_1 = 1/dt */\n";
cout << ind2 <<"now: \t\t" << shp->now << " [double] \t\t/* Start time of the scheduler */\n";
/* Items scheduled now or after now */
cout << ind2 <<"count: \t\t" << shp->count << " [int] \t\t/* Total number of items scheduled now or after */\n";
cout << ind2 <<"buf_len: \t\t" << shp->buf_len << " [int] \t\t/* Number of slots in the scheduler */\n";
cout << ind2 <<"index: \t\t" << shp->index << " [int] \t\t/* index of the next time block */\n";
if (shp->circ_buf_count != NULL) {
cout << ind2 <<"circ_buf_count: \t\t" << *shp->circ_buf_count << " [int] \t\t/* How many items are scheduled in each slot */\n";
}
else {
cout << ind2 <<"circ_buf_count: \t\t" << "NULL" << " [int*] \t\t/* How many items are scheduled in each slot */\n";
}
cout << ind2 <<"circ_buf_head: **\t\t" << (void**)shp->circ_buf_head << " [abstract_element] \t\t// Array of linked lists of scheduled items for each slot\n";
cout << ind2 <<"circ_buf_tail: **\t\t" << (void**)shp->circ_buf_tail << " [abstract_element] \t\t// Array of tails of the linked lists\n";
cout << ind2 <<"contents (current, circ_buf_head):\n";
for (int i = -1; i < shp->buf_len; i++) {
int k = 0;
for (struct abstract_element *aep = (i < 0) ? shp->current
: shp->circ_buf_head[i];
aep != NULL; aep = aep->next) {
cout << ind2 << " " << i << ":\n";
if (strcmp(name, "releaser") == 0) {
struct release_event_queue *req = (struct release_event_queue *)aep;
dump_release_event_queue(req, ind2);
}
else if (strcmp(name, "dynamic_geometry_scheduler") == 0) {
// TODO
}
else {
struct abstract_molecule *amp = (struct abstract_molecule *)aep;
if (amp->properties == NULL) {
cout << ind2 << " " << i << "." << k << ": " << (void*)amp << ", properties: " << (void*)amp->properties << "\n";
k++;
continue;
}
else {
k++;
}
dump_abstract_molecule(amp, IND_ADD2(ind2));
}
}
}
/* Items scheduled before now */
/* These events must be serviced before simulation can advance to now */
cout << ind2 <<"current_count: \t\t" << shp->current_count << " [int] \t\t/* Number of current items */\n";
cout << ind2 <<"current: *\t\t" << (void*)shp->current << " [abstract_element] \t\t/* List of items scheduled now */\n";
cout << ind2 <<"current_tail: *\t\t" << shp->current_tail << " [abstract_element] \t\t/* Tail of list of items */\n";
cout << ind2 <<"defunct_count: \t\t" << shp->defunct_count << " [int] \t\t/* Number of defunct items (set by user)*/\n";
cout << ind2 <<"error: \t\t" << shp->error << " [int] \t\t/* Error code (1 - on error, 0 - no errors) */\n";
cout << ind2 <<"depth: \t\t" << shp->depth << " [int] \t\t/* Tier of scheduler in timescale hierarchy, 0-based */\n";
#endif
}
}
void dump_species_item(species* spec, const char* ind) {
DECL_IND2(ind);
cout << ind2 <<"species_id: \t\t" << spec->species_id << " [u_int] \t\t/* Unique ID for this species */\n";
cout << ind2 <<"chkpt_species_id: \t\t" << spec->chkpt_species_id << " [u_int] \t\t/* Unique ID for this species from the checkpoint file */\n";
cout << ind2 <<"hashval: \t\t" << spec->hashval << " [u_int] \t\t/* Hash value (may be nonunique) */\n";
cout << ind2 <<"sym: *\t\t" << spec->sym << " [sym_entry] \t\t/* Symbol table entry (name) */\n";
cout << ind2 <<"sm_dat_head: *\t\t" << spec->sm_dat_head << " [sm_dat] \t\t/* If IS_SURFACE this points to head of effector data list associated with surface class */\n";
cout << ind2 <<"population: \t\t" << spec->population << " [u_int] \t\t/* How many of this species exist? */\n";
cout << ind2 <<"D: \t\t" << spec->D << " [double] \t\t/* Diffusion constant */\n";
cout << ind2 <<"space_step: \t\t" << spec->space_step << " [double] \t\t/* Characteristic step length */\n";
cout << ind2 <<"time_step: \t\t" << spec->time_step << " [double] \t\t/* Minimum (maximum?) sensible timestep */\n";
cout << ind2 <<"max_step_length: \t\t" << spec->max_step_length << " [double] \t\t/* maximum allowed random walk step */\n";
cout << ind2 <<"flags: \t\t" << spec->flags << " [u_int] " << get_species_flags_string(spec->flags) << " \t\t/* Species Flags: Vol Molecule? Surface Molecule? Surface Class? Counting stuff, etc... */\n";
cout << ind2 <<"n_deceased: \t\t" << spec->n_deceased << " [long long] \t\t/* Total number that have been destroyed. */\n";
cout << ind2 <<"cum_lifetime_seconds: \t\t" << spec->cum_lifetime_seconds << " [double] \t\t/* Seconds lived by now-destroyed molecules */\n";
/* if species s a surface_class (IS_SURFACE) below there are linked lists of
* molecule names/orientations that may be present in special reactions for
* this surface class */
cout << ind2 <<"refl_mols: *\t\t" << spec->refl_mols << " [name_orient] \t\t// names of the mols that REFLECT from surface\n";
cout << ind2 <<"transp_mols: *\t\t" << spec->transp_mols << " [name_orient] \t\t/* names of the mols that are TRANSPARENT for surface */\n";
cout << ind2 <<"absorb_mols: *\t\t" << spec->absorb_mols << " [name_orient] \t\t// names of the mols that ABSORB at surface\n";
cout << ind2 <<"clamp_mols: *\t\t" << spec->clamp_mols << " [name_orient] \t\t/* names of mols that CLAMP_CONC at surface */\n";
}
void dump_species(species* spec, const char* name, const char* comment, const char* ind) {
cout << ind << name << ": *\t\t" << (void*)spec << " [species] \t\t" << comment << "\n";
if (spec != nullptr) {
dump_species_item(spec, ind);
}
}
void dump_species_list(int n_species, const char* num_name, species** species_list, const char* name, const char* comment, const char* ind) {
DECL_IND2(ind);
cout << ind2 << name << "[" << num_name << "]: \t\t" << (void**)species_list << "[" << n_species << "]" << " [species*[]] \t\t" << comment << "\n";
for (int i = 0; i < n_species; i++) {
species* spec = species_list[i];
cout << ind2 << " " << i << ": " << (void*)spec << "\n";
dump_species_item(spec, IND_ADD2(ind2));
}
}
string viz_output_flag_to_str(u_short flag) {
string res = "";
if (flag & VIZ_ALL_MOLECULES) {
res += "VIZ_ALL_MOLECULES";
}
if (flag & VIZ_MOLECULES_STATES) {
res += "VIZ_MOLECULES_STATES";
}
if (flag & VIZ_SURFACE_STATES) {
res += "VIZ_SURFACE_STATES";
}
if (res == "") {
res = "NONE";
}
return res;
}
void dump_frame_data_list(frame_data_list* frame_data_head, const char* name, const char* comment, const char* ind) {
DECL_IND2(ind);
cout << ind << name << ": *\t\t" << frame_data_head << " [frame_data_list] \t\t" << comment << "\n";
if (frame_data_head == nullptr) {
cout << ind2 << "NULL\n";
return;
}
cout << ind2 << "next: *\t\t" << frame_data_head->next << " [frame_data_list] \t\t\n";
cout << ind2 << "list_type: \t\t" << frame_data_head->list_type << " [output_timer_type_t] \t\t/* Data Output Timing Type (OUTPUT_BY_TIME_LIST, etc) */\n";
cout << ind2 << "type: \t\t" << frame_data_head->type << " [viz_frame_type_t] \t\t/* Visualization Frame Data Type (ALL_FRAME_DATA, etc) */\n";
cout << ind2 << "viz_iteration: \t\t" << frame_data_head->viz_iteration << " [long long] \t\t/* Value of the current iteration step. */\n";
cout << ind2 << "n_viz_iterations: \t\t" << frame_data_head->n_viz_iterations << " [long long] \t\t/* Number of iterations in the iteration_list. */\n";
cout << ind2 << "iteration_list: *\t\t" << frame_data_head->iteration_list << " [num_expr_list] \t\t/* Linked list of iteration steps values */\n";
cout << ind2 << "curr_viz_iteration: *\t\t" << frame_data_head->curr_viz_iteration << " [num_expr_list] \t\t/* Points to the current iteration in the linked list */\n";
}
void dump_viz_output_block(viz_output_block* viz_blocks, const char* name, const char* comment, const char* ind) {
DECL_IND2(ind);
cout << ind << name << ": *\t\t" << (void*)viz_blocks << " [viz_output_block] \t\t" << comment << "\n";
if (viz_blocks == nullptr) {
return;
}
cout << ind2 << "next: *\t\t" << viz_blocks->next << " [viz_output_block] \t\t/* Link to next block */\n";
dump_frame_data_list(viz_blocks->frame_data_head, "frame_data_head", "/* head of the linked list of viz frames to output */", ind2);
cout << ind2 << "viz_mode: \t\t" << viz_blocks->viz_mode << " [viz_mode_t] \t\t\n";
cout << ind2 << "file_prefix_name: *\t\t" << viz_blocks->file_prefix_name << " [char] \t\t\n";
cout << ind2 << "viz_output_flag: \t\t" << viz_output_flag_to_str(viz_blocks->viz_output_flag) << " [u_short] \t\t/* Takes VIZ_ALL_MOLECULES, VIZ_MOLECULES_STATES, etc. */\n";
if (viz_blocks->species_viz_states == nullptr) {
cout << ind2 << "species_viz_states: *\t\t" << viz_blocks->species_viz_states << " [int (ptr)] \t\t\n";
}
else {
cout << ind2 << "species_viz_states: \t\t" << *viz_blocks->species_viz_states << " [int] \t\t\n";
}
cout << ind2 << "default_mol_state: \t\t" << viz_blocks->default_mol_state << " [int] \t\t// Only set if (viz_output_flag & VIZ_ALL_MOLECULES)\n";
/* Parse-time only: Tables to hold temporary information. */
//struct pointer_hash parser_species_viz_states;
}
void dump_output_trigger_data(output_trigger_data* otd, const char* name, const char* comment, const char* ind) {
cout << ind << name << ": *\t\t" << otd << " [output_trigger_data] \t\t" << comment << "\n";
if (otd == nullptr) {
return;
}
DECL_IND2(ind);
cout << ind2 << "t_iteration: \t\t" << otd->t_iteration << " [double] \t\t /* Iteration time of the triggering event (in sec) */\n";
cout << ind2 << "event_time: \t\t" << otd->event_time << " [double] \t\t /* Exact time of the event */\n";
cout << ind2 << "loc: \t\t" << otd->loc << " [vector3] \t\t /* Position of event */\n";
cout << ind2 << "how_many: \t\t" << otd->how_many << " [int] \t\t /* Number of events */\n";
cout << ind2 << "orient: \t\t" << otd->orient << " [short] \t\t /* Orientation information */\n";
// TODO: dump flags
cout << ind2 << "flags: \t\t" << otd->flags << " [short] \t\t /* Output Trigger Flags */\n";
if (otd->name != nullptr) {
cout << ind2 << "name: \t\t" << otd->name << " [char*] \t\t /* Name to give event */\n";
}
else {
cout << ind2 << "name: \t\t" << (void*)otd->name << " [char*] \t\t /* Name to give event */\n";
}
cout << ind2 << "id: \t\t" << otd->id << " [u_long] \t\t /**/\n";
}
void dump_output_buffer(output_buffer* obuf, const char* name, const char* comment, const char* ind) {
cout << ind << name << ": *\t\t" << obuf << " [output_buffer] \t\t" << comment << "\n";
if (obuf == nullptr) {
return;
}
DECL_IND2(ind);
cout << ind2 << "data_type: \t\t" << obuf->data_type << " [count_type_t] \t\t /**/\n";
switch(obuf->data_type) {
case COUNT_UNSET: // probably wrong
cout << ind2 << "cval: \t\t" << obuf->val.cval << " [char] \t\t /**/\n";
break;
case COUNT_DBL:
cout << ind2 << "dval: \t\t" << obuf->val.dval << " [double] \t\t /**/\n";
break;
case COUNT_INT:
cout << ind2 << "ival: \t\t" << obuf->val.ival << " [int] \t\t /**/\n";
break;
case COUNT_TRIG_STRUCT:
//cout << ind2 << "tval: \t\t" << obuf->val.tval << " [output_trigger_data*] \t\t /**/\n";
dump_output_trigger_data(obuf->val.tval, "val.tval", "", ind2);
break;
default:
assert(false);
}
}
void dump_one_output_column(output_column* column, const char* ind) {
cout << ind << "next: \t\t" << (void*)column->next << " [output_column*] \t\t /* Next column in this set */\n";
cout << ind << "set: \t\t" << (void*)column->set << " [output_set*] \t\t /* Which set do we belong to? */\n";
cout << ind << "initial_value: \t\t" << column->initial_value << " [double] \t\t /* To continue existing cumulative counts--not implemented yet--and keep track of triggered data */\n";
//cout << ind << "buffer: \t\t" << column->buffer << " [output_buffer*] \t\t /* Output buffer array (cast based on data_type) */\n";
dump_output_buffer(column->buffer, "buffer", "/* Data for one output column *", ind);
cout << ind << "expr: \t\t" << column->expr << " (" << (void*)column->expr << ") [output_expression*] \t\t /* Evaluate this to calculate our value (NULL if trigger) */\n";
}
void dump_output_column(output_column* ocol, const char* name, const char* comment, const char* ind) {
cout << ind << name << ": *\t\t" << ocol << " [output_column] \t\t" << comment << "\n";
DECL_IND2(ind);
output_column* curr = ocol;
while (curr != nullptr) {
dump_one_output_column(curr, ind2);
curr = curr->next;
}
}
void dump_one_output_set(output_set* block, const char* ind) {
cout << ind << "next: \t\t" << (void*)block->next << " [output_set*] \t\t /* Next data set in this block */\n";
cout << ind << "block: \t\t" << (void*)block->block << " [output_block*] \t\t /* Which block do we belong to? */\n";
cout << ind << "outfile_name: \t\t" << block->outfile_name << " [char*] \t\t /* Filename */\n";
cout << ind << "file_flags: \t\t" << block->file_flags << " [overwrite_policy_t] \t\t /* Overwrite Policy Flags: tells us how to handle existing files */\n";
cout << ind << "chunk_count: \t\t" << block->chunk_count << " [u_int] \t\t /* Number of buffered output chunks processed */\n";
if (block->header_comment != nullptr) {
cout << ind << "header_comment: \t\t" << block->header_comment << " [char*] \t\t /* Comment character(s) for header */\n";
}
else {
cout << ind << "header_comment: \t\t" << (void*)block->header_comment << " [char*] \t\t /* Comment character(s) for header */\n";
}
cout << ind << "exact_time_flag: \t\t" << block->exact_time_flag << " [int] \t\t /* Boolean value; nonzero means print exact time in TRIGGER statements */\n";
//cout << ind << "column_head: \t\t" << block->column_head << " [output_column*] \t\t /* Data for one output column */\n";
dump_output_column(block->column_head, "column_head", "/* Data for one output column */", ind);
}
void dump_output_set(output_set* oset, const char* name, const char* comment, const char* ind) {
cout << ind << name << ": *\t\t" << oset << " [output_set] \t\t" << comment << "\n";
DECL_IND2(ind);
output_set* curr = oset;
int i = 0;
while (curr != nullptr) {
cout << ind << i << ": \n";
i++;
dump_one_output_set(curr, ind2);
curr = curr->next;
}
}
void dump_one_output_block(output_block* block, const char* ind) {
cout << ind << "next: \t\t" << (void*)block->next << " [output_block*] \t\t /* Next in world or scheduler */\n";
cout << ind << "t: \t\t" << block->t << " [double] \t\t /* Scheduled time to update counters */\n";
cout << ind << "timer_type: \t\t" << block->timer_type << " [output_timer_type_t] \t\t /* Data Output Timing Type (OUTPUT_BY_STEP, etc) */\n";
cout << ind << "step_time: \t\t" << block->step_time << " [double] \t\t /* Output interval (seconds) */\n";
cout << ind << "time_list_head: \t\t" << block->time_list_head << " [num_expr_list*] \t\t /* List of output times/iteration numbers */\n";
cout << ind << "time_now: \t\t" << block->time_now << " [num_expr_list*] \t\t /* Current entry in list */\n";
cout << ind << "buffersize: \t\t" << block->buffersize << " [u_int] \t\t /* Size of output buffer */\n";
cout << ind << "trig_bufsize: \t\t" << block->trig_bufsize << " [u_int] \t\t /* Size of output buffer for triggers */\n";
cout << ind << "buf_index: \t\t" << block->buf_index << " [u_int] \t\t /* Index into buffer (for non-triggers) */\n";
dump_double_array(block->buffersize, "buffersize", block->time_array, "time_array", "/* Array of output times (for non-triggers) */", ind);
dump_output_set(block->data_set_head, "data_set_head", "/* Linked list of data sets (separate files) */", ind);
}
void dump_output_blocks(output_block* output_block_head, const char* name, const char* comment, const char* ind) {
cout << ind << name << ": *\t\t" << output_block_head << " [output_block] \t\t" << comment << "\n";
DECL_IND2(ind);
output_block* curr = output_block_head;
int i = 0;
while (curr != nullptr) {
cout << ind << i << ": \n";
i++;
dump_one_output_block(curr, ind2);
curr = curr->next;
}
}
void dump_one_output_request(output_request* req, const char* ind) {
cout << ind << "next: \t\t" << (void*)req->next << " [output_request*] \t\t /* Next request in global list */\n";
cout << ind << "requester: \t\t" << req->requester << " (" << (void*)req->requester << ") [output_expression*] \t\t /* Expression in which we appear */\n";
cout << ind << "count_target: \t\t" << req->count_target << " [sym_entry*] \t\t /* Mol/rxn we're supposed to count */\n";
cout << ind << "count_orientation: \t\t" << req->count_orientation << " [short] \t\t /* orientation of the molecule we are supposed to count */\n";
cout << ind << "count_location: \t\t" << req->count_location << " [sym_entry*] \t\t /* Object or region on which we're supposed to count it */\n";
cout << ind << "report_type: \t\t" << get_report_type_flags_string(req->report_type) << " [byte] \t\t /* Output Report Flags telling us how to count */\n";
cout << ind << "periodic_box: \t\t" << (void*)req->periodic_box << " [periodic_image*] \t\t /* periodic box we are counting in; NULL means that we don't care and count everywhere */\n";
}
void dump_output_requests(output_request* output_request_head, const char* name, const char* comment, const char* ind) {
cout << ind << name << ": *\t\t" << output_request_head << " [output_request] \t\t" << comment << "\n";
DECL_IND2(ind);
output_request* curr = output_request_head;
int i = 0;
while (curr != nullptr) {
cout << ind << i << ": \n";
i++;
dump_one_output_request(curr, ind2);
curr = curr->next;
}
}
void dump_sym_table(sym_table_head* t, const char* name, const char* comment, const char* ind) {
cout << ind << name << ": *\t\t" << t << " [sym_table_head] \t\t" << comment << "\n";
if (t == nullptr) {
return;
}
DECL_IND2(ind);
cout << ind2 << "n_bins: \t\t" << t->n_bins << " [int] \t\t /**/\n";
cout << ind2 << "n_entries: \t\t" << t->n_entries << " [int] \t\t /**/\n";
int dumped_symbols = 0;
for (int i = 0; i < t->n_bins; i++) {
if (t->entries[i] != nullptr) {
cout << ind2 << "[" << i << "]:" << t->entries[i] << "\n";
dumped_symbols++;
}
}
if (dumped_symbols != t->n_entries) {
cout << "internal warning: when dumping symbol table: dumped_symbols != t->n_entries\n";
}
}
void dump_name_list(name_list* obj, const char* name, const char* comment, const char* ind) {
name_list* curr = obj;
int i = 0;
while (curr != NULL) {
cout << ind << i << ": " << str(curr->name) << "\n";
i++;
curr = curr->next;
}
}
void dump_dyngeom_parse_vars(dyngeom_parse_vars* dg_parse, const char* name, const char* comment, const char* ind) {
cout << ind << name << ": *\t\t" << (void*)dg_parse << " [dyngeom_parse_vars] \t\t" << comment << "\n";
if (dg_parse == nullptr) {
return;
}
DECL_IND2(ind)
dump_sym_table(dg_parse->reg_sym_table, "reg_sym_table", "", ind2);
//cout << ind2 << "root_object: \t\t" << dg_parse->root_object << " [object*] \t\t object *root_instance;\n";
dump_object_list(dg_parse->root_object, "root_object", "", ind2);
//cout << ind2 << "current_object: \t\t" << dg_parse->current_object << " [object*] \t\t region *current_region;\n";
dump_object_list(dg_parse->current_object, "current_object", "", ind2);
//cout << ind2 << "object_name_list: \t\t" << dg_parse->object_name_list << " [name_list*] \t\t name_list *object_name_list_end;\n";
dump_name_list(dg_parse->object_name_list, "object_name_list", "", ind2);
cout << ind2 << "curr_file: \t\t" << str(dg_parse->curr_file) << " [char*] \t\t /* Name of MDL file currently being parsed */\n";
dump_int_array(MAX_INCLUDE_DEPTH, "MAX_INCLUDE_DEPTH", (int*)dg_parse->line_num, "line_num", "/* Line numbers and filenames for all of the currently parsing files */", ind2);
dump_string_array(MAX_INCLUDE_DEPTH, "MAX_INCLUDE_DEPTH", dg_parse->include_filename, "include_filename", "/* Line numbers and filenames for all of the currently parsing files */", ind2);
cout << ind2 << "include_stack_ptr: \t\t" << dg_parse->include_stack_ptr << " [u_int] \t\t /* Stack pointer for filename/line number stack */\n";
cout << ind2 << "comment_started: \t\t" << dg_parse->comment_started << " [int] \t\t /* Line number where last top-level (i.e. non-nested) multi-line (C-style) comment was started in the current MDL file. */\n";
}
void dump_dg_time_filename_list(dg_time_filename* fn, const char* name, const char* comment, const char* ind) {
cout << ind << name << ": *\t\t" << (void*)fn << " [dyngeom_parse_vars] \t\t" << comment << "\n";
dg_time_filename* curr = fn;
int i = 0;
while (curr != NULL) {
cout << ind << i << ": " << curr->event_time << " - " << str(curr->mdl_file_path) << "\n";
i++;
curr = curr->next;
}
}
/*extern "C"*/ void dump_volume(struct volume* s, const char* comment, unsigned int selected_details /* mask */) {
cout << "********* volume dump :" << comment << "************ (START)\n";
cout << comment << "\n";
cout << "bond_angle: \t\t" << s->bond_angle << " [double] \t\t/* Defines the default bond rotation angle between molecules. Default is 0. */\n";
// These are only used with dynamic geometry
//cout << "dg_parse: *\t\t" << (void*)s->dg_parse << " [dyngeom_parse_vars] \n";
dump_dyngeom_parse_vars(s->dg_parse, "dg_parse", "", "");
cout << "dynamic_geometry_filename: *\t\t" << str(s->dynamic_geometry_filename) << " [char] \n";
dump_molecules(s->num_all_molecules, s->all_molecules);
cout << "names_to_ignore: *\t\t" << (void*)s->names_to_ignore << " [string_buffer] \n";
/* Coarse partitions are input by the user */
/* They may also be generated automagically */
/* They mark the positions of initial partition boundaries */
dump_double_array(s->nx_parts, "nx_parts", s->x_partitions, "x_partitions", "/* Coarse X partition boundaries */", "", 1000);
dump_double_array(s->ny_parts, "ny_parts", s->y_partitions, "y_partitions", "/* Coarse Y partition boundaries */", "", 1000);
dump_double_array(s->nz_parts, "nz_parts", s->z_partitions, "z_partitions", "/* Coarse Z partition boundaries */", "", 1000);
cout << "mem_part_x: \t\t" << s->mem_part_x << " [int] \t\t/* Granularity of memory-partition binning for the X-axis */\n";
cout << "mem_part_y: \t\t" << s->mem_part_y << " [int] \t\t/* Granularity of memory-partition binning for the Y-axis */\n";
cout << "mem_part_z: \t\t" << s->mem_part_z << " [int] \t\t/* Granularity of memory-partition binning for the Z-axis */\n";
cout << "mem_part_pool: \t\t" << s->mem_part_pool << " [int] \t\t/* Scaling factor for sizes of memory pools in each storage */\n";
/* Fine partitions are intended to allow subdivision of coarse partitions */
/* Subdivision is not yet implemented */
dump_double_array(s->n_fineparts, "n_fineparts", s->x_fineparts, "x_fineparts", "/* Fine X partition boundaries */", "");
dump_double_array(s->n_fineparts, "n_fineparts", s->y_fineparts, "y_fineparts", "/* Fine Y partition boundaries */", "");
dump_double_array(s->n_fineparts, "n_fineparts", s->z_fineparts, "z_fineparts", "/* Fine Z partition boundaries */", "");
cout << "periodic_traditional: \t\t" << s->periodic_traditional << " [bool] \n";
#ifdef DUMP_WAYPOINTS
dump_waypoints(s->n_waypoints, s->waypoints);
#endif
cout << "place_waypoints_flag: \t\t" << (int)s->place_waypoints_flag << " [byte] \t\t/* Used to save memory if waypoints not needed */\n";
#ifdef DUMP_SUBVOLUMES
dump_subvolumes(s->n_subvols, "n_subvols", "/* How many coarse subvolumes? */", s->subvol, "subvol", "/* Array containing all subvolumes */", "");
#endif
cout << "n_walls: \t\t" << s->n_walls << " [int] \t\t/* Total number of walls */\n";
cout << "n_verts: \t\t" << s->n_verts << " [int] \t\t/* Total number of vertices */\n";
dump_vector3_array(s->n_verts, "n_verts", s->all_vertices, "all_vertices", "/* Central repository of vertices with a partial order imposed by natural ordering of storages*/", "");
#ifdef DUMP_WALLS
dump_wall_list_array(s->n_verts, "n_verts", s->walls_using_vertex, "walls_using_vertex", "/* Array of linked lists of walls using a vertex (has the size of all_vertices array) */", "");
#endif
cout << "rx_hashsize: \t\t" << s->rx_hashsize << " [int] \t\t/* How many slots in our reaction hash table? */\n";
cout << "n_reactions: \t\t" << s->n_reactions << " [int] \t\t/* How many reactions are there, total? */\n";
cout << "reaction_hash: **\t\t" << (void**)s->reaction_hash << " [rxn] \t\t/* A hash table of all reactions. */\n";
dump_reaction_hash_table(s->rx_hashsize, "rx_hashsize", s->reaction_hash, "reaction_hash", "/* A hash table of all reactions. */", "");
cout << "tv_rxn_mem: *\t\t" << (void*)s->tv_rxn_mem << " [mem_helper] \t\t/* Memory to store time-varying reactions */\n";
cout << "count_hashmask: \t\t" << s->count_hashmask << " [int] \t\t/* Mask for looking up count hash table */\n";
cout << "count_hash: **\t\t" << (void**)s->count_hash << " [counter] \t\t/* Count hash table */\n";
dump_schedule_helper(s->count_scheduler, "count_scheduler", "// When to generate reaction output", "", false);
//cout << "counter_by_name: *\t\t" << (void*)s->counter_by_name << " [sym_table_head] \n";
dump_sym_table(s->counter_by_name, "counter_by_name", "", "");
dump_schedule_helper(s->volume_output_scheduler, "volume_output_scheduler", "/* When to generate volume output */", "", false);
cout << "n_species: \t\t" << s->n_species << " [int] \t\t/* How many different species (molecules)? */\n";
//NFSim stats
cout << "n_NFSimSpecies: \t\t" << s->n_NFSimSpecies << " [int] \t\t/* number of graph patterns encountered during the NFSim simulation */\n";
cout << "n_NFSimReactions: \t\t" << s->n_NFSimReactions << " [int] \t\t/* number of reaction rules discovered through an NFSim simulation */\n";
cout << "n_NFSimPReactions: \t\t" << s->n_NFSimPReactions << " [int] \t\t/* number of potential reactions found in the reaction network (not necessarely triggered) */\n";
cout << "species_list: **\t\t" << (void**)s->species_list << " [species] \t\t/* Array of all species (molecules). */\n";
dump_species_list(s->n_species, "n_species", s->species_list, "species_list", "/* Array of all species (molecules). */", "");
// dynamic geometry, not so important for now
cout << "dynamic_geometry_flag: \t\t" << s->dynamic_geometry_flag << " [int] \t\t/* This is used to skip over certain sections in the parser when using dynamic geometries.*/ \n";
cout << "disable_polygon_objects: \t\t" << s->disable_polygon_objects << " [int] \t\t/* This is used to skip over certain sections in the parser when using dynamic geometries.*/\n";
//cout << "dynamic_geometry_head: *\t\t" << (void*)s->dynamic_geometry_head << " [dg_time_filename] \t\t/*List of all the dynamic geometry events that need to be scheduled*/\n";
dump_dg_time_filename_list(s->dynamic_geometry_head, "dynamic_geometry_head", "/*List of all the dynamic geometry events that need to be scheduled*/", " ");
cout << "dynamic_geometry_events_mem: *\t\t" << (void*)s->dynamic_geometry_events_mem << " [mem_helper] \t\t/*Memory to store time and MDL names for dynamic geometry*/\n";
//cout << "dynamic_geometry_scheduler: *\t\t" << (void*)s->dynamic_geometry_scheduler << " [schedule_helper] \t\t/*Scheduler for dynamic geometry (LATER)*/\n";
dump_schedule_helper(s->dynamic_geometry_scheduler, "dynamic_geometry_scheduler", "/*Scheduler for dynamic geometry (LATER)*/", "", false);
dump_schedule_helper(s->releaser, "releaser", "/* Scheduler for release events */", "", false);
cout << "storage_allocator: *\t\t" << (void*)s->storage_allocator << " [mem_helper] \t\t/* Memory for storage list */\n";
cout << "storage_head: *\t\t" << (void*)s->storage_head << " [storage_list] \t\t/* Linked list of all local memory/schedulers\n";
cout << "current_mol_id: \t\t" << s->current_mol_id << " [u_long] \t\t/* next unique molecule id to use*/\n";
cout << "speed_limit: \t\t" << s->speed_limit << " [double] // How far can the fastest particle get in one timestep?\n";
// symbol tables
cout << "fstream_sym_table: *\t\t" << (void*)s->fstream_sym_table << " [sym_table_head] \t\t/* Global MDL file stream symbol hash table */\n";
cout << "var_sym_table: *\t\t" << (void*)s->var_sym_table << " [sym_table_head] \t\t/* Global MDL variables symbol hash table */\n";
cout << "rxn_sym_table: *\t\t" << (void*)s->rxn_sym_table << " [sym_table_head] \t\t/* RXN symbol hash table */\n";
cout << "obj_sym_table: *\t\t" << (void*)s->obj_sym_table << " [sym_table_head] \t\t/* Objects symbol hash table */\n";
cout << "reg_sym_table: *\t\t" << (void*)s->reg_sym_table << " [sym_table_head] \t\t/* Regions symbol hash table */\n";
cout << "mol_sym_table: *\t\t" << (void*)s->mol_sym_table << " [sym_table_head] \t\t/* Molecule type symbol hash table */\n";
cout << "rpat_sym_table: *\t\t" << (void*)s->rpat_sym_table << " [sym_table_head] \t\t/* Release pattern hash table */\n";
cout << "rxpn_sym_table: *\t\t" << (void*)s->rxpn_sym_table << " [sym_table_head] \t\t/* Named reaction pathway hash table */\n";
cout << "mol_ss_sym_table: *\t\t" << (void*)s->mol_ss_sym_table << " [sym_table_head] \t\t/* Spatially structured molecule symbol hash table */\n";
// ???
//cout << "root_object: *\t\t" << (void*)s->root_object << " [object] \t\t\n";
dump_object_list(s->root_object, "root_object", "/* Root of the object template tree */", "");
//cout << "root_instance: *\t\t" << (void*)s->root_instance << " [object] \t\t/* Root of the instantiated object tree */\n";
dump_object_list(s->root_instance, "root_instance", "/* Root of the instantiated object tree */", "");
cout << "periodic_box_obj: *\t\t" << (void*)s->periodic_box_obj << " [object] \n";
// TODO3
cout << "default_release_pattern: *\t\t" << (void*)s->default_release_pattern << " [release_pattern] \t\t/* release once at t=0 */\n";
// ???
cout << "volume_output_head: *\t\t" << (void*)s->volume_output_head << " [volume_output_item] \t\t/* List of all volume data output items */\n";
//cout << "output_block_head: *\t\t" << (void*)s->output_block_head << " [output_block] \t\t/* Global list of reaction data output blocks */\n";
dump_output_blocks(s->output_block_head, "output_block_head", "/* Global list of reaction data output blocks */", "");
//cout << "output_request_head: *\t\t" << (void*)s->output_request_head << " [output_request] \t\t/* Global list linking COUNT statements to internal variables \n";
dump_output_requests(s->output_request_head, "output_request_head", "/* Global list linking COUNT statements to internal variables*/", "");
// some memories
cout << "oexpr_mem: *\t\t" << (void*)s->oexpr_mem << " [mem_helper] \t\t/* Memory to store output_expressions */\n";
cout << "outp_request_mem: *\t\t" << (void*)s->outp_request_mem << " [mem_helper] \t\t/* Memory to store output_requests */\n";
cout << "counter_mem: *\t\t" << (void*)s->counter_mem << " [mem_helper] \t\t/* Memory to store counters (for counting molecules/reactions on regions)\n";
cout << "trig_request_mem: *\t\t" << (void*)s->trig_request_mem << " [mem_helper] \t\t/* Memory to store listeners for trigger events */\n";
cout << "magic_mem: *\t\t" << (void*)s->magic_mem << " [mem_helper] \t\t/* Memory used to store magic lists for reaction-triggered releases and such \n";
//
cout << "elapsed_time: \t\t" << s->elapsed_time << " [double] \t\t/* Used for concentration measurement */\n";
/* Visualization state */
dump_viz_output_block(s->viz_blocks, "viz_blocks", "/* VIZ_OUTPUT blocks from file */", "");
dump_species(s->all_mols, "all_mols", "/* Refers to ALL_MOLECULES keyword */", "");
dump_species(s->all_volume_mols, "all_volume_mols", "/* Refers to ALL_VOLUME_MOLECULES keyword */", "");
dump_species(s->all_surface_mols, "all_surface_mols", "/* Refers to ALL_SURFACE_MOLECULES keyword */", "");
cout << "time_unit: \t\t" << s->time_unit << " [double] \t\t/* Duration of one global time step in real time, Used to convert between real time and internal time */\n";
cout << "time_step_max: \t\t" << s->time_step_max << " [double] \t\t/* Maximum internal time that a molecule may diffuse */\n";
cout << "grid_density: \t\t" << s->grid_density << " [[double] \t\t/* Density of grid for surface molecules, number per um^2 */\n";
cout << "length_unit: \t\t" << s->length_unit << " [double] \t\t/* Internal unit of distance, 1/sqrt(grid_density), in microns\n";
cout << "r_length_unit: \t\t" << s->r_length_unit << " [double] \t\t/* Reciprocal of length_unit to avoid division */\n";
cout << "rx_radius_3d: \t\t" << s->rx_radius_3d << " [double] \t\t/* Interaction radius for reactions between volume molecules \n";
cout << "space_step: \t\t" << s->space_step << " [double] \t\t/* User-supplied desired average diffusion distance for volume molecules\n";
cout << "r_step: *\t\t" << (void*)s->r_step << " [double] \t\t/* Lookup table of 3D diffusion step lengths */\n";
cout << "d_step: *\t\t" << (void*)s->d_step << " [double] \t\t/* Lookup table of 3D diffusion direction vectors */\n";
cout << "r_step_surface: *\t\t" << (void*)s->r_step_surface << " [double] \t\t/* Lookup table of 2D diffusion step lengths */\n";
cout << "r_step_release: *\t\t" << (void*)s->r_step_release << " [double] \t\t/* Lookup table of diffusion lengths for 3D release */\n";
cout << "radial_subdivisions: \t\t" << s->radial_subdivisions << " [u_int] \t\t/* Size of 2D and 3D step length lookup tables */\n";
cout << "radial_directions: \t\t" << s->radial_directions << " [u_int] \t\t/* Requested size of 3D direction lookup table */\n";
cout << "num_directions: \t\t" << s->num_directions << " [u_int] \t\t/* Actual size of 3D direction lookup table */\n";
cout << "directions_mask: \t\t" << s->directions_mask << " [int] \t\t/* Mask to obtain RNG bits for direction lookup */\n";
cout << "fully_random: \t\t" << s->fully_random << " [int] \t\t/* If set, generate directions with trig functions instead of lookup table \n";
cout << "dissociation_index: \t\t" << s->dissociation_index << " [int] \t\t/* Used to keep 3D products from reacting with each other too soon \n";
// chkpt
cout << "chkpt_iterations: \t\t" << s->chkpt_iterations << " [long long] \t\t/* Number of iterations to advance before checkpointing\n";
cout << "chkpt_init: \t\t" << s->chkpt_init << " [u_int] \t\t/* Set if this is the initial run of a simulation with no previous checkpoints\n";
cout << "chkpt_flag: \t\t" << s->chkpt_flag << " [u_int] \t\t/* Set if there are any CHECKPOINT statements in mdl file */\n";
cout << "chkpt_seq_num: \t\t" << s->chkpt_seq_num << " [u_int] \t\t/* Number of current run in checkpoint sequence */\n";
cout << "keep_chkpts: \t\t" << s->keep_chkpts << " [int] \t\t/* flag to indicate if checkpoints should be kept */\n";
cout << "chkpt_infile: *\t\t" << (void*)s->chkpt_infile << " [char] \t\t/* Name of checkpoint file to read from */\n";
cout << "chkpt_outfile: *\t\t" << (void*)s->chkpt_outfile << " [char] \t\t/* Name of checkpoint file to write to */\n";
cout << "chkpt_byte_order_mismatch: \t\t" << s->chkpt_byte_order_mismatch << " [u_int] \t\t/* Flag that defines whether mismatch in byte order exists between the saved checkpoint file and the machine reading it\n";
cout << "chkpt_start_time_seconds: \t\t" << s->chkpt_start_time_seconds << " [double] \t\t/* start of the simulation time (in sec) for new checkpoint\n";
cout << "current_time_seconds: \t\t" << s->current_time_seconds << " [double] \t\t/* current simulation time in seconds */\n";
/* simulation start time (in seconds) or time of most recent checkpoint */
cout << "simulation_start_seconds: \t\t" << s->simulation_start_seconds << " [double] \n";
cout << "diffusion_number: \t\t" << s->diffusion_number << " [long long] \t\t/* Total number of times molecules have had their positions updated */\n";
cout << "diffusion_cumtime: \t\t" << s->diffusion_cumtime << " [double] \t\t/* Total time spent diffusing by all molecules */\n";
cout << "ray_voxel_tests: \t\t" << s->ray_voxel_tests << " [long long] \t\t/* How many ray-subvolume intersection tests have we performed */\n";
cout << "ray_polygon_tests: \t\t" << s->ray_polygon_tests << " [long long] \t\t/* How many ray-polygon intersection tests have we performed */\n";
cout << "ray_polygon_colls: \t\t" << s->ray_polygon_colls << " [long long] \t\t/* How many ray-polygon intersections have occured */\n";
cout << "dyngeom_molec_displacements: \t\t" << s->dyngeom_molec_displacements << " [long long] \t\t/* Total number of dynamic geometry molecule displacements */\n";
/* below "vol" means volume molecule, "surf" means surface molecule */
cout << "vol_vol_colls: \t\t" << s->vol_vol_colls << " [long long] \t\t/* How many vol-vol collisions have occured */\n";
cout << "vol_surf_colls: \t\t" << s->vol_surf_colls << " [long long] \t\t/* How many vol-surf collisions have occured */\n";
cout << "surf_surf_colls: \t\t" << s->surf_surf_colls << " [long long] \t\t/* How many surf-surf collisions have occured */\n";
cout << "vol_wall_colls: \t\t" << s->vol_wall_colls << " [long long] \t\t/* How many vol-wall collisions have occured */\n";
cout << "vol_vol_vol_colls: \t\t" << s->vol_vol_vol_colls << " [long long] // How many vol-vol-vol collisions have occured\n";
cout << "vol_vol_surf_colls: \t\t" << s->vol_vol_surf_colls << " [long long] \t\t/* How many vol-vol-surf collisions have occured */\n";
cout << "vol_surf_surf_colls: \t\t" << s->vol_surf_surf_colls << " [long long] \t\t/* How many vol-surf-surf collisions have occured */\n";
cout << "surf_surf_surf_colls: \t\t" << s->surf_surf_surf_colls << " [long long] \t\t/* How many surf-surf-surf collisions have occured */\n";
cout << "bb_llf: \t\t" << s->bb_llf << " [vector3] \t\t/* llf corner of world bounding box */\n";
cout << "bb_urb: \t\t" << s->bb_urb << " [vector3] \t\t/* urb corner of world bounding box */\n";
cout << "rng: *\t\t" << (void*)s->rng << " [rng_state] \t\t/* State of the random number generator (currently isaac64) */\n";
cout << "init_seed: \t\t" << s->init_seed << " [u_int] \t\t/* Initial seed value for random number generator */\n";
cout << "current_iterations: \t\t" << s->current_iterations << " [long long] \t\t/* How many iterations have been run so far */\n";
// Starting iteration number for current run or iteration of most recent
// checkpoint
cout << "start_iterations: \t\t" << s->start_iterations << " [long long] \n";
cout << "last_timing_time: \t\t" << s->last_timing_time << " [timeval] \t\t/* time and iteration of last timing event */\n";
cout << "last_timing_iteration: \t\t" << s->last_timing_iteration << " [long long] \t\t/* during the main run_iteration loop */\n";
cout << "procnum: \t\t" << s->procnum << " [int] \t\t/* Processor number for a parallel run */\n";
cout << "quiet_flag: \t\t" << s->quiet_flag << " [int] \t\t/* Quiet mode */\n";
cout << "with_checks_flag: \t\t" << s->with_checks_flag << " [int] \t\t/* Check geometry for overlapped walls? */\n";
cout << "coll_mem: *\t\t" << (void*)s->coll_mem << " [mem_helper] \t\t/* Collision list */\n";
cout << "sp_coll_mem: *\t\t" << (void*)s->sp_coll_mem << " [mem_helper] \t\t/* Collision list (trimol) */\n";
cout << "tri_coll_mem: *\t\t" << (void*)s->tri_coll_mem << " [mem_helper] \t\t/* Collision list (trimol) */\n";
cout << "exdv_mem: *\t\t" << (void*)s->exdv_mem << " [mem_helper] // Vertex lists f ct interaction disk area\n";
/* Current version number. Format is "3.XX.YY" where XX is major release
* number (for new features) and YY is minor release number (for patches) */
cout << "mcell_version: *\t\t" << (void*)s->mcell_version << " [const char] \n";
cout << "use_expanded_list: \t\t" << s->use_expanded_list << " [int] \t\t/* If set, check neighboring subvolumes for mol-mol interactions */\n";
cout << "randomize_smol_pos: \t\t" << s->randomize_smol_pos << " [int] \t\t/* If set, always place surface molecule at random location instead of center of grid */\n";
cout << "vacancy_search_dist2: \t\t" << s->vacancy_search_dist2 << " [double] \t\t/* Square of distance to search for free grid location to place surface product */\n";
cout << "surface_reversibility: \t\t" << s->surface_reversibility << " [byte] \t\t/* If set, match unbinding diffusion distribution to binding distribution at surface */\n";
cout << "volume_reversibility: \t\t" << s->volume_reversibility << " [byte] \t\t/* If set, match unbinding diffusion distribution to binding distribution in volume */\n";
/* If set to NEAREST_TRIANGLE, molecules are moved to a random location
* slightly offset from the enclosing wall. If set to NEAREST_POINT, then
* they are moved to the closest point on that wall (still slightly offset).
* */
cout << "dynamic_geometry_molecule_placement: \t\t" << s->dynamic_geometry_molecule_placement << " [int] \n";
/* MCell startup command line arguments */
cout << "seed_seq: \t\t" << s->seed_seq << " [u_int] \t\t/* Seed for random number generator */\n";
cout << "iterations: \t\t" << s->iterations << " [long long] \t\t/* How many iterations to run */\n";
cout << "log_freq: \t\t" << s->log_freq << " [unsigned long] \t\t/* Interval between simulation progress reports, default scales as sqrt(iterations) */\n";
cout << "mdl_infile_name: *\t\t" << (void*)s->mdl_infile_name << " [char] \t\t/* Name of MDL file specified on command line */\n";
cout << "curr_file: *\t\t" << (void*)s->curr_file << " [const char ] \t\t/* Name of MDL file currently being parsed */\n";
// XXX: Why do we allocate this on the heap rather than including it inline?
cout << "notify: *\t\t" << (void*)s->notify << " [notifications] \t\t/* Notification/warning/output flags */\n";
cout << "clamp_list: *\t\t" << (void*)s->clamp_list << " [ccn_clamp_data] \t\t/* List of objects at which volume molecule concentrations should be clamped */\n";
/* Flags for asynchronously-triggered checkpoints */
/* Flag indicating whether a checkpoint has been requested. */
cout << "checkpoint_requested: \t\t" << s->checkpoint_requested << " [checkpoint_request_type_t] \n";
cout << "checkpoint_alarm_time: \t\t" << s->checkpoint_alarm_time << " [unsigned int] \t\t// number of seconds between checkpoints\n";
cout << "continue_after_checkpoint: \t\t" << s->continue_after_checkpoint << " [int] \t\t/* 0: exit after chkpt, 1: continue after chkpt */\n";
cout << "last_checkpoint_iteration: \t\t" << s->last_checkpoint_iteration << " [long long] \t\t/* Last iteration when chkpt was created */\n";
cout << "begin_timestamp: \t\t" << s->begin_timestamp << " [time_t] \t\t/* Time since epoch at beginning of 'main' */\n";
cout << "initialization_state: *\t\t" << (void*)s->initialization_state << " [char] \t\t/* NULL after initialization completes */\n";
cout << "rxn_flags: \t\t" << s->rxn_flags << " [reaction_flags] \n";
/* shared walls information per mesh vertex is created when there are
reactions present with more than one surface reactant or more than one
surface product */
cout << "create_shared_walls_info_flag: \t\t" << s->create_shared_walls_info_flag << " [int] \n";
/* resource usage during initialization */
cout << "u_init_time: \t\t" << s->u_init_time << " [timeval] \t\t/* user time */\n";
cout << "s_init_time: \t\t" << s->s_init_time << " [timeval] \t\t/* system time */\n";
cout << "t_start: \t\t" << s->t_start << " [time_t] \t\t/* global start time */\n";
cout << "reaction_prob_limit_flag: \t\t" << s->reaction_prob_limit_flag << " [byte] \t\t/* checks whether there is at least one reaction with probability greater than 1 including variable rate reactions */\n";
//JJT: Checks if we will be communicating with nfsim
cout << "nfsim_flag: \t\t" << s->nfsim_flag << " [int] \n";
cout << "global_nfsim_volume: *\t\t" << (void*)s->global_nfsim_volume << " [species] \n";
cout << "global_nfsim_surface: *\t\t" << (void*)s->global_nfsim_surface << " [species] \n";
cout << "species_mesh_transp: *\t\t" << (void*)s->species_mesh_transp << " [pointer_hash] \n";
cout << "********* volume dump :" << comment << "************ (END)\n";
cout.flush();
}
// ----------- other debug functions -------
string collision_flags_to_str(int flags) {
string res;
if (flags == COLLIDE_MISS) {
res = "COLLIDE_MISS";
return res;
}
if (flags == COLLIDE_REDO) {
res = "COLLIDE_REDO";
return res;
}
#define CHECK_FLAG(F) if (flags & F) res += #F ","
CHECK_FLAG(COLLIDE_FRONT);
CHECK_FLAG(COLLIDE_BACK);
CHECK_FLAG(COLLIDE_VOL_M);
CHECK_FLAG(COLLIDE_SV_NX);
CHECK_FLAG(COLLIDE_SV_PX);
CHECK_FLAG(COLLIDE_SV_NY);
CHECK_FLAG(COLLIDE_SV_PY);
CHECK_FLAG(COLLIDE_SV_NZ);
CHECK_FLAG(COLLIDE_SV_PZ);
CHECK_FLAG(COLLIDE_MASK);
CHECK_FLAG(COLLIDE_WALL);
CHECK_FLAG(COLLIDE_VOL);
CHECK_FLAG(COLLIDE_SUBVOL);
CHECK_FLAG(COLLIDE_VOL_VOL);
CHECK_FLAG(COLLIDE_VOL_SURF);
CHECK_FLAG(COLLIDE_SURF_SURF);
CHECK_FLAG(COLLIDE_SURF);
#undef CHECK_FLAG
return res;
}
void dump_one_collision(collision* col) {
cout << "next: *\t\t" << col->next << " [collision] \t\t\n";
cout << "t: \t\t" << col->t << " [double] \t\t/* Time of collision (may be slightly early) */\n";
cout << "target: *\t\t" << (void*)col->target << " [void] \t\t/* Thing that we hit: wall, molecule, subvol etc */\n";
cout << "what: \t\t" << collision_flags_to_str(col->what) << " [int] \t\t/* Target-type Flags: what kind of thing did we hit? */\n";
cout << "intermediate: *\t\t" << col->intermediate << " [rxn] \t\t/* Reaction that told us we could hit it */\n";
//if (col->intermediate != nullptr && col->intermediate->sym != nullptr && col->intermediate->sym->name != nullptr) {
// cout << "intermediate->sym->name: *\t\t" << col->intermediate->sym->name << "\n";
//}
cout << "loc: \t\t" << col->loc << " [vector3] \t\t/* Location of impact */\n";
}
void dump_collisions(collision* shead) {
/*cout << "Collision list: " << ((shead == nullptr) ? "EMPTY" : "") << "\n";
*/
int i = 0;
collision* ptr = shead;
while (ptr != NULL) {
if (ptr->what & COLLIDE_VOL /* != 0 && ptr->t < 1.0 && ptr->t >= 0.0*/) {
cout << " " << "mol collision " << i << ": "
//<< "diff_idx: " << ptr-> diffused_molecule_idx
<< "coll_idx: " << ((volume_molecule*)ptr->target)->id
<< ", time: " << ptr->t
<< ", pos: " << ptr->loc
<< "\n";
i++;
}
else if (
(ptr->what & COLLIDE_SUBVOL) == 0
&& (ptr->what == COLLIDE_REDO
|| (ptr->what & COLLIDE_FRONT) != 0
|| (ptr->what & COLLIDE_BACK) != 0
)
) {
#ifndef NODEBUG_WALL_COLLISIONS
const char* name = ((wall*)ptr->target)->parent_object->sym->name;
cout << " " << "wall collision " << i << ": "
//<< "diff_idx: " << ptr-> diffused_molecule_idx
<< "obj name: " << ((name != nullptr) ? name : "")
<< ", wall side: " << ((wall*)ptr->target)->side
<< ", time: " << ptr->t
<< ", pos: " << ptr->loc
<< "\n";
#endif
i++;
}
ptr = ptr->next;
}
}
// ----------- differential dumps ---------------
string get_species_name(volume_molecule* vm) {
return vm->properties->sym->name;
}
string get_species_name(surface_molecule* sm) {
return sm->properties->sym->name;
}
void dump_volume_molecule(
volume_molecule* vm,
const char* ind,
bool for_diff,
const char* extra_comment,
unsigned long long iteration,
double time,
bool print_position,
bool print_flags
) {
if (!for_diff) {
cout << ind << "id: \t\t" << vm->id << " [u_long] \t\t\n";
cout << ind << "pos: \t\t" << vm->pos << " [vector3] \t\t/* Position in space */\n";
cout << ind << "properties: *\t\t" << vm->properties << " [species] \t\t\n";
cout << ind << " species name: *\t\t" << vm->properties->sym->name << " [char] \t\t\n";
}
else {
cout << extra_comment << "it: " << iteration << ", id: " << vm->id;
if ((vm->properties->flags & EXTERNAL_SPECIES) == 0) {
cout << ", species: " << get_species_name(vm);
}
else {
cout << ", species: " << graph_pattern_to_bngl(vm->graph_data->graph_pattern);
}
if (print_position) {
cout << ", pos: " << vm->pos;
}
if (print_flags) {
cout << ", flags: " << get_molecule_flags_string(vm->flags, false);
}
cout << ", time: " << time << "\n";
}
}
void dump_surface_molecule(
surface_molecule* sm,
const char* ind,
bool for_diff,
const char* extra_comment,
unsigned long long iteration,
double time,
bool print_position,
bool print_flags
) {
if (!for_diff) {
cout << ind << "id: \t\t" << sm->id << " [u_long] \t\t\n";
cout << ind << "pos: \t\t" << sm->s_pos << " [vector2] \t\t/* Position in space */\n";
cout << ind << "properties: *\t\t" << sm->properties << " [species] \t\t\n";
cout << ind << " species name: *\t\t" << sm->properties->sym->name << " [char] \t\t\n";
}
else {
cout << extra_comment << "it: " << iteration << ", id: " << sm->id;
if ((sm->properties->flags & EXTERNAL_SPECIES) == 0) {
cout << ", species: " << get_species_name(sm);
}
else {
cout << ", species: " << graph_pattern_to_bngl(sm->graph_data->graph_pattern);
}
if (print_position) {
cout << ", pos: " << sm->s_pos
<< ", orient: " << sm->orient
<< ", wall side: " << ((sm->grid == nullptr || sm->grid->surface == nullptr) ? -1 : sm->grid->surface->side)
<< ", grid index: " << sm->grid_index;
}
if (print_flags) {
cout << ", flags: " << get_molecule_flags_string(sm->flags, false);
}
cout << ", time: " << time << "\n";
}
}
void dump_vector2(struct vector2 vec, const char* extra_comment) {
cout << extra_comment << vec << "\n";
}
void dump_vector3(struct vector3 vec, const char* extra_comment) {
cout << extra_comment << vec << "\n";
}
void dump_tile_neighbors_list(struct tile_neighbor *tile_nbr_head, const char* extra_comment, const char* ind) {
struct tile_neighbor *curr = tile_nbr_head;
int i = 0;
std::cout << ind << extra_comment << "\n";
while (curr != nullptr) {
std::cout << ind << i << ": " << curr->idx << "\n";
curr = curr->next;
i++;
}
}
void dump_processing_reaction(
long long it,
struct vector3 *hitpt, double t,
struct rxn *rx, /*int path,*/
struct abstract_molecule *reacA,
struct abstract_molecule *reacB,
struct wall *w
) {
assert(reacA != nullptr);
bool two_reactants = rx->n_reactants == 2;
cout << "Processing reaction:it:" << it << ", ";
if (two_reactants) {
if (reacB != nullptr) {
cout <<
"bimol rxn" <<
", idA:" << reacA->id <<
", idB:" << reacB->id <<
//TODO ", rxn: " << rx->to_string(p) <<
", time: " << t;
if (hitpt != nullptr) {
cout << ", pos " << *hitpt;
}
}
else {
assert(w != nullptr);
cout <<
"wall collision" <<
", idA:" << reacA->id <<
//", wall_index:" << w->side <<
//TODO ", rxn: " << rx->to_string(p) <<
", time: " << t;
if (hitpt != nullptr) {
cout << ", pos " << *hitpt;
}
}
}
else {
cout <<
"unimol rxn" <<
", idA:" << reacA->id <<
// ", rxn: " << rx->to_string(p) <<
", time: " << t;
}
cout << "\n";
}
| C++ |
3D | mcellteam/mcell | src/wall_util.h | .h | 6,775 | 161 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
#include "edge_util.h"
/* This linked list node is used in walls overlap test */
struct wall_aux_list {
struct wall *this_wall; /* wall */
double d_prod; /* dot product of wall's normal and random vector */
struct wall_aux_list *next;
};
struct plane {
struct vector3 n; /* Plane normal. Points x on the plane satisfy
dot_prod(n,x) = d */
double d; /* d = dot_prod(n,p) for a given point p on
the plane */
};
int surface_net(struct wall **facelist, int nfaces);
void init_edge_transform(struct edge *e, int edgenum);
int sharpen_object(struct geom_object *parent);
int sharpen_world(struct volume *world);
double closest_interior_point(struct vector3 *pt, struct wall *w,
struct vector2 *ip, double r2);
int find_edge_point(struct wall *here, struct vector2 *loc,
struct vector2 *disp, struct vector2 *edgept);
struct wall *traverse_surface(struct wall *here, struct vector2 *loc, int which,
struct vector2 *newloc);
int is_manifold(struct region *r, int count_regions_flag);
void jump_away_line(struct vector3 *p, struct vector3 *v, double k,
struct vector3 *A, struct vector3 *B, struct vector3 *n,
struct rng_state *rng);
int collide_wall(struct vector3 *point, struct vector3 *move, struct wall *face,
double *t, struct vector3 *hitpt, int update_move,
struct rng_state *rng, struct notifications *notify,
long long *polygon_tests);
int collide_mol(struct vector3 *point, struct vector3 *move,
struct abstract_molecule *a, double *t, struct vector3 *hitpt,
double rx_radius_3d);
int intersect_box(struct vector3 *llf, struct vector3 *urb, struct wall *w);
void init_tri_wall(struct geom_object *objp, int side, struct vector3 *v0,
struct vector3 *v1, struct vector3 *v2);
struct wall_list *wall_to_vol(struct wall *w, struct subvolume *sv);
struct wall *localize_wall(struct wall *w, struct storage *stor);
int distribute_object(struct volume *world, struct geom_object *parent);
int distribute_world(struct volume *world);
void closest_pt_point_triangle(struct vector3 *p, struct vector3 *a,
struct vector3 *b, struct vector3 *c,
struct vector3 *final_result);
int test_bounding_boxes(struct vector3 *llf1, struct vector3 *urb1,
struct vector3 *llf2, struct vector3 *urb2);
int release_onto_regions(struct volume *world, struct release_site_obj *rso,
struct surface_molecule *sm, int n);
struct surface_molecule *place_single_molecule(struct volume *state,
struct wall *w,
unsigned int grid_index,
struct species *spec,
struct graph_data* graph,
short flags, short orientation,
double t, double t2,
double birthday,
struct periodic_image *periodic_box,
struct vector3 *pos3d);
void push_wall_to_list(struct wall_list **wall_nbr_head, struct wall *w);
void delete_wall_list(struct wall_list *wl_head);
struct wall_list *find_nbr_walls_shared_one_vertex(struct volume *world,
struct wall *origin,
long long int *shared_vert);
int walls_share_full_edge(struct wall *w1, struct wall *w2);
struct region_list *find_region_by_wall(struct wall *this_wall);
struct name_list *find_regions_names_by_wall(
struct wall *w, struct string_buffer *ignore_regs);
struct region_list *
find_restricted_regions_by_wall(struct volume *world, struct wall *this_wall,
struct surface_molecule *sm);
struct region_list *
find_restricted_regions_by_object(struct volume *world, struct geom_object *obj,
struct surface_molecule *sm);
int are_restricted_regions_for_species_on_object(struct volume *world,
struct geom_object *obj,
struct surface_molecule *sm);
int is_wall_edge_region_border(struct wall *this_wall, struct edge *this_edge);
int is_wall_edge_restricted_region_border(struct volume *world,
struct wall *this_wall,
struct edge *this_edge,
struct surface_molecule *sm);
int find_shared_edge_index_of_neighbor_wall(struct wall *orig_wall,
struct wall *nbr_wall);
void find_neighbor_wall_and_edge(struct wall *orig_wall, int orig_edge_ind,
struct wall **nbr_wall, int *nbr_edge_ind);
int wall_contains_both_vertices(struct wall *w, struct vector3 *vert_A,
struct vector3 *vert_B);
int are_walls_coincident(struct wall *w1, struct wall *w2, double eps);
int are_walls_coplanar(struct wall *w1, struct wall *w2, double eps);
void sorted_insert_wall_aux_list(struct wall_aux_list **headRef,
struct wall_aux_list *newNode);
void delete_wall_aux_list(struct wall_aux_list *head);
int walls_belong_to_at_least_one_different_restricted_region(
struct volume *world, struct wall *w1, struct surface_molecule *sm1,
struct wall *w2, struct surface_molecule *sm2);
int wall_belongs_to_all_regions_in_region_list(struct wall *w,
struct region_list *rlp_head);
int wall_belongs_to_any_region_in_region_list(struct wall *w,
struct region_list *rlp_head);
int region_belongs_to_region_list(struct region *rp, struct region_list *head);
void find_wall_center(struct wall *w, struct vector3 *center);
| Unknown |
3D | mcellteam/mcell | src/dyngeom.c | .c | 84,145 | 2,261 | /******************************************************************************
*
* Copyright (C) 2006-2014 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
* ****************************************************************************/
#include "config.h"
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "chkpt.h"
#include "vol_util.h"
#include "grid_util.h"
#include "wall_util.h"
#include "init.h"
#include "logging.h"
#include "count_util.h"
#include "diffuse.h"
#include "dyngeom.h"
#include "mcell_misc.h"
#include "dyngeom_parse_extras.h"
#include "mdlparse_aux.h"
#include "react.h"
#include "nfsim_func.h"
#include "debug_config.h"
#include "dump_state.h"
#define NO_MESH "\0"
/***************************************************************************
save_all_molecules: Save all the molecules currently in the scheduler.
In: state: MCell state
storage_head: we will pull all the molecules out of the scheduler from
this
Out: An array of all the molecules to be saved
***************************************************************************/
struct molecule_info **save_all_molecules(struct volume *state,
struct storage_list *storage_head) {
// Find total number of molecules in the scheduler.
unsigned long long num_all_molecules = count_items_in_scheduler(storage_head);
int ctr = 0;
struct molecule_info **all_molecules = CHECKED_MALLOC_ARRAY(
struct molecule_info *, num_all_molecules, "all molecules");
// Iterate over all the molecules in every scheduler of every storage.
for (struct storage_list *sl_ptr = storage_head; sl_ptr != NULL;
sl_ptr = sl_ptr->next) {
for (struct schedule_helper *sh_ptr = sl_ptr->store->timer; sh_ptr != NULL;
sh_ptr = sh_ptr->next_scale) {
for (int i = -1; i < sh_ptr->buf_len; i++) {
for (struct abstract_element *ae_ptr =
(i < 0) ? sh_ptr->current : sh_ptr->circ_buf_head[i];
ae_ptr != NULL; ae_ptr = ae_ptr->next) {
struct abstract_molecule *am_ptr = (struct abstract_molecule *)ae_ptr;
if (am_ptr->properties == NULL)
continue;
struct molecule_info *mol_info =
CHECKED_MALLOC_STRUCT(struct molecule_info, "molecule info");
all_molecules[ctr] = mol_info;
mol_info->molecule = CHECKED_MALLOC_STRUCT(struct abstract_molecule,
"abstract molecule");
// Mesh names needed for VOLUME molecules
struct string_buffer *nested_mesh_names = NULL;
// Region names and mesh name needed for SURFACE molecules
struct string_buffer *reg_names =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
if (initialize_string_buffer(reg_names, MAX_NUM_REGIONS)) {
return NULL;
}
char *mesh_name = NULL;
if ((am_ptr->properties->flags & NOT_FREE) == 0) {
save_volume_molecule(state, mol_info, am_ptr, &nested_mesh_names);
} else if ((am_ptr->properties->flags & ON_GRID) != 0) {
if (save_surface_molecule(mol_info, am_ptr, ®_names, &mesh_name))
return NULL;
} else {
destroy_string_buffer(reg_names);
continue;
}
save_common_molecule_properties(
mol_info, am_ptr, reg_names, nested_mesh_names, mesh_name);
ctr += 1;
}
}
}
}
state->num_all_molecules = ctr;
return all_molecules;
}
/***************************************************************************
save_common_molecule_properties:
In: mol_info: holds all the information for recreating and placing a molecule
am_ptr: abstract molecule pointer
reg_names: the region names the molecule is on (surface molecules)
nested_mesh_names: the meshes the molecule is nested inside of (volume molecs)
mesh_name: mesh name that molecule is in (surface molecs)
Out: Nothing. The common properties of surface and volume molecules are saved
in mol_info.
***************************************************************************/
void save_common_molecule_properties(struct molecule_info *mol_info,
struct abstract_molecule *am_ptr,
struct string_buffer *reg_names,
struct string_buffer *nested_mesh_names,
char *mesh_name) {
mol_info->molecule->t = am_ptr->t;
mol_info->molecule->t2 = am_ptr->t2;
mol_info->molecule->flags = am_ptr->flags;
mol_info->molecule->properties = am_ptr->properties;
mol_info->molecule->birthday = am_ptr->birthday;
mol_info->molecule->id = am_ptr->id;
mol_info->molecule->periodic_box = am_ptr->periodic_box;
mol_info->molecule->mesh_name = CHECKED_STRDUP(mesh_name, "mesh name");
// Only free temporary object names we just allocated above.
// Don't want to accidentally free symbol names of objects.
if (mesh_name && (strcmp(mesh_name, NO_MESH) != 0) &&
((am_ptr->properties->flags & NOT_FREE) == 0)) {
free(mesh_name);
}
mol_info->reg_names = reg_names;
mol_info->mesh_names = nested_mesh_names;
}
/***************************************************************************
save_volume_molecule:
In: state: MCell state
mol_info: holds all the information for recreating and placing a molecule
am_ptr: abstract molecule pointer
nested_mesh_names: mesh names that molecule is inside of
Out: Nothing. Molecule info and mesh name are updated
***************************************************************************/
void save_volume_molecule(struct volume *state,
struct molecule_info *mol_info,
struct abstract_molecule *am_ptr,
struct string_buffer **nested_mesh_names) {
struct volume_molecule *vm_ptr = (struct volume_molecule *)am_ptr;
*nested_mesh_names = find_enclosing_meshes(state, vm_ptr, NULL);
mol_info->pos.x = vm_ptr->pos.x;
mol_info->pos.y = vm_ptr->pos.y;
mol_info->pos.z = vm_ptr->pos.z;
mol_info->orient = 0;
}
/***************************************************************************
save_surface_molecule:
In: mol_info: holds all the information for recreating and placing a molecule
am_ptr: abstract molecule pointer
reg_names: surface region names that the molecule is on get stored here
mesh_name: mesh name that molecule is on gets stored here
Out: Zero on success. One otherwise. Save relevant surface molecule data in
mol_info. Set the mesh_name. Populate reg_names with the region names the
sm is on.
***************************************************************************/
int save_surface_molecule(struct molecule_info *mol_info,
struct abstract_molecule *am_ptr,
struct string_buffer **reg_names,
char **mesh_name) {
struct vector3 where;
struct surface_molecule *sm_ptr = (struct surface_molecule *)am_ptr;
uv2xyz(&sm_ptr->s_pos, sm_ptr->grid->surface, &where);
mol_info->pos.x = where.x;
mol_info->pos.y = where.y;
mol_info->pos.z = where.z;
mol_info->orient = sm_ptr->orient;
*mesh_name = sm_ptr->grid->surface->parent_object->sym->name;
struct name_list *reg_name_list_head, *reg_name_list;
reg_name_list_head = find_regions_names_by_wall(sm_ptr->grid->surface, NULL);
// Add the names from reg_name_list_head to reg_names
for (reg_name_list = reg_name_list_head; reg_name_list != NULL;
reg_name_list = reg_name_list->next) {
char *str = CHECKED_STRDUP(reg_name_list->name, "region name");
if (add_string_to_buffer(*reg_names, str)) {
free(str);
destroy_string_buffer(*reg_names);
return 1;
}
}
if (reg_name_list_head != NULL) {
remove_molecules_name_list(®_name_list_head);
}
remove_surfmol_from_list(&sm_ptr->grid->sm_list[sm_ptr->grid_index], sm_ptr);
return 0;
}
/***************************************************************************
cleanup_names_molecs: Cleanup molecule data and string buffers for mesh and
region names
In: num_all_molecules: the number of all the molecules we just placed
all_molecules: array of info about all the molecules we just placed
Out: Nothing
***************************************************************************/
void cleanup_names_molecs(
int num_all_molecules,
struct molecule_info **all_molecules) {
for (int i = 0; i < num_all_molecules; i++) {
char *mesh_name = (char *)all_molecules[i]->molecule->mesh_name;
if (mesh_name && (strcmp(mesh_name, NO_MESH) != 0)) {
free(mesh_name);
}
free(all_molecules[i]->molecule);
// XXX: Could consolidate "reg_names" and "mesh_names", but we might want
// both for surface molecules eventually.
destroy_string_buffer(all_molecules[i]->reg_names);
free(all_molecules[i]->reg_names);
// This is currently unused for surface molecules.
if (all_molecules[i]->mesh_names != NULL) {
destroy_string_buffer(all_molecules[i]->mesh_names);
free(all_molecules[i]->mesh_names);
}
free(all_molecules[i]);
}
free(all_molecules);
}
/***************************************************************************
place_all_molecules: Place all molecules currently in the scheduler into the
world.
In: state: MCell state
meshes_to_ignore: don't place molecules on these meshes
regions_to_ignore: don't place molecules on these regions
Out: Zero on success. One otherwise.
***************************************************************************/
int place_all_molecules(
struct volume *state,
struct string_buffer *meshes_to_ignore,
struct string_buffer *regions_to_ignore) {
struct volume_molecule vm;
memset(&vm, 0, sizeof(struct volume_molecule));
struct volume_molecule *vm_ptr = &vm;
struct volume_molecule *vm_guess = NULL;
int num_all_molecules = state->num_all_molecules;
for (int n_mol = 0; n_mol < num_all_molecules; n_mol++) {
struct molecule_info *mol_info = state->all_molecules[n_mol];
struct abstract_molecule *am_ptr = mol_info->molecule;
initialize_diffusion_function(am_ptr);
// Insert volume molecule into world.
if ((am_ptr->properties->flags & NOT_FREE) == 0) {
vm_ptr->t = am_ptr->t;
vm_ptr->t2 = am_ptr->t2;
vm_ptr->flags = am_ptr->flags;
vm_ptr->properties = am_ptr->properties;
vm_ptr->birthday = am_ptr->birthday;
vm_ptr->id = am_ptr->id;
vm_ptr->pos.x = mol_info->pos.x;
vm_ptr->pos.y = mol_info->pos.y;
vm_ptr->pos.z = mol_info->pos.z;
vm_ptr->periodic_box = am_ptr->periodic_box;
initialize_diffusion_function((struct abstract_molecule*)vm_ptr);
vm_guess = insert_volume_molecule_encl_mesh(
state, vm_ptr, vm_guess, mol_info->mesh_names, meshes_to_ignore);
if (vm_guess == NULL) {
mcell_error("Cannot insert copy of molecule of species '%s' into "
"world.\nThis may be caused by a shortage of memory.",
vm_ptr->properties->sym->name);
}
}
// Insert surface molecule into world.
else if ((am_ptr->properties->flags & ON_GRID) != 0) {
const char *mesh_name = am_ptr->mesh_name;
struct surface_molecule *sm = insert_surface_molecule(
state, am_ptr->properties, &mol_info->pos, mol_info->orient,
state->vacancy_search_dist2, am_ptr->t, mesh_name,
mol_info->reg_names, regions_to_ignore, am_ptr->periodic_box);
free(am_ptr->periodic_box);
if (sm == NULL) {
mcell_warn("Unable to find surface upon which to place molecule %s.",
am_ptr->properties->sym->name);
}
}
}
cleanup_names_molecs(state->num_all_molecules, state->all_molecules);
return 0;
}
/***************************************************************************
compare_molecule_nesting:
Compare where the molecule was (prior to the geometry change) with where
it is now relative to the meshes. This also takes into account meshes nested
inside other meshes.
First, a little discussion on notation for the sake of being clear and
concise. When we say something like A->B->C->null, this means that mesh A is
inside mesh B which is inside mesh C. Lastly, C is an outermost mesh. Now,
onto the algorithm itself...
First, assume there is overlap, which we will check later.
For example:
mesh_names_old: A->B->C->D->null
mesh_names_new: C->D->null
A was the closest enclosing mesh and then C became the closest enclosing
mesh. That means the molecule moved from A to C.
The order could be reversed like this:
mesh_names_old: C->D->null
mesh_names_new: A->B->C->D->null
This means the molecule moved from C to A.
Check the last overlapping entry for both. If they actually overlap, these
strings will be the same. Otherwise, this is nonoverlapping (aside for null)
like this:
mesh_names_old: C->D->null
mesh_names_new: E->F->null
This means the molecule moved from C to E.
Next, we see if movement is possible from the starting position to ending
position.
In: move_molecule: if set, we need to move the molecule
out_to_in: if set, the molecule moved from outside to inside
mesh_names_old: a list of names that the molecule was nested in
mesh_names_new: a list of names that the molecule is nested in
mesh_transp: the object transparency rules for this species
Out: The name of the mesh that we are either immediately inside or outside of.
Also move_molecule and out_to_in are set.
***************************************************************************/
const char *compare_molecule_nesting(int *move_molecule,
int *out_to_in,
struct string_buffer *mesh_names_old,
struct string_buffer *mesh_names_new,
struct mesh_transparency *mesh_transp) {
int old_n_strings = mesh_names_old->n_strings;
int new_n_strings = mesh_names_new->n_strings;
int difference;
const char *old_mesh_name;
const char *new_mesh_name;
const char *best_mesh = mesh_names_old->strings[0];
struct string_buffer *compare_this;
// mesh_names_old example: C->D->null
// mesh_names_new example: A->B->C->D->null
if (old_n_strings < new_n_strings) {
difference = new_n_strings - old_n_strings;
old_mesh_name = mesh_names_old->strings[0];
new_mesh_name = mesh_names_new->strings[difference];
compare_this = mesh_names_new;
*out_to_in = 1;
}
// mesh_names_old example: A->B->C->D->null
// mesh_names_new example: C->D->null
else if (new_n_strings < old_n_strings) {
difference = old_n_strings - new_n_strings;
old_mesh_name = mesh_names_old->strings[difference];
new_mesh_name = mesh_names_new->strings[0];
compare_this = mesh_names_old;
*out_to_in = 0;
}
// Same amount of nesting
else {
difference = 0;
old_mesh_name = mesh_names_old->strings[0];
new_mesh_name = mesh_names_new->strings[0];
// Doesn't really matter if we use old or new one
compare_this = mesh_names_old;
}
if (old_mesh_name == NULL) {
old_mesh_name = NO_MESH;
}
if (new_mesh_name == NULL) {
new_mesh_name = NO_MESH;
}
if (best_mesh == NULL) {
best_mesh = NO_MESH;
}
int names_match = (strcmp(old_mesh_name, new_mesh_name) == 0);
if (names_match && (difference != 0)) {
best_mesh = check_overlapping_meshes(
move_molecule, out_to_in, difference, compare_this, best_mesh,
mesh_transp);
}
else if (!names_match) {
best_mesh = check_nonoverlapping_meshes(
move_molecule, out_to_in, mesh_names_old, mesh_names_new, best_mesh,
mesh_transp);
}
return best_mesh;
}
/***************************************************************************
check_overlapping_meshes:
In: move_molecule: if set, we need to move the molecule
out_to_in: if set, the molecule moved from outside to inside
difference: number of different meshes between old and new
compare_this: the mesh names to check
best_mesh: the current best mesh name
mesh_transp: the object transparency rules for this species
Out: The name of the mesh that we are either immediately inside or outside of.
Also move_molecule and out_to_in are set.
***************************************************************************/
const char *check_overlapping_meshes(
int *move_molecule,
int *out_to_in,
int difference,
struct string_buffer *compare_this,
const char *best_mesh,
struct mesh_transparency *mesh_transp) {
int start;
int increment;
int end;
// The molecule moved from *outside* a mesh to *inside* a mesh
if (*out_to_in) {
// We offset the starting value by one, because, even though the molecule
// started at the mesh corresponding to the "difference" index value, we
// only care if it was stopped by the next mesh inward.
start = difference-1;
increment = -1;
end = 0;
}
// The molecule moved from *inside* a mesh to *outside* a mesh
else {
start = 0;
increment = 1;
end = difference;
}
best_mesh = check_outin_or_inout(
start, increment, end, move_molecule, out_to_in, best_mesh,
compare_this, mesh_transp);
if (strcmp(best_mesh, NO_MESH) == 0) {
return NULL;
}
else {
return best_mesh;
}
}
/***************************************************************************
check_nonoverlapping_meshes:
By nonoverlapping, we mean that a molecule moved from one mesh (or set of
nested meshes) to another mesh (or nested set) which it neither contains nor
is inside of. For example, a molecule in A->B->null that moved to C->D->null
would be considered nonoverlapping. A is not in C and C is not in A.
In: move_molecule: if set, we need to move the molecule
out_to_in: if set, the molecule moved from outside to inside
mesh_names_old: the nested mesh names prior to this dyngeom event
mesh_names_new: the nested mesh names during to this dyngeom event
best_mesh: the mesh the molecule should actully be inside
mesh_transp: the object transparency rules for this species
Out: The name of the mesh that we are either immediately inside or outside of.
Also move_molecule and out_to_in are set.
***************************************************************************/
const char *check_nonoverlapping_meshes(int *move_molecule,
int *out_to_in,
struct string_buffer *mesh_names_old,
struct string_buffer *mesh_names_new,
const char *best_mesh,
struct mesh_transparency *mesh_transp) {
*out_to_in = 0;
int start = 0;
int increment = 1;
int end = mesh_names_old->n_strings;
// Moving in to out
best_mesh = check_outin_or_inout(
start, increment, end, move_molecule, out_to_in, best_mesh,
mesh_names_old, mesh_transp);
// Moving out to in
if (!(*move_molecule)) {
*out_to_in = 1;
start = mesh_names_new->n_strings;
end = 0;
increment = -1;
best_mesh = check_outin_or_inout(
start, increment, end, move_molecule, out_to_in, best_mesh,
mesh_names_new, mesh_transp);
}
return best_mesh;
}
/***************************************************************************
check_outin_or_inout:
See if a molecule can move from through the meshes (mesh_names) in the
direction specified (out_to_in). If it has to stop, return the name of the
mesh that blocks it.
In: start: start checking at this index
increment: move forward or backward through the string buffer
end: stop checking at this index
move_molecule: if set, we need to move the molecule
out_to_in: if set, the molecule moved from outside to inside
best_mesh: the current best mesh name
mesh_names: mesh names that molecule is inside of
mesh_transp: the object transparency rules for this species
Out: The name of the mesh that we are either immediately inside or outside of.
Also move_molecule and out_to_in are set.
***************************************************************************/
const char *check_outin_or_inout(
int start,
int increment,
int end,
int *move_molecule,
int *out_to_in,
const char *best_mesh,
struct string_buffer *mesh_names,
struct mesh_transparency *mesh_transp) {
int done = 0;
int mesh_idx = start;
while (!done) {
const char *mesh_name = mesh_names->strings[mesh_idx];
if (mesh_name == NULL) {
mesh_name = NO_MESH;
}
struct mesh_transparency *mt = mesh_transp;
for (; mt != NULL; mt = mt->next) {
if (strcmp(mesh_name, mt->name) == 0) {
if (((*out_to_in) && !mt->out_to_in) ||
(!(*out_to_in) && !mt->in_to_out)) {
best_mesh = mesh_name;
*move_molecule = 1;
done = 1;
}
break;
}
}
if (mesh_idx == end) {
done = 1;
}
mesh_idx = mesh_idx + increment;
}
return best_mesh;
}
/*************************************************************************
insert_volume_molecule_encl_mesh:
In: state: MCell state
vm: pointer to volume_molecule that we're going to place in local storage
vm_guess: pointer to a volume_molecule that may be nearby
nested_mesh_names_old: the meshes this molecule was inside of previously
meshes_to_ignore: the meshes we should ignore when placing this molecule
Out: pointer to the new volume_molecule (copies data from volume molecule
passed in), or NULL if out of memory. Molecule is placed in scheduler
also.
*************************************************************************/
struct volume_molecule *insert_volume_molecule_encl_mesh(
struct volume *state,
struct volume_molecule *vm,
struct volume_molecule *vm_guess,
struct string_buffer *nested_mesh_names_old,
struct string_buffer *meshes_to_ignore) {
struct subvolume *sv;
// We should only have to do this the first time this function gets called
if (vm_guess == NULL)
sv = find_subvolume(state, &(vm->pos), NULL);
// This should speed things up if the last molecule was close to this one
else if (inside_subvolume(&(vm->pos), vm_guess->subvol, state->x_fineparts,
state->y_fineparts, state->z_fineparts)) {
sv = vm_guess->subvol;
} else
sv = find_subvolume(state, &(vm->pos), vm_guess->subvol);
struct volume_molecule *new_vm = (struct volume_molecule *)CHECKED_MEM_GET(
sv->local_storage->mol, "volume molecule");
memcpy(new_vm, vm, sizeof(struct volume_molecule));
new_vm->mesh_name = NULL;
new_vm->prev_v = NULL;
new_vm->next_v = NULL;
new_vm->next = NULL;
new_vm->subvol = sv;
new_vm->periodic_box = vm->periodic_box;
struct string_buffer *nested_mesh_names_new = find_enclosing_meshes(
state, new_vm, meshes_to_ignore);
// Make a new string buffer without all the meshes we don't care about (i.e.
// the ones we *removed* in this dyn_geom_event). We are already ingoring the
// ones just *added* in this dyn_geom_event (in find_enclosing_meshes). Maybe
// we should do that here to be consistent and keep the logic decoupled.
struct string_buffer *nested_mesh_names_old_filtered =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(nested_mesh_names_old_filtered, MAX_NUM_OBJECTS);
diff_string_buffers(
nested_mesh_names_old_filtered, nested_mesh_names_old, meshes_to_ignore);
const char *species_name = new_vm->properties->sym->name;
unsigned int keyhash = (unsigned int)(intptr_t)(species_name);
void *key = (void *)(species_name);
struct mesh_transparency *mesh_transp = (
struct mesh_transparency *)pointer_hash_lookup(state->species_mesh_transp,
key, keyhash);
int move_molecule = 0;
int out_to_in = 0;
const char *mesh_name = compare_molecule_nesting(
&move_molecule,
&out_to_in,
nested_mesh_names_old_filtered,
nested_mesh_names_new,
mesh_transp);
struct vector3 new_pos;
if (move_molecule) {
/* move molecule to another location so that it is directly inside or
* outside of "mesh_name" */
#ifdef DEBUG_DYNAMIC_GEOMETRY
dump_volume_molecule(vm, "", true, "Moving vm towards new wall: ", state->current_iterations, /*vm->t*/0, true);
#endif
place_mol_relative_to_mesh(
state, &(vm->pos), sv, mesh_name, &new_pos, out_to_in);
check_for_large_molecular_displacement(
&(vm->pos), &new_pos, vm, &(state->time_unit),
state->notify->large_molecular_displacement);
new_vm->pos = new_pos;
struct subvolume *new_sv = find_subvolume(state, &(new_vm->pos), NULL);
new_vm->subvol = new_sv;
state->dyngeom_molec_displacements++;
#ifdef DEBUG_DYNAMIC_GEOMETRY
dump_volume_molecule(new_vm, "", true, "Vm after being moved: ", state->current_iterations, /*vm->t*/0, true);
#endif
}
destroy_string_buffer(nested_mesh_names_old_filtered);
free(nested_mesh_names_old_filtered);
destroy_string_buffer(nested_mesh_names_new);
free(nested_mesh_names_new);
new_vm->birthplace = new_vm->subvol->local_storage->mol;
ht_add_molecule_to_list(&(new_vm->subvol->mol_by_species), new_vm);
new_vm->subvol->mol_count++;
new_vm->properties->population++;
if ((new_vm->properties->flags & COUNT_SOME_MASK) != 0) {
new_vm->flags |= COUNT_ME;
}
// XXX: need to set periodic box properly
if (new_vm->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) {
count_region_from_scratch(state, (struct abstract_molecule *)new_vm, NULL,
1, &(new_vm->pos), NULL, new_vm->t,
new_vm->periodic_box);
}
if (schedule_add_mol(new_vm->subvol->local_storage->timer, new_vm))
mcell_allocfailed("Failed to add volume molecule to scheduler.");
return new_vm;
}
/*************************************************************************
check_for_large_molecular_displacement:
In: old_pos: The current position of the molecule
new_pos: The position we are trying to move the molecule to
vm: volume molecule
timestep: global timestep in seconds
large_molecular_displacement_warning: the warning value
(ignore, warn, error) set for molecular displacement
Out: 0 on success, 1 otherwise.
************************************************************************/
void check_for_large_molecular_displacement(
struct vector3 *old_pos,
struct vector3 *new_pos,
struct volume_molecule *vm,
double *timestep,
enum warn_level_t large_molecular_displacement_warning) {
double displacement = distance_vec3(old_pos, new_pos) / 100.0;
double l_perp_bar = sqrt(4 * 1.0e8 * vm->properties->D * *timestep / MY_PI);
double l_r_bar = 2 * l_perp_bar;
if (displacement >= l_r_bar) {
switch (large_molecular_displacement_warning) {
case WARN_COPE:
break;
case WARN_WARN:
mcell_warn("Displacement of '%s' is greater than l_r_bar.\n"
"\tdisplacement = %.9g microns\n"
"\tl_r_bar = %.9g microns\n",
vm->properties->sym->name, displacement, l_r_bar);
break;
case WARN_ERROR:
mcell_error("Displacement of '%s' is greater than l_r_bar.\n"
"\tdisplacement = %.9g microns\n"
"\tl_r_bar = %.9g microns\n",
vm->properties->sym->name, displacement, l_r_bar);
}
}
}
/*************************************************************************
hit_wall:
In: w: wall
name_hits_head: the head of a list that tracks the meshes we've hit and
how many times they've been hit
name_tail_head: the tail of the same list
displace_vector: a large displacement vector that spans the whole
simulation space
Out: Head and tail are updated. In other words, we track meshes we've hit
************************************************************************/
int hit_wall(
struct wall *w,
struct name_hits **name_hits_head,
struct name_hits **name_tail_head,
struct vector3 *displace_vector) {
// Discard open-type meshes, like planes, etc.
if (w->parent_object->is_closed <= 0)
return 1;
/* Discard the cases when the random vector just grazes the mesh at the
* encounter point */
double d_prod = dot_prod(displace_vector, &(w->normal));
if (!distinguishable(d_prod, 0, EPS_C))
return 1;
// First time hitting *any* object
if (*name_hits_head == NULL) {
// name and count of hits
struct name_hits *nh = CHECKED_MALLOC_STRUCT(
struct name_hits, "struct name_hits");
nh->name = CHECKED_STRDUP(w->parent_object->sym->name,
"w->parent_object->sym->name");
nh->hits = 1;
nh->next = NULL;
*name_hits_head = nh;
*name_tail_head = *name_hits_head;
// We've hit at least one object already
} else {
int found = 0; // flag
for (struct name_hits *nhl = *name_hits_head; nhl != NULL; nhl = nhl->next) {
// Keep track of how many times we hit *this* object
if (strcmp(nhl->name, w->parent_object->sym->name) == 0) {
nhl->hits++;
found = 1;
break;
}
}
// First time hitting *this* object
if (!found) {
// Add to the end of list
struct name_hits *nh =
CHECKED_MALLOC_STRUCT(struct name_hits, "struct name_hits");
nh->name = CHECKED_STRDUP(w->parent_object->sym->name,
"w->parent_object->sym->name");
nh->hits = 1;
nh->next = (*name_tail_head)->next;
(*name_tail_head)->next = nh;
*name_tail_head = (*name_tail_head)->next;
}
}
return 0;
}
/*************************************************************************
hit_subvol:
In: state: MCell state
mesh_names: meshes that the molecule is inside of
smash: the thing that the current molecule has collided with
shead: the head of a list of what the current molecule has collided with
name_hits_head: the head of a list that tracks the meshes we've hit and
how many times they've been hit
sv: subvolume
virt_mol:
Out: Compile list of meshes we are inside of (hit odd number of times) or
update next subvolume
************************************************************************/
void hit_subvol(
struct n_parts *np,
struct string_buffer *mesh_names,
struct collision *smash,
struct collision *shead,
struct name_hits *name_hits_head,
struct subvolume *sv,
struct volume_molecule *virt_mol) {
virt_mol->pos.x = smash->loc.x;
virt_mol->pos.y = smash->loc.y;
virt_mol->pos.z = smash->loc.z;
virt_mol->subvol = NULL;
struct subvolume *new_sv = traverse_subvol(
sv, smash->what - COLLIDE_SV_NX - COLLIDE_SUBVOL,
np->ny_parts, np->nz_parts);
// Hit the edge of the world
if (new_sv == NULL) {
if (shead != NULL)
mem_put_list(sv->local_storage->coll, shead);
// Compile the final list of meshes (names and counts) that we are inside
for (struct name_hits *nhl = name_hits_head; nhl != NULL; nhl = nhl->next) {
if (nhl->hits % 2 != 0) {
char *mesh_name = CHECKED_STRDUP(nhl->name, "mesh name");
if (add_string_to_buffer(mesh_names, mesh_name)) {
free(mesh_name);
destroy_string_buffer(mesh_names);
}
}
}
// Clean up
while (name_hits_head != NULL) {
struct name_hits *nnext = name_hits_head->next;
free(name_hits_head->name);
free(name_hits_head);
name_hits_head = nnext;
}
return;
}
if (shead != NULL)
mem_put_list(sv->local_storage->coll, shead);
virt_mol->subvol = new_sv;
}
/*************************************************************************
find_enclosing_meshes:
In: state: MCell state
vm: volume molecule
meshes_to_ignore: ignore these meshes when checking what this molecule
is inside of
Out: String buffer of enclosing meshes if they exist. NULL otherwise.
************************************************************************/
struct string_buffer *find_enclosing_meshes(
struct volume *state,
struct volume_molecule *vm,
struct string_buffer *meshes_to_ignore) {
// We create a virtual molecule, so that we don't displace the real one (vm).
struct volume_molecule virt_mol;
memcpy(&virt_mol, vm, sizeof(struct volume_molecule));
virt_mol.prev_v = NULL;
virt_mol.next_v = NULL;
virt_mol.next = NULL;
// This is where we will store the names of the meshes we are nested in.
struct string_buffer *mesh_names =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
if (initialize_string_buffer(mesh_names, MAX_NUM_OBJECTS)) {
return NULL;
}
// Displacement vector along arbitray cardinal axis.
struct vector3 displace_vector = {0.0, 0.0, 1.0};
// Find the diagonal of the world's bounding box
struct vector3 world_diag;
vectorize(&state->bb_urb, &state->bb_llf, &world_diag);
// Length of the world's bounding box diagonal
double world_diag_length = vect_length(&world_diag);
// Set world diagonal to nonzero value so we don't fail in traverse_subvol
if (!distinguishable(world_diag_length, 0, EPS_C)) {
world_diag_length = 1.0;
}
// Scale displacement vector by the length of the world
displace_vector.x *= world_diag_length;
displace_vector.y *= world_diag_length;
displace_vector.z *= world_diag_length;
struct collision *smash; /* Thing we've hit that's under consideration */
struct collision *shead = NULL; // Head of the linked list of collisions
struct subvolume *sv = virt_mol.subvol;
struct name_hits *nh_head = NULL, *nh_tail = NULL;
do {
// Get collision list for walls and a subvolume. We don't care about
// colliding with other molecules like we do with reactions
shead = ray_trace(state, &(virt_mol.pos), NULL, sv, &displace_vector, NULL);
if (shead == NULL)
mcell_internal_error("ray_trace() returned NULL.");
if (shead->next != NULL) {
shead =
(struct collision *)ae_list_sort((struct abstract_element *)shead);
}
for (smash = shead; smash != NULL; smash = smash->next) {
// We hit a wall
if ((smash->what & COLLIDE_WALL) != 0) {
// Only check this when we are placing molecules, not when we are
// saving them.
struct wall *w = (struct wall *)smash->target;
if ((meshes_to_ignore) && (is_string_present_in_string_array(
w->parent_object->sym->name,
meshes_to_ignore->strings,
meshes_to_ignore->n_strings))) {
continue;
}
if (hit_wall(w, &nh_head, &nh_tail, &displace_vector)) {
continue;
}
// We hit a subvolume
} else if ((smash->what & COLLIDE_SUBVOL) != 0) {
// Numbers of coarse partitions
struct n_parts np = {
state->nx_parts, state->ny_parts, state->nz_parts};
hit_subvol(&np, mesh_names, smash, shead, nh_head, sv, &virt_mol);
// We hit the edge of the world
if (virt_mol.subvol == NULL) {
return mesh_names;
}
sv = virt_mol.subvol;
break;
}
}
} while (smash != NULL);
free(mesh_names);
return NULL;
}
/**********************************************************************
place_mol_relative_to_mesh:
In: state: MCell state
loc: 3D location of molecule
sv: start subvolume
mesh_name: name of closest enclosing mesh (NULL means that molecule
is outside of all meshes)
new_pos: new position of molecule (return value)
out_to_in: if set, the molecule moved from outside to inside
Note: new position of molecule that is just behind the closest
wall that belongs to object called "mesh_name" (if "mesh_name != NULL")
or just outside the closest wall that belongs to the farthest
enclosing mesh object (if "mesh_name == NULL").
Note: we call this function when geometry changes after checkpoint so that:
1) before checkpoint molecule was inside the mesh, and after
checkpoint it is outside the mesh,
2) before checkpoint molecule was outside all meshes, and after
checkpoint it is inside the mesh,
3) before checkpoint molecule was inside one mesh, and after
checkpoint it is inside another mesh.
Here by mesh we mean the closest enclosing mesh.
**********************************************************************/
void place_mol_relative_to_mesh(struct volume *state,
struct vector3 *loc,
struct subvolume *sv,
const char *mesh_name,
struct vector3 *new_pos,
int out_to_in) {
struct vector2 s_loc;
struct vector2 best_s_loc;
struct wall *best_w = NULL;
double d2;
double best_d2 = GIGANTIC + 1;
for (struct wall_list *wl = sv->wall_head; wl != NULL; wl = wl->next) {
if (strcmp(wl->this_wall->parent_object->sym->name, mesh_name) != 0) {
continue;
}
d2 = closest_interior_point(loc, wl->this_wall, &s_loc, GIGANTIC);
if (d2 < best_d2) {
best_d2 = d2;
best_w = wl->this_wall;
best_s_loc = s_loc;
}
}
// Look into neighbor subvolumes
const int sv_index = sv - state->subvol;
int sv_remain = sv_index;
// Turn linear sv_index into part_x, part_y, part_z triple.
const int part_x =
sv_remain / ((state->ny_parts - 1) * (state->nz_parts - 1));
sv_remain -= part_x * ((state->ny_parts - 1) * (state->nz_parts - 1));
const int part_y = sv_remain / (state->nz_parts - 1);
sv_remain -= part_y * (state->nz_parts - 1);
const int part_z = sv_remain;
// Find min x partition.
int x_min;
for (x_min = part_x; x_min > 0; x_min--) {
d2 = loc->x - state->x_partitions[x_min];
d2 *= d2;
if (d2 >= best_d2)
break;
}
// Find max x partition.
int x_max;
for (x_max = part_x; x_max < state->nx_parts - 1; x_max++) {
d2 = loc->x - state->x_partitions[x_max + 1];
d2 *= d2;
if (d2 >= best_d2)
break;
}
// Find min y partition.
int y_min;
for (y_min = part_y; y_min > 0; y_min--) {
d2 = loc->y - state->y_partitions[y_min];
d2 *= d2;
if (d2 >= best_d2)
break;
}
// Find max y partition.
int y_max;
for (y_max = part_y; y_max < state->ny_parts - 1; y_max++) {
d2 = loc->y - state->y_partitions[y_max + 1];
d2 *= d2;
if (d2 >= best_d2)
break;
}
// Find min z partition.
int z_min;
for (z_min = part_z; z_min > 0; z_min--) {
d2 = loc->z - state->z_partitions[z_min];
d2 *= d2;
if (d2 >= best_d2)
break;
}
// Find max z partition.
int z_max;
for (z_max = part_z; z_max < state->nz_parts - 1; z_max++) {
d2 = loc->z - state->z_partitions[z_max + 1];
d2 *= d2;
if (d2 >= best_d2)
break;
}
if (x_min < part_x || x_max > part_x || y_min < part_y || y_max > part_y ||
z_min < part_z || z_max > part_z) {
for (int px = x_min; px < x_max; px++) {
for (int py = y_min; py < y_max; py++) {
for (int pz = z_min; pz < z_max; pz++) {
const int this_sv =
pz + (state->nz_parts - 1) * (py + (state->ny_parts - 1) * px);
if (this_sv == sv_index)
continue;
for (struct wall_list *wl = state->subvol[this_sv].wall_head;
wl != NULL; wl = wl->next) {
if (strcmp(wl->this_wall->parent_object->sym->name, mesh_name) != 0) {
continue;
}
d2 = closest_interior_point(loc, wl->this_wall, &s_loc, GIGANTIC);
if (d2 < best_d2) {
best_d2 = d2;
best_w = wl->this_wall;
best_s_loc = s_loc;
}
}
}
}
}
}
#ifdef DEBUG_DYNAMIC_GEOMETRY
dump_wall(best_w, "", true);
#endif
if (best_w == NULL) {
mcell_internal_error("Error in function 'place_mol_relative_to_mesh()'.");
}
// We will return the point just behind or in front of the closest enclosing
// mesh
/* the parametric equation of ray is L(t) = A + t(B - A),
where A - start vector, B - some point on the ray, and parameter t >= 0 */
struct vector3 v;
if (state->dynamic_geometry_molecule_placement == 1) {
double s1 = sqrt(rng_dbl(state->rng));
double s2 = rng_dbl(state->rng) * s1;
v.x = best_w->vert[0]->x + s1 * (best_w->vert[1]->x - best_w->vert[0]->x) + s2 * (best_w->vert[2]->x - best_w->vert[1]->x);
v.y = best_w->vert[0]->y + s1 * (best_w->vert[1]->y - best_w->vert[0]->y) + s2 * (best_w->vert[2]->y - best_w->vert[1]->y);
v.z = best_w->vert[0]->z + s1 * (best_w->vert[1]->z - best_w->vert[0]->z) + s2 * (best_w->vert[2]->z - best_w->vert[1]->z);
}
else if (state->dynamic_geometry_molecule_placement == 0) {
uv2xyz(&best_s_loc, best_w, &v);
}
double bump = (out_to_in > 0) ? EPS_C : -EPS_C;
struct vector3 displacement = {2 * bump * best_w->normal.x,
2 * bump * best_w->normal.y,
2 * bump * best_w->normal.z,
};
struct subvolume *new_sv = find_subvolume(state, &v, NULL);
tiny_diffuse_3D(state, new_sv, &displacement, &v, best_w);
// Make sure we didn't end up on a neighbor's wall, which is kind of easy to
// do with, for example, a shrinking box/cuboid.
for (int edge = 0; edge < 3; edge++) {
struct wall *neighbor = NULL;
if (best_w != best_w->edges[edge]->forward) {
neighbor = best_w->edges[edge]->forward;
}
else if (best_w != best_w->edges[edge]->backward) {
neighbor = best_w->edges[edge]->backward;
}
else {
continue;
}
d2 = closest_interior_point(&v, neighbor, &best_s_loc, GIGANTIC);
if (!distinguishable(d2, 0, EPS_C)) {
new_sv = find_subvolume(state, &v, NULL);
bump = (out_to_in > 0) ? EPS_C : -EPS_C;
displacement.x = 2 * bump * neighbor->normal.x;
displacement.y = 2 * bump * neighbor->normal.y;
displacement.z = 2 * bump * neighbor->normal.z;
new_sv = find_subvolume(state, &v, NULL);
tiny_diffuse_3D(state, new_sv, &displacement, &v, neighbor);
break;
}
}
new_pos->x = v.x;
new_pos->y = v.y;
new_pos->z = v.z;
}
/***************************************************************************
destroy_mesh_transp_data:
In: mol_sym_table:
species_mesh_transp:
Out: Destroy mesh-species transparency data structure
***************************************************************************/
void destroy_mesh_transp_data(
struct sym_table_head *mol_sym_table,
struct pointer_hash *species_mesh_transp) {
for (int n_mol_bin = 0; n_mol_bin < mol_sym_table->n_bins; n_mol_bin++) {
for (struct sym_entry *sym_ptr = mol_sym_table->entries[n_mol_bin];
sym_ptr != NULL; sym_ptr = sym_ptr->next) {
const char *species_name = sym_ptr->name;
if (strcmp(species_name, "ALL_MOLECULES") == 0)
continue;
else if (strcmp(species_name, "ALL_VOLUME_MOLECULES") == 0)
continue;
else if (strcmp(species_name, "ALL_SURFACE_MOLECULES") == 0)
continue;
unsigned int keyhash = (unsigned int)(intptr_t)(species_name);
void *key = (void *)(species_name);
struct mesh_transparency *mesh_transp = (
struct mesh_transparency *)pointer_hash_lookup(
species_mesh_transp, key, keyhash);
delete_void_list((struct void_list *)mesh_transp);
}
}
pointer_hash_destroy(species_mesh_transp);
free(species_mesh_transp);
}
/***************************************************************************
destroy_everything:
In: state: MCell state
Out: Zero on success. One otherwise. This wipes out almost everything in the
simulation except for things like the symbol tables, reactions, etc.
Currently, this is necessary for dynamic geometries. In principle, it
would make more sense to only trash the meshes changing, but there are
so many tightly coupled dependencies that it's difficult to do it at
this time.
***************************************************************************/
int destroy_everything(struct volume *state) {
destroy_objects(state->root_instance, 1);
destroy_objects(state->root_object, 0);
state->root_instance->first_child = NULL;
state->root_instance->last_child = NULL;
state->root_instance->n_walls = 0;
state->root_instance->n_walls_actual = 0;
state->root_instance->n_verts = 0;
state->root_object->first_child = NULL;
state->root_object->last_child = NULL;
state->root_object->n_walls = 0;
state->root_object->n_walls_actual = 0;
state->root_object->n_verts = 0;
if (state->clamp_list) {
free(state->clamp_list->side_idx);
free(state->clamp_list->cum_area);
}
destroy_walls(state);
// Destroy memory helpers
delete_mem(state->coll_mem);
delete_mem(state->exdv_mem);
struct storage_list *mem;
for (mem = state->storage_head; mem != NULL; mem = mem->next) {
delete_mem(mem->store->list);
delete_mem(mem->store->mol);
delete_mem(mem->store->smol);
delete_mem(mem->store->face);
delete_mem(mem->store->join);
delete_mem(mem->store->grids);
delete_mem(mem->store->regl);
delete_mem(mem->store->pslv);
}
// Destroy subvolumes
for (int i = 0; i < state->n_subvols; i++) {
struct subvolume *sv = &state->subvol[i];
pointer_hash_destroy(&sv->mol_by_species);
sv->local_storage->wall_head = NULL;
sv->local_storage->wall_count = 0;
sv->local_storage->vert_count = 0;
sv->wall_head = NULL;
}
for (mem = state->storage_head; mem != NULL; mem = mem->next) {
delete_scheduler(mem->store->timer);
free(mem->store);
}
state->storage_head->store = NULL;
state->storage_head = NULL;
delete_mem(state->storage_allocator);
delete_mem(state->sp_coll_mem);
delete_mem(state->tri_coll_mem);
destroy_partitions(state);
free(state->waypoints);
// Destroy mesh-species transparency data structure
destroy_mesh_transp_data(state->mol_sym_table, state->species_mesh_transp);
for (struct clamp_data *clamp_list = state->clamp_list;
clamp_list != NULL;
clamp_list = clamp_list->next) {
clamp_list->n_sides = 0;
}
return 0;
}
/***************************************************************************
destroy_walls:
In: state: MCell state
Out: Free up the memory for the walls and vertices
***************************************************************************/
void destroy_walls(struct volume *state) {
if (state->walls_using_vertex) {
for (int i = 0; i<state->n_verts; i++) {
delete_void_list((struct void_list *)state->walls_using_vertex[i]);
}
}
free(state->walls_using_vertex);
free(state->all_vertices);
state->n_walls = 0;
state->n_verts = 0;
}
/***************************************************************************
destroy_partitions:
In: state: MCell state
Out: Free up the memory for the fine and coarse partitions
***************************************************************************/
void destroy_partitions(struct volume *state) {
state->n_fineparts = 0;
free(state->x_fineparts);
free(state->y_fineparts);
free(state->z_fineparts);
state->x_fineparts = NULL;
state->y_fineparts = NULL;
state->z_fineparts = NULL;
free(state->x_partitions);
free(state->y_partitions);
free(state->z_partitions);
state->x_partitions = NULL;
state->y_partitions = NULL;
state->z_partitions = NULL;
}
/***************************************************************************
destroy_objects:
In: obj_ptr: object to be destroyed
free_poly_flag: see explanation in destroy_poly_object
Out: Zero on success. One otherwise. Recursively destroys objects.
Note: Currently, this ultimately only destroys polygon objects. I don't know
if there's a need to trash release objects that use release patterns.
***************************************************************************/
int destroy_objects(struct geom_object *obj_ptr, int free_poly_flag) {
obj_ptr->sym->count = 0;
switch (obj_ptr->object_type) {
case META_OBJ:
for (struct geom_object *child_obj_ptr = obj_ptr->first_child;
child_obj_ptr != NULL; child_obj_ptr = child_obj_ptr->next) {
destroy_objects(child_obj_ptr, free_poly_flag);
child_obj_ptr->n_walls = 0;
child_obj_ptr->n_walls_actual = 0;
child_obj_ptr->n_verts = 0;
child_obj_ptr->first_child = NULL;
child_obj_ptr->last_child = NULL;
}
break;
case BOX_OBJ:
case POLY_OBJ:
destroy_poly_object(obj_ptr, free_poly_flag);
break;
// do nothing
case REL_SITE_OBJ:
case VOXEL_OBJ:
break;
}
return 0;
}
/***************************************************************************
destroy_poly_object:
In: obj_ptr: object
free_poly_flag: Destroy polygon_object if set. There's a pointer to this
in the object definition (child of root_object) AND the instantiated
object (child of root_insance), so we only want to free it once.
Out: Zero on success. One otherwise. Polygon object is destroyed
***************************************************************************/
int destroy_poly_object(struct geom_object *obj_ptr, int free_poly_flag) {
if (free_poly_flag) {
for (int wall_num = 0; wall_num < obj_ptr->n_walls; wall_num++) {
struct wall *w = obj_ptr->wall_p[wall_num];
if (w->grid) {
/*free(w->grid->mol);*/
delete_void_list((struct void_list *)w->grid->sm_list);
}
delete_void_list((struct void_list *)w->surf_class_head);
}
struct polygon_object *poly_obj_ptr = (struct polygon_object *)obj_ptr->contents;
free(poly_obj_ptr->side_removed);
poly_obj_ptr->side_removed = NULL;
free(poly_obj_ptr->element);
poly_obj_ptr->element = NULL;
poly_obj_ptr->references--;
// Clean up when there are no other instances of this object
if (poly_obj_ptr->references == 0) {
free(obj_ptr->contents);
obj_ptr->contents = NULL;
}
free(obj_ptr->last_name);
obj_ptr->last_name = NULL;
}
obj_ptr->sym->count = 0;
free(obj_ptr->walls);
free(obj_ptr->wall_p);
obj_ptr->wall_p = NULL;
free(obj_ptr->vertices);
obj_ptr->vertices = NULL;
obj_ptr->wall_p = NULL;
obj_ptr->n_walls = 0;
obj_ptr->n_walls_actual = 0;
obj_ptr->n_verts = 0;
struct region_list *regs, *next_regs;
for (regs = obj_ptr->regions; regs != NULL;) {
if (free_poly_flag && (strcmp(regs->reg->region_last_name, "ALL") != 0)) {
//XXX: this doesn't work with dynamic geometries and pymcell...
/*free(regs->reg->region_last_name);*/
regs->reg->region_last_name = NULL;
}
delete_void_list((struct void_list *)regs->reg->sm_dat_head);
regs->reg->sm_dat_head = NULL;
free(regs->reg->membership);
regs->reg->membership = NULL;
free(regs->reg->bbox);
regs->reg->bbox = NULL;
if (regs->reg->boundaries) {
pointer_hash_destroy(regs->reg->boundaries);
}
free(regs->reg->boundaries);
regs->reg->boundaries = NULL;
regs->reg->sym->count = 0;
next_regs = regs->next;
free(regs);
regs = next_regs;
}
obj_ptr->regions = NULL;
obj_ptr->num_regions = 0;
obj_ptr->total_area = 0;
init_matrix(obj_ptr->t_matrix);
return 0;
}
/***************************************************************************
reset_current_counts:
In: mol_sym_table:
count_hashmask:
count_hash:
Out: Zero on success. Species populations are set to zero. Counts on/in
regions are also set to zero.
***************************************************************************/
int reset_current_counts(struct sym_table_head *mol_sym_table,
int count_hashmask,
struct counter **count_hash) {
// Set global populations of species back to zero, since they will get set to
// the proper values when we insert the molecules into the world
for (int n_mol_bin = 0; n_mol_bin < mol_sym_table->n_bins; n_mol_bin++) {
for (struct sym_entry *sym_ptr = mol_sym_table->entries[n_mol_bin];
sym_ptr != NULL; sym_ptr = sym_ptr->next) {
struct species *mol = (struct species *)sym_ptr->value;
mol->population = 0;
}
}
// Set counts on/in regions back to zero for the same reasons listed above.
for (int i = 0; i <= count_hashmask; i++) {
if (count_hash[i] != NULL) {
struct counter *c;
for (c = count_hash[i]; c != NULL; c = c->next) {
if ((c->counter_type & MOL_COUNTER) != 0) {
c->data.move.n_enclosed = 0;
c->data.move.n_at = 0;
}
}
}
}
return 0;
}
/***************************************************************************
check_count_validity:
Check if all the regions that we are counting in/on are
valid/defined/existent or invalid/undefined/non-existent. This is necessary
since objects can appear or disappear with dynamic geometries.
In: output_request_head:
regions_to_ignore:
new_region_names:
meshes_to_ignore:
new_mesh_names:
Out: If a count type needs changed, it is done by reset_count_type.
***************************************************************************/
void check_count_validity(struct output_request *output_request_head,
struct string_buffer *regions_to_ignore,
struct string_buffer *new_region_names,
struct string_buffer *meshes_to_ignore,
struct string_buffer *new_mesh_names) {
for (struct output_request *request = output_request_head;
request != NULL; request = request->next) {
if (request->count_location != NULL) {
if (request->count_location->sym_type != REG) {
mcell_internal_error(
"Non-region location symbol (type=%d) in count request.",
request->count_location->sym_type);
}
const char *reg_name = request->count_location->name;
// Counting in/on an object
if (is_reverse_abbrev(",ALL", reg_name)) {
struct region *reg_of_count = (
struct region *)request->count_location->value;
const char *obj_name = reg_of_count->parent->sym->name;
reset_count_type(
obj_name,
request,
meshes_to_ignore,
new_mesh_names);
}
// Counting in/on a region
else {
reset_count_type(
reg_name,
request,
regions_to_ignore,
new_region_names);
}
}
}
}
/***************************************************************************
reset_count_type:
We may need to either change the count type from valid->invalid or
invalid->valid. For example, if we were counting all the molecules in an
object that disappeared, we would need to change the type from COUNT_INT to
UNSET.
In: name: the name of the mesh/region
request: information about count statement we want to reset
names_to_ignore: a string buffer of meshes/regions to ignore
new_names: a string buffer of meshes/regions that were just added
Out: none
***************************************************************************/
void reset_count_type(const char *name,
struct output_request *request,
struct string_buffer *names_to_ignore,
struct string_buffer *new_names) {
int num_ignore = names_to_ignore->n_strings;
int num_add = new_names->n_strings;
struct output_buffer *buffer = request->requester->column->buffer;
struct output_block *block = request->requester->column->set->block;
int buf_index = block->buf_index;
int buffersize = block->buffersize;
int trig_bufsize = block->trig_bufsize;
// Reset count type that were potentially unset. This should be more
// efficient.
if (is_string_present_in_string_array(
name, new_names->strings, num_add)) {
// XXX: We can't assume that a count which was originally unset should
// now be an int.
if (buffer[0].data_type == COUNT_UNSET) {
for (int idx = buf_index; idx < buffersize; idx++) {
buffer[idx].data_type = COUNT_INT;
}
}
else if (buffer[0].data_type == COUNT_TRIG_STRUCT) {
for (int idx = buf_index; idx < trig_bufsize; idx++) {
buffer[idx].data_type = COUNT_TRIG_STRUCT;
}
}
else if (buffer[0].data_type == COUNT_INT) {
for (int idx = buf_index; idx < buffersize; idx++) {
buffer[idx].data_type = COUNT_INT;
}
}
else if (buffer[0].data_type == COUNT_DBL) {
for (int idx = buf_index; idx < buffersize; idx++) {
buffer[idx].data_type = COUNT_DBL;
}
}
}
// Unset count types for meshes that were removed.
else if (is_string_present_in_string_array(
name, names_to_ignore->strings, num_ignore)) {
if (buffer[0].data_type == COUNT_TRIG_STRUCT) {
for (int idx = buf_index; idx < trig_bufsize; idx++) {
buffer[idx].val.tval->name = NULL;
}
}
else {
for (int idx = buf_index; idx < buffersize; idx++) {
buffer[idx].data_type = COUNT_UNSET;
}
}
}
}
/***************************************************************************
init_species_mesh_transp:
In: state: MCell state
Out: Zero on success. Create a data structure so we can quickly check if a
molecule species can move in or out of any given surface region
***************************************************************************/
int init_species_mesh_transp(struct volume *state) {
struct pointer_hash *species_mesh_transp;
if ((species_mesh_transp = CHECKED_MALLOC_STRUCT(
struct pointer_hash, "pointer_hash")) == NULL) {
mcell_internal_error("Out of memory while creating molecule-object "
"transparency pointer hash");
}
if (pointer_hash_init(species_mesh_transp, state->n_species)) {
mcell_error(
"Failed to initialize data structure for molecule-object transparency.");
}
// Initialize pointer hash with species names as keys and values are a linked
// list of pointers of mesh_transparency. The mesh_transparency struct
// contains the mesh name and whether the species can go in_to_out and/or
// out_to_in. These are initially set to 0 (not transparent), and can be set
// to 1 (transparent) in find_vm_obj_region_transp.
state->species_mesh_transp = species_mesh_transp;
for (int i = 0; i < state->n_species; i++) {
struct species *spec = state->species_list[i];
const char *species_name = spec->sym->name;
if (spec->flags & IS_SURFACE)
continue;
if (strcmp(species_name, "ALL_MOLECULES") == 0)
continue;
else if (strcmp(species_name, "ALL_VOLUME_MOLECULES") == 0)
continue;
else if (strcmp(species_name, "ALL_SURFACE_MOLECULES") == 0)
continue;
unsigned int keyhash = (unsigned int)(intptr_t)(species_name);
void *key = (void *)(species_name);
struct mesh_transparency *mesh_transp_head = NULL;
struct mesh_transparency *mesh_transp_tail = NULL;
int sm_flag = 0;
if (spec->flags & ON_GRID) {
sm_flag = 1;
}
find_all_obj_region_transp(state->root_instance, &mesh_transp_head,
&mesh_transp_tail, species_name, sm_flag);
if (pointer_hash_add(
state->species_mesh_transp, key, keyhash, (void *)mesh_transp_head)) {
mcell_allocfailed("Failed to store species-mesh transparency in"
" pointer_hash table.");
}
}
return 0;
}
/***************************************************************************
find_sm_region_transp:
In: obj_ptr: the mesh object
mesh_transp_head: Head of the mesh transparency list
mesh_transp_tail: Tail of the mesh transparency list
species_name: the species/molecule name
Out: Zero on success. Create a data structure so we can quickly check if a
surface molecule species can move in or out of any given surface region
***************************************************************************/
int find_sm_region_transp(struct geom_object *obj_ptr,
struct mesh_transparency **mesh_transp_head,
struct mesh_transparency **mesh_transp_tail,
const char *species_name) {
// Check every region on the object
for (struct region_list *reg_list_ptr = obj_ptr->regions;
reg_list_ptr != NULL;
reg_list_ptr = reg_list_ptr->next) {
struct region *reg_ptr = reg_list_ptr->reg;
if (reg_ptr->surf_class != NULL) {
// Unlike volume molecules, we need to create a mesh transparency entry
// for every region instead of every object.
struct mesh_transparency *mesh_transp;
mesh_transp = CHECKED_MALLOC_STRUCT(
struct mesh_transparency, "object transparency");
mesh_transp->next = NULL;
mesh_transp->name = reg_ptr->sym->name;
// Ignore this until I merge in Markus' experimental changes
mesh_transp->in_to_out = 0;
mesh_transp->out_to_in = 0;
// Default state for surface molecules is transparent, so we just
// need to check reflective and absorptive regions
mesh_transp->transp_top_front = 1;
mesh_transp->transp_top_back = 1;
if (*mesh_transp_tail == NULL) {
*mesh_transp_head = mesh_transp;
*mesh_transp_tail = mesh_transp;
(*mesh_transp_head)->next = NULL;
(*mesh_transp_tail)->next = NULL;
}
else {
(*mesh_transp_tail)->next = mesh_transp;
*mesh_transp_tail = mesh_transp;
}
// Check if species_name is in the absorptive list for this region
check_surf_class_properties(
species_name, mesh_transp, reg_ptr->surf_class->absorb_mols);
// Check if species_name is in the relective list for this region
check_surf_class_properties(
species_name, mesh_transp, reg_ptr->surf_class->refl_mols);
}
}
return 0;
}
/***************************************************************************
check_surf_class_properties:
In: species_name: the name of the molecule/species that we are checking
mesh_transp: contains info about whether the species is transparent to
the regions on this mesh
surf_class_props: absorptive/reflective surface class properties
Out: None. Check if species_name is in the absorptive/reflective list for
a given region
***************************************************************************/
void check_surf_class_properties(
const char *species_name,
struct mesh_transparency *mesh_transp,
struct name_orient *surf_class_props) {
struct name_orient *no;
for (no = surf_class_props; no != NULL; no = no->next) {
if (strcmp(no->name, species_name) == 0) {
// Absorptive/Reflective to top front molecules
if (no->orient == 1) {
mesh_transp->transp_top_front = 0;
break;
}
// Absorptive/Reflective to top back molecules
else if (no->orient == -1) {
mesh_transp->transp_top_back = 0;
break;
}
// Absorptive/Reflective from top front or top back (e.g. ABSORPTIVE = A;)
else if (no->orient == 0) {
mesh_transp->transp_top_front = 0;
mesh_transp->transp_top_back = 0;
break;
}
}
}
}
/***************************************************************************
find_vm_obj_region_transp:
In: obj_ptr: The object we are currently checking for transparency
mesh_transp_head: Head of the mesh transparency list
mesh_transp_tail: Tail of the mesh transparency list
species_name: The name of the molecule/species we are checking
Out: Zero on success. Check every region on obj_ptr to see if any of them are
transparent to the volume molecules with species_name.
***************************************************************************/
int find_vm_obj_region_transp(struct geom_object *obj_ptr,
struct mesh_transparency **mesh_transp_head,
struct mesh_transparency **mesh_transp_tail,
const char *species_name) {
struct mesh_transparency *mesh_transp;
mesh_transp =
CHECKED_MALLOC_STRUCT(struct mesh_transparency, "object transparency");
mesh_transp->next = NULL;
mesh_transp->name = obj_ptr->sym->name;
mesh_transp->in_to_out = 0;
mesh_transp->out_to_in = 0;
if (*mesh_transp_tail == NULL) {
*mesh_transp_head = mesh_transp;
*mesh_transp_tail = mesh_transp;
(*mesh_transp_head)->next = NULL;
(*mesh_transp_tail)->next = NULL;
}
else {
(*mesh_transp_tail)->next = mesh_transp;
*mesh_transp_tail = mesh_transp;
}
// Assuming the first region in the region list will always be ALL.
// Could be unsafe.
double volume = obj_ptr->regions->reg->volume;
// Set volume for the ALL reg if it hasn't been done already. Bit clunky...
if (!distinguishable(volume, 0.0, EPS_C)) {
int count_regions_flag = 0;
is_manifold(obj_ptr->regions->reg, count_regions_flag);
volume = obj_ptr->regions->reg->volume;
}
// Check every region on the object
for (struct region_list *reg_list_ptr = obj_ptr->regions;
reg_list_ptr != NULL;
reg_list_ptr = reg_list_ptr->next) {
struct region *reg_ptr = reg_list_ptr->reg;
if (reg_ptr->surf_class != NULL) {
struct name_orient *no;
// Check if species_name is in the transparency list for this region
for (no = reg_ptr->surf_class->transp_mols; no != NULL; no = no->next) {
if (strcmp(no->name, species_name) == 0) {
// Side note about reg_ptr->volume stuff below: if volume is
// positive, then we have outward facing normals. this is the typical
// case. if volume is negative, then you have inward facing normals.
// Transparent from outside to inside
if ((no->orient == 1 && volume > 0) ||
(no->orient == -1 && volume < 0)) {
mesh_transp->out_to_in = 1;
break;
}
// Transparent from inside to outside
else if ((no->orient == -1 && volume > 0) ||
(no->orient == 1 && volume < 0)) {
mesh_transp->in_to_out = 1;
break;
}
// Transparent from either direction (e.g. TRANSPARENT = A;)
else if (no->orient == 0) {
mesh_transp->in_to_out = 1;
mesh_transp->out_to_in = 1;
break;
}
}
}
}
}
return 0;
}
/***************************************************************************
find_all_obj_region_transp:
In: obj_ptr: The mesh object
mesh_transp_head: Head of the object transparency list
mesh_transp_tail: Tail of the object transparency list
species_name: The name of the molecule/species we are checking
sm_flag: surface molecule flag
Out: Zero on success. Check every polygon object to see if it is transparent
to species_name.
***************************************************************************/
int find_all_obj_region_transp(struct geom_object *obj_ptr,
struct mesh_transparency **mesh_transp_head,
struct mesh_transparency **mesh_transp_tail,
const char *species_name,
int sm_flag) {
switch (obj_ptr->object_type) {
case META_OBJ:
for (struct geom_object *child_obj_ptr = obj_ptr->first_child;
child_obj_ptr != NULL; child_obj_ptr = child_obj_ptr->next) {
if (find_all_obj_region_transp(
child_obj_ptr, mesh_transp_head, mesh_transp_tail, species_name,
sm_flag))
return 1;
}
break;
case BOX_OBJ:
case POLY_OBJ:
if (sm_flag) {
if (find_sm_region_transp(
obj_ptr, mesh_transp_head, mesh_transp_tail, species_name)) {
return 1;
}
}
else {
if (find_vm_obj_region_transp(
obj_ptr, mesh_transp_head, mesh_transp_tail, species_name)) {
return 1;
}
}
break;
case VOXEL_OBJ:
case REL_SITE_OBJ:
break;
}
return 0;
}
/************************************************************************
add_dynamic_geometry_events:
In: dynamic_geometry_filename: filename and path for dyngeom file
dynamic_geometry_filepath: XXX: identical to above? remove?
timestep: global timestep in seconds
dynamic_geometry_events_mem: memory to store time and MDL names for
dynamic geometry
dg_time_fname_head: the head of the dynamic geometry event list
Out: 0 on success, 1 on failure. dynamic geometry events are added to
dg_time_fname_head from which they will eventually be added to a
scheduler.
***********************************************************************/
int add_dynamic_geometry_events(
struct mdlparse_vars *parse_state,
const char *dynamic_geometry_filepath,
double timestep,
struct mem_helper *dynamic_geometry_events_mem,
struct dg_time_filename **dg_time_fname_head) {
struct volume *state = parse_state->vol;
struct dyngeom_parse_vars *dg_parse = create_dg_parse(state);
state->dg_parse = dg_parse;
FILE *f = fopen(dynamic_geometry_filepath, "r");
if (!f) {
return 1;
} else {
const char *SEPARATORS = "\f\n\r\t\v ,;";
const char *FIRST_DIGIT = "+-0123456789";
struct dg_time_filename *dg_time_fname_tail = NULL;
char buf[2048];
char *char_ptr;
char *zero_file_name = NULL;
int linecount = 0;
int i;
while (fgets(buf, 2048, f)) {
linecount++;
// Ignore leading whitespace
for (i = 0; i < 2048; i++) {
if (!strchr(SEPARATORS, buf[i]))
break;
}
if (i < 2048 && strchr(FIRST_DIGIT, buf[i])) {
// Grab time
double time = strtod((buf + i), &char_ptr);
if (char_ptr == (buf + i))
continue; /* Conversion error. */
// Skip over whitespace between time and filename
for (i = char_ptr - buf; i < 2048; i++) {
if (!strchr(SEPARATORS, buf[i]))
break;
}
if (i == 2048) {
mcell_error(
"an entry in the dynamic geometry file consists of too many "
"characters (it uses 2048 or more characters).");
return(1);
}
// Grab mdl filename. This could probably be cleaned up
char *line_ending = strchr(buf + i, '\n');
int line_ending_idx = line_ending - buf;
int file_name_length = line_ending_idx - i + 1;
char* file_name = new char[file_name_length];
strncpy(file_name, buf + i, file_name_length);
file_name[file_name_length - 1] = '\0';
// Expand path name if needed
char *full_file_name = mcell_find_include_file(
file_name, dynamic_geometry_filepath);
delete file_name;
// Treat time 0 as if it were an include file.
if (!distinguishable(time, 0, EPS_C)) {
if (zero_file_name) {
free(zero_file_name);
}
zero_file_name = full_file_name;
continue;
}
// Do the normal DG parsing on every other time
else {
parse_dg_init(dg_parse, full_file_name, state);
destroy_objects(state->root_instance, 0);
destroy_objects(state->root_object, 0);
struct dg_time_filename *dyn_geom;
dyn_geom = (struct dg_time_filename *)CHECKED_MEM_GET(dynamic_geometry_events_mem,
"time-varying dynamic geometry");
if (dyn_geom == NULL) {
free(zero_file_name);
fclose(f);
return 1;
}
dyn_geom->event_time = round(time / timestep);
dyn_geom->mdl_file_path = full_file_name;
dyn_geom->next = NULL;
// Append each entry to end of dg_time_fname_head list
if (*dg_time_fname_head == NULL) {
*dg_time_fname_head = dyn_geom;
dg_time_fname_tail = dyn_geom;
} else {
dg_time_fname_tail->next = dyn_geom;
dg_time_fname_tail = dyn_geom;
}
}
}
}
fclose(f);
parse_state->current_object = parse_state->vol->root_object;
#ifdef NOSWIG
if (zero_file_name && mdlparse_file(parse_state, zero_file_name))
{
free(zero_file_name);
return 1;
}
#endif
free(zero_file_name);
}
// this free causes double free errors
// free((char*)dynamic_geometry_filepath);
// Disable parsing of geometry for the rest of the MDL. It should only happen
// via files referenced in the DG file.
state->disable_polygon_objects = 1;
return 0;
}
/************************************************************************
get_mesh_instantiation_names:
In: obj_ptr: the root instance meta object
mesh_names: an initialized but empty string buffer
Out: mesh_names is updated so that it contains a list of all the mesh objects
with their fully qualified names.
***********************************************************************/
const char *get_mesh_instantiation_names(struct geom_object *obj_ptr,
struct string_buffer *mesh_names) {
switch (obj_ptr->object_type) {
case META_OBJ:
for (struct geom_object *child_obj_ptr = obj_ptr->first_child;
child_obj_ptr != NULL; child_obj_ptr = child_obj_ptr->next) {
char *mesh_name = (char *)get_mesh_instantiation_names(
child_obj_ptr, mesh_names);
if ((mesh_name != NULL) &&
(add_string_to_buffer(mesh_names, mesh_name))) {
free(mesh_name);
destroy_string_buffer(mesh_names);
return NULL;
}
}
break;
case BOX_OBJ:
case POLY_OBJ:
return CHECKED_STRDUP(obj_ptr->sym->name, "mesh name");
// do nothing
case REL_SITE_OBJ:
case VOXEL_OBJ:
break;
}
return NULL;
}
/************************************************************************
diff_string_buffers:
In: diff_names: The new names are stored here
names_a: One set of names
names_b: Another set of names
Out: Assign difference of names_a and names_b to diff_names.
Example: {A,B,C} - {B,C,D} = {A}. There might not be any if the the old
and new list are identical. I'm sure this could be much more efficient,
but it is sufficient for now. Note: This is very similar to
sym_diff_string_buffers. Consolidate these.
***********************************************************************/
void diff_string_buffers(
struct string_buffer *diff_names,
struct string_buffer *names_a,
struct string_buffer *names_b) {
int n_strings_old = names_a->n_strings;
int n_strings_new = names_b->n_strings;
for (int i = 0; i < n_strings_old; i++) {
if (!(is_string_present_in_string_array(
names_a->strings[i], names_b->strings, n_strings_new))) {
char *diff_name = CHECKED_STRDUP(names_a->strings[i], "name");
if (add_string_to_buffer(diff_names, diff_name)) {
destroy_string_buffer(diff_names);
}
}
}
}
/************************************************************************
sym_diff_string_buffers:
In: diff_names: The new names are stored here
names_a: One set of names
names_b: Another set of names
Out: Assign symmetric difference of names_a and names_b to diff_names.
Example: {A,B,C} + {B,C,D} = {A,D}. There might not be any if the the old
and new list are identical. I'm sure this could be much more efficient,
but it is sufficient for now.
***********************************************************************/
void sym_diff_string_buffers(
struct string_buffer *diff_names,
struct string_buffer *names_a,
struct string_buffer *names_b,
enum warn_level_t add_remove_mesh_warning) {
int n_strings_old = names_a->n_strings;
int n_strings_new = names_b->n_strings;
// Track objects which have been removed
for (int i = 0; i < n_strings_old; i++) {
if (!(is_string_present_in_string_array(
names_a->strings[i], names_b->strings, n_strings_new))) {
char *diff_name = CHECKED_STRDUP(names_a->strings[i], "name");
switch (add_remove_mesh_warning) {
case WARN_COPE:
break;
case WARN_WARN:
mcell_warn("\"%s\" removed.", diff_name);
break;
case WARN_ERROR:
mcell_error("\"%s\" removed.", diff_name);
}
if (add_string_to_buffer(diff_names, diff_name)) {
destroy_string_buffer(diff_names);
}
}
}
// Track objects which have been added
for (int i = 0; i < n_strings_new; i++) {
if (!(is_string_present_in_string_array(
names_b->strings[i], names_a->strings, n_strings_old))) {
char *diff_name = CHECKED_STRDUP(names_b->strings[i], "name");
switch (add_remove_mesh_warning) {
case WARN_COPE:
break;
case WARN_WARN:
mcell_warn("\"%s\" added.", diff_name);
break;
case WARN_ERROR:
mcell_error("\"%s\" added.", diff_name);
}
if (add_string_to_buffer(diff_names, diff_name)) {
destroy_string_buffer(diff_names);
}
}
}
}
/***************************************************************************
get_reg_names_all_objects:
In: obj_ptr: grab the region names of this object (if it's a poly object) or
its children (if it's a meta object)
region_names: we will store all of the region names in this
Out: 0 on success, 1 on failure.
***************************************************************************/
int get_reg_names_all_objects(
struct geom_object *obj_ptr,
struct string_buffer *region_names) {
switch (obj_ptr->object_type) {
case META_OBJ:
for (struct geom_object *child_obj_ptr = obj_ptr->first_child;
child_obj_ptr != NULL; child_obj_ptr = child_obj_ptr->next) {
if (get_reg_names_all_objects(child_obj_ptr, region_names))
return 1;
}
break;
case BOX_OBJ:
case POLY_OBJ:
if (get_reg_names_this_object(obj_ptr, region_names))
return 1;
break;
case VOXEL_OBJ:
case REL_SITE_OBJ:
break;
}
return 0;
}
/***************************************************************************
get_reg_names_this_object:
In: obj_ptr: we will get region names from this object
region_names: we will store all of the region names in this
Out: 0 on success, 1 on failure.
***************************************************************************/
int get_reg_names_this_object(
struct geom_object *obj_ptr,
struct string_buffer *region_names) {
for (struct region_list *reg_list_ptr = obj_ptr->regions;
reg_list_ptr != NULL;
reg_list_ptr = reg_list_ptr->next) {
struct region *reg_ptr = reg_list_ptr->reg;
// We only care about regions with boundaries so ignore these
if ((strcmp(reg_ptr->region_last_name, "ALL") == 0) ||
(reg_ptr->region_has_all_elements))
continue;
char *region_name = CHECKED_STRDUP(reg_ptr->sym->name, "region name");
if ((region_name != NULL) &&
(add_string_to_buffer(region_names, region_name))) {
free(region_name);
destroy_string_buffer(region_names);
return 1;
}
}
return 0;
}
/***************************************************************************
update_geometry:
In: state: MCell state
dyn_geom: info about next dyngeom event (time and geom filename)
Out: None. Molecule positions are saved. Old geometry is trashed. New
geometry is created. Molecules are placed (and moved if necessary).
***************************************************************************/
void update_geometry(struct volume *state,
struct dg_time_filename *dyn_geom) {
state->all_molecules = save_all_molecules(state, state->storage_head);
// Turn off progress reports to avoid spamming mostly useless info to stdout
state->notify->progress_report = NOTIFY_NONE;
if (state->dynamic_geometry_flag != 1) {
free(state->mdl_infile_name);
}
// Make list of already existing regions with fully qualified names.
struct string_buffer *old_region_names =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(old_region_names, MAX_NUM_OBJECTS);
get_reg_names_all_objects(state->root_instance, old_region_names);
// Make list of already existing meshes with fully qualified names.
struct string_buffer *old_inst_mesh_names =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(old_inst_mesh_names, MAX_NUM_OBJECTS);
get_mesh_instantiation_names(state->root_instance, old_inst_mesh_names);
state->mdl_infile_name = dyn_geom->mdl_file_path;
if (mcell_redo_geom(state)) {
mcell_error("An error occurred while processing geometry changes.");
}
// Make NEW list of fully qualified region names.
struct string_buffer *new_region_names =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(new_region_names, MAX_NUM_OBJECTS);
get_reg_names_all_objects(state->root_instance, new_region_names);
// Make NEW list of instantiated, fully qualified mesh names.
struct string_buffer *new_inst_mesh_names =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(new_inst_mesh_names, MAX_NUM_OBJECTS);
get_mesh_instantiation_names(state->root_instance, new_inst_mesh_names);
struct string_buffer *meshes_to_ignore =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(meshes_to_ignore, MAX_NUM_OBJECTS);
// Compare old list of mesh names with new list.
sym_diff_string_buffers(
meshes_to_ignore, old_inst_mesh_names, new_inst_mesh_names,
state->notify->add_remove_mesh_warning);
struct string_buffer *regions_to_ignore =
CHECKED_MALLOC_STRUCT(struct string_buffer, "string buffer");
initialize_string_buffer(regions_to_ignore, MAX_NUM_OBJECTS);
// Compare old list of region names with new list.
sym_diff_string_buffers(
regions_to_ignore, old_region_names, new_region_names,
state->notify->add_remove_mesh_warning);
check_count_validity(
state->output_request_head,
regions_to_ignore,
new_region_names,
meshes_to_ignore,
new_inst_mesh_names);
place_all_molecules(state, meshes_to_ignore, regions_to_ignore);
destroy_string_buffer(old_region_names);
destroy_string_buffer(new_region_names);
destroy_string_buffer(old_inst_mesh_names);
destroy_string_buffer(new_inst_mesh_names);
destroy_string_buffer(meshes_to_ignore);
destroy_string_buffer(regions_to_ignore);
free(old_region_names);
free(new_region_names);
free(old_inst_mesh_names);
free(new_inst_mesh_names);
free(meshes_to_ignore);
free(regions_to_ignore);
}
| C |
3D | mcellteam/mcell | src/mcell_reactions.h | .h | 5,696 | 159 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_species.h"
#define REGULAR_ARROW 0x00
#define ARROW_BIDIRECTIONAL 0x01
#define ARROW_CATALYTIC 0x02
// typedef struct sym_entry mcell_symbol;
enum {
RATE_UNSET = -1,
RATE_CONSTANT = 0,
RATE_FILE = 1,
};
/* Special pathway types. */
enum special_pathway_t {
RFLCT, /* Special pathway: reflective surface */
TRANSP, /* Special pathway: transparent surface */
SINK /* Special pathway: absorptive surface */
};
struct reaction_def {
struct sym_entry *sym;
};
struct release_single_molecule_list {
struct release_single_molecule *rsm_head;
struct release_single_molecule *rsm_tail;
int rsm_count;
};
struct reaction_arrow {
int flags;
struct mcell_species catalyst;
};
struct reaction_rate {
int rate_type;
union {
double rate_constant;
char *rate_file;
} v;
};
struct reaction_rates {
struct reaction_rate forward_rate;
struct reaction_rate backward_rate;
};
MCELL_STATUS
mcell_modify_multiple_rate_constants(struct volume *world, char **names, double *rate_constants, int n_rxns);
MCELL_STATUS
mcell_modify_rate_constant(struct volume *world, char *name, double rate);
MCELL_STATUS
mcell_add_reaction_simplified(
struct volume *state,
struct mcell_species *reactants,
struct reaction_arrow *arrow,
struct mcell_species *surfs,
struct mcell_species *products,
struct reaction_rates *rates,
struct sym_entry *pathname);
MCELL_STATUS
mcell_add_reaction(struct notifications *notify,
double **r_step_release,
struct sym_table_head *rxn_sym_table,
u_int radial_subdivisions,
double vacancy_search_dist2,
struct mcell_species *reactants,
struct reaction_arrow *react_arrow,
struct mcell_species *surf_class,
struct mcell_species *products, struct sym_entry *pathname,
struct reaction_rates *rates,
const char *forward_rate_filename,
const char *backward_rate_filename);
MCELL_STATUS mcell_add_surface_reaction(struct sym_table_head *rxn_sym_table,
int reaction_type,
struct species *surface_class,
struct sym_entry *reactant_sym,
short orient);
MCELL_STATUS
mcell_add_clamp(struct sym_table_head *rxn_sym_table,
struct species *surface_class,
struct sym_entry *mol_sym, short orient,
int clamp_type,
double clamp_value);
MCELL_STATUS init_reactions(MCELL_STATE *state);
MCELL_STATUS mcell_change_reaction_rate(MCELL_STATE *state,
const char *reaction_name,
double new_rate);
struct reaction_rates mcell_create_reaction_rates(int forwardRateType,
double forwardRateConstant,
int backwardRateType,
double backwardRateConstant);
//helper functions for initializing a reaction structure
MCELL_STATUS extract_reactants(struct pathway *path,
struct mcell_species *reactants,
int *num_reactants, int *num_vol_mols,
int *num_surface_mols,
int *all_3d,
int *oriented_count);
MCELL_STATUS extract_products(struct notifications *notify,
struct pathway *path,
struct mcell_species *products,
int *num_surf_products,
int bidirectional,
int all_3d);
int set_product_geometries(struct pathway *path, struct rxn *rx,
struct product *prod);
//initializes the rxn->info field with null values
int init_reaction_info(struct rxn* rx);
char *create_rx_name(struct pathway *p);
//JJT:stuff I exposed from mcell_reactions.c so that nfsim-related functions can use them
int scale_rxn_probabilities(unsigned char *reaction_prob_limit_flag,
struct notifications *notify,
struct pathway *path, struct rxn *rx,
double pb_factor);
//nfsim stuff
//initialize reaction objects given a set of reactants
//int outcome_unimolecular_nfsim(struct volume *world, struct rxn *rx, int path,
// struct abstract_molecule *reac, double t);
int outcome_nfsim(struct volume *world, struct rxn *rx, int path,
struct abstract_molecule *reac, struct abstract_molecule *reac2, double t);
//get the graph properties for a given graph object
void properties_nfsim(struct volume*, struct abstract_molecule *reac);
struct sym_entry *mcell_new_rxn_pathname(struct volume *state, char *name);
| Unknown |
3D | mcellteam/mcell | src/sym_table.h | .h | 1,197 | 33 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
struct species *new_species(void);
struct geom_object *new_object(void);
struct release_pattern *new_release_pattern(void);
struct rxn *new_reaction(void);
struct rxn_pathname *new_reaction_pathname(void);
struct region *new_region(void);
struct file_stream *new_filestream(void);
int dump_symtab(struct sym_table_head *hashtab);
unsigned long hash(char const *sym);
struct sym_entry *retrieve_sym(char const *sym, struct sym_table_head *hashtab);
struct sym_entry *store_sym(char const *sym, enum symbol_type_t sym_type,
struct sym_table_head *hashtab, void *data);
struct sym_table_head *init_symtab(int size);
void destroy_symtab(struct sym_table_head *tab);
| Unknown |
3D | mcellteam/mcell | src/count_util.c | .c | 76,361 | 2,063 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/**************************************************************************\
** File: count_util.c **
** **
** Purpose: Handles counting of interesting events **
** **
** Testing status: untested. **
\**************************************************************************/
#include "config.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rng.h"
#include "logging.h"
#include "grid_util.h"
#include "wall_util.h"
#include "vol_util.h"
#include "count_util.h"
#include "react_output.h"
//#include "util.h"
#include "sym_table.h"
#include "dyngeom_parse_extras.h"
/* Instantiate a request to track a particular quantity */
static int instantiate_count_request(
int dyn_geom_flag, struct output_request *request, int count_hashmask,
struct counter **count_hash, struct mem_helper *trig_request_mem,
double *elapsed_time, struct mem_helper *counter_mem);
/* Create a new counter data structure */
static struct counter *create_new_counter(struct region *where, void *who,
byte what, struct periodic_image *img, struct mem_helper *counter_mem);
/* Pare down the region lists, annihilating any regions which appear in both
* lists. */
static void clean_region_lists(struct subvolume *my_sv,
struct region_list **p_all_regs,
struct region_list **p_all_antiregs);
/* Check if the object corresponding to a particular symbol has been referenced
* directly or indirectly from one of the INSTANTIATE blocks in the model.
*/
/*static int is_object_instantiated(struct sym_entry *entry,*/
/* struct object *root_instance);*/
/* Find the list of regions enclosing a particular point. given a particular
* starting point and starting region list. */
static int find_enclosing_regions(struct volume *world, struct vector3 *loc,
struct vector3 *start,
struct region_list **rlp,
struct region_list **arlp,
struct mem_helper *rmem);
void count_region_list(
struct volume *world,
struct region_list *regions,
struct surface_molecule *sm,
struct vector3 *where,
int count_hashmask,
int inc,
struct periodic_image *previous_box);
/*************************************************************************
eps_equals:
In: two doubles
Out: 1 if they are equal to within some small tolerance, 0 otherwise
*************************************************************************/
static int eps_equals(double x, double y) {
double mag = fabs(x);
if (mag < fabs(y))
mag = fabs(y);
double diff = fabs(x - y);
return diff < EPS_C * (mag + 1.0);
}
/*************************************************************************
dup_region_list:
In: a list of regions
memory handler to use for duplicated regions
Out: The duplicated list of regions, or NULL on a memory allocation
error.
*************************************************************************/
static struct region_list *dup_region_list(struct region_list *r,
struct mem_helper *mh) {
struct region_list *nr, *rp, *r0;
if (r == NULL)
return NULL;
r0 = rp = NULL;
while (r != NULL) {
nr = (struct region_list *)CHECKED_MEM_GET(mh, "region list entry");
nr->next = NULL;
nr->reg = r->reg;
if (rp == NULL)
r0 = rp = nr;
else {
rp->next = nr;
rp = nr;
}
r = r->next;
}
return r0;
}
/*************************************************************************
region_listed:
In: list of regions
one specific region we're interested in
Out: 1 if the region is in the list. 0 if not.
*************************************************************************/
int region_listed(struct region_list *rl, struct region *r) {
while (rl != NULL) {
if (rl->reg == r)
return 1;
rl = rl->next;
}
return 0;
}
/*************************************************************************
count_region_update:
In: world: simulation state
sp: species of thing that hit
periodic_box: periodic box of molecule being counted
rl: region list for the wall we hit
dir: direction of impact relative to surface normal for volume molecule,
or relative to the region border for surface molecule (inside out = 1,
ouside in = 0)
crossed: whether we crossed or not
loc: location of the hit (for triggers)
t: time of the hit (for triggers)
Out: Returns none.
Appropriate counters are updated, that is, hit counters are updated
according to which side was hit, and crossings counters and counts
within enclosed regions are updated if the surface was crossed.
*************************************************************************/
void count_region_update(
struct volume *world,
struct volume_molecule *vm,
struct species *sp,
u_long id,
struct periodic_image *periodic_box,
struct region_list *rl,
int direction,
int crossed,
struct vector3 *loc,
double t) {
int count_hits = 0;
double hits_to_ccn = 0;
if ((sp->flags & COUNT_HITS) && ((sp->flags & NOT_FREE) == 0)) {
count_hits = 1;
/*hits_to_ccn = vm->get_time_step(vm) **/
hits_to_ccn = sp->time_step *
2.9432976599069717358e-3 / /* 1e6*sqrt(MY_PI)/(1e-15*N_AV) */
/*(vm->get_space_step(vm) * world->length_unit * world->length_unit **/
(sp->space_step * world->length_unit * world->length_unit *
world->length_unit);
}
struct counter *hit_count = NULL;
for (; rl != NULL; rl = rl->next) {
if (!(rl->reg->flags & COUNT_SOME_MASK)) {
continue;
}
if (!(rl->reg->flags & sp->flags & (COUNT_HITS | COUNT_CONTENTS | COUNT_ENCLOSED))) {
continue;
}
int hash_bin = (rl->reg->hashval + sp->hashval) & world->count_hashmask;
for (hit_count = world->count_hash[hash_bin]; hit_count != NULL;
hit_count = hit_count->next) {
if (!(hit_count->reg_type == rl->reg && hit_count->target == sp)) {
continue;
}
// count only in the relevant periodic box
if (world->periodic_box_obj && !world->periodic_traditional) {
if (!periodic_boxes_are_identical(periodic_box, hit_count->periodic_box)) {
continue;
}
else {
struct vector3 pos_output = {0.0, 0.0, 0.0};
convert_relative_to_abs_PBC_coords(
world->periodic_box_obj,
periodic_box,
world->periodic_traditional,
loc,
&pos_output);
loc->x = pos_output.x;
loc->y = pos_output.y;
loc->z = pos_output.z;
}
}
if (crossed) {
if (direction == 1) {
if (hit_count->counter_type & TRIG_COUNTER) {
hit_count->data.trig.t_event = (double)world->current_iterations + t;
hit_count->data.trig.orient = 0;
if (rl->reg->flags & sp->flags & COUNT_HITS) {
fire_count_event(world, hit_count, 1, loc,
REPORT_FRONT_HITS | REPORT_TRIGGER, id);
fire_count_event(world, hit_count, 1, loc,
REPORT_FRONT_CROSSINGS | REPORT_TRIGGER, id);
}
if (rl->reg->flags & sp->flags & COUNT_CONTENTS) {
fire_count_event(world, hit_count, 1, loc,
REPORT_ENCLOSED | REPORT_CONTENTS |
REPORT_TRIGGER, id);
}
} else {
if (rl->reg->flags & sp->flags & COUNT_HITS) {
hit_count->data.move.front_hits++;
hit_count->data.move.front_to_back++;
}
if (rl->reg->flags & sp->flags & COUNT_CONTENTS) {
hit_count->data.move.n_enclosed++;
}
}
} else {
if (hit_count->counter_type & TRIG_COUNTER) {
hit_count->data.trig.t_event = (double)world->current_iterations + t;
hit_count->data.trig.orient = 0;
if (rl->reg->flags & sp->flags & COUNT_HITS) {
fire_count_event(world, hit_count, 1, loc,
REPORT_BACK_HITS | REPORT_TRIGGER, id);
fire_count_event(world, hit_count, 1, loc,
REPORT_BACK_CROSSINGS | REPORT_TRIGGER, id);
}
if (rl->reg->flags & sp->flags & COUNT_CONTENTS) {
fire_count_event(
world, hit_count, -1, loc,
REPORT_ENCLOSED | REPORT_CONTENTS | REPORT_TRIGGER, id);
}
} else {
if (rl->reg->flags & sp->flags & COUNT_HITS) {
hit_count->data.move.back_hits++;
hit_count->data.move.back_to_front++;
}
if (rl->reg->flags & sp->flags & COUNT_CONTENTS) {
hit_count->data.move.n_enclosed--;
}
}
}
} else if (rl->reg->flags & sp->flags & COUNT_HITS) {
/* Didn't cross, only hits might update */
if (direction == 1) {
if (hit_count->counter_type & TRIG_COUNTER) {
hit_count->data.trig.t_event = (double)world->current_iterations + t;
hit_count->data.trig.orient = 0;
fire_count_event(world, hit_count, 1, loc,
REPORT_FRONT_HITS | REPORT_TRIGGER, id);
} else {
hit_count->data.move.front_hits++;
}
} else {
if (hit_count->counter_type & TRIG_COUNTER) {
hit_count->data.trig.t_event = (double)world->current_iterations + t;
hit_count->data.trig.orient = 0;
fire_count_event(world, hit_count, 1, loc,
REPORT_BACK_HITS | REPORT_TRIGGER, id);
} else
hit_count->data.move.back_hits++;
}
}
if ((count_hits && rl->reg->area != 0.0) &&
((sp->flags & NOT_FREE) == 0)) {
if ((hit_count->counter_type & TRIG_COUNTER) == 0) {
hit_count->data.move.scaled_hits += hits_to_ccn / rl->reg->area;
}
}
}
}
}
/**************************************************************************
count_region_border_update:
In: world: simulation state
sp: species of thing that hit
hd_info: information about the hit (linked list of "hit_data")
Out: Returns none.
Appropriate counters are updated, that is,
hit counters are updated according to which side was hit,
and crossings counters are updated if the region border was crossed.
We consider FRONT_HITS/FRONT_CROSSINGS when the molecule
crosses region border "inside out" and BACK_HITS/BACK_CROSSINGS
when the molecule hits region border "outside in".
**************************************************************************/
void count_region_border_update(struct volume *world, struct species *sp,
struct hit_data *hd_info, u_long id) {
assert((sp->flags & NOT_FREE) != 0);
for (struct hit_data *hd = hd_info; hd != NULL; hd = hd->next) {
for (struct region_list *rl = hd->count_regions; rl != NULL; rl = rl->next) {
if ((rl->reg->flags & COUNT_SOME_MASK) &&
(rl->reg->flags & sp->flags & COUNT_HITS)) {
int hash_bin = (rl->reg->hashval + sp->hashval) & world->count_hashmask;
for (struct counter *hit_count = world->count_hash[hash_bin];
hit_count != NULL; hit_count = hit_count->next) {
if (((hit_count->reg_type != rl->reg) || (hit_count->target != sp))) {
continue;
}
if ((hit_count->orientation != ORIENT_NOT_SET) &&
(hit_count->orientation != hd->orientation) &&
(hit_count->orientation != 0)) {
continue;
}
if (hit_count->counter_type & TRIG_COUNTER) {
hit_count->data.trig.t_event = hd->t;
hit_count->data.trig.orient = 0;
if (hd->direction == 1) {
fire_count_event(world, hit_count, 1, &(hd->loc),
REPORT_FRONT_HITS | REPORT_TRIGGER, id);
if (hd->crossed) {
fire_count_event(world, hit_count, 1, &(hd->loc),
REPORT_FRONT_CROSSINGS | REPORT_TRIGGER, id);
}
} else {
fire_count_event(world, hit_count, 1, &(hd->loc),
REPORT_BACK_HITS | REPORT_TRIGGER, id);
if (hd->crossed) {
fire_count_event(world, hit_count, 1, &(hd->loc),
REPORT_BACK_CROSSINGS | REPORT_TRIGGER, id);
}
}
} else {
if (hd->direction == 1) {
hit_count->data.move.front_hits++;
if (hd->crossed) {
hit_count->data.move.front_to_back++;
}
} else {
hit_count->data.move.back_hits++;
if (hd->crossed) {
hit_count->data.move.back_to_front++;
}
}
}
}
}
}
} /* end for (hd...) */
}
/*************************************************************************
count_region_from_scratch:
In: world: simulation state
am: molecule to count, or NULL
rxpn: reaction pathname to count, or NULL
n: number of these to count
loc: location at which to count them (may be NULL)
my_wall: wall at which this happened (may be NULL)
t: time of the hit (for triggers)
periodic_box:
Out: Returns zero on success and 1 on failure.
Appropriate counters are updated and triggers are fired.
Note: At least one of molecule or rxn pathname must be non-NULL; if other
inputs are NULL, sensible values will be guessed (which may themselves
be NULL). This routine is not super-fast for volume counts (enclosed
counts) since it has to dynamically create and test lists of enclosing
regions.
*************************************************************************/
void count_region_from_scratch(struct volume *world,
struct abstract_molecule *am,
struct rxn_pathname *rxpn,
int n,
struct vector3 *loc,
struct wall *my_wall,
double t,
struct periodic_image *periodic_box) {
struct region_list *rl, *arl, *nrl, *narl; /*a=anti n=new*/
struct counter *c;
void *target; /* what we're counting: am->properties or rxpn */
int hashval; /* Hash value of what we're counting */
double t_hit, t_sv_hit;
struct vector3 delta, hit; /* For raytracing */
struct vector3 xyz_loc; /* Computed location of mol if loc==NULL */
byte count_flags;
int pos_or_neg; /* Sign of count (neg for antiregions) */
int orient = SHRT_MIN; /* orientation of the molecule also serves as a flag
for triggering reactions */
/* Set up values and fill in things the calling function left out */
if (rxpn != NULL) {
hashval = rxpn->hashval;
target = rxpn;
count_flags = REPORT_RXNS;
} else {
hashval = am->properties->hashval;
target = am->properties;
count_flags = REPORT_CONTENTS;
if (loc == NULL) {
if (am->properties->flags & ON_GRID) {
uv2xyz(&(((struct surface_molecule *)am)->s_pos),
((struct surface_molecule *)am)->grid->surface, &xyz_loc);
loc = &xyz_loc;
} else
loc = &(((struct volume_molecule *)am)->pos);
}
if (my_wall == NULL && (am->properties->flags & ON_GRID) != 0) {
my_wall = ((struct surface_molecule *)am)->grid->surface;
}
if (am->properties->flags & ON_GRID) {
orient = ((struct surface_molecule *)am)->orient;
} else {
orient = 0;
}
}
// We do this, because fire_count_event needs a molecule id
u_long mol_id = -1;
if (am != NULL) {
mol_id = am->id;
}
/* Count surface molecules and reactions on surfaces--easy */
if (my_wall != NULL && (my_wall->flags & COUNT_CONTENTS) != 0) {
for (rl = my_wall->counting_regions; rl != NULL; rl = rl->next) {
int hash_bin = (hashval + rl->reg->hashval) & world->count_hashmask;
for (c = world->count_hash[hash_bin]; c != NULL; c = c->next) {
if (c->target == target && c->reg_type == rl->reg &&
(c->counter_type & ENCLOSING_COUNTER) == 0) {
if (c->counter_type & TRIG_COUNTER) {
c->data.trig.t_event = t;
c->data.trig.orient = orient;
// XXX: may need to convert loc for PBCs
fire_count_event(world, c, n, loc, count_flags | REPORT_TRIGGER, mol_id);
} else if (rxpn == NULL) {
if (am->properties->flags & ON_GRID) {
if ((c->orientation == ORIENT_NOT_SET) ||
(c->orientation == orient) || (c->orientation == 0)) {
// count only in the relevant periodic box
if (periodic_boxes_are_identical(am->periodic_box, c->periodic_box)) {
c->data.move.n_at += n;
}
}
} else {
c->data.move.n_at += n;
}
} else if ((rxpn != NULL) && (periodic_boxes_are_identical(periodic_box, c->periodic_box))) {
c->data.rx.n_rxn_at += n;
}
}
}
}
}
/* Waypoints must have been placed in order for the following code to work. */
if (!world->place_waypoints_flag) {
assert (am != NULL && (am->properties->flags & COUNT_ENCLOSED) == 0 &&
(am->properties->flags & NOT_FREE) != 0);
return;
}
/* Count volume molecules, vol reactions, and surface stuff that is
* enclosed--hard!!*/
if (am == NULL || (am->properties->flags & COUNT_ENCLOSED) != 0 ||
(am->properties->flags & NOT_FREE) == 0) {
const int px = bisect(world->x_partitions, world->nx_parts, loc->x);
const int py = bisect(world->y_partitions, world->ny_parts, loc->y);
const int pz = bisect(world->z_partitions, world->nz_parts, loc->z);
const int this_sv =
pz + (world->nz_parts - 1) * (py + (world->ny_parts - 1) * px);
struct waypoint *wp = &(world->waypoints[this_sv]);
struct subvolume *my_sv = &(world->subvol[this_sv]);
struct vector3 here = {wp->loc.x, wp->loc.y, wp->loc.z};
struct region_list *all_regs = NULL;
struct region_list *all_antiregs = NULL;
/* Copy all the potentially relevant regions from the nearest waypoint */
for (rl = wp->regions; rl != NULL; rl = rl->next) {
if (rl->reg == NULL)
continue;
int hash_bin = (hashval + rl->reg->hashval) & world->count_hashmask;
if (world->count_hash[hash_bin] == NULL)
continue; /* Won't count on this region so ignore it */
nrl = (struct region_list *)CHECKED_MEM_GET(
my_sv->local_storage->regl, "list of enclosing regions for count");
nrl->reg = rl->reg;
nrl->next = all_regs;
all_regs = nrl;
}
/* And all the antiregions (regions crossed from inside to outside only) */
for (arl = wp->antiregions; arl != NULL; arl = arl->next) {
int hash_bin = (hashval + arl->reg->hashval) & world->count_hashmask;
if (world->count_hash[hash_bin] == NULL)
continue; /* Won't count on this region so ignore it */
narl = (struct region_list *)CHECKED_MEM_GET(
my_sv->local_storage->regl, "list of enclosing regions for count");
narl->reg = arl->reg;
narl->next = all_antiregs;
all_antiregs = narl;
}
/* Raytrace across any walls from waypoint to us and add to region lists */
for (struct subvolume *sv = &(world->subvol[this_sv]); sv != NULL;
sv = next_subvol(&here, &delta, sv, world->x_fineparts,
world->y_fineparts, world->z_fineparts,
world->ny_parts, world->nz_parts)) {
delta.x = loc->x - here.x;
delta.y = loc->y - here.y;
delta.z = loc->z - here.z;
t_sv_hit = collide_sv_time(&here, &delta, sv, world->x_fineparts,
world->y_fineparts, world->z_fineparts);
if (t_sv_hit > 1.0)
t_sv_hit = 1.0;
for (struct wall_list *wl = sv->wall_head; wl != NULL; wl = wl->next) {
/* Skip wall that we are on unless we're a volume molecule */
if (my_wall == wl->this_wall &&
(am == NULL || (am->properties->flags & NOT_FREE))) {
continue;
}
if (wl->this_wall->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) {
int hit_code = collide_wall(&here, &delta, wl->this_wall, &t_hit,
&hit, 0, world->rng, world->notify,
&(world->ray_polygon_tests));
if (hit_code == COLLIDE_MISS) {
continue;
}
world->ray_polygon_colls++;
if (t_hit <= t_sv_hit && (hit.x - loc->x) * delta.x +
(hit.y - loc->y) * delta.y + (hit.z - loc->z) * delta.z < 0) {
for (rl = wl->this_wall->counting_regions; rl != NULL;
rl = rl->next) {
if ((rl->reg->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) != 0) {
int hash_bin =
(hashval + rl->reg->hashval) & world->count_hashmask;
if (world->count_hash[hash_bin] == NULL) {
continue; /* Won't count on this region so ignore it */
}
nrl = (struct region_list *)CHECKED_MEM_GET(
my_sv->local_storage->regl,
"list of enclosing regions for count");
nrl->reg = rl->reg;
if (hit_code == COLLIDE_FRONT) {
nrl->next = all_regs;
all_regs = nrl;
} else if (hit_code == COLLIDE_BACK) {
nrl->next = all_antiregs;
all_antiregs = nrl;
}
}
}
}
}
}
}
/* Clean up region lists */
if (all_regs != NULL && all_antiregs != NULL)
clean_region_lists(my_sv, &all_regs, &all_antiregs);
/* Actually check the regions here */
count_flags |= REPORT_ENCLOSED;
for (nrl = all_regs; nrl != NULL; nrl = (nrl == all_regs) ? all_antiregs : NULL)
/* Trick so we don't need to duplicate this code */ {
if (nrl == all_regs) {
pos_or_neg = 1;
} else {
pos_or_neg = -1;
}
for (rl = nrl; rl != NULL; rl = rl->next) {
int hash_bin = (hashval + rl->reg->hashval) & world->count_hashmask;
for (c = world->count_hash[hash_bin]; c != NULL; c = c->next) {
if (am != NULL
&& !periodic_boxes_are_identical(c->periodic_box, periodic_box)) {
continue;
}
if (rxpn != NULL
&& !periodic_boxes_are_identical(c->periodic_box, periodic_box)) {
continue;
}
if (c->target == target && c->reg_type == rl->reg &&
((c->counter_type & ENCLOSING_COUNTER) != 0 ||
(am != NULL && (am->properties->flags & ON_GRID) == 0)) &&
(my_wall == NULL ||
(am != NULL && (am->properties->flags & NOT_FREE) == 0) ||
!region_listed(my_wall->counting_regions, rl->reg))) {
if (c->counter_type & TRIG_COUNTER) {
c->data.trig.t_event = t;
c->data.trig.orient = orient;
// Don't count triggers after a dynamic geometry event
if (!world->dynamic_geometry_flag) {
// XXX: may need to convert loc for PBCs
fire_count_event(world, c, n * pos_or_neg, loc,
count_flags | REPORT_TRIGGER, mol_id);
}
} else if (rxpn == NULL) {
if (am->properties->flags & ON_GRID) {
if ((c->orientation == ORIENT_NOT_SET) ||
(c->orientation == orient) || (c->orientation == 0)) {
c->data.move.n_enclosed += n * pos_or_neg;
}
} else {
c->data.move.n_enclosed += n * pos_or_neg;
}
} else {
c->data.rx.n_rxn_enclosed += n * pos_or_neg;
}
}
}
}
}
/* Free region memory */
if (all_regs != NULL)
mem_put_list(my_sv->local_storage->regl, all_regs);
if (all_antiregs != NULL)
mem_put_list(my_sv->local_storage->regl, all_antiregs);
}
}
/*************************************************************************
count_moved_surface_mol:
In: world: simulation state
sm: molecule to count
sg: new grid for molecule
loc: new location on that grid
count_hashmask:
count_hash:
ray_polygon_colls:
Out: Returns zero on success and 1 on failure.
Appropriate counters are updated and triggers are fired.
Note: This routine is not super-fast for enclosed counts for
surface molecules since it raytraces without using waypoints.
*************************************************************************/
void count_moved_surface_mol(
struct volume *world,
struct surface_molecule *sm,
struct surface_grid *sg,
struct vector2 *loc,
int count_hashmask,
struct counter **count_hash,
long long *ray_polygon_colls,
struct periodic_image *previous_box) {
struct vector3 origin;
struct vector3 target;
struct region_list *pos_regs = NULL;
struct region_list *neg_regs = NULL;
struct region_list *nrl = NULL;
struct region_list *prl = NULL;
struct region_list *rl = NULL;
struct region_list *rl2 = NULL;
struct storage *stor = sm->grid->surface->birthplace;
// Different grids implies different walls, so we might have changed regions
/*if (sm->grid != sg) {*/
if ((sm->grid != sg) ||
(world->periodic_box_obj && !world->periodic_traditional)) {
int delete_me = 0;
if ((sm->grid->surface->flags & COUNT_CONTENTS) != 0 &&
(sg->surface->flags & COUNT_CONTENTS) != 0) {
delete_me = 1;
nrl = sm->grid->surface->counting_regions;
prl = sg->surface->counting_regions;
while (prl != NULL && nrl != NULL) {
if (prl->reg == nrl->reg) {
rl = (struct region_list *)CHECKED_MEM_GET(stor->regl, "region list entry");
rl->next = pos_regs;
rl->reg = prl->reg;
pos_regs = rl;
prl = prl->next;
rl2 = (struct region_list *)CHECKED_MEM_GET(stor->regl, "region list entry");
rl2->next = neg_regs;
rl2->reg = nrl->reg;
neg_regs = rl2;
nrl = nrl->next;
continue;
}
while (prl != NULL && prl->reg < nrl->reg) { /* Entering these regions */
rl = (struct region_list *)CHECKED_MEM_GET(stor->regl, "region list entry");
rl->next = pos_regs;
rl->reg = prl->reg;
pos_regs = rl;
prl = prl->next;
}
while (nrl != NULL && (prl == NULL || nrl->reg < prl->reg)) { /* Leaving these regions */
rl = (struct region_list *)CHECKED_MEM_GET(stor->regl, "region list entry");
rl->next = neg_regs;
rl->reg = nrl->reg;
neg_regs = rl;
nrl = nrl->next;
}
}
/* If we exhaust all negative regions before we've exhausted all
* positive regions, the above loop will terminate, leaving some
* regions uncounted. */
while (prl != NULL) {
rl = (struct region_list *)CHECKED_MEM_GET(stor->regl,
"region list entry");
rl->next = pos_regs;
rl->reg = prl->reg;
pos_regs = rl;
prl = prl->next;
}
/* I don't think this can happen, but it could potentially happen
* if, say, prl started off NULL (i.e. one of the grids belonged
* to no counting regions at all). */
while (nrl != NULL) {
rl = (struct region_list *)CHECKED_MEM_GET(stor->regl,
"region list entry");
rl->next = neg_regs;
rl->reg = nrl->reg;
neg_regs = rl;
nrl = nrl->next;
}
} else if (sm->grid->surface->flags & COUNT_CONTENTS) {
neg_regs = sm->grid->surface->counting_regions;
} else if (sg->surface->flags & COUNT_CONTENTS) {
pos_regs = sg->surface->counting_regions;
}
// Different walls and possibly different periodic box
if (pos_regs != NULL) {
uv2xyz(loc, sg->surface, &target);
count_region_list(
world, pos_regs, sm, &target, count_hashmask, 1, previous_box);
}
if (neg_regs != NULL) {
uv2xyz(&(sm->s_pos), sm->grid->surface, &origin);
count_region_list(
world, neg_regs, sm, &origin, count_hashmask, -1, previous_box);
}
if (delete_me) {
if (pos_regs != NULL)
mem_put_list(stor->regl, pos_regs);
if (neg_regs != NULL)
mem_put_list(stor->regl, neg_regs);
}
}
/* Have to raytrace */
uv2xyz(&(sm->s_pos), sm->grid->surface, &origin);
uv2xyz(loc, sg->surface, &target);
if ((sm->properties->flags & COUNT_ENCLOSED) &&
(periodic_boxes_are_identical(previous_box, sm->periodic_box))) {
pos_regs = neg_regs = NULL;
struct vector3 delta = {target.x - origin.x, target.y - origin.y, target.z - origin.z};
struct vector3 here = origin;
/* Collect all the relevant regions we pass through */
for (struct subvolume *sv = find_subvolume(world, &origin, NULL); sv != NULL;
sv = next_subvol(&here, &delta, sv, world->x_fineparts, world->y_fineparts,
world->z_fineparts, world->ny_parts, world->nz_parts)) {
int j = 0;
for (struct wall_list *wl = sv->wall_head; wl != NULL; wl = wl->next) {
if (wl->this_wall == sm->grid->surface || wl->this_wall == sg->surface) {
continue; // ignore the origin and target walls
}
struct vector3 hit = {0.0, 0.0, 0.0};
double t = 0.0;
j = collide_wall(&here, &delta, wl->this_wall, &t, &hit, 0, world->rng,
world->notify, &(world->ray_polygon_tests));
/* we only consider the collision if it happens in the current subvolume.
Otherwise we may double count collision for walls that span multiple
subvolumes */
if (!inside_subvolume(&hit, sv, world->x_fineparts, world->y_fineparts,
world->z_fineparts)) {
continue;
}
if (j != COLLIDE_MISS) {
(*ray_polygon_colls)++;
}
/* check that hit is encountered before we reach the target */
if (j != COLLIDE_MISS && (hit.x - target.x) * delta.x +
(hit.y - target.y) * delta.y + (hit.z - target.z) * delta.z < 0) {
for (rl = wl->this_wall->counting_regions; rl != NULL; rl = rl->next) {
if ((rl->reg->flags & COUNT_ENCLOSED) == 0) {
continue; /* Only ENCLOSED counted here */
}
if (j == COLLIDE_FRONT) {
prl = (struct region_list *)CHECKED_MEM_GET(stor->regl, "region list entry");
prl->reg = rl->reg;
prl->next = pos_regs;
pos_regs = prl;
} else if (j == COLLIDE_BACK) {
nrl = (struct region_list *)CHECKED_MEM_GET(stor->regl, "region list entry");
nrl->reg = rl->reg;
nrl->next = neg_regs;
neg_regs = nrl;
}
}
}
}
}
if (pos_regs != NULL) {
pos_regs = (struct region_list *)void_list_sort((struct void_list *)pos_regs);
}
if (neg_regs != NULL) {
neg_regs = (struct region_list *)void_list_sort((struct void_list *)neg_regs);
}
prl = pos_regs;
nrl = neg_regs;
struct vector3 *where = NULL;
int n;
while (prl != NULL || nrl != NULL) {
if (prl == NULL) {
rl = nrl;
nrl = nrl->next;
n = -1;
where = &origin;
} else if (nrl == NULL) {
rl = prl;
prl = prl->next;
n = 1;
where = ⌖
} else if (prl->reg < nrl->reg) {
rl = prl;
prl = prl->next;
n = 1;
where = &origin;
} else if (nrl->reg < prl->reg) {
rl = nrl;
nrl = nrl->next;
n = -1;
where = ⌖
} else {
rl = NULL;
prl = prl->next;
nrl = nrl->next;
}
if (rl == NULL) {
continue;
}
int hash_bin = (sm->properties->hashval + rl->reg->hashval) & count_hashmask;
for (struct counter *c = count_hash[hash_bin]; c != NULL; c = c->next) {
if (c->target == sm->properties && c->reg_type == rl->reg &&
(c->counter_type & ENCLOSING_COUNTER) != 0) {
assert(!region_listed(sm->grid->surface->counting_regions, rl->reg));
assert(!region_listed(sg->surface->counting_regions, rl->reg));
if (c->counter_type & TRIG_COUNTER) {
c->data.trig.t_event = sm->t;
c->data.trig.orient = sm->orient;
fire_count_event(world, c, n, where, REPORT_CONTENTS | REPORT_ENCLOSED |
REPORT_TRIGGER, sm->id);
} else if ((c->orientation == ORIENT_NOT_SET) ||
(c->orientation == sm->orient) ||
(c->orientation == 0)) {
/*c->data.move.n_enclosed += n;*/
if (periodic_boxes_are_identical(c->periodic_box, sm->periodic_box)) {
c->data.move.n_enclosed += n;
}
}
}
}
}
if (pos_regs != NULL)
mem_put_list(stor->regl, pos_regs);
if (neg_regs != NULL)
mem_put_list(stor->regl, neg_regs);
}
else if ((sm->properties->flags & COUNT_ENCLOSED) &&
(!periodic_boxes_are_identical(previous_box, sm->periodic_box))) {
// Increment count of where we are going now (target)
count_region_from_scratch(world, (struct abstract_molecule *)sm, NULL, 1, &target, NULL, 1.0, sm->periodic_box);
// Decrement count of where we were before (origin)
count_region_from_scratch(world, (struct abstract_molecule *)sm, NULL, -1, &origin, NULL, 1.0, previous_box);
}
}
/*************************************************************************
fire_count_event:
In: world: simulation state
event: counter of thing that just happened (trigger of some sort)
n: number of times that thing happened (or hit direction for triggers)
where: location where it happened
what: what happened (Report Type Flags)
Out: None
*************************************************************************/
void fire_count_event(struct volume *world, struct counter *event, int n,
struct vector3 *where, byte what, u_long id) {
short flags;
if ((what & REPORT_TYPE_MASK) == REPORT_RXNS)
flags = TRIG_IS_RXN;
else if ((what & REPORT_TYPE_MASK) == REPORT_CONTENTS)
flags = 0;
else
flags = TRIG_IS_HIT;
byte whatelse = what;
if ((what & REPORT_TYPE_MASK) == REPORT_FRONT_HITS)
whatelse = (what - REPORT_FRONT_HITS) | REPORT_ALL_HITS;
else if ((what & REPORT_TYPE_MASK) == REPORT_BACK_HITS)
whatelse = (what - REPORT_BACK_HITS) | REPORT_ALL_HITS;
else if ((what & REPORT_TYPE_MASK) == REPORT_FRONT_CROSSINGS)
whatelse = (what - REPORT_FRONT_CROSSINGS) | REPORT_ALL_CROSSINGS;
else if ((what & REPORT_TYPE_MASK) == REPORT_BACK_CROSSINGS)
whatelse = (what - REPORT_BACK_CROSSINGS) | REPORT_ALL_CROSSINGS;
struct trigger_request *tr;
for (tr = event->data.trig.listeners; tr != NULL; tr = tr->next) {
if (tr->ear->report_type == what) {
memcpy(&(event->data.trig.loc), where, sizeof(struct vector3));
if ((what & REPORT_TYPE_MASK) == REPORT_FRONT_HITS ||
(what & REPORT_TYPE_MASK) == REPORT_FRONT_CROSSINGS) {
add_trigger_output(world, event, tr->ear, n, flags, id);
} else if ((what & REPORT_TYPE_MASK) == REPORT_BACK_HITS ||
(what & REPORT_TYPE_MASK) == REPORT_BACK_CROSSINGS) {
add_trigger_output(world, event, tr->ear, -n, flags, id);
} else {
add_trigger_output(world, event, tr->ear, n, flags, id);
}
} else if (tr->ear->report_type == whatelse) {
memcpy(&(event->data.trig.loc), where, sizeof(struct vector3));
if ((what & REPORT_TYPE_MASK) == REPORT_FRONT_HITS ||
(what & REPORT_TYPE_MASK) == REPORT_FRONT_CROSSINGS) {
add_trigger_output(world, event, tr->ear, n, flags, id);
} else {
add_trigger_output(world, event, tr->ear, -n, flags, id);
}
}
}
}
/*************************************************************************
find_enclosing_regions:
In: world: simulation state
loc: location we want to end up
start: starting position
rlp: list of regions we're inside at the starting position
arlp: list of inside-out regions we're "outside" at the starting position
rmem: memory handler to store lists of regions
Out: 0 on success, 1 on memory allocation error. The region and
inside-out region lists are updated to be correct at the ending
position.
*************************************************************************/
static int find_enclosing_regions(struct volume *world,
struct vector3 *loc,
struct vector3 *start,
struct region_list **rlp,
struct region_list **arlp,
struct mem_helper *rmem) {
struct vector3 outside, delta, hit;
struct wall_list *wl;
struct region_list *rl, *arl;
struct region_list *trl, *tarl, *xrl, *yrl, *nrl;
struct wall_list dummy;
rl = *rlp;
arl = *arlp;
if (start == NULL || (distinguishable(loc->x, start->x, EPS_C)) ||
(distinguishable(loc->y, start->y, EPS_C)) || loc->z < start->z) {
outside.x = loc->x;
outside.y = loc->y;
outside.z = (world->z_partitions[0] + world->z_partitions[1]) / 2;
} else {
outside.x = start->x;
outside.y = start->y;
outside.z = start->z;
}
delta.x = 0.0;
delta.y = 0.0;
delta.z = loc->z - outside.z;
struct subvolume *sv = find_subvolume(world, &outside, NULL);
struct subvolume *svt = find_subvolume(world, loc, NULL);
int traveling = 1;
double t;
while (traveling) {
tarl = trl = NULL;
double t_hit_sv = collide_sv_time(&outside, &delta, sv, world->x_fineparts,
world->y_fineparts, world->z_fineparts);
for (wl = sv->wall_head; wl != NULL; wl = wl->next) {
int hit_code =
collide_wall(&outside, &delta, wl->this_wall, &t, &hit, 0, world->rng,
world->notify, &(world->ray_polygon_tests));
if ((hit_code != COLLIDE_MISS) &&
(world->notify->final_summary == NOTIFY_FULL)) {
world->ray_polygon_colls++;
}
if (hit_code == COLLIDE_REDO) {
while (trl != NULL) {
xrl = trl->next;
mem_put(rmem, trl);
trl = xrl;
}
while (tarl != NULL) {
xrl = tarl->next;
mem_put(rmem, tarl);
tarl = xrl;
}
dummy.next = sv->wall_head;
wl = &dummy;
continue; /* Trick to restart for loop */
} else if (hit_code == COLLIDE_MISS || !(t >= 0 && t < 1.0) ||
t > t_hit_sv ||
(wl->this_wall->flags &
(COUNT_CONTENTS | COUNT_RXNS | COUNT_ENCLOSED)) == 0 ||
(hit.x - outside.x) * delta.x + (hit.y - outside.y) * delta.y +
(hit.z - outside.z) * delta.z <
0)
continue;
else {
for (xrl = wl->this_wall->counting_regions; xrl != NULL;
xrl = xrl->next) {
if ((xrl->reg->flags &
(COUNT_CONTENTS | COUNT_RXNS | COUNT_ENCLOSED)) != 0) {
nrl = (struct region_list *)CHECKED_MEM_GET(rmem,
"region list entry");
nrl->reg = xrl->reg;
if (hit_code == COLLIDE_BACK) {
nrl->next = tarl;
tarl = nrl;
} else {
nrl->next = trl;
trl = nrl;
}
}
}
}
}
xrl = trl;
while (trl != NULL) {
nrl = NULL;
yrl = arl;
while (yrl != NULL) {
if (xrl->reg == yrl->reg) {
if (nrl == NULL) {
arl = yrl->next;
mem_put(rmem, yrl);
} else {
nrl->next = yrl->next;
mem_put(rmem, yrl);
}
trl = trl->next;
mem_put(rmem, xrl);
xrl = NULL;
break;
} else {
nrl = yrl;
yrl = yrl->next;
}
}
if (xrl != NULL) {
trl = trl->next;
xrl->next = rl;
rl = xrl;
xrl = trl;
} else
xrl = trl;
}
xrl = tarl;
while (tarl != NULL) {
nrl = NULL;
yrl = rl;
while (yrl != NULL) {
if (xrl->reg == yrl->reg) {
if (nrl == NULL) {
rl = yrl->next;
mem_put(rmem, yrl);
} else {
nrl->next = yrl->next;
mem_put(rmem, yrl);
}
tarl = tarl->next;
mem_put(rmem, xrl);
xrl = NULL;
break;
} else {
nrl = yrl;
yrl = yrl->next;
}
}
if (xrl != NULL) {
tarl = tarl->next;
xrl->next = arl;
arl = xrl;
xrl = tarl;
} else
xrl = tarl;
}
if (sv == svt)
traveling = 0;
else {
sv = next_subvol(&outside, &delta, sv, world->x_fineparts,
world->y_fineparts, world->z_fineparts, world->ny_parts,
world->nz_parts);
delta.x = loc->x - outside.x;
delta.y = loc->y - outside.y;
delta.z = loc->z - outside.z;
if (sv == NULL) {
if ((delta.x * delta.x + delta.y * delta.y + delta.z * delta.z) <
EPS_C * EPS_C) {
mcell_log("Didn't quite reach waypoint target, fudging.");
traveling = 0;
} else {
mcell_log("Couldn't reach waypoint target.");
sv = find_subvolume(world, &outside, NULL);
}
}
}
}
*rlp = rl;
*arlp = arl;
return 0;
}
/*************************************************************************
place_waypoints:
In: world: simulation state
Out: Returns 1 if malloc fails, 0 otherwise.
Allocates waypoints to SSVs, if any are needed.
Note: you must have initialized SSVs before calling this routine!
*************************************************************************/
int place_waypoints(struct volume *world) {
int waypoint_in_wall = 0;
/* Being exactly in the center of a subdivision can be bad. */
/* Define "almost center" positions for X, Y, Z */
#define W_Xa (0.5 + 0.0005 * MY_PI)
#define W_Ya (0.5 + 0.0002 * MY_PI *MY_PI)
#define W_Za (0.5 - 0.00007 * MY_PI *MY_PI *MY_PI)
#define W_Xb (1.0 - W_Xa)
#define W_Yb (1.0 - W_Ya)
#define W_Zb (1.0 - W_Za)
/* Probably ought to check for whether you really need waypoints */
if (world->waypoints != NULL)
free(world->waypoints);
world->n_waypoints = world->n_subvols;
world->waypoints =
CHECKED_MALLOC_ARRAY(struct waypoint, world->n_waypoints, "waypoints");
memset(world->waypoints, 0, world->n_waypoints * sizeof(struct waypoint));
for (int px = 0; px < world->nx_parts - 1; px++) {
for (int py = 0; py < world->ny_parts - 1; py++) {
for (int pz = 0; pz < world->nz_parts - 1; pz++) {
const int this_sv =
pz + (world->nz_parts - 1) * (py + (world->ny_parts - 1) * px);
struct waypoint *wp = &(world->waypoints[this_sv]);
struct subvolume *sv = &(world->subvol[this_sv]);
/* Place waypoint near center of subvolume (W_#a=W_#b=0.5 gives center)
*/
wp->loc.x = W_Xa * world->x_fineparts[sv->llf.x] +
W_Xb * world->x_fineparts[sv->urb.x];
wp->loc.y = W_Ya * world->y_fineparts[sv->llf.y] +
W_Yb * world->y_fineparts[sv->urb.y];
wp->loc.z = W_Za * world->z_fineparts[sv->llf.z] +
W_Zb * world->z_fineparts[sv->urb.z];
do {
waypoint_in_wall = 0;
struct wall_list *wl;
for (wl = sv->wall_head; wl != NULL; wl = wl->next) {
double d = dot_prod(&(wp->loc), &(wl->this_wall->normal));
if (eps_equals(d, wl->this_wall->d)) {
waypoint_in_wall++;
d = EPS_C * (double)((rng_uint(world->rng) & 0xF) - 8);
if (!distinguishable(d, 0, EPS_C))
d = 8 * EPS_C;
wp->loc.x += d * wl->this_wall->normal.x;
wp->loc.y += d * wl->this_wall->normal.y;
wp->loc.z += d * wl->this_wall->normal.z;
break;
}
}
} while (waypoint_in_wall);
if (pz > 0) {
if (world->waypoints[this_sv - 1].regions != NULL) {
wp->regions = dup_region_list(world->waypoints[this_sv - 1].regions,
sv->local_storage->regl);
if (wp->regions == NULL)
return 1;
} else
wp->regions = NULL;
if (world->waypoints[this_sv - 1].antiregions != NULL) {
wp->antiregions =
dup_region_list(world->waypoints[this_sv - 1].antiregions,
sv->local_storage->regl);
if (wp->antiregions == NULL)
return 1;
} else
wp->antiregions = NULL;
if (find_enclosing_regions(
world, &(wp->loc), &(world->waypoints[this_sv - 1].loc),
&(wp->regions), &(wp->antiregions), sv->local_storage->regl))
return 1;
} else {
wp->regions = NULL;
wp->antiregions = NULL;
if (find_enclosing_regions(world, &(wp->loc), NULL, &(wp->regions),
&(wp->antiregions),
sv->local_storage->regl))
return 1;
}
}
}
}
return 0;
#undef W_Zb
#undef W_Yb
#undef W_Xb
#undef W_Za
#undef W_Ya
#undef W_Xa
}
/******************************************************************
prepare_counters:
In: world: simulation state
Out: 0 if counter statements are correct, 1 otherwise.
Note: A statement is incorrect if a non-closed manifold region
tries to count a freely diffusing molecule. Fixes up all
count requests to point at the data we care about.
********************************************************************/
int prepare_counters(struct volume *world) {
/* First give everything a sensible name, if needed */
for (struct output_block *block = world->output_block_head; block != NULL;
block = block->next) {
for (struct output_set *set = block->data_set_head; set != NULL;
set = set->next) {
if (set->header_comment == NULL)
continue;
for (struct output_column *column = set->column_head; column != NULL;
column = column->next) {
if (column->expr->title == NULL)
column->expr->title = oexpr_title(column->expr);
if (column->expr->title == NULL)
mcell_allocfailed("Unable to create title for reaction data output.");
}
}
}
/* Then convert all requests to real counts */
for (struct output_request *request = world->output_request_head;
request != NULL; request = request->next) {
/* check whether the "count_location" refers to the instantiated
object or region */
if (request->count_location != NULL) {
char *name = request->count_location->name;
if (!((is_object_instantiated(request->count_location, world->root_instance)) ||
((world->dg_parse != NULL ) &&
((retrieve_sym(name, world->dg_parse->reg_sym_table) != NULL) ||
(retrieve_sym(name, world->dg_parse->obj_sym_table) != NULL)))))
mcell_error("The object/region name '%s' in the COUNT/TRIGGER "
"statement is not fully referenced.\n"
" This occurs when a count is requested on an object "
"which has not been referenced\n"
" (directly or indirectly) from an INSTANTIATE block in "
"the MDL file.", name);
}
if (request->count_target->sym_type == MOL) {
struct species *sp = (struct species *)(request->count_target->value);
/* For volume molecules: */
if ((sp->flags & ON_GRID) == 0) {
/* Make sure orientation is not set */
if (request->count_orientation != ORIENT_NOT_SET) {
switch (world->notify->useless_vol_orient) {
case WARN_WARN:
mcell_warn("An orientation has been given for the molecule '%s', "
"which is a volume molecule.\n"
" Orientation is valid only for surface molecules, and "
"will be ignored.",
request->count_target->name);
/* Fall through */
case WARN_COPE:
request->count_orientation = ORIENT_NOT_SET;
break;
case WARN_ERROR:
mcell_error("An orientation has been given for the molecule '%s', "
"which is a volume molecule.\n"
" Orientation is valid only for surface molecules.",
request->count_target->name);
/*break;*/
}
}
}
}
if (request->count_location != NULL &&
request->count_location->sym_type == OBJ) {
if (expand_object_output(request,
(struct geom_object *)request->count_location->value,
world->reg_sym_table))
mcell_error("Failed to expand request to count on object.");
}
if (instantiate_count_request(
world->dynamic_geometry_flag, request, world->count_hashmask,
world->count_hash, world->trig_request_mem, &world->elapsed_time,
world->counter_mem)) {
mcell_error("Failed to instantiate count request.");
}
}
return 0;
}
/******************************************************************
is_object_instantiated:
In: entry: symbol table entry to check
root_instance: symbol_table entry against which the object is tested
Out: 1 if the name of the object or one of its descendants matches the name
of the symbol passed, 0 otherwise.
Note: Checking is performed for all instantiated objects
********************************************************************/
int is_object_instantiated(struct sym_entry *entry,
struct geom_object *root_instance) {
struct geom_object *obj = NULL;
if (entry->sym_type == REG) {
struct region *reg = (struct region *)entry->value;
obj = ((struct region *)(entry->value))->parent;
if (region_listed(obj->regions, reg)) {
return 1;
}
else {
return 0;
}
}
else if (entry->sym_type == OBJ && entry->count != 0)
obj = ((struct geom_object *)(entry->value));
else
return 0;
for (; obj != NULL; obj = obj->parent) {
if (obj == root_instance)
return 1;
}
return 0;
}
/*************************************************************************
check_counter_geometry:
In: count_hashmask:
count_hash:
place_waypoints_flag:
Out: 0 on success, 1 on failure.
Checks all counters to make sure that if they are ENCLOSING,
they count on closed regions. If not, the function prints out
the offending region name and returns 1.
*************************************************************************/
int check_counter_geometry(int count_hashmask, struct counter **count_hash,
byte *place_waypoints_flag) {
/* Check to make sure what we've created is geometrically sensible */
for (int i = 0; i < count_hashmask + 1; i++) {
for (struct counter *cp = count_hash[i]; cp != NULL; cp = cp->next) {
if ((cp->counter_type & ENCLOSING_COUNTER) != 0) {
struct region *rp = cp->reg_type;
if (rp->manifold_flag == MANIFOLD_UNCHECKED) {
int count_regions_flag = 1;
if (is_manifold(rp, count_regions_flag))
rp->manifold_flag = IS_MANIFOLD;
else
rp->manifold_flag = NOT_MANIFOLD;
}
if (rp->manifold_flag == NOT_MANIFOLD)
mcell_error("Cannot count molecules or events inside non-manifold "
"object region '%s'. Please make sure that all "
"objects/regions used to count 3D molecules are "
"closed/watertight.",
rp->sym->name);
(*place_waypoints_flag) = 1;
}
}
}
return 0;
}
/*************************************************************************
expand_object_output:
In: request: request for a count
obj: object upon which the request is made.
Out: 0 on success, 1 on failure (memory allocation only?).
Request is split into a separate request for each BOX and POLY
object's ALL region that is a child of this object. The result
is then added up here.
Note: This is probably broken for concentration. It may also not be
the most intuitive interpretation when used inside a large
object with multiple layers of nesting--if one molecule is
inside three sub-objects, it will be counted three times!
PostNote: Checks that COUNT/TRIGGER statements are not allowed for
metaobjects and release objects.
*************************************************************************/
int expand_object_output(
struct output_request *request,
struct geom_object *obj,
struct sym_table_head *reg_sym_table) {
#ifdef ALLOW_COUNTS_ON_METAOBJECT
int n_expanded;
#endif
switch (obj->object_type) {
case REL_SITE_OBJ:
mcell_error("COUNT and TRIGGER statements on release object '%s' are not "
"allowed.\n",
obj->sym->name);
/*break;*/
case META_OBJ:
/* XXX: Should this really be disabled? Some comments by Tom lead me to
* believe that, despite the potential confusion for users, this should
* not be disabled.
*/
#ifndef ALLOW_COUNTS_ON_METAOBJECT
mcell_error(
"COUNT and TRIGGER statements on metaobject '%s' are not allowed.\n",
obj->sym->name);
#else
#error "Support for counting in/on a metaobject doesn't work right now."
n_expanded = 0;
for (struct geom_object *child = obj->first_child; child != NULL;
child = child->next) {
if (!object_has_geometry(child))
continue; /* NOTE -- for objects nested N deep, we check this
N+(N-1)+...+2+1 times (slow) */
if (n_expanded > 0) {
struct output_request *new_request =
(struct output_request *)mem_get(world->outp_request_mem);
struct output_expression *oe = request->requester;
struct output_expression *oel = new_output_expr(world->oexpr_mem);
struct output_expression *oer = new_output_expr(world->oexpr_mem);
if (new_request == NULL || oel == NULL || oer == NULL)
mcell_allocfailed("Failed to expand count expression on object %s.",
obj->sym->name);
oel->column = oer->column = oe->column;
oel->expr_flags = oer->expr_flags = oe->expr_flags;
oel->up = oer->up = oe;
oel->left = request;
oer->left = new_request;
oel->oper = oer->oper = '#';
oe->expr_flags = (oe->expr_flags & OEXPR_TYPE_MASK) | OEXPR_LEFT_OEXPR |
OEXPR_RIGHT_OEXPR;
oe->left = oel;
oe->right = oer;
oe->oper = '+';
new_request->report_type = request->report_type;
new_request->count_target = request->count_target;
new_request->requester = oer;
request->requester = oel;
new_request->next = request->next;
request->next = new_request;
request = new_request;
}
if (expand_object_output(request, child, reg_sym_table))
return 1;
++n_expanded;
}
if (n_expanded == 0)
mcell_error("Trying to count on object %s but it has no geometry.",
obj->sym->name);
#endif
break;
case BOX_OBJ:
case POLY_OBJ: {
request->count_location = NULL;
for (struct region_list *rl = obj->regions; rl != NULL; rl = rl->next) {
if (is_reverse_abbrev(",ALL", rl->reg->sym->name)) {
request->count_location = rl->reg->sym;
break;
}
}
char *region_name = CHECKED_SPRINTF("%s,ALL", obj->sym->name);
if (request->count_location == NULL)
request->count_location = retrieve_sym(region_name, reg_sym_table);
free(region_name);
if (request->count_location == NULL)
mcell_internal_error("ALL region missing on object %s", obj->sym->name);
}
break;
default:
UNHANDLED_CASE(obj->object_type);
/*return 1;*/
}
return 0;
}
/*************************************************************************
object_has_geometry:
In: obj: object (instantiated in world)
Out: 0 if there are no geometrical objects within that object (and it
is not a geometrical object itself). 1 if there are such object.
*************************************************************************/
int object_has_geometry(struct geom_object *obj) {
struct geom_object *child;
switch (obj->object_type) {
case BOX_OBJ:
case POLY_OBJ:
return 1;
/*break;*/
case META_OBJ:
for (child = obj->first_child; child != NULL; child = child->next) {
if (object_has_geometry(child))
return 1;
}
break;
case REL_SITE_OBJ:
case VOXEL_OBJ:
default:
return 0;
/*break;*/
}
return 0;
}
/*************************************************************************
instantiate_count_request:
In: request: request for a count
count_hashmask:
count_hash:
trig_request_mem:
elapsed_time:
counter_mem:
Out: 0 on success, 1 on failure (memory allocation only?).
Requesting output tree gets appropriate node pointed to the
memory location where we will be collecting data.
*************************************************************************/
static int instantiate_count_request(
int dyn_geom_flag, struct output_request *request, int count_hashmask,
struct counter **count_hash, struct mem_helper *trig_request_mem,
double *elapsed_time, struct mem_helper *counter_mem) {
int request_hash = 0;
struct rxn_pathname *rxpn_to_count;
struct rxn *rx_to_count = NULL;
struct species *mol_to_count = NULL;
struct region *reg_of_count;
struct counter *count = NULL;
struct trigger_request *trig_req;
u_int report_type_only;
byte count_type;
int is_enclosed;
/* Set up and figure out hash value */
void *to_count = request->count_target->value;
switch (request->count_target->sym_type) {
case MOL:
rxpn_to_count = NULL;
rx_to_count = NULL;
mol_to_count = (struct species *)to_count;
if ((mol_to_count->flags & NOT_FREE) == 0 &&
(request->report_type & REPORT_TYPE_MASK) == REPORT_CONTENTS) {
request->report_type |= REPORT_ENCLOSED;
}
request_hash = mol_to_count->hashval;
break;
case RXPN:
rxpn_to_count = (struct rxn_pathname *)to_count;
rx_to_count = rxpn_to_count->rx;
mol_to_count = NULL;
if ((rx_to_count->players[0]->flags & NOT_FREE) == 0 &&
(rx_to_count->n_reactants == 1 ||
(rx_to_count->players[1]->flags & NOT_FREE) == 0)) {
request->report_type |= REPORT_ENCLOSED;
}
request_hash = rxpn_to_count->hashval;
break;
default:
UNHANDLED_CASE(request->count_target->sym_type);
/*return 1;*/
}
if (request->count_location != NULL) {
if (request->count_location->sym_type != REG)
mcell_internal_error(
"Non-region location symbol (type=%d) in count request.",
request->count_location->sym_type);
reg_of_count = (struct region *)request->count_location->value;
request_hash += reg_of_count->hashval;
} else
reg_of_count = NULL;
request_hash &= count_hashmask;
/* Now create count structs and set output expression to point to data */
report_type_only = request->report_type & REPORT_TYPE_MASK;
if (!dyn_geom_flag) {
request->requester->expr_flags &= ~OEXPR_LEFT_REQUEST;
}
if ((request->report_type & REPORT_TRIGGER) == 0 &&
request->count_location == NULL) /* World count is easy! */
{
request->report_type &= ~REPORT_ENCLOSED;
switch (report_type_only) {
case REPORT_CONTENTS:
request->requester->expr_flags |= OEXPR_LEFT_INT;
request->requester->left = (void *)&(mol_to_count->population);
break;
case REPORT_RXNS:
assert(rx_to_count != NULL);
request->requester->expr_flags |= OEXPR_LEFT_DBL;
request->requester->left =
(void *)&(rx_to_count->info[rxpn_to_count->path_num].count);
break;
default:
mcell_internal_error("Invalid report type 0x%x in count request.",
report_type_only);
/*return 1;*/
}
} else /* Triggered count or count on region */
{
/* Set count type flags */
if (report_type_only == REPORT_RXNS)
count_type = RXN_COUNTER;
else
count_type = MOL_COUNTER;
if (request->report_type & REPORT_ENCLOSED) {
assert(reg_of_count != NULL);
reg_of_count->flags |= COUNT_ENCLOSED;
count_type |= ENCLOSING_COUNTER;
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_ENCLOSED;
}
if (request->report_type & REPORT_TRIGGER) {
assert(reg_of_count != NULL);
count_type |= TRIG_COUNTER;
reg_of_count->flags |= COUNT_TRIGGER;
}
for (count = count_hash[request_hash]; count != NULL; count = count->next) {
if (count->reg_type == reg_of_count && count->target == to_count &&
count_type == count->counter_type &&
count->orientation == request->count_orientation &&
periodic_boxes_are_identical(count->periodic_box, request->periodic_box))
break;
}
if (count == NULL) {
count = create_new_counter(reg_of_count, request->count_target->value,
count_type, request->periodic_box, counter_mem);
if (request->count_orientation != ORIENT_NOT_SET) {
count->orientation = request->count_orientation;
}
count->next = count_hash[request_hash];
count_hash[request_hash] = count;
}
is_enclosed = ((request->report_type & REPORT_ENCLOSED) != 0);
/* set periodic box */
count->periodic_box = request->periodic_box;
/* Point appropriately */
if (request->report_type & REPORT_TRIGGER) {
trig_req = (struct trigger_request *)CHECKED_MEM_GET(
trig_request_mem, "trigger notification request");
trig_req->next = count->data.trig.listeners;
count->data.trig.listeners = trig_req;
trig_req->ear = request;
request->requester->expr_flags |= OEXPR_TYPE_TRIG;
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_TRIGGER;
assert(reg_of_count != NULL);
switch (report_type_only) {
case REPORT_CONTENTS:
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_CONTENTS;
reg_of_count->flags |= COUNT_CONTENTS;
break;
case REPORT_RXNS:
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_RXNS;
reg_of_count->flags |= COUNT_RXNS;
break;
case REPORT_FRONT_HITS:
case REPORT_BACK_HITS:
case REPORT_FRONT_CROSSINGS:
case REPORT_BACK_CROSSINGS:
case REPORT_ALL_HITS:
case REPORT_ALL_CROSSINGS:
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_HITS;
reg_of_count->flags |= COUNT_HITS;
break;
case REPORT_CONCENTRATION:
if (mol_to_count != NULL) {
if (mol_to_count->flags & ON_GRID) {
mcell_error("ESTIMATE_CONC counting on regions is implemented only "
"for volume molecules, while %s is a surface molecule.",
mol_to_count->sym->name);
} else {
mol_to_count->flags |= COUNT_HITS;
reg_of_count->flags |= COUNT_HITS;
}
}
break;
default:
UNHANDLED_CASE(report_type_only);
/*return 1;*/
}
} else /* Not trigger--set up for regular count */
{
assert(reg_of_count != NULL);
request->requester->expr_flags |= OEXPR_LEFT_DBL; /* Assume double */
switch (report_type_only) {
case REPORT_CONTENTS:
request->requester->expr_flags -= OEXPR_LEFT_DBL;
request->requester->expr_flags |= OEXPR_LEFT_INT;
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_CONTENTS;
reg_of_count->flags |= COUNT_CONTENTS;
if (!is_enclosed)
request->requester->left = (void *)&(count->data.move.n_at);
else
request->requester->left = (void *)&(count->data.move.n_enclosed);
break;
case REPORT_RXNS:
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_RXNS;
reg_of_count->flags |= COUNT_RXNS;
if (!is_enclosed)
request->requester->left = (void *)&(count->data.rx.n_rxn_at);
else
request->requester->left = (void *)&(count->data.rx.n_rxn_enclosed);
break;
case REPORT_FRONT_HITS:
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_HITS;
reg_of_count->flags |= COUNT_HITS;
request->requester->left = (void *)&(count->data.move.front_hits);
break;
case REPORT_BACK_HITS:
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_HITS;
reg_of_count->flags |= COUNT_HITS;
request->requester->left = (void *)&(count->data.move.back_hits);
break;
case REPORT_FRONT_CROSSINGS:
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_HITS;
reg_of_count->flags |= COUNT_HITS;
request->requester->left = (void *)&(count->data.move.front_to_back);
break;
case REPORT_BACK_CROSSINGS:
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_HITS;
reg_of_count->flags |= COUNT_HITS;
request->requester->left = (void *)&(count->data.move.back_to_front);
break;
case REPORT_ALL_HITS:
request->requester->expr_flags |= OEXPR_RIGHT_DBL;
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_HITS;
reg_of_count->flags |= COUNT_HITS;
request->requester->left = (void *)&(count->data.move.front_hits);
request->requester->right = (void *)&(count->data.move.back_hits);
break;
case REPORT_ALL_CROSSINGS:
request->requester->expr_flags |= OEXPR_RIGHT_DBL;
reg_of_count->flags |= COUNT_HITS;
if (mol_to_count != NULL)
mol_to_count->flags |= COUNT_HITS;
request->requester->left = (void *)&(count->data.move.front_to_back);
request->requester->right = (void *)&(count->data.move.back_to_front);
break;
case REPORT_CONCENTRATION:
request->requester->expr_flags |= OEXPR_RIGHT_DBL;
if (mol_to_count != NULL) {
if (mol_to_count->flags & ON_GRID) {
mcell_error("ESTIMATE_CONC counting on regions is implemented only "
"for volume molecules, while %s is a surface molecule.",
mol_to_count->sym->name);
} else {
mol_to_count->flags |= COUNT_HITS;
}
}
reg_of_count->flags |= COUNT_HITS;
request->requester->left = (void *)&(count->data.move.scaled_hits);
request->requester->right = (void *)(elapsed_time);
request->requester->oper = '/';
break;
default:
UNHANDLED_CASE(report_type_only);
/*return 1;*/
}
}
}
return 0;
}
/*************************************************************************
create_new_counter:
In: where: region upon which to count
who: target we're going to count (species or rxn pathname)
what: what to count (*_COUNTER flags)
img: in what periodic image to count
counter_mem:
Out: Newly allocated counter initialized with the given region and
target, or NULL if there is a memory allocation error.
Note: memory is allocated from world->counter_mem using mem_get,
not from the global heap using malloc.
*************************************************************************/
static struct counter *create_new_counter(struct region *where, void *who,
byte what, struct periodic_image *img, struct mem_helper *counter_mem) {
struct counter *c;
c = (struct counter *)CHECKED_MEM_GET(counter_mem, "counter");
c->next = NULL;
c->reg_type = where;
c->target = who;
c->orientation = ORIENT_NOT_SET;
c->counter_type = what;
c->periodic_box = img;
if (what & TRIG_COUNTER) {
c->data.trig.t_event = 0.0;
c->data.trig.loc.x = c->data.trig.loc.y = c->data.trig.loc.z = 0.0;
c->data.trig.orient = SHRT_MIN;
c->data.trig.listeners = NULL;
} else if (what & RXN_COUNTER) {
c->data.rx.n_rxn_at = c->data.rx.n_rxn_enclosed = 0.0;
} else if (what & MOL_COUNTER) {
c->data.move.n_at = c->data.move.n_enclosed = 0;
c->data.move.front_hits = c->data.move.back_hits = 0.0;
c->data.move.front_to_back = c->data.move.back_to_front = 0.0;
c->data.move.scaled_hits = 0.0;
}
return c;
}
/*************************************************************************
clean_region_lists:
Cleans the region and antiregion lists, annihilating any items which appear
on both lists.
In: my_sv: subvolume containing waypoint
p_all_regs: pointer to receive list of regions
p_all_antiregs: pointer to receive list of antiregions
Out: None
*************************************************************************/
static void clean_region_lists(struct subvolume *my_sv,
struct region_list **p_all_regs,
struct region_list **p_all_antiregs) {
if ((*p_all_regs)->next != NULL || (*p_all_antiregs)->next != NULL) {
struct region_list pre_sentry, pre_antisentry;
struct region_list *prl, *parl, *rl, *arl;
/* Sort by memory address to make mutual annihilation faster */
if ((*p_all_regs)->next != NULL)
*p_all_regs =
(struct region_list *)void_list_sort((struct void_list *)*p_all_regs);
if ((*p_all_antiregs)->next != NULL)
*p_all_antiregs = (struct region_list *)void_list_sort(
(struct void_list *)*p_all_antiregs);
/* Need previous entry to fix up list, so we'll make an imaginary one for
* 1st list element */
pre_sentry.next = *p_all_regs;
pre_antisentry.next = *p_all_antiregs;
prl = &pre_sentry;
parl = &pre_antisentry;
/* If we cross a region both ways, throw both out (once) */
for (rl = *p_all_regs, arl = *p_all_antiregs; rl != NULL && arl != NULL;
prl = rl, rl = rl->next, parl = arl, arl = arl->next) {
if (rl->reg == arl->reg) /* Mutual annihilation */
{
prl->next = rl->next;
parl->next = arl->next;
mem_put(my_sv->local_storage->regl, rl);
mem_put(my_sv->local_storage->regl, arl);
rl = prl;
arl = parl;
}
}
*p_all_regs = pre_sentry.next;
*p_all_antiregs = pre_antisentry.next;
} else if ((*p_all_regs)->reg == (*p_all_antiregs)->reg) {
/* Crossed one region both ways, toss them */
mem_put(my_sv->local_storage->regl, *p_all_regs);
mem_put(my_sv->local_storage->regl, *p_all_antiregs);
*p_all_regs = NULL;
*p_all_antiregs = NULL;
}
}
/*
* function updating the hit counts during diffusion of a 2d
* molecule if the latter hits a counted on region border on
* the target wall.
*
* in:
* ----
*
* hd_head : head to linked list of hit_data for target region
* current : wall we are currently on
* target : wall we are hitting and which is counted on
* sm : surface molecule which is diffusing
* direction: direction in which we are hitting the region border
* (0: outside in, 1: inside out)
* crossed : indicates if we crossed the region border or not
* (0: did not cross, 1: crossed)
*
* out:
* ----
*
* nothing
*
*
* side effects:
* -------------
*
* a new hit_data structure is created and appended to the linked
* list hd_head
*
* */
void update_hit_data(struct hit_data **hd_head, struct wall *current,
struct wall *target, struct surface_molecule *sm,
struct vector2 boundary_pos, int direction, int crossed) {
struct hit_data *hd;
hd = CHECKED_MALLOC_STRUCT(struct hit_data, "hit_data");
hd->count_regions = target->counting_regions;
hd->direction = direction;
hd->crossed = crossed;
hd->orientation = sm->orient;
uv2xyz(&boundary_pos, current, &(hd->loc));
hd->t = sm->t;
if (*hd_head == NULL) {
hd->next = NULL;
*hd_head = hd;
} else {
hd->next = *hd_head;
*hd_head = hd;
}
}
/* count_regions_list updates COUNTS and TRIGGERS for surface_molecule sm
* for all regions in the provided region_list */
void count_region_list(
struct volume *world,
struct region_list *regions,
struct surface_molecule *sm,
struct vector3 *where,
int count_hashmask,
int inc,
struct periodic_image *previous_box) {
struct counter **count_hash = world->count_hash;
for (struct region_list *rl = regions; rl != NULL; rl = rl->next) {
int hash_bin = (sm->properties->hashval + rl->reg->hashval) & count_hashmask;
for (struct counter *c = count_hash[hash_bin]; c != NULL; c = c->next) {
if (c->target == sm->properties && c->reg_type == rl->reg &&
(c->counter_type & ENCLOSING_COUNTER) == 0) {
if (c->counter_type & TRIG_COUNTER) {
// pass
/*c->data.trig.t_event = sm->t;*/
/*c->data.trig.orient = sm->orient;*/
/*fire_count_event(world, c, inc, where, REPORT_CONTENTS | REPORT_TRIGGER, sm->id); */
}
else if ((c->orientation == ORIENT_NOT_SET) ||
(c->orientation == sm->orient) || (c->orientation == 0)) {
if ((inc == 1) && (periodic_boxes_are_identical(
sm->periodic_box, c->periodic_box))) {
c->data.move.n_at++;
}
else if ((inc == -1) && (previous_box != NULL) &&
(periodic_boxes_are_identical(previous_box, c->periodic_box))) {
c->data.move.n_at--;
}
}
}
}
}
}
| C |
3D | mcellteam/mcell | src/mcell_misc.h | .h | 1,480 | 46 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "config.h"
#include "mcell_init.h"
#include "mcell_structs.h"
void mcell_print_version(void);
void mcell_print_usage(const char *executable_name);
void mcell_print_stats(void);
void mcell_dump_state(MCELL_STATE *state);
int mcell_argparse(int argc, char **argv, MCELL_STATE *state);
struct num_expr_list *mcell_copysort_numeric_list(struct num_expr_list *head);
void mcell_sort_numeric_list(struct num_expr_list *head);
void mcell_free_numeric_list(struct num_expr_list *nel);
MCELL_STATUS mcell_generate_range(struct num_expr_list_head *list, double start,
double end, double step);
int mcell_generate_range_singleton(struct num_expr_list_head *lh, double value);
// Find an include file based on the path of the currently parsed file
char *mcell_find_include_file(char const *path, char const *cur_path);
// XXX this is a temporary hack to be able to print in mcell.c
// since mcell disables regular printf
void mcell_print(const char *message);
| Unknown |
3D | mcellteam/mcell | src/c_vector.cpp | .cpp | 1,351 | 57 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
// this is an auxiliary file that provides std::vector functionality, used in viz_output.c
#include <vector>
#include <algorithm>
#include "c_vector.h"
#include "mcell_structs.h"
using namespace std;
typedef vector<void*> stl_vector_t;
c_vector_t* vector_create() {
return new stl_vector_t();
}
void vector_push_back(c_vector_t* v, void* a) {
((stl_vector_t*)v)->push_back(a);
}
unsigned long long vector_get_size(c_vector_t* v) {
return ((stl_vector_t*)v)->size();
}
void* vector_at(c_vector_t* v, unsigned long long i) {
return ((stl_vector_t*)v)->at(i);
}
void vector_delete(c_vector_t* v) {
delete (stl_vector_t*)v;
}
void vector_sort_by_mol_id(c_vector_t* v) {
stl_vector_t& vec = *(stl_vector_t*)v;
sort(vec.begin(), vec.end(),
[](const void* a, const void* b) -> bool
{
return ((abstract_molecule*)a)->id < ((abstract_molecule*)b)->id;
});
}
| C++ |
3D | mcellteam/mcell | src/mdlparse_util.h | .h | 42,706 | 943 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef MDLPARSE_UTIL_H
#define MDLPARSE_UTIL_H
#include "vector.h"
#include "mcell_structs.h"
#include "mcell_react_out.h"
#include "mcell_reactions.h"
#include "mcell_objects.h"
#include "mdlparse_aux.h"
/* ====================================
* Caveat lector: Most of the functions in this file (and the corresponding .c
* file) are designed to be called from the grammar, and take care of cleaning
* up memory allocation. If you are in doubt about whether you can still use
* any pointers you've passed in check the function source code to be certain.
* In most cases, the answer is "no".
* ====================================
*/
/* Strips the quotes from a quoted string, freeing the original. */
char *mdl_strip_quotes(char *in);
/* Concatenates two strings, freeing the original strings. */
char *mdl_strcat(char *s1, char *s2);
/* Duplicates a string. */
char *mdl_strdup(char const *s1);
/* Display a warning message about something encountered during the
* parse process. */
void mdl_warning(struct mdlparse_vars *parse_state, char const *fmt, ...)
PRINTF_FORMAT(2);
/* Check that the speficied file mode string is valid for an fopen statement.
*/
int mdl_valid_file_mode(struct mdlparse_vars *parse_state, const char *mode);
/* Error-reporting version of log */
int mdl_expr_log(struct mdlparse_vars *parse_state, double in, double *out);
/* Error-reporting version of log10 */
int mdl_expr_log10(struct mdlparse_vars *parse_state, double in, double *out);
/* Error-reporting version of MOD */
int mdl_expr_mod(struct mdlparse_vars *parse_state, double in, double divisor,
double *out);
/* Error-reporting version of division operator */
int mdl_expr_div(struct mdlparse_vars *parse_state, double in, double divisor,
double *out);
/* Error-reporting version of exponentiation operator */
int mdl_expr_pow(struct mdlparse_vars *parse_state, double in, double exponent,
double *out);
/* Get a uniform random number */
double mdl_expr_rng_uniform(struct mdlparse_vars *parse_state);
/* Round a value off to n digits */
double mdl_expr_roundoff(double in, int ndigits);
/* Turn a string into a double */
int mdl_expr_string_to_double(struct mdlparse_vars *parse_state, char *str,
double *out);
/* Add a new file handle to the symbol table. */
struct sym_entry *mdl_new_filehandle(struct mdlparse_vars *parse_state,
char *name);
/* Process an fopen statement, opening a new file handle. */
int mdl_fopen(struct mdlparse_vars *parse_state, struct sym_entry *filesym,
char *name, char *mode);
/* Process an fclose statement, closing an existing file handle. */
int mdl_fclose(struct mdlparse_vars *parse_state, struct sym_entry *filesym);
/* Create a new double argument for a printf argument list. */
struct arg *mdl_new_printf_arg_double(double d);
/* Create a new string argument for a printf argument list. */
struct arg *mdl_new_printf_arg_string(char const *str);
/* Expands C-style escape sequences in the string. */
char *mdl_expand_string_escapes(char *in);
/* printf-like formatting of MDL arguments. Prints to the defined err_file. */
int mdl_printf(struct mdlparse_vars *parse_state, char *fmt,
struct arg *arg_head);
/* fprintf-like formatting of MDL arguments. */
int mdl_fprintf(struct mdlparse_vars *parse_state, struct file_stream *filep,
char *fmt, struct arg *arg_head);
/* (expression-form) sprintf-like formatting of MDL arguments. */
char *mdl_string_format(struct mdlparse_vars *parse_state, char *fmt,
struct arg *arg_head);
/* sprintf-like formatting of MDL arguments. */
int mdl_sprintf(struct mdlparse_vars *parse_state, struct sym_entry *assign_var,
char *fmt, struct arg *arg_head);
/* strtime-like formatting of current time. */
int mdl_fprint_time(struct mdlparse_vars *parse_state, struct sym_entry *filep,
char *fmt);
/* strtime-like formatting of current time. Prints to the defined err_file. */
void mdl_print_time(struct mdlparse_vars *parse_state, char *fmt);
/* Generate a num_expr_list containing the numeric values from start to end,
* incrementing by step. */
int mdl_generate_range(struct mdlparse_vars *parse_state,
struct num_expr_list_head *list, double start,
double end, double step);
/* Generate a numeric list containing a single value. */
int mdl_generate_range_singleton(struct num_expr_list_head *lh, double value);
/* Add a value to a numeric list. */
int mdl_add_range_value(struct num_expr_list_head *lh, double value);
#ifdef DEBUG
/* Display a human-readable representation of the specified array. */
void mdl_debug_dump_array(struct num_expr_list *nel);
#else
#define mdl_debug_dump_array(x) /* do nothing */
#endif
/* Create a 3-D vector from a numeric array. */
struct vector3 *mdl_point(struct mdlparse_vars *parse_state,
struct num_expr_list_head *vals);
/* Create a 3-D vector equal to s*[1, 1, 1] for some scalar s. */
struct vector3 *mdl_point_scalar(double val);
/* Get a named variable if it exists, or create it if it doesn't. */
struct sym_entry *mdl_get_or_create_variable(struct mdlparse_vars *parse_state,
char *name);
/* Assign a "double" value to a variable, freeing any previous value. */
int mdl_assign_variable_double(struct mdlparse_vars *parse_state,
struct sym_entry *sym, double value);
/* Assign a string value to a variable, freeing any previous value. */
int mdl_assign_variable_string(struct mdlparse_vars *parse_state,
struct sym_entry *sym, char *value);
/* Assign an array value to a variable, freeing any previous value. */
int mdl_assign_variable_array(struct mdlparse_vars *parse_state,
struct sym_entry *sym,
struct num_expr_list *value);
/* Assign one variable value to another variable, freeing any previous value.
*/
int mdl_assign_variable(struct mdlparse_vars *parse_state,
struct sym_entry *sym, struct sym_entry *value);
/* Set all notification levels to a particular value. */
void mdl_set_all_notifications(struct volume *vol, byte notify_value);
/* Set the iteration report frequency. */
int mdl_set_iteration_report_freq(struct mdlparse_vars *parse_state,
long long interval);
/* Set all warning levels to a particular value. */
void mdl_set_all_warnings(struct volume *vol, byte warning_level);
/* Set the lifetime warning threshold. */
int mdl_set_lifetime_warning_threshold(struct mdlparse_vars *parse_state,
long long lifetime);
/* Set the missed reaction warning threshold. */
int mdl_set_missed_reaction_warning_threshold(struct mdlparse_vars *parse_state,
double rxfrac);
/* Set the global timestep for the simulation. */
int mdl_set_time_step(struct mdlparse_vars *parse_state, double step);
/* Set the maximum timestep for the simulation. */
int mdl_set_max_time_step(struct mdlparse_vars *parse_state, double step);
/* Set the global space step for the simulation. */
int mdl_set_space_step(struct mdlparse_vars *parse_state, double step);
/* Set the number of iterations for the simulation. */
int mdl_set_num_iterations(struct mdlparse_vars *parse_state,
long long numiters);
/* Set the number of radial directions. */
int mdl_set_num_radial_directions(struct mdlparse_vars *parse_state,
int numdirs);
/* Set the number of radial subdivisions. */
int mdl_set_num_radial_subdivisions(struct mdlparse_vars *parse_state,
int numdivs);
/* Set the interaction radius. */
int mdl_set_interaction_radius(struct mdlparse_vars *parse_state,
double interaction_radius);
/* Set the effector grid density. */
int mdl_set_grid_density(struct mdlparse_vars *parse_state, double density);
/* Schedule an asynchronous checkpoint. */
int mdl_set_realtime_checkpoint(struct mdlparse_vars *parse_state,
long duration, int cont_after_cp);
/* Set the input checkpoint file to use. */
int mdl_set_checkpoint_infile(struct mdlparse_vars *parse_state, char *name);
/* Set the output checkpoint file to use. */
int mdl_set_checkpoint_outfile(struct mdlparse_vars *parse_state, char *name);
/* Set if intermediate checkpoint files should be kept */
int mdl_keep_checkpoint_files(struct mdlparse_vars *parse_state, int keepFiles);
/* Set the number of iterations between checkpoints. */
int mdl_set_checkpoint_interval(struct mdlparse_vars *parse_state,
long long iters, int continueAfterChkpt);
/* Set the partitioning in a particular dimension. */
int mdl_set_partition(struct mdlparse_vars *parse_state, int dim,
struct num_expr_list_head *head);
/* Starts creating a new object. This function has side effects, and must be
* paired with a call to mdl_finish_object(parse_state) */
struct sym_entry *mdl_start_object(struct mdlparse_vars *parse_state,
char *name);
/* "Finishes" a new object, undoing the state changes that occurred when the
* object was "started".
*/
void mdl_finish_object(struct mdlparse_vars *parse_state);
/* Adds the first element to an empty object list. */
void mdl_object_list_singleton(struct object_list *head, struct geom_object *objp);
/* Adds an element to an object list. */
void mdl_add_object_to_list(struct object_list *head, struct geom_object *objp);
/* Find an existing object or print an error message if the object isn't found.
*/
struct sym_entry *mdl_existing_object(struct mdlparse_vars *parse_state,
char *name);
/* Find a list of existing objects matching a particular wildcard. */
struct sym_table_list *
mdl_existing_objects_wildcard(struct mdlparse_vars *parse_state,
char *wildcard);
/* Find an existing region or print an error message if it isn't found. */
struct sym_entry *mdl_existing_region(struct mdlparse_vars *parse_state,
struct sym_entry *obj_symp, char *name);
/* Find an existing molecule species, or print an error message if it isn't
* found. */
struct sym_entry *mdl_existing_molecule(struct mdlparse_vars *parse_state,
char *name);
/* Turn a single symbol into a singleton symbol list. */
struct sym_table_list *
mdl_singleton_symbol_list(struct mdlparse_vars *parse_state,
struct sym_entry *sym);
/* Find an existing molecule species, and return it in a singleton list, or
* print an error message if it isn't found. */
struct sym_table_list *
mdl_existing_molecule_list(struct mdlparse_vars *parse_state, char *name);
/* Find a list of all molecule species matching the specified wildcard. Print
* an error message if it doesn't match any. */
struct sym_table_list *
mdl_existing_molecules_wildcard(struct mdlparse_vars *parse_state,
char *wildcard);
/* Find an existing surface molecule species, or print an error message if it
* isn't found, or isn't a surface molecule. */
struct sym_entry *
mdl_existing_surface_molecule(struct mdlparse_vars *parse_state, char *name);
/* Find an existing surface class species, or print an error message if it
* isn't found, or isn't a surface class. */
struct sym_entry *mdl_existing_surface_class(struct mdlparse_vars *parse_state,
char *name);
/* Find a named variable if it exists, or print an error if it does not. */
struct sym_entry *mdl_existing_variable(struct mdlparse_vars *parse_state,
char *name);
/* Find an existing array symbol, or print an error message if it isn't found.
*/
struct sym_entry *mdl_existing_array(struct mdlparse_vars *parse_state,
char *name);
/* Find a named numeric variable if it exists, or print an error message if it
* isn't found. */
struct sym_entry *mdl_existing_double(struct mdlparse_vars *parse_state,
char *name);
/* Find a named string variable if it exists, or print an error message if it
* isn't found. */
struct sym_entry *mdl_existing_string(struct mdlparse_vars *parse_state,
char *name);
/* Get a named numeric or array variable if it exists. Print an error message
* if it isn't found. */
struct sym_entry *mdl_existing_num_or_array(struct mdlparse_vars *parse_state,
char *name);
/* Find an existing named reaction pathway or molecule, or print an error
* message if it isn't found. */
struct sym_entry *
mdl_existing_rxn_pathname_or_molecule(struct mdlparse_vars *parse_state,
char *name);
/* Find an existing reaction pathway or release pattern, or print an error
* message if it isn't found, or if the name could refer to either a release
* pattern or a reaction pathway.
*/
struct sym_entry *
mdl_existing_release_pattern_or_rxn_pathname(struct mdlparse_vars *parse_state,
char *name);
/* Find an existing file stream or print an error message if it isn't found. */
struct sym_entry *mdl_existing_file_stream(struct mdlparse_vars *parse_state,
char *name);
/* Find all mesh objects (polygons and boxes) that match a given wildcard. */
struct sym_table_list *mdl_meshes_by_wildcard(struct mdlparse_vars *parse_state,
char *wildcard);
/* Apply a rotation to the given transformation matrix. */
int mdl_transform_rotate(struct mdlparse_vars *parse_state, double (*mat)[4],
struct vector3 *axis, double angle);
/* Deep copy an object. */
int mdl_deep_copy_object(struct mdlparse_vars *parse_state,
struct geom_object *dst_obj, struct geom_object *src_obj);
/* Prepare a region description for use in the simulation by creating a
* membership bitmask on the region object. */
int mdl_normalize_elements(struct mdlparse_vars *parse_state,
struct region *reg, int existing);
/* Finalizes the polygonal structure of the box, normalizing all regions. */
int mdl_triangulate_box_object(struct mdlparse_vars *parse_state,
struct sym_entry *box_sym,
struct polygon_object *pop,
double box_aspect_ratio);
/* Check that the specified diffusion constant is valid, correcting it if
* appropriate. */
int mdl_check_diffusion_constant(struct mdlparse_vars *parse_state, double *d);
/* Finish the creation of a series of molecules, undoing any state changes we
* made during the creation of the molecules. */
void mdl_print_species_summary(MCELL_STATE *state,
struct mcell_species_spec *species);
void mdl_print_species_summaries(struct volume *state,
struct parse_mcell_species_list_item *mols);
int mdl_add_to_species_list(struct parse_mcell_species_list *list,
struct mcell_species_spec *spec);
/* Start parsing the innards of a release site. */
int mdl_start_release_site(struct mdlparse_vars *parse_state,
struct sym_entry *symp, int shape);
/* Finish parsing the innards of a release site. */
struct geom_object *mdl_finish_release_site(struct mdlparse_vars *parse_state,
struct sym_entry *symp);
/* Validate a release site. */
int mdl_is_release_site_valid(struct mdlparse_vars *parse_state,
struct release_site_obj *rsop);
/* Set the geometry for a particular release site to be a region expression. */
int mdl_set_release_site_geometry_region(struct mdlparse_vars *parse_state,
struct release_site_obj *rsop,
struct geom_object *objp,
struct release_evaluator *re);
/* Set the geometry for a particular release site to be an entire object. */
int
mdl_set_release_site_geometry_object(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
struct geom_object *obj_ptr);
/* Set the molecule to be released from this release site. */
int mdl_set_release_site_molecule(struct mdlparse_vars *parse_state,
struct release_site_obj *rsop,
struct mcell_species *mol_type);
/* Set the diameter of a release site. */
int mdl_set_release_site_diameter(struct mdlparse_vars *parse_state,
struct release_site_obj *rsop, double diam);
/* Set the diameter of the release site along the X, Y, and Z axes. */
int mdl_set_release_site_diameter_array(struct mdlparse_vars *parse_state,
struct release_site_obj *rsop,
int n_diams,
struct num_expr_list *diams,
double factor);
/* Set the diameters of the release site along the X, Y, and Z axes from a
* variable, either scalar or vector. */
int mdl_set_release_site_diameter_var(struct mdlparse_vars *parse_state,
struct release_site_obj *rsop,
double factor, struct sym_entry *symp);
int mdl_set_release_site_periodic_box(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
struct vector3 *periodic_box);
/* Set the release probability for a release site. */
int mdl_set_release_site_probability(struct mdlparse_vars *parse_state,
struct release_site_obj *rsop,
double prob);
/* Set the release pattern to be used by a particular release site. */
int mdl_set_release_site_pattern(struct mdlparse_vars *parse_state,
struct release_site_obj *rsop,
struct sym_entry *pattern);
/* */
int mdl_set_release_site_graph_pattern(struct mdlparse_vars *parse_state,
struct release_site_obj *rel_site_obj_ptr,
char* graph_pattern);
/* Set the molecule positions for a LIST release. */
int mdl_set_release_site_molecule_positions(
struct mdlparse_vars *parse_state, struct release_site_obj *rsop,
struct release_single_molecule_list *list);
/* Create a mew single molecule release position for a LIST release site. */
struct release_single_molecule *
mdl_new_release_single_molecule(struct mdlparse_vars *parse_state,
struct mcell_species *mol_type,
struct vector3 *pos);
/* Set a release quantity from this release site based on a fixed concentration
* within the release-site's area. */
int mdl_set_release_site_concentration(struct mdlparse_vars *parse_state,
struct release_site_obj *rsop,
double conc);
/* Set an item to be the sole element of a vertex list. */
void mdl_vertex_list_singleton(struct vertex_list_head *head,
struct vertex_list *item);
/* Append a vertex to a list. */
void mdl_add_vertex_to_list(struct vertex_list_head *head,
struct vertex_list *item);
/* Allocate an item for a vertex list. */
struct vertex_list *mdl_new_vertex_list_item(struct vector3 *vertex);
/* Set an item to be the sole element of an element connection list. */
void
mdl_element_connection_list_singleton(struct element_connection_list_head *head,
struct element_connection_list *item);
/* Append an element connection to a list. */
void
mdl_add_element_connection_to_list(struct element_connection_list_head *head,
struct element_connection_list *item);
/* Create an element connection (essentially a triplet of vertex indices). */
struct element_connection_list *
mdl_new_element_connection(struct mdlparse_vars *parse_state,
struct num_expr_list_head *indices);
/* Create a tetrahedral element connection (essentially a quadruplet of vertex
* indices). */
struct element_connection_list *
mdl_new_tet_element_connection(struct mdlparse_vars *parse_state,
struct num_expr_list_head *indices);
/* Create a new polygon list object. */
struct geom_object *
mdl_new_polygon_list(struct mdlparse_vars *parse_state, char *obj_name,
int n_vertices, struct vertex_list *vertices,
int n_connections,
struct element_connection_list *connections);
/* Finalize the polygon list, cleaning up any state updates that were made when
* we started creating the polygon. */
int mdl_finish_polygon_list(struct mdlparse_vars *parse_state,
struct geom_object *obj_ptr);
/* Create a new voxel list object. */
struct voxel_object *
mdl_new_voxel_list(struct mdlparse_vars *parse_state, struct sym_entry *sym,
int n_vertices, struct vertex_list *vertices,
int n_connections,
struct element_connection_list *connections);
struct polygon_object *mdl_create_periodic_box(
struct mdlparse_vars *parse_state,
struct vector3 *llf,
struct vector3 *urb,
bool isPeriodicX,
bool isPeriodicY,
bool isPeriodicZ);
int mdl_finish_periodic_box(struct mdlparse_vars *parse_state);
/* Create a new box object, with particular corners. */
struct polygon_object *mdl_new_box_object(struct mdlparse_vars *parse_state,
struct sym_entry *sym,
struct vector3 *llf,
struct vector3 *urb);
/* Finalize the box object, cleaning up any state updates that were made when
* we started creating the box. */
int mdl_finish_box_object(struct mdlparse_vars *parse_state,
struct sym_entry *symp);
/* Create a named region on an object. */
struct region *mdl_create_region(struct mdlparse_vars *parse_state,
struct geom_object *objp, const char *name);
/* Get a region on an object, creating it if it does not exist yet. */
struct region *mdl_get_region(struct mdlparse_vars *parse_state,
struct geom_object *objp, const char *name);
/* Begin construction of a region on an existing object. */
int mdl_start_existing_obj_region_def(struct mdlparse_vars *parse_state,
struct sym_entry *obj_symp);
/* Append elements to an element list. */
void mdl_add_elements_to_list(struct element_list_head *list,
struct element_list *head,
struct element_list *tail);
/* Marks elements as being excluded, rather than included (the default). */
void mdl_set_elements_to_exclude(struct element_list *els);
/* Create a new element list for a region description. */
struct element_list *mdl_new_element_list(struct mdlparse_vars *parse_state,
unsigned int begin, unsigned int end);
/* Create a new element list for a region description based on a side name. */
struct element_list *mdl_new_element_side(struct mdlparse_vars *parse_state,
unsigned int side);
/* Create a new element list for a "previous region" include/exclude statement.
*/
struct element_list *mdl_new_element_previous_region(
struct mdlparse_vars *parse_state, struct geom_object *objp,
struct region *rp_container, char *name_region_referent, int exclude);
/* Allocate a new region element list item for an include/exclude PATCH
* statement. */
struct element_list *mdl_new_element_patch(struct mdlparse_vars *parse_state,
struct polygon_object *poly,
struct vector3 *llf,
struct vector3 *urb, int exclude);
/* Set the elements for a region, normalizing the region if it's on a polygon
* list object. */
int mdl_set_region_elements(struct mdlparse_vars *parse_state,
struct region *rgn, struct element_list *elements,
int normalize_now);
/* Create a new named reaction pathway name structure. */
struct sym_entry *mdl_new_rxn_pathname(struct mdlparse_vars *parse_state,
char *name);
/* Adds an effector (or list of effectors) to a region. These effectors will
* be placed on the surface at initialization time. */
void mdl_add_surf_mol_to_region(struct region *rgn, struct sm_dat_list *lst);
/* Set the surface class of this region, possibly inheriting the viz_value. */
void mdl_set_region_surface_class(struct mdlparse_vars *parse_state,
struct region *rgn, struct sym_entry *scsymp);
/****************************************************************
* Reaction output
***************************************************************/
/* Finalizes a reaction data output block, checking for errors, and allocating
* the output buffer. */
int mdl_output_block_finalize(struct mdlparse_vars *parse_state,
struct output_block *obp);
/* Populate an output set. */
struct output_set *mdl_populate_output_set(struct mdlparse_vars *parse_state,
char *comment, int exact_time,
struct output_column *col_head,
int file_flags, char *outfile_name);
/* Construct and add an output block to the world. */
int mdl_add_reaction_output_block_to_world(struct mdlparse_vars *parse_state,
int buffer_size,
struct output_times_inlist *otimes,
struct output_set_list *osets);
/* Joins two subtrees into a reaction data output expression tree, with a
* specified operation. */
struct output_expression *mdl_join_oexpr_tree(struct mdlparse_vars *parse_state,
struct output_expression *left,
struct output_expression *right,
char oper);
/* Converts an output expression tree generated from a wildcard into a
* summation expression tree. */
struct output_expression *mdl_sum_oexpr(struct output_expression *expr);
/* Creates a constant output expression for reaction data output. */
struct output_expression *
mdl_new_oexpr_constant(struct mdlparse_vars *parse_state, double value);
/* Generates a reaction data output expression from the first count syntax form
* (simple molecule, unquoted, no orientation). */
struct output_expression *mdl_count_syntax_1(struct mdlparse_vars *parse_state,
struct sym_entry *what,
struct sym_entry *where,
int hit_spec, int count_flags);
/* Generates a reaction data output expression from the second count syntax
* form (simple molecule, unquoted, orientation in braces). */
struct output_expression *mdl_count_syntax_2(struct mdlparse_vars *parse_state,
struct sym_entry *mol_type,
short orient,
struct sym_entry *where,
int hit_spec, int count_flags);
/* Generates a reaction data output expression from the third count syntax form
* (quoted string, possibly a wildcard, possibly an oriented molecule). */
struct output_expression *mdl_count_syntax_3(struct mdlparse_vars *parse_state,
char *what,
struct sym_entry *where,
int hit_spec, int count_flags);
struct output_expression *mdl_count_syntax_periodic_1(struct mdlparse_vars *parse_state,
struct sym_entry *what, struct sym_entry *where, struct vector3 *periodicBox,
int hit_spec, int count_flags);
struct output_expression *mdl_count_syntax_periodic_2(
struct mdlparse_vars *parse_state,
struct sym_entry *mol_type,
short orient,
struct sym_entry *where,
struct vector3 *periodicBox,
int hit_spec,
int count_flags);
struct output_expression *mdl_count_syntax_periodic_3(
struct mdlparse_vars *parse_state,
char *what,
struct sym_entry *where,
struct vector3 *periodicBox,
int hit_spec,
int count_flags);
/* Prepare a single count expression for inclusion in an output set. */
int mdl_single_count_expr(struct mdlparse_vars *parse_state,
struct output_column_list *list,
struct output_expression *expr, char *custom_header);
/****************************************************************
* Viz output
***************************************************************/
/* Build a new VIZ output block, containing parameters for an output set for
* visualization. */
int mdl_new_viz_output_block(struct mdlparse_vars *parse_state);
/* Set the mode for a new VIZ output block. */
int mdl_set_viz_mode(struct viz_output_block *vizblk, int mode);
/* Set the molecule format for a new VIZ output block. */
int mdl_set_viz_molecule_format(struct mdlparse_vars *parse_state,
struct viz_output_block *vizblk, int format);
/* Set the filename prefix for a new VIZ output block. */
int mdl_set_viz_filename_prefix(struct mdlparse_vars *parse_state,
struct viz_output_block *vizblk,
char *filename);
/* Error-checking wrapper for a specified visualization state. */
int mdl_viz_state(struct mdlparse_vars *parse_state, int *target, double value);
/* Sets a flag on all of the listed species, requesting that they be visualized.
*/
int mdl_set_viz_include_molecules(struct mdlparse_vars *parse_state,
struct viz_output_block *vizblk,
struct sym_table_list *list, int viz_state);
/* Sets a flag on a viz block, requesting that all species be visualized. */
int mdl_set_viz_include_all_molecules(struct viz_output_block *vizblk,
int viz_state);
/* Adds some new molecule output frames to a list. */
int mdl_new_viz_mol_frames(struct mdlparse_vars *parse_state,
struct viz_output_block *vizblk,
struct frame_data_list_head *frames, int time_type,
int mol_item_type,
struct num_expr_list_head *timelist);
/* Build a list of times for VIZ output, one timepoint per iteration in the
* simulation. */
int mdl_new_viz_all_times(struct mdlparse_vars *parse_state,
struct num_expr_list_head *list);
/* Build a list of iterations for VIZ output, one for each iteration in the
* simulation. */
int mdl_new_viz_all_iterations(struct mdlparse_vars *parse_state,
struct num_expr_list_head *list);
/* Set the viz_state value for a molecular species. */
int mdl_set_molecule_viz_state(struct viz_output_block *vizblk,
struct species *specp, int viz_state);
/* Set the viz_state for a particular region. */
int mdl_set_region_viz_state(struct mdlparse_vars *parse_state,
struct viz_output_block *vizblk, struct region *rp,
int viz_state);
/****************************************************************
* Volume output
***************************************************************/
/* Create a new volume output request. */
struct volume_output_item *mdl_new_volume_output_item(
struct mdlparse_vars *parse_state, char *filename_prefix,
struct species_list *molecules, struct vector3 *location,
struct vector3 *voxel_size, struct vector3 *voxel_count,
struct output_times *ot);
/* Create new default output timing for volume output. */
struct output_times *
mdl_new_output_times_default(struct mdlparse_vars *parse_state);
/* Create new "step" output timing for volume output. */
struct output_times *
mdl_new_output_times_step(struct mdlparse_vars *parse_state, double step);
/* Create new "iteration list" output timing for volume output. */
struct output_times *
mdl_new_output_times_iterations(struct mdlparse_vars *parse_state,
struct num_expr_list_head *iters);
/* Create new "time list" output timing for volume output. */
struct output_times *
mdl_new_output_times_time(struct mdlparse_vars *parse_state,
struct num_expr_list_head *times);
/****************************************************************
* Release patterns
***************************************************************/
/* Create a new release pattern. There must not yet be a release pattern with
* the given name. */
struct sym_entry *mdl_new_release_pattern(struct mdlparse_vars *parse_state,
char *name);
/* Fill in the details of a release pattern. */
int mdl_set_release_pattern(struct mdlparse_vars *parse_state,
struct sym_entry *rpat_sym,
struct release_pattern *rpat_data);
/****************************************************************
* Molecules
***************************************************************/
/* Create a new species. There must not yet be a molecule or named reaction
* pathway with the supplied name. */
struct sym_entry *mdl_new_mol_species(struct mdlparse_vars *parse_state,
char *name);
/* Assemble a molecule species from its component pieces. */
struct mcell_species_spec *mdl_create_species(struct mdlparse_vars *parse_state,
char *name, double D, int is_2d,
double custom_time_step,
int target_only,
double max_step_length,
int external_molecule);
/****************************************************************
* BNGL Molecule Spatial Structure
***************************************************************/
/* Create a new BNGL molecule symbol. There must not yet be a BNGL molecule
* with the supplied name. */
struct sym_entry *mdl_new_bngl_molecule(struct mdlparse_vars *parse_state,
char *name);
/* Create a new BNGL component symbol. There must not yet be a BNGL component
* with the supplied name associated with the BNGL molecule. */
struct mol_comp_ss *mdl_add_bngl_component(struct mdlparse_vars *parse_state,
struct sym_entry *bngl_mol_sym,
char *component_name);
/* Set Transformation Matrix of BNGL component. */
void mdl_set_bngl_component_layout(struct mdlparse_vars *parse_state,
struct mol_comp_ss *mol_comp_ssp,
double loc_x,
double loc_y,
double loc_z,
double rot_axis_x,
double rot_axis_y,
double rot_axis_z,
double rot_angle);
/****************************************************************
* Reactions, surface classes
***************************************************************/
/* Check whether the reaction rate is valid. */
int mdl_valid_rate(struct mdlparse_vars *parse_state,
struct reaction_rate *rate);
/* Set the reactant/product list to contain a single item. */
int mdl_reaction_player_singleton(struct mdlparse_vars *parse_state,
struct mcell_species_list *list,
struct mcell_species *spec);
/* Add a single item to a reactant/product player list. */
int mdl_add_reaction_player(struct mdlparse_vars *parse_state,
struct mcell_species_list *list,
struct mcell_species *spec);
/* Set a reaction rate from a variable. */
int mdl_reaction_rate_from_var(struct mdlparse_vars *parse_state,
struct reaction_rate *rate,
struct sym_entry *symp);
/* Assemble a standard reaction from its component parts. */
struct mdlparse_vars *mdl_assemble_reaction(struct mdlparse_vars *parse_state,
struct mcell_species *reactants,
struct mcell_species *surface_class,
struct reaction_arrow *react_arrow,
struct mcell_species *products,
struct reaction_rates *rate,
struct sym_entry *pathname);
/* Assemble a surface reaction from its component parts. */
struct mdlparse_vars *
mdl_assemble_surface_reaction(struct mdlparse_vars *parse_state,
int reaction_type, struct species *surface_class,
struct sym_entry *reactant_sym, short orient);
/* Assemble a concentration or flux clamp reaction from its component parts. */
struct mdlparse_vars *mdl_assemble_clamp_reaction(
struct mdlparse_vars *parse_state, struct species *surface_class,
struct sym_entry *mol_sym, short orient, int clamp_type, double clamp_value);
/* Start a surface class declaration. */
void mdl_start_surface_class(struct mdlparse_vars *parse_state,
struct sym_entry *symp);
/* Finish a surface class declaration. Undoes side effects from
* mdl_start_surface_class. */
void mdl_finish_surface_class(struct mdlparse_vars *parse_state);
/* Create a new effector data for surface molecule initialization. */
struct sm_dat *mdl_new_surf_mol_data(struct mdlparse_vars *parse_state,
struct mcell_species *eff_info,
double quant);
int warn_about_high_rates(struct mdlparse_vars *parse_state, FILE *warn_file,
int rate_warn, int print_once);
void alphabetize_pathway(struct pathway *path, struct rxn *reaction);
void check_duplicate_special_reactions(struct pathway *path);
int set_product_geometries(struct pathway *path, struct rxn *rx,
struct product *prod);
int scale_probabilities(struct pathway *path, struct rxn *rx,
struct mdlparse_vars *parse_state, double pb_factor);
void add_surface_reaction_flags(struct mdlparse_vars *parse_state);
void free_vertex_list(struct vertex_list *vlp);
/**********************************************************************
*** helper functions for release sites creation
**********************************************************************/
// Adds a release molecule descriptor to a list.
void
add_release_single_molecule_to_list(struct release_single_molecule_list *list,
struct release_single_molecule *mol);
// Populates a list with a single LIST release molecule descriptor.
void
release_single_molecule_singleton(struct release_single_molecule_list *list,
struct release_single_molecule *mol);
/* Set a release quantity from this release site based on a fixed density
* within the release-site's area. */
int set_release_site_density(struct release_site_obj *rel_site_obj_ptr,
double dens);
/* Set a release quantity from this release site based on a fixed concentration
* in a sphere of a gaussian-distributed diameter with a particular mean and
* std. deviation. */
void set_release_site_volume_dependent_number(
struct release_site_obj *rel_site_obj_ptr, double mean, double stdev,
double conc);
/****************************************************************************
*** helper function for object creation
****************************************************************************/
void transform_translate(MCELL_STATE *state, double (*mat)[4],
struct vector3 *xlat);
void transform_scale(double (*mat)[4], struct vector3 *scale);
int transform_rotate(double (*mat)[4], struct vector3 *axis, double angle);
void check_regions(struct geom_object *rootInstance, struct geom_object *child_head);
int finish_polygon_list(struct geom_object *obj_ptr,
struct object_creation *obj_creation);
struct geom_object *start_object(MCELL_STATE *state,
struct object_creation *obj_creation,
char *name,
int *error_code);
#endif // MDLPARSE_UTIL_H
| Unknown |
3D | mcellteam/mcell | src/react.h | .h | 11,259 | 252 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
//#include "sym_table.h"
#include <stdbool.h>
#include <nfsim_c.h>
#include <nfsim_c_structs.h>
#include "mcell_structs.h"
enum {
PRODUCT_FLAG_NOT_SET,
PRODUCT_FLAG_USE_UV_LOC,
PRODUCT_FLAG_USE_REACA_UV,
PRODUCT_FLAG_USE_REACB_UV,
PRODUCT_FLAG_USE_REACC_UV,
PRODUCT_FLAG_USE_RANDOM
};
enum {
PLAYER_SURF_MOL = 'g',
PLAYER_VOL_MOL = 'm',
PLAYER_WALL = 'w',
PLAYER_NONE = '\0',
};
#define IS_SURF_MOL(g) ((g) != NULL && ((g)->properties->flags & ON_GRID))
/* In react_trig.c */
struct rxn *trigger_unimolecular(struct rxn **reaction_hash, int hashsize,
u_int hash, struct abstract_molecule *reac);
int trigger_surface_unimol(struct rxn **reaction_hash, int rx_hashsize,
struct species *all_mols,
struct species *all_volume_mols,
struct species *all_surface_mols,
struct abstract_molecule *reac, struct wall *w,
struct rxn **matching_rxns);
int trigger_bimolecular_preliminary(struct rxn **reaction_hash, int hashsize,
u_int hashA, u_int hashB,
struct species *reacA,
struct species *reacB);
int process_bimolecular(struct abstract_molecule *reacA,
struct abstract_molecule *reacB,
struct rxn* inter,
short orientA,
short orientB,
struct rxn **matching_rxns,
int num_matching_rxns);
int trigger_bimolecular(struct rxn **reaction_hash, int rx_hashsize,
u_int hashA, u_int hashB,
struct abstract_molecule *reacA,
struct abstract_molecule *reacB, short orientA,
short orientB, struct rxn **matching_rxns);
int trigger_trimolecular(struct rxn **reaction_hash, int rx_hashsize,
u_int hashA, u_int hashB, u_int hashC,
struct species *reacA, struct species *reacB,
struct species *reacC, int orientA, int orientB,
int orientC, struct rxn **matching_rxns);
int trigger_intersect(struct rxn **reaction_hash, int rx_hashsize,
struct species *all_mols, struct species *all_volume_mols,
struct species *all_surface_mols, u_int hashA,
struct abstract_molecule *reacA, short orientA,
struct wall *w, struct rxn **matching_rxns,
int allow_rx_transp, int allow_rx_reflec,
int allow_rx_absorb_reg_border);
void compute_lifetime(struct volume *state,
struct rxn *r,
struct abstract_molecule *am);
int check_for_unimolecular_reaction(struct volume *state,
struct abstract_molecule *am);
struct rxn *pick_unimolecular_reaction(struct volume *state,
struct abstract_molecule *am);
int find_unimol_reactions_with_surf_classes(
struct rxn **reaction_hash, int rx_hashsize,
struct abstract_molecule *reacA, struct wall *w, u_int hashA, int orientA,
int num_matching_rxns, int allow_rx_transp, int allow_rx_reflec,
int allow_rx_absorb_reg_border, struct rxn **matching_rxns);
int find_surface_mol_reactions_with_surf_classes(
struct rxn **reaction_hash, int rx_hashsize, struct species *all_mols,
struct species *all_surface_mols, int orientA, struct species *scl,
int num_matching_rxns, int allow_rx_transp, int allow_rx_reflec,
int allow_rx_absorb_reg_border, struct rxn **matching_rxns);
int find_volume_mol_reactions_with_surf_classes(
struct rxn **reaction_hash, int rx_hashsize, struct species *all_mols,
struct species *all_volume_mols, int orientA, struct species *scl,
int num_matching_rxns, int allow_rx_transp, int allow_rx_reflec,
struct rxn **matching_rxns);
/* In react_cond.c */
double timeof_unimolecular(struct rxn *rx, struct abstract_molecule *a,
struct rng_state *rng);
int which_unimolecular(struct rxn *rx, struct abstract_molecule *a,
struct rng_state *rng);
int binary_search_double(double *A, double match, int max, double mult);
int test_bimolecular(struct rxn *rx, double scaling, double local_prob_factor,
struct abstract_molecule *a1, struct abstract_molecule *a2,
struct rng_state *rng);
int test_many_bimolecular(struct rxn **rx, double *scaling,
double local_prob_factor, int n, int *chosen_pathway,
struct rng_state *rng,
int all_neighbors_flag);
int test_many_reactions_all_neighbors(struct rxn **rx, double *scaling,
double *local_prob_factor, int n,
int *chosen_pathway,
struct rng_state *rng);
int test_intersect(struct rxn *rx, double scaling, struct rng_state *rng);
int test_many_intersect(struct rxn **rx, double scaling, int n,
int *chosen_pathway, struct rng_state *rng);
struct rxn *test_many_unimol(struct rxn **rx, int n,
struct abstract_molecule *a,
struct rng_state *rng);
void update_probs(struct volume *world, struct rxn *rx, double t);
/* In react_outc.c */
int outcome_unimolecular(struct volume *world, struct rxn *rx, int path,
struct abstract_molecule *reac, double t);
int outcome_bimolecular(struct volume *world, struct rxn *rx, int path,
struct abstract_molecule *reacA,
struct abstract_molecule *reacB, short orientA,
short orientB, double t, struct vector3 *hitpt,
struct vector3 *loc_okay);
int outcome_trimolecular(struct volume *world, struct rxn *rx, int path,
struct abstract_molecule *reacA,
struct abstract_molecule *reacB,
struct abstract_molecule *reacC, short orientA,
short orientB, short orientC, double t,
struct vector3 *hitpt, struct vector3 *loc_okay);
int outcome_intersect(struct volume *world, struct rxn *rx, int path,
struct wall *surface, struct abstract_molecule *reac,
short orient, double t, struct vector3 *hitpt,
struct vector3 *loc_okay);
int is_compatible_surface(void *req_species, struct wall *w);
void add_reactants_to_product_list(struct rxn *rx, struct abstract_molecule *reacA,
struct abstract_molecule *reacB, struct abstract_molecule *reacC,
struct abstract_molecule **player, char *player_type);
struct surface_molecule *
place_sm_product(struct volume *world, struct species *product_species, struct graph_data*,
struct surface_grid *grid, int grid_index,
struct vector2 *mol_uv_pos, short orient, double t,
struct periodic_image *periodic_box);
int reaction_wizardry(struct volume *world, struct magic_list *incantation,
struct wall *surface, struct vector3 *hitpt, double t);
void tiny_diffuse_3D(
struct volume *world,
struct subvolume *subvol,
struct vector3 *displacement,
struct vector3 *pos,
struct wall *w);
struct volume_molecule *
place_volume_product(struct volume *world, struct species *product_species, struct graph_data*,
struct surface_molecule *sm_reactant, struct wall *w,
struct subvolume *subvol, struct vector3 *hitpt,
short orient, double t, struct periodic_image *periodic_box);
/* ALL_INSIDE: flag that indicates that all reactants lie inside their
* respective restrictive regions
* ALL_OUTSIDE: flag that indicates that all reactants lie outside
* their respective restrictive regions
* SURF1_IN_SURF2_OUT: flag that indicates that reactant "sm_1" lies
* inside and reactant "sm_2" lies outside of their
* respective restrictive regions
* SURF1_OUT_SURF2_IN: flag that indicates that reactant "sm_1" lies outside
* and reactant "sm_2" lies inside of their
* respective restrictive regions
* SURF1_IN: flag that indicates that only reactant "sm_1" has
* restrictive regions on the object and it lies
* inside its restrictive region.
* SURF1_OUT: flag that indicates that only reactant "sm_1" has
* restrictive regions on the object and it lies
* outside its restrictive region.
* SURF2_IN: flag that indicates that only reactant "sm_2" has
* restrictive regions on the object and it lies
* inside its restrictive region.
* SURF2_OUT: flag that indicates that only reactant "sm_2" has
* restrictive regions on the object and it lies
* outside its restrictive region. */
#define ALL_INSIDE 0x01
#define ALL_OUTSIDE 0x02
#define SURF1_IN_SURF2_OUT 0x04
#define SURF1_OUT_SURF2_IN 0x08
#define SURF1_IN 0x10
#define SURF1_OUT 0x20
#define SURF2_IN 0x40
#define SURF2_OUT 0x80
int determine_molecule_region_topology(
struct volume *world, struct surface_molecule *sm_1,
struct surface_molecule *sm_2, struct region_list **rlp_wall_1_ptr,
struct region_list **rlp_wall_2_ptr, struct region_list **rlp_obj_1_ptr,
struct region_list **rlp_obj_2_ptr, bool is_unimol);
bool product_tile_can_be_reached(struct wall *target,
struct region_list *rlp_head_wall_1,
struct region_list *rlp_head_wall_2,
struct region_list *rlp_head_obj_1,
struct region_list *rlp_head_obj_2,
int sm_bitmask, bool is_unimol);
//NFSim specific functions
//This function creates a queryOptions object for designing an NFSim experiment query
queryOptions initializeNFSimQueryForUnimolecularReactions(struct abstract_molecule *);
int initializeNFSimReaction(struct volume* state, struct rxn*, int, void*,
struct abstract_molecule*, struct abstract_molecule *);
int trigger_bimolecular_nfsim(struct volume* state, struct abstract_molecule *,
struct abstract_molecule *,short,
short, struct rxn **);
unsigned long lhash(const char *str);
| Unknown |
3D | mcellteam/mcell | src/mcell_dyngeom.h | .h | 900 | 29 | /******************************************************************************
*
* Copyright (C) 2006-2014 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
*****************************************************************************/
#ifndef MCELL_DYNGEOM_H
#define MCELL_DYNGEOM_H
#include "mcell_objects.h"
struct mesh_region_string_buffs {
struct string_buffer *old_inst_mesh_names;
struct string_buffer *old_region_names;
};
int mcell_add_dynamic_geometry_file(char *dynamic_geometry_filepath,
struct mdlparse_vars *parse_state);
int mcell_change_geometry(struct volume *state, struct poly_object_list *pobj_list);
#endif
| Unknown |
3D | mcellteam/mcell | src/rng.c | .c | 11,797 | 239 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <math.h>
#include <iostream>
#include "rng.h"
//#include "mcell_structs.h"
static void dump_rng_call_info(struct isaac64_state* rng, const char* extra_comment) {
std::cout << " " << extra_comment << "randcnt:" << rng->randcnt << ", aa:" <<
(unsigned)rng->aa << ", bb:" << (unsigned)rng->bb << ", cc:" << (unsigned)rng->cc << "\n";
}
/*************************************************************************
* Ziggurat Gaussian generator
*
* The Ziggurat algorithm works, loosely speaking, by dividing the
* probability space under the Gaussian pdf into 128 rectangular
* regions of equal probability. Obviously, since the regions are
* rectangular, each region will intersect the pdf, and part of the
* region will lie outside.
*
* With a single random integer selection, we choose a region under the
* curve and an x position within the bounds of the region. Using
* table "K" below, it quickly determines whether the column of the
* region with the chosen X position lies entirely under the pdf. If
* so, the value is chosen. If not, it will choose an independent Y
* coordinate, and test whether the X,Y point lies under the pdf.
* Essentially, this weights values based on the fraction of the cross
* section of the box which lies inside the curve at the chosen X
* coordinate.
*
* Now, the bottom-most region, encompassing the tails, is dealt with
* as a special case, using a more expensive formula to choose an X and
* Y within the region, and applying the same rejection test.
*
* For a full description, see
* The Ziggurat method for generating random variables -
* Marsaglia, Tsang - 2000
*************************************************************************/
#define R_VALUE (3.442619855899)
static const double SCALE_FACTOR = R_VALUE;
static const double RECIP_SCALE_FACTOR = 1.0 / R_VALUE;
/* Tabulated PDF at ends of strips */
static const double YTAB[128] = {
1.0000000000000, 0.96359862301100, 0.93628081335300, 0.91304110425300,
0.8922785066960, 0.87323935691900, 0.85549640763400, 0.83877892834900,
0.8229020836990, 0.80773273823400, 0.79317104551900, 0.77913972650500,
0.7655774360820, 0.75243445624800, 0.73966978767700, 0.72724912028500,
0.7151433774130, 0.70332764645500, 0.69178037703500, 0.68048276891000,
0.6694182972330, 0.65857233912000, 0.64793187618900, 0.63748525489600,
0.6272219914500, 0.61713261153200, 0.60720851746700, 0.59744187729600,
0.5878255314650, 0.57835291380300, 0.56901798419800, 0.55981517091100,
0.5507393208770, 0.54178565668200, 0.53294973914500, 0.52422743462800,
0.5156148863730, 0.50710848925300, 0.49870486747800, 0.49040085481200,
0.4821934769860, 0.47407993601000, 0.46605759612500, 0.45812397121400,
0.4502767134670, 0.44251360317100, 0.43483253947300, 0.42723153202200,
0.4197086933790, 0.41226223212000, 0.40489044654800, 0.39759171895500,
0.3903645103820, 0.38320735581600, 0.37611885978800, 0.36909769233400,
0.3621425852820, 0.35525232883400, 0.34842576841500, 0.34166180177600,
0.3349593763110, 0.32831748658800, 0.32173517206300, 0.31521151497000,
0.3087456383670, 0.30233670433800, 0.29598391232000, 0.28968649757100,
0.2834437297390, 0.27725491156000, 0.27111937764900, 0.26503649338700,
0.2590056539120, 0.25302628318300, 0.24709783313900, 0.24121978293200,
0.2353916382390, 0.22961293064900, 0.22388321712200, 0.21820207951800,
0.2125691242010, 0.20698398170900, 0.20144630649600, 0.19595577674500,
0.1905120942560, 0.18511498440600, 0.17976419618500, 0.17445950232400,
0.1692006994920, 0.16398760860000, 0.15882007519500, 0.15369796996400,
0.1486211893480, 0.14358965629500, 0.13860332114300, 0.13366216266900,
0.1287661893090, 0.12391544058200, 0.11910998874500, 0.11434994070300,
0.1096354402300, 0.10496667053300, 0.10034385723200, 0.09576727182660,
0.0912372357329, 0.08675412501270, 0.08231837593200, 0.07793049152950,
0.0735910494266, 0.06930071117420, 0.06506023352900, 0.06087048217450,
0.0567324485840, 0.05264727098000, 0.04861626071630, 0.04464093597690,
0.0407230655415, 0.03686472673860, 0.03306838393780, 0.02933699774110,
0.0256741818288, 0.02208443726340, 0.01857352005770, 0.01514905528540,
0.0118216532614, 0.00860719483079, 0.00553245272614, 0.00265435214565
};
/* Tabulated 'K' for quick out on strips (strip #0 at bottom, strips
* 1...127 counting down from the top */
static const unsigned long KTAB[128] = {
3961069056u, 0u, 3223204864u, 3653799168u, 3837168384u, 3938453504u,
4002562304u, 4046735616u, 4078995712u, 4103576064u, 4122919680u, 4138533632u,
4151398144u, 4162178048u, 4171339520u, 4179219968u, 4186068736u, 4192074496u,
4197382656u, 4202106624u, 4206336512u, 4210145280u, 4213591808u, 4216723968u,
4219582464u, 4222200320u, 4224606208u, 4226823936u, 4228873984u, 4230773504u,
4232538112u, 4234180864u, 4235713280u, 4237145088u, 4238485504u, 4239742208u,
4240921856u, 4242030848u, 4243074816u, 4244058368u, 4244986112u, 4245861888u,
4246689024u, 4247471360u, 4248211200u, 4248911616u, 4249574656u, 4250202624u,
4250797824u, 4251361536u, 4251895808u, 4252401920u, 4252881408u, 4253335552u,
4253765632u, 4254172416u, 4254556928u, 4254920192u, 4255262976u, 4255586048u,
4255889920u, 4256175360u, 4256442880u, 4256693248u, 4256926464u, 4257143040u,
4257343488u, 4257528064u, 4257696768u, 4257850368u, 4257988608u, 4258111488u,
4258219776u, 4258312704u, 4258391040u, 4258454016u, 4258502144u, 4258535168u,
4258552832u, 4258554880u, 4258541056u, 4258511360u, 4258464768u, 4258401536u,
4258320896u, 4258222080u, 4258104832u, 4257968128u, 4257811200u, 4257633280u,
4257433088u, 4257209856u, 4256961792u, 4256687616u, 4256385792u, 4256054272u,
4255691264u, 4255294208u, 4254860288u, 4254386688u, 4253869824u, 4253305856u,
4252690176u, 4252017664u, 4251282176u, 4250476800u, 4249593088u, 4248621568u,
4247550720u, 4246366464u, 4245052672u, 4243589120u, 4241950720u, 4240106752u,
4238018048u, 4235635200u, 4232893184u, 4229705472u, 4225955328u, 4221478912u,
4216040192u, 4209284608u, 4200653824u, 4189208320u, 4173230848u, 4149180928u,
4108286464u, 4020287488u,
};
/* Tabulated 'W' - scale for output values which aren't in the tails.
*/
static const double WTAB[128] = {
8.6953453083203121e-10, 6.3405591725390621e-11, 8.4488869224218753e-11,
9.9314962924609369e-11, 1.1116387731953125e-10, 1.2122657128203126e-10,
1.3008270556367187e-10, 1.3806213294726563e-10, 1.4537213775703125e-10,
1.5215230301562501e-10, 1.5850154873593751e-10, 1.6449279254492188e-10,
1.7018149410312499e-10, 1.7561092513125e-10, 1.8081557188632812e-10,
1.8582341630273437e-10, 1.9065751455351563e-10, 1.9533711929062499e-10,
1.9987849626093751e-10, 2.04295530709375e-10, 2.08600185790625e-10,
2.1280285463710938e-10, 2.1691263460195312e-10, 2.2093754361679686e-10,
2.2488469284960938e-10, 2.2876042594218749e-10, 2.3257043236796876e-10,
2.3631984053750003e-10, 2.4001329488320311e-10, 2.4365502016640626e-10,
2.4724887549179688e-10, 2.5079839997539061e-10, 2.5430685159257813e-10,
2.5777724040898438e-10, 2.6121235716445313e-10, 2.6461479798749998e-10,
2.6798698586328124e-10, 2.7133118937656251e-10, 2.7464953914179685e-10,
2.7794404227695312e-10, 2.8121659520312502e-10, 2.8446899501171874e-10,
2.8770294960624999e-10, 2.9092008678046877e-10, 2.9412196238398437e-10,
2.973100676984375e-10, 3.0048583611992187e-10, 3.0365064925234374e-10,
3.0680584247773435e-10, 3.0995271007539061e-10, 3.1309250994960936e-10,
3.1622646801875002e-10, 3.1935578230429687e-10, 3.2248162677148437e-10,
3.2560515494570314e-10, 3.2872750334726564e-10, 3.3184979476601564e-10,
3.3497314140859373e-10, 3.3809864793867189e-10, 3.4122741443554687e-10,
3.4436053929296873e-10, 3.4749912207851561e-10, 3.5064426637031249e-10,
3.537970825980469e-10, 3.569586908984375e-10, 3.6013022401210936e-10,
3.6331283023710936e-10, 3.6650767646015627e-10, 3.6971595128828127e-10,
3.7293886829960937e-10, 3.7617766944101564e-10, 3.7943362859414062e-10,
3.8270805533945314e-10, 3.8600229894414062e-10, 3.8931775261445313e-10,
3.9265585803906251e-10, 3.9601811027343748e-10, 3.9940606299218751e-10,
4.0282133419531251e-10, 4.0626561237890627e-10, 4.0974066326171876e-10,
4.1324833716015624e-10, 4.1679057705078127e-10, 4.2036942743359373e-10,
4.2398704412499999e-10, 4.27645705109375e-10, 4.313478225390625e-10,
4.3509595613671873e-10, 4.3889282815234374e-10, 4.4274134012109375e-10,
4.4664459169921876e-10, 4.5060590190234376e-10, 4.5462883316796875e-10,
4.5871721866015623e-10, 4.6287519341406249e-10, 4.6710722996874996e-10,
4.7141817933203126e-10, 4.7581331823437496e-10, 4.8029840394531247e-10,
4.8487973809375004e-10, 4.8956424139453126e-10, 4.943595416328125e-10,
4.9927407779687501e-10, 5.0431722412109373e-10, 5.0949943883203125e-10,
5.1483244374218751e-10, 5.2032944281249999e-10, 5.2600539028906247e-10,
5.3187732267968745e-10, 5.3796477383984377e-10, 5.4429029952734371e-10,
5.5088014832421874e-10, 5.5776513099609373e-10, 5.6498176366796878e-10,
5.725737958203125e-10, 5.8059429076562498e-10, 5.8910851843359379e-10,
5.9819807578906255e-10, 6.0796692205859379e-10, 6.185505133828125e-10,
6.3013017932812498e-10, 6.4295684709374998e-10, 6.5739255938671875e-10,
6.7398878396093752e-10, 6.9364952928125e-10, 7.1802168155078126e-10,
7.5064859720703123e-10, 8.0193543731249999e-10,
};
/*************************************************************************
rng_gauss:
In: struct rng_state *rng - uniform RNG state
Out: Returns a Gaussian variate (mean 0, variance 1)
*************************************************************************/
static double rng_gauss(struct rng_state *rng) {
double x, y;
double sign = 1.0;
#ifdef DEBUG_RNG_CALLS
dump_rng_call_info(rng, "rng_gauss");
#endif
int npasses = 0;
do {
unsigned long bits = rng_uint(rng);
unsigned long region, pos_within_region;
++npasses;
/* Partition bits:
* - Bits 0...7: select a region under the curve
* - Bit 8: sign bit
* - Bits 9...31 pick a point within the region
* */
sign = (bits & 0x80) ? -1.0 : 1.0;
region = bits & 0x0000007f;
pos_within_region = bits & 0xffffff00;
/* Compute our X, and check if the X value lies entirely under the
* curve for the chosen region */
x = pos_within_region * WTAB[region];
if (pos_within_region < KTAB[region])
break;
/* If we're in one of the 127 cheap regions */
if (region != 0) {
double yR, yB;
yB = YTAB[region];
yR = YTAB[region - 1] - yB;
y = yB + yR * rng_dbl(rng);
}
/* If we're in the expensive region */
else {
x = SCALE_FACTOR - log1p(-rng_dbl(rng)) * RECIP_SCALE_FACTOR;
y = exp(-SCALE_FACTOR * (x - 0.5 * SCALE_FACTOR)) * rng_dbl(rng);
}
} while (y >= exp(-0.5 * x * x));
return sign * x;
}
#if !defined(NDEBUG) || defined(DEBUG_RNG_CALLS)
static double rng_dbl(struct rng_state *rng) {
#ifdef DEBUG_RNG_CALLS
dump_rng_call_info(rng, "");
#endif
return isaac64_dbl32(rng);
}
#endif
#if !defined(NDEBUG) || defined(DEBUG_RNG_CALLS)
static unsigned int rng_uint(struct rng_state *rng) {
#ifdef DEBUG_RNG_CALLS
dump_rng_call_info(rng, "");
#endif
return isaac64_uint32(rng);
}
#endif
| C |
3D | mcellteam/mcell | src/vol_util.h | .h | 5,676 | 131 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
int inside_subvolume(struct vector3 *point, struct subvolume *subvol,
double *x_fineparts, double *y_fineparts,
double *z_fineparts);
struct subvolume *find_coarse_subvol(struct volume *world, struct vector3 *loc);
struct subvolume *traverse_subvol(struct subvolume *here,
int which, int ny_parts, int nz_parts);
struct subvolume *next_subvol(struct vector3 *here, struct vector3 *move,
struct subvolume *sv, double *x_fineparts,
double *y_fineparts, double *z_fineparts,
int ny_parts, int nz_parts);
struct subvolume *find_subvolume(struct volume *world, struct vector3 *loc,
struct subvolume *guess);
double collide_sv_time(struct vector3 *point, struct vector3 *move,
struct subvolume *sv, double *x_fineparts,
double *y_fineparts, double *z_fineparts);
int is_defunct_molecule(struct abstract_element *e);
struct wall* find_closest_wall(
struct volume *state, struct vector3 *loc, double search_diam,
struct vector2 *best_uv, int *grid_index, struct species *s, const char *mesh_name,
struct string_buffer *reg_names, struct string_buffer *regions_to_ignore);
struct surface_molecule *
place_surface_molecule(struct volume *state, struct species *s,
struct vector3 *loc, short orient, double search_diam,
double t, struct subvolume **psv, const char *mesh_name,
struct string_buffer *reg_names,
struct string_buffer *regions_to_ignore,
struct periodic_image *periodic_box);
struct surface_molecule *
insert_surface_molecule(struct volume *state, struct species *s,
struct vector3 *loc, short orient, double search_diam,
double t, const char *mesh_name,
struct string_buffer *reg_names,
struct string_buffer *regions_to_ignore,
struct periodic_image *periodic_box);
struct volume_molecule *insert_volume_molecule(struct volume *world,
struct volume_molecule *vm,
struct volume_molecule *guess);
struct volume_molecule *migrate_volume_molecule(struct volume_molecule *vm,
struct subvolume *new_sv);
int eval_rel_region_3d(struct release_evaluator *expr, struct waypoint *wp,
struct region_list *in_regions,
struct region_list *out_regions);
int release_molecules(struct volume *world, struct release_event_queue *req);
int release_by_list(struct volume *state, struct release_event_queue *req,
struct volume_molecule *vm);
int release_ellipsoid_or_rectcuboid(struct volume *state,
struct release_event_queue *req,
struct volume_molecule *vm, int number);
int set_partitions(struct volume *world);
double increase_fine_partition_size(struct volume *state, double *fineparts,
double *f_min, double *f_max,
double smallest_spacing);
void set_fineparts(double min, double max, double *partitions,
double *fineparts, int n_parts, int in, int start);
void set_auto_partitions(struct volume *state, double steps_min,
double steps_max, struct vector3 *part_min,
struct vector3 *part_max, double f_max,
double smallest_spacing);
void set_user_partitions(struct volume *state, double dfx, double dfy,
double dfz);
void find_closest_fine_part(double *partitions, double *fineparts,
int n_fineparts, int n_parts);
double *add_extra_outer_partitions(double *partitions, double bb_llf_val,
double bb_urb_val, double df_val,
int *n_parts);
void path_bounding_box(struct vector3 *loc, struct vector3 *displacement,
struct vector3 *llf, struct vector3 *urb,
double rx_radius_3d);
void ht_add_molecule_to_list(struct pointer_hash *h, struct volume_molecule *vm);
void ht_remove(struct pointer_hash *h, struct per_species_list *psl);
void collect_molecule(struct volume_molecule *vm);
bool periodic_boxes_are_identical(const struct periodic_image *b1,
const struct periodic_image *b2);
int convert_relative_to_abs_PBC_coords(
struct geom_object *periodic_box_obj,
struct periodic_image *periodic_box,
bool periodic_traditional,
struct vector3 *pos,
struct vector3 *pos_output);
struct surface_molecule_list* add_surfmol_with_unique_pb_to_list(
struct surface_molecule_list *sm_list,
struct surface_molecule *sm);
void remove_surfmol_from_list(
struct surface_molecule_list **sm_head,
struct surface_molecule *sm);
| Unknown |
3D | mcellteam/mcell | src/isaac64.c | .c | 5,846 | 156 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/*
------------------------------------------------------------------------------
isaac64.c: My random number generator for 64-bit machines.
By Bob Jenkins, 1996. Public Domain.
------------------------------------------------------------------------------
*/
#include "config.h"
#include "isaac64.h"
#define ind_isaac64(mm, x) (*(ub8 *)((ub1 *)(mm) + ((x) & ((RANDSIZ - 1) << 3))))
#define rngstep_isaac64(mix, a, b, mm, m, m2, r, x) \
{ \
x = *m; \
a = (mix) + *(m2++); \
*(m++) = y = ind_isaac64(mm, x) + a + b; \
*(r++) = b = ind_isaac64(mm, y >> RANDSIZL) + x; \
}
#define mix_isaac64(a, b, c, d, e, f, g, h) \
{ \
a -= e; \
f ^= h >> 9; \
h += a; \
b -= f; \
g ^= a << 9; \
a += b; \
c -= g; \
h ^= b >> 23; \
b += c; \
d -= h; \
a ^= c << 15; \
c += d; \
e -= a; \
b ^= d >> 14; \
d += e; \
f -= b; \
c ^= e << 20; \
e += f; \
g -= c; \
d ^= f >> 17; \
f += g; \
h -= d; \
e ^= g << 14; \
g += h; \
}
static void isaac64_generate(struct isaac64_state *rng) {
ub8 a, b, x, y, *m, *m2, *r, *mend;
m = rng->mm;
r = rng->randrsl;
a = rng->aa;
b = rng->bb + (++rng->cc);
for (m = rng->mm, mend = m2 = m + (RANDSIZ / 2); m < mend;) {
rngstep_isaac64(~(a ^ (a << 21)), a, b, rng->mm, m, m2, r, x);
rngstep_isaac64(a ^ (a >> 5), a, b, rng->mm, m, m2, r, x);
rngstep_isaac64(a ^ (a << 12), a, b, rng->mm, m, m2, r, x);
rngstep_isaac64(a ^ (a >> 33), a, b, rng->mm, m, m2, r, x);
}
for (m2 = rng->mm; m2 < mend;) {
rngstep_isaac64(~(a ^ (a << 21)), a, b, rng->mm, m, m2, r, x);
rngstep_isaac64(a ^ (a >> 5), a, b, rng->mm, m, m2, r, x);
rngstep_isaac64(a ^ (a << 12), a, b, rng->mm, m, m2, r, x);
rngstep_isaac64(a ^ (a >> 33), a, b, rng->mm, m, m2, r, x);
}
rng->bb = b;
rng->aa = a;
++rng->rngblocks;
}
static void isaac64_init(struct isaac64_state *rng, ub4 seed) {
ub8 *r, *m;
ub8 a, b, c, d, e, f, g, h;
ub4 i;
rng->rngblocks = 0;
rng->aa = (ub8)0;
rng->bb = (ub8)0;
rng->cc = (ub8)0;
a = b = c = d = e = f = g = h = 0x9e3779b97f4a7c13LL; /* the golden ratio */
r = rng->randrsl;
m = rng->mm;
for (i = 0; i < RANDSIZ; ++i)
r[i] = (ub8)0;
r[0] = seed;
for (i = 0; i < 4; ++i) /* scramble it */
{
mix_isaac64(a, b, c, d, e, f, g, h);
}
for (i = 0; i < RANDSIZ; i += 8) /* fill in m[] with messy stuff */
{
/* use all the information in the seed */
a += r[i];
b += r[i + 1];
c += r[i + 2];
d += r[i + 3];
e += r[i + 4];
f += r[i + 5];
g += r[i + 6];
h += r[i + 7];
mix_isaac64(a, b, c, d, e, f, g, h);
m[i] = a;
m[i + 1] = b;
m[i + 2] = c;
m[i + 3] = d;
m[i + 4] = e;
m[i + 5] = f;
m[i + 6] = g;
m[i + 7] = h;
}
/* do a second pass to make all of the seed affect all of m[] */
for (i = 0; i < RANDSIZ; i += 8) {
a += m[i];
b += m[i + 1];
c += m[i + 2];
d += m[i + 3];
e += m[i + 4];
f += m[i + 5];
g += m[i + 6];
h += m[i + 7];
mix_isaac64(a, b, c, d, e, f, g, h);
m[i] = a;
m[i + 1] = b;
m[i + 2] = c;
m[i + 3] = d;
m[i + 4] = e;
m[i + 5] = f;
m[i + 6] = g;
m[i + 7] = h;
}
isaac64_generate(rng); /* fill in the first set of results */
rng->randcnt = RANDMAX; /* prepare to use the first set of results */
}
| C |
3D | mcellteam/mcell | src/pymcell_unittests.py | .py | 1,080 | 34 | import unittest
import pymcell as m
class SimpleSpeciesTestCase(unittest.TestCase):
def setUp(self):
self.vm1 = m.Species("vm1", 1e-6)
self.vm1_down = m.OrientedSpecies(self.vm1, m.Orient.down)
self.sm1 = m.Species("sm1", 1e-6, surface=True)
self.sm1_up = m.OrientedSpecies(self.sm1, m.Orient.up)
self.vm2 = m.Species("vm2", 1e-6)
self.vm2_down = m.OrientedSpecies(self.vm2, m.Orient.down)
def test_mol_is_3d(self):
assert self.vm1.surface == False, "Volume molecule has 'surface' True"
def test_mol_is_2d(self):
assert self.sm1.surface == True, "Surface molecule has 'surface' False"
class SimpleReactionTestCase(SimpleSpeciesTestCase):
def test_vm1_to_null(self):
rxn = m.Reaction(self.vm1.down(), None, 1e8)
def test_vm1_to_vm2(self):
rxn = m.Reaction(self.vm1, self.vm2, 1e8)
def test_vm1sm1_to_vm2(self):
rxn = m.Reaction((self.vm1.down(), self.sm1.up()), self.vm2.down(), 1e8)
if __name__ == "__main__":
unittest.main()
| Python |
3D | mcellteam/mcell | src/sched_util.h | .h | 3,264 | 79 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
/* Everything managed by scheduler must begin as if it were derived from
* abstract_element */
struct abstract_element {
struct abstract_element *next;
double t; /* Time at which the element is scheduled */
};
/* Implements a multi-scale, discretized event scheduler */
struct schedule_helper {
struct schedule_helper *next_scale; /* Next coarser time scale */
double dt; /* Timestep per slot */
double dt_1; /* dt_1 = 1/dt */
double now; /* Start time of the scheduler */
/* Items scheduled now or after now */
int count; /* Total number of items scheduled now or after */
int buf_len; /* Number of slots in the scheduler */
int index; /* Index of the next time block */
int *circ_buf_count; /* How many items are scheduled in each slot */
// Array of linked lists of scheduled items for each slot
struct abstract_element **circ_buf_head;
// Array of tails of the linked lists
struct abstract_element **circ_buf_tail;
/* Items scheduled before now */
/* These events must be serviced before simulation can advance to now */
int current_count; /* Number of current items */
struct abstract_element *current; /* List of items scheduled now */
struct abstract_element *current_tail; /* Tail of list of items */
int defunct_count; /* Number of defunct items (set by user)*/
int error; /* Error code (1 - on error, 0 - no errors) */
int depth; /* "Tier" of scheduler in timescale hierarchy, 0-based */
};
struct abstract_element *ae_list_sort(struct abstract_element *ae);
struct schedule_helper *create_scheduler(double dt_min, double dt_max,
int maxlen, double start_iterations);
int schedule_insert(struct schedule_helper *sh, void *data,
int put_neg_in_current);
int schedule_deschedule(struct schedule_helper *sh, void *data);
int schedule_reschedule(struct schedule_helper *sh, void *data, double new_t);
/*void schedule_excert(struct schedule_helper *sh,void *data,void *blank,int
* size);*/
int schedule_advance(struct schedule_helper *sh, struct abstract_element **head,
struct abstract_element **tail);
void *schedule_next(struct schedule_helper *sh);
void *schedule_peak(struct schedule_helper *sh);
#define schedule_add(x, y) schedule_insert((x), (y), 1)
int schedule_add_mol(struct schedule_helper *sh, void* /*struct abstract_molecule* */ data);
int schedule_anticipate(struct schedule_helper *sh, double *t);
struct abstract_element *
schedule_cleanup(struct schedule_helper *sh,
int (*is_defunct)(struct abstract_element *e));
void delete_scheduler(struct schedule_helper *sh);
void sort_schedule_by_time_and_id(struct schedule_helper *sh);
| Unknown |
3D | mcellteam/mcell | src/isaac64.h | .h | 3,891 | 93 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/*
------------------------------------------------------------------------------
isaac64.h: definitions for a random number generator
Bob Jenkins, 1996, Public Domain
Modified for modularity by Tom Bartol and Rex Kerr
------------------------------------------------------------------------------
*/
#pragma once
#include <inttypes.h>
#define RANDSIZL (8)
#define RANDSIZ (1 << RANDSIZL)
#define RANDMAX (2 * RANDSIZ)
typedef unsigned long long ub8;
typedef uint32_t ub4;
typedef unsigned short int ub2;
typedef unsigned char ub1;
#define DBL32 (2.3283064365386962890625e-10)
#define DBL53 (1.1102230246251565404236316680908203125e-16)
#define DBL64 (5.42101086242752217003726400434970855712890625e-20)
#define MSK53 0x001FFFFFFFFFFFFFLL
struct isaac64_state {
unsigned int randcnt;
ub8 aa;
ub8 bb;
ub8 cc;
ub8 randrsl[RANDSIZ];
ub8 mm[RANDSIZ];
ub8 rngblocks;
};
static void isaac64_init(struct isaac64_state *rng, ub4 seed);
static void isaac64_generate(struct isaac64_state *rng);
/*
------------------------------------------------------------------------------
Macros to get individual random numbers
------------------------------------------------------------------------------
*/
#define isaac64_uint32(rng) \
((rng)->randcnt > 0 ? (*(((ub4 *)((rng)->randrsl)) + ((rng)->randcnt -= 1))) \
: (isaac64_generate(rng), (rng)->randcnt = RANDMAX - 1, \
*(((ub4 *)((rng)->randrsl)) + (rng)->randcnt)))
#define isaac64_uint64(rng) \
((rng)->randcnt > 1 \
? (*((ub8 *)(((ub4 *)((rng)->randrsl)) + ((rng)->randcnt -= 2)))) \
: (isaac64_generate((rng)), (rng)->randcnt = RANDMAX - 2, \
*((ub8 *)(((ub4 *)((rng)->randrsl)) + (rng)->randcnt))))
#define isaac64_dbl32(rng) \
((rng)->randcnt > 0 \
? (DBL32 *(*(((ub4 *)((rng)->randrsl)) + ((rng)->randcnt -= 1)))) \
: (isaac64_generate(rng), (rng)->randcnt = RANDMAX - 1, \
DBL32 * (*(((ub4 *)((rng)->randrsl)) + (rng)->randcnt))))
#define isaac64_dbl53(rng) \
((rng)->randcnt > 1 \
? (DBL53 *( \
(*((ub8 *)(((ub4 *)((rng)->randrsl)) + ((rng)->randcnt -= 2)))) >> \
11)) \
: (isaac64_generate(rng), (rng)->randcnt = RANDMAX - 2, \
DBL53 * \
((*((ub8 *)(((ub4 *)((rng)->randrsl)) + (rng)->randcnt))) >> 11)))
#define isaac64_dbl64(rng) \
((rng)->randcnt > 1 \
? (DBL64 *(*((ub8 *)(((ub4 *)((rng)->randrsl)) + ((rng)->randcnt -= 2))))) \
: (isaac64_generate(rng), (rng)->randcnt = RANDMAX - 2, \
DBL64 * (*((ub8 *)(((ub4 *)((rng)->randrsl)) + (rng)->randcnt)))))
#include "isaac64.c"
| Unknown |
3D | mcellteam/mcell | src/react_trig.c | .c | 43,059 | 1,153 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/**************************************************************************\
** File: react_trig.c **
** **
** Purpose: Detects the possibility of a uni/bimolecular/surface reaction **
** **
** Testing status: partially validated (see validate_react_trig.c) **
\**************************************************************************/
#include "config.h"
#include <string.h>
#include <stdlib.h>
#include "logging.h"
#include "mcell_structs.h"
#include "react.h"
#include "react_nfsim.h"
#include "vol_util.h"
#include "dump_state.h"
#include "debug_config.h"
/*************************************************************************
trigger_unimolecular:
In: hash value of molecule's species
pointer to a molecule
Out: NULL if there are no unimolecular reactions for this species
pointer to the reaction if there are
Note: This is only tested on molecules that have just been created
or come off the scheduling queue--do not run on a scheduled
molecule.
*************************************************************************/
struct rxn *trigger_unimolecular(struct rxn **reaction_hash, int rx_hashsize,
u_int hash, struct abstract_molecule *reac) {
struct rxn *inter = reaction_hash[hash & (rx_hashsize - 1)];
while (inter != NULL) {
if (inter->n_reactants == 1 &&
inter->players[0] == reac->properties) {
return inter;
}
inter = inter->next;
}
return NULL;
}
/*************************************************************************
trigger_surface_unimol:
In: pointer to a molecule (had better be a surface molecule)
pointer to a wall to test for reaction (if NULL, molecule will use
its own wall)
array of matching reactions
Out: Number of matching reactions for this species on this surface class
All matching reactions are put into an "matching_rxns" array.
Note: this is just a wrapper around trigger_intersect
*************************************************************************/
int trigger_surface_unimol(struct rxn **reaction_hash, int rx_hashsize,
struct species *all_mols,
struct species *all_volume_mols,
struct species *all_surface_mols,
struct abstract_molecule *mol, struct wall *w,
struct rxn **matching_rxns) {
struct surface_molecule *sm = (struct surface_molecule *)mol;
if (w == NULL) {
w = sm->grid->surface;
}
int num_matching_rxns = trigger_intersect(
reaction_hash, rx_hashsize, all_mols, all_volume_mols, all_surface_mols,
sm->properties->hashval, mol, sm->orient, w, matching_rxns, 0, 0, 0);
return num_matching_rxns;
}
/*************************************************************************
trigger_bimolecular_preliminary:
In: hashA - hash value for first molecule
hashB - hash value for second molecule
reacA - species of first molecule
reacB - species of second molecule
Out: 1 if any reaction exists naming the two specified reactants, 0
otherwise.
Note: This is a quick test used to determine which per-species lists to
traverse when checking for mol-mol collisions.
*************************************************************************/
int trigger_bimolecular_preliminary(struct rxn **reaction_hash, int rx_hashsize,
u_int hashA, u_int hashB,
struct species *reacA,
struct species *reacB) {
u_int hash = (hashA + hashB) & (rx_hashsize - 1);
for (struct rxn *inter = reaction_hash[hash]; inter != NULL; inter = inter->next) {
/* Enough reactants? (3=>wall also) */
if (inter->n_reactants < 2)
continue;
/* Do we have the right players? */
if ((reacA == inter->players[0] && reacB == inter->players[1])) {
return 1;
} else if ((reacB == inter->players[0] && reacA == inter->players[1])) {
return 1;
}
}
return 0;
}
/******
Tests whether reactants reacA and reacB meet the physical conditions to react together given reaction
inter
Out: 1 if the reactants interact, 0 if they don't, -1 if they don't and we have to stop testing
*****/
int process_bimolecular(struct abstract_molecule *reacA,
struct abstract_molecule *reacB,
struct rxn* inter,
short orientA,
short orientB,
struct rxn **matching_rxns,
int num_matching_rxns){
//u_int hash; /* index in the reaction hash table */
int test_wall; /* flag */
short geomA, geomB;
struct surf_class_list *scl;
//int right_walls_surf_classes;
/* flag to check whether SURFACE_CLASSES of the walls for one or both
* reactants match the SURFACE_CLASS of the reaction (if needed) */
/*right_walls_surf_classes = 0;*/
/* Right number of reactants? */
if (inter->n_reactants < 2)
return 0;
else if (inter->n_reactants > 2 && !(inter->players[2]->flags & IS_SURFACE))
return 0;
/* Do we have the right players? */
if (reacA->properties == reacB->properties) {
// FIXME: Shouldn't this be && instead of ||???
if ((reacA->properties != inter->players[0] ||
reacA->properties != inter->players[1]))
return 0;
} else if ((reacA->properties == inter->players[0] &&
reacB->properties == inter->players[1])) {
;
} else if ((reacB->properties == inter->players[0] &&
reacA->properties == inter->players[1])) {
;
} else {
return 0;
}
test_wall = 0;
geomA = inter->geometries[0];
geomB = inter->geometries[1];
/* Check to see if orientation classes are zero/different */
if (geomA == 0 || geomB == 0 || (geomA + geomB) * (geomA - geomB) != 0) {
if (inter->n_reactants == 2) {
if (num_matching_rxns >= MAX_MATCHING_RXNS)
return -1;
matching_rxns[num_matching_rxns] = inter;
return 1;
} else {
test_wall = 1;
}
}
else if (orientA != 0 && orientA * orientB * geomA * geomB > 0) {
/* Same class, is the orientation correct? */
if (inter->n_reactants == 2) {
if (num_matching_rxns >= MAX_MATCHING_RXNS)
return -1;
matching_rxns[num_matching_rxns] = inter;
return 1;
} else {
test_wall = 1;
}
}
/* See if we need to check a wall (fails if we're in free space) */
if (test_wall && orientA != 0) {
struct wall *w_A = NULL, *w_B = NULL;
/*short geomW;*/
/* short orientW = 1; Walls always have orientation 1 */
/* If we are oriented, one of us is a surface mol. */
/* For volume molecule wall that matters is the target's wall */
if (((reacA->properties->flags & NOT_FREE) == 0) &&
(reacB->properties->flags & ON_GRID) != 0) {
w_B = (((struct surface_molecule *)reacB)->grid)->surface;
} else if (((reacA->properties->flags & ON_GRID) != 0) &&
(reacB->properties->flags & ON_GRID) != 0) {
w_A = (((struct surface_molecule *)reacA)->grid)->surface;
w_B = (((struct surface_molecule *)reacB)->grid)->surface;
}
/* If a wall was found, we keep going to check....
This is a case for reaction between volume and surface molecules */
if ((w_A == NULL) && (w_B != NULL)) {
/* Right wall type--either this type or generic type? */
for (scl = w_B->surf_class_head; scl != NULL; scl = scl->next) {
if (inter->players[2] == scl->surf_class) {
/*right_walls_surf_classes = 1;*/
break;
}
}
}
} /* end if (test_wall && orientA != NULL) */
return 0;
}
/*************************************************************************
trigger_bimolecular:
In: hash values of the two colliding molecules
pointers to the two colliding molecules
orientations of the two colliding molecules
both zero away from a surface
both nonzero (+-1) at a surface
A is the moving molecule and B is the target
array of pointers to the possible reactions
Out: number of possible reactions for molecules reacA and reacB
Also the first 'number' slots in the 'matching_rxns'
array are filled with pointers to the possible reactions objects.
Note: The target molecule is already scheduled and can be destroyed
but not rescheduled. Assume we have or will check separately that
the moving molecule is not inert!
*************************************************************************/
int trigger_bimolecular(struct rxn **reaction_hash, int rx_hashsize,
u_int hashA, u_int hashB,
struct abstract_molecule *reacA,
struct abstract_molecule *reacB, short orientA,
short orientB, struct rxn **matching_rxns) {
/*struct surf_class_list *scl, *scl2;*/
// reactions between reacA and reacB only happen if both are in the same periodic box
if (!periodic_boxes_are_identical(reacA->periodic_box, reacB->periodic_box)) {
return 0;
}
int num_matching_rxns = 0; /* number of matching reactions */
u_int hash = (hashA + hashB) & (rx_hashsize - 1); /* index in the reaction hash table */
for (struct rxn *inter = reaction_hash[hash]; inter != NULL; inter = inter->next) {
int right_walls_surf_classes = 0; /* flag to check whether SURFACE_CLASSES
of the walls for one or both reactants
match the SURFACE_CLASS of the reaction
(if needed) */
/* skip irrelevant reactions (i.e. non vol-surf reactions) */
if (inter->n_reactants < 2) {
continue;
} else if (inter->n_reactants > 2 && !(inter->players[2]->flags & IS_SURFACE)) {
continue;
}
/* Do we have the right players? */
if (reacA->properties == reacB->properties) {
// FIXME: Shouldn't this be && instead of ||???
if ((reacA->properties != inter->players[0] ||
reacA->properties != inter->players[1]))
continue;
} else if ((reacA->properties == inter->players[0] &&
reacB->properties == inter->players[1])) {
;
} else if ((reacB->properties == inter->players[0] &&
reacA->properties == inter->players[1])) {
;
} else {
continue;
}
/* Check to see if orientation classes are zero/different */
int test_wall = 0;
short geomA = inter->geometries[0];
short geomB = inter->geometries[1];
if (geomA == 0 || geomB == 0 || (geomA + geomB) * (geomA - geomB) != 0) {
if (inter->n_reactants == 2) {
if (num_matching_rxns >= MAX_MATCHING_RXNS) {
break;
}
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
continue;
} else {
test_wall = 1;
}
} else if (orientA != 0 && orientA * orientB * geomA * geomB > 0) {
/* Same class, is the orientation correct? */
if (inter->n_reactants == 2) {
if (num_matching_rxns >= MAX_MATCHING_RXNS) {
break;
}
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
continue;
} else {
test_wall = 1;
}
}
/* See if we need to check a wall (fails if we're in free space) */
if (test_wall && orientA != 0) {
struct wall *w_A = NULL, *w_B = NULL;
short geomW;
/* If we are oriented, one of us is a surface mol. */
/* For volume molecule wall that matters is the target's wall */
if (((reacA->properties->flags & NOT_FREE) == 0) &&
(reacB->properties->flags & ON_GRID) != 0) {
w_B = (((struct surface_molecule *)reacB)->grid)->surface;
} else if (((reacA->properties->flags & ON_GRID) != 0) &&
(reacB->properties->flags & ON_GRID) != 0) {
w_A = (((struct surface_molecule *)reacA)->grid)->surface;
w_B = (((struct surface_molecule *)reacB)->grid)->surface;
}
struct surf_class_list *scl, *scl2;
/* If a wall was found, we keep going to check....
This is a case for reaction between volume and surface molecules */
if ((w_A == NULL) && (w_B != NULL)) {
/* Right wall type--either this type or generic type? */
for (scl = w_B->surf_class_head; scl != NULL; scl = scl->next) {
if (inter->players[2] == scl->surf_class) {
right_walls_surf_classes = 1;
break;
}
}
}
/* if both reactants are surface molecules they should be on
the walls with the same SURFACE_CLASS */
if ((w_A != NULL) && (w_B != NULL)) {
for (scl = w_A->surf_class_head; scl != NULL; scl = scl->next) {
for (scl2 = w_B->surf_class_head; scl2 != NULL; scl2 = scl->next) {
if (scl->surf_class == scl2->surf_class) {
if (inter->players[2] == scl->surf_class) {
right_walls_surf_classes = 1;
break;
}
}
}
}
}
if (right_walls_surf_classes) {
geomW = inter->geometries[2];
if (geomW == 0) {
if (num_matching_rxns >= MAX_MATCHING_RXNS) {
break;
}
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
continue;
}
/* We now care whether A and B correspond to player [0] and [1] or */
/* vice versa, so make sure A==[0] and B==[1] so W can */
/* match with the right one! */
if (reacA->properties != inter->players[0]) {
short temp = geomB;
geomB = geomA;
geomA = temp;
}
if (geomA == 0 || (geomA + geomW) * (geomA - geomW) != 0) { /* W not in A's class */
if (geomB == 0 || (geomB + geomW) * (geomB - geomW) != 0) {
if (num_matching_rxns >= MAX_MATCHING_RXNS) {
break;
}
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
continue;
}
if (orientB * geomB * geomW > 0) {
if (num_matching_rxns >= MAX_MATCHING_RXNS) {
break;
}
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
continue;
}
} else { /* W & A in same class */
if (orientA * geomA * geomW > 0) {
if (num_matching_rxns >= MAX_MATCHING_RXNS) {
break;
}
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
continue;
}
}
} /* if (right_walls_surf_classes) ... */
} /* end if (test_wall && orientA != NULL) */
} /* end for (inter = reaction_hash[hash]; ...) */
if (num_matching_rxns > MAX_MATCHING_RXNS) {
mcell_warn("Number of matching reactions exceeds the maximum allowed "
"number MAX_MATCHING_RXNS.");
}
return num_matching_rxns;
}
/*************************************************************************
trigger_trimolecular:
In: hash values of the three colliding molecules
pointers to the species of three colliding molecules
(reacA is the moving molecule and reacB and reacC are the targets)
orientations of the three molecules
array of pointers to the possible reactions
Out: number of possible reactions for species reacA, reacB, and reacC
Also the first "number" slots in the "matching_rxns"
array are filled with pointers to the possible reactions objects.
Note: The target molecules are already scheduled and can be destroyed
but not rescheduled. Assume we have or will check separately that
the moving molecule is not inert!
PostNote1: If one of the targets is a surface_molecule - it is reacC,
if two of the targets are surface molecules - they are
reacB and reacC.
*************************************************************************/
int trigger_trimolecular(struct rxn **reaction_hash, int rx_hashsize,
u_int hashA, u_int hashB, u_int hashC,
struct species *reacA, struct species *reacB,
struct species *reacC, int orientA, int orientB,
int orientC, struct rxn **matching_rxns) {
u_int rawhash = 0;
u_int hash = 0; /* index in the reaction hash table */
int num_matching_rxns = 0; /* number of matching reactions */
short geomA = SHRT_MIN, geomB = SHRT_MIN, geomC = SHRT_MIN;
struct rxn *inter;
int correct_players_flag;
int correct_orientation_flag;
if (strcmp(reacA->sym->name, reacB->sym->name) < 0) {
if (strcmp(reacB->sym->name, reacC->sym->name) < 0)
rawhash = (hashA + hashB);
else
rawhash = (hashA + hashC);
} else if (strcmp(reacA->sym->name, reacC->sym->name) < 0)
rawhash = (hashB + hashA);
else
rawhash = (hashB + hashC);
hash = rawhash & (rx_hashsize - 1);
inter = reaction_hash[hash];
while (inter != NULL) {
if (inter->n_reactants == 3) /* Enough reactants? */
{
correct_players_flag = 0;
correct_orientation_flag = 0;
/* Check that we have the right players */
if (reacA == inter->players[0]) {
if ((reacB == inter->players[1] && reacC == inter->players[2])) {
geomA = inter->geometries[0];
geomB = inter->geometries[1];
geomC = inter->geometries[2];
correct_players_flag = 1;
} else if ((reacB == inter->players[2] && reacC == inter->players[1])) {
geomA = inter->geometries[0];
geomB = inter->geometries[2];
geomC = inter->geometries[1];
correct_players_flag = 1;
}
} else if (reacA == inter->players[1]) {
if ((reacB == inter->players[0]) && (reacC == inter->players[2])) {
geomA = inter->geometries[1];
geomB = inter->geometries[0];
geomC = inter->geometries[2];
correct_players_flag = 1;
} else if ((reacB == inter->players[2]) &&
(reacC == inter->players[0])) {
geomA = inter->geometries[1];
geomB = inter->geometries[2];
geomC = inter->geometries[0];
correct_players_flag = 1;
}
} else if (reacA == inter->players[2]) {
if ((reacB == inter->players[0]) && (reacC == inter->players[1])) {
geomA = inter->geometries[2];
geomB = inter->geometries[0];
geomC = inter->geometries[1];
correct_players_flag = 1;
} else if ((reacB == inter->players[1]) &&
(reacC == inter->players[0])) {
geomA = inter->geometries[2];
geomB = inter->geometries[1];
geomC = inter->geometries[0];
correct_players_flag = 1;
}
}
/* Check to see if orientation classes are zero or different.
In such case we do not care about relative orientations of the
volume and surface reactants.
*/
if ((geomA == 0) && (geomB == 0) && (geomC == 0)) {
/* all volume molecules */
correct_orientation_flag = 1;
}
/* two volume and one surface molecule */
/* since geomA = geomB we will test only for geomA */
else if (((reacA->flags & NOT_FREE) == 0) &&
((reacB->flags & NOT_FREE) == 0) &&
((reacC->flags & ON_GRID) != 0)) {
/* different orientation classes */
if ((geomA + geomC) * (geomA - geomC) != 0) {
correct_orientation_flag = 1;
}
/* Same class, is the orientation correct? */
else if (orientA != 0 && orientA * orientC * geomA * geomC > 0) {
correct_orientation_flag = 1;
}
}
/* (one volume molecule and two surface molecules) or
(three surface molecules) */
else {
/* different orientation classes for all 3 reactants */
if (((geomA + geomC) * (geomA - geomC) != 0) &&
((geomA + geomB) * (geomA - geomB) != 0) &&
((geomB + geomC) * (geomB - geomC) != 0)) {
correct_orientation_flag = 1;
}
/* two reactants in the zero orientation class */
else if ((geomB == 0) && (geomC == 0) && (orientA != 0) &&
(geomA != 0)) {
correct_orientation_flag = 1;
} else if ((geomA == 0) && (geomC == 0) && (orientB != 0) &&
(geomB != 0)) {
correct_orientation_flag = 1;
} else if ((geomA == 0) && (geomB == 0) && (orientC != 0) &&
(geomC != 0)) {
correct_orientation_flag = 1;
}
/* one reactant in the zero orientation class */
else if (geomA == 0) {
/* different orientation classes */
if ((geomB + geomC) * (geomB - geomC) != 0) {
correct_orientation_flag = 1;
}
/* Same class, is the orientation correct? */
else if (orientB != 0 && orientB * orientC * geomB * geomC > 0) {
correct_orientation_flag = 1;
}
} else if (geomB == 0) {
/* different orientation classes */
if ((geomA + geomC) * (geomA - geomC) != 0) {
correct_orientation_flag = 1;
}
/* Same class, is the orientation correct? */
else if (orientA != 0 && orientA * orientC * geomA * geomC > 0) {
correct_orientation_flag = 1;
}
} else if (geomC == 0) {
/* different orientation classes */
if ((geomA + geomB) * (geomA - geomB) != 0) {
correct_orientation_flag = 1;
}
/* Same class, is the orientation correct? */
else if (orientA != 0 && orientA * orientB * geomA * geomB > 0) {
correct_orientation_flag = 1;
}
/* two geometries are the same */
} else if (geomB == geomC) {
/* different orientation classes */
if (((geomA + geomB) * (geomA - geomB) != 0) &&
(orientB == orientC)) {
correct_orientation_flag = 1;
}
/* Same class, is the orientation correct? */
else if ((orientA != 0 && orientA * orientB * geomA * geomB > 0) &&
(orientB == orientC)) {
correct_orientation_flag = 1;
}
} else if (geomA == geomC) {
/* different orientation classes */
if (((geomA + geomB) * (geomA - geomB) != 0) &&
(orientA == orientC)) {
correct_orientation_flag = 1;
}
/* Same class, is the orientation correct? */
else if ((orientA != 0 && orientA * orientB * geomA * geomB > 0) &&
(orientA == orientC)) {
correct_orientation_flag = 1;
}
} else if (geomA == geomB) {
/* different orientation classes */
if (((geomA + geomC) * (geomA - geomC) != 0) &&
(orientA == orientB)) {
correct_orientation_flag = 1;
}
/* Same class, is the orientation correct? */
else if ((orientA != 0 && orientA * orientC * geomA * geomC > 0) &&
(orientA == orientB)) {
correct_orientation_flag = 1;
}
/* all three geometries are non-zero but the same */
} else if ((geomA == geomB) && (geomA == geomC)) {
if ((orientA == orientB) && (orientA == orientC)) {
/* Same class, is the orientation correct? */
if (orientA != 0 && orientA * orientC * geomA * geomC > 0 &&
orientA * orientB * geomA * geomB > 0) {
correct_orientation_flag = 1;
}
}
}
}
if (correct_players_flag && correct_orientation_flag) {
if (num_matching_rxns >= MAX_MATCHING_RXNS)
break;
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
}
}
inter = inter->next;
}
if (num_matching_rxns > MAX_MATCHING_RXNS) {
mcell_warn("Number of matching reactions exceeds the maximum allowed "
"number MAX_MATCHING_RXNS.");
}
return num_matching_rxns;
}
/*************************************************************************
trigger_intersect:
In: hash value of molecule's species
pointer to a molecule
orientation of that molecule
pointer to a wall
array of matching reactions (placeholder for output)
flags that tells whether we should include special reactions
(REFL/TRANSP/ABSORB_REGION_BORDER) in the output array
Out: number of matching reactions for this
molecule/wall intersection, or for this mol/generic wall,
or this wall/generic mol. All matching reactions are placed in
the array "matching_rxns" in the first "number" slots.
Note: Moving molecule may be inert.
*************************************************************************/
int trigger_intersect(struct rxn **reaction_hash, int rx_hashsize,
struct species *all_mols, struct species *all_volume_mols,
struct species *all_surface_mols, u_int hashA,
struct abstract_molecule *reacA, short orientA,
struct wall *w, struct rxn **matching_rxns,
int allow_rx_transp, int allow_rx_reflec,
int allow_rx_absorb_reg_border) {
int num_matching_rxns = 0; /* number of matching rxns */
if (w->surf_class_head != NULL) {
num_matching_rxns = find_unimol_reactions_with_surf_classes(
reaction_hash, rx_hashsize, reacA, w, hashA, orientA, num_matching_rxns,
allow_rx_transp, allow_rx_reflec, allow_rx_absorb_reg_border,
matching_rxns);
}
for (struct surf_class_list *scl = w->surf_class_head; scl != NULL; scl = scl->next) {
if ((reacA->properties->flags & NOT_FREE) == 0) {
num_matching_rxns = find_volume_mol_reactions_with_surf_classes(
reaction_hash, rx_hashsize, all_mols, all_volume_mols, orientA,
scl->surf_class, num_matching_rxns, allow_rx_transp, allow_rx_reflec,
matching_rxns);
} else if ((reacA->properties->flags & ON_GRID) != 0) {
num_matching_rxns = find_surface_mol_reactions_with_surf_classes(
reaction_hash, rx_hashsize, all_mols, all_surface_mols, orientA,
scl->surf_class, num_matching_rxns, allow_rx_transp, allow_rx_reflec,
allow_rx_absorb_reg_border, matching_rxns);
}
}
return num_matching_rxns;
}
/*************************************************************************
*
* find all unimolecular reactions of reacA with surface classes on
* wall w.
*
* in: molecule to check for reactions,
* wall we want to test for reactions
* hash of molecule
* orientation of molecule
* number of matching reactions before the function call
* flag signalling the presence of transparent region border
* flag signalling the presence of a reflective region border
* flag signalling the presence of a absorbing region border
* array holding matching reactions
*
* out: returns number of matching reactions
* adds matching reactions to matching_rxns array
*
*************************************************************************/
int find_unimol_reactions_with_surf_classes(
struct rxn **reaction_hash, int rx_hashsize,
struct abstract_molecule *reacA, struct wall *w, u_int hashA, int orientA,
int num_matching_rxns, int allow_rx_transp, int allow_rx_reflec,
int allow_rx_absorb_reg_border, struct rxn **matching_rxns) {
u_int hash, hashW;
for (struct surf_class_list *scl = w->surf_class_head; scl != NULL; scl = scl->next) {
hashW = scl->surf_class->hashval;
hash = (hashA + hashW) & (rx_hashsize - 1);
struct rxn *inter = reaction_hash[hash];
while (inter != NULL) {
if (inter->n_reactants == 2) {
if ((inter->n_pathways == RX_TRANSP) && (!allow_rx_transp)) {
inter = inter->next;
continue;
}
if ((inter->n_pathways == RX_REFLEC) && (!allow_rx_reflec)) {
inter = inter->next;
continue;
}
if ((inter->n_pathways == RX_ABSORB_REGION_BORDER) &&
(!allow_rx_absorb_reg_border)) {
inter = inter->next;
continue;
}
if ((reacA->properties == inter->players[0] &&
scl->surf_class == inter->players[1]) ||
(reacA->properties == inter->players[1] &&
scl->surf_class == inter->players[0])) {
short geom1 = inter->geometries[0];
short geom2 = inter->geometries[1];
/* reaction matches if at least one of reactant/surface has
* a random orientation */
if (geom1 == 0 || geom2 == 0) {
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
}
/* reaction matches if reaction/surface are in different
* reaction classes */
else if ((geom1 + geom2) * (geom1 - geom2) != 0) {
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
}
/* reaction matches if reaction/surface are in same reaction
* class and their orientations match */
else if (orientA * geom1 * geom2 > 0) {
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
}
}
}
inter = inter->next;
}
}
return num_matching_rxns;
}
/*************************************************************************
*
* find all volume reactions for any volume molecule with orientation
* orientA with a surface class triggered via the ALL_MOLECULES and
* ALL_VOLUME_MOLECULE keywords
*
* in: orientation of surface molecule
* surface class species to test
* number of matching reactions before the function call
* flag signalling the presence of transparent region border
* flag signalling the presence of a reflective region border
* flag signalling the presence of a absorbing region border
* array holding matching reactions
*
* out: returns number of matching reactions
* adds matching reactions to matching_rxns array
*
*************************************************************************/
int find_volume_mol_reactions_with_surf_classes(
struct rxn **reaction_hash, int rx_hashsize, struct species *all_mols,
struct species *all_volume_mols, int orientA, struct species *scl,
int num_matching_rxns, int allow_rx_transp, int allow_rx_reflec,
struct rxn **matching_rxns) {
short geom1, geom2;
u_int hash_ALL_M = all_mols->hashval;
u_int hash_ALL_VOLUME_M = all_volume_mols->hashval;
u_int hashW = scl->hashval;
u_int hash = (hashW + hash_ALL_M) & (rx_hashsize - 1);
u_int hash2 = (hashW + hash_ALL_VOLUME_M) & (rx_hashsize - 1);
struct rxn *inter = reaction_hash[hash];
struct rxn *inter2 = reaction_hash[hash2];
while (inter != NULL) {
if (inter->n_reactants == 2) {
if ((inter->n_pathways == RX_TRANSP) && (!allow_rx_transp)) {
inter = inter->next;
continue;
}
if ((inter->n_pathways == RX_REFLEC) && (!allow_rx_reflec)) {
inter = inter->next;
continue;
}
if (all_mols == inter->players[0] && scl == inter->players[1]) {
geom1 = inter->geometries[0];
geom2 = inter->geometries[1];
if (geom1 == 0) {
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
} else if (geom2 == 0 || (geom1 + geom2) * (geom1 - geom2) != 0) {
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
} else if (orientA * geom1 * geom2 > 0) {
matching_rxns[num_matching_rxns] = inter;
num_matching_rxns++;
}
}
}
inter = inter->next;
}
while (inter2 != NULL) {
if (inter2->n_reactants == 2) {
if ((inter2->n_pathways == RX_TRANSP) && (!allow_rx_transp)) {
inter2 = inter2->next;
continue;
}
if ((inter2->n_pathways == RX_REFLEC) && (!allow_rx_reflec)) {
inter2 = inter2->next;
continue;
}
if (all_volume_mols == inter2->players[0] && scl == inter2->players[1]) {
geom1 = inter2->geometries[0];
geom2 = inter2->geometries[1];
if (geom1 == 0) {
matching_rxns[num_matching_rxns] = inter2;
num_matching_rxns++;
} else if (geom2 == 0 || (geom1 + geom2) * (geom1 - geom2) != 0) {
matching_rxns[num_matching_rxns] = inter2;
num_matching_rxns++;
} else if (orientA * geom1 * geom2 > 0) {
matching_rxns[num_matching_rxns] = inter2;
num_matching_rxns++;
}
}
}
inter2 = inter2->next;
}
return num_matching_rxns;
}
/*************************************************************************
*
* find all surface reactions for any surface molecule with orientation
* orientA on a surface class triggered via the ALL_MOLECULES and
* ALL_SURFACE_MOLECULE keywords
*
* in: orientation of surface molecule
* surface class species to test
* number of matching reactions before the function call
* flag signalling the presence of transparent region border
* flag signalling the presence of a reflective region border
* flag signalling the presence of a absorbing region border
* array holding matching reactions
*
* out: returns number of matching reactions
* adds matching reactions to matching_rxns array
*
*************************************************************************/
int find_surface_mol_reactions_with_surf_classes(
struct rxn **reaction_hash, int rx_hashsize, struct species *all_mols,
struct species *all_surface_mols, int orientA, struct species *scl,
int num_matching_rxns, int allow_rx_transp, int allow_rx_reflec,
int allow_rx_absorb_reg_border, struct rxn **matching_rxns) {
short geom1, geom2;
u_int hash_ALL_M = all_mols->hashval;
u_int hash_ALL_SURFACE_M = all_surface_mols->hashval;
u_int hashW = scl->hashval;
u_int hash = (hashW + hash_ALL_M) & (rx_hashsize - 1);
u_int hash2 = (hashW + hash_ALL_SURFACE_M) & (rx_hashsize - 1);
struct rxn *inter = reaction_hash[hash];
struct rxn *inter2 = reaction_hash[hash2];
while (inter != NULL) {
if (inter->n_reactants == 2) {
if ((inter->n_pathways == RX_TRANSP) && (!allow_rx_transp)) {
inter = inter->next;
continue;
}
if ((inter->n_pathways == RX_REFLEC) && (!allow_rx_reflec)) {
inter = inter->next;
continue;
}
/* In the context of ALL_MOLECULES and moving surface molecule
if the reaction is not of the type RX_REFLEC or RX_TRANSP
it should be then RX_ABSORB_REGION_BORDER and we force it here
to be this type. */
if (all_mols == inter->players[0] && scl == inter->players[1]) {
geom1 = inter->geometries[0];
geom2 = inter->geometries[1];
if (geom1 == 0) {
matching_rxns[num_matching_rxns] = inter;
if ((inter->n_pathways != RX_REFLEC) &&
(inter->n_pathways != RX_TRANSP) && allow_rx_absorb_reg_border) {
matching_rxns[num_matching_rxns]->n_pathways =
RX_ABSORB_REGION_BORDER;
}
num_matching_rxns++;
} else if (geom2 == 0 || (geom1 + geom2) * (geom1 - geom2) != 0) {
matching_rxns[num_matching_rxns] = inter;
if ((inter->n_pathways != RX_REFLEC) &&
(inter->n_pathways != RX_TRANSP) && allow_rx_absorb_reg_border) {
matching_rxns[num_matching_rxns]->n_pathways =
RX_ABSORB_REGION_BORDER;
}
num_matching_rxns++;
} else if (orientA * geom1 * geom2 > 0) {
matching_rxns[num_matching_rxns] = inter;
if ((inter->n_pathways != RX_REFLEC) &&
(inter->n_pathways != RX_TRANSP) && allow_rx_absorb_reg_border) {
matching_rxns[num_matching_rxns]->n_pathways =
RX_ABSORB_REGION_BORDER;
}
num_matching_rxns++;
}
}
}
inter = inter->next;
}
while (inter2 != NULL) {
if (inter2->n_reactants == 2) {
if ((inter2->n_pathways == RX_TRANSP) && (!allow_rx_transp)) {
inter2 = inter2->next;
continue;
}
if ((inter2->n_pathways == RX_REFLEC) && (!allow_rx_reflec)) {
inter2 = inter2->next;
continue;
}
if ((inter2->n_pathways == RX_ABSORB_REGION_BORDER) &&
(!allow_rx_absorb_reg_border)) {
inter2 = inter2->next;
continue;
}
if (all_surface_mols == inter2->players[0] && scl == inter2->players[1]) {
geom1 = inter2->geometries[0];
geom2 = inter2->geometries[1];
if (geom1 == 0) {
matching_rxns[num_matching_rxns] = inter2;
num_matching_rxns++;
} else if (geom2 == 0 || (geom1 + geom2) * (geom1 - geom2) != 0) {
matching_rxns[num_matching_rxns] = inter2;
num_matching_rxns++;
} else if (orientA * geom1 * geom2 > 0) {
matching_rxns[num_matching_rxns] = inter2;
num_matching_rxns++;
}
}
}
inter2 = inter2->next;
}
return num_matching_rxns;
}
/*************************************************************************
*
* compute_lifetime
*
* Determine time of next unimolecular reaction; may need to check before the
* next rate change for time dependent rates.
*
* In: state: system state
* am: pointer to abstract molecule to be tested for unimolecular reaction
*
*************************************************************************/
void compute_lifetime(struct volume *state,
struct rxn *r,
struct abstract_molecule *am) {
if (r != NULL) {
double tt = FOREVER;
am->t2 = timeof_unimolecular(r, am, state->rng);
#ifdef DEBUG_RXNS
struct volume *world = state;
if ((am->flags & TYPE_VOL) != 0) {
DUMP_CONDITION3(
dump_volume_molecule((struct volume_molecule *)am, "", true, "Assigned unimolecular time (prev rng):", world->current_iterations, am->t2, true);
);
}
else {
DUMP_CONDITION3(
dump_surface_molecule((struct surface_molecule *)am, "", true, "Assigned unimolecular time (prev rng):", world->current_iterations, am->t2, true);
);
}
#endif
if (r->prob_t != NULL) {
tt = r->prob_t->time;
}
if (am->t + am->t2 > tt) {
am->t2 = tt - am->t;
am->flags |= ACT_CHANGE;
}
} else {
am->t2 = FOREVER;
}
}
/*************************************************************************
*
* This function tests for the occurence of unimolecular reactions and is used
* during the main event loop (run_timestep).
*
* In: state: system state
* am: pointer to abstract molecule to be tested for unimolecular
* reaction
*
* Out: 1 if molecule still exists
* 0 if molecule is gone
*
*************************************************************************/
int check_for_unimolecular_reaction(struct volume *state,
struct abstract_molecule *am) {
struct rxn *r = NULL;
if ((am->flags & (ACT_NEWBIE + ACT_CHANGE)) != 0) {
am->flags -= (am->flags & (ACT_NEWBIE + ACT_CHANGE));
if ((am->flags & ACT_REACT) != 0) {
r = pick_unimolecular_reaction(state, am);
compute_lifetime(state, r, am);
//temporary reaction for querying an external species
/*if(am->properties->flags & EXTERNAL_SPECIES){
free(r);
}*/
}
} else if ((am->flags & ACT_REACT) != 0) {
r = pick_unimolecular_reaction(state, am);
int i = 0;
int j = 0;
if (r != NULL) {
i = which_unimolecular(r, am, state->rng);
j = outcome_unimolecular(state, r, i, am, am->t);
} else {
j = RX_NO_RX;
}
if (j != RX_DESTROY) { // We still exist
compute_lifetime(state, r, am);
} else { // We don't exist. Try to recover memory.
return 0;
}
}
return 1;
}
/**********************************************************************
*
* This function picks a unimolecular reaction for molecule "am"
*
* In: state: system state
* am: pointer to abstract molecule am for which to pick a unimolecular
* reaction
*
* Out: the picked reaction or NULL if none was found
*
**********************************************************************/
struct rxn *pick_unimolecular_reaction(struct volume *state,
struct abstract_molecule *am) {
struct rxn *r2 = NULL;
int num_matching_rxns = 0;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
//relegate initialization to nfsim
if(am->properties->flags & EXTERNAL_SPECIES){
r2 = pick_unimolecular_reaction_nfsim(state, am);
return r2;
}
//else
struct rxn *r = trigger_unimolecular(state->reaction_hash, state->rx_hashsize,
am->properties->hashval, am);
if ((r != NULL) && (r->prob_t != NULL)) {
update_probs(state, r, (am->t + am->t2) * (1.0 + EPS_C));
}
int can_surf_react = ((am->properties->flags & CAN_SURFWALL) != 0);
if (can_surf_react) {
num_matching_rxns =
trigger_surface_unimol(
state->reaction_hash, state->rx_hashsize, state->all_mols,
state->all_volume_mols, state->all_surface_mols, am, NULL,
matching_rxns);
for (int jj = 0; jj < num_matching_rxns; jj++) {
if ((matching_rxns[jj] != NULL) && (matching_rxns[jj]->prob_t != NULL)) {
update_probs(
state, matching_rxns[jj], (am->t + am->t2) * (1.0 + EPS_C));
}
}
}
if (r != NULL) {
matching_rxns[num_matching_rxns] = r;
num_matching_rxns++;
}
if (num_matching_rxns == 1) {
r2 = matching_rxns[0];
} else if (num_matching_rxns > 1) {
r2 = test_many_unimol(matching_rxns, num_matching_rxns, am, state->rng);
}
return r2;
}
| C |
3D | mcellteam/mcell | src/react_util.h | .h | 1,377 | 35 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
double compute_pb_factor(double time_unit,
double length_unit,
double grid_density,
double rx_radius_3d,
struct reaction_flags *rxn_flags,
int *create_shared_walls_info_flag,
struct rxn *rx,
int max_num_surf_products);
int get_rxn_by_name(struct rxn **reaction_hash, int hashsize,
const char *rx_name, struct rxn **found_rx, int *path_id);
int change_reaction_probability(byte *reaction_prob_limit_flag,
struct notifications *notify, struct rxn *rx,
int path_id, double new_rate);
void issue_reaction_probability_warnings(struct notifications *notify,
struct rxn *rx);
| Unknown |
3D | mcellteam/mcell | src/vol_util.c | .c | 94,050 | 2,689 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/**************************************************************************\
** File: vol_util.c **
** **
** Purpose: Adds, subtracts, and moves particles around (bookkeeping). **
** **
** Testing status: compiles. Worked earlier, but has been changed. **
\**************************************************************************/
#include "config.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "diffuse.h"
#include "vector.h"
#include "logging.h"
#include "rng.h"
#include "mem_util.h"
#include "count_util.h"
#include "vol_util.h"
#include "react.h"
#include "wall_util.h"
#include "grid_util.h"
#include "nfsim_func.h"
#include "mcell_reactions.h"
#include "diffuse.h"
#include "debug_config.h"
#include "dump_state.h"
static int test_max_release(double num_to_release, char *name);
static int check_release_probability(double release_prob, struct volume *state,
struct release_event_queue *req,
struct release_pattern *rpat);
static int skip_past_events(double release_prob, struct volume *state,
struct release_event_queue *req,
struct release_pattern *rpat);
static int calculate_number_to_release(struct release_site_obj *rso,
struct volume *state);
static int release_inside_regions(struct volume *state,
struct release_site_obj *rso,
struct volume_molecule *vm, int n);
static int num_vol_mols_from_conc(struct release_site_obj *rso,
double length_unit, bool *exactNumber);
/*************************************************************************
inside_subvolume:
In: pointer to vector3
pointer to subvolume
Out: nonzero if the vector is inside the subvolume.
*************************************************************************/
int inside_subvolume(struct vector3 *point, struct subvolume *subvol,
double *x_fineparts, double *y_fineparts,
double *z_fineparts) {
return ((point->x >= x_fineparts[subvol->llf.x]) &&
(point->x <= x_fineparts[subvol->urb.x]) &&
(point->y >= y_fineparts[subvol->llf.y]) &&
(point->y <= y_fineparts[subvol->urb.y]) &&
(point->z >= z_fineparts[subvol->llf.z]) &&
(point->z <= z_fineparts[subvol->urb.z]));
}
/*************************************************************************
find_coarse_subvolume:
In: pointer to vector3
Out: pointer to the coarse subvolume that the vector is within
*************************************************************************/
struct subvolume *find_coarse_subvol(struct volume *state,
struct vector3 *loc) {
int i = bisect(state->x_partitions, state->nx_parts, loc->x);
int j = bisect(state->y_partitions, state->ny_parts, loc->y);
int k = bisect(state->z_partitions, state->nz_parts, loc->z);
return &(state->subvol
[k + (state->nz_parts - 1) * (j + (state->ny_parts - 1) * i)]);
}
/*************************************************************************
traverse_subvol:
In: pointer to our current subvolume
pointer to a vector3 of where we want to be
which direction we're traveling to get there
Out: subvolume that's closest to where we want to be in our direction
Note: BSP trees traverse is not yet implemented
*************************************************************************/
struct subvolume *traverse_subvol(struct subvolume *here,
int which, int ny_parts, int nz_parts) {
switch (which) {
case X_NEG:
if (here->world_edge & X_NEG_BIT)
return NULL;
return here - (nz_parts - 1) * (ny_parts - 1);
case X_POS:
if (here->world_edge & X_POS_BIT)
return NULL;
return here + (nz_parts - 1) * (ny_parts - 1);
case Y_NEG:
if (here->world_edge & Y_NEG_BIT)
return NULL;
return here - (nz_parts - 1);
case Y_POS:
if (here->world_edge & Y_POS_BIT)
return NULL;
return here + (nz_parts - 1);
case Z_NEG:
if (here->world_edge & Z_NEG_BIT)
return NULL;
return here - 1;
case Z_POS:
if (here->world_edge & Z_POS_BIT)
return NULL;
return here + 1;
default:
mcell_internal_error(
"Invalid direction specified in traverse_subvol (dir=%d).", which);
return NULL;
} /* end switch */
}
/*************************************************************************
collide_sv_time:
In: pointer to a vector3 of where we are (*here)
pointer to a vector3 of where we want to be
our current subvolume
Out: time to hit the closest wall of the subvolume
*************************************************************************/
double collide_sv_time(struct vector3 *here, struct vector3 *move,
struct subvolume *sv, double *x_fineparts,
double *y_fineparts, double *z_fineparts) {
double dx, dy, dz, tx, ty, tz, t;
if ((!distinguishable(move->x, 0, EPS_C)) &&
(!distinguishable(move->y, 0, EPS_C)) &&
(!distinguishable(move->z, 0, EPS_C))) {
return GIGANTIC;
}
if (move->x > 0)
dx = x_fineparts[sv->urb.x] - here->x;
else {
dx = x_fineparts[sv->llf.x] - here->x;
}
if (move->y > 0)
dy = y_fineparts[sv->urb.y] - here->y;
else {
dy = y_fineparts[sv->llf.y] - here->y;
}
if (move->z > 0)
dz = z_fineparts[sv->urb.z] - here->z;
else {
dz = z_fineparts[sv->llf.z] - here->z;
}
tx = GIGANTIC;
if (distinguishable(move->x, 0, EPS_C)) {
tx = dx / move->x;
}
ty = GIGANTIC;
if (distinguishable(move->y, 0, EPS_C)) {
ty = dy / move->y;
}
tz = GIGANTIC;
if (distinguishable(move->z, 0, EPS_C)) {
tz = dz / move->z;
}
if (tx < ty) {
if (tx < tz) {
t = tx;
} else {
t = tz;
}
} else {
if (ty < tz) {
t = ty;
} else {
t = tz;
}
}
return t;
}
/*************************************************************************
next_subvol:
In: pointer to a vector3 of where we are (*here)
pointer to a vector3 of where we want to be
our current subvolume
Out: next subvolume along that vector or NULL if the endpoint is
in the current subvolume. *here is updated to just inside
the next subvolume.
*************************************************************************/
struct subvolume *next_subvol(struct vector3 *here, struct vector3 *move,
struct subvolume *sv, double *x_fineparts,
double *y_fineparts, double *z_fineparts,
int ny_parts, int nz_parts) {
double dx, dy, dz, tx, ty, tz, t;
int which;
int whichx = 1, whichy = 1, whichz = 1;
if ((!distinguishable(move->x, 0, EPS_C)) &&
(!distinguishable(move->y, 0, EPS_C)) &&
(!distinguishable(move->z, 0, EPS_C))) {
return NULL;
}
if (move->x > 0)
dx = x_fineparts[sv->urb.x] - here->x;
else {
dx = x_fineparts[sv->llf.x] - here->x;
whichx = 0;
}
if (move->y > 0)
dy = y_fineparts[sv->urb.y] - here->y;
else {
dy = y_fineparts[sv->llf.y] - here->y;
whichy = 0;
}
if (move->z > 0)
dz = z_fineparts[sv->urb.z] - here->z;
else {
dz = z_fineparts[sv->llf.z] - here->z;
whichz = 0;
}
if (move->x == 0.0) {
ty = dy * move->z;
if (ty < 0)
ty = -ty;
tz = move->y * dz;
if (tz < 0)
tz = -tz;
if (ty < tz) {
t = dy / move->y;
which = Y_NEG + whichy;
} else {
t = dz / move->z;
which = Z_NEG + whichz;
}
} else if (move->y == 0.0) {
tx = dx * move->z;
if (tx < 0)
tx = -tx;
tz = move->x * dz;
if (tz < 0)
tz = -tz;
if (tx < tz) {
t = dx / move->x;
which = X_NEG + whichx;
} else {
t = dz / move->z;
which = Z_NEG + whichz;
}
} else if (move->z == 0.0) {
tx = dx * move->y;
if (tx < 0)
tx = -tx;
ty = move->x * dy;
if (ty < 0)
ty = -ty;
if (tx < ty) {
t = dx / move->x;
which = X_NEG + whichx;
} else {
t = dy / move->y;
which = Y_NEG + whichy;
}
} else {
tx = dx * move->y * move->z;
if (tx < 0)
tx = -tx;
ty = move->x * dy * move->z;
if (ty < 0)
ty = -ty;
tz = move->x * move->y * dz;
if (tz < 0)
tz = -tz;
if (tx < ty) {
if (tx < tz) {
t = dx / move->x;
which = X_NEG + whichx;
} else {
t = dz / move->z;
which = Z_NEG + whichz;
}
} else /* ty<tx */
{
if (ty < tz) {
t = dy / move->y;
which = Y_NEG + whichy;
} else {
t = dz / move->z;
which = Z_NEG + whichz;
}
}
}
if (t >= 1.0) {
here->x += move->x;
here->y += move->y;
here->z += move->z;
return NULL;
} else {
here->x += t * move->x;
here->y += t * move->y;
here->z += t * move->z;
t = 1.0 - t;
move->x *= t;
move->y *= t;
move->z *= t;
return traverse_subvol(sv, which, ny_parts, nz_parts);
}
}
/*************************************************************************
find_subvolume:
In: pointer to a vector3 of where we are
pointer to a subvolume we might be in or near
Out: subvolume that we are in
*************************************************************************/
struct subvolume *find_subvolume(struct volume *state, struct vector3 *loc,
struct subvolume *guess) {
/* This code is faster if coarse subvolumes are always used */
if (guess == NULL)
return find_coarse_subvol(state, loc);
else {
if (state->x_fineparts[guess->llf.x] <= loc->x &&
loc->x <= state->x_fineparts[guess->urb.x] &&
state->y_fineparts[guess->llf.y] <= loc->y &&
loc->y <= state->y_fineparts[guess->urb.y] &&
state->z_fineparts[guess->llf.z] <= loc->z &&
loc->z <= state->z_fineparts[guess->urb.z]) {
return guess;
} else
return find_coarse_subvol(state, loc);
}
}
/*************************************************************************
is_defunct_molecule
In: abstract_element that is assumed to be an abstract_molecule
Out: 0 if the properties field is set, 1 if it is NULL
Note: This function is passed to sched_util so it can tell which
molecules are active and which are defunct and can be cleaned up.
*************************************************************************/
int is_defunct_molecule(struct abstract_element *e) {
return ((struct abstract_molecule *)e)->properties == NULL;
}
/*struct surface_molecule **/
/*place_surface_molecule(struct volume *state, struct species *s,*/
/* struct vector3 *loc, short orient, double search_diam,*/
/* double t, struct subvolume **psv, char *mesh_name,*/
/* struct string_buffer *reg_names,*/
/* struct string_buffer *regions_to_ignore) {*/
struct wall* find_closest_wall(
struct volume *state, struct vector3 *loc, double search_diam,
struct vector2 *best_uv, int *grid_index, struct species *s, const char *mesh_name,
struct string_buffer *reg_names, struct string_buffer *regions_to_ignore) {
double d2;
struct vector2 s_loc;
/*struct vector2 best_uv;*/
struct vector3 best_xyz;
double search_d2;
if (search_diam <= EPS_C)
search_d2 = EPS_C * EPS_C;
else
search_d2 = search_diam * search_diam;
struct subvolume *sv = find_subvolume(state, loc, NULL);
char *species_name = s->sym->name;
unsigned int keyhash = (unsigned int)(intptr_t)(species_name);
void *key = (void *)(species_name);
struct mesh_transparency *mesh_transp = (
struct mesh_transparency *)pointer_hash_lookup(state->species_mesh_transp,
key, keyhash);
double best_d2 = search_d2 * 2 + 1;
struct wall *best_w = NULL;
struct wall_list *wl;
for (wl = sv->wall_head; wl != NULL; wl = wl->next) {
if (verify_wall_regions_match(
mesh_name, reg_names, wl->this_wall, regions_to_ignore, mesh_transp,
species_name)) {
continue;
}
d2 = closest_interior_point(loc, wl->this_wall, &s_loc, search_d2);
if (d2 <= search_d2 && d2 < best_d2) {
best_d2 = d2;
best_w = wl->this_wall;
best_uv->u = s_loc.u;
best_uv->v = s_loc.v;
}
}
if (search_d2 > EPS_C * EPS_C) /* Might need to look in adjacent subvolumes */
{
const int sv_index = sv - state->subvol;
int sv_remain = sv_index;
/* Turn linear sv_index into part_x, part_y, part_z triple. */
const int part_x =
sv_remain / ((state->ny_parts - 1) * (state->nz_parts - 1));
sv_remain -= part_x * ((state->ny_parts - 1) * (state->nz_parts - 1));
const int part_y = sv_remain / (state->nz_parts - 1);
sv_remain -= part_y * (state->nz_parts - 1);
const int part_z = sv_remain;
/* Find min x partition. */
int x_min;
for (x_min = part_x; x_min > 0; x_min--) {
d2 = loc->x - state->x_partitions[x_min];
d2 *= d2;
if (d2 >= best_d2 || d2 >= search_d2)
break;
}
/* Find max x partition. */
int x_max;
for (x_max = part_x; x_max < state->nx_parts - 1; x_max++) {
d2 = loc->x - state->x_partitions[x_max + 1];
d2 *= d2;
if (d2 >= best_d2 || d2 >= search_d2)
break;
}
/* Find min y partition. */
int y_min;
for (y_min = part_y; y_min > 0; y_min--) {
d2 = loc->y - state->y_partitions[y_min];
d2 *= d2;
if (d2 >= best_d2 || d2 >= search_d2)
break;
}
/* Find max y partition. */
int y_max;
for (y_max = part_y; y_max < state->ny_parts - 1; y_max++) {
d2 = loc->y - state->y_partitions[y_max + 1];
d2 *= d2;
if (d2 >= best_d2 || d2 >= search_d2)
break;
}
/* Find min z partition. */
int z_min;
for (z_min = part_z; z_min > 0; z_min--) {
d2 = loc->z - state->z_partitions[z_min];
d2 *= d2;
if (d2 >= best_d2 || d2 >= search_d2)
break;
}
/* Find max z partition. */
int z_max;
for (z_max = part_z; z_max < state->nz_parts - 1; z_max++) {
d2 = loc->z - state->z_partitions[z_max + 1];
d2 *= d2;
if (d2 >= best_d2 || d2 >= search_d2)
break;
}
if (x_min < part_x || x_max > part_x || y_min < part_y || y_max > part_y ||
z_min < part_z || z_max > part_z) {
for (int px = x_min; px <= x_max; px++) {
for (int py = y_min; py <= y_max; py++) {
for (int pz = z_min; pz <= z_max; pz++) {
const int this_sv =
pz + (state->nz_parts - 1) * (py + (state->ny_parts - 1) * px);
if (this_sv == sv_index)
continue;
for (wl = state->subvol[this_sv].wall_head; wl != NULL;
wl = wl->next) {
if (verify_wall_regions_match(
mesh_name, reg_names, wl->this_wall, regions_to_ignore,
mesh_transp, species_name)) {
continue;
}
d2 =
closest_interior_point(loc, wl->this_wall, &s_loc, search_d2);
if (d2 <= search_d2 && d2 < best_d2) {
best_d2 = d2;
best_w = wl->this_wall;
best_uv->u = s_loc.u;
best_uv->v = s_loc.v;
}
}
}
}
}
if (best_w != NULL) {
uv2xyz(best_uv, best_w, &best_xyz);
sv = find_subvolume(state, &best_xyz,
sv); /* May have switched subvolumes */
}
}
}
if (best_w == NULL) {
return NULL;
}
/* We can look this far around the surface we hit for an empty spot */
d2 = search_d2 - best_d2;
if (best_w->grid == NULL) {
if (create_grid(state, best_w, sv))
mcell_allocfailed("Failed to create grid for wall.");
*grid_index = uv2grid(best_uv, best_w->grid);
} else {
*grid_index = uv2grid(best_uv, best_w->grid);
struct surface_molecule_list *sm_list = best_w->grid->sm_list[*grid_index];
if (sm_list && sm_list->sm) {
// XXX: this isn't good enough. we should only return this if the PB of
// sm isn't represented in the PB list.
if (state->periodic_box_obj && !state->periodic_traditional) {
return best_w;
}
if (d2 <= EPS_C * EPS_C) {
return NULL;
} else {
struct wall* orig_best_w = best_w;
best_w = search_nbhd_for_free(
state, best_w, best_uv, d2, grid_index, NULL, NULL, mesh_name,
reg_names);
ASSERT_FOR_MCELL4(orig_best_w == best_w);
if (best_w == NULL) {
return NULL;
}
if (state->randomize_smol_pos)
grid2uv_random(best_w->grid, *grid_index, best_uv, state->rng);
else
grid2uv(best_w->grid, *grid_index, best_uv);
}
}
}
return best_w;
}
/*************************************************************************
place_surface_molecule
In: species for the new molecule
3D location of the new molecule
orientation of the new molecule
diameter to search for a free surface spot
schedule time for the new molecule
Out: pointer to the new molecule, or NULL if no free spot was found.
Note: This function halts the program if it runs out of memory.
This function is similar to insert_surface_molecule, but it does
not schedule the molecule or add it to the count. This is done
to simplify the logic when placing a surface macromolecule.
(i.e. place all molecules, and once we're sure we've succeeded,
schedule them all and count them all.)
*************************************************************************/
struct surface_molecule *
place_surface_molecule(struct volume *state, struct species *s,
struct vector3 *loc, short orient, double search_diam,
double t, struct subvolume **psv, const char *mesh_name,
struct string_buffer *reg_names,
struct string_buffer *regions_to_ignore,
struct periodic_image *periodic_box) {
struct vector2 best_uv;
struct vector3 best_xyz;
int grid_index = 0;
int *grid_index_p = &grid_index;
struct wall *best_w = find_closest_wall(
state, loc, search_diam, &best_uv, grid_index_p, s, mesh_name, reg_names,
regions_to_ignore);
if (best_w == NULL) {
return NULL;
}
if (state->periodic_box_obj) {
struct polygon_object *p = (struct polygon_object*)(state->periodic_box_obj->contents);
struct subdivided_box *sb = p->sb;
struct vector3 llf = {sb->x[0], sb->y[0], sb->z[0]};
struct vector3 urb = {sb->x[1], sb->y[1], sb->z[1]};
struct vector3 pos3d;
uv2xyz(&best_uv, best_w, &pos3d);
if (!point_in_box(&llf, &urb, &pos3d)) {
return NULL;
}
}
struct surface_molecule_list *sm_list = best_w->grid->sm_list[grid_index];
if (state->periodic_box_obj && periodicbox_in_surfmol_list(periodic_box, sm_list)) {
return NULL;
}
uv2xyz(&best_uv, best_w, &best_xyz);
struct subvolume *sv = NULL;
sv = find_subvolume(state, &best_xyz, sv);
struct surface_molecule *sm;
sm = (struct surface_molecule *)CHECKED_MEM_GET(sv->local_storage->smol, "surface molecule");
sm->mesh_name = NULL;
sm->birthplace = sv->local_storage->smol;
sm->birthday = convert_iterations_to_seconds(
state->start_iterations, state->time_unit,
state->simulation_start_seconds, t);
sm->id = state->current_mol_id++;
sm->properties = s;
initialize_diffusion_function((struct abstract_molecule*)sm);
s->population++;
sm->periodic_box = CHECKED_MALLOC_STRUCT(struct periodic_image,
"periodic image descriptor");
sm->periodic_box->x = periodic_box->x;
sm->periodic_box->y = periodic_box->y;
sm->periodic_box->z = periodic_box->z;
sm->flags = TYPE_SURF | ACT_NEWBIE | IN_SCHEDULE;
if (sm->get_space_step(sm) > 0)
sm->flags |= ACT_DIFFUSE;
if (trigger_unimolecular(state->reaction_hash, state->rx_hashsize, s->hashval,
(struct abstract_molecule *)sm) != NULL ||
(s->flags & CAN_SURFWALL) != 0)
sm->flags |= ACT_REACT;
sm->t = t;
sm->t2 = 0.0;
sm->grid = best_w->grid;
sm->grid_index = grid_index;
sm->s_pos.u = best_uv.u;
sm->s_pos.v = best_uv.v;
sm->orient = orient;
sm_list = add_surfmol_with_unique_pb_to_list(sm_list, sm);
if (sm_list == NULL) {
return NULL;
}
sm->grid->sm_list[sm->grid_index] = sm_list;
sm->grid->n_occupied++;
sm->flags |= IN_SURFACE;
if ((s->flags & COUNT_ENCLOSED) != 0)
sm->flags |= COUNT_ME;
*psv = sv;
return sm;
}
/*************************************************************************
insert_surface_molecule
In: species for the new molecule
3D location of the new molecule
orientation of the new molecule
diameter to search for a free surface spot (vector3 now, should be
double!)
schedule time for the new molecule
Out: pointer to the new molecule, or NULL if no free spot was found.
Note: This function halts the program if it runs out of memory.
*************************************************************************/
struct surface_molecule *
insert_surface_molecule(struct volume *state, struct species *s,
struct vector3 *loc, short orient, double search_diam,
double t, const char *mesh_name,
struct string_buffer *reg_names,
struct string_buffer *regions_to_ignore,
struct periodic_image *periodic_box) {
struct subvolume *sv = NULL;
struct surface_molecule *sm =
place_surface_molecule(
state, s, loc, orient, search_diam, t, &sv, mesh_name, reg_names,
regions_to_ignore, periodic_box);
if (sm == NULL)
return NULL;
#ifdef DEBUG_DYNAMIC_GEOMETRY
dump_surface_molecule(sm, "", true, "Sm after being moved: ", state->current_iterations, /*vm->t*/0, true);
#endif
if (periodic_box != NULL) {
sm->periodic_box->x = periodic_box->x;
sm->periodic_box->y = periodic_box->y;
sm->periodic_box->z = periodic_box->z;
}
if (sm->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED))
count_region_from_scratch(state, (struct abstract_molecule *)sm, NULL, 1,
NULL, sm->grid->surface, sm->t, NULL);
if (schedule_add_mol(sv->local_storage->timer, sm))
mcell_allocfailed("Failed to add surface molecule to scheduler.");
return sm;
}
/*************************************************************************
insert_volume_molecule
In: pointer to a volume_molecule that we're going to place in local storage
pointer to a volume_molecule that may be nearby
Out: pointer to the new volume_molecule (copies data from volume molecule
passed in), or NULL if out of memory. Molecule is placed in scheduler
also.
*************************************************************************/
struct volume_molecule *insert_volume_molecule(
struct volume *state, struct volume_molecule *vm,
struct volume_molecule *vm_guess) {
struct subvolume *sv;
if (vm_guess == NULL)
sv = find_subvolume(state, &(vm->pos), NULL);
else if (inside_subvolume(&(vm->pos), vm_guess->subvol, state->x_fineparts,
state->y_fineparts, state->z_fineparts))
sv = vm_guess->subvol;
else
sv = find_subvolume(state, &(vm->pos), vm_guess->subvol);
// Make sure this molecule isn't outside of the periodic boundaries
struct vector3 llf, urb;
if (state->periodic_box_obj) {
struct polygon_object *p = (struct polygon_object*)(state->periodic_box_obj->contents);
struct subdivided_box *sb = p->sb;
struct vector3 llf = {sb->x[0], sb->y[0], sb->z[0]};
struct vector3 urb = {sb->x[1], sb->y[1], sb->z[1]};
if (!point_in_box(&llf, &urb, &vm->pos)) {
mcell_error("cannot release '%s' outside of periodic boundaries.",
vm->properties->sym->name);
return NULL;
}
}
struct volume_molecule *new_vm;
new_vm = (struct volume_molecule *)CHECKED_MEM_GET(sv->local_storage->mol, "volume molecule");
memcpy(new_vm, vm, sizeof(struct volume_molecule));
new_vm->mesh_name = NULL;
new_vm->birthplace = sv->local_storage->mol;
new_vm->id = state->current_mol_id++;
#ifdef DEBUG_RELEASES
vm->id = new_vm->id;
#endif
new_vm->prev_v = NULL;
new_vm->next_v = NULL;
new_vm->next = NULL;
new_vm->subvol = sv;
ht_add_molecule_to_list(&sv->mol_by_species, new_vm);
sv->mol_count++;
new_vm->properties->population++;
new_vm->periodic_box = CHECKED_MALLOC_STRUCT(struct periodic_image,
"periodic image descriptor");
new_vm->periodic_box->x = vm->periodic_box->x;
new_vm->periodic_box->y = vm->periodic_box->y;
new_vm->periodic_box->z = vm->periodic_box->z;
//initialize function pointer to diffusion function
initialize_diffusion_function((struct abstract_molecule*)new_vm);
if ((new_vm->properties->flags & COUNT_SOME_MASK) != 0)
new_vm->flags |= COUNT_ME;
if (new_vm->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) {
count_region_from_scratch(state, (struct abstract_molecule *)new_vm, NULL,
1, &(new_vm->pos), NULL, new_vm->t,
new_vm->periodic_box);
}
if (schedule_add_mol(sv->local_storage->timer, new_vm))
mcell_allocfailed("Failed to add volume molecule to scheduler.");
return new_vm;
}
static int remove_from_list(struct volume_molecule *it) {
if (it->prev_v) {
#ifdef DEBUG_LIST_CHECKS
if (*it->prev_v != it) {
mcell_error_nodie("Stale previous pointer!");
}
#endif
*(it->prev_v) = it->next_v;
} else {
#ifdef DEBUG_LIST_CHECKS
mcell_error_nodie("No previous pointer.");
#endif
}
if (it->next_v) {
#ifdef DEBUG_LIST_CHECKS
if (it->next_v->prev_v != &it->next_v) {
mcell_error_nodie("Stale next pointer!");
}
#endif
it->next_v->prev_v = it->prev_v;
}
it->prev_v = NULL;
it->next_v = NULL;
return 1;
}
/*************************************************************************
migrate_volume_molecule:
In: pointer to a volume_molecule already in a subvolume
pointer to the new subvolume to move it to
Out: pointer to moved molecule. The molecule's position is updated
but it is not rescheduled. Returns NULL if out of memory.
*************************************************************************/
struct volume_molecule *migrate_volume_molecule(struct volume_molecule *vm,
struct subvolume *new_sv) {
struct volume_molecule *new_vm;
new_sv->mol_count++;
vm->subvol->mol_count--;
if (vm->subvol->local_storage == new_sv->local_storage) {
if (remove_from_list(vm)) {
vm->subvol = new_sv;
ht_add_molecule_to_list(&new_sv->mol_by_species, vm);
return vm;
}
}
new_vm = (struct volume_molecule *)CHECKED_MEM_GET(new_sv->local_storage->mol, "volume molecule");
memcpy(new_vm, vm, sizeof(struct volume_molecule));
new_vm->birthplace = new_sv->local_storage->mol;
new_vm->mesh_name = NULL;
new_vm->prev_v = NULL;
new_vm->next_v = NULL;
new_vm->next = NULL;
new_vm->subvol = new_sv;
ht_add_molecule_to_list(&new_sv->mol_by_species, new_vm);
collect_molecule(vm);
return new_vm;
}
/*************************************************************************
eval_rel_region_3d:
In: an expression tree containing regions to release on
the waypoint for the current subvolume
a list of regions entered from the waypoint to the release loc.
a list of regions exited from the waypoint to the release loc.
Out: 1 if the location chosen satisfies the expression, 0 if not.
*************************************************************************/
int eval_rel_region_3d(struct release_evaluator *expr, struct waypoint *wp,
struct region_list *in_regions,
struct region_list *out_regions) {
struct region *r;
struct region_list *rl;
int satisfies_l, satisfies_r;
satisfies_l = 0;
if (expr->op & REXP_LEFT_REGION) {
r = (struct region *)expr->left;
for (rl = wp->regions; rl != NULL; rl = rl->next) {
if (rl->reg == r) {
satisfies_l = 1;
break;
}
}
if (satisfies_l) {
for (rl = out_regions; rl != NULL; rl = rl->next) {
if (rl->reg == r) {
satisfies_l = 0;
break;
}
}
} else {
for (rl = in_regions; rl != NULL; rl = rl->next) {
if (rl->reg == r) {
satisfies_l = 1;
break;
}
}
}
} else
satisfies_l = eval_rel_region_3d((struct release_evaluator *)expr->left, wp, in_regions, out_regions);
if (expr->op & REXP_NO_OP)
return satisfies_l;
satisfies_r = 0;
if (expr->op & REXP_RIGHT_REGION) {
r = (struct region *)expr->right;
for (rl = wp->regions; rl != NULL; rl = rl->next) {
if (rl->reg == r) {
satisfies_r = 1;
break;
}
}
if (satisfies_r) {
for (rl = out_regions; rl != NULL; rl = rl->next) {
if (rl->reg == r) {
satisfies_r = 0;
break;
}
}
} else {
for (rl = in_regions; rl != NULL; rl = rl->next) {
if (rl->reg == r) {
satisfies_r = 1;
break;
}
}
}
} else
satisfies_r = eval_rel_region_3d((struct release_evaluator *)expr->right, wp, in_regions, out_regions);
if (expr->op & REXP_UNION)
return (satisfies_l || satisfies_r);
else if (expr->op & (REXP_INTERSECTION))
return (satisfies_l && satisfies_r);
else if (expr->op & REXP_SUBTRACTION)
return (satisfies_l && !satisfies_r);
return 0;
}
/*************************************************************************
vacuum_inside_regions:
In: pointer to a release site object
template molecule to remove
integer number of molecules to remove (negative)
Out: 0 on success, 1 on failure; molecule(s) are removed from the
state as specified.
Note: if more molecules are to be removed than actually exist, all
existing molecules of the specified type are removed.
*************************************************************************/
static int vacuum_inside_regions(struct volume *state,
struct release_site_obj *rso,
struct volume_molecule *vm, int n) {
struct volume_molecule *mp;
struct release_region_data *rrd;
struct region_list *extra_in, *extra_out;
struct region_list *rl, *rl2;
struct waypoint *wp;
struct subvolume *sv = NULL;
struct mem_helper *mh;
struct void_list *vl;
struct void_list *vl_head = NULL;
int vl_num = 0;
double t;
struct vector3 hit, delta;
struct vector3 *origin;
struct wall_list *wl;
rrd = rso->region_data;
mh = create_mem(sizeof(struct void_list), 1024);
if (mh == NULL)
return 1;
const int x_min = bisect(state->x_partitions, state->nx_parts, rrd->llf.x);
const int x_max =
bisect_high(state->x_partitions, state->nx_parts, rrd->urb.x);
const int y_min = bisect(state->y_partitions, state->ny_parts, rrd->llf.y);
const int y_max =
bisect_high(state->y_partitions, state->ny_parts, rrd->urb.y);
const int z_min = bisect(state->z_partitions, state->nz_parts, rrd->llf.z);
const int z_max =
bisect_high(state->z_partitions, state->nz_parts, rrd->urb.z);
for (int px = x_min; px < x_max; px++) {
for (int py = y_min; py < y_max; py++) {
for (int pz = z_min; pz < z_max; pz++) {
const int this_sv =
pz + (state->nz_parts - 1) * (py + (state->ny_parts - 1) * px);
sv = &(state->subvol[this_sv]);
struct per_species_list *psl =
(struct per_species_list *)pointer_hash_lookup(
&sv->mol_by_species, vm->properties, vm->properties->hashval);
if (psl != NULL) {
for (mp = psl->head; mp != NULL; mp = mp->next_v) {
extra_in = extra_out = NULL;
wp = &(state->waypoints[this_sv]);
origin = &(wp->loc);
delta.x = mp->pos.x - origin->x;
delta.y = mp->pos.y - origin->y;
delta.z = mp->pos.z - origin->z;
for (wl = sv->wall_head; wl != NULL; wl = wl->next) {
int hitcode = collide_wall(origin, &delta, wl->this_wall, &t,
&hit, 0, state->rng, state->notify,
&(state->ray_polygon_tests));
if (hitcode != COLLIDE_MISS) {
state->ray_polygon_colls++;
for (rl = wl->this_wall->counting_regions; rl != NULL;
rl = rl->next) {
if (hitcode == COLLIDE_FRONT || hitcode == COLLIDE_BACK) {
rl2 = (struct region_list *)CHECKED_MEM_GET(
sv->local_storage->regl, "region list");
rl2->reg = rl->reg;
if (hitcode == COLLIDE_FRONT) {
rl2->next = extra_in;
extra_in = rl2;
} else /*hitcode == COLLIDE_BACK*/
{
rl2->next = extra_out;
extra_out = rl2;
}
}
}
}
}
for (rl = extra_in; rl != NULL; rl = rl->next) {
if (rl->reg == NULL)
continue;
for (rl2 = extra_out; rl2 != NULL; rl2 = rl2->next) {
if (rl2->reg == NULL)
continue;
if (rl->reg == rl2->reg) {
rl->reg = NULL;
rl2->reg = NULL;
break;
}
}
}
if (eval_rel_region_3d(rrd->expression, wp, extra_in, extra_out)) {
vl = (struct void_list *)CHECKED_MEM_GET(mh, "temporary list");
vl->data = mp;
vl->next = vl_head;
vl_head = vl;
vl_num++;
}
if (extra_in != NULL)
mem_put_list(sv->local_storage->regl, extra_in);
if (extra_out != NULL)
mem_put_list(sv->local_storage->regl, extra_out);
}
}
}
}
}
for (vl = vl_head; n < 0 && vl_num > 0 && vl != NULL;
vl = vl->next, vl_num--) {
if (rng_dbl(state->rng) < ((double)(-n)) / ((double)vl_num)) {
mp = (struct volume_molecule *)vl->data;
mp->properties->population--;
mp->subvol->mol_count--;
if ((mp->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) != 0)
count_region_from_scratch(state, (struct abstract_molecule *)mp, NULL,
-1, &(mp->pos), NULL, mp->t, NULL);
if (mp->flags & IN_SCHEDULE) {
mp->subvol->local_storage->timer
->defunct_count++; /* Tally for garbage collection */
}
collect_molecule(mp);
n++;
}
}
delete_mem(mh);
return 0;
}
/*************************************************************************
is_point_inside_release_region:
Check if a given point is inside the specified region.
*************************************************************************/
static int is_point_inside_region(struct volume *state,
struct vector3 const *pos,
struct release_evaluator *expression,
struct subvolume *sv) {
struct region_list *extra_in = NULL, *extra_out = NULL, *cur_region;
struct waypoint *wp;
struct vector3 delta;
struct vector3 *origin;
struct wall_list *wl;
int bad_location = 0;
int result;
/* If no subvolume hint was given, or the hint is incorrect, find the right
* subvolume
*/
if (sv == NULL ||
!inside_subvolume((struct vector3 *)pos, sv, state->x_fineparts,
state->y_fineparts, state->z_fineparts))
sv = find_subvolume(state, (struct vector3 *)pos, sv);
/* Find waypoint, compute trajectory from waypoint */
wp = &(state->waypoints[sv - state->subvol]);
origin = &(wp->loc);
delta.x = pos->x - origin->x;
delta.y = pos->y - origin->y;
delta.z = pos->z - origin->z;
for (wl = sv->wall_head; wl != NULL; wl = wl->next) {
struct vector3 hit_pos;
double hit_time;
int hit_check =
collide_wall(origin, &delta, wl->this_wall, &hit_time, &hit_pos, 0,
state->rng, state->notify, &(state->ray_polygon_tests));
if (hit_check != COLLIDE_MISS) {
state->ray_polygon_colls++;
if ((hit_time > -EPS_C && hit_time < EPS_C) ||
(hit_time > 1.0 - EPS_C && hit_time < 1.0 + EPS_C)) {
bad_location = 1;
break;
}
for (cur_region = wl->this_wall->counting_regions; cur_region != NULL;
cur_region = cur_region->next) {
struct region_list *crossed_region =
(struct region_list *)CHECKED_MEM_GET(sv->local_storage->regl,
"region list");
crossed_region->reg = cur_region->reg;
if (hit_check == COLLIDE_FRONT) {
crossed_region->next = extra_in;
extra_in = crossed_region;
} else if (hit_check == COLLIDE_BACK) {
crossed_region->next = extra_out;
extra_out = crossed_region;
} else {
bad_location = 1;
break;
}
}
}
}
if (bad_location) {
if (extra_in != NULL)
mem_put_list(sv->local_storage->regl, extra_in);
if (extra_out != NULL)
mem_put_list(sv->local_storage->regl, extra_out);
return 0;
}
for (cur_region = extra_in; cur_region != NULL;
cur_region = cur_region->next) {
struct region_list *out_region = NULL;
if (cur_region->reg == NULL)
continue;
for (out_region = extra_out; out_region != NULL;
out_region = out_region->next) {
if (out_region->reg == NULL)
continue;
if (cur_region->reg == out_region->reg) {
cur_region->reg = NULL;
out_region->reg = NULL;
break;
}
}
}
result = eval_rel_region_3d(expression, wp, extra_in, extra_out);
if (extra_in != NULL)
mem_put_list(sv->local_storage->regl, extra_in);
if (extra_out != NULL)
mem_put_list(sv->local_storage->regl, extra_out);
return result;
}
/*************************************************************************
release_inside_regions:
In: pointer to a release site object
template molecule to release
integer number of molecules to release
Out: 0 on success, 1 on failure; molecule(s) are released into the
state as specified.
Note: if the CCNNUM release method is used, the number of molecules
passed in is ignored.
*************************************************************************/
static int release_inside_regions(struct volume *state,
struct release_site_obj *rso,
struct volume_molecule *vm, int n) {
struct release_region_data *rrd = rso->region_data;
vm->previous_wall = NULL;
vm->index = -1;
// test if the release region is a single object (versus a CSG expression)
// since then we can compute the number of molecules exactly.
bool exactNumber = false;
if (rso->release_number_method == CCNNUM) {
n = num_vol_mols_from_conc(rso, state->length_unit, &exactNumber);
}
if (n < 0)
return vacuum_inside_regions(state, rso, vm, n);
struct volume_molecule *new_vm = NULL;
struct subvolume *sv = NULL;
while (n > 0) {
vm->pos.x = rrd->llf.x + (rrd->urb.x - rrd->llf.x) * rng_dbl(state->rng);
vm->pos.y = rrd->llf.y + (rrd->urb.y - rrd->llf.y) * rng_dbl(state->rng);
vm->pos.z = rrd->llf.z + (rrd->urb.z - rrd->llf.z) * rng_dbl(state->rng);
if (!is_point_inside_region(state, &vm->pos, rrd->expression, NULL)) {
if (rso->release_number_method == CCNNUM && !exactNumber)
n--;
continue;
}
/* Actually place the molecule */
vm->subvol = sv;
vm->periodic_box->x = rso->periodic_box->x;
vm->periodic_box->y = rso->periodic_box->y;
vm->periodic_box->z = rso->periodic_box->z;
new_vm = insert_volume_molecule(state, vm, new_vm);
if (new_vm == NULL)
return 1;
n--;
}
return 0;
}
/*************************************************************************
release_molecules:
In: pointer to a release event
Out: 0 on success, 1 on failure; next event is scheduled and molecule(s)
are released into the state as specified.
Note: if a release is triggered by a reaction, there isn't anything
to schedule. Also, in that case, rpat isn't really a release
pattern (it's a rxn_pathname in disguise) so be sure to not
dereference it!
*************************************************************************/
int release_molecules(struct volume *state, struct release_event_queue *req) {
if (req == NULL)
return 0;
struct release_site_obj *rso = req->release_site;
struct volume_molecule vm;
memset(&vm, 0, sizeof(struct volume_molecule));
/* Set up canonical molecule to be released */
/* If we have a list, assume a 3D molecule and fix later */
if (rso->mol_list != NULL || (rso->mol_type->flags & NOT_FREE) == 0) {
vm.flags = TYPE_VOL | IN_VOLUME;
} else {
vm.flags = TYPE_SURF | IN_SURFACE;
}
vm.flags |= IN_SCHEDULE | ACT_NEWBIE;
if (req->train_counter == 0) {
req->train_counter++;
}
struct release_pattern *rpat = rso->pattern;
if (skip_past_events(rso->release_prob, state, req, rpat)) {
return 0;
}
if (check_release_probability(rso->release_prob, state, req, rpat)) {
return 0;
}
// Set molecule characteristics.
vm.mesh_name = NULL;
vm.t = req->event_time;
vm.properties = rso->mol_type;
vm.t2 = 0.0;
vm.birthday = convert_iterations_to_seconds(
state->start_iterations, state->time_unit,
state->simulation_start_seconds, vm.t);
struct periodic_image periodic_box = {rso->periodic_box->x,
rso->periodic_box->y,
rso->periodic_box->z
};
vm.periodic_box = &periodic_box;
struct abstract_molecule *ap = (struct abstract_molecule *)(&vm);
if(ap->properties && (ap->properties->flags & EXTERNAL_SPECIES)){
//TODO: i should check against a hashmap storing rso->graph_pattern data instead of reacting this object
int error = get_graph_data(lhash(rso->graph_pattern), &ap->graph_data);
if(error != 0){
if(!ap->graph_data){
ap->graph_data = CHECKED_MALLOC_ARRAY(struct graph_data, 1, "structure to store graph data");
ap->graph_data->graph_pattern = rso->graph_pattern;
ap->graph_data->graph_pattern_hash = lhash(ap->graph_data->graph_pattern);
properties_nfsim(state, ap);
}
store_graph_data(lhash(rso->graph_pattern), ap->graph_data);
state->n_NFSimSpecies += 1;
}
}
else{
ap->graph_data = NULL;
//ap->graph_pattern = NULL;
//ap->graph_pattern_hash = 0;
}
// All molecules are the same, so we can set flags
if (rso->mol_list == NULL) {
initialize_diffusion_function(ap);
if (trigger_unimolecular(state->reaction_hash, state->rx_hashsize,
rso->mol_type->hashval, ap) != NULL ||
(rso->mol_type->flags & CAN_SURFWALL) != 0)
ap->flags |= ACT_REACT;
if (ap->get_space_step(ap) > 0.0)
ap->flags |= ACT_DIFFUSE;
}
int number = calculate_number_to_release(rso, state);
if (rso->release_shape == SHAPE_REGION) {
u_int pop_before = ap->properties->population;
if (ap->flags & TYPE_VOL) {
if (release_inside_regions(state, rso, (struct volume_molecule *)ap,
number))
return 1;
} else {
if (release_onto_regions(state, rso, (struct surface_molecule *)ap,
number))
return 1;
}
if (state->notify->release_events == NOTIFY_FULL) {
if (number >= 0) {
//nfsim observable table update for initial populations
if(state->nfsim_flag){
constructNauty_c(vm.graph_data->graph_pattern, ap->properties->population - pop_before);
mcell_log("Released %d %s from \"%s\" at iteration %lld.",
ap->properties->population - pop_before,
ap->graph_data->graph_pattern, rso->name, state->current_iterations);
}
else{
mcell_log("Released %d %s from \"%s\" at iteration %lld.",
ap->properties->population - pop_before,
rso->mol_type->sym->name, rso->name, state->current_iterations);
}
} else {
//nfsim observable table update for initial populations
if(state->nfsim_flag)
constructNauty_c(vm.graph_data->graph_pattern, pop_before - ap->properties->population);
mcell_log("Removed %d %s from \"%s\" at iteration %lld.",
pop_before - ap->properties->population,
rso->mol_type->sym->name, rso->name, state->current_iterations);
}
}
}
// Guaranteed to be 3D molec or at least specified by 3D location if in list
else {
vm.previous_wall = NULL;
vm.index = -1;
if (rso->mol_list != NULL) {
if (release_by_list(state, req, &vm)) {
return 1;
}
} else if (rso->diameter != NULL) {
if (release_ellipsoid_or_rectcuboid(state, req, &vm, number)) {
return 1;
}
} else {
double location[1][4];
location[0][0] = rso->location->x;
location[0][1] = rso->location->y;
location[0][2] = rso->location->z;
location[0][3] = 1;
mult_matrix(location, req->t_matrix, location, 1, 4, 4);
vm.pos.x = location[0][0];
vm.pos.y = location[0][1];
vm.pos.z = location[0][2];
struct volume_molecule *vm_guess = NULL;
for (int i = 0; i < number; i++) {
vm_guess = insert_volume_molecule(state, &vm, vm_guess);
if (vm_guess == NULL)
return 1;
vm.periodic_box->x = rso->periodic_box->x;
vm.periodic_box->y = rso->periodic_box->y;
vm.periodic_box->z = rso->periodic_box->z;
}
if (state->notify->release_events == NOTIFY_FULL) {
mcell_log("Released %d %s from \"%s\" at iteration %lld.", number,
rso->mol_type->sym->name, rso->name, state->current_iterations);
}
}
}
/* Schedule next release event. */
if (!distinguishable(rso->release_prob, MAGIC_PATTERN_PROBABILITY, EPS_C))
return 0; /* Triggered by reaction, don't schedule */
req->event_time += rpat->release_interval;
/* we may need to move to the next train. */
if (!distinguishable(req->event_time,
req->train_high_time + rpat->train_duration, EPS_C) ||
req->event_time > req->train_high_time + rpat->train_duration) {
req->train_high_time += rpat->train_interval;
req->event_time = req->train_high_time;
req->train_counter++;
}
if (req->train_counter <= rpat->number_of_trains &&
req->event_time < FOREVER) {
if (schedule_add(state->releaser, req))
mcell_allocfailed("Failed to add release request to scheduler.");
}
else {
free(req);
}
return 0;
}
/*************************************************************************
release_ellipsoid_or_rectcuboid:
This function is used for CUBIC (aka RECTANGULAR), SPHERICAL (aka
ELLIPTICAL), and SPHERICAL_SHELL release sites.
In: state: MCell simulation state
req:
vm: volume molecule being released
number: number to release
Out: 0 on success, 1 on failure
*************************************************************************/
int release_ellipsoid_or_rectcuboid(struct volume *state,
struct release_event_queue *req,
struct volume_molecule *vm, int number) {
struct release_site_obj *rso = req->release_site;
struct vector3 *diam_xyz = rso->diameter;
struct vector3 pos;
const int is_spheroidal = (rso->release_shape == SHAPE_SPHERICAL ||
rso->release_shape == SHAPE_ELLIPTIC ||
rso->release_shape == SHAPE_SPHERICAL_SHELL);
for (int i = 0; i < number; i++) {
do /* Pick values in unit square, toss if not in unit circle */
{
pos.x = (rng_dbl(state->rng) - 0.5);
pos.y = (rng_dbl(state->rng) - 0.5);
pos.z = (rng_dbl(state->rng) - 0.5);
} while (is_spheroidal &&
pos.x * pos.x + pos.y * pos.y + pos.z * pos.z >= 0.25);
if (rso->release_shape == SHAPE_SPHERICAL_SHELL) {
double r = sqrt(pos.x * pos.x + pos.y * pos.y + pos.z * pos.z) * 2.0;
if (r == 0.0) {
pos.x = 0.0;
pos.y = 0.0;
pos.z = 0.5;
} else {
pos.x /= r;
pos.y /= r;
pos.z /= r;
}
}
double location[1][4];
location[0][0] = pos.x * diam_xyz->x + rso->location->x;
location[0][1] = pos.y * diam_xyz->y + rso->location->y;
location[0][2] = pos.z * diam_xyz->z + rso->location->z;
location[0][3] = 1;
mult_matrix(location, req->t_matrix, location, 1, 4, 4);
vm->pos.x = location[0][0];
vm->pos.y = location[0][1];
vm->pos.z = location[0][2];
struct volume_molecule *guess = NULL;
/* Insert copy of vm into state */
vm->periodic_box->x = rso->periodic_box->x;
vm->periodic_box->y = rso->periodic_box->y;
vm->periodic_box->z = rso->periodic_box->z;
guess = insert_volume_molecule(state, vm, guess);
#ifdef DEBUG_RELEASES
dump_volume_molecule(vm, "", true, "Released vm:", state->current_iterations, vm->t, true);
#endif
if (guess == NULL)
return 1;
}
if (state->notify->release_events == NOTIFY_FULL) {
mcell_log("Released %d %s from \"%s\" at iteration %lld.", number,
rso->mol_type->sym->name, rso->name, state->current_iterations);
}
return 0;
}
/*************************************************************************
release_by_list:
This function is used for LIST based release sites.
In: state: MCell simulation state
req:
vm: volume molecule being released
Out: 0 on success, 1 on failure
*************************************************************************/
int release_by_list(struct volume *state, struct release_event_queue *req,
struct volume_molecule *vm) {
int i = 0; /* serves as counter for released molecules */
int i_failed = 0; /* serves as counted for the failed to release molecules */
struct release_site_obj *rso = req->release_site;
struct release_single_molecule *rsm = rso->mol_list;
for (; rsm != NULL; rsm = rsm->next) {
double location[1][4];
location[0][0] = rsm->loc.x + rso->location->x;
location[0][1] = rsm->loc.y + rso->location->y;
location[0][2] = rsm->loc.z + rso->location->z;
location[0][3] = 1;
mult_matrix(location, req->t_matrix, location, 1, 4, 4);
vm->pos.x = location[0][0];
vm->pos.y = location[0][1];
vm->pos.z = location[0][2];
struct volume_molecule *vm_guess = NULL;
if ((rsm->mol_type->flags & NOT_FREE) == 0) {
struct abstract_molecule *ap = (struct abstract_molecule *)(vm);
vm->properties = rsm->mol_type;
initialize_diffusion_function(ap);
// Have to set flags, since insert_volume_molecule doesn't
if (trigger_unimolecular(state->reaction_hash, state->rx_hashsize,
ap->properties->hashval, ap) != NULL ||
(ap->properties->flags & CAN_SURFWALL) != 0) {
ap->flags |= ACT_REACT;
}
if (vm->get_space_step(vm) > 0.0)
ap->flags |= ACT_DIFFUSE;
vm_guess = insert_volume_molecule(state, vm, vm_guess);
if (vm_guess == NULL)
return 1;
vm_guess->periodic_box->x = rso->periodic_box->x;
vm_guess->periodic_box->y = rso->periodic_box->y;
vm_guess->periodic_box->z = rso->periodic_box->z;
i++;
} else {
double diam;
if (rso->diameter == NULL)
diam = 0.0;
else
diam = rso->diameter->x;
short orient;
if (rsm->orient > 0)
orient = 1;
else if (rsm->orient < 0)
orient = -1;
else {
orient = (rng_uint(state->rng) & 1) ? 1 : -1;
}
// Don't have to set flags, insert_surface_molecule takes care of it
struct surface_molecule *sm;
sm = insert_surface_molecule(state, rsm->mol_type, &vm->pos, orient,
diam, req->event_time, NULL, NULL, NULL,
rso->periodic_box);
if (sm == NULL) {
mcell_warn("Molecule release is unable to find surface upon which "
"to place molecule %s.\n"
" This could be caused by too small of a SITE_DIAMETER "
"on the release site '%s'.",
rsm->mol_type->sym->name, rso->name);
i_failed++;
} else {
i++;
}
}
}
if (state->notify->release_events == NOTIFY_FULL) {
mcell_log("Released %d molecules from list \"%s\" at iteration %lld.", i,
rso->name, state->current_iterations);
}
if (i_failed > 0)
mcell_warn("Failed to release %d molecules from list \"%s\" at "
"iteration %lld.",
i_failed, rso->name, state->current_iterations);
return 0;
}
/*************************************************************************
find_exponential_params:
In: value of f(0)
value of f(N)
difference between f(1) and f(0)
number of data points
pointer to where we store the scaling factor A
pointer to the constant offset B
pointer to the rate of decay k
Out: no return value. This is a utility function that uses bisection
to solve for A,B,k to find an exponentially increasing function
f(n) = A*exp(n*k)+B
subject to the contstraints
f(0) = c
f(1) = c+d
f(N) = C
*************************************************************************/
static void find_exponential_params(double c, double C, double d, double N,
double *A, double *B, double *k) {
double k_min = 0;
double k_mid = 0;
double k_max = log(GIGANTIC) / N;
for (int i = 0; i < 720; i++) {
k_mid = 0.5 * (k_min + k_max);
double f = c + (exp(N * k_mid) - 1.0) * d / (exp(k_mid) - 1.0);
if (C > f)
k_min = k_mid;
else
k_max = k_mid;
if ((k_max - k_min) / (k_max + k_min) < EPS_C)
break;
}
*k = k_mid;
*A = d / (exp(*k) - 1.0);
*B = c - *A;
}
/*************************************************************************
check_partitions_against_interaction_diameter:
In: nothing. Uses struct volume *state, assumes partitions are set.
Out: 0 on success, 1 on error
*************************************************************************/
static int check_partitions_against_interaction_diameter(struct volume *state) {
int i;
if (state->x_partitions != NULL) {
for (i = 1; i < state->nx_parts; i++) {
if (state->x_partitions[i] - state->x_partitions[i - 1] <
2 * state->rx_radius_3d) {
mcell_error("X partitions closer than interaction diameter\n"
" X partition #%d at %g\n"
" X partition #%d at %g\n"
" Interaction diameter %g",
i, state->length_unit * state->x_partitions[i - 1], i + 1,
state->length_unit * state->x_partitions[i],
2 * state->length_unit * state->rx_radius_3d);
/*return 1;*/
}
}
}
if (state->y_partitions != NULL) {
for (i = 1; i < state->ny_parts; i++) {
if (state->y_partitions[i] - state->y_partitions[i - 1] <
2 * state->rx_radius_3d) {
mcell_error("Y partitions closer than interaction diameter\n"
" Y partition #%d at %g\n"
" Y partition #%d at %g\n"
" Interaction diameter %g",
i, state->length_unit * state->y_partitions[i - 1], i + 1,
state->length_unit * state->y_partitions[i],
2 * state->length_unit * state->rx_radius_3d);
/*return 1;*/
}
}
}
if (state->z_partitions != NULL) {
for (i = 1; i < state->nz_parts; i++) {
if (state->z_partitions[i] - state->z_partitions[i - 1] <
2 * state->rx_radius_3d) {
mcell_error("Z partitions closer than interaction diameter\n"
" Z partition #%d at %g\n"
" Z partition #%d at %g\n"
" Interaction diameter %g\n",
i, state->length_unit * state->z_partitions[i - 1], i + 1,
state->length_unit * state->z_partitions[i],
2 * state->length_unit * state->rx_radius_3d);
/*return 1;*/
}
}
}
return 0;
}
/*************************************************************************
set_partitions:
In: nothing. Uses struct volume *state, assumes bounding box is set.
Out: 0 on success, 1 on error; coarse and fine partitions are set.
*************************************************************************/
int set_partitions(struct volume *state) {
/* Set sensible bounds for spacing between fine partitions (minimum size of
* subdivision) */
double smallest_spacing = 0.1 * state->r_length_unit; /* 100nm */
if (2 * state->rx_radius_3d > smallest_spacing)
smallest_spacing = 2 * state->rx_radius_3d;
/* We have 2^15 possible fine partitions; we'll use 24k of them */
if (state->n_fineparts != 4096 + 16384 + 4096) {
state->n_fineparts = 4096 + 16384 + 4096;
state->x_fineparts =
CHECKED_MALLOC_ARRAY(double, state->n_fineparts, "x fine partitions");
state->y_fineparts =
CHECKED_MALLOC_ARRAY(double, state->n_fineparts, "y fine partitions");
state->z_fineparts =
CHECKED_MALLOC_ARRAY(double, state->n_fineparts, "z fine partitions");
}
// Something like the maximum expected error--not sure exactly what this is
double dfx = 1e-3 + (state->bb_urb.x - state->bb_llf.x) / 8191.0;
double dfy = 1e-3 + (state->bb_urb.y - state->bb_llf.y) / 8191.0;
double dfz = 1e-3 + (state->bb_urb.z - state->bb_llf.z) / 8191.0;
// Make sure fine partition follow the "2 x reaction radius" rule, I guess.
double f_min = state->bb_llf.x - dfx;
double f_max = state->bb_urb.x + dfx;
dfx = increase_fine_partition_size(state, state->x_fineparts, &f_min, &f_max,
smallest_spacing);
struct vector3 part_min, part_max;
part_min.x = f_min;
part_max.x = f_max;
// Same thing for y as we just did for x
f_min = state->bb_llf.y - dfy;
f_max = state->bb_urb.y + dfy;
dfy = increase_fine_partition_size(state, state->y_fineparts, &f_min, &f_max,
smallest_spacing);
part_min.y = f_min;
part_max.y = f_max;
// And same again for z
f_min = state->bb_llf.z - dfz;
f_max = state->bb_urb.z + dfz;
dfz = increase_fine_partition_size(state, state->z_fineparts, &f_min, &f_max,
smallest_spacing);
part_min.z = f_min;
part_max.z = f_max;
/* Try to figure out how many timesteps our fastest particle can make in the
* whole state (along longest and shortest axes) */
double f = part_max.x - part_min.x;
f_min = f_max = f;
f = part_max.y - part_min.y;
if (f < f_min)
f_min = f;
else if (f > f_max)
f_max = f;
f = part_max.z - part_min.z;
if (f < f_min)
f_min = f;
else if (f > f_max)
f_max = f;
double steps_min, steps_max;
if (!distinguishable(state->speed_limit, 0, EPS_C)) {
steps_min = f_min;
steps_max = f_max;
} else {
steps_min = f_min / state->speed_limit;
steps_max = f_max / state->speed_limit;
}
/* Verify that partitions are not closer than interaction diameter. */
if (check_partitions_against_interaction_diameter(state))
return 1;
if (state->x_partitions != NULL || state->y_partitions != NULL ||
state->z_partitions != NULL) {
if (state->x_partitions == NULL)
mcell_error("Some axes are partitioned, but the X-axis is not.");
if (state->y_partitions == NULL)
mcell_error("Some axes are partitioned, but the Y-axis is not.");
if (state->z_partitions == NULL)
mcell_error("Some axes are partitioned, but the Z-axis is not.");
}
/* Use automatic partitioning only when there are no user-specified
* partitions */
if (state->x_partitions == NULL && state->y_partitions == NULL &&
state->z_partitions == NULL) {
set_auto_partitions(state, steps_min, steps_max, &part_min, &part_max,
f_max, smallest_spacing);
} else {
set_user_partitions(state, dfx, dfy, dfz);
}
/* And finally we tell the user what happened */
if (state->notify->partition_location == NOTIFY_FULL) {
mcell_log_raw("X partitions: ");
mcell_log_raw("-inf ");
for (int i = 1; i < state->nx_parts - 1; i++)
mcell_log_raw("%.5f ", state->length_unit * state->x_partitions[i]);
mcell_log_raw("inf\n");
mcell_log_raw("Y partitions: ");
mcell_log_raw("-inf ");
for (int i = 1; i < state->ny_parts - 1; i++)
mcell_log_raw("%.5f ", state->length_unit * state->y_partitions[i]);
mcell_log_raw("inf\n");
mcell_log_raw("Z partitions: ");
mcell_log_raw("-inf ");
for (int i = 1; i < state->nz_parts - 1; i++)
mcell_log_raw("%.5f ", state->length_unit * state->z_partitions[i]);
mcell_log_raw("inf\n");
}
return 0;
}
double increase_fine_partition_size(struct volume *state, double *fineparts,
double *f_min, double *f_max,
double smallest_spacing) {
/* Not sure how this is supposed to work--looks like two ideas mixed,
* probably broken */
/* Was supposed to make sure that the fine partitions would still obey the
* 2*reaction radius rule */
if (*f_max - *f_min < smallest_spacing) {
if (state->notify->progress_report != NOTIFY_NONE)
mcell_log_raw("Rescaling: was %.3f to %.3f, now ",
(*f_min) * state->length_unit,
(*f_max) * state->length_unit);
double f = smallest_spacing - (*f_max - *f_min);
*f_max += 0.5 * f;
*f_min -= 0.5 * f;
if (state->notify->progress_report != NOTIFY_NONE)
mcell_log_raw("%.3f to %.3f\n", (*f_min) * state->length_unit,
(*f_max) * state->length_unit);
}
// Set bounds over which to do linear subdivision (state bounding box)
double df = (*f_max - *f_min) / 16383.0;
// Subdivide state bounding box
for (int i = 0; i < 16384; i++) {
fineparts[4096 + i] = *f_min + df * ((double)i);
}
/* Create an exponentially increasing fine partition size as we go to
* -infinity */
double A, B, k;
find_exponential_params(-*f_min, 1e12, df, 4096, &A, &B, &k);
for (int i = 1; i <= 4096; i++)
fineparts[4096 - i] = -(A * exp(i * k) + B);
/* And again as we go to +infinity */
find_exponential_params(*f_max, 1e12, df, 4096, &A, &B, &k);
for (int i = 1; i <= 4096; i++)
fineparts[4096 + 16383 + i] = A * exp(i * k) + B;
return df;
}
void set_auto_partitions(struct volume *state, double steps_min,
double steps_max, struct vector3 *part_min,
struct vector3 *part_max, double f_max,
double smallest_spacing) {
/* perform automatic partitioning */
/* Guess how big to make partitions--nothing really clever about what's done
* here */
if (steps_max / MAX_TARGET_TIMESTEP > MAX_COARSE_PER_AXIS) {
state->nx_parts = state->ny_parts = state->nz_parts = MAX_COARSE_PER_AXIS;
} else if (steps_min / MIN_TARGET_TIMESTEP < MIN_COARSE_PER_AXIS) {
state->nx_parts = state->ny_parts = state->nz_parts = MIN_COARSE_PER_AXIS;
} else {
state->nx_parts = steps_min / MIN_TARGET_TIMESTEP;
if (state->nx_parts > MAX_COARSE_PER_AXIS)
state->nx_parts = MAX_COARSE_PER_AXIS;
if ((state->nx_parts & 1) != 0)
state->nx_parts += 1;
state->ny_parts = state->nz_parts = state->nx_parts;
}
/* Allocate memory for our automatically created partitions */
state->x_partitions =
CHECKED_MALLOC_ARRAY(double, state->nx_parts, "x partitions");
state->y_partitions =
CHECKED_MALLOC_ARRAY(double, state->ny_parts, "y partitions");
state->z_partitions =
CHECKED_MALLOC_ARRAY(double, state->nz_parts, "z partitions");
/* Calculate aspect ratios so that subvolumes are approximately cubic */
double x_aspect = (part_max->x - part_min->x) / f_max;
double y_aspect = (part_max->y - part_min->y) / f_max;
double z_aspect = (part_max->z - part_min->z) / f_max;
int x_in = (int)floor((state->nx_parts - 2) * x_aspect + 0.5);
int y_in = (int)floor((state->ny_parts - 2) * y_aspect + 0.5);
int z_in = (int)floor((state->nz_parts - 2) * z_aspect + 0.5);
if (x_in < 2)
x_in = 2;
if (y_in < 2)
y_in = 2;
if (z_in < 2)
z_in = 2;
/* If we've violated our 2*reaction radius criterion, fix it */
smallest_spacing = 2 * state->rx_radius_3d;
if ((part_max->x - part_min->x) / (x_in - 1) < smallest_spacing) {
x_in = 1 + (int)floor((part_max->x - part_min->x) / smallest_spacing);
}
if ((part_max->y - part_min->y) / (y_in - 1) < smallest_spacing) {
y_in = 1 + (int)floor((part_max->y - part_min->y) / smallest_spacing);
}
if ((part_max->z - part_min->z) / (z_in - 1) < smallest_spacing) {
z_in = 1 + (int)floor((part_max->z - part_min->z) / smallest_spacing);
}
/* Set up to walk symmetrically out from the center of the state, dropping
* partitions on the way */
if (x_in < 2)
x_in = 2;
if (y_in < 2)
y_in = 2;
if (z_in < 2)
z_in = 2;
int x_start = (state->nx_parts - x_in) / 2;
int y_start = (state->ny_parts - y_in) / 2;
int z_start = (state->nz_parts - z_in) / 2;
if (x_start < 1)
x_start = 1;
if (y_start < 1)
y_start = 1;
if (z_start < 1)
z_start = 1;
set_fineparts(part_min->x, part_max->x, state->x_partitions,
state->x_fineparts, state->nx_parts, x_in, x_start);
set_fineparts(part_min->y, part_max->y, state->y_partitions,
state->y_fineparts, state->ny_parts, y_in, y_start);
set_fineparts(part_min->z, part_max->z, state->z_partitions,
state->z_fineparts, state->nz_parts, z_in, z_start);
}
void set_fineparts(double min, double max, double *partitions,
double *fineparts, int n_parts, int in, int start) {
/* Now go through and drop partitions in each direction (picked from
* sensibly close fine partitions) */
double f = (max - min) / (in - 1);
int j = 0;
partitions[0] = fineparts[1];
/* Dunno how this actually works! */
for (int i = start; i < start + in; i++) {
partitions[i] = fineparts[4096 + (i - start) * 16384 / (in - 1)];
}
for (int i = start - 1; i > 0; i--) {
for (j = 0; partitions[i + 1] - fineparts[4095 - j] < f; j++) {
}
partitions[i] = fineparts[4095 - j];
}
for (int i = start + in; i < n_parts - 1; i++) {
for (j = 0; fineparts[4096 + 16384 + j] - partitions[i - 1] < f; j++) {
}
partitions[i] = fineparts[4096 + 16384 + j];
}
partitions[n_parts - 1] = fineparts[4096 + 16384 + 4096 - 2];
}
void set_user_partitions(struct volume *state, double dfx, double dfy,
double dfz) {
// User-supplied partitions
// We need to keep the outermost partition away from the state bounding box.
// We do this by adding a larger outermost partition, calculated somehow or
// other.
dfx += 1e-3;
dfy += 1e-3;
dfz += 1e-3;
state->x_partitions =
add_extra_outer_partitions(state->x_partitions, state->bb_llf.x,
state->bb_urb.x, dfx, &state->nx_parts);
state->y_partitions =
add_extra_outer_partitions(state->y_partitions, state->bb_llf.y,
state->bb_urb.y, dfy, &state->ny_parts);
state->z_partitions =
add_extra_outer_partitions(state->z_partitions, state->bb_llf.z,
state->bb_urb.z, dfz, &state->nz_parts);
find_closest_fine_part(state->x_partitions, state->x_fineparts,
state->n_fineparts, state->nx_parts);
find_closest_fine_part(state->y_partitions, state->y_fineparts,
state->n_fineparts, state->ny_parts);
find_closest_fine_part(state->z_partitions, state->z_fineparts,
state->n_fineparts, state->nz_parts);
}
void find_closest_fine_part(double *partitions, double *fineparts,
int n_fineparts, int n_parts) {
/* Now that we've added outermost partitions, we find the closest fine
* partition along each axis */
partitions[0] = fineparts[1];
for (int i = 1; i < n_parts - 1; i++) {
partitions[i] =
fineparts[bisect_near(fineparts, n_fineparts, partitions[i])];
}
partitions[n_parts - 1] = fineparts[4096 + 16384 + 4096 - 2];
}
double *add_extra_outer_partitions(double *partitions, double bb_llf_val,
double bb_urb_val, double df_val,
int *n_parts) {
/* All this code just adds extra outermost partitions if they might be too
* close to the outermost objects in the state */
/* Don't ask me how it actually does it (or if it does it successfully...) */
double *dbl_array;
if (partitions[1] + df_val > bb_llf_val) {
if (partitions[1] - df_val < bb_llf_val)
partitions[1] = bb_llf_val - df_val;
else {
dbl_array = CHECKED_MALLOC_ARRAY(double, (*n_parts + 1),
"x partitions (expanded in -X dir)");
dbl_array[0] = partitions[0];
dbl_array[1] = bb_llf_val - df_val;
memcpy(&(dbl_array[2]), &(partitions[1]),
sizeof(double) * (*n_parts - 1));
free(partitions);
partitions = dbl_array;
*n_parts = *n_parts + 1;
}
}
if (partitions[*n_parts - 2] - df_val < bb_urb_val) {
if (partitions[*n_parts - 2] + df_val > bb_urb_val)
partitions[*n_parts - 2] = bb_urb_val + df_val;
else {
dbl_array = CHECKED_MALLOC_ARRAY(double, (*n_parts + 1),
"x partitions (expanded in +X dir)");
dbl_array[*n_parts] = partitions[*n_parts - 1];
dbl_array[*n_parts - 1] = bb_urb_val + df_val;
memcpy(dbl_array, partitions, sizeof(double) * (*n_parts - 1));
free(partitions);
partitions = dbl_array;
*n_parts = *n_parts + 1;
}
}
return partitions;
}
/************************************************************************
In: starting position of the molecule
displacement (random walk) vector
vector to store one corner of the bounding box
vector to store the opposite corner of the bounding box
Out: No return value. The vectors are set to define the bounding box
of the random walk movement that extends for R_INT in all
directions.
************************************************************************/
void path_bounding_box(struct vector3 *loc, struct vector3 *displacement,
struct vector3 *llf, struct vector3 *urb,
double rx_radius_3d) {
struct vector3 final_pos; /* final position of the molecule after random walk */
double R; /* molecule interaction radius */
R = rx_radius_3d;
vect_sum(loc, displacement, &final_pos);
llf->x = urb->x = loc->x;
llf->y = urb->y = loc->y;
llf->z = urb->z = loc->z;
if (final_pos.x < llf->x) {
llf->x = final_pos.x;
}
if (final_pos.x > urb->x) {
urb->x = final_pos.x;
}
if (final_pos.y < llf->y) {
llf->y = final_pos.y;
}
if (final_pos.y > urb->y) {
urb->y = final_pos.y;
}
if (final_pos.z < llf->z) {
llf->z = final_pos.z;
}
if (final_pos.z > urb->z) {
urb->z = final_pos.z;
}
/* Extend the bounding box at the distance R. */
llf->x -= R;
llf->y -= R;
llf->z -= R;
urb->x += R;
urb->y += R;
urb->z += R;
}
/***************************************************************************
collect_molecule:
Perform garbage collection on a discarded molecule. If the molecule is no
longer in any lists, it will be freed.
In: vm: the molecule
Out: Nothing. Molecule is unlinked from its list in the subvolume, and
possibly returned to its birthplace.
***************************************************************************/
void collect_molecule(struct volume_molecule *vm) {
/* Unlink from the previous item */
if (vm->prev_v != NULL) {
#ifdef DEBUG_LIST_CHECKS
if (*vm->prev_v != vm) {
mcell_error_nodie("Stale previous pointer! ACK! THRBBPPPPT!");
}
#endif
*(vm->prev_v) = vm->next_v;
}
/* Unlink from the following item */
if (vm->next_v != NULL) {
#ifdef DEBUG_LIST_CHECKS
if (vm->next_v->prev_v != &vm->next_v) {
mcell_error_nodie("Stale next pointer! ACK! THRBBPPPPT!");
}
#endif
vm->next_v->prev_v = vm->prev_v;
}
/* Clear our next/prev pointers */
vm->prev_v = NULL;
vm->next_v = NULL;
/* Dispose of the molecule */
vm->properties = NULL;
vm->flags &= ~IN_VOLUME;
if ((vm->flags & IN_MASK) == 0)
mem_put(vm->birthplace, vm);
}
/***************************************************************************
ht_add_molecule_to_list:
Add a molecule to the appropriate molecule list in a subvolume's pointer
hash. It is assumed that the molecule's subvolume pointer is valid and
points to the right subvolume.
If the molecule takes part in any mol-mol interactions (including
trimolecular reactions involving two or more volume molecules), it is added
to a list containing only molecules of the same species. If it does NOT
take part in any such interactions, it is added to a single molecule list
which keeps track of all molecules which do not interact with other volume
molecules.
In: h: the pointer hash to which to add the molecule
vm: the molecule
Out: Nothing. Molecule is added to the subvolume's molecule lists.
***************************************************************************/
void ht_add_molecule_to_list(struct pointer_hash *h,
struct volume_molecule *vm) {
struct per_species_list *list = NULL;
//if we are using external molecules store information per the graph tag instead of species struct
if(vm->properties->flags & EXTERNAL_SPECIES){
if(vm->graph_data)
list = (struct per_species_list *)pointer_hash_lookup(h, vm->graph_data->graph_pattern,
vm->graph_data->graph_pattern_hash);
else
list = NULL;
/* If not, create one and add it in */
if (list == NULL) {
list = (struct per_species_list *)CHECKED_MEM_GET(
vm->subvol->local_storage->pslv, "per-species molecule list");
list->properties = vm->properties;
list->graph_data = vm->graph_data;
//list->graph_data->graph_pattern = strdup(vm->graph_data->graph_pattern);
//list->graph_pattern_hash = vm->graph_pattern_hash;
list->head = NULL;
if(vm->graph_data){
if (pointer_hash_add(h, vm->graph_data->graph_pattern, vm->graph_data->graph_pattern_hash, list))
mcell_allocfailed("Failed to add species to subvolume species table.");
}
list->next = vm->subvol->species_head;
vm->subvol->species_head = list;
}
}
else{
/* See if we have a list */
list = (struct per_species_list *)pointer_hash_lookup(h, vm->properties,
vm->properties->hashval);
/* If not, create one and add it in */
if (list == NULL) {
list = (struct per_species_list *)CHECKED_MEM_GET(
vm->subvol->local_storage->pslv, "per-species molecule list");
list->properties = vm->properties;
list->head = NULL;
if (pointer_hash_add(h, vm->properties, vm->properties->hashval, list))
mcell_allocfailed("Failed to add species to subvolume species table.");
list->next = vm->subvol->species_head;
vm->subvol->species_head = list;
}
}
/* Link the molecule into the list */
vm->next_v = list->head;
if (list->head)
list->head->prev_v = &vm->next_v;
vm->prev_v = &list->head;
list->head = vm;
}
/***************************************************************************
ht_remove:
Remove a species list from a pointer hash. This is a fairly simple wrapper
around pointer_hash_remove, which simply looks up the key (the species),
and avoids trying to remove the non-interacting molecules list from the
pointer hash, since it should never be added in the first place.
Note that the per-species list must still be valid at this point -- it must
not have been freed, nor its 'properties' pointer nilled.
In: h: the pointer hash to which to add the molecule
psl: the species list to remove
Out: Nothing. Molecule is added to the subvolume's molecule lists.
***************************************************************************/
void ht_remove(struct pointer_hash *h, struct per_species_list *psl) {
struct species *s = psl->properties;
if (s == NULL)
return;
if(s->flags & EXTERNAL_SPECIES){
//XXX: should there really be any momemnt where this is true?
if (psl->graph_data)
(void)pointer_hash_remove(h, psl->graph_data->graph_pattern, psl->graph_data->graph_pattern_hash);
}
else
(void)pointer_hash_remove(h, s, s->hashval);
}
/***************************************************************************
test_max_release:
In: num_to_release: The number to release
name: The of the release site
Out: The number to release
***************************************************************************/
static int test_max_release(double num_to_release, char *name) {
long long num = (long long)num_to_release;
if (num > (long long)INT_MAX)
mcell_error("Release site \"%s\" tries to release more than INT_MAX "
"(2147483647) molecules.",
name);
return num;
}
/***************************************************************************
check_release_probability:
In: release_prob: the probability of release
state: MCell state
req: release event
rpat: release pattern
Out: Return 1 if release probability is < k (random number). Otherwise 0.
***************************************************************************/
static int check_release_probability(double release_prob, struct volume *state,
struct release_event_queue *req,
struct release_pattern *rpat) {
/* check whether the release will happen */
if (release_prob < 1.0) {
double k = rng_dbl(state->rng);
if (release_prob < k) {
/* make sure we will try the release pattern again in the future */
req->event_time += rpat->release_interval;
/* we may need to move to the next train. */
if (!distinguishable(req->event_time,
req->train_high_time + rpat->train_duration,
EPS_C) ||
req->event_time > req->train_high_time + rpat->train_duration) {
req->train_high_time += rpat->train_interval;
req->event_time = req->train_high_time;
req->train_counter++;
}
if (req->train_counter <= rpat->number_of_trains &&
req->event_time < FOREVER) {
if (schedule_add(state->releaser, req))
mcell_allocfailed("Failed to add release request to scheduler.");
}
return 1;
}
}
return 0;
}
/***************************************************************************
check_past_events:
Skip events that happened in the past (delay<0 or after checkpoint)
In: release_prob: the probability of release
state: MCell state
req: release event
rpat: release pattern
Out: Return 1 if release pattern is not a reaction and release event hasn't
happened yet
***************************************************************************/
static int skip_past_events(double release_prob, struct volume *state,
struct release_event_queue *req,
struct release_pattern *rpat) {
if (req->event_time < state->current_iterations &&
(distinguishable(release_prob, MAGIC_PATTERN_PROBABILITY, EPS_C))) {
do {
/* Schedule next release event and leave the function.
This part of the code is relevant to checkpointing. */
if (release_prob < 1.0) {
if (!distinguishable(release_prob, 0, EPS_C))
return 0;
req->event_time += rpat->release_interval;
} else {
req->event_time += rpat->release_interval;
}
/* we may need to move to the next train. */
if (!distinguishable(req->event_time,
req->train_high_time + rpat->train_duration,
EPS_C) ||
req->event_time > req->train_high_time + rpat->train_duration) {
req->train_high_time += rpat->train_interval;
req->event_time = req->train_high_time;
req->train_counter++;
}
} while (req->event_time <= state->start_iterations);
if (req->train_counter <= rpat->number_of_trains &&
req->event_time < FOREVER) {
if (schedule_add(state->releaser, req))
mcell_allocfailed("Failed to add release request to scheduler.");
}
return 1;
}
return 0;
}
/***************************************************************************
calculate_number_to_release:
In: rso: Release site object
state: MCell state
Out: number: The number of molecules to be released
***************************************************************************/
static int calculate_number_to_release(struct release_site_obj *rso,
struct volume *state) {
int number;
double vol, num_to_release;
switch (rso->release_number_method) {
case CONSTNUM:
num_to_release = rso->release_number;
number = test_max_release(num_to_release, rso->name);
break;
case GAUSSNUM:
if (rso->standard_deviation > 0) {
num_to_release = (rng_gauss(state->rng) * rso->standard_deviation +
rso->release_number);
number = test_max_release(num_to_release, rso->name);
} else {
rso->release_number_method = CONSTNUM;
num_to_release = rso->release_number;
number = test_max_release(num_to_release, rso->name);
}
break;
case VOLNUM: {
double diam = rso->mean_diameter;
if (rso->standard_deviation > 0) {
diam += rng_gauss(state->rng) * rso->standard_deviation;
}
vol = (MY_PI / 6.0) * diam * diam * diam;
num_to_release = N_AV * 1e-15 * rso->concentration * vol + 0.5;
number = test_max_release(num_to_release, rso->name);
break;
}
case CCNNUM:
case DENSITYNUM:
if (rso->diameter == NULL)
number = 0;
else {
switch (rso->release_shape) {
case SHAPE_SPHERICAL:
case SHAPE_ELLIPTIC:
vol = (1.0 / 6.0) * MY_PI * rso->diameter->x * rso->diameter->y *
rso->diameter->z;
break;
case SHAPE_RECTANGULAR:
case SHAPE_CUBIC:
vol = rso->diameter->x * rso->diameter->y * rso->diameter->z;
break;
case SHAPE_SPHERICAL_SHELL:
mcell_error("Release site \"%s\" tries to release a concentration on a "
"spherical shell.",
rso->name);
/*vol = 0;*/
/*break;*/
default:
mcell_internal_error("Release by concentration on invalid release site "
"shape (%d) for release site \"%s\".",
rso->release_shape, rso->name);
/*break;*/
}
num_to_release = N_AV * 1e-15 * rso->concentration * vol *
state->length_unit * state->length_unit *
state->length_unit +
0.5;
number = test_max_release(num_to_release, rso->name);
}
break;
default:
mcell_internal_error(
"Release site \"%s\" has invalid release number method (%d).",
rso->name, rso->release_number_method);
/*number = 0;*/
/*break;*/
}
return number;
}
/*
* num_vol_mols_from_conc computes the number of volume molecules to be
* released within a closed object. There are two cases:
* - for a single closed object we know the exact volume and can thus compute
* the exact number of molecules required and release them by setting
* exactNumber to true.
* - for a release object consisting of a boolean expression of closed objects
* we are currently not able to compute the volume exactly. Instead we compute
* the number of molecules in the bounding box and then release an approximate
* number by setting exactNumber to false.
*/
int num_vol_mols_from_conc(struct release_site_obj *rso, double length_unit,
bool *exactNumber) {
struct release_region_data *rrd = rso->region_data;
struct release_evaluator *eval = rrd->expression;
double vol = 0.0;
if (eval->left != NULL && (eval->op & REXP_LEFT_REGION) &&
eval->right == NULL && (eval->op & REXP_NO_OP)) {
struct region *r = (struct region *)eval->left;
assert(r->manifold_flag !=
MANIFOLD_UNCHECKED); // otherwise we have no volume
vol = r->volume;
*exactNumber = true;
} else {
vol = (rrd->urb.x - rrd->llf.x) * (rrd->urb.y - rrd->llf.y) *
(rrd->urb.z - rrd->llf.z);
}
double num_to_release = (N_AV * 1e-15 * rso->concentration * vol *
length_unit * length_unit * length_unit) +
0.5;
return test_max_release(num_to_release, rso->name);
}
/*************************************************************************
periodic_boxes_are_identical() tests if two periodic boxes are identical
In: b1: pointer to first periodic_box struct
b2: pointer to second periodic_box struct
Out: true if the two boxes are identical and false otherwise.
NOTE: If one or both of b1 or b2 are NULL we also return true.
This behavior makes sure that e.g. a COUNT without any periodic
box defined always matches any other periodic box.
*************************************************************************/
bool periodic_boxes_are_identical(const struct periodic_image *b1,
const struct periodic_image *b2) {
if (b1 == NULL || b2 == NULL) {
return true;
}
return (b1->x == b2->x) && (b1->y == b2->y) && (b1->z == b2->z);
}
/*************************************************************************
convert_relative_to_abs_PBC_coords is used to convert the PBC coordinate
system. This is probably not the best name for this function, since the
meaning of relative and absolute are somewhat ambiguous in this context.
Note: This is only needed for the non-traditional form of PBCs.
In: periodic_box_obj: The actual periodic box object
periodic_box: The current periodic box that the molecule is in
periodic_traditional: A flag to indicate whether we are using traditional
PBCs or mirrored geometry PBCs
pos: The position of the molecule prior to conversion
pos_output: The position of the molecule after conversion
Out: If 0, then coordinates were successfully converted. If 1, then
coordinates were not or did not need to be converted.
*************************************************************************/
int convert_relative_to_abs_PBC_coords(
struct geom_object *periodic_box_obj,
struct periodic_image *periodic_box,
bool periodic_traditional,
struct vector3 *pos,
struct vector3 *pos_output) {
double llx = 0.0;
double urx = 0.0;
double lly = 0.0;
double ury = 0.0;
double llz = 0.0;
double urz = 0.0;
double x_box_length = 0.0;
double y_box_length = 0.0;
double z_box_length = 0.0;
if (periodic_box_obj && !(periodic_traditional)) {
assert(periodic_box_obj->object_type == BOX_OBJ);
struct polygon_object* p = (struct polygon_object*)(periodic_box_obj->contents);
struct subdivided_box* sb = p->sb;
x_box_length = sb->x[1] - sb->x[0];
y_box_length = sb->y[1] - sb->y[0];
z_box_length = sb->z[1] - sb->z[0];
llx = sb->x[0];
urx = sb->x[1];
lly = sb->y[0];
ury = sb->y[1];
llz = sb->z[0];
urz = sb->z[1];
}
if (periodic_box_obj && !(periodic_traditional)) {
int pos_or_neg = (periodic_box->x > 0) ? 1 : -1;
double difference = (periodic_box->x > 0) ? urx - pos->x : pos->x - llx;
// translate X
if (periodic_box->x == 0) {
pos_output->x = pos->x;
}
else if (periodic_box->x % 2 == 0) {
pos_output->x = pos->x + pos_or_neg * (abs(periodic_box->x) * x_box_length);
}
else {
pos_output->x = pos->x + pos_or_neg * ((abs(periodic_box->x) - 1) * x_box_length + 2 * difference);
}
// translate Y
pos_or_neg = (periodic_box->y > 0) ? 1 : -1;
difference = (periodic_box->y > 0) ? ury - pos->y : pos->y - lly;
if (periodic_box->y == 0) {
pos_output->y = pos->y;
}
else if (periodic_box->y % 2 == 0) {
pos_output->y = pos->y + pos_or_neg * (abs(periodic_box->y) * y_box_length);
}
else {
pos_output->y = pos->y + pos_or_neg * ((abs(periodic_box->y) - 1) * y_box_length + 2 * difference);
}
// translate Z
pos_or_neg = (periodic_box->z > 0) ? 1 : -1;
difference = (periodic_box->z > 0) ? urz - pos->z : pos->z - llz;
if (periodic_box->z == 0) {
pos_output->z = pos->z;
}
else if (periodic_box->z % 2 == 0) {
pos_output->z = pos->z + pos_or_neg * (abs(periodic_box->z) * z_box_length);
}
else {
pos_output->z = pos->z + pos_or_neg * ((abs(periodic_box->z) - 1) * z_box_length + 2 * difference);
}
return 0;
}
else {
return 1;
}
}
/*************************************************************************
add_surfmol_with_unique_pb_to_list
In: sm_list: a list of surface molecules
sm: the surface molecule we want to add to the list
Out: Return the head of the list. Also, sm should be added to sm_list if the
periodic box it inhabits isn't already in the list.
*************************************************************************/
struct surface_molecule_list* add_surfmol_with_unique_pb_to_list(
struct surface_molecule_list *sm_list,
struct surface_molecule *sm) {
struct surface_molecule_list *sm_list_head = sm_list;
struct surface_molecule_list *sm_entry = CHECKED_MALLOC_STRUCT(
struct surface_molecule_list, "surface molecule list");
sm_entry->sm = sm;
sm_entry->next = NULL;
if (sm_list == NULL) {
sm_list_head = sm_entry;
}
else if (sm_list->sm == NULL) {
sm_list_head->sm = sm;
free(sm_entry);
}
else {
for (; sm_list != NULL; sm_list = sm_list->next) {
if (sm && periodic_boxes_are_identical(
sm_list->sm->periodic_box, sm->periodic_box)) {
free(sm_entry);
return NULL;
}
if (sm_list->next == NULL) {
sm_list->next = sm_entry;
break;
}
}
}
return sm_list_head;
}
/*************************************************************************
remove_surfmol_from_list
In: sm_head: pointer to the head of a list of surface molecules
sm: the surface molecule we want to remove from the list
Out: Remove sm from the surface molecule list. Return 1 on failure, 0
otherwise.
*************************************************************************/
void remove_surfmol_from_list(
struct surface_molecule_list **sm_head,
struct surface_molecule *sm) {
struct surface_molecule_list *sm_list = *sm_head;
struct surface_molecule_list *prev = *sm_head;
if (sm_list == NULL) {
}
else if (sm_list->sm == sm) {
if (sm_list->next != NULL) {
*sm_head = sm_list->next;
}
else {
*sm_head = NULL;
}
free(sm_list);
}
else {
for (; sm_list != NULL; sm_list = sm_list->next) {
if (sm_list->sm == sm) {
prev->next = sm_list->next;
free(sm_list);
sm_list = NULL;
break;
}
prev = sm_list;
}
}
return;
}
| C |
3D | mcellteam/mcell | src/c_vector.h | .h | 1,010 | 41 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
// this is an auxiliary file that provides std::vector functionality that contains pointers as elements
// used in viz_output.c
#ifndef C_VECTOR_H
#define C_VECTOR_H
#ifdef __cplusplus
//extern "C" {
#endif
typedef void c_vector_t;
c_vector_t* vector_create();
void vector_push_back(c_vector_t* v, void* a);
unsigned long long vector_get_size(c_vector_t* v);
void* vector_at(c_vector_t* v, unsigned long long i);
void vector_delete(c_vector_t* v);
void vector_sort_by_mol_id(c_vector_t* v);
#ifdef __cplusplus
//}
#endif
#endif // C_VECTOR_H
| Unknown |
3D | mcellteam/mcell | src/mcell_run.h | .h | 1,382 | 38 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_init.h"
/* this function runs the whole simulations */
MCELL_STATUS mcell_run_simulation(MCELL_STATE *state);
/* this function runs n iterations */
MCELL_STATUS mcell_run_n_iterations(MCELL_STATE *state, long long output_frequency,
int *restarted_from_checkpoint, int n_iter);
/* this function runs a single iteration of simulations */
MCELL_STATUS mcell_run_iteration(MCELL_STATE *state, long long output_frequency,
int *restarted_from_checkpoint);
/* flush all output buffers to disk to disk after the simulation
* run is complete */
MCELL_STATUS mcell_flush_data(MCELL_STATE *state);
/* print any warnings that were gererated during the simulation
* run */
MCELL_STATUS mcell_print_final_warnings(MCELL_STATE *state);
/* print the final simulation statistics */
MCELL_STATUS mcell_print_final_statistics(MCELL_STATE *state);
| Unknown |
3D | mcellteam/mcell | src/react_outc_nfsim.c | .c | 28,885 | 817 | #include "config.h"
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "count_util.h"
#include "grid_util.h"
#include "logging.h"
#include "mcell_reactions.h"
#include "nfsim_func.h"
#include "react.h"
#include "react_nfsim.h"
#include "react_util.h"
#include "rng.h"
#include "util.h"
#include "vol_util.h"
#include "wall_util.h"
static queryOptions
initializeNFSimQueryforUnimolecularFiring(struct abstract_molecule *am,
const char *external_path);
static bool calculate_nfsim_reactivity(struct graph_data *);
static void calculate_nfsim_diffusion_derived_data(struct volume *state,
struct graph_data *data);
void set_nfsim_product_geometries(struct pathway *path, struct rxn *rx,
int prod_orientation, int prod_index) {
if ((prod_orientation + path->orientation1) *
(prod_orientation - path->orientation1) ==
0 &&
prod_orientation * path->orientation1 != 0) {
if (prod_orientation == path->orientation1)
rx->geometries[prod_index] = 1;
else
rx->geometries[prod_index] = -1;
} else if (rx->n_reactants > 1 &&
(prod_orientation + path->orientation2) *
(prod_orientation - path->orientation2) ==
0 &&
prod_orientation * path->orientation2 != 0) {
if (prod_orientation == path->orientation2)
rx->geometries[prod_index] = 2;
else
rx->geometries[prod_index] = -2;
} else {
rx->geometries[prod_index] = 1;
}
}
queryOptions initializeNFSimQueryNoFiring(struct abstract_molecule *am) {
// constant settings
queryOptions options;
static const char *optionKeys[1] = {"systemQuery"};
options.optionValues = CHECKED_MALLOC_ARRAY(char *, 1, "option array");
options.optionValues[0] = strdup("complex");
// initialize speciesArray with the string we are going to query
char **speciesArray =
CHECKED_MALLOC_ARRAY(char *, 1, "string array of patterns");
speciesArray[0] = am->graph_data->graph_pattern;
static const int optionSeeds[1] = {1};
// copy these settings to the options object
options.initKeys = speciesArray;
options.initValues = optionSeeds;
options.numOfInitElements = 1;
// experiment design: query for reactions with 1 reactant
options.optionKeys = optionKeys;
// options.optionValues = optionValues;
options.numOfOptions = 1;
return options;
}
/**********************************************************************
*
* This function creates a queryOptions object for designing an NFSim
* experiment query after a unimolecular reaction fires.
*
* In: The abstract molecule whose nfsim status we are going to verify
*
* Out: the queryOptions object we will use to interact with nfsim
*
**********************************************************************/
queryOptions
initializeNFSimQueryforUnimolecularFiring(struct abstract_molecule *am,
const char *external_path) {
// constant settings
queryOptions options;
static const char *optionKeys[2] = {"systemQuery", "reaction"};
options.optionValues = CHECKED_MALLOC_ARRAY(char *, 2, "option array");
options.optionValues[0] = strdup("complex");
options.optionValues[1] = strdup(external_path);
// initialize speciesArray with the string we are going to query
char **speciesArray =
CHECKED_MALLOC_ARRAY(char *, 1, "string array of patterns");
speciesArray[0] = am->graph_data->graph_pattern;
static const int optionSeeds[1] = {1};
// copy these settings to the options object
options.initKeys = speciesArray;
options.initValues = optionSeeds;
options.numOfInitElements = 1;
// experiment design: query for reactions with 1 reactant
options.optionKeys = optionKeys;
// options.optionValues = optionValues;
options.numOfOptions = 2;
return options;
}
queryOptions
initializeNFSimQueryforBimolecularFiring(struct abstract_molecule *am,
struct abstract_molecule *am2,
const char *external_path) {
// constant settings
queryOptions options;
static const char *optionKeys[2] = {"systemQuery", "reaction"};
options.optionValues = CHECKED_MALLOC_ARRAY(char *, 2, "option array");
// options.optionValues[0] = CHECKED_MALLOC_ARRAY(char, strlen("complex"),
// "reaction which we will step over");
// strcpy(options.optionValues[0], "complex");
// optionValues[0] = "complex";
// options.optionValues[1] = CHECKED_MALLOC_ARRAY(char, strlen(external_path),
// "reaction which we will step over");
// strcpy(options.optionValues[1], external_path);
options.optionValues[0] = strdup("complex");
options.optionValues[1] = strdup(external_path);
// initialize speciesArray with the string we are going to query
char **speciesArray =
CHECKED_MALLOC_ARRAY(char *, 2, "string array of patterns");
speciesArray[0] = am->graph_data->graph_pattern;
speciesArray[1] = am2->graph_data->graph_pattern;
static const int optionSeeds[2] = {1, 1};
// copy these settings to the options object
options.initKeys = speciesArray;
options.initValues = optionSeeds;
options.numOfInitElements = 2;
// experiment design: query for reactions with 1 reactant
options.optionKeys = optionKeys;
// options.optionValues = optionValues;
options.numOfOptions = 2;
return options;
}
static void find_objects(struct geom_object* current_parent,
const char* name1, struct geom_object** obj1,
const char* name2, struct geom_object** obj2) {
struct geom_object* curr = current_parent;
while (curr != NULL) {
// did we find our object?
if (*obj1 == NULL && curr->last_name != NULL && strcmp(curr->last_name, name1) == 0) {
*obj1 = curr;
}
if (*obj2 == NULL && curr->last_name != NULL && strcmp(curr->last_name, name2) == 0) {
*obj2 = curr;
}
if (*obj1 != NULL && *obj2 != NULL) {
// terminate search
return;
}
// check children
find_objects(curr->first_child, name1, obj1, name2, obj2);
// next object in list
curr = curr->next;
}
}
static bool has_region(struct geom_object* obj, const char* reg_name) {
for (struct region_list *r = obj->regions; r != NULL; r = r->next) {
if (r->reg != NULL && strcmp(r->reg->region_last_name, reg_name) == 0) {
return true;
}
}
return false;
}
int prepare_reaction_nfsim(struct volume *world, struct rxn *rx, void *results,
int path, struct abstract_molecule *reac,
struct abstract_molecule *reac2) {
const char *product_pattern = NULL;
void *individualResult;
int numOfResults = mapvector_size(results);
for (int productIdx = 0; productIdx < numOfResults; productIdx++) {
individualResult = mapvector_get(results, productIdx);
product_pattern = map_get(individualResult,
"label"); // results->results[productIdx].label;
constructNauty_c(product_pattern, 1);
// TODO: we are ignoring optimizing for overlaps for now
/*if(strcmp(reac->graph_pattern, product_pattern) == 0 && overlapFlag == 0){
overlapFlag = 1;
}
else{
rx->product_idx_aux[path]++;
}*/
}
rx->product_idx_aux[path] = numOfResults;
if (rx->nfsim_players[path] == NULL) {
rx->nfsim_players[path] = CHECKED_MALLOC_ARRAY(
struct species *, numOfResults, "reaction players array");
rx->nfsim_geometries[path] = CHECKED_MALLOC_ARRAY(
short, numOfResults, "geometries associated to this path");
}
rx->product_graph_data[path] = CHECKED_MALLOC_ARRAY(
struct graph_data *, rx->product_idx_aux[path],
"graph patterns for products that have been added to the system");
int counter = 0;
const char *diffusion;
rx->external_reaction_data[path].products = numOfResults;
for (int productIdx = 0; productIdx < numOfResults; productIdx++) {
individualResult = mapvector_get(results, productIdx);
product_pattern = map_get(individualResult,
"label"); // results->results[productIdx].label;
// query graph_pattern hashmap instead of recreating stuff
unsigned long graph_hash = lhash(product_pattern);
int error =
get_graph_data(graph_hash, &rx->product_graph_data[path][counter]);
if (error != 0) {
rx->product_graph_data[path][counter] = CHECKED_MALLOC_ARRAY(
struct graph_data, 1, "graph pattern for a single path");
rx->product_graph_data[path][counter]->graph_pattern =
strdup(product_pattern);
rx->product_graph_data[path][counter]->graph_pattern_hash =
lhash(product_pattern);
diffusion = map_get(individualResult, "diffusion_function");
if (diffusion) {
rx->product_graph_data[path][counter]->graph_diffusion =
atof(diffusion);
calculate_nfsim_diffusion_derived_data(
world, rx->product_graph_data[path][counter]);
} else {
rx->product_graph_data[path][counter]->graph_diffusion = -1;
rx->product_graph_data[path][counter]->time_step = -1;
rx->product_graph_data[path][counter]->space_step = -1;
}
calculate_nfsim_reactivity(rx->product_graph_data[path][counter]);
store_graph_data(graph_hash, rx->product_graph_data[path][counter]);
world->n_NFSimSpecies += 1;
}
counter++;
//}
}
// recalculate the position of all players
int num_players = rx->n_reactants;
int kk = rx->n_pathways;
if (kk <= RX_SPECIAL)
kk = 1;
for (int n_pathway = 0; n_pathway < kk; n_pathway++) {
int k = rx->product_idx_aux[n_pathway] + rx->n_reactants;
rx->product_idx[n_pathway] = num_players;
num_players += k;
}
rx->product_idx[kk] = num_players;
// we will be recreating the players and geometries arrays. this might not be
// the most efficient approach but this is because we don't know the total
// number of products before each path is fired individually in nfsim
// XXX: maybe fire them manually and just get the number of products per path
// even if we don't store path information?
if (rx->players != NULL)
free(rx->players);
free(rx->geometries);
rx->players = CHECKED_MALLOC_ARRAY(struct species *, num_players,
"reaction players array");
rx->geometries =
CHECKED_MALLOC_ARRAY(short, num_players, "reaction geometries array");
memset(rx->players, 0, sizeof(struct species *) * num_players);
memset(rx->geometries, 0, sizeof(short) * num_players);
// create pathway that will form players
struct pathway *pathp = (struct pathway *)CHECKED_MALLOC_STRUCT(
struct pathway, "reaction pathway");
if (pathp == NULL) {
return -1;
}
memset(pathp, 0, sizeof(struct pathway));
/* Scan reactants, copying into the new pathway */
int num_vol_mols = 0;
int num_surface_mols = 0;
int all_3d = 1;
/*int complex_type = 0;*/
int reactant_idx = 0;
int oriented_count = 0;
/*int num_complex_reactants = 0;*/
bool orientation_flag1 = 0, orientation_flag2 = 0;
int reactantOrientation1, reactantOrientation2, productOrientation;
// obtain orientation information
calculate_reactant_orientation(reac, reac2, &orientation_flag1,
&orientation_flag2, &reactantOrientation1,
&reactantOrientation2);
struct sym_entry *nfsim_molecule = reac->properties->sym;
// create first reactant entry
rx->geometries[0] = reactantOrientation1;
struct mcell_species *reactants = mcell_add_to_species_list(
nfsim_molecule, orientation_flag1, reactantOrientation1, NULL);
// second reactant entry
if (reac2 != NULL) {
rx->geometries[1] = reactantOrientation2;
nfsim_molecule = reac2->properties->sym;
reactants = mcell_add_to_species_list(nfsim_molecule, orientation_flag2,
reactantOrientation2, reactants);
}
// we will be storing prodcut compartment information in here
compartmentStruct *compartmentInfoArray =
CHECKED_MALLOC_ARRAY(compartmentStruct, numOfResults,
"Creating array of compartment information");
for (int i = 0; i < numOfResults; i++) {
// what compartment is the species now in
individualResult = mapvector_get(results, i);
compartmentInfoArray[i] = getCompartmentInformation_c(map_get(
individualResult,
"compartment")); // getCompartmentInformation_c(results->results[i].compartment);
}
struct species *nfsim_molecule_template;
// get the mcell species proxy we will be using
if (compartmentInfoArray[0].spatialDimensions == 2)
nfsim_molecule_template = world->global_nfsim_surface;
else
nfsim_molecule_template = world->global_nfsim_volume;
// calculate orientation information if its not a vol vol reaciton
if (orientation_flag2) {
orientation_flag1 = true;
individualResult = mapvector_get(results, 0);
const char* outside = compartmentInfoArray[0].outside;
// originalCompartment is in fact the taget compartment where we should place out product
const char* originalCompartment = map_get(individualResult, "originalCompartment");
bool originalCompartmentEmpty = strcmp(originalCompartment, "") == 0;
if (!originalCompartmentEmpty && strcmp(outside, originalCompartment) == 0) {
// outside and original are the same, not completely sure what to do here,
// keeping original implementation
productOrientation = -1;
}
else if (!originalCompartmentEmpty && strcmp(outside, "") != 0) {
// 1) find object with "outside or "originalCompartment" name in world->root_instance,
// then check its regions
// 2) a region of its object is either "ALL" or its surface
// 3) if we go from surface into the object -> orientation == -1,
// all other cases are kept as they were implemented originally because we
// do not have other information about the hierarchy of objects
struct geom_object* objOutside = NULL;
struct geom_object* objOrigCompartment = NULL;
find_objects(world->root_instance, outside, &objOutside, originalCompartment, &objOrigCompartment);
// if we found only one of these objects, check its regions
if (objOutside != NULL && objOrigCompartment != NULL) {
// both are objects, default behavior should be ok
mcell_warn(
"Handling orientation of NFsim reaction where both compartents %s (orig) and %s (outside) are objects is not supported yet, "
"using default orientation 1 (outside)", originalCompartment, outside);
productOrientation = 1;
} else if (objOutside == NULL && objOrigCompartment == NULL) {
mcell_error(
"NFsim reaction returned compartments %s (orig) and %s (outside) that were not identified as object, this is not supported yet.",
originalCompartment, outside
);
exit(1);
} else {
if (objOrigCompartment != NULL) {
if (has_region(objOrigCompartment, outside)) {
// we go from outside (e.g. PM) inside (e.g. CP)
productOrientation = -1;
} else {
// relationship is not known...
mcell_warn(
"Handling orientation of NFsim reaction where both compartent %s (orig) and %s (outside) are not in object-region relationship is not supported yet, "
"using default orientation 1 (outside)", originalCompartment, outside);
productOrientation = 1;
}
} else {
if (has_region(objOutside, originalCompartment)) {
// we go from inside (e.g. CP) outside (e.g. PM)
productOrientation = 1;
} else {
// relationship is not known but we can assume that we go onto surface because the original compartment object is NULL,
// therefore it is a region not an object,
// selecting 1 because we need to stay on the 'outside' side of the surface
productOrientation = 1;
}
}
}
} else {
// outside is empty, we get this type of information from reactions like this:
// MemA@PM -> Mem@PM+A@EC - we need to go outside from membrane PM to EC
productOrientation = 1;
}
} else {
orientation_flag1 = false;
productOrientation = 0;
}
struct mcell_species *products =
mcell_add_to_species_list(nfsim_molecule_template->sym, orientation_flag1,
productOrientation, NULL);
rx->nfsim_geometries[path][0] = productOrientation;
// if theres more than one product
for (int i = 1; i < numOfResults; i++) {
// compartmentInfo =
// getCompartmentInformation_c(results->results[i].compartment);
if (compartmentInfoArray[i].spatialDimensions == 2)
nfsim_molecule_template = world->global_nfsim_surface;
else
nfsim_molecule_template = world->global_nfsim_volume;
if (orientation_flag2) {
individualResult = mapvector_get(results, i);
if (strcmp(compartmentInfoArray[i].outside,
map_get(individualResult, "originalCompartment")) ==
0) { // results->results[i].originalCompartment) == 0){
productOrientation = -1;
} else {
productOrientation = 1;
}
} else {
productOrientation = 0;
}
rx->nfsim_geometries[path][i] = productOrientation;
products = mcell_add_to_species_list(nfsim_molecule_template->sym,
orientation_flag1, productOrientation,
products);
}
// free up compartment struct helpers
for (int i = 0; i < numOfResults; i++) {
delete_compartmentStructs(compartmentInfoArray[i]);
}
free(compartmentInfoArray);
// create out pathway
if (extract_reactants(pathp, reactants, &reactant_idx, &num_vol_mols,
&num_surface_mols, &all_3d, &oriented_count) != 0) {
return -1;
}
int num_surf_products = 0;
/*int num_complex_products = 0;*/
int bidirectional = 0;
if (extract_products(world->notify, pathp, products, &num_surf_products,
bidirectional, all_3d) == MCELL_FAIL) {
return MCELL_FAIL;
}
mcell_delete_species_list(reactants);
mcell_delete_species_list(products);
int k = 0;
struct product *prod = NULL;
// store this nfsim path information
counter = 0;
// XXX: it might be necessary to clear out the stuff in pathp at the very end
for (prod = pathp->product_head; counter < numOfResults;) {
rx->nfsim_players[path][counter] = prod->prod;
++counter;
if (counter < numOfResults)
prod = prod->next;
}
prod->next = NULL;
if (rx->players != NULL) {
free(rx->players);
free(rx->geometries);
}
rx->players = CHECKED_MALLOC_ARRAY(struct species *, num_players,
"reaction players array");
rx->geometries =
CHECKED_MALLOC_ARRAY(short, num_players, "reaction geometries array");
memset(rx->players, 0, sizeof(struct species *) * num_players);
memset(rx->geometries, 0, sizeof(short) * num_players);
// recreate players array
rx->players[0] = pathp->reactant1;
// if its a bimolecular reaction
if (reac2 != NULL)
rx->players[1] = pathp->reactant2;
for (int n_pathway = 0; n_pathway < rx->n_pathways; n_pathway++) {
k = rx->product_idx[n_pathway] + rx->n_reactants;
counter = 0;
for (counter = 0; counter < rx->product_idx_aux[n_pathway]; counter++) {
// XXX: right now we are ignoring recycled species which is inefficient
// if (recycled1 == 0 && prod->prod == pathp->reactant1) {
// recycled1 = 1;
// kk = rx->product_idx[path] + 0;
//}
// else {
kk = k;
k++;
//}
// kk = rx->product_idx[path] + 0;
rx->players[kk] = rx->nfsim_players[n_pathway][counter];
set_nfsim_product_geometries(
pathp, rx, rx->nfsim_geometries[n_pathway][counter], kk);
}
} /* end for (n_pathway = 0, ...) */
init_reaction_info(rx);
rx->info[path].pathname = NULL;
// adjust reaction probabilities
// adjust_rates_nfsim(world, rx, pathp);
// cleanup path information
struct product *tmp = pathp->product_head;
struct product *tmp2 = NULL;
while (tmp != NULL) {
tmp2 = tmp->next;
free(tmp);
tmp = tmp2;
}
free(pathp);
return MCELL_SUCCESS;
}
void free_reaction_nfsim(struct rxn *rx, int path) {
free(rx->nfsim_players[path]);
free(rx->nfsim_geometries[path]);
// i actually need to iterate over all products
/*for(int i=0; i < rx->external_reaction_data[path].products;i++){
free(rx->product_graph_data[path][i]->graph_pattern);
free(rx->product_graph_data[path][i]);
}*/
free(rx->product_graph_data[path]);
rx->nfsim_players[path] = NULL;
rx->nfsim_geometries[path] = NULL;
rx->product_graph_data[path] = NULL;
}
//int outcome_unimolecular_nfsim(struct volume *world, struct rxn *rx, int path,
// struct abstract_molecule *reac, double t) {
// int result = RX_A_OK;
//
// if (rx->product_idx_aux[path] == -1) {
// mcell_log("uni restart %s\n", reac->graph_data->graph_pattern);
// queryOptions options = initializeNFSimQueryforUnimolecularFiring(
// reac, rx->external_reaction_data[path].reaction_name);
//
// void *results = mapvector_create();
//
// initAndQuerySystemStatus_c(options, results);
//
// constructNauty_c(reac->graph_data->graph_pattern, -1);
//
// // fill in the rxn react structure with the appropiate information
// world->n_NFSimReactions += 1;
// prepare_reaction_nfsim(world, rx, results, path, reac, NULL);
// }
// return result;
//}
/*
Calculate the space_Step and time_step associated to this molecule based on
right now it only considers global time_steps and space_steps
*/
void calculate_nfsim_diffusion_derived_data(struct volume *state,
struct graph_data *data) {
double global_time_unit = state->time_unit;
const char *compartment1 =
extractSpeciesCompartmentFromNauty_c(data->graph_pattern);
compartmentStruct reactantCompartmentInfo1 =
getCompartmentInformation_c(compartment1);
// free string allocated in extractSpeciesCompartmentFromNauty_c
free((char*)compartment1);
if (!distinguishable(state->space_step, 0, EPS_C)) // Global timestep
{
data->space_step =
sqrt(4.0 * 1.0e8 * data->graph_diffusion * global_time_unit) *
state->r_length_unit;
data->time_step = 1.0;
} else /* Global spacestep */
{
double space_step = state->space_step * state->length_unit;
if (reactantCompartmentInfo1.spatialDimensions == 2) {
data->time_step =
space_step * space_step /
(MY_PI * 1.0e8 * data->graph_diffusion * global_time_unit);
} else {
data->time_step =
space_step * space_step * MY_PI /
(16.0 * 1.0e8 * data->graph_diffusion * global_time_unit);
}
data->space_step = sqrt(4.0 * 1.0e8 * data->graph_diffusion *
data->time_step * global_time_unit) *
state->r_length_unit;
}
// free strings allocated in getCompartmentInformation_c
free(reactantCompartmentInfo1.name);
free(reactantCompartmentInfo1.outside);
}
bool calculate_nfsim_reactivity(struct graph_data *graph) {
graph->flags = 0;
queryOptions options =
initializeNFSimQueryForBimolecularReactions(graph, NULL, "0");
void *results = mapvectormap_create();
initAndQueryByNumReactant_c(options, results);
bool dimensionalityFlag = true;
if (mapvectormap_size(results) > 0) {
char **resultKeys = mapvectormap_getKeys(results);
// we know that it only contains one result
void *headComplex = mapvectormap_get(results, resultKeys[0]);
int resultSize = mapvectormap_size(results);
for (int i = 0; i < resultSize; i++) {
free(resultKeys[i]);
}
free(resultKeys);
int headNumAssociatedReactions = mapvector_size(headComplex);
void *pathInformation;
for (int path = 0; path < headNumAssociatedReactions; path++) {
pathInformation = mapvector_get(headComplex, path);
const char *dimensionality =
map_get(pathInformation, "reactionDimensionality");
if (!dimensionality) {
dimensionalityFlag = false;
break;
}
if (strcmp(dimensionality, "VOLSURF") == 0) {
graph->flags |= CAN_VOLSURF;
}
if (strcmp(dimensionality, "VOLVOL") == 0) {
graph->flags |= CAN_VOLVOL;
}
if (strcmp(dimensionality, "SURFSURF") == 0) {
graph->flags |= CAN_SURFSURF;
}
}
}
// cleanup
mapvectormap_delete(results);
if (dimensionalityFlag) {
return true;
} else {
graph->flags = -1;
return false;
}
}
/**
Doesn't fire any reactions, it just queries NFSim for the properties of a given
graph pattern
used for initialization and copies them to the reac->graph_data object
**/
void properties_nfsim(struct volume *world, struct abstract_molecule *reac) {
// XXX: this could be stored in a hashmap for initialization purposes if it
// becomes oto much of an
// issue to query everytime. we are not doi9ng it right now since this
// function is only called
// when initially releasing particles. moreover it might be worth it to have a
// hashmap containing
// graph_data properties instead of it being stored in every particle...
// initialize system with only one molecule
queryOptions options = initializeNFSimQueryNoFiring(reac);
void *results = mapvector_create();
initAndQuerySystemStatus_c(options, results);
// get the first result since we are only querying information for one
// molecule
void *individualResult = mapvector_get(results, 0);
const char *result = map_get(individualResult, "diffusion_function");
if (result) {
reac->graph_data->graph_diffusion = atof(result);
calculate_nfsim_diffusion_derived_data(world, reac->graph_data);
} else {
reac->graph_data->graph_diffusion = -1;
reac->graph_data->space_step = -1;
reac->graph_data->time_step = -1;
reac->get_diffusion = get_standard_diffusion;
reac->get_space_step = get_standard_space_step;
reac->get_time_step = get_standard_time_step;
}
mapvector_delete(results);
// now lets get information about the reactionality of this reactant
if (calculate_nfsim_reactivity(reac->graph_data)) {
reac->get_flags = get_nfsim_flags;
} else {
reac->get_flags = get_standard_flags;
}
free(options.optionValues[0]);
free(options.optionValues);
free(options.initKeys);
}
int outcome_nfsim(struct volume *world, struct rxn *rx, int path,
struct abstract_molecule *reac,
struct abstract_molecule *reac2, double t) {
int result = RX_A_OK;
queryOptions options;
// if this is a reaction rule that can be mapped in different ways we need to
// resample
if (rx->product_idx_aux[path] != -1 &&
rx->external_reaction_data[path].resample == 1) {
free_reaction_nfsim(rx, path);
rx->product_idx_aux[path] = -1;
}
// if we don't have previous information about this path then build up the
// rxn structure
if (rx->product_idx_aux[path] == -1) {
world->n_NFSimReactions += 1;
if (reac2 == NULL)
options = initializeNFSimQueryforUnimolecularFiring(
reac, rx->external_reaction_data[path].reaction_name);
else {
options = initializeNFSimQueryforBimolecularFiring(
reac, reac2, rx->external_reaction_data[path].reaction_name);
}
void *results = mapvector_create();
initAndQuerySystemStatus_c(options, results);
// queryResults results = initAndQuerySystemStatus_c(options);
// frees up the option object
free(options.optionValues[0]);
free(options.optionValues[1]);
free(options.optionValues);
free(options.initKeys);
// fill in the rxn react structure with the appropiate information
prepare_reaction_nfsim(world, rx, results, path, reac, reac2);
// frees up the query result
mapvector_delete(results);
}
// otherwise just update populations
else {
for (int i = 0; i < rx->product_idx_aux[path]; i++) {
constructNauty_c(rx->product_graph_data[path][i]->graph_pattern, 1);
}
// and clean the info information for good measure
rx->info[path].pathname = NULL;
}
// also decrease reactant populations
constructNauty_c(reac->graph_data->graph_pattern, -1);
if (reac2 != NULL)
constructNauty_c(reac2->graph_data->graph_pattern, -1);
return result;
}
| C |
3D | mcellteam/mcell | src/edge_util.c | .c | 7,068 | 224 | /******************************************************************************
*
* Copyright (C) 2006-2017,2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <stdlib.h>
#include <iostream>
#include "edge_util.h"
#include "mcell_structs.h"
#include "sym_table.h"
#include "debug_config.h"
/**************************************************************************\
** Edge hash table section--finds common edges in polygons **
\**************************************************************************/
/***************************************************************************
edge_equals:
In: pointers to two poly_edge structs
Out: Returns 1 if the edges are the same, 0 otherwise.
Note: Orientation invariant, so an edge between vertex 1 and 2
is the same as an edge between vertex 2 and 1.
***************************************************************************/
int edge_equals(struct poly_edge *e1, struct poly_edge *e2) {
if ((!distinguishable(e1->v1x, e2->v1x, EPS_C)) &&
(!distinguishable(e1->v1y, e2->v1y, EPS_C)) &&
(!distinguishable(e1->v1z, e2->v1z, EPS_C)) &&
(!distinguishable(e1->v2x, e2->v2x, EPS_C)) &&
(!distinguishable(e1->v2y, e2->v2y, EPS_C)) &&
(!distinguishable(e1->v2z, e2->v2z, EPS_C))) {
return 1;
}
if ((!distinguishable(e1->v1x, e2->v2x, EPS_C)) &&
(!distinguishable(e1->v1y, e2->v2y, EPS_C)) &&
(!distinguishable(e1->v1z, e2->v2z, EPS_C)) &&
(!distinguishable(e1->v2x, e2->v1x, EPS_C)) &&
(!distinguishable(e1->v2y, e2->v1y, EPS_C)) &&
(!distinguishable(e1->v2z, e2->v1z, EPS_C))) {
return 1;
}
return 0;
}
/***************************************************************************
edge_hash:
In: pe: pointer to a poly_edge struct
nkeys: number of keys in the hash table
Out: Returns a hash value between 0 and nkeys-1.
Note: Orientation invariant, so a hash with the two endpoints swapped
will be the same.
***************************************************************************/
int edge_hash(struct poly_edge *pe, int nkeys) {
/* Get hash of X,Y,Z set of doubles for 1st and 2nd points */
/* (Assume they're laid out consecutively in memory) */
/* FIXME: This seems like a hack. Since poly_edge is a struct there's no
* guarantee what the memory layout will be and the compiler may pad */
unsigned int hashL = jenkins_hash((ub1 *)&(pe->v1x), 3 * sizeof(double));
unsigned int hashR = jenkins_hash((ub1 *)&(pe->v2x), 3 * sizeof(double));
return (hashL + hashR) %
nkeys; /* ^ is symmetric so doesn't matter which is L and which is R */
}
/***************************************************************************
*
* create_new_poly_edge creates a new poly_edge and attaches it to the
* past pointer to linked list of poly_edges
*
***************************************************************************/
static struct poly_edge* create_new_poly_edge(struct poly_edge* list) {
struct poly_edge *pei = CHECKED_MALLOC_STRUCT_NODIE(struct poly_edge, "polygon edge");
if (pei == NULL) {
return NULL;
}
pei->next = list->next;
list->next = pei;
pei->n = 0;
pei->face[0] = -1;
pei->face[1] = -1;
pei->edge[0] = -1;
pei->edge[1] = -1;
return pei;
}
/***************************************************************************
ehtable_init:
In: eht: pointer to an edge_hashtable struct
nkeys: number of keys that the hash table uses
Out: Returns 0 on success, 1 on failure.
Hash table is initialized.
***************************************************************************/
int ehtable_init(struct edge_hashtable *eht, int nkeys) {
eht->nkeys = nkeys;
eht->stored = 0;
eht->distinct = 0;
eht->data =
CHECKED_MALLOC_ARRAY_NODIE(struct poly_edge, nkeys, "edge hash table");
if (eht->data == NULL)
return 1;
for (int i = 0; i < nkeys; i++) {
eht->data[i].next = NULL;
eht->data[i].n = 0;
eht->data[i].face[0] = eht->data[i].face[1] = -1;
}
return 0;
}
/***************************************************************************
ehtable_add:
In: pointer to an edge_hashtable struct
pointer to the poly_edge to add
Out: Returns 0 on success, 1 on failure.
Edge is added to the hash table.
***************************************************************************/
int ehtable_add(struct edge_hashtable *eht, struct poly_edge *pe) {
#ifdef DEBUG_GEOM_OBJ_INITIALIZATION
std::cout << "ehtable_add:\n";
dump_poly_edge(0, pe);
#endif
int i = edge_hash(pe, eht->nkeys);
struct poly_edge *pep = &(eht->data[i]);
while (pep != NULL) {
if (pep->n == 0) /* New entry */
{
pep->n = 1;
pep->face[0] = pe->face[0];
pep->edge[0] = pe->edge[0];
pep->v1x = pe->v1x;
pep->v1y = pe->v1y;
pep->v1z = pe->v1z;
pep->v2x = pe->v2x;
pep->v2y = pe->v2y;
pep->v2z = pe->v2z;
eht->stored++;
eht->distinct++;
return 0;
}
if (edge_equals(pep, pe)) /* This edge exists already ... */
{
if (pep->face[1] == -1) /* ...and we're the 2nd one */
{
pep->face[1] = pe->face[0];
pep->edge[1] = pe->edge[0];
pep->n++;
eht->stored++;
return 0;
} else /* ...or we're 3rd and need more space */
{
if (pep->next != NULL) {
if (edge_equals(pep->next, pe)) /* Space already there */
{
pep->n++;
pep = pep->next;
continue; /* Use space on next loop */
}
}
struct poly_edge *pei = create_new_poly_edge(pep);
if (pei == NULL) {
return 1;
}
pep->n++;
pep = pei;
eht->distinct--; /* Not really distinct, just need more space */
}
} else if (pep->next != NULL) {
pep = pep->next;
} else { /* Hit end of list, so make space for use next loop. */
struct poly_edge *pei = create_new_poly_edge(pep);
if (pei == NULL) {
return 1;
}
pep = pei;
}
}
return 0;
}
/***************************************************************************
ehtable_kill:
In: eht: pointer to an edge_hashtable struct
Out: No return value. Hashtable data is deallocated.
Note: eht itself is not freed, since it isn't created with ehtable_init.
***************************************************************************/
void ehtable_kill(struct edge_hashtable *eht) {
struct poly_edge *pe;
for (int i = 0; i < eht->nkeys; i++) {
while (eht->data[i].next != NULL) {
pe = eht->data[i].next;
eht->data[i].next = pe->next;
free(pe);
}
}
free(eht->data);
eht->data = NULL;
eht->nkeys = 0;
}
| C |
3D | mcellteam/mcell | src/mcell_reactions.c | .c | 138,355 | 3,961 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <assert.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include "nfsim_func.h"
#include "diffuse_util.h"
#include "sym_table.h"
#include "logging.h"
#include "react_util.h"
#include "strfunc.h"
#include "react.h"
#include "mcell_reactions.h"
#include "diffuse.h"
#include "vol_util.h"
#include "mcell_structs.h"
/* static helper functions */
static char *concat_rx_name(char *name1, char *name2);
MCELL_STATUS extract_reactants(struct pathway *path,
struct mcell_species *reactants,
int *num_reactants, int *num_vol_mols,
int *num_surface_mols,
int *all_3d,
int *oriented_count);
static MCELL_STATUS extract_catalytic_arrow(struct pathway *path,
struct reaction_arrow *react_arrow,
int *num_reactants,
int *num_vol_mols,
int *num_surface_mols, int *all_3d,
int *oriented_count);
static MCELL_STATUS extract_surface(struct pathway *path,
struct mcell_species *surf_class,
int *num_reactants,
unsigned int *num_surfaces,
int *oriented_count);
MCELL_STATUS extract_products(struct notifications *notify,
struct pathway *path,
struct mcell_species *products,
int *num_surf_products,
int bidirectional,
int all_3d);
static MCELL_STATUS check_surface_specs(struct notifications *notify,
int num_reactants, int num_surfaces,
int num_vol_mols, int all_3d,
int oriented_count);
static MCELL_STATUS add_catalytic_species_to_products(struct pathway *path,
int catalytic,
int bidirectional,
int all_3d);
static MCELL_STATUS invert_current_reaction_pathway(
struct sym_table_head *rxn_sym_table,
double vacancy_search_dist2,
struct pathway *pathp,
struct reaction_rate *reverse_rate,
const char *rate_filename);
static char *create_prod_signature(struct product **product_head);
static void set_reaction_player_flags(struct rxn *rx);
static int build_reaction_hash_table(
struct rxn ***reaction_hash, int *n_reactions,
struct sym_table_head *rxn_sym_table, int *rx_hashsize, int num_rx);
static void check_reaction_for_duplicate_pathways(struct pathway **head);
static int load_rate_file(struct volume* state, struct rxn *rx, char *fname, int path);
static void add_surface_reaction_flags(struct sym_table_head *mol_sym_table,
struct species *all_mols,
struct species *all_surface_mols,
struct species *all_volume_mols);
static void alphabetize_pathway(struct pathway *path, struct rxn *reaction);
static struct rxn *split_reaction(struct rxn *rx);
static void check_duplicate_special_reactions(struct pathway *path);
static int sort_product_list_compare(struct product *list_item,
struct product *new_item);
static struct product *sort_product_list(struct product *product_head);
/*************************************************************************
*
* mcell_modify_multiple_rate_constants - modifies the rate constant of multiple reactions with
* names.
*
*************************************************************************/
MCELL_STATUS
mcell_modify_multiple_rate_constants(struct volume *world, char **names, double *rate_constants, int n_rxns) {
// Store what each type of reaction is
// diffusing
struct rxn **reactions_ud = (struct rxn **)malloc(0 * sizeof(*reactions_ud)); // Empty
// unimolecular non-diffusing, volume
struct rxn **reactions_undv = (struct rxn **)malloc(0 * sizeof(*reactions_undv));
// unimolecular non-diffusing, surface
struct rxn **reactions_unds = (struct rxn **)malloc(0 * sizeof(*reactions_unds));
// Keep track of the size
int n_reactions_ud=0;
int n_reactions_undv=0;
int n_reactions_unds=0;
// Go through all the reactions
int i_rxn=0;
while(i_rxn < n_rxns)
{
// Grab the reaction
struct sym_table_head *rxpn_sym_table = world->rxpn_sym_table;
struct sym_entry *sym = retrieve_sym(names[i_rxn], rxpn_sym_table);
// If the reaction couldn't be found by name, return fail
if (sym == NULL)
{
return MCELL_FAIL;
}
// Found the reaction, now do the changing
// What is the pathway that needs to be changed?
struct rxn_pathname *rxpn = (struct rxn_pathname *)sym->value;
// The reaction that owns this pathway
struct rxn *reaction = rxpn->rx;
// The index of the pathway in this reaction
int j = rxpn->path_num;
// Check what type of reaction this is; store this to update the scheduler later
int can_diffuse = distinguishable(reaction->players[0]->D, 0, EPS_C);
if (reaction->n_reactants == 1 && can_diffuse)
{
// unimolecular reactions w/ diffusable reactants
reactions_ud = (struct rxn **) realloc(reactions_ud, (n_reactions_ud + 1)*sizeof(*reactions_ud));
reactions_ud[n_reactions_ud] = reaction;
n_reactions_ud++;
}
else if (((!can_diffuse) && (reaction->n_reactants == 1)) ||
((!can_diffuse) && (reaction->n_reactants == 2) && (reaction->players[1]->flags == IS_SURFACE)))
{
// unimolecular reactions w/ non-diffusable reactants
// Surface or volume
if ((reaction->players[0]->flags & NOT_FREE) != 0)
{
// Surface
reactions_unds = (struct rxn **) realloc(reactions_unds, (n_reactions_unds + 1)*sizeof(*reactions_unds));
reactions_unds[n_reactions_unds] = reaction;
n_reactions_unds++;
}
else
{
// Volume
reactions_undv = (struct rxn **) realloc(reactions_undv, (n_reactions_undv + 1)*sizeof(*reactions_undv));
reactions_undv[n_reactions_undv] = reaction;
n_reactions_undv++;
}
}
// From the new rate constant, compute the NEW probability for this pathway
double p = rate_constants[i_rxn] * reaction->pb_factor;
// Find the delta_prob for this pathway
double delta_prob;
if (j == 0)
delta_prob = p - reaction->cum_probs[0];
else
delta_prob = p - (reaction->cum_probs[j] - reaction->cum_probs[j - 1]);
// Update the prob for this pathway, but ALSO all other pathways above it
for (int k = j; k < reaction->n_pathways; k++)
{
reaction->cum_probs[k] += delta_prob;
}
reaction->max_fixed_p += delta_prob;
reaction->min_noreaction_p += delta_prob;
// Go to the next reaction that needs to be changed
i_rxn++;
}
// Now, reschedule all necessary reactions at once
// Check: are there any reactions with diffusable reactants
if (n_reactions_ud > 0) // There is at least one
{
for (struct storage_list *local = world->storage_head; local != NULL; local = local->next)
{
struct abstract_element *head_molecule = local->store->timer->current;
while (local->store->timer->current != NULL)
{
struct abstract_molecule *am = (struct abstract_molecule *)schedule_peak(local->store->timer);
// Go through all types of these reactions
for (int i_reactions_ud=0; i_reactions_ud<n_reactions_ud; i_reactions_ud++)
{
// We only want to update molecules involved in this reaction.
// Also, skip dead molecs (props=NULL). They'll be cleaned up later.
if ((am->properties != NULL) && (am->properties->species_id == reactions_ud[i_reactions_ud]->players[0]->species_id))
{
// Setting t2=0 and ACT_CHANGE will cause the lifetime to be
// recomputed during the next timestep
am->t2 = 0.0;
am->flags |= ACT_CHANGE;
}
}
}
// Reset current molecule in scheduler now that we're done "peaking"
local->store->timer->current = head_molecule;
}
}
// Check: are there any reactions with NON-diffusable reagents
// Volume case
if (n_reactions_undv > 0) // There is at least one
{
int n_subvols = world->n_subvols;
for (int i = 0; i < n_subvols; i++)
{
struct subvolume *sv = &(world->subvol[i]);
for (struct per_species_list *psl = sv->species_head; psl != NULL; psl = psl->next)
{
if (psl->properties == NULL)
{
continue;
}
for (struct volume_molecule *vm = psl->head; vm != NULL; vm = vm->next_v)
{
if ((vm->properties != NULL) && (vm->t > world->current_iterations))
{
// Go through all types of these reactions
for (int i_reactions_undv=0; i_reactions_undv<n_reactions_undv; i_reactions_undv++)
{
// More efficient here would be a hash table from species_id to reaction
if (vm->properties->species_id == reactions_undv[i_reactions_undv]->players[0]->species_id)
{
for (struct storage_list *local = world->storage_head; local != NULL; local = local->next)
{
vm->flags |= ACT_CHANGE;
vm->t2 = 0.0;
schedule_reschedule(local->store->timer, vm, world->current_iterations);
}
}
}
}
}
}
}
}
// Surface case
if (n_reactions_unds > 0) // There is at least one
{
int n_subvols = world->n_subvols;
for (int i = 0; i < n_subvols; i++)
{
struct subvolume *sv = &(world->subvol[i]);
for (struct wall_list *wl = sv->wall_head; wl != NULL; wl = wl->next)
{
struct surface_grid *grid = wl->this_wall->grid;
if (grid != NULL)
{
for (u_int tile_idx = 0; tile_idx < grid->n_tiles; tile_idx++)
{
if (grid->sm_list[tile_idx])
{
struct surface_molecule *sm = grid->sm_list[tile_idx]->sm;
if ((sm->properties != NULL) && (sm->t > world->current_iterations))
{
// Go through all types of these reactions
for (int i_reactions_unds=0; i_reactions_unds<n_reactions_unds; i_reactions_unds++)
{
// More efficient here would be a hash table from species_id to reaction
if (sm->properties->species_id == reactions_unds[i_reactions_unds]->players[0]->species_id)
{
for (struct storage_list *local = world->storage_head; local != NULL; local = local->next)
{
sm->flags |= ACT_CHANGE;
sm->t2 = 0.0;
schedule_reschedule(local->store->timer, sm, world->current_iterations);
}
}
}
}
}
}
}
}
}
}
free(reactions_ud);
free(reactions_undv);
free(reactions_unds);
return MCELL_SUCCESS;
}
/*************************************************************************
*
* mcell_modify_rate_constant - modifies the rate constant of a reaction with a
* specified name. For example, if you have this:
*
* vm + vm -> NULL [1e7] : rxn
*
* then you can change the rate constant from 1e7 to 0 like this:
*
* mcell_modify_rate_constant(world, "rxn", 0)
*
* NOTE: This is inefficient and needs more extensive testing
*
*************************************************************************/
MCELL_STATUS
mcell_modify_rate_constant(struct volume *world, char *name, double rate_constant) {
struct sym_table_head *rxpn_sym_table = world->rxpn_sym_table;
struct sym_entry *sym = retrieve_sym(name, rxpn_sym_table);
if (sym == NULL)
{
return MCELL_FAIL;
}
else
{
// What is the pathway that needs to be changed?
struct rxn_pathname *rxpn = (struct rxn_pathname *)sym->value;
// The reaction that owns this pathway
struct rxn *reaction = rxpn->rx;
// The index of the pathway in this reaction
int j = rxpn->path_num;
// From the new rate constant, compute the NEW probability for this pathway
double p = rate_constant * reaction->pb_factor;
// Find the delta_prob for this pathway
double delta_prob;
if (j == 0)
delta_prob = p - reaction->cum_probs[0];
else
delta_prob = p - (reaction->cum_probs[j] - reaction->cum_probs[j - 1]);
// Update the prob for this pathway, but ALSO all other pathways above it
for (int k = j; k < reaction->n_pathways; k++)
{
reaction->cum_probs[k] += delta_prob;
}
reaction->max_fixed_p += delta_prob;
reaction->min_noreaction_p += delta_prob;
// Print if the flags are set
/*
if (world->notify->time_varying_reactions == NOTIFY_FULL &&
reaction->cum_probs[j] >= world->notify->reaction_prob_notify) {
// Print the reaction probabilities
double new_prob;
if (j == 0)
{
new_prob = reaction->cum_probs[0];
}
else
{
new_prob = reaction->cum_probs[j] - reaction->cum_probs[j - 1];
}
// Print the new_prob
if (reaction->n_reactants == 1)
{
mcell_log_raw("Probability %.4e set for %s[%d] -> ", new_prob,
reaction->players[0]->sym->name, reaction->geometries[0]);
}
else if (reaction->n_reactants == 2)
{
mcell_log_raw("Probability %.4e set for %s[%d] + %s[%d] -> ", new_prob,
reaction->players[0]->sym->name, reaction->geometries[0],
reaction->players[1]->sym->name, reaction->geometries[1]);
}
else
{
mcell_log_raw("Probability %.4e set for %s[%d] + %s[%d] + %s[%d] -> ",
new_prob, reaction->players[0]->sym->name, reaction->geometries[0],
reaction->players[1]->sym->name, reaction->geometries[1],
reaction->players[2]->sym->name, reaction->geometries[2]);
}
for (unsigned int n_product = reaction->product_idx[j];
n_product < reaction->product_idx[j + 1]; n_product++)
{
if (reaction->players[n_product] != NULL)
{
mcell_log_raw("%s[%d] ", reaction->players[n_product]->sym->name,
reaction->geometries[n_product]);
}
}
mcell_log_raw("\n");
}
*/
// This is the old code as of 01.27.2017. Fixed based on react_cond.c
/*
int num_path = reaction->n_pathways;
double p = rate_constant * reaction->pb_factor;
double delta_prob = 0;
if (num_path > 1) {
delta_prob = \
p - (reaction->cum_probs[num_path-1] - reaction->cum_probs[num_path-2]);
}
else {
delta_prob = p - (reaction->cum_probs[num_path-1]);
}
reaction->cum_probs[num_path-1] += delta_prob;
reaction->max_fixed_p += delta_prob;
reaction->min_noreaction_p += delta_prob;
*/
// Now reschedule all the necessary reactions
int can_diffuse = distinguishable(reaction->players[0]->D, 0, EPS_C);
// Need to recompute lifetimes for unimolecular reactions w/ diffusable
// reactants.
if (reaction->n_reactants == 1 && can_diffuse)
{
for (struct storage_list *local = world->storage_head; local != NULL; local = local->next)
{
struct abstract_element *head_molecule = local->store->timer->current;
while (local->store->timer->current != NULL)
{
struct abstract_molecule *am = (struct abstract_molecule *)schedule_peak(local->store->timer);
// We only want to update molecules involved in this reaction.
// Also, skip dead molecs (props=NULL). They'll be cleaned up later.
if ((am->properties != NULL) && (am->properties->species_id == reaction->players[0]->species_id))
{
// Setting t2=0 and ACT_CHANGE will cause the lifetime to be
// recomputed during the next timestep
am->t2 = 0.0;
am->flags |= ACT_CHANGE;
}
}
// Reset current molecule in scheduler now that we're done "peaking"
local->store->timer->current = head_molecule;
}
}
// Need to recompute lifetimes for non-diffusing molecules that are
// unimolecular or where you have a surface molecule at a surface class
// (e.g. sm@sc->whatever). These molecules won't come up next in the
// scheduler, so we have to hunt them all down... :(
if (((!can_diffuse) && (reaction->n_reactants == 1)) ||
((!can_diffuse) && (reaction->n_reactants == 2) && (reaction->players[1]->flags == IS_SURFACE)))
{
for (struct storage_list *local = world->storage_head; local != NULL; local = local->next)
{
int n_subvols = world->n_subvols;
for (int i = 0; i < n_subvols; i++)
{
struct subvolume *sv = &(world->subvol[i]);
// Reschedule the surface molecules involved in the reaction
if ((reaction->players[0]->flags & NOT_FREE) != 0)
{
for (struct wall_list *wl = sv->wall_head; wl != NULL; wl = wl->next)
{
struct surface_grid *grid = wl->this_wall->grid;
if (grid != NULL)
{
for (u_int tile_idx = 0; tile_idx < grid->n_tiles; tile_idx++)
{
if (grid->sm_list[tile_idx])
{
struct surface_molecule *sm = grid->sm_list[tile_idx]->sm;
if ((sm->properties != NULL) &&
(sm->properties->species_id == reaction->players[0]->species_id) &&
(sm->t > world->current_iterations))
{
sm->flags |= ACT_CHANGE;
sm->t2 = 0.0;
schedule_reschedule(local->store->timer, sm, world->current_iterations);
}
}
}
}
}
}
// Reschedule the volume molecules involved in the reaction
else
{
for (struct per_species_list *psl = sv->species_head; psl != NULL; psl = psl->next)
{
if (psl->properties == NULL)
{
continue;
}
for (struct volume_molecule *vm = psl->head; vm != NULL; vm = vm->next_v)
{
if ((vm->properties != NULL) &&
(vm->properties->species_id == reaction->players[0]->species_id) &&
(vm->t > world->current_iterations))
{
vm->flags |= ACT_CHANGE;
vm->t2 = 0.0;
schedule_reschedule(local->store->timer, vm, world->current_iterations);
}
}
}
}
}
}
}
}
return MCELL_SUCCESS;
}
MCELL_STATUS
mcell_add_reaction_simplified(
struct volume *state,
struct mcell_species *reactants,
struct reaction_arrow *arrow,
struct mcell_species *surfs,
struct mcell_species *products,
struct reaction_rates *rates,
struct sym_entry *pathname) {
mcell_add_reaction(state->notify, &state->r_step_release,
state->rxn_sym_table, state->radial_subdivisions,
state->vacancy_search_dist2, reactants, arrow, surfs,
products, pathname, rates, NULL, NULL);
return MCELL_SUCCESS;
}
/*************************************************************************
*
* mcell_add_reaction add a single reaction described by reaction_def to
* the simulations.
*
*************************************************************************/
MCELL_STATUS
mcell_add_reaction(struct notifications *notify,
double **r_step_release,
struct sym_table_head *rxn_sym_table,
u_int radial_subdivisions,
double vacancy_search_dist2,
struct mcell_species *reactants,
struct reaction_arrow *react_arrow,
struct mcell_species *surf_class,
struct mcell_species *products, struct sym_entry *pathname,
struct reaction_rates *rates,
const char *forward_rate_filename,
const char *backward_rate_filename) {
char *rx_name;
struct sym_entry *symp;
int bidirectional = 0;
int num_surf_products = 0;
struct rxn *rxnp;
/* Create pathway */
struct pathway *pathp = (struct pathway *)CHECKED_MALLOC_STRUCT(
struct pathway, "reaction pathway");
if (pathp == NULL) {
return MCELL_FAIL;
}
memset(pathp, 0, sizeof(struct pathway));
/* Scan reactants, copying into the new pathway */
int num_vol_mols = 0;
int num_surface_mols = 0;
int all_3d = 1;
int reactant_idx = 0;
int oriented_count = 0;
int surface = -1;
int catalytic = -1;
unsigned int num_surfaces = 0;
if (react_arrow->flags & ARROW_BIDIRECTIONAL) {
bidirectional = 1;
}
if (extract_reactants(pathp, reactants, &reactant_idx, &num_vol_mols,
&num_surface_mols, &all_3d,
&oriented_count) == MCELL_FAIL) {
free(pathp);
return MCELL_FAIL;
}
/* Grab info from the arrow */
if (react_arrow->flags & ARROW_CATALYTIC) {
if (extract_catalytic_arrow(pathp, react_arrow, &reactant_idx,
&num_vol_mols, &num_surface_mols, &all_3d,
&oriented_count) == MCELL_FAIL) {
free(pathp);
return MCELL_FAIL;
}
catalytic = reactant_idx - 1;
}
/* If a surface was specified, include it */
if (surf_class->mol_type != NULL) {
if (extract_surface(pathp, surf_class, &reactant_idx, &num_surfaces,
&oriented_count) == MCELL_FAIL) {
free(pathp);
return MCELL_FAIL;
}
surface = reactant_idx - 1;
all_3d = 0;
}
/* Create a reaction name for the pathway we're creating */
rx_name = create_rx_name(pathp);
if (rx_name == NULL) {
free(pathp);
mcell_error("Out of memory while creating reaction.");
return MCELL_FAIL;
}
/* If this reaction doesn't exist, create it */
if ((symp = retrieve_sym(rx_name, rxn_sym_table)) != NULL) {
/* do nothing */
} else if ((symp = store_sym(rx_name, RX, rxn_sym_table, NULL)) ==
NULL) {
free(pathp);
free(rx_name);
mcell_error("Out of memory while creating reaction.");
/*return MCELL_FAIL;*/
}
free(rx_name);
rxnp = (struct rxn *)symp->value;
rxnp->n_reactants = reactant_idx;
++rxnp->n_pathways;
/* Check for invalid reaction specifications */
if (check_surface_specs(notify, rxnp->n_reactants, num_surfaces,
num_vol_mols, all_3d, oriented_count) == MCELL_FAIL) {
free(pathp);
return MCELL_FAIL;
}
/* Add catalytic reagents to the product list.
* - For unidirectional catalytic reactions - copy catalyst to products
* only if catalyst is not a surface_clas.
* - For bidirectional catalytic reactions always copy catalyst to
* products and take care that surface_class will not appear in the
* products later after inverting the reaction
*/
if (catalytic >= 0) {
if (add_catalytic_species_to_products(pathp, catalytic, bidirectional,
all_3d) == MCELL_FAIL) {
free(pathp);
return MCELL_FAIL;
}
}
/* Add in all products */
if (extract_products(notify, pathp, products, &num_surf_products,
bidirectional, all_3d) == MCELL_FAIL) {
free(pathp);
return MCELL_FAIL;
}
// mem_put_list(parse_state->mol_data_list_mem, products);
/* Attach reaction pathway name, if we have one */
if (pathname != NULL) {
struct rxn_pathname *rxpnp = (struct rxn_pathname *)pathname->value;
rxpnp->rx = rxnp;
pathp->pathname = rxpnp;
}
if (pathp->product_head != NULL) {
pathp->prod_signature = create_prod_signature(&pathp->product_head);
if (pathp->prod_signature == NULL) {
free(pathp);
mcell_error(
"Error creating 'prod_signature' field for the reaction pathway.");
return MCELL_FAIL;
}
} else
pathp->prod_signature = NULL;
/* Copy in forward rate */
switch (rates->forward_rate.rate_type) {
case RATE_UNSET:
mcell_error_raw("File %s, Line %d: Internal error: Rate is not set",
__FILE__, __LINE__);
free(pathp);
return MCELL_FAIL;
case RATE_CONSTANT:
pathp->km = rates->forward_rate.v.rate_constant;
pathp->km_filename = NULL;
break;
case RATE_FILE:
pathp->km = 0.0;
pathp->km_filename = (char *)forward_rate_filename;
free(rates->forward_rate.v.rate_file);
rates->forward_rate.v.rate_file = NULL;
break;
default:
UNHANDLED_CASE(rates->forward_rate.rate_type);
}
/* Add the pathway to the list for this reaction */
if (rates->forward_rate.rate_type == RATE_FILE) {
struct pathway *tpp;
if (rxnp->pathway_head == NULL) {
rxnp->pathway_head = pathp;
pathp->next = NULL;
} else /* Move varying reactions to the end of the list */
{
for (tpp = rxnp->pathway_head;
tpp->next != NULL && tpp->next->km_filename == NULL;
tpp = tpp->next) {
}
pathp->next = tpp->next;
tpp->next = pathp;
}
} else {
pathp->next = rxnp->pathway_head;
rxnp->pathway_head = pathp;
}
/* If we're doing 3D releases, set up array so we can release reversibly */
if (*r_step_release == NULL && all_3d && pathp->product_head != NULL) {
*r_step_release = init_r_step_3d_release(radial_subdivisions);
if (*r_step_release == NULL) {
free(pathp);
mcell_error("Out of memory building r_step array.");
return MCELL_FAIL;
}
}
/* If the vacancy search distance is zero and this reaction produces more
* surface molecules than it comsumes, it can never succeed, except if it is
* a volume molecule hitting the surface and producing a single surface
* molecule. Fail with an error message.
*/
if ((!distinguishable(vacancy_search_dist2, 0, EPS_C)) &&
(num_surf_products > num_surface_mols)) {
/* The case with one volume molecule reacting with the surface and
* producing one surface molecule is okay.
*/
if (num_surface_mols == 0 && num_vol_mols == 1 && num_surf_products == 1) {
/* do nothing */
} else {
free(pathp);
mcell_error("number of surface products exceeds number of surface "
"reactants, but VACANCY_SEARCH_DISTANCE is not specified or "
"set to zero.");
return MCELL_FAIL;
}
}
/* A non-reversible reaction may not specify a reverse reaction rate */
if (rates->backward_rate.rate_type != RATE_UNSET && !bidirectional) {
free(pathp);
mcell_error("reverse rate specified but the reaction isn't reversible.");
return MCELL_FAIL;
}
/* Create reverse reaction if we need to */
if (bidirectional) {
/* A bidirectional reaction must specify a reverse rate */
if (rates->backward_rate.rate_type == RATE_UNSET) {
free(pathp);
mcell_error("reversible reaction indicated but no reverse rate "
"supplied.");
return MCELL_FAIL;
}
/* if "surface_class" is present on the reactant side of the reaction copy
* it to the product side of the reaction.
*
* Reversible reaction of the type:
* A' @ surf' <---> C''[>r1,<r2]
*
* is equivalent now to the two reactions:
* A' @ surf' ---> C'' [r1]
* C'' @ surf' ----> A' [r2]
*
* Reversible reaction of the type:
* A' + B' @ surf' <---> C'' + D'' [>r1,<r2]
*
* is equivalent now to the two reactions:
* A' + B @ surf' ---> C'' + D'' [r1]
* C'' + D'' @ surf' ----> A' + B' [r2]
*/
if (surface != -1 && surface != catalytic) {
struct product *prodp;
prodp = (struct product *)CHECKED_MALLOC_STRUCT(struct product,
"reaction product");
if (prodp == NULL) {
// mem_put(parse_state->prod_mem, prodp);
free(pathp);
return MCELL_FAIL;
}
switch (surface) {
case 1:
prodp->prod = pathp->reactant2;
prodp->orientation = pathp->orientation2;
break;
case 2:
prodp->prod = pathp->reactant3;
prodp->orientation = pathp->orientation3;
break;
case 0:
default:
mcell_internal_error(
"Surface appears in invalid reactant slot in reaction (%d).",
surface);
/*break;*/
}
prodp->next = pathp->product_head;
pathp->product_head = prodp;
}
/* Invert the current reaction pathway */
if (invert_current_reaction_pathway(
rxn_sym_table, vacancy_search_dist2, pathp,
&rates->backward_rate, backward_rate_filename)) {
free(pathp);
return MCELL_FAIL;
}
}
//set diffusion function
rxnp->get_reactant_diffusion = rxn_get_standard_diffusion;
return MCELL_SUCCESS;
}
/*************************************************************************
*
* mcell_add_surface_reaction adds a single surface reaction described
* by reaction_def to the simulations.
*
*************************************************************************/
MCELL_STATUS
mcell_add_surface_reaction(struct sym_table_head *rxn_sym_table,
int reaction_type, struct species *surface_class,
struct sym_entry *reactant_sym, short orient) {
struct species *reactant = (struct species *)reactant_sym->value;
/* Make sure the other reactant isn't a surface */
if (reactant->flags == IS_SURFACE) {
// mdlerror_fmt(parse_state,
// "Illegal reaction between two surfaces in surface reaction:
// %s -%s-> ...",
// reactant_sym->name,
// surface_class->sym->name);
return MCELL_FAIL;
}
/* Build reaction name */
char *rx_name =
concat_rx_name(surface_class->sym->name, reactant_sym->name);
if (rx_name == NULL) {
// mdlerror_fmt(parse_state,
// "Out of memory while parsing surface reaction: %s -%s-> ...",
// surface_class->sym->name,
// reactant_sym->name);
return MCELL_FAIL;
}
/* Find or create reaction */
struct sym_entry *reaction_sym;
if ((reaction_sym = retrieve_sym(rx_name, rxn_sym_table)) != NULL) {
/* do nothing */
} else if ((reaction_sym =
store_sym(rx_name, RX, rxn_sym_table, NULL)) == NULL) {
free(rx_name);
// mdlerror_fmt(parse_state,
// "Out of memory while creating surface reaction: %s -%s->
// ...",
// reactant_sym->name,
// surface_class->sym->name);
return MCELL_FAIL;
}
free(rx_name);
/* Create pathway */
struct pathway *pathp = (struct pathway *)CHECKED_MALLOC_STRUCT(
struct pathway, "reaction pathway");
if (pathp == NULL)
return MCELL_FAIL;
memset(pathp, 0, sizeof(struct pathway));
struct rxn *rxnp = (struct rxn *)reaction_sym->value;
rxnp->n_reactants = 2;
++rxnp->n_pathways;
pathp->pathname = NULL;
pathp->reactant1 = surface_class;
pathp->reactant2 = (struct species *)reactant_sym->value;
pathp->reactant3 = NULL;
pathp->km = GIGANTIC;
pathp->km_filename = NULL;
pathp->prod_signature = NULL;
pathp->flags = 0;
pathp->orientation1 = 1;
pathp->orientation3 = 0;
if (orient == 0) {
pathp->orientation2 = 0;
} else {
pathp->orientation2 = (orient < 0) ? -1 : 1;
}
struct name_orient *no;
no = CHECKED_MALLOC_STRUCT(struct name_orient, "struct name_orient");
no->name = CHECKED_STRDUP(reactant->sym->name, "reactant name");
if (orient == 0) {
no->orient = 0;
} else {
no->orient = (orient < 0) ? -1 : 1;
}
struct product *prodp;
switch (reaction_type) {
case RFLCT:
prodp = (struct product *)CHECKED_MALLOC_STRUCT(struct product,
"reaction product");
if (prodp == NULL) {
free(no);
free(pathp);
return MCELL_FAIL;
}
pathp->flags |= PATHW_REFLEC;
prodp->prod = pathp->reactant2;
prodp->orientation = 1;
prodp->next = NULL;
pathp->product_head = prodp;
if (pathp->product_head != NULL) {
pathp->prod_signature = create_prod_signature(&pathp->product_head);
if (pathp->prod_signature == NULL) {
// mdlerror(parse_state, "Error creating 'prod_signature' field for the
// reaction pathway.");
free(no);
free(pathp);
return MCELL_FAIL;
}
}
if (surface_class->refl_mols == NULL) {
no->next = NULL;
surface_class->refl_mols = no;
} else {
no->next = surface_class->refl_mols;
surface_class->refl_mols = no;
}
break;
case TRANSP:
prodp = (struct product *)CHECKED_MALLOC_STRUCT(struct product,
"reaction product");
if (prodp == NULL) {
free(no);
free(pathp);
return MCELL_FAIL;
}
pathp->flags |= PATHW_TRANSP;
prodp->prod = pathp->reactant2;
prodp->orientation = -1;
prodp->next = NULL;
pathp->product_head = prodp;
if (pathp->product_head != NULL) {
pathp->prod_signature = create_prod_signature(&pathp->product_head);
if (pathp->prod_signature == NULL) {
free(no);
free(pathp);
return MCELL_FAIL;
}
}
if (surface_class->transp_mols == NULL) {
no->next = NULL;
surface_class->transp_mols = no;
} else {
no->next = surface_class->transp_mols;
surface_class->transp_mols = no;
}
break;
case SINK:
pathp->flags |= PATHW_ABSORP;
pathp->product_head = NULL;
if (surface_class->absorb_mols == NULL) {
no->next = NULL;
surface_class->absorb_mols = no;
} else {
no->next = surface_class->absorb_mols;
surface_class->absorb_mols = no;
}
break;
default:
// mdlerror(parse_state, "Unknown special surface type.");
free(no);
free(pathp);
return MCELL_FAIL;
}
pathp->next = rxnp->pathway_head;
rxnp->pathway_head = pathp;
rxnp->get_reactant_diffusion = rxn_get_standard_diffusion;
return MCELL_SUCCESS;
}
/*************************************************************************
*
* mcell_add_clamp adds a surface clamp to the simulation
*
*************************************************************************/
MCELL_STATUS
mcell_add_clamp(struct sym_table_head *rxn_sym_table,
struct species *surface_class,
struct sym_entry *mol_sym, short orient,
int clamp_type,
double clamp_value) {
struct rxn *rxnp;
struct pathway *pathp;
struct sym_entry *stp3;
struct species *specp = (struct species *)mol_sym->value;
struct name_orient *no;
if (specp->flags == IS_SURFACE) {
// mdlerror_fmt(parse_state,
// "Illegal reaction between two surfaces in surface
// reaction: %s -%s-> ...",
// mol_sym->name, surface_class->sym->name);
return MCELL_FAIL;
}
if (specp->flags & ON_GRID) {
// mdlerror(parse_state, "Concentration clamp does not work on surface
// molecules.");
return MCELL_FAIL;
}
if (specp->flags & NOT_FREE || specp->D <= 0.0) {
// mdlerror(parse_state, "Concentration clamp must be applied to molecule
// diffusing in 3D");
return MCELL_FAIL;
}
if (clamp_value < 0) {
// mdlerror(parse_state, "Concentration can only be clamped to positive
// values.");
return MCELL_FAIL;
}
char *rx_name = concat_rx_name(surface_class->sym->name, mol_sym->name);
if (rx_name == NULL) {
// mdlerror_fmt(parse_state,
// "Memory allocation error: %s -%s-> ...",
// surface_class->sym->name, mol_sym->name);
return MCELL_FAIL;
}
if ((stp3 = retrieve_sym(rx_name, rxn_sym_table)) != NULL) {
/* do nothing */
} else if ((stp3 = store_sym(rx_name, RX, rxn_sym_table, NULL)) ==
NULL) {
free(rx_name);
// mdlerror_fmt(parse_state,
// "Cannot store surface reaction: %s -%s-> ...",
// mol_sym->name, surface_class->sym->name);
return MCELL_FAIL;
}
free(rx_name);
pathp = (struct pathway *)CHECKED_MALLOC_STRUCT(struct pathway,
"reaction pathway");
if (pathp == NULL)
return MCELL_FAIL;
memset(pathp, 0, sizeof(struct pathway));
rxnp = (struct rxn *)stp3->value;
rxnp->n_reactants = 2;
++rxnp->n_pathways;
pathp->pathname = NULL;
pathp->reactant1 = surface_class;
pathp->reactant2 = (struct species *)mol_sym->value;
pathp->reactant3 = NULL;
pathp->flags = 0;
pathp->km = clamp_value;
pathp->km_filename = NULL;
pathp->orientation1 = 1;
pathp->orientation3 = 0;
if (orient == 0) {
pathp->orientation2 = 0;
} else {
pathp->orientation2 = (orient < 0) ? -1 : 1;
}
if (clamp_type == CLAMP_TYPE_CONC) {
pathp->flags |= PATHW_CLAMP_CONC;
pathp->product_head = NULL;
pathp->prod_signature = NULL;
}
else {
pathp->flags |= PATHW_CLAMP_FLUX | PATHW_REFLEC;
pathp->product_head = NULL;
pathp->prod_signature = NULL;
/*
Original implementation from branch neumann_boundaries
created rxn a+ sc -> a, however in this case the molecules could pass through
the clamped membrane which does not seem correct*/
#if 0
struct product *prodp;
prodp = (struct product *)CHECKED_MALLOC_STRUCT(struct product,
"reaction product");
if (prodp == NULL) {
free(pathp);
return MCELL_FAIL;
}
prodp->prod = pathp->reactant2;
prodp->orientation = pathp->orientation2;
prodp->next = NULL;
pathp->product_head = prodp;
if (pathp->product_head != NULL) {
pathp->prod_signature = create_prod_signature(&pathp->product_head);
if (pathp->prod_signature == NULL) {
// mdlerror(parse_state, "Error creating 'prod_signature' field for the
// reaction pathway.");
free(pathp);
return MCELL_FAIL;
}
}
#endif
}
no = CHECKED_MALLOC_STRUCT(struct name_orient, "struct name_orient");
no->name = CHECKED_STRDUP(mol_sym->name, "molecule name");
no->orient = pathp->orientation2;
if (surface_class->clamp_mols == NULL) {
no->next = NULL;
surface_class->clamp_mols = no;
} else {
no->next = surface_class->clamp_mols;
surface_class->clamp_mols = no;
}
rxnp->get_reactant_diffusion = rxn_get_standard_diffusion;
pathp->next = rxnp->pathway_head;
rxnp->pathway_head = pathp;
return MCELL_SUCCESS;
}
/************************************************************************
*
* function for changing the reaction rate constant of a given named
* reaction.
*
* The call expects:
*
* - MCELL_STATE
* - reaction name: const char* containing the name of reaction
* - new rate: a double with the new reaction rate constant
*
* NOTE: This function can be called anytime after the
* REACTION_DATA_OUTPUT has been either parsed or
* set up with API calls.
*
* Returns 1 on error and 0 on success
*
************************************************************************/
MCELL_STATUS
mcell_change_reaction_rate(MCELL_STATE *state, const char *reaction_name,
double new_rate) {
// sanity check
if (new_rate < 0.0) {
return MCELL_FAIL;
}
// retrive reaction corresponding to name if it exists
struct rxn *rx = NULL;
int path_id = 0;
if (get_rxn_by_name(state->reaction_hash, state->rx_hashsize, reaction_name,
&rx, &path_id)) {
return MCELL_FAIL;
}
// now change the rate
if (change_reaction_probability(
&state->reaction_prob_limit_flag, state->notify, rx, path_id,
new_rate)) {
return MCELL_FAIL;
}
return MCELL_SUCCESS;
}
/*******************************************************************************
*
* static helper functions: initializes the rx->info field
*
******************************************************************************/
int init_reaction_info(struct rxn* rx){
struct pathway *path;
if (rx->n_pathways > 0) {
rx->info = CHECKED_MALLOC_ARRAY(struct pathway_info, rx->n_pathways,
"reaction pathway info");
if (rx->info == NULL)
return 1;
path = rx->pathway_head;
for (int n_pathway = 0; path != NULL;
n_pathway++, path = path->next) {
rx->info[n_pathway].count = 0;
rx->info[n_pathway].pathname =
path->pathname; /* Keep track of named rxns */
if (path->pathname != NULL) {
rx->info[n_pathway].pathname->path_num = n_pathway;
rx->info[n_pathway].pathname->rx = rx;
}
}
} else /* Special reaction, only one exit pathway */
{
rx->info = CHECKED_MALLOC_STRUCT(struct pathway_info,
"reaction pathway info");
if (rx->info == NULL)
return 1;
rx->info[0].count = 0;
rx->info[0].pathname = rx->pathway_head->pathname;
if (rx->pathway_head->pathname != NULL) {
rx->info[0].pathname->path_num = 0;
rx->info[0].pathname->rx = rx;
}
}
return 0;
}
/*************************************************************************
init_reactions:
Postprocess the parsed reactions, moving them to the reaction hash table,
and transferring information from the pathway structures to a more compact,
runtime-optimized form.
In: state: simulation state
Out: Returns 1 on error, 0 on success.
Reaction hash table is built and geometries are set properly. Unlike in
the parser, reactions with different reactant geometries are _different
reactions_, and are stored as separate struct rxns.
Note: The user inputs _geometric equivalence classes_, but here we convert
from that to _output construction geometry_. A geometry of 0 means to
choose a random orientation. A geometry of k means to adopt the
geometry of the k'th species in the list (reactants start at #1,
products are in order after reactants). A geometry of -k means to adopt
the opposite of the geometry of the k'th species. The first n_reactants
products determine the fate of the reactants (NULL = destroyed), and the
rest are real products.
PostNote: The reactants are used for triggering, and those have equivalence
class geometry even in here.
*************************************************************************/
int init_reactions(MCELL_STATE *state) {
struct pathway *path;
struct product *prod = NULL;
short geom;
int num_rx = 0;
state->vacancy_search_dist2 *= state->r_length_unit; /* Convert units */
state->vacancy_search_dist2 *= state->vacancy_search_dist2; /* Take square */
if (state->rx_radius_3d <= 0.0) {
state->rx_radius_3d = 1.0 / sqrt(MY_PI * state->grid_density);
}
state->tv_rxn_mem = create_mem(sizeof(struct t_func), 100);
if (state->tv_rxn_mem == NULL)
return 1;
for (int n_rxn_bin = 0; n_rxn_bin < state->rxn_sym_table->n_bins;
n_rxn_bin++) {
for (struct sym_entry *sym = state->rxn_sym_table->entries[n_rxn_bin];
sym != NULL; sym = sym->next) {
struct rxn *reaction = (struct rxn *)sym->value;
reaction->next = NULL;
for (path = reaction->pathway_head; path != NULL; path = path->next) {
check_duplicate_special_reactions(path);
/* if one of the reactants is a surface, move it to the last reactant.
* Also arrange reactant1 and reactant2 in alphabetical order */
if (reaction->n_reactants > 1) {
struct species *temp_sp;
/* Put surface last */
if ((path->reactant1->flags & IS_SURFACE) != 0) {
temp_sp = path->reactant1;
path->reactant1 = path->reactant2;
path->reactant2 = temp_sp;
geom = path->orientation1;
path->orientation1 = path->orientation2;
path->orientation2 = geom;
}
if (reaction->n_reactants > 2) {
if ((path->reactant2->flags & IS_SURFACE) != 0) {
temp_sp = path->reactant3;
path->reactant3 = path->reactant2;
path->reactant2 = temp_sp;
geom = path->orientation3;
path->orientation3 = path->orientation2;
path->orientation2 = geom;
}
}
alphabetize_pathway(path, reaction);
} /* end if (n_reactants > 1) */
} /* end for (path = reaction->pathway_head; ...) */
/* if reaction contains equivalent pathways, split this reaction into a
* linked list of reactions each containing only equivalent pathways. */
struct rxn *rx = split_reaction(reaction);
/* set the symbol value to the head of the linked list of reactions */
sym->value = (void *)rx;
while (rx != NULL) {
double pb_factor = 0.0;
/* Check whether reaction contains pathways with equivalent product
* lists. Also sort pathways in alphabetical order according to the
* "prod_signature" field. */
check_reaction_for_duplicate_pathways(&rx->pathway_head);
num_rx++;
/* At this point we have reactions of the same geometry and can
* collapse them and count how many non-reactant products are in each
* pathway. */
/* Search for reactants that appear as products */
/* Any reactants that don't appear are set to be destroyed. */
rx->product_idx = CHECKED_MALLOC_ARRAY(u_int, rx->n_pathways + 1,
"reaction product index array");
rx->cum_probs = CHECKED_MALLOC_ARRAY(
double, rx->n_pathways, "reaction cumulative probabilities array");
/* Note, that the last member of the array "rx->product_idx" contains
* size of the array "rx->players" */
if (rx->product_idx == NULL || rx->cum_probs == NULL)
return 1;
int n_prob_t_rxns = 0; /* # of pathways with time-varying rates */
path = rx->pathway_head;
for (int n_pathway = 0; path != NULL; n_pathway++, path = path->next) {
rx->product_idx[n_pathway] = 0;
/* Look for clamp */
if ( path->reactant2 != NULL
&& (path->reactant2->flags & IS_SURFACE) != 0
&& path->km >= 0.0
&& ( ( path->product_head == NULL && (path->flags & PATHW_CLAMP_CONC) != 0 )
||
( path->product_head == NULL && (path->flags & PATHW_CLAMP_FLUX) != 0 ) )
) {
struct clamp_data *cdp;
if (n_pathway != 0 || path->next != NULL)
mcell_warn("Mixing surface modes with other surface reactions. "
"Please don't.");
if (path->km > 0) {
cdp = CHECKED_MALLOC_STRUCT(struct clamp_data,
"clamp data");
if (cdp == NULL)
return 1;
cdp->surf_class = path->reactant2;
cdp->mol = path->reactant1;
cdp->clamp_value = path->km;
if ((path->flags & PATHW_CLAMP_CONC) != 0) {
cdp->clamp_type = CLAMP_TYPE_CONC;
}
else {
cdp->clamp_type = CLAMP_TYPE_FLUX;
}
if (path->orientation1 * path->orientation2 == 0) {
cdp->orient = 0;
} else {
cdp->orient =
(path->orientation1 == path->orientation2) ? 1 : -1;
}
cdp->sides = NULL;
cdp->next_mol = NULL;
cdp->next_obj = NULL;
cdp->objp = NULL;
cdp->n_sides = 0;
cdp->side_idx = NULL;
cdp->cum_area = NULL;
cdp->scaling_factor = 0.0;
cdp->next = state->clamp_list;
state->clamp_list = cdp;
}
path->clamp_concentration = path->km; // remember for mcell3->4 converter
path->km = GIGANTIC;
if ((path->flags & PATHW_CLAMP_FLUX) != 0) {
rx->n_pathways = RX_REFLEC;
if (path->reactant2 != NULL &&
(path->reactant2->flags & IS_SURFACE) &&
(path->reactant1->flags & ON_GRID)) {
path->reactant1->flags |= CAN_REGION_BORDER;
}
}
} else if ((path->flags & PATHW_TRANSP) != 0) {
rx->n_pathways = RX_TRANSP;
if (path->reactant2 != NULL &&
(path->reactant2->flags & IS_SURFACE) &&
(path->reactant1->flags & ON_GRID)) {
path->reactant1->flags |= CAN_REGION_BORDER;
}
} else if ((path->flags & PATHW_REFLEC) != 0) {
rx->n_pathways = RX_REFLEC;
if (path->reactant2 != NULL &&
(path->reactant2->flags & IS_SURFACE) &&
(path->reactant1->flags & ON_GRID)) {
path->reactant1->flags |= CAN_REGION_BORDER;
}
} else if (path->reactant2 != NULL &&
(path->reactant2->flags & IS_SURFACE) &&
(path->reactant1->flags & ON_GRID) &&
(path->product_head == NULL) &&
(path->flags & PATHW_ABSORP)) {
rx->n_pathways = RX_ABSORB_REGION_BORDER;
path->reactant1->flags |= CAN_REGION_BORDER;
} else if ((strcmp(path->reactant1->sym->name,
"ALL_SURFACE_MOLECULES") == 0)) {
if (path->reactant2 != NULL &&
(path->reactant2->flags & IS_SURFACE) &&
(path->product_head == NULL) && (path->flags & PATHW_ABSORP)) {
rx->n_pathways = RX_ABSORB_REGION_BORDER;
path->reactant1->flags |= CAN_REGION_BORDER;
}
}
if (path->km_filename == NULL)
rx->cum_probs[n_pathway] = path->km;
else {
rx->cum_probs[n_pathway] = 0;
n_prob_t_rxns++;
}
/* flags that tell whether reactant_1 is also on the product list,
same for reactant_2 and reactant_3 */
int recycled1 = 0;
int recycled2 = 0;
int recycled3 = 0;
for (prod = path->product_head; prod != NULL; prod = prod->next) {
if (recycled1 == 0 && prod->prod == path->reactant1)
recycled1 = 1;
else if (recycled2 == 0 && prod->prod == path->reactant2)
recycled2 = 1;
else if (recycled3 == 0 && prod->prod == path->reactant3)
recycled3 = 1;
else
rx->product_idx[n_pathway]++;
}
} /* end for (n_pathway=0,path=rx->pathway_head; ...) */
/* Now that we know how many products there really are, set the index
* array and malloc space for the products and geometries. */
int num_players = rx->n_reactants;
int kk = rx->n_pathways;
if (kk <= RX_SPECIAL)
kk = 1;
for (int n_pathway = 0; n_pathway < kk; n_pathway++) {
int k = rx->product_idx[n_pathway] + rx->n_reactants;
rx->product_idx[n_pathway] = num_players;
num_players += k;
}
rx->product_idx[kk] = num_players;
rx->players = CHECKED_MALLOC_ARRAY(struct species *, num_players,
"reaction players array");
rx->geometries = CHECKED_MALLOC_ARRAY(short, num_players,
"reaction geometries array");
if (rx->players == NULL || rx->geometries == NULL)
return 1;
/* Load all the time-varying rates from disk (if any), merge them into
* a single sorted list, and pull off any updates for time zero. */
if (n_prob_t_rxns > 0) {
path = rx->pathway_head;
for (int n_pathway = 0; path != NULL;
n_pathway++, path = path->next) {
if (path->km_filename != NULL) {
if (load_rate_file(state, rx, path->km_filename, n_pathway))
mcell_error("Failed to load rates from file '%s'.",
path->km_filename);
}
free(path->km_filename);
path->km_filename = NULL;
}
rx->prob_t = (struct t_func *)ae_list_sort(
(struct abstract_element *)rx->prob_t);
while (rx->prob_t != NULL && rx->prob_t->time <= 0.0) {
rx->cum_probs[rx->prob_t->path] = rx->prob_t->value;
rx->prob_t = rx->prob_t->next;
}
} /* end if (n_prob_t_rxns > 0) */
/* Set the geometry of the reactants. These are used for triggering. */
/* Since we use flags to control orientation changes, just tell everyone
* to stay put. */
path = rx->pathway_head;
rx->players[0] = path->reactant1;
rx->geometries[0] = path->orientation1;
if (rx->n_reactants > 1) {
rx->players[1] = path->reactant2;
rx->geometries[1] = path->orientation2;
if (rx->n_reactants > 2) {
rx->players[2] = path->reactant3;
rx->geometries[2] = path->orientation3;
}
}
//JJT: once reactants have been initialized we can assign diffusion/space/timestep functions
initialize_rxn_diffusion_functions(rx);
//JJT: initialize nfsim reaction fields to null since they will not be used for this normal reaction
rx->external_reaction_data = NULL;
rx->product_graph_data = NULL;
rx->reactant_graph_data = NULL;
/* maximum number of surface products */
path = rx->pathway_head;
int max_num_surf_products = set_product_geometries(path, rx, prod);
pb_factor = compute_pb_factor(
state->time_unit, state->length_unit, state->grid_density,
state->rx_radius_3d,
&state->rxn_flags,
&state->create_shared_walls_info_flag,
rx, max_num_surf_products);
rx->pb_factor = pb_factor;
path = rx->pathway_head;
if (scale_rxn_probabilities(&state->reaction_prob_limit_flag, state->notify,
path, rx, pb_factor))
return 1;
if (n_prob_t_rxns > 0) {
for (struct t_func *tp = rx->prob_t; tp != NULL; tp = tp->next)
tp->value *= pb_factor;
}
/* Move counts from list into array */
if(init_reaction_info(rx) != 0)
return MCELL_FAIL;
/* Compute cumulative properties */
for (int n_pathway = 1; n_pathway < rx->n_pathways; ++n_pathway)
rx->cum_probs[n_pathway] += rx->cum_probs[n_pathway - 1];
if (rx->n_pathways > 0)
rx->min_noreaction_p = rx->max_fixed_p =
rx->cum_probs[rx->n_pathways - 1];
else
rx->min_noreaction_p = rx->max_fixed_p = 1.0;
rx = rx->next;
}
}
}
if (state->rxn_flags.surf_surf_reaction_flag ||
state->rxn_flags.surf_surf_surf_reaction_flag) {
if (state->notify->reaction_probabilities == NOTIFY_FULL)
mcell_log("For reaction between two (or three) surface molecules the "
"upper probability limit is given. The effective reaction "
"probability will be recalculated dynamically during "
"simulation.");
}
if (build_reaction_hash_table(&state->reaction_hash, &state->n_reactions,
state->rxn_sym_table, &state->rx_hashsize,
num_rx))
return 1;
state->rx_radius_3d *= state->r_length_unit; /* Convert into length units */
for (int n_rxn_bin = 0; n_rxn_bin < state->rx_hashsize; n_rxn_bin++) {
for (struct rxn *this_rx = state->reaction_hash[n_rxn_bin]; this_rx != NULL;
this_rx = this_rx->next) {
set_reaction_player_flags(this_rx);
}
}
#if 0
// TODO: move this to a separate function and call after mcell4 conversion
// pathway_head is used there - this is sued in mcell4's init
for (int n_rxn_bin = 0; n_rxn_bin < state->rx_hashsize; n_rxn_bin++) {
for (struct rxn *this_rx = state->reaction_hash[n_rxn_bin]; this_rx != NULL;
this_rx = this_rx->next) {
/* Here we deallocate all memory used for creating pathways. */
path = this_rx->pathway_head;
struct pathway *next_path = path;
while (next_path != NULL) {
next_path = path->next;
if (path->prod_signature != NULL) {
free(path->prod_signature);
}
struct product *dead_prod = path->product_head;
struct product *nxt = dead_prod;
while (nxt != NULL) {
nxt = dead_prod->next;
free(dead_prod);
dead_prod = nxt;
}
free(path);
path = next_path;
}
//set_reaction_player_flags(this_rx);
this_rx->pathway_head = NULL;
}
}
#endif
add_surface_reaction_flags(state->mol_sym_table, state->all_mols, state->all_surface_mols,
state->all_volume_mols);
if (state->notify->reaction_probabilities == NOTIFY_FULL)
mcell_log_raw("\n");
return 0;
}
/*******************************************************************************
*
* static helper functions
*
******************************************************************************/
/*************************************************************************
*
* extract_reactants extracts the reactant info into a pathway structure
*
*************************************************************************/
MCELL_STATUS
extract_reactants(struct pathway *pathp, struct mcell_species *reactants,
int *num_reactants, int *num_vol_mols, int *num_surface_mols,
int *all_3d, int *oriented_count) {
int reactant_idx = 0;
struct mcell_species *current_reactant;
for (current_reactant = reactants;
reactant_idx < 3 && current_reactant != NULL;
++reactant_idx, current_reactant = current_reactant->next) {
/* Extract orientation and species */
short orient = current_reactant->orient_set ? current_reactant->orient : 0;
struct species *reactant_species =
(struct species *)current_reactant->mol_type->value;
/* Count the type of this reactant */
if (current_reactant->orient_set) {
++(*oriented_count);
}
if (reactant_species->flags & NOT_FREE) {
*all_3d = 0;
if (reactant_species->flags & ON_GRID) {
++(*num_surface_mols);
}
} else {
++(*num_vol_mols);
}
/* Copy in reactant info */
switch (reactant_idx) {
case 0:
pathp->reactant1 = reactant_species;
pathp->orientation1 = orient;
break;
case 1:
pathp->reactant2 = reactant_species;
pathp->orientation2 = orient;
break;
case 2:
pathp->reactant3 = reactant_species;
pathp->orientation3 = orient;
break;
default:
UNHANDLED_CASE(reactant_idx);
}
}
*num_reactants = reactant_idx;
/* we had more than 3 reactants */
if (current_reactant != NULL) {
return MCELL_FAIL;
} else {
return MCELL_SUCCESS;
}
}
/*************************************************************************
*
* extract_catalytic_arrow extracts the info for a catalytic arrow
* into a pathway structure
*
*************************************************************************/
MCELL_STATUS
extract_catalytic_arrow(struct pathway *pathp,
struct reaction_arrow *react_arrow, int *reactant_idx,
int *num_vol_mols, int *num_surface_mols, int *all_3d,
int *oriented_count) {
struct species *catalyst_species =
(struct species *)react_arrow->catalyst.mol_type->value;
short orient =
react_arrow->catalyst.orient_set ? react_arrow->catalyst.orient : 0;
/* XXX: Should surface class be allowed inside a catalytic arrow? */
if (catalyst_species->flags & IS_SURFACE) {
mcell_error("a surface class may not appear inside a catalytic arrow");
return MCELL_FAIL;
}
/* Count the type of this reactant */
if (react_arrow->catalyst.orient_set) {
++(*oriented_count);
}
if (catalyst_species->flags & NOT_FREE) {
*all_3d = 0;
if (catalyst_species->flags & ON_GRID) {
++(*num_surface_mols);
}
} else {
++(*num_vol_mols);
}
/* Copy in catalytic reactant */
switch (*reactant_idx) {
case 1:
pathp->reactant2 = (struct species *)react_arrow->catalyst.mol_type->value;
pathp->orientation2 = orient;
break;
case 2:
pathp->reactant3 = (struct species *)react_arrow->catalyst.mol_type->value;
pathp->orientation3 = orient;
break;
case 0:
default:
// mcell_internal_error("Catalytic reagent ended up in an invalid slot
// (%d).", reactant_idx);
return MCELL_FAIL;
}
++(*reactant_idx);
return MCELL_SUCCESS;
}
/*************************************************************************
*
* extract_surface extracts the info for a surface included in the
* reaction specification
*
*************************************************************************/
MCELL_STATUS
extract_surface(struct pathway *path, struct mcell_species *surf_class,
int *num_reactants, unsigned int *num_surfaces,
int *oriented_count) {
short orient = surf_class->orient_set ? surf_class->orient : 0;
if (surf_class->orient_set) {
(*oriented_count)++;
}
/* Copy reactant into next available slot */
switch (*num_reactants) {
case 0:
// mdlerror(parse_state, "Before defining reaction surface class at least
// one reactant should be defined.");
return MCELL_FAIL;
case 1:
path->reactant2 = (struct species *)surf_class->mol_type->value;
path->orientation2 = orient;
break;
case 2:
path->reactant3 = (struct species *)surf_class->mol_type->value;
path->orientation3 = orient;
break;
default:
// mdlerror(parse_state, "Too many reactants--maximum number is two plus
// reaction surface class.");
return MCELL_FAIL;
}
(*num_reactants)++;
(*num_surfaces)++;
return MCELL_SUCCESS;
}
/*************************************************************************
*
* check_surface_specs performs a number of sanity checks to make sure
* the surface specifications are sane
*
*************************************************************************/
MCELL_STATUS
check_surface_specs(struct notifications *notify, int num_reactants,
int num_surfaces, int num_vol_mols, int all_3d,
int oriented_count) {
if (num_surfaces > 1) {
/* Shouldn't happen */
mcell_internal_error(
"Too many surfaces--reactions can take place on at most one surface.");
return MCELL_FAIL;
}
if (num_surfaces == num_reactants) {
mcell_error("Reactants cannot consist entirely of surfaces. Use a surface "
"release site instead!");
return MCELL_FAIL;
}
if ((num_vol_mols == 2) && (num_surfaces == 1)) {
mcell_error(
"Reaction between two volume molecules and a surface is not defined.");
return MCELL_FAIL;
}
if (all_3d) {
if (oriented_count != 0) {
if (notify->useless_vol_orient == WARN_ERROR) {
mcell_error("Orientation specified for molecule in reaction in volume");
return MCELL_FAIL;
} else if (notify->useless_vol_orient == WARN_WARN) {
mcell_warn("Orientation specified for molecule in reaction in volume");
}
}
} else {
if (num_reactants != oriented_count) {
if (notify->missed_surf_orient == WARN_ERROR) {
mcell_error("Orientation not specified for molecule in reaction "
"at surface\n (use ; or ', or ,' for random orientation)");
return MCELL_FAIL;
} else if (notify->missed_surf_orient == WARN_WARN) {
mcell_warn("Orientation not specified for molecule in reaction at "
"surface\n (use ; or ', or ,' for random orientation)");
}
}
}
return MCELL_SUCCESS;
}
/*************************************************************************
*
* add_catalytic_species_to_products adds all species that are part of a
* catalytic reaction to the list of products.
*
*************************************************************************/
MCELL_STATUS
add_catalytic_species_to_products(struct pathway *path, int catalytic,
int bidirectional, int all_3d) {
struct species *catalyst;
short catalyst_orient;
switch (catalytic) {
case 0:
catalyst = path->reactant1;
catalyst_orient = path->orientation1;
break;
case 1:
catalyst = path->reactant2;
catalyst_orient = path->orientation2;
break;
case 2:
catalyst = path->reactant3;
catalyst_orient = path->orientation3;
break;
default:
mcell_internal_error("Catalytic reagent index is invalid.");
return MCELL_FAIL;
}
if (bidirectional || !(catalyst->flags & IS_SURFACE)) {
struct product *prodp = (struct product *)CHECKED_MALLOC_STRUCT(
struct product, "reaction product");
if (prodp == NULL) {
return MCELL_FAIL;
}
prodp->prod = catalyst;
if (all_3d) {
prodp->orientation = 0;
} else {
prodp->orientation = catalyst_orient;
}
prodp->next = path->product_head;
path->product_head = prodp;
}
return MCELL_SUCCESS;
}
/*************************************************************************
*
* extract_products extracts the product info into a pathway structure
*
*************************************************************************/
MCELL_STATUS
extract_products(struct notifications *notify, struct pathway *pathp,
struct mcell_species *products, int *num_surf_products,
int bidirectional,
int all_3d) {
struct mcell_species *current_product;
for (current_product = products; current_product != NULL;
current_product = current_product->next) {
/* Nothing to do for NO_SPECIES */
if (current_product->mol_type == NULL)
continue;
/* Create new product */
struct product *prodp = (struct product *)CHECKED_MALLOC_STRUCT(
struct product, "reaction product");
if (prodp == NULL) {
// mcell_error_raw("Out of memory while creating reaction: %s -> ... ",
// rxnp->sym->name);
return MCELL_FAIL;
}
/* Set product species and orientation */
prodp->prod = (struct species *)current_product->mol_type->value;
if (all_3d) {
prodp->orientation = 0;
} else {
prodp->orientation = current_product->orient;
}
/* Disallow surface as product unless reaction is bidirectional */
if (!bidirectional) {
if (prodp->prod->flags & IS_SURFACE) {
mcell_error_raw("Surface_class '%s' is not allowed to be on the "
"product side of the reaction.",
prodp->prod->sym->name);
free(prodp);
return MCELL_FAIL;
}
}
/* Append product to list */
prodp->next = pathp->product_head;
pathp->product_head = prodp;
if (prodp->prod->flags & ON_GRID) {
++(*num_surf_products);
}
/* Add product if it isn't a surface */
if (!(prodp->prod->flags & IS_SURFACE)) {
if (all_3d == 0) {
if (!current_product->orient_set) {
if (notify->missed_surf_orient == WARN_ERROR) {
mcell_error("Product orientation not specified for molecule in "
"reaction at surface\n (use ; or ', or ,' for random "
"orientation)");
return MCELL_FAIL;
} else if (notify->missed_surf_orient == WARN_WARN) {
mcell_warn("Product orientation not specified for molecule in "
"reaction at surface\n (use ; or ', or ,' for random "
"orientation)");
}
}
} else {
if ((prodp->prod->flags & NOT_FREE) != 0) {
mcell_error("Reaction has only volume reactants but is trying to "
"create a surface product");
return MCELL_FAIL;
}
if (current_product->orient_set) {
if (notify->useless_vol_orient == WARN_ERROR) {
mcell_error("Orientation specified for molecule in reaction in "
"volume");
return MCELL_FAIL;
} else if (notify->useless_vol_orient == WARN_WARN) {
mcell_warn("Orientation specified for molecule in reaction in "
"volume");
}
}
}
}
}
return MCELL_SUCCESS;
}
/*************************************************************************
create_rx_name:
Assemble reactants alphabetically into a reaction name string.
In: p: reaction pathway whose reaction name we are to create
Out: a string to be used as a symbol name for the reaction
*************************************************************************/
char *create_rx_name(struct pathway *p) {
struct species *reagents[3];
int n_reagents = 0;
/* Store reagents in an array. */
reagents[0] = p->reactant1;
reagents[1] = p->reactant2;
reagents[2] = p->reactant3;
/* Count non-null reagents. */
for (n_reagents = 0; n_reagents < 3; ++n_reagents)
if (reagents[n_reagents] == NULL)
break;
/* Sort reagents. */
for (int i = 0; i < n_reagents; ++i) {
for (int j = i + 1; j < n_reagents; ++j) {
/* If 'j' precedes 'i', 'j' wins. */
if (strcmp(reagents[j]->sym->name, reagents[i]->sym->name) < 0) {
struct species *tmp = reagents[j];
reagents[j] = reagents[i];
reagents[i] = tmp;
}
}
}
/* Now, produce a name! */
switch (n_reagents) {
case 1:
return alloc_sprintf("%s", reagents[0]->sym->name);
case 2:
return alloc_sprintf("%s+%s", reagents[0]->sym->name,
reagents[1]->sym->name);
case 3:
return alloc_sprintf("%s+%s+%s", reagents[0]->sym->name,
reagents[1]->sym->name, reagents[2]->sym->name);
default:
// mcell_internal_error("Invalid number of reagents in reaction pathway
// (%d).", n_reagents);
return NULL;
}
}
/*************************************************************************
concat_rx_name:
Concatenates reactants onto a reaction name.
In: name1: name of first reactant (or first part of reaction name)
name2: name of second reactant (or second part of reaction name)
Out: reaction name as a string, or NULL if an error occurred
*************************************************************************/
static char *concat_rx_name(char *name1, char *name2) {
char *rx_name;
/* Sort them */
if (strcmp(name2, name1) <= 0) {
char *nametmp = name1;
name1 = name2;
name2 = nametmp;
}
/* Build the name */
rx_name = CHECKED_SPRINTF("%s+%s", name1, name2);
/* Die if we failed to allocate memory */
if (rx_name == NULL)
return NULL;
return rx_name;
}
/***********************************************************************
invert_current_reaction_pathway:
Creates a new reversed pathway, where the reactants of new pathway are the
products of the current pathway, and the products of new pathway are the
reactants of the current pathway.
In: rxn_sym_table:
vacancy_search_dist2:
pathp: pathway to invert
reverse_rate: the reverse reaction rate
rate_filename:
Out: Returns 1 on error and 0 - on success. The new pathway is added to the
linked list of the pathways for the current reaction.
***********************************************************************/
MCELL_STATUS invert_current_reaction_pathway(
struct sym_table_head *rxn_sym_table,
double vacancy_search_dist2,
struct pathway *pathp,
struct reaction_rate *reverse_rate,
const char *rate_filename) {
struct product *prodp;
int num_surf_products = 0;
int num_surface_mols = 0;
int num_vol_mols = 0;
/* flag that tells whether there is a surface_class
among products in the direct reaction */
int is_surf_class = 0;
int all_3d = 1; // flag that tells whether all products are volume_molecules
int nprods; /* number of products */
for (nprods = 0, prodp = pathp->product_head; prodp != NULL;
prodp = prodp->next) {
nprods++;
if ((prodp->prod->flags & NOT_FREE) != 0)
all_3d = 0;
if ((prodp->prod->flags & IS_SURFACE) != 0) {
is_surf_class = 1;
}
}
if (nprods == 0) {
// mdlerror(parse_state, "Can't create a reverse reaction with no
// products");
return MCELL_FAIL;
}
if (nprods == 1 && (pathp->product_head->prod->flags & IS_SURFACE)) {
// mdlerror(parse_state, "Can't create a reverse reaction starting from only
// a surface");
return MCELL_FAIL;
}
if (nprods > 3) {
// mdlerror(parse_state, "Can't create a reverse reaction involving more
// than three products. Please note that surface_class from the reaction
// reactant side also counts as a product.");
return MCELL_FAIL;
}
if (pathp->pathname != NULL) {
// mdlerror(parse_state, "Can't name bidirectional reactions--write each
// reaction and name them separately");
return MCELL_FAIL;
}
if (all_3d) {
if ((pathp->reactant1->flags & NOT_FREE) != 0)
all_3d = 0;
if (pathp->reactant2 != NULL && (pathp->reactant2->flags & NOT_FREE) != 0)
all_3d = 0;
if (pathp->reactant3 != NULL && (pathp->reactant3->flags & NOT_FREE) != 0)
all_3d = 0;
if (!all_3d) {
// mdlerror(parse_state, "Cannot reverse orientable reaction with only
// volume products");
return MCELL_FAIL;
}
}
prodp = pathp->product_head;
char *inverse_name;
if (nprods == 1) {
inverse_name = strdup(prodp->prod->sym->name);
if (inverse_name == NULL)
return MCELL_FAIL;
} else if (nprods == 2) {
inverse_name =
concat_rx_name(prodp->prod->sym->name, prodp->next->prod->sym->name);
} else {
char *tmp_inverse_name = concat_rx_name(
prodp->prod->sym->name, prodp->next->prod->sym->name);
if (tmp_inverse_name == NULL) {
return MCELL_FAIL;
}
inverse_name =
concat_rx_name(tmp_inverse_name, prodp->next->next->prod->sym->name);
free(tmp_inverse_name);
}
if (inverse_name == NULL) {
return MCELL_FAIL;
}
struct sym_entry *sym = retrieve_sym(inverse_name, rxn_sym_table);
if (sym == NULL) {
sym = store_sym(inverse_name, RX, rxn_sym_table, NULL);
if (sym == NULL) {
// mdlerror_fmt(parse_state, "File '%s', Line %ld: Out of memory while
// storing reaction pathway.", __FILE__, (long)__LINE__);
free(inverse_name);
return MCELL_FAIL;
}
}
free(inverse_name);
struct rxn *rx = (struct rxn *)sym->value;
rx->n_reactants = nprods;
rx->n_pathways++;
struct pathway *path = (struct pathway *)CHECKED_MALLOC_STRUCT(
struct pathway, "reaction pathway");
if (path == NULL) {
return MCELL_FAIL;
}
path->pathname = NULL;
path->flags = 0;
path->reactant1 = prodp->prod;
if ((path->reactant1->flags & NOT_FREE) == 0) {
++num_vol_mols;
} else {
if (path->reactant1->flags & ON_GRID) {
++num_surface_mols;
}
}
path->orientation1 = prodp->orientation;
path->reactant2 = NULL;
path->reactant3 = NULL;
path->prod_signature = NULL;
if (nprods > 1) {
path->reactant2 = prodp->next->prod;
if ((path->reactant2->flags & NOT_FREE) == 0) {
++num_vol_mols;
} else {
if (path->reactant2->flags & ON_GRID) {
++num_surface_mols;
}
}
path->orientation2 = prodp->next->orientation;
}
if (nprods > 2) {
path->reactant3 = prodp->next->next->prod;
if ((path->reactant3->flags & NOT_FREE) == 0) {
++num_vol_mols;
} else {
if (path->reactant3->flags & ON_GRID) {
++num_surface_mols;
}
}
path->orientation3 = prodp->next->next->orientation;
}
switch (reverse_rate->rate_type) {
case RATE_UNSET:
// mdlerror_fmt(parse_state, "File %s, Line %d: Internal error: Reverse rate
// is not set", __FILE__, __LINE__);
free(path);
return MCELL_FAIL;
case RATE_CONSTANT:
path->km = reverse_rate->v.rate_constant;
path->km_filename = NULL;
break;
case RATE_FILE:
path->km = 0.0;
path->km_filename = (char *)rate_filename;
free(reverse_rate->v.rate_file);
reverse_rate->v.rate_file = NULL;
break;
default:
UNHANDLED_CASE(reverse_rate->rate_type);
}
path->product_head = (struct product *)CHECKED_MALLOC_STRUCT(
struct product, "reaction product");
if (path->product_head == NULL) {
free(path);
return 1;
}
path->product_head->orientation = pathp->orientation1;
path->product_head->prod = pathp->reactant1;
path->product_head->next = NULL;
if (path->product_head->prod->flags & ON_GRID)
++num_surf_products;
if ((pathp->reactant2 != NULL) &&
((pathp->reactant2->flags & IS_SURFACE) == 0)) {
path->product_head->next = (struct product *)CHECKED_MALLOC_STRUCT(
struct product, "reaction product");
if (path->product_head->next == NULL) {
free(path);
return 1;
}
path->product_head->next->orientation = pathp->orientation2;
path->product_head->next->prod = pathp->reactant2;
path->product_head->next->next = NULL;
if (path->product_head->next->prod->flags & ON_GRID)
++num_surf_products;
if ((pathp->reactant3 != NULL) &&
((pathp->reactant3->flags & IS_SURFACE) == 0)) {
path->product_head->next->next = (struct product *)CHECKED_MALLOC_STRUCT(
struct product, "reaction product");
if (path->product_head->next->next == NULL) {
free(path);
return 1;
}
path->product_head->next->next->orientation = pathp->orientation3;
path->product_head->next->next->prod = pathp->reactant3;
path->product_head->next->next->next = NULL;
if (path->product_head->next->next->prod->flags & ON_GRID)
++num_surf_products;
}
}
path->prod_signature = create_prod_signature(&path->product_head);
if (path->prod_signature == NULL) {
// mdlerror(parse_state, "Error creating 'prod_signature' field for reaction
// pathway.");
free(path);
return MCELL_FAIL;
}
if ((!distinguishable(vacancy_search_dist2, 0, EPS_C)) &&
(num_surf_products > num_surface_mols)) {
/* the case with one volume molecule reacting with the surface
and producing one surface molecule is excluded */
if (!((num_surface_mols == 0) && (num_vol_mols == 1))) {
// mdlerror(parse_state, "Error: number of surface products exceeds number
// of surface reactants, but VACANCY_SEARCH_DISTANCE is not specified or
// set to zero.");
free(path);
return MCELL_FAIL;
}
}
/* Now go back to the original reaction and if there is a "surface_class"
among products - remove it. We do not need it now on the product side
of the reaction */
if (is_surf_class) {
prodp = pathp->product_head;
if (prodp->prod->flags & IS_SURFACE) {
pathp->product_head = prodp->next;
prodp->next = NULL;
// mem_put(parse_state->prod_mem, (void *)prodp);
} else if (prodp->next->prod->flags & IS_SURFACE) {
// struct product *temp = prodp->next;
prodp->next = prodp->next->next;
// mem_put(parse_state->prod_mem, temp);
} else {
// struct product *temp = prodp->next->next;
prodp->next->next = prodp->next->next->next;
// mem_put(parse_state->prod_mem, temp);
}
}
path->next = rx->pathway_head;
rx->pathway_head = path;
return 0;
}
/************************************************************************
* static helper functions
************************************************************************/
/*************************************************************************
sort_product_list_compare:
Comparison function for products to be sorted when generating the product
signature.
In: list_item: first item to compare
new_item: second item to compare
Out: -1 if list_item < new_item, 1 if list_item > new_item, 0 if they are
equal
XXX Currently this function also appears in mdlparse_util.c. It should
eventually be removed from there and only appear in this file.
*************************************************************************/
static int sort_product_list_compare(struct product *list_item,
struct product *new_item) {
int cmp = strcmp(list_item->prod->sym->name, new_item->prod->sym->name);
if (cmp == 0) {
if (list_item->orientation > new_item->orientation)
cmp = -1;
else if (list_item->orientation < new_item->orientation)
cmp = 1;
else
cmp = 0;
}
return cmp;
}
/*************************************************************************
sort_product_list:
Sorts product_head in alphabetical order, and descending orientation order.
Current algorithm uses insertion sort.
In: product_head: list to sort
Out: the new list head
XXX Currently this function also appears in mdlparse_util.c. It should
eventually be removed from there and only appear in this file.
*************************************************************************/
static struct product *sort_product_list(struct product *product_head) {
struct product *next; /* Saved next item (next field in product is
overwritten) */
struct product *iter; /* List iterator */
struct product *result = NULL; /* Sorted list */
int cmp;
/* Use insertion sort to sort the list of products */
for (struct product *current = product_head; current != NULL;
current = next) {
next = current->next;
/* First item added always goes at the head */
if (result == NULL) {
current->next = result;
result = current;
continue;
}
/* Check if the item belongs at the head */
cmp = sort_product_list_compare(result, current);
if (cmp >= 0) {
current->next = result;
result = current;
continue;
}
/* Otherwise, if it goes after the current entry, scan forward to find the
insert point */
else {
/* locate the node before the point of insertion */
iter = result;
while (iter->next != NULL && sort_product_list_compare(iter, current) < 0)
iter = iter->next;
current->next = iter->next;
iter->next = current;
}
}
return result;
}
/*************************************************************************
create_prod_signature:
Returns a string containing all products in the product_head list,
separated by '+', and sorted in alphabetical order by name and descending
orientation order.
In: product_head: list of products
Out: product signature as a string. *product_head list is sorted in
alphabetical order by name, and descending order by orientation. Returns
NULL on failure.
XXX Currently this function also appears in mdlparse_util.c. It should
eventually be removed from there and only appear in this file.
*************************************************************************/
char *create_prod_signature(struct product **product_head) {
/* points to the head of the sorted alphabetically list of products */
char *prod_signature = NULL;
*product_head = sort_product_list(*product_head);
/* create prod_signature string */
struct product *current = *product_head;
if (current == NULL) {
return NULL;
}
prod_signature = CHECKED_STRDUP(current->prod->sym->name, "product name");
/* Concatenate to create product signature */
char *temp_str = NULL;
while (current->next != NULL) {
temp_str = prod_signature;
prod_signature = CHECKED_SPRINTF("%s+%s", prod_signature,
current->next->prod->sym->name);
if (prod_signature == NULL) {
if (temp_str != NULL)
free(temp_str);
return NULL;
}
if (temp_str != NULL)
free(temp_str);
current = current->next;
}
return prod_signature;
}
/*************************************************************************
* init_reactions and related machinery
*************************************************************************/
/*************************************************************************
check_duplicate_special_reactions:
Check for duplicate special reaction pathways (e.g. TRANSPARENT = molecule).
In: path: Parse-time structure for reaction pathways
Out: Nothing.
Note: I'm not sure if this code is ever actually called.
*************************************************************************/
void check_duplicate_special_reactions(struct pathway *path) {
/* if it is a special reaction - check for the duplicates pathways */
if (path->next != NULL) {
if ((path->flags & PATHW_TRANSP) && (path->next->flags & PATHW_TRANSP)) {
if ((path->orientation2 == path->next->orientation2) ||
(path->orientation2 == 0) || (path->next->orientation2 == 0)) {
mcell_error("Exact duplicates of special reaction TRANSPARENT = %s are "
"not allowed. Please verify the contents of "
"DEFINE_SURFACE_CLASS statement.",
path->reactant2->sym->name);
}
}
if ((path->flags & PATHW_REFLEC) && (path->next->flags & PATHW_REFLEC)) {
if ((path->orientation2 == path->next->orientation2) ||
(path->orientation2 == 0) || (path->next->orientation2 == 0)) {
mcell_error("Exact duplicates of special reaction REFLECTIVE = %s are "
"not allowed. Please verify the contents of "
"DEFINE_SURFACE_CLASS statement.",
path->reactant2->sym->name);
}
}
if ((path->flags & PATHW_ABSORP) && (path->next->flags & PATHW_ABSORP)) {
if ((path->orientation2 == path->next->orientation2) ||
(path->orientation2 == 0) || (path->next->orientation2 == 0)) {
mcell_error("Exact duplicates of special reaction ABSORPTIVE = %s are "
"not allowed. Please verify the contents of "
"DEFINE_SURFACE_CLASS statement.",
path->reactant2->sym->name);
}
}
}
}
/*************************************************************************
set_product_geometries:
Walk through the list, setting the geometries of each of the products. We do
this by looking for an earlier geometric match and pointing there or we just
point to 0 if there is no match.
In: path: Parse-time structure for reaction pathways
rx: Pathways leading away from a given intermediate
prod: Parse-time structure for products of reaction pathways
Out: max_num_surf_products: Maximum number of surface products
*************************************************************************/
int set_product_geometries(struct pathway *path, struct rxn *rx,
struct product *prod) {
int recycled1, recycled2, recycled3;
int k, kk, k2;
short geom;
struct product *prod2;
int max_num_surf_products; /* maximum number of surface products */
int num_surf_products_per_pathway;
max_num_surf_products = 0;
for (int n_pathway = 0; path != NULL; n_pathway++, path = path->next) {
recycled1 = 0;
recycled2 = 0;
recycled3 = 0;
k = rx->product_idx[n_pathway] + rx->n_reactants;
num_surf_products_per_pathway = 0;
for (prod = path->product_head; prod != NULL; prod = prod->next) {
if (recycled1 == 0 && prod->prod == path->reactant1) {
recycled1 = 1;
kk = rx->product_idx[n_pathway] + 0;
} else if (recycled2 == 0 && prod->prod == path->reactant2) {
recycled2 = 1;
kk = rx->product_idx[n_pathway] + 1;
} else if (recycled3 == 0 && prod->prod == path->reactant3) {
recycled3 = 1;
kk = rx->product_idx[n_pathway] + 2;
} else {
kk = k;
k++;
}
if (prod->prod->flags & ON_GRID)
num_surf_products_per_pathway++;
rx->players[kk] = prod->prod;
if ((prod->orientation + path->orientation1) *
(prod->orientation - path->orientation1) ==
0 &&
prod->orientation * path->orientation1 != 0) {
if (prod->orientation == path->orientation1)
rx->geometries[kk] = 1;
else
rx->geometries[kk] = -1;
} else if (rx->n_reactants > 1 &&
(prod->orientation + path->orientation2) *
(prod->orientation - path->orientation2) ==
0 &&
prod->orientation * path->orientation2 != 0) {
if (prod->orientation == path->orientation2)
rx->geometries[kk] = 2;
else
rx->geometries[kk] = -2;
} else if (rx->n_reactants > 2 &&
(prod->orientation + path->orientation3) *
(prod->orientation - path->orientation3) ==
0 &&
prod->orientation * path->orientation3 != 0) {
if (prod->orientation == path->orientation3)
rx->geometries[kk] = 3;
else
rx->geometries[kk] = -3;
} else {
k2 = 2 * rx->n_reactants + 1; /* Geometry index of first non-reactant
product, counting from 1. */
geom = 0;
for (prod2 = path->product_head;
prod2 != prod && prod2 != NULL && geom == 0; prod2 = prod2->next) {
if ((prod2->orientation + prod->orientation) *
(prod2->orientation - prod->orientation) ==
0 &&
prod->orientation * prod2->orientation != 0) {
if (prod2->orientation == prod->orientation)
geom = 1;
else
geom = -1;
} else
geom = 0;
if (recycled1 == 1) {
if (prod2->prod == path->reactant1) {
recycled1 = 2;
geom *= rx->n_reactants + 1;
}
} else if (recycled2 == 1) {
if (prod2->prod == path->reactant2) {
recycled2 = 2;
geom *= rx->n_reactants + 2;
}
} else if (recycled3 == 1) {
if (prod2->prod == path->reactant3) {
recycled3 = 2;
geom *= rx->n_reactants + 3;
}
} else {
geom *= k2;
k2++;
}
}
rx->geometries[kk] = geom;
}
if (num_surf_products_per_pathway > max_num_surf_products)
max_num_surf_products = num_surf_products_per_pathway;
}
k = rx->product_idx[n_pathway];
if (recycled1 == 0)
rx->players[k] = NULL;
if (recycled2 == 0 && rx->n_reactants > 1)
rx->players[k + 1] = NULL;
if (recycled3 == 0 && rx->n_reactants > 2)
rx->players[k + 2] = NULL;
} /* end for (n_pathway = 0, ...) */
return max_num_surf_products;
}
/*************************************************************************
alphabetize_pathway:
The reaction pathway (path) is alphabetized.
In: path: Parse-time structure for reaction pathways
reaction: Reaction pathways leading away from a given intermediate
Out: Nothing.
*************************************************************************/
void alphabetize_pathway(struct pathway *path, struct rxn *reaction) {
short geom, geom2;
struct species *temp_sp, *temp_sp2;
/* Alphabetize if we have two molecules */
if ((path->reactant2->flags & IS_SURFACE) == 0) {
if (strcmp(path->reactant1->sym->name, path->reactant2->sym->name) > 0) {
temp_sp = path->reactant1;
path->reactant1 = path->reactant2;
path->reactant2 = temp_sp;
geom = path->orientation1;
path->orientation1 = path->orientation2;
path->orientation2 = geom;
} else if (strcmp(path->reactant1->sym->name, path->reactant2->sym->name) ==
0) {
if (path->orientation1 < path->orientation2) {
geom = path->orientation1;
path->orientation1 = path->orientation2;
path->orientation2 = geom;
}
}
}
/* Alphabetize if we have three molecules */
if (reaction->n_reactants == 3) {
if ((path->reactant3->flags & IS_SURFACE) == 0) {
if (strcmp(path->reactant1->sym->name, path->reactant3->sym->name) > 0) {
/* Put reactant3 at the beginning */
temp_sp = path->reactant1;
geom = path->orientation1;
path->reactant1 = path->reactant3;
path->orientation1 = path->orientation3;
/* Put former reactant1 in place of reactant2 */
temp_sp2 = path->reactant2;
geom2 = path->orientation2;
path->reactant2 = temp_sp;
path->orientation2 = geom;
/* Put former reactant2 in place of reactant3 */
path->reactant3 = temp_sp2;
path->orientation3 = geom2;
} else if (strcmp(path->reactant2->sym->name,
path->reactant3->sym->name) > 0) {
/* Put reactant3 after reactant1 */
temp_sp = path->reactant2;
path->reactant2 = path->reactant3;
path->reactant3 = temp_sp;
geom = path->orientation2;
path->orientation2 = path->orientation3;
path->orientation3 = geom;
}
} /*end */
}
}
/*************************************************************************
warn_about_high_rates:
If HIGH_REACTION_PROBABILITY is set to WARNING or ERROR, and the reaction
probability is high, give the user a warning or error respectively.
In: notify:
warn_file: The log/error file. Can be stdout/stderr
rate_warn: If 1, warn the user about high reaction rates (or give error)
print_once: If the warning has been printed once, don't repeat it
Out: print_once. Also print out reaction probabilities (with warning/error)
*************************************************************************/
static int warn_about_high_rates(struct notifications *notify, FILE *warn_file,
int rate_warn, int print_once) {
if (rate_warn) {
if (notify->high_reaction_prob == WARN_ERROR) {
warn_file = mcell_get_error_file();
if (!print_once) {
fprintf(warn_file, "\n");
fprintf(
warn_file,
"Reaction probabilities generated for the following reactions:\n");
print_once = 1;
}
fprintf(warn_file, "\tError: High ");
} else {
if (!print_once) {
fprintf(warn_file, "\n");
fprintf(
warn_file,
"Reaction probabilities generated for the following reactions:\n");
print_once = 1;
}
if (notify->high_reaction_prob == WARN_WARN)
fprintf(warn_file, "\tWarning: High ");
else
fprintf(warn_file, "\t");
}
} else {
if (!print_once) {
fprintf(warn_file, "\n");
fprintf(
warn_file,
"Reaction probabilities generated for the following reactions:\n");
print_once = 1;
}
fprintf(warn_file, "\t");
}
return print_once;
}
/*************************************************************************
add_surface_reaction_flags:
In: mol_sym_table:
all_mols:
all_surface_mols:
all_volume_mols:
Out: Nothing
*************************************************************************/
void add_surface_reaction_flags(struct sym_table_head *mol_sym_table,
struct species *all_mols,
struct species *all_surface_mols,
struct species *all_volume_mols) {
struct species *temp_sp;
/* Add flags for surface reactions with ALL_MOLECULES */
if (all_mols->flags & (CAN_VOLWALL | CAN_SURFWALL)) {
for (int n_mol_bin = 0; n_mol_bin < mol_sym_table->n_bins;
n_mol_bin++) {
for (struct sym_entry *symp = mol_sym_table->entries[n_mol_bin];
symp != NULL; symp = symp->next) {
temp_sp = (struct species *)symp->value;
if (temp_sp == all_mols)
continue;
if (temp_sp == all_volume_mols)
continue;
if (temp_sp == all_surface_mols)
continue;
if (((temp_sp->flags & NOT_FREE) == 0) &&
((temp_sp->flags & CAN_VOLWALL) == 0)) {
temp_sp->flags |= CAN_VOLWALL;
} else if ((temp_sp->flags & ON_GRID) &&
((temp_sp->flags & CAN_REGION_BORDER) == 0)) {
temp_sp->flags |= CAN_REGION_BORDER;
}
}
}
}
/* Add flags for surface reactions with ALL_VOLUME_MOLECULES */
if (all_volume_mols->flags & CAN_VOLWALL) {
for (int n_mol_bin = 0; n_mol_bin < mol_sym_table->n_bins;
n_mol_bin++) {
for (struct sym_entry *symp = mol_sym_table->entries[n_mol_bin];
symp != NULL; symp = symp->next) {
temp_sp = (struct species *)symp->value;
if (temp_sp == all_mols)
continue;
if (temp_sp == all_volume_mols)
continue;
if (temp_sp == all_surface_mols)
continue;
if (((temp_sp->flags & NOT_FREE) == 0) &&
((temp_sp->flags & CAN_VOLWALL) == 0)) {
temp_sp->flags |= CAN_VOLWALL;
}
}
}
}
/* Add flags for surface reactions with ALL_SURFACE_MOLECULES */
if (all_surface_mols->flags & CAN_SURFWALL) {
for (int n_mol_bin = 0; n_mol_bin < mol_sym_table->n_bins;
n_mol_bin++) {
for (struct sym_entry *symp = mol_sym_table->entries[n_mol_bin];
symp != NULL; symp = symp->next) {
temp_sp = (struct species *)symp->value;
if (temp_sp == all_mols)
continue;
if (temp_sp == all_volume_mols)
continue;
if (temp_sp == all_surface_mols)
continue;
if (((temp_sp->flags & ON_GRID) &&
((temp_sp->flags & CAN_REGION_BORDER) == 0))) {
temp_sp->flags |= CAN_REGION_BORDER;
}
}
}
}
}
/*************************************************************************
scale_rxn_probabilities:
Scale probabilities, notifying and warning as appropriate.
In: reaction_prob_limit_flag:
path: Parse-time structure for reaction pathways
rx: Pathways leading away from a given intermediate
pb_factor:
Out: Return 1 if rates are high and HIGH_REACTION_PROBABILITY is set to ERROR
Note: This does not work properly right now. Even if rates are high and
HIGH_REACTION_PROBABILITY is set to ERROR, the error is ignored
*************************************************************************/
int scale_rxn_probabilities(unsigned char *reaction_prob_limit_flag,
struct notifications *notify,
struct pathway *path, struct rxn *rx,
double pb_factor) {
int print_once = 0; /* flag */
FILE *warn_file;
int is_gigantic;
double rate;
for (int n_pathway = 0; path != NULL; n_pathway++, path = path->next) {
int rate_notify = 0, rate_warn = 0;
if (!distinguishable(rx->cum_probs[n_pathway], GIGANTIC, EPS_C))
is_gigantic = 1;
else
is_gigantic = 0;
/* automatic surface reactions will be printed out from 'init_sim()'. */
if (is_gigantic)
continue;
rate = pb_factor * rx->cum_probs[n_pathway];
rx->cum_probs[n_pathway] = rate;
if ((notify->reaction_probabilities == NOTIFY_FULL &&
((rate >= notify->reaction_prob_notify) ||
(notify->reaction_prob_notify == 0.0))))
rate_notify = 1;
if ((notify->high_reaction_prob != WARN_COPE &&
((rate >= notify->reaction_prob_warn) ||
((notify->reaction_prob_warn == 0.0)))))
rate_warn = 1;
if ((rate > 1.0) && (!*reaction_prob_limit_flag)) {
*reaction_prob_limit_flag = 1;
}
if (rate_warn || rate_notify) {
warn_file = mcell_get_log_file();
print_once =
warn_about_high_rates(notify, warn_file, rate_warn,
print_once);
fprintf(warn_file, "Probability %.4e set for ", rate);
if (rx->n_reactants == 1)
fprintf(warn_file, "%s{%d} -> ", rx->players[0]->sym->name,
rx->geometries[0]);
else if (rx->n_reactants == 2) {
if (rx->players[1]->flags & IS_SURFACE) {
fprintf(warn_file, "%s{%d} @ %s{%d} -> ", rx->players[0]->sym->name,
rx->geometries[0], rx->players[1]->sym->name,
rx->geometries[1]);
} else {
fprintf(warn_file, "%s{%d} + %s{%d} -> ", rx->players[0]->sym->name,
rx->geometries[0], rx->players[1]->sym->name,
rx->geometries[1]);
}
} else {
if (rx->players[2]->flags & IS_SURFACE) {
fprintf(warn_file, "%s{%d} + %s{%d} @ %s{%d} -> ",
rx->players[0]->sym->name, rx->geometries[0],
rx->players[1]->sym->name, rx->geometries[1],
rx->players[2]->sym->name, rx->geometries[2]);
} else {
fprintf(warn_file, "%s{%d} + %s{%d} + %s{%d} -> ",
rx->players[0]->sym->name, rx->geometries[0],
rx->players[1]->sym->name, rx->geometries[1],
rx->players[2]->sym->name, rx->geometries[2]);
}
}
if (path->product_head == NULL) {
fprintf(warn_file, "NULL ");
} else {
for (struct product *prod = path->product_head; prod != NULL;
prod = prod->next) {
fprintf(warn_file, "%s{%d} ", prod->prod->sym->name,
prod->orientation);
}
}
fprintf(warn_file, "\n");
if (rate_warn && notify->high_reaction_prob == WARN_ERROR)
return 1;
}
}
return 0;
}
/*************************************************************************
equivalent_geometry_for_two_reactants:
In: o1a: orientation of the first reactant from first reaction
o1b: orientation of the second reactant from first reaction
o2a: orientation of the first reactant from second reaction
o2b: orientation of the second reactant from second reaction
Out: Returns 1 if the two pathways (defined by pairs o1a-o1b and o2a-o2b)
have equivalent geometry, 0 otherwise.
*************************************************************************/
static int equivalent_geometry_for_two_reactants(int o1a, int o1b, int o2a,
int o2b) {
/* both reactants for each pathway are in the same
orientation class and parallel one another */
if ((o1a == o1b) && (o2a == o2b)) {
return 1;
/* both reactants for each pathway are in the same
orientation class and opposite one another */
} else if ((o1a == -o1b) && (o2a == -o2b)) {
return 1;
}
/* reactants are not in the same orientation class */
if (abs(o1a) != abs(o1b)) {
if ((abs(o2a) != abs(o2b)) || ((o2a == 0) && (o2b == 0))) {
return 1;
}
}
if (abs(o2a) != abs(o2b)) {
if ((abs(o1a) != abs(o1b)) || ((o1a == 0) && (o1b == 0))) {
return 1;
}
}
return 0;
}
/*************************************************************************
equivalent_geometry:
In: p1, p2: pathways to compare
n: The number of reactants for the pathways
Out: Returns 1 if the two pathways are the same (i.e. have equivalent
geometry), 0 otherwise.
*************************************************************************/
static int equivalent_geometry(struct pathway *p1, struct pathway *p2, int n) {
short o11, o12, o13, o21, o22, o23; /* orientations of individual reactants */
/* flags for 3-reactant reactions signaling whether molecules orientations
* are parallel one another and molecule and surface orientaions are parallel
* one another
*/
int mols_parallel_1 = SHRT_MIN + 1; /* for first pathway */
int mols_parallel_2 = SHRT_MIN + 2; /* for second pathway */
int mol_surf_parallel_1 = SHRT_MIN + 3; /* for first pathway */
int mol_surf_parallel_2 = SHRT_MIN + 4; /* for second pathway */
if (n < 2) {
/* one reactant case */
/* RULE: all one_reactant pathway geometries are equivalent */
return 1;
} else if (n < 3) {
/* two reactants case */
/* RULE - Two pathways have equivalent geometry when:
1) Both pathways have exactly the same number of reactants;
2) There exists an identity mapping between reactants from Pathway 1 and
Pathway 2 such that for each pair of reactants, r1a and r1b from
Pathway
1, and r2a, and r2b from Pathway 2:
- r1a is the same species as r2a (likewise for r1b and r2b);
- r1a and r1b have the same orientation in the same orientation class
if and only if r2a and r2b do;
- r1a and r1b have the opposite orientation in the same orientation
class if and only if r2a and r2b do;
- r1a and r1b are not in the same orientation class, either because
they have different orientation classes or both are in the zero
orientation class, if and only if r2a and r2b are not in the same
orientation class or both are in the zero orientation class
*/
o11 = p1->orientation1;
o12 = p1->orientation2;
o21 = p2->orientation1;
o22 = p2->orientation2;
return equivalent_geometry_for_two_reactants(o11, o12, o21, o22);
} else if (n < 4) {
/* three reactants case */
o11 = p1->orientation1;
o12 = p1->orientation2;
o13 = p1->orientation3;
o21 = p2->orientation1;
o22 = p2->orientation2;
o23 = p2->orientation3;
/* special case: two identical reactants */
if ((p1->reactant1 == p1->reactant2) && (p2->reactant1 == p2->reactant2)) {
/* Case 1: two molecules and surface are in the same orientation class */
if ((abs(o11) == abs(o12)) && (abs(o11) == abs(o13))) {
if (o11 == o12)
mols_parallel_1 = 1;
else
mols_parallel_1 = 0;
if (mols_parallel_1) {
if ((o11 == -o13) || (o12 == -o13)) {
mol_surf_parallel_1 = 0;
} else {
mol_surf_parallel_1 = 1;
}
} else {
mol_surf_parallel_1 = 0;
}
if ((abs(o21) == abs(o22)) && (abs(o21) == abs(o23))) {
if (o21 == o22)
mols_parallel_2 = 1;
else
mols_parallel_2 = 0;
if (mols_parallel_2) {
if ((o21 == -o23) || (o22 == -o23)) {
mol_surf_parallel_2 = 0;
} else {
mol_surf_parallel_2 = 1;
}
} else {
mol_surf_parallel_2 = 0;
}
}
if ((mols_parallel_1 == mols_parallel_2) &&
(mol_surf_parallel_1 == mol_surf_parallel_2)) {
return 1;
}
} /* end case 1 */
/* Case 2: one molecule and surface are in the same orientation class */
else if ((abs(o11) == abs(o13)) || (abs(o12) == abs(o13))) {
if ((o11 == o13) || (o12 == o13))
mol_surf_parallel_1 = 1;
else
mol_surf_parallel_1 = 0;
/* check that pathway2 is also in the case2 */
if ((abs(o21) != abs(o23)) || (abs(o22) != abs(o23))) {
if ((abs(o21) == abs(o23)) || (abs(o22) == abs(o23))) {
if ((o21 == o23) || (o22 == o23))
mol_surf_parallel_2 = 1;
else
mol_surf_parallel_2 = 0;
}
}
if (mol_surf_parallel_1 == mol_surf_parallel_2) {
return 1;
}
} /* end case 2 */
/* Case 3: two molecules but not surface are in the same
orientation class */
else if ((abs(o11) == abs(o12)) && (abs(o11) != abs(o13))) {
if (o11 == o12)
mols_parallel_1 = 1;
else
mols_parallel_1 = 0;
if ((abs(o21) == abs(o22)) && (abs(o21) != abs(o23))) {
if (o21 == o22)
mols_parallel_2 = 1;
else
mols_parallel_2 = 0;
}
if (mols_parallel_1 == mols_parallel_2) {
return 1;
}
}
/* Case 4: all molecules and surface are in different orientation classes
*/
else if ((abs(o11) != abs(o13)) && (abs(o12) != abs(o13)) &&
(abs(o11) != abs(o12))) {
if ((abs(o21) != abs(o23)) && (abs(o22) != abs(o23)) &&
(abs(o21) != abs(o22))) {
return 1;
}
} /* end all cases */
} else { /* no identical reactants */
if ((equivalent_geometry_for_two_reactants(o11, o12, o21, o22)) &&
(equivalent_geometry_for_two_reactants(o12, o13, o22, o23)) &&
(equivalent_geometry_for_two_reactants(o11, o13, o21, o23))) {
return 1;
}
}
} // end if (n < 4)
return 0;
}
/*************************************************************************
create_sibling_reaction:
Create a sibling reaction to the given reaction -- a reaction into which
some of the pathways may be split by split_reaction.
In: rx: reaction for whom to create sibling
Out: sibling reaction, or NULL on error
*************************************************************************/
static struct rxn *create_sibling_reaction(struct rxn *rx) {
struct rxn *reaction = CHECKED_MALLOC_STRUCT(struct rxn, "reaction");
if (reaction == NULL)
return NULL;
reaction->next = NULL;
reaction->sym = rx->sym;
reaction->n_reactants = rx->n_reactants;
reaction->get_reactant_diffusion = rx->get_reactant_diffusion;
reaction->n_pathways = 0;
reaction->cum_probs = NULL;
reaction->product_idx = NULL;
reaction->max_fixed_p = 0.0;
reaction->min_noreaction_p = 0.0;
reaction->pb_factor = 0.0;
reaction->players = NULL;
reaction->geometries = NULL;
reaction->n_occurred = 0;
reaction->n_skipped = 0.0;
reaction->prob_t = NULL;
reaction->pathway_head = NULL;
reaction->info = NULL;
reaction->product_graph_data = NULL;
reaction->external_reaction_data = NULL;
return reaction;
}
/*************************************************************************
split_reaction:
In: rx: reaction to split
Out: Returns head of the linked list of reactions where each reaction
contains only geometrically equivalent pathways
*************************************************************************/
struct rxn *split_reaction(struct rxn *rx) {
struct rxn *curr_rxn_ptr = NULL, *head = NULL, *end = NULL;
struct rxn *reaction;
struct pathway *to_place, *temp;
/* keep reference to the head of the future linked_list */
head = end = rx;
to_place = head->pathway_head->next;
head->pathway_head->next = NULL;
head->n_pathways = 1;
while (to_place != NULL) {
if (to_place->flags &
(PATHW_TRANSP | PATHW_REFLEC | PATHW_ABSORP | PATHW_CLAMP_CONC | PATHW_CLAMP_FLUX)) {
reaction = create_sibling_reaction(rx);
if (reaction == NULL)
return NULL;
reaction->pathway_head = to_place;
to_place = to_place->next;
reaction->pathway_head->next = NULL;
++reaction->n_pathways;
end->next = reaction;
end = reaction;
} else {
for (curr_rxn_ptr = head; curr_rxn_ptr != NULL;
curr_rxn_ptr = curr_rxn_ptr->next) {
if (curr_rxn_ptr->pathway_head->flags &
(PATHW_TRANSP | PATHW_REFLEC | PATHW_ABSORP))
continue;
if (equivalent_geometry(to_place, curr_rxn_ptr->pathway_head,
curr_rxn_ptr->n_reactants))
break;
}
if (!curr_rxn_ptr) {
reaction = create_sibling_reaction(rx);
if (reaction == NULL)
return NULL;
end->next = reaction;
end = reaction;
curr_rxn_ptr = end;
}
temp = to_place;
to_place = to_place->next;
temp->next = curr_rxn_ptr->pathway_head;
curr_rxn_ptr->pathway_head = temp;
++curr_rxn_ptr->n_pathways;
}
}
return head;
}
/*************************************************************************
check_reaction_for_duplicate_pathways:
In: head: head of linked list of pathways
Out: Sorts linked list of pathways in alphabetical order according to the
"prod_signature" field. Checks for the duplicate pathways. Prints error
message and exits simulation if duplicates found.
Note: This function is called after 'split_reaction()' function so all
pathways have equivalent geometry from the reactant side. Here we check
whether relative orientation of all players (both reactants and
products) is the same for the two seemingly identical pathways.
RULE: Two reactions pathways are duplicates if and only if
(a) they both have the same number and species of reactants;
(b) they both have the same number and species of products;
(c) there exists a bijective mapping between the reactants and products
of the two pathways such that reactants map to reactants, products
map to products, and the two pathways have equivalent geometry
under mapping.
Two pathways R1 and R2 have an equivalent geometry under a mapping
M if and only if for every pair of players "i" and "j" in R1, the
corresponding players M(i) and M(j) in R2 have the same orientation
relation as do "i" and "j" in R1.
Two players "i" and "j" in a reaction pathway have the following
orientation:
parallel - if both "i" and "j" are in the same nonzero orientation
class with the same sign;
antiparallel (opposite) - if they are both in the same nonzero
orientation class but have opposite sign;
independent - if they are in different orientation classes or both
in the zero orientation class.
PostNote: In this function we check only the validity of Rule (c) since
conditions of Rule (a) and (b) are already satisfied when the
function is called.
*************************************************************************/
void check_reaction_for_duplicate_pathways(struct pathway **head) {
struct pathway *result = NULL; /* build the sorted list here */
struct pathway *null_result = NULL; /* put pathways with NULL
prod_signature field here */
struct pathway *current, *next, **pprev;
struct product *iter1, *iter2;
int pathways_equivalent; /* flag */
int i, j;
int num_reactants; /* number of reactants in the pathway */
int num_products; /* number of products in the pathway */
int num_players; /* total number of reactants and products in the pathway */
int *orient_players_1,
*orient_players_2; /* array of orientations of players */
int o1a, o1b, o2a, o2b;
/* extract pathways with "prod_signature" field equal to NULL into
* "null_result" list */
current = *head;
pprev = head;
while (current != NULL) {
if (current->prod_signature == NULL) {
*pprev = current->next;
current->next = null_result;
null_result = current;
current = *pprev;
} else {
pprev = ¤t->next;
current = current->next;
}
}
/* check for duplicate pathways in null_result */
current = null_result;
if ((current != NULL) && (current->next != NULL)) {
/* From the previously called function "split_reaction()" we know that
* reactant-reactant pairs in two pathways are equivalent. Because there
* are no products the pathways are duplicates.
RULE: There may be no more than one pathway with zero (--->NULL)
products in the reaction->pathway_head
after calling the function "split_reaction()"
*/
if (current->reactant2 == NULL)
mcell_error("Exact duplicates of reaction %s ----> NULL are not "
"allowed. Please verify that orientations of reactants are "
"not equivalent.",
current->reactant1->sym->name);
else if (current->reactant3 == NULL)
mcell_error("Exact duplicates of reaction %s + %s ----> NULL are not "
"allowed. Please verify that orientations of reactants are "
"not equivalent.",
current->reactant1->sym->name, current->reactant2->sym->name);
else
mcell_error("Exact duplicates of reaction %s + %s + %s ----> NULL are "
"not allowed. Please verify that orientations of reactants "
"are not equivalent.",
current->reactant1->sym->name, current->reactant2->sym->name,
current->reactant3->sym->name);
}
/* now sort the remaining pathway list by "prod_signature" field and check
* for the duplicates */
current = *head;
while (current != NULL) {
next = current->next;
/* insert in sorted order into the "result" */
if (result == NULL ||
(strcmp(result->prod_signature, current->prod_signature) >= 0)) {
current->next = result;
result = current;
} else {
struct pathway *iter = result;
while (iter->next != NULL && (strcmp(iter->next->prod_signature,
current->prod_signature) < 0)) {
iter = iter->next;
}
current->next = iter->next;
iter->next = current;
}
/* move along the original list */
current = next;
}
/* Now check for the duplicate pathways */
/* Since the list is sorted we can proceed down the list and compare the
* adjacent nodes */
current = result;
if (current != NULL) {
while (current->next != NULL) {
if (strcmp(current->prod_signature, current->next->prod_signature) == 0) {
pathways_equivalent = 1;
/* find total number of players in the pathways */
num_reactants = 0;
num_products = 0;
if (current->reactant1 != NULL)
num_reactants++;
if (current->reactant2 != NULL)
num_reactants++;
if (current->reactant3 != NULL)
num_reactants++;
iter1 = current->product_head;
while (iter1 != NULL) {
num_products++;
iter1 = iter1->next;
}
num_players = num_reactants + num_products;
/* create arrays of players orientations */
orient_players_1 = CHECKED_MALLOC_ARRAY(int, num_players,
"reaction player orientations");
if (orient_players_1 == NULL)
mcell_die();
orient_players_2 = CHECKED_MALLOC_ARRAY(int, num_players,
"reaction player orientations");
if (orient_players_2 == NULL)
mcell_die();
if (current->reactant1 != NULL)
orient_players_1[0] = current->orientation1;
if (current->reactant2 != NULL)
orient_players_1[1] = current->orientation2;
if (current->reactant3 != NULL)
orient_players_1[2] = current->orientation3;
if (current->next->reactant1 != NULL)
orient_players_2[0] = current->next->orientation1;
if (current->next->reactant2 != NULL)
orient_players_2[1] = current->next->orientation2;
if (current->next->reactant3 != NULL)
orient_players_2[2] = current->next->orientation3;
iter1 = current->product_head;
iter2 = current->next->product_head;
for (i = num_reactants; i < num_players; i++) {
orient_players_1[i] = iter1->orientation;
orient_players_2[i] = iter2->orientation;
iter1 = iter1->next;
iter2 = iter2->next;
}
/* below we will compare only reactant-product and product-product
* combinations because reactant-reactant combinations were compared
* previously in the function "equivalent_geometry()" */
/* Initial assumption - pathways are equivalent. We check whether this
* assumption is valid by comparing pairs as described above */
i = 0;
while ((i < num_players) && (pathways_equivalent)) {
if (i < num_reactants) {
j = num_reactants;
} else {
j = i + 1;
}
for (; j < num_players; j++) {
o1a = orient_players_1[i];
o1b = orient_players_1[j];
o2a = orient_players_2[i];
o2b = orient_players_2[j];
if (!equivalent_geometry_for_two_reactants(o1a, o1b, o2a, o2b)) {
pathways_equivalent = 0;
break;
}
}
i++;
}
if (pathways_equivalent) {
if (current->reactant1 != NULL) {
if (current->reactant2 == NULL)
mcell_error("Exact duplicates of reaction %s ----> %s are not "
"allowed. Please verify that orientations of "
"reactants are not equivalent.",
current->reactant1->sym->name, current->prod_signature);
else if (current->reactant3 == NULL)
mcell_error("Exact duplicates of reaction %s + %s ----> %s are "
"not allowed. Please verify that orientations of "
"reactants are not equivalent.",
current->reactant1->sym->name,
current->reactant2->sym->name, current->prod_signature);
else
mcell_error("Exact duplicates of reaction %s + %s + %s ----> %s "
"are not allowed. Please verify that orientations of "
"reactants are not equivalent.",
current->reactant1->sym->name,
current->reactant2->sym->name,
current->reactant3->sym->name, current->prod_signature);
}
}
free(orient_players_1);
free(orient_players_2);
}
current = current->next;
}
}
if (null_result == NULL) {
*head = result;
} else if (result == NULL) {
*head = null_result;
} else {
current = result;
while (current->next != NULL) {
current = current->next;
}
current->next = null_result;
null_result->next = NULL;
*head = result;
}
}
/*************************************************************************
set_reaction_player_flags:
Set the reaction player flags for all participating species in this
reaction.
In: rx: the reaction
Out: Nothing. Species flags may be updated.
*************************************************************************/
void set_reaction_player_flags(struct rxn *rx) {
switch (rx->n_reactants) {
case 1:
/* do nothing */
return;
case 2:
if (strcmp(rx->players[0]->sym->name, "ALL_MOLECULES") == 0) {
rx->players[0]->flags |= (CAN_VOLWALL | CAN_SURFWALL);
} else if (strcmp(rx->players[0]->sym->name, "ALL_VOLUME_MOLECULES") == 0) {
rx->players[0]->flags |= CAN_VOLWALL;
} else if (strcmp(rx->players[0]->sym->name, "ALL_SURFACE_MOLECULES") ==
0) {
rx->players[0]->flags |= CAN_SURFWALL;
} else if ((rx->players[0]->flags & NOT_FREE) == 0) {
/* two volume molecules */
if ((rx->players[1]->flags & NOT_FREE) == 0) {
rx->players[0]->flags |= CAN_VOLVOL;
rx->players[1]->flags |= CAN_VOLVOL;
}
/* one volume molecules and one wall */
else if ((rx->players[1]->flags & IS_SURFACE) != 0) {
rx->players[0]->flags |= CAN_VOLWALL;
}
/* one volume molecule and one surface molecule */
else if ((rx->players[1]->flags & ON_GRID) != 0) {
rx->players[0]->flags |= CAN_VOLSURF;
}
} else if ((rx->players[0]->flags & IS_SURFACE) != 0) {
/* one volume molecule and one wall */
if ((rx->players[1]->flags & NOT_FREE) == 0) {
rx->players[1]->flags |= CAN_VOLWALL;
}
/* one surface molecule and one wall */
else if ((rx->players[1]->flags & ON_GRID) != 0) {
rx->players[1]->flags |= CAN_SURFWALL;
}
} else if ((rx->players[0]->flags & ON_GRID) != 0) {
/* one volume molecule and one surface molecule */
if ((rx->players[1]->flags & NOT_FREE) == 0) {
rx->players[1]->flags |= CAN_VOLSURF;
}
/* two surface molecules */
else if ((rx->players[1]->flags & ON_GRID) != 0) {
rx->players[0]->flags |= CAN_SURFSURF;
rx->players[1]->flags |= CAN_SURFSURF;
}
/* one surface molecule and one wall */
else if ((rx->players[1]->flags & IS_SURFACE) != 0) {
rx->players[0]->flags |= CAN_SURFWALL;
}
}
break;
case 3:
if ((rx->players[2]->flags & IS_SURFACE) != 0) {
/* two molecules and surface */
if ((rx->players[0]->flags & NOT_FREE) == 0) {
/* one volume molecule, one surface molecule, one surface */
if ((rx->players[1]->flags & ON_GRID) != 0) {
rx->players[0]->flags |= CAN_VOLSURF;
}
} else if ((rx->players[0]->flags & ON_GRID) != 0) {
/* one volume molecule, one surface molecule, one surface */
if ((rx->players[1]->flags & NOT_FREE) == 0) {
rx->players[1]->flags |= CAN_VOLSURF;
}
/* two surface molecules, one surface */
else if ((rx->players[1]->flags & ON_GRID) != 0) {
rx->players[0]->flags |= CAN_SURFSURF;
rx->players[1]->flags |= CAN_SURFSURF;
}
}
} else {
if ((rx->players[0]->flags & NOT_FREE) == 0) {
if ((rx->players[1]->flags & NOT_FREE) == 0) {
/* three volume molecules */
if ((rx->players[2]->flags & NOT_FREE) == 0) {
rx->players[0]->flags |= CAN_VOLVOLVOL;
rx->players[1]->flags |= CAN_VOLVOLVOL;
rx->players[2]->flags |= CAN_VOLVOLVOL;
}
/* two volume molecules and one surface molecule */
else if ((rx->players[2]->flags & ON_GRID) != 0) {
rx->players[0]->flags |= CAN_VOLVOLSURF;
rx->players[1]->flags |= CAN_VOLVOLSURF;
}
} else if ((rx->players[1]->flags & ON_GRID) != 0) {
/* two volume molecules and one surface molecule */
if ((rx->players[2]->flags & NOT_FREE) == 0) {
rx->players[0]->flags |= CAN_VOLVOLSURF;
rx->players[2]->flags |= CAN_VOLVOLSURF;
}
/* one volume molecules and two surface molecules */
else if ((rx->players[2]->flags & ON_GRID) != 0) {
rx->players[0]->flags |= CAN_VOLSURFSURF;
}
}
} else if ((rx->players[0]->flags & ON_GRID) != 0) {
if ((rx->players[1]->flags & NOT_FREE) == 0) {
/* two volume molecules and one surface molecule */
if ((rx->players[2]->flags & NOT_FREE) == 0) {
rx->players[1]->flags |= CAN_VOLVOLSURF;
rx->players[2]->flags |= CAN_VOLVOLSURF;
}
/* one volume molecule and two surface molecules */
else if ((rx->players[2]->flags & ON_GRID) != 0) {
rx->players[1]->flags |= CAN_VOLSURFSURF;
}
} else if ((rx->players[1]->flags & ON_GRID) != 0) {
/* one volume molecule and two surface molecules */
if ((rx->players[2]->flags & NOT_FREE) == 0) {
rx->players[2]->flags |= CAN_VOLSURFSURF;
}
/* three surface molecules */
else if ((rx->players[2]->flags & ON_GRID) != 0) {
rx->players[0]->flags |= CAN_SURFSURFSURF;
rx->players[1]->flags |= CAN_SURFSURFSURF;
rx->players[2]->flags |= CAN_SURFSURFSURF;
}
}
}
}
break;
default:
// assert(0);
break;
}
}
/*************************************************************************
build_reaction_hash_table:
Scan the symbol table, copying all reactions found into the reaction hash.
In: reaction_hash:
n_reactions:
rxn_sym_table:
rx_hashsize:
num_rx: num reactions expected
Out: 0 on success, 1 if we fail to allocate the table
*************************************************************************/
int build_reaction_hash_table(
struct rxn ***reaction_hash, int *n_reactions,
struct sym_table_head *rxn_sym_table, int *rx_hashsize, int num_rx) {
struct rxn **rx_tbl = NULL;
int rx_hash;
for (rx_hash = 2; rx_hash <= num_rx && rx_hash != 0; rx_hash <<= 1)
;
rx_hash <<= 1;
if (rx_hash == 0)
rx_hash = MAX_RX_HASH;
if (rx_hash > MAX_RX_HASH)
rx_hash = MAX_RX_HASH;
#ifdef REPORT_RXN_HASH_STATS
mcell_log("Num rxns: %d", num_rx);
mcell_log("Size of hash: %d", rx_hash);
#endif
/* Create the reaction hash table */
*rx_hashsize = rx_hash;
rx_hash -= 1;
rx_tbl = CHECKED_MALLOC_ARRAY(struct rxn *, *rx_hashsize,
"reaction hash table");
if (rx_tbl == NULL)
return 1;
*reaction_hash = rx_tbl;
for (int i = 0; i <= rx_hash; i++)
rx_tbl[i] = NULL;
#ifdef REPORT_RXN_HASH_STATS
int numcoll = 0;
#endif
for (int i = 0; i < rxn_sym_table->n_bins; i++) {
for (struct sym_entry *sym = rxn_sym_table->entries[i]; sym != NULL;
sym = sym->next) {
struct rxn *rx = (struct rxn *)sym->value;
int table_slot;
if (rx->n_reactants == 1) {
table_slot = rx->players[0]->hashval & rx_hash;
} else {
table_slot =
(rx->players[0]->hashval + rx->players[1]->hashval) & rx_hash;
}
#ifdef REPORT_RXN_HASH_STATS
if (rx_tbl[table_slot] != NULL) {
mcell_log("Collision: %s and %s", rx_tbl[table_slot]->sym->name,
sym->name);
++numcoll;
}
#endif
*n_reactions = *n_reactions + 1;
while (rx->next != NULL)
rx = rx->next;
rx->next = rx_tbl[table_slot];
rx_tbl[table_slot] = (struct rxn *)sym->value;
}
}
#ifdef REPORT_RXN_HASH_STATS
mcell_log("Num collisions: %d", numcoll);
#endif
return 0;
}
/*****************************************************************************
*
* mcell_create_reaction_rates list creates a struct reaction_rates used
* for creating reactions from a forward and backward reaction rate.
* The backward rate is only needed for catalytic arrow and should be
* RATE_UNUSED otherwise.
*
*****************************************************************************/
struct reaction_rates mcell_create_reaction_rates(int forwardRateType,
double forwardRateConstant,
int backwardRateType,
double backwardRateConstant) {
struct reaction_rate forwardRate;
forwardRate.rate_type = forwardRateType;
forwardRate.v.rate_constant = forwardRateConstant;
struct reaction_rate backwardRate;
backwardRate.rate_type = backwardRateType;
backwardRate.v.rate_constant = backwardRateConstant;
struct reaction_rates rates = { forwardRate, backwardRate };
return rates;
}
/*************************************************************************
load_rate_file:
Read in a time-varying reaction rate constant file.
In: time_unit:
tv_rxn_mem:
rx: Reaction structure that we'll load the rates into.
fname: Filename to read the rates from.
path: Index of the pathway that these rates apply to.
neg_reaction: warning or error policy for negative reactions.
Out: Returns 1 on error, 0 on success.
Rate constants are added to the prob_t linked list. If there is a rate
constant given for time <= 0, then this rate constant is stuck into
cum_probs and the (time <= 0) entries are not added to the list. If no
initial rate constnat is given in the file, it is assumed to be zero.
Note: The file format is assumed to be two columns of numbers; the first
column is time (in seconds) and the other is rate constant (in
appropriate units) that starts at that time. Lines that are not numbers
are ignored.
*************************************************************************/
int load_rate_file(struct volume* state, struct rxn *rx, char *fname, int path) {
struct mem_helper *tv_rxn_mem = state->tv_rxn_mem;
const char *RATE_SEPARATORS = "\f\n\r\t\v ,;";
const char *FIRST_DIGIT = "+-0123456789";
int i;
FILE *f = fopen(fname, "r");
if (!f)
return 1;
else {
struct t_func *tp, *tp2;
double t, rate_constant;
char buf[2048];
char *cp;
int linecount = 0;
#ifdef DEBUG
int valid_linecount = 0;
#endif
tp2 = NULL;
while (fgets(buf, 2048, f)) {
linecount++;
for (i = 0; i < 2048; i++) {
if (!strchr(RATE_SEPARATORS, buf[i]))
break;
}
if (i < 2048 && strchr(FIRST_DIGIT, buf[i])) {
t = strtod((buf + i), &cp);
if (cp == (buf + i))
continue; /* Conversion error. */
for (i = cp - buf; i < 2048; i++) {
if (!strchr(RATE_SEPARATORS, buf[i]))
break;
}
// This is kind of a silly corner case, but let's check for it to keep
// coverity happy.
if (i == 2048) {
mcell_error(
"a time in the rate constant file consists of too many characters "
"(it uses 2048 or more characters).");
return(1);
}
rate_constant = strtod((buf + i), &cp);
if (cp == (buf + i))
continue; /* Conversion error */
/* at this point we need to handle negative reaction rate constants */
if (rate_constant < 0.0)
{
if (state->notify->neg_reaction == WARN_ERROR)
{
mcell_error("reaction rate constants should be zero or positive.");
return 1;
}
else if (state->notify->neg_reaction == WARN_WARN) {
mcell_warn("negative reaction rate constant %f; setting to zero "
"and continuing.", rate_constant);
rate_constant = 0.0;
}
}
tp = (struct t_func *)CHECKED_MEM_GET(tv_rxn_mem,
"time-varying reaction rate constants");
if (tp == NULL) {
fclose(f);
return 1;
}
tp->next = NULL;
tp->path = path;
// tp->time is in fact iteration, we need to convert the iteration correctly in case we
// are continuing from a checkpoint with a different timestep
tp->time = convert_seconds_to_iterations(
state->start_iterations, state->time_unit,
state->chkpt_start_time_seconds, t);
tp->value = rate_constant;
tp->value_from_file = rate_constant; // tp->value gets updated later, for MCell we need the value from file
#ifdef DEBUG
valid_linecount++;
#endif
if (rx->prob_t == NULL) {
rx->prob_t = tp;
tp2 = tp;
} else {
if (tp2 == NULL) {
tp2 = tp;
tp->next = rx->prob_t;
rx->prob_t = tp;
} else {
if (tp->time < tp2->time)
mcell_warn(
"In rate constants file '%s', line %d is out of sequence. "
"Resorting.", fname, linecount);
tp->next = tp2->next;
tp2->next = tp;
tp2 = tp;
}
}
}
}
#ifdef DEBUG
mcell_log("Read %d rate constants from file %s.", valid_linecount, fname);
#endif
fclose(f);
}
return 0;
}
struct sym_entry *mcell_new_rxn_pathname(struct volume *state, char *name) {
if ((retrieve_sym(name, state->rxpn_sym_table)) != NULL) {
mcell_log("Named reaction pathway already defined: %s", name);
return NULL;
} else if ((retrieve_sym(name, state->mol_sym_table)) != NULL) {
mcell_log("Named reaction pathway already defined as a molecule: %s", name);
return NULL;
}
struct sym_entry *symp = store_sym(name, RXPN, state->rxpn_sym_table, NULL);
if (symp == NULL) {
mcell_log("Out of memory while creating reaction name: %s", name);
return NULL;
}
return symp;
}
| C |
3D | mcellteam/mcell | src/mcell_surfclass.h | .h | 1,229 | 45 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "config.h"
#include "logging.h"
#include "sym_table.h"
#include "mcell_species.h"
#include "init.h"
#include "mcell_structs.h"
MCELL_STATUS mcell_add_surf_class_properties(
MCELL_STATE *state,
int reaction_type,
mcell_symbol *sc_sym,
mcell_symbol *reactant_sym,
short orient);
MCELL_STATUS mcell_create_surf_class(
MCELL_STATE *state,
const char *surf_class_name,
mcell_symbol **sc_sym);
struct sm_dat *mcell_add_mol_release_to_surf_class(
MCELL_STATE *state,
struct sym_entry *sc_sym,
struct mcell_species *sm_info,
double quantity,
int density_or_num,
struct sm_dat *smd_list);
MCELL_STATUS mcell_assign_surf_class_to_region(
struct sym_entry *sc_sym,
struct region *rgn);
| Unknown |
3D | mcellteam/mcell | src/config-nix.h | .h | 1,670 | 45 | /******************************************************************************
*
* Copyright (C) 2006-2025 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/* *nix-specific includes and defines */
#ifndef MCELL_CONFIG_NIX_H
#define MCELL_CONFIG_NIX_H
/* Macro for eliminating "unused variable" or "unused parameter" warnings. */
#define UNUSED(p) ((void)(p))
#ifndef __GNUC__
#ifndef __attribute__
#define __attribute__(x) /* empty */
#endif
#endif
#if __GNUC__ < 3
#ifndef __attribute__
#define __attribute__(x) /* empty */
#endif
#endif
#define PRINTF_FORMAT(arg) \
__attribute__((__format__(printf, arg, arg + 1))) /* specifies that a \
function is uses a \
printf-like format - \
only used for \
compile-time warnings \
*/
#define PRINTF_FORMAT_V(arg) \
__attribute__((__format__(printf, arg, 0))) /* same but with va_list \
argument */
#endif
| Unknown |
3D | mcellteam/mcell | src/version_info.c | .c | 4,037 | 117 | /******************************************************************************
*
* Copyright (C) 2006-2025 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _MSC_VER
#include <unistd.h>
#include <sys/time.h>
#endif
#include <time.h>
#include "config.h"
#include "version_info.h"
#include "version.h"
const char mcell_version[] = MCELL_VERSION;
/*
* Prints out authors' institutions.
*
* f: file handle to which to write
*/
void print_credits(FILE *f) {
fprintf(
f,
" Copyright (C) 2006-2025 by\n"
" The National Center for Multiscale Modeling of Biological Systems,\n"
" The Salk Institute for Biological Studies, and\n"
" Pittsburgh Supercomputing Center, Carnegie Mellon University,\n\n\n"
"**********************************************************************\n"
"MCell development is supported by the NIGMS-funded (P41GM103712)\n"
"National Center for Multiscale Modeling of Biological Systems (MMBioS).\n"
"Please acknowledge MCell in your publications.\n"
"**********************************************************************"
"\n\n");
}
/*
* Prints out brief version info.
*
* f: file handle to which to write
*/
void print_version(FILE *f) {
char hostname[256];
char curtime[128];
time_t now = time(NULL);
/* Print the version line */
fprintf(f, "MCell %s", MCELL_VERSION);
if (strncmp(MCELL_REVISION, "", strlen(MCELL_REVISION)) != 0)
fprintf(f, " (commit: %s date: %s)", MCELL_REVISION, MCELL_REVISION_DATE);
if (!MCELL_REVISION_COMMITTED)
fprintf(f, " [unofficial revision]");
fprintf(f, "\n");
#ifndef _WIN64
/* Print the current machine details */
gethostname(hostname, sizeof(hostname));
fprintf(f, " Running on %s at %s\n", hostname, ctime_r(&now, curtime));
#endif
print_credits(f);
}
/*
* Prints out full version info.
*
* f: file handle to which to write
*/
void print_full_version(FILE *f) {
/* Print version line */
print_version(f);
/* Print build info */
fprintf(f, " Built at %s on %s by %s\n", MCELL_BUILDDATE, MCELL_BUILDHOST,
MCELL_BUILDUSER);
fprintf(f, " Src directory: %s\n", MCELL_SRCDIR);
fprintf(f, " Build directory: %s\n", MCELL_BUILDDIR);
fprintf(f, " Branch: %s\n", MCELL_REVISION_BRANCH);
fprintf(f, " Machine info: %s\n", MCELL_BUILDUNAME);
fprintf(f, "\n");
/* Print detailed build options */
fprintf(f, " Build configuration:\n");
fprintf(f, " Compiler: %s [%s]\n", MCELL_CC, MCELL_CC_PATH);
fprintf(f, " version: %s\n", MCELL_CC_VERSION);
fprintf(f, " Linker: %s [%s]\n", MCELL_LD, MCELL_LD_PATH);
fprintf(f, " version: %s\n", MCELL_LD_VERSION);
fprintf(f, " lex: %s [%s]\n", MCELL_FLEX, MCELL_FLEX_PATH);
fprintf(f, " version: %s\n", MCELL_FLEX_VERSION);
fprintf(f, " yacc: %s [%s]\n", MCELL_BISON, MCELL_BISON_PATH);
fprintf(f, " version: %s\n", MCELL_BISON_VERSION);
fprintf(f, "\n");
if (MCELL_CFLAGS[0] != '\0' || MCELL_LDFLAGS[0] != '\0' ||
MCELL_LFLAGS[0] != '\0' || MCELL_YFLAGS[0] != '\0') {
fprintf(f, " Build flags:\n");
if (MCELL_CFLAGS[0] != '\0')
fprintf(f, " Compiler flags: %s\n", MCELL_CFLAGS);
if (MCELL_LDFLAGS[0] != '\0')
fprintf(f, " Linker flags: %s\n", MCELL_LDFLAGS);
if (MCELL_LFLAGS[0] != '\0')
fprintf(f, " lex flags: %s\n", MCELL_LFLAGS);
if (MCELL_YFLAGS[0] != '\0')
fprintf(f, " yacc flags: %s\n", MCELL_YFLAGS);
fprintf(f, "\n");
}
}
| C |
3D | mcellteam/mcell | src/mcell_structs.h | .h | 86,736 | 2,049 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "config.h"
#ifndef _MSC_VER
#include <sys/time.h>
#include <sys/types.h>
#endif
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
#include "mem_util.h"
#include "sched_util.h"
#include "util.h"
#include "mcell_structs_shared.h"
/*****************************************************/
/** Brand new constants created for use in MCell3 **/
/*****************************************************/
#define ORIENT_NOT_SET -100
/* Species flags */
/* Surface classes have IS_SURFACE set, molecules do not. */
/* Surface molecules have ON_GRID set */
/* Volume molecules have NOT_FREE clear (i.e. flags&NOT_FREE==0) */
/* CAN_ flags specify what types of reactions this molecule can undergo */
/* CANT_INITIATE means that this molecule may not trigger a reaction with
another molecule */
/* COUNT_TRIGGER means that someone wants to output a TRIGGER statement when
something happens to this molecule */
// COUNT_CONTENTS is set if you're counting numbers of molecules in/on regions
/* COUNT_HITS is set if you're counting when the molecules hit regions */
/* COUNT_RXNS is set if you're counting reactions involving this molecule */
/* COUNT_ENCLOSED set if you count what happens inside closed region (vol
molecules, or surface mols treated as if they were vol mols) */
/* COUNT_SOME_MASK is a bitmask which is nonzero if any counting happens */
/* CAN_REGION_BORDER is set when surface molecule can interact with region
border that is declared REFLECTIVE/TRANSPARENT/ABSORPTIVE for that
molecule */
/* REGION_PRESENT set for the surface molecule when it is part of the
SURFACE_CLASS definition and there are regions defined with this
SURFACE_CLASS assigned */
/*
JJT: EXTERN defines a species whose reaction rates calculation will be delegated
to an external application
*/
#define ON_GRID 0x01
#define IS_SURFACE 0x02
#define NOT_FREE 0x03
#define TIME_VARY 0x04
#define CAN_VOLVOLVOL 0x08
#define CAN_VOLVOL 0x10
#define CAN_VOLSURF 0x20
#define CAN_VOLWALL 0x40
#define CAN_SURFSURF 0x80
#define CAN_SURFWALL 0x100
#define CAN_VOLVOLSURF 0x200
#define CANT_INITIATE 0x400
#define COUNT_TRIGGER 0x0800
#define COUNT_CONTENTS 0x1000
#define COUNT_HITS 0x2000
#define COUNT_RXNS 0x4000
#define COUNT_ENCLOSED 0x8000
#define COUNT_SOME_MASK 0xF800
#define CAN_VOLSURFSURF 0x10000
#define CAN_SURFSURFSURF 0x20000
#define SET_MAX_STEP_LENGTH 0x80000
#define CAN_REGION_BORDER 0x100000
#define REGION_PRESENT 0x200000
#define EXTERNAL_SPECIES 0x400000
/* Abstract Molecule Flags */
/* RULES: only one of TYPE_SURF, TYPE_VOL set. */
/* ACT_NEWBIE beats ACT_REACT */
/* Can free up memory when nothing in IN_MASK */
/* Molecule type--surface molecule, 3D molecule, or mask to pick off either */
#define TYPE_SURF 0x001
#define TYPE_VOL 0x002
#define TYPE_MASK 0x003
/* NEWBIE molecules get scheduled before anything else happens to them. */
/* ACT_REACT is set for molecules taking part in unimolecular reaction, or
reaction with a surface */
/* CHANGE molecules have had their rate constant changed */
/* DIFFUSE molecules diffuse (duh!) */
/* CLAMPED molecules diffuse for part of a timestep and don't react with
surfaces */
#define ACT_DIFFUSE 0x008
#define ACT_REACT 0x020
#define ACT_NEWBIE 0x040
#define ACT_CHANGE 0x080
#define ACT_CLAMPED 0x1000
/* Flags telling us which linked lists the molecule appears in. */
#define IN_SCHEDULE 0x100
#define IN_SURFACE 0x200
#define IN_VOLUME 0x400
/* And a mask to pick off all three IN_ flags */
#define IN_MASK 0x700
/* Flags telling us what our counting status is */
#define COUNT_ME 0x800
/* Flag indicating that a molecule is old enough to take the maximum timestep */
#define MATURE_MOLECULE 0x2000
/* End of Abstract Molecule Flags. */
/* Output Report Flags */
/* rxn/mol/region counter report types */
/* Do not set both WORLD and ENCLOSED flags; ENCLOSED applies only to regions */
/* First set reports a single number */
#define REPORT_NOTHING 0
#define REPORT_CONTENTS 1
#define REPORT_RXNS 2
#define REPORT_FRONT_HITS 3
#define REPORT_BACK_HITS 4
#define REPORT_FRONT_CROSSINGS 5
#define REPORT_BACK_CROSSINGS 6
/* Anything >= REPORT_MULTIPLE reports some combination of the above */
#define REPORT_MULTIPLE 7
#define REPORT_ALL_HITS 8
#define REPORT_ALL_CROSSINGS 9
/* Concentration is kind of special. */
#define REPORT_CONCENTRATION 10
#define REPORT_ELAPSED_TIME 11
/* All basic report types can be masked with this value */
#define REPORT_TYPE_MASK 0x0F
/* And finally we have some flags to say whether we're to count over */
/* the entire world or the volume enclosed by a region (set only one) */
#define REPORT_WORLD 0x20
#define REPORT_ENCLOSED 0x40
#define REPORT_TRIGGER 0x80
/* rxn/mol/region counter flags */
/* Only set one of MOL_COUNTER or RXN_COUNTER */
/* Set ENCLOSING_COUNTER if the region is closed and counts inside itself */
#define MOL_COUNTER 1
#define RXN_COUNTER 2
#define ENCLOSING_COUNTER 4
#define TRIG_COUNTER 8
/* Manifold Flags */
enum manifold_flag_t {
MANIFOLD_UNCHECKED, /* Manifold status is unknown */
NOT_MANIFOLD, /* Known to be non-manifold */
IS_MANIFOLD /* Known to be manifold */
};
/* Pathway flags */
// TRANSPARENT means surface reaction between the molecule and TRANSPARENT wall
// REFLECTIVE means surface reaction between the molecule and REFLECTIVE wall
// CLAMP_CONC means surface reaction of CLAMP_CONCENTRATION type
// CLAMP_FLUX means surface reaction of CLAMP_FLUX type
#define PATHW_TRANSP 0x0001
#define PATHW_REFLEC 0x0002
#define PATHW_ABSORP 0x0004
#define PATHW_CLAMP_CONC 0x0008
#define PATHW_CLAMP_FLUX 0x0010
/* Clamp types */
#define CLAMP_TYPE_CONC 0x0000
#define CLAMP_TYPE_FLUX 0x0001
#define BRANCH_X 0x04
#define BRANCH_Y 0x08
#define BRANCH_Z 0x10
/* Direction Values */
#define X_NEG 0
#define X_POS 1
#define Y_NEG 2
#define Y_POS 3
#define Z_NEG 4
#define Z_POS 5
/* Collision types for rays striking surfaces */
/* First a bunch of target types */
/* REDO happens if you can't tell whether you hit or not (hit near an edge, for
* example */
#define COLLIDE_REDO -1
/* MISS means we hit nothing */
#define COLLIDE_MISS 0
/* FRONT and BACK are for surfaces */
#define COLLIDE_FRONT 1
#define COLLIDE_BACK 2
/* MOL_M is collision with a volume molecule */
#define COLLIDE_VOL_M 3
/* SV_?? is for collisions with subvolumes (negative and positive for each
* coordinate axis */
#define COLLIDE_SV_NX 4
#define COLLIDE_SV_PX 5
#define COLLIDE_SV_NY 6
#define COLLIDE_SV_PY 7
#define COLLIDE_SV_NZ 8
#define COLLIDE_SV_PZ 9
/* A mask to pick off all of the collision target types */
#define COLLIDE_MASK 0x0F
/* Bitmasks for each of the major types of collision */
#define COLLIDE_WALL 0x10
#define COLLIDE_VOL 0x20 /* collision between 2 volume molecules */
#define COLLIDE_SUBVOL 0x40
#define COLLIDE_VOL_VOL 0x80 /* collision between 3 volume molecules */
#define COLLIDE_VOL_SURF 0x100 /* collision between 2 volume molecules and 1
surface molecule taken in the order
mol-mol-grid */
#define COLLIDE_SURF_SURF 0x200 /* collision between 1 volume molecule and 2
surface molecules */
#define COLLIDE_SURF 0x400 /* bimolecular collision between moving
volume_molecule and surface_molecule */
/* Size constants */
/* EPS_C is the fractional difference between two values that is considered
* meaningful */
/* GIGANTIC is a distance that is larger than any possible simulation */
/* FOREVER is a time that cannot be reached within one simulation (too many
* timesteps) */
#define EPS_C 1e-12
#define SQRT_EPS_C 1e-6
#define GIGANTIC (double)1e140
#define FOREVER (double)1e20
#define MESH_DISTINCTIVE EPS_C
/* How big will we let the reaction table get? */
/* 0x400000 = 8 million */
#define MAX_RX_HASH 0x400000
/* How big will we let the count-by-region table get? */
/* 0x10000 = 128K */
#define MAX_COUNT_HASH 0x10000
/* mask for count-by-region hash */
#define COUNT_HASHMASK 0xffff
/* What's the upper bound on the number of coarse partitions? */
/* Not used for user-defined partitions */
#define MAX_COARSE_PER_AXIS 16
#define MIN_COARSE_PER_AXIS 6
#define MAX_TARGET_TIMESTEP 1.0e6
#define MIN_TARGET_TIMESTEP 10.0
/* Flags for parser to indicate which axis we are partitioning */
enum partition_axis_t {
X_PARTS, /* X-axis partitions */
Y_PARTS, /* Y-axis partitions */
Z_PARTS /* Z-axis partitions */
};
/* Release Shape Flags */
enum release_shape_t {
SHAPE_UNDEFINED = -1, /* Not specified */
SHAPE_SPHERICAL, /* Volume enclosed by a sphere */
SHAPE_CUBIC, /* Volume enclosed by a cube */
SHAPE_ELLIPTIC, /* Volume enclosed by an ellipsoid */
SHAPE_RECTANGULAR, /* Volume enclosed by a rect. solid */
SHAPE_SPHERICAL_SHELL, /* Surface of a sphere */
SHAPE_REGION, /* Inside/on the surface of an arbitrary region */
SHAPE_LIST /* Individiaul mol. placement by list */
};
/* Region Expression Flags */
/* Boolean set operations for releases on regions */
/* Set only one of NO_OP, UNION, INTERSECTION, SUBTRACTION, INCLUSION */
#define REXP_NO_OP 0x01
#define REXP_UNION 0x02
#define REXP_INTERSECTION 0x04
#define REXP_SUBTRACTION 0x08
#define REXP_MASK 0x1F
#define REXP_LEFT_REGION 0x20
#define REXP_RIGHT_REGION 0x40
/* Distance in length units to search for a new site for a surface molecule */
/* after checkpointing. Current site might be full, so a value >1 is */
/* advisable. Being a little generous here. */
#define CHKPT_GRID_TOLERANCE 2.0
/* Constants for garbage collection of defunct molecules */
/* (those that were consumed when hit by another molecule) */
#define MIN_DEFUNCT_FOR_GC 1024
#define MAX_DEFUNCT_FRAC 0.2
/* Constants for notification levels */
enum notify_level_t {
NOTIFY_NONE, /* no output */
NOTIFY_BRIEF, /* give a brief description (only used for a few types) */
NOTIFY_FULL, /* give a (possibly verbose) description */
};
/* Constants for warning levels */
enum warn_level_t {
WARN_COPE, /* do something sensible and continue silently */
WARN_WARN, /* do something sensible but emit a warning message */
WARN_ERROR /* treat the warning and an error and stop */
};
/* Overwrite Policy Flags */
/* Flags for different types of file output */
enum overwrite_policy_t {
FILE_UNDEFINED, /* not specified */
FILE_OVERWRITE, /* always overwrite, even after a checkpoint */
FILE_SUBSTITUTE, /* DEFAULT: append to entries earlier in time than "now", but
overwrite later entries */
FILE_APPEND, /* always append to file, even on a new run */
FILE_APPEND_HEADER, /* always append to file, including the header, even on a
new run */
FILE_CREATE, /* always create the file, or give an error if the file already
exists (to prevent overwriting) */
};
/* Output Expression Flags */
/* INT means that this expression is an integer */
/* DBL means that this expression is a double */
/* TRIG means that this expression will actually be handled by a triggering
* event */
/* MASK lets us pick off the INT/DBL/TRIG flags */
/* CONST means that this expression will not change during runtime (compute at
* parse time and store) */
#define OEXPR_TYPE_UNDEF 0x0
#define OEXPR_TYPE_INT 0x1
#define OEXPR_TYPE_DBL 0x2
#define OEXPR_TYPE_TRIG 0x3
#define OEXPR_TYPE_MASK 0x7
#define OEXPR_TYPE_CONST 0x8
/* Same things for sub-expressions to the left, plus */
/* REQUEST means that the expression contains a request for a count statement,
* not real count data yet (needs to be initialized) */
/* OEXPR means that the expression is itself an expression that needs to be
* evaluated (not data) */
#define OEXPR_LEFT_INT 0x10
#define OEXPR_LEFT_DBL 0x20
#define OEXPR_LEFT_TRIG 0x30
#define OEXPR_LEFT_REQUEST 0x40
#define OEXPR_LEFT_OEXPR 0x50
#define OEXPR_LEFT_MASK 0x70
#define OEXPR_LEFT_CONST 0x80
/* Same things again for sub-expressions to the right */
#define OEXPR_RIGHT_INT 0x100
#define OEXPR_RIGHT_DBL 0x200
#define OEXPR_RIGHT_TRIG 0x300
#define OEXPR_RIGHT_REQUEST 0x400
#define OEXPR_RIGHT_OEXPR 0x500
#define OEXPR_RIGHT_MASK 0x700
#define OEXPR_RIGHT_CONST 0x800
/* Magic value to indicate that a release pattern is actually a reaction */
/* Should be some number not between 0 and 1 that is also not -1 */
#define MAGIC_PATTERN_PROBABILITY 1.101001000100001
/* Output Trigger Flags */
/* Don't set both RXN and HIT flags */
#define TRIG_IS_RXN 0x1
#define TRIG_IS_HIT 0x2
/* Range of molecule indices used to avoid self-reactions for 3D unbinding */
#define DISSOCIATION_MAX -1000
#define DISSOCIATION_MIN -1000000000
/* Checkpoint related flags */
enum checkpoint_request_type_t {
CHKPT_NOT_REQUESTED, /* No CP requested */
CHKPT_SIGNAL_CONT, /* CP requested via SIGUSR* signal, continue after CP */
CHKPT_SIGNAL_EXIT, /* CP requested via SIGUSR* signal, exit after CP */
CHKPT_ALARM_CONT, /* CP requested via "alarm" signal, continue after CP */
CHKPT_ALARM_EXIT, /* CP requested via "alarm" signal, exit after CP */
CHKPT_ITERATIONS_CONT, /* CP requested due to iteration count, continue after
CP */
CHKPT_ITERATIONS_EXIT, // CP requested due to iteration count, exit after CP
};
/*********************************************************/
/** Constants used in MCell3 brought over from MCell2 **/
/*********************************************************/
/* 1/2^32 */
#define R_UINT_MAX 2.3283064365386962890625e-10
#define ROUND_UP 0.5
/* Placement Type Flags */
/* Place either a certain density or an exact number of surface molecules */
#define SURFMOLDENS 0
#define SURFMOLNUM 1
/* Viz output options */
#define VIZ_ALL_MOLECULES 0x01
#define VIZ_MOLECULES_STATES 0x02
#define VIZ_SURFACE_STATES 0x04
/************************************************************/
/** Old constants copied from MCell2, some may be broken **/
/************************************************************/
/* maximum allowed nesting level of INCLUDE_FILE statements in MDL */
#define MAX_INCLUDE_DEPTH 16
/* default size of output count buffers */
#define COUNTBUFFERSIZE 10000
/* Symbol types */
/* Data types for items in MDL parser symbol tables. */
enum symbol_type_t {
RX, /* chemical reaction */
RXPN, /* name of chemical reaction */
MOL, /* molecule or surface class type (i.e. species) */
MOL_SS, /* spatially structured molecule */
MOL_COMP_SS, /* spatially structured component of molecule */
OBJ, /* meta-object */
RPAT, /* release pattern */
REG, /* object region */
DBL, /* double (numeric variable in MDL file) */
STR, /* string (text variable in MDL file) */
ARRAY, /* numeric array (array variable in MDL file) */
FSTRM, /* file stream type for "C"-style file-io in MDL file */
TMP, /* temporary place-holder type for assignment statements */
COUNT_OBJ_PTR, /* a pointer to an output block of given name */
VOID_PTR, /* a void pointer to be managed by code */
};
#define MOL_COMP_SS_SYM_TABLE_SIZE 8
/* Count column data types */
enum count_type_t {
COUNT_UNSET = -1, /* no value specified */
COUNT_DBL, /* double */
COUNT_INT, /* integer type */
COUNT_TRIG_STRUCT, /* trigger_struct data type (for TRIGGER statements) */
};
#define COINCIDENT 0
#define XYZ 1
#define XYZA 2
#define XYZVA 3
/* Object Type Flags */
enum object_type_t {
META_OBJ, /* Meta-object: aggregation of other objects */
BOX_OBJ, /* Box object: Polygonalized cuboid */
POLY_OBJ, /* Polygon list object: list of arbitrary triangles */
REL_SITE_OBJ, /* Release site object */
VOXEL_OBJ, /* Voxel object (so-far unused) */
};
// Used to reference a list of all the elements (i.e. ALL_ELEMENTS)
#define ALL_SIDES INT_MAX
/* Viz state values */
#define EXCLUDE_OBJ INT_MIN /*object is not visualized */
#define INCLUDE_OBJ INT_MAX /*object is visualized but state value is not set*/
/* Data Output Timing Type */
/* Reaction and Viz data output timing */
enum output_timer_type_t {
OUTPUT_BY_STEP,
OUTPUT_BY_TIME_LIST,
OUTPUT_BY_ITERATION_LIST,
};
/* Visualization Frame Data Type */
/* Used to select type of data to include in viz output files */
enum viz_frame_type_t {
MOL_POS,
MOL_ORIENT,
ALL_MOL_DATA,
NUM_FRAME_TYPES,
};
/* Release Number Flags */
enum release_number_type_t {
CONSTNUM,
GAUSSNUM,
VOLNUM,
CCNNUM,
DENSITYNUM
};
/******
Structure used for managing graph information obtained from NFSim or
calculated from data obtained from nfsim
****/
struct graph_data {
char* graph_pattern;
char* graph_compartment;
unsigned long graph_pattern_hash;
double graph_diffusion;
double space_step;
double time_step;
int flags;
};
/****
structure to keep information about external reactions (from nfsim)
*/
struct external_reaction_datastruct{
char* reaction_name;
int resample;
int reactants;
int products;
};
/**********************************************/
/** New/reworked structures used in MCell3 **/
/**********************************************/
typedef unsigned char byte;
/* If you don't include sys/types.h, #define SYS_TYPES_NOT_LOADED so */
/* you get the u_short/int/long set of types */
#ifdef SYS_TYPES_NOT_LOADED
typedef unsigned short u_short;
typedef unsigned int u_int;
typedef unsigned long u_long;
#endif
/* Linked list used to separate molecules by species */
struct per_species_list {
struct per_species_list *next; /* pointer to next p-s-l */
struct species *properties; /* species for items in this bin */
struct volume_molecule *head; /* linked list of mols */
//JJT: nfsim related fields
struct graph_data* graph_data;
};
/* Properties of one type of molecule or surface */
struct species {
u_int species_id; /* Unique ID for this species */
u_int chkpt_species_id; /* Unique ID for this species from the
checkpoint file */
u_int hashval; /* Hash value (may be nonunique) */
struct sym_entry *sym; /* Symbol table entry (name) */
struct sm_dat *sm_dat_head; /* If IS_SURFACE this points to head of effector
data list associated with surface class */
u_int population; /* How many of this species exist? */
double D; /* Diffusion constant */
double space_step; /* Characteristic step length */
double time_step; /* Minimum (maximum?) sensible timestep */
double max_step_length; /* maximum allowed random walk step */
u_int flags; /* Species Flags: Vol Molecule? Surface Molecule?
Surface Class? Counting stuff, etc... */
long long n_deceased; /* Total number that have been destroyed. */
double cum_lifetime_seconds; /* Seconds lived by now-destroyed molecules */
/* if species s a surface_class (IS_SURFACE) below there are linked lists of
* molecule names/orientations that may be present in special reactions for
* this surface class */
struct name_orient *refl_mols; // names of the mols that REFLECT from surface
struct name_orient *
transp_mols; /* names of the mols that are TRANSPARENT for surface */
struct name_orient *absorb_mols; // names of the mols that ABSORB at surface
struct name_orient *clamp_mols; /* names of mols that CLAMP_CONC or
CLAMP_FLUX at surface */
// mcell4 - we need to store information on whether the user set custom time or space step
// 0 - not set, < 0 - custom space step, > 0 custom time step
double custom_time_step_from_mdl;
};
/* All pathways leading away from a given intermediate */
struct rxn {
struct rxn *next; /* next node in the reaction linked list where each node
contains only pathways with equivalent geometry */
struct sym_entry *sym; /* Ptr to symbol table entry for this rxn */
u_int n_reactants; /* How many reactants? (At least 1.) */
int n_pathways; /* How many pathways lead away? (Negative = special
reaction, i.e. transparent etc...) */
double *cum_probs; /* Cumulative probabilities for (entering) all pathways */
double max_fixed_p; /* Maximum 'p' for region of p-space for all
non-cooperative pathways */
double min_noreaction_p; /* Minimum 'p' for region of p-space which is always
in the non-reacting "pathway". (note that
cooperativity may mean that some values of p less
than this still do not produce a reaction) */
double pb_factor; /* Conversion factor from rxn rate to rxn probability (used
for cooperativity) */
int *product_idx_aux; /* Number of unique players in each pathway. Used for on-the fly calculation of
product_idx indexes */
u_int *product_idx; /* Index of 1st player for products of each pathway */
struct species **players; /* Identities of reactants/products */
/* this information is kept in a separate array because with nfsim we dont know ahead of time
how many paths/products per path are there, we only know when it fires*/
struct species ***nfsim_players; /* a matrix of the nfsim elements associated with each path */
short *geometries; /* Geometries of reactants/products */
short **nfsim_geometries; /* geometries of the nfsim geometries associated with each path */
long long n_occurred; /* How many times has this reaction occurred? */
double n_skipped; /* How many reactions were skipped due to probability
overflow? */
struct t_func *
prob_t; /* List of probabilities changing over time, by pathway */
struct pathway *pathway_head; /* List of pathways built at parse-time */
struct pathway_info *info; /* Counts and names for each pathway */
//char** external_reaction_names; /* Stores reaction results stored from an external program (like nfsim)*/
struct external_reaction_datastruct* external_reaction_data; /* Stores reaction results stored from an external program (like nfsim)*/
struct graph_data** reactant_graph_data; /* stores the graph patterns associated with the reactants for every path */
struct graph_data*** product_graph_data; /* Stores the graph patterns associated with our products for each path*/
double (*get_reactant_diffusion)(struct rxn*, int); /* returns the diffusion value associated with its reactants*/
double (*get_reactant_time_step)(struct rxn*, int); /* returns the diffusion value associated with its reactants*/
double (*get_reactant_space_step)(struct rxn*, int); /* returns the diffusion value associated with its reactants*/
};
/* User-defined name of a reaction pathway */
struct rxn_pathname {
struct sym_entry *sym; /* Ptr to symbol table entry for this rxn name */
u_int hashval; /* Hash value for counting named rxns on regions */
u_int path_num; /* Pathway number in rxn */
struct rxn *rx; /* The rxn associated with this name */
struct magic_list *magic; /* A list of stuff that magically happens when the
reaction happens */
};
/* Parse-time structure for reaction pathways */
/* Everything except pathname can be deallocated after init_reactions */
struct pathway {
struct pathway *next; /* Next pathway for this reaction */
struct rxn_pathname *pathname; /* Data for named reaction pathway or NULL */
struct species *reactant1; /* First reactant in reaction pathway */
struct species *reactant2; /* Second reactant (NULL if none) */
struct species *reactant3; /* Third reactant (NULL if none) */
double km; /* Rate constant */
double clamp_concentration; /* Concentration clamp constant, used only by MCell3->4 converter */
char *km_filename; /* Filename for time-varying rates */
short orientation1; /* Orientation of first reactant */
short orientation2; /* Orientation of second reactant */
short orientation3; /* Orientation of third reactant */
struct product *product_head; /* Linked lists of species created */
char *prod_signature; /* string created from the names of products
put in alphabetical order */
short flags; /* flags describing special reactions -
REFLECTIVE, TRANSPARENT, CLAMP_CONCENTRATION */
};
/* Parse-time structure for products of reaction pathways */
struct product {
struct product *next;
struct species *prod; /* Molecule type to be created */
short orientation; /* Orientation to place molecule */
};
/* Run-time info for each pathway */
/* Always do basic counts--do more sophisticated stuff if pathname!=NULL */
struct pathway_info {
double count; /* How many times the pathway has been taken */
struct rxn_pathname *pathname; /* The name of the pathway or NULL */
};
/* Piecewise constant function for time-varying reaction rates */
struct t_func {
struct t_func *next;
double time; /* Time to switch to next rate */
double value; /* Current rate */
double value_from_file; /* MCell4, rate value that was loaded from the file*/
int path; /* Which rxn pathway is this for? */
};
// Used for dynamic geometry.
struct molecule_info {
struct abstract_molecule *molecule;
struct string_buffer *reg_names; /* Region names */
struct string_buffer *mesh_names; /* Mesh names that molec is nested in */
struct vector3 pos; /* Position in space */
short orient; /* Which way do we point? */
};
/* periodic_image tracks the periodic box a molecule is in in the presence
* of periodic boundary conditions along one or several coordinate axes.
* The central/starting box is at {0,0,0} */
struct periodic_image {
int16_t x;
int16_t y;
int16_t z;
};
/* Abstract structure that starts all molecule structures */
/* Used to make C structs act like C++ objects */
struct abstract_molecule {
struct abstract_molecule *next; /* Next molecule in scheduling queue */
double t; /* Scheduling time. */
double t2; /* Time of next unimolecular reaction */
short flags; /* Abstract Molecule Flags: Who am I, what am I doing, etc. */
struct species *properties; /* What type of molecule are we? */
struct mem_helper *birthplace; /* What was I allocated from? */
double birthday; /* Real time at which this particle was born */
u_long id; /* unique identifier of this molecule */
struct periodic_image* periodic_box; /* track the periodic box a molecule is in */
/* structs used by the nfsim integration */
struct graph_data* graph_data; /* nfsim graph structure data */
u_int (*get_flags)(void *); /* returns the reactivity flags associated with this particle */
double (*get_diffusion)(void *); /* returns the diffusion value */
double (*get_time_step)(void *); /* function pointer to a method that returns the time step */
double (*get_space_step)(void *); /* function pointer to a method that returns the space step */
/* end structs used by the nfsim integration */
char *mesh_name; // Name of mesh that molecule is either in
// (volume molecule) or on (surface molecule)
};
/* Volume molecules: freely diffusing or fixed in solution */
struct volume_molecule {
struct abstract_molecule *next;
double t;
double t2;
short flags;
struct species *properties;
struct mem_helper *birthplace;
double birthday;
u_long id;
struct periodic_image* periodic_box; /* track the periodic box a molecule is in */
struct graph_data* graph_data;
u_int (*get_flags)(void *); /* returns the reactivity flags associated with this particle */
double (*get_diffusion)(void *); /* returns the diffusion value */
double (*get_time_step)(void *); /* returns the diffusion value */
double (*get_space_step)(void *); /* returns the diffusion value */
char *mesh_name; // Name of mesh that the molecule is in
struct vector3 pos; /* Position in space */
struct subvolume *subvol; /* Partition we are in */
struct wall *previous_wall; /* Wall we were released from */
int index; /* Index on that wall (don't rebind) */
struct volume_molecule **prev_v; /* Previous molecule in this subvolume */
struct volume_molecule *next_v; /* Next molecule in this subvolume */
};
/* Fixed molecule on a grid on a surface */
struct surface_molecule {
struct abstract_molecule *next;
double t;
double t2;
short flags;
struct species *properties;
struct mem_helper *birthplace;
double birthday;
u_long id;
struct periodic_image* periodic_box; /* track the periodic box a molecule is in */
struct graph_data* graph_data;
u_int (*get_flags)(void *); /* returns the reactivity flags associated with this particle */
double (*get_diffusion)(void *); /* returns the diffusion value */
double (*get_time_step)(void *); /* returns the diffusion value */
double (*get_space_step)(void *); /* returns the diffusion value */
char *mesh_name; // Name of mesh that the molecule is on
unsigned int grid_index; /* Which gridpoint do we occupy? */
short orient; /* Which way do we point? */
struct surface_grid *grid; /* Our grid (which tells us our surface) */
struct vector2 s_pos; /* Where are we in surface coordinates? */
};
struct mol_ss {
struct sym_entry *sym;
// struct sym_table_head *mol_comp_ss_sym_table;
struct mol_comp_ss *mol_comp_ss_head;
struct mol_comp_ss *mol_comp_ss_tail;
};
struct mol_comp_ss {
// struct vector3 loc;
// struct vector3 axis;
// double angle;
// struct sym_entry *sym;
char *name;
byte spatial_type;
double loc_x;
double loc_y;
double loc_z;
double rot_axis_x;
double rot_axis_y;
double rot_axis_z;
double rot_angle;
double t_matrix[4][4];
struct mol_comp_ss *next;
};
/* Used to transform coordinates of surface molecules diffusing between
* adjacent walls */
struct edge {
struct wall *forward; /* For which wall is this a forwards transform? */
struct wall *backward; /* For which wall is this a reverse transform? */
struct vector2 translate; /* Translation vector between coordinate systems */
double cos_theta; /* Cosine of angle between coordinate systems */
double sin_theta; /* Sine of angle between coordinate systems */
double length; /* Length of the shared edge */
double length_1; /* Reciprocal of length of shared edge */
// for mcell4 only
int edge_num_used_for_init;
};
struct wall {
struct wall *next; /* Next wall in the universe */
struct surf_class_list *
surf_class_head; /* linked list of surface classes for this wall (multiple
surface classes may come from the overlapping regions */
int num_surf_classes; /* number of attached surface classes */
int side; /* index of this wall in its parent object */
struct vector3 *vert[3]; /* Array of pointers to vertices */
double uv_vert1_u; /* Surface u-coord of 2nd corner (v=0) */
struct vector2 uv_vert2; /* Surface coords of third corner */
struct edge *edges[3]; /* Array of pointers to each edge. */
struct wall *nb_walls[3]; /* Array of pointers to walls that share an edge*/
double area; /* Area of this element */
struct vector3 normal; /* Normal vector for this wall */
struct vector3 unit_u; /* U basis vector for this wall */
struct vector3 unit_v; /* V basis vector for this wall */
double d; /* Distance to origin (point normal form) */
struct surface_grid *grid; /* Grid of effectors for this wall */
u_short flags; /* Count Flags: flags for whether and what we need to count */
struct geom_object *parent_object; /* The object we are a part of */
struct storage *birthplace; /* Where we live in memory */
struct region_list *counting_regions; /* Counted-on regions containing this
wall */
};
/* Linked list of walls (for subvolumes) */
struct wall_list {
struct wall_list *next; /* The next entry in the list */
struct wall *this_wall; /* The wall in this entry */
};
// Connection list used when creating geometry
struct element_connection_list {
struct element_connection_list *next;
int n_verts;
int *indices;
};
/* A linked list used to store the coordinates of vertices and the
corresponding normal vectors */
struct vertex_list {
struct vector3 *vertex; /* pointer to one polygon vertex */
struct vertex_list *next; /* pointer to next vertex list */
};
/* Grid over a surface containing surface_molecules */
struct surface_grid {
int n; /* Number of slots along each axis */
double inv_strip_wid; /* Reciprocal of the width of one strip */
double vert2_slope; /* Slope from vertex 0 to vertex 2 */
double fullslope; /* Slope of full width of triangle */
struct vector2 vert0; /* Projection of vertex zero onto unit_u and unit_v of
wall */
double binding_factor; /* Binding probability correction factor for surface
area */
u_int n_tiles; /* Number of tiles in effector grid (triangle: grid_size^2,
rectangle: 2*grid_size^2) */
u_int n_occupied; /* Number of tiles occupied by surface_molecules */
/* Array of pointers to surface_molecule_list for each tile */
struct surface_molecule_list **sm_list;
struct subvolume *subvol; /* Best match for which subvolume we're in */
struct wall *surface; /* The wall that we are in */
};
/* 3D vector of integers */
struct int3D {
int x;
int y;
int z;
};
/* Point in space that will tell us which compartments we're in
as determined by tracing from infinity */
struct waypoint {
struct vector3 loc; /* This is where the waypoint is */
struct region_list *regions; /* We are inside these regions */
struct region_list *
antiregions; /* We are outside of (but hit) these regions */
};
/* Contains local memory and scheduler for molecules, walls, wall_lists, etc. */
struct storage {
struct mem_helper *list; /* Wall lists */
struct mem_helper *mol; /* Molecules */
struct mem_helper *smol; /* Surface molecules */
struct mem_helper *face; /* Walls */
struct mem_helper *join; /* Edges */
struct mem_helper *grids; /* Effector grids */
struct mem_helper *coll; /* Collision list */
struct mem_helper *sp_coll; /* Collision list - helps in trimolecular
reactions*/
struct mem_helper *tri_coll; /* Collision list for trimolecular collisions */
struct mem_helper *regl; /* Region lists */
struct mem_helper *exdv; /* Vertex lists for exact interaction disk area */
struct mem_helper *pslv; /* Per-species-lists for vol mols */
struct wall *wall_head; /* Locally stored walls */
int wall_count; /* How many local walls? */
int vert_count; /* How many vertices? */
struct schedule_helper *timer; /* Local scheduler */
double current_time; /* Local time */
double max_timestep; /* Local maximum timestep */
};
/* Linked list of storage areas. */
struct storage_list {
struct storage_list *next;
struct storage *store;
};
/* Walls and molecules in a spatial subvolume */
struct subvolume {
struct wall_list *wall_head; /* Head of linked list of intersecting walls */
struct pointer_hash mol_by_species; /* table of species->molecule list */
struct per_species_list *species_head;
int mol_count; /* How many molecules are here? */
struct int3D llf; /* Indices of left lower front corner */
struct int3D urb; /* Indices of upper right back corner */
short world_edge; /* Direction Bit Flags that are set for SSVs at edge of
world */
struct storage *local_storage; /* Local memory and scheduler */
};
/* Count data specific to named reaction pathways */
struct rxn_counter_data {
double n_rxn_at; /* # rxn occurrance on surface */
double n_rxn_enclosed; /* # rxn occurrance inside closed region */
};
/* Count data specific to molecules */
struct move_counter_data {
double front_hits; /* # hits on front of region (normal up) */
double back_hits; /* # hits on back of region */
double front_to_back; /* # crossings from front to back */
double back_to_front; /* # crossings from back to front */
double scaled_hits; /* To determine integrated concentration */
int n_at; /* # molecules on region surface */
int n_enclosed; /* # molecules inside closed region */
};
/* Counter data specific to trigger events */
struct trig_counter_data {
double t_event; /* Event time (exact) */
struct vector3 loc; /* Real position of event */
short orient; // For MOL_COUNTER: molecule orientation
struct trigger_request *listeners; /* Places waiting to be notified */
};
/* List of output items that need to know about this specific trigger event */
struct trigger_request {
struct trigger_request *next; /* Next request */
struct output_request *ear; /* Who wants to hear about the trigger */
};
/* Shared memory for appropriate counts */
union counter_data {
struct rxn_counter_data rx;
struct move_counter_data move;
struct trig_counter_data trig;
};
/* Struct to count rxns or molecules within regions (where "within" includes */
/* on the inside of a fully closed surface) */
struct counter {
struct counter *next;
byte counter_type; /* Counter Type Flags (MOL_COUNTER etc.) */
struct region *reg_type; /* Region we are counting on */
void *target; /* Mol or rxn pathname we're counting (as indicated by
counter_type) */
short orientation; /* requested surface molecule orientation */
struct periodic_image *periodic_box; /* periodic box we are counting in; NULL
means that we don't care and count everywhere */
union counter_data data; /* data for the count:
reference data.move for move counter
reference data.rx for rxn counter
reference data.trig for trigger */
};
enum magic_types {
magic_undefined,
magic_release
};
struct magic_list {
struct magic_list *next;
void *data;
enum magic_types type;
};
struct reaction_flags {
/* flags that tells whether reactions of certain types are present in the
simulation (used for the molecule collision report, also see above
the corresponding counters) */
int vol_vol_reaction_flag;
int vol_surf_reaction_flag;
int surf_surf_reaction_flag;
int vol_wall_reaction_flag;
int vol_vol_vol_reaction_flag;
int vol_vol_surf_reaction_flag;
int vol_surf_surf_reaction_flag;
int surf_surf_surf_reaction_flag;
};
/* All data about the world */
struct volume {
long int dump_level; /* Requests additional text output. 0 for no additional, >0 implies more. */
long int viz_options; /* Defines requested additional viz output options. */
double bond_angle; /* Defines the default bond rotation angle between molecules. Default is 0. */
// These are only used with dynamic geometry
struct dyngeom_parse_vars *dg_parse;
char *dynamic_geometry_filename;
struct molecule_info **all_molecules;
int num_all_molecules;
struct string_buffer *names_to_ignore;
/* Coarse partitions are input by the user */
/* They may also be generated automagically */
/* They mark the positions of initial partition boundaries */
int nx_parts; /* Number of coarse X partition boundaries */
int ny_parts; /* Number of coarse Y partition boundaries */
int nz_parts; /* Number of coarse Z partition boundaries */
double *x_partitions; /* Coarse X partition boundaries */
double *y_partitions; /* Coarse Y partition boundaries */
double *z_partitions; /* Coarse Z partition boundaries */
int mem_part_x; /* Granularity of memory-partition binning for the X-axis */
int mem_part_y; /* Granularity of memory-partition binning for the Y-axis */
int mem_part_z; /* Granularity of memory-partition binning for the Z-axis */
int mem_part_pool; /* Scaling factor for sizes of memory pools in each
storage. */
/* Fine partitions are intended to allow subdivision of coarse partitions */
/* Subdivision is not yet implemented */
int n_fineparts; /* Number of fine partition boundaries */
double *x_fineparts; /* Fine X partition boundaries */
double *y_fineparts; /* Fine Y partition boundaries */
double *z_fineparts; /* Fine Z partition boundaries */
bool periodic_traditional;
int n_waypoints; /* How many waypoints (one per subvol) */
struct waypoint *waypoints; /* Waypoints contain fully-closed region
information */
byte place_waypoints_flag; /* Used to save memory if waypoints not needed */
int n_subvols; /* How many coarse subvolumes? */
struct subvolume *subvol; /* Array containing all subvolumes */
int n_walls; /* Total number of walls */
int n_verts; /* Total number of vertices */
struct vector3 *all_vertices; /* Central repository of vertices with a
partial order imposed by natural ordering
of "storages" */
/* Array of linked lists of walls using a vertex (has the size of
* "all_vertices" array */
struct wall_list **walls_using_vertex;
int rx_hashsize; /* How many slots in our reaction hash table? */
int n_reactions; /* How many reactions are there, total? */
struct rxn **reaction_hash; /* A hash table of all reactions. */
struct mem_helper *tv_rxn_mem; /* Memory to store time-varying reactions */
int count_hashmask; /* Mask for looking up count hash table */
struct counter **count_hash; /* Count hash table */
struct schedule_helper *count_scheduler; // When to generate reaction output
struct sym_table_head *counter_by_name;
struct schedule_helper *volume_output_scheduler; /* When to generate volume
output */
int n_species; /* How many different species (molecules)? */
//NFSim stats
int n_NFSimSpecies; /* number of graph patterns encountered during the NFSim simulation */
int n_NFSimReactions; /* number of reaction rules discovered through an NFSim simulation */
int n_NFSimPReactions; /* number of potential reactions found in the reaction network (not necessarely triggered) */
struct species **species_list; /* Array of all species (molecules). */
// This is used to skip over certain sections in the parser when using
// dynamic geometries.
int dynamic_geometry_flag;
int disable_polygon_objects;
// List of all the dynamic geometry events that need to be scheduled
struct dg_time_filename *dynamic_geometry_head;
// Memory to store time and MDL names for dynamic geometry
struct mem_helper *dynamic_geometry_events_mem;
// Scheduler for dynamic geometry
struct schedule_helper *dynamic_geometry_scheduler;
struct schedule_helper *releaser; /* Scheduler for release events */
struct mem_helper *storage_allocator; /* Memory for storage list */
struct storage_list *storage_head; /* Linked list of all local
memory/schedulers */
u_long current_mol_id; /* next unique molecule id to use*/
double speed_limit; // How far can the fastest particle get in one timestep?
struct sym_table_head *fstream_sym_table; /* Global MDL file stream symbol
hash table */
struct sym_table_head *var_sym_table; /* Global MDL variables symbol hash
table */
struct sym_table_head *rxn_sym_table; /* RXN symbol hash table */
struct sym_table_head *obj_sym_table; /* Objects symbol hash table */
struct sym_table_head *reg_sym_table; /* Regions symbol hash table */
struct sym_table_head *mol_sym_table; /* Molecule type symbol hash table */
struct sym_table_head *rpat_sym_table; /* Release pattern hash table */
struct sym_table_head *rxpn_sym_table; /* Named reaction pathway hash table */
struct sym_table_head *mol_ss_sym_table; /* Spatially structured molecule symbol hash table */
struct geom_object *root_object; /* Root of the object template tree */
struct geom_object *root_instance; /* Root of the instantiated object tree */
struct geom_object *periodic_box_obj;
struct release_pattern *default_release_pattern; /* release once at t=0 */
struct volume_output_item *volume_output_head; /* List of all volume data
output items */
struct output_block *
output_block_head; /* Global list of reaction data output blocks */
struct output_request *output_request_head; /* Global list linking COUNT
statements to internal
variables */
struct mem_helper *oexpr_mem; /* Memory to store output_expressions */
struct mem_helper *outp_request_mem; /* Memory to store output_requests */
struct mem_helper *counter_mem; /* Memory to store counters (for counting
molecules/reactions on regions) */
struct mem_helper *
trig_request_mem; /* Memory to store listeners for trigger events */
struct mem_helper *magic_mem; /* Memory used to store magic lists for
reaction-triggered releases and such */
double elapsed_time; /* Used for concentration measurement */
/* Visualization state */
struct viz_output_block *viz_blocks; /* VIZ_OUTPUT blocks from file */
struct species *all_mols; /* Refers to ALL_MOLECULES keyword */
struct species *all_volume_mols; // Refers to ALL_VOLUME_MOLECULES keyword
struct species *all_surface_mols; // Refers to ALL_SURFACE_MOLECULES keyword
double time_unit; /* Duration of one global time step in real time */
/* Used to convert between real time and internal time */
double time_step_max; /* Maximum internal time that a molecule may diffuse */
double
grid_density; /* Density of grid for surface molecules, number per um^2 */
double length_unit; /* Internal unit of distance, 1/sqrt(grid_density), in
microns */
double r_length_unit; /* Reciprocal of length_unit to avoid division */
double rx_radius_3d; /* Interaction radius for reactions between volume
molecules */
double space_step; /* User-supplied desired average diffusion distance for
volume molecules */
double *r_step; /* Lookup table of 3D diffusion step lengths */
double *d_step; /* Lookup table of 3D diffusion direction vectors */
double *r_step_surface; /* Lookup table of 2D diffusion step lengths */
double *r_step_release; /* Lookup table of diffusion lengths for 3D release */
u_int radial_subdivisions; /* Size of 2D and 3D step length lookup tables */
u_int radial_directions; /* Requested size of 3D direction lookup table */
u_int num_directions; /* Actual size of 3D direction lookup table */
int directions_mask; /* Mask to obtain RNG bits for direction lookup */
int fully_random; /* If set, generate directions with trig functions instead
of lookup table */
int dissociation_index; /* Used to keep 3D products from reacting with each
other too soon */
long long chkpt_iterations; /* Number of iterations to advance before
checkpointing */
u_int chkpt_init; /* Set if this is the initial run of a simulation with no
previous checkpoints */
u_int
chkpt_flag; /* Set if there are any CHECKPOINT statements in "mdl" file */
u_int chkpt_seq_num; /* Number of current run in checkpoint sequence */
int keep_chkpts; /* flag to indicate if checkpoints should be kept */
char *chkpt_infile; /* Name of checkpoint file to read from */
char *chkpt_outfile; /* Name of checkpoint file to write to */
u_int chkpt_byte_order_mismatch; /* Flag that defines whether mismatch in
byte order exists between the saved
checkpoint file and the machine reading
it */
double chkpt_start_time_seconds; /* start of the simulation time (in sec)
for new checkpoint */
double current_time_seconds; /* current simulation time in seconds */
/* simulation start time (in seconds) or time of most recent checkpoint */
double simulation_start_seconds;
long long diffusion_number; /* Total number of times molecules have had their
positions updated */
double diffusion_cumtime; /* Total time spent diffusing by all molecules */
long long ray_voxel_tests; /* How many ray-subvolume intersection tests have
we performed */
long long ray_polygon_tests; /* How many ray-polygon intersection tests have
we performed */
long long ray_polygon_colls; /* How many ray-polygon intersections have
occured */
long long dyngeom_molec_displacements; /* Total number of dynamic geometry
molecule displacements */
/* below "vol" means volume molecule, "surf" means surface molecule */
long long vol_vol_colls; /* How many vol-vol collisions have occured */
long long vol_surf_colls; /* How many vol-surf collisions have occured */
long long surf_surf_colls; /* How many surf-surf collisions have occured */
long long vol_wall_colls; /* How many vol-wall collisions have occured */
long long vol_vol_vol_colls; // How many vol-vol-vol collisions have occured
long long
vol_vol_surf_colls; /* How many vol-vol-surf collisions have occured */
long long vol_surf_surf_colls; /* How many vol-surf-surf collisions have
occured */
long long surf_surf_surf_colls; /* How many surf-surf-surf collisions have
occured */
long long diffuse_3d_calls;
struct vector3 bb_llf; /* llf corner of world bounding box */
struct vector3 bb_urb; /* urb corner of world bounding box */
struct rng_state *rng; /* State of the random number generator (currently
isaac64) */
u_int init_seed; /* Initial seed value for random number generator */
long long current_iterations; /* How many iterations have been run so far */
// Starting iteration number for current run or iteration of most recent
// checkpoint
long long start_iterations;
struct timeval last_timing_time; /* time and iteration of last timing event */
long long last_timing_iteration; /* during the main run_iteration loop */
int procnum; /* Processor number for a parallel run */
int quiet_flag; /* Quiet mode */
int with_checks_flag; /* Check geometry for overlapped walls? */
struct mem_helper *coll_mem; /* Collision list */
struct mem_helper *sp_coll_mem; /* Collision list (trimol) */
struct mem_helper *tri_coll_mem; /* Collision list (trimol) */
struct mem_helper *exdv_mem; // Vertex lists for exact interaction disk area
/* Current version number. Format is "3.XX.YY" where XX is major release
* number (for new features) and YY is minor release number (for patches) */
char const *mcell_version;
int use_expanded_list; /* If set, check neighboring subvolumes for mol-mol
interactions */
int randomize_smol_pos; /* If set, always place surface molecule at random
location instead of center of grid */
double vacancy_search_dist2; /* Square of distance to search for free grid
location to place surface product */
byte surface_reversibility; /* If set, match unbinding diffusion distribution
to binding distribution at surface */
byte volume_reversibility; /* If set, match unbinding diffusion distribution
to binding distribution in volume */
/* If set to NEAREST_TRIANGLE, molecules are moved to a random location
* slightly offset from the enclosing wall. If set to NEAREST_POINT, then
* they are moved to the closest point on that wall (still slightly offset).
* */
int dynamic_geometry_molecule_placement;
/* MCell startup command line arguments */
u_int seed_seq; /* Seed for random number generator */
long long iterations; /* How many iterations to run */
unsigned long log_freq; /* Interval between simulation progress reports,
default scales as sqrt(iterations) */
char *mdl_infile_name; /* Name of MDL file specified on command line */
char const *curr_file; /* Name of MDL file currently being parsed */
// XXX: Why do we allocate this on the heap rather than including it inline?
struct notifications *notify; /* Notification/warning/output flags */
struct clamp_data *clamp_list; /* List of objects at which volume
molecule concentration or flux
should be clamped */
/* Flags for asynchronously-triggered checkpoints */
/* Flag indicating whether a checkpoint has been requested. */
enum checkpoint_request_type_t checkpoint_requested;
unsigned int checkpoint_alarm_time; // number of seconds between checkpoints
int
continue_after_checkpoint; /* 0: exit after chkpt, 1: continue after chkpt */
long long
last_checkpoint_iteration; /* Last iteration when chkpt was created */
time_t begin_timestamp; /* Time since epoch at beginning of 'main' */
const char *initialization_state; /* NULL after initialization completes */
struct reaction_flags rxn_flags;
/* shared walls information per mesh vertex is created when there are
reactions present with more than one surface reactant or more than one
surface product */
int create_shared_walls_info_flag;
/* resource usage during initialization */
struct timeval u_init_time; /* user time */
struct timeval s_init_time; /* system time */
int it1_time_set;
struct timeval u_it1_time; /* user time when iteration 1 started */
struct timeval s_it1_time; /* system time when iteration 1 started */
time_t t_start; /* global start time */
byte reaction_prob_limit_flag; /* checks whether there is at least one
reaction with probability greater
than 1 including variable rate reactions */
//JJT: Checks if we will be communicating with nfsim
int nfsim_flag;
struct species* global_nfsim_volume;
struct species* global_nfsim_surface;
struct pointer_hash *species_mesh_transp;
// mcell4 -specific items
int use_mcell4;
int dump_mcell3;
int dump_mcell4;
int dump_mcell4_with_geometry;
int mdl2datamodel4;
int mdl2datamodel4_only_viz;
// min and max values from PARTITION_X|Y|Z settings,
// these are processed already in parser and are not accessible through other variables
// during conversion, index is dimension
bool partitions_initialized;
struct vector3 partition_llf;
struct vector3 partition_urb;
struct vector3 partition_step;
struct vector3 num_subparts;
};
/* Data structure to store information about collisions. */
struct collision {
struct collision *next;
double t; /* Time of collision (may be slightly early) */
void *target; /* Thing that we hit: wall, molecule, subvol etc */
int what; /* Target-type Flags: what kind of thing did we hit? */
struct rxn *intermediate; /* Reaction that told us we could hit it */
struct vector3 loc; /* Location of impact */
};
/* Special type of collision - used when moving molecule
can engage in tri-molecular collisions */
struct sp_collision {
struct sp_collision *next;
double t; /* Time of collision (may be slightly early) */
double t_start; /* Start time of random walk */
struct vector3 pos_start; /* Start position of random walk */
struct subvolume *sv_start; /* Start subvolume */
struct species *moving; /* Species of the moving molecule */
void *target; /* Thing that we hit: wall, molecule, subvol etc */
int what; /* Target-type Flags: what kind of thing did we hit? */
struct vector3 disp; /* Random walk displacement for the moving molecule */
struct vector3 loc; /* Location of impact */
};
/* Data structure to store information about trimolecular and bimolecular
collisions. */
struct tri_collision {
struct tri_collision *next;
double t; /* Time of collision (may be slightly early) */
void *target1; /* First thing that we hit: wall, molecule, subvol etc */
void *target2; /* Second thing that we hit: wall, molecule, subvol etc -
always the furthest from the moving molecule */
short orient; /* orientation of the moving volume_molecule when it hits the
surface_molecule */
int what; /* Target-type Flags: what kind of thing did we hit? */
struct rxn *
intermediate; /* Reaction that told us we could hit target1 and/or target2 */
struct vector3 loc; /* Assumed location of impact */
struct vector3 loc1; /* Location of impact with first target */
struct vector3 loc2; /* Location of impact with second target */
struct vector3 last_walk_from; /* Location of mol. before last step before
final collision */
double factor; /* Result of "exact_disk()" with both targets or scaling coef.
for MOL_WALL interaction */
double local_prob_factor; /* coefficient depending on the number of nearest
neighbors for MOL_GRID_GRID interaction */
struct wall *wall; /* pointer to the wall in the collision if such exists */
};
/* Data structures to store information about exact interaction disk geometry */
struct exd_vertex {
struct exd_vertex *next;
double u, v; /* x,y style coordinates */
double r2, zeta; /* r,theta style coordinates */
struct exd_vertex *e; /* Edge to next vertex */
struct exd_vertex *span; /* List of edges spanning this point */
int role; /* Exact Disk Flags: Head, tail, whatever */
};
struct dg_time_filename {
struct dg_time_filename *next;
double event_time; // Time to switch geometry
char *mdl_file_path; // Name of mdl containg new geometry
};
/* Data structures to describe release events */
struct release_event_queue {
struct release_event_queue *next;
double event_time; /* Time of the release */
struct release_site_obj *release_site; /* What to release, where to release
it, etc */
double t_matrix[4][4]; // transformation matrix for location of release site
int train_counter; /* counts executed trains */
double train_high_time; /* time of the train's start */
};
/* Release site information */
struct release_site_obj {
struct vector3 *location; /* location of release site */
struct species *mol_type; /* species to be released */
byte release_number_method; /* Release Number Flags: controls how
release_number is used (enum
release_number_type_t) */
int8_t release_shape; /* Release Shape Flags: controls shape over which to
release (enum release_shape_t) */
short orientation; /* Orientation of released surface molecules */
double release_number; /* Number to release */
double mean_diameter; /* Diameter for symmetric releases */
double concentration; /* Concentration of molecules to release. Units are
Molar for volume molecules, and number per um^2 for
surface molecules. */
double standard_deviation; /* Standard deviation of release_number for
GAUSSNUM, or of mean_diameter for VOLNUM */
struct vector3 *diameter; /* x,y,z diameter for geometrical release shapes */
struct release_region_data *
region_data; /* Information related to release on regions */
struct release_single_molecule *
mol_list; /* Information related to release by list */
double release_prob; /* Probability of releasing at scheduled time */
struct periodic_image *periodic_box;
struct release_pattern *pattern; /* Timing of releases by virtual function
generator */
char *name; /* Fully referenced name of the instantiated release_site */
char *graph_pattern; /* JJT: Graph definition of the structured molecules being released in this site*/
};
/* Timing pattern for molecule release from a release site. */
struct release_pattern {
struct sym_entry *sym; /* Symbol hash table entry for the pattern */
double delay; /* Delay between time 0 and first release event. */
double release_interval; /* Time between release events within a train. */
double train_interval; /* Time from the start of one train to the start of
the next one. */
double train_duration; /* Length of the train. */
int number_of_trains; /* How many trains are produced. */
};
/* Extended data for complex releases on regions, including boolean
combinations of regions. Not all fields are used for all release types. */
struct release_region_data {
struct vector3 llf; /* One corner of bounding box for release volume */
struct vector3 urb; /* Opposite corner */
int n_walls_included; /* How many walls total */
double *cum_area_list; /* Cumulative area of all walls */
int *wall_index; /* Indices of each wall (by object) */
int *obj_index; /* Indices for objects (in owners array) */
int n_objects; /* How many objects are there total */
struct geom_object **owners; /* Array of pointers to each object */
struct bit_array **in_release; /* Array of bit arrays; each bit array says
which walls are in release for an object */
int *walls_per_obj; /* Number of walls in release for each object */
struct geom_object *self; /* A pointer to our own release site object */
struct release_evaluator *expression; /* A set-construction expression
combining regions to form this
release site */
};
/* Data structure used to build boolean combinations of regions */
struct release_evaluator {
byte op; /* Region Expression Flags: the operation used */
void *left; /* The left side of the expression--another evaluator or a region
object depending on bitmask of op */
void *right; /* The right side--same thing */
};
/* Data structure used to store LIST releases */
struct release_single_molecule {
struct release_single_molecule *next;
struct species *mol_type; /* Species to release */
struct vector3 loc; /* Position to release it */
short orient; /* Orientation (for 2D species) */
};
/* Holds information about a box with rectangular patches on it. */
struct subdivided_box {
int nx; /* number of subdivisions including box corners in X-direction */
int ny; /* number of subdivisions including box corners in Y-direction */
int nz; /* number of subdivisions including box corners in Z-direction */
double *x; /* array of X-coordinates of subdivisions */
double *y; /* array of Y-coordinates of subdivisions */
double *z; /* array of Z-coordinates of subdivisions */
};
/* Holds information about what we want dumped to the screen */
struct notifications {
/* Informational stuff, most possible values NOTIFY_FULL or NOTIFY_NONE */
/* see corresponding keywords */
enum notify_level_t progress_report; /* PROGRESS_REPORT */
enum notify_level_t diffusion_constants; /* DIFFUSION_CONSTANT_REPORT */
enum notify_level_t reaction_probabilities; /* PROBABILITY_REPORT */
enum notify_level_t time_varying_reactions; /* VARYING_PROBABILITY_REPORT */
double reaction_prob_notify; /* PROBABILITY_REPORT_THRESHOLD */
enum notify_level_t partition_location; /* PARTITION_LOCATION_REPORT */
enum notify_level_t box_triangulation; /* BOX_TRIANGULATION_REPORT */
enum notify_level_t iteration_report; /* ITERATION_REPORT */
long long custom_iteration_value; /* ITERATION_REPORT */
enum notify_level_t throughput_report; /* THROUGHPUT_REPORT */
enum notify_level_t checkpoint_report; /* CHECKPOINT_REPORT */
enum notify_level_t release_events; /* RELEASE_EVENT_REPORT */
enum notify_level_t file_writes; /* FILE_OUTPUT_REPORT */
enum notify_level_t final_summary; /* FINAL_SUMMARY */
enum notify_level_t reaction_output_report; /* REACTION_OUTPUT_REPORT */
enum notify_level_t volume_output_report; /* VOLUME_OUTPUT_REPORT */
enum notify_level_t viz_output_report; /* VIZ_OUTPUT_REPORT */
enum notify_level_t molecule_collision_report; /* MOLECULE_COLLISION_REPORT */
/* Warning stuff, possible values IGNORED, WARNING, ERROR */
/* see corresponding keywords */
enum warn_level_t neg_diffusion; /* NEGATIVE_DIFFUSION_CONSTANT */
enum warn_level_t neg_reaction; /* NEGATIVE_REACTION_RATE */
enum warn_level_t high_reaction_prob; /* HIGH_REACTION_PROBABILITY */
double reaction_prob_warn; /* HIGH_PROBABILITY_THRESHOLD */
enum warn_level_t close_partitions; /* CLOSE_PARTITION_SPACING */
enum warn_level_t degenerate_polys; /* DEGENERATE_POLYGONS */
enum warn_level_t overwritten_file; /* OVERWRITTEN_OUTPUT_FILE */
enum warn_level_t short_lifetime; /* LIFETIME_TOO_SHORT */
long long short_lifetime_value; /* LIFETIME_THRESHOLD */
enum warn_level_t missed_reactions; /* MISSED_REACTIONS */
double missed_reaction_value; /* MISSED_REACTION_THRESHOLD */
enum warn_level_t missed_surf_orient; /* MISSING_SURFACE_ORIENTATION */
enum warn_level_t useless_vol_orient; /* USELESS_VOLUME_ORIENTATION */
enum warn_level_t mol_placement_failure; /* MOLECULE_PLACEMENT_FAILURE */
enum warn_level_t invalid_output_step_time; /* INVALID_OUTPUT_STEP_TIME */
/* LARGE_MOLECULAR_DISPLACEMENT (for dynamic geometry) */
enum warn_level_t large_molecular_displacement;
/* ADD_REMOVE_MESH (for dynamic geometry) */
enum warn_level_t add_remove_mesh_warning;
};
/* Information related to concentration clamp surfaces, by object */
struct clamp_data {
struct clamp_data *next; // The next clamp, by surf class
struct species *surf_class; /* Which surface class clamps? */
struct species *mol; /* Which molecule does it clamp? */
int clamp_type; /* Type of clamp, CLAMP_TYPE_CONC or FLUX */
double clamp_value; /* At what concentration or flux value? */
short orient; /* On which side? */
struct geom_object *objp; /* Which object are we clamping? */
struct bit_array *sides; /* Which walls in that object? */
int n_sides; /* How many walls? */
int *side_idx; /* Indices of the walls that are clamped */
double *cum_area; /* Cumulative area of all the clamped walls */
double scaling_factor; /* Used to predict #mols/timestep */
struct clamp_data *next_mol; /* Next clamp, by molecule, for this class */
struct clamp_data *next_obj; /* Next clamp, by object, for this class */
};
/* Structure for a VOLUME_DATA_OUTPUT item */
struct volume_output_item {
/* Do not move or reorder these 2 items. scheduler depends upon them */
struct volume_output_item *next;
double t;
char *filename_prefix;
/* what? */
int num_molecules;
struct species **molecules; /* sorted by address */
/* where? */
struct vector3 location;
struct vector3 voxel_size;
int nvoxels_x;
int nvoxels_y;
int nvoxels_z;
/* when? */
enum output_timer_type_t timer_type;
double step_time;
int num_times;
double *times; /* in numeric order */
double *next_time; /* points into times */
};
/* Data for a single REACTION_DATA_OUTPUT block */
struct output_block {
struct output_block *next; /* Next in world or scheduler */
double t; /* Scheduled time to update counters */
enum output_timer_type_t timer_type; /* Data Output Timing Type
(OUTPUT_BY_STEP, etc) */
double step_time; /* Output interval (seconds) */
struct num_expr_list *time_list_head; /* List of output times/iteration
numbers */
struct num_expr_list *time_now; /* Current entry in list */
u_int buffersize; /* Size of output buffer */
u_int trig_bufsize; /* Size of output buffer for triggers */
u_int buf_index; /* Index into buffer (for non-triggers) */
double *time_array; /* Array of output times (for non-triggers) */
/* Linked list of data sets (separate files) */
struct output_set *data_set_head;
};
/* Data that controls what output is written to a single file */
struct output_set {
struct output_set *next; /* Next data set in this block */
struct output_block *block; /* Which block do we belong to? */
char *outfile_name; /* Filename */
enum overwrite_policy_t file_flags; /* Overwrite Policy Flags: tells us how to
* handle existing files */
u_int chunk_count; /* Number of buffered output chunks processed */
const char *header_comment; /* Comment character(s) for header */
int exact_time_flag; /* Boolean value; nonzero means print exact time in
TRIGGER statements */
struct output_column *column_head; /* Data for one output column */
};
struct output_buffer {
enum count_type_t data_type;
union {
char cval;
double dval;
int ival;
struct output_trigger_data *tval;
} val;
};
/* Data that controls what data is written to one column of output file */
struct output_column {
struct output_column *next; /* Next column in this set */
struct output_set *set; /* Which set do we belong to? */
double initial_value; /* To continue existing cumulative counts--not
implemented yet--and keep track of triggered
data */
struct output_buffer *buffer; /* Output buffer array (cast based on data_type) */
/* Evaluate this to calculate our value (NULL if trigger) */
struct output_expression *expr;
};
/* Expression evaluation tree to compute output value for one column */
struct output_expression {
struct output_column *column; /* Which column are we going to? */
int expr_flags; /* Output Expression Flags: what are we and what is left and
right? */
struct output_expression *up; /* Parent output expression */
void *left; /* Item on the left */
void *right; /* Item on the right */
char oper; /* Operation to apply to items */
double value; /* Resulting value from operation */
char *title; /* String describing this expression for user */
};
/* Information about a requested COUNT or TRIGGER statement */
/* Used during initialization to link output expressions with appropriate
target, and instruct MCell3 to collect appropriate statistics at the target.
*/
struct output_request {
struct output_request *next; /* Next request in global list */
struct output_expression *requester; /* Expression in which we appear */
struct sym_entry *count_target; /* Mol/rxn we're supposed to count */
short count_orientation; /* orientation of the molecule
we are supposed to count */
struct sym_entry *count_location; /* Object or region on which we're supposed to count it */
byte report_type; /* Output Report Flags telling us how to count */
struct periodic_image *periodic_box; /* periodic box we are counting in; NULL
means that we don't care and count everywhere */
};
/* Data stored when a trigger event happens */
struct output_trigger_data {
double t_iteration; /* Iteration time of the triggering event (in sec) */
double event_time; /* Exact time of the event */
struct vector3 loc; /* Position of event */
int how_many; /* Number of events */
short orient; /* Orientation information */
short flags; /* Output Trigger Flags */
char *name; /* Name to give event */
u_long id;
};
/******************************************************************/
/** Everything below this line has been copied from MCell 2.69 **/
/******************************************************************/
/* A polygon list object, part of a surface. */
struct polygon_object {
int n_verts; /* Number of vertices in polyhedron */
struct vertex_list *parsed_vertices; /* Temporary linked list */
int n_walls; /* Number of triangles in polyhedron */
struct element_data *element; /* Array specifying the vertex
connectivity of each triangle */
struct subdivided_box *sb; /* Holds corners of box if necessary */
struct bit_array *side_removed; // Bit array; if bit is set, side is removed
int references; // The number of instances of this poly obj
// Need this for cleaning up after dyngeoms
};
/* Data structure used to build one triangular polygon according to the
* connectivity in the MDL file. */
struct element_data {
int vertex_index[3]; /* Array of vertex indices forming a triangle */
};
/* A voxel list object, part of a volume */
struct voxel_object {
struct vector3 *vertex; /* Array of tetrahedron vertices */
struct tet_element_data *element; /* Array tet_element_data data structures */
struct tet_neighbors_data *neighbor; /* Array tet_neighbors_data data
structures */
int n_verts; /* Number of vertices in polyhedron */
int n_voxels; /* Number of voxels in polyhedron */
};
/**
* Data structure used to build one tetrahedron.
* This data structure is used to store the data from the MDL file
* and to contruct each tetrahedron of a voxel object.
*/
struct tet_element_data {
int vertex_index[4]; /* Array of vertex indices forming a tetrahedron. */
};
/**
* This data structure is used to store the data about neighbors
* of each tetrahedron of a voxel object.
*/
struct tet_neighbors_data {
int neighbors_index[4]; /* Array of indices pointing to the neighbors of
tetrahedron. */
};
/* Surface molecule placement data */
struct sm_dat {
struct sm_dat *next;
struct species *sm; /* Species to place on surface */
// Placement Type Flags: either SURFMOLDENS or SURFMOLNUM
byte quantity_type;
// Amount of surface molecules to place by density or number
double quantity;
short orientation; /* Orientation of molecules to place */
};
/* Linked list of wall index ranges for regions */
struct element_list {
struct element_list *next;
u_int begin; /* First number in the range */
u_int end; /* Last number in the range */
struct element_special *special; /* Pre-existing region or patch on box */
};
/* Elements can be patches on boxes or pre-existing regions */
struct element_special {
struct vector3 corner1; /* Corner of patch on box */
struct vector3 corner2; /* Opposite corner of patch on box */
struct region *referent; /* Points to pre-existing region on object */
byte exclude; /* If set, remove elements rather than include them */
};
/* Region of an object */
/* If region is a manifold then it can be used as both a volume and surface
region. Otherwise it can only be used as a surface region. */
struct region {
struct sym_entry *sym; /* Symbol hash table entry for this region */
u_int hashval; /* Hash value for counter hash table */
const char *region_last_name; /* Name of region without prepended object name */
struct geom_object *parent; /* Parent of this region */
struct element_list *element_list_head; /* List of element ranges comprising
this region (used at parse time) */
struct bit_array *membership; /* Each bit indicates whether the corresponding
wall is in the region */
struct sm_dat *sm_dat_head; /* List of surface molecules to add to region */
struct species *surf_class; /* Surface class of this region */
struct vector3 *bbox; /* Array of length 2 to hold corners of region bounding
box (used for release in region) */
double area; /* Area of region */
u_short flags; /* Counting subset of Species Flags */
byte manifold_flag; /* Manifold Flags: If IS_MANIFOLD, region is a closed
manifold and thus defines a volume */
double volume; /* volume of region for closed manifolds */
struct pointer_hash *boundaries; /* hash table of edges that constitute
external boundary of the region */
int region_has_all_elements; /* flag that tells whether the region contains
ALL_ELEMENTS (effectively comprises the whole
object) */
};
/* A list of surface molecules */
struct surface_molecule_list {
struct surface_molecule_list *next;
struct surface_molecule *sm;
};
/* A list of regions */
struct region_list {
struct region_list *next;
struct region *reg; /* A region */
};
/* Container data structure for all physical objects */
struct geom_object {
struct geom_object *next; /* Next sibling object */
struct geom_object *parent; /* Parent meta object */
struct geom_object *first_child; /* First child object */
struct geom_object *last_child; /* Last child object */
struct sym_entry *sym; /* Symbol hash table entry for this object */
char *last_name; /* Name of object without pre-pended parent object name, must not be const char* */
enum object_type_t object_type; /* Object Type Flags */
void *contents; /* Actual physical object, cast according to object_type */
u_int num_regions; /* Number of regions defined on object */
struct region_list *regions; /* List of regions for this object */
int n_walls; /* Total number of walls in object */
int n_walls_actual; /* Number of non-null walls in object */
struct wall *walls; /* Array of walls in object */
struct wall **wall_p; // Array of ptrs to walls in object (used at run-time)
int n_verts; /* Total number of vertices in object */
struct vector3 **vertices; /* Array of pointers to vertices
(linked to "all_vertices" array) */
double total_area; /* Area of object in length units */
u_int n_tiles; /* Number of surface grid tiles on object */
u_int n_occupied_tiles; /* Number of occupied tiles on object */
double t_matrix[4][4]; /* Transformation matrix for object */
short is_closed; /* Flag that describes the geometry
of the polygon object (e.g. for sphere
is_closed = 1 and for plane is 0) */
bool periodic_x; // This flag only applies to box objects BOX_OBJ. If set
bool periodic_y; // any volume molecules encountering the box surface in the x,
bool periodic_z; // y or z direction are reflected back into the box as if they
// had entered the adjacent neighboring box */
};
/* Doubly linked list of object names */
struct name_list {
struct name_list *next;
struct name_list *prev;
char *name; /* An object name */
};
/* Linked list of names-orientations. Used in printing special reactions report
for surface classes */
struct name_orient {
struct name_orient *next;
char *name; /* molecule name */
int orient; /* molecule orientation */
};
struct visualization_state {
/* Iteration numbers */
long long last_meshes_iteration;
long long last_mols_iteration;
/* Tokenized filename prefix */
char *filename_prefix_basename;
char *filename_prefix_dirname;
/* All visualized volume molecule species */
int n_vol_species;
struct species **vol_species;
/* All visualized surface molecule species */
int n_grid_species;
struct species **grid_species;
/* Iteration numbers and times of outputs */
struct iteration_counter output_times;
struct iteration_counter mesh_output_iterations;
struct iteration_counter vol_mol_output_iterations;
struct iteration_counter surface_mol_output_iterations;
};
struct viz_output_block {
struct viz_output_block *next; /* Link to next block */
struct frame_data_list *frame_data_head; /* head of the linked list of viz
frames to output */
enum viz_mode_t viz_mode;
char *file_prefix_name;
u_short viz_output_flag; /* Takes VIZ_ALL_MOLECULES, VIZ_MOLECULES_STATES,
etc. */
int *species_viz_states;
int default_mol_state; // Only set if (viz_output_flag & VIZ_ALL_MOLECULES)
/* Parse-time only: Tables to hold temporary information. */
struct pointer_hash parser_species_viz_states;
};
/* Geometric transformation data for a physical object */
struct transformation {
struct vector3 translate; /* X,Y,Z translation vector */
struct vector3 scale; /* X,Y,Z scaling factors */
struct vector3 rot_axis; /* Vector defining an axis of rotation */
double rot_angle; /* Rotation angle in degrees */
};
/* Linked list of viz data to be output */
struct frame_data_list {
struct frame_data_list *next;
enum output_timer_type_t list_type; /* Data Output Timing Type
(OUTPUT_BY_TIME_LIST, etc) */
enum viz_frame_type_t
type; /* Visualization Frame Data Type (ALL_FRAME_DATA, etc) */
long long viz_iteration; /* Value of the current iteration step. */
long long n_viz_iterations; /* Number of iterations in the iteration_list. */
struct num_expr_list *
iteration_list; /* Linked list of iteration steps values */
struct num_expr_list *curr_viz_iteration; /* Points to the current iteration
in the linked list */
};
struct frame_data_list_head {
struct frame_data_list *frame_head;
struct frame_data_list *frame_tail;
};
/* A pointer to filehandle and its real name */
/* Used for user defined file IO operations */
struct file_stream {
char *name; /* File name */
FILE *stream; /* File handle structure */
};
/* Symbol hash table */
/* Used to parse and store user defined symbols from the MDL input file */
struct sym_table_head {
struct sym_entry **entries;
int n_entries;
int n_bins;
};
/* Symbol hash table entry */
/* Used to parse and store user defined symbols from the MDL input file */
struct sym_entry {
struct sym_entry *next; /* Chain to next symbol in this bin of the hash */
int sym_type; /* Symbol Type */
char *name; /* Name of symbol*/
void *value; /* Stored value, cast by sym_type */
int count;
};
/* Linked list of symbols */
/* Used to parse and retrieve user defined symbols having wildcards from the
* MDL input file */
struct sym_table_list {
struct sym_table_list *next;
struct sym_entry *node; /* Symbol table entry matching a user input wildcard
string */
};
/* Linked list of numerical expressions */
/* Used for parsing MDL input file arithmetic expressions */
struct num_expr_list {
struct num_expr_list *next;
double value; /* Value of one element of the expression */
};
/* Linked list of surface classes */
struct surf_class_list {
struct surf_class_list *next;
struct species *surf_class;
};
/* Linked list of edges - used for REGION borders */
struct edge_list {
struct edge_list *next;
struct edge *ed;
};
/* Data about hits/crossing of region borders */
struct hit_data {
struct hit_data *next;
struct region_list *count_regions; /* list of regions we are counting on */
int direction; /* 1 - INSIDE_OUT, 0 - OUTSIDE_IN */
int crossed; /* 1 - if crossed, 0 - if not */
short orientation; /* orientation of the surface molecule */
struct vector3 loc; /* location of the hit */
double t; /* time of the hit */
};
struct object_list {
struct geom_object *obj_head;
struct geom_object *obj_tail;
};
double rxn_get_nfsim_diffusion(struct rxn*, int);
double rxn_get_standard_diffusion(struct rxn*, int);
| Unknown |
3D | mcellteam/mcell | src/viz_output.h | .h | 872 | 27 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#define ASCII_VIZ_EXTERNAL_SPECIES_NAME
#include "mcell_structs.h"
/* Header file for visualization output routines */
int update_frame_data_list(struct volume *world,
struct viz_output_block *vizblk);
int init_frame_data_list(struct volume *world, struct viz_output_block *vizblk);
int finalize_viz_output(struct volume *world, struct viz_output_block *vizblk);
| Unknown |
3D | mcellteam/mcell | src/vector.h | .h | 2,737 | 70 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
/* Header file for 3D vector routines */
struct vector2 {
double u;
double v;
};
struct vector3 {
double x;
double y;
double z;
};
void mult_matrix(double (*m1)[4], double (*m2)[4], double (*om)[4],
short unsigned int l, short unsigned int m,
short unsigned int n);
void normalize(struct vector3 *v);
void init_matrix(double (*im)[4]);
void scale_matrix(double (*im)[4], double (*om)[4], struct vector3 *scale);
void translate_matrix(double (*im)[4], double (*om)[4],
struct vector3 *translate);
void rotate_matrix(double (*im)[4], double (*om)[4], struct vector3 *axis,
double angle);
void tform_matrix(struct vector3 *scale, struct vector3 *translate,
struct vector3 *axis, double angle, double (*om)[4]);
void vectorize(struct vector3 *p1, struct vector3 *p2, struct vector3 *v);
double vect_length(struct vector3 *v);
double dot_prod(struct vector3 *v1, struct vector3 *v2);
void cross_prod(struct vector3 *v1, struct vector3 *v2, struct vector3 *v3);
void vect_sum(struct vector3 *v1, struct vector3 *v2, struct vector3 *v3);
void scalar_prod(struct vector3 *v1, double a, struct vector3 *result);
int distinguishable_vec3(struct vector3 *a, struct vector3 *b, double eps);
int distinguishable_vec2(struct vector2 *a, struct vector2 *b, double eps);
double distance_vec3(struct vector3 *a, struct vector3 *b);
int parallel_segments(struct vector3 *A, struct vector3 *B, struct vector3 *R,
struct vector3 *S);
int point_in_triangle(struct vector3 *p, struct vector3 *a, struct vector3 *b,
struct vector3 *c);
int same_side(struct vector3 *p1, struct vector3 *p2, struct vector3 *a,
struct vector3 *b);
int intersect_point_segment(struct vector3 *P, struct vector3 *A,
struct vector3 *B);
double cross2D(struct vector2 *a, struct vector2 *b);
void vectorize2D(struct vector2 *p1, struct vector2 *p2, struct vector2 *p3);
int point_in_triangle_2D(struct vector2 *p, struct vector2 *a,
struct vector2 *b, struct vector2 *c);
int point_in_box(struct vector3 *low_left, struct vector3 *up_right,
struct vector3 *point);
| Unknown |
3D | mcellteam/mcell | src/sched_util.c | .c | 21,046 | 728 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <float.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "sched_util.h"
#include "mcell_structs.h"
#include "debug_config.h"
#include "dump_state.h"
/*************************************************************************
ae_list_sort:
In: head of a linked list of abstract_elements
Out: head of the newly sorted list
Note: uses mergesort
*************************************************************************/
struct abstract_element *ae_list_sort(struct abstract_element *ae) {
struct abstract_element *stack[64];
int stack_n[64];
struct abstract_element *left = NULL, *right = NULL, *merge = NULL,
*tail = NULL;
int si = 0;
if (ae == NULL)
return NULL;
while (ae != NULL) {
if (ae->next == NULL) {
stack[si] = ae;
stack_n[si] = 1;
ae = NULL;
si++;
} else if (ae->t <= ae->next->t) {
stack[si] = ae;
stack_n[si] = 2;
ae = ae->next->next;
stack[si]->next->next = NULL;
si++;
} else {
stack[si] = ae->next;
stack_n[si] = 2;
left = ae;
ae = ae->next->next;
stack[si]->next = left;
left->next = NULL;
si++;
}
while (si > 1 && stack_n[si - 1] * 2 >= stack_n[si - 2]) {
stack_n[si - 2] += stack_n[si - 1];
left = stack[si - 2];
right = stack[si - 1];
if (left->t <= right->t) {
merge = left;
left = left->next;
} else {
merge = right;
right = right->next;
}
merge->next = NULL;
tail = merge;
while (1) {
if (left == NULL) {
tail->next = right;
break;
}
if (right == NULL) {
tail->next = left;
break;
}
if (left->t <= right->t) {
tail->next = left;
tail = left;
left = left->next;
} else {
tail->next = right;
tail = right;
right = right->next;
}
}
stack[si - 2] = merge;
si--;
}
}
while (si > 1) /* Exact duplicate of code in loop--keep it this way! */
{
stack_n[si - 2] += stack_n[si - 1];
left = stack[si - 2];
right = stack[si - 1];
if (left->t <= right->t) {
merge = left;
left = left->next;
} else {
merge = right;
right = right->next;
}
merge->next = NULL;
tail = merge;
while (1) {
if (left == NULL) {
tail->next = right;
break;
}
if (right == NULL) {
tail->next = left;
break;
}
if (left->t <= right->t) {
tail->next = left;
tail = left;
left = left->next;
} else {
tail->next = right;
tail = right;
right = right->next;
}
}
stack[si - 2] = merge;
si--;
}
return stack[0];
}
/*************************************************************************
create_scheduler:
In: timestep per slot in this scheduler
time for all slots in this scheduler
maximum number of slots in this scheduler
the current time
Out: pointer to a new instance of schedule_helper; pass this to later
functions. (Dispose of with delete_scheduler.) Returns NULL
if out of memory.
*************************************************************************/
struct schedule_helper *create_scheduler(double dt_min, double dt_max,
int maxlen, double start_iterations) {
double n_slots = dt_max / dt_min;
int len;
if (n_slots < (double)(maxlen - 1))
len = (int)n_slots + 1;
else
len = maxlen;
if (len < 2)
len = 2;
struct schedule_helper *sh = NULL;
sh = (struct schedule_helper *)malloc(sizeof(struct schedule_helper));
if (sh == NULL)
return NULL;
memset(sh, 0, sizeof(struct schedule_helper));
sh->dt = dt_min;
sh->dt_1 = 1 / dt_min;
sh->now = start_iterations;
sh->buf_len = len;
sh->circ_buf_count = (int *)calloc(len, sizeof(int));
if (sh->circ_buf_count == NULL)
goto failure;
sh->circ_buf_head = (struct abstract_element **)calloc(
len * 2, sizeof(struct abstract_element*));
if (sh->circ_buf_head == NULL)
goto failure;
sh->circ_buf_tail = sh->circ_buf_head + len;
if (sh->dt * sh->buf_len < dt_max) {
ASSERT_FOR_MCELL4(false);
sh->next_scale =
create_scheduler(dt_min * len, dt_max, maxlen, sh->now + dt_min * len);
if (sh->next_scale == NULL)
goto failure;
sh->next_scale->depth = sh->depth + 1;
}
return sh;
failure:
if (sh != NULL)
delete_scheduler(sh);
return NULL;
}
int schedule_add_mol(struct schedule_helper *sh, void *data) {
struct abstract_molecule *am = (struct abstract_molecule *)data;
#ifdef DEBUG_SCHEDULER
if ((am->flags & TYPE_SURF) != 0) {
struct surface_molecule* sm = (struct surface_molecule*)am;
dump_surface_molecule(sm, "", true, "\n* Scheduled a new sm action: ", 0, sm->t, true);
}
else {
struct volume_molecule* vm = (struct volume_molecule*)am;
dump_volume_molecule(vm, "", true, "\n* Scheduled a new vm action: ", 0, vm->t, true);
}
#endif
return schedule_insert(sh, am, 1);
}
/*************************************************************************
schedule_insert:
In: scheduler that we are using
data to schedule (assumed to start with abstract_element struct)
flag to indicate whether times in the "past" go into the list
of current events (if 0, go into next event, not current).
Out: 0 on success, 1 on memory allocation failure. Data item is
placed in scheduler at end of list for its time slot.
*************************************************************************/
int schedule_insert(struct schedule_helper *sh, void *data,
int put_neg_in_current) {
struct abstract_element *ae = (struct abstract_element *)data;
if (put_neg_in_current && ae->t < sh->now) {
/* insert item into current list */
sh->current_count++;
if (sh->current_tail == NULL) {
sh->current = sh->current_tail = ae;
ae->next = NULL;
} else {
sh->current_tail->next = ae;
sh->current_tail = ae;
ae->next = NULL;
}
return 0;
}
/* insert item into future lists */
sh->count++;
double nsteps = (ae->t - sh->now) * sh->dt_1;
if (nsteps < ((double)sh->buf_len)) {
/* item fits in array for this scale */
int i;
if (nsteps < 0.0)
i = sh->index;
else
i = (int)nsteps + sh->index;
if (i >= sh->buf_len)
i -= sh->buf_len;
if (sh->circ_buf_tail[i] == NULL) {
sh->circ_buf_count[i] = 1;
sh->circ_buf_head[i] = sh->circ_buf_tail[i] = ae;
ae->next = NULL;
} else {
sh->circ_buf_count[i]++;
/* For schedulers other than the first tier, maintain a LIFO ordering */
if (sh->depth) {
ae->next = sh->circ_buf_head[i];
sh->circ_buf_head[i] = ae;
}
/* For first-tier scheduler, maintain FIFO ordering */
else {
sh->circ_buf_tail[i]->next = ae;
ae->next = NULL;
sh->circ_buf_tail[i] = ae;
}
}
} else {
/* item fits in array for coarser scale */
if (sh->next_scale == NULL) {
sh->next_scale = create_scheduler(
sh->dt * sh->buf_len, sh->dt * sh->buf_len * sh->buf_len, sh->buf_len,
sh->now + sh->dt * (sh->buf_len - sh->index));
if (sh->next_scale == NULL)
return 1;
sh->next_scale->depth = sh->depth + 1;
}
/* insert item at coarser scale and insist that item is not placed in
* "current" list */
return schedule_insert(sh->next_scale, data, 0);
}
return 0;
}
/*************************************************************************
unlink_list_item:
Removes a specific item from the linked list.
In: struct abstract_element **hd - pointer to head of list
struct abstract_element **tl - pointer to tail of list
struct abstract_element *it - pointer to item to unlink
Out: 0 on success, 1 if the item was not found
*************************************************************************/
static int unlink_list_item(struct abstract_element **hd,
struct abstract_element **tl,
struct abstract_element *it) {
struct abstract_element *prev = NULL;
while (*hd != NULL) {
if (*hd == it) {
(*hd) = (*hd)->next;
if (*tl == it)
*tl = prev;
return 0;
}
prev = *hd;
hd = &prev->next;
}
return 1;
}
/*************************************************************************
schedule_deschedule:
Removes an item from the schedule.
In: struct schedule_helper *sh - the scheduler from which to remove
void *data - the item to remove
Out: 0 on success, 1 if the item was not found
*************************************************************************/
int schedule_deschedule(struct schedule_helper *sh, void *data) {
struct abstract_element *ae = (struct abstract_element *)data;
/* If the item is in "current" */
if (sh->current && ae->t < sh->now) {
if (unlink_list_item(&sh->current, &sh->current_tail, ae))
return 1;
--sh->current_count;
return 0;
}
double nsteps = (ae->t - sh->now) * sh->dt_1;
if (nsteps < ((double)sh->buf_len)) {
int list_idx;
if (nsteps < 0.0)
list_idx = sh->index;
else
list_idx = (int)nsteps + sh->index;
if (list_idx >= sh->buf_len)
list_idx -= sh->buf_len;
if (unlink_list_item(&sh->circ_buf_head[list_idx],
&sh->circ_buf_tail[list_idx], ae)) {
/* If we fail to find it in this level, it may be in the next level.
* Note that when we are descheduling, we may need to look in more than
* one place, depending upon how long ago the item to be descheduled was
* originally scheduled. */
if (sh->next_scale) {
if (!schedule_deschedule(sh->next_scale, data)) {
--sh->count;
return 0;
} else
return 1;
} else
return 1;
}
--sh->count;
--sh->circ_buf_count[list_idx];
return 0;
} else {
if (!sh->next_scale)
return 1;
if (!schedule_deschedule(sh->next_scale, data)) {
--sh->count;
return 0;
} else
return 1;
}
}
/*************************************************************************
schedule_reschedule:
Moves an item from one time to another in the schedule.
In: struct schedule_helper *sh - the scheduler from which to remove
void *data - the item to remove
double new_t - the new time for the item
Out: 0 on success, 1 if the item was not found
*************************************************************************/
int schedule_reschedule(struct schedule_helper *sh, void *data, double new_t) {
if (!schedule_deschedule(sh, data)) {
struct abstract_element *ae = (struct abstract_element *)data;
ae->t = new_t;
return schedule_insert(sh, data, 1);
} else
return 1;
}
/*************************************************************************
schedule_advance:
In: scheduler that we are using
a pointer to the head-pointer for the list of the next time block
a pointer to the tail-pointer for the list of the next time block
Out: Number of items in the next block of time. These items start
with *head, and end with *tail. Returns -1 on memory error.
*************************************************************************/
int schedule_advance(struct schedule_helper *sh, struct abstract_element **head,
struct abstract_element **tail) {
int n;
struct abstract_element *p, *nextp;
if (head != NULL)
*head = sh->circ_buf_head[sh->index];
if (tail != NULL)
*tail = sh->circ_buf_tail[sh->index];
sh->circ_buf_head[sh->index] = sh->circ_buf_tail[sh->index] = NULL;
sh->count -= n = sh->circ_buf_count[sh->index];
sh->circ_buf_count[sh->index] = 0;
sh->index++;
sh->now += sh->dt;
if (sh->index >= sh->buf_len) {
/* Move events from coarser time scale to this time scale */
sh->index = 0;
if (sh->next_scale != NULL) {
/* Save our depth */
int old_depth = sh->depth;
int conservecount = sh->count;
/* Hack: Toggle the non-zero-ness of our depth to toggle FIFO/LIFO
* behavior
*/
sh->depth = old_depth ? 0 : -1;
if (schedule_advance(sh->next_scale, &p, NULL) == -1) {
sh->depth = old_depth;
return -1;
}
while (p != NULL) {
nextp = p->next;
if (schedule_insert(sh, (void *)p, 0)) {
sh->depth = old_depth;
return -1;
}
p = nextp;
}
/* moved items were already counted when originally scheduled so don't
* count again */
sh->count = conservecount;
/* restore our depth */
sh->depth = old_depth;
}
}
return n;
}
/*************************************************************************
schedule_next:
In: scheduler that we are using
Out: Next item to deal with. If we are out of items for the current
timestep, NULL is returned and the time is advanced to the next
timestep. If there is a memory error, NULL is returned and
sh->error is set to 1.
*************************************************************************/
void *schedule_next(struct schedule_helper *sh) {
void *data;
if (sh->current == NULL) {
sh->current_count = schedule_advance(sh, &sh->current, &sh->current_tail);
if (sh->current_count == -1)
sh->error = 1;
return NULL;
} else {
sh->current_count--;
data = sh->current;
sh->current = sh->current->next;
if (sh->current == NULL)
sh->current_tail = NULL;
return data;
}
}
/*************************************************************************
schedule_peak:
In: scheduler that we are using
Out: Next item (e.g. molecule) to deal with. NULL if scheduler is empty
This is very similar to schedule_next, but the idea here is that we don't
want to change the state of anything (specifically current_count).
XXX: The caller needs to reset sh->current when it's done "peaking"
*************************************************************************/
void *schedule_peak(struct schedule_helper *sh) {
void *data;
// Nothing to see here; move on
if (sh->current == NULL) {
return NULL;
}
// Ooh. Found something!
else {
data = sh->current;
sh->current = sh->current->next;
return data;
}
}
/*************************************************************************
schedule_anticipate:
In: scheduler that we are using
pointer to double to store the anticipated time of next event
Out: 1 if there is an event anticipated, 0 otherwise
*************************************************************************/
int schedule_anticipate(struct schedule_helper *sh, double *t) {
int i, j;
double earliest_t = DBL_MAX;
if (sh->current != NULL) {
*t = sh->now;
return 1;
} else if (sh->count == 0)
return 0;
while (sh->next_scale != NULL && sh->count == sh->next_scale->count)
sh = sh->next_scale;
for (; sh != NULL; sh = sh->next_scale) {
if (earliest_t < sh->now)
break;
for (i = 0; i < sh->buf_len; i++) {
j = i + sh->index;
if (j >= sh->buf_len)
j -= sh->buf_len;
if (sh->circ_buf_count[j] > 0) {
earliest_t = sh->now + sh->dt * i;
break;
}
}
}
if (earliest_t < DBL_MAX) {
*t = earliest_t;
return 1;
} else
return 0;
}
/*************************************************************************
schedule_cleanup:
In: scheduler that we are using
pointer to a function that will return 0 if an abstract_element is
okay, or 1 if it is defunct
Out: all defunct items are removed from the scheduler and returned as
a linked list (so appropriate action can be taken, such as
deallocation)
*************************************************************************/
struct abstract_element *
schedule_cleanup(struct schedule_helper *sh,
int (*is_defunct)(struct abstract_element*)) {
struct abstract_element *defunct_list;
struct abstract_element *ae;
struct abstract_element *temp;
struct schedule_helper *top;
struct schedule_helper *shp;
int i;
defunct_list = NULL;
top = sh;
for (; sh != NULL; sh = sh->next_scale) {
sh->defunct_count = 0;
for (i = 0; i < sh->buf_len; i++) {
/* Remove defunct elements from beginning of list */
while (sh->circ_buf_head[i] != NULL &&
(*is_defunct)(sh->circ_buf_head[i])) {
temp = sh->circ_buf_head[i]->next;
sh->circ_buf_head[i]->next = defunct_list;
defunct_list = sh->circ_buf_head[i];
sh->circ_buf_head[i] = temp;
sh->circ_buf_count[i]--;
sh->count--;
for (shp = top; shp != sh; shp = shp->next_scale)
shp->count--;
}
if (sh->circ_buf_head[i] == NULL) {
sh->circ_buf_tail[i] = NULL;
} else {
/* Now remove defunct elements from later in list */
for (ae = sh->circ_buf_head[i]; ae != NULL; ae = ae->next) {
while (ae->next != NULL && (*is_defunct)(ae->next)) {
temp = ae->next->next;
ae->next->next = defunct_list;
defunct_list = ae->next;
ae->next = temp;
sh->circ_buf_count[i]--;
sh->count--;
for (shp = top; shp != sh; shp = shp->next_scale)
shp->count--;
}
if (ae->next == NULL) {
sh->circ_buf_tail[i] = ae;
break;
}
}
}
}
}
return defunct_list;
}
/*************************************************************************
delete_scheduler:
In: scheduler that we are using
Out: No return value. The scheduler is freed from dynamic memory.
*************************************************************************/
void delete_scheduler(struct schedule_helper *sh) {
if (sh) {
if (sh->next_scale != NULL)
delete_scheduler(sh->next_scale);
if (sh->circ_buf_head)
free(sh->circ_buf_head);
if (sh->circ_buf_count)
free(sh->circ_buf_count);
free(sh);
}
}
#if defined(MCELL3_SORTED_MOLS_ON_RUN_TIMESTEP) || defined(MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_ID)
#include <vector>
#include <algorithm>
static bool less_time_and_id(struct abstract_molecule* a1, struct abstract_molecule* a2) {
assert(a1 != NULL);
assert(a2 != NULL);
// WARNING: this comparison is a bit 'shaky' - the constant 100*EPS_C there...
return (a1->t + 100*EPS_C < a2->t) || (fabs(a1->t - a2->t) < 100*EPS_C && a1->id < a2->id);
}
static bool is_sorted(struct abstract_molecule* list) {
if (list == NULL || list->next == NULL) {
return true;
}
struct abstract_molecule* prev = list;
for (struct abstract_molecule* curr = list->next; curr != NULL; curr = curr->next) {
if (!less_time_and_id(prev, curr)) {
return false;
}
prev = curr;
}
return true;
}
// used only when MCELL3_SORTED_MOLS_ON_RUN_TIMESTEP or MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_IDis defined
void sort_schedule_by_time_and_id(struct schedule_helper *sh) {
for (struct schedule_helper* sh_current = sh; sh_current != NULL; sh_current = sh_current->next_scale) {
// we need abstract_molecule so that we are able to sort by id
struct abstract_molecule* list = (struct abstract_molecule*)sh_current->current;
// used code from https://en.wikipedia.org/wiki/Insertion_sort#List_insertion_sort_code_in_C
// zero or one element in list
if (list == NULL || list->next == NULL) {
return ;
}
if (is_sorted(list)) {
// conversion and sorting takes long time, a minor optimization for faster debugging
continue;
}
std::vector<struct abstract_molecule*> vec;
for (struct abstract_molecule* item = list; item != NULL; item = item->next) {
vec.push_back(item);
}
std::sort(vec.begin(), vec.end(), less_time_and_id);
sh_current->current = (struct abstract_element*)vec[0];
for (size_t i = 1; i < vec.size(); i++) {
vec[i - 1]->next = vec[i];
}
vec.back()->next = NULL;
sh_current->current_tail = (struct abstract_element*)vec.back();
}
}
#endif // defined(MCELL3_SORTED_MOLS_ON_RUN_TIMESTEP) || defined(MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_ID)
| C |
3D | mcellteam/mcell | src/react_outc_trimol.c | .c | 82,041 | 1,985 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <vector>
#include "logging.h"
#include "rng.h"
#include "util.h"
#include "grid_util.h"
#include "mcell_structs.h"
#include "count_util.h"
#include "react.h"
#include "vol_util.h"
#include "wall_util.h"
static int outcome_products_trimol_reaction_random(
struct volume *world, struct wall *w, struct vector3 *hitpt, double t,
struct rxn *rx, int path, struct abstract_molecule *reacA,
struct abstract_molecule *reacB, struct abstract_molecule *reacC,
short orientA, short orientB, short orientC);
/*************************************************************************
outcome_products_trimol_reaction_random:
In: first wall in the reaction
hit point (if any)
time of the reaction
reaction
path of the reaction
first reactant (moving molecule)
second reactant
third reactant
orientation of the first reactant
orientation of the second reactant
orientation of the third reactant
Note: This function replaces surface reactants (if needed) by the surface
products picked in the random order from the list of products.
It also places surface products on the randomly selected tiles
from the list of neighbors.
Note: Policy on surface products placement is described in the document
"policy_surf_products_placement.doc" (see "src/docs").
************************************************************************/
static int outcome_products_trimol_reaction_random(
struct volume *world, struct wall *w, struct vector3 *hitpt, double t,
struct rxn *rx, int path, struct abstract_molecule *reacA,
struct abstract_molecule *reacB, struct abstract_molecule *reacC,
short orientA, short orientB, short orientC) {
if (reacA != NULL && reacB != NULL) {
assert(periodic_boxes_are_identical(reacA->periodic_box, reacB->periodic_box));
} else if (reacA != NULL && reacC != NULL) {
assert(periodic_boxes_are_identical(reacA->periodic_box, reacC->periodic_box));
} else if (reacB != NULL && reacC != NULL) {
assert(periodic_boxes_are_identical(reacB->periodic_box, reacC->periodic_box));
}
bool update_dissociation_index =
false; /* Do we need to advance the dissociation index? */
bool cross_wall = false; /* Did the moving molecule cross the plane? */
struct subvolume *last_subvol =
NULL; /* Last subvolume (guess used to speed sv finding) */
int const i0 =
rx->product_idx[path]; /* index of the first player for the pathway */
int const iN =
rx->product_idx[path + 1]; /* index of the first player for the next
pathway */
assert(iN > i0);
struct species **rx_players =
rx->players + i0; /* Players array from the reaction. */
int const n_players = iN - i0; /* number of reaction players */
std::vector<struct abstract_molecule *> product(n_players); /* array of products */
/* array that decodes the type of each product */
std::vector<char> product_type(n_players);
std::vector<short> product_orient(n_players); /* array of orientations for each product */
/* array of surface_grids for products */
std::vector<struct surface_grid *> product_grid(n_players);
std::vector<int> product_grid_idx(n_players); /* array of grid indices for products */
std::vector<byte> product_flag(n_players); /* array of placement flags for products */
struct tile_neighbor *tile_nbr_head = NULL; /* list of neighbor tiles */
struct tile_neighbor *tile_nbr; /* iterator */
/* head of the linked list of vacant neighbor tiles */
struct tile_neighbor *tile_vacant_nbr_head = NULL;
struct surface_grid *tile_grid; /* surface grid the tile belongs to */
int tile_idx; /* index of the tile on the grid */
unsigned int rnd_num; /* random number */
int num_vacant_tiles = 0; /* number of vacant tiles */
int num_surface_products = 0; /* not counting reactants */
int num_surface_static_products =
0; /* # of products with (D_2D == 0) not counting reactants */
int num_surface_static_reactants = 0; /* # of reactants with (D_2D == 0) */
/* total number of surface reactants */
int num_surface_reactants = 0;
/* number of surface reactants that are not replaced in the reaction */
int num_surface_reactants_to_stay = 0;
int list_length; /* length of the linked list tile_nbr_head */
/* flags */
int replace_p1 = 0, replace_p2 = 0, replace_p3 = 0, only_one_to_replace = 0,
two_to_replace = 0;
int find_neighbor_tiles_flag = 0;
struct wall *w_1, *w_2, *w_3;
/* flag that indicates that all reactants lie inside their
respective restrictive regions */
int all_inside_restricted_boundary = 0;
/* flag that indicates that all reactants lie outside
their respective restrictive regions */
int all_outside_restricted_boundary = 0;
/* flag that indicates that reactants "sm_1" and "sm_2"
lies inside and reactant "grid_3" lies outside of their
respective restrictive regions */
int sm_1_inside_sm_2_inside_grid_3_outside = 0;
/* flag that indicates that reactants "sm_1" and "grid_3"
lies inside and reactant "sm_2" lies outside of their
respective restrictive regions */
int sm_1_inside_sm_2_outside_grid_3_inside = 0;
/* flag that indicates that reactant "sm_1" lies outside
and reactants "sm_2" and "grid_3" lie inside of their
respective restrictive regions */
int sm_1_outside_sm_2_inside_grid_3_inside = 0;
/* flag that indicates that reactant "sm_1" lies inside
and reactants "sm_2" and "grid_3" lie outside of their
respective restrictive regions */
int sm_1_inside_sm_2_outside_grid_3_outside = 0;
/* flag that indicates that reactants "sm_1" and "grid_3" lie outside
and reactant "sm_2" lies inside of their
respective restrictive regions */
int sm_1_outside_sm_2_inside_grid_3_outside = 0;
/* flag that indicates that reactants "sm_1" and "sm_2"
lie outside and reactant "grid_3" lies inside of their
respective restrictive regions */
int sm_1_outside_sm_2_outside_grid_3_inside = 0;
/* flag that indicates that reactants "sm_1" and "sm_2"
lie inside their respective restrictive regions
and reactant "grid_3" has no restrictive region border properties */
int only_sm_1_sm_2_inside = 0;
/* flag that indicates that reactant "sm_1" lies inside
and "sm_2" lies outside their respective restrictive regions
and reactant "grid_3" has no restrictive region border properties */
int only_sm_1_inside_sm_2_outside = 0;
/* flag that indicates that reactant "sm_1" lies outside
and "sm_2" lies inside their respective restrictive regions
and reactant "grid_3" has no restrictive region border properties */
int only_sm_1_outside_sm_2_inside = 0;
/* flag that indicates that reactants "sm_1" and "sm_2"
lie outside their respective restrictive regions
and reactant "grid_3" has no restrictive region border properties */
int only_sm_1_sm_2_outside = 0;
/* flag that indicates that reactants "sm_1" and "grid_3"
lie inside their respective restrictive regions
and reactant "sm_2" has no restrictive region border properties */
int only_sm_1_grid_3_inside = 0;
/* flag that indicates that reactant "sm_1" lies inside
and "grid_3" lies outside their respective restrictive regions
and reactant "sm_2" has no restrictive region border properties */
int only_sm_1_inside_grid_3_outside = 0;
/* flag that indicates that reactant "sm_1" lies outside
and "grid_3" lies inside their respective restrictive regions
and reactant "sm_2" has no restrictive region border properties */
int only_sm_1_outside_grid_3_inside = 0;
/* flag that indicates that reactants "sm_1" and "grid_3"
lie outside their respective restrictive regions
and reactant "sm_2" has no restrictive region border properties */
int only_sm_1_grid_3_outside = 0;
/* flag that indicates that reactants "sm_2" and "grid_3"
lie inside their respective restrictive regions
and reactant "sm_1" has no restrictive region border properties */
int only_sm_2_grid_3_inside = 0;
/* flag that indicates that reactant "sm_2" lies inside
and "grid_3" lies outside their respective restrictive regions
and reactant "sm_1" has no restrictive region border properties */
int only_sm_2_inside_grid_3_outside = 0;
/* flag that indicates that reactant "sm_2" lies outside
and "grid_3" lies inside their respective restrictive regions
and reactant "sm_1" has no restrictive region border properties */
int only_sm_2_outside_grid_3_inside = 0;
/* flag that indicates that reactants "sm_2" and "grid_3"
lie outside their respective restrictive regions
and reactant "sm_1" has no restrictive region border properties */
int only_sm_2_grid_3_outside = 0;
/* flag that indicates that only reactant "sm_1" has
restrictive regions on the object and it lies
inside it's restrictive region. */
int only_sm_1_inside = 0;
/* flag that indicates that only reactant "sm_1" has
restrictive regions on the object and it lies
outside it's restrictive region. */
int only_sm_1_outside = 0;
/* flag that indicates that only reactant "sm_2" has
restrictive regions on the object and it lies
inside it's restrictive region. */
int only_sm_2_inside = 0;
/* flag that indicates that only reactant "sm_2" has
restrictive regions on the object and it lies
outside it's restrictive region. */
int only_sm_2_outside = 0;
/* flag that indicates that only reactant "grid_3" has
restrictive regions on the object and it lies
inside it's restrictive region. */
int only_grid_3_inside = 0;
/* flag that indicates that only reactant "grid_3" has
restrictive regions on the object and it lies
outside it's restrictive region. */
int only_grid_3_outside = 0;
/* list of the restricted regions for the reactants by wall */
struct region_list *rlp_head_wall_1 = NULL, *rlp_head_wall_2 = NULL,
*rlp_head_wall_3 = NULL;
/* list of the restricted regions for the reactants by object */
struct region_list *rlp_head_obj_1 = NULL, *rlp_head_obj_2 = NULL,
*rlp_head_obj_3 = NULL;
struct vector2 rxn_uv_pos; /* position of the reaction */
int rxn_uv_idx = -1; /* tile index of the reaction place */
struct abstract_molecule *tmp_mol;
short tmp_orient;
if ((reacA == NULL) || (reacB == NULL) || (reacC == NULL)) {
mcell_internal_error("One of the reactants in "
"'outcome_products_trimol_reaction_random()' is "
"NULL.");
}
/* Clear the initial product info. */
for (int i = 0; i < n_players; ++i) {
product[i] = NULL;
product_type[i] = PLAYER_NONE;
product_orient[i] = 0;
product_grid[i] = NULL;
product_grid_idx[i] = -1;
product_flag[i] = PRODUCT_FLAG_NOT_SET;
}
/* Flag indicating that a surface is somehow involved with this reaction. */
struct surface_molecule *const sm_1 =
IS_SURF_MOL(reacA) ? (struct surface_molecule *)reacA : NULL;
struct surface_molecule *const sm_2 =
IS_SURF_MOL(reacB) ? (struct surface_molecule *)reacB : NULL;
struct surface_molecule *const grid_3 =
IS_SURF_MOL(reacC) ? (struct surface_molecule *)reacC : NULL;
struct surface_molecule *sm_reactant = NULL;
if (sm_1 != NULL) {
sm_reactant = sm_1;
} else if (sm_2 != NULL) {
sm_reactant = sm_2;
} else if (grid_3 != NULL) {
sm_reactant = grid_3;
}
bool const is_orientable = (w != NULL) || (sm_reactant != NULL);
/* Where are reactants relative to the restrictive region border? */
if ((sm_1 != NULL) && (sm_2 != NULL) && (grid_3 != NULL)) {
/* trimol_reaction */
if ((sm_1->properties->flags & CAN_REGION_BORDER) &&
(sm_2->properties->flags & CAN_REGION_BORDER) &&
(grid_3->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1) &&
are_restricted_regions_for_species_on_object(
world, sm_2->grid->surface->parent_object, sm_2) &&
are_restricted_regions_for_species_on_object(
world, grid_3->grid->surface->parent_object, grid_3)) {
w_1 = sm_1->grid->surface;
w_2 = sm_2->grid->surface;
w_3 = grid_3->grid->surface;
rlp_head_wall_1 = find_restricted_regions_by_wall(world, w_1, sm_1);
rlp_head_wall_2 = find_restricted_regions_by_wall(world, w_2, sm_2);
rlp_head_wall_3 = find_restricted_regions_by_wall(world, w_3, grid_3);
if ((rlp_head_wall_1 != NULL) && (rlp_head_wall_2 != NULL) &&
(rlp_head_wall_3 != NULL)) {
/* all reactants are inside their respective
restricted regions */
all_inside_restricted_boundary = 1;
} else if ((rlp_head_wall_1 == NULL) && (rlp_head_wall_2 == NULL) &&
(rlp_head_wall_3 == NULL)) {
/* all reactants are outside their respective
restricted regions */
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
rlp_head_obj_3 = find_restricted_regions_by_object(
world, w_3->parent_object, grid_3);
all_outside_restricted_boundary = 1;
} else if ((rlp_head_wall_1 != NULL) && (rlp_head_wall_2 != NULL) &&
(rlp_head_wall_3 == NULL)) {
rlp_head_obj_3 = find_restricted_regions_by_object(
world, w_3->parent_object, grid_3);
sm_1_inside_sm_2_inside_grid_3_outside = 1;
} else if ((rlp_head_wall_1 != NULL) && (rlp_head_wall_3 != NULL) &&
(rlp_head_wall_2 == NULL)) {
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
sm_1_inside_sm_2_outside_grid_3_inside = 1;
} else if ((rlp_head_wall_1 == NULL) && (rlp_head_wall_2 != NULL) &&
(rlp_head_wall_3 == NULL)) {
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
rlp_head_obj_3 = find_restricted_regions_by_object(
world, w_3->parent_object, grid_3);
sm_1_outside_sm_2_inside_grid_3_outside = 1;
} else if ((rlp_head_wall_1 != NULL) && (rlp_head_wall_2 == NULL) &&
(rlp_head_wall_3 == NULL)) {
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
rlp_head_obj_3 = find_restricted_regions_by_object(
world, w_3->parent_object, grid_3);
sm_1_inside_sm_2_outside_grid_3_outside = 1;
} else if ((rlp_head_wall_1 == NULL) && (rlp_head_wall_2 != NULL) &&
(rlp_head_wall_3 != NULL)) {
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
sm_1_outside_sm_2_inside_grid_3_inside = 1;
} else if ((rlp_head_wall_1 == NULL) && (rlp_head_wall_2 == NULL) &&
(rlp_head_wall_3 != NULL)) {
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
sm_1_outside_sm_2_outside_grid_3_inside = 1;
}
} else if ((sm_1->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1) &&
(sm_2->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_2->grid->surface->parent_object, sm_2) &&
(!(grid_3->properties->flags & CAN_REGION_BORDER) ||
!are_restricted_regions_for_species_on_object(
world, grid_3->grid->surface->parent_object, grid_3))) {
/* only reactants "sm_1" and "sm_2" have restrictive
region border property */
w_1 = sm_1->grid->surface;
rlp_head_wall_1 = find_restricted_regions_by_wall(world, w_1, sm_1);
w_2 = sm_2->grid->surface;
rlp_head_wall_2 = find_restricted_regions_by_wall(world, w_2, sm_2);
if ((rlp_head_wall_1 != NULL) && (rlp_head_wall_2 != NULL)) {
only_sm_1_sm_2_inside = 1;
} else if ((rlp_head_wall_1 != NULL) && (rlp_head_wall_2 == NULL)) {
only_sm_1_inside_sm_2_outside = 1;
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
} else if ((rlp_head_wall_1 == NULL) && (rlp_head_wall_2 != NULL)) {
only_sm_1_outside_sm_2_inside = 1;
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
} else if ((rlp_head_wall_1 == NULL) && (rlp_head_wall_2 == NULL)) {
only_sm_1_sm_2_outside = 1;
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
}
} else if ((sm_1->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1) &&
(!(sm_2->properties->flags & CAN_REGION_BORDER) ||
!are_restricted_regions_for_species_on_object(
world, sm_2->grid->surface->parent_object, sm_2)) &&
(grid_3->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, grid_3->grid->surface->parent_object, grid_3)) {
/* only reactants "sm_1" and "grid_3" have restrictive
region border property */
w_1 = sm_1->grid->surface;
rlp_head_wall_1 = find_restricted_regions_by_wall(world, w_1, sm_1);
w_3 = grid_3->grid->surface;
rlp_head_wall_3 = find_restricted_regions_by_wall(world, w_3, grid_3);
if ((rlp_head_wall_1 != NULL) && (rlp_head_wall_3 != NULL)) {
only_sm_1_grid_3_inside = 1;
} else if ((rlp_head_wall_1 != NULL) && (rlp_head_wall_3 == NULL)) {
only_sm_1_inside_grid_3_outside = 1;
rlp_head_obj_3 = find_restricted_regions_by_object(
world, w_3->parent_object, grid_3);
} else if ((rlp_head_wall_1 == NULL) && (rlp_head_wall_3 != NULL)) {
only_sm_1_outside_grid_3_inside = 1;
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
} else if ((rlp_head_wall_1 == NULL) && (rlp_head_wall_3 == NULL)) {
only_sm_1_grid_3_outside = 1;
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
rlp_head_obj_3 = find_restricted_regions_by_object(
world, w_3->parent_object, grid_3);
}
} else if ((!(sm_1->properties->flags & CAN_REGION_BORDER) ||
(!are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1))) &&
(sm_2->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_2->grid->surface->parent_object, sm_2) &&
(grid_3->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, grid_3->grid->surface->parent_object, grid_3)) {
/* only reactants "sm_2" and "grid_3" have restrictive
region border property */
w_2 = sm_2->grid->surface;
rlp_head_wall_2 = find_restricted_regions_by_wall(world, w_2, sm_2);
w_3 = grid_3->grid->surface;
rlp_head_wall_3 = find_restricted_regions_by_wall(world, w_3, grid_3);
if ((rlp_head_wall_2 != NULL) && (rlp_head_wall_3 != NULL)) {
only_sm_2_grid_3_inside = 1;
} else if ((rlp_head_wall_2 != NULL) && (rlp_head_wall_3 == NULL)) {
only_sm_2_inside_grid_3_outside = 1;
rlp_head_obj_3 = find_restricted_regions_by_object(
world, w_3->parent_object, grid_3);
} else if ((rlp_head_wall_2 == NULL) && (rlp_head_wall_3 != NULL)) {
only_sm_2_outside_grid_3_inside = 1;
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
} else if ((rlp_head_wall_2 == NULL) && (rlp_head_wall_3 == NULL)) {
only_sm_2_grid_3_outside = 1;
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
rlp_head_obj_3 = find_restricted_regions_by_object(
world, w_3->parent_object, grid_3);
}
} else if ((sm_1->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1) &&
(!(sm_2->properties->flags & CAN_REGION_BORDER) ||
!are_restricted_regions_for_species_on_object(
world, sm_2->grid->surface->parent_object, sm_2)) &&
(!(grid_3->properties->flags & CAN_REGION_BORDER) ||
!are_restricted_regions_for_species_on_object(
world, grid_3->grid->surface->parent_object, grid_3))) {
/* only reactant "sm_1" has restrictive region border property */
w_1 = sm_1->grid->surface;
rlp_head_wall_1 = find_restricted_regions_by_wall(world, w_1, sm_1);
if (rlp_head_wall_1 != NULL) {
only_sm_1_inside = 1;
} else {
rlp_head_obj_1 =
find_restricted_regions_by_object(world, w_1->parent_object, sm_1);
only_sm_1_outside = 1;
}
} else if ((sm_2->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, sm_2->grid->surface->parent_object, sm_2) &&
(!(sm_1->properties->flags & CAN_REGION_BORDER) ||
!are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1)) &&
(!(grid_3->properties->flags & CAN_REGION_BORDER) ||
!are_restricted_regions_for_species_on_object(
world, grid_3->grid->surface->parent_object, grid_3))) {
/* only reactant "sm_2" has restrictive region border property */
w_2 = sm_2->grid->surface;
rlp_head_wall_2 = find_restricted_regions_by_wall(world, w_2, sm_2);
if (rlp_head_wall_2 != NULL)
only_sm_2_inside = 1;
else {
rlp_head_obj_2 =
find_restricted_regions_by_object(world, w_2->parent_object, sm_2);
only_sm_2_outside = 1;
}
} else if ((grid_3->properties->flags & CAN_REGION_BORDER) &&
are_restricted_regions_for_species_on_object(
world, grid_3->grid->surface->parent_object, grid_3) &&
(!(sm_1->properties->flags & CAN_REGION_BORDER) ||
!are_restricted_regions_for_species_on_object(
world, sm_1->grid->surface->parent_object, sm_1)) &&
(!(sm_2->properties->flags & CAN_REGION_BORDER) ||
!are_restricted_regions_for_species_on_object(
world, sm_2->grid->surface->parent_object, sm_2))) {
/* only reactant "grid_3" has restrictive region border property */
w_3 = grid_3->grid->surface;
rlp_head_wall_3 = find_restricted_regions_by_wall(world, w_3, grid_3);
if (rlp_head_wall_3 != NULL)
only_grid_3_inside = 1;
else {
rlp_head_obj_3 = find_restricted_regions_by_object(
world, w_3->parent_object, grid_3);
only_grid_3_outside = 1;
}
}
}
/* reacA is the molecule which initiated the reaction. */
struct abstract_molecule *const initiator = reacA;
short const initiatorOrient = orientA;
/* make sure that reacA corresponds to rx->players[0],
reacB - to rx->players[1], and reacC - to rx->players[2]
in trimolecular reaction */
if (reacA->properties == rx->players[0]) {
if (reacB->properties == rx->players[2] &&
reacB->properties != rx->players[1]) {
/* switch B and C */
tmp_mol = reacB;
reacB = reacC;
reacC = tmp_mol;
tmp_orient = orientB;
orientB = orientC;
orientC = tmp_orient;
}
} else if (reacA->properties == rx->players[1]) {
if (reacB->properties == rx->players[0] &&
reacB->properties != rx->players[1]) {
/* switch reacA and reacB */
tmp_mol = reacB;
reacB = reacA;
reacA = tmp_mol;
tmp_orient = orientB;
orientB = orientA;
orientA = tmp_orient;
} else if (reacC->properties == rx->players[0]) {
/* switch reacA and reacC */
tmp_mol = reacA;
reacA = reacC;
reacC = tmp_mol;
tmp_orient = orientA;
orientA = orientC;
orientC = tmp_orient;
/* now switch reacC and reacB */
tmp_mol = reacB;
reacB = reacC;
reacC = tmp_mol;
tmp_orient = orientB;
orientB = orientC;
orientC = tmp_orient;
}
} else if (reacA->properties == rx->players[2]) {
if (reacB->properties == rx->players[0]) {
/* switch reacA and reacB */
tmp_mol = reacB;
reacB = reacA;
reacA = tmp_mol;
tmp_orient = orientB;
orientB = orientA;
orientA = tmp_orient;
/* switch reacB and reacC */
tmp_mol = reacB;
reacB = reacC;
reacC = tmp_mol;
tmp_orient = orientB;
orientB = orientC;
orientC = tmp_orient;
} else if ((reacC->properties == rx->players[0]) &&
(reacC->properties != rx->players[2])) {
/* switch reacA and reacC */
tmp_mol = reacA;
reacA = reacC;
reacC = tmp_mol;
tmp_orient = orientA;
orientA = orientC;
orientC = tmp_orient;
}
}
add_reactants_to_product_list(rx, reacA, reacB, reacC, &product[0], &product_type[0]);
/* Determine whether any of the reactants can be replaced by a product. */
if (product_type[0] == PLAYER_SURF_MOL) {
num_surface_reactants++;
if (rx_players[0] == NULL)
replace_p1 = 1;
else
num_surface_reactants_to_stay++;
}
if (product_type[1] == PLAYER_SURF_MOL) {
num_surface_reactants++;
if (rx_players[1] == NULL)
replace_p2 = 1;
else
num_surface_reactants_to_stay++;
}
if (product_type[2] == PLAYER_SURF_MOL) {
num_surface_reactants++;
if (rx_players[2] == NULL)
replace_p3 = 1;
else
num_surface_reactants_to_stay++;
}
if (replace_p1 && (!replace_p2) && (!replace_p3)) {
only_one_to_replace = 1;
} else if ((!replace_p1) && replace_p2 && (!replace_p3)) {
only_one_to_replace = 1;
} else if ((!replace_p1) && (!replace_p2) && replace_p3) {
only_one_to_replace = 1;
}
if (replace_p1 && (replace_p2) && (!replace_p3)) {
two_to_replace = 1;
} else if (replace_p1 && (!replace_p2) && replace_p3) {
two_to_replace = 1;
} else if ((!replace_p1) && replace_p2 && replace_p3) {
two_to_replace = 1;
}
/* find out number of surface products */
for (int n_product = rx->n_reactants; n_product < n_players; ++n_product) {
if (rx_players[n_product] == NULL)
continue;
if (rx_players[n_product]->flags & ON_GRID) {
num_surface_products++;
if (!distinguishable(rx_players[n_product]->D, 0, EPS_C))
num_surface_static_products++;
}
}
if (num_surface_reactants >= 2)
find_neighbor_tiles_flag = 1;
if ((num_surface_reactants == 1) && (num_surface_products > 1))
find_neighbor_tiles_flag = 1;
/* Determine the point of reaction on the surface. */
if (is_orientable) {
if (sm_reactant)
rxn_uv_pos = sm_reactant->s_pos;
else {
xyz2uv(hitpt, w, &rxn_uv_pos);
}
if ((w == NULL) && (sm_reactant != NULL))
w = sm_reactant->grid->surface;
assert(w != NULL);
if (w->grid == NULL) {
/* reacA must be a volume molecule, or this wall would have a grid
* already. */
assert(!IS_SURF_MOL(reacA));
if (create_grid(world, w, ((struct volume_molecule *)reacA)->subvol))
mcell_allocfailed("Failed to create a grid for a wall.");
}
if (find_neighbor_tiles_flag) {
/* create list of neighbor tiles around rxn_uv_pos */
rxn_uv_idx = uv2grid(&rxn_uv_pos, w->grid);
if (sm_reactant != NULL) {
find_neighbor_tiles(world, sm_reactant, sm_reactant->grid,
sm_reactant->grid_index, 1, 0, &tile_nbr_head,
&list_length);
} else {
find_neighbor_tiles(world, sm_reactant, w->grid, rxn_uv_idx, 1, 0,
&tile_nbr_head, &list_length);
}
/* Create list of vacant tiles */
for (tile_nbr = tile_nbr_head; tile_nbr != NULL;
tile_nbr = tile_nbr->next) {
struct surface_molecule_list *sm_list = tile_nbr->grid->sm_list[tile_nbr->idx];
if (sm_list == NULL || sm_list->sm == NULL) {
num_vacant_tiles++;
push_tile_neighbor_to_list(&tile_vacant_nbr_head, tile_nbr->grid,
tile_nbr->idx);
}
}
}
}
/* find out number of static surface reactants */
if ((sm_1 != NULL) && !distinguishable(sm_1->properties->D, 0, EPS_C))
num_surface_static_reactants++;
if ((sm_2 != NULL) && !distinguishable(sm_2->properties->D, 0, EPS_C))
num_surface_static_reactants++;
if ((grid_3 != NULL) && !distinguishable(grid_3->properties->D, 0, EPS_C))
num_surface_static_reactants++;
/* If the reaction involves a surface, make sure there is room for each
* product. */
if (is_orientable) {
/* Can this reaction happen at all? */
if (replace_p1 && replace_p2 && replace_p3) {
if (num_surface_products > num_vacant_tiles + 3) {
if (tile_nbr_head != NULL)
delete_tile_neighbor_list(tile_nbr_head);
if (tile_vacant_nbr_head != NULL)
delete_tile_neighbor_list(tile_vacant_nbr_head);
return RX_BLOCKED;
}
} else if (two_to_replace) {
if (num_surface_products > num_vacant_tiles + 2) {
if (tile_nbr_head != NULL)
delete_tile_neighbor_list(tile_nbr_head);
if (tile_vacant_nbr_head != NULL)
delete_tile_neighbor_list(tile_vacant_nbr_head);
return RX_BLOCKED;
}
} else if (only_one_to_replace) {
if (num_surface_products > num_vacant_tiles + 1) {
if (tile_nbr_head != NULL)
delete_tile_neighbor_list(tile_nbr_head);
if (tile_vacant_nbr_head != NULL)
delete_tile_neighbor_list(tile_vacant_nbr_head);
return RX_BLOCKED;
}
} else {
/* none of the reactants is replaced */
if (num_surface_products > num_vacant_tiles) {
if (tile_nbr_head != NULL)
delete_tile_neighbor_list(tile_nbr_head);
if (tile_vacant_nbr_head != NULL)
delete_tile_neighbor_list(tile_vacant_nbr_head);
return RX_BLOCKED;
}
}
/* set the orientations of the products. */
for (int n_product = 0; n_product < n_players; ++n_product) {
/* Skip NULL reactants. */
if (rx_players[n_product] == NULL)
continue;
int this_geometry = rx->geometries[i0 + n_product];
/* Geometry of 0 means "random orientation" */
if (this_geometry == 0)
product_orient[n_product] = (rng_uint(world->rng) & 1) ? 1 : -1;
else {
/* Geometry < 0 means inverted orientation */
if (this_geometry < 0) {
this_geometry = -this_geometry;
if (this_geometry > (int)rx->n_reactants)
product_orient[n_product] =
-product_orient[this_geometry - rx->n_reactants - 1];
else if (this_geometry == 1)
product_orient[n_product] = -orientA;
else if ((this_geometry == 2) && (reacB != NULL))
product_orient[n_product] = -orientB;
else if ((this_geometry == 3) && (reacC != NULL))
product_orient[n_product] = -orientC;
else
product_orient[n_product] = -1;
}
/* Geometry > 0 means "positive" orientation. */
else {
if (this_geometry > (int)rx->n_reactants)
product_orient[n_product] =
product_orient[this_geometry - rx->n_reactants - 1];
else if (this_geometry == 1)
product_orient[n_product] = orientA;
else if ((this_geometry == 2) && (reacB != NULL))
product_orient[n_product] = orientB;
else if ((this_geometry == 3) && (reacC != NULL))
product_orient[n_product] = orientC;
else
product_orient[n_product] = 1;
}
}
/* If this is a reactant... */
if (n_product < (int)rx->n_reactants) {
/* If this is a surface molecule, we need to set its orientation. */
if (rx_players[n_product]->flags & ON_GRID) {
assert(IS_SURF_MOL(product[n_product]));
struct surface_molecule *sm =
(struct surface_molecule *)product[n_product];
/* If the new orientation doesn't match the old, we've got some work
* to do. */
if (sm->orient != product_orient[n_product]) {
/* We're about to update the molecule's orientation, so we will
* first remove it from the counts in case we have any
* orientation-sensitive counts. Then, we will update the
* orientation. Finally, we will add the molecule back into the
* counts in its new orientation.
*/
/* Remove molecule from counts in old orientation, if mol is
* counted. */
if (product[n_product]->properties->flags &
(COUNT_CONTENTS | COUNT_ENCLOSED))
count_region_from_scratch(world,
product[n_product], /* molecule */
NULL, /* rxn pathway */
-1, /* remove count */
NULL, /* Location at which to count */
w, /* Wall on which this happened */
t, /* Time of occurrence */
NULL);
/* Force check for the unimolecular reactions
after changing orientation.
There are two possible cases to be covered here:
1) when (sm->t2) was previously set to FOREVER
2) there may be two or more unimolecular
reactions involving surface class that have
different kinetics.
*/
if (((sm->flags & ACT_REACT) != 0) &&
((sm->properties->flags & CAN_SURFWALL) != 0))
sm->t2 = 0;
/* Set the molecule's orientation. */
sm->orient = product_orient[n_product];
/* Add molecule back to counts in new orientation, if mol is
* counted. */
if (product[n_product]->properties->flags &
(COUNT_CONTENTS | COUNT_ENCLOSED))
count_region_from_scratch(world,
product[n_product], /* molecule */
NULL, /* rxn pathway */
1, /* add count */
NULL, /* Location at which to count */
w, /* Wall on which this happened */
t, /* Time of occurrence */
NULL);
}
}
/* Otherwise, check if we've crossed the plane. */
else {
if (product[n_product] == initiator) {
if (product_orient[n_product] != initiatorOrient)
cross_wall = true;
}
}
}
}
/* find out where to place surface products */
/* Some special cases are listed below. */
if (num_surface_products == 1) {
if ((num_surface_static_reactants == 1) &&
(num_surface_static_products == 1) &&
(replace_p1 || replace_p2 || replace_p3)) {
/* the lonely static product always replaces the lonely static reactant
*/
for (int n_product = rx->n_reactants; n_product < n_players;
n_product++) {
if (rx_players[n_product] == NULL)
continue;
if ((rx_players[n_product]->flags & NOT_FREE) == 0)
continue;
if (distinguishable(rx_players[n_product]->D, 0, EPS_C))
continue;
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET) {
if (replace_p1 && !distinguishable(reacA->properties->D, 0, EPS_C)) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[n_product] =
((struct surface_molecule *)reacA)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
break;
} else if (replace_p2 && !distinguishable(reacB->properties->D, 0, EPS_C)) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[n_product] =
((struct surface_molecule *)reacB)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacB)->grid_index;
replace_p2 = 0;
break;
} else if (replace_p3 && !distinguishable(reacC->properties->D, 0, EPS_C)) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACC_UV;
product_grid[n_product] =
((struct surface_molecule *)reacC)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacC)->grid_index;
replace_p3 = 0;
break;
}
}
}
} else if (replace_p1 && replace_p2 && replace_p3) {
/* if all reactants should be replaced and there is only one
surface product here we make sure that initiator molecule
is replaced */
for (int n_product = rx->n_reactants; n_product < n_players;
n_product++) {
if (rx_players[n_product] == NULL)
continue;
if ((rx_players[n_product]->flags & NOT_FREE) == 0)
continue;
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET) {
if (reacA == initiator) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[n_product] =
((struct surface_molecule *)reacA)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
} else if (reacB == initiator) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[n_product] =
((struct surface_molecule *)reacB)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacB)->grid_index;
replace_p2 = 0;
} else {
product_flag[n_product] = PRODUCT_FLAG_USE_REACC_UV;
product_grid[n_product] =
((struct surface_molecule *)reacC)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacC)->grid_index;
replace_p3 = 0;
}
break;
}
}
} else if (two_to_replace) {
/* replace one of the two reactants randomly */
while (true) {
rnd_num = rng_uint(world->rng) % (rx->n_reactants);
if ((rnd_num == 0) && replace_p1)
break;
if ((rnd_num == 1) && replace_p2)
break;
if ((rnd_num == 2) && replace_p3)
break;
}
for (int n_product = rx->n_reactants; n_product < n_players;
n_product++) {
if (rx_players[n_product] == NULL)
continue;
if ((rx_players[n_product]->flags & NOT_FREE) == 0)
continue;
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET) {
if (rnd_num == 0) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[n_product] =
((struct surface_molecule *)reacA)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
} else if (rnd_num == 1) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[n_product] =
((struct surface_molecule *)reacB)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacB)->grid_index;
replace_p2 = 0;
} else if (rnd_num == 2) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACC_UV;
product_grid[n_product] =
((struct surface_molecule *)reacC)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacC)->grid_index;
replace_p3 = 0;
}
break;
}
}
} else if (only_one_to_replace) {
/* no need for a random number here */
for (int n_product = rx->n_reactants; n_product < n_players;
n_product++) {
if (rx_players[n_product] == NULL)
continue;
if ((rx_players[n_product]->flags & NOT_FREE) == 0)
continue;
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET) {
if (replace_p1) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[n_product] =
((struct surface_molecule *)reacA)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
break;
} else if (replace_p2) {
product_flag[n_product] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[n_product] =
((struct surface_molecule *)reacB)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacB)->grid_index;
replace_p2 = 0;
break;
} else {
product_flag[n_product] = PRODUCT_FLAG_USE_REACC_UV;
product_grid[n_product] =
((struct surface_molecule *)reacC)->grid;
product_grid_idx[n_product] =
((struct surface_molecule *)reacC)->grid_index;
replace_p3 = 0;
break;
}
}
}
}
} else if (num_surface_products > 1) {
int count;
if (num_surface_static_reactants > 0) {
if (num_surface_static_products >= num_surface_static_reactants) {
count = 0;
while (count < num_surface_static_reactants) {
rnd_num = rng_uint(world->rng) % n_players;
/* pass reactants */
if (rnd_num < 3)
continue;
if (rx_players[rnd_num] == NULL)
continue;
if ((rx_players[rnd_num]->flags & NOT_FREE) == 0)
continue;
if (distinguishable(rx_players[rnd_num]->D, 0, EPS_C))
continue;
if (product_flag[rnd_num] == PRODUCT_FLAG_NOT_SET) {
if ((!distinguishable(reacA->properties->D, 0, EPS_C)) && replace_p1) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacA)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
count++;
continue;
}
if ((!distinguishable(reacB->properties->D, 0, EPS_C)) && replace_p2) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacB)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacB)->grid_index;
replace_p2 = 0;
count++;
continue;
}
if ((!distinguishable(reacC->properties->D, 0, EPS_C)) && replace_p3) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACC_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacC)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacC)->grid_index;
replace_p3 = 0;
count++;
continue;
}
}
} /* end while */
} else { /*(num_surface_static_products<num_surface_static_reactants)*/
count = 0;
while (count < num_surface_static_products) {
rnd_num = rng_uint(world->rng) % n_players;
/* pass reactants */
if (rnd_num < 3)
continue;
if (rx_players[rnd_num] == NULL)
continue;
if ((rx_players[rnd_num]->flags & NOT_FREE) == 0)
continue;
if (distinguishable(rx_players[rnd_num]->D, 0, EPS_C))
continue;
if (product_flag[rnd_num] == PRODUCT_FLAG_NOT_SET) {
if ((!distinguishable(reacA->properties->D, 0, EPS_C)) && replace_p1) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacA)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
count++;
continue;
}
if ((!distinguishable(reacB->properties->D, 0, EPS_C)) && replace_p2) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacB)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacB)->grid_index;
replace_p2 = 0;
count++;
continue;
}
if ((!distinguishable(reacC->properties->D, 0, EPS_C)) && replace_p3) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACC_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacC)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacC)->grid_index;
replace_p3 = 0;
count++;
continue;
}
}
} /* end while */
}
}
/* check whether there are any surface reactants left to replace
with surface products since we are done with static
reactants/products */
if (replace_p1 || replace_p2 || replace_p3) {
/* are there any surface products left that have not replaced yet
reactants? */
int surf_prod_left = 0, surf_reactant_left = 0;
for (int n_product = rx->n_reactants; n_product < n_players;
n_product++) {
if (rx_players[n_product] == NULL)
continue;
if ((rx_players[n_product]->flags & NOT_FREE) == 0)
continue;
if (product_flag[n_product] == PRODUCT_FLAG_NOT_SET)
surf_prod_left++;
}
if (replace_p1)
surf_reactant_left++;
if (replace_p2)
surf_reactant_left++;
if (replace_p3)
surf_reactant_left++;
if (surf_prod_left > 0) {
if (surf_prod_left >= surf_reactant_left) {
count = 0;
while (count < surf_reactant_left) {
rnd_num = rng_uint(world->rng) % n_players;
/* pass reactants */
if (rnd_num < 3)
continue;
if (rx_players[rnd_num] == NULL)
continue;
if ((rx_players[rnd_num]->flags & NOT_FREE) == 0)
continue;
if (product_flag[rnd_num] == PRODUCT_FLAG_NOT_SET) {
if (replace_p1) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacA)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
count++;
continue;
}
if (replace_p2) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacB)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacB)->grid_index;
replace_p2 = 0;
count++;
continue;
}
if (replace_p3) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACC_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacC)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacC)->grid_index;
replace_p3 = 0;
count++;
continue;
}
}
} /* end while */
} else { /* surf_prod_left < surf_reactant_left */
count = 0;
while (count < surf_prod_left) {
rnd_num = rng_uint(world->rng) % n_players;
/* pass reactants */
if (rnd_num < 3)
continue;
if (rx_players[rnd_num] == NULL)
continue;
if ((rx_players[rnd_num]->flags & NOT_FREE) == 0)
continue;
if (product_flag[rnd_num] == PRODUCT_FLAG_NOT_SET) {
if (replace_p1) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACA_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacA)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacA)->grid_index;
replace_p1 = 0;
count++;
continue;
}
if (replace_p2) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACB_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacB)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacB)->grid_index;
replace_p2 = 0;
count++;
continue;
}
if (replace_p3) {
product_flag[rnd_num] = PRODUCT_FLAG_USE_REACC_UV;
product_grid[rnd_num] =
((struct surface_molecule *)reacC)->grid;
product_grid_idx[rnd_num] =
((struct surface_molecule *)reacC)->grid_index;
replace_p3 = 0;
count++;
continue;
}
}
} /* end while */
}
}
}
}
int num_attempts = 0;
/* all other products are placed on one of the randomly chosen vacant
tiles */
for (int n_product = rx->n_reactants; n_product < n_players; ++n_product) {
/* If the product is a volume product, no placement is required. */
if (rx_players[n_product]->flags & ON_GRID) {
if (product_flag[n_product] != PRODUCT_FLAG_NOT_SET)
continue;
if (num_vacant_tiles == 0) {
if (tile_nbr_head != NULL)
delete_tile_neighbor_list(tile_nbr_head);
if (tile_vacant_nbr_head != NULL)
delete_tile_neighbor_list(tile_vacant_nbr_head);
return RX_BLOCKED;
}
while (true) {
if (num_attempts > SURFACE_DIFFUSION_RETRIES) {
if (tile_nbr_head != NULL)
delete_tile_neighbor_list(tile_nbr_head);
if (tile_vacant_nbr_head != NULL)
delete_tile_neighbor_list(tile_vacant_nbr_head);
return RX_BLOCKED;
}
/* randomly pick a tile from the list */
rnd_num = rng_uint(world->rng) % num_vacant_tiles;
tile_idx = -1;
tile_grid = NULL;
if (get_tile_neighbor_from_list_of_vacant_neighbors(
tile_vacant_nbr_head, rnd_num, &tile_grid, &tile_idx) == 0) {
if (tile_nbr_head != NULL)
delete_tile_neighbor_list(tile_nbr_head);
if (tile_vacant_nbr_head != NULL)
delete_tile_neighbor_list(tile_vacant_nbr_head);
return RX_BLOCKED;
}
if (tile_idx < 0)
continue; /* this tile was checked out before */
assert(tile_grid != NULL);
if (all_inside_restricted_boundary) {
/* if this tile is not inside the restricted boundary
- try again */
int cond_1 = 0, cond_2 = 0, cond_3 = 0;
cond_1 = (!wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_1));
cond_2 = (!wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_2));
cond_3 = (!wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_3));
if (cond_1 || cond_2 || cond_3) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (all_outside_restricted_boundary) {
int cond_1 = 0, cond_2 = 0, cond_3 = 0;
cond_1 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_1);
cond_2 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_2);
cond_3 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_3);
if (cond_1 || cond_2 || cond_3) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (sm_1_inside_sm_2_inside_grid_3_outside) {
int cond_1 = 0, cond_2 = 0, cond_3 = 0;
cond_1 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_1));
cond_2 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_2));
cond_3 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_3);
if (cond_1 || cond_2 || cond_3) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (sm_1_inside_sm_2_outside_grid_3_inside) {
int cond_1 = 0, cond_2 = 0, cond_3 = 0;
cond_1 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_1));
cond_2 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_2);
cond_3 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_3));
if (cond_1 || cond_2 || cond_3) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (sm_1_inside_sm_2_outside_grid_3_outside) {
int cond_1 = 0, cond_2 = 0, cond_3 = 0;
cond_1 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_1));
cond_2 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_2);
cond_3 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_3);
if (cond_1 || cond_2 || cond_3) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (sm_1_outside_sm_2_inside_grid_3_outside) {
int cond_1 = 0, cond_2 = 0, cond_3 = 0;
cond_1 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_1);
cond_2 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_2));
cond_3 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_3);
if (cond_1 || cond_2 || cond_3) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (sm_1_outside_sm_2_inside_grid_3_inside) {
int cond_1 = 0, cond_2 = 0, cond_3 = 0;
cond_1 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_1);
cond_2 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_2));
cond_3 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_3));
if (cond_1 || cond_2 || cond_3) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (sm_1_outside_sm_2_outside_grid_3_inside) {
int cond_1 = 0, cond_2 = 0, cond_3 = 0;
cond_1 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_1);
cond_2 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_2);
cond_3 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_3));
if (cond_1 || cond_2 || cond_3) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_1_sm_2_inside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_1));
cond_2 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_2));
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_1_inside_sm_2_outside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_1));
cond_2 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_2);
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_1_outside_sm_2_inside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_1);
cond_2 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_2));
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_1_sm_2_outside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_1);
cond_2 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_2);
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_1_grid_3_inside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_1));
cond_2 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_3));
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_1_inside_grid_3_outside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_1));
cond_2 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_3);
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_1_outside_grid_3_inside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_1);
cond_2 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_3));
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_1_grid_3_outside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_1);
cond_2 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_3);
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_2_grid_3_inside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_2));
cond_2 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_3));
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_2_inside_grid_3_outside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_2));
cond_2 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_3);
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_2_outside_grid_3_inside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_2);
cond_2 = !(wall_belongs_to_all_regions_in_region_list(
tile_grid->surface, rlp_head_wall_3));
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_2_grid_3_outside) {
int cond_1 = 0, cond_2 = 0;
cond_1 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_2);
cond_2 = wall_belongs_to_any_region_in_region_list(
tile_grid->surface, rlp_head_obj_3);
if (cond_1 || cond_2) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_1_inside) {
if (!wall_belongs_to_all_regions_in_region_list(tile_grid->surface,
rlp_head_wall_1)) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_1_outside) {
if (wall_belongs_to_any_region_in_region_list(tile_grid->surface,
rlp_head_obj_1)) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_2_inside) {
if (!wall_belongs_to_all_regions_in_region_list(tile_grid->surface,
rlp_head_wall_2)) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_sm_2_outside) {
if (wall_belongs_to_any_region_in_region_list(tile_grid->surface,
rlp_head_obj_2)) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_grid_3_inside) {
if (!wall_belongs_to_all_regions_in_region_list(tile_grid->surface,
rlp_head_wall_3)) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
} else if (only_grid_3_outside) {
if (wall_belongs_to_any_region_in_region_list(tile_grid->surface,
rlp_head_obj_3)) {
uncheck_vacant_tile(tile_vacant_nbr_head, rnd_num);
num_attempts++;
continue;
}
}
product_grid[n_product] = tile_grid;
product_grid_idx[n_product] = tile_idx;
product_flag[n_product] = PRODUCT_FLAG_USE_RANDOM;
break;
}
}
}
} /* end if (is_orientable) */
/* Determine the location of the reaction for count purposes. */
struct vector3 count_pos_xyz;
if (hitpt != NULL)
count_pos_xyz = *hitpt;
else if (sm_reactant)
uv2xyz(&sm_reactant->s_pos, sm_reactant->grid->surface, &count_pos_xyz);
else
count_pos_xyz = ((struct volume_molecule *)reacA)->pos;
/* Create and place each product. */
struct vector3 mol_pos_tmp;
struct subvolume *product_subvol = NULL;
for (int n_product = rx->n_reactants; n_product < n_players; ++n_product) {
struct abstract_molecule *this_product = NULL;
struct species *const product_species = rx_players[n_product];
/* If the product is a surface molecule, place it on the grid. */
if (product_species->flags & ON_GRID) {
struct vector2 prod_uv_pos;
/* Pick an appropriate position for the new molecule. */
if (world->randomize_smol_pos) {
switch (product_flag[n_product]) {
case PRODUCT_FLAG_USE_REACA_UV:
prod_uv_pos = ((struct surface_molecule *)reacA)->s_pos;
break;
case PRODUCT_FLAG_USE_REACB_UV:
prod_uv_pos = ((struct surface_molecule *)reacB)->s_pos;
break;
case PRODUCT_FLAG_USE_REACC_UV:
prod_uv_pos = ((struct surface_molecule *)reacC)->s_pos;
break;
case PRODUCT_FLAG_USE_RANDOM:
grid2uv_random(product_grid[n_product], product_grid_idx[n_product],
&prod_uv_pos, world->rng);
break;
default:
UNHANDLED_CASE(product_flag[n_product]);
/*break;*/
}
} else
grid2uv(product_grid[n_product], product_grid_idx[n_product],
&prod_uv_pos);
this_product = (struct abstract_molecule *)place_sm_product(
world, product_species, 0, product_grid[n_product],
product_grid_idx[n_product], &prod_uv_pos, product_orient[n_product],
t, reacA->periodic_box);
}
/* else place the molecule in space. */
else {
/* Unless this is a unimolecular reaction, we will have a hitpt. */
if (!hitpt) {
/* If this is a unimolecular surface rxn... */
if (reacA->properties->flags & ON_GRID) {
uv2xyz(&((struct surface_molecule *)reacA)->s_pos,
((struct surface_molecule *)reacA)->grid->surface,
&mol_pos_tmp);
product_subvol = find_subvolume(world, &mol_pos_tmp, last_subvol);
}
/* ... else a unimolecular volume rxn. */
else {
mol_pos_tmp = ((struct volume_molecule *)reacA)->pos;
product_subvol = ((struct volume_molecule *)reacA)->subvol;
}
hitpt = &mol_pos_tmp;
} else
product_subvol = find_subvolume(world, hitpt, last_subvol);
this_product = (struct abstract_molecule *)place_volume_product(
world, product_species, 0, sm_reactant, w, product_subvol, hitpt,
product_orient[n_product], t, reacA->periodic_box);
if (((struct volume_molecule *)this_product)->index < DISSOCIATION_MAX)
update_dissociation_index = true;
}
/* Update molecule counts */
++product_species->population;
if (product_species->flags & (COUNT_CONTENTS | COUNT_ENCLOSED))
count_region_from_scratch(world, this_product, NULL, 1, NULL, NULL, t, NULL);
}
/* If necessary, update the dissociation index. */
if (update_dissociation_index) {
if (--world->dissociation_index < DISSOCIATION_MIN)
world->dissociation_index = DISSOCIATION_MAX;
}
/* Handle events triggered off of named reactions */
if (rx->info[path].pathname != NULL) {
/* No flags for reactions so we have to check regions if we have waypoints!
* Fix to be more efficient for WORLD-only counts? */
if (world->place_waypoints_flag)
count_region_from_scratch(world, NULL, rx->info[path].pathname, 1,
&count_pos_xyz, w, t, NULL);
/* Other magical stuff. For now, can only trigger releases. */
if (rx->info[path].pathname->magic != NULL) {
if (reaction_wizardry(world, rx->info[path].pathname->magic, w,
&count_pos_xyz, t))
mcell_allocfailed("Failed to complete reaction triggered release after "
"a '%s' reaction.",
rx->info[path].pathname->sym->name);
}
}
if (tile_nbr_head != NULL)
delete_tile_neighbor_list(tile_nbr_head);
if (tile_vacant_nbr_head != NULL)
delete_tile_neighbor_list(tile_vacant_nbr_head);
return cross_wall ? RX_FLIP : RX_A_OK;
}
/*************************************************************************
outcome_trimolecular:
In: reaction that's occurring
path the reaction's taking
three molecules that are reacting (first is moving one
and the last one is the furthest from the moving molecule or
the one that is hit the latest)
orientations of the molecules
time that the reaction is occurring
location of collision between moving molecule and the furthest target
Out: Value based on outcome:
RX_FLIP if the molecule goes across the membrane
RX_DESTROY if the molecule no longer exists
RX_A_OK if everything proceeded smoothly
Products are created as needed.
Note: reacA is the triggering molecule (e.g. moving)
reacC is the target furthest from the reacA
*************************************************************************/
int outcome_trimolecular(struct volume *world, struct rxn *rx, int path,
struct abstract_molecule *reacA,
struct abstract_molecule *reacB,
struct abstract_molecule *reacC, short orientA,
short orientB, short orientC, double t,
struct vector3 *hitpt, struct vector3 *loc_okay) {
struct wall *w = NULL;
struct volume_molecule *vm = NULL;
struct surface_molecule *sm = NULL;
int result;
/* flags */
int killA = 0, killB = 0, killC = 0;
int reacA_is_free = 0;
int reacB_is_free = 0;
int reacC_is_free = 0;
int num_surface_reactants = 0;
if ((reacA->properties->flags & NOT_FREE) == 0) {
reacA_is_free = 1;
} else
num_surface_reactants++;
if ((reacB->properties->flags & NOT_FREE) == 0)
reacB_is_free = 1;
else
num_surface_reactants++;
if ((reacC->properties->flags & NOT_FREE) == 0)
reacC_is_free = 1;
else
num_surface_reactants++;
if (!reacA_is_free) {
sm = (struct surface_molecule *)reacA;
} else if (!reacB_is_free) {
sm = (struct surface_molecule *)reacB;
} else if (!reacC_is_free) {
sm = (struct surface_molecule *)reacC;
}
if (sm != NULL)
w = sm->grid->surface;
result = outcome_products_trimol_reaction_random(world, w, hitpt, t, rx, path,
reacA, reacB, reacC, orientA,
orientB, orientC);
if (result == RX_BLOCKED)
return RX_BLOCKED;
rx->n_occurred++;
rx->info[path].count++;
/* Figure out if either of the reactants was destroyed */
if (rx->players[0] == reacA->properties) {
if (rx->players[1] == reacB->properties) {
killC = (rx->players[rx->product_idx[path] + 2] == NULL);
killB = (rx->players[rx->product_idx[path] + 1] == NULL);
killA = (rx->players[rx->product_idx[path]] == NULL);
} else {
killB = (rx->players[rx->product_idx[path] + 2] == NULL);
killC = (rx->players[rx->product_idx[path] + 1] == NULL);
killA = (rx->players[rx->product_idx[path]] == NULL);
}
} else if (rx->players[0] == reacB->properties) {
if (rx->players[1] == reacA->properties) {
killC = (rx->players[rx->product_idx[path] + 2] == NULL);
killA = (rx->players[rx->product_idx[path] + 1] == NULL);
killB = (rx->players[rx->product_idx[path]] == NULL);
} else {
killA = (rx->players[rx->product_idx[path] + 2] == NULL);
killC = (rx->players[rx->product_idx[path] + 1] == NULL);
killB = (rx->players[rx->product_idx[path]] == NULL);
}
} else if (rx->players[0] == reacC->properties) {
if (rx->players[1] == reacA->properties) {
killB = (rx->players[rx->product_idx[path] + 2] == NULL);
killA = (rx->players[rx->product_idx[path] + 1] == NULL);
killC = (rx->players[rx->product_idx[path]] == NULL);
} else {
killA = (rx->players[rx->product_idx[path] + 2] == NULL);
killB = (rx->players[rx->product_idx[path] + 1] == NULL);
killC = (rx->players[rx->product_idx[path]] == NULL);
}
}
if (killC) {
vm = NULL;
if ((reacC->properties->flags & ON_GRID) != 0) {
sm = (struct surface_molecule *)reacC;
remove_surfmol_from_list(&sm->grid->sm_list[sm->grid_index], sm);
sm->grid->n_occupied--;
if (sm->flags & IN_SURFACE)
sm->flags -= IN_SURFACE;
if (sm->flags & IN_SCHEDULE) {
sm->grid->subvol->local_storage->timer->defunct_count++;
}
} else {
vm = (struct volume_molecule *)reacC;
vm->subvol->mol_count--;
if (vm->flags & IN_SCHEDULE) {
vm->subvol->local_storage->timer->defunct_count++;
}
}
if ((reacC->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) != 0) {
count_region_from_scratch(world, reacC, NULL, -1, NULL, NULL, t, NULL);
}
reacC->properties->n_deceased++;
double t_time = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, t);
reacC->properties->cum_lifetime_seconds += t_time - reacC->birthday;
reacC->properties->population--;
if (vm != NULL)
collect_molecule(vm);
else {
reacC->properties = NULL;
if ((reacC->flags & IN_MASK) == 0)
mem_put(reacC->birthplace, reacC);
}
}
if (killB) {
vm = NULL;
if ((reacB->properties->flags & ON_GRID) != 0) {
sm = (struct surface_molecule *)reacB;
remove_surfmol_from_list(&sm->grid->sm_list[sm->grid_index], sm);
sm->grid->n_occupied--;
if (sm->flags & IN_SURFACE)
sm->flags -= IN_SURFACE;
if (sm->flags & IN_SCHEDULE) {
sm->grid->subvol->local_storage->timer->defunct_count++;
}
} else {
vm = (struct volume_molecule *)reacB;
vm->subvol->mol_count--;
if (vm->flags & IN_SCHEDULE) {
vm->subvol->local_storage->timer->defunct_count++;
}
}
if ((reacB->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) != 0) {
count_region_from_scratch(world, reacB, NULL, -1, NULL, NULL, t, NULL);
}
reacB->properties->n_deceased++;
double t_time = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, t);
reacB->properties->cum_lifetime_seconds += t_time - reacB->birthday;
reacB->properties->population--;
if (vm != NULL)
collect_molecule(vm);
else {
reacB->properties = NULL;
if ((reacB->flags & IN_MASK) == 0)
mem_put(reacB->birthplace, reacB);
}
}
if (killA) {
vm = NULL;
if ((reacA->properties->flags & ON_GRID) != 0) {
sm = (struct surface_molecule *)reacA;
remove_surfmol_from_list(&sm->grid->sm_list[sm->grid_index], sm);
sm->grid->n_occupied--;
if (sm->flags & IN_SURFACE)
sm->flags -= IN_SURFACE;
if (sm->flags & IN_SCHEDULE) {
sm->grid->subvol->local_storage->timer->defunct_count++;
}
} else {
vm = (struct volume_molecule *)reacA;
vm->subvol->mol_count--;
if (vm->flags & IN_SCHEDULE) {
vm->subvol->local_storage->timer->defunct_count++;
}
}
if ((reacA->properties->flags & ON_GRID) !=
0) /* Surface molecule is OK where it is, doesn't obey COUNT_ME */
{
if (reacA->properties->flags &
COUNT_SOME_MASK) /* If we're ever counted, try to count us now */
{
count_region_from_scratch(world, reacA, NULL, -1, NULL, NULL, t, NULL);
}
} else if ((reacA->flags & COUNT_ME) && world->place_waypoints_flag) {
/* Subtlety: we made it up to hitpt, but our position is wherever we were
* before that! */
if (hitpt == NULL || (reacB_is_free && reacC_is_free))
/* Vol-vol-vol rx should be counted at hitpt */
{
count_region_from_scratch(world, reacA, NULL, -1, hitpt, NULL, t, NULL);
} else /* reaction involving surface or surface_molecule but we don't want
to
count exactly on a wall or we might count on the wrong side */
{
struct vector3 fake_hitpt;
vm = (struct volume_molecule *)reacA;
/* Halfway in between where we were and where we react should be a safe
* away-from-wall place to remove us */
if (loc_okay == NULL)
loc_okay = &(vm->pos);
fake_hitpt.x = 0.5 * hitpt->x + 0.5 * loc_okay->x;
fake_hitpt.y = 0.5 * hitpt->y + 0.5 * loc_okay->y;
fake_hitpt.z = 0.5 * hitpt->z + 0.5 * loc_okay->z;
count_region_from_scratch(world, reacA, NULL, -1, &fake_hitpt, NULL, t, NULL);
}
}
reacA->properties->n_deceased++;
double t_time = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, t);
reacA->properties->cum_lifetime_seconds += t_time - reacA->birthday;
reacA->properties->population--;
if (vm != NULL)
collect_molecule(vm);
else
reacA->properties = NULL;
return RX_DESTROY;
}
return result;
}
| C |
3D | mcellteam/mcell | src/grid_util.h | .h | 7,428 | 168 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
#include "dyngeom.h"
#define TILE_CHECKED 0x01
/* contains information about the neigbors of the tile */
struct tile_neighbor {
struct surface_grid *grid; /* surface grid the tile is on */
unsigned int idx; /* index on that tile */
short int flag; /* flag */
struct tile_neighbor *next;
};
void xyz2uv(struct vector3 *a, struct wall *w, struct vector2 *b);
void uv2xyz(struct vector2 *a, struct wall *w, struct vector3 *b);
int xyz2grid(struct vector3 *v, struct surface_grid *sm);
void grid2xyz(struct surface_grid *sm, int idx, struct vector3 *v);
int uv2grid(struct vector2 *v, struct surface_grid *sm);
void grid2uv(struct surface_grid *sm, int idx, struct vector2 *v);
void grid2uv_random(struct surface_grid *sm, int idx, struct vector2 *v,
struct rng_state *rng);
void init_grid_geometry(struct surface_grid *sm);
int create_grid(struct volume *world, struct wall *w, struct subvolume *guess);
void grid_neighbors(struct volume *world, struct surface_grid *grid, int idx,
int create_grid_flag, struct surface_grid **nb_grid,
int *nb_idx);
int nearest_free(struct surface_grid *sm, struct vector2 *v, double max_d2,
double *found_dist2);
int verify_wall_regions_match(
const char *mesh_name, struct string_buffer *reg_names, struct wall *w,
struct string_buffer *regions_to_ignore,
struct mesh_transparency *mesh_transp, const char *species_name);
struct wall *search_nbhd_for_free(struct volume *world, struct wall *origin,
struct vector2 *point, double max_d2,
int *found_idx,
int (*ok)(void *, struct wall *),
void *context, const char *mesh_name,
struct string_buffer *reg_names);
void delete_tile_neighbor_list(struct tile_neighbor *head);
void delete_region_list(struct region_list *head);
void push_tile_neighbor_to_list(struct tile_neighbor **head,
struct surface_grid *grid, int idx);
int push_tile_neighbor_to_list_with_checking(struct tile_neighbor **head,
struct surface_grid *grid,
int idx);
int add_more_tile_neighbors_to_list_fast(struct tile_neighbor **head,
struct surface_grid *orig_grid,
int orig_strip, int orig_stripe,
int orig_flip, struct vector3 *start,
struct vector3 *end, int edge_index,
struct surface_grid *new_grid);
int is_neighbor_tile(struct surface_grid *orig_grid, int orig_idx,
struct surface_grid *new_grid, int new_idx);
int get_tile_neighbor_from_list_of_vacant_neighbors(struct tile_neighbor *head,
int index,
struct surface_grid **grid,
int *idx);
void uncheck_vacant_tile(struct tile_neighbor *head, int list_index);
void find_closest_position(struct surface_grid *grid1, int idx1,
struct surface_grid *grid2, int idx2,
struct vector2 *p);
int is_inner_tile(struct surface_grid *sm, int idx);
void find_neighbor_tiles(struct volume *world, struct surface_molecule *sm,
struct surface_grid *grid, int tile_idx,
int create_grid_flag, int search_for_reactant,
struct tile_neighbor **tile_nbr_head,
int *list_length);
void grid_all_neighbors_for_inner_tile(struct volume *world,
struct surface_grid *grid, int idx,
struct vector2 *pos,
struct tile_neighbor **tile_nbr_head,
int *list_length);
void grid_all_neighbors_across_walls_through_edges(
struct volume *world, struct surface_molecule *sm,
struct surface_grid *grid, int idx, int create_grid_flag,
int search_for_reactant, struct tile_neighbor **tile_nbr_head,
int *list_length);
void grid_all_neighbors_across_walls_through_vertices(
struct volume *world, struct surface_molecule *sm,
struct wall_list *wall_nbr_head, struct surface_grid *grid,
int create_grid_flag, int search_for_reactant,
struct tile_neighbor **tile_nbr_head, int *list_length);
void append_tile_neighbor_list(struct tile_neighbor **head1,
struct tile_neighbor **head2);
void get_tile_vertices(struct surface_grid *sg, int idx, int *flp,
struct vector2 *R, struct vector2 *S, struct vector2 *T);
int tile_orientation(struct vector2 *v, struct surface_grid *sm);
double get_tile_area(struct vector2 *A, struct vector2 *B, struct vector2 *C);
int move_strip_up(struct surface_grid *grid, int idx);
int move_strip_down(struct surface_grid *grid, int idx);
void place_product_shared_segment(struct vector2 *R_shared,
struct vector2 *S_shared, struct vector2 *T,
struct vector2 *prod, double k1, double k2);
void place_product_shared_vertex(struct vector2 *R_shared, struct vector2 *S,
struct vector2 *T, struct vector2 *prod,
double k1, double k2);
void place_product_close_to_segment_endpoint(struct vector2 *S,
struct vector2 *E,
struct vector2 *prod, double k1,
double k2);
int is_corner_tile(struct surface_grid *sm, int idx);
void find_shared_vertices_corner_tile_parent_wall(struct volume *world,
struct surface_grid *sm,
int idx,
long long int *shared_vert);
void find_shared_vertices_for_neighbor_walls(struct wall *orig_wall,
struct wall *nb_wall,
int *shared_vert_1,
int *shared_vert_2);
int find_wall_vertex_for_corner_tile(struct surface_grid *grid, int idx);
int is_surface_molecule_behind_restrictive_boundary(struct surface_molecule *sm,
struct wall *wall,
struct rxn **reaction_hash,
int rx_hashsize);
| Unknown |
3D | mcellteam/mcell | src/mcell_species.c | .c | 12,051 | 355 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include "logging.h"
#include <math.h>
#include <stdlib.h>
#include "diffuse_util.h"
#include "sym_table.h"
#include "mcell_species.h"
#include "logging.h"
/* static helper functions */
static struct species *assemble_mol_species(MCELL_STATE *state,
struct sym_entry *sym_ptr,
struct mcell_species_spec *species);
static int ensure_rdstep_tables_built(MCELL_STATE *state);
/*************************************************************************
mcell_create_species:
Create a new species. This uses the same helper functions as the parser,
but is meant to be used independent of the parser.
In: state: the simulation state
name: molecule name
D: diffusion constant
is_2d: 1 if the species is a 2D molecule, 0 if 3D
custom_time_step: time_step for the molecule (< 0.0 for a custom space
step, >0.0 for custom timestep, 0.0 for default
timestep)
target_only: 1 if the molecule cannot initiate reactions
max_step_length:
Out: Returns 0 on sucess and 1 on error
*************************************************************************/
MCELL_STATUS
mcell_create_species(MCELL_STATE *state, struct mcell_species_spec *species,
mcell_symbol **species_ptr) {
struct sym_entry *sym = NULL;
int error_code = new_mol_species(state, species->name, &sym);
if (error_code) {
return error_code;
}
assemble_mol_species(state, sym, species);
error_code = ensure_rdstep_tables_built(state);
if (error_code) {
return error_code;
}
if (species_ptr != NULL) {
*species_ptr = sym;
}
return MCELL_SUCCESS;
}
/*****************************************************************************
*
* mcell_add_to_species_list creates a linked list of mcell_species from
* mcell_symbols.
*
* The list of mcell_species is for example used to provide the list
* of reactants, products and surface classes needed for creating
* reactions.
*
* During the first invocation of this function, NULL should be provided for
* the species_list to initialize a new mcell_species list with mcell_symbol.
* On subsecquent invocations the current mcell_species list should
* be provided as species_list to which the new mcell_symbol will be appended
* with the appropriate flags for orientation status.
*
*****************************************************************************/
struct mcell_species *
mcell_add_to_species_list(mcell_symbol *species_ptr, bool is_oriented,
int orientation, struct mcell_species *species_list) {
struct mcell_species *species = (struct mcell_species *)CHECKED_MALLOC_STRUCT(
struct mcell_species, "species list");
if (species == NULL) {
return NULL;
}
species->next = NULL;
species->mol_type = species_ptr;
species->orient_set = is_oriented ? 1 : 0;
species->orient = orientation;
if (species_list != NULL) {
species->next = species_list;
}
return species;
}
/*****************************************************************************
*
* mcell_delete_species_list frees all memory associated with a list of
* mcell_species
*
*****************************************************************************/
void mcell_delete_species_list(struct mcell_species *species) {
struct mcell_species *tmp = species;
while (species) {
tmp = species->next;
free(species);
species = tmp;
}
}
/**************************************************************************
new_mol_species:
Create a new species. There must not yet be a molecule or named reaction
pathway with the supplied name.
In: state: the simulation state
name: name for the new species
sym_ptr: symbol for the species
Out: 0 on success, positive integer on failure
**************************************************************************/
int new_mol_species(MCELL_STATE *state, const char *name, struct sym_entry **sym_ptr) {
// Molecule already defined
if (retrieve_sym(name, state->mol_sym_table) != NULL) {
return 2;
}
// Molecule already defined as a named reaction pathway
else if (retrieve_sym(name, state->rxpn_sym_table) != NULL) {
return 3;
}
*sym_ptr = store_sym(name, MOL, state->mol_sym_table, NULL);
// Out of memory while creating molecule
if (*sym_ptr == NULL) {
return 4;
}
return 0;
}
/*****************************************************************************
*
* static helper functions
*
*****************************************************************************/
/**************************************************************************
assemble_mol_species:
Helper function to assemble a molecule species from its component pieces.
NOTE: A couple of comments regarding the unit conversions below:
Internally, mcell works with with the per species length
normalization factor
new_spec->space_step = sqrt(4*D*t), D = diffusion constant (1)
If the user supplies a CUSTOM_SPACE_STEP or SPACE_STEP then
it is assumed to correspond to the average diffusion step and
is hence equivalent to lr_bar in 2 or 3 dimensions for surface and
volume molecules, respectively:
lr_bar_2D = sqrt(pi*D*t) (2)
lr_bar_3D = 2*sqrt(4*D*t/pi) (3)
Hence, given a CUSTOM_SPACE_STEP/SPACE_STEP we need to
solve eqs (2) and (3) for t and obtain new_spec->space_step
via equation (1)
2D:
lr_bar_2D = sqrt(pi*D*t) => t = (lr_bar_2D^2)/(pi*D)
3D:
lr_bar_3D = 2*sqrt(4*D*t/pi) => t = pi*(lr_bar_3D^2)/(16*D)
The remaining coefficients are:
- 1.0e8 : needed to convert D from cm^2/s to um^2/s
- global_time_unit, length_unit, r_length_unit: mcell
internal time/length conversions.
In: state: the simulation state
sym_ptr: symbol for the species
D: diffusion constant
is_2d: 1 if the species is a 2D molecule, 0 if 3D
custom_time_step: time_step for the molecule (<0.0 for a custom space
step, >0.0 for custom timestep, 0.0 for default
timestep)
target_only: 1 if the molecule cannot initiate reactions
Out: the species, or NULL if an error occurred
**************************************************************************/
struct species *assemble_mol_species(MCELL_STATE *state,
struct sym_entry *sym_ptr,
struct mcell_species_spec *species) {
// Fill in species info
// The global time step must be defined before creating any species since it
// is used in calculations involving custom time and space steps
double global_time_unit = state->time_unit;
struct species *new_spec = (struct species *)sym_ptr->value;
if (species->is_2d) {
new_spec->flags |= ON_GRID;
} else {
new_spec->flags &= ~ON_GRID;
}
new_spec->D = species->D;
new_spec->time_step = species->custom_time_step;
new_spec->custom_time_step_from_mdl = species->custom_time_step;
if (species->target_only) {
new_spec->flags |= CANT_INITIATE;
}
if (species->max_step_length > 0) {
new_spec->flags |= SET_MAX_STEP_LENGTH;
}
if (species->external_species) {
//store this as information in the species flag
new_spec->flags |= EXTERNAL_SPECIES;
// but also store this at the system level since these species are special, they are proxies
// for nfsim species so we will need to reuse this type down the line
if(species->is_2d)
state->global_nfsim_surface = new_spec;
else
state->global_nfsim_volume = new_spec;
}
// Determine the actual space step and time step
// Immobile (boring)
if (!distinguishable(new_spec->D, 0, EPS_C)) {
new_spec->space_step = 0.0;
new_spec->time_step = 1.0;
}
// Custom timestep or spacestep
else if (new_spec->time_step != 0.0) {
// Hack--negative value means custom space step
if (new_spec->time_step < 0) {
double lr_bar = -new_spec->time_step;
if (species->is_2d) {
new_spec->time_step =
lr_bar * lr_bar / (MY_PI * 1.0e8 * new_spec->D * global_time_unit);
} else {
new_spec->time_step =
lr_bar * lr_bar * MY_PI /
(16.0 * 1.0e8 * new_spec->D * global_time_unit);
}
new_spec->space_step =
sqrt(4.0 * 1.0e8 * new_spec->D * new_spec->time_step *
global_time_unit) *
state->r_length_unit;
}
else {
new_spec->space_step =
sqrt(4.0 * 1.0e8 * new_spec->D * new_spec->time_step) *
state->r_length_unit;
new_spec->time_step /= global_time_unit;
}
}
// Global timestep (this is the typical case)
else if (!distinguishable(state->space_step, 0, EPS_C)) {
new_spec->space_step =
sqrt(4.0 * 1.0e8 * new_spec->D * global_time_unit) *
state->r_length_unit;
new_spec->time_step = 1.0;
}
// Global spacestep
else {
double space_step = state->space_step * state->length_unit;
if (species->is_2d) {
new_spec->time_step =
space_step * space_step /
(MY_PI * 1.0e8 * new_spec->D * global_time_unit);
}
else {
new_spec->time_step =
space_step * space_step * MY_PI /
(16.0 * 1.0e8 * new_spec->D * global_time_unit);
}
new_spec->space_step = sqrt(4.0 * 1.0e8 * new_spec->D *
new_spec->time_step * global_time_unit) *
state->r_length_unit;
}
new_spec->refl_mols = NULL;
new_spec->transp_mols = NULL;
new_spec->absorb_mols = NULL;
new_spec->clamp_mols = NULL;
species->custom_time_step = new_spec->time_step;
species->space_step = new_spec->space_step;
return new_spec;
}
/**************************************************************************
ensure_rdstep_tables_built:
Build the r_step/d_step tables if they haven't been built yet.
In: state: the simulation state
Out: 0 on success, positive integer on failure
**************************************************************************/
int ensure_rdstep_tables_built(MCELL_STATE *state) {
if (state->r_step != NULL && state->r_step_surface != NULL &&
state->d_step != NULL) {
return 0;
}
if (state->r_step == NULL) {
// Out of memory while creating r_step data for molecule
if ((state->r_step = init_r_step(state->radial_subdivisions)) == NULL) {
return 5;
}
}
if (state->r_step_surface == NULL) {
state->r_step_surface = init_r_step_surface(state->radial_subdivisions);
// Cannot store r_step_surface data.
if (state->r_step_surface == NULL) {
return 6;
}
}
if (state->d_step == NULL) {
// Out of memory while creating d_step data for molecule
if ((state->d_step = init_d_step(state->radial_directions,
&state->num_directions)) == NULL) {
return 7;
}
// Num directions, rounded up to the nearest 2^n - 1
state->directions_mask = state->num_directions;
state->directions_mask |= (state->directions_mask >> 1);
state->directions_mask |= (state->directions_mask >> 2);
state->directions_mask |= (state->directions_mask >> 4);
state->directions_mask |= (state->directions_mask >> 8);
state->directions_mask |= (state->directions_mask >> 16);
// Internal error: bad number of default RADIAL_DIRECTIONS (max 131072).
if (state->directions_mask > (1 << 18)) {
return 8;
}
}
return 0;
}
| C |
3D | mcellteam/mcell | src/rules_py/mcell3r.py | .py | 5,071 | 119 | #!/usr/bin/env python3
import os
import sys
import subprocess
import argparse
from pathlib import Path
def define_console():
parser = argparse.ArgumentParser(description='MCellR runner/postprocessor')
parser.add_argument('-v', '--version', action='store_true', help='print program version and exit')
parser.add_argument('-f', '--fullversion', action='store_true', help='print detailed version report and exit')
parser.add_argument('-s', '--seed', type=str, help='choose random sequence number (default: 1)')
parser.add_argument('-i', '--iterations', type=str, help='override iterations in MDL file')
parser.add_argument('-l', '--logfile', type=str, help='send output log to file (default: stdout)')
parser.add_argument('-x', '--logfreq', type=str, help='output log frequency')
parser.add_argument('-e', '--errfile', type=str, help='send errors to log file (default: stderr)')
parser.add_argument('-p', '--checkpoint_infile', type=str, help='read checkpoint file')
parser.add_argument('-o', '--checkpoint_outfile', type=str, help='write checkpoint file')
parser.add_argument('-q', '--quiet', action='store_true', help='suppress all unrequested output except for errors')
parser.add_argument('-w', '--with_checks', type=str, help='yes/no : default yes perform check of the geometry for coincident walls')
parser.add_argument('-r', '--rules', type=str, help='rules file', required=True)
parser.add_argument('-m', '--mdl_infile', type=str, help='MDL main input file', required=True)
parser.add_argument('-b', '--bond_angle', type=str, help='Default Bond Angle', required=False)
parser.add_argument('-z', '--z_options', type=str, help='Visualization Options', required=False)
parser.add_argument('-d', '--dump_level', type=str, help='Dump Level for text output', required=False)
return parser
if __name__ == "__main__":
print ( "Top of mcell3r.py/main" )
sys.stdout.flush()
parser = define_console()
args = parser.parse_args()
print(args)
cmd_args = ''
if args.version:
cmd_args = cmd_args + ' -version'
if args.fullversion:
cmd_args = cmd_args + ' -fullversion'
if args.seed:
cmd_args = cmd_args + ' -seed %s' % (args.seed)
else:
cmd_args = cmd_args + ' -seed 1'
args.seed = '1'
if args.iterations:
cmd_args = cmd_args + ' -iterations %s' % (args.iterations)
if args.logfile:
cmd_args = cmd_args + ' -logfile %s' % (args.logfile)
if args.logfreq:
cmd_args = cmd_args + ' -logfreq %s' % (args.logfreq)
if args.errfile:
cmd_args = cmd_args + ' -errfile %s' % (args.errfile)
if args.checkpoint_infile:
cmd_args = cmd_args + ' -checkpoint_infile %s' % (args.checkpoint_infile)
if args.checkpoint_outfile:
cmd_args = cmd_args + ' -checkpoint_outfile %s' % (args.checkpoint_outfile)
if args.z_options:
cmd_args = cmd_args + ' -z %s' % (args.z_options)
if args.bond_angle:
cmd_args = cmd_args + ' -b %s' % (args.bond_angle)
if args.dump_level:
cmd_args = cmd_args + ' -dump %s' % (args.dump_level)
if args.quiet:
cmd_args = cmd_args + ' -quiet'
if args.with_checks:
cmd_args = cmd_args + ' -with_checks %s' % (args.with_checks)
if args.rules:
cmd_args = cmd_args + ' -rules %s' % (args.rules)
if args.mdl_infile:
cmd_args = cmd_args + ' %s' % (args.mdl_infile)
print(cmd_args)
script_path = os.path.dirname(os.path.realpath(__file__))
my_env = os.environ.copy()
if (sys.platform == 'darwin'):
if my_env.get('DYLD_LIBRARY_PATH'):
my_env['DYLD_LIBRARY_PATH']=os.path.join(script_path,'lib') + os.pathsep + my_env['DYLD_LIBRARY_PATH']
else:
my_env['DYLD_LIBRARY_PATH']=os.path.join(script_path,'lib')
else:
if my_env.get('LD_LIBRARY_PATH'):
my_env['LD_LIBRARY_PATH']=os.path.join(script_path,'lib') + os.pathsep + my_env['LD_LIBRARY_PATH']
else:
my_env['LD_LIBRARY_PATH']=os.path.join(script_path,'lib')
mcell_cmd = os.path.join(script_path, 'mcell')
mcell_args = [ mcell_cmd ]
mcell_args.extend ( cmd_args.split() )
postproc_cmd = os.path.join(script_path, 'postprocess_mcell3r.py')
pp_cmd = [ sys.executable, postproc_cmd ]
pp_cmd.extend ( [args.seed, args.rules] )
print ( "Start mcell itself" )
sys.stdout.flush()
mcellproc = subprocess.Popen(mcell_args, env=my_env)
mcellproc.wait()
print ( "Done with mcell itself" )
print ( "Begin postprocessing with " + str(pp_cmd) )
sys.stdout.flush()
postproc = subprocess.Popen(pp_cmd)
postproc.wait()
print ( "Done with postprocessing" )
print ( "Bottom of mcell3r.py/main" )
sys.stdout.flush()
| Python |
3D | mcellteam/mcell | src/rules_py/nfsim_python.py | .py | 4,194 | 112 | from ctypes import Structure, c_int, c_char_p, c_void_p, cdll, POINTER
class NFSim:
def __init__(self, libnfsim_c_path, libNFsim_path=None):
if libNFsim_path!=None:
libNFsim = cdll.LoadLibrary(libNFsim_path)
self.lib = cdll.LoadLibrary(libnfsim_c_path)
self.lib.setupNFSim_c.argtypes = [c_char_p, c_int]
self.lib.initSystemXML_c.argtypes = [c_char_p]
self.lib.querySystemStatus_c.argtypes = [c_char_p, c_void_p]
self.lib.mapvector_create.restype = c_void_p
self.lib.map_get.restype = c_char_p
self.lib.mapvector_size.argtypes = [c_void_p]
self.lib.mapvector_get.argtypes = [c_void_p, c_int]
self.lib.mapvector_get.restype = c_void_p
self.lib.map_get.argtypes = [c_void_p, c_char_p]
self.lib.map_get.restype = c_char_p
self.lib.mapvector_delete.argtypes = [c_void_p]
def init_nfsim(self, fileName, verbose):
"""
inits an nfsim object with a given xml file and a verbosity setting
"""
c_fileName = c_char_p(bytes(fileName,'ASCII'))
self.lib.setupNFSim_c(c_fileName, 1, verbose)
def reset_system(self):
"""
Resets an nfsim system to having no seeds species
"""
return self.lib.resetSystem_c()
def init_system_nauty(self, initDict):
"""
Initializes an nfsim simulation with a given nfsim dictionary with the species in nauty format
"""
species = [x for x in initDict]
seeds = [initDict[x] for x in initDict]
CArray = c_char_p * len(initDict)
speciesCArray = CArray(*species)
seedCArray = CArray(*seeds)
return self.lib.initSystemNauty_c(speciesCArray, seedCArray, len(initDict))
def init_system_xml(self, initXML):
"""
Initializes an nfsim simulation with a given seed species XML string
"""
c_initXML = c_char_p(bytes(initXML,'ASCII'))
return self.lib.initSystemXML_c(c_initXML)
def querySystemStatus(self, option):
"""
returns all species that participate in active reactions with numReactants reactants
"""
mem = self.lib.mapvector_create()
key = c_char_p(bytes(option,'ASCII'))
self.lib.querySystemStatus_c(key,mem)
results = []
n = self.lib.mapvector_size(mem)
for idx in range(0, n):
# XXX:ideally i would like to returns all key values but that will
# require a lil more work on the wrapper side
partialResults = self.lib.mapvector_get(mem, idx)
retval = self.lib.map_get(partialResults,b"label")
results.append(retval.decode('ASCII'))
self.lib.mapvector_delete(mem)
return sorted(results, key=len)
if __name__ == "__main__":
nfsim = NFSim('./debug/libnfsim_c.so')
nfsim.init_nfsim("cbngl_test_empty.xml", 0)
nfsim.reset_system()
#nfsim.init_system_nauty({"c:a~NO_STATE!4!2,c:l~NO_STATE!3,c:l~NO_STATE!3!0,m:Lig!2!1,m:Rec!0":1})
#nfsim.init_system_nauty({"c:a~NO_STATE!4!2,c:l~NO_STATE!3,c:l~NO_STATE!3!0,m:Lig!1!2,m:Rec!0,":1})
#print '---', nfsim.querySystemStatus("observables")
nfsim.init_system_nauty({"c:l~NO_STATE!3!1,c:r~NO_STATE!2!0,m:L@EC!1,m:R@PM!0,":1})
print('----', nfsim.querySystemStatus(b"complex"))
"""
nfsim.initSystemXML('''<Model><ListOfSpecies><Species id="S1" concentration="1" name="@PM:Lig(l!1,l).Rec(a!1)" compartment="PM">
<ListOfMolecules>
<Molecule id="S1_M1" name="Lig" compartment="PM">
<ListOfComponents>
<Component id="S1_M1_C1" name="l" numberOfBonds="0"/>
<Component id="S1_M1_C2" name="l" numberOfBonds="1"/>
</ListOfComponents>
</Molecule>
<Molecule id="S1_M2" name="Rec" compartment="PM">
<ListOfComponents>
<Component id="S1_M2_C1" name="a" numberOfBonds="1"/>
</ListOfComponents>
</Molecule>
</ListOfMolecules>
<ListOfBonds>
<Bond id="S1_B1" site1="S1_M1_C1" site2="S1_M2_C1"/>
</ListOfBonds>
</Species></ListOfSpecies></Model>''')
"""
| Python |
3D | mcellteam/mcell | src/rules_py/write_bngxmle.py | .py | 2,628 | 53 | from lxml import etree
def create_property_node(parentNode, key, value):
if value.startswith('"'):
propertyNode = etree.SubElement(parentNode, "Property", id=key, value=value.strip('"'), type="str")
else:
propertyNode = etree.SubElement(parentNode, "Property", id=key, value=value, type="num")
return propertyNode
def write2bngxmle(properties_dict, model_name):
'''
creates a bng-xml v1.1 spec from model properties
'''
root = etree.Element("bngexperimental", version="1.1", name=model_name)
if len(properties_dict['modelProperties']) > 0:
listOfModelProperties = etree.SubElement(root, "ListOfProperties")
for element in properties_dict['modelProperties']:
create_property_node(listOfModelProperties, element.strip().lower(), properties_dict['modelProperties'][element].strip())
listOfCompartments = etree.SubElement(root, "ListOfCompartments")
for element in properties_dict['compartmentProperties']:
compartmentNode = etree.SubElement(listOfCompartments, "Compartment", id=element)
listOfCompartmentProperties = etree.SubElement(compartmentNode, "ListOfProperties")
for propertyEntry in properties_dict['compartmentProperties'][element]:
create_property_node(listOfCompartmentProperties, propertyEntry[0].strip().lower(), propertyEntry[1].strip())
listOfMoleculeTypes = etree.SubElement(root, "ListOfMoleculeTypes")
for element in properties_dict['moleculeProperties']:
moleculeNode = etree.SubElement(listOfMoleculeTypes, "MoleculeType", id=element)
listOfMoleculeProperties = etree.SubElement(moleculeNode, "ListOfProperties")
for propertyEntry in properties_dict['moleculeProperties'][element]:
propertyNode = create_property_node(listOfMoleculeProperties, propertyEntry[0].strip().lower(), propertyEntry[1]['name'].strip())
if len(propertyEntry[1]['parameters']) > 0:
sublistOfMoleculeProperties = etree.SubElement(propertyNode, "ListOfProperties")
for parameter in propertyEntry[1]['parameters']:
etree.SubElement(sublistOfMoleculeProperties, "Property", id=parameter[0], value=parameter[1])
return etree.tostring(root, pretty_print=True)
def merge_bxbxe(base_bngxml, extended_bngxml):
'''
temporary method to concatenate a bng-xml 1.0 and bng-xml 1.1 definition
'''
basedoc = etree.parse(base_bngxml).getroot()
edoc = etree.parse(extended_bngxml).getroot()
basedoc.append(edoc)
return etree.tostring(basedoc, encoding='unicode', pretty_print=True)
| Python |
3D | mcellteam/mcell | src/rules_py/write_mdl.py | .py | 17,848 | 453 | import json
import grammar_definition as gd
import argparse
import read_mdl
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
def read_bngljson(bngljson):
with open(bngljson, 'r') as f:
json_dict = json.load(f)
return json_dict
def write_raw_section(original_mdl, buffer, tab):
if type(original_mdl) == str:
buffer.write(tab + original_mdl + '\n')
elif len(original_mdl) == 0:
return '{}'
elif len(original_mdl) == 1:
write_raw_section(original_mdl[0], buffer, tab)
elif len(original_mdl) == 2:
if type(original_mdl[0]) == list:
for element in original_mdl:
write_raw_section(element, buffer, tab + '\t')
elif type(original_mdl[1]) == list:
buffer.write('{1}{0}{{\n'.format(original_mdl[0], tab))
write_raw_section(original_mdl[1], buffer, tab + '\t')
buffer.write('{0}}}\n\n'.format(tab))
elif type(original_mdl[1]) == str:
buffer.write(
'{0}{1} = {2}\n'.format(
tab, original_mdl[0], original_mdl[1].strip()))
else:
if original_mdl[1] == '@':
buffer.write(tab + ' '.join(original_mdl) + '\n')
else:
for element in original_mdl:
write_raw_section(element, buffer, tab)
return buffer.getvalue()
def write_section(original_mdl):
final_section = StringIO()
if original_mdl[0] == 'DEFINE_MOLECULES':
pass
else:
return write_raw_section(original_mdl.asList(), final_section, '') + '\n'
def read_mdlr(mdlrfile):
with open(mdlrfile, 'r') as f:
mdlr = f.read()
return mdlr
def construct_mcell(xml_structs, mdlr_path, output_file_name, nauty_dict):
'''
uses information from the bngxml and the original mdl to create a plain mdl
file. this is mainly important to assign the right surface/volume
compartment to the seed species.
'''
# load up data structures
mdlr = read_mdlr(mdlr_path)
section_mdlr = gd.nonhashedgrammar.parseString(mdlr)
statement_mdlr = gd.statementGrammar.parseString(mdlr)
hashed_mdlr = gd.grammar.parseString(mdlr)
# create output buffers
final_mdl = StringIO()
molecule_mdl = StringIO()
reaction_mdl = StringIO()
output_mdl = StringIO()
seed_mdl = StringIO()
mod_surf_reg__mdl = StringIO()
surface_classes__mdl = StringIO()
# output statements as is
for element in statement_mdlr:
final_mdl.write('{0} = {1}\n'.format(element[0], element[1]))
final_mdl.write('\n')
final_mdl.write('INCLUDE_FILE = "{0}.molecules.mdl"\n'.format(output_file_name))
final_mdl.write('INCLUDE_FILE = "{0}.reactions.mdl"\n'.format(output_file_name))
final_mdl.write('INCLUDE_FILE = "{0}.seed.mdl"\n'.format(output_file_name))
final_mdl.write('INCLUDE_FILE = "{0}.surface_classes.mdl"\n'.format(output_file_name))
final_mdl.write('INCLUDE_FILE = "{0}.mod_surf_reg.mdl"\n'.format(output_file_name))
final_mdl.write('INCLUDE_FILE = "{0}.output.mdl"\n'.format(output_file_name))
# output sections using json information
section_order = {'DEFINE_SURFACE_CLASSES': surface_classes__mdl,
'MODIFY_SURFACE_REGIONS': mod_surf_reg__mdl,
'DEFINE_MOLECULES': molecule_mdl,
'DEFINE_REACTIONS': reaction_mdl,
'REACTION_DATA_OUTPUT': output_mdl,
'INSTANTIATE': seed_mdl}
for element in section_mdlr:
if element[0] not in section_order:
final_mdl.write(write_section(element))
dimensionality_dict = {}
bngLabel = {}
# molecules
molecule_mdl.write('DEFINE_MOLECULES\n{\n')
if 'DEFINE_MOLECULES' in section_mdlr.keys():
for element in section_mdlr['DEFINE_MOLECULES']:
write_raw_section(element, molecule_mdl, '\t')
dimensionality_dict['volume_proxy'] = '3D'
molecule_mdl.write('\t{0} //{1}\n\t{{ \n'.format('volume_proxy', 'proxy molecule type. the instance contains the actual information'))
molecule_mdl.write('\t\tDIFFUSION_CONSTANT_{0}D = {1}\n'.format(3, 1))
molecule_mdl.write('\t\tEXTERN\n')
molecule_mdl.write('\t}\n')
dimensionality_dict['surface_proxy'] = '2D'
molecule_mdl.write('\t{0} //{1}\n\t{{ \n'.format('surface_proxy', 'proxy surface type. the instance contains the actual information'))
molecule_mdl.write('\t\tDIFFUSION_CONSTANT_{0}D = {1}\n'.format(2, 1))
molecule_mdl.write('\t\tEXTERN\n')
molecule_mdl.write('\t}\n')
molecule_mdl.write('}\n\n')
try:
molecule_str = read_mdl.process_molecules_for_final_mdl(hashed_mdlr['molecules'])
molecule_mdl.write('DEFINE_MOLECULE_STRUCTURES {\n')
molecule_mdl.write(molecule_str)
molecule_mdl.write('}\n')
except 'KeyError':
eprint('There is an issue with the molecules section in the mdlr file')
# extract bng name
# for molecule in json_dict['mol_list']:
# dimensionality_dict[molecule['name']] = molecule['type']
# bngLabel[molecule['name']] = molecule['extendedName']
compartmentDict = {}
for molecule in xml_structs['molecules']:
bngLabel[molecule.name] = molecule.str2()
for compartment in xml_structs['compartments']:
compartmentDict[compartment['identifier']] = compartment
# reactions
reaction_mdl.write('DEFINE_REACTIONS\n{\n')
if 'DEFINE_REACTIONS' in section_mdlr.keys():
for element in section_mdlr['DEFINE_REACTIONS']:
write_raw_section(element, reaction_mdl, '\t')
artificialRate = '1e-15'
reaction_mdl.write('\t{0} -> {1} [{2}]\n'.format('volume_proxy', 'volume_proxy', artificialRate))
reaction_mdl.write('\t{0} + {0} -> {0} + {0} [{1}]\n'.format('volume_proxy', artificialRate))
reaction_mdl.write('\t{0}; + {1}; -> {0}; [{2}]\n'.format('volume_proxy', 'surface_proxy', artificialRate))
reaction_mdl.write('\t{1}; + {1}; -> {1}; [{2}]\n'.format('volume_proxy', 'surface_proxy', artificialRate))
reaction_mdl.write('\t{1}; -> {1}; [{2}]\n'.format('volume_proxy', 'surface_proxy', artificialRate))
reaction_mdl.write('}\n')
if 'MODIFY_SURFACE_REGIONS' in section_mdlr.keys():
mod_surf_reg__mdl.write('MODIFY_SURFACE_REGIONS {\n')
for element in section_mdlr['MODIFY_SURFACE_REGIONS']:
if type(element) is str:
mod_surf_reg__mdl.write(" {0} {{\n".format(element))
else:
mod_surf_reg__mdl.write(" {0} = {1}\n }}\n".format(element[0][0], element[0][1]))
mod_surf_reg__mdl.write('}\n')
if 'DEFINE_SURFACE_CLASSES' in section_mdlr.keys():
surface_classes__mdl.write('DEFINE_SURFACE_CLASSES {\n')
for element in section_mdlr['DEFINE_SURFACE_CLASSES']:
surface_classes__mdl.write(" {0} {{\n {1} = {2}\n }}\n".format(element[0], element[1][0][0], element[1][0][1]))
surface_classes__mdl.write('}\n')
# seed species
seed_mdl.write('INSTANTIATE Scene OBJECT\n{\n')
if 'INSTANTIATE' in section_mdlr.keys():
for element in section_mdlr['INSTANTIATE'][-1].asList():
seed_mdl.write('\t' + ' '.join(element[:-1]))
seed_mdl.write(write_raw_section(element[-1], seed_mdl, '') + '\n')
# include geometry information related to this scene
mdlrseeds = []
for entries in hashed_mdlr['initialization']['entries']:
if entries[1] != 'RELEASE_SITE':
seed_mdl.write('\t{0} OBJECT {1} {{}}\n'.format(entries[0], entries[1]))
else:
mdlrseeds.append(entries)
for bngseed, mdlrseed in zip(xml_structs['seedspecies'], mdlrseeds):
if bngseed['structure'].trueName not in nauty_dict:
# skipping seeds/releases whose number to release is 0, nfsim ignores them
continue
seed_mdl.write('\t{0} {1} //{2}\n'.format(mdlrseed[0], mdlrseed[1], str(bngseed['structure'])))
seed_mdl.write('\t{\n')
# print the shape option first
for element in mdlrseed[2]:
if element[0] == 'SHAPE':
seed_mdl.write('\t\t{0} = {1}\n'.format(element[0].strip(), element[1].strip()))
# volume molecules are default
if bngseed['structure'].compartment == '' or compartmentDict[bngseed['structure'].compartment]['dimensions'] in ['3', 3]:
seed_mdl.write('\t\tMOLECULE = {0}\n'.format('volume_proxy'))
else:
seed_mdl.write('\t\tMOLECULE = {0}{1}\n'.format('surface_proxy', "'"))
for element in mdlrseed[2]:
if element[0] not in ['SHAPE', 'MOLECULE']:
seed_mdl.write('\t\t{0} = {1}\n'.format(element[0].strip(), element[1].strip()))
else:
pass
seed_mdl.write('\t\tGRAPH_PATTERN = "{0}"\n'.format(nauty_dict[bngseed['structure'].trueName]))
seed_mdl.write('\t}\n')
seed_mdl.write('}\n')
output_mdl.write('REACTION_DATA_OUTPUT\n{\n')
if 'REACTION_DATA_OUTPUT' in section_mdlr.keys():
for element in section_mdlr['REACTION_DATA_OUTPUT']:
write_raw_section(element, output_mdl, '\t')
for element in hashed_mdlr['observables']:
if type(element[0]) == str:
output_mdl.write('\t{0} = {1}\n'.format(element[0], element[1]))
output_mdl.write('}\n')
return {'main': final_mdl,
'molecules': molecule_mdl,
'reactions': reaction_mdl,
'mod_surf_reg': mod_surf_reg__mdl,
'surface_classes': surface_classes__mdl,
'rxn_output': output_mdl,
'seeding': seed_mdl}
def construct_mdl(jsonPath, mdlr_path, output_file_name):
"""
Create an _mdl readable by standard mcell.
Keyword arguments:
json_path -- A json dictionary containing structures and parameters extracted from the mdlr input
mdlr_path -- An mdlr file. In this method we will be mainly extracting the non RBM sections
Returns:
A dictionary containing the different _mdl sections
"""
# load up data structures
json_dict = read_bngljson(jsonPath)
mdlr = read_mdlr(mdlr_path)
# print mdlr
section_mdlr = gd.nonhashedgrammar.parseString(mdlr)
statement_mdlr = gd.statementGrammar.parseString(mdlr)
# create output buffers
final_mdl = StringIO()
molecule_mdl = StringIO()
reaction_mdl = StringIO()
output_mdl = StringIO()
seed_mdl = StringIO()
# output statements as is
for element in statement_mdlr:
final_mdl.write('{0} = {1}\n'.format(element[0], element[1]))
final_mdl.write('\n')
final_mdl.write('INCLUDE_FILE = "{0}.molecules.mdl"\n'.format(output_file_name))
final_mdl.write('INCLUDE_FILE = "{0}.reactions.mdl"\n'.format(output_file_name))
final_mdl.write('INCLUDE_FILE = "{0}.seed.mdl"\n\n'.format(output_file_name))
# output sections using json information
section_order = {'DEFINE_MOLECULES': molecule_mdl, 'DEFINE_REACTIONS': reaction_mdl, 'REACTION_DATA_OUTPUT': output_mdl, 'INSTANTIATE': seed_mdl}
for element in section_mdlr:
if element[0] not in section_order:
final_mdl.write(write_section(element))
final_mdl.write('INCLUDE_FILE = "{0}.output.mdl"\n'.format(output_file_name))
dimensionality_dict = {}
# molecules
molecule_mdl.write('DEFINE_MOLECULES\n{\n')
if 'DEFINE_MOLECULES' in section_mdlr.keys():
for element in section_mdlr['DEFINE_MOLECULES']:
write_raw_section(element, molecule_mdl, '\t')
for molecule in json_dict['mol_list']:
dimensionality_dict[molecule['name']] = molecule['type']
molecule_mdl.write('\t{0} //{1}\n\t{{ \n'.format(molecule['name'], molecule['extendedName']))
molecule_mdl.write('\t\tDIFFUSION_CONSTANT_{0} = {1}\n'.format(molecule['type'], molecule['dif']))
molecule_mdl.write('\t}\n')
molecule_mdl.write('}\n')
# reactions
reaction_mdl.write('DEFINE_REACTIONS\n{\n')
if 'DEFINE_REACTIONS' in section_mdlr.keys():
for element in section_mdlr['DEFINE_REACTIONS']:
write_raw_section(element, reaction_mdl, '\t')
for reaction in json_dict['rxn_list']:
reaction_mdl.write('\t{0} -> {1} [{2}]\n'.format(reaction['reactants'], reaction['products'], reaction['fwd_rate']))
reaction_mdl.write('}\n')
# seed species
seed_mdl.write('INSTANTIATE Scene OBJECT\n{\n')
if 'INSTANTIATE' in section_mdlr.keys():
for element in section_mdlr['INSTANTIATE'][-1].asList():
seed_mdl.write('\t' + ' '.join(element[:-1]))
seed_mdl.write(write_raw_section(element[-1], seed_mdl, '') + '\n')
#
for seed in json_dict['rel_list']:
seed_mdl.write('\t{0} RELEASE_SITE\n\t{{\n'.format(seed['name']))
seed_mdl.write('\t\tSHAPE = Scene.{0}\n'.format(seed['object_expr']))
orientation = seed['orient'] if dimensionality_dict[seed['molecule']] == '2D' else ''
seed_mdl.write('\t\tMOLECULE = {0}{1}\n'.format(seed['molecule'], orientation))
if seed['quantity_type'] == 'DENSITY':
quantity_type = 'DENSITY' if dimensionality_dict[seed['molecule']] == '2D' else 'CONCENTRATION'
else:
quantity_type = seed['quantity_type']
seed_mdl.write('\t\t{0} = {1}\n'.format(quantity_type, seed['quantity_expr']))
seed_mdl.write('\t\tRELEASE_PROBABILITY = 1\n'.format(seed['molecule']))
seed_mdl.write('\t}\n')
seed_mdl.write('}\n')
# rxn_output
output_mdl.write('REACTION_DATA_OUTPUT\n{\n')
if 'REACTION_DATA_OUTPUT' in section_mdlr.keys():
for element in section_mdlr['REACTION_DATA_OUTPUT']:
write_raw_section(element, output_mdl, '\t')
for obs in json_dict['obs_list']:
if any([x != ['0'] for x in obs['value']]):
output_mdl.write('\t{')
output_mdl.write(' + '.join(['COUNT[{0},WORLD]'.format(x[0]) for x in obs['value'] if x != ['0']]) + '}')
output_mdl.write(' => "./react_data/{0}.dat"\n'.format(obs['name']))
output_mdl.write('}\n')
return {'main': final_mdl,
'molecules': molecule_mdl,
'reactions': reaction_mdl,
'rxn_output': output_mdl,
'seeding': seed_mdl}
def define_console():
parser = argparse.ArgumentParser(description='SBML to BNGL translator')
parser.add_argument(
'-ij',
'--input_json',
type=str,
help='input SBML-JSON file',
required=True)
parser.add_argument(
'-im',
'--input_mdl',
type=str,
help='input SBML-JSON file',
required=True)
parser.add_argument('-o', '--output', type=str, help='output _mdl file')
return parser
def write_mdl(mdl_dict, output_file_name):
with open('{0}.main.mdl'.format(output_file_name), 'w') as f:
f.write(mdl_dict['main'].getvalue())
with open('{0}.molecules.mdl'.format(output_file_name), 'w') as f:
f.write(mdl_dict['molecules'].getvalue())
with open('{0}.reactions.mdl'.format(output_file_name), 'w') as f:
f.write(mdl_dict['reactions'].getvalue())
with open('{0}.surface_classes.mdl'.format(output_file_name), 'w') as f:
f.write(mdl_dict['surface_classes'].getvalue())
with open('{0}.mod_surf_reg.mdl'.format(output_file_name), 'w') as f:
f.write(mdl_dict['mod_surf_reg'].getvalue())
with open('{0}.seed.mdl'.format(output_file_name), 'w') as f:
f.write(mdl_dict['seeding'].getvalue())
with open('{0}.output.mdl'.format(output_file_name), 'w') as f:
f.write(mdl_dict['rxn_output'].getvalue())
def verbose_write_mdl(mdl_dict, output_file_name):
print ( "\n\n\nBegin Really Writing!!\n\n\n" )
full_output = None
full_output = mdl_dict['main'].getvalue();
print ( "\n\n\nFile: main:\n\n" + full_output + "\n\n\n" )
f = open('{0}.main.mdl'.format(output_file_name), 'w')
f.write(full_output)
f.flush()
f.close()
full_output = mdl_dict['molecules'].getvalue();
print ( "\n\n\nFile: molecules:\n\n" + full_output + "\n\n\n" )
f = open('{0}.molecules.mdl'.format(output_file_name), 'w')
f.write(full_output)
f.flush()
f.close()
full_output = mdl_dict['reactions'].getvalue();
print ( "\n\n\nFile: reactions:\n\n" + full_output + "\n\n\n" )
f = open('{0}.reactions.mdl'.format(output_file_name), 'w')
f.write(full_output)
f.flush()
f.close()
full_output = mdl_dict['surface_classes'].getvalue();
print ( "\n\n\nFile: surface_classes:\n\n" + full_output + "\n\n\n" )
f = open('{0}.surface_classes.mdl'.format(output_file_name), 'w')
f.write(full_output)
f.flush()
f.close()
full_output = mdl_dict['mod_surf_reg'].getvalue();
print ( "\n\n\nFile: mod_surf_reg:\n\n" + full_output + "\n\n\n" )
f = open('{0}.mod_surf_reg.mdl'.format(output_file_name), 'w')
f.write(full_output)
f.flush()
f.close()
full_output = mdl_dict['seeding'].getvalue();
print ( "\n\n\nFile: seed:\n\n" + full_output + "\n\n\n" )
f = open('{0}.seed.mdl'.format(output_file_name), 'w')
f.write(full_output)
f.flush()
f.close()
full_output = mdl_dict['rxn_output'].getvalue();
print ( "\n\n\nFile: output:\n\n" + full_output + "\n\n\n" )
f = open('{0}.output.mdl'.format(output_file_name), 'w')
f.write(full_output)
f.flush()
f.close()
print ( "\n\n\nDone Really Writing!!\n\n\n" )
if __name__ == "__main__":
parser = define_console()
namespace = parser.parse_args()
final_name = namespace.output if namespace.output else 'example_expanded'
mdl_dict = construct_mdl(
namespace.input_json, namespace.input_mdl, final_name)
write_mdl(mdl_dict)
| Python |
3D | mcellteam/mcell | src/rules_py/small_structures.py | .py | 30,264 | 801 | # -*- coding: utf-8 -*-
"""
Created on Wed May 30 11:44:17 2012
@author: proto
"""
from copy import deepcopy
import re
from random import randint
from pyparsing import Word, Suppress, Optional, alphanums, Group, ZeroOrMore
from collections import Counter, defaultdict
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
def parseReactions(reaction):
components = (Word(alphanums + "_") + Optional(Group('~' + Word(alphanums+"_")))
+ Optional(Group('!' + Word(alphanums+'+?'))))
molecule = (Word(alphanums + "_")
+ Optional(Suppress('(') + Group(components) + ZeroOrMore(Suppress(',') + Group(components))
+Suppress(')')))
species = Group(molecule) + ZeroOrMore(Suppress('.') + Group(molecule))
result = species.parseString(reaction).asList()
return result
def readFromString(string):
sp = Species()
reactionList = parseReactions(string)
for molecule in reactionList:
mol = Molecule(molecule[0], '')
if len(molecule) > 1:
for idx in range(1, len(molecule)):
comp = Component(molecule[idx][0], '')
if len(molecule[idx]) > 1:
for idx2 in range(1, len(molecule[idx])):
if molecule[idx][idx2][0] == '~':
comp.addState(molecule[idx][idx2][1])
elif molecule[idx][idx2][0] == '!':
comp.addBond(molecule[idx][idx2][1])
mol.addComponent(comp)
sp.addMolecule(mol)
return sp
class Rule:
def __init__(self, label=''):
self.label = label
self.reactants = []
self.products = []
self.rates = []
self.bidirectional = False
self.actions = []
self.mapping = []
def addReactant(self, reactant):
self.reactants.append(reactant)
def addProduct(self, product):
self.products.append(product)
def addReactantList(self, reactants):
self.reactants.extend(reactants)
def addProductList(self, products):
self.products.extend(products)
def addRate(self, rate):
self.rates.append(rate)
def addMapping(self, mapping):
self.mapping.add(mapping)
def addMappingList(self, mappingList):
self.mapping.extend(mappingList)
def addActionList(self, actionList):
self.actions.extend(actionList)
def __str__(self):
finalStr = ''
if self.label != '':
finalStr += '{0}: '.format(self.label)
arrow = ' <-> ' if self.bidirectional or len(self.rates) > 1 else ' -> '
finalStr += ' + '.join([str(x) for x in self.reactants]) + arrow + ' + '.join([str(x) for x in self.products]) + ' ' + ','.join(self.rates)
return finalStr
class Species:
def __init__(self):
self.molecules = []
self.bondNumbers = []
self.bonds = []
self.identifier = randint(0, 100000)
self.idx = ''
self.compartment = ''
def getBondNumbers(self):
bondNumbers = [0]
for element in self.molecules:
bondNumbers.extend(element.getBondNumbers())
return bondNumbers
def copy(self):
species = Species()
species.identifier = randint(0, 1000000)
for molecule in self.molecules:
species.molecules.append(molecule.copy())
return species
def getMoleculeById(self, idx):
for molecule in self.molecules:
if molecule.idx == idx:
return molecule
def addMolecule(self, molecule, concatenate=False, iteration=1):
if not concatenate:
self.molecules.append(molecule)
else:
counter = 1
for element in self.molecules:
if element.name == molecule.name:
if iteration == counter:
element.extend(molecule)
return
else:
counter +=1
self.molecules.append(molecule)
#self.molecules.append(molecule)
#for element in self.molecules:
# if element.name == molecule.name:
def addCompartment(self, tags):
for molecule in self.molecules:
molecule.setCompartment(tags)
def deleteMolecule(self, moleculeName):
deadMolecule = None
for element in self.molecules:
if element.name == moleculeName:
deadMolecule = element
if deadMolecule == None:
return
bondNumbers = deadMolecule.getBondNumbers()
self.molecules.remove(deadMolecule)
for element in self.molecules:
for component in element.components:
for number in bondNumbers:
if str(number) in component.bonds:
component.bonds.remove(str(number))
def getMolecule(self, moleculeName):
for molecule in self.molecules:
if moleculeName == molecule.name:
return molecule
return None
def getSize(self):
return len(self.molecules)
def getMoleculeNames(self):
return [x.name for x in self.molecules]
def contains(self, moleculeName):
for molecule in self.molecules:
if moleculeName == molecule.name:
return True
return False
def addChunk(self, tags, moleculesComponents, precursors):
'''
temporary transitional method
'''
for (tag, components) in zip (tags, moleculesComponents):
if self.contains(tag):
tmp = self.getMolecule(tag)
else:
tmp = Molecule(tag)
#for element in precursors:
# if element.getMolecule(tag) != None:
# tmp = element.getMolecule(tag)
for component in components:
if tmp.contains(component[0][0]):
tmpCompo = tmp.getComponent(component[0][0])
#continue
else:
tmpCompo = Component(component[0][0])
for index in range(1, len(component[0])):
tmpCompo.addState(component[0][index])
if len(component) > 1:
tmpCompo.addBond(component[1])
if not tmp.contains(component[0][0]):
tmp.addComponent(tmpCompo)
if not self.contains(tag):
self.molecules.append(tmp)
def extend(self, species, update=True):
if(len(self.molecules) == len(species.molecules)):
for (selement, oelement) in zip(self.molecules, species.molecules):
for component in oelement.components:
if component.name not in [x.name for x in selement.components]:
selement.components.append(component)
else:
for element in selement.components:
if element.name == component.name:
element.addStates(component.states, update)
else:
for element in species.molecules:
if element.name not in [x.name for x in self.molecules]:
self.addMolecule(deepcopy(element), update)
else:
for molecule in self.molecules:
if molecule.name == element.name:
for component in element.components:
if component.name not in [x.name for x in molecule.components]:
molecule.addComponent(deepcopy(component), update)
else:
comp = molecule.getComponent(component.name)
for state in component.states:
comp.addState(state, update)
def updateBonds(self, bondNumbers):
newBondNumbers = deepcopy(bondNumbers)
correspondence = {}
intersection = [int(x) for x in newBondNumbers if x in self.getBondNumbers()]
for element in self.molecules:
for component in element.components:
for index in range(0, len(component.bonds)):
if int(component.bonds[index]) in intersection:
if component.bonds[index] in correspondence:
component.bonds[index] = correspondence[component.bonds[index]]
else:
correspondence[component.bonds[index]] = max(intersection) + 1
component.bonds[index] = max(intersection) + 1
#intersection = [int(x) for x in newBondNumbers if x in self.getBondNumbers()]
def append(self, species):
newSpecies = (deepcopy(species))
newSpecies.updateBonds(self.getBondNumbers())
for element in newSpecies.molecules:
self.molecules.append(deepcopy(element))
def sort(self):
"""
Sort molecules by number of components, then number of bonded components, then the negative sum of the bond index, then number
of active states, then string length
"""
self.molecules.sort(key=lambda molecule: (len(molecule.components),
-min([int(y) if y not in ['?', '+'] else 999 for x in molecule.components for y in x.bonds] + [999]),
-len([x for x in molecule.components if len(x.bonds) > 0]),
-len([x for x in molecule.components if x.activeState not in [0, '0']]),
len(str(molecule)),
str(molecule)),
reverse=True)
def __str__(self):
self.sort()
name = ''
moleculeStrings = [x.toString() for x in self.molecules]
if self.compartment != '':
name += '@{0}:'.format(self.compartment)
#name += '.'.join(moleculeStrings)
moleculeStrings = [x if '@{0}'.format(self.compartment) not in x else x[:-len('@{0}'.format(self.compartment))] for x in moleculeStrings ]
name += '.'.join(moleculeStrings)
else:
name += '.'.join(moleculeStrings)
'''
name = name.replace('~', '')
name = name.replace('~', '')
name = name.replace(',', '')
name = name.replace('.', '')
name = name.replace('(', '')
name = name.replace(')', '')
name = name.replace('!', '')
name = name.replace('_', '')
'''
return name
def str2(self):
return '.'.join([x.str2() for x in self.molecules])
def getBondDict(self):
bondDict = defaultdict(list)
bondIdx = 1
for idx, molecule in enumerate(self.molecules):
for idx2, component in enumerate(molecule.components):
for bond in component.bonds:
bondDict[bond].append('M{0}_C{1}'.format(idx, idx2))
return bondDict
def toXML(self, identifier, tab=''):
xmlStr = StringIO.StringIO()
xmlStr.write('{0}<ListOfMolecules>\n'.format(tab))
for idx, molecule in enumerate(self.molecules):
xmlStr.write(molecule.toXML('{0}_M{1}'.format(identifier, idx), tab + '\t'))
xmlStr.write('{0}</ListOfMolecules>\n'.format(tab))
bondDict = self.getBondDict()
xmlStr.write('{0}<ListOfBonds>\n'.format(tab))
for key in bondDict:
xmlStr.write('{0}\t<Bond id="{1}_B{2}" site1="{1}_{3}" site2="{1}_{4}"/>\n'.format(tab, identifier,
key, bondDict[key][0],
bondDict[key][1]))
xmlStr.write('{0}</ListOfBonds>\n'.format(tab))
return xmlStr.getvalue()
def reset(self):
for element in self.molecules:
element.reset()
def toString(self):
return self.__str__()
def extractAtomicPatterns(self, action, site1, site2, differentiateDimers=False):
atomicPatterns = {}
bondedPatterns = {}
reactionCenter = []
context = []
#one atomic pattern for the state, one for the bond
nameCounter = Counter([x.name for x in self.molecules])
nameCounterCopy = Counter([x.name for x in self.molecules])
self.sort()
for molecule in self.molecules:
moleculeCounter = nameCounter[molecule.name] - nameCounterCopy[molecule.name]
nameCounterCopy[molecule.name] -= 1
for component in molecule.components:
if component.activeState != '':
speciesStructure = Species()
# one atomic pattern for the states
speciesStructure.bonds = self.bonds
if differentiateDimers:
moleculeStructure = Molecule(molecule.name + '%{0}'.format(moleculeCounter), molecule.idx)
else:
moleculeStructure = Molecule(molecule.name, molecule.idx)
componentStructure = Component(component.name, component.idx)
componentStructure.addState(component.activeState)
componentStructure.activeState = component.activeState
moleculeStructure.addComponent(componentStructure)
speciesStructure.addMolecule(moleculeStructure)
if componentStructure.idx in [site1, site2] and action == 'StateChange':
reactionCenter.append((speciesStructure))
else:
context.append((speciesStructure))
atomicPatterns[str(speciesStructure)] = speciesStructure
speciesStructure = Species()
#one atomic pattern for the bonds
speciesStructure.bonds = self.bonds
if differentiateDimers:
moleculeStructure = Molecule(molecule.name + '%{0}'.format(moleculeCounter), molecule.idx)
else:
moleculeStructure = Molecule(molecule.name, molecule.idx)
componentStructure = Component(component.name, component.idx)
moleculeStructure.addComponent(componentStructure)
speciesStructure.addMolecule(moleculeStructure)
#atomicPatterns[str(speciesStructure)] = speciesStructure
if len(component.bonds) == 0:
#if component.activeState == '':
atomicPatterns[str(speciesStructure)] = speciesStructure
else:
if component.bonds[0] != '+':
componentStructure.addBond(1)
else:
componentStructure.addBond('+')
if component.bonds[0] not in bondedPatterns:
bondedPatterns[component.bonds[0]] = speciesStructure
elif '+' not in component.bonds[0] or \
len(bondedPatterns[component.bonds[0]].molecules) == 0:
bondedPatterns[component.bonds[0]].addMolecule(moleculeStructure)
if componentStructure.idx in [site1, site2] and action != 'StateChange':
reactionCenter.append((speciesStructure))
elif len(component.bonds) > 0 or component.activeState == '':
context.append((speciesStructure))
for element in bondedPatterns:
atomicPatterns[str(bondedPatterns[element])] = bondedPatterns[element]
reactionCenter = [str(x) for x in reactionCenter
if str(x) in atomicPatterns]
context = [str(x) for x in context if str(x) in atomicPatterns]
return atomicPatterns, reactionCenter, context
def graphVizGraph(self, graph, identifier, layout='LR', options={}):
speciesDictionary = {}
graphName = "%s_%s" % (identifier, str(self))
for idx, molecule in enumerate(self.molecules):
ident = "%s_m%i" %(graphName, idx)
speciesDictionary[molecule.idx] = ident
if len(self.molecules) == 1:
compDictionary = molecule.graphVizGraph(graph, ident, flag=False, options=options)
else:
#s1 = graph.subgraph(name = graphName, label=' ')
compDictionary = molecule.graphVizGraph(graph, ident, flag=False, options=options)
speciesDictionary.update(compDictionary)
for bond in self.bonds:
if bond[0] in speciesDictionary and bond[1] in speciesDictionary:
if layout == 'RL':
graph.add_edge(speciesDictionary[bond[1]], speciesDictionary[bond[0]], dir='none', len=0.1, weight=100)
else:
graph.add_edge(speciesDictionary[bond[0]], speciesDictionary[bond[1]], dir='none', len=0.1, weight=100)
return speciesDictionary
def containsComponentIdx(self, idx, dictionary):
for molecule in self.molecules:
for component in molecule.components:
if component.idx == idx:
return dictionary[idx]
return None
def notContainsComponentIdx(self, idx):
context = []
for molecule in self.molecules:
for component in molecule.components:
if component.idx not in idx:
context.append(component)
return context
def hasWildCardBonds(self):
for molecule in self.molecules:
if molecule.hasWildcardBonds():
return True
return False
def listOfBonds(self, nameDict):
listofbonds = {}
for bond in self.bonds:
mol1 = re.sub('_C[^_]*$', '', bond[0])
mol2 = re.sub('_C[^_]*$', '', bond[1])
if nameDict[mol1] not in listofbonds:
listofbonds[nameDict[mol1]] = {}
listofbonds[nameDict[mol1]][nameDict[bond[0]]] = [(nameDict[mol2], nameDict[bond[1]])]
if nameDict[mol2] not in listofbonds:
listofbonds[nameDict[mol2]] = {}
listofbonds[nameDict[mol2]][nameDict[bond[1]]] = [(nameDict[mol1], nameDict[bond[0]])]
return listofbonds
class Molecule:
def __init__(self, name, idx):
self.components = []
self.name, self.idx = name, idx
self.compartment = ''
self.uniqueIdentifier = randint(0, 100000)
def copy(self):
molecule = Molecule(self.name, self.idx)
for element in self.components:
molecule.components.append(element.copy())
return molecule
def addChunk(self, chunk):
component = Component(chunk[0][0][0][0])
component.addState(chunk[0][0][0][1])
self.addComponent(component)
def addComponent(self, component, overlap=0):
if not overlap:
self.components.append(component)
else:
if not component.name in [x.name for x in self.components]:
self.components.append(component)
else:
compo = self.getComponent(component.name)
for state in component.states:
compo.addState(state)
def setCompartment(self, compartment):
self.compartment = compartment
def getComponentById(self, idx):
for component in self.components:
if component.idx == idx:
return component
def getBondNumbers(self):
bondNumbers = []
for element in self.components:
bondNumbers.extend([int(x) for x in element.bonds if x != '+'])
return bondNumbers
def getComponent(self, componentName):
for component in self.components:
if componentName == component.getName():
return component
def removeComponent(self, componentName):
x = [x for x in self.components if x.name == componentName]
if x != []:
self.components.remove(x[0])
def removeComponents(self, components):
for element in components:
if element in self.components:
self.components.remove(element)
def addBond(self, componentName, bondName):
bondNumbers = self.getBondNumbers()
while bondName in bondNumbers:
bondName += 1
component = self.getComponent(componentName)
component.addBond(bondName)
def getComponentWithBonds(self):
return [x for x in self.components if x.bonds != []]
def contains(self, componentName):
return componentName in [x.name for x in self.components]
def __str__(self):
self.components = sorted(self.components, key = lambda st:st.name)
finalStr = self.name
if len(self.components) > 0:
finalStr += '(' + ','.join([str(x) for x in self.components]) + ')'
if self.compartment != '':
finalStr += '@' + self.compartment
return finalStr
def toXML(self, identifier, tab):
buffer = StringIO.StringIO()
buffer.write('{2}<Molecule id="{0}" name="{1}">\n'.format(identifier, self.name, tab))
buffer.write('{0}<ListOfComponents>\n'.format(tab))
for idx, component in enumerate(self.components):
buffer.write(component.toXML('{0}_C{1}'.format(identifier, idx), tab + '\t'))
buffer.write('{0}</ListOfComponents>\n'.format(tab))
return buffer.getvalue()
def toString(self):
return self.__str__()
def str2(self):
self.components.sort()
return self.name + '(' + ','.join([x.str2() for x in self.components]) + ')'
def str3(self):
return self.name + '(' + self.components[0].name + ')'
def extend(self, molecule):
for element in molecule.components:
comp = [x for x in self.components if x.name == element.name]
if len(comp) == 0:
self.components.append(deepcopy(element))
else:
for bond in element.bonds:
comp[0].addBond(bond)
for state in element.states:
comp[0].addState(state)
def reset(self):
for element in self.components:
element.reset()
def update(self, molecule):
for comp in molecule.components:
if comp.name not in [x.name for x in self.components]:
self.components.append(deepcopy(comp))
def graphVizGraph(self, graph, identifier, components=None, flag=False, options={}):
moleculeDictionary = {}
flag = False
'''
if flag:
graph.add_node(identifier, label=self.__str__(), name="cluster%s_%s" % (identifier, self.idx))
print "cluster%s_%s" % (identifier, self.idx)
else:
print identifier
graph.add_node(identifier, label=self.__str__(), name=identifier)
moleculeDictionary[self.idx] = identifier
return moleculeDictionary
'''
if len(self.components) == 0:
graph.add_node(identifier, label=self.name)
moleculeDictionary[self.idx] = identifier
else:
if not flag:
s1 = graph.subgraph(name = "cluster%s_%s" % (identifier, self.idx), label=self.name, **options)
else:
s1 = graph.subgraph(name = identifier, label=self.name, **options)
s1.add_node('cluster%s_%s_dummy' % (identifier, self.idx), shape='point', style='invis')
if components == None:
tmpComponents = self.components
else:
tmpComponents = components
for idx, component in enumerate(tmpComponents):
ident = "%s_c%i" %(identifier, idx)
moleculeDictionary[component.idx] = ident
compDictionary = component.graphVizGraph(s1, ident)
moleculeDictionary.update(compDictionary)
return moleculeDictionary
def hasWildcardBonds(self):
for component in self.components:
if component.hasWilcardBonds():
return True
return False
def distance(self, cMolecule):
distance = 0
distance += 10000 if self.name != cMolecule.name else 0
for component1, component2 in zip(self.components, cMolecule.components):
distance += not component1.bonds == component2.bonds
distance += not component1.activeState == component2.activeState
return distance
def compare(self, cMolecule):
self.components = sorted(self.components, key=lambda st:st.name)
cMolecule.components = sorted(cMolecule.components, key=lambda st:st.name)
for c1, c2 in zip(self.components, cMolecule.components):
if c1.activeState != c2.activeState:
c1.activeState = ''
if c1.bonds != c2.bonds:
'''
if len(c1.bonds) != len(c2.bonds) or '?' in c1.bonds or '?' in c2.bonds:
c1.bonds = ['?']
else:
c1.bonds = ['+']
'''
class Component:
def __init__(self, name, idx, bonds = [], states=[]):
self.name, self.idx = name, idx
self.states = []
self.bonds = []
self.activeState = ''
def copy(self):
component = Component(self.name, self.idx, deepcopy(self.bonds), deepcopy(self.states))
component.activeState = deepcopy(self.activeState)
return component
def addState(self, state, update=True):
if not state in self.states:
self.states.append(state)
if update:
self.setActiveState(state)
def addStates(self, states, update=True):
for state in states:
if state not in self.states:
self.addState(state, update)
def addBond(self, bondName):
if not bondName in self.bonds:
self.bonds.append(bondName)
def setActiveState(self, state):
if state not in self.states:
return False
self.activeState = state
return True
def getRuleStr(self):
tmp = self.name
if self.activeState != '':
tmp += '~' + self.activeState
if len(self.bonds) > 0:
tmp += '!' + '!'.join([str(x) for x in self.bonds])
return tmp
def getTotalStr(self):
return self.name + '~'.join(self.states)
def getName(self):
return self.name
def __str__(self):
return self.getRuleStr()
def str2(self):
tmp = self.name
if len(self.bonds) > 0:
tmp += '!' + '!'.join([str(x) for x in self.bonds])
if len(self.states) > 0:
tmp += '~' + '~'.join([str(x) for x in self.states])
return tmp
def toXML(self, identifier, tab):
if self.activeState != '':
return '{0}<Component id="{1}" name="{2}" state="{3}" numberOfBonds="{4}"/>\n'.format(tab, identifier,
self.name, self.activeState, len(self.bonds))
else:
return '{0}<Component id="{1}" name="{2}" state="{3}" numberOfBonds="{4}"/>\n'.format(tab, identifier,
self.name, self.activeState, len(self.bonds))
def __hash__(self):
return self.name
def reset(self):
self.bonds = []
if '0' in self.states:
self.activeState = '0'
def hasWilcardBonds(self):
if '+' in self.bonds:
return True
return False
def graphVizGraph(self, graph, identifier):
compDictionary = {}
if len(self.states) == 0:
graph.add_node(identifier, label=self.name)
else:
s1 = graph.subgraph(name="cluster%s_%s" % (identifier, self.idx), label=self.name)
if self.activeState != '':
ident = "%s" % (identifier)
compDictionary[self.activeState] = ident
s1.add_node(ident, label = self.activeState)
else:
for idx, state in enumerate(self.state):
ident = "%s_s%i" % (identifier, idx)
s1.add_node(ident, label = state)
compDictionary[state] = ident
return compDictionary
# def createGraph(self, identifier):
# return component, compDictionary
def __lt__(self, other):
return str(self) < str(other)
class States:
def __init__(self, name='', idx=''):
self.name = name
self.idx = idx
class Action:
def __init__(self):
self.action = ''
self.site1 = ''
self.site2 = ''
def setAction(self, action, site1, site2=''):
self.action = action
self.site1 = site1
self.site2 = site2
def __str__(self):
return '%s, %s, %s' % (self.action, self.site1, self.site2)
class Databases:
def __init__(self):
self.translator = {}
self.synthesisDatabase = {}
self.catalysisDatabase = {}
self.rawDatabase = {}
self.labelDictionary = {}
self.synthesisDatabase2 = {}
def getRawDatabase(self):
return self.rawDatabase
def getLabelDictionary(self):
return self.labelDictionary
def add2LabelDictionary(self, key, value):
temp = tuple(key)
temp = temp.sort()
self.labelDictionary[temp] = value
def add2RawDatabase(self, rawDatabase):
pass
def getTranslator(self):
return self.translator
if __name__ == "__main__":
sp = readFromString('A(b!1,p~P).B(a!1)')
print(sp.toXML('S1', '\t'))
| Python |
3D | mcellteam/mcell | src/rules_py/postprocess_mcell3r.py | .py | 2,253 | 71 | #!/usr/bin/env python
import os
import sys
import shutil
def postprocess(mcellr_react_filename, run_seed):
print('')
print ( ' Postprocessing: %s' % (mcellr_react_filename) )
mcellr_react_dir = './'
react_dir = os.path.join(mcellr_react_dir, 'react_data')
# if os.path.exists(react_dir):
# shutil.rmtree(react_dir,ignore_errors=True)
# if not os.path.exists(react_dir):
# os.makedirs(react_dir)
seed_dir = 'seed_%05d' % run_seed
react_seed_dir = os.path.join(react_dir, seed_dir)
# if os.path.exists(react_seed_dir):
# shutil.rmtree(react_seed_dir,ignore_errors=True)
if not os.path.exists(react_seed_dir):
os.makedirs(react_seed_dir)
# Read the MCellR data file and split into a list of rows where each row is a list of columns
mcellr_react_file = open (mcellr_react_filename,'r')
all_react_data = mcellr_react_file.read()
react_data_all = [ [t.strip() for t in s.split(',') if len(t.strip()) > 0] for s in all_react_data.split('\n') if len(s) > 0 ]
react_data_header = []
react_data_rows = []
if len(react_data_all) > 0:
react_data_header = react_data_all[0]
react_data_rows = react_data_all[1:]
for col in range(1,len(react_data_header)):
out_file_name = os.path.join ( react_seed_dir, react_data_header[col] + '.dat' )
print ( ' Writing data to ' + out_file_name )
f = open(out_file_name,'w')
for row in react_data_rows:
# print ( ' ' + row[0] + ' ' + row[col] )
f.write ( row[0] + ' ' + row[col] + '\n' )
f.close()
if __name__ == '__main__':
if (len(sys.argv) < 3):
print('\nUsage: %s run_seed mcellr_rules_file\n' % (sys.argv[0]))
print(' Split contents of MCellR gdat reaction output into')
print(' separate output files in react_data/seed_nnnnn/ subdirs\n')
exit(1)
run_seed = int(sys.argv[1])
rules_file = sys.argv[2]
mols_data_file = rules_file + '.seed_%05d.gdat' % (run_seed)
reactions_data_file = rules_file + '_reactions.seed_%05d.gdat' % (run_seed)
print('')
print ( 'Postprocessing MCellR Reaction Output...')
postprocess(mols_data_file, run_seed)
postprocess(reactions_data_file, run_seed)
print('')
print ( 'Done Postprocessing MCellR Reaction Output' )
print('')
| Python |
3D | mcellteam/mcell | src/rules_py/grammar_definition.py | .py | 9,831 | 178 | from pyparsing import Word, Suppress, Optional, alphanums, Group, ZeroOrMore, \
Keyword, Literal, CaselessLiteral, nums, Combine, alphas, nestedExpr, \
cppStyleComment, OneOrMore, quotedString, restOfLine, delimitedList, \
dictOf, Forward, Dict
lbrace = Suppress("{")
rbrace = Suppress("}")
lbracket = Suppress("[")
rbracket = Suppress("]")
lparen = Suppress("(")
rparen = Suppress(")")
equal = Suppress("=")
comma = Suppress(",")
point = Literal('.')
tilde = ('~')
bang = ('!')
e = CaselessLiteral('E')
plusorminus = Literal('+') | Literal('-')
hashsymbol = Suppress("#")
dbquotes = '"'
uni_arrow = Literal("->")
bi_arrow = Literal("<->")
# system keywords
system_constants_ = Keyword("SYSTEM_CONSTANTS")
# molecule keywords
define_molecules_ = Keyword("DEFINE_MOLECULES")
define_functions_ = Keyword("DEFINE_FUNCTIONS")
diffusion_constant_3d_ = Keyword("DIFFUSION_CONSTANT_3D")
diffusion_constant_2d_ = Keyword("DIFFUSION_CONSTANT_2D")
diffusion_function_ = Keyword("DIFFUSION_FUNCTION")
# reaction keywords
define_reactions_ = Keyword("DEFINE_REACTIONS")
# spatial component keywords
location = Keyword("loc")
rotation = Keyword("rot")
# seed species keywords
instantiate_ = Keyword("INSTANTIATE")
object_ = Keyword("OBJECT")
parent_ = Keyword("PARENT")
release_site_ = Keyword("RELEASE_SITE")
# observables keywords
reaction_data_output_ = Keyword("REACTION_DATA_OUTPUT")
step_ = Keyword("STEP")
count_ = Keyword("COUNT")
# keywords inherited from bng
species_ = Keyword("Species")
molecules_ = Keyword("Molecules")
# misc
number = Word(nums)
integer = Combine(Optional(plusorminus) + number)
real = Combine(integer +
Optional(point + Optional(number)) +
Optional(e + integer))
numarg = (real | integer)
identifier = Word(alphas + "_", alphanums + "_")
dotidentifier = Word(alphas, alphanums + "_" + ".")
bracketidentifier = identifier + lbracket + Word(alphas) + rbracket
statement = Group(identifier + equal + (quotedString | restOfLine))
# math
mathElements = (numarg | ',' | '+' | '-' | '*' | '/' | '^' | '&' | '>' | '<' | '=' | '|' | identifier)
nestedMathDefinition = nestedExpr('(', ')', content=mathElements)
mathDefinition = OneOrMore(mathElements)
section_enclosure2_ = nestedExpr('{', '}')
section_enclosure_ = Forward()
nestedBrackets = nestedExpr('[', ']', content=section_enclosure_)
nestedCurlies = nestedExpr('{', '}', content=section_enclosure_)
section_enclosure_ << (statement | Group(identifier + ZeroOrMore(identifier) + nestedCurlies) | Group(identifier + '@' + restOfLine) | Word(alphas, alphanums + "_[]") | identifier | Suppress(',') | '@' | real)
function_entry_ = Suppress(dbquotes) + Group(identifier.setResultsName('functionName') + Suppress(lparen) +
delimitedList(Group(identifier.setResultsName('key') + Suppress(equal) + (identifier | numarg).setResultsName('value')), delim=',').setResultsName('parameters') + Suppress(rparen)) + Suppress(dbquotes)
name = Word(alphanums + '_')
species = Suppress('()') + Optional(Suppress('@' + Word(alphanums + '_-'))) + \
ZeroOrMore(Suppress('+') + Word(alphanums + "_" + ":#-") + Suppress("()") + Optional(Suppress('@' + Word(alphanums + '_-'))))
# bng pattern definition
component_definition = Group(identifier.setResultsName('componentName') +
Optional(Group(Suppress(tilde) + delimitedList(identifier | integer, delim='~')).setResultsName('state')) +
Optional(lbrace +
# loc=[x1,y1,z1]
location + equal + Group(lbracket + (numarg | identifier) + comma + (numarg | identifier) + comma + (numarg | identifier) + rbracket).setResultsName('componentLoc') +
comma +
# rot=[x2,y2,z2,A]
rotation + equal + Group(lbracket + (numarg | identifier) + comma + (numarg | identifier) + comma + (numarg | identifier) + comma + (numarg | identifier) + rbracket).setResultsName('componentRot') +
rbrace))
component_statement = Group(identifier.setResultsName('componentName') +
Optional(Group(Suppress(tilde) + (identifier | integer)).setResultsName('state')) +
Optional(Group(Suppress(bang) + (numarg | '+' | '?')).setResultsName('bond')))
molecule_definition = Group(identifier.setResultsName('moleculeName') +
Optional((lparen + Optional(delimitedList(component_definition, delim=',').setResultsName('components')) + rparen)) +
Optional(Group('@' + Word(alphanums + '_-')).setResultsName('moleculeCompartment')))
molecule_instance = Group(identifier.setResultsName('moleculeName') +
Optional((lparen + Optional(delimitedList(component_statement, delim=',').setResultsName('components')) + rparen)) +
Optional(Group('@' + Word(alphanums + '_-')).setResultsName('moleculeCompartment')))
species_definition = Group(Optional(Group('@' + Word(alphanums + '_')).setResultsName('speciesCompartment') + Suppress(':')) +
delimitedList(molecule_instance, delim='.').setResultsName('speciesPattern'))
reaction_definition = Group(Group(delimitedList(species_definition, delim='+')).setResultsName('reactants') + (uni_arrow | bi_arrow) +
Group(delimitedList(species_definition, delim='+')).setResultsName('products') +
Group(lbracket + (numarg | (identifier + Suppress(Optional('()')))) + Optional(comma + (numarg | (identifier + Suppress(Optional('()'))))) + rbracket).setResultsName('rate'))
# generic hash section grammar
hashed_section = (hashsymbol + Group(OneOrMore(name) + section_enclosure2_))
# hash system_constants
# system_constants = Group()
hashed_system_constants = Group(hashsymbol + Suppress(system_constants_) + lbrace + OneOrMore(statement) + rbrace)
# hash molecule_entry
diffusion_entry_ = Group((diffusion_constant_2d_.setResultsName('2D') | diffusion_constant_3d_.setResultsName('3D')) + Suppress(equal) + (function_entry_.setResultsName('function') | (identifier | numarg).setResultsName('variable')))
molecule_entry = Group(molecule_definition + Optional(Group(lbrace + Optional(diffusion_entry_.setResultsName('diffusionFunction')) + (ZeroOrMore(statement)).setResultsName('moleculeParameters') + rbrace)))
hashed_molecule_section = Group(hashsymbol + Suppress(define_molecules_) + lbrace + OneOrMore(molecule_entry) + rbrace)
# hash function entry
function_name = Group(identifier + '()')
math_function_entry = Group(function_name.setResultsName('functionName') + Suppress(equal) + Group(restOfLine).setResultsName('functionBody'))
hashed_function_section = Group(hashsymbol + Suppress(define_functions_) + lbrace + ZeroOrMore(math_function_entry) + rbrace)
# hash reaction entry
hashed_reaction_section = Group(hashsymbol + Suppress(define_reactions_) + lbrace + OneOrMore(reaction_definition) + rbrace)
# hash observable entry
count_definition = Group(count_ + lbracket + species_definition.setResultsName('speciesPattern') + Suppress(',') + identifier + rbracket)
observable_entry = Group(lbrace + Group(delimitedList(count_definition, delim='+')).setResultsName('patterns') + rbrace + Suppress('=>') + quotedString.setResultsName('outputfile'))
bngobservable_entry = Group((species_ | molecules_).setResultsName('obskey') + identifier.setResultsName('obsname') + Group(delimitedList(species_definition, delim=',')).setResultsName('obspatterns'))
hashed_observable_section = Group(hashsymbol + Suppress(reaction_data_output_) + lbrace + OneOrMore(statement).setResultsName('statements') + ZeroOrMore(observable_entry).setResultsName('mdlobs') + ZeroOrMore(bngobservable_entry).setResultsName('bngobs') + rbrace)
# hash initialization entry
key = identifier + Suppress('=')
value = restOfLine
release_site_definition = Group(identifier.setResultsName('name') + release_site_ + lbrace + dictOf(key, value).setResultsName('entries') + rbrace)
object_definition = Group(identifier.setResultsName('compartmentName') + Suppress(object_) + (bracketidentifier | identifier) + (nestedExpr('{', '}', content=statement)).setResultsName('compartmentOptions'))
hashed_initialization_section = Group(hashsymbol + Suppress(instantiate_) + identifier.setResultsName('name') +
identifier.setResultsName('type') + lbrace + Group(ZeroOrMore(release_site_definition | object_definition)).setResultsName('entries') + rbrace)
other_sections = section_enclosure_
# statement = Group(identifier + equal + (quotedString | OneOrMore(mathElements))) + Suppress(LineEnd() | StringEnd())
grammar = ZeroOrMore(Suppress(other_sections) | Suppress(statement) | hashed_system_constants.setResultsName('systemConstants') |
hashed_molecule_section.setResultsName('molecules') | hashed_reaction_section.setResultsName('reactions') |
hashed_observable_section.setResultsName('observables') |
hashed_initialization_section.setResultsName('initialization') |
hashed_function_section.setResultsName('math_functions')
# | Suppress(hashed_section)
)
nonhashedgrammar = ZeroOrMore(Suppress(statement) | Suppress(hashed_section) | Dict(other_sections))
statementGrammar = ZeroOrMore(statement | Suppress(other_sections) | Suppress(hashed_section))
singleLineComment = "//" + restOfLine
grammar.ignore(singleLineComment)
grammar.ignore(cppStyleComment)
nonhashedgrammar.ignore(singleLineComment)
nonhashedgrammar.ignore(cppStyleComment)
statementGrammar.ignore(singleLineComment)
statementGrammar.ignore(cppStyleComment)
| Python |
3D | mcellteam/mcell | src/rules_py/mdlr2mdl.py | .py | 11,374 | 267 | #!/usr/bin/env python3
import argparse
import read_mdl
import write_mdl
from subprocess import call
import split_bngxml
import re
from nfsim_python import NFSim
import os
import read_bngxml
import write_bngxmle as writeBXe
import sys
# set by argument
FAIL_ON_ERROR = False
def define_console():
parser = argparse.ArgumentParser(description='SBML to BNGL translator')
parser.add_argument('-i', '--input', type=str, help='input MDLr file', required=True)
parser.add_argument('-n', '--nfsim', action='store_true', help='mcell-nfsim mode')
parser.add_argument('-o', '--output', type=str, help='output MDL file')
parser.add_argument('-b', '--bng-executable', type=str, help='file path pointing to the BNG2.pl file')
parser.add_argument('-m', '--mcell-executable', type=str, help='file path pointing to the MCell binary')
parser.add_argument('-r', '--run', action='store_true', help='run generated model with mcell')
parser.add_argument('-f', '--fail-on-error', action='store_true', help='exit with exit code 1 on error')
return parser
def get_script_path():
return os.path.dirname(os.path.realpath(__file__))
class MDLR2MDL(object):
'''
given an mdlr definition this script will get a set of mdl files compatible
with an nfsim bng-xml definition
'''
def __init__(self, configpath):
self.config = {}
self.config['bionetgen'] = os.path.join(configpath,'bng2','BNG2.pl')
self.config['mcell'] = os.path.join(configpath,'mcell')
self.config['libpath'] = os.path.join(configpath,'lib')
self.config['scriptpath'] = configpath
prefix = "lib"
if (sys.platform == 'linux') or (sys.platform == 'linux2'):
extension = "so"
elif (sys.platform == 'darwin'):
extension = "dylib"
elif (sys.platform == 'win32'):
extension = "dll"
else:
raise Exception("Unexpected platform: {0}".format(sys.platform))
libNFsim_path = os.path.join(self.config['libpath'], '{0}NFsim.{1}'.format(prefix, extension))
libnfsim_c_path = os.path.join(self.config['libpath'], '{0}nfsim_c.{1}'.format(prefix, extension))
if not os.path.exists(libNFsim_path):
# try the build directory paths
libNFsim_path = os.path.join(self.config['libpath'], '..', 'nfsim', '{0}NFsim.{1}'.format(prefix, extension))
if not os.path.exists(libnfsim_c_path):
# try the cygwin variant
libnfsim_c_path = os.path.join(self.config['libpath'], '..', 'nfsimCInterface', '{0}nfsim_c.{1}'.format(prefix, extension))
if not os.path.exists(libNFsim_path):
# default to system search using LD_LIBRARY_PATH on Unix or PATH on Windows
libNFsim_path = '{0}NFsim.{1}'.format(prefix, extension)
if not os.path.exists(libnfsim_c_path):
# default to system search
libnfsim_c_path = '{0}nfsim_c.{1}'.format(prefix, extension)
print("Loading libs from " + libNFsim_path + " and " + libnfsim_c_path + ".")
self.nfsim = NFSim(libnfsim_c_path, libNFsim_path=libNFsim_path)
def process_mdlr(self, mdlrPath):
'''
main method. extracts species definition, creates bng-xml, creates mdl
definitions
'''
try:
nauty_dict = self.xml2hnauty_species_definitions(mdlrPath)
except OSError:
print('Cannot open BNG2.pl. Please check BioNetGen is installed at: %s' % (self.config['bionetgen']))
sys.exit(0)
# append extended bng-xml to the bng-xml definition (the one that
# doesn't include seed information)
bngxmlestr = writeBXe.merge_bxbxe(
namespace.input + '_rules.xml', namespace.input + '_extended_bng.xml')
with open(mdlrPath + '_rules.xml', 'w') as f:
f.write(bngxmlestr)
xmlspec = read_bngxml.parseFullXML(namespace.input + '.xml')
# write out the equivalent plain mdl stuffs
mdl_dict = write_mdl.construct_mcell(
xmlspec, namespace.input, final_name.split(os.sep)[-1], nauty_dict)
write_mdl.write_mdl(mdl_dict, final_name)
def tokenize_seed_elements(self, seed):
# extract species names
seedKeys = re.findall(
'concentration="[0-9a-zA-Z_]+" name="[_0-9a-zA-Z@:(~!),.]+"', seed)
seedKeys = [re.sub('concentration="([0-9a-zA-Z_]+)" name="([_0-9a-zA-Z@:(~!),.]+)"', '\g<2>;\g<1>', x) for x in seedKeys]
seedList = seed.split('</Species>')
seedList = [x.strip() for x in seedList if x != '']
seedList = [x + '</Species>' for x in seedList]
# Jose's code here seems to go overboard and also rename components named S[0-9]+
# The intent seems to be to rename Species id's from "S[0-9]+" to S1, with double quotes dropped
#
# seedList = [re.sub('"S[0-9]+"', "S1", x) for x in seedList]
#
# Attempt to fix this by parsing the full context of 'Species id=...'
seedList = [re.sub('Species id="S[0-9]+"', 'Species id=S1', x) for x in seedList]
seedList = [re.sub('concentration="[0-9a-zA-Z_]+"', 'concentration="1"', x) for x in seedList]
seedList = ['<Model><ListOfSpecies>{0}</ListOfSpecies></Model>'.format(x) for x in seedList]
# seed_dict = {x:y for x, y in zip(seedKeys, seedList)}
seed_dict = {x.split(';')[0]: y for x, y in zip(seedKeys, seedList) if x.split(';')[1] != '0'}
# print '---', seed_dict.keys()
return seed_dict
def get_names_from_definition_string(self, defStr):
species_names = re.findall('[0-9a-zA-Z_]+\(', defStr)
return [x[:-1] for x in species_names]
def xml2hnauty_species_definitions(self, inputMDLRFile):
"""
Temporary function for translating xml bng definitions to nauty species
definition strings
it call the nfsim library to get the list of possible complexes in the
system, however the function right now returns the species in question
+ all molecule types (if we are sending a lone molecule tye as
initialization it still returns all molecule types), which means the
list requires filtering. and the filtering is not pretty
How to solve: make it so that nfsim returns a more sensible complex
list (filtering out unrelated molecule types) or create a nauty label
creation mechanism locally
"""
command = ['perl', self.config['bionetgen'], '-xml', '-check', inputMDLRFile + '.bngl']
output_dir = os.path.dirname(inputMDLRFile)
if output_dir:
command.extend(['--outdir', output_dir])
# get a bng-xml file
print("\n====> Running BioNetGen with explicit \"perl\": " + " ".join(command) + "\n")
returncode = call(command)
if returncode != 0:
print("BioNetGen failed with exit code " + str(returncode))
if FAIL_ON_ERROR:
sys.exit(1)
# extract seed species definition
seed, rest = split_bngxml.extractSeedBNG(inputMDLRFile + '.xml')
# store xml with non-seed sections and load up nfsim library
print("\nStore xml with non-seed sections and load up nfsim library\n")
with open(namespace.input + '_rules.xml', 'w') as f:
f.write(rest)
# load up nfsim library
print("Initializing NFSim using: " + namespace.input + '_rules.xml')
self.nfsim.init_nfsim(namespace.input + '_rules.xml', 0)
# remove encapsulating tags
seed = seed[30:-30]
# get the seed species definitions as a list
# print(">>>>>>>>>> THE SEED LIST: \n", str(seed))
seed_dict = self.tokenize_seed_elements(seed)
nauty_dict = {}
# print(">>>>>>>>>> SEED DICT: \n", seed_dict)
for seed in seed_dict:
# initialize nfsim with each species definition and get back a
# dirty list where one of the entries is the one we want
#
# XXX: i think i've solved it on the nfsim side, double check
tmpList = self.get_nauty_string(seed_dict[seed])
# print('>>>>>>>> SEED_DICT[SEED]: ' + str(seed_dict[seed]))
# print('>>>>>>>> tmpList: ' + str(tmpList))
# and now filter it out...
# get species names from species definition string
species_names = self.get_names_from_definition_string(seed)
nauty_dict[seed] = [x for x in tmpList if all(y in x for y in species_names)][0]
return nauty_dict
def get_nauty_string(self, xmlSpeciesDefinition):
self.nfsim.reset_system()
self.nfsim.init_system_xml(xmlSpeciesDefinition)
result = self.nfsim.querySystemStatus("complex")
return result
if __name__ == "__main__":
mdlr2mdl = MDLR2MDL(get_script_path())
parser = define_console()
namespace = parser.parse_args()
if namespace.fail_on_error:
FAIL_ON_ERROR = True
bngl_path = namespace.input + '.bngl'
final_name = namespace.output if namespace.output else namespace.input
print("Running " + namespace.input)
# mdl to bngl
result_dict = read_mdl.construct_bng_from_mdlr(
namespace.input, namespace.nfsim)
output_dir = os.sep.join(namespace.output.split(os.sep)[:-1])
# create bngl file
read_mdl.output_bngl(result_dict['bnglstr'], bngl_path)
# temporarily store bng-xml information in a separate file for display
# purposes
with open(namespace.input + '_extended_bng.xml', 'wb') as f:
f.write(result_dict['bngxmlestr'])
# get canonical label -bngl label dictionary
if not namespace.nfsim:
# bngl 2 sbml 2 json
read_mdl.bngl2json(namespace.input + '.bngl')
# json 2 plain mdl
mdl_dict = write_mdl.constructMDL(
namespace.input + '_sbml.xml.json', namespace.input, final_name)
# create an mdl with nfsim-species and nfsim-reactions
write_mdl.write_mdl(mdl_dict, final_name)
else:
mdlr2mdl.process_mdlr(namespace.input)
# get the species definitions
noext = os.path.splitext(namespace.input)[0]
xml_name = "{0}.mdlr_rules.xml".format(noext)
# my_env = {}
script_path = mdlr2mdl.config['scriptpath']
my_env = os.environ.copy()
if (sys.platform == 'darwin'):
if my_env.get('DYLD_LIBRARY_PATH'):
my_env['DYLD_LIBRARY_PATH']=os.path.join(script_path,'lib') + os.pathsep + my_env['DYLD_LIBRARY_PATH']
else:
my_env['DYLD_LIBRARY_PATH']=os.path.join(script_path,'lib')
else:
if my_env.get('LD_LIBRARY_PATH'):
my_env['LD_LIBRARY_PATH']=os.path.join(script_path,'lib') + os.pathsep + my_env['LD_LIBRARY_PATH']
else:
my_env['LD_LIBRARY_PATH']=os.path.join(script_path,'lib')
if namespace.run:
# Generate command to run MCell
mcell_path = mdlr2mdl.config['mcell']
mdl_name = "{0}.main.mdl".format(namespace.output)
cmd = [mcell_path, mdl_name, "-r", xml_name]
# Print the command to run MCell
print("\n====> Running MCell with: " + " ".join(cmd) + "\n")
# Actually run MCell (if desired)
call(cmd,env=my_env)
| Python |
3D | mcellteam/mcell | src/rules_py/read_mdl.py | .py | 14,763 | 375 | from __future__ import print_function
from grammar_definition import statementGrammar, grammar, species_definition
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import small_structures as st
from subprocess import call
from collections import defaultdict
import write_bngxmle
import os
# special object created for releases in case
# when there are no compartments
DEFAULT_COMPARTMENT = 'default_compartment'
def eprint(*args, **kwargs):
'''
stderr printing
'''
print(*args, file=sys.stderr, **kwargs)
def process_parameters(statements):
pstr = StringIO()
pstr.write('begin parameters\n')
for parameter in statements:
if parameter[1][0] != '"':
temp_str = '\t{0} {1}\n'.format(parameter[0], parameter[1]).replace('/*', '#')
temp_str.replace('//', '#')
else:
continue
pstr.write(temp_str)
pstr.write('end parameters\n')
return pstr.getvalue()
def create_molecule_from_pattern(molecule_pattern, idx):
tmp_molecule = st.Molecule(molecule_pattern['moleculeName'], idx)
if 'moleculeCompartment' in molecule_pattern:
tmp_molecule.compartment = molecule_pattern['moleculeCompartment'][1]
if 'components' in molecule_pattern.keys():
for idx2, component in enumerate(molecule_pattern['components']):
tmp_component = st.Component(component['componentName'], '{0}_{1}'.format(idx, idx2))
if 'state' in component:
for state in component['state']:
if state != '':
tmp_component.addState(state)
if 'bond' in component.keys():
for bond in component['bond']:
tmp_component.addBond(bond)
tmp_molecule.addComponent(tmp_component)
return tmp_molecule
def create_species_from_pattern(speciesPattern):
tmp_species = st.Species()
if 'speciesCompartment' in speciesPattern.keys():
tmp_species.compartment = speciesPattern['speciesCompartment'][1]
for idx, element in enumerate(speciesPattern['speciesPattern']):
tmp_species.addMolecule(create_molecule_from_pattern(element, idx))
return tmp_species
def process_molecules_for_final_mdl(molecules):
""" grab molecule defintions from mdlr for final mdl. """
molecule_str = ""
for idx, molecule in enumerate(molecules):
diffusion_list = molecule[1]['diffusionFunction']
molecule_name = molecule[0][0]
component_str = ""
component_list = molecule[0][1:]
for c_idx, component in enumerate(component_list):
if c_idx > 0:
component_str += ", "
c_name = component['componentName']
try:
c_loc = component['componentLoc']
x1, y1, z1 = c_loc[0], c_loc[1], c_loc[2]
c_rot = component['componentRot']
x2, y2, z2, angle = c_rot[0], c_rot[1], c_rot[2], c_rot[3]
component_str += "{}{{loc=[{}, {}, {}], rot=[{}, {}, {}, {}]}}".format(c_name, x1, y1, z1, x2, y2, z2, angle)
except KeyError:
component_str += c_name
molecule_str += "\t{}({})\n".format(molecule_name, component_str)
# molecule_str += "\t{\n"
# molecule_str += "\t\t{} = {}\n".format(diffusion_list[0], diffusion_list[1])
# molecule_str += "\t}\n"
return molecule_str
def process_molecules(molecules):
mstr = StringIO()
molecule_list = []
mstr.write('begin molecule types\n')
for idx, molecule in enumerate(molecules):
tmp_molecule = create_molecule_from_pattern(molecule[0], idx)
molecule_list.append((tmp_molecule.name, str(tmp_molecule)))
mstr.write('\t{0}\n'.format(tmp_molecule.str2()))
mstr.write('end molecule types\n')
return mstr.getvalue(), molecule_list
def process_init_compartments(initializations):
sstr = StringIO()
cstr = StringIO()
sstr.write('begin seed species\n')
cstr.write('begin compartments\n')
for initialization in initializations:
# print initialization.keys()
if 'name' in initialization.keys():
tmp_species = None
initialConditions = 0
for entry in initialization['entries']:
if entry[0] == 'MOLECULE':
pattern = species_definition.parseString(entry[1])
tmp_species = create_species_from_pattern(pattern[0])
elif entry[0] in ['NUMBER_TO_RELEASE', 'CONCENTRATION']:
initialConditions = entry[1]
sstr.write('\t {0} {1}\n'.format(str(tmp_species), initialConditions))
else:
optionDict = {'parent': '', 'name': initialization['compartmentName']}
for option in initialization['compartmentOptions'][0]:
if len(option) > 0:
if option[0] == 'MEMBRANE':
tmp = option[1].strip()
optionDict['membrane'] = tmp.split(' ')[0]
elif option[0] == 'PARENT':
tmp = option[1].strip()
optionDict['parent'] = tmp
if 'membrane' in optionDict:
cstr.write('\t{0} 2 1 {1}\n'.format(optionDict['membrane'], optionDict['parent']))
cstr.write('\t{0} 3 1 {1}\n'.format(optionDict['name'], optionDict['membrane']))
else:
if optionDict['name'] == DEFAULT_COMPARTMENT:
# skip this special name - BNGL has not compartments
continue
tmp = '{0} 3 1 {1}'.format(optionDict['name'], optionDict['parent'])
tmp = tmp.strip()
cstr.write('\t{0}\n'.format(tmp))
sstr.write('end seed species\n')
cstr.write('end compartments\n')
return sstr.getvalue(), cstr.getvalue()
def process_observables(observables):
ostr = StringIO()
ostr.write('begin observables\n')
for observable in observables:
if 'patterns' in observable.keys() and 'outputfile' in observable.keys():
if observable['outputfile'].endswith('_Species.dat'):
tmpObservable = '\tSpecies ' # extension, not supported by the CellBlender plotting
else:
tmpObservable = '\tMolecules ' # this is the default
tmpObservable += '{0} '.format(observable['outputfile'].split('/')[-1].split('.')[0])
patternList = []
for pattern in observable['patterns']:
patternList.append(str(create_species_from_pattern(pattern['speciesPattern'])))
tmpObservable += ', '.join(patternList)
ostr.write(tmpObservable + '\n')
elif 'obskey' in observable.keys():
tmpObservable = '\t{0} '.format(observable['obskey'])
tmpObservable += '{0} '.format(observable['obsname'])
patternList = []
for pattern in observable['obspatterns']:
patternList.append(str(create_species_from_pattern(pattern)))
tmpObservable += ', '.join(patternList)
ostr.write(tmpObservable + '\n')
ostr.write('end observables\n')
return ostr.getvalue()
def process_mtobservables(moleculeTypes):
'''
creates a list of observables from just molecule types
'''
ostr = StringIO()
raise Exception
ostr.write('begin observables\n')
for moleculeType in moleculeTypes:
ostr.write('\t Species {0} {1}\n'.format(moleculeType[0], moleculeType[1]))
ostr.write('end observables\n')
return ostr.getvalue()
def process_reaction_rules(rules):
rStr = StringIO()
rStr.write('begin reaction rules\n')
for rule in rules:
tmp_rule = st.Rule()
for pattern in rule['reactants']:
tmp_rule.addReactant(create_species_from_pattern(pattern))
for pattern in rule['products']:
tmp_rule.addProduct(create_species_from_pattern(pattern))
for rate in rule['rate']:
tmp_rule.addRate(rate)
rStr.write('\t{0}\n'.format(str(tmp_rule)))
rStr.write('end reaction rules\n')
return rStr.getvalue()
def process_diffussion_elements(parameters, extendedData):
'''
extract the list of properties associated to molecule types and compartment
objects. right now this information will be encoded into the bng-exml spec.
It also extracts some predetermined model properties.
'''
modelProperties = {}
moleculeProperties = defaultdict(list)
compartmentProperties = defaultdict(list)
for parameter in extendedData['system']:
modelProperties[parameter[0].strip()] = parameter[1].strip()
for molecule in extendedData['molecules']:
if 'moleculeParameters' in molecule[1]:
for propertyValue in molecule[1]['moleculeParameters']:
data = {'name': propertyValue[1].strip(), 'parameters': []}
moleculeProperties[molecule[0][0]].append((propertyValue[0], data))
if 'diffusionFunction' in molecule[1]:
if 'function' in molecule[1]['diffusionFunction'].keys():
parameters = molecule[1]['diffusionFunction'][1]['parameters']
data = {'name': '"{0}"'.format(molecule[1]['diffusionFunction'][1]['functionName']), 'parameters': [(x['key'], x['value']) for x in parameters]}
else:
data = {'name': molecule[1]['diffusionFunction'][1].strip(), 'parameters': []}
if '3D' in molecule[1]['diffusionFunction'].keys():
dimensionality = {'name': '3', 'parameters': []}
if '2D' in molecule[1]['diffusionFunction'].keys():
dimensionality = {'name': '2', 'parameters': []}
moleculeProperties[molecule[0][0]].append(('diffusion_function', data))
moleculeProperties[molecule[0][0]].append(('dimensionality', dimensionality))
for seed in extendedData['initialization']:
if 'compartmentName' in seed.keys():
membrane = ''
membrane_properties = []
for element in seed['compartmentOptions'][0]:
# skip stuff already covered by normal cbng
if element[0] in ['PARENT']:
continue
if element[0] == 'MEMBRANE':
membrane = element[1].strip().split(' ')[0]
elif element[0].startswith('MEMBRANE'):
membrane_properties.append((element[0].split('_')[1], element[1].strip()))
else:
compartmentProperties[seed['compartmentName']].append((element[0], element[1]))
if membrane != '' and len(membrane_properties) > 0:
compartmentProperties[membrane] = membrane_properties
return {'modelProperties': modelProperties, 'moleculeProperties': moleculeProperties,
'compartmentProperties': compartmentProperties}
def process_functions(rawFunctions):
ofun = StringIO()
ofun.write('begin functions\n')
for function in rawFunctions:
ofun.write('{0}() ={1}\n'.format(function['functionName'][0], function['functionBody'][0]))
ofun.write('end functions\n')
return ofun.getvalue()
def write_default_functions():
defaultFunctions = StringIO()
defaultFunctions.write('begin functions\n')
defaultFunctions.write('\teinstein_stokes(p_kb, p_t, p_rs, p_mu)= p_kb*p_t/(6*3.141592*p_mu*p_rs)\n')
defaultFunctions.write('\tsaffman_delbruck(p_kb, p_t, p_rc, p_mu, p_mu_ex, p_gamma, p_h) = p_kb*p_t*log((p_mu*p_h/(p_rc*p_mu_ex)-p_gamma))/(4*3.141592*p_mu*p_h)\n')
defaultFunctions.write('end functions\n')
return defaultFunctions.getvalue()
def construct_bng_from_mdlr(mdlrPath, nfsimFlag=False, separate_spatial=True):
'''
initializes a bngl file and an extended-bng-xml file with a MDLr file description
'''
with open(mdlrPath, 'r') as f:
mdlr = f.read()
statements = statementGrammar.parseString(mdlr)
sections = grammar.parseString(mdlr)
final_bngl_str = StringIO()
final_bngl_str.write('begin model\n')
parameterStr = process_parameters(statements)
try:
moleculeStr, molecule_list = process_molecules(sections['molecules'])
except 'KeyError':
eprint('There is an issue with the molecules section in the mdlr file')
try:
seedspecies, compartments = process_init_compartments(sections['initialization']['entries'])
except KeyError:
eprint('There is an issue with the initialization section in the mdlr file')
if 'math_functions' in sections:
functions = process_functions(sections['math_functions'])
else:
functions = ''
observables = ''
if not nfsimFlag:
observables = process_observables(sections['observables'])
else:
try:
observables = process_observables(sections['observables'])
except KeyError:
eprint('There is an issue with the observables section in the mdlr file')
reactions = process_reaction_rules(sections['reactions'])
final_bngl_str.write(parameterStr)
final_bngl_str.write(moleculeStr)
final_bngl_str.write(compartments)
final_bngl_str.write(seedspecies)
final_bngl_str.write(observables)
final_bngl_str.write(functions)
final_bngl_str.write(reactions)
final_bngl_str.write('end model\n')
# add processing actions
if not nfsimFlag:
final_bngl_str.write('generate_network({overwrite=>1})\n')
final_bngl_str.write('writeSBML()\n')
'''
eventually this stuff should be integrated into bionetgen proper
'''
if separate_spatial:
extended_data = {}
if 'systemConstants' in sections.keys():
extended_data['system'] = sections['systemConstants']
else:
extended_data['system'] = []
extended_data['molecules'] = sections['molecules']
extended_data['initialization'] = sections['initialization']['entries']
propertiesDict = process_diffussion_elements(statements, extended_data)
bngxmle = write_bngxmle.write2bngxmle(propertiesDict, mdlrPath.split(os.sep)[-1])
return {'bnglstr': final_bngl_str.getvalue(), 'bngxmlestr': bngxmle}
def bngl2json(bnglFile):
call(['bngdev', bnglFile])
sbmlName = '.'.join(bnglFile.split('.')[:-1]) + '_sbml.xml'
print(sbmlName)
call(['./sbml2json', '-i', sbmlName])
def output_bngl(bngl_str, bnglPath):
with open(bnglPath, 'w') as f:
f.write(bngl_str)
if __name__ == "__main__":
bngl_str = construct_bng_from_mdlr('example.mdlr')
bnglPath = 'output.bngl'
output_bngl(bngl_str, bnglPath)
# bngl2json(bnglFile)
| Python |
3D | mcellteam/mcell | src/rules_py/split_bngxml.py | .py | 864 | 33 | import argparse
def defineConsole():
"""
input console options
"""
parser = argparse.ArgumentParser(description='SBML to BNGL translator')
parser.add_argument('-i', '--input', type=str, help='input MDLr file', required=True)
return parser
def extractSeedBNG(xmlname):
with open(xmlname, 'r') as f:
bngxml = f.read()
start = bngxml.find('<ListOfSpecies>')
end = bngxml.find('</ListOfSpecies>') + len('</ListOfSpecies>')
seedxml = '<Model>\n' + bngxml[start:end] + '</Model>\n'
restxml = bngxml[:start] + '<ListOfSpecies>\n</ListOfSpecies>' + bngxml[end:]
return seedxml, restxml
if __name__ == "__main__":
parser = defineConsole()
namespace = parser.parse_args()
seed, rest = extractSeedBNG(namespace.input)
with open(namespace.input + '_rules.xml', 'w') as f:
f.write(rest)
| Python |
3D | mcellteam/mcell | src/rules_py/read_bngxml.py | .py | 13,302 | 374 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 19 14:28:16 2012
@author: proto
"""
from lxml import etree
import small_structures as st
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
# http://igraph.sourceforge.net/documentation.html
# ----------------------------------------------------------------------
def findBond(bondDefinitions, component):
'''
Returns an appropiate bond number when verifying how to molecules connect
in a species
'''
for idx, bond in enumerate(bondDefinitions.getchildren()):
if component in [bond.get('site1'), bond.get('site2')]:
return str(idx + 1)
def createMolecule(molecule, bonds):
nameDict = {}
mol = st.Molecule(molecule.get('name'), molecule.get('id'))
if molecule.get('compartment') not in ['', None]:
mol.setCompartment(molecule.get('compartment'))
nameDict[molecule.get('id')] = molecule.get('name')
listOfComponents = molecule.find('.//{http://www.sbml.org/sbml/level3}ListOfComponents')
if listOfComponents is not None:
for element in listOfComponents:
component = st.Component(element.get('name'), element.get('id'))
nameDict[element.get('id')] = element.get('name')
if element.get('numberOfBonds') in ['+', '?']:
component.addBond(element.get('numberOfBonds'))
elif element.get('numberOfBonds') != '0':
component.addBond(findBond(bonds, element.get('id')))
state = element.get('state') if element.get('state') is not None else ''
component.states.append(state)
component.activeState = state
mol.addComponent(component)
return mol, nameDict
def createSpecies(pattern):
tmpDict = {}
species = st.Species()
species.idx = pattern.get('id')
species.trueName = pattern.get('name')
compartment = pattern.get('compartment')
if compartment is not None:
species.compartment = compartment
mol = pattern.find('.//{http://www.sbml.org/sbml/level3}ListOfMolecules')
bonds = pattern.find('.//{http://www.sbml.org/sbml/level3}ListOfBonds')
for molecule in mol.getchildren():
molecule, nameDict = createMolecule(molecule, bonds)
tmpDict.update(nameDict)
species.addMolecule(molecule)
if bonds is not None:
species.bonds = [(bond.get('site1'), bond.get('site2')) for bond in bonds]
tmpDict.update(nameDict)
return species, tmpDict
def parseRule(rule, parameterDict):
'''
Parses a rule XML section
Returns: a list of the reactants and products used, followed by the mapping
between the two and the list of operations that were performed
'''
rp = rule.find('.//{http://www.sbml.org/sbml/level3}ListOfReactantPatterns')
pp = rule.find('.//{http://www.sbml.org/sbml/level3}ListOfProductPatterns')
mp = rule.find('.//{http://www.sbml.org/sbml/level3}Map')
op = rule.find('.//{http://www.sbml.org/sbml/level3}ListOfOperations')
rt = rule.find('.//{http://www.sbml.org/sbml/level3}RateLaw')
nameDict = {}
reactants = []
products = []
actions = []
mappings = []
if len(rp) == 0:
sp = st.Species()
ml = st.Molecule('0', '')
sp.addMolecule(ml)
reactants.append(sp)
if len(pp) == 0:
sp = st.Species()
ml = st.Molecule('0', '')
sp.addMolecule(ml)
products.append(sp)
for pattern in rp:
elm, tmpDict = createSpecies(pattern)
reactants.append(elm)
nameDict.update(tmpDict)
for pattern in pp:
elm, tmpDict = createSpecies(pattern)
products.append(elm)
nameDict.update(tmpDict)
for operation in op:
action = st.Action()
tag = operation.tag
tag = tag.replace('{http://www.sbml.org/sbml/level3}', '')
if operation.get('site1') is not None:
action.setAction(tag, operation.get('site1'), operation.get('site2'))
else:
action.setAction(tag, operation.get('site'), None)
actions.append(action)
for mapping in mp:
tmpMap = (mapping.get('sourceID'), mapping.get('targetID'))
mappings.append(tmpMap)
rateConstants = rt.find('.//{http://www.sbml.org/sbml/level3}ListOfRateConstants')
if rateConstants is None:
rateConstants = rt.get('name')
else:
for constant in rateConstants:
tmp = constant.get('value')
rateConstants = tmp
rateConstantsValue = parameterDict[rateConstants] if rateConstants in parameterDict else rateConstants
# rule = st.Rule()
label = rule.get('name')
label = label.replace('(', '_').replace(')', '_')
rule = st.Rule(label)
rule.addReactantList(reactants)
rule.addProductList(products)
rule.addActionList(actions)
rule.addMappingList(mappings)
rule.addRate(rateConstants)
# return reactants, products, actions, mappings, nameDict,rateConstantsValue,rateConstants
return rule, nameDict, rateConstantsValue, rateConstants
def parseMolecules(molecules):
'''
Parses an XML molecule section
Returns: a molecule structure
'''
mol = st.Molecule(molecules.get('id'), molecules.get('id'))
components = \
molecules.find('.//{http://www.sbml.org/sbml/level3}ListOfComponentTypes')
if components is not None:
for component in components.getchildren():
comp = parseComponent(component)
mol.addComponent(comp)
return mol
def parseComponent(component):
'''
parses a bngxml molecule types section
'''
comp = st.Component(component.get('id'), component.get('id'))
states = component.find('.//{http://www.sbml.org/sbml/level3}ListOfAllowedStates')
if states is not None:
for state in states.getchildren():
comp.addState(state.get('id'))
return comp
def parseObservable(observable):
name = observable.get('name')
otype = observable.get('type')
rp = observable.find('.//{http://www.sbml.org/sbml/level3}ListOfPatterns')
patternList = []
for pattern in rp:
elm, tmpDict = createSpecies(pattern)
patternList.append(elm)
return name, otype, patternList
def parseObservables(observables):
observableDescription = []
for observable in observables:
observableDescription.append(parseObservable(observable))
return observableDescription
def parseFunction(function):
referenceList = []
name = function.get('id')
# expression = function.find('.//{http://www.sbml.org/sbml/level3}Expression')
expression = function.findtext('.//{http://www.sbml.org/sbml/level3}Expression')
references = function.find('.//{http://www.sbml.org/sbml/level3}ListOfReferences')
for reference in references:
referenceList.append([reference.get('name'), reference.get('type')])
return name, expression, referenceList
def parseFunctions(functions):
functionDescription = []
for function in functions:
functionDescription.append(parseFunction(function))
return functionDescription
def parseFullXML(xmlFile):
doc = etree.parse(xmlFile)
molecules = doc.findall('.//{http://www.sbml.org/sbml/level3}MoleculeType')
seedspecies = doc.findall('.//{http://www.sbml.org/sbml/level3}Species')
rules = doc.findall('.//{http://www.sbml.org/sbml/level3}ReactionRule')
functions = doc.findall('.//{http://www.sbml.org/sbml/level3}Function')
structureDefinitions = {}
ruleDescription = []
moleculeList = []
seedSpeciesList = []
compartmentList = []
observables = doc.findall('.//{http://www.sbml.org/sbml/level3}Observable')
parameters = doc.findall('.//{http://www.sbml.org/sbml/level3}Parameter')
compartments = doc.findall('.//{http://www.sbml.org/sbml/level3}compartment')
parameterDict = {}
for parameter in parameters:
parameterDict[parameter.get('id')] = parameter.get('value')
structureDefinitions['parameters'] = parameterDict
for compartment in compartments:
compartmentDict = {}
compartmentDict['identifier'] = compartment.get('id')
compartmentDict['dimensions'] = compartment.get('spatialDimensions')
compartmentDict['size'] = compartment.get('size')
compartmentDict['outside'] = compartment.get('outside')
compartmentList.append(compartmentDict)
structureDefinitions['compartments'] = compartmentList
for molecule in molecules:
moleculeList.append(parseMolecules(molecule))
structureDefinitions['molecules'] = moleculeList
for species in seedspecies:
concentration = species.get('concentration')
compartment = species.get('compartment')
seedSpeciesList.append({'concentration': concentration, 'structure': createSpecies(species)[0],
'compartment': compartment})
structureDefinitions['seedspecies'] = seedSpeciesList
for rule in rules:
# description = parseRule(rule, parameterDict)
# if 'reverse' in description[0].label:
# ruleDescription[-1][0].bidirectional= True
# ruleDescription[-1][0].rates.append(description[0].rates[0])
# else:
ruleDescription.append(parseRule(rule, parameterDict))
structureDefinitions['rules'] = ruleDescription
structureDefinitions['functions'] = parseFunctions(functions)
structureDefinitions['observables'] = parseObservables(observables)
return structureDefinitions
def parseXMLStruct(doc):
molecules = doc.findall('.//{http://www.sbml.org/sbml/level3}MoleculeType')
rules = doc.findall('.//{http://www.sbml.org/sbml/level3}ReactionRule')
ruleDescription = []
moleculeList = []
parameters = doc.findall('.//{http://www.sbml.org/sbml/level3}Parameter')
parameterDict = {}
for parameter in parameters:
parameterDict[parameter.get('id')] = parameter.get('value')
for molecule in molecules:
moleculeList.append(parseMolecules(molecule))
for rule in rules:
description = parseRule(rule, parameterDict)
# if 'reverse' in description[0].label:
# ruleDescription[-1][0].bidirectional= True
# ruleDescription[-1][0].rates.append(description[0].rates[0])
# else:
ruleDescription.append(parseRule(rule, parameterDict))
return moleculeList, ruleDescription, parameterDict
def parseXMLFromString(xmlString):
doc = etree.fromstring(xmlString)
return parseXMLStruct(doc)
def parseXML(xmlFile):
doc = etree.parse(xmlFile)
return parseXMLStruct(doc)
def getNumObservablesXML(xmlFile):
doc = etree.parse(xmlFile)
observables = doc.findall('.//{http://www.sbml.org/sbml/level3}Observable')
return len(observables)
def createBNGLFromDescription(namespace):
"""creates a bngl file from a dictionary description containing molecules, species, etc."""
bnglString = StringIO()
bnglString.write('begin model\n')
# parameters
bnglString.write('begin parameters\n')
for parameterName in namespace['parameters']:
bnglString.write('\t{0} {1}\n'.format(parameterName, namespace['parameters'][parameterName]))
bnglString.write('end parameters\n')
# molecule types
bnglString.write('begin molecule types\n')
for molecule in namespace['molecules']:
bnglString.write('\t' + molecule.str2() + '\n')
bnglString.write('end molecule types\n')
# compartments
bnglString.write('begin compartments\n')
for compartment in namespace['compartments']:
bnglString.write('\t{0} {1} {2}'.format(compartment['identifier'], compartment['dimensions'], compartment['size']))
if compartment['outside']:
bnglString.write('\t {0}\n'.format(compartment['outside']))
else:
bnglString.write('\n')
bnglString.write('end compartments\n')
# seed species
bnglString.write('begin seed species\n')
for seedspecies in namespace['seedspecies']:
if seedspecies['concentration'] not in [0, '0', '0.0']:
bnglString.write('\t{0} {1}\n'.format(seedspecies['structure'], seedspecies['concentration']))
bnglString.write('end seed species\n')
# observables
bnglString.write('begin observables\n')
for observables in namespace['observables']:
bnglString.write('\t{0} {1} {2}\n'.format(observables[1], observables[0], ', '.join([str(x) for x in observables[2]])))
bnglString.write('end observables\n')
# functions
bnglString.write('begin functions\n')
for functions in namespace['functions']:
bnglString.write('\t{0}() = {1}\n'.format(functions[0], functions[1]))
bnglString.write('end functions\n')
# rules
bnglString.write('begin reaction rules\n')
for rule in namespace['rules']:
bnglString.write('\t{0}\n'.format(rule[0]))
bnglString.write('end reaction rules\n')
bnglString.write('end model\n')
return bnglString.getvalue()
if __name__ == "__main__":
# mol,rule,par = parseXML("output19.xml")
# print [str(x) for x in mol]
with open('output19.xml', 'r') as f:
s = f.read()
print(parseXMLFromString(s))
# print getNumObservablesXML('output19.xml')
| Python |
3D | mcellteam/mcell | appveyor_windows/mdlparse.c | .c | 301,064 | 6,571 | /* A Bison parser, made by GNU Bison 3.0.4. */
/* Bison implementation for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "3.0.4"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 1
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* Substitute the variable and function names. */
#define yyparse mdlparse
#define yylex mdllex
#define yyerror mdlerror
#define yydebug mdldebug
#define yynerrs mdlnerrs
/* Copy the first part of user declarations. */
#line 1 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:339 */
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <errno.h>
#include "rng.h"
#include "logging.h"
#include "vector.h"
#include "strfunc.h"
#include "mem_util.h"
#include "sym_table.h"
#include "diffuse_util.h"
#include "mdlparse_util.h"
#include "mdlparse_aux.h"
#include "util.h"
#include "react_output.h"
#include "mcell_misc.h"
#include "mcell_structs.h"
#include "mcell_viz.h"
#include "mcell_release.h"
#include "mcell_objects.h"
#include "mcell_dyngeom.h"
/* make sure to declare yyscan_t before including mdlparse.h */
typedef void *yyscan_t;
#include "mdlparse.h"
int mdllex_init(yyscan_t *ptr_yy_globals) ;
int mdllex_destroy(yyscan_t yyscanner);
void mdlrestart(FILE *infile, yyscan_t scanner);
int mdllex(YYSTYPE *yylval, struct mdlparse_vars *parse_state, yyscan_t scanner);
#ifdef DEBUG_MDL_PARSER
#define FAILCHECK(t) do { mcell_error_nodie("Parser fail: %s:%d (%s)\n", __FILE__, __LINE__, t); return 1; } while(0)
#else
#define FAILCHECK(t) return 1
#endif
#define CHECK(a) do { if ((a) != 0) FAILCHECK("non-zero"); } while (0)
#define CHECKN(a) do { if ((a) == NULL) FAILCHECK("NULL"); } while (0)
#define CHECKF(a) do { \
if (isnan(a)) \
{ \
mdlerror(parse_state, "Expression result is not a number"); \
FAILCHECK("NaN"); \
} \
else if (isinf(a)) \
{ \
mdlerror(parse_state, "Expression result is infinite"); \
FAILCHECK("Infinite"); \
} \
} while(0)
#undef yyerror
#define yyerror(a, b, c) mdlerror(a, c)
#line 137 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:339 */
# ifndef YY_NULLPTR
# if defined __cplusplus && 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif
/* In a future release of Bison, this section will be replaced
by #include "mdlparse.h". */
#ifndef YY_MDL_HOME_JCZECH_MCELL_BUILD_DEPS_MDLPARSE_H_INCLUDED
# define YY_MDL_HOME_JCZECH_MCELL_BUILD_DEPS_MDLPARSE_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int mdldebug;
#endif
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
ABS = 258,
ABSORPTIVE = 259,
ACCURATE_3D_REACTIONS = 260,
ACOS = 261,
ALL_CROSSINGS = 262,
ALL_DATA = 263,
ALL_ELEMENTS = 264,
ALL_ENCLOSED = 265,
ALL_HITS = 266,
ALL_ITERATIONS = 267,
ALL_MOLECULES = 268,
ALL_NOTIFICATIONS = 269,
ALL_TIMES = 270,
ALL_WARNINGS = 271,
ASCII = 272,
ASIN = 273,
ASPECT_RATIO = 274,
ATAN = 275,
BACK = 276,
BACK_CROSSINGS = 277,
BACK_HITS = 278,
BOTTOM = 279,
BOX = 280,
BOX_TRIANGULATION_REPORT = 281,
BRIEF = 282,
CEIL = 283,
CELLBLENDER = 284,
CENTER_MOLECULES_ON_GRID = 285,
CHECKPOINT_INFILE = 286,
CHECKPOINT_ITERATIONS = 287,
CHECKPOINT_OUTFILE = 288,
CHECKPOINT_REALTIME = 289,
CHECKPOINT_REPORT = 290,
CLAMP_CONCENTRATION = 291,
CLOSE_PARTITION_SPACING = 292,
CONCENTRATION = 293,
CORNERS = 294,
COS = 295,
COUNT = 296,
CUBIC = 297,
CUBIC_RELEASE_SITE = 298,
CUSTOM_SPACE_STEP = 299,
CUSTOM_TIME_STEP = 300,
DEFINE_MOLECULE = 301,
DEFINE_MOLECULES = 302,
DEFINE_REACTIONS = 303,
DEFINE_RELEASE_PATTERN = 304,
DEFINE_SURFACE_CLASS = 305,
DEFINE_SURFACE_CLASSES = 306,
DEFINE_SURFACE_REGIONS = 307,
DEGENERATE_POLYGONS = 308,
DELAY = 309,
DENSITY = 310,
DIFFUSION_CONSTANT_2D = 311,
DIFFUSION_CONSTANT_3D = 312,
DIFFUSION_CONSTANT_REPORT = 313,
DYNAMIC_GEOMETRY = 314,
DYNAMIC_GEOMETRY_MOLECULE_PLACEMENT = 315,
EFFECTOR_GRID_DENSITY = 316,
ELEMENT_CONNECTIONS = 317,
ELLIPTIC = 318,
ELLIPTIC_RELEASE_SITE = 319,
EQUAL = 320,
ERROR = 321,
ESTIMATE_CONCENTRATION = 322,
EXCLUDE_ELEMENTS = 323,
EXCLUDE_PATCH = 324,
EXCLUDE_REGION = 325,
EXIT = 326,
EXP = 327,
EXPRESSION = 328,
EXTERN = 329,
FALSE = 330,
FCLOSE = 331,
FILENAME = 332,
FILENAME_PREFIX = 333,
FILE_OUTPUT_REPORT = 334,
FINAL_SUMMARY = 335,
FLOOR = 336,
FOPEN = 337,
FORMAT = 338,
FPRINTF = 339,
FPRINT_TIME = 340,
FRONT = 341,
FRONT_CROSSINGS = 342,
FRONT_HITS = 343,
GAUSSIAN_RELEASE_NUMBER = 344,
GEOMETRY = 345,
GRAPH_PATTERN = 346,
HEADER = 347,
HIGH_PROBABILITY_THRESHOLD = 348,
HIGH_REACTION_PROBABILITY = 349,
IGNORED = 350,
INCLUDE_ELEMENTS = 351,
INCLUDE_FILE = 352,
INCLUDE_PATCH = 353,
INCLUDE_REGION = 354,
INPUT_FILE = 355,
INSTANTIATE = 356,
LLINTEGER = 357,
FULLY_RANDOM = 358,
INTERACTION_RADIUS = 359,
ITERATION_LIST = 360,
ITERATION_NUMBERS = 361,
ITERATION_REPORT = 362,
ITERATIONS = 363,
KEEP_CHECKPOINT_FILES = 364,
LEFT = 365,
LIFETIME_THRESHOLD = 366,
LIFETIME_TOO_SHORT = 367,
LIST = 368,
LOCATION = 369,
LOG = 370,
LOG10 = 371,
MAX_TOK = 372,
MAXIMUM_STEP_LENGTH = 373,
MEAN_DIAMETER = 374,
MEAN_NUMBER = 375,
MEMORY_PARTITION_X = 376,
MEMORY_PARTITION_Y = 377,
MEMORY_PARTITION_Z = 378,
MEMORY_PARTITION_POOL = 379,
MICROSCOPIC_REVERSIBILITY = 380,
MIN_TOK = 381,
MISSED_REACTIONS = 382,
MISSED_REACTION_THRESHOLD = 383,
MISSING_SURFACE_ORIENTATION = 384,
MOD = 385,
MODE = 386,
MODIFY_SURFACE_REGIONS = 387,
MOLECULE = 388,
MOLECULE_COLLISION_REPORT = 389,
MOLECULE_DENSITY = 390,
MOLECULE_NUMBER = 391,
MOLECULE_POSITIONS = 392,
MOLECULES = 393,
MOLECULE_PLACEMENT_FAILURE = 394,
NAME_LIST = 395,
NEAREST_POINT = 396,
NEAREST_TRIANGLE = 397,
NEGATIVE_DIFFUSION_CONSTANT = 398,
NEGATIVE_REACTION_RATE = 399,
NO = 400,
NOEXIT = 401,
NONE = 402,
NO_SPECIES = 403,
NOT_EQUAL = 404,
NOTIFICATIONS = 405,
NUMBER_OF_SUBUNITS = 406,
NUMBER_OF_TRAINS = 407,
NUMBER_TO_RELEASE = 408,
OBJECT = 409,
OFF = 410,
ON = 411,
ORIENTATIONS = 412,
OUTPUT_BUFFER_SIZE = 413,
INVALID_OUTPUT_STEP_TIME = 414,
LARGE_MOLECULAR_DISPLACEMENT = 415,
ADD_REMOVE_MESH = 416,
OVERWRITTEN_OUTPUT_FILE = 417,
PARTITION_LOCATION_REPORT = 418,
PARTITION_X = 419,
PARTITION_Y = 420,
PARTITION_Z = 421,
PERIODIC_BOX = 422,
PERIODIC_X = 423,
PERIODIC_Y = 424,
PERIODIC_Z = 425,
PERIODIC_TRADITIONAL = 426,
PI_TOK = 427,
POLYGON_LIST = 428,
POSITIONS = 429,
PRINTF = 430,
PRINT_TIME = 431,
PROBABILITY_REPORT = 432,
PROBABILITY_REPORT_THRESHOLD = 433,
PROGRESS_REPORT = 434,
RADIAL_DIRECTIONS = 435,
RADIAL_SUBDIVISIONS = 436,
RAND_GAUSSIAN = 437,
RAND_UNIFORM = 438,
REACTION_DATA_OUTPUT = 439,
REACTION_OUTPUT_REPORT = 440,
REAL = 441,
RECTANGULAR_RELEASE_SITE = 442,
RECTANGULAR_TOKEN = 443,
REFLECTIVE = 444,
RELEASE_EVENT_REPORT = 445,
RELEASE_INTERVAL = 446,
RELEASE_PATTERN = 447,
RELEASE_PROBABILITY = 448,
RELEASE_SITE = 449,
REMOVE_ELEMENTS = 450,
RIGHT = 451,
ROTATE = 452,
ROUND_OFF = 453,
SCALE = 454,
SEED = 455,
SHAPE = 456,
SHOW_EXACT_TIME = 457,
SIN = 458,
SITE_DIAMETER = 459,
SITE_RADIUS = 460,
SPACE_STEP = 461,
SPHERICAL = 462,
SPHERICAL_RELEASE_SITE = 463,
SPHERICAL_SHELL = 464,
SPHERICAL_SHELL_SITE = 465,
SPRINTF = 466,
SQRT = 467,
STANDARD_DEVIATION = 468,
PERIODIC_BOX_INITIAL = 469,
STEP = 470,
STRING_TO_NUM = 471,
STR_VALUE = 472,
SUBUNIT = 473,
SUBUNIT_RELATIONSHIPS = 474,
SUMMATION_OPERATOR = 475,
SURFACE_CLASS = 476,
SURFACE_ONLY = 477,
TAN = 478,
TARGET_ONLY = 479,
TET_ELEMENT_CONNECTIONS = 480,
THROUGHPUT_REPORT = 481,
TIME_LIST = 482,
TIME_POINTS = 483,
TIME_STEP = 484,
TIME_STEP_MAX = 485,
TO = 486,
TOP = 487,
TRAIN_DURATION = 488,
TRAIN_INTERVAL = 489,
TRANSLATE = 490,
TRANSPARENT = 491,
TRIGGER = 492,
TRUE = 493,
UNLIMITED = 494,
USELESS_VOLUME_ORIENTATION = 495,
VACANCY_SEARCH_DISTANCE = 496,
VAR = 497,
VARYING_PROBABILITY_REPORT = 498,
VERTEX_LIST = 499,
VIZ_OUTPUT = 500,
VIZ_OUTPUT_REPORT = 501,
VIZ_VALUE = 502,
VOLUME_DATA_OUTPUT = 503,
VOLUME_OUTPUT_REPORT = 504,
VOLUME_DEPENDENT_RELEASE_NUMBER = 505,
VOLUME_ONLY = 506,
VOXEL_COUNT = 507,
VOXEL_LIST = 508,
VOXEL_SIZE = 509,
WARNING = 510,
WARNINGS = 511,
WORLD = 512,
YES = 513,
UNARYMINUS = 514
};
#endif
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 67 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:355 */
int ival;
int tok;
double dbl;
long long llival;
char *str;
struct sym_entry *sym;
struct vector3 *vec3;
struct num_expr_list_head nlist;
struct release_evaluator *rev;
struct sym_table_list *symlist;
struct output_times *otimes;
/* Reaction output */
struct output_times_inlist ro_otimes;
struct output_column_list ro_cols;
struct output_set *ro_set;
struct output_set_list ro_sets;
struct output_expression *cnt;
/* Viz output */
struct frame_data_list_head frame_list;
/* Region definitions */
struct element_list *elem_list_item;
struct element_list_head elem_list;
struct region *reg;
/* Diffusion constants */
struct diffusion_constant diff_const;
/* Geometry */
struct vertex_list_head vertlist;
struct vertex_list *vertlistitem;
struct element_connection_list_head ecl;
struct element_connection_list *elem_conn;
struct geom_object *obj;
struct object_list obj_list;
struct voxel_object *voxel;
/* Molecule species */
struct mcell_species mol_type;
struct mcell_species_list mol_type_list;
struct mcell_species_spec *mcell_mol_spec;
struct parse_mcell_species_list mcell_species_lst;
struct sm_dat *surf_mol_dat;
struct sm_dat_list surf_mol_dat_list;
struct species_list species_lst;
struct species_list_item *species_lst_item;
/* Reactions */
struct reaction_arrow react_arrow;
struct reaction_rate react_rate;
struct reaction_rates react_rates;
/* Release sites/patterns */
struct release_pattern rpat;
struct release_single_molecule *rsm;
struct release_single_molecule_list rsm_list;
/* printf arguments */
struct arg *printfarg;
struct arg_list printfargs;
#line 503 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:355 */
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
int mdlparse (struct mdlparse_vars *parse_state, yyscan_t scanner);
#endif /* !YY_MDL_HOME_JCZECH_MCELL_BUILD_DEPS_MDLPARSE_H_INCLUDED */
/* Copy the second part of user declarations. */
#line 519 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:358 */
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#else
typedef signed char yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned int
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
# endif
# endif
# ifndef YY_
# define YY_(Msgid) Msgid
# endif
#endif
#ifndef YY_ATTRIBUTE
# if (defined __GNUC__ \
&& (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
|| defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
# else
# define YY_ATTRIBUTE(Spec) /* empty */
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
#endif
#if !defined _Noreturn \
&& (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
# if defined _MSC_VER && 1200 <= _MSC_VER
# define _Noreturn __declspec (noreturn)
# else
# define _Noreturn YY_ATTRIBUTE ((__noreturn__))
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
#else
# define YYUSE(E) /* empty */
#endif
#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
/* Use EXIT_SUCCESS as a witness for stdlib.h. */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's 'empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined EXIT_SUCCESS
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined EXIT_SUCCESS
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss_alloc;
YYSTYPE yyvs_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
# define YYCOPY_NEEDED 1
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (0)
#endif
#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
/* Copy COUNT objects from SRC to DST. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(Dst, Src, Count) \
__builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
# else
# define YYCOPY(Dst, Src, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(Dst)[yyi] = (Src)[yyi]; \
} \
while (0)
# endif
# endif
#endif /* !YYCOPY_NEEDED */
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 150
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 2815
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 280
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 290
/* YYNRULES -- Number of rules. */
#define YYNRULES 624
/* YYNSTATES -- Number of states. */
#define YYNSTATES 1232
/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
by yylex, with out-of-bounds checking. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 514
#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
as returned by yylex, without out-of-bounds checking. */
static const yytype_uint16 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 260, 271,
275, 276, 264, 262, 272, 263, 2, 265, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 261, 270,
278, 259, 277, 2, 279, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 268, 2, 269, 267, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 273, 2, 274, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120, 121, 122, 123, 124,
125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
135, 136, 137, 138, 139, 140, 141, 142, 143, 144,
145, 146, 147, 148, 149, 150, 151, 152, 153, 154,
155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
165, 166, 167, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, 179, 180, 181, 182, 183, 184,
185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
195, 196, 197, 198, 199, 200, 201, 202, 203, 204,
205, 206, 207, 208, 209, 210, 211, 212, 213, 214,
215, 216, 217, 218, 219, 220, 221, 222, 223, 224,
225, 226, 227, 228, 229, 230, 231, 232, 233, 234,
235, 236, 237, 238, 239, 240, 241, 242, 243, 244,
245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
255, 256, 257, 258, 266
};
#if YYDEBUG
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
static const yytype_uint16 yyrline[] =
{
0, 602, 602, 606, 607, 612, 613, 614, 615, 616,
617, 618, 619, 620, 621, 622, 623, 624, 625, 626,
627, 628, 629, 630, 631, 632, 637, 640, 643, 646,
649, 652, 655, 656, 659, 660, 661, 662, 663, 664,
667, 668, 669, 670, 674, 675, 676, 686, 698, 701,
704, 716, 717, 730, 731, 737, 760, 761, 762, 763,
766, 769, 772, 773, 784, 787, 790, 791, 794, 795,
798, 799, 802, 803, 806, 810, 811, 812, 813, 814,
815, 816, 817, 818, 819, 820, 821, 822, 823, 824,
825, 826, 827, 828, 829, 830, 831, 832, 833, 834,
835, 836, 837, 838, 839, 843, 844, 848, 849, 850,
851, 854, 860, 861, 862, 863, 864, 865, 866, 869,
873, 876, 879, 882, 885, 888, 889, 899, 900, 901,
913, 917, 923, 928, 932, 941, 945, 946, 950, 951,
952, 953, 954, 955, 956, 957, 958, 959, 960, 961,
962, 963, 964, 965, 966, 970, 971, 975, 979, 980,
987, 991, 992, 996, 997, 998, 999, 1000, 1001, 1002,
1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012,
1013, 1017, 1018, 1019, 1025, 1026, 1027, 1028, 1029, 1033,
1034, 1035, 1039, 1040, 1041, 1042, 1050, 1051, 1052, 1053,
1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063,
1064, 1065, 1066, 1067, 1074, 1075, 1076, 1077, 1081, 1085,
1086, 1087, 1094, 1095, 1098, 1102, 1106, 1107, 1111, 1120,
1123, 1127, 1128, 1132, 1133, 1142, 1153, 1154, 1158, 1159,
1169, 1170, 1173, 1177, 1181, 1194, 1195, 1200, 1204, 1210,
1211, 1216, 1216, 1221, 1224, 1226, 1231, 1232, 1236, 1239,
1245, 1250, 1251, 1252, 1255, 1256, 1259, 1263, 1267, 1274,
1278, 1287, 1291, 1300, 1307, 1312, 1313, 1316, 1319, 1320,
1323, 1324, 1325, 1328, 1333, 1339, 1340, 1341, 1342, 1345,
1346, 1350, 1355, 1356, 1359, 1363, 1364, 1368, 1371, 1372,
1375, 1376, 1380, 1381, 1384, 1395, 1412, 1413, 1414, 1418,
1419, 1420, 1427, 1434, 1437, 1441, 1448, 1450, 1452, 1454,
1456, 1460, 1461, 1468, 1468, 1479, 1482, 1483, 1484, 1485,
1486, 1495, 1498, 1501, 1504, 1506, 1510, 1514, 1515, 1516,
1521, 1534, 1535, 1538, 1539, 1544, 1543, 1550, 1551, 1556,
1555, 1563, 1564, 1565, 1566, 1567, 1568, 1569, 1570, 1577,
1578, 1579, 1580, 1581, 1586, 1585, 1592, 1593, 1594, 1595,
1596, 1600, 1601, 1604, 1608, 1609, 1610, 1617, 1618, 1619,
1620, 1621, 1622, 1624, 1626, 1630, 1631, 1635, 1636, 1637,
1638, 1643, 1644, 1650, 1657, 1665, 1666, 1670, 1671, 1676,
1679, 1687, 1684, 1702, 1705, 1708, 1709, 1713, 1718, 1719,
1723, 1726, 1728, 1734, 1735, 1739, 1739, 1751, 1752, 1755,
1756, 1757, 1758, 1759, 1760, 1761, 1765, 1766, 1771, 1772,
1773, 1774, 1778, 1783, 1787, 1791, 1792, 1795, 1796, 1797,
1800, 1803, 1804, 1807, 1810, 1811, 1815, 1821, 1822, 1827,
1828, 1827, 1838, 1835, 1848, 1852, 1856, 1860, 1870, 1873,
1867, 1880, 1881, 1877, 1890, 1891, 1895, 1896, 1900, 1901,
1905, 1906, 1909, 1910, 1924, 1930, 1931, 1936, 1937, 1939,
1936, 1948, 1951, 1953, 1958, 1959, 1963, 1970, 1976, 1977,
1982, 1982, 1992, 1991, 2002, 2003, 2014, 2015, 2016, 2019,
2023, 2031, 2038, 2039, 2040, 2054, 2055, 2056, 2060, 2060,
2066, 2067, 2068, 2072, 2076, 2080, 2081, 2090, 2094, 2095,
2096, 2097, 2098, 2099, 2100, 2101, 2102, 2107, 2107, 2109,
2110, 2110, 2114, 2115, 2116, 2117, 2118, 2121, 2124, 2128,
2138, 2139, 2140, 2141, 2142, 2143, 2147, 2152, 2157, 2162,
2167, 2172, 2176, 2177, 2178, 2181, 2182, 2185, 2186, 2187,
2188, 2189, 2190, 2191, 2192, 2195, 2196, 2203, 2203, 2210,
2211, 2215, 2216, 2219, 2220, 2221, 2225, 2226, 2236, 2239,
2243, 2249, 2250, 2265, 2266, 2267, 2271, 2277, 2278, 2282,
2283, 2287, 2289, 2293, 2294, 2298, 2299, 2302, 2308, 2309,
2326, 2331, 2332, 2336, 2342, 2343, 2360, 2364, 2365, 2366,
2373, 2389, 2393, 2394, 2404, 2407, 2425, 2426, 2435, 2439,
2443, 2464, 2465, 2466, 2467
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || 0
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"$end", "error", "$undefined", "ABS", "ABSORPTIVE",
"ACCURATE_3D_REACTIONS", "ACOS", "ALL_CROSSINGS", "ALL_DATA",
"ALL_ELEMENTS", "ALL_ENCLOSED", "ALL_HITS", "ALL_ITERATIONS",
"ALL_MOLECULES", "ALL_NOTIFICATIONS", "ALL_TIMES", "ALL_WARNINGS",
"ASCII", "ASIN", "ASPECT_RATIO", "ATAN", "BACK", "BACK_CROSSINGS",
"BACK_HITS", "BOTTOM", "BOX", "BOX_TRIANGULATION_REPORT", "BRIEF",
"CEIL", "CELLBLENDER", "CENTER_MOLECULES_ON_GRID", "CHECKPOINT_INFILE",
"CHECKPOINT_ITERATIONS", "CHECKPOINT_OUTFILE", "CHECKPOINT_REALTIME",
"CHECKPOINT_REPORT", "CLAMP_CONCENTRATION", "CLOSE_PARTITION_SPACING",
"CONCENTRATION", "CORNERS", "COS", "COUNT", "CUBIC",
"CUBIC_RELEASE_SITE", "CUSTOM_SPACE_STEP", "CUSTOM_TIME_STEP",
"DEFINE_MOLECULE", "DEFINE_MOLECULES", "DEFINE_REACTIONS",
"DEFINE_RELEASE_PATTERN", "DEFINE_SURFACE_CLASS",
"DEFINE_SURFACE_CLASSES", "DEFINE_SURFACE_REGIONS",
"DEGENERATE_POLYGONS", "DELAY", "DENSITY", "DIFFUSION_CONSTANT_2D",
"DIFFUSION_CONSTANT_3D", "DIFFUSION_CONSTANT_REPORT", "DYNAMIC_GEOMETRY",
"DYNAMIC_GEOMETRY_MOLECULE_PLACEMENT", "EFFECTOR_GRID_DENSITY",
"ELEMENT_CONNECTIONS", "ELLIPTIC", "ELLIPTIC_RELEASE_SITE", "EQUAL",
"ERROR", "ESTIMATE_CONCENTRATION", "EXCLUDE_ELEMENTS", "EXCLUDE_PATCH",
"EXCLUDE_REGION", "EXIT", "EXP", "EXPRESSION", "EXTERN", "FALSE",
"FCLOSE", "FILENAME", "FILENAME_PREFIX", "FILE_OUTPUT_REPORT",
"FINAL_SUMMARY", "FLOOR", "FOPEN", "FORMAT", "FPRINTF", "FPRINT_TIME",
"FRONT", "FRONT_CROSSINGS", "FRONT_HITS", "GAUSSIAN_RELEASE_NUMBER",
"GEOMETRY", "GRAPH_PATTERN", "HEADER", "HIGH_PROBABILITY_THRESHOLD",
"HIGH_REACTION_PROBABILITY", "IGNORED", "INCLUDE_ELEMENTS",
"INCLUDE_FILE", "INCLUDE_PATCH", "INCLUDE_REGION", "INPUT_FILE",
"INSTANTIATE", "LLINTEGER", "FULLY_RANDOM", "INTERACTION_RADIUS",
"ITERATION_LIST", "ITERATION_NUMBERS", "ITERATION_REPORT", "ITERATIONS",
"KEEP_CHECKPOINT_FILES", "LEFT", "LIFETIME_THRESHOLD",
"LIFETIME_TOO_SHORT", "LIST", "LOCATION", "LOG", "LOG10", "MAX_TOK",
"MAXIMUM_STEP_LENGTH", "MEAN_DIAMETER", "MEAN_NUMBER",
"MEMORY_PARTITION_X", "MEMORY_PARTITION_Y", "MEMORY_PARTITION_Z",
"MEMORY_PARTITION_POOL", "MICROSCOPIC_REVERSIBILITY", "MIN_TOK",
"MISSED_REACTIONS", "MISSED_REACTION_THRESHOLD",
"MISSING_SURFACE_ORIENTATION", "MOD", "MODE", "MODIFY_SURFACE_REGIONS",
"MOLECULE", "MOLECULE_COLLISION_REPORT", "MOLECULE_DENSITY",
"MOLECULE_NUMBER", "MOLECULE_POSITIONS", "MOLECULES",
"MOLECULE_PLACEMENT_FAILURE", "NAME_LIST", "NEAREST_POINT",
"NEAREST_TRIANGLE", "NEGATIVE_DIFFUSION_CONSTANT",
"NEGATIVE_REACTION_RATE", "NO", "NOEXIT", "NONE", "NO_SPECIES",
"NOT_EQUAL", "NOTIFICATIONS", "NUMBER_OF_SUBUNITS", "NUMBER_OF_TRAINS",
"NUMBER_TO_RELEASE", "OBJECT", "OFF", "ON", "ORIENTATIONS",
"OUTPUT_BUFFER_SIZE", "INVALID_OUTPUT_STEP_TIME",
"LARGE_MOLECULAR_DISPLACEMENT", "ADD_REMOVE_MESH",
"OVERWRITTEN_OUTPUT_FILE", "PARTITION_LOCATION_REPORT", "PARTITION_X",
"PARTITION_Y", "PARTITION_Z", "PERIODIC_BOX", "PERIODIC_X", "PERIODIC_Y",
"PERIODIC_Z", "PERIODIC_TRADITIONAL", "PI_TOK", "POLYGON_LIST",
"POSITIONS", "PRINTF", "PRINT_TIME", "PROBABILITY_REPORT",
"PROBABILITY_REPORT_THRESHOLD", "PROGRESS_REPORT", "RADIAL_DIRECTIONS",
"RADIAL_SUBDIVISIONS", "RAND_GAUSSIAN", "RAND_UNIFORM",
"REACTION_DATA_OUTPUT", "REACTION_OUTPUT_REPORT", "REAL",
"RECTANGULAR_RELEASE_SITE", "RECTANGULAR_TOKEN", "REFLECTIVE",
"RELEASE_EVENT_REPORT", "RELEASE_INTERVAL", "RELEASE_PATTERN",
"RELEASE_PROBABILITY", "RELEASE_SITE", "REMOVE_ELEMENTS", "RIGHT",
"ROTATE", "ROUND_OFF", "SCALE", "SEED", "SHAPE", "SHOW_EXACT_TIME",
"SIN", "SITE_DIAMETER", "SITE_RADIUS", "SPACE_STEP", "SPHERICAL",
"SPHERICAL_RELEASE_SITE", "SPHERICAL_SHELL", "SPHERICAL_SHELL_SITE",
"SPRINTF", "SQRT", "STANDARD_DEVIATION", "PERIODIC_BOX_INITIAL", "STEP",
"STRING_TO_NUM", "STR_VALUE", "SUBUNIT", "SUBUNIT_RELATIONSHIPS",
"SUMMATION_OPERATOR", "SURFACE_CLASS", "SURFACE_ONLY", "TAN",
"TARGET_ONLY", "TET_ELEMENT_CONNECTIONS", "THROUGHPUT_REPORT",
"TIME_LIST", "TIME_POINTS", "TIME_STEP", "TIME_STEP_MAX", "TO", "TOP",
"TRAIN_DURATION", "TRAIN_INTERVAL", "TRANSLATE", "TRANSPARENT",
"TRIGGER", "TRUE", "UNLIMITED", "USELESS_VOLUME_ORIENTATION",
"VACANCY_SEARCH_DISTANCE", "VAR", "VARYING_PROBABILITY_REPORT",
"VERTEX_LIST", "VIZ_OUTPUT", "VIZ_OUTPUT_REPORT", "VIZ_VALUE",
"VOLUME_DATA_OUTPUT", "VOLUME_OUTPUT_REPORT",
"VOLUME_DEPENDENT_RELEASE_NUMBER", "VOLUME_ONLY", "VOXEL_COUNT",
"VOXEL_LIST", "VOXEL_SIZE", "WARNING", "WARNINGS", "WORLD", "YES", "'='",
"'&'", "':'", "'+'", "'-'", "'*'", "'/'", "UNARYMINUS", "'^'", "'['",
"']'", "';'", "'\\''", "','", "'{'", "'}'", "'('", "')'", "'>'", "'<'",
"'@'", "$accept", "mdl_format", "mdl_stmt_list", "mdl_stmt", "str_value",
"var", "file_name", "existing_object", "existing_region", "point",
"point_or_num", "boolean", "orientation_class", "list_orient_marks",
"head_mark", "tail_mark", "orient_class_number", "list_range_specs",
"range_spec", "include_stmt", "assignment_stmt", "assign_var",
"existing_var_only", "array_value", "array_expr_only", "existing_array",
"num_expr", "num_value", "intOrReal", "num_expr_only",
"existing_num_var", "arith_expr", "str_expr", "str_expr_only",
"existing_str_var", "io_stmt", "fopen_stmt", "new_file_stream",
"file_mode", "fclose_stmt", "existing_file_stream", "format_string",
"list_args", "list_arg", "printf_stmt", "fprintf_stmt", "sprintf_stmt",
"print_time_stmt", "fprint_time_stmt", "notification_def",
"notification_list", "notification_item_def", "notify_bilevel",
"notify_level", "warnings_def", "warning_list", "warning_item_def",
"warning_level", "chkpt_stmt", "exit_or_no", "time_expr",
"parameter_def", "memory_partition_def", "partition_def",
"partition_dimension", "molecules_def", "define_one_molecule",
"define_multiple_molecules", "list_molecule_stmts", "molecule_stmt",
"molecule_name", "new_molecule", "diffusion_def", "mol_timestep_def",
"target_def", "maximum_step_length_def", "extern_def",
"existing_molecule", "existing_surface_molecule",
"existing_molecule_opt_orient", "surface_classes_def",
"define_one_surface_class", "define_multiple_surface_classes",
"list_surface_class_stmts", "surface_class_stmt", "$@1",
"existing_surface_class", "list_surface_prop_stmts", "surface_prop_stmt",
"surface_rxn_stmt", "surface_rxn_type", "equals_or_to",
"surface_class_mol_stmt", "surface_mol_stmt", "list_surface_mol_density",
"list_surface_mol_num", "surface_mol_quant", "rx_net_def",
"list_rx_stmts", "rx_stmt", "list_dashes", "right_arrow", "left_arrow",
"double_arrow", "right_cat_arrow", "double_cat_arrow", "reaction_arrow",
"new_rxn_pathname", "rxn", "reactant_list", "reactant",
"opt_reactant_surface_class", "reactant_surface_class", "product_list",
"product", "rx_rate_syntax", "rx_rate1", "rx_rate2", "rx_dir_rate",
"atomic_rate", "release_pattern_def", "new_release_pattern",
"existing_release_pattern_xor_rxpn", "list_req_release_pattern_cmds",
"train_count", "instance_def", "$@2", "physical_object_def",
"object_def", "new_object", "start_object", "end_object",
"list_opt_object_cmds", "opt_object_cmd", "transformation",
"meta_object_def", "list_objects", "object_ref", "existing_object_ref",
"$@3", "release_site_def", "release_site_def_new", "$@4",
"release_site_geom", "release_region_expr", "release_site_def_old",
"$@5", "release_site_geom_old", "list_release_site_cmds",
"existing_num_or_array", "release_site_cmd", "site_size_cmd",
"release_number_cmd", "constant_release_number_cmd",
"gaussian_release_number_cmd", "volume_dependent_number_cmd",
"concentration_dependent_release_cmd", "molecule_release_pos_list",
"molecule_release_pos", "new_object_name", "polygon_list_def", "@6",
"vertex_list_cmd", "single_vertex", "list_points",
"element_connection_cmd", "list_element_connections",
"element_connection", "list_opt_polygon_object_cmds",
"opt_polygon_object_cmd", "remove_side", "$@7",
"remove_element_specifier_list", "side_name", "element_specifier_list",
"element_specifier", "incl_element_list_stmt", "excl_element_list_stmt",
"just_an_element_list", "list_element_specs", "element_spec",
"prev_region_stmt", "prev_region_type", "patch_statement", "patch_type",
"in_obj_define_surface_regions", "list_in_obj_surface_region_defs",
"in_obj_surface_region_def", "$@8", "$@9", "voxel_list_def", "$@10",
"tet_element_connection_cmd", "element_connection_tet",
"list_tet_arrays", "periodic_box_def", "$@11", "$@12", "box_def", "$@13",
"$@14", "periodic_x_def", "periodic_y_def", "periodic_z_def",
"periodic_traditional", "opt_aspect_ratio_def",
"existing_obj_define_surface_regions",
"list_existing_obj_surface_region_defs",
"existing_obj_surface_region_def", "$@15", "$@16", "$@17", "new_region",
"list_opt_surface_region_stmts", "opt_surface_region_stmt",
"set_surface_class_stmt", "mod_surface_regions",
"list_existing_surface_region_refs", "existing_surface_region_ref",
"$@18", "output_def", "$@19", "output_buffer_size_def",
"output_timer_def", "step_time_def", "iteration_time_def",
"real_time_def", "list_count_cmds", "count_cmd", "count_stmt", "$@20",
"custom_header_value", "custom_header", "exact_time_toggle",
"list_count_exprs", "single_count_expr", "count_expr", "count_value",
"$@21", "$@22", "file_arrow", "outfile_syntax",
"existing_rxpn_or_molecule", "existing_molecule_required_orient_braces",
"count_syntax", "count_syntax_1", "count_syntax_2", "count_syntax_3",
"count_syntax_periodic_1", "count_syntax_periodic_2",
"count_syntax_periodic_3", "count_location_specifier", "opt_hit_spec",
"hit_spec", "opt_custom_header", "viz_output_def", "$@23",
"list_viz_output_cmds", "viz_output_maybe_mode_cmd", "viz_mode_def",
"viz_output_cmd", "viz_frames_def", "viz_filename_prefix_def",
"viz_molecules_block_def", "list_viz_molecules_block_cmds",
"viz_molecules_block_cmd", "viz_molecules_name_list_cmd",
"optional_state", "viz_include_mols_cmd_list", "viz_include_mols_cmd",
"existing_one_or_multiple_molecules", "viz_time_spec",
"viz_molecules_time_points_def", "viz_molecules_time_points_cmds",
"viz_molecules_time_points_one_cmd", "viz_iteration_spec",
"viz_molecules_iteration_numbers_def",
"viz_molecules_iteration_numbers_cmds",
"viz_molecules_iteration_numbers_one_cmd", "viz_molecules_one_item",
"volume_output_def", "volume_output_filename_prefix",
"volume_output_molecule_list", "volume_output_molecule_decl",
"volume_output_molecule", "volume_output_molecules",
"volume_output_location", "volume_output_voxel_size",
"volume_output_voxel_count", "volume_output_times_def", YY_NULLPTR
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[NUM] -- (External) token number corresponding to the
(internal) symbol number NUM (which must be that of a token). */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
275, 276, 277, 278, 279, 280, 281, 282, 283, 284,
285, 286, 287, 288, 289, 290, 291, 292, 293, 294,
295, 296, 297, 298, 299, 300, 301, 302, 303, 304,
305, 306, 307, 308, 309, 310, 311, 312, 313, 314,
315, 316, 317, 318, 319, 320, 321, 322, 323, 324,
325, 326, 327, 328, 329, 330, 331, 332, 333, 334,
335, 336, 337, 338, 339, 340, 341, 342, 343, 344,
345, 346, 347, 348, 349, 350, 351, 352, 353, 354,
355, 356, 357, 358, 359, 360, 361, 362, 363, 364,
365, 366, 367, 368, 369, 370, 371, 372, 373, 374,
375, 376, 377, 378, 379, 380, 381, 382, 383, 384,
385, 386, 387, 388, 389, 390, 391, 392, 393, 394,
395, 396, 397, 398, 399, 400, 401, 402, 403, 404,
405, 406, 407, 408, 409, 410, 411, 412, 413, 414,
415, 416, 417, 418, 419, 420, 421, 422, 423, 424,
425, 426, 427, 428, 429, 430, 431, 432, 433, 434,
435, 436, 437, 438, 439, 440, 441, 442, 443, 444,
445, 446, 447, 448, 449, 450, 451, 452, 453, 454,
455, 456, 457, 458, 459, 460, 461, 462, 463, 464,
465, 466, 467, 468, 469, 470, 471, 472, 473, 474,
475, 476, 477, 478, 479, 480, 481, 482, 483, 484,
485, 486, 487, 488, 489, 490, 491, 492, 493, 494,
495, 496, 497, 498, 499, 500, 501, 502, 503, 504,
505, 506, 507, 508, 509, 510, 511, 512, 513, 61,
38, 58, 43, 45, 42, 47, 514, 94, 91, 93,
59, 39, 44, 123, 125, 40, 41, 62, 60, 64
};
# endif
#define YYPACT_NINF -1031
#define yypact_value_is_default(Yystate) \
(!!((Yystate) == (-1031)))
#define YYTABLE_NINF -401
#define yytable_value_is_error(Yytable_value) \
0
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
static const yytype_int16 yypact[] =
{
2559, -175, -162, -93, -41, -17, -6, -114, -138, 82,
-114, -114, 115, 135, 15, 178, 200, 177, 224, 228,
246, -1031, 251, 254, 262, 274, 281, 288, 291, 300,
282, 287, -1031, -1031, -1031, 292, 244, 279, 308, 310,
301, 323, 309, 326, 327, 329, -1031, 316, 319, 322,
596, 2559, -1031, -42, -1031, -1031, 339, -1031, -1031, 517,
-1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031,
-1031, -1031, 342, -1031, -1031, -1031, -1031, -1031, -1031, -1031,
-1031, -1031, -1031, -1031, 165, -1031, -1031, -1031, -1031, 431,
-1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, 144,
144, -29, 2430, -29, 2430, -1031, -1031, 341, -114, -114,
-1031, 355, -1031, 358, -1031, -114, -114, -29, -51, 2430,
-114, -114, -114, -29, -114, 2430, 2430, 144, 2430, 2430,
2430, 2430, 397, -114, 980, -1031, 576, -29, -29, 2029,
2430, 458, 2430, -114, 2430, 2430, 2430, -1031, 555, 685,
-1031, -1031, 1873, 361, 104, 292, -1031, -1031, 292, -1031,
292, -1031, -1031, 292, 292, 292, -1031, -1031, -1031, -1031,
-1031, -1031, -1031, -1031, 362, -1031, -1031, -1031, -1031, -1031,
383, -1031, -1031, 369, 370, 374, 378, 379, 385, 387,
389, -1031, 390, 391, 398, 399, 401, -1031, -1031, -1031,
-1031, 402, -1031, 410, 412, 413, 415, 2430, 2430, 2430,
-1031, -19, -1031, -1031, -1031, -1031, -1031, 1006, 4, 142,
-179, -1031, -1031, 350, -1031, -172, -1031, -1031, -116, -1031,
-1031, -1031, -71, -1031, -1031, -1031, 22, -1031, 383, 409,
-1031, -1031, 528, -1031, 396, 420, 423, 383, -1031, 543,
-1031, 528, 528, -1031, 528, 528, 528, 528, -1031, -1031,
-1031, 432, 426, 46, -1031, 443, 444, 448, 450, 451,
455, 456, 459, 462, 465, 468, 469, 470, 473, 475,
477, 478, 481, 351, -1031, 482, 383, -1031, 441, -1031,
528, 528, 485, -1031, 528, -1031, 479, 528, 528, 528,
624, 504, 627, 508, 521, 522, 523, 539, 542, 546,
548, 550, 552, 559, 560, 567, 568, 572, 584, 590,
599, 881, -1031, 2144, 638, -1031, -1031, 528, 764, -1031,
841, 409, -29, -1031, -1031, -1031, -1031, 719, -114, -1031,
532, -1031, 532, -29, -29, 2430, 2430, 2430, 2430, 2430,
2430, 2430, 2430, 2430, 2430, 2430, 2430, 2430, 2430, 2430,
2430, -29, 2430, 589, 589, 394, -1031, -1031, 2430, 2430,
2430, 2430, 2430, -1031, 2430, -1031, 604, 608, 289, -1031,
-1031, -1031, -1031, -1031, 2430, -1031, 108, -1031, -1031, -1031,
-1031, -1031, -114, -114, -137, 1, -1031, -1031, -1031, 549,
-1031, -1031, -1031, -29, -29, -114, -1031, -1031, -1031, 144,
144, 144, 39, 144, 144, 1680, 144, 144, 144, 2430,
144, 39, 144, 144, 144, 39, 39, -1031, -1031, 104,
-25, -1031, 2430, -13, -29, 609, 17, -1031, -29, 611,
-32, -1031, -31, -31, -31, 2430, -31, 2430, -31, -31,
2430, -31, -31, -31, -31, -31, -31, -31, -31, -31,
-1031, -1031, 2430, 102, -1031, 528, 603, 612, 713, -1031,
296, -114, -1031, -1031, 687, 616, 666, 538, 833, -1031,
-1031, 417, 588, 614, 620, 665, 684, 805, 831, 848,
872, 1102, 1108, 1114, 1135, 977, 984, -183, 999, -1031,
260, 260, 589, 589, -1031, 1153, 2430, 2430, 648, 649,
696, 811, -1031, -1031, -1031, -1031, 350, -1031, -1031, 668,
-159, -1031, -164, -1031, -1031, -1031, -81, 677, 678, 679,
680, 686, -1031, 37, -114, -1031, 657, 681, -1031, -1031,
-1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, 528, -1031,
-1031, -1031, -1031, 528, -1031, -1031, -1031, -1031, -1031, -1031,
-1031, 671, -1031, 1911, -1031, 528, 697, 698, 699, -24,
-1031, -1031, -1031, -1031, 28, 703, 682, -33, -1031, -1031,
-1031, -1031, 383, -114, 704, -1031, 710, -1031, -1031, -1031,
-1031, -1031, -1031, 528, -1031, 528, -1031, -1031, 528, -1031,
-1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, 558, -1031,
2144, -29, 104, 18, 152, -1031, 708, 538, 104, 700,
-1031, 717, 718, 715, 722, 724, 730, 729, 731, 732,
736, -1031, -1031, 745, 738, 538, -1031, 746, -1031, -1031,
-1031, -1031, -1031, 740, -1031, 204, -1031, -1031, -1031, -1031,
-1031, -1031, -1031, -1031, -1031, -1031, 2430, 2430, 2430, 2430,
-1031, -1031, -1031, -1031, 2430, 528, 528, 2430, 2430, -1031,
854, -1031, -1031, 751, -1031, -1031, 668, -1031, 668, -1031,
-1031, -181, -1031, 2430, 2182, 2430, 2430, 2430, -1031, -114,
743, 748, -1031, -1031, -1031, -1031, -1031, 86, -1031, -1031,
-1031, 749, 215, -1031, -1031, -47, 104, -1031, -1031, 409,
-1031, 104, 2430, 104, 763, 771, -1031, 67, -1031, -1031,
-1031, -1031, 220, -1031, -1031, -1031, -29, -21, -1031, -1031,
-1031, -1031, 761, 104, 775, 785, 2430, -1031, 383, 768,
767, 292, 786, 787, 791, -1031, -1031, -1031, -1031, -3,
538, -1031, -1031, -63, 104, -1031, 2430, 2430, 931, -29,
104, -114, -114, 2430, -114, 2430, 104, 933, 152, -1031,
2300, 104, -1031, -1031, 1052, 1067, 1086, 1092, 1167, 528,
528, 799, 987, -23, -1031, -1031, -81, 295, 801, -1031,
-1031, 528, -1031, 528, -1031, 528, 528, 528, 807, -114,
-114, -1031, -1031, 16, -1031, -1031, 818, -1031, -1031, -1031,
-1031, 893, -1031, 528, -1031, 306, 144, -4, -1031, -1031,
-1031, 383, 806, 809, 810, -64, -1031, -1031, -1031, -1031,
-114, -1031, 2300, 825, 55, 483, -1031, 104, -1031, 104,
2300, 104, -1031, -1031, -1031, -1031, -1031, -1031, -168, 432,
-1031, 202, 152, -1031, -1031, -1031, -1031, -46, 152, 528,
528, 827, 383, -1031, -1031, 104, 68, -1031, 528, -1031,
-1031, 528, -1031, 830, -1031, 1173, -1031, -1031, -1031, -1031,
50, -1031, -14, -1031, -1031, -1031, -1031, 2430, 2430, -1031,
816, -1031, 1911, 1911, -1031, -1031, 409, 163, -1031, -114,
-1031, 2430, 350, 832, 80, -1031, 154, -1031, 350, -1031,
824, -114, 850, -1031, -1031, -1031, 383, -1031, -1031, -1031,
851, 863, -1031, -4, -4, -1031, 21, -1031, 889, -1031,
26, -1031, 26, -1031, -1031, -1031, 1173, -1031, -1031, -1031,
2300, 857, 883, 901, 826, 2430, 1080, -1031, 868, -1031,
-1031, 193, -168, -168, -168, -1031, -1031, -1031, -1031, 2430,
-1031, -1031, -1031, 2430, -1031, -1031, 888, 895, 201, -1031,
-1031, -1031, 528, 528, -1031, -1031, -1031, -1031, 295, -1031,
528, -1031, 2430, -1031, -1031, -1031, -1031, -1031, 447, -1031,
144, 973, 894, 2430, -4, 907, -1031, 184, -4, 91,
-29, -4, -4, -4, -4, -1031, -1031, -1031, -1031, 12,
-1031, 890, 20, 13, -1031, 898, -1031, 104, 2430, 104,
-1031, 734, 919, -1031, 152, 2430, -1031, 915, 915, -1031,
343, 510, -114, -1031, -1031, 911, 528, 922, -1031, -1031,
925, -1031, -1031, 447, -1031, -1031, -1031, -1031, 942, -1031,
945, -1031, 956, 1048, 95, 1030, 597, 95, -1031, -1031,
941, 943, 944, -29, 383, 151, 151, -1031, -1031, -1031,
-1031, 10, 963, -1031, -1031, -1031, -1031, 963, -1031, -1031,
8, -1031, 528, -1031, -1031, 2430, -1031, -1031, 528, 966,
-1031, 968, 171, -1031, 959, 1210, -1031, 965, 967, -1031,
-1031, -114, 104, 144, 978, 1066, 971, 972, 982, 985,
983, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, 989,
-1031, -1031, 979, -1031, -1031, -1031, -1031, -1031, 2430, -1031,
-1031, -1031, -1031, -1031, 528, -14, 2430, 2430, -1031, -1031,
-1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, 571, 991,
-1031, 447, -1031, 1002, -1031, 1462, 1462, 145, -1031, 1004,
-1031, 144, 1018, -1031, 157, -1031, 157, 157, -1031, -1031,
-1031, 528, -1031, 882, 41, 447, 2430, -1031, 1462, 210,
225, -1031, 104, -1031, 144, 1007, -1031, 432, -1031, 1011,
1012, 1014, 152, -1031, 1029, 447, 528, -1031, -1031, -1031,
-1031, -1031, -1031, 89, -1031, 89, -1031, 89, -1031, -1031,
2430, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031,
1017, -1031, 1017, 1017, 909, 212, 580, -1031, -1031, -1031,
-1031, -1031
};
/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE does not specify something else to do. Zero
means the default is an error. */
static const yytype_uint16 yydefact[] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 323, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 219, 220, 221, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 27, 0, 0, 0,
0, 2, 3, 331, 5, 6, 0, 7, 112, 0,
113, 114, 115, 116, 117, 118, 8, 9, 10, 11,
14, 12, 0, 15, 222, 223, 16, 245, 246, 17,
18, 20, 19, 325, 0, 326, 327, 348, 347, 0,
329, 330, 13, 328, 21, 22, 23, 24, 25, 0,
0, 0, 0, 0, 0, 229, 224, 0, 0, 0,
313, 0, 230, 0, 247, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 332, 0, 0, 0, 0,
0, 494, 0, 0, 0, 0, 0, 567, 0, 0,
1, 4, 0, 0, 0, 0, 367, 368, 0, 369,
0, 366, 370, 0, 0, 0, 35, 37, 39, 38,
34, 36, 201, 200, 0, 108, 26, 107, 111, 184,
28, 105, 106, 0, 0, 0, 0, 0, 0, 0,
0, 70, 0, 0, 0, 0, 0, 93, 95, 94,
71, 0, 96, 0, 0, 0, 0, 0, 0, 0,
74, 189, 66, 68, 69, 67, 185, 192, 189, 0,
0, 226, 242, 40, 294, 0, 275, 277, 295, 292,
315, 251, 0, 249, 29, 477, 0, 475, 0, 211,
212, 213, 206, 123, 0, 0, 0, 55, 331, 0,
324, 207, 199, 187, 214, 215, 216, 217, 209, 210,
208, 0, 0, 0, 488, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 136, 0, 124, 125, 0, 204,
203, 205, 0, 492, 197, 60, 0, 196, 198, 202,
571, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 161, 0, 61, 58, 59, 0, 72, 56,
73, 57, 0, 65, 218, 62, 63, 0, 0, 349,
0, 364, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 104, 103, 0, 191, 190, 0, 0,
0, 0, 0, 186, 0, 188, 0, 0, 233, 225,
227, 43, 48, 49, 0, 244, 41, 44, 45, 42,
274, 276, 0, 0, 0, 0, 254, 248, 250, 0,
474, 476, 122, 0, 0, 0, 490, 487, 489, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 135, 137, 0,
0, 133, 0, 0, 0, 0, 0, 572, 0, 0,
0, 612, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
160, 162, 0, 0, 51, 53, 0, 0, 331, 344,
0, 334, 341, 343, 0, 0, 0, 0, 0, 125,
109, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 75,
98, 99, 100, 101, 102, 193, 0, 0, 0, 0,
236, 0, 46, 47, 293, 253, 40, 296, 278, 0,
0, 285, 0, 287, 286, 288, 0, 0, 0, 0,
0, 0, 312, 0, 0, 125, 0, 0, 482, 157,
138, 145, 153, 159, 158, 140, 147, 148, 155, 154,
156, 144, 141, 143, 139, 150, 146, 149, 142, 152,
151, 0, 31, 0, 130, 495, 0, 0, 0, 502,
496, 497, 498, 125, 0, 0, 0, 0, 569, 577,
576, 578, 611, 0, 0, 613, 0, 183, 181, 182,
163, 168, 169, 167, 166, 172, 171, 173, 174, 175,
177, 164, 165, 178, 179, 180, 170, 176, 0, 64,
0, 0, 0, 0, 0, 342, 0, 0, 0, 0,
452, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 385, 386, 0, 0, 334, 371, 0, 376, 387,
388, 389, 390, 0, 401, 0, 91, 88, 87, 89,
83, 85, 76, 82, 77, 78, 0, 0, 0, 0,
84, 90, 97, 86, 0, 232, 231, 0, 0, 237,
238, 50, 297, 281, 279, 280, 0, 282, 0, 300,
301, 0, 298, 0, 0, 0, 0, 0, 263, 0,
0, 0, 261, 262, 252, 255, 256, 0, 257, 266,
481, 0, 0, 134, 30, 0, 0, 129, 127, 128,
126, 0, 0, 0, 0, 0, 508, 0, 503, 505,
506, 507, 0, 574, 575, 573, 0, 0, 568, 570,
615, 616, 614, 0, 0, 0, 0, 52, 121, 0,
0, 0, 0, 0, 0, 333, 340, 335, 336, 0,
334, 404, 405, 0, 0, 334, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 372,
0, 0, 411, 110, 0, 0, 0, 0, 194, 235,
234, 0, 240, 0, 283, 284, 0, 0, 289, 302,
303, 316, 322, 321, 320, 317, 319, 318, 0, 0,
0, 265, 264, 0, 478, 131, 0, 491, 485, 483,
484, 470, 500, 499, 501, 0, 0, 0, 493, 504,
132, 579, 0, 0, 0, 0, 581, 583, 584, 585,
0, 618, 0, 0, 621, 0, 119, 0, 345, 0,
0, 0, 354, 355, 358, 356, 353, 357, 0, 352,
359, 351, 0, 403, 406, 455, 456, 0, 0, 395,
396, 0, 384, 374, 375, 0, 0, 397, 391, 314,
382, 381, 380, 0, 365, 373, 378, 377, 379, 410,
0, 408, 334, 79, 80, 92, 81, 0, 0, 241,
0, 299, 0, 0, 311, 309, 310, 0, 306, 0,
291, 0, 40, 0, 0, 269, 0, 271, 40, 258,
0, 0, 0, 458, 510, 511, 512, 513, 514, 527,
0, 0, 530, 0, 0, 518, 0, 515, 565, 519,
0, 590, 0, 580, 582, 617, 65, 32, 619, 33,
0, 0, 0, 0, 0, 0, 472, 334, 0, 338,
337, 0, 0, 0, 0, 350, 454, 457, 453, 0,
399, 383, 398, 0, 407, 409, 0, 0, 0, 412,
413, 414, 195, 239, 228, 307, 308, 304, 0, 290,
260, 243, 0, 267, 270, 268, 272, 259, 0, 486,
0, 464, 0, 0, 0, 0, 525, 0, 0, 0,
0, 0, 0, 0, 0, 517, 607, 609, 608, 0,
604, 0, 0, 0, 598, 0, 620, 0, 0, 0,
610, 0, 0, 461, 0, 0, 360, 361, 362, 363,
0, 0, 0, 415, 402, 0, 273, 0, 445, 442,
0, 444, 441, 479, 426, 428, 429, 430, 0, 431,
0, 471, 0, 466, 0, 0, 0, 0, 520, 516,
0, 0, 532, 0, 566, 521, 522, 523, 524, 603,
605, 0, 588, 586, 594, 593, 589, 588, 597, 599,
0, 623, 622, 624, 54, 0, 411, 346, 339, 0,
392, 0, 0, 447, 0, 0, 305, 0, 0, 427,
482, 0, 0, 0, 0, 468, 0, 538, 0, 0,
0, 540, 541, 542, 543, 544, 545, 529, 526, 0,
533, 536, 534, 537, 509, 601, 602, 606, 0, 592,
591, 595, 596, 600, 473, 462, 0, 0, 446, 448,
449, 425, 422, 420, 421, 423, 424, 419, 437, 0,
439, 417, 418, 434, 435, 0, 0, 0, 440, 0,
465, 0, 0, 459, 0, 539, 0, 0, 528, 531,
535, 587, 334, 0, 0, 0, 0, 416, 0, 0,
0, 480, 0, 467, 0, 0, 552, 554, 553, 555,
555, 555, 0, 393, 0, 450, 438, 436, 433, 432,
443, 469, 460, 0, 548, 0, 546, 0, 547, 463,
0, 482, 562, 564, 559, 561, 558, 563, 560, 557,
555, 556, 555, 555, 0, 0, 0, 551, 549, 550,
394, 451
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int16 yypgoto[] =
{
-1031, -1031, -1031, 1247, -845, 0, -102, -111, -131, -397,
-782, -96, -501, -1031, 914, 917, 194, -1031, 694, -1031,
-1031, 1162, -139, -145, -140, -1031, 840, -423, -136, -146,
-1031, -124, -76, -109, -1031, -1031, -1031, -1031, -1031, -1031,
352, -120, -393, -1031, -1031, -1031, -1031, -1031, -1031, -1031,
-1031, 1024, 499, 63, -1031, -1031, 990, 674, -1031, 1095,
-1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -58,
-1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -496,
-1031, -1031, -1031, -1031, -67, -1031, 407, -1031, -1031, -1031,
-1031, -1031, -1031, 777, -1031, -1031, -649, -1031, -1031, 1096,
-322, -235, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031,
930, -1031, -1031, -1031, 537, -1031, -1031, -1031, 346, -384,
-1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, -282, -107,
-16, -722, -621, -1031, -1031, 1209, -1031, 864, -1031, -1031,
-1031, -1031, -1031, -1031, -569, -1031, -1031, -1031, 720, -1031,
-582, -1031, -1031, -1031, -1031, -1031, -1031, -1031, 472, -1031,
-1031, -1031, 997, 591, -1031, -1031, -1031, 461, 256, -1031,
-1031, -1031, -1031, -1031, -1030, -994, -1031, -1031, -1031, -624,
167, -1031, -1031, -1031, -1031, -1031, -1031, 266, -1031, -1031,
-1031, -1031, -1031, 495, -1031, -1031, -1031, -1031, -1031, -1031,
-1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, 1124, -1031,
-1031, -1031, 829, -1020, -1031, -1031, -1031, -1031, 1098, -1031,
-1031, -1031, -1031, -1031, -1031, -1031, -1031, -1031, 667, -1031,
-1031, -1031, -1031, -1031, -1031, 392, -362, -1031, -1031, -1031,
-1031, -1031, -1031, -1031, 328, -1031, -1031, -1031, -1031, -1031,
-1031, -628, -800, -1031, -1031, -1031, -1031, -1031, -1031, -1031,
812, -1031, -1031, -1031, -1031, 562, -1031, 311, -1031, -1031,
-1031, -1031, -1031, -1031, 381, -1031, -1031, -1031, 382, -873,
-1031, -1031, -1031, 955, 553, -1031, -1031, -1031, -1031, -1031
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int16 yydefgoto[] =
{
-1, 50, 51, 52, 177, 210, 179, 261, 850, 937,
938, 539, 385, 386, 387, 388, 389, 463, 464, 54,
55, 56, 894, 562, 335, 336, 327, 212, 213, 895,
214, 215, 238, 181, 182, 57, 58, 59, 739, 60,
244, 287, 430, 710, 61, 62, 63, 64, 65, 66,
283, 284, 540, 545, 67, 321, 322, 590, 68, 373,
218, 69, 70, 71, 72, 73, 74, 75, 220, 106,
107, 113, 378, 510, 670, 782, 890, 223, 903, 224,
76, 77, 78, 232, 114, 396, 516, 533, 695, 696,
697, 803, 698, 808, 904, 906, 905, 79, 225, 226,
783, 521, 522, 523, 524, 525, 526, 900, 227, 228,
229, 394, 517, 681, 682, 788, 789, 790, 897, 898,
80, 111, 870, 395, 794, 81, 124, 82, 83, 84,
338, 746, 614, 747, 748, 85, 471, 472, 473, 947,
86, 87, 474, 617, 851, 88, 477, 164, 635, 878,
636, 637, 638, 639, 640, 641, 642, 866, 867, 89,
90, 772, 476, 752, 753, 644, 880, 881, 882, 969,
970, 1095, 1149, 1150, 1043, 1044, 1045, 1046, 1152, 1153,
1154, 1047, 1048, 1049, 1050, 971, 1092, 1093, 1175, 1211,
91, 755, 620, 856, 857, 92, 991, 1185, 93, 1086,
1172, 1053, 1105, 1163, 913, 1023, 94, 236, 237, 399,
910, 1100, 1094, 705, 809, 810, 95, 263, 264, 538,
96, 433, 293, 569, 570, 571, 572, 717, 718, 719,
817, 917, 720, 721, 926, 927, 928, 929, 992, 995,
1063, 1124, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115,
1116, 1189, 1204, 1221, 1005, 97, 300, 577, 436, 437,
578, 579, 580, 581, 825, 826, 827, 1129, 1012, 1076,
1077, 1133, 828, 1013, 1014, 1127, 829, 1009, 1010, 1011,
98, 302, 440, 441, 731, 732, 586, 735, 834, 944
};
/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule whose
number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_int16 yytable[] =
{
53, 216, 262, 172, 173, 235, 329, 105, 239, 334,
110, 112, 326, 325, 768, 672, 328, 249, 288, 136,
1006, 1006, 1125, 1131, 676, 180, 678, 180, 330, 908,
680, 253, 561, 1072, 1006, 587, 260, 919, 966, 842,
-120, 688, 822, 331, 575, 723, 874, 247, 233, 1099,
221, 53, 366, 769, 174, 527, 469, 724, 949, 1015,
843, 286, 286, 46, 588, 1151, 543, 679, 714, 920,
46, 175, 520, 689, 46, 366, 823, 344, 46, 1194,
1157, 786, 584, 46, 99, 822, 645, 787, 690, 691,
240, 241, 566, 662, 575, 379, 1212, 100, 191, 1213,
1214, 178, 390, 178, 674, 576, 439, 848, 105, 222,
844, 1215, 1216, 677, 166, 112, 234, 178, 675, 823,
243, 243, 243, 178, 248, 235, 518, 367, 46, 852,
955, -400, 262, 234, 858, 108, 958, 178, 178, 337,
1015, 519, 702, 295, 339, 1195, 392, 340, 341, 342,
367, 907, 324, 528, 333, 576, 1217, 1099, 1016, 714,
941, 46, 380, 393, 824, 398, 101, 1074, 769, 1007,
1007, 46, 690, 691, 806, 725, 1218, 1219, 715, 46,
722, 967, 200, 1007, 167, 845, 1008, 1008, 176, 469,
155, 1225, 529, 798, 168, 169, 46, 673, 376, 377,
1008, 1099, 567, 397, 846, 323, 847, 824, 156, 1106,
933, 853, 1106, 46, 568, 740, 921, -60, 102, 166,
105, 751, 323, 479, 589, 222, 692, 807, 956, 157,
466, 470, 112, 922, 530, 531, 234, 176, 46, 46,
674, 728, 103, 368, 369, 370, 371, 563, 372, 716,
46, 564, 46, 104, 675, 984, 180, 986, 46, 923,
46, 968, 46, 234, 46, 864, 865, 286, 480, 715,
942, 924, 848, 693, 117, 532, 323, 170, 323, 951,
690, 691, 943, 535, 536, 497, 1069, 1078, 46, 167,
680, 135, 46, 998, 1073, 999, 400, 171, 183, 168,
169, 184, 1087, 368, 369, 370, 371, 909, 372, 811,
46, 694, 176, 185, 573, 186, 544, 801, 323, 158,
407, 155, 46, 187, 964, 544, 1024, 286, 286, 544,
544, 46, 178, 508, 509, 188, 831, 46, 468, 156,
716, 818, 961, 178, 178, 802, 46, 690, 691, 742,
1060, 743, 159, 1061, 983, 109, 751, 323, 286, 160,
157, 178, 582, 863, 470, 265, 806, 189, 1062, 872,
865, 609, 323, 161, 610, 162, 190, 266, 174, 382,
383, 166, 170, 1027, 1028, 1029, 267, 744, 115, 174,
1206, 1208, 222, 515, 925, 175, 46, 191, 742, 46,
743, 981, 171, 178, 178, 537, 175, 987, 116, 268,
192, 193, 194, 46, 1186, 1003, 1004, 708, 163, 1181,
1227, 195, 1228, 1229, 707, 196, 745, 328, 985, 333,
269, 270, 977, 806, 178, 978, 744, 118, 178, 330,
946, 784, 948, 785, 950, 1138, 1001, 1002, 1003, 1004,
613, 167, 120, 914, 709, 952, 953, 954, 271, 119,
1058, 168, 169, 1202, 952, 953, 954, 197, 960, 1026,
1209, 468, 166, 245, 246, 1034, 563, 198, 199, 1198,
773, 200, 1178, 159, 555, 272, 1231, 563, 559, 560,
160, 805, 563, 201, 1199, 202, 820, 1178, 203, 121,
925, 925, 741, 122, 161, 123, 162, 204, 975, 976,
125, 205, 176, 126, 273, 1037, 1038, 1039, 206, 137,
222, 127, 222, 176, 370, 371, 222, 372, 274, 275,
276, 1179, 1180, 128, 700, 738, 277, 46, 1190, 1191,
129, 278, 167, 1040, 170, 1041, 1042, 130, 46, 163,
131, 1192, 168, 169, 138, 133, 1089, 207, 208, 132,
134, 996, 997, 324, 171, 135, 812, 139, 814, 140,
209, 925, 892, 893, 141, 925, 621, 279, 925, 925,
925, 925, 142, 730, 143, 144, 145, 1212, 146, 147,
1213, 1214, 148, 622, 280, 149, 150, 281, 152, 153,
282, 154, 1215, 1216, 165, 368, 369, 370, 371, 855,
372, 178, 333, 234, 219, 285, 292, 1090, 333, 258,
381, 382, 383, 384, 877, 427, 879, 623, 230, 624,
876, 231, 1056, 301, 328, 170, 332, 343, 849, 1065,
1066, 1067, 1068, 344, 345, 346, 330, 1217, 259, 347,
821, 328, 625, 348, 349, 171, 368, 369, 370, 371,
350, 372, 351, 330, 352, 353, 354, 1218, 1219, -105,
499, 626, 402, 355, 356, 627, 357, 358, 896, 368,
369, 370, 371, 862, 372, 359, 939, 360, 361, 222,
362, 628, 403, 646, 939, 404, 328, 158, 945, 406,
405, 303, 409, 410, 328, 1159, 333, 411, 330, 412,
413, 333, 855, 333, 414, 415, 330, 431, 416, 915,
918, 417, 304, 1091, 418, 838, 178, 419, 420, 421,
629, 630, 422, 333, 423, 879, 424, 425, 305, 916,
426, 429, 631, 632, 432, 368, 369, 370, 371, 234,
372, 434, 633, 333, 333, 435, 328, 328, 467, 178,
333, 222, 222, 438, 869, 439, 333, 442, 330, 330,
875, 333, 368, 369, 370, 371, 475, 372, 306, 307,
443, 444, 445, 896, 896, 1200, 222, 324, 634, 736,
368, 369, 370, 371, 939, 372, 308, 309, 446, 902,
902, 447, 1176, 222, 328, 448, 1220, 449, 1222, 450,
1223, 451, 310, 311, 312, 178, 330, 534, 452, 453,
368, 369, 370, 371, 313, 372, 454, 455, 314, 315,
730, 456, 936, 368, 369, 370, 371, 333, 372, 333,
936, 333, 328, 457, 316, 317, 318, 319, 234, 458,
368, 369, 370, 371, 330, 372, 372, 333, 459, 1001,
1002, 1003, 1004, 506, 647, 333, 222, 507, 574, 896,
583, 612, 1081, 1118, 1083, 611, 368, 369, 370, 371,
333, 372, 368, 369, 370, 371, -400, 372, 616, 618,
648, 619, 324, 324, 1051, 643, 649, 303, -111, 979,
-74, -74, -74, -74, 902, -74, 902, 667, 668, 541,
542, 515, 546, 547, 549, 550, 551, 552, 304, 554,
669, 556, 557, 558, 1064, 320, 1126, 368, 369, 370,
371, 518, 372, 703, 305, 1132, 683, 684, 685, 686,
936, 650, 211, 706, 217, 687, 368, 369, 370, 371,
704, 372, 234, 234, 234, 727, 711, 712, 713, 242,
651, 1123, 726, 733, 734, 251, 252, 749, 254, 255,
256, 257, 781, 754, 306, 307, 756, 757, 324, 290,
291, 759, 294, 760, 297, 298, 299, 180, 758, 761,
763, 764, 308, 309, 265, 765, 368, 369, 370, 371,
178, 372, 762, 1084, 766, 770, 266, 1160, 310, 311,
312, 767, 1075, 771, 674, 267, 799, 333, 804, 333,
313, 800, 815, 830, 314, 315, -68, -68, -68, -68,
816, -68, 700, 1188, 832, 1188, 1188, 833, 268, 837,
316, 317, 318, 319, 836, 839, 840, 363, 364, 365,
841, 861, 873, 1187, 1107, 1187, 1187, 1107, 888, 269,
270, 889, 899, 178, 912, 1183, 901, 368, 369, 370,
371, 333, 372, 368, 369, 370, 371, 911, 372, 930,
333, 652, 931, 932, 940, 671, 959, 271, 1201, 963,
974, 982, 700, 368, 369, 370, 371, 988, 372, 1022,
1020, 1158, 333, -67, -67, -67, -67, 653, -67, 990,
368, 369, 370, 371, 272, 372, 1017, 591, 592, 993,
594, 320, 596, 597, 654, 599, 600, 601, 602, 603,
604, 605, 606, 607, 368, 369, 370, 371, 994, 372,
1025, 1052, 1018, 273, 368, 369, 370, 371, 655, 372,
1000, 1001, 1002, 1003, 1004, 460, 1193, 274, 275, 276,
1019, 1032, 1054, 465, 234, 277, 234, 234, 1033, 1071,
278, 368, 369, 370, 371, 1057, 372, 1080, 1085, 954,
1096, 1097, 333, 1230, 1098, 481, 482, 483, 484, 485,
486, 487, 488, 489, 490, 491, 492, 493, 494, 495,
496, 1101, 498, 333, 1102, 333, 279, 333, 500, 501,
502, 503, 504, 183, 505, 1103, 184, 1104, 1120, 1141,
1121, 1122, 1128, 280, 511, 1136, 281, 1137, 185, 282,
186, 1142, 1140, 1155, 1143, 1156, 1162, 1161, 187, 368,
369, 370, 371, 1164, 372, 384, 368, 369, 370, 371,
188, 372, 1168, 660, 1166, 548, 1170, 1167, 1169, 553,
661, 368, 369, 370, 371, 1177, 372, 374, 368, 369,
370, 371, 565, 372, 1178, 663, 1182, 1184, 1037, 1038,
1039, 745, 189, 1203, 1205, 593, 1207, 595, 1210, 1226,
598, 190, 368, 369, 370, 371, 1144, 372, 151, 1117,
512, 1165, 608, 513, 737, 296, 1040, 428, 1041, 1042,
699, 461, 191, 375, 368, 369, 370, 371, 989, 372,
1145, 391, 514, 891, 1035, 192, 193, 194, 883, 368,
369, 370, 371, 250, 372, 615, 195, 750, 962, 478,
196, 965, 1135, 884, 854, 1197, 665, 666, 368, 369,
370, 371, 957, 372, 368, 369, 370, 371, 1139, 372,
401, 408, 885, 701, 368, 369, 370, 371, 886, 372,
368, 369, 370, 371, 656, 372, 368, 369, 370, 371,
657, 372, 197, 935, 819, 1119, 658, 934, 1130, 729,
1059, 1070, 198, 199, 1079, 585, 200, 368, 369, 370,
371, 0, 372, 0, 0, 0, 1146, 659, 201, 0,
202, 0, 0, 203, 664, 368, 369, 370, 371, 0,
372, 0, 204, 0, 0, 0, 205, 0, 887, 368,
369, 370, 371, 206, 372, -74, -74, -74, -74, 0,
-74, 0, 1147, 0, 0, 0, 0, 0, 0, 0,
465, 0, 46, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 183, 0, 0, 184, 0,
0, 1141, 207, 208, 0, 0, 0, 0, 0, 0,
185, 0, 186, 1142, 0, 209, 1143, 0, 0, 0,
187, 0, 0, 0, 0, 0, 774, 775, 776, 777,
0, 0, 188, 0, 778, 0, 0, 779, 780, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 791, 793, 795, 796, 797, 0, 0,
0, 0, 0, 0, 189, 0, 0, 0, 0, 0,
0, 0, 0, 190, 0, 0, 0, 0, 1144, 0,
0, 0, 813, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 191, 0, 0, 0, 0, 0,
0, 0, 1145, 0, 0, 0, 835, 192, 193, 194,
0, 0, 0, 0, 0, 0, 0, 0, 195, 0,
0, 0, 196, 0, 0, 0, 859, 860, 0, 0,
0, 0, 0, 868, 0, 871, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 197, 0, 0, 0, 0, 0,
0, 0, 0, 0, 198, 199, 0, 0, 200, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1146, 0,
201, 0, 202, 0, 0, 203, 0, 0, 0, 0,
0, 0, 0, 0, 204, 0, 0, 0, 205, 0,
0, 0, 0, 183, 0, 206, 184, 0, 0, 0,
0, 0, 0, 0, 1147, 0, 0, 0, 185, 0,
186, 0, 0, 0, 46, 0, 0, 0, 187, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
188, 0, 0, 0, 207, 208, 0, 972, 973, 0,
0, 0, 0, 0, 0, 0, 0, 209, 0, 0,
0, 980, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 189, 0, 0, 166, 0, 0, 0, 0,
0, 190, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 191, 0, 0, 1021, 0, 0, 0, 0,
0, 0, 0, 0, 0, 192, 193, 194, 0, 1030,
0, 0, 0, 1031, 0, 0, 195, 0, 0, 0,
196, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1036, 0, 0, 167, 0, 0, 0, 0,
0, 0, 0, 1055, 0, 168, 169, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 197, 0, 0, 0, 0, 0, 1082, 0,
0, 0, 198, 199, 0, 1088, 200, 0, 0, 0,
0, 0, 0, 0, 0, 0, 183, 0, 201, 184,
202, 0, 0, 203, 0, 0, 0, 0, 0, 0,
0, 185, 204, 186, 0, 0, 205, 0, 0, 0,
0, 187, 0, 206, 0, 0, 0, 0, 0, 0,
0, 0, 0, 188, 183, 0, 0, 184, 170, 0,
0, 0, 46, 0, 0, 1134, 0, 0, 0, 185,
0, 186, 0, 0, 0, 1148, 0, 0, 171, 187,
0, 0, 207, 208, 0, 189, 0, 0, 0, 0,
0, 188, 0, 0, 190, 209, 174, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1171, 0,
0, 0, 0, 175, 0, 191, 1173, 1174, 0, 0,
0, 0, 0, 189, 0, 0, 0, 0, 192, 193,
194, 0, 190, 0, 174, 1148, 1148, 0, 0, 195,
0, 0, 0, 196, 0, 0, 0, 0, 0, 0,
0, 175, 0, 191, 0, 0, 1196, 0, 1148, 0,
0, 0, 0, 0, 0, 0, 192, 193, 194, 0,
0, 0, 183, 0, 0, 184, 0, 195, 0, 0,
0, 196, 0, 0, 0, 197, 0, 185, 0, 186,
1224, 0, 0, 0, 0, 198, 199, 187, 0, 200,
0, 0, 0, 0, 0, 0, 0, 0, 0, 188,
0, 201, 0, 202, 0, 0, 203, 0, 0, 0,
0, 0, 0, 197, 0, 204, 0, 0, 0, 205,
176, 0, 0, 198, 199, 0, 206, 200, 0, 0,
0, 189, 0, 0, 0, 0, 0, 0, 0, 201,
190, 202, 0, 0, 203, 46, 0, 0, 0, 0,
0, 0, 0, 204, 0, 0, 0, 205, 176, 0,
0, 191, 289, 0, 206, 207, 208, 0, 0, 0,
0, 323, 0, 0, 192, 193, 194, 183, 209, 0,
184, 0, 0, 46, 0, 195, 0, 0, 0, 196,
0, 0, 185, 0, 186, 0, 0, 0, 0, 0,
0, 0, 187, 207, 208, 0, 0, 0, 0, 0,
0, 0, 0, 0, 188, 183, 209, 0, 184, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
185, 197, 186, 0, 0, 0, 0, 0, 0, 0,
187, 198, 199, 0, 0, 200, 189, 0, 0, 0,
0, 0, 188, 0, 0, 190, 0, 201, 0, 202,
0, 0, 203, 0, 0, 0, 0, 0, 0, 0,
0, 204, 0, 0, 0, 205, 191, 0, 0, 0,
0, 0, 206, 0, 189, 0, 0, 0, 0, 192,
193, 194, 0, 190, 0, 0, 0, 0, 0, 0,
195, 46, 0, 0, 196, 0, 0, 0, 0, 0,
0, 0, 0, 0, 191, 0, 0, 0, 0, 0,
0, 207, 208, 0, 0, 0, 0, 192, 193, 194,
0, 0, 0, 183, 209, 0, 184, 0, 195, 0,
0, 0, 196, 0, 0, 0, 197, 0, 185, 0,
186, 0, 0, 0, 0, 0, 198, 199, 187, 0,
200, 0, 0, 0, 0, 0, 0, 0, 0, 0,
188, 0, 201, 0, 202, 0, 0, 203, 0, 0,
0, 0, 0, 0, 197, 0, 204, 0, 0, 0,
205, 0, 0, 0, 198, 199, 0, 206, 200, 0,
0, 0, 189, 0, 0, 0, 0, 0, 0, 0,
201, 190, 202, 0, 0, 203, 46, 0, 0, 0,
0, 0, 0, 0, 204, 0, 0, 0, 205, 0,
0, 0, 191, 0, 0, 206, 207, 208, 0, 0,
0, 0, 462, 0, 0, 192, 193, 194, 0, 209,
0, 792, 0, 0, 46, 0, 195, 0, 0, 0,
196, 0, 0, 183, 0, 0, 184, 0, 0, 0,
0, 0, 0, 0, 207, 208, 0, 0, 185, 0,
186, 0, 0, 0, 0, 0, 0, 209, 187, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
188, 0, 197, 0, 0, 0, 0, 0, 0, 0,
0, 0, 198, 199, 0, 0, 200, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 201, 0,
202, 0, 189, 203, 0, 0, 0, 0, 0, 0,
0, 190, 204, 0, 0, 0, 205, 0, 0, 0,
0, 0, 0, 206, 0, 0, 0, 0, 0, 0,
0, 0, 191, 0, 0, 0, 0, 0, 0, 0,
0, 0, 46, 0, 0, 192, 193, 194, 0, 0,
0, 0, 0, 0, 0, 0, 195, 0, 0, 0,
196, 0, 207, 208, 1, 0, 0, 0, 323, 0,
0, 0, 0, 0, 0, 209, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
3, 4, 5, 6, 0, 0, 0, 0, 0, 0,
0, 0, 197, 0, 0, 7, 8, 9, 10, 11,
12, 13, 198, 199, 0, 0, 200, 0, 14, 15,
16, 0, 0, 0, 0, 0, 0, 0, 201, 0,
202, 0, 0, 203, 0, 17, 0, 0, 0, 0,
0, 0, 204, 18, 19, 0, 205, 0, 0, 0,
0, 0, 0, 206, 0, 0, 20, 0, 0, 0,
21, 0, 0, 22, 0, 0, 0, 23, 24, 0,
0, 0, 46, 0, 0, 0, 0, 0, 0, 0,
25, 26, 27, 28, 29, 0, 0, 0, 0, 0,
0, 30, 207, 208, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 209, 0, 0, 0, 31,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 32, 33, 34, 35, 0, 0, 0,
0, 0, 0, 0, 36, 37, 0, 0, 0, 38,
39, 0, 0, 40, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 41, 0, 0, 0, 0,
42, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 43, 44,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
45, 46, 0, 0, 47, 0, 0, 48, 0, 0,
0, 0, 0, 0, 0, 49
};
static const yytype_int16 yycheck[] =
{
0, 103, 133, 99, 100, 116, 152, 7, 117, 154,
10, 11, 152, 152, 635, 516, 152, 124, 138, 35,
8, 8, 12, 15, 520, 101, 522, 103, 152, 13,
526, 127, 429, 13, 8, 66, 132, 41, 52, 42,
82, 4, 106, 152, 77, 17, 768, 123, 115, 1043,
108, 51, 71, 635, 83, 54, 338, 29, 840, 932,
63, 137, 138, 242, 95, 1095, 27, 148, 92, 73,
242, 100, 394, 36, 242, 71, 140, 260, 242, 38,
1100, 262, 114, 242, 259, 106, 479, 268, 135, 136,
141, 142, 105, 276, 77, 274, 7, 259, 102, 10,
11, 101, 274, 103, 263, 138, 138, 275, 108, 109,
113, 22, 23, 277, 75, 115, 116, 117, 277, 140,
120, 121, 122, 123, 124, 236, 263, 146, 242, 750,
852, 173, 263, 133, 755, 273, 858, 137, 138, 155,
1013, 278, 535, 143, 160, 1175, 262, 163, 164, 165,
146, 800, 152, 152, 154, 138, 67, 1151, 940, 92,
105, 242, 220, 279, 228, 232, 259, 1012, 750, 157,
157, 242, 135, 136, 221, 147, 87, 88, 202, 242,
573, 195, 186, 157, 145, 188, 174, 174, 217, 471,
25, 1211, 191, 689, 155, 156, 242, 519, 56, 57,
174, 1195, 215, 274, 207, 268, 209, 228, 43, 1054,
274, 274, 1057, 242, 227, 612, 220, 259, 259, 75,
220, 618, 268, 343, 255, 225, 189, 274, 274, 64,
332, 338, 232, 237, 233, 234, 236, 217, 242, 242,
263, 274, 259, 262, 263, 264, 265, 272, 267, 273,
242, 276, 242, 259, 277, 904, 332, 906, 242, 263,
242, 882, 242, 263, 242, 761, 762, 343, 344, 202,
215, 275, 275, 236, 259, 274, 268, 238, 268, 848,
135, 136, 227, 403, 404, 361, 274, 274, 242, 145,
786, 273, 242, 272, 274, 274, 274, 258, 3, 155,
156, 6, 1024, 262, 263, 264, 265, 803, 267, 706,
242, 274, 217, 18, 434, 20, 412, 231, 268, 154,
274, 25, 242, 28, 274, 421, 947, 403, 404, 425,
426, 242, 332, 44, 45, 40, 733, 242, 338, 43,
273, 274, 274, 343, 344, 259, 242, 135, 136, 197,
259, 199, 187, 262, 274, 273, 753, 268, 434, 194,
64, 361, 438, 760, 471, 14, 221, 72, 277, 766,
866, 269, 268, 208, 272, 210, 81, 26, 83, 271,
272, 75, 238, 952, 953, 954, 35, 235, 273, 83,
1190, 1191, 392, 393, 817, 100, 242, 102, 197, 242,
199, 902, 258, 403, 404, 405, 100, 908, 273, 58,
115, 116, 117, 242, 257, 264, 265, 563, 253, 274,
1220, 126, 1222, 1223, 563, 130, 274, 563, 274, 429,
79, 80, 269, 221, 434, 272, 235, 259, 438, 563,
837, 676, 839, 678, 841, 274, 262, 263, 264, 265,
154, 145, 275, 147, 563, 262, 263, 264, 107, 259,
276, 155, 156, 1185, 262, 263, 264, 172, 865, 276,
1192, 471, 75, 121, 122, 274, 272, 182, 183, 269,
276, 186, 272, 187, 421, 134, 274, 272, 425, 426,
194, 276, 272, 198, 269, 200, 276, 272, 203, 275,
923, 924, 613, 275, 208, 259, 210, 212, 892, 893,
259, 216, 217, 259, 163, 68, 69, 70, 223, 275,
520, 259, 522, 217, 264, 265, 526, 267, 177, 178,
179, 1155, 1156, 259, 534, 611, 185, 242, 1166, 1167,
259, 190, 145, 96, 238, 98, 99, 259, 242, 253,
259, 1172, 155, 156, 275, 273, 213, 262, 263, 259,
273, 923, 924, 563, 258, 273, 711, 259, 713, 259,
275, 994, 277, 278, 273, 998, 38, 226, 1001, 1002,
1003, 1004, 259, 583, 275, 259, 259, 7, 259, 273,
10, 11, 273, 55, 243, 273, 0, 246, 259, 82,
249, 259, 22, 23, 173, 262, 263, 264, 265, 754,
267, 611, 612, 613, 273, 39, 158, 274, 618, 222,
270, 271, 272, 273, 770, 274, 771, 89, 273, 91,
770, 273, 994, 78, 770, 238, 275, 275, 749, 1001,
1002, 1003, 1004, 260, 275, 275, 770, 67, 251, 275,
726, 787, 114, 275, 275, 258, 262, 263, 264, 265,
275, 267, 275, 787, 275, 275, 275, 87, 88, 260,
276, 133, 276, 275, 275, 137, 275, 275, 787, 262,
263, 264, 265, 759, 267, 275, 832, 275, 275, 689,
275, 153, 272, 276, 840, 272, 832, 154, 215, 273,
268, 16, 259, 259, 840, 1102, 706, 259, 832, 259,
259, 711, 857, 713, 259, 259, 840, 276, 259, 815,
816, 259, 37, 213, 259, 741, 726, 259, 259, 259,
192, 193, 259, 733, 259, 880, 259, 259, 53, 815,
259, 259, 204, 205, 259, 262, 263, 264, 265, 749,
267, 272, 214, 753, 754, 131, 892, 893, 39, 759,
760, 761, 762, 259, 764, 138, 766, 259, 892, 893,
770, 771, 262, 263, 264, 265, 244, 267, 93, 94,
259, 259, 259, 892, 893, 1182, 786, 787, 250, 231,
262, 263, 264, 265, 940, 267, 111, 112, 259, 799,
800, 259, 231, 803, 940, 259, 1203, 259, 1205, 259,
1207, 259, 127, 128, 129, 815, 940, 268, 259, 259,
262, 263, 264, 265, 139, 267, 259, 259, 143, 144,
830, 259, 832, 262, 263, 264, 265, 837, 267, 839,
840, 841, 978, 259, 159, 160, 161, 162, 848, 259,
262, 263, 264, 265, 978, 267, 267, 857, 259, 262,
263, 264, 265, 259, 276, 865, 866, 259, 259, 978,
259, 259, 1017, 276, 1019, 272, 262, 263, 264, 265,
880, 267, 262, 263, 264, 265, 173, 267, 201, 273,
276, 225, 892, 893, 990, 62, 276, 16, 260, 899,
262, 263, 264, 265, 904, 267, 906, 259, 259, 410,
411, 911, 413, 414, 415, 416, 417, 418, 37, 420,
224, 422, 423, 424, 1000, 240, 1071, 262, 263, 264,
265, 263, 267, 276, 53, 1080, 259, 259, 259, 259,
940, 276, 102, 272, 104, 259, 262, 263, 264, 265,
269, 267, 952, 953, 954, 273, 259, 259, 259, 119,
276, 1063, 259, 259, 254, 125, 126, 259, 128, 129,
130, 131, 118, 273, 93, 94, 259, 259, 978, 139,
140, 259, 142, 259, 144, 145, 146, 1063, 273, 259,
259, 259, 111, 112, 14, 259, 262, 263, 264, 265,
1000, 267, 273, 269, 259, 259, 26, 1103, 127, 128,
129, 273, 1012, 273, 263, 35, 273, 1017, 269, 1019,
139, 273, 259, 262, 143, 144, 262, 263, 264, 265,
259, 267, 1032, 1164, 259, 1166, 1167, 252, 58, 272,
159, 160, 161, 162, 276, 259, 259, 207, 208, 209,
259, 120, 119, 1164, 1054, 1166, 1167, 1057, 259, 79,
80, 74, 261, 1063, 171, 1161, 259, 262, 263, 264,
265, 1071, 267, 262, 263, 264, 265, 259, 267, 273,
1080, 276, 273, 273, 259, 274, 259, 107, 1184, 259,
274, 259, 1092, 262, 263, 264, 265, 273, 267, 19,
274, 1101, 1102, 262, 263, 264, 265, 276, 267, 259,
262, 263, 264, 265, 134, 267, 259, 443, 444, 268,
446, 240, 448, 449, 276, 451, 452, 453, 454, 455,
456, 457, 458, 459, 262, 263, 264, 265, 275, 267,
272, 168, 259, 163, 262, 263, 264, 265, 276, 267,
261, 262, 263, 264, 265, 274, 274, 177, 178, 179,
259, 273, 268, 323, 1164, 185, 1166, 1167, 273, 279,
190, 262, 263, 264, 265, 268, 267, 279, 259, 264,
269, 259, 1182, 274, 259, 345, 346, 347, 348, 349,
350, 351, 352, 353, 354, 355, 356, 357, 358, 359,
360, 259, 362, 1203, 259, 1205, 226, 1207, 368, 369,
370, 371, 372, 3, 374, 259, 6, 169, 277, 9,
277, 277, 259, 243, 384, 259, 246, 259, 18, 249,
20, 21, 273, 268, 24, 268, 170, 259, 28, 262,
263, 264, 265, 272, 267, 273, 262, 263, 264, 265,
40, 267, 269, 276, 272, 415, 277, 272, 269, 419,
276, 262, 263, 264, 265, 274, 267, 261, 262, 263,
264, 265, 432, 267, 272, 276, 272, 259, 68, 69,
70, 274, 72, 272, 272, 445, 272, 447, 259, 272,
450, 81, 262, 263, 264, 265, 86, 267, 51, 269,
386, 1107, 462, 386, 610, 143, 96, 283, 98, 99,
533, 321, 102, 218, 262, 263, 264, 265, 911, 267,
110, 225, 392, 786, 978, 115, 116, 117, 276, 262,
263, 264, 265, 124, 267, 471, 126, 617, 866, 342,
130, 880, 1086, 276, 753, 1178, 506, 507, 262, 263,
264, 265, 857, 267, 262, 263, 264, 265, 1092, 267,
236, 263, 276, 534, 262, 263, 264, 265, 276, 267,
262, 263, 264, 265, 272, 267, 262, 263, 264, 265,
272, 267, 172, 830, 717, 1057, 272, 825, 1077, 577,
998, 1009, 182, 183, 1013, 440, 186, 262, 263, 264,
265, -1, 267, -1, -1, -1, 196, 272, 198, -1,
200, -1, -1, 203, 261, 262, 263, 264, 265, -1,
267, -1, 212, -1, -1, -1, 216, -1, 261, 262,
263, 264, 265, 223, 267, 262, 263, 264, 265, -1,
267, -1, 232, -1, -1, -1, -1, -1, -1, -1,
610, -1, 242, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 3, -1, -1, 6, -1,
-1, 9, 262, 263, -1, -1, -1, -1, -1, -1,
18, -1, 20, 21, -1, 275, 24, -1, -1, -1,
28, -1, -1, -1, -1, -1, 656, 657, 658, 659,
-1, -1, 40, -1, 664, -1, -1, 667, 668, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 683, 684, 685, 686, 687, -1, -1,
-1, -1, -1, -1, 72, -1, -1, -1, -1, -1,
-1, -1, -1, 81, -1, -1, -1, -1, 86, -1,
-1, -1, 712, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 102, -1, -1, -1, -1, -1,
-1, -1, 110, -1, -1, -1, 736, 115, 116, 117,
-1, -1, -1, -1, -1, -1, -1, -1, 126, -1,
-1, -1, 130, -1, -1, -1, 756, 757, -1, -1,
-1, -1, -1, 763, -1, 765, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 172, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 182, 183, -1, -1, 186, -1,
-1, -1, -1, -1, -1, -1, -1, -1, 196, -1,
198, -1, 200, -1, -1, 203, -1, -1, -1, -1,
-1, -1, -1, -1, 212, -1, -1, -1, 216, -1,
-1, -1, -1, 3, -1, 223, 6, -1, -1, -1,
-1, -1, -1, -1, 232, -1, -1, -1, 18, -1,
20, -1, -1, -1, 242, -1, -1, -1, 28, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
40, -1, -1, -1, 262, 263, -1, 887, 888, -1,
-1, -1, -1, -1, -1, -1, -1, 275, -1, -1,
-1, 901, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 72, -1, -1, 75, -1, -1, -1, -1,
-1, 81, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 102, -1, -1, 945, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 115, 116, 117, -1, 959,
-1, -1, -1, 963, -1, -1, 126, -1, -1, -1,
130, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 982, -1, -1, 145, -1, -1, -1, -1,
-1, -1, -1, 993, -1, 155, 156, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 172, -1, -1, -1, -1, -1, 1018, -1,
-1, -1, 182, 183, -1, 1025, 186, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 3, -1, 198, 6,
200, -1, -1, 203, -1, -1, -1, -1, -1, -1,
-1, 18, 212, 20, -1, -1, 216, -1, -1, -1,
-1, 28, -1, 223, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 40, 3, -1, -1, 6, 238, -1,
-1, -1, 242, -1, -1, 1085, -1, -1, -1, 18,
-1, 20, -1, -1, -1, 1095, -1, -1, 258, 28,
-1, -1, 262, 263, -1, 72, -1, -1, -1, -1,
-1, 40, -1, -1, 81, 275, 83, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, 1128, -1,
-1, -1, -1, 100, -1, 102, 1136, 1137, -1, -1,
-1, -1, -1, 72, -1, -1, -1, -1, 115, 116,
117, -1, 81, -1, 83, 1155, 1156, -1, -1, 126,
-1, -1, -1, 130, -1, -1, -1, -1, -1, -1,
-1, 100, -1, 102, -1, -1, 1176, -1, 1178, -1,
-1, -1, -1, -1, -1, -1, 115, 116, 117, -1,
-1, -1, 3, -1, -1, 6, -1, 126, -1, -1,
-1, 130, -1, -1, -1, 172, -1, 18, -1, 20,
1210, -1, -1, -1, -1, 182, 183, 28, -1, 186,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 40,
-1, 198, -1, 200, -1, -1, 203, -1, -1, -1,
-1, -1, -1, 172, -1, 212, -1, -1, -1, 216,
217, -1, -1, 182, 183, -1, 223, 186, -1, -1,
-1, 72, -1, -1, -1, -1, -1, -1, -1, 198,
81, 200, -1, -1, 203, 242, -1, -1, -1, -1,
-1, -1, -1, 212, -1, -1, -1, 216, 217, -1,
-1, 102, 103, -1, 223, 262, 263, -1, -1, -1,
-1, 268, -1, -1, 115, 116, 117, 3, 275, -1,
6, -1, -1, 242, -1, 126, -1, -1, -1, 130,
-1, -1, 18, -1, 20, -1, -1, -1, -1, -1,
-1, -1, 28, 262, 263, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 40, 3, 275, -1, 6, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
18, 172, 20, -1, -1, -1, -1, -1, -1, -1,
28, 182, 183, -1, -1, 186, 72, -1, -1, -1,
-1, -1, 40, -1, -1, 81, -1, 198, -1, 200,
-1, -1, 203, -1, -1, -1, -1, -1, -1, -1,
-1, 212, -1, -1, -1, 216, 102, -1, -1, -1,
-1, -1, 223, -1, 72, -1, -1, -1, -1, 115,
116, 117, -1, 81, -1, -1, -1, -1, -1, -1,
126, 242, -1, -1, 130, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 102, -1, -1, -1, -1, -1,
-1, 262, 263, -1, -1, -1, -1, 115, 116, 117,
-1, -1, -1, 3, 275, -1, 6, -1, 126, -1,
-1, -1, 130, -1, -1, -1, 172, -1, 18, -1,
20, -1, -1, -1, -1, -1, 182, 183, 28, -1,
186, -1, -1, -1, -1, -1, -1, -1, -1, -1,
40, -1, 198, -1, 200, -1, -1, 203, -1, -1,
-1, -1, -1, -1, 172, -1, 212, -1, -1, -1,
216, -1, -1, -1, 182, 183, -1, 223, 186, -1,
-1, -1, 72, -1, -1, -1, -1, -1, -1, -1,
198, 81, 200, -1, -1, 203, 242, -1, -1, -1,
-1, -1, -1, -1, 212, -1, -1, -1, 216, -1,
-1, -1, 102, -1, -1, 223, 262, 263, -1, -1,
-1, -1, 268, -1, -1, 115, 116, 117, -1, 275,
-1, 239, -1, -1, 242, -1, 126, -1, -1, -1,
130, -1, -1, 3, -1, -1, 6, -1, -1, -1,
-1, -1, -1, -1, 262, 263, -1, -1, 18, -1,
20, -1, -1, -1, -1, -1, -1, 275, 28, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
40, -1, 172, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 182, 183, -1, -1, 186, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, 198, -1,
200, -1, 72, 203, -1, -1, -1, -1, -1, -1,
-1, 81, 212, -1, -1, -1, 216, -1, -1, -1,
-1, -1, -1, 223, -1, -1, -1, -1, -1, -1,
-1, -1, 102, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 242, -1, -1, 115, 116, 117, -1, -1,
-1, -1, -1, -1, -1, -1, 126, -1, -1, -1,
130, -1, 262, 263, 5, -1, -1, -1, 268, -1,
-1, -1, -1, -1, -1, 275, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 30,
31, 32, 33, 34, -1, -1, -1, -1, -1, -1,
-1, -1, 172, -1, -1, 46, 47, 48, 49, 50,
51, 52, 182, 183, -1, -1, 186, -1, 59, 60,
61, -1, -1, -1, -1, -1, -1, -1, 198, -1,
200, -1, -1, 203, -1, 76, -1, -1, -1, -1,
-1, -1, 212, 84, 85, -1, 216, -1, -1, -1,
-1, -1, -1, 223, -1, -1, 97, -1, -1, -1,
101, -1, -1, 104, -1, -1, -1, 108, 109, -1,
-1, -1, 242, -1, -1, -1, -1, -1, -1, -1,
121, 122, 123, 124, 125, -1, -1, -1, -1, -1,
-1, 132, 262, 263, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 275, -1, -1, -1, 150,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 164, 165, 166, 167, -1, -1, -1,
-1, -1, -1, -1, 175, 176, -1, -1, -1, 180,
181, -1, -1, 184, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 206, -1, -1, -1, -1,
211, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, 229, 230,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
241, 242, -1, -1, 245, -1, -1, 248, -1, -1,
-1, -1, -1, -1, -1, 256
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint16 yystos[] =
{
0, 5, 30, 31, 32, 33, 34, 46, 47, 48,
49, 50, 51, 52, 59, 60, 61, 76, 84, 85,
97, 101, 104, 108, 109, 121, 122, 123, 124, 125,
132, 150, 164, 165, 166, 167, 175, 176, 180, 181,
184, 206, 211, 229, 230, 241, 242, 245, 248, 256,
281, 282, 283, 285, 299, 300, 301, 315, 316, 317,
319, 324, 325, 326, 327, 328, 329, 334, 338, 341,
342, 343, 344, 345, 346, 347, 360, 361, 362, 377,
400, 405, 407, 408, 409, 415, 420, 421, 425, 439,
440, 470, 475, 478, 486, 496, 500, 535, 560, 259,
259, 259, 259, 259, 259, 285, 349, 350, 273, 273,
285, 401, 285, 351, 364, 273, 273, 259, 259, 259,
275, 275, 275, 259, 406, 259, 259, 259, 259, 259,
259, 259, 259, 273, 273, 273, 410, 275, 275, 259,
259, 273, 259, 275, 259, 259, 259, 273, 273, 273,
0, 283, 259, 82, 259, 25, 43, 64, 154, 187,
194, 208, 210, 253, 427, 173, 75, 145, 155, 156,
238, 258, 291, 291, 83, 100, 217, 284, 285, 286,
312, 313, 314, 3, 6, 18, 20, 28, 40, 72,
81, 102, 115, 116, 117, 126, 130, 172, 182, 183,
186, 198, 200, 203, 212, 216, 223, 262, 263, 275,
285, 306, 307, 308, 310, 311, 286, 306, 340, 273,
348, 349, 285, 357, 359, 378, 379, 388, 389, 390,
273, 273, 363, 364, 285, 287, 487, 488, 312, 313,
141, 142, 306, 285, 320, 320, 320, 312, 285, 409,
415, 306, 306, 291, 306, 306, 306, 306, 222, 251,
291, 287, 288, 497, 498, 14, 26, 35, 58, 79,
80, 107, 134, 163, 177, 178, 179, 185, 190, 226,
243, 246, 249, 330, 331, 39, 312, 321, 321, 103,
306, 306, 158, 502, 306, 285, 301, 306, 306, 306,
536, 78, 561, 16, 37, 53, 93, 94, 111, 112,
127, 128, 129, 139, 143, 144, 159, 160, 161, 162,
240, 335, 336, 268, 285, 302, 304, 306, 308, 309,
311, 313, 275, 285, 303, 304, 305, 410, 410, 410,
410, 410, 410, 275, 260, 275, 275, 275, 275, 275,
275, 275, 275, 275, 275, 275, 275, 275, 275, 275,
275, 275, 275, 306, 306, 306, 71, 146, 262, 263,
264, 265, 267, 339, 261, 339, 56, 57, 352, 274,
349, 270, 271, 272, 273, 292, 293, 294, 295, 296,
274, 379, 262, 279, 391, 403, 365, 274, 364, 489,
274, 488, 276, 272, 272, 268, 273, 274, 498, 259,
259, 259, 259, 259, 259, 259, 259, 259, 259, 259,
259, 259, 259, 259, 259, 259, 259, 274, 331, 259,
322, 276, 259, 501, 272, 131, 538, 539, 259, 138,
562, 563, 259, 259, 259, 259, 259, 259, 259, 259,
259, 259, 259, 259, 259, 259, 259, 259, 259, 259,
274, 336, 268, 297, 298, 306, 286, 39, 285, 408,
409, 416, 417, 418, 422, 244, 442, 426, 442, 321,
312, 306, 306, 306, 306, 306, 306, 306, 306, 306,
306, 306, 306, 306, 306, 306, 306, 312, 306, 276,
306, 306, 306, 306, 306, 306, 259, 259, 44, 45,
353, 306, 294, 295, 390, 285, 366, 392, 263, 278,
380, 381, 382, 383, 384, 385, 386, 54, 152, 191,
233, 234, 274, 367, 268, 321, 321, 285, 499, 291,
332, 332, 332, 27, 291, 333, 332, 332, 306, 332,
332, 332, 332, 306, 332, 333, 332, 332, 332, 333,
333, 289, 303, 272, 276, 306, 105, 215, 227, 503,
504, 505, 506, 321, 259, 77, 138, 537, 540, 541,
542, 543, 312, 259, 114, 563, 566, 66, 95, 255,
337, 337, 337, 306, 337, 306, 337, 337, 306, 337,
337, 337, 337, 337, 337, 337, 337, 337, 306, 269,
272, 272, 259, 154, 412, 417, 201, 423, 273, 225,
472, 38, 55, 89, 91, 114, 133, 137, 153, 192,
193, 204, 205, 214, 250, 428, 430, 431, 432, 433,
434, 435, 436, 62, 445, 322, 276, 276, 276, 276,
276, 276, 276, 276, 276, 276, 272, 272, 272, 272,
276, 276, 276, 276, 261, 306, 306, 259, 259, 224,
354, 274, 292, 380, 263, 277, 359, 277, 359, 148,
359, 393, 394, 259, 259, 259, 259, 259, 4, 36,
135, 136, 189, 236, 274, 368, 369, 370, 372, 373,
285, 492, 322, 276, 269, 493, 272, 302, 309, 313,
323, 259, 259, 259, 92, 202, 273, 507, 508, 509,
512, 513, 322, 17, 29, 147, 259, 273, 274, 540,
285, 564, 565, 259, 254, 567, 231, 298, 312, 318,
289, 287, 197, 199, 235, 274, 411, 413, 414, 259,
428, 289, 443, 444, 273, 471, 259, 259, 273, 259,
259, 259, 273, 259, 259, 259, 259, 273, 412, 430,
259, 273, 441, 276, 306, 306, 306, 306, 306, 306,
306, 118, 355, 380, 381, 381, 262, 268, 395, 396,
397, 306, 239, 306, 404, 306, 306, 306, 359, 273,
273, 231, 259, 371, 269, 276, 221, 274, 373, 494,
495, 289, 303, 306, 303, 259, 259, 510, 274, 508,
276, 312, 106, 140, 228, 544, 545, 546, 552, 556,
262, 289, 259, 252, 568, 306, 276, 272, 410, 259,
259, 259, 42, 63, 113, 188, 207, 209, 275, 287,
288, 424, 412, 274, 443, 303, 473, 474, 412, 306,
306, 120, 312, 289, 359, 359, 437, 438, 306, 285,
402, 306, 289, 119, 411, 285, 304, 309, 429, 303,
446, 447, 448, 276, 276, 276, 276, 261, 259, 74,
356, 394, 277, 278, 302, 309, 313, 398, 399, 261,
387, 259, 285, 358, 374, 376, 375, 376, 13, 359,
490, 259, 171, 484, 147, 291, 312, 511, 291, 41,
73, 220, 237, 263, 275, 307, 514, 515, 516, 517,
273, 273, 273, 274, 545, 564, 285, 289, 290, 309,
259, 105, 215, 227, 569, 215, 289, 419, 289, 290,
289, 424, 262, 263, 264, 411, 274, 473, 411, 259,
289, 274, 438, 259, 274, 447, 52, 195, 412, 449,
450, 465, 306, 306, 274, 399, 399, 269, 272, 285,
306, 292, 259, 274, 376, 274, 376, 292, 273, 366,
259, 476, 518, 268, 275, 519, 516, 516, 272, 274,
261, 262, 263, 264, 265, 534, 8, 157, 174, 557,
558, 559, 548, 553, 554, 559, 290, 259, 259, 259,
274, 306, 19, 485, 412, 272, 276, 424, 424, 424,
306, 306, 273, 273, 274, 398, 306, 68, 69, 70,
96, 98, 99, 454, 455, 456, 457, 461, 462, 463,
464, 291, 168, 481, 268, 306, 516, 268, 276, 515,
259, 262, 277, 520, 312, 516, 516, 516, 516, 274,
558, 279, 13, 274, 284, 285, 549, 550, 274, 554,
279, 303, 306, 303, 269, 259, 479, 411, 306, 213,
274, 213, 466, 467, 492, 451, 269, 259, 259, 455,
491, 259, 259, 259, 169, 482, 284, 285, 522, 523,
524, 525, 526, 527, 528, 529, 530, 269, 276, 524,
277, 277, 277, 286, 521, 12, 303, 555, 259, 547,
547, 15, 303, 551, 306, 448, 259, 259, 274, 467,
273, 9, 21, 24, 86, 110, 196, 232, 306, 452,
453, 454, 458, 459, 460, 268, 268, 493, 285, 289,
291, 259, 170, 483, 272, 296, 272, 272, 269, 269,
277, 306, 480, 306, 306, 468, 231, 274, 272, 459,
459, 274, 272, 291, 259, 477, 257, 287, 288, 531,
531, 531, 412, 274, 38, 454, 306, 460, 269, 269,
289, 291, 411, 272, 532, 272, 532, 272, 532, 411,
259, 469, 7, 10, 11, 22, 23, 67, 87, 88,
289, 533, 289, 289, 306, 493, 272, 532, 532, 532,
274, 274
};
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint16 yyr1[] =
{
0, 280, 281, 282, 282, 283, 283, 283, 283, 283,
283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
283, 283, 283, 283, 283, 283, 284, 285, 286, 287,
288, 289, 290, 290, 291, 291, 291, 291, 291, 291,
292, 292, 292, 292, 293, 293, 293, 293, 294, 295,
296, 297, 297, 298, 298, 299, 300, 300, 300, 300,
301, 302, 303, 303, 304, 305, 306, 306, 307, 307,
308, 308, 309, 309, 310, 311, 311, 311, 311, 311,
311, 311, 311, 311, 311, 311, 311, 311, 311, 311,
311, 311, 311, 311, 311, 311, 311, 311, 311, 311,
311, 311, 311, 311, 311, 312, 312, 313, 313, 313,
313, 314, 315, 315, 315, 315, 315, 315, 315, 316,
317, 318, 319, 320, 321, 322, 322, 323, 323, 323,
324, 325, 326, 327, 328, 329, 330, 330, 331, 331,
331, 331, 331, 331, 331, 331, 331, 331, 331, 331,
331, 331, 331, 331, 331, 331, 331, 332, 333, 333,
334, 335, 335, 336, 336, 336, 336, 336, 336, 336,
336, 336, 336, 336, 336, 336, 336, 336, 336, 336,
336, 337, 337, 337, 338, 338, 338, 338, 338, 339,
339, 339, 340, 340, 340, 340, 341, 341, 341, 341,
341, 341, 341, 341, 341, 341, 341, 341, 341, 341,
341, 341, 341, 341, 342, 342, 342, 342, 343, 344,
344, 344, 345, 345, 346, 347, 348, 348, 349, 350,
351, 352, 352, 353, 353, 353, 354, 354, 355, 355,
356, 356, 357, 358, 359, 360, 360, 361, 362, 363,
363, 365, 364, 366, 367, 367, 368, 368, 369, 369,
369, 370, 370, 370, 371, 371, 372, 373, 373, 374,
374, 375, 375, 376, 377, 378, 378, 379, 380, 380,
381, 382, 383, 384, 385, 386, 386, 386, 386, 387,
387, 388, 389, 389, 390, 391, 391, 392, 393, 393,
394, 394, 395, 395, 396, 397, 398, 398, 398, 399,
399, 399, 400, 401, 402, 403, 403, 403, 403, 403,
403, 404, 404, 406, 405, 407, 408, 408, 408, 408,
408, 409, 410, 411, 412, 412, 413, 414, 414, 414,
415, 416, 416, 417, 417, 419, 418, 420, 420, 422,
421, 423, 423, 423, 423, 423, 423, 423, 423, 424,
424, 424, 424, 424, 426, 425, 427, 427, 427, 427,
427, 428, 428, 429, 430, 430, 430, 430, 430, 430,
430, 430, 430, 430, 430, 431, 431, 432, 432, 432,
432, 433, 433, 434, 435, 436, 436, 437, 437, 438,
439, 441, 440, 442, 443, 444, 444, 445, 446, 446,
447, 448, 448, 449, 449, 451, 450, 452, 452, 453,
453, 453, 453, 453, 453, 453, 454, 454, 455, 455,
455, 455, 456, 457, 458, 459, 459, 460, 460, 460,
461, 462, 462, 463, 464, 464, 465, 466, 466, 468,
469, 467, 471, 470, 472, 473, 474, 474, 476, 477,
475, 479, 480, 478, 481, 481, 482, 482, 483, 483,
484, 484, 485, 485, 486, 487, 487, 489, 490, 491,
488, 492, 493, 493, 494, 494, 495, 496, 497, 497,
499, 498, 501, 500, 502, 502, 503, 503, 503, 504,
505, 506, 507, 507, 507, 508, 508, 508, 510, 509,
511, 511, 511, 512, 513, 514, 514, 515, 516, 516,
516, 516, 516, 516, 516, 516, 516, 518, 517, 517,
519, 517, 520, 520, 520, 520, 520, 521, 522, 523,
524, 524, 524, 524, 524, 524, 525, 526, 527, 528,
529, 530, 531, 531, 531, 532, 532, 533, 533, 533,
533, 533, 533, 533, 533, 534, 534, 536, 535, 537,
537, 538, 538, 539, 539, 539, 540, 540, 541, 542,
543, 544, 544, 545, 545, 545, 546, 547, 547, 548,
548, 549, 549, 550, 550, 551, 551, 552, 553, 553,
554, 555, 555, 556, 557, 557, 558, 559, 559, 559,
560, 561, 562, 562, 563, 564, 565, 565, 566, 567,
568, 569, 569, 569, 569
};
/* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 1, 1, 2, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 1, 1, 1, 1, 2, 2, 1, 1,
3, 1, 3, 1, 7, 3, 3, 3, 3, 3,
1, 1, 1, 1, 3, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 3, 4, 4, 4, 6,
6, 6, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 6, 1, 1, 1, 1, 4, 3, 3,
3, 3, 3, 2, 2, 1, 1, 1, 1, 3,
5, 1, 1, 1, 1, 1, 1, 1, 1, 7,
1, 1, 4, 1, 1, 0, 3, 1, 1, 1,
5, 7, 7, 4, 6, 4, 1, 2, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 1, 1, 1,
4, 1, 2, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 1, 1, 1, 3, 3, 4, 3, 4, 0,
1, 1, 1, 3, 5, 7, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 1,
1, 1, 1, 1, 2, 4, 1, 2, 8, 1,
1, 3, 3, 0, 3, 3, 0, 1, 0, 3,
0, 1, 1, 2, 2, 1, 1, 2, 4, 1,
2, 0, 5, 1, 0, 2, 1, 1, 3, 4,
4, 1, 1, 1, 1, 1, 1, 4, 4, 1,
2, 1, 2, 3, 4, 1, 2, 1, 1, 2,
2, 2, 2, 3, 3, 1, 1, 1, 1, 0,
2, 6, 1, 3, 1, 0, 2, 2, 1, 3,
1, 1, 1, 1, 3, 5, 1, 2, 2, 1,
1, 1, 5, 1, 1, 0, 4, 4, 4, 4,
4, 1, 1, 0, 3, 1, 1, 1, 1, 1,
1, 1, 1, 1, 0, 2, 1, 3, 3, 5,
6, 1, 2, 1, 1, 0, 7, 1, 1, 0,
8, 3, 3, 3, 3, 3, 3, 3, 3, 1,
3, 3, 3, 3, 0, 7, 1, 1, 1, 1,
1, 1, 2, 1, 3, 3, 1, 3, 3, 3,
3, 3, 3, 4, 3, 1, 1, 1, 1, 1,
1, 3, 6, 9, 12, 3, 3, 1, 2, 2,
1, 0, 9, 4, 1, 1, 2, 4, 1, 2,
1, 0, 2, 1, 1, 0, 5, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 2, 1, 1,
1, 1, 5, 5, 1, 1, 3, 1, 3, 1,
3, 1, 1, 5, 1, 1, 4, 1, 2, 0,
0, 7, 0, 8, 4, 1, 1, 2, 0, 0,
14, 0, 0, 14, 0, 3, 0, 3, 0, 3,
0, 3, 0, 3, 4, 1, 2, 0, 0, 0,
11, 1, 0, 2, 1, 1, 3, 4, 1, 2,
0, 5, 0, 7, 0, 3, 1, 1, 1, 3,
3, 3, 0, 1, 2, 1, 1, 1, 0, 6,
1, 1, 1, 3, 3, 1, 3, 2, 1, 1,
3, 3, 3, 3, 3, 2, 4, 0, 5, 4,
0, 5, 1, 2, 2, 3, 2, 1, 1, 2,
1, 1, 1, 1, 1, 1, 4, 4, 4, 6,
6, 6, 1, 1, 1, 0, 2, 1, 1, 1,
1, 1, 1, 1, 1, 0, 2, 0, 6, 1,
2, 0, 1, 3, 3, 3, 1, 1, 1, 3,
4, 1, 2, 1, 1, 1, 4, 2, 0, 2,
0, 2, 2, 1, 1, 1, 1, 4, 1, 2,
3, 1, 1, 4, 1, 2, 3, 1, 1, 1,
9, 3, 1, 2, 3, 1, 1, 3, 3, 3,
3, 0, 3, 3, 3
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY) \
{ \
yychar = (Token); \
yylval = (Value); \
YYPOPSTACK (yylen); \
yystate = *yyssp; \
goto yybackup; \
} \
else \
{ \
yyerror (parse_state, scanner, YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (0)
/* Error token number */
#define YYTERROR 1
#define YYERRCODE 256
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (0)
/* This macro is provided for backward compatibility. */
#ifndef YY_LOCATION_PRINT
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
#endif
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value, parse_state, scanner); \
YYFPRINTF (stderr, "\n"); \
} \
} while (0)
/*----------------------------------------.
| Print this symbol's value on YYOUTPUT. |
`----------------------------------------*/
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, struct mdlparse_vars *parse_state, yyscan_t scanner)
{
FILE *yyo = yyoutput;
YYUSE (yyo);
YYUSE (parse_state);
YYUSE (scanner);
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# endif
YYUSE (yytype);
}
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, struct mdlparse_vars *parse_state, yyscan_t scanner)
{
YYFPRINTF (yyoutput, "%s %s (",
yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep, parse_state, scanner);
YYFPRINTF (yyoutput, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
{
int yybot = *yybottom;
YYFPRINTF (stderr, " %d", yybot);
}
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (0)
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
static void
yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule, struct mdlparse_vars *parse_state, yyscan_t scanner)
{
unsigned long int yylno = yyrline[yyrule];
int yynrhs = yyr2[yyrule];
int yyi;
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr,
yystos[yyssp[yyi + 1 - yynrhs]],
&(yyvsp[(yyi + 1) - (yynrhs)])
, parse_state, scanner);
YYFPRINTF (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyssp, yyvsp, Rule, parse_state, scanner); \
} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
static YYSIZE_T
yystrlen (const char *yystr)
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
static char *
yystpcpy (char *yydest, const char *yysrc)
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return yystpcpy (yyres, yystr) - yyres;
}
# endif
/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
about the unexpected token YYTOKEN for the state stack whose top is
YYSSP.
Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is
not large enough to hold the message. In that case, also set
*YYMSG_ALLOC to the required number of bytes. Return 2 if the
required number of bytes is too large to store. */
static int
yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
yytype_int16 *yyssp, int yytoken)
{
YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
YYSIZE_T yysize = yysize0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
/* Internationalized format string. */
const char *yyformat = YY_NULLPTR;
/* Arguments of yyformat. */
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* Number of reported tokens (one for the "unexpected", one per
"expected"). */
int yycount = 0;
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yychar) is if
this state is a consistent state with a default action. Thus,
detecting the absence of a lookahead is sufficient to determine
that there is no unexpected or expected token to report. In that
case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is a
consistent state with a default action. There might have been a
previous inconsistent state, consistent state with a non-default
action, or user semantic action that manipulated yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state merging
(from LALR or IELR) and default reductions corrupt the expected
token list. However, the list is correct for canonical LR with
one exception: it will still contain any token that will not be
accepted due to an error action in a later state.
*/
if (yytoken != YYEMPTY)
{
int yyn = yypact[*yyssp];
yyarg[yycount++] = yytname[yytoken];
if (!yypact_value_is_default (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yyx;
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
&& !yytable_value_is_error (yytable[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
break;
}
yyarg[yycount++] = yytname[yyx];
{
YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
if (! (yysize <= yysize1
&& yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
}
}
}
switch (yycount)
{
# define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
# undef YYCASE_
}
{
YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
if (*yymsg_alloc < yysize)
{
*yymsg_alloc = 2 * yysize;
if (! (yysize <= *yymsg_alloc
&& *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
*yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
return 1;
}
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
{
char *yyp = *yymsg;
int yyi = 0;
while ((*yyp = *yyformat) != '\0')
if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyformat += 2;
}
else
{
yyp++;
yyformat++;
}
}
return 0;
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, struct mdlparse_vars *parse_state, yyscan_t scanner)
{
YYUSE (yyvaluep);
YYUSE (parse_state);
YYUSE (scanner);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
YYUSE (yytype);
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/*----------.
| yyparse. |
`----------*/
int
yyparse (struct mdlparse_vars *parse_state, yyscan_t scanner)
{
/* The lookahead symbol. */
int yychar;
/* The semantic value of the lookahead symbol. */
/* Default value used for initialization, for pacifying older GCCs
or non-GCC compilers. */
YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
/* Number of syntax errors so far. */
int yynerrs;
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
'yyss': related to states.
'yyvs': related to semantic values.
Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken = 0;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yyssp = yyss = yyssa;
yyvsp = yyvs = yyvsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = yylex (&yylval, parse_state, scanner);
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 29:
#line 646 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_object(parse_state, (yyvsp[0].str))); }
#line 2981 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 30:
#line 649 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_region(parse_state, (yyvsp[-3].sym), (yyvsp[-1].str))); }
#line 2987 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 31:
#line 652 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.vec3) = mdl_point(parse_state, &(yyvsp[0].nlist))); }
#line 2993 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 33:
#line 656 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.vec3) = mdl_point_scalar((yyvsp[0].dbl))); }
#line 2999 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 34:
#line 659 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 1; }
#line 3005 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 35:
#line 660 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 3011 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 36:
#line 661 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 1; }
#line 3017 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 37:
#line 662 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 3023 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 38:
#line 663 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 1; }
#line 3029 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 39:
#line 664 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 3035 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 40:
#line 667 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type).orient_set = 0; }
#line 3041 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 43:
#line 670 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type).orient_set = 1; (yyval.mol_type).orient = 0; }
#line 3047 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 44:
#line 674 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type).orient = 1; (yyval.mol_type).orient_set = 1; }
#line 3053 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 45:
#line 675 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type).orient = -1; (yyval.mol_type).orient_set = 1; }
#line 3059 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 46:
#line 676 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.mol_type) = (yyvsp[-1].mol_type);
if ((yyval.mol_type).orient >= 32767)
{
/* Seriously? Wow. */
mdlerror(parse_state, "molecule orientation must not be greater than 32767");
return 1;
}
++ (yyval.mol_type).orient;
}
#line 3074 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 47:
#line 686 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.mol_type) = (yyvsp[-1].mol_type);
if ((yyval.mol_type).orient <= -32768)
{
/* Seriously? Wow. */
mdlerror(parse_state, "molecule orientation must not be less than -32768");
return 1;
}
-- (yyval.mol_type).orient;
}
#line 3089 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 50:
#line 704 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.mol_type).orient = (int) (yyvsp[-1].dbl);
(yyval.mol_type).orient_set = 1;
if ((yyval.mol_type).orient != (yyvsp[-1].dbl))
{
mdlerror(parse_state, "molecule orientation specified inside braces must be an integer between -32768 and 32767.");
return 1;
}
}
#line 3103 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 52:
#line 717 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if ((yyvsp[-2].nlist).value_tail)
{
(yyval.nlist) = (yyvsp[-2].nlist);
(yyval.nlist).value_count += (yyvsp[0].nlist).value_count;
(yyval.nlist).value_tail->next = (yyvsp[0].nlist).value_head;
(yyval.nlist).value_tail = (yyvsp[0].nlist).value_tail;
}
else
(yyval.nlist) = (yyvsp[0].nlist);
}
#line 3119 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 53:
#line 730 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mcell_generate_range_singleton(&(yyval.nlist), (yyvsp[0].dbl))); }
#line 3125 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 54:
#line 731 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_generate_range(parse_state, &(yyval.nlist), (yyvsp[-5].dbl), (yyvsp[-3].dbl), (yyvsp[-1].dbl))); }
#line 3131 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 55:
#line 737 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
char *include_path = mcell_find_include_file((yyvsp[0].str), parse_state->vol->curr_file);
if (include_path == NULL)
{
mdlerror_fmt(parse_state, "Out of memory while trying to open include file '%s'", (yyvsp[0].str));
free((yyvsp[0].str));
return 1;
}
if (mdlparse_file(parse_state, include_path))
{
free(include_path);
free((yyvsp[0].str));
return 1;
}
free(include_path);
free((yyvsp[0].str));
}
#line 3153 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 56:
#line 760 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_assign_variable_double(parse_state, (yyvsp[-2].sym), (yyvsp[0].dbl))); }
#line 3159 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 57:
#line 761 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_assign_variable_string(parse_state, (yyvsp[-2].sym), (yyvsp[0].str))); }
#line 3165 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 58:
#line 762 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_assign_variable(parse_state, (yyvsp[-2].sym), (yyvsp[0].sym))); }
#line 3171 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 59:
#line 763 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_assign_variable_array(parse_state, (yyvsp[-2].sym), (yyvsp[0].nlist).value_head)); }
#line 3177 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 60:
#line 766 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_get_or_create_variable(parse_state, (yyvsp[0].str))); }
#line 3183 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 61:
#line 769 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_variable(parse_state, (yyvsp[0].str))); }
#line 3189 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 63:
#line 773 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
struct num_expr_list *elp;
(yyval.nlist).value_head = (struct num_expr_list *) (yyvsp[0].sym)->value;
(yyval.nlist).value_count = 1;
for (elp = (yyval.nlist).value_head; elp->next != NULL; elp = elp->next)
++ (yyval.nlist).value_count;
(yyval.nlist).value_tail = elp;
(yyval.nlist).shared = 1;
}
#line 3203 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 64:
#line 784 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_debug_dump_array((yyvsp[-1].nlist).value_head); (yyval.nlist) = (yyvsp[-1].nlist); }
#line 3209 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 65:
#line 787 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_array(parse_state, (yyvsp[0].str))); }
#line 3215 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 69:
#line 795 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = *(double *) (yyvsp[0].sym)->value; }
#line 3221 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 70:
#line 798 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = (yyvsp[0].llival); }
#line 3227 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 74:
#line 806 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_double(parse_state, (yyvsp[0].str))); }
#line 3233 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 75:
#line 810 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = (yyvsp[-1].dbl); }
#line 3239 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 76:
#line 811 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKF((yyval.dbl) = exp((yyvsp[-1].dbl))); }
#line 3245 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 77:
#line 812 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_expr_log(parse_state, (yyvsp[-1].dbl), &(yyval.dbl))); }
#line 3251 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 78:
#line 813 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_expr_log10(parse_state, (yyvsp[-1].dbl), &(yyval.dbl))); }
#line 3257 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 79:
#line 814 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = max2d((yyvsp[-3].dbl), (yyvsp[-1].dbl)); }
#line 3263 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 80:
#line 815 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = min2d((yyvsp[-3].dbl), (yyvsp[-1].dbl)); }
#line 3269 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 81:
#line 816 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = mdl_expr_roundoff((yyvsp[-1].dbl), (int) (yyvsp[-3].dbl)); }
#line 3275 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 82:
#line 817 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = floor((yyvsp[-1].dbl)); }
#line 3281 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 83:
#line 818 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = ceil((yyvsp[-1].dbl)); }
#line 3287 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 84:
#line 819 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = sin((yyvsp[-1].dbl)); }
#line 3293 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 85:
#line 820 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = cos((yyvsp[-1].dbl)); }
#line 3299 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 86:
#line 821 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKF((yyval.dbl) = tan((yyvsp[-1].dbl))); }
#line 3305 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 87:
#line 822 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKF((yyval.dbl) = asin((yyvsp[-1].dbl))); }
#line 3311 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 88:
#line 823 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKF((yyval.dbl) = acos((yyvsp[-1].dbl))); }
#line 3317 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 89:
#line 824 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = atan((yyvsp[-1].dbl)); }
#line 3323 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 90:
#line 825 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKF((yyval.dbl) = sqrt((yyvsp[-1].dbl))); }
#line 3329 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 91:
#line 826 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = fabs((yyvsp[-1].dbl)); }
#line 3335 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 92:
#line 827 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_expr_mod(parse_state, (yyvsp[-3].dbl), (yyvsp[-1].dbl), &(yyval.dbl))); }
#line 3341 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 93:
#line 828 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = MY_PI; }
#line 3347 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 94:
#line 829 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = mdl_expr_rng_uniform(parse_state); }
#line 3353 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 95:
#line 830 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = rng_gauss(parse_state->vol->rng); }
#line 3359 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 96:
#line 831 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = parse_state->vol->seed_seq; }
#line 3365 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 97:
#line 832 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_expr_string_to_double(parse_state, (yyvsp[-1].str), &(yyval.dbl))); }
#line 3371 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 98:
#line 833 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKF((yyval.dbl) = (yyvsp[-2].dbl) + (yyvsp[0].dbl)); }
#line 3377 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 99:
#line 834 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKF((yyval.dbl) = (yyvsp[-2].dbl) - (yyvsp[0].dbl)); }
#line 3383 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 100:
#line 835 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKF((yyval.dbl) = (yyvsp[-2].dbl) * (yyvsp[0].dbl)); }
#line 3389 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 101:
#line 836 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_expr_div(parse_state, (yyvsp[-2].dbl), (yyvsp[0].dbl), &(yyval.dbl))); }
#line 3395 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 102:
#line 837 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_expr_pow(parse_state, (yyvsp[-2].dbl), (yyvsp[0].dbl), &(yyval.dbl))); }
#line 3401 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 103:
#line 838 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = -(yyvsp[0].dbl); }
#line 3407 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 104:
#line 839 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = (yyvsp[0].dbl); }
#line 3413 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 106:
#line 844 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.str) = mdl_strdup((char const *) (yyvsp[0].sym)->value)); }
#line 3419 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 107:
#line 848 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.str) = mdl_strip_quotes((yyvsp[0].str))); }
#line 3425 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 108:
#line 849 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.str) = mdl_strdup(parse_state->vol->mdl_infile_name)); }
#line 3431 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 109:
#line 850 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.str) = mdl_strcat((yyvsp[-2].str), (yyvsp[0].str))); }
#line 3437 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 110:
#line 851 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.str) = mdl_string_format(parse_state, (yyvsp[-2].str), (yyvsp[-1].printfargs).arg_head)); }
#line 3443 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 111:
#line 854 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_string(parse_state, (yyvsp[0].str))); }
#line 3449 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 119:
#line 870 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_fopen(parse_state, (yyvsp[-6].sym), (yyvsp[-3].str), (yyvsp[-1].str))); }
#line 3455 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 120:
#line 873 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_new_filehandle(parse_state, (yyvsp[0].str))); }
#line 3461 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 121:
#line 876 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.str) = (yyvsp[0].str); CHECK(mdl_valid_file_mode(parse_state, (yyvsp[0].str))); }
#line 3467 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 122:
#line 879 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_fclose(parse_state, (yyvsp[-1].sym))); }
#line 3473 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 123:
#line 882 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_file_stream(parse_state, (yyvsp[0].str))); }
#line 3479 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 124:
#line 885 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.str) = mdl_expand_string_escapes((yyvsp[0].str))); }
#line 3485 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 125:
#line 888 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.printfargs).arg_head = (yyval.printfargs).arg_tail = NULL; }
#line 3491 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 126:
#line 889 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.printfargs) = (yyvsp[-2].printfargs);
if ((yyval.printfargs).arg_tail)
(yyval.printfargs).arg_tail = (yyval.printfargs).arg_tail->next = (yyvsp[0].printfarg);
else
(yyval.printfargs).arg_tail = (yyval.printfargs).arg_head = (yyvsp[0].printfarg);
(yyvsp[0].printfarg)->next = NULL;
}
#line 3504 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 127:
#line 899 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.printfarg) = mdl_new_printf_arg_double((yyvsp[0].dbl))); }
#line 3510 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 128:
#line 900 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.printfarg) = mdl_new_printf_arg_string((yyvsp[0].str))); }
#line 3516 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 129:
#line 901 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
switch ((yyvsp[0].sym)->sym_type)
{
case DBL: CHECKN((yyval.printfarg) = mdl_new_printf_arg_double(*(double *) (yyvsp[0].sym)->value)); break;
case STR: CHECKN((yyval.printfarg) = mdl_new_printf_arg_string((char *) (yyvsp[0].sym)->value)); break;
default:
mdlerror(parse_state, "invalid variable type referenced");
return 1;
}
}
#line 3531 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 130:
#line 913 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_printf(parse_state, (yyvsp[-2].str), (yyvsp[-1].printfargs).arg_head)); }
#line 3537 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 131:
#line 919 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_fprintf(parse_state, (struct file_stream *) (yyvsp[-4].sym)->value, (yyvsp[-2].str), (yyvsp[-1].printfargs).arg_head)); }
#line 3543 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 132:
#line 925 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_sprintf(parse_state, (yyvsp[-4].sym), (yyvsp[-2].str), (yyvsp[-1].printfargs).arg_head)); }
#line 3549 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 133:
#line 928 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_print_time(parse_state, (yyvsp[-1].str)); }
#line 3555 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 134:
#line 934 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_fprint_time(parse_state, (yyvsp[-3].sym), (yyvsp[-1].str))); }
#line 3561 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 138:
#line 950 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) mdl_set_all_notifications(parse_state->vol, (yyvsp[0].tok)); }
#line 3567 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 139:
#line 951 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->progress_report = (yyvsp[0].tok); }
#line 3573 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 140:
#line 952 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->diffusion_constants = (yyvsp[0].tok); }
#line 3579 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 141:
#line 953 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->reaction_probabilities = (yyvsp[0].tok); }
#line 3585 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 142:
#line 954 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->time_varying_reactions = (yyvsp[0].tok); }
#line 3591 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 143:
#line 955 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->reaction_prob_notify = (yyvsp[0].dbl); }
#line 3597 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 144:
#line 956 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->partition_location = (yyvsp[0].tok); }
#line 3603 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 145:
#line 957 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->box_triangulation = (yyvsp[0].tok); }
#line 3609 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 146:
#line 958 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->release_events = (yyvsp[0].tok); }
#line 3615 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 147:
#line 959 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->file_writes = (yyvsp[0].tok); }
#line 3621 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 148:
#line 960 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->final_summary = (yyvsp[0].tok); }
#line 3627 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 149:
#line 961 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->throughput_report = (yyvsp[0].tok); }
#line 3633 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 150:
#line 962 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->reaction_output_report = (yyvsp[0].tok); }
#line 3639 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 151:
#line 963 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->volume_output_report = (yyvsp[0].tok); }
#line 3645 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 152:
#line 964 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->viz_output_report = (yyvsp[0].tok); }
#line 3651 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 153:
#line 965 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->checkpoint_report = (yyvsp[0].tok); }
#line 3657 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 154:
#line 966 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if (!parse_state->vol->quiet_flag && parse_state->vol->log_freq == ULONG_MAX)
parse_state->vol->notify->iteration_report = (yyvsp[0].tok);
}
#line 3666 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 155:
#line 970 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) CHECK(mdl_set_iteration_report_freq(parse_state, (long long) (yyvsp[0].dbl))); }
#line 3672 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 156:
#line 971 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ if (!parse_state->vol->quiet_flag) parse_state->vol->notify->molecule_collision_report = (yyvsp[0].tok); }
#line 3678 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 157:
#line 975 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = ((yyvsp[0].tok) ? NOTIFY_FULL : NOTIFY_NONE); }
#line 3684 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 158:
#line 979 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = ((yyvsp[0].tok) ? NOTIFY_FULL : NOTIFY_NONE); }
#line 3690 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 159:
#line 980 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = NOTIFY_BRIEF; }
#line 3696 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 163:
#line 996 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_set_all_warnings(parse_state->vol, (byte) (yyvsp[0].tok)); }
#line 3702 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 164:
#line 997 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->neg_diffusion = (byte)(yyvsp[0].tok); }
#line 3708 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 165:
#line 998 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->neg_reaction = (byte)(yyvsp[0].tok); }
#line 3714 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 166:
#line 999 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->high_reaction_prob = (byte)(yyvsp[0].tok); }
#line 3720 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 167:
#line 1000 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->reaction_prob_warn = (yyvsp[0].dbl); }
#line 3726 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 168:
#line 1001 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->close_partitions = (byte)(yyvsp[0].tok); }
#line 3732 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 169:
#line 1002 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->degenerate_polys = (byte)(yyvsp[0].tok); }
#line 3738 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 170:
#line 1003 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->overwritten_file = (byte)(yyvsp[0].tok); }
#line 3744 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 171:
#line 1004 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->short_lifetime = (byte)(yyvsp[0].tok); }
#line 3750 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 172:
#line 1005 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_lifetime_warning_threshold(parse_state, (long long) (yyvsp[0].dbl))); }
#line 3756 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 173:
#line 1006 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->missed_reactions = (byte)(yyvsp[0].tok); }
#line 3762 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 174:
#line 1007 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_missed_reaction_warning_threshold(parse_state, (yyvsp[0].dbl))); }
#line 3768 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 175:
#line 1008 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->missed_surf_orient = (byte)(yyvsp[0].tok); }
#line 3774 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 176:
#line 1009 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->useless_vol_orient = (byte)(yyvsp[0].tok); }
#line 3780 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 177:
#line 1010 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->mol_placement_failure = (byte) (yyvsp[0].tok); }
#line 3786 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 178:
#line 1011 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->invalid_output_step_time = (byte) (yyvsp[0].tok); }
#line 3792 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 179:
#line 1012 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->large_molecular_displacement = (byte) (yyvsp[0].tok); }
#line 3798 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 180:
#line 1013 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->notify->add_remove_mesh_warning = (byte) (yyvsp[0].tok); }
#line 3804 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 181:
#line 1017 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = WARN_COPE; }
#line 3810 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 182:
#line 1018 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = WARN_WARN; }
#line 3816 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 183:
#line 1019 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = WARN_ERROR; }
#line 3822 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 184:
#line 1025 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_checkpoint_infile(parse_state, (yyvsp[0].str))); }
#line 3828 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 185:
#line 1026 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_checkpoint_outfile(parse_state, (yyvsp[0].str))); }
#line 3834 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 186:
#line 1027 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_checkpoint_interval(parse_state, (yyvsp[-1].dbl), (yyvsp[0].tok))); }
#line 3840 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 187:
#line 1028 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_keep_checkpoint_files(parse_state, (yyvsp[0].tok))); }
#line 3846 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 188:
#line 1030 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_realtime_checkpoint(parse_state, (long) (yyvsp[-1].dbl), (yyvsp[0].tok))); }
#line 3852 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 189:
#line 1033 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 3858 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 190:
#line 1034 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 1; }
#line 3864 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 191:
#line 1035 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 3870 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 192:
#line 1039 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ /* seconds */ (yyval.dbl) = (yyvsp[0].dbl); }
#line 3876 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 193:
#line 1040 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ /* mm:ss */ (yyval.dbl) = (yyvsp[-2].dbl) * 60 + (yyvsp[0].dbl); }
#line 3882 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 194:
#line 1041 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ /* hh:mm:ss */ (yyval.dbl) = (yyvsp[-4].dbl) * 3600 + (yyvsp[-2].dbl) * 60 + (yyvsp[0].dbl); }
#line 3888 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 195:
#line 1043 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ /* dd:hh:mm:ss */ (yyval.dbl) = (yyvsp[-6].dbl) * 86400 + (yyvsp[-4].dbl) * 3600 + (yyvsp[-2].dbl) * 60 + (yyvsp[0].dbl); }
#line 3894 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 196:
#line 1050 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_time_step(parse_state, (yyvsp[0].dbl))); }
#line 3900 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 197:
#line 1051 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_space_step(parse_state, (yyvsp[0].dbl))); }
#line 3906 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 198:
#line 1052 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_max_time_step(parse_state, (yyvsp[0].dbl))); }
#line 3912 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 199:
#line 1053 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_num_iterations(parse_state, (long long) (yyvsp[0].dbl))); }
#line 3918 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 200:
#line 1054 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->randomize_smol_pos = !((yyvsp[0].tok)); }
#line 3924 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 201:
#line 1055 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->use_expanded_list = (yyvsp[0].tok); }
#line 3930 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 202:
#line 1056 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->vacancy_search_dist2 = max2d((yyvsp[0].dbl), 0.0); }
#line 3936 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 203:
#line 1057 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_num_radial_directions(parse_state, (int) (yyvsp[0].dbl))); }
#line 3942 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 204:
#line 1058 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->fully_random = 1; }
#line 3948 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 205:
#line 1059 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_num_radial_subdivisions(parse_state, (int) (yyvsp[0].dbl))); }
#line 3954 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 206:
#line 1060 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_grid_density(parse_state, (yyvsp[0].dbl))); }
#line 3960 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 207:
#line 1061 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_interaction_radius(parse_state, (yyvsp[0].dbl))); }
#line 3966 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 208:
#line 1062 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->surface_reversibility=(yyvsp[0].tok); parse_state->vol->volume_reversibility=(yyvsp[0].tok); }
#line 3972 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 209:
#line 1063 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->surface_reversibility=1; parse_state->vol->volume_reversibility=0; }
#line 3978 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 210:
#line 1064 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->surface_reversibility=0; parse_state->vol->volume_reversibility=1; }
#line 3984 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 211:
#line 1065 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mcell_add_dynamic_geometry_file((yyvsp[0].str), parse_state)); }
#line 3990 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 212:
#line 1066 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->dynamic_geometry_molecule_placement = 0; }
#line 3996 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 213:
#line 1067 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->dynamic_geometry_molecule_placement = 1; }
#line 4002 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 214:
#line 1074 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->mem_part_x = (int) (yyvsp[0].dbl); }
#line 4008 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 215:
#line 1075 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->mem_part_y = (int) (yyvsp[0].dbl); }
#line 4014 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 216:
#line 1076 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->mem_part_z = (int) (yyvsp[0].dbl); }
#line 4020 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 217:
#line 1077 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->mem_part_pool = (int) (yyvsp[0].dbl); }
#line 4026 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 218:
#line 1081 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mcell_set_partition(parse_state->vol, (yyvsp[-2].tok), & (yyvsp[0].nlist))); }
#line 4032 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 219:
#line 1085 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = X_PARTS; }
#line 4038 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 220:
#line 1086 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = Y_PARTS; }
#line 4044 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 221:
#line 1087 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = Z_PARTS; }
#line 4050 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 224:
#line 1098 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_print_species_summary(parse_state->vol, (yyvsp[0].mcell_mol_spec)); }
#line 4056 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 225:
#line 1102 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_print_species_summaries(parse_state->vol, (yyvsp[-1].mcell_species_lst).species_head); }
#line 4062 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 226:
#line 1106 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mcell_species_lst).species_count = 0; CHECK(mdl_add_to_species_list(&(yyval.mcell_species_lst), (yyvsp[0].mcell_mol_spec))); }
#line 4068 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 227:
#line 1107 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mcell_species_lst) = (yyvsp[-1].mcell_species_lst); CHECK(mdl_add_to_species_list(&(yyval.mcell_species_lst), (yyvsp[0].mcell_mol_spec))); }
#line 4074 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 228:
#line 1117 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.mcell_mol_spec) = mdl_create_species(parse_state, (yyvsp[-7].str), (yyvsp[-5].diff_const).D, (yyvsp[-5].diff_const).is_2d, (yyvsp[-4].dbl), (yyvsp[-3].ival), (yyvsp[-2].dbl), (yyvsp[-1].ival) )); }
#line 4080 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 230:
#line 1123 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_new_mol_species(parse_state, (yyvsp[0].str))); }
#line 4086 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 231:
#line 1127 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.diff_const).is_2d = 0; (yyval.diff_const).D = (yyvsp[0].dbl); CHECK(mdl_check_diffusion_constant(parse_state, & (yyval.diff_const).D)); }
#line 4092 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 232:
#line 1128 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.diff_const).is_2d = 1; (yyval.diff_const).D = (yyvsp[0].dbl); CHECK(mdl_check_diffusion_constant(parse_state, & (yyval.diff_const).D)); }
#line 4098 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 233:
#line 1132 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = 0.0; }
#line 4104 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 234:
#line 1133 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if ((yyvsp[0].dbl) <= 0)
{
mdlerror_fmt(parse_state, "Requested custom time step of %.15g; custom time step must be positive.", (yyvsp[0].dbl));
return 1;
}
(yyval.dbl) = (yyvsp[0].dbl);
}
#line 4118 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 235:
#line 1142 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if ((yyvsp[0].dbl) <= 0)
{
mdlerror_fmt(parse_state, "Requested custom space step of %.15g; custom space step must be positive.", (yyvsp[0].dbl));
return 1;
}
(yyval.dbl) = -(yyvsp[0].dbl);
}
#line 4132 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 236:
#line 1153 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ival) = 0; }
#line 4138 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 237:
#line 1154 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ival) = 1; }
#line 4144 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 238:
#line 1158 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = 0; }
#line 4150 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 239:
#line 1159 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if ((yyvsp[0].dbl) <= 0)
{
mdlerror_fmt(parse_state, "Requested maximum step length of %.15g; maximum step length must be positive.", (yyvsp[0].dbl));
return 1;
}
(yyval.dbl) = (yyvsp[0].dbl);
}
#line 4163 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 240:
#line 1169 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{(yyval.ival) = 0;}
#line 4169 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 241:
#line 1170 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{(yyval.ival) = 1;}
#line 4175 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 242:
#line 1173 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_molecule(parse_state, (yyvsp[0].str))); }
#line 4181 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 243:
#line 1177 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type) = (yyvsp[0].mol_type); CHECKN((yyval.mol_type).mol_type = mdl_existing_surface_molecule(parse_state, (yyvsp[-1].str))); }
#line 4187 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 244:
#line 1181 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.mol_type) = (yyvsp[0].mol_type);
if (! (yyval.mol_type).orient_set)
(yyval.mol_type).orient = 0;
(yyval.mol_type).mol_type = (yyvsp[-1].sym);
}
#line 4198 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 251:
#line 1216 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_start_surface_class(parse_state, (yyvsp[-1].sym)); }
#line 4204 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 252:
#line 1218 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_finish_surface_class(parse_state); }
#line 4210 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 253:
#line 1221 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_surface_class(parse_state, (yyvsp[0].str))); }
#line 4216 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 258:
#line 1238 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN(mdl_assemble_surface_reaction(parse_state, (yyvsp[-2].tok), parse_state->current_surface_class, (yyvsp[0].mol_type).mol_type, (yyvsp[0].mol_type).orient)); }
#line 4222 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 259:
#line 1241 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
struct sym_entry *mol_sym = retrieve_sym("ALL_MOLECULES", parse_state->vol->mol_sym_table);
if(!(yyvsp[0].mol_type).orient_set) (yyvsp[0].mol_type).orient = 0;
CHECKN(mdl_assemble_surface_reaction(parse_state, (yyvsp[-3].tok), parse_state->current_surface_class, mol_sym, (yyvsp[0].mol_type).orient));}
#line 4231 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 260:
#line 1247 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN(mdl_assemble_concentration_clamp_reaction(parse_state, parse_state->current_surface_class, (yyvsp[-2].mol_type).mol_type, (yyvsp[-2].mol_type).orient, (yyvsp[0].dbl))); }
#line 4237 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 261:
#line 1250 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = RFLCT; }
#line 4243 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 262:
#line 1251 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = TRANSP; }
#line 4249 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 263:
#line 1252 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = SINK; }
#line 4255 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 266:
#line 1259 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_surface_class->sm_dat_head = (yyvsp[0].surf_mol_dat_list).sm_head; }
#line 4261 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 267:
#line 1266 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.surf_mol_dat_list) = (yyvsp[-1].surf_mol_dat_list); }
#line 4267 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 268:
#line 1270 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.surf_mol_dat_list) = (yyvsp[-1].surf_mol_dat_list); }
#line 4273 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 269:
#line 1274 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyvsp[0].surf_mol_dat)->quantity_type = SURFMOLDENS;
(yyval.surf_mol_dat_list).sm_tail = (yyval.surf_mol_dat_list).sm_head = (yyvsp[0].surf_mol_dat);
}
#line 4282 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 270:
#line 1279 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.surf_mol_dat_list) = (yyvsp[-1].surf_mol_dat_list);
(yyvsp[0].surf_mol_dat)->quantity_type = SURFMOLDENS;
(yyval.surf_mol_dat_list).sm_tail = (yyval.surf_mol_dat_list).sm_tail->next = (yyvsp[0].surf_mol_dat);
}
#line 4292 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 271:
#line 1287 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyvsp[0].surf_mol_dat)->quantity_type = SURFMOLNUM;
(yyval.surf_mol_dat_list).sm_tail = (yyval.surf_mol_dat_list).sm_head = (yyvsp[0].surf_mol_dat);
}
#line 4301 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 272:
#line 1292 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.surf_mol_dat_list) = (yyvsp[-1].surf_mol_dat_list);
(yyvsp[0].surf_mol_dat)->quantity_type = SURFMOLNUM;
(yyval.surf_mol_dat_list).sm_tail = (yyval.surf_mol_dat_list).sm_tail->next = (yyvsp[0].surf_mol_dat);
}
#line 4311 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 273:
#line 1300 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.surf_mol_dat) = mdl_new_surf_mol_data(parse_state, &(yyvsp[-2].mol_type), (yyvsp[0].dbl))); }
#line 4317 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 283:
#line 1329 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.react_arrow).catalyst = (yyvsp[-1].mol_type); (yyval.react_arrow).flags = ARROW_CATALYTIC; }
#line 4323 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 284:
#line 1334 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.react_arrow).catalyst = (yyvsp[-1].mol_type); (yyval.react_arrow).flags = ARROW_CATALYTIC | ARROW_BIDIRECTIONAL; }
#line 4329 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 285:
#line 1339 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.react_arrow).catalyst.mol_type = NULL; (yyval.react_arrow).flags = 0; }
#line 4335 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 287:
#line 1341 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.react_arrow).catalyst.mol_type = NULL; (yyval.react_arrow).flags = ARROW_BIDIRECTIONAL; }
#line 4341 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 289:
#line 1345 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.sym) = NULL; }
#line 4347 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 290:
#line 1346 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_new_rxn_pathname(parse_state, (yyvsp[0].str))); }
#line 4353 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 291:
#line 1352 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN(mdl_assemble_reaction(parse_state, (yyvsp[-5].mol_type_list).mol_type_head, &(yyvsp[-4].mol_type), &(yyvsp[-3].react_arrow), (yyvsp[-2].mol_type_list).mol_type_head, &(yyvsp[-1].react_rates), (yyvsp[0].sym))); }
#line 4359 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 292:
#line 1355 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_reaction_player_singleton(parse_state, & (yyval.mol_type_list), & (yyvsp[0].mol_type))); }
#line 4365 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 293:
#line 1356 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type_list) = (yyvsp[-2].mol_type_list); CHECK(mdl_add_reaction_player(parse_state, & (yyval.mol_type_list), & (yyvsp[0].mol_type))); }
#line 4371 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 295:
#line 1363 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type).mol_type = NULL; }
#line 4377 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 296:
#line 1364 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type) = (yyvsp[0].mol_type); }
#line 4383 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 297:
#line 1368 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type) = (yyvsp[0].mol_type); (yyval.mol_type).mol_type = (yyvsp[-1].sym); }
#line 4389 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 298:
#line 1371 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_reaction_player_singleton(parse_state, & (yyval.mol_type_list), & (yyvsp[0].mol_type))); }
#line 4395 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 299:
#line 1372 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type_list) = (yyvsp[-2].mol_type_list); CHECK(mdl_add_reaction_player(parse_state, & (yyval.mol_type_list), & (yyvsp[0].mol_type))); }
#line 4401 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 300:
#line 1375 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.mol_type).mol_type = NULL; (yyval.mol_type).orient_set = 0; }
#line 4407 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 304:
#line 1384 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if ((yyvsp[-1].react_rates).forward_rate.rate_type == RATE_UNSET)
{
mdlerror(parse_state, "invalid reaction rate specification: must specify a forward rate.");
return 1;
}
(yyval.react_rates) = (yyvsp[-1].react_rates);
}
#line 4421 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 305:
#line 1395 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if (((yyvsp[-3].react_rates).forward_rate.rate_type != RATE_UNSET && (yyvsp[-1].react_rates).forward_rate.rate_type != RATE_UNSET) ||
((yyvsp[-3].react_rates).backward_rate.rate_type != RATE_UNSET && (yyvsp[-1].react_rates).backward_rate.rate_type != RATE_UNSET))
{
mdlerror_fmt(parse_state, "when two reaction rates are specified, one must be a forward rate, and one must be a reverse rate");
return 1;
}
(yyval.react_rates) = (yyvsp[-3].react_rates);
if ((yyvsp[-1].react_rates).forward_rate.rate_type != RATE_UNSET)
(yyval.react_rates).forward_rate = (yyvsp[-1].react_rates).forward_rate;
else
(yyval.react_rates).backward_rate = (yyvsp[-1].react_rates).backward_rate;
}
#line 4440 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 306:
#line 1412 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.react_rates).forward_rate = (yyvsp[0].react_rate); (yyval.react_rates).backward_rate.rate_type = RATE_UNSET; CHECK(mdl_valid_rate(parse_state, &(yyvsp[0].react_rate))); }
#line 4446 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 307:
#line 1413 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.react_rates).forward_rate = (yyvsp[0].react_rate); (yyval.react_rates).backward_rate.rate_type = RATE_UNSET; CHECK(mdl_valid_rate(parse_state, &(yyvsp[0].react_rate))); }
#line 4452 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 308:
#line 1414 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.react_rates).backward_rate = (yyvsp[0].react_rate); (yyval.react_rates).forward_rate.rate_type = RATE_UNSET; CHECK(mdl_valid_rate(parse_state, &(yyvsp[0].react_rate))); }
#line 4458 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 309:
#line 1418 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.react_rate).rate_type = RATE_CONSTANT; (yyval.react_rate).v.rate_constant = (yyvsp[0].dbl); }
#line 4464 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 310:
#line 1419 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.react_rate).rate_type = RATE_FILE; (yyval.react_rate).v.rate_file = (yyvsp[0].str); }
#line 4470 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 311:
#line 1420 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_reaction_rate_from_var(parse_state, & (yyval.react_rate), (yyvsp[0].sym))); }
#line 4476 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 312:
#line 1431 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_pattern(parse_state, (yyvsp[-3].sym), &(yyvsp[-1].rpat))); }
#line 4482 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 313:
#line 1434 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_new_release_pattern(parse_state, (yyvsp[0].str))); }
#line 4488 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 314:
#line 1437 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_release_pattern_or_rxn_pathname(parse_state, (yyvsp[0].str))); }
#line 4494 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 315:
#line 1441 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.rpat).delay = 0;
(yyval.rpat).release_interval = FOREVER;
(yyval.rpat).train_interval = FOREVER;
(yyval.rpat).train_duration = FOREVER;
(yyval.rpat).number_of_trains = 1;
}
#line 4506 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 316:
#line 1449 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.rpat) = (yyvsp[-3].rpat); (yyval.rpat).delay = (yyvsp[0].dbl) / parse_state->vol->time_unit; }
#line 4512 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 317:
#line 1451 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.rpat) = (yyvsp[-3].rpat); (yyval.rpat).release_interval = (yyvsp[0].dbl) / parse_state->vol->time_unit; }
#line 4518 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 318:
#line 1453 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.rpat) = (yyvsp[-3].rpat); (yyval.rpat).train_interval = (yyvsp[0].dbl) / parse_state->vol->time_unit; }
#line 4524 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 319:
#line 1455 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.rpat) = (yyvsp[-3].rpat); (yyval.rpat).train_duration = (yyvsp[0].dbl) / parse_state->vol->time_unit; }
#line 4530 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 320:
#line 1457 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.rpat) = (yyvsp[-3].rpat); (yyval.rpat).number_of_trains = (yyvsp[0].ival); }
#line 4536 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 321:
#line 1460 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ival) = (int) (yyvsp[0].dbl); }
#line 4542 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 322:
#line 1461 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ival) = INT_MAX; }
#line 4548 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 323:
#line 1468 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_object = parse_state->vol->root_instance; }
#line 4554 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 324:
#line 1469 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
check_regions(parse_state->vol->root_instance, (yyvsp[0].obj));
add_child_objects(parse_state->vol->root_instance, (yyvsp[0].obj), (yyvsp[0].obj));
parse_state->current_object = parse_state->vol->root_object;
}
#line 4564 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 325:
#line 1479 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ add_child_objects(parse_state->vol->root_object, (yyvsp[0].obj), (yyvsp[0].obj)); }
#line 4570 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 331:
#line 1495 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_start_object(parse_state, (yyvsp[0].str))); }
#line 4576 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 333:
#line 1501 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_finish_object(parse_state); }
#line 4582 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 337:
#line 1514 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ transform_translate(parse_state->vol, parse_state->current_object->t_matrix, (yyvsp[0].vec3)); }
#line 4588 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 338:
#line 1515 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ transform_scale(parse_state->current_object->t_matrix, (yyvsp[0].vec3)); }
#line 4594 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 339:
#line 1516 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_transform_rotate(parse_state, parse_state->current_object->t_matrix, (yyvsp[-2].vec3), (yyvsp[0].dbl))); }
#line 4600 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 340:
#line 1525 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
struct geom_object *the_object = (struct geom_object *) (yyvsp[-5].sym)->value;
the_object->object_type = META_OBJ;
add_child_objects(the_object, (yyvsp[-2].obj_list).obj_head, (yyvsp[-2].obj_list).obj_tail);
(yyval.obj) = the_object;
}
#line 4611 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 341:
#line 1534 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_object_list_singleton(& (yyval.obj_list), (yyvsp[0].obj)); }
#line 4617 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 342:
#line 1535 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.obj_list) = (yyvsp[-1].obj_list); mdl_add_object_to_list(& (yyval.obj_list), (yyvsp[0].obj)); }
#line 4623 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 345:
#line 1544 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_deep_copy_object(parse_state, (struct geom_object *) (yyvsp[-3].sym)->value, (struct geom_object *) (yyvsp[-1].sym)->value)); }
#line 4629 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 346:
#line 1546 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.obj) = (struct geom_object *) (yyvsp[-6].sym)->value; }
#line 4635 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 349:
#line 1556 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_start_release_site(parse_state, (yyvsp[-2].sym), SHAPE_UNDEFINED)); }
#line 4641 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 350:
#line 1560 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.obj) = mdl_finish_release_site(parse_state, (yyvsp[-7].sym))); }
#line 4647 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 351:
#line 1563 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_geometry_region(parse_state, parse_state->current_release_site, parse_state->current_object, (yyvsp[0].rev))); }
#line 4653 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 352:
#line 1564 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_geometry_object(parse_state, parse_state->current_release_site, (struct geom_object *) (yyvsp[0].sym)->value)); }
#line 4659 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 353:
#line 1565 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_release_site->release_shape = SHAPE_SPHERICAL; }
#line 4665 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 354:
#line 1566 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_release_site->release_shape = SHAPE_CUBIC; }
#line 4671 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 355:
#line 1567 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_release_site->release_shape = SHAPE_ELLIPTIC; }
#line 4677 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 356:
#line 1568 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_release_site->release_shape = SHAPE_RECTANGULAR; }
#line 4683 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 357:
#line 1569 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_release_site->release_shape = SHAPE_SPHERICAL_SHELL; }
#line 4689 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 358:
#line 1570 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
parse_state->current_release_site->release_shape = SHAPE_LIST;
parse_state->current_release_site->release_number_method = CONSTNUM;
}
#line 4698 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 359:
#line 1577 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.rev) = new_release_region_expr_term((yyvsp[0].sym))); }
#line 4704 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 360:
#line 1578 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.rev) = (yyvsp[-1].rev); }
#line 4710 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 361:
#line 1579 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.rev) = new_release_region_expr_binary((yyvsp[-2].rev), (yyvsp[0].rev), REXP_UNION)); }
#line 4716 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 362:
#line 1580 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.rev) = new_release_region_expr_binary((yyvsp[-2].rev), (yyvsp[0].rev), REXP_SUBTRACTION)); }
#line 4722 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 363:
#line 1581 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.rev) = new_release_region_expr_binary((yyvsp[-2].rev), (yyvsp[0].rev), REXP_INTERSECTION)); }
#line 4728 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 364:
#line 1586 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_start_release_site(parse_state, (yyvsp[-2].sym), (yyvsp[-1].tok))); }
#line 4734 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 365:
#line 1589 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.obj) = mdl_finish_release_site(parse_state, (yyvsp[-6].sym))); }
#line 4740 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 366:
#line 1592 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = SHAPE_SPHERICAL; }
#line 4746 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 367:
#line 1593 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = SHAPE_CUBIC; }
#line 4752 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 368:
#line 1594 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = SHAPE_ELLIPTIC; }
#line 4758 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 369:
#line 1595 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = SHAPE_RECTANGULAR; }
#line 4764 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 370:
#line 1596 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = SHAPE_SPHERICAL_SHELL; }
#line 4770 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 373:
#line 1604 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_num_or_array(parse_state, (yyvsp[0].str))); }
#line 4776 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 374:
#line 1608 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ set_release_site_location(parse_state->vol, parse_state->current_release_site, (yyvsp[0].vec3)); }
#line 4782 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 375:
#line 1609 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_molecule(parse_state, parse_state->current_release_site, & (yyvsp[0].mol_type))); }
#line 4788 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 376:
#line 1610 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if (parse_state->current_release_site->release_shape == SHAPE_LIST)
{
mdlerror(parse_state, "molecules are already specified in a list--cannot set number or density.");
return 1;
}
}
#line 4800 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 377:
#line 1617 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_diameter(parse_state, parse_state->current_release_site, (yyvsp[0].dbl) * (((yyvsp[-2].tok) == SITE_RADIUS) ? 2.0 : 1.0))); }
#line 4806 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 378:
#line 1618 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_diameter_array(parse_state, parse_state->current_release_site, (yyvsp[0].nlist).value_count, (yyvsp[0].nlist).value_head, ((yyvsp[-2].tok) == SITE_RADIUS) ? 2.0 : 1.0)); }
#line 4812 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 379:
#line 1619 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_diameter_var(parse_state, parse_state->current_release_site, ((yyvsp[-2].tok) == SITE_RADIUS) ? 2.0 : 1.0, (yyvsp[0].sym))); }
#line 4818 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 380:
#line 1620 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_periodic_box(parse_state, parse_state->current_release_site, (yyvsp[0].vec3))); }
#line 4824 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 381:
#line 1621 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_probability(parse_state, parse_state->current_release_site, (yyvsp[0].dbl))); }
#line 4830 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 382:
#line 1623 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_pattern(parse_state, parse_state->current_release_site, (yyvsp[0].sym))); }
#line 4836 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 383:
#line 1625 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_molecule_positions(parse_state, parse_state->current_release_site, & (yyvsp[-1].rsm_list))); }
#line 4842 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 384:
#line 1626 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{CHECK(mdl_set_release_site_graph_pattern(parse_state, parse_state->current_release_site, (yyvsp[0].str))); }
#line 4848 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 385:
#line 1630 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = SITE_DIAMETER; }
#line 4854 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 386:
#line 1631 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = SITE_RADIUS; }
#line 4860 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 391:
#line 1643 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ set_release_site_constant_number(parse_state->current_release_site, (yyvsp[0].dbl)); }
#line 4866 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 392:
#line 1646 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ set_release_site_constant_number(parse_state->current_release_site, (yyvsp[-1].dbl)); }
#line 4872 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 393:
#line 1653 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ set_release_site_gaussian_number(parse_state->current_release_site, (yyvsp[-4].dbl), (yyvsp[-1].dbl)); }
#line 4878 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 394:
#line 1661 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ set_release_site_volume_dependent_number(parse_state->current_release_site, (yyvsp[-7].dbl), (yyvsp[-4].dbl), (yyvsp[-1].dbl)); }
#line 4884 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 395:
#line 1665 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_release_site_concentration(parse_state, parse_state->current_release_site, (yyvsp[0].dbl))); }
#line 4890 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 396:
#line 1666 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(set_release_site_density(parse_state->current_release_site, (yyvsp[0].dbl))); }
#line 4896 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 397:
#line 1670 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ release_single_molecule_singleton(& (yyval.rsm_list), (yyvsp[0].rsm)); }
#line 4902 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 398:
#line 1672 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.rsm_list) = (yyvsp[-1].rsm_list); add_release_single_molecule_to_list(& (yyval.rsm_list), (yyvsp[0].rsm)); }
#line 4908 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 399:
#line 1676 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.rsm) = mdl_new_release_single_molecule(parse_state, &(yyvsp[-1].mol_type), (yyvsp[0].vec3))); }
#line 4914 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 401:
#line 1687 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
CHECKN((yyval.obj) = mdl_new_polygon_list(
parse_state, (yyvsp[-4].str), (yyvsp[-1].vertlist).vertex_count, (yyvsp[-1].vertlist).vertex_head,
(yyvsp[0].ecl).connection_count, (yyvsp[0].ecl).connection_head));
}
#line 4924 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 402:
#line 1696 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.obj) = (struct geom_object *) (yyvsp[-3].obj);
CHECK(mdl_finish_polygon_list(parse_state, (yyval.obj)));
}
#line 4933 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 403:
#line 1702 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.vertlist) = (yyvsp[-1].vertlist); }
#line 4939 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 404:
#line 1705 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.vertlistitem) = mdl_new_vertex_list_item((yyvsp[0].vec3))); }
#line 4945 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 405:
#line 1708 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_vertex_list_singleton(& (yyval.vertlist), (yyvsp[0].vertlistitem)); }
#line 4951 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 406:
#line 1709 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.vertlist) = (yyvsp[-1].vertlist); mdl_add_vertex_to_list(& (yyval.vertlist), (yyvsp[0].vertlistitem)); }
#line 4957 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 407:
#line 1714 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ecl) = (yyvsp[-1].ecl); }
#line 4963 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 408:
#line 1718 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_element_connection_list_singleton(& (yyval.ecl), (yyvsp[0].elem_conn)); }
#line 4969 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 409:
#line 1720 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ecl) = (yyvsp[-1].ecl); mdl_add_element_connection_to_list(& (yyval.ecl), (yyvsp[0].elem_conn)); }
#line 4975 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 410:
#line 1723 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.elem_conn) = mdl_new_element_connection(parse_state, & (yyvsp[0].nlist))); }
#line 4981 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 415:
#line 1739 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN(parse_state->current_region = mdl_get_region(parse_state, parse_state->current_object, "REMOVED")); }
#line 4987 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 416:
#line 1741 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
parse_state->current_region->element_list_head = (yyvsp[-1].elem_list).elml_head;
if (parse_state->current_object->object_type == POLY_OBJ)
{
CHECK(mdl_normalize_elements(parse_state, parse_state->current_region,0));
}
}
#line 4999 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 419:
#line 1755 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = Z_POS; }
#line 5005 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 420:
#line 1756 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = Z_NEG; }
#line 5011 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 421:
#line 1757 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = Y_NEG; }
#line 5017 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 422:
#line 1758 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = Y_POS; }
#line 5023 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 423:
#line 1759 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = X_NEG; }
#line 5029 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 424:
#line 1760 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = X_POS; }
#line 5035 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 425:
#line 1761 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = ALL_SIDES; }
#line 5041 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 427:
#line 1767 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.elem_list) = (yyvsp[-1].elem_list); mdl_add_elements_to_list(& (yyval.elem_list), (yyvsp[0].elem_list).elml_head, (yyvsp[0].elem_list).elml_tail); }
#line 5047 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 430:
#line 1773 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.elem_list).elml_tail = (yyval.elem_list).elml_head = (yyvsp[0].elem_list_item); }
#line 5053 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 431:
#line 1774 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.elem_list).elml_tail = (yyval.elem_list).elml_head = (yyvsp[0].elem_list_item); }
#line 5059 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 432:
#line 1779 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.elem_list) = (yyvsp[-1].elem_list); }
#line 5065 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 433:
#line 1784 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.elem_list) = (yyvsp[-1].elem_list); mdl_set_elements_to_exclude((yyval.elem_list).elml_head); }
#line 5071 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 435:
#line 1791 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.elem_list).elml_tail = (yyval.elem_list).elml_head = (yyvsp[0].elem_list_item); }
#line 5077 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 436:
#line 1792 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.elem_list) = (yyvsp[-2].elem_list); mdl_add_elements_to_list(& (yyval.elem_list), (yyvsp[0].elem_list_item), (yyvsp[0].elem_list_item)); }
#line 5083 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 437:
#line 1795 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.elem_list_item) = new_element_list((unsigned int) (yyvsp[0].dbl), (unsigned int) (yyvsp[0].dbl))); }
#line 5089 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 438:
#line 1796 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.elem_list_item) = new_element_list((unsigned int) (yyvsp[-2].dbl), (unsigned int) (yyvsp[0].dbl))); }
#line 5095 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 439:
#line 1797 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.elem_list_item) = mdl_new_element_side(parse_state, (yyvsp[0].tok))); }
#line 5101 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 440:
#line 1800 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.elem_list_item) = mdl_new_element_previous_region(parse_state, parse_state->current_object, parse_state->current_region, (yyvsp[0].str), (yyvsp[-2].tok))); }
#line 5107 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 441:
#line 1803 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 5113 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 442:
#line 1804 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 1; }
#line 5119 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 443:
#line 1807 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.elem_list_item) = mdl_new_element_patch(parse_state, parse_state->current_polygon, (yyvsp[-2].vec3), (yyvsp[0].vec3), (yyvsp[-4].tok))); }
#line 5125 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 444:
#line 1810 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 5131 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 445:
#line 1811 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 1; }
#line 5137 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 449:
#line 1827 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_region = (yyvsp[-1].reg); }
#line 5143 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 450:
#line 1828 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_region_elements(parse_state, (yyvsp[-3].reg), (yyvsp[0].elem_list).elml_head, (yyvsp[-3].reg)->parent->object_type == POLY_OBJ)); }
#line 5149 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 451:
#line 1830 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_region = NULL; }
#line 5155 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 452:
#line 1838 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
CHECKN(mdl_new_voxel_list(parse_state, (yyvsp[-4].sym),
(yyvsp[-1].vertlist).vertex_count, (yyvsp[-1].vertlist).vertex_head,
(yyvsp[0].ecl).connection_count, (yyvsp[0].ecl).connection_head));
}
#line 5165 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 453:
#line 1844 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.obj) = (struct geom_object *) (yyvsp[-7].sym)->value; }
#line 5171 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 454:
#line 1849 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ecl) = (yyvsp[-1].ecl); }
#line 5177 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 455:
#line 1852 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.elem_conn) = mdl_new_tet_element_connection(parse_state, & (yyvsp[0].nlist))); }
#line 5183 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 456:
#line 1856 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.ecl).connection_head = (yyval.ecl).connection_tail = (yyvsp[0].elem_conn);
(yyval.ecl).connection_count = 1;
}
#line 5192 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 457:
#line 1860 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.ecl) = (yyvsp[-1].ecl);
(yyval.ecl).connection_tail = (yyval.ecl).connection_tail->next = (yyvsp[0].elem_conn);
++ (yyval.ecl).connection_count;
}
#line 5202 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 458:
#line 1870 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->vol->periodic_traditional = (yyvsp[0].tok); }
#line 5208 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 459:
#line 1873 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN(mdl_create_periodic_box(parse_state, (yyvsp[-7].vec3), (yyvsp[-5].vec3), (yyvsp[-2].tok), (yyvsp[-1].tok), (yyvsp[0].tok))); }
#line 5214 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 460:
#line 1874 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_finish_periodic_box(parse_state)); }
#line 5220 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 461:
#line 1880 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN(mdl_new_box_object(parse_state, (yyvsp[-8].sym), (yyvsp[-3].vec3), (yyvsp[-1].vec3))); }
#line 5226 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 462:
#line 1881 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_triangulate_box_object(parse_state, (yyvsp[-10].sym), parse_state->current_polygon, (yyvsp[-2].dbl))); }
#line 5232 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 463:
#line 1883 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
CHECK(mdl_finish_box_object(parse_state, (yyvsp[-13].sym)));
(yyval.obj) = (struct geom_object *) (yyvsp[-13].sym)->value;
}
#line 5241 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 464:
#line 1890 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 5247 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 465:
#line 1891 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = (yyvsp[0].tok); }
#line 5253 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 466:
#line 1895 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 5259 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 467:
#line 1896 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = (yyvsp[0].tok); }
#line 5265 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 468:
#line 1900 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 5271 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 469:
#line 1901 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = (yyvsp[0].tok); }
#line 5277 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 470:
#line 1905 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = 0; }
#line 5283 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 471:
#line 1906 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = (yyvsp[0].tok); }
#line 5289 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 472:
#line 1909 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = 0.0; }
#line 5295 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 473:
#line 1910 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.dbl) = (yyvsp[0].dbl);
if ((yyval.dbl) < 2.0)
{
mdlerror(parse_state, "invalid aspect ratio requested (must be greater than or equal to 2.0)");
return 1;
}
}
#line 5308 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 477:
#line 1936 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_start_existing_obj_region_def(parse_state, (yyvsp[0].sym))); }
#line 5314 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 478:
#line 1937 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_region = (yyvsp[-1].reg); }
#line 5320 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 479:
#line 1939 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_set_region_elements(parse_state, (yyvsp[-4].reg), (yyvsp[0].elem_list).elml_head, 1); }
#line 5326 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 480:
#line 1941 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
parse_state->current_region = NULL;
parse_state->current_polygon = NULL;
parse_state->current_object = parse_state->vol->root_object;
}
#line 5336 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 481:
#line 1948 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.reg) = mdl_create_region(parse_state, parse_state->current_object, (yyvsp[0].str))); }
#line 5342 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 485:
#line 1959 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_add_surf_mol_to_region(parse_state->current_region, & (yyvsp[0].surf_mol_dat_list)); }
#line 5348 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 486:
#line 1963 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ mdl_set_region_surface_class(parse_state, parse_state->current_region, (yyvsp[0].sym)); }
#line 5354 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 490:
#line 1982 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_region = (struct region *) (yyvsp[-1].sym)->value; }
#line 5360 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 491:
#line 1984 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->current_region = NULL; }
#line 5366 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 492:
#line 1992 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
parse_state->header_comment = NULL; /* No header by default */
parse_state->exact_time_flag = 1; /* Print exact_time column in TRIGGER output by default */
}
#line 5375 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 493:
#line 1998 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_add_reaction_output_block_to_world(parse_state, (int) (yyvsp[-4].dbl), & (yyvsp[-2].ro_otimes), & (yyvsp[-1].ro_sets))); }
#line 5381 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 494:
#line 2002 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.dbl) = COUNTBUFFERSIZE; }
#line 5387 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 495:
#line 2003 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
double temp_value = (yyvsp[0].dbl);
if (!(temp_value >= 1.0 && temp_value < UINT_MAX))
{
mdlerror_fmt(parse_state, "Requested buffer size of %.15g lines is invalid. Suggested range is 100-1000000.", temp_value);
return 1;
}
(yyval.dbl) = (yyvsp[0].dbl);
}
#line 5401 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 499:
#line 2019 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ro_otimes).type = OUTPUT_BY_STEP; (yyval.ro_otimes).step = (yyvsp[0].dbl); }
#line 5407 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 500:
#line 2023 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.ro_otimes).type = OUTPUT_BY_ITERATION_LIST;
(yyval.ro_otimes).values = (yyvsp[0].nlist);
}
#line 5416 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 501:
#line 2031 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.ro_otimes).type = OUTPUT_BY_TIME_LIST;
(yyval.ro_otimes).values = (yyvsp[0].nlist);
}
#line 5425 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 502:
#line 2038 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ro_sets).set_head = (yyval.ro_sets).set_tail = NULL; }
#line 5431 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 503:
#line 2039 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ro_sets).set_head = (yyval.ro_sets).set_tail = (yyvsp[0].ro_set); }
#line 5437 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 504:
#line 2041 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.ro_sets) = (yyvsp[-1].ro_sets);
if ((yyvsp[0].ro_set) != NULL)
{
if ((yyval.ro_sets).set_tail != NULL)
(yyval.ro_sets).set_tail = (yyval.ro_sets).set_tail->next = (yyvsp[0].ro_set);
else
(yyval.ro_sets).set_tail = (yyval.ro_sets).set_head = (yyvsp[0].ro_set);
}
}
#line 5452 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 506:
#line 2055 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ro_set) = NULL; }
#line 5458 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 507:
#line 2056 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ro_set) = NULL; }
#line 5464 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 508:
#line 2060 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->count_flags = 0; }
#line 5470 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 509:
#line 2062 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.ro_set) = mdl_populate_output_set(parse_state, parse_state->header_comment, parse_state->exact_time_flag, (yyvsp[-3].ro_cols).column_head, (yyvsp[-1].tok), (yyvsp[0].str))); }
#line 5476 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 510:
#line 2066 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.str) = NULL; }
#line 5482 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 511:
#line 2067 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.str) = ((yyvsp[0].tok) ? "" : NULL); }
#line 5488 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 512:
#line 2068 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.str) = (yyvsp[0].str); }
#line 5494 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 513:
#line 2072 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->header_comment = (yyvsp[0].str); }
#line 5500 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 514:
#line 2076 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->exact_time_flag = (yyvsp[0].tok); }
#line 5506 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 516:
#line 2082 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.ro_cols) = (yyvsp[-2].ro_cols);
(yyval.ro_cols).column_tail->next = (yyvsp[0].ro_cols).column_head;
(yyval.ro_cols).column_tail = (yyvsp[0].ro_cols).column_tail;
}
#line 5516 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 517:
#line 2090 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_single_count_expr(parse_state, & (yyval.ro_cols), (yyvsp[-1].cnt), (yyvsp[0].str))); }
#line 5522 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 518:
#line 2094 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_new_oexpr_constant(parse_state, (yyvsp[0].dbl))); }
#line 5528 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 520:
#line 2096 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_join_oexpr_tree(parse_state, (yyvsp[-1].cnt), NULL, '(')); }
#line 5534 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 521:
#line 2097 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_join_oexpr_tree(parse_state, (yyvsp[-2].cnt), (yyvsp[0].cnt), '+')); }
#line 5540 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 522:
#line 2098 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_join_oexpr_tree(parse_state, (yyvsp[-2].cnt), (yyvsp[0].cnt), '-')); }
#line 5546 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 523:
#line 2099 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_join_oexpr_tree(parse_state, (yyvsp[-2].cnt), (yyvsp[0].cnt), '*')); }
#line 5552 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 524:
#line 2100 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_join_oexpr_tree(parse_state, (yyvsp[-2].cnt), (yyvsp[0].cnt), '/')); }
#line 5558 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 525:
#line 2101 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_join_oexpr_tree(parse_state, (yyvsp[0].cnt), NULL, '_')); }
#line 5564 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 526:
#line 2102 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_sum_oexpr((yyvsp[-1].cnt))); }
#line 5570 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 527:
#line 2107 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->count_flags |= COUNT_PRESENT; }
#line 5576 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 528:
#line 2108 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.cnt) = (yyvsp[-1].cnt); }
#line 5582 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 529:
#line 2109 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_new_oexpr_constant(parse_state, (yyvsp[-1].dbl))); }
#line 5588 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 530:
#line 2110 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ parse_state->count_flags |= TRIGGER_PRESENT; }
#line 5594 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 531:
#line 2111 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.cnt) = (yyvsp[-1].cnt); }
#line 5600 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 532:
#line 2114 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = FILE_OVERWRITE; }
#line 5606 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 533:
#line 2115 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = FILE_SUBSTITUTE; }
#line 5612 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 534:
#line 2116 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = FILE_APPEND; }
#line 5618 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 535:
#line 2117 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = FILE_APPEND_HEADER; }
#line 5624 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 536:
#line 2118 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = FILE_CREATE; }
#line 5630 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 538:
#line 2124 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.sym) = mdl_existing_rxn_pathname_or_molecule(parse_state, (yyvsp[0].str))); }
#line 5636 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 539:
#line 2128 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.mol_type) = (yyvsp[0].mol_type);
if ((yyval.mol_type).orient > 0)
(yyval.mol_type).orient = 1;
else if ((yyval.mol_type).orient < 0)
(yyval.mol_type).orient = -1;
CHECKN((yyval.mol_type).mol_type = mdl_existing_molecule(parse_state, (yyvsp[-1].str)));
}
#line 5649 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 546:
#line 2148 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_count_syntax_1(parse_state, (yyvsp[-3].sym), (yyvsp[-1].sym), (yyvsp[0].tok), parse_state->count_flags)); }
#line 5655 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 547:
#line 2153 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_count_syntax_2(parse_state, (yyvsp[-3].mol_type).mol_type, (yyvsp[-3].mol_type).orient, (yyvsp[-1].sym), (yyvsp[0].tok), parse_state->count_flags)); }
#line 5661 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 548:
#line 2158 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_count_syntax_3(parse_state, (yyvsp[-3].str), (yyvsp[-1].sym), (yyvsp[0].tok), parse_state->count_flags)); }
#line 5667 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 549:
#line 2164 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_count_syntax_periodic_1(parse_state, (yyvsp[-5].sym), (yyvsp[-3].sym), (yyvsp[-1].vec3), (yyvsp[0].tok), parse_state->count_flags)); }
#line 5673 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 550:
#line 2168 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_count_syntax_periodic_2(parse_state, (yyvsp[-5].mol_type).mol_type, (yyvsp[-5].mol_type).orient, (yyvsp[-3].sym), (yyvsp[-1].vec3), (yyvsp[0].tok), parse_state->count_flags)); }
#line 5679 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 551:
#line 2173 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.cnt) = mdl_count_syntax_periodic_3(parse_state, (yyvsp[-5].str), (yyvsp[-3].sym), (yyvsp[-1].vec3), (yyvsp[0].tok), parse_state->count_flags)); }
#line 5685 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 552:
#line 2176 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.sym) = NULL; }
#line 5691 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 553:
#line 2177 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.sym) = (yyvsp[0].sym); }
#line 5697 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 554:
#line 2178 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.sym) = (yyvsp[0].sym); }
#line 5703 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 555:
#line 2181 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = REPORT_NOTHING; }
#line 5709 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 556:
#line 2182 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = (yyvsp[0].tok); }
#line 5715 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 557:
#line 2185 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = REPORT_FRONT_HITS; }
#line 5721 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 558:
#line 2186 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = REPORT_BACK_HITS; }
#line 5727 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 559:
#line 2187 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = REPORT_ALL_HITS; }
#line 5733 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 560:
#line 2188 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = REPORT_FRONT_CROSSINGS; }
#line 5739 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 561:
#line 2189 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = REPORT_BACK_CROSSINGS; }
#line 5745 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 562:
#line 2190 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = REPORT_ALL_CROSSINGS; }
#line 5751 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 563:
#line 2191 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = REPORT_CONCENTRATION; }
#line 5757 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 564:
#line 2192 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = REPORT_ENCLOSED; }
#line 5763 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 565:
#line 2195 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.str) = NULL; }
#line 5769 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 566:
#line 2196 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.str) = (yyvsp[0].str); }
#line 5775 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 567:
#line 2203 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_new_viz_output_block(parse_state)); }
#line 5781 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 568:
#line 2206 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ }
#line 5787 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 571:
#line 2215 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_viz_mode(parse_state->vol->viz_blocks, CELLBLENDER_MODE_V1)); }
#line 5793 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 572:
#line 2216 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_viz_mode(parse_state->vol->viz_blocks, (yyvsp[0].ival))); }
#line 5799 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 573:
#line 2219 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ival) = NO_VIZ_MODE; }
#line 5805 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 574:
#line 2220 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ival) = ASCII_MODE; }
#line 5811 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 575:
#line 2221 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ival) = CELLBLENDER_MODE_V1; }
#line 5817 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 577:
#line 2226 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if ((yyvsp[0].frame_list).frame_head)
{
(yyvsp[0].frame_list).frame_tail->next = parse_state->vol->viz_blocks->frame_data_head;
parse_state->vol->viz_blocks->frame_data_head = (yyvsp[0].frame_list).frame_head;
}
}
#line 5829 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 579:
#line 2239 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_viz_filename_prefix(parse_state, parse_state->vol->viz_blocks, (yyvsp[0].str))); }
#line 5835 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 580:
#line 2245 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.frame_list) = (yyvsp[-1].frame_list); }
#line 5841 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 582:
#line 2251 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.frame_list) = (yyvsp[-1].frame_list);
if ((yyval.frame_list).frame_tail)
{
(yyval.frame_list).frame_tail->next = (yyvsp[0].frame_list).frame_head;
if ((yyvsp[0].frame_list).frame_tail)
(yyval.frame_list).frame_tail = (yyvsp[0].frame_list).frame_tail;
}
else
(yyval.frame_list) = (yyvsp[0].frame_list);
}
#line 5857 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 583:
#line 2265 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.frame_list).frame_head = (yyval.frame_list).frame_tail = NULL; }
#line 5863 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 587:
#line 2277 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_viz_state(parse_state, & (yyval.ival), (yyvsp[0].dbl))); }
#line 5869 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 588:
#line 2278 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.ival) = INCLUDE_OBJ; }
#line 5875 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 591:
#line 2288 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_viz_include_molecules(parse_state, parse_state->vol->viz_blocks, (yyvsp[-1].symlist), (yyvsp[0].ival))); }
#line 5881 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 592:
#line 2289 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_set_viz_include_all_molecules(parse_state->vol->viz_blocks, (yyvsp[0].ival))); }
#line 5887 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 593:
#line 2293 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.symlist) = mdl_existing_molecule_list(parse_state, (yyvsp[0].str))); }
#line 5893 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 594:
#line 2294 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.symlist) = mdl_existing_molecules_wildcard(parse_state, (yyvsp[0].str))); }
#line 5899 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 595:
#line 2298 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_new_viz_all_times(parse_state, & (yyval.nlist))); }
#line 5905 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 597:
#line 2304 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.frame_list) = (yyvsp[-1].frame_list); }
#line 5911 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 599:
#line 2310 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if ((yyvsp[-1].frame_list).frame_head != NULL)
{
(yyval.frame_list) = (yyvsp[-1].frame_list);
if ((yyvsp[0].frame_list).frame_head != NULL)
{
(yyval.frame_list).frame_tail->next = (yyvsp[0].frame_list).frame_head;
(yyval.frame_list).frame_tail = (yyvsp[0].frame_list).frame_tail;
}
}
else if ((yyvsp[0].frame_list).frame_head != NULL)
(yyval.frame_list) = (yyvsp[0].frame_list);
}
#line 5929 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 600:
#line 2327 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_new_viz_mol_frames(parse_state, parse_state->vol->viz_blocks, & (yyval.frame_list), OUTPUT_BY_TIME_LIST, (yyvsp[-2].tok), & (yyvsp[0].nlist))); }
#line 5935 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 601:
#line 2331 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_new_viz_all_iterations(parse_state, & (yyval.nlist))); }
#line 5941 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 603:
#line 2338 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.frame_list) = (yyvsp[-1].frame_list); }
#line 5947 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 605:
#line 2344 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if ((yyvsp[-1].frame_list).frame_head != NULL)
{
(yyval.frame_list) = (yyvsp[-1].frame_list);
if ((yyvsp[0].frame_list).frame_head != NULL)
{
(yyval.frame_list).frame_tail->next = (yyvsp[0].frame_list).frame_head;
(yyval.frame_list).frame_tail = (yyvsp[0].frame_list).frame_tail;
}
}
else if ((yyvsp[0].frame_list).frame_head != NULL)
(yyval.frame_list) = (yyvsp[0].frame_list);
}
#line 5965 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 606:
#line 2361 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECK(mdl_new_viz_mol_frames(parse_state, parse_state->vol->viz_blocks, & (yyval.frame_list), OUTPUT_BY_ITERATION_LIST, (yyvsp[-2].tok), & (yyvsp[0].nlist))); }
#line 5971 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 607:
#line 2364 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = ALL_MOL_DATA; }
#line 5977 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 608:
#line 2365 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = MOL_POS; }
#line 5983 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 609:
#line 2366 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.tok) = MOL_ORIENT; }
#line 5989 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 610:
#line 2380 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
struct volume_output_item *vo;
CHECKN(vo = mdl_new_volume_output_item(parse_state, (yyvsp[-6].str), & (yyvsp[-5].species_lst), (yyvsp[-4].vec3), (yyvsp[-3].vec3), (yyvsp[-2].vec3), (yyvsp[-1].otimes)));
vo->next = parse_state->vol->volume_output_head;
parse_state->vol->volume_output_head = vo;
}
#line 6000 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 611:
#line 2389 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.str) = (yyvsp[0].str); }
#line 6006 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 613:
#line 2395 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.species_lst) = (yyvsp[-1].species_lst);
(yyval.species_lst).species_count += (yyvsp[0].species_lst).species_count;
(yyval.species_lst).species_tail->next = (yyvsp[0].species_lst).species_head;
(yyval.species_lst).species_tail = (yyvsp[0].species_lst).species_tail;
}
#line 6017 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 614:
#line 2404 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.species_lst) = (yyvsp[0].species_lst); }
#line 6023 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 615:
#line 2407 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
struct sym_entry *sp;
struct species_list_item *ptrl;
CHECKN(sp = mdl_existing_molecule(parse_state, (yyvsp[0].str)));
ptrl = (struct species_list_item *) mem_get(parse_state->species_list_mem);
if (ptrl == NULL)
{
mdlerror_fmt(parse_state, "Out of memory while parsing molecule list");
return 1;
}
ptrl->spec = (struct species *) sp->value;
ptrl->next = NULL;
(yyval.species_lst_item) = ptrl;
}
#line 6043 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 616:
#line 2425 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.species_lst).species_tail = (yyval.species_lst).species_head = (yyvsp[0].species_lst_item); (yyval.species_lst).species_count = 1; }
#line 6049 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 617:
#line 2427 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
(yyval.species_lst) = (yyvsp[-2].species_lst);
(yyval.species_lst).species_tail = (yyval.species_lst).species_tail->next = (yyvsp[0].species_lst_item);
++ (yyval.species_lst).species_count;
}
#line 6059 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 618:
#line 2435 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.vec3) = (yyvsp[0].vec3); }
#line 6065 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 619:
#line 2439 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ (yyval.vec3) = (yyvsp[0].vec3); }
#line 6071 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 620:
#line 2443 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{
if ((yyvsp[0].vec3)->x < 1.0)
{
mdl_warning(parse_state, "Voxel count (x dimension) too small. Setting x count to 1.");
(yyvsp[0].vec3)->x = 1.0;
}
if ((yyvsp[0].vec3)->y < 1.0)
{
mdl_warning(parse_state, "Voxel count (y dimension) too small. Setting y count to 1.");
(yyvsp[0].vec3)->y = 1.0;
}
if ((yyvsp[0].vec3)->z < 1.0)
{
mdl_warning(parse_state, "Voxel count (z dimension) too small. Setting z count to 1.");
(yyvsp[0].vec3)->z = 1.0;
}
(yyval.vec3) = (yyvsp[0].vec3);
}
#line 6094 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 621:
#line 2464 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.otimes) = mdl_new_output_times_default(parse_state)); }
#line 6100 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 622:
#line 2465 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.otimes) = mdl_new_output_times_step(parse_state, (yyvsp[0].dbl))); }
#line 6106 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 623:
#line 2466 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.otimes) = mdl_new_output_times_iterations(parse_state, & (yyvsp[0].nlist))); }
#line 6112 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
case 624:
#line 2467 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1646 */
{ CHECKN((yyval.otimes) = mdl_new_output_times_time(parse_state, & (yyvsp[0].nlist))); }
#line 6118 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
break;
#line 6122 "/home/jczech/mcell/build/deps/mdlparse.c" /* yacc.c:1646 */
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (parse_state, scanner, YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
yyssp, yytoken)
{
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = YYSYNTAX_ERROR;
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == 1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
if (!yymsg)
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = 2;
}
else
{
yysyntax_error_status = YYSYNTAX_ERROR;
yymsgp = yymsg;
}
}
yyerror (parse_state, scanner, yymsgp);
if (yysyntax_error_status == 2)
goto yyexhaustedlab;
}
# undef YYSYNTAX_ERROR
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval, parse_state, scanner);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp, parse_state, scanner);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined yyoverflow || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (parse_state, scanner, YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval, parse_state, scanner);
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp, parse_state, scanner);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
return yyresult;
}
#line 2470 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1906 */
/* Begin Bison Epilogue: */
/* mdlerror: Standard error callback from parser.
*
* parse_state: the parser state variables
* str: the error message to display
*/
void mdlerror(struct mdlparse_vars *parse_state, char const *str)
{
mdlerror_fmt(parse_state, "%s", str);
}
/* mdlerror_fmt: Print a formatted error message regarding an error in the MDL
* file.
*
* parse_state: the parser state variables
* fmt: the printf-style format string
*/
void mdlerror_fmt(struct mdlparse_vars *parse_state, char const *fmt, ...)
{
va_list arglist;
if (parse_state->vol->procnum != 0)
return;
/* print error location */
if (parse_state->include_stack_ptr == 0)
mcell_error_raw("Fatal error: After parsing file %s\n",
parse_state->vol->curr_file);
else
mcell_error_raw("Fatal error: On line: %d of file %s\n",
parse_state->line_num[parse_state->include_stack_ptr - 1],
parse_state->vol->curr_file);
/* format error message */
va_start(arglist, fmt);
mcell_errorv_nodie(fmt, arglist);
va_end(arglist);
/* terminate error message and flush */
mcell_error_raw("\n");
mcell_die();
}
/* mdlerror_file: Open and parse an MDL file.
*
* parse_state: the parser state variables
* name: the path to the MDL file
*/
int mdlparse_file(struct mdlparse_vars *parse_state, char const *name)
{
int failure;
int cur_stack = parse_state->include_stack_ptr ++;
FILE *infile;
yyscan_t scanner;
char const *prev_file;
/* Put filename and line number on stack */
if (cur_stack >= MAX_INCLUDE_DEPTH)
{
-- parse_state->include_stack_ptr;
mdlerror_fmt(parse_state, "Includes nested too deeply at file %s\n included from %s:%d",
name,
parse_state->include_filename[cur_stack-1],
parse_state->line_num[cur_stack-1]);
return 1;
}
parse_state->line_num[cur_stack] = 1;
parse_state->include_filename[cur_stack] = name;
/* Open file, or know the reason why */
no_printf("Opening file %s\n", name);
if ((infile = fopen(name,"r")) == NULL)
{
char *err = mcell_strerror(errno);
-- parse_state->include_stack_ptr;
if (cur_stack > 0)
mdlerror_fmt(parse_state, "Couldn't open file %s\n included from %s:%d: %s",
name,
parse_state->include_filename[cur_stack-1],
parse_state->line_num[cur_stack-1],
err);
else
mdlerror_fmt(parse_state, "Couldn't open file %s: %s", name, err);
free(err);
return 1;
}
/* Create and initialize a lexer */
if (mdllex_init(&scanner))
{
int err = errno;
if (err == ENOMEM)
mdlerror_fmt(parse_state, "Couldn't initialize lexer for file %s\n included from %s:%d: out of memory",
name, parse_state->include_filename[cur_stack-1], parse_state->line_num[cur_stack-1]);
else if (err == EINVAL)
mdlerror_fmt(parse_state, "Couldn't initialize lexer for file %s\n included from %s:%d: internal error (invalid argument)",
name,
parse_state->include_filename[cur_stack-1],
parse_state->line_num[cur_stack-1]);
else
mdlerror_fmt(parse_state, "Couldn't initialize lexer for file %s\n included from %s:%d: internal error",
name,
parse_state->include_filename[cur_stack-1],
parse_state->line_num[cur_stack-1]);
fclose(infile);
-- parse_state->include_stack_ptr;
return 1;
}
mdlrestart(infile, scanner);
/* Parse this file */
prev_file = parse_state->vol->curr_file;
parse_state->vol->curr_file = name;
failure = mdlparse(parse_state, scanner);
parse_state->vol->curr_file = prev_file;
-- parse_state->include_stack_ptr;
/* Clean up! */
fclose(infile);
mdllex_destroy(scanner);
return failure;
}
/* mdlerror_init: Set up and parse the top-level MDL file.
*
* vol: the world to populate
*/
int mdlparse_init(struct volume *vol)
{
int failure;
struct mdlparse_vars mpv;
vol->initialization_state = "parsing";
memset(&mpv, 0, sizeof(struct mdlparse_vars));
mpv.vol=vol;
mpv.include_stack_ptr=0;
mpv.current_object = vol->root_object;
/* Create memory pools for parsing */
if ((mpv.path_mem = create_mem(sizeof(struct pathway), 4096)) == NULL)
mcell_allocfailed("Failed to allocate temporary memory pool for reaction pathways.");
if ((mpv.prod_mem = create_mem(sizeof(struct product), 4096)) == NULL)
mcell_allocfailed("Failed to allocate temporary memory pool for reaction products.");
if ((mpv.sym_list_mem = create_mem(sizeof(struct sym_table_list),4096)) == NULL)
mcell_allocfailed("Failed to allocate temporary memory pool for symbol lists.");
if ((mpv.species_list_mem = create_mem(sizeof(struct species_list_item), 1024)) == NULL)
mcell_allocfailed("Failed to allocate temporary memory pool for species lists.");
if ((mpv.mol_data_list_mem = create_mem(sizeof(struct mcell_species), 1024)) == NULL)
mcell_allocfailed("Failed to allocate temporary memory pool for oriented species lists.");
if ((mpv.output_times_mem = create_mem(sizeof(struct output_times), 1024)) == NULL)
mcell_allocfailed("Failed to allocate temporary memory pool for output times.");
/* Start parsing at the top-level file */
vol->curr_file = vol->mdl_infile_name;
failure = mdlparse_file(&mpv, vol->mdl_infile_name);
/* Close any open file streams */
for (int i=0; i<vol->fstream_sym_table->n_bins; ++ i)
{
if (vol->fstream_sym_table->entries[i] != NULL)
{
for (struct sym_entry *symp = vol->fstream_sym_table->entries[i];
symp != NULL;
symp = symp->next)
{
if (((struct file_stream *) symp->value)->stream == NULL)
continue;
mdl_fclose(&mpv, symp);
}
}
}
/* Check for required settings */
if (! failure)
{
if (vol->time_unit == 0.0)
{
mdlerror(&mpv, "A valid model requires a time step to be specified using the TIME_STEP declaration");
failure = 1;
}
}
/* If we succeeded, prepare the reactions */
if (failure)
{
mdlerror(&mpv, "Failed to parse input file");
failure = 1;
}
/* Free leftover object names */
while (mpv.object_name_list)
{
struct name_list *l = mpv.object_name_list->next;
free(mpv.object_name_list);
mpv.object_name_list = l;
}
if (mpv.header_comment != 0) {
free(mpv.header_comment);
}
/* Destroy memory pools */
delete_mem(mpv.species_list_mem);
delete_mem(mpv.mol_data_list_mem);
delete_mem(mpv.output_times_mem);
delete_mem(mpv.sym_list_mem);
delete_mem(mpv.prod_mem);
delete_mem(mpv.path_mem);
vol->initialization_state = "initializing";
return failure;
}
| C |
3D | mcellteam/mcell | appveyor_windows/mdlparse.h | .h | 10,323 | 392 | /* A Bison parser, made by GNU Bison 3.0.4. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
#ifndef YY_MDL_HOME_JCZECH_MCELL_BUILD_DEPS_MDLPARSE_H_INCLUDED
# define YY_MDL_HOME_JCZECH_MCELL_BUILD_DEPS_MDLPARSE_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int mdldebug;
#endif
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
ABS = 258,
ABSORPTIVE = 259,
ACCURATE_3D_REACTIONS = 260,
ACOS = 261,
ALL_CROSSINGS = 262,
ALL_DATA = 263,
ALL_ELEMENTS = 264,
ALL_ENCLOSED = 265,
ALL_HITS = 266,
ALL_ITERATIONS = 267,
ALL_MOLECULES = 268,
ALL_NOTIFICATIONS = 269,
ALL_TIMES = 270,
ALL_WARNINGS = 271,
ASCII = 272,
ASIN = 273,
ASPECT_RATIO = 274,
ATAN = 275,
BACK = 276,
BACK_CROSSINGS = 277,
BACK_HITS = 278,
BOTTOM = 279,
BOX = 280,
BOX_TRIANGULATION_REPORT = 281,
BRIEF = 282,
CEIL = 283,
CELLBLENDER = 284,
CENTER_MOLECULES_ON_GRID = 285,
CHECKPOINT_INFILE = 286,
CHECKPOINT_ITERATIONS = 287,
CHECKPOINT_OUTFILE = 288,
CHECKPOINT_REALTIME = 289,
CHECKPOINT_REPORT = 290,
CLAMP_CONCENTRATION = 291,
CLOSE_PARTITION_SPACING = 292,
CONCENTRATION = 293,
CORNERS = 294,
COS = 295,
COUNT = 296,
CUBIC = 297,
CUBIC_RELEASE_SITE = 298,
CUSTOM_SPACE_STEP = 299,
CUSTOM_TIME_STEP = 300,
DEFINE_MOLECULE = 301,
DEFINE_MOLECULES = 302,
DEFINE_REACTIONS = 303,
DEFINE_RELEASE_PATTERN = 304,
DEFINE_SURFACE_CLASS = 305,
DEFINE_SURFACE_CLASSES = 306,
DEFINE_SURFACE_REGIONS = 307,
DEGENERATE_POLYGONS = 308,
DELAY = 309,
DENSITY = 310,
DIFFUSION_CONSTANT_2D = 311,
DIFFUSION_CONSTANT_3D = 312,
DIFFUSION_CONSTANT_REPORT = 313,
DYNAMIC_GEOMETRY = 314,
DYNAMIC_GEOMETRY_MOLECULE_PLACEMENT = 315,
EFFECTOR_GRID_DENSITY = 316,
ELEMENT_CONNECTIONS = 317,
ELLIPTIC = 318,
ELLIPTIC_RELEASE_SITE = 319,
EQUAL = 320,
ERROR = 321,
ESTIMATE_CONCENTRATION = 322,
EXCLUDE_ELEMENTS = 323,
EXCLUDE_PATCH = 324,
EXCLUDE_REGION = 325,
EXIT = 326,
EXP = 327,
EXPRESSION = 328,
EXTERN = 329,
FALSE = 330,
FCLOSE = 331,
FILENAME = 332,
FILENAME_PREFIX = 333,
FILE_OUTPUT_REPORT = 334,
FINAL_SUMMARY = 335,
FLOOR = 336,
FOPEN = 337,
FORMAT = 338,
FPRINTF = 339,
FPRINT_TIME = 340,
FRONT = 341,
FRONT_CROSSINGS = 342,
FRONT_HITS = 343,
GAUSSIAN_RELEASE_NUMBER = 344,
GEOMETRY = 345,
GRAPH_PATTERN = 346,
HEADER = 347,
HIGH_PROBABILITY_THRESHOLD = 348,
HIGH_REACTION_PROBABILITY = 349,
IGNORED = 350,
INCLUDE_ELEMENTS = 351,
INCLUDE_FILE = 352,
INCLUDE_PATCH = 353,
INCLUDE_REGION = 354,
INPUT_FILE = 355,
INSTANTIATE = 356,
LLINTEGER = 357,
FULLY_RANDOM = 358,
INTERACTION_RADIUS = 359,
ITERATION_LIST = 360,
ITERATION_NUMBERS = 361,
ITERATION_REPORT = 362,
ITERATIONS = 363,
KEEP_CHECKPOINT_FILES = 364,
LEFT = 365,
LIFETIME_THRESHOLD = 366,
LIFETIME_TOO_SHORT = 367,
LIST = 368,
LOCATION = 369,
LOG = 370,
LOG10 = 371,
MAX_TOK = 372,
MAXIMUM_STEP_LENGTH = 373,
MEAN_DIAMETER = 374,
MEAN_NUMBER = 375,
MEMORY_PARTITION_X = 376,
MEMORY_PARTITION_Y = 377,
MEMORY_PARTITION_Z = 378,
MEMORY_PARTITION_POOL = 379,
MICROSCOPIC_REVERSIBILITY = 380,
MIN_TOK = 381,
MISSED_REACTIONS = 382,
MISSED_REACTION_THRESHOLD = 383,
MISSING_SURFACE_ORIENTATION = 384,
MOD = 385,
MODE = 386,
MODIFY_SURFACE_REGIONS = 387,
MOLECULE = 388,
MOLECULE_COLLISION_REPORT = 389,
MOLECULE_DENSITY = 390,
MOLECULE_NUMBER = 391,
MOLECULE_POSITIONS = 392,
MOLECULES = 393,
MOLECULE_PLACEMENT_FAILURE = 394,
NAME_LIST = 395,
NEAREST_POINT = 396,
NEAREST_TRIANGLE = 397,
NEGATIVE_DIFFUSION_CONSTANT = 398,
NEGATIVE_REACTION_RATE = 399,
NO = 400,
NOEXIT = 401,
NONE = 402,
NO_SPECIES = 403,
NOT_EQUAL = 404,
NOTIFICATIONS = 405,
NUMBER_OF_SUBUNITS = 406,
NUMBER_OF_TRAINS = 407,
NUMBER_TO_RELEASE = 408,
OBJECT = 409,
OFF = 410,
ON = 411,
ORIENTATIONS = 412,
OUTPUT_BUFFER_SIZE = 413,
INVALID_OUTPUT_STEP_TIME = 414,
LARGE_MOLECULAR_DISPLACEMENT = 415,
ADD_REMOVE_MESH = 416,
OVERWRITTEN_OUTPUT_FILE = 417,
PARTITION_LOCATION_REPORT = 418,
PARTITION_X = 419,
PARTITION_Y = 420,
PARTITION_Z = 421,
PERIODIC_BOX = 422,
PERIODIC_X = 423,
PERIODIC_Y = 424,
PERIODIC_Z = 425,
PERIODIC_TRADITIONAL = 426,
PI_TOK = 427,
POLYGON_LIST = 428,
POSITIONS = 429,
PRINTF = 430,
PRINT_TIME = 431,
PROBABILITY_REPORT = 432,
PROBABILITY_REPORT_THRESHOLD = 433,
PROGRESS_REPORT = 434,
RADIAL_DIRECTIONS = 435,
RADIAL_SUBDIVISIONS = 436,
RAND_GAUSSIAN = 437,
RAND_UNIFORM = 438,
REACTION_DATA_OUTPUT = 439,
REACTION_OUTPUT_REPORT = 440,
REAL = 441,
RECTANGULAR_RELEASE_SITE = 442,
RECTANGULAR_TOKEN = 443,
REFLECTIVE = 444,
RELEASE_EVENT_REPORT = 445,
RELEASE_INTERVAL = 446,
RELEASE_PATTERN = 447,
RELEASE_PROBABILITY = 448,
RELEASE_SITE = 449,
REMOVE_ELEMENTS = 450,
RIGHT = 451,
ROTATE = 452,
ROUND_OFF = 453,
SCALE = 454,
SEED = 455,
SHAPE = 456,
SHOW_EXACT_TIME = 457,
SIN = 458,
SITE_DIAMETER = 459,
SITE_RADIUS = 460,
SPACE_STEP = 461,
SPHERICAL = 462,
SPHERICAL_RELEASE_SITE = 463,
SPHERICAL_SHELL = 464,
SPHERICAL_SHELL_SITE = 465,
SPRINTF = 466,
SQRT = 467,
STANDARD_DEVIATION = 468,
PERIODIC_BOX_INITIAL = 469,
STEP = 470,
STRING_TO_NUM = 471,
STR_VALUE = 472,
SUBUNIT = 473,
SUBUNIT_RELATIONSHIPS = 474,
SUMMATION_OPERATOR = 475,
SURFACE_CLASS = 476,
SURFACE_ONLY = 477,
TAN = 478,
TARGET_ONLY = 479,
TET_ELEMENT_CONNECTIONS = 480,
THROUGHPUT_REPORT = 481,
TIME_LIST = 482,
TIME_POINTS = 483,
TIME_STEP = 484,
TIME_STEP_MAX = 485,
TO = 486,
TOP = 487,
TRAIN_DURATION = 488,
TRAIN_INTERVAL = 489,
TRANSLATE = 490,
TRANSPARENT = 491,
TRIGGER = 492,
TRUE = 493,
UNLIMITED = 494,
USELESS_VOLUME_ORIENTATION = 495,
VACANCY_SEARCH_DISTANCE = 496,
VAR = 497,
VARYING_PROBABILITY_REPORT = 498,
VERTEX_LIST = 499,
VIZ_OUTPUT = 500,
VIZ_OUTPUT_REPORT = 501,
VIZ_VALUE = 502,
VOLUME_DATA_OUTPUT = 503,
VOLUME_OUTPUT_REPORT = 504,
VOLUME_DEPENDENT_RELEASE_NUMBER = 505,
VOLUME_ONLY = 506,
VOXEL_COUNT = 507,
VOXEL_LIST = 508,
VOXEL_SIZE = 509,
WARNING = 510,
WARNINGS = 511,
WORLD = 512,
YES = 513,
UNARYMINUS = 514
};
#endif
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 67 "/home/jczech/mcell/src/mdlparse.y" /* yacc.c:1909 */
int ival;
int tok;
double dbl;
long long llival;
char *str;
struct sym_entry *sym;
struct vector3 *vec3;
struct num_expr_list_head nlist;
struct release_evaluator *rev;
struct sym_table_list *symlist;
struct output_times *otimes;
/* Reaction output */
struct output_times_inlist ro_otimes;
struct output_column_list ro_cols;
struct output_set *ro_set;
struct output_set_list ro_sets;
struct output_expression *cnt;
/* Viz output */
struct frame_data_list_head frame_list;
/* Region definitions */
struct element_list *elem_list_item;
struct element_list_head elem_list;
struct region *reg;
/* Diffusion constants */
struct diffusion_constant diff_const;
/* Geometry */
struct vertex_list_head vertlist;
struct vertex_list *vertlistitem;
struct element_connection_list_head ecl;
struct element_connection_list *elem_conn;
struct geom_object *obj;
struct object_list obj_list;
struct voxel_object *voxel;
/* Molecule species */
struct mcell_species mol_type;
struct mcell_species_list mol_type_list;
struct mcell_species_spec *mcell_mol_spec;
struct parse_mcell_species_list mcell_species_lst;
struct sm_dat *surf_mol_dat;
struct sm_dat_list surf_mol_dat_list;
struct species_list species_lst;
struct species_list_item *species_lst_item;
/* Reactions */
struct reaction_arrow react_arrow;
struct reaction_rate react_rate;
struct reaction_rates react_rates;
/* Release sites/patterns */
struct release_pattern rpat;
struct release_single_molecule *rsm;
struct release_single_molecule_list rsm_list;
/* printf arguments */
struct arg *printfarg;
struct arg_list printfargs;
#line 380 "/home/jczech/mcell/build/deps/mdlparse.h" /* yacc.c:1909 */
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
int mdlparse (struct mdlparse_vars *parse_state, yyscan_t scanner);
#endif /* !YY_MDL_HOME_JCZECH_MCELL_BUILD_DEPS_MDLPARSE_H_INCLUDED */
| Unknown |
3D | mcellteam/mcell | appveyor_windows/config.h | .h | 22,216 | 713 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/* Windows-specific includes and defines */
/*
This file has includes, declarations, and function definitions to make the code
compile on Windows.
The functions where problems may exist are noted below with their caveats.
Some caveats could be addressed with additional code if necessary.
Wrapped Functions: (the function is available in Windows but certain features
are not available)
strerror_r - return value is POSIX-like (not GCC-like) [strerror_s is used]
ctime_r - must be given a fixed-sized on-stack char buffer [ctime_s is
used]
strftime - [adds support for many of the additional format string]
gethostname - [adds special initialization during the first call]
stat/fstat - [adds support for symlink detection]
rename - [adds support for atomic rename]
mkdir - mode argument is ignored [adds the mode argument to the
declaration]
Emulated functions:
getrusage - only supports RUSAGE_SELF, output struct only has ru_utime and
ru_stime, errno not always set, cannot include <sys/resource.h>
symlink - always fails on XP
alarm - return value is not correct, must use set_alarm_handler instead
of sigaction
*/
#ifndef MCELL_CONFIG_WIN_H
#define MCELL_CONFIG_WIN_H
#ifndef MINGW_HAS_SECURE_API
#define MINGW_HAS_SECURE_API /* required for MinGW to expose _s functions */
#endif
#undef __USE_MINGW_ANSI_STDIO
#define __USE_MINGW_ANSI_STDIO \
1 /* allows use of GNU-style printf format strings */
#define PRINTF_FORMAT(arg) \
__attribute__((__format__( \
gnu_printf, arg, arg + 1))) /* for functions that use printf-like \ \ \ \
arguments this corrects warnings */
#define PRINTF_FORMAT_V(arg) __attribute__((__format__(gnu_printf, arg, 0)))
#define WIN32_LEAN_AND_MEAN /* removes many unneeded Windows definitions */
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0502
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdlib.h>
#include <direct.h> /* many POSIX-like functions */
#include <errno.h>
#include <stdio.h> /* _snprintf */
#include <time.h>
typedef unsigned short u_short;
typedef unsigned int u_int;
typedef unsigned long u_long;
// typedef int errno_t;
/* Remove some windows.h definitions that may cause problems */
#undef TRUE
#undef FALSE
#undef ERROR
#undef TRANSPARENT
#undef FILE_OVERWRITE
#undef FILE_CREATE
#ifdef _MSC_VER
#define inline __inline
#define getcwd _getcwd
#define strdup _strdup
#define va_copy(d, s) ((d) = (s))
#endif
/* Macro for eliminating "unused variable" or "unused parameter" warnings. */
#define UNUSED(p) ((void)(p))
#ifndef __GNUC__
#ifndef __attribute__
#define __attribute__(x) /* empty */
#define __restrict__
#endif
#endif
/* MinGW does not include this in any header but has it in the libraries */
#include <string.h> /* include this to make sure we have definitions for the \ \
\ \
\ \ \
declaration below */
_CRTIMP errno_t __cdecl strerror_s(char *_Buf, size_t _SizeInBytes, int errnum);
inline static int strerror_r(int errnum, char *buf, size_t buflen) {
errno_t err = strerror_s(buf, buflen, errnum);
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
/* ctime_r wrapped function */
inline static char *_ctime_r_helper(const time_t *timep, char *buf,
size_t buflen) {
#if defined(_WIN64) || defined(_MSC_VER)
errno_t err = _ctime64_s(buf, buflen, timep);
#else
errno_t err = _ctime32_s(buf, buflen, timep);
#endif
if (err != 0) {
errno = err;
return NULL;
}
return buf;
}
#define ctime_r(timep, buf) \
_ctime_r_helper(timep, buf, sizeof(buf)) // char *ctime_r(const time_t *timep,
// char *buf) { }
/* strftime function with many additional format codes supported on *nix
* machines */
inline static int _is_leap_year(int y) {
return (y & 3) == 0 && ((y % 25) != 0 || (y & 15) == 0);
}
inline static int _iso8061_weeknum(const struct tm *timeptr) {
int Y = timeptr->tm_year, M = timeptr->tm_mon;
int T = timeptr->tm_mday + 4 -
(timeptr->tm_wday == 0 ? 7 : timeptr->tm_wday); // nearest Thursday
if (M == 12 && T > 31) {
return 1;
}
if (M == 1 && T < 1) {
--Y;
M = 12;
T += 31;
}
int D = 275 * M / 9 + T - 31 +
(M > 2 ? (_is_leap_year(Y) - 2) : 0); // day of year
return 1 + D / 7;
}
inline static int _iso8061_wn_year(const struct tm *timeptr) {
int T = timeptr->tm_mday + 4 -
(timeptr->tm_wday == 0 ? 7 : timeptr->tm_wday); // nearest Thursday
return timeptr->tm_year + 1900 +
((timeptr->tm_mon == 11 && T > 31)
? +1
: ((timeptr->tm_mon == 0 && T < 1) ? -1 : 0));
}
inline static void _strnlwr(char *str, size_t count) {
for (char *end = str + count; str < end; ++str) {
*str = tolower(*str);
}
}
inline static void _strnupr(char *str, size_t count) {
for (char *end = str + count; str < end; ++str) {
*str = toupper(*str);
}
}
inline static void _strnchcase(char *str, size_t count) {
for (char *end = str + count; str < end; ++str) {
*str = isupper(*str) ? tolower(*str) : toupper(*str);
}
}
__attribute__((__format__(
gnu_strftime, 3,
0))) inline static size_t _win_strftime(char *strDest, size_t maxsize,
const char *format,
const struct tm *timeptr) {
/* TODO: verify against *nix version, including edge cases */
struct tm t = *timeptr;
const char *f2, *f1 = format;
char *out = strDest, *out_end = strDest + maxsize;
char fbuf[3] = "%%", buf[64];
while ((f2 = strchr(f1, '%')) != NULL) {
if (f2 - f1 > out_end - out) {
return 0;
}
strncpy(out, f1, f2 - f1);
out += f2 - f1;
++f2;
/* Flag */
char flag;
if (*f2 == '_' || *f2 == '-' || *f2 == '0' || *f2 == '^' || *f2 == '#') {
flag = *(f2++);
} else {
flag = 0;
}
/* Width */
size_t width = 0;
while (isdigit(*f2)) {
width = 10 * (width - '0') + *(f2++);
}
if ((ptrdiff_t)width > out_end - out) {
return 0;
}
/* Modifier */
/* TODO: support modifiers, currently they are read but never used */
// char modifier = 0;
if (*f2 == 'E') {
f2++;
// if (*f2 == 'c' || *f2 == 'C' || *f2 == 'x' || *f2 == 'X' || *f2 == 'y'
// || *f2 == 'Y')
// modifier = 'E'; /* E only before: c, C, x, X, y, Y */
} else if (*f2 == 'O') {
f2++;
// if (*f2 == 'd' || *f2 == 'e' || *f2 == 'H' || *f2 == 'I' || *f2 == 'm'
// || *f2 == 'M' || *f2 == 'S' || *f2 == 'u' || *f2 == 'U' || *f2 == 'V'
// || *f2 == 'w' || *f2 == 'W' || *f2 == 'Y')
// modifier = 'O'; /* O only before: d, e, H, I, m, M, S, u, U, V, w,
// W, y */
}
/* Get content */
size_t count;
int is_numeric = 0, is_num_space_padded = 0;
switch (*f2) {
/* single character formats */
case 0:
buf[0] = '%';
count = 1;
break;
case 'n':
buf[0] = '\n';
count = 1;
break;
case 't':
buf[0] = '\t';
count = 1;
break;
/* simple format equivalences */
case 'h':
count = strftime(buf, ARRAYSIZE(buf), "%b", timeptr);
break;
case 'D':
count = strftime(buf, ARRAYSIZE(buf), "%m/%d/%y", timeptr);
break;
case 'F':
count = strftime(buf, ARRAYSIZE(buf), "%Y-%m-%d", timeptr);
break;
case 'r':
count = strftime(buf, ARRAYSIZE(buf), "%I:%M:%S %p", timeptr);
break; /* TODO: this is actually supposed to be locale dependent? */
case 'R':
count = strftime(buf, ARRAYSIZE(buf), "%H:%M", timeptr);
break;
case 'T':
count = strftime(buf, ARRAYSIZE(buf), "%H:%M:%S", timeptr);
break;
case '+':
count = strftime(buf, ARRAYSIZE(buf), "%a %b %d %H:%M:%S %Z %Y", timeptr);
break;
/* lower-case conversions */
case 'P':
_strnlwr(buf, count = strftime(buf, ARRAYSIZE(buf), "%p", timeptr));
break;
/* pad with leading spaces instead of 0s */
case 'e':
count = strftime(buf, ARRAYSIZE(buf), "%d", timeptr);
is_num_space_padded = 1;
is_numeric = 1;
break;
case 'k':
count = strftime(buf, ARRAYSIZE(buf), "%H", timeptr);
is_num_space_padded = 1;
is_numeric = 1;
break;
case 'l':
count = strftime(buf, ARRAYSIZE(buf), "%I", timeptr);
is_num_space_padded = 1;
is_numeric = 1;
break;
/* sprintf conversions */
case 'C':
count = _snprintf(buf, ARRAYSIZE(buf), "%02u",
(timeptr->tm_year + 1900) / 100);
is_numeric = 1;
break;
case 'u':
count = _snprintf(buf, ARRAYSIZE(buf), "%1u",
timeptr->tm_wday == 0 ? 7 : timeptr->tm_wday);
is_numeric = 1;
break;
#if defined(_WIN64) || defined(_MSC_VER)
case 's':
count = _snprintf(buf, ARRAYSIZE(buf), "%08Iu", mktime(&t));
is_numeric = 1;
break;
#else
case 's':
count = _snprintf(buf, ARRAYSIZE(buf), "%04Iu", mktime(&t));
is_numeric = 1;
break;
#endif
/* ISO 8601 week formats */
case 'V':
count = _snprintf(buf, ARRAYSIZE(buf), "%02u", _iso8061_weeknum(timeptr));
is_numeric = 1;
break;
case 'G':
count = _snprintf(buf, ARRAYSIZE(buf), "%04u", _iso8061_wn_year(timeptr));
is_numeric = 1;
break;
case 'g':
count = _snprintf(buf, ARRAYSIZE(buf), "%02u",
_iso8061_wn_year(timeptr) % 100);
is_numeric = 1;
break;
/* supported by Windows natively (or a character that can't be converted,
* which will be converted to empty string) */
/* make sure is_numeric is set appropriately */
case 'd':
case 'H':
case 'I':
case 'j':
case 'm':
case 'M':
case 'S':
case 'U':
case 'w':
case 'W':
case 'y':
case 'Y':
is_numeric = 1;
fbuf[1] = *f2;
count = strftime(buf, ARRAYSIZE(buf), fbuf, timeptr);
break;
default:
fbuf[1] = *f2;
count = strftime(buf, ARRAYSIZE(buf), fbuf, timeptr);
break;
/* TODO: not sure if Windows' %z is the same as POSIX */
}
/* Write output */
size_t trim = 0;
char padding =
(flag == '_')
? ' '
: ((flag == '0')
? '0'
: (is_numeric ? (is_num_space_padded ? ' ' : '0') : ' '));
if (is_numeric) {
if (flag == '-') {
while (trim < count - 1 && buf[trim] == '0') {
++trim;
}
count -= trim;
} else if (padding == ' ') {
for (size_t i = 0; i < count - 1 && buf[i] == '0'; ++i) {
buf[i] = ' ';
}
}
} else if (flag == '^') {
_strnupr(buf, count);
} /* convert alphabetic characters in result string to upper case */
else if (flag == '#') {
_strnchcase(buf, count);
} /* swap the case of the result string */
if ((ptrdiff_t)count > out_end - out) {
return 0;
}
if (count < width) {
memset(out, padding, width - count);
out += width - count;
}
strncpy(out, buf + trim, count);
out += count;
f1 = f2 + 1;
}
/* copy remaining */
size_t len = strlen(f1);
strncpy(out, f1, len);
out[len] = 0;
return out - strDest + len;
}
#define strftime _win_strftime
/* gethostname wrapped function */
#define WSADESCRIPTION_LEN 256
#define WSASYS_STATUS_LEN 128
#define SOCKET_ERROR -1
typedef struct WSAData {
WORD wVersion;
WORD wHighVersion;
#ifdef _WIN64
unsigned short iMaxSockets;
unsigned short iMaxUdpDg;
char *lpVendorInfo;
char szDescription[WSADESCRIPTION_LEN + 1];
char szSystemStatus[WSASYS_STATUS_LEN + 1];
#else
char szDescription[WSADESCRIPTION_LEN + 1];
char szSystemStatus[WSASYS_STATUS_LEN + 1];
unsigned short iMaxSockets;
unsigned short iMaxUdpDg;
char *lpVendorInfo;
#endif
} WSADATA, *LPWSADATA;
typedef int(WINAPI *FUNC_WSAStartup)(WORD wVersionRequested,
LPWSADATA lpWSAData);
typedef int(WINAPI *FUNC_WSAGetLastError)(void);
typedef int(WINAPI *FUNC_gethostname)(char *name, int namelen);
static FUNC_WSAStartup WSAStartup = NULL;
static FUNC_WSAGetLastError WSAGetLastError = NULL;
static FUNC_gethostname win32gethostname = NULL;
inline static int gethostname(char *name, size_t len) {
if (len > INT_MAX) {
errno = EINVAL;
return -1;
}
/* dynamically load the necessary function and initialize the Winsock DLL */
if (win32gethostname == NULL) {
HMODULE ws2 = LoadLibraryA("ws2_32");
WSADATA wsaData;
WSAStartup = (FUNC_WSAStartup)GetProcAddress(ws2, "WSAStartup");
WSAGetLastError =
(FUNC_WSAGetLastError)GetProcAddress(ws2, "WSAGetLastError");
win32gethostname = (FUNC_gethostname)GetProcAddress(ws2, "gethostname");
if (ws2 == NULL || WSAStartup == NULL || WSAGetLastError == NULL ||
win32gethostname == NULL || WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
if (ws2) {
FreeLibrary(ws2);
}
win32gethostname = NULL;
errno = EPERM;
return -1;
}
}
/* call the Win32 gethostname() */
if (win32gethostname(name, (int)len) == SOCKET_ERROR) {
/* error */
switch (WSAGetLastError()) {
case WSAEFAULT:
errno = name ? ENAMETOOLONG : EFAULT;
break;
case WSANOTINITIALISED:
case WSAENETDOWN:
case WSAEINPROGRESS:
errno = EAGAIN;
break;
}
return -1;
}
return 0;
}
/* getrusage emulated function, normally in <sys/resources.h> */
#ifndef _TIMEVAL_DEFINED
#define _TIMEVAL_DEFINED
struct timeval {
long tv_sec;
long tv_usec;
};
#endif
struct rusage {
struct timeval ru_utime; /* user CPU time used */
struct timeval ru_stime; /* system CPU time used */
};
#define RUSAGE_SELF 0
inline static int getrusage(int who, struct rusage *usage) {
if (who != RUSAGE_SELF) {
errno = EINVAL;
return -1;
}
if (usage == NULL) {
errno = EFAULT;
return -1;
}
FILETIME ftCreation, ftExit, ftKernel, ftUser;
if (GetProcessTimes(GetCurrentProcess(), &ftCreation, &ftExit, &ftKernel,
&ftUser) == 0) {
/* error */
/* FIXME: set errno based on GetLastError() */
return -1;
}
ULONGLONG user =
(((ULONGLONG)ftUser.dwHighDateTime) << 32) + ftUser.dwLowDateTime;
ULONGLONG kernel =
(((ULONGLONG)ftKernel.dwHighDateTime) << 32) + ftKernel.dwLowDateTime;
/* Value is in 100 nanosecond intervals */
/* t / 10000000 => timeval.sec */
/* (t % 10000000) / 10 => timeval.usec */
usage->ru_utime.tv_usec = (long)((user % 10000000) / 10);
usage->ru_utime.tv_sec = (long)(user / 10000000);
usage->ru_stime.tv_usec = (long)((kernel % 10000000) / 10);
usage->ru_stime.tv_sec = (long)(kernel / 10000000);
return 0;
}
/* symlink emulated function, normally in <unistd.h> */
#define SYMBOLIC_LINK_FLAG_FILE 0x0
#define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
typedef BOOLEAN(WINAPI *FUNC_CreateSymbolicLink)(LPCSTR lpSymlinkFileName,
LPCSTR lpTargetFileName,
DWORD dwFlags);
static FUNC_CreateSymbolicLink CreateSymbolicLink = NULL;
inline static int _win_is_dir(const char *path) {
DWORD attr = GetFileAttributesA(path);
return attr != INVALID_FILE_ATTRIBUTES &&
(attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
inline static int symlink(const char *oldpath, const char *newpath) {
/* dynamically load the CreateSymbolicLink function */
if (CreateSymbolicLink == NULL) {
/* requires Windows Vista or newer */
CreateSymbolicLink = (FUNC_CreateSymbolicLink)GetProcAddress(
GetModuleHandleA("kernel32"), "CreateSymbolicLinkA");
if (CreateSymbolicLink == NULL) {
errno = EPERM;
return -1;
}
}
if (!CreateSymbolicLink(newpath, oldpath, _win_is_dir(oldpath))) {
/* error */
char buf[MAX_PATH + 1];
switch (GetLastError()) {
case ERROR_INVALID_FUNCTION:
errno = EPERM;
break;
case ERROR_INVALID_REPARSE_DATA: /* when oldpath == "" */
case ERROR_PATH_NOT_FOUND:
errno = strlen(getcwd(buf, sizeof(buf))) + strlen(newpath) >= MAX_PATH
? ENAMETOOLONG
: ENOENT;
break; /* or ENOTDIR or ELOOP(?) */
case ERROR_ACCESS_DENIED:
errno = _win_is_dir(newpath) ? EEXIST : EACCES;
break; /* reports ERROR_ACCESS_DENIED when newpath already exists as a
directory */
case ERROR_NOT_ENOUGH_MEMORY:
errno = ENOMEM;
break;
case ERROR_WRITE_PROTECT:
errno = EROFS;
break;
case ERROR_INVALID_PARAMETER:
errno = EFAULT;
break;
case ERROR_DISK_FULL:
errno = ENOSPC;
break;
case ERROR_ALREADY_EXISTS:
errno = EEXIST;
break;
default:
errno = EIO;
break;
}
return -1;
}
return 0;
}
/* stat and fstat wrapped function */
/* adds S_IFLNK support to stat(path, &s) - necessary since Windows' stat does
* not set S_IFLNK (or even define S_IFLNK) */
#include <sys/stat.h>
#ifndef FSCTL_GET_REPARSE_POINT
#define FSCTL_GET_REPARSE_POINT \
(0x00000009 << 16) | (42 << 2) | 0 | \
(0 << 14) // CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED,
// FILE_ANY_ACCESS) // REPARSE_DATA_BUFFER
#endif
#define S_IFLNK 0120000
#define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
inline static int _is_symlink(const char *path) {
HANDLE hFile = CreateFileA(
path, GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (hFile == INVALID_HANDLE_VALUE) {
return 0;
}
DWORD *data = (DWORD *)malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE), size;
if (data == NULL) {
CloseHandle(hFile);
return 0;
}
BOOL success = DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, data,
MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &size, NULL);
DWORD tag = *data;
free(data);
CloseHandle(hFile);
return success && tag == IO_REPARSE_TAG_SYMLINK;
}
#ifdef stat
/*
we have a version of MinGW that uses a #define to map stat to _stat64
this introduces a ton of problems
to make this work we need to do something similar
since the stat structure is "changing" we also need an fstat...
*/
#undef stat
#undef fstat
#define stat _win_stat
#define fstat _win_fstat
struct stat { // equivalent to _stat64
_dev_t st_dev;
_ino_t st_ino;
unsigned short st_mode;
short st_nlink;
short st_uid;
short st_gid;
_dev_t st_rdev;
__MINGW_EXTENSION __int64 st_size;
__time64_t st_atime;
__time64_t st_mtime;
__time64_t st_ctime;
};
inline static int stat(const char *path, struct stat *buf) {
int retval = _stat64(path, (struct _stat64 *)buf);
if (retval == 0 && _is_symlink(path)) {
buf->st_mode |= S_IFLNK;
}
return retval;
}
inline static int fstat(int fd, struct stat *buf) {
return _fstat64(fd, (struct _stat64 *)buf);
}
#else
// we just use the normal forwarding setup
// no need to treat fstat special
inline static int _win_stat(const char *path, struct stat *buf) {
int retval = stat(path, buf);
if (retval == 0 && _is_symlink(path)) {
buf->st_mode |= S_IFLNK;
}
return retval;
}
#define stat(path, buf) _win_stat(path, buf)
#endif
/* alarm emulated function, normally in <unistd.h> */
/* sigaction(SIGALRM, ...) replaced by set_alarm_handler() */
#define SIGALRM 14
typedef void(__cdecl *ALARM_CB)(int);
static ALARM_CB _alarm_cb = NULL;
static HANDLE _timer = NULL;
inline static void _win_alarm_cb(PVOID lpParameter, BOOLEAN TimerOrWaitFired) {
_timer = NULL;
_alarm_cb(SIGALRM);
}
inline static void set_alarm_handler(ALARM_CB handler) { _alarm_cb = handler; }
inline static unsigned alarm(unsigned seconds) {
unsigned retval = 0;
if (_timer) {
retval = 1; /* fixme: get actual time left in the timer and return that */
DeleteTimerQueueTimer(NULL, _timer, NULL);
_timer = NULL;
}
if (!CreateTimerQueueTimer(&_timer, NULL, (WAITORTIMERCALLBACK)_win_alarm_cb,
NULL, seconds * 1000, 0, WT_EXECUTEONLYONCE)) {
retval = (unsigned)-1;
}
return retval;
}
/* atomic rename wrapped function */
/* Windows rename is not atomic, but there is ReplaceFile (only when actually
* replacing though) */
inline static int _win_rename(const char *old, const char *new) {
DWORD dwAttrib = GetFileAttributes(new);
if (dwAttrib != INVALID_FILE_ATTRIBUTES &&
!(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) {
/* new file exists */
if (ReplaceFile(new, old, NULL, REPLACEFILE_WRITE_THROUGH, NULL, NULL)) {
return 0;
}
/* fixme: set errno based on GetLastError() [possibly doing some filtering
* before] */
errno = EACCES;
return -1;
} else {
return rename(old, new);
}
}
#define rename _win_rename
/* mkdir wrapped function */
inline static int _win_mkdir(const char *pathname, mode_t mode) {
/* TODO: do something with the mode argument */
UNUSED(mode);
return mkdir(pathname);
}
#define mkdir _win_mkdir
#endif
| Unknown |
3D | mcellteam/mcell | appveyor_windows/version.h | .h | 1,949 | 42 | /****************************************************************
* This file is automatically generated. Do not edit it.
* version.h updated at Wed Feb 5 12:46:27 PM PST 2025 on huxley by bkaynak
****************************************************************/
/* Program version info */
#define MCELL_VERSION "4.1.0"
#define MCELL_REVISION "1f73cd52"
#define MCELL_REVISION_DATE " Wed, 26 Feb 2025 13:47:26 -0800"
#define MCELL_REVISION_COMMITTED 1
#define MCELL_REVISION_BRANCH "mcell4_dev"
/* Build info */
#define MCELL_BUILDDATE "Thu May 1 01:13:53 PM PDT 2025"
#define MCELL_BUILDUSER "bkaynak"
#define MCELL_BUILDHOST "huxley"
#define MCELL_SRCDIR "/home/bkaynak/Desktop/xxx/cpp/mcell/mcell4_builds/mcell4_build_311/mcell/src"
#define MCELL_BUILDDIR "/nadata/cnl/home/bkaynak/Desktop/xxx/cpp/mcell/mcell4_builds/mcell4_build_311/mcell_tools/work/build_mcell"
#define MCELL_BUILDUNAME "Linux huxley 6.1.0-32-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.129-1 (2025-03-06) x86_64 GNU/Linux"
/* Tool identity and version info */
#define MCELL_FLEX "flex"
#define MCELL_FLEX_PATH "/usr/bin/flex"
#define MCELL_FLEX_VERSION "flex 2.6.4"
#define MCELL_FLEX_FLAGS "-Crema"
#define MCELL_BISON "bison"
#define MCELL_BISON_PATH "/usr/bin/bison"
#define MCELL_BISON_VERSION "bison (GNU Bison) 3.8.2"
#define MCELL_BISON_FLAGS ""
#define MCELL_CC "cc"
#define MCELL_CC_PATH "/usr/bin/cc"
#define MCELL_CC_VERSION "cc (Debian 12.2.0-14) 12.2.0"
#define MCELL_LD "ld"
#define MCELL_LD_PATH "/usr/bin/ld"
#define MCELL_LD_VERSION "GNU ld (GNU Binutils for Ubuntu) 2.40"
/* Build options */
#define MCELL_LFLAGS "-Crema"
#define MCELL_YFLAGS ""
#define MCELL_CFLAGS "-Wall -Wextra -Wno-unused-parameter -Wno-unused-function -Wno-unused-variable -Wno-deprecated-declarations -fPIC -D_GNU_SOURCE=1 -O3 -finline-limit=10000 -std=c11 -DPYTHON_VERSION=311 -std=c++17 -fpermissive"
#define MCELL_LDFLAGS ""
| Unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.